Skip to content

Latest commit

 

History

History
1307 lines (1091 loc) · 76.4 KB

api.md

File metadata and controls

1307 lines (1091 loc) · 76.4 KB

briefstack web API

The local server started by briefstack web (BRIEF-phase-2 §6). The browser UI uses it; phase 4's global chat and phase 5 can call it too.

Requests

  • The server listens on 127.0.0.1 only. The Host header must be 127.0.0.1:<port> or localhost:<port> (403 web.rejected.host).
  • Every /api call needs the per-launch token in X-Briefstack-Token (401 web.rejected.token). briefstack web prints it in the URL fragment: http://127.0.0.1:<port>/#token=<token>.
  • Every call that is not GET/HEAD also needs Origin equal to the server's own origin, and Sec-Fetch-Site: same-origin when the browser sends it (403 web.rejected.origin).
  • JSON bodies: Content-Type: application/json (else 415 web.unsupportedMediaType), at most 64 KB (else 413 web.bodyTooLarge), valid JSON (else 400 web.invalidJson) of the documented shape, with no extra fields (else 400 web.invalidBody).
  • Unknown route or method: 404 web.notFound.

Server mode (phase 12)

briefstack web --server (server.md) changes only these rules:

  • It listens on --listen (an IP address; 127.0.0.1 by default). The Host header may also be one of --allowed-hosts (name:port, exact), whose Origin must be https://<name:port>; the loopback names keep http://.
  • No token: it is never printed and never accepted. Every /api call needs a device session, the cookie __Host-briefstack-session (HttpOnly; Secure; SameSite=Strict; Path=/), else 401 web.rejected.session. Open without one: GET /api/health, GET /api/server/state and POST /api/server/sign-in (which still needs the Origin check).
  • Codex is off: GET /api/codex answers reason: "serverMode", POST /api/codex/check and PUT /api/settings with codexEnabled: true answer 409 codex.serverMode.

GET /api/server/state

{ "mode": "local" } in local mode (where it needs the token like any other route), or { "mode": "server", "signedIn": true | false } in server mode, with no credential needed. Nothing else.

POST /api/server/sign-in (server mode)

Body { "secret" } (at most 4 KiB; a larger body is a 413). The right access secret answers { "ok": true, "device": { "id", "label" } } with the session cookie in Set-Cookie; the token is never in the body. A wrong one is a 401 server.signInFailed. After 5 failures within 15 minutes every sign-in is refused for 15 minutes, the right secret included: 429 server.signInLocked with params.seconds left. A malformed body is a 400 that never repeats what was sent.

POST /api/server/sign-out (server mode)

Signs this device out: { "ok": true } and a cleared cookie. Its open streams end.

GET /api/server/devices (server mode)

