SLOPSHOPPER

rails-flow

Agentic development flow for Rails 8 projects: orchestrated /feature, /fix and /review commands, fourteen specialist subagents, and hard guardrail hooks. Pairs…

bandguardstatuspromptprocesstimer
★ 1v1.66.0MITupdated 2026-10-22fmanimashaun/claude-skills/plugins/rails-flow
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · rails-flow
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts ⚠ rails-flow: context 49% · 5h 31%
README

Claude Skills — a Rails 8 toolchain for Claude Code

Five plugins that teach Claude to build, review, test and ship Rails 8 applications: the stack doctrine it should follow, the flow it should work in, an independent QA pass that does not trust the developer, a design system, and a release lifecycle.

Install it, then talk to Claude normally. The plugins add commands and specialist agents; you do not need to learn the internals to get value on day one.


Install

/plugin marketplace add fmanimashaun/claude-skills
/plugin install rails-stack@claude-skills     # the doctrine — start here

Then add the flows you want:

/plugin install rails-flow@claude-skills      # build/fix/review loop
/plugin install design-flow@claude-skills     # UI, design system, assets
/plugin install qa-flow@claude-skills         # independent QA
/plugin install pipeline@claude-skills        # release lifecycle
/plugin install nextjs-stack@claude-skills    # Next.js + Supabase + Vercel stack

Or take rails-flow, qa-flow and pipeline in one step. flow-suite is a bundle whose manifest only declares them as dependencies, and installing a plugin installs its dependencies (docs):

/plugin install flow-suite@claude-skills      # rails-flow + qa-flow + pipeline

Verify:

/plugin                    # lists what is installed
/rails-flow:setup-flow     # scaffolds CLAUDE.md, guardrails and the brain into your project

claude.ai / Claude Desktop. Download the .skill files from the latest release and upload them in Settings → Capabilities → Skills. Each is self-contained.

No plugin support (Agent SDK, older clients). Copy the skill directories into your project's .claude/skills/:

