Skip to content

flurdy/agent-skills / skills/next

Rank ready beads across validated workspace stores or one local store. List read-only, or claim one selected bead, show its details, and continue into its work.

scripts/next-select

View on GitHub
#!/usr/bin/env python3
"""Resolve a /next selection to its owning Beads store and act only there.

`stores` lists the usable stores read-only so consumers can route new work.
`related` reports one-hop graph context for a bead or this session's claims, read-only."""

from __future__ import annotations

import argparse
import fcntl
import hashlib
import importlib.util
import json
import os
import subprocess
import sys
import tempfile
from contextlib import contextmanager
from datetime import datetime, timezone
from pathlib import Path
from time import monotonic, sleep
from typing import Any, Iterator

sys.dont_write_bytecode = True

SCRIPT_DIR = Path(__file__).resolve().parent
HANDOFF_LIST = SCRIPT_DIR.parents[1] / "handoffs" / "scripts" / "list.sh"
COMMAND_TIMEOUT_SECONDS = 5
AMBIGUOUS_EXIT = 3
NOT_FOUND_EXIT = 4
UNAVAILABLE_EXIT = 5
STALE_EXIT = 6
MACHINE_MISMATCH_EXIT = 7
CLAIM_VERSION = "agent-claim:v1"
SESSION_ID_VARIABLES = (
    "PI_SESSION_ID",
    "CLAUDE_SESSION_ID",
    "CLAUDE_CODE_SESSION_ID",
    "CODEX_SESSION_ID",
    "CODEX_THREAD_ID",
)


def load_collector() -> Any:
    spec = importlib.util.spec_from_file_location("next_collect", SCRIPT_DIR / "collect.py")
    module = importlib.util.module_from_spec(spec)
    sys.modules[spec.name] = module
    spec.loader.exec_module(module)
    return module


def usable_sources(collector: Any) -> tuple[bool, list[Any]]:
    return collector.discover_sources(Path.cwd())


def probe_issue(collector: Any, source: Any, issue_id: str) -> tuple[bool, str | None]:
    error = collector.store_error(source)
    if error is not None:
        return False, error
    issues, error = collector.load_issues(source, ["list", "--id", issue_id, "--all"])
    return any(issue.get("id") == issue_id for issue in issues), error


def resolution(workspace: bool, source: Any, issue_id: str) -> dict[str, Any]:
    return {
        "status": "resolved",
        "workspace": workspace,
        "id": issue_id,
        "repository": source.name,
        "repository_path": source.relative_path,
        "directory": str(source.directory.resolve()),
    }


def store_listing(collector: Any) -> dict[str, Any]:
    workspace, sources = usable_sources(collector)
    stores = []
    for source in sources:
        error = collector.store_error(source)
        row = {
            "repository": source.name,
            "repository_path": source.relative_path,
            "directory": str(source.directory.resolve()),
            "usable": error is None,
            "error": error,
        }
        if source.store == "workspace":
            row.update(
                owner="workspace",
                directory=str(sources[0].directory.resolve()),
                repository_directory=str(source.directory.resolve()),
            )
        stores.append(row)
    return {"workspace": workspace, "stores": stores}


def ranked_candidates(options: list[str]) -> tuple[list[dict[str, Any]], str | None]:
    try:
        result = subprocess.run(
            [str(SCRIPT_DIR / "next-bd"), "--json", *options],
            capture_output=True,
            check=False,
            text=True,
        )
    except OSError:
        return [], "ranked collection unavailable"
    diagnostic = " ".join(line for line in result.stderr.splitlines()
                          if not line.startswith("Machine:")).strip()[:240] or None
    if result.returncode != 0:
        return [], diagnostic or f"ranked collection exited {result.returncode}"
    try:
        candidates = json.loads(result.stdout)
    except json.JSONDecodeError:
        return [], "invalid ranked collection JSON"
    if not isinstance(candidates, list) or not all(
        isinstance(row, dict) and isinstance(row.get("id"), str) and row["id"].strip()
        for row in candidates
    ):
        return [], "invalid ranked collection JSON: expected candidates with IDs"
    return candidates, diagnostic


