Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 17 additions & 4 deletions docs/design.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,9 @@ In scope now:
- Long-lived agents for a host that runs them under a service manager. `berth serve` runs a yard's backend under the service manager, and `sign-on` opens each agent from a caller that is not a berth.
- Compaction at rest, by a mod in the plugin.
- Waking a steward that a multiplexer resumed, by the same mod.
- Reporting a session's agent state and session id to the herdr app, by the same mod.

Later: the integrations that serve interactive panes only, such as agent-state hooks, a statusline, review tabs and window-manager keybinds. Until the port serves them, they call their multiplexer directly.
Later: the integrations that serve interactive panes only, such as a statusline, review tabs and window-manager keybinds. Until the port serves them, they call their multiplexer directly.

## Layers

Expand All @@ -23,6 +24,7 @@ Later: the integrations that serve interactive panes only, such as agent-state h
| `sign-on` | Launches Claude Code in a berth and gets it past its startup gate, or gets a seat already starting in one past it | `berth` |
| Compaction mod | Compacts a session at rest before it runs low on context | Claude Code |
| Resume hook | Sends a resumed steward through its whole wake ritual | Claude Code |
| App status hook | Reports a session's agent state and session id to its herdr app terminal | Claude Code |
| Skills | `steward`, `worker`, `muster` and `tally` | `sign-on`, `berth` |

The port knows only terminal mechanics. It knows nothing about Claude Code. The startup gate belongs to Claude Code, so it lives in `sign-on`. Compaction is useful without any orchestration, so it runs inside every session that loads the plugin, in a berth or not, and does not use the port.
Expand Down Expand Up @@ -105,13 +107,14 @@ Where a verb needs the caller, such as a worker's opener or the opener a berth o

### Contract for outside consumers

A product outside boatyard may depend on three things, and on nothing else of boatyard's:
A product outside boatyard may depend on four things, and on nothing else of boatyard's:

- **The three variables** above, inherited by every process a berth runs.
- **`berth list`'s JSON:** an array with one object per berth, each holding exactly the fields `id`, `label`, `relationship`, `parent`, `state`, `agent_state` and `agent_session`, with the values the verbs table and *Berth and agent states* give them.
- **The `claude.session` label:** on a herdr app terminal running a Claude Code session that loads the plugin, the hc label `claude.session` holds that session's id, as *Agent state under the herdr app* says.
- **The efforts output:** the JSON lines that `skills/tally/efforts` prints, one per open effort, each holding at least the fields `project`, `top`, `slug`, `steward`, `ready` and `restart`, with the meanings the tally skill gives them. Its other fields, `also`, `status`, `gates` and `asks`, are not part of the contract.

Dropping, renaming or changing the meaning of a variable or a field breaks the contract, and so does a new value that a consumer could not have expected. Boatyard cuts no releases, so the pull request making such a change marks it breaking with a `!` in its title, and the commit it lands as carries the mark on `main`. The port contract suite fails when a field is added, dropped or renamed, so no change to the shape lands unnoticed. The tally efforts check fails when one of the six efforts fields is dropped or renamed.
Dropping, renaming or changing the meaning of a variable, a field or the label breaks the contract, and so does a new value that a consumer could not have expected. Boatyard cuts no releases, so the pull request making such a change marks it breaking with a `!` in its title, and the commit it lands as carries the mark on `main`. The port contract suite fails when a field is added, dropped or renamed, so no change to the shape lands unnoticed. The tally efforts check fails when one of the six efforts fields is dropped or renamed.

### Errors

Expand Down Expand Up @@ -187,6 +190,16 @@ A multiplexer that restores its session resumes each seat's conversation in a ne
- **On a resume of a marked session, the mod submits one message.** It tells the seat to run the wake ritual's reachable half, then its reconstruct half. A worker, a person's session, a fresh start and a compaction get nothing.
- **The message waits until the session's interface has mounted.** Claude Code runs its start hooks before that, and refuses a prompt until it has. A resumed session with no interface, such as a `-p` run, gets nothing.

## Agent state under the herdr app

The herdr app's backend, herdr-core, takes a terminal's agent state only from what its program reports over OSC 7501. It never reads the screen. Claude Code reports its own state, but only when the terminal answers its startup probe within two seconds. A slow start, such as a resume with a large transcript, misses the probe, and the session reports nothing for its whole life. So the plugin's mod reports for it.

