MAESTRO

Programme Notes

Note VII · Engineering

Spend expiring quota on the playbooks you never ran

Subscription plans hand out quota that expires at a reset, and most Maestro users have Auto Run playbooks they wrote and never ran. A Cue pipeline trades one waste for the other: it checks whether quota is really about to expire, picks the oldest unfinished playbook, reviews it for drift, and runs it in its own worktree.

Subscription plans for coding agents sell quota in windows. You get an allowance, a clock runs, and at the reset whatever you did not spend is gone. There is no rollover.

Most people who use Auto Run also have a folder of playbooks they wrote and never launched. Someone asks for a feature, you work it out with an agent until it is a playbook, and then you never get around to running it.

That is two kinds of waste side by side. This post describes a Cue pipeline that trades one for the other. When an account is about to throw quota away, the pipeline picks the oldest unfinished playbook, checks that it still makes sense, and runs it in its own worktree on that account. The output is a draft pull request.

Our worked example uses Claude Max, because its weekly window is the one we measured. The same pipeline works for any provider whose plan has a use-it-or-lose-it window and whose account Maestro can select per agent. The next section says which parts change per provider.

If you run several accounts, balance them first. Balancing agents across accounts moves agents so no account runs dry. This pipeline catches the opposite case: an account that will finish its window with quota left over.

What is generic and what is provider-specific

Almost all of this is plain Maestro. One piece is not: the probe that reads how much of a plan window is used and when it resets.

PartGeneric Maestro?How
ScheduleYesA Cue time.heartbeat subscription
Playbook picker and reviewYesReads your Auto Run folder; the review is one model call on any provider
Worktree agentYesmaestro-cli create-worktree
Billing identityPer providermaestro-cli update-agent --env, with the provider’s own variable
Launch and statusYesmaestro-cli auto-run, maestro-cli auto-run-status
NotificationsYesmaestro-cli notify toast
Quota probeProvider-specificReturns percent used and time to reset for one account

Maestro reads plan windows for two providers today. The Usage Dashboard shows an Anthropic Usage tab for Claude accounts (the session window and the weekly windows) and an OpenAI Usage tab for Codex accounts (Session (5h), Weekly, and any per-model limits). An account on an API key has no plan window. It pays per token, so it has nothing to waste.

The billing identity is the variable that selects the provider’s home directory:

ProviderVariableOne account per value?
Claude CodeCLAUDE_CONFIG_DIRYes
CodexCODEX_HOMEYes
Copilot CLICOPILOT_HOMENo: it moves transcripts, but the login stays machine-wide
OpenCode, Factory DroidnoneNo per-account variable

So the pipeline works as written for Claude Code and Codex accounts. No maestro-cli verb prints plan quota yet. For Claude we use maestro-p --status, which opens Claude’s /usage panel for the login in CLAUDE_CONFIG_DIR and prints it as JSON. For Codex you write a probe that returns the same two numbers for a given CODEX_HOME. Everything after the probe stays the same.

Why a heartbeat, not midnight

The first request was “run it nightly at midnight.” One measurement shows why that is wrong.

Each account runs its own window, and the windows reset at different times. A fixed clock catches each account at an arbitrary point in its week. On the evening we built this, one account had 58 unspent points with twenty minutes left before its reset. A midnight run would have found it freshly reset, and all 58 would have been gone.

So the pipeline is a time.heartbeat every 240 minutes. It asks the question at every point in every window, and the gates below decide whether the answer is “launch” or, much more often, “nothing to do”:

subscriptions:
  - name: waste-no-tokens
    label: Waste No Tokens
    pipeline_name: Token Management
    event: time.heartbeat
    interval_minutes: 240
    action: command
    command:
      mode: shell
      shell: python3 "$HOME/bin/waste_no_tokens.py" --apply

Because it does nothing on almost every run, it appends a ledger line on every run. A job that correctly does nothing and a dead job look the same unless the job writes down that it looked. Cue does not load your shell profile, so pin USER, HOME, PATH, and TERM inside the script.

The three gates

A run launches only if all three gates pass. Each one exists because leaving it out causes a specific failure.

waste   = 100 - projected_window_pct - already_reserved   >= 20 points
runway  = window_hours_left                               >= 6 h
urgency = waste / window_hours_left                       >= 0.5 points/h
Gate left outWhat goes wrong
WasteYou burn quota that ordinary work was going to spend, and take capacity from real work.
RunwayA four-hour run launched with twenty minutes left resets mid-run and bills the next window. That creates waste.
UrgencyA long window with a trickle of spare points looks worth a run. It is not worth a worktree.

