CtrlK
BlogDocsLog inGet started
Tessl Logo
PluginPublic

jbaruch/herdr-policy

Herdr team coordination policy for AI coding agents

Quality

93%

Does it follow best practices?

Run evals on this skill

Adds up to 20 points to the overall score

View guide
SecuritybySnyk

Low

Low-risk findings worth noting

Overview
Quality
Evals
Security
Files

supervision_hook.pyskills/herdr-foreman/foreman/

"""Native Claude/Codex Stop contract for an explicitly bound Herdr foreman only.

stdin: native Stop JSON containing cwd and session_id and/or transcript_path.
stdout: {decision:block,reason:...} only for the matching bound foreman with
unhandled events, active observation obligations, or unreadable owner state.
Workers, other native sessions, and never-bound sessions produce no output.
An empty-but-set team environment blocks until native identity can be checked.
No writes, worker contact, process termination, or acknowledgement occurs.

stop_hook_active does not waive supervision. A genuine user pause remains a
supported boundary. A handoff needs a verified successor or explicitly requested
live reset continuation, never a saved checkpoint alone.
"""

import json
import os
import sys

from . import runnable
from . import foreman_reset
from . import supervision as store
from . import supervision_runtime as runtime
from . import progression_runtime
from .native_policy import executing_policy_root
from .errors import ForemanError


def block(reason):
    return {"decision": "block", "reason": "Herdr supervision — " + reason}


def _ineligible_handoff_clause(continuation):
    """Next action for an ineligible current handoff, keyed by continuation state."""
    state = continuation["state"]
    prefix = (" The saved handoff does not transfer supervision "
              "({}).".format(state))
    if state == "reset_missing":
        return prefix + " Keep the current context, active goal and foreground watch; an ordinary checkpoint never schedules a reset."
    if state == "reset_deliverer_not_live":
        return prefix + " Run `{}` for this owner state to inspect the reset and obtain its reconciliation command; do not schedule another attempt for this stow.".format(
            runnable.command("catch-up"))
    if state in ("reset_failed", "reset_interrupted", "reset_delivered", "reset_reconciled"):
        return prefix + " Keep the current turn and foreground watch; do not retry this stow."
    return prefix + " Keep the current turn and foreground watch."


def check(payload, environ, at, *, root=None, probe=runtime.process_identity):
    if "HERDR_ENV" not in environ or not environ.get("HERDR_PANE_ID") or not isinstance(payload, dict):
        return None
    if not environ["HERDR_ENV"]:
        return block("HERDR_ENV is set but empty. Restore this native session's Herdr environment value before stopping; preserve its owner records.")
    if not isinstance(payload.get("cwd"), str) or not payload["cwd"]:
        return None
    for kind, field in (("id", "session_id"), ("path", "transcript_path")):
        value = payload.get(field)
        if not isinstance(value, str) or not value:
            continue
        who = store.identity(value, payload["cwd"], environ["HERDR_ENV"], kind=kind, pane_id=environ["HERDR_PANE_ID"])
        path = store.binding_path(who, root)
        try:
            binding = store.read_json(path)
            if binding is None:
                continue
            if (not isinstance(binding, dict) or binding.get("schema_version") != 1
                    or binding.get("identity") != who or not isinstance(binding.get("state_path"), str)
                    or type(binding.get("generation")) is not int or binding["generation"] < 1):
                return block("The exact foreman binding is unreadable. Restore {} and reconcile its saved state before stopping.".format(path))
            data = store.load(binding["state_path"])
            if data["binding"] is None:
                return block("This bound foreman's supervision state is missing. Restore {} before stopping; missing state cannot prove its work was resolved.".format(store.store_path(binding["state_path"])))
            if data["binding"]["identity"] != who:
                if binding["generation"] >= data["binding"]["generation"]:
                    return block("This foreman's native binding handoff is incomplete. Retry `{}` for the same owner state before stopping.".format(
                        runnable.command("supervision-bind")))
                continue
            events = store.pending(data)
            active = [row["id"] for row in data["members"] if row["active"]]
            if not events and store.current_holds(data, "waiting_for_user"):
                return None
            delegated = progression_runtime.continuation(binding["state_path"], data, at, executing_policy_root(), probe=probe)
            uncovered = set(active) - delegated["members"]
            unhandled = [event for event in events if event["member"] not in delegated["members"]]
            unhealthy = [task for task, status in delegated["tasks"].items() if status != "live"]
            if not uncovered and not unhandled and not unhealthy:
                return None
            continuation = None
            if not events and store.current_holds(data, "handoff"):
                continuation = foreman_reset.stop_coverage(binding["state_path"], data, probe=probe)
                if continuation["eligible"]:
                    return None
            health = runtime.health(data, at, probe)
            handoff = ""
            if continuation is not None:
                handoff = _ineligible_handoff_clause(continuation)
            return block("{} active assignment(s), {} unhandled event(s), {} task executor(s) needing recovery; watcher is {}.{} These counts exclude exact obligations covered by a healthy task executor. Read the bounded task exception for an admitted workflow. For legacy obligations, run `{}`, reconcile report/ledger evidence, acknowledge handled outcomes, and keep awaiting the foreground `{}` handle. A quiet watch deadline is a checkpoint: start the next foreground watch while authorized work remains. A genuine user-requested pause may use `{}`; a handoff permits Stop only after verified successor takeover, its explicitly requested reset continuation, or the exact healthy task executor is live. State: {}".format(
                len(uncovered), len(unhandled), len(unhealthy), health["state"], handoff, runnable.command("supervision-drain"), runnable.command("supervision-watch"),
                runnable.command("supervision-hold"),
                binding["state_path"]))
        except ForemanError as exc:
            return block("Cannot verify this bound foreman's supervision: {} Resume from its saved state before stopping.".format(exc))
    return None


