Install
Install with PiG
pig install npm:pi-herdr-orchestrationInstall with Pi
pi install npm:pi-herdr-orchestrationPackages run code with your permissions and influence agent behavior. Catalog inclusion is not a security audit. Review the source before installing a third-party package.
Pi manifest JSON
The pi field of package.json.
{
"skills": [
"./skills/pi-herdr-orchestrator",
"./skills/anthropic-small-business-pi",
"./skills/dev-flow"
],
"extensions": [
"./extensions/index.mjs",
"./extensions/capability-preflight.mjs",
"./extensions/workflow-autostart.mjs",
"./workflows/pr-follow.mjs"
]
}README
Written by the package's publisher, shown as published in version 1.6.0 (README.md). PiG does not review it.
Pi Herdr Orchestration
Deterministic, provider-agnostic multi-agent repository orchestration for coding agents. Dynamically coordinates task discovery, dependency graphs, isolated Git worktrees, terminal multiplexing with Herdr, and evidence-based verification across your entire development lifecycle.
The skill runs on Pi, Claude Code, OpenAI Codex, and Google Antigravity. It works out-of-the-box with plain Git and a single agent, and dynamically discovers optional high-leverage integrations at runtime: PiWorkflow, Pi Agent roster (list_agents), Gentle AI / Engram, Herdr, Guardian Angel (GGA), Engineering Excellence, Matt Pocock's skill suite, and context reduction engines.
Table of Contents
- Overview & Core Problems Solved
- Architecture & Workflow Lifecycle
- Cognitive Model & Decision Pipeline
- Skill Ecosystem Integrations
- PiWorkflow (
pi-extensible-workflowsv6.3.0) - Pi Extensible Roles (
@piewf/pi-ext-rolesv0.2.0) - Host Agent Roster (
list_agents) - Gentle AI Suite & Engram
- Engineering Excellence
- Matt Pocock Skill Suite
- Guardian Angel (GGA)
- Context Reduction & Semantic Navigation Stack
- Dynamic Routing Table
- Model-Fit Evidence Envelope
- PiWorkflow (
- Installation & Dependency Management
- Install the Skill via Vercel Skills CLI
- Dependency Bootstrap (System Runtimes & Skill Suites)
- Mandatory Per-Repository Initialization
- Environment Verification
- Docker Compatibility Matrix
- Local Factory Run
- Persisted Graph Supervisor
- PR-Following Workflow
- Optional Rust Graph Core
- Mailbox & Supervision Commands
- Talking Pane Title
- Run Budget & Usage Accounting
- Compaction & Overlap Rules
- Release and npm Trusted Publishing
- Sources & References
- License
Overview & Core Problems Solved
When AI coding agents are assigned complex multi-step backlogs, monorepo refactors, or concurrent issue queues, they typically encounter critical failure modes:
- Agent Sprawl & Race Conditions: Multiple agents editing the same files on the same branch create merge conflicts, clobbered changes, and broken git history.
- Context Window Degradation: Ingesting full transcripts, logs, and whole-codebase dumps degrades LLM attention, leading to hallucinations and sloppy code.
- Premature "Done" Claims: Agents claiming completion based on conversational prose rather than machine-verifiable test runs, linter passes, and runtime evidence.
- Coordination Debt: Parallelizing tasks that secretly share dependencies or API contracts, leading to integration disasters.
Pi Herdr Orchestration solves these problems deterministically. It establishes a strict division of labor, runs tasks in isolated Git worktrees under dedicated Herdr terminal panes, routes domain-specific skills on demand, and requires reproducible proof before any code is merged.
Architecture & Workflow Lifecycle
The Command Hierarchy: Master, Chiefs, and Workers
The orchestrator enforces a clean separation of concerns across three distinct operational tiers:
┌──────────────────────────────────────────────┐
│ [MASTER] Pi Herdr Orchestrator │
│ (Control plane, dependency graph, decisions)│
└──────────────────────┬───────────────────────┘
│
┌──────────────┬─────────────┼──────────────┬──────────────┐
▼ ▼ ▼ ▼ ▼
[CHIEF/SCOUT] [CHIEF/BUILD] [CHIEF/QUALITY][CHIEF/MEMORY] [CHIEF/AUDIT]
(Discovery) (Execution) (Verification) (Persistence) (Cleanup)
│ │ │ │ │
└──────────────┼─────────────┴──────────────┴──────────────┘
│
┌──────────────┴──────────────┐
▼ ▼
[I#42] Auth Fix [PR#18] Review
(Worktree .worktrees/i42) (Worktree .worktrees/pr18)
1. [MASTER] Pi Herdr Orchestrator (The Control Plane)
- Role: Owns the repository scope, backlog discovery, pairwise independence analysis, worktree reservations, merge queue, and final stop conditions.
- Golden Rule: The master never writes or implements code. A master session editing code while coordinating workers is an architectural defect.
2. Department Chiefs (Bounded Supervision)
When the host supports multiple sessions or subagents, the master delegates operational areas to specialized chiefs:
[CHIEF/SCOUT](Discovery & Triage): Maps monorepo boundaries, default branches, CI configurations, and clusters issues by root cause.[CHIEF/BUILD](Implementation & Worktrees): Provisions worktrees, assigns tasks to workers, and supervises progress.[CHIEF/QUALITY](Verification & Reviews): Orchestrates test execution, auto-grilling, adversarial reviews, and quality gates.[CHIEF/MEMORY](Hydration & Persistence): Recalls historical ADRs and conventions via Engram and writes durable post-task learnings.[CHIEF/AUDIT](Reconciliation & Teardown): Audits overall repository health and verifies resource cleanup.
Fallback: If the host cannot create independent subagents, the master flattens the hierarchy into structured phase headers without simulating false parallel execution.
3. Workers (Task Execution Sessions)
- Role: Execute a single, bounded contract (
[I#42],[PR#87],[REV#12]). - Contract Lifecycle: $$\text{DISCOVER} \longrightarrow \text{UNDERSTAND} \longrightarrow \text{PLAN} \longrightarrow \text{IMPLEMENT} \longrightarrow \text{VERIFY} \longrightarrow \text{SELF-REVIEW} \longrightarrow \text{HANDOFF} \longrightarrow \text{READY}$$
- Workers never declare themselves
READYuntil all validation commands pass and evidence is logged.
Tab Isolation with Herdr & Git Worktrees
The orchestrator guarantees clean workspace boundaries:
- 1 Task = 1 Branch = 1 Git Worktree = 1 Dedicated Session/Pane
- Single-Writer Rule: Exactly one writer modifies a given worktree at any time.
- Herdr Terminal Multiplexing:
- Each workflow agent launches in its own Herdr tab inside the workflow workspace, created in
parallel/pipelineadmission order and titled with a stable numbered label (#1 [CHIEF/SCOUT] Discovery,#2 [CHIEF/BUILD] Implementation). - PiWorkflow agents are launched with explicit
label,skills,extensions, and isolatedworktreeoptions. One named workflow run owns the tabs it launches; a new workspace or cwd happens only when the user explicitly requests it. - Terminal state and processes remain persistent and inspectable even during agent context switches; tab liveness never replaces mailbox or Git evidence.
- Each workflow agent launches in its own Herdr tab inside the workflow workspace, created in
Cognitive Model & Decision Pipeline
The orchestrator’s reasoning engine follows five deterministic principles:
1. Independence-First Dispatch & Task Graph
Concurrency is treated as an optimization tool, not an automatic default. Before dispatching any worker, the orchestrator constructs a dependency graph by performing pairwise relation analysis:
| Relation | Condition | Handling Strategy |
|---|---|---|
| Independent | Zero overlap in files, APIs, schemas, or migrations | Dispatched concurrently in isolated worktrees |
| Related | Common subsystem or feature domain | Grouped into a single session or an ordered chain |
| Sequential | Task B depends on the output of Task A | B waits until A merges or starts directly from A's branch |
| Conflicting | Overlapping files, database schemas, or infrastructure | Strictly serialized; base change landed first |
| Duplicate / Superseded | Redundant reports or obsolete requests | De-duplicated and closed with reference |
| Merge-Ready | Code already exists in branch/PR | Routed to review-only session (no new code authored) |
| Blocked | Missing architectural decision, API key, or spec | Held in queue; no worker session launched |
Before an implementer starts, the master records an ownership reservation in the task registry (e.g. frontend/auth/* -> I#42). Any subsequent task claiming that surface is blocked or queued.
2. Progressive Disclosure & Bounded Contexts
Model context windows are treated as scarce, depleting resources:
- Workers never receive a full dump of the repository, entire issue backlogs, or preceding conversation transcripts.
- Each worker receives a bounded brief: exact objective, issue context, allowed and forbidden file scope, required verification commands, and completion criteria.
- Domain skills are loaded only into the specific sessions that need them, keeping the master session lean.
3. Evidence-Based Validation (Proof Before Claim)
Prose claims of success are rejected. Validation follows a strict narrow-to-wide verification funnel:
- Targeted Unit / Regression Check: Failing reproduction test first, followed by minimal fix and passing test.
- Package-Level Suite: Ensures no localized regressions.
- Type-Check & Linter: Compiler and static analysis passes.
- Package Build: Artifact compilation verification.
- Integration / E2E: Cross-package compatibility.
- Docker Compose / Runtime Validation: Starting disposable stacks to check service startup, migrations, health checks, and API connectivity.
- Browser / UI Verification: Checking rendering, responsiveness, console logs, network errors, and accessibility.
Every check is logged as PASS, FAIL, BLOCKED, or NOT RUN. A check marked NOT RUN is never treated as passing.
4. Non-Polluting Compact State Protocol
Parent sessions never ingest worker transcripts. All cross-session communication uses the canonical repo-orchestrator/v1 JSON envelope:
{
"v": "repo-orchestrator/v1",
"kind": "result",
"id": "r_20261008_042",
"parent": "chief-build-01",
"run": "repo-run-10",
"sender": {
"role": "implementer",
"session": "pi-i42",
"tab": "[I#42] Config loading",
"worktree": ".worktrees/issue-42-config-loading"
},
"task": { "id": "I#42", "type": "issue", "goal": "Fix config loading precedence" },
"state": "READY",
"branch": "fix/42-config-loading",
"summary": "Config precedence now prioritizes environment variables over file defaults.",
"checks": [
{ "name": "unit", "status": "PASS", "ref": "test-run-884" },
{ "name": "types", "status": "PASS", "ref": "tsc-clean" },
{ "name": "gga", "status": "PASS", "ref": "gga-hash-cache" }
],
"evidence_ref": "ref:sha256:2df2a23aa02e0171",
"decisions": ["Preserve backward compatibility for legacy JSON configurations."],
"risks": [],
"blockers": [],
"memory": { "task": "I#42", "run": "repo-run-42", "candidate": "<full-commit-id>", "status": "PERSISTED", "ref": "engram:obs-88219", "receipt": "ref:sha256:<provider-receipt-hash>" },
"next": "chief-review"
}
Human-readable Markdown reports (such as the cycle dashboard) are generated directly from these structured envelopes.
5. Multi-Agent Supervision & Context-Preserving Architecture
Dispatched sessions that operate without supervision or feedback loops lead to silent failures, runaway tokens, or deadlocks. Real-world multi-agent orchestration operates like an executive corporate office: master coordinates, workers execute, and communication strictly protects model context windows.
How the Architecture Preserves and Improves Context Windows
- Semantic Evidence Offloading (
ref:sha256:...):- The Problem: Dumping 300+ lines of raw
npm test, compiler diagnostics, or multi-file git diffs directly into conversation tokens pollutes attention, degrades reasoning, and forces premature, lossy compaction. - The Fix: Raw artifacts are SHA-256 hashed and stored on disk under
<git-common-dir>/orchestrator/<run>/evidence/<sha256>.txt. Only the immutable referenceref:sha256:...transits through prompts. The master inspects raw evidence only by exception.
- The Problem: Dumping 300+ lines of raw
- Native Pi Extension (
extensions/index.mjs) vs Subshell Clutter:- The Problem: Repeatedly spawning subshells (
node scripts/mailbox.mjs ...) injects shell process wrappers, terminal ANSI codes, and stderr noise into conversation history. - The Fix: Native in-process Pi tools (
orch_report,orch_status,orch_ask,orch_reply,orch_evidence) communicate purely via in-memory JavaScript objects and JSON files, bypassing shell noise completely.
- The Problem: Repeatedly spawning subshells (
- Prompt Cache Continuity:
- Static brief headers, role definitions, and invariant repository rules are anchored at the prefix of worker prompts. Dynamic per-task arguments are appended at the end. This guarantees maximum prompt cache hits on upstream providers (Anthropic, OpenAI, Gemini), dramatically cutting latency and API costs.
- Bi-directional Ask / Reply Protocol (
orch_ask/orch_reply):- When a worker encounters an ambiguous architectural question or missing credential, it invokes
orch_ask, setting its state toBLOCKEDwith flagASK. - The master sees the question and its
message_idin the supervision dashboard, provides an explicit decision viaorch_replywith thatquestion_id, and automatically transitions the worker back toWORKINGwithout hanging or busy-polling; stale answers are rejected.
- When a worker encounters an ambiguous architectural question or missing credential, it invokes
- Cross-Platform Directory Locking (
lock.mjs):- Protected by atomic directory locks using
node:pathbasename, ensuring zero file corruption or interleaved JSON writes even when 4–6 parallel Herdr panes report simultaneously across Linux, macOS, or Windows.
- Protected by atomic directory locks using
- Continuous Herdr Supervision Loop:
- Master stays active, reconciling mailbox states with live Herdr process liveness (
working,idle,done,blocked):OK: Healthy and reporting on schedule.ASK: Worker submitted a blocking question awaiting master reply.DECIDE: Worker reported terminal state (READY,DEVELOPMENT,BLOCKED,FAILED). Master reconciles with Git/CI.SILENT: Agent is idle in Herdr but last mailbox report wasWORKING. Master reads recent pane output and nudges.STALE: Agent is working in Herdr but has not reported within the stale threshold (default 10 minutes).NEEDS_HUMAN: Herdr recognizes an approval or question dialog; master escalates to the human operator.GONE: Worker agent process missing from Herdr; master checks the worktree and restarts if needed.
- Master stays active, reconciling mailbox states with live Herdr process liveness (
- Interactive TUI Command (
/orch):- Instant visual fleet status directly inside the active Pi session without context pollution.
Current Herdsman alignment
The orchestration contract follows current upstream Herdsman (boadij/pi-herdsman) supervision semantics:
- State compatibility & derived lifecycle: Preserves the canonical uppercase states (
ASSIGNED,WORKING,READY,DEVELOPMENT,BLOCKED,FAILED,CLOSED) unchanged and derives an optional local lowercase lifecycle field (pending,running,ready,blocked,failed,closed) for consumers that want a normalized projection. The derived field is local, not a wire contract: no migration is required and legacy consumers keep reading uppercasestate. Upstream Herdsman publishes a different, assignment-centric public set (working,blocked,settling,unknown,lost); values without a local mapping deriveunknownand fail closed instead of being guessed. - Deduplicated full SHA-256 evidence store: Large logs and diffs are hashed to full 64-char SHA-256 content-addressed files under
evidence/<sha256>.txtand referenced asref:sha256:<hash>. Evidence is inspectable on demand viareadEvidence/orch_evidencewithout copying raw payloads into model prompts. - Candidate-bound terminal evidence:
READYandCLOSEDare accepted only with the exact task, run and immutable candidate identity plus a passing review whose reviewed-file hashes and deletion hashes match the candidate tree and persisted Engram memory for the same identity. A missing, failed, stale or cross-candidate review is persisted asBLOCKED, including aCLOSEDreport for a task with no code change. Terminal states are coordination only: they never authorize push, merge, publication or worktree removal. - Non-blocking notifications: Notifications to master sessions (
herdr agent prompt) run non-blockingly (spawnunref) so delivery issues or unavailable Herdr runtimes cannot block mailbox report persistence or turn a completed task into a false failure. - Fail-closed supervision: Terminal agent states that report
unknownliveness fail closed toDECIDE, mandating that the master reconcile with Git and CI before proceeding rather than assuming tasks are healthy. - Operational boundaries: Role-derived Herdr pane and agent labels (
Lead,Managed Lead,Manager,Chief) are presentation only. Chiefs coordinate and normalize reports within their bounded department; they never perform destructive worktree operations without explicit confirmation from the Master control plane. - Capability-aware dispatch: Select Agents by effective runtime capabilities, not filenames or configured child names. If no suitable child is available, investigate locally and record the capability gap instead of simulating delegation.
- Simulation before live smoke: Prefer deterministic simulated smoke for covered Pi/Herdr boundary scenarios; use live-model smoke when model/provider behavior or instruction adherence is under test.
- Nonterminal execution failure: Treat model execution failure as nonterminal evidence: do not retry automatically, replay tools, stop children, integrate partial work, or publish a successful handoff.
- Terminal failure envelope: A dispatched branch that times out or aborts is classified as
MODEL,CAPABILITY,HERDR,TIMEOUTorUNKNOWNfrom recorded evidence before anything is retried. A run with a timed out branch returnsPARTIALwith every completed sibling result preserved, and recovery only re-dispatches branches without observed side effects.skills/pi-herdr-orchestrator/scripts/fanout-retry.mjsresolves the observation intoFANOUT_COMPLETED,FANOUT_RETRY_BOUNDED,FANOUT_RETRY_EXHAUSTEDorFANOUT_SIDE_EFFECTS_UNCERTAIN, and the graph records afailtransition before any boundedretryso the exact attempt reason stays inevents.jsonl. See supervision.md.
These points are aligned with upstream boadij/pi-herdsman v0.55.0 (2026-11-25, main at 5b5f2464): nonblocking notify_owner that leaves assignment completion eligibility untouched and requires persisted owner receipt (docs/concepts/lifecycle.md), an assignment-centric public state projection where physical unknown fails closed, and role-scoped supervision authority (docs/coordination-api.md). The earlier alignment sources 0dc62d39, a422c804, c72acadf, 44698e40, 56bd0258 and 321114de (October 2026) remain the reference for presentation-only labels and simulated-smoke-first verification. Upstream capabilities this repository does not implement are recorded in coordination.md.
6. Two-Tier Integration & Merge Queue
The master categorizes completed work based on empirical evidence:
STABLE: All acceptance criteria, tests, and reviews pass. Ready to merge or publish to the primary branch (main).DEVELOPMENT: Incomplete, exploratory, or partially verified work. Preserved on an isolated feature branch with a documented handoff state.
Before merging individual green branches into main, the master executes an Integration Pass on the combined branch. Independent tasks that pass in isolation can still conflict when combined; the integration pass prevents broken main branches. A successful pass does not authorize delivery: commit, merge, and publish still require explicit operator authorization.
When a change reaches beta, staging, production, or a live runtime claim, the master follows the ordered production lifecycle: immutable artifact promotion with no rebuild between environments, a fresh temporary PiWorkflow/Herdr runtime smoke that observes the exact candidate, explicit approval gates, post-deploy health evidence, and a rollback decision. Documentation-only changes record the inapplicable stages explicitly.
Skill Ecosystem Integrations
Pi Herdr Orchestration dynamically bridges and routes between major AI coding agent skill ecosystems:
PiWorkflow (pi-extensible-workflows v6.3.0)
- Role: Execution engine substrate. PiWorkflow is the single child scheduler: it owns workflow lifetime, waits for independent child results, and returns the normalized result to the Master Chief. Pi Herdr Orchestration owns scope, routing, supervision, integration, and cleanup; Herdr tabs and panes are inspectable transport and presentation only, never a second scheduler.
- Capabilities Used:
- Deterministic orchestration:
workflow,parallel(...),pipeline(...),withWorktree(...),shell(...), and persistentagent.create(...)handles. - Explicit child loadouts: Every routed child receives a named
@piewf/pi-ext-rolesrole, stablelabel, verifiedskillsselectors reset with!*,extensionsreset with!*and then set to["builtin:codemode", "builtin:tool-search", "builtin:mcp"], no presettimeoutMsor budget, and an isolatedworktreewhen it writes.builtin:codemodeis the stable bridge to MCP tools. Resetting inherited selectors prevents an unrelated unavailable role default such asdesign-tastefrom blocking a non-visual task before dispatch. - Fully inspectable Herdr transport: Repository initialization writes trusted
.pi/pi-extensible-workflows/settings.jsonwithextensionSettings.herdr.enableFullyInspectableMode: true. When Pi runs inside Herdr and@piewf/herdris loaded, every workflow agent launches as its own numbered, labeled tab inside the workflow workspace, in admission order; each write-capable agent keeps its isolated worktree. - Aggregated Telemetry (#318): Automatic calculation of elapsed execution time and total token usage per phase and function, including nested child agents.
- Effort-Aware Model Resolution (#314): Native parsing and propagation of namespaced and colon-bearing model strings (
cliproxyapi/claude-opus-5-5:high,cliproxyapi/gemini-3.8-flash-high). - Reliable Lock Ownership: Records the owner PID and reclaims stale locks only when the recorded process is no longer alive, avoiding deletion of active locks.
- Workflow Recovery: Replaying completed operations through
workflow_status,workflow_retry, andworkflow_resume.
- Deterministic orchestration:
Example dispatch inside a named workflow (name: "repository-audit"):
const reports = await parallel("repository-audit", {
scout: () => agent("Map the repository.", {
role: "scout",
label: "#1 [CHIEF/SCOUT] Discovery",
skills: ["!*", "pi-herdr-orchestrator", "engineering-excellence", "diagnosing-bugs"],
extensions: ["!*", "builtin:codemode", "builtin:tool-search", "builtin:mcp"],
worktree: "scout",
}),
tests: () => agent("Define and run focused checks.", {
role: "tests-expert",
label: "#2 [CHIEF/QUALITY] Tests",
skills: ["!*", "pi-herdr-orchestrator", "engineering-excellence", "tdd"],
extensions: ["!*", "builtin:codemode", "builtin:tool-search", "builtin:mcp"],
worktree: "tests",
}),
});
return reports;
Launch named workflows with foreground: true and no budget; omit timeoutMs on child agents because Vekexasia's runner treats omission as no timer. Use pipeline(...) for ordered stages. Native subagents_run is forbidden for orchestration. Do not use Promise.all/map agent fan-out, omit required roles or extensions, or claim Herdr tabs when the runtime capability report says Herdr is unavailable; a missing requested skill is BLOCKED before dispatch, and an unavailable Herdr or PiWorkflow transport is reported as NOT APPLICABLE instead of being faked. Run the read-only MCP smoke check with node skills/pi-herdr-orchestrator/scripts/check-mcp.mjs --json --timeout-ms 2000; it reports redacted transport reachability and HTTP health status without printing credentials, arguments, or environment values. A URL MCP initialize probe verifies the HTTP MCP endpoint when it returns a protocol response; stdio executable probes remain unverified because they do not start the server.
Pi Extensible Roles (@piewf/pi-ext-roles v0.2.0)
- Role: Independent role authoring, configuration, and runtime preparation.
- Capabilities Used:
- Reusable Markdown role definitions (
roles/*.md) with tool, skill, and context file selectors. - Independent CLI inspection:
pi-role --identify <role>prints the resolved file path and complete role frontmatter. - Native workflow preparation adapter (
registerRolePreparationHook) decoupling roles from the workflow core.
- Reusable Markdown role definitions (
Host Agent Roster (list_agents)
- Role: Live discovery of effective Agent definitions available to the current controller.
- Capability contract: Use the roster result to select Agents by effective capabilities; a configured definition is not proof that it is runnable.
- Failure contract: If roster validation fails, report
BLOCKEDwith the exact definition path and field error. Do not simulate delegation or infer availability from filenames. - Roster diagnostic:
scripts/agent-roster-diagnostic.mjsvalidates a roster read-only.inspectAgentRoster({ definitions, errors })parses names,toolsarrays and delegation fields (mode,thinking);readAgentRoster({ root, readdir, readFile })adds a filesystem that is injectable for deterministic tests. The report carriesstate(healthy,malformed,unavailable),verdict(usable,blocked),usableAgents(name,path, declaredtools) orproblemsentries with the exact definition path, field and error. Object entries such as- "*": falseare malformed tools. A malformed or unavailable roster reportsblocked, an emptyusableAgents, and never authorizes delegation;assertUsableRoster(report)throws before dispatch instead of simulating one. - Roster command:
npm run test:roster;node scripts/agent-roster-diagnostic.mjs --root ~/.pi/agent/agentsprints the JSON report and exits non-zero when the roster is blocked. - Supported repair path: Back up the external definition, change only its YAML frontmatter so
toolsis an array of non-empty strings (for exampletools:\n - read), remove object entries such as- "*": false, then calllist_agentsagain and record the refreshed roster. On 2026-11-26 this repaired nine host definitions andlist_agentsthen reported a valid roster.
Gentle AI Suite & Engram
- Role: Harness discipline, durable memory, and review authority.
- Capabilities Used:
gentle-engram: Persistent project memory across sessions, hydration of historical decisions, cross-agent handoffs.work-unit-commits: Atomic, reviewable, self-contained commit slices.chained-pr: Splitting changes exceeding 400 lines into stacked, reviewable PR chains.gentle-ai-branch-pr: Issue-first branch and PR creation with human-in-the-loop confirmation.gentle-ai-rdd-defect-workflow&gentle_review: Receipt-Driven Development with cryptographic review lineages.judgment-day: Blind dual or adversarial reviews for high-stakes changes.gentle-ai-issue-creation&gentle-ai-rdd-defect-workflow: Issue creation and receipt-backed defect correction when installed and listed by the capability report.
Engineering Excellence
- Role: Software engineering standards, architecture, and production readiness.
- Capabilities Used: SDD (Spec-Driven Development), TDD standards, quality gates, security audits, performance profiling, accessibility/i18n standards, Docker/CI rules,
container-test-matrixfor multi-distribution testing, and context budgeting.
Matt Pocock Skill Suite
- Role: Tactical developer workflows and problem breakdown.
- Capabilities Used:
triage: Classifying incoming issues and bug reports.wayfinder&to-spec: Navigating fuzzy, ambiguous tasks into actionable specifications.to-tickets: Decomposing specifications into atomic ticket graphs with explicit blocking edges.diagnosing-bugs: Tight reproduction loops before code changes.codebase-design&improve-codebase-architecture: Seams, deep module boundaries, and interface contracts.grill-with-docs/grill-me: Adversarial stress-testing of plans and design assumptions.retro: Retrospective learnings capture.
Guardian Angel (GGA)
- Role: Provider-agnostic pre-commit and pre-PR quality gate.
- Capabilities Used:
- Reviewed by default via
kilo:cliproxyapi/gemini-3.8-flash-highwith high reasoning effort. - Bridge integration
agents/gga-pi/routing reviews directly throughpi --printto the local CLIProxyAPI gateway. - Verifies git diffs, rules, and repository invariants after tests and before declaring a worker
READY. Uses hash caching to ensure idempotent verification.
- Reviewed by default via
Context Reduction & Semantic Navigation Stack
- Role: Token preservation and AST-level exploration.
- Capabilities Used:
- Serena: Language-server backed semantic code navigation (symbol search, call graphs) without exploratory file reads.
- graphifyy & LLMLingua: Code knowledge graph construction and prompt token reduction.
- RTK & sqz: Output compression and terminal filtering for large test logs and build output.
- Wizard-AI: Compatibility manager for TOON/LEA tabular data encodings.
Dynamic Routing Table
The orchestrator dynamically routes tasks to the minimal sufficient skill set based on the situation:
| Situation | Minimal Selected Method (First Installed Wins) |
|---|---|
| Raw issue or untriaged PR | Root-only Matt Pocock triage; issue-ops; gentle-ai-issue-creation only when the capability report lists it |
| Backlog sharing common root causes | Root-only analysis with issue-ops; no child selector for uninstalled systemic-issue-triage / issue-root-resolution |
| Ambiguous requirement or design doubt | Matt Pocock grill-with-docs (grill-me), or targeted user question |
| Large ambiguous feature | Root-only Matt Pocock wayfinder $\rightarrow$ to-spec; Engineering Excellence sdd reference |
| Decomposing plan into work items | Matt Pocock to-spec $\rightarrow$ to-tickets; Engineering Excellence sdd |
| Reproducible or hard bug | Matt Pocock diagnosing-bugs $\rightarrow$ tdd regression test; Gentle AI gentle-ai-rdd-defect-workflow |
| Defined feature implementation | Matt Pocock implement (tdd $\rightarrow$ review $\rightarrow$ operator-authorized commit); EE sdd + tdd |
| Refactoring | Behavior-preservation tests first (tdd); Matt Pocock codebase-design |
| Infrastructure / Containers / CI | Engineering Excellence docker, ci, production-readiness; container-test-matrix |
| Production delivery or live runtime verification | Pi Herdr Orchestration production-lifecycle; Engineering Excellence production-readiness, ci-cd-and-publishing |
| Security or Performance Audit | Engineering Excellence security, performance |
| Candidate Code Review | Matt Pocock code-review; Gentle AI judgment-day (dual review); Guardian Angel before READY |
| Commit Creation & Pull Request | Gentle AI gentle-ai-work-unit-commits or work-unit-commits, gentle-ai-chained-pr or chained-pr (>400 lines), gentle-ai-branch-pr; Matt Pocock pr |
| Context Pressure & Session Handoff | Gentle Engram handoff; Matt Pocock handoff; EE context-budget |
Model-Fit Evidence Envelope
The canonical matrix above states configuration, not availability. Model access, entitlement and quota evidence is owned by pi-model-fit and reaches the orchestrator only through a versioned, read-only envelope consumed by skills/pi-herdr-orchestrator/scripts/model-fit-evidence.mjs:
{
"schema": "pi-model-fit-evidence/1",
"source": "pi-model-fit",
"generatedAt": "2026-11-26T11:30:00.000Z",
"evidenceRef": "pi-model-fit/reports/2026-11-26.md#role-matrix",
"routes": [{ "route": "cliproxyapi/claude-opus-5-5:high", "outcome": "PASS" }]
}
readModelFitEvidence(envelope, { now, freshnessMs }) accepts only explicit PASS, UNKNOWN, BLOCKED, and NOT RUN outcomes, preserves evidenceRef, and fails closed: a malformed, foreign-source, stale (default 24 h), future-dated, or unavailable envelope returns BLOCKED or UNKNOWN instead of a route decision. Mixed route outcomes collapse to the worst one (BLOCKED > UNKNOWN > NOT RUN > PASS), the clock and freshness window are injectable for deterministic tests, and routing is always reported as unchanged. The reader writes nothing, never infers entitlement, quota or availability from a static matrix, and never invokes SkillOpt.
npm run test:model-fit
Installation & Dependency Management
Install the Skill via Vercel Skills CLI
Install the skill for any supported agent directly from GitHub:
# Global installation across supported agent runtimes
npx skills add darkrei08/pi-herdr-orchestration \
--skill pi-herdr-orchestrator \
--agent codex claude-code antigravity antigravity-cli pi \
--global
Or from a local clone:
npx skills add . \
--skill pi-herdr-orchestrator \
--agent codex claude-code antigravity antigravity-cli pi \
--global
Anthropic Small Business on Pi
The official Anthropic Small Business plugin remains owned by Claude. Pi consumes its 44 upstream SKILL.md files from the canonical shared skill root and adds the anthropic-small-business-pi adapter for PiWorkflow routing, approvals, memory, artifacts, and connector policy. Do not auto-import the plugin's 35 remote MCP definitions.
After installing or updating the Claude plugin, verify the Pi copy and adapter:
npm run check:anthropic-small-business
npm run test:anthropic-small-business
Select the adapter together with the exact upstream skill in PiWorkflow. The checker must report 44/44 skills, matching canonical copies, valid frontmatter, and zero Pi-configured Anthropic connectors unless each connector was separately authorized and configured.
Dependency Bootstrap (System Runtimes & Skill Suites)
The Vercel Skills CLI installs skill definition files only; it deliberately does not run third-party installers or post-install scripts. Run the dependency bootstrap script to inspect missing dependencies and install required runtimes as well as all 4 required skill suites (Engineering Excellence, Matt Pocock skills, Gentle AI skills, and Pi Herdr Orchestration):
# 1. Read-only dry run (inspects existing software/skills and prints a plan)
node scripts/bootstrap.mjs
# or: npm run bootstrap
# 2. Apply installations (requires explicit --apply flag)
node scripts/bootstrap.mjs --apply
# or: npm run bootstrap:apply
Mandatory Per-Repository Initialization
Every project or repository orchestrated by this skill must be initialized before workers begin execution. Run the repository initialization script:
# 1. Dry run in current repository
node scripts/init-repo.mjs
# or: npm run init-repo
# 2. Apply repository initialization
node scripts/init-repo.mjs --apply
# or: npm run init-repo:apply
# Or target a specific repository path:
node scripts/init-repo.mjs --dir /path/to/my-repo --apply
# Explicitly opt in to project-local CodeGraph indexing and sqz hooks:
node scripts/init-repo.mjs --dir /path/to/my-repo --apply --codegraph --sqz
This command automatically configures:
- Git Baseline: Ensures repository initialization on
mainand creates.worktrees/. - Gitignore Rules: Appends
.worktrees/,.codegraph/, and.atl/to.gitignore. - PiWorkflow + Herdr transport: Writes trusted
.pi/pi-extensible-workflows/settings.jsonwithextensionSettings.herdr.enableFullyInspectableMode: true, preserving existing workflow settings and unrelated keys so workflow agents launch as ordered numbered tabs. - Engram Memory Identity: Generates
.git/engram-project-identity.jsonfor isolated, persistent repository memory. - Guardian Angel (GGA): Creates
.ggaquality-gate configuration and baselineAGENTS.mdguidelines. - Semantic Code Navigation: Deploys Serena project configuration for LSP symbol analysis.
- CodeGraph: Optionally creates a worktree-local
.codegraphindex when requested with--codegraph; ephemeral test worktrees remain unindexed. - Token Compression: Installs the Claude project-local
sqzhook only when explicitly requested with--sqz, skipping when.claude/settings.local.jsonalready exists; detects globalrtkfor terminal and tool reduction. - Herdr Workspace: Registers the named Herdr workspace that hosts workflow agents as ordered, numbered tabs.
- Skill Registry: Catalogs all available skills into
.atl/skill-registry.md.
Environment Verification
Run the read-only capability and host compatibility check:
# Output JSON report
node scripts/check.mjs --json
# or: npm run check:json
# Strict validation (exits nonzero if core runtimes or compaction conflicts exist)
node scripts/check.mjs --strict
# or: npm run check:strict
Docker Compatibility Matrix
scripts/docker-matrix.mjs verifies the cross-platform claims of fast-anything v0.8.5 and optimaizr v0.14.0 against pinned Linux families. It never pulls images and never treats a missing image or runtime as success.
| # | Row | Image |
|---|---|---|
| 1 | debian-13 | debian:13 |
| 2 | ubuntu-24-04 | ubuntu:24.04 |
| 3 | fedora-42 | fedora:42 |
| 4 | archlinux | archlinux:latest |
| 5 | opensuse-tumbleweed | opensuse/tumbleweed |
| 6 | alpine-3-22 | alpine:3.22 |
| 7 | node-24 | node:24-bookworm-slim |
npm run docker:matrix:list # deterministic row listing, no Docker daemon contact
npm run docker:matrix # sequential run, local images only
Every container is started with --rm --pull=never --network none --cap-drop=ALL --security-opt=no-new-privileges --read-only, bounded CPU/memory/PIDs, the repository mounted read-only at /repo, a writable bind mount at /state used as HOME, and a tmpfs at /tmp. Only HOME=/state is injected; no secret or host environment variable reaches the container.
Statuses and exit codes:
| Status | Meaning |
|---|---|
PASS | Image present, node scripts/lint.mjs and npm test passed inside the container |
FAIL | Image present and a repository check failed |
BLOCKED | Image absent locally (pulls are disabled) or node/npm unavailable in the row |
NOT RUN | Docker daemon unavailable, so no row was inspected or executed |
Exit code is the highest observed rank: 0 all PASS, 1 any NOT RUN, 2 any BLOCKED, 3 any FAIL.
Evidence requirements for a support claim:
- Paste the full
npm run docker:matrixoutput, including thedocker-server=line, one line per row, and thesummaryline; record the command exit code. - A row counts only as
PASSwhen its own line saysPASS. Absent images and missingnode/npmmust be reported asBLOCKED, and a stopped Docker daemon asNOT RUN. rustc,cargo,fast-anythingandoptimaizrare probed in every row and listed inruntimes=; a missing binary is a gap, never a pass.- A family without a
PASSline is unverified and must be described as such; macOS and Windows rows are not covered by this matrix.
Local Factory Run
npm run factory executes the repository-owned deterministic gates in one read-only pass and reports each one separately as PASS, FAIL, BLOCKED or NOT RUN: capability preflight (node scripts/check.mjs --strict), host roster status (node scripts/agent-roster-diagnostic.mjs), bounded fan-out and timeout handling (npm run test:fanout), the isolated commit gate (npm run test:fixture), then git diff --check, npm run lint and npm test.
npm run factory
npm run factory -- --json
Live Herdr pane fan-out and live PiWorkflow agent dispatch are always reported as NOT RUN, because the runner starts no session, writes no mailbox record, and creates no worktree or process. Gate order, status meanings, cleanup checks and the report template are in docs/local-factory-run.md.
Read-only profiling
The perf:scan wrapper exposes only doctor, scan, and list-candidates from fast-anything. It runs an allowlisted repository script under the profiler and writes a bounded Markdown report to reports/; it never runs port, verify, enable, disable, or bench.
npm run perf:scan -- doctor
npm run perf:scan -- list-candidates
npm run perf:scan -- scan --date 2026-11-22 scripts/flow-sources-check.mjs
Persisted Graph Supervisor
The graph supervisor is a separate mutable scheduling layer from any read-only execution-graph report. It stores versioned state under <git-common-dir>/orchestrator/<run>/graph/graph.json and append-only transitions in events.jsonl. skills/pi-herdr-orchestrator/scripts/graph-supervisor.mjs accepts immutable trajectory and mailbox records, normalizes legacy uppercase mailbox states, plans waits-for dependencies deterministically, and persists bounded transitions.
The graph supports run, phase, task, agent, worktree, PR, gate, wait, decision, and artifact nodes. Its edge types are contains, delegates, runs-in, checks, waits-for, reports, retries, and produces. Budget limits are checked before transitions; wait and human checkpoint actions do not invoke a model. Missing Herdr data produces a null projection and never discards the persisted graph.
Inside Pi, use the bounded native controls:
orch_graph_status # read graph plan, bounded nodes, and best-effort Herdr projection
orch_graph_step # apply one validated advance/start/complete/wait/poll/pause/resume/fail/retry action
The fail transition (running/waiting/ready/pending to failed with a bounded failure_reason, default unreported) is how a branch that ended without a terminal report reaches the graph before any retry. The status override belongs to complete only; fail always records failed.
The schema is schemas/repo-orchestrator-graph-v1.json. These controls never merge, publish, or replace PiWorkflow as the execution authority.
PR-Following Workflow
The registered PiWorkflow function prFollow follows exactly one issue or pull request from id validation to merge readiness. It takes { target: "issue" | "pr", id, merge? }, rejects a mismatched or non-existent id before launching any agent, runs developer/reviewer cycles, forwards external bot findings verbatim to the next cycle (cap: 3 cycles, then BLOCKED), and polls CI, review and mergeability every 60 s up to 30 attempts without consuming a model call. A merge authorization asks through orch_ask, pauses the run, and resumes from the orch_reply answer without repeating completed work. Every transition reports through orch_report, so orch_status shows the current phase. The function registers through pi.extensions in package.json; the contract, reason codes and dry-run command are in docs/pr-follow-workflow.md.
Optional Rust Graph Core
The repository includes an optional dependency-free Rust implementation of the graph supervisor's deterministic waits-for planning step. It is deliberately limited to pure graph planning: Pi extension loading, Herdr transport, mailbox liveness and filesystem locking remain JavaScript host boundaries.
npm run check:rust
npm run test:rust
npm run graph:plan:rust < graph.json
JavaScript remains the authoritative runtime. See docs/rust-core.md for the protocol, rationale and fallback behavior.
Mailbox & Supervision Commands
Supervise distributed worker sessions and inspect the shared mailbox:
# Check current run status and flagged tasks against Herdr agent liveness
node scripts/mailbox.mjs status --run <run-id>
# or: npm run mailbox:status -- --run <run-id>
# Run the zero-dependency source linter and unit tests
npm run lint
npm test
# Native Pi interactive inspection (inside an active Pi session):
/orch
The report inspects:
- Core prerequisites: Node.js, Git, and Skill definitions.
- Agent runtimes: Pi, PiWorkflow, Gentle AI / Engram, Guardian Angel (GGA), and Herdr.
- Supporting CLIs: GitHub CLI (
gh), Docker, and Docker Compose. - Installed skill suites: Engineering Excellence, Matt Pocock, and Gentle AI.
- Context tooling: Wizard-AI, Serena, graphifyy, RTK, and sqz.
- Active Pi compaction owner.
Talking Pane Title
Every orch_report call renames the reporting agent's Herdr pane so the tab shows who is developing, waiting, or blocked without asking. The exact command issued is:
herdr pane rename <PANE_ID> <TASK> <LIFECYCLE>
<PANE_ID> is the pane identity already stored for the task, else the report's pane parameter, else HERDR_PANE_ID. <LIFECYCLE> is derived from the persisted mailbox state and upper-cased, so the label is deterministic and never contains caller free text such as the summary, phase, or branch: ASSIGNED gives I#84 PENDING, WORKING and DEVELOPMENT give I#84 RUNNING, READY gives I#84 READY, BLOCKED gives I#84 BLOCKED, FAILED gives I#84 FAILED, CLOSED gives I#84 CLOSED, and a PR#127 report gives PR#127 RUNNING. A report downgraded on write is labelled with the stored state: READY or CLOSED without a candidate and fresh evidence binding is persisted as BLOCKED and labelled I#84 BLOCKED.
The rename is presentation only. When no pane identity is known, or Herdr is absent or rejects the command, the report is still persisted and the extension emits an ORCH_PANE_LABEL_SKIPPED warning instead of failing. Pane titles never replace mailbox or Git evidence.
Run Budget & Usage Accounting
Every orch_report persists a run-level usage record next to the task, so the cost of a long loop is visible while it runs instead of after it ends:
{
"usage": {
"agent_launches": 12,
"wall_ms": 1440000,
"tokens": 9200000,
"cost_usd": 41.5,
"phases": { "PLAN": 120000, "IMPLEMENT": 1320000 },
"last": { "agent_launches": 2, "tokens": 410000, "cost_usd": 1.9, "wall_ms": 240000, "phase": "IMPLEMENT" }
}
}
last holds the deltas since the previous report; the top-level fields are the accumulated run totals. wall_ms is measured from the injected clock, so it is always known, and elapsed time is credited to the reporting phase; the first report of PLAN reads phases.PLAN: 0. agent_launches, tokens, and cost_usd are supplied by the runtime through orch_report's usage parameter and are recorded as the string unknown whenever the runtime does not expose them. An unknown metric also makes the accumulated total unknown, because a partial sum cannot be reported as a total. Unknown is never coerced to zero.
A per-run ceiling is configured per call with orch_report's budget parameter, or once for a run with ORCH_RUN_BUDGET holding the same JSON object:
ORCH_RUN_BUDGET='{"tokens": 2000000, "cost_usd": 25, "wall_ms": 28800000, "agent_launches": 40}' \
node scripts/mailbox.mjs report --run <run-id> --task I#84 --state WORKING --summary "cycle 9"
The recognized dimensions are agent_launches, wall_ms, tokens, and cost_usd; any other key is rejected. The ceiling is checked on each state transition before the write. When an accumulated total passes its limit, that report is persisted as BLOCKED and the record carries the breached dimension:
{ "budget_block": { "dimension": "tokens", "limit": 2000000, "observed": 2130000 } }
The orch_report result repeats it as [BUDGET tokens 2130000>2000000]. A CLOSED report is not downgraded, and an unknown dimension can never prove a breach, so it never blocks a run that exposes no metrics. To continue after raising the ceiling, re-report the transition with a new id, because an already-delivered message id is still treated as a replay.
orch_status and node scripts/mailbox.mjs status show the accumulated usage next to every task in the Usage column (launches=12 wall=24m tokens=unknown cost=unknown), prefixed with the breached dimension when the task is blocked by the ceiling.
Compaction & Overlap Rules
To prevent conflicting hooks and transcript corruption, the orchestrator enforces strict overlap guards:
- Pi Compaction Ownership: Under Vekexasia's dotenv model,
pi-codex-contextis the sole third-party compaction owner. The bootstrap intentionally skips@sting8k/pi-vcc. Multiple active compaction owners trigger anincompatibleerror and halt. - Workflow & Memory Ownership: If Gentle AI / Engram or PiWorkflow is active, the orchestrator blocks the installation of overlapping Wizard-AI workflow, proxy, or memory modules, allowing only non-overlapping context tools (graphifyy, LLMLingua).
- Guardian Angel (GGA): The bootstrap installs the
ggabinary but never runsgga initorgga installautomatically, preserving repository configuration.
Release and npm Trusted Publishing
Release tags must match the package.json version. The GitHub Actions workflow uses npm Trusted Publishing through OIDC; it does not depend on a long-lived NPM_TOKEN for normal releases. The one-time package bootstrap, npm login, npm trust, 2FA, GAT deprecation, and reusable commands are documented in docs/releasing.md.
Sources & References
The architecture and routing logic follow the published interfaces and documentation of these upstream projects:
- Vercel Agent Skills: Specification and CLI for universal cross-agent skill installation.
- OpenAI Codex Skills: Standardized
SKILL.mdoperational contract format. - Google Antigravity Skills: Skill discovery specification for Google Antigravity agents.
- Pi Coding Agent: Harness architecture, extensions, sessions, and tool calling by Mario Zechner.
- Pi Extensible Workflows: Multi-agent orchestration engine (
workflow,parallel,withWorktree, checkpoints) by Roberto De Virgilio (@vekexasia). - Engineering Excellence: Framework-agnostic AI software engineering standards by @darkrei08 (upstream fork of micio86dev/Engineering-Excellence).
- Matt Pocock's Skills: Agent workflows for triage, spec decomposition, bug diagnosis, architecture design, and grilling by Matt Pocock (@mattpocock).
- Gentle AI: Harness discipline, Receipt-Driven Development (RDD), and review authority by Gentleman Programming.
- Gentle Engram: Durable project memory and cross-session learning persistence by Gentleman Programming.
- Gentleman Guardian Angel: Provider-agnostic pre-commit and pre-PR quality gate by Gentleman Programming.
- Herdr: Terminal multiplexer and workspace coordinator designed for AI coding agents.
- Serena: Language-server backed semantic navigation engine for AI agents by Oraios.
- graphifyy: Graph-based code analysis and AST dependency extraction.
- LLMLingua: Prompt compression and token reduction framework by Microsoft.
- RTK: Terminal output filter and token reducer for AI agent command execution.
- sqz: Token compression for CLI output and file reads by Ojus Chugh.
- Wizard-AI: Guided setup manager and adapter tooling by @darkrei08.
License
This project is licensed under the MIT License.