Reading cost outside spwn
spwn writes each session’s cost into a file of its own, in spwn’s data folder. Reading it doesn’t need spwn, only a TOML parser, so a script can total a sprint’s branches and a workflow can report what a ticket cost.
The file is not in your repository. spwn used to commit it on the session’s branch; it no longer does, so a branch’s diff is the work and nothing else. The cost of a change still reaches your teammates, in the pull request.
The PR doc
Section titled “The PR doc”Each session has one PR doc:
<app data dir>/pr/<project id>/<branch-slug>.mdThe app data dir is
~/.local/share/gg.spwn.spwn/ on Linux. The slug is the branch name with anything
outside A-Z a-z 0-9 . _ - replaced by -, so branch spwn/1a2b3c4d has its doc at
pr/<project id>/spwn-1a2b3c4d.md. The Inspector’s PR tab shows the full path, and
a workflow gets the folder from spwn.project.prDocs.
The file is TOML front matter between +++ fences, followed by markdown prose:
+++problem = "checkout-latency"reviewer = "dana" # anything you like
[cost]files = 1model = "claude-opus-5"sessions = ["6b254ae6-c327-43f6-a071-e19fc5baad4d"]usd = 5.9289
[cost.tokens]cacheRead = 6120455cacheWrite = 188920cacheWrite1h = 170512cacheWrite5m = 18408input = 310output = 41877requests = 58+++
# Cache the tax lookup
The agent's description of the change…The fences are +++, not ---. Most tools read --- as YAML. The front matter is
free-form: spwn owns cost (plus title, pr, pr_url and pr_repo once a pull
request exists), and every other key is yours. When spwn writes a key, it rewrites only
that key and leaves your comments, key order, and prose unchanged. Every field of
cost is described in How cost is counted.
One file per branch, so no two sessions ever write the same one.
Reading one branch
Section titled “Reading one branch”It is a file; read it:
cat ~/.local/share/gg.spwn.spwn/pr/<project id>/spwn-1a2b3c4d.mdFor one branch on its own, cost.usd and cost.tokens are the figures you want: the
whole conversation, including anything inherited from a fork.
Adding up several branches
Section titled “Adding up several branches”To total several branches, add up each one’s own spend, not its tokens. Three
rules cover every doc:
- If
ownis present, use it. The session is a fork, andownexcludes the conversation it inherited. - If
ownis absent, it equalstokens. The session inherited nothing. - If
ownUnknown = true, skip the session. spwn couldn’t measure what it inherited, and itstokensinclude spend that’s already counted on its parent.
This script applies those rules to every doc in a project’s folder. It uses only
Python’s standard library (3.11 or later, for tomllib):
#!/usr/bin/env python3"""Total what every spwn branch in a project cost, from the PR docs alone."""import pathlib, re, sys, tomllib
FIELDS = ("input", "output", "cacheRead", "cacheWrite", "requests")FRONT = re.compile(r"\A\ufeff?\+\+\+\r?\n(.*?)^\+\+\+\r?$", re.S | re.M)
docs = pathlib.Path(sys.argv[1]) # <app data dir>/pr/<project id>
total = dict.fromkeys(FIELDS, 0)usd = 0.0for path in sorted(docs.glob("*.md")): name = path.stem match = FRONT.match(path.read_text()) cost = tomllib.loads(match.group(1)).get("cost") if match else None if not cost: print(f"{name:32} no cost recorded") continue if cost.get("ownUnknown"): print(f"{name:32} skipped: own share unknown") continue own = cost.get("own", cost["tokens"]) # absent own == tokens own_usd = cost.get("ownUsd") if "own" in cost else cost.get("usd") for k in FIELDS: total[k] += own.get(k, 0) usd += own_usd or 0.0 shown = f"${own_usd:,.2f}" if own_usd is not None else "unpriced" print(f"{name:32} {shown:>10} {own['requests']:>6} req")
print(f"{'total':32} ${usd:>9,.2f} {total['requests']:>6} req " f"{total['output']:,} output tokens")python3 scripts/spwn-cost.py ~/.local/share/gg.spwn.spwn/pr/<project id>A few notes on the result:
- Tokens sum exactly. Dollars are an estimate. A fork’s
ownUsdis itsusdsplit by request share, andusditself comes from a rate table. If the table was emptied, there’s nousd, and the script reportsunpriced. - Only branches that still exist are counted. A doc is removed once its branch and its session are both gone, as described in the next section.
- It runs where spwn runs. The docs are on the machine spwn is on, so this is not a CI job. What CI and reviewers can see is the cost line in the pull request.
After a branch lands
Section titled “After a branch lands”A PR doc lasts as long as something refers to it. When a session is deleted, spwn removes every doc in the project whose branch no longer exists and whose session is gone. A branch that outlives its session keeps its doc.
Once the doc is removed it is gone: nothing commits it, so there is no history of it to read back. What stays is the pull request, whose body carries the cost as of its last Push update.
Upgrading from committed PR docs
Section titled “Upgrading from committed PR docs”Older versions of spwn kept the doc at .spwn/pr/<branch-slug>.md in the worktree and
committed it. Two things are left over from that:
-
A session started under the old version still has its doc in its worktree. spwn moves it into the data folder the first time it reads it, and the file’s deletion shows up in that session’s next commit.
-
Your base branch may still carry
.spwn/pr/files from sessions that merged. Nothing reads them and nothing removes them for you. Delete them once:Terminal window git rm -r .spwn/pr && git commit -m "Remove spwn PR docs from the repo"
Rollups in a workflow
Section titled “Rollups in a workflow”Inside spwn, a workflow can get a group total without reading the
files. session.cost() returns spend across every session working the same problem
as the one you call it on:
export default async (spwn) => { const s = await spwn.sessions.find("TICKET-412"); if (!s) return; const { problem, sessions, total } = await s.cost();
console.log(`${problem.kind} ${problem.key}: $${total.usd ?? "?"} over ${total.requests} requests`); for (const row of sessions) { console.log(row.title, row.branch, row.own ? `${row.own.requests} req` : "not measured"); }};spwn groups sessions within the project by the first rule that applies:
problem.kind |
Groups sessions that… | problem.key |
|---|---|---|
declared |
have the same problem key in their PR doc’s front matter |
that value |
workflowKey |
were created by the same workflow with the same key (sessions.create({ key }) or agents.run({ key })) |
the key |
lineage |
descend from the same root session by forking | the root session’s id |
declared is the only rule that can group sessions that were never forked from one
another. Set it from the PR tab’s front-matter editor, from a workflow with
s.setPr({ problem: "checkout-latency" }), or by having the agent write it into the
doc.
The result has this shape:
totalis the group’s spend, with the same token fields ascost.tokens, plususdandunpricedwhere they apply. spwn computes it by scanning all the group’s transcripts together and deduplicating by request id. It isn’t a sum of anyone’stokens, so shared fork history is counted once.sessionsis one row per member:terminalId,title,branch, andown.ownis the part that’s safe to add up, already resolved (an absentownin the doc shows up here astokens). It’snullfor a session with no cost yet, or one markedownUnknown.
The PR tab shows the same rollup under Spend across this problem. The full types
are in spwn.d.ts
and the Workflows API reference.
In the pull request
Section titled “In the pull request”When spwn opens a pull request from a session, or you press Push update, the body
gets a spwn section between <!-- spwn:begin --> and <!-- spwn:end -->. It ends with
a one-line summary such as Cost to produce: $5.93 · 6.4M tokens. The token count
there is the session’s own input, output, cache-read and cache-write tokens added
together. See Pull requests.