def source_by_name(sources: list[Any], name: str) -> Any | None:
    for source in sources:
        if source.name == name:
            return source
    return None


def owner_match(source: Any, issue_id: str) -> dict[str, str]:
    return {
        "repository": source.name,
        "repository_path": source.relative_path,
        "selector": f"{source.name}:{issue_id}",
    }


def source_failure(collector: Any, source: Any, error: str) -> dict[str, str]:
    failure = {
        "repository": source.name,
        "repository_path": source.relative_path,
        "error": error,
    }
    if (
        source.relative_path != "."
        and not source.store_declared
        and error == collector.MISSING_STORE_ERROR
        and not os.path.lexists(source.directory / ".beads")
    ):
        failure["hint"] = (
            "beadsStore is omitted (defaults to local) and .beads is absent. "
            "Confirm tracking policy: if workspace-owned, declare "
            '"beadsStore": "workspace" for this member in workspace.json; '
            "otherwise restore its local store. This hint does not prove ownership "
            "or authorize configuration changes."
        )
    return failure


def resolve_index(
    workspace: bool, sources: list[Any], index: int, options: list[str]
) -> tuple[dict[str, Any], int]:
    candidates, error = ranked_candidates(options)
    if index < 1 or index > len(candidates):
        if error is not None:
            return {"status": "unavailable", "selector": str(index), "error": error}, UNAVAILABLE_EXIT
        return {"status": "not-found", "selector": str(index)}, NOT_FOUND_EXIT
    candidate = candidates[index - 1]
    name = candidate.get("repository", sources[0].name)
    source = source_by_name(sources, name)
    if source is None:
        return {"status": "not-found", "selector": str(index)}, NOT_FOUND_EXIT
    return resolution(workspace, source, candidate["id"]), 0


def resolve_id(
    collector: Any,
    workspace: bool,
    sources: list[Any],
    issue_id: str,
    qualifier: str | None,
) -> tuple[dict[str, Any], int]:
    selector = f"{qualifier}:{issue_id}" if qualifier is not None else issue_id
    if not workspace and qualifier is None:
        source = sources[0]
        issues, error = collector.load_issues(source, ["show", issue_id])
        if error is None and len(issues) > 1:
            error = "invalid bd JSON: expected a single local issue"
        if error is not None:
            return {
                "status": "unavailable", "selector": issue_id, "id": issue_id,
                "failures": [source_failure(collector, source, error)],
            }, UNAVAILABLE_EXIT
        if issues:
            return resolution(False, source, issue_id), 0
        return {"status": "not-found", "selector": issue_id}, NOT_FOUND_EXIT
    if qualifier is not None:
        source = source_by_name(sources, qualifier)
        if source is None:
            return {"status": "not-found", "selector": selector}, NOT_FOUND_EXIT
        if source.store == "workspace" and collector.store_error(source) is None:
            return {
                "status": "not-found", "selector": selector,
                "owner": "workspace", "owner_selector": f"workspace:{issue_id}",
            }, NOT_FOUND_EXIT
        owned, error = probe_issue(collector, source, issue_id)
        if error is not None:
            return {
                "status": "unavailable",
                "selector": selector,
                "id": issue_id,
                "failures": [source_failure(collector, source, error)],
            }, UNAVAILABLE_EXIT
        if not owned:
            return {"status": "not-found", "selector": selector}, NOT_FOUND_EXIT
        return resolution(workspace, source, issue_id), 0

    owners = []
    failures = []
    for source in sources:
        if source.store == "workspace" and collector.store_error(source) is None:
            continue
        owned, error = probe_issue(collector, source, issue_id)
        if error is not None:
            failures.append(source_failure(collector, source, error))
        elif owned:
            owners.append(source)
    matches = [owner_match(source, issue_id) for source in owners]
    if len(owners) > 1:
        payload: dict[str, Any] = {
            "status": "ambiguous",
            "id": issue_id,
            "matches": matches,
        }
        if failures:
            payload["failures"] = failures
        return payload, AMBIGUOUS_EXIT
    if failures:
        return {
            "status": "unavailable",
            "selector": issue_id,
            "id": issue_id,
            "matches": matches,
            "failures": failures,
        }, UNAVAILABLE_EXIT
    if not owners:
        return {"status": "not-found", "selector": issue_id}, NOT_FOUND_EXIT
    return resolution(workspace, owners[0], issue_id), 0