Fig. 1 · The three gates

A run launches only if all three pass

flowchart TB
  HB["Heartbeat"] --> W{"Waste ≥ 20 points?"}
  W -->|yes| R{"Runway ≥ 6 h?"}
  R -->|yes| U{"Urgency ≥ 0.5 points/h?"}
  U -->|yes| GO(["Launch a run"])
  W e1@-->|no| X(["No run"])
  R e2@-->|no| X
  U e3@-->|no| X
  class W,R,U gate
  class GO step
  class e1,e2,e3 loop

Only the long window counts. Claude and Codex plans also have a five-hour session window. It refills all day, so its unused capacity is never lost. Only the weekly window expires.

The projection is the meter, not a model. The first version borrowed the balancer’s forecast, which weights the last few hours heavily. During one heavy interactive session it projected two accounts at 221% and 152%, so this pipeline saw no waste anywhere while a third account sat at 86% with fourteen hours left. The fix is plain arithmetic on the provider’s own meter:

projected = window_pct + (window_pct / hours_elapsed) * hours_left

It is the calculation you do by eye on the Usage Dashboard. One function computes it for the gate and the status report, so the number you read is the number the tool acted on.

Windows under twelve hours old never launch. A new window at 0% reads as 100 points of waste. Under twelve hours there is no information, and no information means no run.

Rank by urgency, not by points

Our first version picked the wrong account:

AccountUnspentHours leftPoints per hour needed
acct-a911610.56
acct-b52242.13
acct-c641050.61

acct-a had nearly twice the spare points of acct-b and no problem at all: a normal week spends them. acct-b was the account about to lose quota. Points per hour needed is the rate an account must sustain to finish its window spent. When it is high, the clock is the constraint. Below the urgency floor the tool declines even on a large pile of points, because a four-hour run to consume quota that ordinary work will consume is invented work.

Fill from the back of the window

The gates answer whether an account will waste quota. At first they also decided when, and that was a mistake.

One account reset at about 18:00 and nobody used it overnight. Twelve hours later the window cleared the age floor at 0% used: 100 points of projected waste over 156 hours, an urgency of 0.64. Every gate passed, and three runs launched at 06:16 into quota a normal week was about to spend. The rule fits in one sentence:

We’re only burning tokens if there’s tokens left as we get to the end of the time period.

A fixed rule such as “only in the last 24 hours” repeats the midnight mistake. The question is how much will be left, how much the backlog can absorb, and how long that takes. So the timing is a plan:

  1. Forecast the points the window will end with unspent.
  2. Size: pick playbooks oldest-first until their estimated cost covers that waste, or the backlog runs out.
  3. Schedule: work out how long that set takes at three concurrent runs, and launch only when the hours left fall to that duration plus one heartbeat.
launch when  hours_left <= max( longest_run, sum_of_runs / 3 ) + 4 h

Every heartbeat re-projects, so the decision is made on a meter with most of the week behind it.

Measure your own cost per task. We assumed about 20 points per run. The 06:16 batch was the first clean measurement: the account went from 0% to 17% while 56 tasks closed in about four and a half hours. That is roughly 0.3 points and 0.2 hours per open task, an upper bound since some interactive work shared the account. A typical run costs 5 to 7 points, so a 100-point hole needs closer to twenty runs than five.

The backlog is the real limit. Most past windows on our accounts ended at 96% to 100%. The few that ended short (42%, 80%, 84%) were real waste. On the day of the fix, the eligible backlog was two playbooks with 81 open tasks, about 24 points of work, against 100 points of waste. The status report now prints the points no playbook can absorb. Spending more needs more work in the queue, not a smarter clock.

Pick the oldest playbook, then review it

The oldest playbook is the most forgotten and the most likely to have drifted from the code. Picking it forces a review that would otherwise never happen.

  • Unfinished means at least one open - [ ] task. Otherwise a folder with zero tasks gets picked and a window is spent finding out it has nothing to run.
  • Age comes from a YYYY-MM-DD prefix on the playbook folder, not the modified time. Opening a playbook to read it would otherwise make it look new.

Before anything launches, one call to a small model per candidate returns JSON:

FieldValuesDefault when unsure
base_branchyour integration branch or mainthe integration branch (ours is rc)
driftnone, minor, majorunknown, judged against the last 25 commits on both branches
still_worth_runningtrue or falsefalse only if the work is already built or obsolete

Validate every value after parsing, and degrade a failed call to the defaults instead of aborting. On minor or major drift, a second pass edits the playbook in place to match the current code.

Three rules came out of the first live runs:

  1. An obsolete playbook does not use up the launch slot. The first real run found the two oldest playbooks both obsolete. It now skips forward, capped at six reviews.
  2. Cache “obsolete”, never “worth running”. Same playbook, same commits, three reviews: obsolete, obsolete, worth running. Ask the same question every four hours and the model will eventually give the answer that spends quota. Work that is already done stays done; drift keeps building.
  3. Bill the review to another account. Spending the expiring account’s quota to decide whether to spend it is circular.

The launch order

Fig. 2 · The launch order

Repoint the agent, then launch

flowchart TB
  V[Validate inputs] --> W[create-worktree]
  W --> P[Wait for agent to persist]
  P --> E[update-agent --env]
  E --> R[Read it back]
  R --> S[Reserve account]
  S --> L[auto-run --launch]
  L -. next heartbeat .-> PR[Push and open draft PR]
  class V gate
  class PR step
The draft pull request comes from a later heartbeat, not from the launch.

The account an agent bills is set by an environment variable on that agent, so the order is the whole design.

maestro-cli auto-run --worktree creates a worktree and launches in one call. It spawns a new child agent, and a worktree agent inherits its parent’s variables, so the run lands on the parent’s account. The pipeline instead creates the worktree agent, repoints it, and then launches:

# 1. Create a worktree agent in the background (the JSON field is "agentId")
maestro-cli create-worktree -a <parent-agent-id> -b burn/<playbook> \
  --base-branch rc --background --json

# 2. Repoint it at the account that is about to waste quota
maestro-cli update-agent <new-agent-id> --env CLAUDE_CONFIG_DIR="$HOME/.claude-acct-b" --json

# 3. Read it back, and stop on a mismatch
maestro-cli show agent <new-agent-id> --json