{ "devices": [{ "id", "label", "createdAt", "lastSeenAt", "current" }] }: the signed-in devices (label from the browser's User-Agent, "" when it sent none). Never a token or its digest. A device unused for 400 days is forgotten.

POST /api/server/devices/:id/revoke and POST /api/server/devices/revoke-all (server mode)

Sign one device out (404 server.deviceNotFound when there is none with that id), or every device, this one included (the answer clears the cookie). Their open streams end at once.

Errors

Route errors come back as:

{ "code": "creation.limit", "params": { "limit": 2, "active": ["<id>", "<id>"] }, "message": "The limit of active creations is reached (…)." }

message is in the server's language (BRIEFSTACK_LANG, config lang, OS locale). code and params are stable: clients that show their own text use those. The security rejections above send { "code" } only.

Status Codes
400 web.invalidJson, web.invalidBody, web.invalidQuery, creation.invalidAnswer, any other coded error
404 web.notFound, creation.notFound, creation.noSpec, library.noteNotFound, library.commitNotFound, events.sessionNotFound
409 creation.limit, creation.noReply, library.busy, creation.noPending, creation.wrongPending, library.dirtyTree, library.revertConflict
413 web.bodyTooLarge
415 web.unsupportedMediaType
503 creation.unavailable (the server was started without a creation manager; briefstack web always has one), task.stopping (the server is stopping: no task, round or checks start; see the task routes)

Routes

GET /api/health

200 { "ok": true, "version": "0.1.0", "busy": 0 }

busy (step 41): how much work is under way in this server now, so that something which restarts it (a server that updates itself) can wait for 0. It counts one for each creation not finished (a restart leaves it interrupted), each task running a round or checks (a build's cards included), each build planning or with its loop running (its cards, its joins and their checks, a wait for a free slot), the improvement session, an improvement round being checked and each improvement real check running, and the chat while it answers. A build paused, interrupted or finished counts 0 (a restart keeps a usage pause only with buildsAutoResume; without it the build is left interrupted); a build that resumes by itself after a restart counts again once it runs. A creation waiting for the user's answer, and a task round waiting for one, count with no time limit. Not counted: the short git steps of an apply or a revert (tasks, builds, improvements). It is read from memory, never from files, and the answer holds nothing else. In server mode the route answers without a session; in local mode it needs the token, as every /api route.

GET /api/claude and GET /api/claude?refresh=1

The user's Claude Code, as the server read it at start (refresh=1 reads it again): whether it is installed and how its version compares with the one the SDK was built for, and how it signs in, as Claude Code itself reports it (accountInfo(), from a session that sends no message). No executable path, no e-mail or organization, no secret.

{
  "install": { "status": "compatible", "installed": "2.1.310", "expected": "2.1.286" },
  "mode": { "kind": "signIn", "plan": "Claude Pro" }
}

install.status: compatible, older, untested (with both versions), unknownVersion or notFound. mode.kind: signIn (optional plan), apiKey (source: environment, helper, login, bearer or other), cloud (provider, as Claude Code names it: bedrock, vertex, foundry, anthropicAws, mantle, gateway…), none (not signed in) or unknown (Claude Code could not be asked). Without a reader (tests that pass none): 503 { "code": "claude.unavailable" }.

Read routes

All GET, all need the token. They read the config and files on every call, so a change made from the CLI shows at once. Text from notes and generated files passes the secret check first: a line that looks like a secret comes back as [redacted].

GET /api/projects

200 { "projects": [ProjectListing, …] }, newest first. A listing is { slug, file, name, created?, session?, status?, issues? }: status is the note's frontmatter (target, path, status, profile, updated, summary), issues says what is wrong with an invalid one.

GET /api/projects/:slug

{
  "project": { "slug": "…" },
  "note": { "file": "projects/<slug>.md", "text": "…" },
  "timeline": { "summary": {}, "steps": [], "agents": [] },
  "nextSteps": "…",
  "instructions": "…",
  "openCommand": { "cwd": "<project path>", "command": "claude" },
  "targetChoice": { "chosenBy": "user", "reason": "…" }
}
  • timeline is the creation session's (see GET /api/sessions/:id), or null without a session or without its events.jsonl.
  • nextSteps and instructions are the text of NEXT_STEPS.md and INSTRUCTIONS.md for claude-app projects, else null. A missing or oversized (over 256 KB) file is null too.
  • openCommand is where to run claude; null when the note has no valid status block.
  • targetChoice comes from the project's .briefstack/spec.json: chosenBy (user | architect) and reason (the spec's targetReason, redacted), each optional. null when the spec is missing, unreadable or has neither field (projects created before the field existed).
  • 404 library.noteNotFound for an unknown slug; 400 for an invalid one.

GET /api/sessions

200 { "sessions": [{ id, status, outcome?, startedAt?, lastEventAt?, lastStep?, endReason?, idea?, archived? }, …] }, newest first. status is finished | in-progress | interrupted; outcome (completed | cancelled | failed) comes with finished. The UI lists interrupted and cancelled ones apart, named by their idea, with their lastStep. archived (ISO time) marks an unfinished one the user archived: the page hides it unless asked; the chat's list_sessions still lists it, marked.

PUT /api/sessions/:id/archived

Body { "archived": true | false } (phase 9 step 33). Archives or restores an interrupted or cancelled creation: the choice is kept in <home>/archived-sessions.json, never in the session's folder, and nothing is deleted. { id, archived? }. 404 events.sessionNotFound; 409 sessions.notUnfinished for a creation that is neither interrupted nor cancelled; 409 sessions.archiveUnreadable when that file does not read back (it is not overwritten).

idea (read-only, added in the UI pass) is the session's idea.md as the flow wrote it: lines that look like a secret replaced with [redacted], whitespace collapsed to one line, cut to 300 characters (… at the end). It is absent when the file is missing, empty or over 64 KB. Only this route returns it; the chat's list_sessions tool does not.

GET /api/sessions/:id

200 { summary, steps: [{ step, startedAt, finishedAt?, outcome? }], agents: [{ agentId, agentType, startedAt, stoppedAt? }] }. 404 events.sessionNotFound, 400 events.invalidSession.

GET /api/sessions/:id/events

The session's lines for the agent panel (phase 3): 200 { "events": [ { "id", "v", "ts", "session", "source", "type", … } ], "badLines": <n>, "state": <PanelState> }.

  • events: every valid line of events.jsonl in file order, projected (src/panel/project.ts): known fields only (docs/events.md), targets and denial reasons redacted, any absolute path shown as [outside allowed folders], a target at most 120 characters and a reason at most 300. id is the line's position among the valid lines, from 1; the creation stream gives hook and runner lines the same id.
  • badLines: how many lines could not be read.
  • state: buildPanelState(events, { now }) (src/panel/state.ts): the session, one node per agent (main session first), the timeline, the flow steps and plan usage. For a creation still open, the page adds what the creation stream knows (the pending request).
  • 404 events.sessionNotFound, 400 events.invalidSession.

Library

  • GET /api/library/index: { "file": "INDEX.md", "text": "…" | null }.
  • GET /api/library/notes[?section=<s>]: { "notes": [{ section, name?, file, summary }, …] }; sections are profile, projects, log, skills, lessons. An unknown section is a 400.
  • GET /api/library/note?section=<s>[&name=<slug>]: { "file", "text" }. lessons takes no name; the others need one. 404 library.noteNotFound.
  • GET /api/library/history[?limit=<1–200>]: { "commits": [{ sha, shortSha, date, subject, files }, …] }, newest first, 50 by default. A library without git history has none.

GET /api/usage

What briefstack usage show --json prints (profile, label, fromConfig, sessionModel, chat: { model, effort }, agents, tiers, research, reviewRounds, available, drift, envWarnings) plus presets: [{ name, source: "base" | "user", label: { en, es }, sessionModel, effort, chat, tiers, research, reviewRounds, agents }, …] (agents: each flow agent's { model, effort }), lastPlanUsage: { fiveHour, sevenDay, at, fiveHourResetsAt?, sevenDayResetsAt? } (percent or null, the ISO time of the reading, and each window's reset time when the reading gave one) or null, and activity: { creations, builds } (active creations, and builds planning or running) or null. The plan usage is the last one the server read (for a creation's panel, before a start, before a build's task, or for the chat's show_usage), saved in <home>/plan-usage.json; the route never reads the usage itself. The page's note on the week uses them (phase 9 step 33). No token or cost figures.

POST /api/usage/presets

Body { name, base, label: { en, es }, sessionModel?, effort?, agents? } (phase 9 step 33; agents: { <flow agent>: { model, effort? } }). A user preset made from base with those changes, checked with the same schema as the CLI's profiles file and added to the user's usage-profiles.json (an existing one that does not read back is refused, never overwritten). 201 { name }. No agent file changes and the active profile stays: .claude/agents/*.md are written only by briefstack usage set (PUT /api/usage). 409 usage.presetExists for a name that exists, base or user; 400 usage.unknownProfile for an unknown base; 400 usage.invalidProfiles when the result breaks the schema; a name outside [a-z0-9]+(-[a-z0-9]+)* is 400 web.invalidBody.

GET /api/paths

What briefstack paths --json prints: home, configFile, libraryDir, libraryExists, projectsDir, sessionsDir, repoDir, allowedDirs.

GET /api/paths/check?dir=<path>

What briefstack paths check inspects, for a folder that is absolute or starts with ~: { "outDir", "status", "overlaps"? }. status is missing, empty, nonEmpty, notADirectory or forbidden; overlaps (repo, library, home, claudeConfig, appData or localAppData) comes with forbidden. A folder inside one of them, or one that contains one (a drive root, the user's home), is forbidden. Nothing is created. A relative path is a 400 config.relativePath. Settings uses it to say that a missing projects folder will be created.

GET /api/settings

{ "projectsDir", "lang", "configLang": "en" | "es" | null, "permissionPolicy": "ask" | "unattended", "maxActiveCreations": 2, "usageWarning": { "fiveHour": 80, "week": 85 }, "codex": { "enabled": false, "mode": "unelevated", "maxCalls": 5 } }. lang is the language in use; configLang the one saved in the config; usageWarning the plan-usage percentages from which a start shows a warning; codex the Codex settings of task rounds (phase 8, "Codex routes").

Write routes

Mutating: they need the token, the Origin check and a JSON body, as in "Requests". They call the same library code as the CLI. Responses never echo note text and the server log has no bodies, so a refused secret goes nowhere.

PUT /api/library/note

Body { "section", "name"?, "text" } (text up to 48 KB; lessons takes no name, the others need one). Saves the whole note as saveNote does: text that only adds lines at the end becomes a dated append (### YYYY-MM-DD), any other edit is a full rewrite. Notes in projects/ keep a validated status block. One commit and an INDEX.md update. Answers { section, name?, file, mode: "append" | "rewrite" | "create" | "unchanged", indexUpdated, committed, status?, warnings }. Text with a secret is a 400 library.secretContent (params.lines are line numbers) and nothing is written. A text that changes the path of a project note that has one is a 409 library.pathProtected: it is where briefstack made the project, and installs go there.

POST /api/library/revert

Body { "sha" } (4–64 hex characters). Undoes that commit with a new one: { "reverted": sha, "commit": newSha }. 404 library.commitNotFound; 409 library.dirtyTree (uncommitted changes) or 409 library.revertConflict (aborted, the library is as it was). The UI asks for confirmation first.

PUT /api/usage

Body { "profile" }: what briefstack usage set <profile> does (rewrites the repo's agent files and saves activeProfile). Answers { "scope": "repo", "profile", "sessionModel" }. An unknown profile is a 400 usage.unknownProfile.

PUT /api/settings

Body with at least one of:

  • projectsDir: absolute or starting with ~. The folder is created and allowed in the repo's settings.local.json, the old one stays allowed. A relative path is a 400 config.relativePath.
  • lang: "en", "es", or null to clear it.
  • permissionPolicy: "ask" or "unattended".
  • maxActiveCreations: a whole number from 1 up (default 2): how many creations may be active at once.
  • usageWarnFiveHour, usageWarnWeek: whole numbers from 1 to 100 (defaults 80 and 85): the plan-usage warning thresholds.
  • codexEnabled: true or false (default false): whether task rounds may get delegate_to_codex (phase 8).
  • codexMode: "unelevated" (default) or "elevated": Codex's Windows sandbox mode. Saved on any system; only Windows uses it.
  • codexMaxCalls: a whole number from 1 to 10 (default 5): Codex calls per task round, and per implement step of a creation (phase 10).
  • implementMaxMinutes: a whole number from 5 to 120 (default 30), and implementMaxToolCalls: from 20 to 1000 (default 150): the bounds of a creation's implement step (phase 10). Both views answer them as implement: { maxMinutes, maxToolCalls }.
  • buildsAutoResume: true or false (default false): builds a restart interrupted resume by themselves at the next start (phase 12).
  • buildSlotsCap: a whole number from 1 to 4 (default 4): the most cards a build runs at once on this machine (phase 12). Both views answer them as builds: { autoResume, slotsCap }.

Reserve providers are not settings of this route: they are written in config.json by hand (see "Reserve providers").

Answers the same as GET /api/settings.

PUT /api/projects/:slug/archived

Body { "archived": true | false }. Archives (archived: <date> in the note's status block) or unarchives (the line removed) a project; nothing else changes and nothing is deleted. One commit. { "archived": "<date>" | null, "committed", "warnings" }; unchanged when it already was. 404 library.noteNotFound. GET /api/projects keeps listing archived projects (status.archived); the page hides them unless asked.

Creation routes

POST /api/creations

Starts a creation session, which runs the /new-project flow.

  • Body: { "idea": "<free text, 1–20000 chars>", "force"?: true }
  • 201 { "id": "<creation id>" }
  • 409 creation.limit when as many creations as config maxActiveCreations (default 2) are active.
  • 409 usage.high with params { fiveHour, sevenDay, warnFiveHour, warnWeek } when the plan usage is at or above a threshold (Settings) and force is not set: nothing started. The page shows the values and sends the same body with "force": true for "Start anyway". The reading is the /usage one (a session that sends no message); one younger than a minute is reused; without a reading there is no warning.

GET /api/creations

200 { "creations": [CreationState, …] }, oldest first.

GET /api/creations/:id

200 CreationState:

{
  "id": "…",
  "sessionId": "…",
  "idea": "…",
  "profile": "balanced",
  "policy": "ask",
  "status": "running | waiting | finished",
  "outcome": "completed | cancelled | failed | interrupted",
  "pending": { "id": "p3", "kind": "question | permission | spec | grant", "payload": {} },
  "cancelling": true,
  "awaitingReply": { "lastMessage": "…", "at": "<ISO time>" },
  "currentStep": "interview",
  "usageReading": true,
  "denied": [{ "toolName": "Bash", "summary": "…", "agentType": "generator", "at": "<ISO time>" }],
  "error": "…",
  "startedAt": "<ISO time>",
  "finishedAt": "<ISO time>"
}
  • sessionId appears once the runner reports it; it names the session folder (<sessionsDir>/<sessionId>/events.jsonl).
  • status is waiting while pending is set. Only one request is shown at a time; others wait behind it.
  • outcome and finishedAt appear when finished. A creation finishes only when its events.jsonl has session.finished, or when the server ends it: interrupted after a server stop or when the runner ended without closing the flow.
  • cancelling is set between a cancel and the end.
  • awaitingReply is set when the session ended a turn with nothing pending: it waits for a reply the page cannot send. lastMessage is the main session's last text (at most 4000 characters, secrets redacted). It is cleared when a new turn starts, when something is asked, and at the end. The status event of that moment carries runner: { "kind": "status", "status": "turnEnded", "message"? } with the same redacted text.
  • currentStep is the flow step open now (while not finished).
  • usageReading is set until the first plan usage reading arrived or failed.
  • denied lists the requests denied without asking under the unattended policy, for the result screen.
  • code (phase 10): the code the user chose at the spec, { "commands", "checks", "fixPasses", "codex" }; absent for "workspace only".
  • implement (phase 10): the implement step's record, once asked to start: { "state": "running | checking | finishing | done | interrupted | notStarted", "reason"?: "notChosen | wrongFolder | notAProject | commitFailed | usage | usageUnread | snapshotFailed", "usage"?, "workspaceCommit"?, "codeCommit"?, "commitWarning"?, "runs": [{ "command", "exitCode", "timedOut", "output", "durationMs", "at" }], "refused": [{ "command", "at" }], "checks": [{ "pass", "results": [CheckResult] }], "fixPassesUsed", "bounds"?: { "maxMinutes", "maxToolCalls" }, "toolCalls", "limit"?: "time | toolCalls", "warning"?: "checksFailed", "codex": [CodexCall], "codexUnavailable"?, "protectedReverted"?: ["<path>"], "hooksReverted"?: ["<path>"], "revertFailed"?: true, "status"?, "startedAt"?, "finishedAt"? }. hooksReverted: skills, commands and agents changed in the step whose frontmatter declares hooks, put back as the workspace had them (removed when new). Outputs and Codex's messages are cut and redacted; status is the brief's "Current status" as the implementer wrote it (data). The last 50 runs and refusals are kept. revertFailed: protected files or definitions with hooks changed in the step could not be put back, so the code was not committed; the hand-off's briefstack commit of the project is refused then, and while the step runs, checks or commits.

pending.payload per kind:

kind payload
question { "questions": [{ "question", "header", "options": [{ "label", "description" }], "multiSelect" }] } (1–4 questions, AskUserQuestion's shape)
permission { "toolName", "summary", "agentType"? } (summary has any secret-looking line replaced by [redacted])
spec { "specFile", "summaryFile" } (both in the session folder)
grant { "dir" } (an output folder outside projectsDir)

GET /api/creations/:id/spec

The spec the flow last asked the user to approve, for the approval screen: { "summary": "<markdown or null>", "spec": { "name"?, "slug"?, "summary"?, "type"?, "target"?, "targetChosenBy"?, "targetReason"?, "profile"?, "language"? } | null, "librarySkills": [{ "name", "reason", "agent"?, "library"?: { "status", "hasScripts", "network", "license", "description" } }] }. librarySkills are the approved library skills the spec chose (phase 6), with what the library says of each (absent when it has no such skill). code (phase 10): { "offered", "codex", "maxCommands", "maxChecks", "maxFixPasses", "defaultFixPasses" }; offered only for a software spec for claude-code in the web app, codex only when Codex's last check passed with its no-shell part. Both files must be inside the creation's session folder, and lines that look like a secret come back as [redacted]. 404 creation.noSpec before the flow has shown a spec.

POST /api/creations/:id/answer

Body: { "pendingId": "p3", "answer": … }, where answer depends on the pending kind:

kind answer
question { "<question text>": "<option label, labels joined by \", \", or free text>" } with every question of the batch and no other key
permission "allow" or "deny"
spec { "decision": "approve", "removeSkills"?: ["<library skill>", …] }, { "decision": "change", "text": "…" } or { "decision": "cancel" }. With removeSkills the server first takes those library skills out of the spec.json the flow showed (in the session folder) and tells the flow { "decision": "approve", "removedLibrarySkills": […], "note" }; if the file cannot be changed the flow gets a change asking it to remove them
grant true (create it if missing and allow writes there, this session only) or false
  • 200 CreationState (after the answer).
  • 409 creation.noPending when nothing is pending, 409 creation.wrongPending when pendingId is not the one shown (the page is stale: reload the state), 400 creation.invalidAnswer for a wrong shape.
  • Phase 10: a spec approve may carry "code": { "commands": [], "checks": [], "fixPasses": 0–2, "codex": false } for "workspace and a first version of the code". The lists are checked as a build's start checks them, at least one check, Codex only when offered: 400 creation.invalidCode with params { issues, items, codex, notOffered, noChecks, fixed } (items as build.invalidStart's). The flow is then told { "decision": "approve", "code": true, … } and the choice is recorded (code above, and code.json in the session folder); "workspace only" tells the flow exactly what it was told before phase 10. Once the implement step started, a new code answer is refused (fixed).

POST /api/creations/:id/cancel

No body. Cancels through the flow, never by killing a write: a pending question or spec is answered "cancel" (a permission "deny", a grant "no"), the runner is asked to close at its next step, and the flow closes the open step as skipped and the session as cancelled. If it has not done so within 60 s, the server stops the runner and writes those two events itself. 200 CreationState (with cancelling: true). Cancelling a finished creation changes nothing.

POST /api/creations/:id/reply

Body { "text": "<1–10000 characters, trimmed>" }. The free-text reply (BRIEF-phase-4 §3.3): only while the creation has awaitingReply (the session ended a turn with nothing asked in the browser) and is neither cancelling nor asking something; otherwise 409 creation.noReply. The text is sent to the session as a user message, through the same input queue as the first one, and is not stored by briefstack. 200 CreationState (without awaitingReply).

GET /api/creations/:id/stream?from=<seq>

A text/event-stream of the creation's events. It first replays every event with seq > from (default 0; the Last-Event-ID header works too), then sends new ones live, and ends after the event that finishes the creation. A comment line : heartbeat is sent every 15 s. Closing the tab does not affect the creation: reconnect with the last seq seen.

The UI reads it with fetch and a ReadableStream (not EventSource), so it can send the token header.

Each event:

id: 12
event: flow
data: {"seq":12,"ts":"<ISO time>","kind":"flow","data":{…}}

kind data
flow an events.jsonl line from the flow: step.started/step.finished (step, outcome) or session.started/session.finished (outcome)
hook an events.jsonl line from the hooks: subagent.start/subagent.stop (agentId, agentType, model?, effort?), tool.pre/tool.post/tool.failure (tool, toolUseId?, target?, effort?), session.end (reason). Projected and with id, as in GET /api/sessions/:id/events
runner a line the server wrote to events.jsonl itself: tool.denied, session.profile, usage (docs/events.md). Projected and with id
question, permission, spec, grant { "pendingId", "state": "pending", "payload" } when shown, { "pendingId", "state": "answered", "answer" } when answered (by the user or by a cancel)
status { "status", "outcome"?, "sessionId"?, "cancelling"?, "runner"? }: a status change, or progress the runner reports itself in runner. Once per creation the real runner reports runner: { "kind": "effort", "level", "requested"? }: the effort Claude Code applied (from the first PreToolUse hook input) and the one the profile asked for
denied { "toolName", "summary", "agentType"?, "at", "by": "policy" | "runner", "reason"? }

seq starts at 1 and has no gaps within a creation. The flow, hook and runner lines are the lines events.jsonl holds (docs/events.md), projected as in GET /api/sessions/:id/events, so the agent panel reads either with the same buildPanelState.

Chat routes

The global chat (BRIEF-phase-4 §3.1). Without a chat every route answers 503 chat.unavailable. Reads need the token; writes the token and the same-origin check, like every mutating route.

GET /api/chat

200 { thread, messages, status: "idle" | "thinking", pending?, model?, seq }: the active thread ({ id, title, createdAt, updatedAt }), its messages, the confirmation waiting for the user (at most one), the chat's model and effort from the usage profile, and the stream seq to continue from.

A message: { id, ts, role: "user" | "assistant" | "tool" | "confirmation" | "notice", text?, tool?, confirmation?, notice?, detail? }. tool is { name, summary, sources: [{ kind, ref, label? }], error? } (what was asked and where the data came from, never the data itself). confirmation is { id, tool, card, state: "pending" | "confirmed" | "declined" | "failed" | "expired" | "stale", result?, sources? }. stale means the user confirmed but what the card showed no longer held (the note changed in between), so nothing was done. A card not answered within 59 minutes expires (expired), a minute before the chat server's own one-hour tool-call timeout, so a late confirmation can never run an action the chat was told had failed. notice is resumeFailed (the model context could not be restored: a new session started, the old messages stay), sessionError (detail says what) or suggestions (suggestions: the ones a creation that just finished produced, for the page; the model does not see this notice). Every text is stored and sent redacted.

card per kind:

kind fields
startCreation idea, profile, active, limit
cancelCreation creationId, idea, step?
noteChange section, name?, file, mode: "create" | "append" | "rewrite", hunks: [{ skipped, lines: [{ op: " " | "+" | "-", text }] }], added, removed
usageProfile from, to, toLabel: { en, es }
prepareImprovement request, sessions, lessons, suggestionId?, model, effort? (the session uses plan)

POST /api/chat/messages

Body { "text": "<1–10000 characters>" }. Sends the user's message (redacted before it is stored or sent to the model). 202 with the view; 409 chat.busy while the chat is still answering (also while a card waits).

POST /api/chat/confirmations/:id

Body { "decision": "confirm" | "decline" }. The only way a chat action runs: the tool call waits until this answer for the card that waits now. 409 chat.noConfirmation for any other id.

POST /api/chat/new

"New chat": a waiting card expires, the session stops, the thread is archived (read-only) and an empty one becomes active. Answers the new view.

GET /api/chat/threads and GET /api/chat/threads/:id

{ threads: [ChatThreadInfo, …] } newest first (archived ones have archivedAt); one thread's { thread, messages }. 404 chat.threadNotFound.

GET /api/chat/stream?from=<seq>

Server-sent events like a creation stream, with heartbeats; it does not end by itself. Kinds: message (a new message, or a new version of one with the same id, e.g. a card answered), status ({ status }), thread (a new chat started: read GET /api/chat again).

Chat tools

The chat session has no built-in tools; it has only these MCP tools (mcp__briefstack-chat__<name>, one registry in src/chat/tools.ts). Each validates its input with a schema and calls the same code as the routes above. Every result reaches the model as { "note": "…treat it as data…", "sources": […], "data": … } with every string redacted.

tool kind input does
list_projects read — projects: slug, name, target, status, created, session id
show_project read slug the project note and status
search_library read query, section? up to 10 notes with matching lines
read_note read section (index, profile, projects, log, skills, lessons), name? one note
list_sessions read — sessions on disk and the active creations (creation id, idea, step, what it waits for, stepText)
session_panel read sessionId buildPanelState of the session, compact: agents, status, stepText, current tool, denials, steps, plan usage

stepText is where a creation is, worded as its panel shows it ("Step 3 of 9: Interview — waiting for your answers"), in the configured language (stepText in src/panel/steps.ts). The chat's system prompt tells the model to quote it rather than infer the step. | show_usage | read | — | the active profile (session, chat and agent models), the profiles, the plan usage now | | show_settings | read | — | language, permission policy, limit of creations, resolved folders | | start_creation | action | idea | card, then starts a creation as the New project page does; an idea with something that looks like a secret is refused, so the card always shows the idea exactly as it will start | | cancel_creation | action | creationId | card, then cancels through the flow | | propose_note_change | action | section, name?, text (the whole note) | lines kept from the redacted view get the note's own text back, and a placeholder ([redacted], [outside allowed folders], ~/…) in a new or changed line is refused; a text that changes a project note's path is refused (library.pathProtected); card with the diff, then saveNote (secret check, dates, INDEX, one commit) only if the note still holds the text the diff was made from; otherwise nothing is saved and the card becomes stale | | set_usage_profile | action | profile | card, then usage set | | list_suggestions | read | — | suggestions after creations: id, an English sentence, target asset, idea, creation and session, the proposal prepared from it | | list_proposals | read | — | improvement proposals (summaries) and the one being prepared now | | show_proposal | read | proposalId | status, request, diff hunks and rationale per file, validator problems, safety notice, check results, rounds, what blocks applying | | prepare_improvement | action | request, sessions? (up to 5), lessons?, suggestionId? | card, then starts an improvement session (one at a time; a request with a secret is refused). Approving, asking for changes, discarding and reverting are not chat tools: they happen on the proposal page | | list_skills | read | status? | the library's third-party skills: name, the author's description (data), status, tags, source, scripts, network, license, high findings, model review, whether a new version waits | | add_skill | action | url, tags? | card with the link, repo, folder and ref (an invalid link is refused before any card), then fetches the skill into quarantine with its review. Approving, rejecting and deleting are not chat tools: they happen on the skill's page | | add_skill_to_project | action | skill, project (slug) | only an approved skill, only a project with a library note, not twice; never a protected folder or one inside .git (refused before any card). Card with where it goes (location), the project folder, outsideProjects (outside the projects folder: confirming grants that folder for this install only), its license and a scripts note; then the skill joins the project's spec.json librarySkills (the user's choice), the same install as skills install --skill, and one dated line in the project note. If the note points to another folder by then, nothing is installed (stale) |

start_creation and prepare_improvement cards carry usage ({ fiveHour, sevenDay, warnFiveHour, warnWeek }) when the plan usage is at or above a threshold: confirming the card is "start anyway".

An action is refused without a card when another card waits, after 10 cards in 10 minutes, when the text holds a secret, when nothing would change, or when the limit of creations is reached. Not available from the chat: reverting library commits, the projects folder, the permission policy, answering a creation's questions or approving its spec, approving, discarding or reverting an improvement, approving, rejecting or deleting a skill.

Improvement routes

Self-improvement of the creation flow (BRIEF-phase-5). Without an improvement manager every route answers 503 improve.unavailable. Reads need the token; writes the token and the same-origin check. Approve, discard, revert and the real check exist only here, for the proposal page: the chat can prepare an improvement but never apply one.

GET /api/improve

200 { active?, proposals, suggestions, blockers }: the id of the proposal whose session is running, every proposal newest first ({ id, status, title?, request, createdAt, updatedAt, files, appliedCommit?, revertCommit? }), the suggestions after creations, and what blocks applying now (running creations: their ideas, or session <id> for one on disk this server does not run).

A suggestion (BRIEF-phase-5 §3.5; at most three per finished creation, computed without a model, newest first, at most 60 kept): { id, kind, creationId, sessionId?, idea, createdAt, target, params, proposalId? }. kind is failure (params.outcome, steps), textQuestions (count turns that ended waiting for a text answer), denials (count, tools), reviewRounds (count, from 2 up) or lessons (count, the first lines); target is the asset most likely to need the change; proposalId is set once an improvement was prepared from it. A suggestion changes nothing by itself.

Statuses: preparing (the session runs), verifying (the server commits, validates and tests), ready, rejected (a validator failed), failed (the session, the tests or git failed), waiting (approved, waits for no creation running), applied, revertWaiting, reverted, discarded.

GET /api/improve/proposals/:id

200 { proposal, blockers, check? }. proposal has everything but the worktree path: request, title, expectedEffect, evidence ([{ kind, ref, file }]), baseBranch, baseCommit, branch, rounds ([{ n, feedback?, startedAt, endedAt?, outcome?, commit?, denials, text?, error? }]), files ([{ path, kind, status, base?, proposed?, hunks, added, removed, rationale?, evidence? }], diff hunks as in a note-change card), validation ({ ok, problems: [{ kind, file?, line?, detail }] }), checks ({ ok, steps: [{ name: "build" | "lint" | "test", ok, ms, tail }], error? }), head? (the commit of the last checked round; an approval sends it back), safety? ({ state: "flagged" | "clear" | "unavailable", reason, model, at }: a cheap model's reading of the diff, after the validators pass; never blocks), realCheck?, offeredCheck?, appliedCommit?, revertCommit?, error?. check is the offered real check: { name, script, cost: { en, es } }. 404 improve.notFound.

Problem kinds: forbiddenPath (also a file git ignores left in the worktree), notModified (added, deleted or renamed), mode (file mode changed, such as the executable bit), notText, frontmatter, locked, secret, personalPath (also ~/ paths), personalData (an e-mail outside example domains, the git user's name or e-mail, a project name), profileText, lessonText (eight words in a row from the lessons), noChanges, unexplained (no rationale for a changed file). Problems in the title or the expected effect have no file and a detail that starts with "in the title" or "in the expected effect".

POST /api/improve/proposals

Body { "request": "<1–10000>", "sessions"?: [id, …] (at most 5), "lessons"?: boolean, "suggestionId"? }. Starts an improvement session (one at a time): 202 { proposal }; 409 improve.busy while one runs, 409 improve.noRepo when the repo is not on a branch or the home is inside it, 404 improve.suggestionNotFound (also for a discarded suggestion). "force": true in the body skips the plan-usage warning (409 usage.high, as for POST /api/creations).

POST /api/improve/suggestions/:id/discard

Discards a suggestion for good (dismissedAt in <home>/improve/suggestions.json): it is no longer listed here, in the chat or on a result screen, and cannot be prepared. 200 { suggestions }; 404 improve.suggestionNotFound (unknown or already discarded).

POST /api/improve/proposals/:id/changes

Body { "text": "<1–10000>" }. "Ask for changes": a new round on the same branch, from ready, rejected or failed. 202 { proposal }. If the base branch moved, the worktree first moves to its tip, which becomes baseCommit; changes that no longer merge are dropped and the session is told which.

POST /api/improve/proposals/:id/approve

Body { "head": "<commit>" }: the head of the proposal the page showed. From ready with validators and checks passed. Applies the change as one commit on the base branch now, or answers with status waiting while a creation runs (it applies as soon as none does; creation starts wait while it is applied). 409 improve.staleReview when another round was checked since. Refusals leave it ready with error set: 409 improve.notOnBranch, improve.uncommitted, improve.baseChanged (the branch changed a proposed file since the base: ask for changes), improve.moved.

POST /api/improve/proposals/:id/revert

From applied: one revert commit now, or revertWaiting while a creation runs. Same refusals.

POST /api/improve/proposals/:id/discard

From preparing (the session is stopped), ready, rejected, failed or waiting: removes the worktree and the branch.

POST /api/improve/proposals/:id/check

From ready, when the proposal offers a real check: starts it (202); the result is added to the proposal as realCheck. 409 improve.noCheck, 409 improve.checkBusy.

Skill routes

Third-party skills of the library (BRIEF-phase-6). Without a skill service every route answers 503 skills.unavailable. Reads need the token; writes the token and the same-origin check. Each change is one library commit of skills/<name>/ (the metadata note skills/<name>/<name>.md, the files under files/, a new version under next/). Approving, rejecting and deleting exist only here, for the Skills page.

A detail is { "record": SkillRecord, "diff"?: [FileDiff] }. SkillRecord is the metadata note's frontmatter: name, description, status (quarantine | approved | rejected), tags, statusChanged, source { url, repo, path, ref, commit, link }, fetched, license { spdx, source, file? }, hasScripts, network, allowedTools?, files [{ path, size, kind, sha256, executable }], findings [{ rule, severity, file, line?, excerpt? }], model { state: flagged | clear | failed | unavailable, reason, model, at, cut? } (failed: the review ran but its reply was not exactly the answer's JSON, or it broke; unavailable: no model review in this server; cut: files the model saw only in part or not at all, shown as "Partial review"), and next? (the same version fields for a new version in quarantine). FileDiff is { path, change: added | removed | changed, hunks?, binary? } of next against the current files. A change answers { "detail"?, "committed", "warnings" }.

GET /api/skills

200 { skills: [{ name, description, status, tags, repo, path, commit, link, hasScripts, network, license, high, model, update, statusChanged }] }, by name. Notes that do not read back are left out.

GET /api/skills/:name and GET /api/skills/:name/file?path=<p>&version=current|next

The detail; one file of a version as { path, kind, size, text? } (no text for a binary or a file over 512 KB). 404 skills.notFound, 404 skills.fileNotFound (only recorded paths are served), 409 skills.unreadable.

POST /api/skills

Body { "url": "<github link>", "tags"?: [...] }. Fetches the folder from the two GitHub hosts at the commit the ref points to (limits: 200 files, 1 MB each, 5 MB in all; no symlinks, submodules, LFS pointers, .gitattributes or .gitmodules; portable names, without bidirectional or zero-width characters; only 40-hex object ids in a listing; every blob hash checked), reviews it (static rules, license, the model review on every text file) and stores it in quarantine. 201 { detail, committed, warnings }. 400 skills.invalidUrl (params.reason: notHttps, notGithub, shape, notSkillFile), 404 skills.repoNotFound, skills.refNotFound, skills.pathNotFound, 400 skills.noSkillFile, skills.tooLarge, skills.forbiddenEntry, skills.integrity, 422 skills.pathTooLong (a file would land on a path over 250 characters in the library; nothing is written), skills.invalidName, skills.invalidTag, 409 skills.exists (params.sameSource), 429 skills.rateLimited (params.reset), 502 skills.network.

POST /api/skills/:name/approve, /reject, /delete

Approve (from quarantine or rejected; only while the files on disk still match the recorded hashes, else 409 skills.modified), reject (from quarantine or approved), delete (any status). 409 skills.wrongStatus.

PUT /api/skills/:name/tags

Body { "tags": [...] }: lower-case letters, digits and hyphens, at most 30 characters each and 10 in all (400 skills.invalidTag).

POST /api/skills/:name/check-update

Only for an approved skill: fetches the latest commit of the ref it was added from into next/, reviewed like a new skill. { ..., "outcome": "updated" | "upToDate" | "pinned" } (pinned: added at a commit). 409 skills.updatePending while one waits. Never automatic.

POST /api/skills/:name/update/approve and /update/reject

The new version replaces the approved one (checked against its hashes), or is dropped. 409 skills.noUpdate when none waits.

Task routes (phase 7)

Tasks in existing claude-code projects (BRIEF-phase-7). Without a task manager every route answers 503 task.unavailable. Approve, ask for changes, discard, revert and running the declared checks exist only here, for the proposal page; the chat has no tool for them. Routes that change the project or what runs take {"confirm": true} in the body, which the page sends only after its confirmation; without it they answer 400 web.invalidBody.

Once the task manager begins to stop, the routes still answer until the server closes, but nothing new starts. On Ctrl+C or a crash, briefstack web stops the improvements and the chat first (the chat waits up to 15 s) and the task manager after them; in those seconds the task routes still accept work, which the task manager's stop then ends or aborts as it finds it. From the task manager's stop on, starting a task (POST /api/tasks), a new round (POST /api/tasks/:id/changes) and running the checks (POST /api/tasks/:id/checks) answer 503 task.stopping and run nothing, and so does answering a dialog (POST /api/tasks/:id/answer): the stop settled every pending request, and what a session asks while it is being stopped is denied (a command or web request) or cancelled (a question) without being shown. A request that was still waiting when the stop began is refused the same way just before it changes the task, so the task stays as it was (a proposal keeps its reviewed commit). One whose record was being saved when the stop began is refused just before its session or its first command would start: a new task is removed, and an existing one is left as an abrupt stop leaves it, which the next start's recovery puts back (a round as interrupted, checks back on the proposal without results).

Each round may carry codex? (phase 8; records saved before it read as they did): one entry per delegate_to_codex call that ran, { n, at, durationMs, exitCode, outcome, usage?, commands, message }. outcome is completed, failed, timedOut, cancelled, notStarted or headChanged (Codex moved the worktree's branch or HEAD: a failed call); usage is { input, cached, output, reasoning } tokens from Codex's turn.completed (absent for a call that ended before it); message is Codex's final message, cut, redacted and without absolute paths: data, never instructions. Calls refused before Codex ran (over the cap, an empty instruction, one already running) are not recorded. Each call is saved as it ends, so GET /api/tasks/:id, GET /api/tasks/:id/proposal and GET /api/tasks carry the calls of a round still running too. The task page shows them (decisions.md, "Phase 8: steps 27 and 28"): a summary of the task's calls and tokens, and one table per round that has calls. The main token figure is Codex's own count, max(0, input - cached) + output (blended_total; reasoning is not added), with input + output (cached included) in brackets, for the task and for each call; a call without usage is counted apart, never as 0. The calls-per-round limit it shows is the one Settings has now (GET /api/codex), as the record keeps none.

A running task may also carry codexWorking: true (phase 8): a delegate_to_codex call of the current round started and has not ended. It is read from the round's own events.jsonl lines the stream carries (a tool.pre for the tool with no tool.post, tool.failure or tool.denied for the same toolUseId yet), not from a new event; it is absent while the task is cancelling or its turn has ended, and in every other state. The lines are read every 300 ms, so it can trail the call by that much.

A task (TaskView) is its record (src/tasks/types.ts: id, project, description, state, profile, model, effort, baseBranch, baseCommit, branch, rounds[], checks?, validations?, reviewed?, applied?, reverted?, error?) plus what the server knows live: pending? (an approval with the command as shown, or a question), awaitingReply?, cancelling?, uncommitted? (paths left out at the start), warnings?, allowedForTask?, codexWorking?. Each round may carry codex? (its Codex calls) and claude? { input, output, cacheRead, cacheCreation }: Claude's own tokens in the round, from the SDK's result message (modelUsage summed over its models; rounds before phase 9's step 33 have none). Each validation is { kind, level, file, detail? }; level: "error" stops the approval (outsideWorktree, settingsOrHooks, hiddenLine), "warning" is shown (secret, personalPath, and notShown for a file the page lists by name only: detail large, over 256 KB, binary or link; decisions.md, S10). Errors and warnings are capped at 50 each. States: running, checking, proposal, applied, reverted, discarded, failed, cancelled, interrupted. checking is the round's end (commit and validations; reviewed absent) or the declared checks the user asked for (reviewed set). checks absent means the declared checks have not run: they run only from POST /api/tasks/:id/checks, never by themselves (decisions.md, S8). A server stopped while they run leaves the task on proposal without checks at its next start.

Route Body Answer
GET /api/tasks { tasks }, newest first
POST /api/tasks { project, description, force? } 201 { id }; the preconditions refuse with 409 task.*; 409 usage.high without force when plan usage is high
GET /api/tasks/:id the task
GET /api/tasks/:id/stream SSE, as a creation's: flow, hook, runner (the round's events.jsonl lines, projected), status, approval, question, denied; each item has seq, ts, round
POST /api/tasks/:id/answer { pendingId, answer } an approval takes "once", "task" (this exact command for the rest of the task) or "deny"; one whose payload is redacted takes only "deny" (400 creation.invalidAnswer); a question takes { "<question>": "<label>" } or "cancel"
POST /api/tasks/:id/reply { text } the free-text reply after a turn that ended with nothing asked
POST /api/tasks/:id/finish ends the round: commit on the task branch, validations, then proposal; no declared check runs
POST /api/tasks/:id/cancel the existing cancel; a Codex call running then ends with its process tree and is recorded as cancelled
GET /api/tasks/:id/proposal { task, diff, checkCommands? }: each changed file with hunks (secret values masked as [secret]), from the base to task.reviewed (the commit the server checked, which the checks run on), or the applied commit's once applied; checkCommands, for a proposal (or one whose checks run), the project's confirmed checks, which the page's confirmation names
POST /api/tasks/:id/checks { commands, confirm: true } 202 and the task, checking: the project's confirmed checks run in the worktree on task.reviewed, then the task is proposal again with checks (which replace earlier ones). commands is the list the page's confirmation showed (checkCommands): when the confirmed checks are no longer exactly that list (order included), 409 task.checksChanged, nothing runs and the task stays on proposal; the page then loads the list again and shows its confirmation again. Without commands, 400 web.invalidBody. Only from proposal: 409 task.wrongState; 409 task.noChecks without confirmed checks; 409 task.limit at the shared limit. A worktree that is no longer the task's or a branch moved off reviewed, before or after they run, fails the task (task.worktreeChanged, task.branchChanged)
POST /api/tasks/:id/checks/cancel { confirm: true } cancels the running checks only, after the page's confirmation: the running command's process tree is ended (as a server stop ends it) and no other check starts; no result is kept, partial or not, what they left in the worktree is removed, and the task is proposal again without checks, as after a restart (or failed when its worktree or branch changed, as then). 200 and the task; 409 task.checksNotRunning when no checks run (a running round is cancelled with POST /api/tasks/:id/cancel); checks that ended before the cancel reached them keep their results; 503 task.stopping once a server stop began (it ends them itself). The chat has no tool for it
POST /api/tasks/:id/approve { confirm: true } one commit on the default branch with the tree of task.reviewed, no push; 409 task.dirtyFolder, task.notOnBranch, task.conflict, task.blocked, task.projectBusy, task.mergeDrivers, task.branchChanged
POST /api/tasks/:id/changes { text } a new round on the same branch and worktree; 409 task.unsafeChanges when the copy now holds a settings file or a definition a task cannot load, task.worktreeChanged when its .git no longer points at the task
POST /api/tasks/:id/discard { confirm: true } the branch and the worktree are deleted
POST /api/tasks/:id/revert { confirm: true } one revert commit, under the approval's rules
GET /api/projects/:slug/tasks { tasks, checks, start }: the project's tasks, its declared checks ({ command, confirmed }), and whether a task can start ({ ok: true, branch, uncommitted } or { ok: false, code, params, message }; the page shows its own text for code and params, never message)
PUT /api/projects/:slug/checks { commands, confirm: true } the note's checks block rewritten through the library queue, each command recorded as confirmed; 400 task.invalidCheck
POST /api/projects/:slug/git-init { confirm: true } for a folder in no git repository: git init and one commit of its files; 409 task.alreadyRepo, task.insideOtherRepo

Codex routes (phase 8)

Codex in Settings (decisions.md, "Phase 8: step 25"). The switch, the mode and the calls per round are saved with PUT /api/settings. Without a Codex service both routes answer 503 codex.unavailable.

GET /api/codex

Runs nothing: the settings and the last status check. { "enabled", "mode", "maxCalls", "modeOffered", "last"?, "available", "reason"? }. modeOffered is true only on Windows (the mode is not verified elsewhere). last, once checked: { "at", "platform", "mode"?, "found", "version", "login", "sandbox", "ok" }, each of the three { "ok", "text" } (text cut to 300 characters, secrets and absolute paths hidden). available says whether a task round starting now gets delegate_to_codex; when not, reason is off, notChecked (never checked, or checked on another system), checkFailed or modeChanged (Windows: the mode saved now is not the one checked). A round also looks for Codex again; not found, the round has no tool.

POST /api/codex/check

Runs the status check, one at a time, and keeps it in <home>/codex/status.json; answers as GET /api/codex. Three commands, none of which uses the plan, without a shell, with Codex's cleaned environment, in <home>/codex/check/: codex --version, codex login status (its exit code and stderr; auth.json is never read) and codex sandbox [-c windows.sandbox="<mode>"] -P :workspace -- whoami (the mode on Windows only). It passes when all three end with exit code 0. Codex not on the PATH is found: false.

Phase 10: a fourth command, codex debug prompt-input with the no-shell features (--disable shell_tool, multi_agent, plugins, apps, hooks, browser_use, computer_use, -c web_search="disabled"), also without the model, gives last.noShell: { "ok", "text" }: it passes when the rendered tools are in the format briefstack reads (apply_patch as a heading) and declare no tool that runs commands. It is not part of ok (tasks use Codex with its shell); a creation offers the Codex checkbox only when available and noShell.ok, and uses Codex only when codex --version still answers the version checked.

Builds (phase 9)

Builds in claude-code projects (BRIEF-phase-9; PLAN-phase-9 §1; decisions.md, "Phase 9"). Only the pages use these routes: the chat has no tool to plan, start, apply or discard a build. Without a build manager every route answers 503 build.unavailable. A build is an ordinary task for each queued item (build: { id, n } in the task record), run unattended on the integration branch briefstack/build-<id>.

A build record (GET /api/builds/:id): { v, id, project, projectDir, state, profile, model, effort, createdAt, updatedAt, branch, baseBranch?, baseCommit?, plan?, tasks, settings?, roundsRun, pause?, startedAt?, finishedAt?, applied?, reverted?, error? }. state is planning, planned, planFailed, running, paused, interrupted, cancelled, finished, applied, reverted or discarded. plan is the planner's proposal { tasks, commands, checks } (since phase 11 each proposed task also has area and size; plans stored before have none); tasks the queue the user started, each { n, title, instruction, doneWhen, dependsOn, area?, size?, state, taskId?, reason?, skippedFor?, detail?, commit?, denied?, deniedOmitted?, rounds, redo?, join?, task? } (phase 11: a card of the board; area the relative paths it is expected to change, absent in builds started before phase 11 and then the whole project; size S, M or L; redo { reason: conflict | checksFailed, previousTask } when it was redone once; join { outcome: applied | conflict | checksFailed, merged, files?, checks? } its last join, merged when it was joined onto other cards' changes, then checked again there with the build's checks, checks their results; none when the build has no checks) (denied keeps at most 50 entries, from every round; deniedOmitted counts the rest; a task is applied after a round with no blocking validation, every check passing and no command denied in that round, so an applied task may still list denials of an earlier round), with state queued, running, applied, waiting, skipped or cancelled; reason (waiting) checksFailed, denied, blocked, roundFailed, interrupted, notStarted, notApplied, roundsCap, conflict or joinChecksFailed (phase 11: its join collided or failed the checks, and it could not be redone: already redone, or the cap of rounds); task (only on GET /api/builds/:id) the task's own { state, checks?, codexCalls, codexTokens, claudeTokens? }, where claudeTokens { noCache, withCache, rounds } sums Claude's tokens over the task's rounds that have a reading: noCache is input plus output (the page's main figure), withCache adds the prompt cache's reads and writes (in brackets on the page). settings is what the start recorded { limit, commands, checks, fixRounds, maxRounds, thresholds, slots? } (slots how many cards run at once, phase 11; absent is one); pause { reason: usage | usageUnread | user, at, until?, fiveHour?, sevenDay? }. The live view adds pausing, cancelling and waitingSlot (the shared limit is full) when true. detail and error are redacted and without absolute paths. With roundFailed, detail is the round's reason (phase 12, step 42), the same text as the task's error and its round's error: the SDK's message, the exit code, whether Claude Code started the session (its init message), its last error result and up to 20 last lines of Claude Code's stderr, without a reserve provider's key. A round whose every turn ended in an error result is failed with that reason.

A build holds its project (no ordinary task, no other build) in every state but applied, reverted and discarded. While the build's loop drives one of its tasks, the task routes that act on it (approve, discard, changes, checks, answer, reply, finish) answer 409 task.heldByBuild; cancel does not. After a restart, a build left running or paused is interrupted (its running cards waiting, interrupted) and one left planning is planFailed; nothing resumes by itself, unless buildsAutoResume is on (phase 12): the record then keeps what the restart interrupted (restart: { from: "running" | "paused", pause? }; another restart drops an older mark), and once the server listens a build that was running resumes (the usage read first; its interrupted cards started again at the integration head whatever its slots), one paused for usage is paused again with its timer (or resumes when its time passed), and one the user paused, or asked to pause while cards were at work, stays interrupted. A build that cannot resume stays interrupted with its error. autoResumes counts the restarts that cut work short in a row, reset when a card is applied or left waiting and by the user's resume; at 3 the build stays interrupted with autoResumeStopped: true. A round a server stop cut short is not counted in roundsRun (phase 12). Each pass also starts no more cards than buildSlotsCap (Settings), whatever the build's slots. Resuming a build with more than one slot starts again, at the integration head, the cards whose task the stop left interrupted (their tasks discarded); with one slot they wait for the user, as in phase 9.

Cards in parallel (phase 11). Each pass of the loop starts, after one plan-usage reading, the first queued cards in the board's order whose dependencies are applied and whose area overlaps no running card's, while fewer than slots run; a full shared limit makes a card wait for a place. Each card runs in its own task and worktree. When its rounds pass the rules it is joined, one join at a time: on the head it started at, as phase 9 applied a task; onto a head that moved, with merge-tree from the card's start, the build's checks run again on the joined commit in a temporary worktree, and the branch moves onto that commit with a compare and swap. A textual conflict, or checks failing on the joined commit, redo the card once at the integration head; a second failure leaves it waiting. Over the usage threshold no card starts, the running ones finish, and the build pauses; the user's pause does the same; cancel ends every running card's round or checks.

GET /api/projects/:slug/builds

{ builds, plan, thresholds, slotsCap }: the project's builds, whether one can be planned now ({ ok: true } or { ok: false, code, params, message }, for example build.noBrief or build.projectBusy), the default usage thresholds from Settings, and the machine's cap on slots (phase 12, 1 to 4).

POST /api/projects/:slug/builds

Body { "force"?: true }. Checks the project as a task's start does (no open task or build, the shared limit, a clean claude-code project on its branch) and that docs/BRIEF.md exists at the default branch's head, then starts the planner session in the background and answers 201 { id } with the build planning. High plan usage answers 409 usage.high unless force. The planner has no tools but the one Claude Code adds to return structured output; the brief, CLAUDE.md and the package.json scripts are in its prompt as data.

GET /api/builds/:id

The build, as above (404 build.notFound).

POST /api/builds/:id/start

Body { tasks, limit, commands, checks, fixRounds, thresholds: { fiveHour, week }, confirm: true, noChecks?, slots?, reserve? } (reserve: a reserve provider's name, phase 12; it must be in config.json, else 400 build.reserveUnknown; absent, the build pauses at the threshold; the page sends confirm after its dialog, which names the commands; without it 400 web.invalidBody). Only a planned build (409 build.wrongState). Every rule is checked and each problem named in 400 build.invalidStart { issues, items }: 1 to 20 tasks, each depending only on earlier ones, each area (when given) 1 to 10 relative paths with / (no absolute path, drive, .., backslash, wildcard or hidden character) and size (when given) S, M or L; slots (when given) 1 to 4; limit from 1 to the queue's length; commands and checks exact, one per line, plain characters only, no chain, wildcard or secret; fixRounds 0 to 2; thresholds 1 to 100; with no checks, noChecks: true (the user confirmed that every task whose round ends with no denied command is then applied; phase 9 step 33). issues are English texts; items the same problems as codes the page translates ({ key, n?, max?, line?, what?, problem?, name?, fields? }, key one of emptyQueue, tooManyTasks, taskInvalid, laterDependency, areaInvalid (with problem empty, long, absolute, parent, chars or count), sizeInvalid, limit, listTooLong, listLine, listDuplicate, fixRounds, slots, threshold, noChecks; src/builds/commands.ts). Then the integration branch is made at the default branch's head (409 build.branchExists when a branch of that name is already there) and the loop starts; nothing of the start changes afterwards.

POST /api/builds/:id/pause, /resume, /cancel

Cancel takes { "confirm": true } (without it 400 web.invalidBody). Pause: a running build pauses before its next task (pausing: true until then); a build paused for usage becomes paused by the user and no longer resumes by itself. Resume: a paused, interrupted or finished build; a waiting task the user approved since is taken as applied, skipped tasks and waiting tasks with no task of their own are queued again, and the next task starts without reading the plan usage. Cancel: a running build ends the round or checks at work (process tree included) and becomes cancelled once its loop stopped; a paused or interrupted build is cancelled at once. The integration branch stays. A cancel asked is kept in a file of the build's own (<home>/builds/<id>/cancel-asked, not in the record) until the loop records it: a server stop meanwhile leaves the build cancelled after the restart, not interrupted (phase 9 step 33). Otherwise 409 build.wrongState.

Moving or deleting the integration branch (a task applied to it, a discard) is refused with 409 build.branchCheckedOut { branch } while any worktree of the project's repository, the project folder included, has it checked out (phase 9 step 33).

GET /api/builds/:id/diff

{ diff, head? }: the whole change on the integration branch since the start, as a task's proposal diff ({ files, more }), and head, the integration commit it shows (the page sends it back to apply); or the applied commit's change once applied (also once an applied build is discarded); diff: null before the start, or once a build that was never applied is discarded.

POST /api/builds/:id/apply

Body { "confirm": true, "head": "<sha>" } (without them 400 web.invalidBody). head must be the integration head the page showed, and every commit on the branch since the start must be one briefstack made for an applied task, otherwise 409 build.branchMoved (the branch moved since the page read it, or holds a commit briefstack did not make); that head is what lands. A head still at the start is 409 build.nothingToApply. A waiting task the user approved since, or a task the build cancelled after its round and the user approved since, counts as applied. A paused, interrupted, cancelled or finished build with no task at work (409 build.taskRunning) and none waiting for the user (409 build.openTasks { tasks }: approve each onto the build's branch, or discard it, first). One commit on the default branch with the integration branch's whole change, with a task's refusals (task.dirtyFolder, task.notOnBranch, task.conflict, task.mergeDrivers, task.projectBusy, ...); 409 build.alreadyOnBranch { branch } when the whole change is already on the default branch (phase 9 step 33; it was build.nothingToApply). Tasks the build cancelled are discarded with it. A line goes in the project's library note. Nothing is pushed.

POST /api/builds/:id/revert

Body { "confirm": true }. An applied build, or a discarded one that was applied and not reverted (it stays discarded): one commit that undoes the build's commit, with the same refusals.

POST /api/builds/:id/discard

Body { "confirm": true }. A planned or planFailed build, or a started one that is paused, interrupted, cancelled or finished with no task at work: every open task of the build is discarded (its worktree and branch), the integration branch is deleted, and the build becomes discarded. Nothing reaches the project. An applied or reverted build loses only its integration branch (the user's decision, phase 9 step 33): its commits on the default branch and its record stay, and it becomes discarded. The integration branch otherwise stays after an apply or a revert. Refused, with nothing discarded, (409 build.branchCheckedOut) when the project folder or another worktree has the integration branch checked out.

Reserve providers (phase 12)

Configured in config.json, reserveProviders (server.md, §7); these routes only read them. No answer ever holds a key: briefstack holds none, only the path of the file it reads when a round on that provider starts.

At the usage threshold, a build started with reserve goes on with that provider while the plan is over a threshold (each card keeps the provider it started on for all its rounds); otherwise it pauses as before. A provider that is gone from config.json, or whose key file cannot be read as one line, pauses the build with pause.reserveMissing. Each card of a build carries provider (absent: Claude), and each round of its task provider; the round's claude tokens are then that provider's.

GET /api/providers

{ "providers": [{ "name", "baseUrl", "model", "smallModel"?, "keyFile", "note"?, "check"? }] } (check: the last status check while this server runs).

POST /api/providers/:name/check

The status check, which reads no key: { "name", "keyFile": "present" | "missing" | "empty" | "tooLarge", "endpoint": "reachable" | "unreachable", "status"?, "key": "notChecked", "checkedAt" }. keyFile comes from the file's size; endpoint from a GET to baseUrl sent with no credential (any HTTP answer is reachable; status is its code). 404 provider.notFound for a name config.json does not have.

CLI: skills install

briefstack skills install <project-dir> [--skill <name>] [--json]. Without --skill, the library skills of the project's .briefstack/spec.json (librarySkills) not installed yet; with it, one of them only (skills.notInSpec for a skill the spec does not choose). Only approved skills whose library files match their hashes; never over an existing file; never through a link that leads out of the project; never a path over 250 characters (skills.pathTooLong, checked before copying). claude-code: .claude/skills/<name>/ byte for byte; claude-app: skills/<name>.zip (the skill folder at the archive's root) and a line under "Skills" in NEXT_STEPS.md. Each install is recorded in .briefstack/skills.json (source, commit, agent, file hashes, the archive's hash). The validator checks those hashes (librarySkill.*), reports an installed skill the spec does not choose (librarySkill.notChosen), and leaves the skills' own text alone. briefstack validate also reports any file under a .claude/skills/ folder identical to a library skill file the user has not approved (librarySkill.unapproved). The creation guard lets the generator run it, into an allowed folder, and only for the library skills of the spec as the user approved it (the runner records them at the approval): a --skill outside that list, or a project spec.json that names another, is denied, and so is any install before an approval. In a creation no caller may read the library's skills/ folder, nor write or edit in a .claude/skills/<name>/ whose name is that of a library skill: skills install is the only way in.

Appendix: fake runner recordings

FakeRunner (src/creation/fakeRunner.ts) replays a recorded creation for tests and the E2E suite: no tokens, no login. A recording is a text file with one JSON object per line; blank lines and lines starting with # are ignored. Examples are in tests/fixtures/recordings/: full (a whole creation), change-at-spec, working (busy for a long time, to cancel), permissions (two requests and a refusal by the guard) and grant (an output folder to allow). The e2e fixture can also build a recording at run time.

line effect
{"do":"session","phase":"started"} writes session.started
{"do":"session","phase":"finished","outcome":"completed"} writes session.finished and ends the run
{"do":"flow","step":"spec","phase":"started"} writes step.started; "phase":"finished","outcome":"ok" writes step.finished
{"do":"hook","type":"subagent.start","agentType":"architect"} writes a hook line (agentId, agentType, tool, reason optional)
{"do":"emit","event":{"kind":"agent",…}} sends a runner event through io.emit
{"do":"question","questions":[…],"onCancel":"<label>"} asks 1–4 questions
{"do":"permission","toolName":"Bash","summary":"…","agentType":"generator","onDeny":"<label>"} asks for a permission
{"do":"spec","onChange":"<label>","onCancel":"<label>","spec":"…","summary":"…"} writes spec.json and spec-summary.md (when given) in the session folder and asks for approval; a change jumps to onChange
{"do":"grant","dir":"out","onDeny":"<label>"} asks to grant a folder (relative to the session folder)
{"do":"label","name":"…"}, {"do":"goto","label":"…"} jump targets and jumps
{"do":"wait","ms":50} a pause, cut short by a cancel or a stop
{"do":"exit"} ends without closing the session, like a crash
{"do":"claim","dir":"garden","onRefused":"<label>"} claims the output folder (relative to the projectsDir option); when another creation holds it, reports a denial and jumps to onRefused
{"do":"library","section":"lessons","text":"…"} library add into the libraryDir option, through the library queue
{"do":"turnEnd","message":"…"} ends a turn with that text and nothing asked, then waits for the free-text reply
{"do":"generate","dir":"meeting-notes"} what the generator does through the CLI: scaffold of the session's spec.json into the projectsDir option (base templates, no git), then skills install when the spec has library skills (needs the libraryDir option)

Without an on… label, a denied permission or a refused grant just continues, and a cancelled question or spec closes the session as the skill does: the open step as skipped, then session finished cancelled. A cancel requested through the manager does the same before the next line.