git clone https://github.com/fmanimashaun/claude-skills.git /tmp/cs
mkdir -p .claude/skills && cp -R /tmp/cs/plugins/rails-stack/skills/* .claude/skills/

For every project. Same copy, into ~/.claude/skills/ instead.

Updating. /plugin marketplace update claude-skills, then restart Claude Code. To confirm what you actually got — installed versions drift from what you think you installed — run /rails-flow:toolchain-check.


What you get

pluginwhat it does
rails-stackThe doctrine: Rails 8.1, Hotwire, pure RSpec, Tailwind v4, a design system, and the review rules. Bundles seven skills — no commands, it just makes Claude write the right code.
rails-flowThe build loop — /feature, /fix, /review, plus a durable project memory and an autonomous driver.
design-flowUI and design system work — components, tokens, audits, a curated asset library, and an optional pen.dev tier for exploring screens visually before any code is written.
qa-flowAn independent QA engineer that treats the developer's claims as unverified and produces evidence.
pipelineBuild → verify → certify → release, with circuit breakers for unattended runs.
nextjs-stackThe Next.js + Supabase + Vercel stack: how the three fit together, pointing to Vercel's official plugin, the Next.js skills and supabase/agent-skills for each platform's own guidance. It declares the stack's markers for the stack detector.

The seven skills in rails-stack

skillcovers
rails-8the stack — models, jobs, auth, APIs, deployment
hotwireTurbo, Stimulus, Hotwire Native
design-systemthe design system: tokens, components, art direction, reference research
code-reviewcorrectness review classes — the bugs a reviewer must find
quality-passreuse, simplification, efficiency, altitude — advisory, never blocking
derived-artifactsanything whose numbers come from somewhere else
parallel-session-laneworking as one of several agent sessions in one repo

A first run

The shortest path from empty directory to something real:

/rails-flow:setup-flow          # 1. scaffold doctrine + memory into the project
/design-flow:setup              # 2. tokens, brand pack, design system
/rails-flow:feature             # 3. describe what you want; it plans, builds, reviews
/qa-flow:verify                 # 4. an independent pass that does not trust step 3

Steps 1–2 are once per project. Steps 3–4 are the loop.


Commands

feature fix review issues brief spec secure-design slice curate explain graph handoff pr-comments retro report setup-flow toolchain-audit · memory: brain brain-review brain-sync · autonomous: drive escalate toolchain-check · parallel sessions: coordinate claim-coordinator wrap

setup component tokens variants mobile audit critique interface-audit canvas port compose · assets: assets generate

setup-qa cases verify certify functional smoke crawl walkthrough

setup-pipeline pipeline status board ack release install-hooks · cloud: setup-cloud deploy-cloud


How it fits together

Three loops, each with a different job:

  1. Build (rails-flow) — plan, implement, review, remember. Spec-first, IA before code.
  2. Verify (qa-flow) — a separate agent that assumes nothing from the build loop and produces evidence rather than assurances.
  3. Ship (pipeline) — gates the two above into a release, and stops rather than digging when an unattended run goes wrong.

The separation is the point: a build agent that also signs off its own work is a build agent that signs off its own work.

Read next: architecture for the design reasoning and what we deliberately did not adopt · harness doctrine for when a hook should fail open versus closed · code-review graph for the optional tool-gated review integration.


Reporting problems

The toolchain reports its own bugs. From any project using it:

/rails-flow:report

That files a structured, version-pinned, deduplicated issue on this repo. Every issue in the tracker arrived that way, and it is the fastest route to a fix — the report carries the versions and paths a maintainer would otherwise have to ask for.


Repository layout

plugins/             rails-stack (the seven skills — the doctrine that ships) · rails-flow · qa-flow ·
                     pipeline · design-flow · flow-suite
dist/                packaged .skill files for claude.ai
docs/                architecture, coverage and wiki pages
scripts/             the gates that keep all of the above honest
.claude/             maintainer tooling — not distributed

CLAUDE.md is the maintainer's guide to this repo. If you are here to build a Rails app, you want the plugins above, not that file.


Versioning

Components version independently; the marketplace tag is the release label. Every change lands in CHANGELOG.md under its component, and a release publishes one block per component it bumps. Versions are assigned at promotion, never before — a version number on unshipped work is a claim about something you cannot install.

License

MIT — see LICENSE.

Source 5 files
hooks/register.js 14 lines
1// hooks.json names ONE module, so this file registers every mod rails-flow ships.
2// Add a mod here with one import and one call; do not add a second path to hooks.json.
3import { register as contextNudge } from './context-nudge.mjs'
4import { register as laneBand } from './lane-band.js'
5import { register as budgetGuard } from './budget-guard.mjs'
6import { register as sessionReset } from './session-reset.mjs'
7
8export function register(on, options) {
9  contextNudge(on, options)
10  laneBand(on, options)
11  budgetGuard(on, options)
12  sessionReset(on, options)
13}
14
hooks/context-nudge.mjs 231 lines
1// context-nudge: shows how full this session's context window is, and once per climb past a
2// threshold adds ONE line only Claude reads, asking it to offer a handoff (#1547). A session with an elected
3// role is told it resets itself instead, and compacts mid-job at RAILS_FLOW_COMPACT_PCT or a usage warn level
4// (#1723, #1724; hooks/session-reset.mjs).
5// It blocks nothing and rewrites no prompt text: every hook returns next(e), the prompt hook with at
6// most one added context line. Mods need Claude Code 2.1.287 or later.
7//
8// It also carries budget-guard's account-usage view (#1677), because a plugin registers each event once:
9// the 7-day and 5-hour windows join the status line, and once per level reached (warn, then block) one
10// usage line rides on a prompt, so Claude knows its budget without being told. budget-guard.mjs holds the
11// pure helpers; this module passes them data only, never `$`.
12//
13// The figure is the engine's own. `percent` is `tokens` over `window` as a whole percentage, the status
14// line's used_percentage; `tokens` is uncached, cache-written and cache-read input together. It is absent
15// until the first response of a window, and after a compaction until the next response (types for 2.1.287).
16
17// A starting value, not a measured one: nothing has been measured about where a handoff stops being
18// cheap (#1547). RAILS_FLOW_CONTEXT_NUDGE_PCT overrides it, whole percent, 1 to 99.
19const DEFAULT_THRESHOLD = 70
20
21import { budgetLine, DEFAULT_BLOCK, DEFAULT_WARN, level, limitsLabel, msUntil, RESUME_TEXT, windowOf } from './budget-guard.mjs'
22import { compactInstructions, compactReason, DEFAULT_COMPACT_PCT, DEFAULT_COORDINATOR_HANDOFF, debugNote, ensureRole, job, jobDoneShape, state, wholePct } from './session-reset.mjs'
23
24// Mid-job compaction (#1687): which sources have already compacted this climb, so each fires once.
25const compacted = { context: false, five_hour: false, seven_day: false }
26// The one role line (the elected role, or that none could be elected) has been added.
27let askedRole = false
28export const ROLE_LINE =
29  'rails-flow role: rails-flow could not elect a role for this session. Start it with RAILS_FLOW_ROLE=coordinator or ' +
30  'RAILS_FLOW_ROLE=implementation; until then it will neither clear nor compact this session. Say this once.'
31
32// Each window's last reading, and the highest level announced since it was last below warn.
33const WINDOWS = ['five_hour', 'seven_day']
34const reading = { five_hour: null, seven_day: null }
35const announced = { five_hour: null, seven_day: null }
36// The pending resume after the 5-hour window resets, so it is scheduled once.
37let resume = null
38
39// The last fill the engine measured, in whole percent, or null while the live window has no reading.
40let percent = null
41// The main conversation's last request: the share of its input the API served from the prompt cache, whole percent (#1884).
42let cache = null
43// The usage windows' label, kept so a cache reading can redraw the status line without a new measure.
44let limitsText = null
45
46// The share of a request's input read from the prompt cache, in whole percent, or null when it cannot be told. The Claude API
47// reports input in three parts -- `input_tokens` (uncached), `cache_creation_input_tokens` (written to the cache) and
48// `cache_read_input_tokens` (served from it) -- so the hit rate is read / (read + written + uncached). A falling figure is the
49// sign a session's prefix stopped being cached: text injected early that changes each turn, a model switch, an idle gap past
50// the cache's lifetime. Shown on the status line only, so it costs no context.
51export function cacheHit(usage) {
52  if (usage === null || typeof usage !== 'object') return null
53  const read = usage.cache_read_input_tokens
54  const written = usage.cache_creation_input_tokens ?? 0
55  const uncached = usage.input_tokens ?? 0
56  if (![read, written, uncached].every((n) => Number.isFinite(n) && n >= 0)) return null
57  const total = read + written + uncached
58  return total === 0 ? null : Math.round((100 * read) / total)
59}
60
61function statusText() {
62  const parts = [percent === null ? null : `context ${percent}%`, cache === null ? null : `cache ${cache}%`, limitsText].filter(Boolean)
63  return parts.length ? parts.join(' · ') : undefined
64}
65// The line has been added since the fill last fell below the threshold or lost its reading.
66let nudged = false
67
68// The line itself. It rides on a prompt, so its size is a cost: every character is billed again on
69// each later request, which is why it is added once per climb and kept this short.
70export function nudgeLine(fill, role = null) {
71  const head = `Context note: this session's context window is ${fill}% full. Finish the current step, then `
72  if (role === 'coordinator')
73    return `${head}update the coordinator handoff. This session compacts itself at the compact threshold; do not ask the user to run /clear. Say this once; do not repeat it.`
74  if (role === 'implementation')
75    return (
76      `${head}update the handoff (/rails-flow:handoff) and commit and push work in progress. This session compacts itself ` +
77      'at the compact threshold and clears itself once its PR is merged into dev and its worktree is removed; do not ask the user to run /clear. Say this once; do not repeat it.'
78    )
79  return (
80    `${head}offer to ` +
81    'write a handoff with /rails-flow:handoff and tell the user to run /clear (not /compact: the handoff already holds it) before new work. ' +
82    'Say this once; do not repeat it.'
83  )
84}
85
86// The threshold in force: the environment's whole percent when it is one, else the default.
87// A whole percent from 1 to 100, or the default.
88function pct(raw, dflt) {
89  const n = Number.parseInt(raw ?? '', 10)
90  return Number.isInteger(n) && n >= 1 && n <= 100 ? n : dflt
91}
92
93async function budgetLevels($) {
94  return [
95    pct(await $.env.get('RAILS_FLOW_BUDGET_WARN_PCT'), DEFAULT_WARN),
96    pct(await $.env.get('RAILS_FLOW_BUDGET_BLOCK_PCT'), DEFAULT_BLOCK),
97  ]
98}
99
100async function threshold($) {
101  const raw = await $.env.get('RAILS_FLOW_CONTEXT_NUDGE_PCT')
102  const n = Number.parseInt(raw ?? '', 10)
103  return Number.isInteger(n) && n >= 1 && n <= 99 ? n : DEFAULT_THRESHOLD
104}
105
106// Only a prompt from a person at an interactive surface carries the line: `composer` (Enter at the prompt),
107// `bridge` (Remote Control from a phone or the web), or no origin at all, which the engine defines as the
108// user's own. Every other kind is refused on purpose, so the line is not used up on a message the person
109// never reads: a peer session, a scheduled task, a background notification, another plugin, a channel
110// relay. `sdk` is refused too: `claude -p` and the Agent SDK have nobody to run /clear, so asking Claude to
111// tell the user to would only waste the line (mod hooks do run there; the docs say so). The kinds are a
112// closed set in the engine's types for 2.1.287; docs/evidence/audits/2026-10-02-mods-api-2.1.287.md.
113function isTheirs(origin) {
114  return origin === undefined || origin.kind === 'composer' || origin.kind === 'bridge'
115}
116
117// Compact this session, never clear it, when the context fill or a usage window reaches its level while the
118// session has a declared role (#1687). Runs from a timer: compact rejects inside a hook the turn waits on, and
119// a rejection (a turn is running) re-arms the source so the next measure tries again. A role-less session, a
120// `claude -p` run (no surface) and a session whose job is done (it clears instead) are left alone.
121async function maybeCompact($, levels) {
122  try {
123    const role = state.role
124    if (state.rearm !== null) {
125      compacted[state.rearm] = false // the queued /compact was rejected: due again
126      state.rearm = null
127    }
128    const compactPct = wholePct(await $.env.get('RAILS_FLOW_COMPACT_PCT'), DEFAULT_COMPACT_PCT)
129    const sources = {
130      context: { fill: percent, windows: [] },
131      five_hour: { fill: null, windows: [{ lvl: level(reading.five_hour?.pct, ...levels), announced: announced.five_hour }] },
132      seven_day: { fill: null, windows: [{ lvl: level(reading.seven_day?.pct, ...levels), announced: announced.seven_day }] },
133    }
134    for (const [key, src] of Object.entries(sources)) {
135      const live = key === 'context' ? percent !== null && percent >= compactPct : src.windows[0].lvl !== null
136      if (!live) compacted[key] = false
137    }
138    if (role === null || (role === 'implementation' && (jobDoneShape() || job.pending))) return
139    for (const [key, src] of Object.entries(sources)) {
140      if (compacted[key]) continue
141      const reason = compactReason({ role, compactPct, nudged, ...src })
142      if (reason === null) continue
143      const surfaces = (await $.session.surfaces()).length
144      if (surfaces === 0) {
145        debugNote(`compact skipped (${key}: ${reason}): no surface`)
146        return
147      }
148      compacted[key] = true
149      const text = compactInstructions(role, job, (await $.env.get('RAILS_FLOW_COORDINATOR_HANDOFF')) || DEFAULT_COORDINATOR_HANDOFF)
150      // Only RECORD that a compaction is due. This hook fires during a turn, where a compaction is rejected; the
151      // session-reset module queues it at turn.complete, when the session is idle.
152      state.compactDue = { key, text, reason }
153      debugNote(`compact due (${key}: ${reason}) role=${role} fill=${percent} surfaces=${surfaces}`)
154      return
155    }
156  } catch {
157    // Advisory: a failed check leaves the session as it was
158  }
159}
160
161export function register(on) {
162  // Runs after each turn, and whenever the fill moved: the figure is pushed, not polled
163  on('session.measure', async ($, e, next) => {
164    percent = e.context.percent ?? null
165    let now        // a window that has already reset is no reading (#1854); no clock, no filter
166    try {
167      now = await $.clock.now()       // called, never read as a value: the validator rejects `$.clock` used as one (#1893)
168    } catch {
169      now = undefined
170    }
171    const levels = await budgetLevels($)
172    for (const k of WINDOWS) {
173      reading[k] = windowOf(e.rateLimits, k, now)
174      if (level(reading[k]?.pct, ...levels) === null) announced[k] = null
175    }
176    limitsText = limitsLabel(e.rateLimits, now) ?? null
177    $.ui.status(statusText())
178    // At the 5-hour hard level, schedule one prompt for just after the reset, so the work resumes by itself.
179    const five = reading.five_hour
180    if (resume === null && level(five?.pct, ...levels) === 'block' && (await $.env.get('RAILS_FLOW_AUTO_RESUME')) !== '0') {
181      const ms = msUntil(five.resetsAt, await $.clock.now())
182      if (ms !== null) resume = $.clock.after(ms + 120000, () => { resume = null; void $.prompt.submit({ text: RESUME_TEXT }) })
183    }
184    if (percent === null || percent < (await threshold($))) nudged = false
185    await maybeCompact($, levels)
186    return next(e)
187  })
188
189  // Runs once per request to the model (#1884). It forwards the response untouched as it streams, then reads the request's
190  // usage. Only the main conversation's requests count: a subagent's (`e.agentId` set) has its own prefix and cache.
191  on('turn.step', async function* ($, e, next) {
192    const result = yield* next(e)
193    try {
194      if (!e.agentId) {
195        const hit = cacheHit(result?.usage)
196        if (hit !== null) {
197          cache = hit
198          $.ui.status(statusText())
199        }
200      }
201    } catch {
202      // Advisory: a failed reading leaves the status line as it was
203    }
204    return result
205  })
206
207  // Runs when a prompt is submitted
208  on('prompt.submit', async ($, e, next) => {
209    const lines = []
210    const levels = await budgetLevels($)
211    for (const k of WINDOWS) {
212      const lvl = level(reading[k]?.pct, ...levels)
213      if (lvl !== null && lvl !== announced[k] && !(announced[k] === 'block' && lvl === 'warn')) {
214        announced[k] = lvl
215        lines.push(budgetLine(k, reading[k].pct, lvl, reading[k].resetsAt, k === 'five_hour' && resume !== null))
216      }
217    }
218    if (!askedRole && isTheirs(e.origin)) await ensureRole($)      // the "could not elect" line only after a second try (#2307)
219    const role = state.role
220    if (!askedRole && isTheirs(e.origin)) {
221      askedRole = true
222      lines.push(state.line ?? ROLE_LINE)
223    }
224    if (percent !== null && !nudged && isTheirs(e.origin) && percent >= (await threshold($))) {
225      nudged = true
226      lines.push(nudgeLine(percent, role))
227    }
228    return lines.length ? next({ ...e, context: [...(e.context ?? []), ...lines] }) : next(e)
229  })
230}
231
hooks/lane-band.js 89 lines
1// lane-band: a read-only band above the prompt showing where this session is working.
2// Shows the branch, the worktree directory, the assigned lane (RAILS_FLOW_LANE) and the number of
3// uncommitted files, refreshed every two seconds. It blocks nothing and rewrites nothing: every hook
4// returns next(e) unchanged.
5// Verified in the terminal only. `AbovePrompt` is also raised on the Desktop Code tab, but this band's
6// data comes from `$.process`, which Claude Code's type declarations mark "CLI only", and it has not been
7// run on Desktop. The VS Code chat panel draws nothing.
8// Tested with Claude Code 2.1.287 (`claude plugin validate` and `claude plugin test`); mods need that version or later.
9
10// What the band shows. Reset to null when the working directory is not a git repository.
11let info = null
12
13// Run one git command and return its trimmed stdout, or null when git fails or cannot start.
14async function git($, args) {
15  try {
16    const r = await $.process.run(['git', ...args], { timeoutMs: 5000 })
17    return r.exitCode === 0 ? r.stdout.trim() : null
18  } catch {
19    return null
20  }
21}
22
23// Read branch, worktree and dirty count, then ask Claude Code to draw the band again.
24// `--no-optional-locks` keeps `git status` from rewriting .git/index while the user's own git runs.
25async function refresh($) {
26  const top = await git($, ['rev-parse', '--show-toplevel'])
27  let next = null
28  if (top !== null) {
29    const branch = (await git($, ['branch', '--show-current'])) || 'detached HEAD'
30    const status = (await git($, ['--no-optional-locks', 'status', '--porcelain', '--ignore-submodules=dirty'])) ?? ''
31    let lane = ''
32    try {
33      lane = (await $.env.get('RAILS_FLOW_LANE')) || ''
34    } catch {
35      // Keep the band without a lane rather than losing it
36    }
37    next = {
38      branch,
39      worktree: top.split('/').pop(),
40      lane,
41      dirty: status === '' ? 0 : status.split('\n').length,
42    }
43  }
44  info = next
45  $.ui.invalidate('ui.render')
46}
47
48// True while a refresh is running, so a slow one is never overlapped by the next tick.
49let busy = false
50
51// The timer callback. A throw or a rejection here (a failed redraw request, say) is caught here, so
52// the band never depends on how the host treats a callback that fails.
53async function tick($) {
54  if (busy) return
55  busy = true
56  try {
57    await refresh($)
58  } catch {
59    // Keep whatever the band last showed
60  } finally {
61    busy = false
62  }
63}
64
65export function register(on) {
66  // Runs before your first prompt, and again after a reload (which cancels the old timer). The git
67  // calls run on a repeating timer, the documented way to do background work, so neither the first
68  // prompt nor the end of a turn ever waits on them. The first refresh comes one interval after start.
69  on('session.start', async ($, e, next) => {
70    $.clock.every(2000, () => tick($))
71    return next(e)
72  })
73
74  // Runs each time Claude Code draws the band above the prompt
75  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
76    const theirs = await next(e)
77    if (info === null) return theirs
78    const { Box, Text } = $.ui.resolve(e)
79    const parts = [info.branch, info.worktree]
80    if (info.lane) parts.push('lane ' + info.lane)
81    parts.push(info.dirty === 0 ? 'clean' : info.dirty + ' uncommitted')
82    // Keep what the mods after this one draw, and put the line above it
83    return Box({
84      flexDirection: 'column',
85      children: [Text({ dimColor: true, children: [parts.join(' · ')] }), ...(theirs ? [theirs] : [])],
86    })
87  })
88}
89
hooks/budget-guard.mjs 160 lines
1// budget-guard: keeps agent fan-out from spending an account's usage limit (#1676, #1677).
2// Two refusals on the tool.call event, and pure helpers that context-nudge.mjs uses to show the limits.
3// Mods need Claude Code 2.1.287 or later; the declarations cited are in
4// docs/evidence/audits/2026-10-07-mods-tool-call-ratelimits-2.1.292.md.
5//
6// 1. A Workflow whose script has agents only relay SendMessage is refused at any usage. Each agent pays its whole
7//    startup context (measured: ~62k tokens) to send a message a direct SendMessage call sends for a few
8//    hundred. A script that really does work and also messages can say so with the marker below.
9// 2. At or past the hard threshold of the 7-day window, a new Workflow or Agent is refused unless
10//    RAILS_FLOW_BUDGET_ALLOW=1 is set. Direct tool use is never touched.
11// The rate-limit windows appear only on a claude.ai Pro or Max subscription or behind a gateway spend
12// limit, and only after the first response; with no reading, nothing is refused for usage.
13// A reading is the one the session's LAST API RESPONSE reported (the declared `SessionRateLimit` has `kind`, `percentUsed` and `resetsAt`, and no
14// measurement time), so a session that has not had a response since the window reset still holds the OLD window's figure. #1854: on 2026-10-11 eight
15// long-running sessions refused all new work on a weekly 90-96% that /usage showed as 6%, because the weekly window had reset at 02:00 UTC. The hook is
16// advisory, so it fails OPEN: a window whose `resetsAt` has passed is no reading at all, and the refusal says what it knows (the reset time, how long
17// THIS HOOK has seen the same figure, that the harness gives the reading no timestamp) and how to override it. A gateway's
18// window is `spend_limit`, not the 7-day one, so the weekly refusal does not apply behind a gateway alone.
19// A Workflow started by `name` or `scriptPath` carries no `script`, so the relay check cannot see it.
20
21export const DEFAULT_WARN = 80
22export const DEFAULT_BLOCK = 90
23export const STARTUP_TOKENS = 60000
24export const NOT_A_RELAY = '// budget-guard: not a relay'
25
26// Has this window already reset? A reading whose `resetsAt` is at or before `now` describes a window that is over (#1854). With no usable `resetsAt`
27// nothing proves it is stale, so it is not expired.
28export function expired(resetsAt, now) {
29  const t = resetsAt ? Date.parse(resetsAt) : Number.NaN
30  return now !== undefined && !Number.isNaN(t) && t <= now
31}
32
33// The 7-day window's percent used, or null with no reading. With `now`, a window that has already reset is no reading.
34export function weekly(rateLimits, now) {
35  return windowOf(rateLimits, 'seven_day', now)?.pct ?? null
36}
37
38// "week 96% · 5h 40%", or undefined with no reading. Only the two subscription windows; with `now`, windows that have reset are left out.
39export function limitsLabel(rateLimits, now) {
40  const names = { seven_day: 'week', five_hour: '5h' }
41  const parts = (rateLimits ?? [])
42    .filter((r) => names[r.kind] && typeof r.percentUsed === 'number' && !expired(r.resetsAt, now))
43    .map((r) => `${names[r.kind]} ${Math.round(r.percentUsed)}%`)
44  return parts.length ? parts.join(' · ') : undefined
45}
46
47// One window's reading, `{ pct, resetsAt }`, or null. `resetsAt` is ISO 8601 in a mod (the status line's
48// own JSON uses epoch seconds instead; the two are not mixed here).
49// With `now`, a window that has already reset is null (#1854).
50export function windowOf(rateLimits, kind, now) {
51  const w = (rateLimits ?? []).find((r) => r.kind === kind)
52  if (typeof w?.percentUsed !== 'number' || expired(w.resetsAt, now)) return null
53  return { pct: w.percentUsed, resetsAt: w.resetsAt }
54}
55
56// "3 h 10 min", "25 min" or "under a minute".
57export function ageText(ms) {
58  const min = Math.floor(Math.max(0, ms) / 60000)
59  if (min < 1) return 'under a minute'
60  return min < 60 ? `${min} min` : `${Math.floor(min / 60)} h ${min % 60} min`
61}
62
63// The level a reading is at: 'block', 'warn' or null.
64export function level(pct, warn = DEFAULT_WARN, block = DEFAULT_BLOCK) {
65  if (pct === null || pct === undefined) return null
66  return pct >= block ? 'block' : pct >= warn ? 'warn' : null
67}
68
69// " (resets 14:05 UTC)" from an ISO time, or "" without one.
70export function resetText(resetsAt) {
71  const t = resetsAt ? new Date(resetsAt) : null
72  return t && !Number.isNaN(t.getTime()) ? ` (resets ${t.toISOString().slice(11, 16)} UTC)` : ''
73}
74
75// Milliseconds from `now` until `resetsAt`, or null.
76export function msUntil(resetsAt, now) {
77  const t = resetsAt ? Date.parse(resetsAt) : Number.NaN
78  return Number.isNaN(t) ? null : Math.max(0, t - now)
79}
80
81// The one line Claude reads when a window first reaches a level. The point of the warn line is to write
82// things down while there is still budget to do it. Kept short: it is billed again on every later request.
83export function budgetLine(kind, pct, lvl, resetsAt, willResume = false) {
84  const name = kind === 'five_hour' ? '5-hour' : 'weekly'
85  const head = `Usage note: the ${name} limit is ${Math.round(pct)}% used${resetText(resetsAt)}.`
86  if (lvl === 'warn')
87    return `${head} Update the handoff now (/rails-flow:handoff) and commit and push work in progress; avoid Workflow and Agent fan-out.`
88  const wait = kind === 'five_hour' && willResume ? ' rails-flow will resume this session after the reset.' : ''
89  const refuse = kind === 'seven_day' ? ' New Workflow and Agent calls are refused.' : ''
90  return `${head} Stop starting new work: finish this step, update the handoff, commit and push, then stop.${refuse}${wait}`
91}
92
93// What the resume prompt says once the 5-hour window has reset.
94export const RESUME_TEXT =
95  'The 5-hour usage limit has reset. Resume: read the handoff (HANDOFF.md, or the latest PR or issue comment you wrote), check the branch and its pushed SHA, then continue from the recorded next step.'
96
97// A workflow that spawns agents to relay SendMessage. The marker opts out a script that really does work.
98export function isRelay(script) {
99  return typeof script === 'string' && !script.includes(NOT_A_RELAY) && /\bSendMessage\b/.test(script) && /\bagent\s*\(/.test(script)
100}
101
102async function blockAt($) {
103  const n = Number.parseInt((await $.env.get('RAILS_FLOW_BUDGET_BLOCK_PCT')) ?? '', 10)
104  return Number.isInteger(n) && n >= 1 && n <= 100 ? n : DEFAULT_BLOCK
105}
106
107async function nowOf($) {
108  try {
109    return await $.clock.now()      // called, never read as a value: the validator rejects `$.clock` used as one (#1893)
110  } catch {
111    return Date.now()
112  }
113}
114
115// When THIS HOOK first saw each exact reading. The harness gives the reading no time, so "unchanged for hours" is the only age there is, and it is what
116// a stale figure looks like (#1854). Keyed by figure and reset time; a new figure or a new window starts again.
117const firstSeen = new Map()
118
119// The weekly reading that blocks, `{ pct, resetsAt, ageMs }`, or null: no reading, a window that has reset, or below the hard level.
120async function overBlock($) {
121  if ((await $.env.get('RAILS_FLOW_BUDGET_ALLOW')) === '1') return null
122  const now = await nowOf($)
123  const w = windowOf((await $.session.usage()).rateLimits, 'seven_day', now)
124  if (w === null) return null
125  const key = `${w.pct}|${w.resetsAt ?? ''}`
126  if (!firstSeen.has(key)) firstSeen.set(key, now)
127  return w.pct >= (await blockAt($)) ? { ...w, ageMs: now - firstSeen.get(key), now } : null
128}
129
130// The refusal. Says what is known about the reading and how to override it (#1854): it is not a measurement the hook made.
131function refusal(what, r, extra = '') {
132  const t = r.resetsAt ? Date.parse(r.resetsAt) : Number.NaN
133  const resets = Number.isNaN(t) ? '(no usable reset time)' : `(resets ${new Date(t).toISOString().slice(11, 16)} UTC, in ${ageText(t - r.now)})`
134  return (
135    `rails-flow budget-guard: the weekly limit reads ${Math.round(r.pct)}% used ${resets}; ${what} are refused${extra}. ` +
136    `That figure is what the session's last API response reported: the harness gives it no timestamp, and this hook has seen the same reading for ` +
137    `${ageText(r.ageMs)}. Run /usage; if it disagrees, say so and continue, or set RAILS_FLOW_BUDGET_ALLOW=1 to override.`
138  )
139}
140
141export function register(on) {
142  on('tool.call', { tool: 'Workflow' }, async ($, e, next) => {
143    if (isRelay(e.script))
144      return {
145        deny:
146          `rails-flow budget-guard: this workflow spawns agents to relay SendMessage, about ${STARTUP_TOKENS / 1000}k tokens of startup ` +
147          `each. Call SendMessage directly, once per recipient, in one turn. If the agents do real work, add the line "${NOT_A_RELAY}".`,
148      }
149    const r = await overBlock($)
150    if (r !== null) return { deny: refusal('new workflows', r) }
151    return next(e)
152  })
153
154  on('tool.call', { tool: 'Agent' }, async ($, e, next) => {
155    const r = await overBlock($)
156    if (r !== null) return { deny: refusal('new agents', r, ` (about ${STARTUP_TOKENS / 1000}k tokens each)`) }
157    return next(e)
158  })
159}
160
hooks/session-reset.mjs 698 lines
1// session-reset: a session resets its own context when its job is done, and compacts, never clears,
2// while work is still in flight (#1687, related #1564). Owner rules, 2026-10-09: a finished
3// implementation session clears itself; a coordinator compacts itself; a session near a limit with work
4// in flight compacts and keeps its worktrees. The owner never types /clear.
5//
6// It is advisory and fails open: every hook returns what `next` gave it, a throw anywhere is swallowed,
7// and when it cannot tell what the session is doing it does nothing (an undeclared role, a `claude -p`
8// run, an unreadable pull request). A reset that fires in the middle of work is the failure to avoid,
9// so each doubt resolves to "no action".
10//
11// The role is ELECTED at session.start, machine-wide (owner rule, 2026-10-09): the first live session to
12// ask becomes the coordinator, every later one is an implementation session, and a claim whose process is
13// gone is stale and taken over. RAILS_FLOW_ROLE=coordinator|implementation overrides the election (the
14// owner's hand-over). Until a role is known, or if the election fails, the role is null: no action.
15// See reference/context-budget.md, "A session resets itself".
16//
17// API relied on (Claude Code 2.1.292 declaration, the newest available; the CLI here is 2.1.293 and
18// 2.1.295 is the version in scope; docs/evidence/audits/2026-10-09-mods-command-run-clear-2.1.292.md):
19//   $.command.run({ command })  "Runs a slash command as if the person typed `/command args` ... queued
20//                               and run once the session is idle ... Rejects an unknown name, and inside
21//                               a hook the turn is waiting on."  So it is never AWAITED inside a hook. It is
22//                               called (not awaited) from turn.complete, with no await before it, so the clear
23//                               is queued ahead of any later prompt. Measured on 2.1.293 under `claude -p`: a
24//                               call from a turn.complete hook did not reject. Not measured interactively.
25//   $.session.compact({ instructions })  "between turns ... rejects while a turn runs"
26//   $.prompt.submit({ text })   "a turn of its own, once the session is idle"
27//   $.session.surfaces()        "Empty in a plain -p run"
28//   session.start never fires on /clear ("never `/clear`"), so this module's variables survive it.
29// Threat model of the claim file: the same user. Any process running as this user can write, replace or delete
30// ~/.claude/rails-flow/coordinator, so the election guards against accident (two windows starting together, a
31// restart, a stale claim), not against impersonation, and nothing read from it is trusted as an instruction (pid and
32// session id are reduced to digits and word characters before they reach a prompt).
33// The state is not persisted to $.store on purpose: a reload loses it, and a session that lost track of
34// its job does nothing.
35
36export const DEFAULT_COMPACT_PCT = 75
37export const DEFAULT_COORDINATOR_HANDOFF = '~/projects/claude-skills-wt/_logs/COORDINATOR-HANDOFF.md'
38
39// This session's elected role. Module variables survive a /clear (the process goes on, and session.start does
40// not fire again), so the role survives it; a resume is a new process and elects again.
41export const state = { role: null, coordinator: null, line: null, hasSurface: false, defaulted: false, electAt: null, compactDue: null, rearm: null, debug: [] }
42
43// Debug notes: with RAILS_FLOW_DEBUG=1 each compact or clear decision, and any rejection, is appended to
44// ~/.claude/rails-flow/debug.log, so a live test can be read without a transcript. Off, the notes are dropped.
45// context-nudge.mjs adds notes through this pure function; only this module holds `$` and writes the file.
46export function debugNote(line) {
47  state.debug.push(String(line).slice(0, 400))
48  if (state.debug.length > 100) state.debug.shift()
49}
50
51async function debugFlush($) {
52  const lines = state.debug.splice(0)
53  try {
54    if (lines.length === 0 || (await $.env.get('RAILS_FLOW_DEBUG')) !== '1') return
55    await $.process.run(
56      ['sh', '-c', 'd="$HOME/.claude/rails-flow"; mkdir -p "$d" && printf "%s\\n" "$1" | while IFS= read -r l; do printf "%s %s\\n" "$(date +%Y-%m-%dT%H:%M:%S)" "$l"; done >> "$d/debug.log"', 'sh', lines.join('\n')],
57      { timeoutMs: 5000 },
58    )
59  } catch {
60    // A debug log never affects the session
61  }
62}
63
64function say($, line) {
65  debugNote(line)
66  void debugFlush($)
67}
68
69// Queue the compaction the context-nudge decided is due. `/compact` goes through `$.command.run`: it is "queued and
70// run once the session is idle", where `$.session.compact` "rejects while a turn runs" (measured live on 2.1.296: a
71// compact tried from session.measure, which fires during a turn, never ran). Called from turn.complete only.
72function queueCompact($, due) {
73  say($, `compact queued (${due.key}: ${due.reason}) via /compact, role=${state.role}`)
74  const failed = (err) => {
75    state.rearm = due.key
76    say($, `compact REJECTED (${due.key}): ${String(err?.message ?? err).slice(0, 200)}`)
77  }
78  try {
79    $.command
80      .run({ command: 'compact', args: due.text })
81      .then(() => say($, `compact done (${due.key})`))
82      .catch(failed)
83  } catch (err) {
84    failed(err)
85  }
86}
87
88// $3 = "2" is a SYNC: it only reads the claim and never makes, takes or removes one. It reports coordinator when the claim
89// is this process's, implementation when another live process holds it, and `none` otherwise (a dead or missing claim
90// changes nothing). $4, when all digits, is the pid to claim for instead of $PPID: /rails-flow:claim-coordinator passes
91// the engine pid, because its own shell is not the engine (#2070).
92// POSIX sh, run with $1 = this session's id, $2 = "1" to force a claim, $3 = "1" for a RESUMED session: it never
93// makes or takes a claim, it only keeps one that already carries its own session id (owner rule, 2026-10-09, #1724).
94// A resumed session whose claim holds another id, or none, reports implementation. $PPID is the engine's own pid
95// (measured under `claude -p` 2.1.293: the shell `$.process.run` starts has the claude process as parent).
96// The claim is a directory made with mkdir, which is atomic: of two simultaneous starts exactly one makes it.
97// A claim is live only while its pid exists AND its process start time matches (a recycled pid after a
98// reboot is not the coordinator) AND that process is not a pre-warmed spare. A \`claude bg-spare --bg-spare ...\` process is not a
99// user session: it starts fresh (no turns), so it looked like a new session, won the claim and left every real session
100// "implementation" (#2068). A spare never claims (it reports \`spare\`, no role) and a claim a spare holds is not live, so the next real start replaces it. A stale claim is replaced under a second mkdir lock, so two takers cannot
101// both win; a taker that finds the lock held reports implementation (fewer coordinators, never more). A claim directory
102// exists a moment before its `claim` file is written, so an EMPTY claim younger than a minute (and not dated in the future,
103// which clock skew can do) is one being made, and is
104// never taken over (#1728 review: a taker that removed it let both sessions print coordinator). A coordinator that dies is
105// replaced only at the NEXT session start, and RAILS_FLOW_ROLE=coordinator (force) takes the claim without telling the
106// live holder, which keeps believing it coordinates until it next starts.
107export const ELECT_SCRIPT = `
108d="$HOME/.claude/rails-flow"; c="$d/coordinator"; lk="$d/lock"; me="$PPID"; sid="$1"; force="$2"; resumed="$3"
109case "$4" in ''|*[!0-9]*) ;; *) me="$4" ;; esac
110mkdir -p "$d" || { echo error; exit 0; }
111spare() { case " $(ps -o command= -p "$1" 2>/dev/null) " in *" bg-spare --bg-spare "*) return 0 ;; esac; return 1; }
112start() { ps -o lstart= -p "$1" 2>/dev/null | sed 's/^ *//'; }
113claim() { mkdir "$c" 2>/dev/null || return 1; printf '%s\\n%s\\n%s\\n%s\\n' "$me" "$sid" "$(date +%s)" "$(start "$me")" > "$c/claim"; }
114alive() { [ -n "$1" ] && kill -0 "$1" 2>/dev/null && [ "$(start "$1")" = "$2" ] && ! spare "$1"; }
115read_claim() { hp=$(sed -n 1p "$c/claim" 2>/dev/null); hs=$(sed -n 2p "$c/claim" 2>/dev/null); hl=$(sed -n 4p "$c/claim" 2>/dev/null); }
116report() { echo "implementation $hp $hs"; exit 0; }
117if [ "$force" != "1" ] && spare "$me"; then echo spare; exit 0; fi
118if [ "$resumed" = "2" ]; then
119  read_claim
120  if [ "$hp" = "$me" ] && [ "$hl" = "$(start "$me")" ]; then echo coordinator; exit 0; fi
121  if [ -n "$hp" ] && alive "$hp" "$hl"; then report; fi
122  echo none; exit 0
123fi
124if [ "$force" = "1" ]; then rm -rf "$c"; fi
125# The claim a RESUMED session may keep: it carries this session's id, and its process is gone (or is this one). Read again under the lock below.
126owns() { [ -n "$hp" ] && [ "$hs" = "$sid" ] && { [ "$hp" = "$me" ] || ! alive "$hp" "$hl"; }; }
127if [ "$resumed" = "1" ] && [ "$force" != "1" ]; then
128  read_claim
129  if owns; then
130    # The re-claim REWRITES the claim file, so it takes the same lock as the stale takeover below (#2311 review): unlocked, a fresh start taking this dead claim over
131    # (rm -rf, then mkdir) could remove the directory between this read and this write, and both sessions would print coordinator. A holder of the lock sends this
132    # session to implementation (fewer coordinators, never more); the claim is read again under the lock, and the write must land in a claim that still exists.
133    if [ -n "$(find "$lk" -maxdepth 0 -mmin +1 2>/dev/null)" ]; then rmdir "$lk" 2>/dev/null; fi
134    mkdir "$lk" 2>/dev/null || report
135    read_claim
136    if owns && [ -d "$c" ] \\
137       && printf '%s\\n%s\\n%s\\n%s\\n' "$me" "$sid" "$(date +%s)" "$(start "$me")" > "$c/claim"; then rmdir "$lk"; echo coordinator; exit 0; fi
138    rmdir "$lk"; read_claim; report
139  fi
140  report
141fi
142if claim; then echo coordinator; exit 0; fi
143read_claim
144if [ -z "$hp" ]; then sleep 1; read_claim; fi
145future() { ref="$d/.now.$$"; : > "$ref" 2>/dev/null; f=$(find "$c" -maxdepth 0 -newer "$ref" 2>/dev/null); rm -f "$ref"; [ -n "$f" ]; }
146young_empty() { [ -z "$hp" ] && [ -d "$c" ] && [ -z "$(find "$c" -maxdepth 0 -mmin +1 2>/dev/null)" ] && ! future; }
147if young_empty; then report; fi
148if [ "$hp" = "$me" ] && [ "$hl" = "$(start "$me")" ]; then echo coordinator; exit 0; fi
149if alive "$hp" "$hl"; then report; fi
150if [ -n "$(find "$lk" -maxdepth 0 -mmin +1 2>/dev/null)" ]; then rmdir "$lk" 2>/dev/null; fi
151mkdir "$lk" 2>/dev/null || report
152read_claim
153if alive "$hp" "$hl" || young_empty; then rmdir "$lk"; report; fi
154rm -rf "$c"
155if claim; then rmdir "$lk"; echo coordinator; exit 0; fi
156rmdir "$lk"; read_claim; report
157`
158
159// What the script printed -> { role, coordinator }, or null when it said nothing usable.
160export function parseElection(out) {
161  const [role, pid, sid] = String(out ?? '').trim().split(/\s+/)
162  if (role === 'spare') return null      // a pre-warmed spare takes no part in the election (#2068)
163  if (role === 'coordinator') return { role, coordinator: null }
164  // pid and id are read from a file any process of this user can write: only digits and word characters survive
165  if (role === 'implementation') return { role, coordinator: /^\d+$/.test(pid ?? '') ? `session ${/^[\w-]+$/.test(sid ?? '') ? sid : 'unknown'} (pid ${pid})` : null }
166  return null
167}
168
169export function electionLine(r) {
170  if (r.defaulted) {
171    return 'rails-flow role: the election could not run after this restart, so this session defaults to implementation. It clears itself only after a worktree it created is removed and its own PR is merged into dev; ' +
172      'if it is the coordinator, /rails-flow:claim-coordinator takes the role back.'
173  }
174  return r.role === 'coordinator'
175    ? 'rails-flow role: this session was elected coordinator (none was live). It compacts itself near a limit and never clears.'
176    : `rails-flow role: this session is an implementation session; the coordinator is ${r.coordinator ?? 'another live session'}. ` +
177        'It clears itself after its PR is merged into dev and its worktree is removed.'
178}
179
180// Is this session a resume (or continue, or fork)? The mods `session.start` input carries no start source: its
181// SessionStartInput is { cwd, surface, isInteractive } (plugins/rails-flow/.claude-plugin/types/claude-code/index.d.ts
182// line 11679). The `source: 'startup' | 'resume' | 'clear' | 'compact' | 'fork'` field is on the classic hook's
183// SessionStartHookInput (line 11653), which a mod does not receive. A mod sees the transcript instead:
184// `$.session.turns()` (line 2799, "how many prompts the user has sent this session (user turns in the transcript)")
185// is 0 at a fresh start and above 0 in a resumed conversation. Unmeasured live. If it cannot be read the session
186// counts as resumed: fewer coordinators, never more.
187async function isResumed($) {
188  try {
189    return (await $.session.turns()) > 0
190  } catch {
191    return true
192  }
193}
194
195// How long the election's `sh` may run before it counts as no answer. 20 s, not 8: the machine this runs on was measured with I/O stalls of
196// 20 to 60 s (a `git commit` that takes 2 s took 21 s; a 10 s git timeout fired for real in a hook), and the owner restarts every session at once
197// (#2307), so ten elections hit a stalled disk together. A timeout used to leave a resumed session with no role at all.
198export const ELECT_TIMEOUT_MS = 20000
199// A session with no role asks again no more often than this (ensureRole).
200export const ELECT_RETRY_MS = 30000
201
202// Elect this session's role. A fresh session that cannot be told fails open to null: any error leaves it with no automatic action. A RESUMED
203// session never ends with no role (#2307): when the election throws, times out, exits non-zero or prints nothing usable, it DEFAULTS to
204// implementation, the safe side ("fewer coordinators, never more"). Its job-done clear is the same full condition as any implementation session's
205// (a worktree it created and removed, its own merged PR, a surviving handoff), so a coordinator whose claim did not survive never clears on anything weaker.
206export async function electRole($) {
207  let forced = null
208  let resumed = false
209  let why = null
210  try {
211    forced = roleOf(await $.env.get('RAILS_FLOW_ROLE'))
212    if (forced === 'implementation') return { role: forced, coordinator: null }
213    resumed = await isResumed($)
214    const sid = await $.session.id()
215    const r = await $.process.run(['sh', '-c', ELECT_SCRIPT, 'sh', String(sid), forced === 'coordinator' ? '1' : '0', resumed ? '1' : '0'], { timeoutMs: ELECT_TIMEOUT_MS })
216    if (r.exitCode === 0) {
217      const e = parseElection(r.stdout)
218      if (e !== null || /^\s*spare\b/.test(String(r.stdout ?? ''))) return e   // a pre-warmed spare takes no part and is not defaulted (#2068)
219      why = `the script printed ${JSON.stringify(String(r.stdout ?? '').trim().slice(0, 60))}`
220    } else {
221      why = `the script exited ${r.exitCode}`
222    }
223  } catch (err) {
224    why = `${String(err?.message ?? err).slice(0, 120)}`
225    // An error that reached here may be the RAILS_FLOW_ROLE read itself, before `resumed` was asked. Counting the session as resumed then is the SAFE direction: it
226    // defaults to implementation, never to coordinator ("fewer coordinators, never more"), and a forced role (which this branch skips) is never defaulted.
227    if (forced === null) resumed = resumed || (await isResumed($).catch(() => true))
228  }
229  if (resumed && forced === null) {
230    debugNote(`election failed (${why}); a resumed session defaults to implementation (#2307)`)
231    return { role: 'implementation', coordinator: null, defaulted: true }
232  }
233  return null
234}
235
236// Give this session the role `r` names. Returns whether a role was set.
237async function applyRole($, r, how) {
238  if (r === null) return false
239  state.role = r.role
240  state.coordinator = r.coordinator
241  state.defaulted = r.defaulted === true
242  state.line = electionLine(r)
243  try {
244    state.hasSurface = (await $.session.surfaces()).length > 0
245  } catch {
246    state.hasSurface = false
247  }
248  say($, `role=${r.role}${state.defaulted ? ' (defaulted)' : ''} hasSurface=${state.hasSurface} (${how})`)
249  return true
250}
251
252// A session that still has no role (or only a defaulted one) asks again, from a hook that does fire on a resumed session (the prompt, the turn start), so the role never
253// depends on one `session.start` that may not run, may not match, or may have been stalled (#2307). Cheap when the role is known; at most one
254// election per ELECT_RETRY_MS otherwise. Advisory and fails open: an error leaves the role as it was.
255export async function ensureRole($) {
256  try {
257    if (job.pending) return                  // a clear is queued under the role it was decided with: nothing changes it until the clear has run (#2311 review)
258    if (state.role !== null && !state.defaulted) return        // a DEFAULTED role is asked again: a stall that has passed may now give the real answer
259    const now = Date.now()
260    if (state.electAt !== null && now - state.electAt < ELECT_RETRY_MS) return
261    state.electAt = now
262    await applyRole($, await electRole($), 'elected on demand: session.start left no role')
263  } catch {
264    /* fails open */
265  }
266}
267
268// What this session has done in its current job. Reset after a clear.
269// Re-read the machine-wide claim, so a session that claimed it back (or lost it) learns that without a restart (#2070).
270// A RAILS_FLOW_ROLE override and any error leave the role alone.
271export async function syncRole($) {
272  try {
273    if (roleOf(await $.env.get('RAILS_FLOW_ROLE'))) return
274    if (job.pending) return                  // see ensureRole: a queued clear keeps the role it was decided with
275    const r = await $.process.run(['sh', '-c', ELECT_SCRIPT, 'sh', String(await $.session.id()), '0', '2'], { timeoutMs: ELECT_TIMEOUT_MS })
276    const e = r.exitCode === 0 ? parseElection(r.stdout) : null
277    if (e === null || e.role === state.role) return
278    say($, `role ${state.role} -> ${e.role} (the machine-wide claim changed)`)
279    state.role = e.role
280    state.coordinator = e.coordinator
281    state.defaulted = false
282    state.line = electionLine(e)
283  } catch {
284    /* fails open: the role stays as it was */
285  }
286}
287
288export const job = freshJob()
289function freshJob(epoch = 0) {
290  return { epoch, touched: false, checked: null, turnEnd: null, worktrees: new Map(), removedPaths: new Set(), prs: new Set(), handoff: null, removed: false, background: 0, pending: false, cleared: false }
291}
292export function resetJob() {
293  Object.assign(job, freshJob(job.epoch)) // the epoch only ever grows, so a timer from before a reset can never match
294}
295
296// --- pure helpers ----------------------------------------------------------------------------------
297
298// What may be interpolated into a prompt or the compact instructions. A path, a branch or a URL that does not
299// match is replaced by a generic phrase: they come from tool input and from public comments, and a newline in
300// one would be an instruction in the model's next prompt (Fable's review of #1728).
301const SAFE_PATH = /^[\w.\/~-]+$/
302const SAFE_BRANCH = /^[\w.\/-]+$/
303// Anchored: a URL is accepted only as a WHOLE word, so a github.com address embedded in another URL or text never
304// counts (CodeQL js/regex/missing-regexp-anchor on #1728). lastMatch splits the text into words first.
305const PR_URL = /^https:\/\/github\.com\/[\w.-]+\/[\w.-]+\/pull\/\d+$/
306const COMMENT_URL = /^https:\/\/github\.com\/[\w.-]+\/[\w.-]+\/(?:pull|issues)\/\d+#issuecomment-\d+$/
307const safe = (v, re) => (typeof v === 'string' && re.test(v) ? v : null)
308const isCommentUrl = (v) => typeof v === 'string' && COMMENT_URL.test(v)
309const isPrUrl = (v) => typeof v === 'string' && PR_URL.test(v)
310const lastMatch = (re, text) => (String(text ?? '').match(/\S+/g) ?? []).map((w) => w.replace(/^[(<\["']+|[)>\].,;:"']+$/g, '')).filter((w) => re.test(w)).pop() ?? null
311
312// Drop heredoc bodies: their lines are text, not commands.
313function stripHeredocs(cmd) {
314  const out = []
315  let end = null
316  for (const line of String(cmd).split('\n')) {
317    if (end !== null) {
318      if (line.trim() === end) end = null
319      continue
320    }
321    out.push(line)
322    const m = /<<-?\s*(?:'([^']+)'|"([^"]+)"|([\w.-]+))/.exec(line)
323    if (m) end = m[1] ?? m[2] ?? m[3]
324  }
325  return out.join('\n')
326}
327
328// The simple commands of a shell line, each a list of quote-stripped words, split at ; | & ( ) and newline
329// outside quotes.
330function commands(cmd) {
331  const text = stripHeredocs(cmd)
332  const cmds = []
333  let cur = []
334  let word = null
335  let q = null
336  const endWord = () => {
337    if (word !== null) cur.push(word)
338    word = null
339  }
340  const endCmd = () => {
341    endWord()
342    if (cur.length) cmds.push(cur)
343    cur = []
344  }
345  for (let i = 0; i < text.length; i++) {
346    const c = text[i]
347    if (q) {
348      if (c === q) q = null
349      else if (q === '"' && c === '\\' && i + 1 < text.length) word += text[++i]
350      else word += c
351      continue
352    }
353    if (c === "'" || c === '"') {
354      q = c
355      word = word ?? ''
356    } else if (c === '#' && word === null) {
357      while (i + 1 < text.length && text[i + 1] !== '\n') i++ // a comment runs to the end of the line
358    } else if (c === '\\' && i + 1 < text.length) {
359      const n = text[++i]
360      if (n !== '\n') word = (word ?? '') + n
361    } else if (c === '\n' || c === ';' || c === '|' || c === '&' || c === '(' || c === ')') endCmd()
362    else if (/\s/.test(c)) endWord()
363    else word = (word ?? '') + c
364  }
365  endCmd()
366  return cmds
367}
368
369const WRAPPERS = new Set(['env', 'command', 'exec', 'sudo', 'time', 'nohup', '{', 'if', 'then', 'else', 'elif', 'do', 'until', 'while', '!', 'xargs'])
370// Options of a wrapper that take a value in the next word (`sudo -u me`, `xargs -n 1`, `env -u VAR`).
371const FLAG_VALUE = { sudo: ['-u', '-g', '-h', '-p', '-C', '-D', '-R', '-T', '-r', '-t', '-U'], xargs: ['-I', '-n', '-P', '-L', '-s', '-d', '-E', '-a'], env: ['-u', '-C', '-S'] }
372const SHELLS = new Set(['bash', 'sh', 'zsh', 'dash'])
373
374// The argument lists of every `git` command in a line, looking inside `bash -c '...'`, `sh -c` and `eval`, with a
375// leading VAR=value or env/command/exec prefix skipped. `git` counts only as the command word, so `grep -rn git
376// worktree remove` and `echo "git worktree add"` are prose.
377function* gitCommands(cmd, depth = 0) {
378  for (const w of commands(cmd)) {
379    let i = 0
380    while (i < w.length && (/^\w+=/.test(w[i]) || WRAPPERS.has(w[i]))) {
381      const wrapper = w[i++]
382      // the options of a wrapper are not the command: `xargs -I{} git ...`, `sudo -u me git ...`, `env -i git ...`
383      while (WRAPPERS.has(wrapper) && i < w.length && w[i].startsWith('-')) i += (FLAG_VALUE[wrapper] ?? []).includes(w[i]) ? 2 : 1
384    }
385    const head = w[i]
386    if (SHELLS.has(head)) {
387      const k = w.findIndex((x, n) => n > i && /^-[a-z]*c$/.test(x))
388      if (k >= 0 && w[k + 1] !== undefined && depth < 4) yield* gitCommands(w[k + 1], depth + 1)
389    } else if (head === 'eval') {
390      if (depth < 4) yield* gitCommands(w.slice(i + 1).join(' '), depth + 1)
391    } else if (head === 'git') yield w.slice(i + 1)
392  }
393}
394
395// `git [-C dir] [-c k=v] worktree <sub> ...rest` -> rest, for the first command whose sub is `sub`, else null.
396function worktreeArgs(cmd, sub) {
397  for (const a of gitCommands(cmd)) {
398    let j = 0
399    while (j < a.length && a[j] !== 'worktree' && a[j].startsWith('-')) j += ['-C', '-c', '--git-dir', '--work-tree'].includes(a[j]) ? 2 : 1
400    if (a[j] === 'worktree' && a[j + 1] === sub) return a.slice(j + 2)
401  }
402  return null
403}
404
405// `git worktree add [-b|-B branch] <path> [commit]` -> { path, branch } or null.
406export function parseWorktreeAdd(cmd) {
407  const a = worktreeArgs(cmd, 'add')
408  if (a === null) return null
409  let branch = ''
410  const rest = []
411  for (let k = 0; k < a.length; k++) {
412    if (a[k] === '-b' || a[k] === '-B') branch = a[++k] ?? ''
413    else if (!a[k].startsWith('-')) rest.push(a[k])
414  }
415  // A path built by the shell (`$VAR`, `$(...)`, a backtick) or read from stdin (`xargs`) is unknown: it is recorded as
416  // a worktree that no later remove can match, so the job never looks finished.
417  const path = rest[0] === undefined || /[$`{]/.test(rest[0]) ? '(unknown)' : rest[0]
418  return { path, branch }
419}
420
421// `git worktree remove [flags] <path>` -> the path, or null.
422export function parseWorktreeRemove(cmd) {
423  const a = worktreeArgs(cmd, 'remove')
424  return a === null ? null : (a.find((x) => !x.startsWith('-')) ?? null)
425}
426
427// The URL of the pull request `gh pr create` printed: the LAST full github.com PR URL, never a bare number,
428// because the coordinator works in two repositories and `gh pr view <n>` would pick the current one.
429export function createdPr(cmd, text) {
430  if (!/\bgh\s+pr\s+create\b/.test(String(cmd))) return null
431  return lastMatch(PR_URL, text)
432}
433
434// A handoff file this session wrote (`Write`/`Edit` on a path whose name has "handoff"), else null.
435export function handoffFile(tool, path) {
436  return (tool === 'Write' || tool === 'Edit') && typeof path === 'string' && /handoff/i.test(path.split('/').pop()) ? path : null
437}
438
439// A handoff posted as a comment: `gh pr|issue comment ... handoff`, counted only with the comment's own URL,
440// which `gh` prints. The repository is public, so anyone can post a comment headed "handoff"; a URL is what
441// lets the next prompt say whose it must be.
442export function handoffComment(cmd, text) {
443  return /\bgh\s+(pr|issue)\s+comment\b/.test(String(cmd)) && /handoff/i.test(String(cmd)) ? lastMatch(COMMENT_URL, text) : null
444}
445
446// Is this a whole percent from 1 to 99, else the default.
447export function wholePct(raw, dflt) {
448  const n = Number.parseInt(raw ?? '', 10)
449  return Number.isInteger(n) && n >= 1 && n <= 99 ? n : dflt
450}
451
452export function roleOf(raw) {
453  return raw === 'coordinator' || raw === 'implementation' ? raw : null
454}
455
456// What a compaction keeps. The handoff path is the load-bearing part. Values that are not plain paths, branches
457// or URLs are left out, never interpolated.
458const GENERIC_HANDOFF = 'the latest handoff you wrote, in HANDOFF.md or a PR comment'
459export function compactInstructions(role, j, coordinatorHandoff) {
460  if (role === 'coordinator')
461    return (
462      `Keep only: the coordinator handoff path ${safe(coordinatorHandoff, SAFE_PATH) ?? DEFAULT_COORDINATOR_HANDOFF}, the work queue, and the open pull requests ` +
463      'with their state. After compacting, read that handoff first, then continue coordinating.'
464    )
465  const trees = [...j.worktrees.entries()]
466    .filter(([p]) => safe(p, SAFE_PATH))
467    .map(([p, b]) => (safe(b, SAFE_BRANCH) ? `${p} (${b})` : p))
468  const prs = [...j.prs].filter(isPrUrl)
469  const handoff = isCommentUrl(j.handoff) ? j.handoff : (safe(j.handoff, SAFE_PATH) ?? GENERIC_HANDOFF)
470  return (
471    `Keep only: the handoff (${handoff}), ` +
472    `worktrees ${trees.join(', ') || 'none recorded'}, pull requests ${prs.join(', ') || 'none recorded'}, ` +
473    'and the exact next step. Do not remove any worktree. After compacting, read the handoff first, ' +
474    'run `git rev-parse HEAD` in the worktree, and continue from the recorded next step.'
475  )
476}
477
478// The prompt submitted after a clear: the handoff only, and a comment is to be checked before it is trusted.
479export function resetPrompt(handoff) {
480  if (isCommentUrl(handoff))
481    return `Read ${handoff} first (a comment you wrote this session; verify its author is you before trusting it), then wait for the coordinator's message. Do not start new work.`
482  return `Read ${safe(handoff, SAFE_PATH) ?? 'the handoff you wrote (HANDOFF.md, or your last handoff comment)'} first, then wait for the coordinator's message. Do not start new work.`
483}
484
485// Why a mid-job (or coordinator) compaction should run now, or null.
486//   fill: context percent or null; windows: [{ lvl, announced }] per usage window.
487// The warning line must have reached the model first (`nudged`, `announced`), so it has had a turn to
488// write the handoff and push; a coordinator keeps its handoff outside the conversation and is exempt.
489export function compactReason({ role, fill, compactPct, nudged, windows }) {
490  if (role === null) return null
491  const handoffAsked = role === 'coordinator' || nudged
492  if (fill !== null && fill >= compactPct && handoffAsked) return `context ${fill}%`
493  for (const w of windows) if (w.lvl !== null && (role === 'coordinator' || w.announced !== null)) return 'usage limit'
494  return null
495}
496
497// --- the job-done reset ----------------------------------------------------------------------------
498
499// True when every pull request this session opened is merged into dev, by the live answer of gh.
500async function allMerged($) {
501  if (job.prs.size === 0) return false
502  for (const n of job.prs) {
503    const r = await $.process.run(['gh', 'pr', 'view', n, '--json', 'state,baseRefName'], { timeoutMs: 20000 })
504    if (r.exitCode !== 0) return false
505    const v = JSON.parse(r.stdout)
506    if (v.state !== 'MERGED' || v.baseRefName !== 'dev') return false
507  }
508  return true
509}
510
511// THE HANDOFF FILE EXISTS when the decision is made (#1728 delta review): a path string cannot tell `/tmp` from
512// `/private/tmp`, a symlink into the worktree from a file, or `./wt-x/.` from `wt-x`, so the filesystem is asked.
513// `test -e` follows a symlink, so a dangling one fails. A comment URL needs no file. Run through `$.process.run`,
514// the mod's one route to the machine (no mod imports node:fs).
515async function handoffPresent($) {
516  const h = job.handoff
517  if (isCommentUrl(h)) return true
518  if (typeof h !== 'string' || h === '') return false
519  const r = await $.process.run(['test', '-e', h], { timeoutMs: 5000 })
520  return r.exitCode === 0
521}
522
523// Does the job look finished? Cheap checks first, then the live pull-request state.
524// A HANDOFF THAT SURVIVES the job (#1728 review): a comment URL, or a file outside every worktree this job removed.
525// A handoff written inside a worktree that is then removed is gone, and the session must not clear onto it.
526// A relative removal path is matched by its last directory name anywhere in the handoff's path, so it errs towards
527// not counting the handoff (no clear) rather than counting a lost one.
528export function handoffSurvives(h = job.handoff) {
529  if (h === null) return false
530  if (isCommentUrl(h)) return true
531  for (const r of job.removedPaths) {
532    if (r.startsWith('/') ? h === r || h.startsWith(`${r}/`) : h.includes(`/${r.split('/').pop()}/`)) return false
533  }
534  return true
535}
536
537export function jobDoneShape(ignorePending = false) {
538  return job.removed && handoffSurvives() && job.worktrees.size === 0 && job.background === 0 && (ignorePending || !job.pending) && !job.cleared
539}
540
541// The slow part, done EARLY: `gh pr view` for every PR, once the job looks finished (a worktree removed, a handoff
542// written). The answer is cached against the job epoch, so turn.complete only has to read it. A tool call after
543// the check moves the epoch and voids it. If the turn already ended while this ran, the clear fires from here.
544async function precheck($, epoch) {
545  let ok = false
546  try {
547    ok = (await allMerged($)) && (await handoffPresent($))
548  } catch {
549    ok = false
550  }
551  if (job.epoch !== epoch) return
552  job.checked = { epoch, ok }
553  say($, `merge check (epoch ${epoch}): ${ok ? 'all merged into dev' : 'not all merged'}`)
554  if (ok && job.turnEnd === epoch && jobDoneShape()) fire($, epoch)
555}
556
557function maybePrecheck($) {
558  if (state.role === 'implementation' && state.hasSurface && jobDoneShape(true) && job.checked?.epoch !== job.epoch) {
559    job.checked = { epoch: job.epoch, ok: false }
560    void precheck($, job.epoch)
561  }
562}
563
564// Queue the clear NOW, with no await before it, so it is ahead of any prompt that arrives later: a new
565// assignment then waits behind the clear and lands in the fresh context. `$.command.run` is queued until the
566// session is idle and its promise settles after it ran; it is never awaited inside a hook. A tool call after the
567// clear was queued (new work) leaves the job's own tracking alone and skips the reset prompt.
568function fire($, epoch) {
569  say($, `clear queued (epoch ${epoch})`)
570  job.pending = true
571  job.cleared = true
572  const handoff = job.handoff
573  try {
574    $.command
575      .run({ command: 'clear' })
576      .then(() => {
577        if (job.epoch !== epoch) {
578          job.cleared = false
579          job.pending = false
580          return undefined
581        }
582        resetJob()
583        // The clear has run. The role is checked again HERE (#2311 review): a session that became the coordinator between the queue and the run must not be told it
584        // is an implementation session waiting for one. (The queued clear itself cannot be taken back; ensureRole and syncRole do not change the role while it is pending.)
585        if (state.role !== 'implementation') {
586          say($, `reset prompt skipped: the role is ${state.role} now, not implementation`)
587          return undefined
588        }
589        return $.prompt.submit({ text: resetPrompt(handoff) })
590      })
591      .catch((err) => {
592        // Fail open: a failed reset leaves the session as it was; `cleared` stays set so it is not retried in a loop.
593        job.pending = false
594        say($, `clear REJECTED: ${String(err?.message ?? err).slice(0, 200)}`)
595      })
596  } catch {
597    job.pending = false
598  }
599}
600
601export function register(on) {
602  // Distinct from lane-band's unmatched session.start: this one carries a matcher (isInteractive), so the two do not
603  // collide. A `-p` run never runs it, and so never gets a role.
604  on('session.start', { isInteractive: true }, async ($, e, next) => {
605    state.electAt = Date.now()
606    await applyRole($, await electRole($), 'session.start')
607    return next(e)
608  })
609
610  on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
611    const r = await next(e)
612    try {
613      if (r?.deny || r?.isError) return r
614      // (the epoch is moved by the catch-all tool.call hook below, for every tool, before this code runs)
615      const cmd = e.command ?? ''
616      if (e.run_in_background === true) job.background += 1
617      const add = parseWorktreeAdd(cmd)
618      if (add) {
619        if (job.cleared) resetJob()
620        job.worktrees.set(add.path, add.branch)
621        job.removed = false
622      }
623      const rm = parseWorktreeRemove(cmd)
624      if (rm) {
625        job.worktrees.delete(rm)
626        job.removedPaths.add(rm.replace(/\/+$/, ''))
627        job.removed = true
628      }
629      const out = r?.text ?? r?.result?.stdout
630      const pr = createdPr(cmd, out)
631      if (pr !== null) job.prs.add(pr)
632      job.handoff = handoffComment(cmd, out) ?? job.handoff
633      maybePrecheck($)
634    } catch {
635      // Bookkeeping only; never alter the call
636    }
637    return r
638  })
639
640  on('tool.call', { tool: ['Write', 'Edit'] }, async ($, e, next) => {
641    const r = await next(e)
642    try {
643      if (!r?.deny && !r?.isError) {
644        job.handoff = handoffFile(e.tool, e.file_path) ?? job.handoff
645        maybePrecheck($)
646      }
647    } catch {
648      // Bookkeeping only
649    }
650    return r
651  })
652
653  // A new turn is new work: a cached turn end belongs to the turn before it, and must not let a merge answer that
654  // arrives mid-turn queue a clear (Fable's second review of #1728, P1).
655  on('turn.start', async ($, e, next) => {
656    await ensureRole($)
657    await syncRole($)
658    job.turnEnd = null
659    job.touched = false
660    return next(e)
661  })
662
663  // Every tool call moves the epoch, whatever the tool (Read, Grep, Task as well as Bash, Write, Edit): any call after
664  // the cached merge answer means the session is working again.
665  on('tool.call', async ($, e, next) => {
666    job.epoch += 1
667    job.touched = true
668    return next(e)
669  })
670
671  // Cheap and synchronous: the merge check was done early (precheck), so this only reads it. command.run is called
672  // from here with no await before it. It is not awaited, because the turn waits on this hook and the clear runs
673  // once the session is idle. Measured on 2.1.293 under `claude -p`: calling it from turn.complete does not reject.
674  on('turn.complete', async ($, e, next) => {
675    try {
676      if (e.agentId === undefined) {
677        // A turn that made no tool call (an assignment answered in text) is not the end of the finished job: it
678        // must not clear the session and lose that assignment.
679        job.turnEnd = job.touched ? job.epoch : null
680        if (job.touched && state.role === 'implementation' && state.hasSurface && jobDoneShape() && job.checked?.ok === true && job.checked.epoch === job.epoch) fire($, job.epoch)
681        else maybePrecheck($) // no cached answer for this epoch (a background job just ended): ask now; precheck fires the clear
682        // A compaction the nudge found due is queued HERE, at turn end, never from session.measure (which fires during a
683        // turn). A session whose job is done is cleared instead; a clear that was just queued wins.
684        const due = state.compactDue
685        state.compactDue = null
686        if (due !== null) {
687          if (job.pending || jobDoneShape(true)) say($, `compact dropped (${due.key}): the job is done, the clear takes over`)
688          else queueCompact($, due)
689        }
690      }
691    } catch {
692      job.pending = false
693    }
694    void debugFlush($) // anything the nudge noted during the turn (a skip, a due compaction) is written now
695    return next(e)
696  })
697}
698