Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ Requirements: Node 18+ on `PATH` (the hooks are Node scripts), git, and the GitH
| Session rules (`rules/`) | Injected at every session and subagent start by a hook, so they hold without anyone loading a skill. |
| `bstack:mode` | Router: goal, smallest change, playbook and risk tier. Playbooks: investigate, bug-fix, feature, refactor, migration, ticket, ship, autonomous-run. |
| `bstack:plan` | Sizes the work, grills you where intent is unclear, and writes a spec with ticket sub-issues, or a map of decision tickets for foggy work. Keeps `GLOSSARY.md` and ADRs. |
| `bstack:orchestrator` | One T3 Code thread for all repos: takes a goal, starts one lane (a child thread in its own worktree) per ticket on the model `scripts/model.mjs lane` names, answers the lanes' technical questions and asks you only what is yours to decide. See [Orchestrator](#orchestrator). |
| `bstack:triage` | Sorts incoming issues: checks the claim, finds duplicates and work already done, writes acceptance criteria, labels the state. |
| `bstack:audit` | Review and clean up a whole repo: map, find, prove, present once, fix through small gated PRs. |
| `bstack:vibecoding` | Prototype an idea fast when you ask for it: no plan, tests, PR or review before it runs. Then discard it, or harden it into a ticket that ships through the full gate. |
Expand All @@ -53,6 +54,14 @@ idea or bug report -> bstack:triage or bstack:plan -> tickets (issues) -> ticket
- Issues are kept by the agent, never by hand. Specs are temporary: once merged, the code and tests are the truth.
- `scripts/tracker.mjs labels` creates the labels a repo lacks and changes nothing else. It needs `gh` 2.94 or newer.

## Orchestrator

Start a new thread in T3 Code, in any project, on your usual model at medium effort, and write `/bstack:orchestrator` followed by the goal, for example `/bstack:orchestrator byg #42 i owner/repo`. Leave the thread open; T3 wakes it when a lane finishes or asks.

- Each ticket becomes a lane: a child thread started with `delegate_task` in a worktree from the default branch, with a brief of Goal, Done when, Constraints and Result form (`scripts/lane.mjs brief`). The lane is a full bstack session: it builds, starts its own judge and merges.
- A lane answers with JSON that matches `skills/orchestrator/lane-result.schema.json` (`scripts/lane.mjs result` checks it). The orchestrator reads no diff, log or transcript.
- It answers technical questions itself and records them on the ticket. Questions on the stop list, and about goal, scope or priority, come to you together, each with a recommended answer, while the other lanes go on.

## What the hooks enforce

The guard runs before every `Bash` and `PowerShell` command (Windows routes shell commands through PowerShell, so a Bash-only hook would never fire there), every file write and every MCP tool call. It fails closed.
Expand Down
91 changes: 91 additions & 0 deletions plugins/bstack/scripts/lane.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
#!/usr/bin/env node
// The two ends of a lane the orchestrator starts (#323): the brief it sends, and the result it reads back.
// lane.mjs brief < {"goal", "done", "constraints": [...]} or {"goal", "done", "open": true}
// lane.mjs result < the lane's last message
// `result` prints the lane result as compact JSON when it matches lane-result.schema.json, else exits 1
// with what did not fit.
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { isMain } from './lib/is-main.mjs';

const USAGE = 'usage: lane.mjs brief|result < input';
export const SCHEMA_FILE = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'skills', 'orchestrator', 'lane-result.schema.json');
export const SCHEMA = JSON.parse(fs.readFileSync(SCHEMA_FILE, 'utf8'));

const STEP_LINE = /^\s*(\d+[.)](\s|$)|step\b)/im;

export function brief({ goal, done, constraints = [], open = false }) {
const parts = { Goal: goal, 'Done when': done };
const missing = Object.entries(parts).filter(([, v]) => typeof v !== 'string' || !v.trim()).map(([k]) => k);
if (missing.length) throw new Error(`brief needs ${missing.join(' and ')}`);
if (!Array.isArray(constraints) || constraints.some(c => typeof c !== 'string')) throw new Error('constraints must be a list of strings');
const texts = [goal, done, ...constraints];
if (texts.some(t => STEP_LINE.test(t))) throw new Error('a brief says what, never how: no numbered steps');
const lines = [`Goal: ${goal.trim()}`, '', `Done when: ${done.trim()}`];
if (open) return `${lines.join('\n')}\n`;
if (constraints.length) lines.push('', 'Constraints:', ...constraints.map(c => `- ${c.trim()}`));
lines.push('', 'Result form: your last message is only one JSON object that matches this schema, nothing around it.',
JSON.stringify(SCHEMA.properties), `Required: ${SCHEMA.required.join(', ')}.`);
return `${lines.join('\n')}\n`;
}

const typeOf = v => (v === null ? 'null' : Array.isArray(v) ? 'array' : Number.isInteger(v) ? 'integer' : typeof v);