def resolve(selector: str, options: list[str], expected_id: str) -> tuple[dict[str, Any], int]:
    collector = load_collector()
    collector.beads_read_timeout()
    workspace, sources = usable_sources(collector)
    if selector.isdigit():
        resolved, code = resolve_index(workspace, sources, int(selector), options)
    else:
        qualifier, separator, issue_id = selector.partition(":")
        if separator:
            resolved, code = resolve_id(
                collector, workspace, sources, issue_id, qualifier
            )
        else:
            resolved, code = resolve_id(
                collector, workspace, sources, selector, None
            )
    if code == 0 and expected_id and resolved["id"] != expected_id:
        return {
            "status": "stale",
            "selector": selector,
            "expected": expected_id,
            "actual": resolved["id"],
        }, STALE_EXIT
    return resolved, code


def run_handoff(directory: Path, issue_id: str, extra: list[str]) -> int:
    if not HANDOFF_LIST.is_file():
        print(f"next-select: handoff lookup unavailable: {HANDOFF_LIST}", file=sys.stderr)
        return 0
    result = subprocess.run(
        [str(HANDOFF_LIST), "--bead", issue_id, *extra],
        cwd=directory,
        check=False,
    )
    return result.returncode


def harness_session_id() -> str:
    for variable in SESSION_ID_VARIABLES:
        value = os.environ.get(variable, "").strip()
        if value:
            return " ".join(value.split())
    return "unavailable"


def claim_marker(directory: Path, session_id: str) -> str:
    identity = json.dumps(
        {
            "owning_store": str(directory.resolve()),
            "session_id": session_id,
        },
        sort_keys=True,
        separators=(",", ":"),
    )
    return f"{CLAIM_VERSION} {identity}"


def claim_lock_path(directory: Path, issue_id: str) -> Path:
    identity = f"{directory.resolve()}\0{issue_id}".encode()
    digest = hashlib.sha256(identity).hexdigest()
    return Path(tempfile.gettempdir()) / f"next-select-claim-{digest}.lock"


@contextmanager
def claim_lock(directory: Path, issue_id: str) -> Iterator[None]:
    descriptor = os.open(
        claim_lock_path(directory, issue_id),
        os.O_CREAT | os.O_RDWR,
        0o600,
    )
    lock = os.fdopen(descriptor, "w")
    deadline = monotonic() + COMMAND_TIMEOUT_SECONDS
    try:
        while True:
            try:
                fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
                break
            except BlockingIOError:
                if monotonic() >= deadline:
                    raise TimeoutError("claim attribution lock timed out")
                sleep(0.05)
        yield
    finally:
        fcntl.flock(lock, fcntl.LOCK_UN)
        lock.close()


def claimed(directory: Path, issue_id: str, marker: str) -> tuple[bool, str | None]:
    """Whether the issue's comments carry this claim marker; error when unreadable."""
    try:
        existing = subprocess.run(
            ["bd", "-C", str(directory), "comments", issue_id, "--json", "--readonly"],
            capture_output=True,
            check=False,
            text=True,
            timeout=COMMAND_TIMEOUT_SECONDS,
        )
    except (OSError, subprocess.TimeoutExpired) as error:
        return False, f"claim lookup failed: {error}"
    if existing.returncode != 0:
        return False, existing.stderr.strip() or f"claim lookup exited {existing.returncode}"
    try:
        comments = json.loads(existing.stdout)
    except json.JSONDecodeError as error:
        return False, f"invalid comment JSON: {error}"
    if not isinstance(comments, list):
        return False, "invalid comment JSON: expected a list"
    return any(
        isinstance(comment, dict)
        and isinstance(comment.get("text"), str)
        and marker in comment["text"]
        for comment in comments
    ), None


