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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ Start a new thread in T3 Code, in any project, on your usual model at medium eff

- 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.
- A spec runs as a queue (`/bstack:orchestrator kør #318 i owner/repo`): a research lane names the areas each ticket touches, and `scripts/queue.mjs` puts tickets that share an area in one lane in blocker order and starts the next ready ticket when a lane merges, at most three builders at once. It ends when the spec is closed, or lists the tickets that wait for you.
- 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
Expand Down
171 changes: 171 additions & 0 deletions plugins/bstack/scripts/queue.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
#!/usr/bin/env node
// The orchestrator's queue (#324): which tickets of one or more specs start now, and in which lane.
// queue.mjs <spec or ticket>... [-R owner/repo] [--areas <file>] [--running <ref,...>] [--builders <n>]
// Refs are owner/repo#n, issue URLs, or #n with -R. Open tickets come from tracker.mjs next; --areas is a JSON
// object from ticket ref to the paths it is likely to touch. Tickets of one repo whose areas overlap form one
// lane, in blocker order, and a lane runs one ticket at a time. Running: claimed tickets plus --running (lanes
// alive without a claim). Prints { lanes, running, start, waiting, end } as JSON; `end` is "done" when no ticket
// is open, "owner" when nothing runs or can start and the rest waits for a person, else null.
import fs from 'node:fs';
import { execFileSync } from 'node:child_process';
import { frontier } from './tracker.mjs';
import { isMain } from './lib/is-main.mjs';

const USAGE = 'usage: queue.mjs <spec or ticket>... [-R owner/repo] [--areas <file>] [--running <ref,...>] [--builders <n>]';
export const BUILDERS = 3;
const OWNER_LABELS = {
'ready-for-human': 'needs a person (ready-for-human)',
'plan:grill': 'a decision to settle with the owner (plan:grill)',
'plan:prototype': 'a prototype to react to with the owner (plan:prototype)',
};

export function toRef(value, repo) {
const s = String(value).trim();
const url = /github\.com\/([^/]+\/[^/]+)\/(?:issues|pull)\/(\d+)/.exec(s);
if (url) return `${url[1]}#${url[2]}`.toLowerCase();
const full = /^([\w.-]+\/[\w.-]+)#(\d+)$/.exec(s);
if (full) return `${full[1]}#${full[2]}`.toLowerCase();
const bare = /^#?(\d+)$/.exec(s);
if (bare && repo) return `${repo}#${bare[1]}`.toLowerCase();
throw new Error(`cannot read ticket ref ${s}${bare ? ' without -R owner/repo' : ''}`);
}

const repoOf = ref => ref.slice(0, ref.lastIndexOf('#'));
const issueArg = ref => `https://github.com/${repoOf(ref)}/issues/${ref.slice(ref.lastIndexOf('#') + 1)}`;
const labels = t => (t.labels ?? []).map(l => l.name ?? l);
const isParent = i => labels(i).some(l => l === 'plan:spec' || l === 'plan:map') || (i.subIssuesSummary?.total ?? 0) > 0;

export function collect(gh, refs, { has } = {}) {
const tickets = new Map();
const add = (rows, state) => {
for (const r of rows) {
const ref = toRef(r.url);
const blockedBy = (r.blockedBy ?? []).map(b => toRef(b, repoOf(ref)));
tickets.set(ref, { ref, number: r.number, title: r.title, url: r.url, labels: labels(r), state, blockedBy, reason: r.reason });
}
};
const loose = [];
const order = [];
for (const ref of refs) {
const head = JSON.parse(gh(['issue', 'view', issueArg(ref), '--json', 'url,labels,subIssues,subIssuesSummary']));
if (!isParent(head)) { loose.push(issueArg(ref)); order.push(ref); continue; }
order.push(...(head.subIssues?.nodes ?? []).filter(s => s.url).map(s => toRef(s.url)));
const f = frontier(gh, { parent: issueArg(ref), has });
add(f.ready, 'ready'); add(f.blocked, 'blocked'); add(f.claimed, 'running'); add(f.unprovable, 'owner');
}
if (loose.length) {
const f = frontier(gh, { tickets: loose, has });
add(f.ready, 'ready'); add(f.blocked, 'blocked'); add(f.claimed, 'running'); add(f.unprovable, 'owner');
}
const rank = ref => (order.includes(ref) ? order.indexOf(ref) : order.length);
return [...tickets.values()].sort((a, b) => rank(a.ref) - rank(b.ref));
}

const norm = area => String(area).trim().replace(/\\/g, '/').replace(/^\.(\/|$)/, '').replace(/\/+$/, '').toLowerCase();
const wholeRepo = '';
const overlaps = (a, b) => a === b || a === wholeRepo || b === wholeRepo || a.startsWith(`${b}/`) || b.startsWith(`${a}/`);

function areasOf(areas, ref) {
const entry = Object.entries(areas).find(([k]) => toRef(k, repoOf(ref)) === ref);
return (entry?.[1] ?? []).map(norm);
}