export function check(value, schema = SCHEMA, at = 'result') {
const errors = [];
const types = [schema.type ?? []].flat();
if (types.length && !types.includes(typeOf(value))) return [`${at}: is ${typeOf(value)}, wants ${types.join(' or ')}`];
if (schema.enum && !schema.enum.includes(value)) errors.push(`${at}: ${JSON.stringify(value)} is not one of ${schema.enum.join(', ')}`);
if (typeOf(value) === 'object') {
for (const key of schema.required ?? []) if (!(key in value)) errors.push(`${at}: missing ${key}`);
for (const [key, v] of Object.entries(value)) {
const sub = schema.properties?.[key];
if (sub) errors.push(...check(v, sub, `${at}.${key}`));
else if (schema.additionalProperties === false) errors.push(`${at}: unknown field ${key}`);
}
}
if (typeOf(value) === 'array' && schema.items) value.forEach((v, i) => errors.push(...check(v, schema.items, `${at}[${i}]`)));
return errors;
}

function lastObject(text) {
const trimmed = text.trim();
const fenced = [...trimmed.matchAll(/```(?:json)?\s*\n([\s\S]*?)\n```/g)].map(m => m[1]);
const candidates = [trimmed, ...fenced.reverse()];
for (let i = trimmed.length; i > 0;) {
i = trimmed.lastIndexOf('{', i - 1);
if (i < 0) break;
candidates.push(trimmed.slice(i));
}
for (const c of candidates) {
try { return JSON.parse(c); } catch {}
}
throw new Error('no JSON object in the lane message');
}

export function result(text) {
const value = lastObject(text);
const errors = check(value);
if (errors.length) throw new Error(errors.join('\n'));
return JSON.stringify(value);
}

const MODES = {
brief: input => brief(JSON.parse(input)),
result: input => `${result(input)}\n`,
};

if (isMain(import.meta.url)) {
const mode = MODES[process.argv[2]];
if (!mode) {
process.stderr.write(`${USAGE}\n`);
process.exit(2);
}
try {
process.stdout.write(mode(fs.readFileSync(0, 'utf8').replace(/^/, '')));
} catch (e) {
process.stderr.write(`${e.message}\n`);
process.exit(1);
}
}
3 changes: 2 additions & 1 deletion plugins/bstack/skills/mode/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@ Three lines, then start:
| An issue to build, or "the next ticket" | [ticket](playbooks/ticket.md) |
| A prototype or POC the user asked for | the `bstack:vibecoding` skill |
| A branch exists and must land | [ship](playbooks/ship.md) |
| "Keep going until X", or a run without the user | [autonomous-run](playbooks/autonomous-run.md) |
| A goal to run without the user in T3 Code (its delegate tools are loaded), or work across repos | the `bstack:orchestrator` skill; a lane it started (a brief with a Result form) is a ticket |
| "Keep going until X", or a run without the user outside T3 Code | [autonomous-run](playbooks/autonomous-run.md) |
| Review or clean up a whole repo | the `bstack:audit` skill |
| Incoming issues to sort | the `bstack:triage` skill |

Expand Down
2 changes: 1 addition & 1 deletion plugins/bstack/skills/mode/playbooks/autonomous-run.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# Autonomous run

For "keep going until X", background sessions and runs nobody watches.
For "keep going until X", background sessions and runs nobody watches. In T3 Code, where the delegate tools are loaded, a goal runs through the `bstack:orchestrator` skill instead.

**Goal:** a stop condition written as a checkable predicate, not a duration, and stated in the first reply: "every finding in the audit list has a merged PR or a stated reason", "every ticket under the spec is closed, or handed to the user as `ready-for-human`". **Done when** it holds on main.

Expand Down
53 changes: 53 additions & 0 deletions plugins/bstack/skills/orchestrator/SKILL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
---
name: orchestrator
description: Run a goal from brief to merged through lanes, child threads in T3 Code, one per ticket, across any repo, and come back to the owner only for strategic questions. Holds ticket and PR numbers and states, never code. Use for "orkestrér", "kør det her", "run this across repos", "orchestrate", or a run without the user in T3 Code.
---

# Orchestrator

**Goal:** the owner gives a goal; every ticket under it ends merged, capped or with a question for the owner, and the owner is asked only what is theirs to decide. Any thread that loads this skill is the orchestrator. It keeps no memory: GitHub and the T3 thread list hold the state, so its context can be thrown away at any time.

**Done when** every lane's ticket reads back closed and its PR merged (`gh issue view <n> -R <repo> --json state`, `gh pr view <pr> -R <repo> --json state,mergedAt`), or the owner has the open questions.

Reading code, diffs, logs or a lane's transcript, and fixing anything, is the lane's work. Read a lane's thread only when it is stuck: it failed without a result, or its result does not parse.

## Size the goal

As `bstack:plan` sizes it: one ticket; a spec with tickets; or questions to the owner when the intent is unclear. Planning is a lane of its own (`bstack:plan` in that repo) when it needs a grilling or research; the orchestrator does not write specs itself. A ticket labelled `ready-for-human` or `plan:*` is not a build lane.