def record_claim(directory: Path, issue_id: str, machine_note: str = "") -> int:
    session_id = harness_session_id()
    marker = claim_marker(directory, session_id)
    already, error = claimed(directory, issue_id, marker)
    if error is not None:
        print(f"next-select: {error}", file=sys.stderr)
        return 1
    if already:
        return 0

    timestamp = datetime.now(timezone.utc).isoformat(timespec="seconds").replace(
        "+00:00", "Z"
    )
    body = "\n".join(
        (
            marker,
            "Agent-driven in_progress claim attribution.",
            f"session_id: {session_id}",
            f"claimed_at_utc: {timestamp}",
            f"owning_store: {directory.resolve()}",
            "Session activity is unverified.",
            machine_note,
        )
    ).rstrip()
    try:
        added = subprocess.run(
            ["bd", "-C", str(directory), "comments", "add", issue_id, body],
            check=False,
            timeout=COMMAND_TIMEOUT_SECONDS,
        )
    except (OSError, subprocess.TimeoutExpired) as error:
        print(f"next-select: claim attribution failed: {error}", file=sys.stderr)
        return 1
    return added.returncode


def run_start(directory: Path, issue_id: str, allow_other_machine: bool = False) -> int:
    try:
        with claim_lock(directory, issue_id):
            collector = load_collector()
            machine = collector.machine_identity()
            rows, error = collector.load_issues(
                collector.Source("local", ".", directory), ["show", issue_id]
            )
            if error or len(rows) != 1:
                print(json.dumps({"status": "unavailable", "id": issue_id,
                                  "error": error or "expected one current issue"}))
                return UNAVAILABLE_EXIT
            eligibility = collector.machine_eligibility(rows[0], machine)
            override = (allow_other_machine and eligibility["state"] == "mismatch"
                        and rows[0].get("status") not in {"blocked", "deferred", "closed"})
            if not eligibility["eligible"] and not override:
                print(json.dumps({"status": "machine-mismatch", "id": issue_id,
                                  "machine": machine, "machine_eligibility": eligibility}))
                return MACHINE_MISMATCH_EXIT
            note = ""
            if override:
                note = (f"machine-override: local {machine['id']}; targets "
                        f"{', '.join(eligibility['required'])}; explicit tracking override only; "
                        "machine-local execution and lease checks remain separate.")
                print(note, file=sys.stderr)
            claimed = record_claim(directory, issue_id, note)
            if claimed != 0:
                return claimed
            update = subprocess.run(
                [
                    "bd",
                    "-C",
                    str(directory),
                    "update",
                    issue_id,
                    "--status=in_progress",
                ],
                check=False,
                timeout=COMMAND_TIMEOUT_SECONDS,
            )
            if update.returncode != 0:
                return update.returncode
            return subprocess.run(
                ["bd", "-C", str(directory), "show", issue_id],
                check=False,
                timeout=COMMAND_TIMEOUT_SECONDS,
            ).returncode
    except (OSError, subprocess.TimeoutExpired, TimeoutError) as error:
        print(f"next-select: claim failed: {error}", file=sys.stderr)
        return 1


def session_focus(
    collector: Any, sources: list[Any], session_id: str
) -> tuple[dict[Any, list[str]], list[tuple[Any, str]]]:
    """In-progress issues whose claim attribution names this session, per owning store."""
    focus: dict[Any, list[str]] = {}
    failures = []
    for source in sources:
        error = collector.store_error(source)
        if source.store == "workspace" and error is None:
            continue
        issues: list[dict[str, Any]] = []
        if error is None:
            issues, error = collector.load_issues(
                source, ["list", "--status=in_progress", "--flat", "--limit=0"])
        marker = claim_marker(source.directory, session_id)
        for issue in issues if error is None else []:
            owned, error = claimed(source.directory, issue["id"], marker)
            if error is not None:
                error = f"{issue['id']}: {error}"
                break
            if owned:
                focus.setdefault(source, []).append(issue["id"])
        if error is not None:
            focus.pop(source, None)
            failures.append((source, error))
    return focus, failures


