From cb44bd1f470dc288aa524ddcde06ae8b78b0531f Mon Sep 17 00:00:00 2001 From: Benjamin Carrasco Date: Sat, 5 Dec 2026 19:03:01 +0100 Subject: [PATCH] feat(orchestrator): lanes spread over machines and accounts (#325) place.mjs reads the slots (machine and Claude account pairs) from T3's own answers, keeps only machines with the repo, takes the slot with the fewest running lanes and the account with more quota left in a tie, and skips an account at its limit until its reset. quota probes each account once with a headless call. The skill places every lane through it, posts the line on the ticket, and restarts a lane that failed on the limit from its pushed branch. --- plugins/bstack/scripts/place.mjs | 132 ++++++++++++++++++++ plugins/bstack/skills/orchestrator/SKILL.md | 10 +- tests/place.test.mjs | 117 +++++++++++++++++ 3 files changed, 256 insertions(+), 3 deletions(-) create mode 100644 plugins/bstack/scripts/place.mjs create mode 100644 tests/place.test.mjs diff --git a/plugins/bstack/scripts/place.mjs b/plugins/bstack/scripts/place.mjs new file mode 100644 index 0000000..4150d4d --- /dev/null +++ b/plugins/bstack/scripts/place.mjs @@ -0,0 +1,132 @@ +#!/usr/bin/env node +// Where the orchestrator starts a lane (#325): a slot is one machine and one Claude account. +// place.mjs quota [--settings ] probes each Claude account in T3's settings once +// place.mjs pick < {"repo", "tickets", "environments", "quota", "now"?} +// `pick` reads the slots from T3's own answers (capabilities, projects, threads per environment) and +// prints one placement per ticket, each with the line the orchestrator posts on that ticket. +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { spawnSync } from 'node:child_process'; +import { isMain } from './lib/is-main.mjs'; + +const USAGE = 'usage: place.mjs quota [--settings ] | place.mjs pick < input'; +const CLAUDE_DRIVER = 'claudeAgent'; +const HOLDS_A_PROCESS = new Set(['running', 'starting', 'preparing', 'queued']); +const PROBE_ARGS = ['-p', '--model', 'haiku', '--output-format', 'stream-json', '--verbose', '--max-turns', '1']; + +export const settingsFile = () => path.join(os.homedir(), '.t3', 'userdata', 'settings.json'); +const expandHome = dir => (/^~($|[\\/])/.test(dir) ? path.join(os.homedir(), dir.slice(1)) : dir); + +export function accounts(settings) { + return Object.entries(settings.providerInstances ?? {}) + .filter(([, p]) => p.driver === CLAUDE_DRIVER && p.enabled !== false) + .map(([id, p]) => ({ id, configDir: expandHome(p.config?.homePath ?? '~/.claude') })); +} + +export function quotaOf(streamJson) { + const event = streamJson.split('\n').map(line => { try { return JSON.parse(line); } catch { return null; } }) + .find(e => e?.type === 'rate_limit_event'); + const info = event?.rate_limit_info; + if (!info) return { status: 'unknown' }; + const windows = Object.values(info.unifiedWindows ?? {}); + const used = Math.max(info.utilization ?? 0, ...windows.map(w => w.utilization ?? 0)); + const blocking = windows.filter(w => w.status === 'rejected').map(w => w.resetsAt); + const resetsAt = blocking.length ? Math.max(...blocking) : info.resetsAt; + return { status: info.status, left: Math.round((1 - used) * 100) / 100, resetsAt }; +} + +const realProbe = configDir => spawnSync('claude', PROBE_ARGS, { + input: 'Reply with OK only.', encoding: 'utf8', timeout: 60000, + env: { ...process.env, CLAUDE_CONFIG_DIR: configDir }, +}).stdout ?? ''; + +export function quota(settings, probe = realProbe) { + return Object.fromEntries(accounts(settings).map(a => [a.id, quotaOf(probe(a.configDir))])); +} + +const repoKey = repo => `github.com/${repo}`.toLowerCase(); +const utc = epoch => `${new Date(epoch * 1000).toISOString().slice(0, 16).replace('T', ' ')} UTC`; + +function slotsOf({ repo, environments, quota: q = {}, now }) { + const accountIds = [...new Set(environments.flatMap(e => (e.capabilities?.providers ?? []) + .filter(p => p.driverKind === CLAUDE_DRIVER).map(p => p.providerInstanceId)))].sort(); + const accountName = id => `account ${accountIds.indexOf(id) + 1}`; + const machineName = e => `machine ${e.environmentId.slice(0, 8)}`; + const slots = []; + const skipped = []; + for (const env of environments) { + const project = (env.projects ?? []).find(p => !p.archivedAt && !p.deletedAt + && p.repositoryIdentity?.canonicalKey?.toLowerCase() === repoKey(repo)); + if (!project) { skipped.push(`${machineName(env)} has no clone of the repo`); continue; } + for (const provider of env.capabilities?.providers ?? []) { + if (provider.driverKind !== CLAUDE_DRIVER || !provider.canRunChildTask) continue; + const id = provider.providerInstanceId; + const account = q[id] ?? { status: 'unknown' }; + if (account.status === 'rejected' && !(account.resetsAt <= now)) { + skipped.push(`${accountName(id)} at its limit until ${account.resetsAt ? utc(account.resetsAt) : 'an unknown reset'}`); + continue; + } + const running = (env.threads ?? []).filter(t => t.providerInstanceId === id && HOLDS_A_PROCESS.has(t.status)).length; + slots.push({ environmentId: env.environmentId, projectId: project.id, providerInstanceId: id, running, + left: typeof account.left === 'number' ? account.left : null, name: `${machineName(env)}, ${accountName(id)}` }); + } + } + return { slots, skipped: [...new Set(skipped)] }; +} + +const byLoadThenQuota = (a, b) => a.running - b.running || (b.left ?? -1) - (a.left ?? -1) + || a.environmentId.localeCompare(b.environmentId) || a.providerInstanceId.localeCompare(b.providerInstanceId); + +function reasonFor(best, slots, skipped) { + const others = slots.filter(s => s !== best); + const parts = [`fewest running lanes (${best.running}${others.length ? `, against ${others.map(s => s.running).join(', ')}` : ''})`]; + const tied = others.filter(s => s.running === best.running); + const percent = left => (left === null ? 'unknown' : `${Math.round(left * 100)} %`); + if (best.left !== null && tied.some(s => (s.left ?? -1) < best.left)) parts.push(`most quota left in the tie (${percent(best.left)}, against ${tied.map(s => percent(s.left)).join(', ')})`); + else if (tied.length) parts.push('a tie, taken in id order'); + if (skipped.length) parts.push(`skipped: ${skipped.join('; ')}`); + return parts.join('; '); +} + +export function pick(input) { + const { tickets = [], environments } = input; + if (typeof input.repo !== 'string' || !Array.isArray(environments) || !tickets.length) throw new Error('pick needs repo, tickets and environments'); + const now = input.now ?? Math.floor(Date.now() / 1000); + const { slots, skipped } = slotsOf({ ...input, now }); + if (!slots.length) throw new Error(`no slot for ${input.repo}: ${skipped.join('; ') || 'no Claude account can run a child task'}`); + return tickets.map(ticket => { + const best = [...slots].sort(byLoadThenQuota)[0]; + const placement = { + ticket, environmentId: best.environmentId, projectId: best.projectId, providerInstanceId: best.providerInstanceId, + line: `Placement: ${best.name}. Reason: ${reasonFor(best, slots, skipped)}.`, + }; + best.running++; + return placement; + }); +} + +function settingsArg(args) { + if (args.length === 0) return settingsFile(); + if (args.length === 2 && args[0] === '--settings') return args[1]; + throw new Error(USAGE); +} + +const MODES = { + quota: args => `${JSON.stringify(quota(JSON.parse(fs.readFileSync(settingsArg(args), 'utf8').replace(/^/, ''))))}\n`, + pick: () => `${JSON.stringify(pick(JSON.parse(fs.readFileSync(0, 'utf8').replace(/^/, ''))))}\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(process.argv.slice(3))); + } catch (e) { + process.stderr.write(`${e.message}\n`); + process.exit(1); + } +} diff --git a/plugins/bstack/skills/orchestrator/SKILL.md b/plugins/bstack/skills/orchestrator/SKILL.md index 992431c..27abbee 100644 --- a/plugins/bstack/skills/orchestrator/SKILL.md +++ b/plugins/bstack/skills/orchestrator/SKILL.md @@ -20,8 +20,12 @@ As `bstack:plan` sizes it: one ticket; a spec with tickets; or questions to the One lane per ticket, in the ticket's repo, in its own worktree. 1. Model: `node "${CLAUDE_PLUGIN_ROOT}/scripts/model.mjs" lane build -R ` prints `{ model, effort }` (`research` or `mechanical` for those kinds; `--failed ` 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 --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 `# `, 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 , made from origin's default branch; remove it when done." +3. Slot: a machine and a Claude account, placed by `node "${CLAUDE_PLUGIN_ROOT}/scripts/place.mjs" pick` with `{ "repo", "tickets", "environments", "quota" }` on stdin. Place every ticket of a round in one call, so they spread. + - `environments`: this machine (the `environmentId` that `t3_environment_links` returns at the top) and each linked one with `status: reachable`, each as `{ environmentId, capabilities, projects, threads }`: the `orchestrator_capabilities` answer, all pages of `t3_project_list`, and `t3_thread_list` with `allProjects`, `includeSubagents` and statuses running, starting, preparing and queued, all for that `environmentId`. + - `quota`: the output of `node "${CLAUDE_PLUGIN_ROOT}/scripts/place.mjs" quota`, once per round. It probes each Claude account in this machine's T3 settings with one small headless call; an account has the same provider instance id on every machine. + - It prints per ticket the `environmentId`, `projectId`, `providerInstanceId` and a `line`. It exits 1 when no slot can take the lane, with why. A repo that moved keeps its old owner in T3, so pass the name T3 shows (`gh repo view --json nameWithOwner` to compare). No machine has the repo: `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. Every account at its limit: report it with the reset time. +4. `delegate_task` with that brief as `task`, `isolation: "worktree"`, `mode: "async"`, a `title` of `# `, and `target`: the slot's `environmentId` (left out on this machine), `projectId` and `providerInstanceId`, `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 , made from origin's default branch; remove it when done." +5. Post the slot's `line` on the ticket (`gh issue comment`). Constraints every build brief carries: - Build issue in through the bstack ticket and ship playbooks; a `bstack:judge` you start judges. @@ -42,7 +46,7 @@ Pipe the lane's last message to `node "${CLAUDE_PLUGIN_ROOT}/scripts/lane.mjs" r - **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. +- A lane that failed on the account limit (its result starts with `Claude API rate limit reached`): run `place.mjs quota` again, so that account reads `rejected` until its reset, and start the lane again through `place.mjs pick`. Its brief adds the constraint "Continue from the pushed branch and its PR; do not start over", with the branch from `gh pr list -R --search "Closes # in:body" --json number,headRefName` or the ticket's status comment. No pushed branch: start from the default branch. 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. diff --git a/tests/place.test.mjs b/tests/place.test.mjs new file mode 100644 index 0000000..cd217a2 --- /dev/null +++ b/tests/place.test.mjs @@ -0,0 +1,117 @@ +// #325: the orchestrator spreads lanes over the machine and account pairs T3 reports, fewest running +// lanes first, more quota left in a tie, and never on an account at its limit. +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { spawnSync } from 'node:child_process'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { accounts, pick, quota, quotaOf } from '../plugins/bstack/scripts/place.mjs'; + +const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..'); +const SCRIPT = path.join(ROOT, 'plugins', 'bstack', 'scripts', 'place.mjs'); +const NOW = 1796500000; +const RESET = NOW + 3600; + +const claude = (id, canRun = true) => ({ providerInstanceId: id, driverKind: 'claudeAgent', canRunChildTask: canRun }); +const project = (id, key) => ({ id, repositoryIdentity: key ? { canonicalKey: key } : null, archivedAt: null, deletedAt: null }); +const threads = (id, n, status = 'running') => Array.from({ length: n }, () => ({ providerInstanceId: id, status })); +const env = (environmentId, { projects = [project(`p-${environmentId}`, 'github.com/o/r')], providers = [claude('acctA'), claude('acctB')], running = [] } = {}) => ({ + environmentId, capabilities: { providers: [...providers, { providerInstanceId: 'other', driverKind: 'codex', canRunChildTask: true }] }, projects, threads: running, +}); +const OPEN = { acctA: { status: 'allowed', left: 0.5, resetsAt: RESET }, acctB: { status: 'allowed', left: 0.8, resetsAt: RESET } }; +const slotOf = p => `${p.environmentId}/${p.providerInstanceId}`; + +test('four lanes started at once land on both machines and both accounts', () => { + const placed = pick({ repo: 'o/r', tickets: [1, 2, 3, 4], environments: [env('mach1'), env('mach2')], quota: OPEN, now: NOW }); + assert.deepEqual(new Set(placed.map(slotOf)), new Set(['mach1/acctA', 'mach1/acctB', 'mach2/acctA', 'mach2/acctB'])); + assert.deepEqual(placed.map(p => p.projectId), ['p-mach1', 'p-mach2', 'p-mach1', 'p-mach2']); +}); + +test('a lane goes only to a machine that has the repo', () => { + const placed = pick({ repo: 'O/R', tickets: [1, 2], environments: [env('mach1', { projects: [project('x', 'github.com/o/other'), project('y', null)] }), env('mach2')], quota: OPEN, now: NOW }); + assert.deepEqual(placed.map(p => p.environmentId), ['mach2', 'mach2']); + assert.match(placed[0].line, /skipped: machine mach1 has no clone of the repo/); + const archived = { ...project('z', 'github.com/o/r'), archivedAt: '2026-12-01' }; + assert.throws(() => pick({ repo: 'o/r', tickets: [1], environments: [env('mach1', { projects: [archived] })], quota: OPEN, now: NOW }), /no slot for o\/r: machine mach1 has no clone/); +}); + +test('the slot with the fewest running lanes wins; waiting and finished threads hold no process', () => { + const busy = [...threads('acctA', 2), ...threads('acctB', 1), ...threads('acctB', 1, 'starting'), ...threads('acctA', 3, 'waiting'), ...threads('acctB', 2, 'completed')]; + const placed = pick({ repo: 'o/r', tickets: [1], environments: [env('mach1', { running: busy }), env('mach2', { running: [...threads('acctA', 1), ...threads('acctB', 1, 'queued')] })], quota: OPEN, now: NOW }); + assert.equal(slotOf(placed[0]), 'mach2/acctB'); + assert.equal(placed[0].line, 'Placement: machine mach2, account 2. Reason: fewest running lanes (1, against 2, 2, 1); most quota left in the tie (80 %, against 50 %).'); +}); + +test('more quota left wins a tie; an unknown figure loses it', () => { + const placed = pick({ repo: 'o/r', tickets: [1], environments: [env('mach1')], quota: { acctA: { status: 'allowed', left: 0.9 } }, now: NOW }); + assert.equal(placed[0].providerInstanceId, 'acctA'); + assert.match(placed[0].line, /most quota left in the tie \(90 %, against unknown\)/); + const even = pick({ repo: 'o/r', tickets: [1], environments: [env('mach1')], quota: {}, now: NOW }); + assert.match(even[0].line, /a tie, taken in id order/); +}); + +test('an account at its limit gets no lanes until its reset', () => { + const limited = { ...OPEN, acctB: { status: 'rejected', left: 0, resetsAt: RESET } }; + const placed = pick({ repo: 'o/r', tickets: [1, 2, 3], environments: [env('mach1'), env('mach2')], quota: limited, now: NOW }); + assert.deepEqual(placed.map(p => p.providerInstanceId), ['acctA', 'acctA', 'acctA']); + assert.match(placed[0].line, /skipped: account 2 at its limit until 2026-12-0\d \d\d:\d\d UTC\.$/); + const after = pick({ repo: 'o/r', tickets: [1, 2], environments: [env('mach1')], quota: limited, now: RESET }); + assert.deepEqual(after.map(p => p.providerInstanceId).sort(), ['acctA', 'acctB']); + const allOut = { acctA: { status: 'rejected', resetsAt: RESET }, acctB: { status: 'rejected' } }; + assert.throws(() => pick({ repo: 'o/r', tickets: [1], environments: [env('mach1')], quota: allOut, now: NOW }), /account 1 at its limit until .*; account 2 at its limit until an unknown reset/); +}); + +test('only Claude accounts that can run a child task are slots', () => { + const placed = pick({ repo: 'o/r', tickets: [1, 2], environments: [env('mach1', { providers: [claude('acctA', false), claude('acctB')] })], quota: OPEN, now: NOW }); + assert.deepEqual(placed.map(p => p.providerInstanceId), ['acctB', 'acctB']); + assert.throws(() => pick({ repo: 'o/r', tickets: [1], environments: [env('mach1', { providers: [] })], quota: OPEN, now: NOW }), /no Claude account can run a child task/); + assert.throws(() => pick({ repo: 'o/r', tickets: [], environments: [] }), /needs repo, tickets and environments/); +}); + +const ALLOWED_STREAM = [ + '{"type":"system","subtype":"init"}', + '{"type":"rate_limit_event","rate_limit_info":{"status":"allowed_warning","resetsAt":1796612400,"rateLimitType":"seven_day","utilization":0.81,"unifiedWindows":{"five_hour":{"utilization":0.08,"resetsAt":1796505600,"status":"allowed"},"seven_day":{"utilization":0.81,"resetsAt":1796612400,"status":"allowed_warning"}}}}', + '{"type":"result","is_error":false}', +].join('\n'); +const REJECTED_STREAM = '{"type":"rate_limit_event","rate_limit_info":{"status":"rejected","resetsAt":1796508600,"rateLimitType":"seven_day","unifiedWindows":{"five_hour":{"utilization":0,"resetsAt":1796508600,"status":"allowed"},"seven_day":{"utilization":1,"resetsAt":1796706000,"status":"rejected"}}}}\n{"type":"result","is_error":true}'; + +test('the quota probe reads the rate limit event of a headless call', () => { + assert.deepEqual(quotaOf(ALLOWED_STREAM), { status: 'allowed_warning', left: 0.19, resetsAt: 1796612400 }); + assert.deepEqual(quotaOf(REJECTED_STREAM), { status: 'rejected', left: 0, resetsAt: 1796706000 }); + assert.deepEqual(quotaOf('not json\n{"type":"result"}'), { status: 'unknown' }); +}); + +test('each enabled Claude account in T3 settings is probed with its own config dir', () => { + const settings = { providerInstances: { + main: { driver: 'claudeAgent', enabled: true, config: {} }, + second: { driver: 'claudeAgent', enabled: true, config: { homePath: '~/.claude-second' } }, + off: { driver: 'claudeAgent', enabled: false }, + codex: { driver: 'codex', enabled: true }, + } }; + assert.deepEqual(accounts(settings), [ + { id: 'main', configDir: path.join(os.homedir(), '.claude') }, + { id: 'second', configDir: path.join(os.homedir(), '.claude-second') }, + ]); + const seen = []; + const result = quota(settings, dir => { seen.push(dir); return dir.endsWith('second') ? REJECTED_STREAM : ALLOWED_STREAM; }); + assert.equal(seen.length, 2); + assert.deepEqual(result, { main: { status: 'allowed_warning', left: 0.19, resetsAt: 1796612400 }, second: { status: 'rejected', left: 0, resetsAt: 1796706000 } }); +}); + +test('the command prints placements as JSON or exits 1 with the reason', () => { + const input = JSON.stringify({ repo: 'o/r', tickets: [5], environments: [env('mach1')], quota: OPEN, now: NOW }); + const ok = spawnSync(process.execPath, [SCRIPT, 'pick'], { input: `\uFEFF${input}`, encoding: 'utf8' }); + assert.equal(ok.status, 0, ok.stderr); + assert.equal(JSON.parse(ok.stdout)[0].providerInstanceId, 'acctB'); + const none = spawnSync(process.execPath, [SCRIPT, 'pick'], { input: JSON.stringify({ repo: 'o/r', tickets: [5], environments: [] }), encoding: 'utf8' }); + assert.equal(none.status, 1); + assert.equal(spawnSync(process.execPath, [SCRIPT, 'nope'], { encoding: 'utf8' }).status, 2); + assert.equal(spawnSync(process.execPath, [SCRIPT, 'quota', '--bad'], { encoding: 'utf8' }).status, 1); +}); + +test('the skill runs placement before every lane and posts its line', () => { + const skill = fs.readFileSync(path.join(ROOT, 'plugins', 'bstack', 'skills', 'orchestrator', 'SKILL.md'), 'utf8'); + for (const cmd of ['scripts/place.mjs" quota', 'scripts/place.mjs" pick']) assert.ok(skill.includes(cmd), cmd); +});