- **The mod reports only what Claude Code already knows.** On Claude Code's own events it writes the state to the session's terminal: idle at a session start, working at a prompt, blocked on a permission prompt or a question to the person, working again once the blocked tool has run, done when the turn ends, error when it fails, and clear when the session ends. A compaction reports nothing, because it can come in the middle of a turn. An idle prompt after an interrupted turn reports idle.
- **The report goes to the Claude Code process's own tty.** A hook's child process has no controlling terminal, so it writes to the device that `ps` names for the session's process.
- **The mod records the session id on the terminal** as the hc label `claude.session`, at each session start but a compaction's, so a `/clear` relabels the terminal with its new id. Like herdr's own agent session, it stays after the agent leaves.
- **It acts only in an app terminal.** It acts where `HC_TERMINAL_ID` is set and `HERDR_PANE_ID` is not. herdr panes inherit the app terminal's variables when herdr runs inside one, and herdr has its own integration.
- **A report that fails is logged to the debug log,** and the session carries on.

## Skills

| Skill | Role | Invocation |
Expand Down Expand Up @@ -223,7 +236,7 @@ Pull requests are GitHub's. The skills read, wait on and merge them with `gh` an
- **Port contract suite.** One suite states what every adapter must do: open in each relationship, list, name, send-text, send-key, wait-text, read, state, agent state across all three agent states and none, close, and the cascade when an independent berth closes. It runs against every adapter.
- For herdr, it runs a throwaway server with `HOME` redirected and every `HERDR_*` variable unset. An inherited `HERDR_SOCKET_PATH` would otherwise drive the live session. The server runs inside the nix build sandbox, so the suite is a flake check.
- herdr treats a process named `claude` as an agent and reads its state from the screen. The suite drives the states with a stand-in process of that name, not with Claude Code.
- **Unit tests.** The mod's compaction rule and its rule for a resumed steward have their own tests, run by `claude plugin test` against a stand-in engine. So does each adapter's mapping from backend states to the port's agent states, including the herdr parked-on-background-work and lost-agent corrections.
- **Unit tests.** The mod's compaction rule, its rule for a resumed steward and its reports to the herdr app have their own tests, run by `claude plugin test` against a stand-in engine. So does each adapter's mapping from backend states to the port's agent states, including the herdr parked-on-background-work and lost-agent corrections.
- **End to end.** One real effort runs on `steward` and `worker`.

## Open decisions
Expand Down
146 changes: 146 additions & 0 deletions hooks/herdr-app-report.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,146 @@
import type { EngineInterface, On } from 'claude-code'
import { expect, test } from 'claude-code/testing'

const ESC = '\x1b'
const report = (fields: string) => `${ESC}]7501;:${fields}:app=claude-code${ESC}\\`

const IN_APP_TERMINAL = { HC_TERMINAL_ID: 't7' }

// The engine beneath the plugin: a Claude Code process whose pid is 4242, in a
// terminal whose environment is `env`. A test reads back the status reports
// written to that process's tty and the hc commands the plugin ran.
function seat(on: On, env: Record<string, string> = IN_APP_TERMINAL) {
const world = { reports: [] as string[], hc: [] as string[][] }
on('store.get', () => ({ value: undefined }))
on('env.get', (_$, e) => ({ value: env[e.name] }))
on('process.hookEnv', () => ({ value: { CLAUDE_PID: '4242' } }))
on('process.run', (_$, e) => {
const [program, ...args] = e.argv
if (program === 'hc') world.hc.push(args)
else if (program === 'sh' && args[3] === '4242') world.reports.push(args[4])
return { value: { exitCode: 0, stdout: '', stderr: '' } }
})
on('tool.call', () => ({ result: {} }))
for (const event of ['SessionStart', 'UserPromptSubmit', 'PostToolUse', 'Notification', 'Stop', 'StopFailure', 'SessionEnd'] as const) {
on(`classic.${event}`, () => ({}))
}
return world
}

const SESSION = { session_id: 'session-1' }

async function startTurn($: EngineInterface) {
await $.classic.SessionStart({ ...SESSION, source: 'resume' })
await $.classic.UserPromptSubmit({ ...SESSION, prompt: 'go' })
}

test('a session start reports idle and labels the terminal with the session id', async ($, on) => {
const app = seat(on)
await $.classic.SessionStart({ ...SESSION, source: 'resume' })
expect(app.reports).toEqual([report('state=idle')])
expect(app.hc).toEqual([['label', 't7', 'claude.session=session-1']])
})