def related(selector: str) -> tuple[dict[str, Any], int]:
    collector = load_collector()
    workspace, sources = usable_sources(collector)
    payload: dict[str, Any] = {"workspace": workspace, "focus": [],
                               "diagnostics": [], "unavailable_stores": []}
    if selector:
        resolved, code = resolve(selector, [], "")
        if code != 0:
            return {**payload, **resolved}, code
        focus = {source_by_name(sources, resolved["repository"]): [resolved["id"]]}
        failures: list[tuple[Any, str]] = []
        payload["focus_source"] = "selector"
    else:
        session_id = harness_session_id()
        if session_id == "unavailable":
            return {**payload, "status": "no-session"}, NOT_FOUND_EXIT
        focus, failures = session_focus(collector, sources, session_id)
        payload.update(focus_source="session", session_id=session_id)
    for source, ids in focus.items():
        views, error = collector.related_view(source, ids, workspace)
        if error is not None:
            failures.append((source, error))
        payload["focus"].extend(views)
    for source, error in failures:
        payload["diagnostics"].append(f"{source.name}: {error}")
        payload["unavailable_stores"].append(collector.unavailable_store(source, error))
    if payload["focus"]:
        return {**payload, "status": "ok"}, 0
    if failures:
        return {**payload, "status": "unavailable"}, UNAVAILABLE_EXIT
    return {**payload, "status": "none"}, NOT_FOUND_EXIT


def parse_arguments(argv: list[str]) -> argparse.Namespace:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("command", choices=("stores", "resolve", "handoff", "start", "related"))
    parser.add_argument("selector", nargs="?", default="")
    parser.add_argument("--avoid-busy", action="store_true")
    parser.add_argument("--type", default="")
    parser.add_argument("--expect-id", default="")
    parser.add_argument("--check-branches", action="store_true")
    parser.add_argument("--allow-other-machine", action="store_true",
                        help="explicit tracking override for a known direct-ID machine mismatch")
    arguments = parser.parse_args(argv)
    if arguments.command == "stores" and arguments.selector:
        parser.error("stores takes no selector")
    if arguments.command not in ("stores", "related") and not arguments.selector:
        parser.error(f"{arguments.command} requires a selector")
    if arguments.command == "related" and (
        arguments.selector.isdigit() or arguments.avoid_busy or arguments.type or arguments.expect_id
    ):
        parser.error("related takes only an optional bead ID or repo:id selector")
    if arguments.allow_other_machine and (arguments.command != "start" or arguments.selector.isdigit()):
        parser.error("--allow-other-machine requires start with a direct bead ID")
    return arguments


def main(argv: list[str]) -> int:
    arguments = parse_arguments(argv)
    try:
        load_collector().beads_read_timeout()
    except ValueError as error:
        print(f"next-select: {error}", file=sys.stderr)
        return 2
    if arguments.command in ("stores", "related"):
        if arguments.command == "stores":
            payload, code = store_listing(load_collector()), 0
        else:
            payload, code = related(arguments.selector)
        json.dump(payload, sys.stdout, separators=(",", ":"))
        sys.stdout.write("\n")
        return code
    options = []
    if arguments.avoid_busy:
        options.append("--avoid-busy")
    if arguments.type:
        options.append(f"--type={arguments.type}")

    resolved, code = resolve(arguments.selector, options, arguments.expect_id)
    if code != 0 or arguments.command == "resolve":
        json.dump(resolved, sys.stdout, separators=(",", ":"))
        sys.stdout.write("\n")
        return code

    directory = Path(resolved["directory"])
    if arguments.command == "handoff":
        return run_handoff(
            directory,
            resolved["id"],
            ["--check-branches"] if arguments.check_branches else [],
        )
    return run_start(directory, resolved["id"], arguments.allow_other_machine)


if __name__ == "__main__":
    raise SystemExit(main(sys.argv[1:]))
slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack."Stars: 198kUpdated Claude CodeCodexVerifiedInstall
ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt.Stars: 194kUpdated Claude CodeCodexVerifiedInstall