Dispatcher

From Kanevry/session-orchestrator · View interactive version

Dispatcher is an AI agent skill from the GitHub repository Kanevry/session-orchestrator. Use when you want the orchestrator to pick the next repo to work on across your whole portfolio — it enumerates candidate repos below the confinement root, resolves free/busy from each repo's session.lock lease, ranks the FREE ones by backlog priority × staleness × readiness, recommends the single m

How to use this skill

Skill file

Dispatcher Skill

Plugin root: ${CLAUDE_PLUGIN_ROOT}. Claude Code replaces this with the plugin's absolute path when it loads this file. Where it appears unreplaced — in a file this skill reads with the Read tool, or on Codex, Cursor or Pi — the plugin root is the directory that contains this skill's skills/ folder (two levels above the folder of this SKILL.md). Write that absolute path literally into every command that starts a plugin script: the Bash tool has no plugin variable, and shell variables do not survive between tool calls.

Cross-repo autopilot front-door — enumerate → rank → owner-AUQ → atomic claim → route. Read-only until the operator confirms; the only mutating step is the atomic session.lock claim, and it happens BEFORE any launch.

Invocation

Invoked as /dispatcher [--dry-run] [--repo <name>] with arguments: $ARGUMENTS.

Parse $ARGUMENTS before doing anything else. The recognized flags are exactly those of the CLI table below and are passed straight through to scripts/lib/dispatcher/cli.mjs:

If $ARGUMENTS contains an unrecognized flag (starts with -- but is not one of the above), inform the user:

Unknown flag '<flag>'. Recognized flags: --dry-run, --repo <name>, --start-dir <path>, --json.

Then continue with the remaining valid arguments.

Soul

The dispatcher answers one question: "of all my repos, which is the most worthwhile to work on right now, and is it free?" It scans the confinement-root children, resolves each repo's free/busy status from its session.lock v2 lease (same lease semantics as the vault-status board), ranks only the FREE ones by priority × staleness × readiness, and recommends the single best one. You confirm via a picker, it claims the lease atomically (winning the race or excluding-and-re-ranking on a loss), then routes you to the entry command for that repo. Busy repos are listed-as-such, never selected.

When to use

When NOT to use

Phase 1: Enumerate + Rank

Run the read path (non-mutating). Either invoke the CLI directly or call runDispatch from the module:

node "${CLAUDE_PLUGIN_ROOT}/scripts/lib/dispatcher/cli.mjs" --json

The JSON object has keys { candidates, free, ranked, warnings, recommended }:

Ranking combines three signals per repo (implementation: scripts/lib/dispatcher/rank.mjs): backlog priority (critical/high counts), staleness (days since the last completed session — older = more worthwhile, capped at 90d), and readiness (CI status × host resource verdict — only ever dampens). A null priority (glab/gh missing) is ranked on staleness × readiness alone with a warning; the dispatcher NEVER blocks on a missing CLI.

Phase 1.5: Verdict gate (autonomy-gated launch) — #682

Decides ONE thing for the recommended repo R (ranked[0]): may the dispatcher launch WITHOUT per-selection confirmation, or must it inform-and-ask? This sits BETWEEN ranking (Phase 1) and the Owner-AUQ (Phase 2). It is a pre-launch decision, NOT a per-iteration kill-switch — the autopilot loop's 10 kill-switches are reused unchanged once a session is running (see skills/autopilot/SKILL.md § Pre-Loop Verdict Gate).

Compute the suitability verdict for R via the pure four-gate engine computeSuitabilityVerdict(deps) from scripts/lib/autonomy/suitability.mjs. The engine is pure + DI: the dispatcher gathers every signal and passes it in.

Source each verdict input as follows (the dispatcher already has most in hand from Phase 1):

| deps field | Source | Notes |

|---|---|---|

| autonomy | resolveDispatcherAutonomy({ committed, env, ownerConfig }) from scripts/lib/config/dispatcher-autonomy.mjs | The effective dial. Defaults to 'off' when unset (fail-closed). |

| confidenceFloor | the confidence-floor from the parsed dispatcher-autonomy: block (default 0.5) | Same source object as autonomy. |

| confidence | mode-selector selectMode(signals).confidence (0..1 float) for the recommended session-type | The same mode-selector the Phase-2 heuristic and autopilot use. |

| ci | checkCiStatus({ repoRoot: R }) → { status } \| null | CRITICAL (NICE-b): Phase-1 rank.mjs exposes only the BARE status string (readiness.ciStatus). The engine's G3 gate expects an OBJECT { status } — wrap it as { status: ciStatus } when you HAVE a status; on a genuine ABSENCE (no CI configured) pass ci = null. Since #1031 checkCiStatus no longer returns null on failure — an unreadable state comes back as {severity:'warn', ok:false, degraded:<reason>}, and Phase-1 rank.mjs surfaces exactly that as readiness.ciDegraded with readiness.ciStatus === 'unknown'. Wrap that state as { status: 'unknown' } (the engine warns 'CI signal unknown — treated as absent' and G3 still passes) rather than flattening it to null — null claims a measured absence the probe never established. Do NOT synthesize { status: undefined } (or {}): that present-but-unusable object hits the engine's MALFORMED branch ('CI signal malformed — treated as absent') instead of the clean ABSENT branch ('CI signal absent'). Both pass G3 + warn, but null is the honest "no signal" — reserve the malformed branch for a genuinely unexpected shape. A bare string ALSO hits the malformed branch — always wrap or null. |