def main():
    # The CLI remains the package's single wall-clock source.
    from .cli import now_iso
    try:
        payload = json.load(sys.stdin)
    except (json.JSONDecodeError, UnicodeDecodeError) as exc:
        print("herdr-supervision-stop: cannot identify the native session from invalid hook JSON: {}. Restore native hook payload delivery.".format(exc), file=sys.stderr)
        return 0
    bound = False
    try:
        if isinstance(payload, dict) and payload.get("cwd") and "HERDR_ENV" in os.environ and os.environ.get("HERDR_PANE_ID"):
            if not os.environ["HERDR_ENV"]:
                # The team context is unusable, not proved standalone. Keep an
                # unexpected evaluation failure from dropping its repair gate.
                bound = True
            else:
                for kind, field in (("id", "session_id"), ("path", "transcript_path")):
                    if isinstance(payload.get(field), str) and payload[field]:
                        who = store.identity(payload[field], payload["cwd"], os.environ["HERDR_ENV"], kind=kind, pane_id=os.environ["HERDR_PANE_ID"])
                        bound = bound or store.binding_path(who).exists()
        result = check(payload, os.environ, now_iso())
    # outer-boundary-process-contract: native Stop treats nonzero/invalid stdout
    # as no block; emit a structured block for unexpected evaluation errors so
    # a bound foreman's supervision does not silently disappear on a traceback.
    except Exception as exc:
        print("herdr-supervision-stop: evaluation failed ({}); inspect the hook installation.".format(type(exc).__name__), file=sys.stderr)
        if bound:
            print(json.dumps(block("The bound foreman's supervision could not be evaluated. Restore the hook/state installation and reconcile active work before stopping.")))
        return 0
    if result is not None:
        print(json.dumps(result))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())

skills

herdr-foreman

foreman

__init__.py

__main__.py

antigravity_native.py

assign.py

attention_view.py

attention.py

billing.py

bootstrap_recovery.py

brief_inputs.py

capabilities.py

chronology.py

churn.py

claude_native.py

cli.py

codex_goals.py

command_context.py

composer.py

composition.py

config.py

context_evidence.py

context_output.py

coordination_metrics.py

cost_report.py

delivery_collection.py

diagnostics.py

engagement.py

errors.py

foreman_queue.py

foreman_reset.py

github_context.py

herdr.py

historical.py

home.py

host_goals.py

launch.py

lifecycle.py

load_set.py

measure.py

measurement_capture.py

measurement_retry.py

members.py

memory.py

model_unavailability.py

native_permissions.py

native_policy.py

no_work_recovery.py

observer_projection.py

observer_role.py

oracle.py

parsers.py

partition.py

plan_explanation.py

planner.py

policy_paths.py

probe_recovery.py

probe.py

process_lease.py

progression_owner.py

progression_runtime.py

progression_service.py

provision.py

recovery.py

release_activation.py

release_checkout.py

release_flight.py

release_rebind.py

remote_owner.py

remote_service.py

renderable.py

report_contract.py

report_delivery.py

report_gates.py

reset_input_hook.py

restoration.py

retrospective_runtime.py

retrospective.py

role_clear.py

role_context.py

runnable.py

selection.py

session_start_hook.py

state.py

successors.py

supervision_gate.py

supervision_hook.py

supervision_runtime.py

supervision.py

task_evidence.py

tier_routing.py

tiers.py

triggers.py

workflow_adoption.py

workflow_artifacts.py

workflow_batch.py

workflow_capacity.py

workflow_contract.py

workflow_dispatch.py

workflow_native.py

workflow_planning.py

workflow_profiles.py

workflow_readiness.py

workflow_recovery.py

workflow_release.py

workflow_rename.py

workflow_review.py

workflow_service.py

workflow_upgrade.py

workflow_workspace.py

antigravity.example.json

bootstrap-repository.py

compose-briefs.sh

config.example.json

foreman-tier-check.py

foreman.sh

label-workspaces.sh

measurements.py

native-hook.sh

observer-view.py

policy-paths.py

prepare-briefs.py

provision-worktree.sh

prune-report-caches.py

resolve-gates.sh

resolve-policy-paths.sh

review-package.sh

roster.sh

round-preflight.sh

SKILL.md

start-judge-worker.sh

state-schema.md

sweep-worktrees.sh

verify-authority.sh

wait-report.sh

workflow-review.py

README.md

tile.json