function blockerOrder(group) {
const inGroup = new Set(group.map(t => t.ref));
const done = new Set();
const order = [];
while (order.length < group.length) {
const next = group.find(t => !done.has(t.ref) && t.blockedBy.every(b => !inGroup.has(b) || done.has(b)))
?? group.find(t => !done.has(t.ref));
done.add(next.ref);
order.push(next);
}
return order;
}

export function lanes(tickets, areas = {}) {
const parent = new Map(tickets.map(t => [t.ref, t.ref]));
const root = r => (parent.get(r) === r ? r : root(parent.get(r)));
const touched = tickets.map(t => ({ t, areas: areasOf(areas, t.ref) }));
for (const [i, a] of touched.entries()) {
for (const b of touched.slice(i + 1)) {
if (repoOf(a.t.ref) !== repoOf(b.t.ref)) continue;
if (a.areas.some(x => b.areas.some(y => overlaps(x, y)))) parent.set(root(b.t.ref), root(a.t.ref));
}
}
const groups = new Map();
for (const { t, areas: own } of touched) {
const g = groups.get(root(t.ref)) ?? { repo: repoOf(t.ref), areas: new Set(), tickets: [] };
own.forEach(a => g.areas.add(a));
g.tickets.push(t);
groups.set(root(t.ref), g);
}
return [...groups.values()].map(g => ({ repo: g.repo, areas: [...g.areas].sort(), tickets: blockerOrder(g.tickets) }));
}

function waitsFor(t, all) {
const label = labels(t).find(l => OWNER_LABELS[l]);
if (label) return OWNER_LABELS[label];
if (t.reason) return `cannot be proven here: ${t.reason}`;
return `blocked by ${t.blockedBy.map(b => (all.has(b) ? b : `${b} (outside the queue)`)).join(', ')}`;
}

export function plan(tickets, { areas = {}, running = [], builders = BUILDERS } = {}) {
const alive = new Set(running);
const all = new Map(tickets.map(t => [t.ref, t]));
const stateOf = t => (alive.has(t.ref) ? 'running' : t.state === 'ready' && labels(t).some(l => OWNER_LABELS[l]) ? 'owner' : t.state);
const laneList = lanes(tickets, areas).map((lane, i) => ({
lane: i + 1, repo: lane.repo, areas: lane.areas,
tickets: lane.tickets.map(t => ({ ref: t.ref, number: t.number, title: t.title, url: t.url, state: stateOf(t) })),
}));
const runningCount = laneList.flatMap(l => l.tickets).filter(t => t.state === 'running').length;
const start = [];
for (const l of laneList) {
if (runningCount + start.length >= builders) break;
if (l.tickets.some(t => t.state === 'running')) continue;
const next = l.tickets.find(t => t.state === 'ready');
if (next) start.push({ ...next, lane: l.lane });
}
const waiting = laneList.flatMap(l => l.tickets).filter(t => t.state === 'owner' || t.state === 'blocked')
.map(t => ({ ref: t.ref, url: t.url, title: t.title, for: waitsFor(all.get(t.ref), all) }));
const end = !tickets.length ? 'done' : !runningCount && !start.length ? 'owner' : null;
return { lanes: laneList, running: runningCount, start, waiting, end };
}

export function parseArgs(argv) {
const out = { refs: [], repo: null, areas: null, running: [], builders: BUILDERS };
const value = (flag, v) => {
if (v === undefined || v.startsWith('-')) throw new Error(`${flag} needs a value\n${USAGE}`);
return v;
};
const raw = [];
for (let i = 0; i < argv.length; i++) {
const a = argv[i];
if (a === '-R' || a === '--repo') out.repo = value(a, argv[++i]);
else if (a === '--areas') out.areas = value(a, argv[++i]);
else if (a === '--running') out.running.push(...value(a, argv[++i]).split(',').filter(Boolean));
else if (a === '--builders') {
out.builders = Number(value(a, argv[++i]));
if (!Number.isInteger(out.builders) || out.builders < 1) throw new Error(`--builders needs a whole number above 0\n${USAGE}`);
} else if (a.startsWith('-')) throw new Error(`unknown flag ${a}\n${USAGE}`);
else raw.push(a);
}
if (!raw.length) throw new Error(USAGE);
out.refs = raw.map(r => toRef(r, out.repo));
out.running = out.running.map(r => toRef(r, out.repo));
return out;
}

const realGh = args => execFileSync('gh', args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 45000, maxBuffer: 64 << 20 });