test('a cleared session labels the terminal with its new session id', async ($, on) => {
const app = seat(on)
await $.classic.SessionStart({ ...SESSION, source: 'startup' })
await $.classic.SessionStart({ session_id: 'session-2', source: 'clear' })
expect(app.hc.at(-1)).toEqual(['label', 't7', 'claude.session=session-2'])
})

test('a compaction reports nothing, as it may come in the middle of a turn', async ($, on) => {
const app = seat(on)
await startTurn($)
await $.classic.SessionStart({ ...SESSION, source: 'compact' })
expect(app.reports.at(-1)).toBe(report('state=working'))
expect(app.hc.length).toBe(1)
})

test('a turn reports working, then done', async ($, on) => {
const app = seat(on)
await startTurn($)
await $.classic.Stop({ ...SESSION, stop_hook_active: false })
expect(app.reports.slice(1)).toEqual([report('state=working'), report('state=done')])
})

test('a turn that fails reports error', async ($, on) => {
const app = seat(on)
await startTurn($)
await $.classic.StopFailure({ ...SESSION, error: 'server_error' })
expect(app.reports.at(-1)).toBe(report('state=error'))
})

test('a permission prompt reports blocked, and the tool that runs after it reports working', async ($, on) => {
const app = seat(on)
await startTurn($)
await $.classic.Notification({ ...SESSION, message: 'needs permission', notification_type: 'permission_prompt' })
await $.classic.PostToolUse({ ...SESSION, tool_name: 'Bash', tool_input: {}, tool_response: {}, tool_use_id: 'u1' })
expect(app.reports.slice(2)).toEqual([report('state=blocked:kind=permission'), report('state=working')])
})

test('a question to the person reports blocked on a question', async ($, on) => {
const app = seat(on)
await startTurn($)
await $.tool.call({ tool: 'AskUserQuestion', questions: [] })
expect(app.reports.at(-1)).toBe(report('state=blocked:kind=question'))
})

test('an ordinary tool call reports nothing', async ($, on) => {
const app = seat(on)
await startTurn($)
await $.tool.call({ tool: 'Bash', command: 'ls' })
await $.classic.PostToolUse({ ...SESSION, tool_name: 'Bash', tool_input: {}, tool_response: {}, tool_use_id: 'u1' })
expect(app.reports.length).toBe(2)
})

test('an idle prompt after an interrupted turn reports idle', async ($, on) => {
const app = seat(on)
await startTurn($)
await $.classic.Notification({ ...SESSION, message: 'waiting', notification_type: 'idle_prompt' })
expect(app.reports.at(-1)).toBe(report('state=idle'))
})

test('an idle prompt after a finished turn leaves it done', async ($, on) => {
const app = seat(on)
await startTurn($)
await $.classic.Stop({ ...SESSION, stop_hook_active: false })
await $.classic.Notification({ ...SESSION, message: 'waiting', notification_type: 'idle_prompt' })
expect(app.reports.at(-1)).toBe(report('state=done'))
})

test('a session end clears the status', async ($, on) => {
const app = seat(on)
await startTurn($)
await $.classic.SessionEnd({ ...SESSION, reason: 'prompt_input_exit' })
expect(app.reports.at(-1)).toBe(report('state=clear'))
})

test('outside an app terminal it does nothing', async ($, on) => {
const app = seat(on, {})
await startTurn($)
expect(app.reports).toEqual([])
expect(app.hc).toEqual([])
})

test('under herdr it does nothing, even inside an app terminal', async ($, on) => {
const app = seat(on, { ...IN_APP_TERMINAL, HERDR_PANE_ID: 'p1' })
await startTurn($)
expect(app.reports).toEqual([])
expect(app.hc).toEqual([])
})

test('a report that cannot be written leaves the session running, and says why in the debug log', async ($, on) => {
const logged: string[] = []
on('ui.log', (_$, e) => {
logged.push(e.text)
return { value: undefined }
})
on('store.get', () => ({ value: undefined }))
on('env.get', (_$, e) => ({ value: IN_APP_TERMINAL[e.name as keyof typeof IN_APP_TERMINAL] }))
on('process.hookEnv', () => ({ value: { CLAUDE_PID: '4242' } }))
on('process.run', () => ({ value: { exitCode: 1, stdout: '', stderr: 'no tty' } }))
on('classic.SessionStart', () => ({}))
await $.classic.SessionStart({ ...SESSION, source: 'startup' })
expect(logged.length).toBe(2)
expect(logged[0]).toContain('no tty')
})
101 changes: 101 additions & 0 deletions hooks/herdr-app-report.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
import type { EngineInterface, Register } from 'claude-code'