| resourceVerdict | the host resource verdict string ('green'\|'warn'\|'degraded'\|'critical') from rank.mjs (readiness.resourceVerdict) or a fresh evaluate(probe(), thresholds).verdict | Host-level — already fetched once in Phase 1. NICE-b: on a genuine probe FAILURE (no signal), prefer resourceVerdict = null over synthesizing 'green'. null = "no signal" ⇒ G4 passes + warns ('resource signal absent') — honest. Synthesizing 'green' fabricates a positive signal the host never reported and can let an autonomous launch proceed against an unknown host state. Pass the real verdict string when you have one; null when you do not. |

| recentRuns | readRecentAutopilotRuns({ repoRoot: R }) from scripts/lib/autopilot/recent-runs.mjs | NEW reader. Reads <R>/.orchestrator/metrics/autopilot.jsonl, returns the most-recent records (newest-last), never throws ([] on missing/unreadable). Pass the TRUE count — the engine's G2 gate omits-with-warn below 5 runs and otherwise checks fired/N < 0.2. |

The launch decision (FAIL-CLOSED invariant):

verdict = computeSuitabilityVerdict({ autonomy, confidenceFloor, confidence, ci, resourceVerdict, recentRuns })

IF autonomy === 'autonomous-gated' AND verdict.suitable === true:
    # MAY launch WITHOUT per-selection confirmation:
    # skip the Phase-2 AUQ and proceed straight to Phase 3 (atomic claim) → Phase 4 (route).
ELSE:
    # INFORM the operator of verdict.rationale + verdict.warnings,
    # then run the Phase-2 AUQ (ask before launch). NEVER auto-launch.

Phase 2: Owner-AUQ

Conditional (#682): SKIP this phase when Phase 1.5 green-lit an autonomous launch (autonomy === 'autonomous-gated' AND verdict.suitable === true) — in that branch proceed straight to Phase 3. In EVERY other case (any non-autonomous-gated dial, OR a non-suitable verdict) this phase RUNS: inform the operator of the verdict first, then ask. The dispatcher NEVER auto-launches outside the green-verdict autonomous-gated branch.

Present the decision to the operator via the AskUserQuestion tool — never inline prose (.claude/rules/ask-via-tool.md AUQ-001..005, enforced).

Recommended session-type heuristic for option 1: high critical/high backlog ⇒ /session deep; stale-but-clean (no backlog signal, high staleness) ⇒ /discovery or /session housekeeping; unscoped/new work ⇒ /plan. Offer the alternatives as the other options.

Phase 3: Atomic claim

Claim the lease for repo R BEFORE launching anything. This runs in BOTH branches — the operator-confirmed Phase-2 path AND the autonomous-gated green-verdict path that skipped Phase 2 (#682). The claim ALWAYS precedes the Phase-4 route: an autonomous launch does not bypass the atomic claim, it only bypasses the per-selection AUQ.

// via the module (preferred — returns the acquire() result verbatim)
import { claimRepo } from 'scripts/lib/dispatcher/cli.mjs';
const res = claimRepo({ repoRoot: R, sessionId, mode, ttlHours, semanticSessionId });

Or reuse the primitive directly: acquire({ sessionId, mode, ttlHours, repoRoot, semanticSessionId }) from scripts/lib/session-lock.mjs. The claim is a linkSync create-or-fail = atomic.

Do NOT reinvent the claim — always go through claimRepo/acquire. The ok:false path is the load-bearing concurrency guard: two parallel dispatchers can both recommend R, but only one wins the linkSync; the loser must re-rank, never force.

Phase 4: Route

With the lease held, routing splits on whether the chosen entry is model-invocable:

planning precursor) are NOT something the coordinator can invoke itself. commands/session.md

documents session and plan as reserved terminal-only built-in names — under

non-interactive (claude -p) invocation the bare form answers `"isn't available in this

environment" — and skills/plan/SKILL.md` additionally carries

disable-model-invocation: true, which blocks the Skill tool from invoking it regardless of

interactivity. The coordinator therefore hands the operator the exact command to type, one

line per option — /session-orchestrator:session <mode> or `/session-orchestrator:plan

[new|feature|retro]` — rather than attempting to invoke either itself.

skills/discovery/SKILL.md carries no disable-model-invocation flag, so the coordinator MAY

invoke it directly via the Skill tool when the operator picks this option — no hand-off line

needed.

/plan and /discovery remain read-only precursors, NOT execution modes — the menu may route to them, but they only produce artifacts for a later execution session. The full mode taxonomy lives in the mode-selector surface (P2 of this epic); the dispatcher only routes to the entry command the operator picked.

Phase 5: Edge cases

CLI

node "${CLAUDE_PLUGIN_ROOT}/scripts/lib/dispatcher/cli.mjs" [--json] [--dry-run] [--repo <name>] [--start-dir <path>] [--help] [--version]

| Flag | Description |

|---|---|

| --json | Emit { candidates, free, ranked, warnings, recommended } as a single JSON object to stdout. |

| --dry-run | Explicit non-mutating rank (the read path is already non-mutating; documents intent). |

| --repo <name> | Filter the human-readable table to one repoName (informational; does not change ranking). |

| --start-dir <path> | Override the scan root (defaults to the confinement root). |

| --help / --version | Print usage / version and exit 0. |

Data → stdout, warnings/errors → stderr (never mixed). Exit codes follow .claude/rules/cli-design.md:

| Code | Meaning |

|---|---|

| 0 | Success |

| 1 | User/input error (e.g. bad --start-dir) |

| 2 | System error (unexpected dispatch failure) |

Anti-Patterns

Critical Rules

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.