if (isMain(import.meta.url)) {
try {
const args = parseArgs(process.argv.slice(2));
const areas = args.areas ? JSON.parse(fs.readFileSync(args.areas, 'utf8').replace(/^/, '')) : {};
const result = plan(collect(realGh, args.refs), { areas, running: args.running, builders: args.builders });
process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
} catch (e) {
process.stderr.write(`queue: ${String(e.stderr || e.message || e).trim()}\n`);
process.exit(1);
}
}
12 changes: 9 additions & 3 deletions plugins/bstack/scripts/tracker.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,12 @@ export function ensureLabels(gh, repo) {

const FIELDS = 'number,title,url,state,labels,assignees,blockedBy,subIssuesSummary,body';

const openBlockers = issue => (issue.blockedBy?.nodes ?? issue.blockedBy ?? []).filter(b => (b.state ?? 'OPEN') === 'OPEN');

function classify(issue) {
if (issue.state && issue.state !== 'OPEN') return 'closed';
if ((issue.assignees ?? []).length) return 'claimed';
const blockers = issue.blockedBy?.nodes ?? issue.blockedBy ?? [];
if (blockers.some(b => (b.state ?? 'OPEN') === 'OPEN')) return 'blocked';
if (openBlockers(issue).length) return 'blocked';
return 'ready';
}

Expand All @@ -62,7 +63,11 @@ const EXTS = process.platform === 'win32' ? (process.env.PATHEXT ?? '.EXE').spli
const onPath = cmd => (process.env.PATH ?? '').split(path.delimiter).some(dir => dir && EXTS.some(ext => existsSync(path.join(dir, cmd + ext))));
const proofSurface = body => (/^[-> \t]*Proof surface:(.*)$/im.exec(body ?? '')?.[1] ?? '').replace(/\([^)]*\)/g, '').split(',').map(c => c.trim()).filter(Boolean);

export function frontier(gh, { parent, repo, has = onPath } = {}) {
export function frontier(gh, { parent, tickets, repo, has = onPath } = {}) {
if (tickets) {
const issues = tickets.map(t => JSON.parse(gh(['issue', 'view', String(t), '--json', FIELDS, ...(/^https?:/.test(t) ? [] : repoArgs(repo))])));
return { parent: null, progress: null, ...sort(issues, has) };
}
if (parent) {
const p = JSON.parse(gh(['issue', 'view', String(parent), '--json', 'number,title,url,labels,subIssues,subIssuesSummary', ...repoArgs(repo)]));
const open = (p.subIssues?.nodes ?? []).filter(s => s.state === 'OPEN');
Expand All @@ -84,6 +89,7 @@ function sort(issues, has) {
const missing = kind === 'ready' ? proofSurface(i.body).filter(c => !has(c)) : [];
if (missing.length) out.unprovable.push({ ...brief(i), reason: `missing on PATH: ${missing.join(', ')}` });
else if (kind === 'claimed') out.claimed.push({ ...brief(i), assignees: names(i.assignees) });
else if (kind === 'blocked') out.blocked.push({ ...brief(i), blockedBy: openBlockers(i).map(b => b.url ?? b.number) });
else if (kind !== 'closed') out[kind].push(brief(i));
}
return { next: out.ready[0] ?? null, ...out };
Expand Down
13 changes: 12 additions & 1 deletion plugins/bstack/skills/orchestrator/SKILL.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
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.
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. Runs a spec's tickets as a queue of lanes. Use for "orkestrér", "kør det her", "kør specen", "run this across repos", "orchestrate", or a run without the user in T3 Code.
---

# Orchestrator
Expand Down Expand Up @@ -33,6 +33,17 @@ Constraints every build brief carries:

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

## A queue of tickets

For a spec, or a list of tickets, in one repo or several, until the spec is closed or every open ticket waits for the owner.
1. Areas, once before the start: one open-task lane on `model.mjs lane research`, briefed to name the files or directories each open ticket is likely to touch, its last message only a JSON object from `owner/repo#n` to a list of repo-relative paths. Save it as a file and post it as one comment on the spec, so a renewal finds it.
2. `node "${CLAUDE_PLUGIN_ROOT}/scripts/queue.mjs" <spec or tickets> [-R owner/repo] --areas <file> [--running <refs>]`: `--running` lists the tickets whose lane threads are alive without a claim (one you just answered). It reads the tickets through `tracker.mjs next`, puts tickets of one repo whose areas overlap in one lane in blocker order, runs one ticket per lane, and prints `start`: the tickets to start now, at most three builders at once (`--builders` raises it only when no repo in the queue builds into a shared target dir).
3. Start a lane for each ticket in `start`, then end the turn.
4. On every lane result, after handling it: a lane that stopped with `needs_owner` or `capped` gets the `ready-for-human` label and one comment on its ticket with what the owner is needed for, so the queue skips it. Run `queue.mjs` again and start what it prints, without the owner.
5. `end` is `done`: read the spec back as closed (`gh issue view`), close it as the ticket playbook says if the last lane did not. `end` is `owner`: the last message lists each ticket in `waiting` with what it waits for, and the owner questions.

When the owner answers, remove the label and send the answer to the lane, or start the ticket again from its pushed branch.

## 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.
Expand Down
Loading
Loading