// Claude Code reports its own status to a herdr app terminal over OSC 7501,
// but only when the terminal answers its startup probe within two seconds. A
// slow start, such as a resume with a large transcript, misses the probe and
// never reports. These hooks report the same states from Claude Code's own
// events, and record the session id as the terminal's `claude.session` label.

type State = 'idle' | 'working' | 'done' | 'blocked' | 'error' | 'clear'
type Kind = 'permission' | 'question'

const ESC = '\x1b'
const statusReport = (state: State, kind?: Kind) =>
`${ESC}]7501;:state=${state}${kind === undefined ? '' : `:kind=${kind}`}:app=claude-code${ESC}\\`

// A hook's child has no controlling terminal, so the report goes to the tty
// of the Claude Code process itself. ps names it as `pts/3` on Linux and
// `ttys003` on macOS, and `?` or `??` for none.
const WRITE_TO_TTY_OF = [
'tty=$(ps -o tty= -p "$1" | tr -d " ")',
'case "$tty" in ""|"?"|"??") echo "process $1 has no tty" >&2; exit 1;; esac',
'printf "%s" "$2" > "/dev/$tty"',
].join('\n')

// herdr runs its own integration, and its panes inherit the app terminal's
// variables when herdr itself runs inside one.
async function appTerminal($: EngineInterface): Promise<string | undefined> {
if ((await $.env.get('HERDR_PANE_ID')) !== undefined) return undefined
return $.env.get('HC_TERMINAL_ID')
}

async function run($: EngineInterface, argv: string[]) {
const what = argv[0] === 'hc' ? argv.join(' ') : 'the status report'
try {
const { exitCode, stderr } = await $.process.run(argv)
if (exitCode !== 0) $.ui.log(`herdr app: ${what} failed: ${stderr.trim()}`, { to: 'debug' })
} catch (err) {
$.ui.log(`herdr app: ${what} failed: ${String(err)}`, { to: 'debug' })
}
}

async function report($: EngineInterface, state: State, kind?: Kind): Promise<State> {
if ((await appTerminal($)) !== undefined) {
const { CLAUDE_PID } = await $.process.hookEnv()
await run($, ['sh', '-c', WRITE_TO_TTY_OF, 'sh', CLAUDE_PID, statusReport(state, kind)])
}
return state
}

export const register: Register = (on) => {
let last: State | undefined

// A compaction keeps the session id, and may come in the middle of a turn.
on('classic.SessionStart', { source: ['startup', 'resume', 'clear', 'fork'] }, async ($, e, next) => {
const terminal = await appTerminal($)
if (terminal !== undefined) {
last = await report($, 'idle')
await run($, ['hc', 'label', terminal, `claude.session=${e.session_id}`])
}
return next(e)
})

on('classic.UserPromptSubmit', async ($, e, next) => {
last = await report($, 'working')
return next(e)
})

on('tool.call', { tool: ['AskUserQuestion', 'ExitPlanMode'] }, async ($, e, next) => {
last = await report($, 'blocked', 'question')
return next(e)
})

// Nothing else reports working again once a permission is granted.
on('classic.PostToolUse', async ($, e, next) => {
if (last === 'blocked') last = await report($, 'working')
return next(e)
})

on('classic.Notification', async ($, e, next) => {
if (e.notification_type === 'permission_prompt') last = await report($, 'blocked', 'permission')
else if (e.notification_type === 'elicitation_dialog') last = await report($, 'blocked', 'question')
// A turn the person interrupted ends without a Stop.
else if (e.notification_type === 'idle_prompt' && (last === 'working' || last === 'blocked')) last = await report($, 'idle')
return next(e)
})

on('classic.Stop', async ($, e, next) => {
last = await report($, 'done')
return next(e)
})

on('classic.StopFailure', async ($, e, next) => {
last = await report($, 'error')
return next(e)
})

on('classic.SessionEnd', async ($, e, next) => {
last = await report($, 'clear')
return next(e)
})
}
2 changes: 2 additions & 0 deletions hooks/register.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import type { Register } from 'claude-code'
import { register as compactAtRest } from './compact-at-rest.ts'
import { register as herdrAppReport } from './herdr-app-report.ts'
import { register as stewardResume } from './steward-resume.ts'

export const register: Register = (on, options) => {
compactAtRest(on, options)
herdrAppReport(on, options)
stewardResume(on, options)
}