# 4. Launch, with absolute paths to the playbook documents
maestro-cli auto-run /abs/path/to/playbook/*.md -a <new-agent-id> --launch

For Codex, step 2 sets CODEX_HOME.

Wait for the agent to persist. A new worktree agent lives only in the app’s memory for a few seconds, until a debounced write puts it on disk, and update-agent resolves agents from disk. Six creates once returned valid ids, six updates said “Agent not found” in the same second, and all six agents existed minutes later. Poll until the agent appears.

Read the account back. “We never set it” and “we set it correctly” both look like a healthy agent on a valid account. Only the re-read tells them apart.

Reserve before launch. If you also run the balancer, it looks for the account with the most room, which is the same account this pipeline is about to fill. A forced rebalance right after launch does not help: a sixty-second-old agent has no activity in Maestro’s stats yet. So both tools read a small reservation file (“this account will lose N points over the next H hours”). The order is reserve, launch, rebalance, and reserved agents are pinned so the balancer cannot move them mid-run.

Use absolute paths. auto-run resolves relative paths against the CLI’s working directory, and under Cue that is not your playbook folder.

The pull request comes from a later heartbeat

--create-pr is accepted only with --worktree, the one flag this design cannot use. So each heartbeat starts with a sweep over recorded runs:

maestro-cli auto-run-status -a <agent-id> --json

Once running is false, the sweep checks for an existing PR on the branch in any state (gh pr list --head <branch> --state all). If there is none, it pushes the branch detached, because our pre-push hook runs the full CI gate and outlasts a heartbeat. The next heartbeat confirms the branch reached the remote and runs gh pr create --draft. A run with no commits gets a yellow toast and no PR. A run paused on an error counts as still running, so it waits for a person instead of shipping.

The pipeline never merges. The worktree stays, because the next step is a person opening it and polishing the PR. On launch, a sticky toast says what happened:

maestro-cli notify toast "Expiring quota spent" "burn/<playbook> launched on acct-b, 30 pts expiring" \
  --color green --dismissible --agent <new-agent-id> --source-agent "Waste No Tokens"

Sticky, because this fires while you sleep, and a notice that auto-dismisses unseen looks like a run that never happened.

Failures a dry run could not see

The design was about a third of the work. The rest was the launch path, and every failure there was invisible to a dry run, because a dry run stops before the steps that break.

  • Reading an interface from memory. create-worktree --json returns agentId, not id. The parser found nothing and reported “no agent id” after the agent already existed, leaving an orphan on the wrong account.
  • State that only the happy path writes. The attempt counter was written at the end, so a crash erased the record that a worktree existed. The next heartbeat made another orphan. The attempt is now saved before the review, and an exception handler flushes the ledger.
  • continue versus break. A launch failure is a fault in the launch path, not the playbook. Moving to the next playbook made six orphans and exited 0. It now stops on the first launch error and exits 1, so Cue shows it failing.
  • Cleanup that lied. Cleanup looked for the worktree at the wrong path and reported a refused branch delete as “absent.” Maestro later adopted the stray worktree as an agent. Cleanup now asks git worktree list --porcelain where the branch lives.
  • The test that skipped the step that broke. Our zero-cost probe walked every launch step except Auto Run, because that step spends quota. The gate then qualified eight times in eight days, and every launch was refused at that step: --create-pr requires --worktree. The flag had been copied from the help text and never run. The job showed red each time, and nobody reads a red light on a job that usually does nothing. The two-attempt cap retired four healthy playbooks for a fault that was never theirs.
  • The PR step. A 180-second push timeout against the CI pre-push hook crashed the whole run, five heartbeats in a row. The sweep now pushes detached and catches every failure per run.
PASS create-worktree agentId=<id>
PASS wait-for-persist 9.1s
PASS update-agent
PASS pin-readback got=~/.claude-acct-b
PASS auto-run-argv
PASS cleanup leftovers=none
probe-launch: ALL PASS in 12.1s

With the old command patched back in, the probe stops where production broke:

FAIL auto-run-argv Error: --branch, --base-branch, --worktree-path, --create-pr,
     and --pr-target-branch require --worktree

What it never does

RuleWhy
Never launches on an account it could not readUnknown is not empty.
Never launches on an API-key accountIt has no window, so nothing expires.
Never launches a playbook already in flightMatched by the reservation label.
Never picks a playbook a third timeOtherwise oldest-first re-picks the same stuck playbook forever.
Never mergesThe output is a draft PR and a worktree. A person finishes it.
--status never spendsThe first version made a model call per playbook just to print a table.

Build it

Maestro does not spend expiring quota natively yet, and you do not need it to. Worktrees, per-agent environment, Auto Run, toasts, and scheduling are all CLI verbs, so the agent in your tab can assemble them. In dependency order:

  1. One home directory per plan account (CLAUDE_CONFIG_DIR or CODEX_HOME). One account works too.
  2. A quota probe returning percent used and hours to reset for the long window: maestro-p --status for Claude, your own for Codex.
  3. The three gates, the twelve-hour floor, and ranking by points per hour needed. Default to doing nothing.
  4. The timing plan, sized with your own measured cost per task.
  5. A playbook picker: open tasks only, oldest date prefix first, skipping anything in flight or tried twice.
  6. A review call, validated, caching only “obsolete”, billed to another account.
  7. The launch in order, with the persist wait, the full --env map, and the read-back. On any failure after the worktree exists, remove the agent (maestro-cli remove-agent), the worktree, and the branch.
  8. A finish sweep and a reservation file, if you run a balancer.
  9. Crash-safe state and a non-zero exit on the first launch error.
  10. A --probe-launch mode, proven to fail once before you trust the schedule.
  11. The Cue heartbeat. Trigger it once with maestro-cli cue trigger waste-no-tokens and check maestro-cli cue activity. Alert on a run of failures, not only on staleness: eight days of red is how the --create-pr bug hid.

Or describe it to a Maestro agent:

Every four hours, check each of my plan accounts. If one will end its week with at least 20 points unspent, has at least six hours left, and would need more than half a point an hour to spend it normally, work out how much of my playbook backlog fills that gap and how long it takes, and wait until just late enough to finish before the reset. Then pick my oldest playbooks with open tasks, check each against the current code, fix any drift, and run each in its own worktree billed to that account. Open a draft PR when each finishes, never merge, and leave me a toast. Build a zero-cost test of the launch path that sends the real commands, prove it can fail, and run it before you schedule anything.

Tagged cue auto-run maestro-cli worktrees usage-dashboard scheduling