## Start a lane

One lane per ticket, in the ticket's repo, in its own worktree.
1. Model: `node "${CLAUDE_PLUGIN_ROOT}/scripts/model.mjs" lane build <n> -R <owner/repo>` prints `{ model, effort }` (`research` or `mechanical` for those kinds; `--failed <n>` after failed lanes). Map the family to the provider's model id from `orchestrator_capabilities`; `session` means the orchestrator's own model.
2. Brief: `node "${CLAUDE_PLUGIN_ROOT}/scripts/lane.mjs" brief` with `{ "goal", "done", "constraints": [...] }` on stdin. It prints Goal, Done when, Constraints and Result form, in English; it refuses numbered steps, because a brief says what, never how. An open task (research, a question) gets `{ "goal", "done", "open": true }`: a goal and a done-when only.
3. Project: the `t3_project_list` entry whose `repositoryIdentity` names the repo. A repo that moved keeps its old owner there, so compare `gh repo view <remoteUrl> --json nameWithOwner`. No entry: `t3_project_clone` into a folder next to the other projects, then `t3_project_create` on it. Both need a full-access thread; when T3 refuses them (`capability_denied`), registering the repo is an owner question (access), recommended answer: the owner adds the folder as a project in T3.
4. `delegate_task` with that brief as `task`, `isolation: "worktree"`, `mode: "async"`, a `title` of `#<n> <ticket title>`, and `target`: that `projectId`, a Claude `providerInstanceId` that `canRunChildTask` and is not at its limit, `model`, and `options: { "effort": ... }`. When T3 refuses the `projectId` ("A local task runs in this thread's project"), start the lane without it and add the constraint "Work in your own git worktree of <the repo's clone>, made from origin's default branch; remove it when done."

Constraints every build brief carries:
- Build issue <url> in <owner/repo> through the bstack ticket and ship playbooks; a `bstack:judge` you start judges.
- Done means the PR that says `Closes #<n>` is squash-merged with green checks and a verdict for its head, read back as merged, the issue is closed, and the branch and worktree are removed.
- Start from the default branch on origin.
- No deploys. A question on the stop list of the session rules: do not ask anyone; stop and report it in `questions` with state `needs_owner`.
- Three rounds with blocking findings: stop with state `capped`.
- Plus whatever the owner or the spec fixed for this ticket.

Then end the turn. T3 wakes the orchestrator when a lane finishes or asks; never poll (`task_status` on a running lane, sleeps, watchers).

## When a lane wakes it

Pipe the lane's last message to `node "${CLAUDE_PLUGIN_ROOT}/scripts/lane.mjs" result`. It prints the result as JSON matching [lane-result.schema.json](lane-result.schema.json), or what did not fit. A result that does not fit goes back to the lane with `t3_thread_send` and `outputSchema` set to the schema file; that is not reading its work.

- `merged`: read the issue and PR states back from GitHub, then report.
- `needs_owner` or `blocked` with `questions`, or a pending question in the lane (`t3_pending_request list` on its thread): sort each question.
- **Technical** (how to build, which tool, a test approach, and any reversible choice inside the ticket's scope, even one that shapes behaviour): answer it yourself, send the answer to the lane's thread with `t3_thread_send`, and record it on the ticket in one comment (`gh issue comment`: the question, the answer, why).
- **The owner's**: on the stop list of the session rules, or about goal, scope, priority or a product choice no experiment can settle. Collect it; the other lanes go on.
- `capped`: report it with its open findings; what to do at the cap is the owner's until its own ticket says otherwise.
- A lane that failed on the account limit (`Claude API rate limit reached`): start it again on another account from its pushed branch, or report it.

Before ending a turn with owner questions, ask them all at once, each with your recommended answer. Send the answers to the lanes that asked, and record each on its ticket.

## To the owner

Danish, at the `ultra` level of `bstack:style`: per lane, the ticket, the state and the PR, as links. Warnings and questions to the owner are full sentences: what is at stake, the options, your pick and why.

The orchestrator itself runs on the owner's model at medium effort.
24 changes: 24 additions & 0 deletions plugins/bstack/skills/orchestrator/lane-result.schema.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "bstack lane result",
"type": "object",
"additionalProperties": false,
"required": ["ticket", "pr", "state", "head", "open_findings", "questions", "decisions"],
"properties": {
"ticket": { "type": "integer" },
"pr": { "type": ["integer", "null"] },
"state": { "enum": ["merged", "capped", "blocked", "needs_owner"] },
"head": { "type": ["string", "null"] },
"open_findings": {
"type": "array",
"items": {
"type": "object",
"additionalProperties": false,
"required": ["id", "title"],
"properties": { "id": { "type": "string" }, "title": { "type": "string" } }
}
},
"questions": { "type": "array", "items": { "type": "string" } },
"decisions": { "type": "array", "items": { "type": "string" } }
}
}
Loading
Loading