Keeps the decisions and actions an assistant is waiting on you for in the session task list: numbered D1, A1, ..., checked for a recommendation and a link…

A queue for everything your assistant is waiting on you for. Questions an assistant asks get buried in long messages and scroll away; this plugin pins each one as a numbered card (D1 for a decision, A1 for something only you can do) in a sidebar and the footer, with a recommendation you can accept in one click.

That's a real session, sped up while the assistant works. I asked Claude to plan moving a small Flask service from SQLite to Postgres without writing any code. It queued its questions as tasks, shown as cards in the sidebar, each with the answer it recommends. One click on Accept all put an answer line for every recommendation in my prompt, and one Enter settled them. What's left are the two things only I can do: tell it where the database lives, and hand over a sample of the data.
claude plugin marketplace add lokkju/skills
claude plugin install session-decisions@lokkju
Restart Claude Code. There's nothing you have to configure; the skill tells the assistant when to queue something, and the hook keeps it honest. There are two options: forge_hosts is for repositories on a self-hosted forge, and handoff_check turns off the check for work handed to you outside the queue.
The assistant creates an ordinary task with a subject in one of two forms:
| Kind | Subject | Becomes |
|---|---|---|
| Decision | DECIDE: Postgres driver? (recommend psycopg 3) [#12] | D3 DECIDE: Postgres driver? (recommend psycopg 3) [#12] |
| Action | ACTION: Provision the target database [no link] | A2 ACTION: Provision the target database [no link] |
A hook on TaskCreate assigns the label and refuses a decision with no recommendation, or any item with no link, telling the assistant what's missing. The link is an issue (#123, owner/repo#123), a merge or pull request (!45), a URL, or no link. An assistant that can't write a recommendation isn't ready to ask yet, which is the point.
● queued D3 (revised D3 where it revised a decision_add item), and ✓ D3 · <ruling> once it's settled. Click the label to open the item in full. The tool's result, the labelled subject the assistant reads, isn't drawn, so the item never shows twice; ctrl+o shows the call and its result whole. Claude Code folds a TaskCreate call into a group with the calls around it, which draws nothing on the main view, so the line draws in that group's place.● 5 decisions sits beside the mode labels. Click it to open the queue; Esc closes it.DECIDE or ACTION chip, the label, a recommends <choice> tag, the question with any qualifier under it, the link, and the item's age, which turns red after a day. An item the assistant revised after asking (its description has a Revised (<date>): ... line) shows revised <date>, so a changed recommendation doesn't slip past you. The assistant revises with TaskUpdate, or with the plugin's decision_update tool for an item it added without the task tools. The question and qualifier draw as markdown; one-line rows, chips and toasts show it as plain text.#12, !45, owner/repo#12, or no link) sits at the right end of the button row. A URL gets a line of its own under the question, as a clickable link: a GitHub issue or pull request reads owner/repo#12 and a GitHub repository owner/repo; any other URL is shown whole and wraps instead of being cut off. A plain http: URL other than localhost can't be a clickable link in Claude Code, so it's shown as dim text. When the session's repository has a remote on a forge the plugin can name, the short link and any #12, !45 or owner/repo#12 in the question are clickable too, pointing at that forge: #12 an issue (GitHub and Forgejo send it on to a pull request with that number), !45 a pull or merge request. It reads origin (or the only remote) once, at session start, and knows github.com, gitlab.com, codeberg.org, and hosts named gitlab.*, forgejo.* or gitea.*. A self-hosted forge's kind can't be told from any other name, so on any other host the references stay text unless forge_hosts names it. A repository whose remote is an SSH alias, a mirror, or otherwise not where its issues live can say where they do in its git config. On the terminal a link is an OSC 8 hyperlink, which most terminals open with a click (or ctrl/cmd+click); one without OSC 8 support shows the text alone.[more]: after the question, or after the qualifier when there is one, on its last row when there's room and on a row of its own when the text fills it. A card without [more] is the whole item. [more], or a press on the card's label, shows the item in full in the queue pane, in place of the list; from the transcript line the pane opens for it, with the keys, at any terminal width. The view has the card's top row with a ↑↓ PgUp PgDn scroll · Esc closes hint, then its buttons: Accept for a decision or Done for an action, Answer, Copy link when the link is a URL or a reference the plugin can resolve, Copy <command> for the first command in backticks, and Back to the list, scrolled where you left it with the focus on that item's label (Close when the pane opened just for this item). Under them come the question, the link, Recommended: <the full recommendation> and the whole description, drawn as markdown (lists, tables and code blocks included), ending in a dim ─ end of D3 ─ line so you can tell you've reached the bottom. Nothing is cut: the pane scrolls with the arrows, PgUp and PgDn, Home and End, and the mouse wheel, and Tab walks the buttons wherever the view is scrolled to. Accept, Done and Answer fill the prompt as the card's buttons do and leave the view; copying works on the terminal, and Claude Code has no clipboard path for the other surfaces yet. Esc closes the pane and changes nothing.Accept puts D3: go with <the recommendation> in your prompt, Done puts A2: done, and Answer puts D3: for you to finish. The details view [more] opens fills the same lines. Each press adds or replaces that item's line, so one message can answer several items; Accept all adds a line for every open recommendation. You edit and send it like any other message, and the assistant marks each item completed with a dated Ruling (2026-10-08): ... line. Completed items stay in the task list as the session's record; Settled (n) in the sidebar shows them.
A ruling can stop holding after the fact: you said "try the web JSON" for D2, and the web JSON turns out blocked. The assistant asks the new question as a new item, D5, and marks D2 with the plugin's decision_supersede tool, which adds Superseded (2026-10-26) by D5: <why> to D2's record. That works when TaskUpdate can no longer reach D2's task, as after Claude Code deletes a finished list's task files. D2 then shows as superseded (→ D2 2026-10-26 · superseded by D5) in the sidebar and as (superseded) in /decisions all, and D5's card says replaces D2: try the web JSON.
| Command | What it does |
|---|---|
/decisions | Lists the open items |
/decisions all | Adds the settled ones, with their rulings |
/decisions pane | Opens the sidebar |
/decisions reconcile | Has the assistant check every open item against the session and propose, in one table, which to close, revise or keep |
/decisions wrap | Has the assistant settle every open item before the session ends: escalate it to the tracker, carry it into the handoff, or drop it |
Long sessions leave items open after the conversation has moved past them: a question you answered without its label, an A4: done sent while the assistant was busy, a recommendation that stopped fitting once you added three more disks. /decisions reconcile prints the open items as a table (label, kind, how long each has waited, link, text), followed by every line of your own messages that names one of their labels, and asks the assistant to reconcile them.
The assistant checks each item for evidence that it's settled (your words answering it, by label or by subject; a merged pull request or closed issue it links to; a later item that supersedes it) and answers with one table: close, with your words or the forge state quoted as the ruling; update, with the new subject; or keep. It never closes an item on its own judgment, and keep is the answer whenever the evidence is ambiguous. Once you say yes, it applies every change in one message. The plugin's decision_list tool hands the assistant the same table and lines, so it can reconcile when you ask in your own words.
When a session is compacted or resumed, the assistant is reminded of what's still open, so a question asked two hours ago doesn't silently fall out of context.
Labels are session-scoped. Anything recorded outside the session (commits, issues, pull requests) carries the ruling and its date, never D3, which means nothing anywhere else.
The skill tells the assistant to queue every step only you can do, but the slip comes at the end of a long reply: a "Left for you:" list (merge these PRs, run this on each host) with none of it queued. When a reply ends, the plugin reads it for work handed to you that isn't in the queue. If it finds any, a toast names the first line (2 hand-offs not queued: Merge #41 and #42), and with your next message the assistant is told which lines they were and to queue whatever is still waiting on you. It never blocks or rewrites the reply, and costs no extra model call.
It looks for three things:
Left for you:, Next steps for you:, You'll need to:, ## What you need to do);You'll need to merge it once CI passes, left for you, your call, please merge #12, run these on each host), including the user-only steps an assistant tends to leave in prose because they never block its own work: the only thing blocking the build restart, I cannot write to Vault for you, I don't have access to the registry, say the word and I'll push, approve the SSH key prompt, put the client secret in Vault, the push needs your approval;A24 is in the queue for that, with no A24), which means the item was never created. The toast says so (A24 named but not in the queue), and the reminder tells the assistant to create it.To keep false alarms rare, it skips:
A3: rotate the key), or that an item already covers: an open item, or one queued this turn, that shares a reference (#41, !4, a URL) with it, or most of its words;if you need to roll back, you won't need to, will you need to review it first?);It'll lay out the options and the questions only you can answer, The report lists the steps you'll need to run), and only you can answer or decide with nothing after it;For you to compare, the two plans are:), and a bare Next steps:, which is usually the assistant's own plan.It reads the main conversation's replies, not a subagent's, and stays quiet while a Stop hook has the assistant continuing. Set handoff_check to false (in /config, or under options as in Forge hosts) to turn it off.
forge_hosts tells the plugin what kind of forge a host runs, for the ones it can't name itself: host=kind entries split by commas, where the kind is github, gitlab, forgejo or gitea (Gitea links the same way Forgejo does). For example:
git.lab.example.com=forgejo, code.example.com=gitlab
With that set, a repository whose origin is ssh://git@git.lab.example.com/me/demo.git links #12 to https://git.lab.example.com/me/demo/issues/12 and !4 to .../pulls/4. An entry wins over the built-in rules for its host, so gitlab.example.com=forgejo corrects a host whose name says the wrong thing. GitLab paths keep their subgroups (group/sub/proj/-/work_items/12).
Set it in /config (search for "Forge hosts"), or in ~/.claude/settings.json:
{
"pluginConfigs": {
"session-decisions@lokkju": { "options": { "forge_hosts": "git.lab.example.com=forgejo" } }
}
}
The plugin reads the remote at session start, so a change applies from the next session. An entry it can't use (no =, a URL instead of a host name, an unknown kind) is skipped, and a toast at session start names it; the other entries still apply.
forge_hosts maps a host to one kind of forge for every repository. Some repositories need their own answer: the remote is an SSH host alias (homelab-git:lokkju/demo.git) whose name doesn't resolve on the web, the remote is a mirror or a push-only URL and the issues live on another forge, or the SSH host isn't the web host (ssh.git.lab.example.com against git.lab.example.com). Two git config keys in the clone say where its references link to, and win over forge_hosts and the built-in rules:
| Key | Value |
|---|---|
tracker.web | The repository's web URL, https:// only: https://git.lab.lokkju.com/lokkju/demo. |
tracker.forge | github, gitlab, forgejo or gitea. |
git config tracker.forge forgejo
git config tracker.web https://git.lab.lokkju.com/lokkju/demo
With both set, #12 links to https://git.lab.lokkju.com/lokkju/demo/issues/12 and !4 to .../pulls/4, whatever origin says; the remote isn't read at all. Either key works alone:
tracker.web alone takes the kind from its host, as forge_hosts and the built-in rules name it, so git config tracker.web https://github.com/acme/tracker is enough for a mirror whose issues are on GitHub.tracker.forge alone keeps the remote's host and path and names its kind, for a host forge_hosts doesn't list when you'd rather not name it for every repository.A forge under a subpath works for GitHub and Forgejo, whose repositories are always the last two segments: https://code.example.org/forge/me/tool links #12 to https://code.example.org/forge/me/tool/issues/12 and other/repo#7 to https://code.example.org/forge/other/repo/issues/7. GitLab's groups nest, so its whole path is the project and the instance is taken to sit at the host's root; #12 and !4 link correctly under a subpath, but group/project#7 will miss the subpath.
The keys are ordinary git config, so they're per clone (.git/config) and never committed. That suits an SSH alias, which belongs to one machine's ~/.ssh/config. To set them for every clone that uses an alias, put them in a file that ~/.gitconfig includes for remotes with that alias (git 2.36 or later), which works for tracker.forge; tracker.web names one repository, so it belongs in each clone:
[includeIf "hasconfig:remote.*.url:homelab-git:*/**"]
path = ~/.config/git/homelab.gitconfig
The names aren't this plugin's own: forge-tracker answers the same question for its reports, and the tracker.* keys are meant for both. The plugin reads them at session start, with the remote, so a change applies from the next session. A value it can't use (an unknown kind, a URL that isn't https:// or has fewer than two path segments) is skipped, a toast at session start names it, and the plugin carries on as if that key weren't set.
Claude Code 2.1.300 or newer (MIN_CLAUDE_CODE in hooks/version.ts). On an older build the plugin says so in a toast and a transcript line, tells the assistant it's off, and stays off: no pane, footer, /decisions, labels or checks until you run claude update.
It needs function hooks, which interactive sessions and background jobs load. A plain claude -p run doesn't load them unless CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1 is set; there the skill tells the assistant to number items itself.
Function hooks also need workspace trust. A session in a folder whose trust prompt you haven't accepted runs with no hooks at all: no plugin's, and not this one, so there's no TaskCreate check and no decision_add. Claude Code 2.1.302 would start a background job in such a folder (a repo you'd just cloned, say) and run it that way for its whole life (#107); 2.1.306 refuses to start one there and tells you to run claude in the folder once first. Resuming the job after you've accepted the prompt loads the plugin. Until then the skill has the assistant keep its items as a labelled list in its replies.
Where Claude Code seats its own security plugin (cc-plugin-sec-default: on a machine with managed settings, and for Team and Enterprise organizations), that plugin runs first and sends every classic.* hook event on past the plugins you install, so this plugin's SessionStart, UserPromptSubmit and Stop hooks don't run (#120). The reminder of open items after compaction or resume goes, and so does the hand-off reminder the assistant gets with your next prompt; the skill has the assistant say so once, queue its hand-offs without waiting for a check, and list the open items itself after a compaction. The hand-off toast still shows, from the end of the turn, and labelling, the cards, the sidebar, the footer and /decisions work as usual.
Not every session gets TaskCreate. For models newer than Claude 4.x, Claude Code turns the task tools on only for background jobs, a launch tool list that names them, or CLAUDE_CODE_ENABLE_TODO_TOOLS (#4). Since Claude Code 2.1.300 the haiku alias is Haiku 5.5 on the Anthropic API, so this covers haiku as well. To get them in an ordinary session, set it in ~/.claude/settings.json:
{ "env": { "CLAUDE_CODE_ENABLE_TODO_TOOLS": "1" } }
Without them, the assistant uses the plugin's decision_add and decision_close tools instead. The items show the same way in the cards, the sidebar, the footer and /decisions; only /decisions tags them ledger, since that's the one difference you'd notice: they don't appear in ctrl+t.
A background subagent (Agent with run_in_background) never gets the task tools, even in a session that has them. Its items go through decision_add into the session's one queue, numbered after the main conversation's, so a subagent's item can be D2 after your D1; they show everywhere but ctrl+t, which lists the main conversation's D1 and not the subagent's D2. When a background subagent settles one of the main conversation's task-list items, decision_close settles it in the queue, as it does after a restart that drops the task tools. A foreground subagent has the task tools, and its items land in the main task list with the same labels.
With NO_COLOR set or TERM=dumb, chips and glyphs fall back to ASCII ([DECIDE], +, x). Otherwise the cards use Claude Code's theme colors and follow your theme.
The plugin never polls. It keeps the items in the session's plugin state and updates them from TaskCreate and TaskUpdate calls as they finish; the footer, sidebar and cards redraw from that state. It reads the task files once, at session start and after compaction or resume, to pick up items it didn't see created, and merges them with the items it already holds and the ones in its store rather than replacing them.
Label counters, creation times, the fallback ledger and a copy of every settled task-list item (completed with TaskUpdate, settled by decision_close, or marked by decision_supersede) are stored as one record in the plugin's store. A settled item outlives its task file, which Claude Code deletes once every task in the list is completed, and a session picks up its numbering and ledger again whatever happens to its id:
claude --resume, --continue and compaction keep the session id and its task list, and the record is the session's.CLAUDE_CODE_TASK_LIST_ID set, the record is keyed by that task list instead, so a session that comes back under a new id on the same list finds it. A record kept under the session id before the list was named moves under the list the first time it's read. Sessions sharing the list write the one record, keeping each other's ledger items and the higher counters.--fork-session) and has no record of its own also looks at its transcript: what decision_add, decision_update and decision_close answered there names the ledger items it had. It starts from the record whose ledger holds every one of them by label, at least one word for word, and closed wherever the transcript closed it; when it also has task files, that record's task list has to match them too. That's how a session whose items are all in the ledger finds its record, and an unrelated session in the same project, whose transcript never had those answers, is never taken for it.--fork-session gives a new id and an empty task list: its ledger items carry over through the transcript, its task-list items don't.The task tools can come and go within one session: a restart or resume can drop them, and CLAUDE_CODE_ENABLE_TODO_TOOLS brings them back. Items added with decision_add while they were missing stay ledger items when they return, and decision_close still settles them. A task-list item asked before the tools went away can't be updated with TaskUpdate, so decision_close settles it instead: the plugin marks it completed with the ruling in its own state and store, and keeps it settled when it re-reads a task file that still shows it open. While TaskUpdate is offered, decision_close refuses task-list items and points the assistant at TaskUpdate, and a status TaskUpdate sets replaces the plugin's ruling.
On VS Code and mobile there's no footer count (Claude Code only raises the footer on the terminal and des
hooks/register.tsx 1431 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { Counters, Details, Item, Kind, Loop, SessionRecord } from '../types'
5import {
6 applyUpdate,
7 age,
8 coverLabels,
9 isOpen,
10 itemFromTask,
11 listing,
12 mergeAnswers,
13 mergeHydrated,
14 nextNumber,
15 ordered,
16 reminder,
17 retitle,
18 revise,
19 replacedText,
20 replaces,
21 settle,
22 subjectOf,
23 supersede,
24 upsert,
25} from './queue'
26import { type Message, type Trail, ledgerMatches, trailOf } from './lineage'
27import { githubShort, isShortLink, linkHref, plainText } from './markdown'
28import { MORE, detailsExtras, hasMore, moreSplit } from './more'
29import { type Forge, type ForgeHosts, linkRefs, parseForgeHosts, parseOverride, refHref, resolveForge } from './forge'
30import { handoffs, nudge, unknownLabels } from './handoff'
31import { RECONCILE, brief } from './reconcile'
32import { refusal } from './version'
33import { LETTER, formatSubject, parseDraft, problems, recommendation, revisedIn, rulingIn, shortRecommendation, splitBody, supersededIn } from './subject'
34
35type $ = EngineInterface
36
37const PANE = 'session-decisions'
38const ADD_TOOL = 'mcp__session-decisions__decision_add'
39const CLOSE_TOOL = 'mcp__session-decisions__decision_close'
40const UPDATE_TOOL = 'mcp__session-decisions__decision_update'
41const LIST_TOOL = 'mcp__session-decisions__decision_list'
42const SUPERSEDE_TOOL = 'mcp__session-decisions__decision_supersede'
43// The tools whose transcript row draws as one line naming its item, and whose result draws nothing.
44const CARD_TOOLS = ['TaskCreate', ADD_TOOL, UPDATE_TOOL] as const
45const SAFE_ID = /^[A-Za-z0-9._-]{1,128}$/
46const KEEP_RECORDS = 100
47const RECORD = /^(session|list):/
48
49const items = atom({ plugin: 'session-decisions', key: 'items' } as const, [] as Item[])
50const counters = atom({ plugin: 'session-decisions', key: 'counters' } as const, { D: 0, A: 0 } as Counters)
51const created = atom({ plugin: 'session-decisions', key: 'created' } as const, {} as Record<string, number>)
52// Settled task-list items as the queue knows them, by task id: completed with TaskUpdate, settled
53// by decision_close while TaskUpdate wasn't available, or marked by decision_supersede. They outlive
54// their task files, which Claude Code deletes once every task in the list is completed.
55const closed = atom({ plugin: 'session-decisions', key: 'closed' } as const, {} as Record<string, Item>)
56// Subagent loops by agent id: how each was spawned, or that it has called a task tool.
57const loops = atom({ plugin: 'session-decisions', key: 'loops' } as const, {} as Record<string, Loop>)
58const TASK_TOOLS = ['TaskCreate', 'TaskGet', 'TaskList', 'TaskUpdate'] as const
59// When the person's latest prompt was sent, so the hand-off check counts the items this turn made.
60const turnStarted = atom({ plugin: 'session-decisions', key: 'turnStarted' } as const, 0)
61// The hand-off reminder the model gets with the person's next prompt; empty when there's none.
62const handoffNudge = atom({ plugin: 'session-decisions', key: 'handoffNudge' } as const, '')
63const showSettled = atom({ plugin: 'session-decisions', key: 'showSettled' } as const, false)
64const paneDismissed = atom({ plugin: 'session-decisions', key: 'paneDismissed' } as const, false)
65const autoOpened = atom({ plugin: 'session-decisions', key: 'autoOpened' } as const, false)
66const details = atom({ plugin: 'session-decisions', key: 'details' } as const, null as Details | null)
67// Whether this surface docks panes beside the transcript: fixed per session on the terminal and
68// learnt from the footer's drawing. A module variable, since a drawing may not write state.
69let docks = false
70// Whether the queue pane is on screen, as this module last saw it open, draw or close.
71let paneUp = false
72// The screen's height as the last drawing saw it, so the details view can ask for a pane that
73// tall; null until something has drawn on a surface that measures.
74let screenRows: number | null = null
75function measure(site: { viewport?: { rows: number; columns: number } }) {
76 if (site.viewport && site.viewport.rows > 0) screenRows = site.viewport.rows
77}
78// The first row the queue list showed when it was last drawn or scrolled, so Back from the details
79// view puts the list where it was; null until the list has been seen.
80let listOffset: number | null = null
81// While Back restores the list: the row its window started at, where the list's drawing puts a
82// marker for the scroll to bring to the top. A plugin's $.ui.scroll names things, never rows.
83let restoreRow: number | null = null
84const ascii = atom({ plugin: 'session-decisions', key: 'ascii' } as const, false)
85// Whether the last hydrate found no stored record and no transcript to look for one in, so the
86// next prompt should look again. A module variable: it's about this process, not the queue.
87let lineageOpen = false
88// The forge the session's repository is on, read from its git config and remote at session start, so `#12`
89// and `!4` can link to it; null outside a repository or on a host whose kind isn't known.
90let forge: Forge | null = null
91// Whether classic.Stop ran in the main loop's current turn, so turn.complete doesn't check the
92// reply a second time. A module variable: it lasts one turn of this process.
93let stopRan = false
94// Whether this Claude Code is new enough (hooks/version.ts), asked once per load: why the plugin
95// stays off, or null when it runs. Every hook that would draw or check something asks it first, so
96// on an older build the plugin is off as a whole rather than half working.
97let gate: Promise<string | null> | null = null
98function off($: $): Promise<string | null> {
99 gate ??= $.session.version().then(
100 found => refusal(found.version),
101 () => refusal(null),
102 )
103 return gate
104}
105
106/**
107 * The repository's forge: its `tracker.forge` and `tracker.web` git config when set, then the
108 * `origin` remote, or the only remote when there's no `origin`; `hosts` names the kind of a host
109 * the built-in rules don't know, or of one they'd get wrong. Notes name override values it can't use.
110 */
111async function repoForge($: $, hosts: ForgeHosts): Promise<{ forge: Forge | null; notes: string[] }> {
112 const git = async (...args: string[]) => {
113 const ran = await $.process.run(['git', ...args], { timeoutMs: 5000 })
114 return ran.exitCode === 0 ? ran.stdout.trim() : ''
115 }
116 try {
117 const { override, notes } = parseOverride(await git('config', '--get-regexp', '^tracker\\.(forge|web)$'))
118 let url = ''
119 if (!override.web) {
120 url = await git('remote', 'get-url', 'origin')
121 if (!url) {
122 const names = (await git('remote')).split('\n').filter(Boolean)
123 if (names.length === 1) url = await git('remote', 'get-url', names[0] ?? '')
124 }
125 }
126 return { forge: resolveForge(url, hosts, override), notes }
127 } catch {
128 return { forge: null, notes: [] }
129 }
130}
131
132const DAY = 24 * 60 * 60 * 1000
133// Claude Code's own theme keys, so the cards follow whichever theme the person runs.
134const ACCENT = 'claude'
135const KIND_COLOR = { DECIDE: 'warning', ACTION: 'suggestion' } as const
136// Columns a bordered card's frame takes: a border and a column of padding on each side.
137const CARD_FRAME = 4
138
139/**
140 * The item a finished TaskCreate, decision_add or decision_update call made or changed, found by
141 * the task id or label in its output; undefined for any other call or one that didn't finish.
142 */
143function rowItem(
144 list: readonly Item[],
145 call: { tool: string; isRunning?: boolean; isErrored: boolean; isInterrupted?: boolean; output?: unknown },
146): Item | undefined {
147 if (call.isRunning || call.isErrored || call.isInterrupted) return undefined
148 if (call.tool === 'TaskCreate') {
149 const id = String((call.output as { task?: { id?: unknown } } | undefined)?.task?.id ?? '')
150 return id ? list.find(one => one.source === 'tasks' && one.id === id) : undefined
151 }
152 if (call.tool !== ADD_TOOL && call.tool !== UPDATE_TOOL) return undefined
153 const label = String(call.output ?? '').split(' ')[0]
154 return label ? list.find(one => one.source === 'ledger' && one.label === label) : undefined
155}
156
157function safeId(id: unknown): string | null {
158 return typeof id === 'string' && SAFE_ID.test(id) && id !== '.' && id !== '..' ? id : null
159}
160
161async function sessionId($: $): Promise<string | null> {
162 return safeId(await $.session.id())
163}
164
165/** The task list this session shares with others, when CLAUDE_CODE_TASK_LIST_ID names one. */
166async function sharedList($: $): Promise<string | null> {
167 return safeId(await $.env.get('CLAUDE_CODE_TASK_LIST_ID'))
168}
169
170async function tasksRoot($: $): Promise<string> {
171 return `${(await $.env.get('CLAUDE_CONFIG_DIR')) || `${await $.env.get('HOME')}/.claude`}/tasks`
172}
173
174/** The task list Claude Code keeps for this session (read only; the format is undocumented). */
175async function tasksDir($: $, sid: string): Promise<string> {
176 return `${await tasksRoot($)}/${(await sharedList($)) ?? sid}`
177}
178
179/**
180 * Where this session's record lives in `$.store`: under the shared task list when there is one,
181 * since a fork or a resume can change the session id while the list stays; otherwise under the
182 * session, whose id is its task list's name.
183 */
184async function recordKey($: $, sid: string): Promise<string> {
185 const list = await sharedList($)
186 return list ? `list:${list}` : `session:${sid}`
187}
188
189/** The decision items in the task files, or null when the directory can't be read. */
190async function readTaskFiles($: $, dir: string): Promise<Item[] | null> {
191 let entries
192 try {
193 entries = await $.fs.list(dir)
194 } catch {
195 return (await $.fs.exists(dir).catch(() => true)) ? null : []
196 }
197 const found: Item[] = []
198 for (const entry of entries) {
199 if (entry.kind !== 'file' || !entry.name.endsWith('.json')) continue
200 try {
201 const data = JSON.parse(await $.fs.read(`${dir}/${entry.name}`))
202 if (data && typeof data === 'object' && typeof data.subject === 'string') {
203 const item = itemFromTask({ ...data, id: String(data.id ?? entry.name.replace(/\.json$/, '')) })
204 if (item) found.push(item)
205 }
206 } catch {
207 // unreadable or half-written: skip it, as the task list itself would
208 }
209 }
210 return found
211}
212
213// $.tool.list() names a deferred tool before the model loads it (Claude Code 2.1.286), so a
214// refusal that points at TaskUpdate says how to reach it.
215const LOAD = ' If TaskUpdate is deferred, load it with ToolSearch first.'
216
217/** Whether the main loop has TaskUpdate, loaded or deferred; false when the host can't say. */
218async function taskUpdateOffered($: $): Promise<boolean> {
219 try {
220 return (await $.tool.list()).some(tool => tool.name === 'TaskUpdate')
221 } catch {
222 return false
223 }
224}
225
226/**
227 * Whether the loop a tool call came from has TaskUpdate. `$.tool.list()` answers for the main loop
228 * even inside a subagent (Claude Code 2.1.300, lokkju/skills#37), and a background subagent gets
229 * no task tools, so a subagent's loop is judged by what the plugin saw of it: one that has called
230 * a task tool has them, a foreground one has what the main loop has, and a background one, or one
231 * whose spawn the plugin didn't see, is taken not to.
232 */
233async function taskUpdateFor($: $, agentId: string | undefined): Promise<boolean> {
234 if (agentId === undefined) return taskUpdateOffered($)
235 const loop = (await read($, loops))[agentId]
236 if (loop === 'tasks') return true
237 if (loop === 'foreground') return taskUpdateOffered($)
238 return false
239}
240
241function asRecord(value: unknown): SessionRecord {
242 const raw = value as Partial<SessionRecord> | undefined
243 return {
244 counters: { D: Number(raw?.counters?.D) || 0, A: Number(raw?.counters?.A) || 0 },
245 created: raw?.created && typeof raw.created === 'object' ? raw.created : {},
246 ledger: Array.isArray(raw?.ledger) ? raw.ledger : [],
247 closed: raw?.closed && typeof raw.closed === 'object' ? raw.closed : {},
248 touched: Number(raw?.touched) || 0,
249 }
250}
251
252/** The main conversation's transcript as `$.session.messages()` has it; empty when it can't be read. */
253async function conversation($: $): Promise<readonly Message[]> {
254 try {
255 const rows = await $.session.messages()
256 return Array.isArray(rows) ? (rows as readonly Message[]) : []
257 } catch {
258 return []
259 }
260}
261
262/**
263 * This session's stored record, and whether there was one. The first read under a shared task
264 * list takes over the record this session kept under its own id. A session with no record that
265 * carries decision items, in its task files or in its transcript, came from another session under
266 * a new id, so it starts from that session's record (see `carriedFrom`).
267 */
268async function loadRecord(
269 $: $,
270 sid: string,
271 fromFiles: readonly Item[] | null,
272 trail: Trail,
273): Promise<{ record: SessionRecord; isStored: boolean }> {
274 const key = await recordKey($, sid)
275 const stored = await $.store.get(key)
276 if (stored !== undefined) return { record: asRecord(stored), isStored: true }
277 const own = key === `session:${sid}` ? undefined : await $.store.get(`session:${sid}`)
278 const found = own !== undefined ? asRecord(own) : key.startsWith('session:') ? await carriedFrom($, sid, fromFiles ?? [], trail) : null
279 if (!found) return { record: asRecord(undefined), isStored: false }
280 await $.store.set(key, { ...found, touched: await $.clock.now() })
281 if (own !== undefined) await $.store.delete(`session:${sid}`)
282 return { record: found, isStored: true }
283}
284
285/**
286 * The record of the session this one carries on from under a new id: the most recently used one
287 * that agrees with every sign of it this session has, and there has to be at least one.
288 * - Task files. Backgrounding a session copies its task files under the new id, so the record's
289 * own task list holds every decision item in this one's by task id and label, and at least one
290 * of them word for word. A label survives a revised subject, so items either session changed
291 * after the fork still match; the word-for-word one keeps two short lists that both start at
292 * task 1, D1 apart.
293 * - The transcript. A resume, restart or fork that changes the id keeps the conversation, and with
294 * it what decision_add, decision_update and decision_close answered, so the record's ledger
295 * holds those items (`ledgerMatches`). That is the only sign a session whose items are all in
296 * the ledger has; an unrelated session in the same project never has the same answers.
297 */
298async function carriedFrom($: $, sid: string, carried: readonly Item[], trail: Trail): Promise<SessionRecord | null> {
299 if (carried.length === 0 && trail.ledger.size === 0) return null
300 const root = await tasksRoot($)
301 const covers = (record: SessionRecord) =>
302 carried.every(item => record.counters[LETTER[item.kind]] >= Number(item.label.slice(1)))
303 let best: SessionRecord | null = null
304 for (const key of await $.store.keys()) {
305 const other = key.startsWith('session:') ? safeId(key.slice('session:'.length)) : null
306 if (!other || other === sid) continue
307 const record = asRecord(await $.store.get(key))
308 if (!covers(record) || (best && record.touched <= best.touched)) continue
309 if (ledgerMatches(record, trail) === false) continue
310 if (carried.length > 0) {
311 const theirs = await readTaskFiles($, `${root}/${other}`)
312 const same = (item: Item, exact: boolean) =>
313 theirs?.some(one => one.id === item.id && one.label === item.label && (!exact || one.body === item.body))
314 if (!carried.every(item => same(item, false)) || !carried.some(item => same(item, true))) continue
315 }
316 best = record
317 }
318 return best
319}
320
321/**
322 * Write this session's record. Sessions on one shared task list write one record, so what another
323 * wrote since is kept: the higher counters, every creation time, and every ledger item, with the
324 * settled copy of an item either side settled.
325 */
326async function persist($: $): Promise<void> {
327 const sid = await sessionId($)
328 if (!sid) return
329 const key = await recordKey($, sid)
330 const stored = asRecord(await $.store.get(key))
331 const mine = await read($, counters)
332 const ledger = (await read($, items)).filter(item => item.source === 'ledger')
333 const theirs = stored.ledger.filter(item => {
334 const own = ledger.find(one => one.id === item.id)
335 return !own || (isOpen(own) && !isOpen(item))
336 })
337 const record: SessionRecord = {
338 counters: { D: Math.max(mine.D, stored.counters.D), A: Math.max(mine.A, stored.counters.A) },
339 created: { ...stored.created, ...(await read($, created)) },
340 ledger: [...ledger.filter(item => !theirs.some(one => one.id === item.id)), ...theirs],
341 closed: await read($, closed),
342 touched: await $.clock.now(),
343 }
344 await $.store.set(key, record)
345}
346
347/** Drop all but the most recently used records, session and list alike, to stay under the store's cap. */
348async function prune($: $): Promise<void> {
349 const keys = (await $.store.keys()).filter(key => RECORD.test(key))
350 if (keys.length <= KEEP_RECORDS) return
351 const touched = await Promise.all(
352 keys.map(async key => [key, Number(((await $.store.get(key)) as SessionRecord)?.touched) || 0] as const),
353 )
354 touched.sort((a, b) => b[1] - a[1])
355 await Promise.all(touched.slice(KEEP_RECORDS).map(([key]) => $.store.delete(key)))
356}
357
358/**
359 * Rebuild the items from the task files, the stored ledger and stored rulings, keeping what's
360 * already in state; the one read this plugin makes. `given` is the session id a hook's input
361 * names, which a resume settles before `$.session.id()` does.
362 */
363async function hydrate($: $, given?: string): Promise<void> {
364 const sid = safeId(given) ?? (await sessionId($))
365 if (!sid) return
366 const fromFiles = await readTaskFiles($, await tasksDir($, sid))
367 const messages = await conversation($)
368 const trail = trailOf(messages)
369 const { record, isStored } = await loadRecord($, sid, fromFiles, trail)
370 // A session with no record yet may be one whose transcript the engine hadn't loaded when this
371 // ran; the next prompt looks again, until the record exists or the transcript has been read.
372 lineageOpen = !isStored && messages.length === 0
373 const current = await read($, items)
374 const settled = { ...record.closed, ...(await read($, closed)) }
375 const known = { ...record.created, ...(await read($, created)) }
376 const merged = mergeHydrated(fromFiles, current, { ledger: record.ledger, closed: settled }).map(item => ({
377 ...item,
378 created: item.created ?? current.find(one => one.id === item.id && one.source === item.source)?.created ?? known[item.label],
379 }))
380 await update($, items, () => merged)
381 await update($, created, () => known)
382 await update($, closed, () => settled)
383 // Labels the conversation has already shown count too, so a session whose record is gone
384 // still never hands out one of them again.
385 const shown = trail.labels.map(label => ({ label }))
386 await update($, counters, now =>
387 coverLabels(coverLabels({ D: Math.max(now.D, record.counters.D), A: Math.max(now.A, record.counters.A) }, merged), shown),
388 )
389 await publish($, merged)
390}
391
392/** After the queue changes: close a sidebar this plugin opened once nothing is left open. */
393async function publish($: $, list: readonly Item[]): Promise<void> {
394 if (list.some(isOpen)) return
395 await update($, paneDismissed, () => false)
396 if (await read($, autoOpened)) {
397 await update($, autoOpened, () => false)
398 await $.ui.close({ id: PANE }).catch(() => undefined)
399 }
400}
401
402/** Open the queue as a sidebar, unasked, where the surface docks panes and the person hasn't closed it. */
403async function offerSidebar($: $): Promise<void> {
404 if (!docks || (await read($, paneDismissed))) return
405 const opened = await $.ui.open({ id: PANE, title: 'Decisions', columns: 52 }).catch(() => null)
406 if (opened) await update($, autoOpened, () => true)
407}
408
409/** Open the queue because the person asked: it seats at any width and takes the keys. */
410async function openPane($: $): Promise<void> {
411 await update($, paneDismissed, () => false)
412 await update($, autoOpened, () => false)
413 await $.ui.open({ id: PANE, title: 'Decisions', focus: true, closeOnEscape: true, columns: 52 }).catch(() => undefined)
414}
415
416async function change($: $, fn: (list: Item[]) => Item[]): Promise<Item[]> {
417 let after: Item[] = []
418 await update($, items, list => (after = fn(list)))
419 await publish($, after)
420 return after
421}
422
423/** Assign the next label for `kind`; the versioned update keeps parallel creates apart. */
424async function assign($: $, kind: Kind): Promise<string> {
425 const list = await read($, items)
426 let number = 0
427 await update($, counters, now => {
428 number = nextNumber(now, list, kind)
429 return { ...now, [LETTER[kind]]: number }
430 })
431 const label = `${LETTER[kind]}${number}`
432 const at = await $.clock.now()
433 await update($, created, map => ({ ...map, [label]: at }))
434 return label
435}
436
437async function announce($: $, item: Item): Promise<void> {
438 $.ui.toast(`${item.label} added: ${plainText(splitBody(item.body).question)}`)
439 await offerSidebar($)
440}
441
442/** The lines of a reply that hand the person work without a queue entry; null when there are none. */
443async function unqueued($: $, reply: string): Promise<{ lines: string[]; missing: string[] } | null> {
444 if (!reply) return null
445 const since = await read($, turnStarted)
446 const all = await read($, items)
447 const queue = all.filter(item => isOpen(item) || (item.created ?? 0) >= since)
448 const known = all.map(item => item.label)
449 const lines = handoffs(reply, queue, { known })
450 if (lines.length === 0) return null
451 return { lines, missing: unknownLabels(reply, known) }
452}
453
454/** The hand-off check's toast: short, since a toast is narrow, naming the count and the first hand-off. */
455function warn($: $, found: { lines: string[]; missing: string[] }): void {
456 const count = found.lines.length === 1 ? 'A hand-off' : `${found.lines.length} hand-offs`
457 $.ui.toast(
458 found.missing.length > 0
459 ? `${found.missing.join(', ')} named but not in the queue`
460 : `${count} not queued: ${plainText(found.lines[0] ?? '')}`,
461 )
462}
463
464const WRAP = `Wrap up this session's decision queue, as the session-decisions skill describes: for every open item below, ask me in one message whether to escalate it (create it in the project's tracker as a question for the right person, and link it), carry it forward (it stays open and goes in the handoff), or drop it. Then apply my answers, completing each settled item with a "Ruling (<YYYY-MM-DD>): ..." line, and report what changed.`
465
466export const register: Register = (on, options) => {
467 // The forge_hosts option (plugin.json userConfig), read as the module loads.
468 const forgeHosts = parseForgeHosts(options?.forge_hosts)
469 const checkHandoffs = options?.handoff_check !== false
470 gate = null
471 on('session.start', async ($, e, next) => {
472 // Too old a Claude Code: say so where the person will see it, and register nothing.
473 const refused = await off($)
474 if (refused) {
475 $.ui.toast(refused, { timeoutMs: 20_000 })
476 $.ui.log(refused)
477 return next(e)
478 }
479 // Each registration stands alone: a host that refuses one still gets the rest and the queue.
480 const quietly = (work: Promise<unknown>) => work.catch(() => undefined)
481 await quietly($.command.register({
482 name: 'decisions',
483 description: "Show this session's open decisions (D) and actions (A); 'all' adds settled ones, 'pane' opens the panel, 'reconcile' closes or revises the ones the session has settled, 'wrap' settles each before the session ends.",
484 argumentHint: '[all | pane | reconcile | wrap]',
485 immediate: true,
486 }))
487 await quietly($.tool.register({
488 name: 'decision_add',
489 description:
490 'Fallback for the session-decisions queue, only when TaskCreate is not available: adds a DECIDE or ACTION item and returns its labelled subject.',
491 inputSchema: {
492 type: 'object',
493 properties: {
494 kind: { type: 'string', enum: ['DECIDE', 'ACTION'] },
495 text: { type: 'string', description: '<question> (recommend <choice>) [<link>], or <what the user has to do> [<link>]' },
496 description: { type: 'string', description: 'The context the user needs to answer.' },
497 },
498 required: ['kind', 'text'],
499 },
500 }))
501 await quietly($.tool.register({
502 name: 'decision_update',
503 description:
504 "Revises an open fallback-ledger item from decision_add when its question, options, recommendation or context change, keeping its label. Task-list items are revised with TaskUpdate instead.",
505 inputSchema: {
506 type: 'object',
507 properties: {
508 label: { type: 'string', description: 'The item label, such as D3.' },
509 text: { type: 'string', description: 'The new subject after the colon, in the form decision_add takes; omit to keep it.' },
510 description: { type: 'string', description: 'What changed and why, recorded as a dated Revised line.' },
511 },
512 required: ['label'],
513 },
514 }))
515 await quietly($.tool.register({
516 name: 'decision_close',
517 description:
518 "Settles a fallback-ledger item from decision_add with the user's ruling. Task-list items are settled with TaskUpdate instead, unless TaskUpdate is not available in this session.",
519 inputSchema: {
520 type: 'object',
521 properties: {
522 label: { type: 'string', description: 'The item label, such as D3.' },
523 ruling: { type: 'string', description: 'The answer, as it should be recorded.' },
524 },
525 required: ['label', 'ruling'],
526 },
527 }))
528 await quietly($.tool.register({
529 name: 'decision_supersede',
530 description:
531 "Marks a settled decision-queue item, task-list or fallback-ledger, whose ruling stopped holding (its premise failed) as superseded by the new item that replaces it, recording a dated Superseded line. Works when TaskUpdate can't reach the completed task. Create the new item first; an open item is settled as superseded instead.",
532 inputSchema: {
533 type: 'object',
534 properties: {
535 label: { type: 'string', description: 'The settled item, such as D2.' },
536 by: { type: 'string', description: 'The new item that replaces it, such as D5.' },
537 why: { type: 'string', description: 'Why the ruling no longer holds.' },
538 },
539 required: ['label', 'by', 'why'],
540 },
541 }))
542 await quietly($.tool.register({
543 name: 'decision_list',
544 description:
545 "Lists this session's open decision-queue items, task-list and fallback-ledger alike (label, kind, age, link, text), and the lines of the user's messages that name them, for reconciling the queue.",
546 inputSchema: { type: 'object', properties: {} },
547 }))
548 if (forgeHosts.notes.length) $.ui.toast(`session-decisions: forge_hosts ignores ${forgeHosts.notes.join('; ')}`)
549 const found = await repoForge($, forgeHosts.hosts)
550 if (found.notes.length) $.ui.toast(`session-decisions: git config ignores ${found.notes.join('; ')}`)
551 forge = found.forge
552 const term = await $.env.get('TERM')
553 const noColor = await $.env.get('NO_COLOR')
554 await update($, ascii, () => Boolean(noColor) || term === 'dumb')
555 // 1.0 pinned the open count as a status notice; this version shows it in the footer instead.
556 $.ui.status(undefined)
557 await hydrate($)
558 await quietly(prune($))
559 return next(e)
560 })
561
562 // After compaction or resume, remind the model of what is still waiting on the user.
563 on('classic.SessionStart', async ($, e, next) => {
564 const result = await next(e)
565 // Off on this build: the model keeps the queue itself, as the skill says to without the hooks.
566 const refused = await off($)
567 if (refused) {
568 const note = `The session-decisions plugin ${refused} Its hooks are not running in this session and decision_add is not registered: number items yourself, as the session-decisions skill says to when the hook isn't running (or when the plugin isn't loaded, if TaskCreate is missing too), and tell the user once that the plugin is off and why.`
569 return { ...result, additionalContext: [...(result.additionalContext ?? []), note] }
570 }
571 if (e.source !== 'compact' && e.source !== 'resume') return result
572 // Under --continue, $.session.id() still answers a placeholder here; the input has the real id.
573 await hydrate($, e.session_id)
574 const text = reminder(await read($, items))
575 if (!text) return result
576 return { ...result, additionalContext: [...(result.additionalContext ?? []), text] }
577 })
578
579 // The hand-off check: a reply that hands the person work without queuing it gets a toast now,
580 // and the model a reminder with the person's next prompt. It never blocks the reply.
581 on('classic.UserPromptSubmit', async ($, e, next) => {
582 if (await off($)) return next(e)
583 const result = await next(e)
584 const now = await $.clock.now()
585 await update($, turnStarted, () => now)
586 if (lineageOpen) await hydrate($, e.session_id)
587 const pending = await read($, handoffNudge)
588 if (!pending) return result
589 await update($, handoffNudge, () => '')
590 return { ...result, additionalContext: [...(result.additionalContext ?? []), pending] }
591 })
592
593 on('classic.Stop', async ($, e, next) => {
594 if (await off($)) return next(e)
595 stopRan = true
596 const result = await next(e)
597 if (!checkHandoffs || e.stop_hook_active || result.block !== undefined) return result
598 const found = await unqueued($, String(e.last_assistant_message ?? ''))
599 if (!found) return result
600 await update($, handoffNudge, () => nudge(found.lines, found.missing))
601 warn($, found)
602 return result
603 })
604
605 // A managed plugin seated first (Claude Code's own security plugin, cc-plugin-sec-default) can
606 // send every classic.* event on past this plugin, so classic.Stop never runs. turn.complete
607 // isn't one it passes over: when classic.Stop didn't run for the turn, the person still gets
608 // the toast. The model's reminder stays with classic.Stop and the next classic.UserPromptSubmit.
609 on('turn.complete', async ($, e, next) => {
610 const result = await next(e)
611 if (e.agentId !== undefined) return result
612 const ran = stopRan
613 stopRan = false
614 if (ran || !checkHandoffs || e.reason !== 'answer' || (await off($))) return result
615 const found = await unqueued($, e.answer)
616 if (found) warn($, found)
617 return result
618 })
619
620 // What decision_close and decision_update need to know about a subagent: whether it was spawned
621 // in the background, which gives it no task tools. A teammate or a workflow's agent isn't
622 // recorded, and counts as having none until it calls one.
623 on('agent.spawn', async ($, e, next) => {
624 if (await off($)) return next(e)
625 const ran = await next(e)
626 const id = ran.agentId
627 if (id && !e.isTeammate && !e.workflow) {
628 const loop: Loop = e.background ? 'background' : 'foreground'
629 await update($, loops, (map): Record<string, Loop> => (map[id] === 'tasks' ? map : { ...map, [id]: loop }))
630 }
631 return ran
632 })
633
634 // A subagent that calls a task tool has them, however it was spawned.
635 on('tool.call', { tool: TASK_TOOLS }, async ($, e, next) => {
636 if (await off($)) return next(e)
637 const ran = await next(e)
638 const id = e.agentId
639 if (id !== undefined && ran.deny === undefined && !ran.isError) {
640 await update($, loops, (map): Record<string, Loop> => (map[id] === 'tasks' ? map : { ...map, [id]: 'tasks' }))
641 }
642 return ran
643 })
644
645 on('tool.call', { tool: 'TaskCreate' }, async ($, e, next) => {
646 if (await off($)) return next(e)
647 const draft = parseDraft(String(e.subject ?? ''))
648 if (!draft) return next(e)
649 const found = problems(draft)
650 if (found.length) return { deny: `session-decisions: ${found.join('; ')}` }
651 const label = await assign($, draft.kind)
652 const ran = await next({ ...e, subject: formatSubject(label, draft) })
653 if (ran.deny !== undefined || ran.isError) return ran
654 const task = ran.result.task
655 const item = itemFromTask({ id: task.id, subject: task.subject, description: String(e.description ?? '') })
656 if (item) {
657 const at = (await read($, created))[item.label] ?? (await $.clock.now())
658 await change($, list => upsert(list, { ...item, created: at }))
659 await update($, counters, now => coverLabels(now, [item]))
660 await persist($)
661 await announce($, item)
662 }
663 return ran
664 })
665
666 // A new subject keeps the item's label: the assistant writes drafts, and the hook relabels them
667 // the way TaskCreate does, so a revised question never loses its D<n> or A<n>.
668 on('tool.call', { tool: 'TaskUpdate' }, async ($, e, next) => {
669 if (await off($)) return next(e)
670 const taskId = String(e.taskId)
671 let subject = e.subject
672 let assigned: string | null = null
673 if (subject !== undefined) {
674 const plan = retitle(await read($, items), taskId, String(subject))
675 if (plan.kind === 'deny') return { deny: `session-decisions: ${plan.reason}` }
676 if (plan.kind === 'subject') subject = plan.subject
677 if (plan.kind === 'assign') {
678 assigned = await assign($, plan.draft.kind)
679 subject = formatSubject(assigned, plan.draft)
680 }
681 }
682 const ran = await next(subject === e.subject ? e : { ...e, subject })
683 if (ran.deny !== undefined || ran.isError) return ran
684 const before = await read($, items)
685 const after = await change($, list =>
686 applyUpdate(list, { taskId, subject, description: e.description, status: e.status }),
687 )
688 // The queue keeps its own copy of a settled task item, so the item outlives its task file. A
689 // status set through TaskUpdate is in the task file now, so that copy follows it: the item as
690 // TaskUpdate left it while it's completed (with any Superseded line already recorded), none once
691 // it's open again or deleted.
692 const kept = (await read($, closed))[taskId]
693 const now = after.find(one => one.source === 'tasks' && one.id === taskId)
694 const keep = now && !isOpen(now) ? withMarks(now, kept) : undefined
695 const recorded = keep !== undefined || kept !== undefined
696 if (keep) {
697 if (keep !== now) await change($, list => list.map(one => (one === now ? keep : one)))
698 await update($, closed, map => ({ ...map, [taskId]: keep }))
699 } else if (kept) {
700 await update($, closed, map => {
701 const { [taskId]: _, ...rest } = map
702 return rest
703 })
704 }
705 if (after === before) {
706 if (recorded) await persist($)
707 return ran
708 }
709 await update($, counters, now => coverLabels(now, after))
710 if (assigned) {
711 const at = (await read($, created))[assigned] ?? (await $.clock.now())
712 const fresh = await change($, list =>
713 list.map(one => (one.source === 'tasks' && one.id === taskId ? { ...one, created: one.created ?? at } : one)),
714 )
715 const item = fresh.find(one => one.source === 'tasks' && one.id === taskId)
716 if (item) await announce($, item)
717 }
718 await persist($)
719 return ran
720 })
721
722 on('tool.call', { tool: ADD_TOOL }, async ($, e) => {
723 const kind = e.kind === 'ACTION' ? 'ACTION' : e.kind === 'DECIDE' ? 'DECIDE' : null
724 if (!kind) return { deny: 'session-decisions: kind must be DECIDE or ACTION' }
725 const draft = { kind, body: String(e.text ?? '').trim() } as const
726 const found = problems(draft)
727 if (found.length) return { deny: `session-decisions: ${found.join('; ')}` }
728 const label = await assign($, kind)
729 const item: Item = {
730 id: label,
731 source: 'ledger',
732 label,
733 kind,
734 body: draft.body,
735 status: 'pending',
736 description: String(e.description ?? ''),
737 created: (await read($, created))[label],
738 }
739 await change($, list => [...list, item])
740 await persist($)
741 await announce($, item)
742 return { result: subjectOf(item) }
743 })
744
745 on('tool.call', { tool: UPDATE_TOOL }, async ($, e) => {
746 const label = String(e.label ?? '').trim().toUpperCase()
747 const text = e.text === undefined ? undefined : String(e.text).trim()
748 const note = e.description === undefined ? undefined : String(e.description).trim()
749 if (!text && !note) return { deny: 'session-decisions: give the new text, a description of what changed, or both.' }
750 const list = await read($, items)
751 const matches = list.filter(item => item.label === label)
752 const target = matches.find(item => item.source === 'ledger') ?? matches.find(isOpen) ?? matches[0]
753 if (!target) return { deny: `session-decisions: ${label} isn't in this session's decision queue.` }
754 if (target.source === 'tasks') {
755 return {
756 deny: (await taskUpdateFor($, e.agentId))
757 ? `session-decisions: ${label} is a task-list item; revise it with TaskUpdate, keeping its label, and add a Revised line to its description.${LOAD}`
758 : `session-decisions: ${label} is a task-list item and TaskUpdate isn't available here; close it with decision_close as superseded and add the revised item with decision_add.`,
759 }
760 }
761 if (!isOpen(target)) return { deny: `session-decisions: ${label} is settled; add a new item with decision_add instead.` }
762 if (text) {
763 const found = problems({ kind: target.kind, body: text })
764 if (found.length) return { deny: `session-decisions: ${found.join('; ')}` }
765 }
766 const date = new Date(await $.clock.now()).toISOString().slice(0, 10)
767 const done = revise(target, { body: text || undefined, note }, date)
768 await change($, now => now.map(item => (item.source === 'ledger' && item.id === target.id ? done : item)))
769 await persist($)
770 return { result: subjectOf(done) }
771 })
772
773 on('tool.call', { tool: CLOSE_TOOL }, async ($, e) => {
774 const label = String(e.label ?? '').trim().toUpperCase()
775 const ruling = String(e.ruling ?? '').trim()
776 const list = await read($, items)
777 const matches = list.filter(item => item.label === label)
778 // A ledger item first; of two task items with one label, the open one.
779 const target =
780 matches.find(item => item.source === 'ledger') ?? matches.find(isOpen) ?? matches[0]
781 if (!target) return { deny: `session-decisions: ${label} isn't in this session's decision queue.` }
782 if (target.source === 'tasks' && (await taskUpdateFor($, e.agentId))) {
783 return {
784 deny: `session-decisions: ${label} is a task-list item; mark it completed with TaskUpdate and add the ruling to its description.${LOAD}`,
785 }
786 }
787 const date = new Date(await $.clock.now()).toISOString().slice(0, 10)
788 const done = settle(target, ruling, date)
789 await change($, now => now.map(item => (item.source === target.source && item.id === target.id ? done : item)))
790 if (target.source === 'tasks') await update($, closed, map => ({ ...map, [target.id]: done }))
791 await persist($)
792 if (target.source === 'ledger') return { result: `${label} closed` }
793 if (e.agentId !== undefined) {
794 return {
795 result: `${label} closed in the decision queue. This agent has no TaskUpdate, so the task still shows it open until the main conversation marks it completed; the queue keeps the ruling.`,
796 }
797 }
798 return {
799 result: `${label} closed in the decision queue. TaskUpdate isn't available here, so its task still shows it open; the queue keeps the ruling.`,
800 }
801 })
802
803 on('tool.call', { tool: SUPERSEDE_TOOL }, async ($, e) => {
804 const label = String(e.label ?? '').trim().toUpperCase()
805 const by = String(e.by ?? '').trim().toUpperCase()
806 const why = String(e.why ?? '').trim()
807 const list = await read($, items)
808 const matches = list.filter(item => item.label === label)
809 const target = matches.find(item => !isOpen(item)) ?? matches[0]
810 if (!target) {
811 return {
812 deny: `session-decisions: ${label} isn't in this session's decision queue, so there's no record to mark; say in your reply that ${label} is superseded by ${by}.`,
813 }
814 }
815 if (isOpen(target)) {
816 return {
817 deny: `session-decisions: ${label} is still open; settle it with the ruling "superseded by ${by}" instead (TaskUpdate for a task-list item, decision_close for a ledger item or where TaskUpdate isn't available).`,
818 }
819 }
820 if (by === label || !/^[DA]\d+$/.test(by) || !list.some(item => item.label === by)) {
821 return { deny: `session-decisions: ${by || 'by'} isn't another item in this session's decision queue; create the new item first and pass its label as by.` }
822 }
823 const date = new Date(await $.clock.now()).toISOString().slice(0, 10)
824 const done = supersede(target, by, why, date)
825 await change($, now => now.map(item => (item.source === target.source && item.id === target.id ? done : item)))
826 if (target.source === 'tasks') await update($, closed, map => ({ ...map, [target.id]: done }))
827 await persist($)
828 return { result: `${label} superseded by ${by}` }
829 })
830
831 on('tool.call', { tool: LIST_TOOL }, async $ => {
832 return { result: brief(await read($, items), await conversation($), await $.clock.now()) }
833 })
834
835 on('command.run', { command: 'decisions' }, async ($, e) => {
836 const arg = e.args.trim().toLowerCase()
837 const list = await read($, items)
838 const now = await $.clock.now()
839 if (arg === 'pane') {
840 await update($, paneDismissed, () => false)
841 const opened = await $.ui
842 .open({ id: PANE, title: 'Decisions', focus: true, closeOnEscape: true, columns: 52 })
843 .catch((err: unknown) => ({ isPlaced: false as const, reason: String(err) }))
844 return { text: opened.isPlaced ? 'Decisions pane opened.' : `${listing(list, now)}\n\n(The pane can't be shown here: ${opened.reason})` }
845 }
846 if (arg === 'reconcile') {
847 if (!list.some(isOpen)) return { text: 'No open decisions or actions; nothing to reconcile.' }
848 // The person sees the brief once, as the command's output; the model reads it as the
849 // command's note, ahead of the short request that starts its turn.
850 const text = brief(list, await conversation($), now)
851 submitSoon($, RECONCILE)
852 return { text, context: [text] }
853 }
854 if (arg === 'wrap') {
855 const open = list.filter(isOpen)
856 if (open.length === 0) return { text: 'No open decisions or actions; nothing to wrap up.' }
857 submitSoon($, `${WRAP}\n\n${listing(list, now)}`)
858 return { text: listing(list, now) }
859 }
860 return { text: listing(list, now, arg === 'all') }
861 })
862
863 // A sidebar the person closes stays closed until the queue empties; closing a pane that opened
864 // only to show an item's details doesn't count as closing the sidebar.
865 on('ui.close', async ($, e, next) => {
866 if (await off($)) return next(e)
867 if (e.id !== PANE) return next(e)
868 const shown = await read($, details)
869 if (shown) await update($, details, () => null)
870 if (e.origin.kind === 'person' && !shown?.owns) {
871 await update($, paneDismissed, () => true)
872 await update($, autoOpened, () => false)
873 }
874 const closed = await next(e)
875 paneUp = false
876 return closed
877 })
878
879 // A pane waiting undrawn (opened unasked on a narrow terminal) isn't one the person has seen.
880 on('ui.open', async ($, e, next) => {
881 if (await off($)) return next(e)
882 const opened = await next(e)
883 if (e.id === PANE) paneUp = opened.value?.isPlaced === true
884 return opened
885 })
886
887 // The footer: a count beside the mode labels that opens the queue. It also learns whether
888 // this surface docks panes, which decides whether the sidebar may open unasked.
889 on('ui.render', { component: 'SessionMode' }, async ($, e, next) => {
890 if (await off($)) return next(e)
891 docks = e.viewport?.isFullscreen === true
892 measure(e)
893 const open = (await read($, items)).filter(isOpen).length
894 if (open === 0) return next(e)
895
896 const { Box, Button, Text } = $.ui.resolve(e)
897 const plain = await read($, ascii)
898 const below = await next(e)
899 return (
900 <Box flexDirection="row" gap={1}>
901 {below}
902 <Box key="decisions-footer" flexDirection="row">
903 <Text color="warning">{plain ? '*' : '●'} </Text>
904 <Button
905 key="decisions-count"
906 plain
907 label={`${open} ${open === 1 ? 'decision' : 'decisions'}`}
908 onPress={() => void openPane($)}
909 />
910 </Box>
911 </Box>
912 )
913 })
914
915 // The queue has its own places (the sidebar, the footer, /decisions), so the transcript keeps one
916 // line where an item was queued or revised: `queued D3`, which opens it, and `✓ D3 · <ruling>`
917 // once settled. The tool's result row, the labelled subject the model reads, draws nothing, so
918 // the item isn't printed twice; ctrl+o still shows the call and its result in full.
919 for (const tool of CARD_TOOLS) {
920 on('ui.render', { component: 'ToolUse', props: { tool } }, async ($, e, next) => {
921 if (await off($)) return next(e)
922 measure(e)
923 if (e.props.isExpanded) return next(e)
924 const item = rowItem(await read($, items), e.props)
925 if (!item) return next(e)
926 return drawMention($, e, item, tool === UPDATE_TOOL ? 'revised' : 'queued')
927 })
928 on('ui.render', { component: 'ToolResult', props: { tool } }, async ($, e, next) => {
929 if (await off($)) return next(e)
930 if (e.props.isExpanded || !rowItem(await read($, items), e.props)) return next(e)
931 const { Box } = $.ui.resolve(e)
932 return <Box key="decisions-result" />
933 })
934 }
935
936 // Claude Code 2.1.286 folds a TaskCreate call into a tool group with the calls around it (a
937 // ToolSearch that loaded it, say), and a folded group of those draws as nothing at all, so its
938 // line would show only in ctrl+o. A folded group draws as usual with its items' lines under it;
939 // an unfolded one is ToolUse rows, which draw them already.
940 on('ui.render', { component: 'ToolGroup' }, async ($, e, next) => {
941 if (await off($)) return next(e)
942 if (e.props.isExpanded) return next(e)
943 const list = await read($, items)
944 const found: { item: Item; verb: 'queued' | 'revised' }[] = []
945 for (const call of e.props.calls) {
946 const item = rowItem(list, call)
947 if (item && !found.some(one => one.item === item)) found.push({ item, verb: call.tool === UPDATE_TOOL ? 'revised' : 'queued' })
948 }
949 if (found.length === 0) return next(e)
950 measure(e)
951 const { Box } = $.ui.resolve(e)
952 const below = await next(e)
953 return (
954 <Box flexDirection="column">
955 {below}
956 {await Promise.all(
957 found.map(async ({ item, verb }) => (
958 <Box key={`group-${item.source}-${item.id}`} flexDirection="column">
959 {await drawMention($, e, item, verb)}
960 </Box>
961 )),
962 )}
963 </Box>
964 )
965 })
966
967 // The list's place as the person scrolls it, for Back from the details view to return to.
968 on('ui.scroll', { requestId: PANE }, async ($, e, next) => {
969 if (await off($)) return next(e)
970 const moved = await next(e)
971 if (moved.deny === undefined && !(await read($, details))) listOffset = e.offset
972 return moved
973 })
974
975 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
976 measure(e)
977 paneUp = true
978 const { Box, Button, Text } = $.ui.resolve(e)
979 const list = ordered(await read($, items))
980 const settledOpen = await read($, showSettled)
981 const plain = await read($, ascii)
982 const docked = e.props.placement === 'dock'
983 const shown = await read($, details)
984 const focus = shown ? list.find(item => keyOf(item) === shown.item && isOpen(item)) : undefined
985 if (focus) return drawDetails($, e, focus, shown?.owns === true)
986 if (e.props.scroll && restoreRow === null) listOffset = e.props.scroll.offset
987 const open = list.filter(isOpen)
988 const settled = list.filter(item => !isOpen(item))
989 const accepts = open.flatMap(item => {
990 const choice = item.kind === 'DECIDE' ? recommendation(item.body) : null
991 return choice ? [`${item.label}: go with ${choice}`] : []
992 })
993
994 return (
995 <Box flexDirection="column">
996 {restoreRow !== null && <Box key="list-place" position="absolute" top={restoreRow} left={0} width={1} height={1} />}
997 <Box key="head" flexDirection="row" gap={1} marginBottom={1}>
998 <Text bold>Decisions</Text>
999 {open.length > 0 ? chip(Text, plain, `${open.length} open`, ACCENT) : <Text dimColor>Nothing waiting on you</Text>}
1000 <Box flexGrow={1} />
1001 {accepts.length > 1 && <Button key="accept-all" label="Accept all" variant="primary" onPress={answer($, accepts)} />}
1002 </Box>
1003 {await Promise.all(
1004 open.map(async (item, i) => (
1005 <Box key={`slot-${item.source}-${item.id}`} flexDirection="column" marginBottom={docked ? 1 : 0}>
1006 {await contained($, e, item, () => drawCard($, e, item, { bordered: !docked, isNext: i === 0, compact: false, width: e.props.bodyColumns - (docked ? 0 : CARD_FRAME) }))}
1007 </Box>
1008 )),
1009 )}
1010 {settled.length > 0 && (
1011 <Button
1012 key="settled"
1013 plain
1014 dimColor
1015 label={`${settledOpen ? (plain ? 'v' : '⌄') : plain ? '>' : '›'} Settled (${settled.length})`}
1016 onPress={() => update($, showSettled, value => !value)}
1017 />
1018 )}
1019 {settledOpen &&
1020 (await Promise.all(
1021 settled.map(async item => (
1022 <Box key={`slot-${item.source}-${item.id}`} flexDirection="column">
1023 {await contained($, e, item, () => drawCard($, e, item, { bordered: false, isNext: false, compact: true, width: null }))}
1024 </Box>
1025 )),
1026 ))}
1027 </Box>
1028 )
1029 })
1030}
1031
1032/**
1033 * A settled task item as TaskUpdate left it, with the ruling and Superseded line the queue recorded
1034 * on its earlier copy when TaskUpdate's new description dropped them; `item` itself when there's
1035 * nothing to add.
1036 */
1037function withMarks(item: Item, kept: Item | undefined): Item {
1038 if (!kept) return item
1039 const lines = item.description.split('\n')
1040 const ruling = rulingIn(item.description) ? undefined : (rulingIn(kept.description) ?? undefined)
1041 const marked = kept.description.split('\n').reverse().find(line => line.startsWith('Superseded ('))
1042 const added = [ruling, marked].filter((line): line is string => Boolean(line) && !lines.includes(line as string))
1043 if (added.length === 0) return item
1044 return { ...item, description: [item.description, ...added].filter(Boolean).join('\n') }
1045}
1046
1047/**
1048 * Send a prompt once the command that asked for it has answered. The host refuses a submit from
1049 * inside a `command.run` hook, since the prompt would wait on the turn that hook holds; a timer
1050 * runs it after the hook returns, and the host starts the turn once the session is idle.
1051 */
1052function submitSoon($: $, text: string): void {
1053 $.clock.after(0, () => {
1054 void $.prompt.submit({ text }).catch((err: unknown) => $.ui.toast(`session-decisions: couldn't send the prompt: ${String(err)}`))
1055 })
1056}
1057
1058/** Each press adds or replaces its item's line in the draft, so one message can answer several. */
1059function answer($: $, lines: string[]) {
1060 return () =>
1061 void $.prompt
1062 .read()
1063 .then(box => $.prompt.fill({ text: mergeAnswers(box.text, lines) }))
1064 .catch(() => undefined)
1065}
1066
1067/** Copy a command from a card; a surface with no clipboard path says so in a toast. */
1068async function copy($: $, text: string, surface: Surface): Promise<void> {
1069 const done = await $.ui.copy({ text, surface }).catch((err: unknown) => ({ isCopied: false as const, reason: String(err) }))
1070 $.ui.toast(done.isCopied ? 'Copied' : `Couldn't copy: ${done.reason}`)
1071}
1072
1073type Elements = ReturnType<$['ui']['resolve']>
1074
1075function chip(Text: Elements['Text'], plain: boolean, text: string, color: string, dim = false) {
1076 return (
1077 <Text bold backgroundColor={dim ? undefined : color} color={dim ? undefined : 'inverseText'} dimColor={dim}>
1078 {plain ? `[${text}]` : ` ${text} `}
1079 </Text>
1080 )
1081}
1082
1083/**
1084 * One card, or a plain line naming its item when building the card throws: an element this build
1085 * refuses as it is made (lokkju/skills#119) then costs that card alone, not the whole pane. A tree
1086 * the engine refuses after the hook returns can't be caught here; the engine drops the pane for it.
1087 */
1088async function contained($: $, site: Parameters<$['ui']['resolve']>[0], item: Item, draw: () => Promise<JSX.Element>) {
1089 try {
1090 return await draw()
1091 } catch (err) {
1092 $.ui.log(`session-decisions: couldn't draw ${item.label}: ${String(err)}`, { to: 'debug' })
1093 const { Text } = $.ui.resolve(site)
1094 return <Text key={`card-${item.source}-${item.id}`}>{`${item.label} ${plainText(splitBody(item.body).question)}`}</Text>
1095 }
1096}
1097
1098/**
1099 * One item. Open: kind chip, label, recommendation tag, age, the question, the qualifier, and its
1100 * buttons; `bordered` draws a round frame (the accent one for `isNext`). When the details view has
1101 * more than the card shows, the text ends with `[more]`, beside its last row when it fits in `width`
1102 * (the columns inside the frame) and on a row of its own otherwise. Settled, or `compact`: one dim
1103 * line with the ruling.
1104 */
1105async function drawCard(
1106 $: $,
1107 site: Parameters<$['ui']['resolve']>[0],
1108 item: Item,
1109 opts: { bordered: boolean; isNext: boolean; compact: boolean; width: number | null },
1110) {
1111 const { Box, Button, Link, Markdown, Text } = $.ui.resolve(site) as Elements
1112 const plain = await read($, ascii)
1113 const now = await $.clock.now()
1114 const parts = splitBody(item.body)
1115
1116 if (!isOpen(item) || opts.compact) {
1117 const superseded = isOpen(item) ? null : supersededIn(item.description)
1118 const ruling = superseded
1119 ? `${superseded.date} · superseded by ${superseded.by}${superseded.why ? `: ${superseded.why}` : ''}`
1120 : (rulingIn(item.description) ?? '').replace(/^Ruling \(([^)]*)\):\s*/, '$1 · ')
1121 const moot = superseded !== null || /·\s*moot\b/i.test(ruling)
1122 const glyph = superseded ? (plain ? '>' : '→') : moot ? (plain ? 'x' : '✗') : plain ? '+' : '✓'
1123 return (
1124 <Box key={`card-${item.source}-${item.id}`} flexDirection="row" gap={1}>
1125 <Text color={moot ? undefined : 'success'} dimColor={moot}>
1126 {glyph}
1127 </Text>
1128 <Text bold dimColor>
1129 {item.label}
1130 </Text>
1131 <Box flexShrink={1}>
1132 <Text dimColor wrap="truncate-end">
1133 {plainText(ruling || parts.question)}
1134 </Text>
1135 </Box>
1136 </Box>
1137 )
1138 }
1139
1140 const rec = parts.recommendation ? shortRecommendation(parts.recommendation) : null
1141 const choice = parts.recommendation ? shortRecommendation(plainText(parts.recommendation)).choice : null
1142 const old = replaces(await read($, items), item.label)
1143 const short = parts.link === null || isShortLink(parts.link)
1144 const stale = item.created !== undefined && now - item.created > DAY
1145 const revised = revisedIn(item.description)
1146 const frame = opts.bordered
1147 ? { borderStyle: 'round', borderColor: opts.isNext ? ACCENT : 'inactive', hover: { borderColor: ACCENT }, paddingX: 1 }
1148 : {}
1149 const more = () => void showDetails($, item)
1150 const question = linkRefs(parts.question, forge)
1151 const qualifier = rec?.qualifier ? linkRefs(rec.qualifier, forge) : null
1152 // [more] follows whichever line of text comes last: the qualifier when there is one. It is drawn
1153 // in the accent color and underlined, so it reads as a control beside the question (normal text)
1154 // and beside the qualifier (dim text) alike.
1155 const ending = hasMore({ parts, description: item.description }, forge)
1156 ? {
1157 split: moreSplit(qualifier ?? question, opts.width),
1158 button: (
1159 <Button key={`more-${item.label}`} plain label={MORE} hover={{ bold: true }} onPress={more}>
1160 <Text color={ACCENT} underline>
1161 {MORE}
1162 </Text>
1163 </Button>
1164 ),
1165 }
1166 : null
1167 const line = (key: string, text: string, dim: boolean) => {
1168 const drawn = (k: string, t: string) => <Markdown key={k} text={t} dimColor={dim || undefined} />
1169 if (!ending) return drawn(key, text)
1170 if (!ending.split) {
1171 return (
1172 <Box key={`${key}-end`} flexDirection="column">
1173 {drawn(key, text)}
1174 {ending.button}
1175 </Box>
1176 )
1177 }
1178 const { head, tail } = ending.split
1179 // The tail shrinks and wraps when the width it was measured at is more than the card has.
1180 return (
1181 <Box key={`${key}-end`} flexDirection="column">
1182 {head && drawn(`${key}-head`, head)}
1183 <Box key={`${key}-tail`} flexDirection="row" gap={1}>
1184 <Box key={`${key}-tail-text`} flexShrink={1}>
1185 {drawn(head ? `${key}-tail` : key, tail)}
1186 </Box>
1187 {ending.button}
1188 </Box>
1189 </Box>
1190 )
1191 }
1192 return (
1193 <Box key={`card-${item.source}-${item.id}`} flexDirection="column" {...frame}>
1194 <Box key="top" flexDirection="row" gap={1}>
1195 {chip(Text, plain, item.kind, KIND_COLOR[item.kind])}
1196 <Button key={`label-${item.label}`} plain label={item.label} hover={{ bold: true }} onPress={more} />
1197 {choice && chip(Text, plain, `recommends ${choice}`, 'success')}
1198 <Box flexGrow={1} />
1199 {revised && <Text dimColor>{`revised ${revised}`}</Text>}
1200 {item.created !== undefined && (hooks/queue.ts 288 lines1// The queue as plain data: labelling, applying task-list changes, and the text views.
2// Nothing here touches `$`, so it's tested directly.
3
4import type { Counters, Item, Kind, Status } from '../types'
5import { LETTER, formatSubject, parseDraft, parseLabel, problems, revisedIn, rulingIn, rulingText, splitBody, supersededIn } from './subject'
6import type { Draft } from './subject'
7
8const OPEN: ReadonlySet<string> = new Set(['pending', 'in_progress'])
9
10export const isOpen = (item: Item): boolean => OPEN.has(item.status)
11
12/** The number part of a label; 0 for an item the hook didn't get to label ("D?"). */
13export function labelNumber(label: string): number {
14 const digits = label.slice(1)
15 return /^\d+$/.test(digits) ? Number(digits) : 0
16}
17
18/** Next number for this kind: one past both the counter and any label already in use. */
19export function nextNumber(counters: Counters, items: readonly Item[], kind: Kind): number {
20 const letter = LETTER[kind]
21 const inUse = items.filter(item => item.label[0] === letter).map(item => labelNumber(item.label))
22 return Math.max(counters[letter], ...inUse) + 1
23}
24
25/** Counters raised to cover every label in `items`, so numbering never repeats one. */
26export function coverLabels(counters: Counters, items: readonly Pick<Item, 'label'>[]): Counters {
27 const out = { ...counters }
28 for (const item of items) {
29 const letter = item.label[0] as 'D' | 'A'
30 if (letter === 'D' || letter === 'A') out[letter] = Math.max(out[letter], labelNumber(item.label))
31 }
32 return out
33}
34
35function asStatus(value: unknown): Status {
36 return value === 'in_progress' || value === 'completed' ? value : 'pending'
37}
38
39/** A task-list task as an item, or null when it isn't a decision item. */
40export function itemFromTask(task: {
41 id: string
42 subject: string
43 description?: string
44 status?: unknown
45}): Item | null {
46 const label = parseLabel(task.subject)
47 const common = {
48 id: String(task.id),
49 source: 'tasks' as const,
50 status: asStatus(task.status),
51 description: task.description ?? '',
52 }
53 if (label) {
54 return { ...common, label: `${label.letter}${label.number}`, kind: label.kind, body: label.body }
55 }
56 const draft = parseDraft(task.subject) // created while the hook wasn't running: unlabelled
57 if (!draft) return null
58 return { ...common, label: `${LETTER[draft.kind]}?`, kind: draft.kind, body: draft.body }
59}
60
61/** Items with `item` replacing the one of the same source and id, or appended. */
62export function upsert(items: readonly Item[], item: Item): Item[] {
63 const at = items.findIndex(one => one.source === item.source && one.id === item.id)
64 if (at < 0) return [...items, item]
65 return items.map((one, i) => (i === at ? item : one))
66}
67
68export type TaskChange = {
69 taskId: string
70 subject?: string
71 description?: string
72 status?: Status | 'deleted'
73}
74
75/** Apply a TaskUpdate that succeeded to the items; `items` itself when it touches none of them. */
76export function applyUpdate(items: readonly Item[], change: TaskChange): Item[] {
77 const id = String(change.taskId)
78 const current = items.find(one => one.source === 'tasks' && one.id === id)
79 if (change.status === 'deleted') return current ? items.filter(one => one !== current) : (items as Item[])
80 if (!current) {
81 if (change.subject === undefined) return items as Item[]
82 const added = itemFromTask({ id, subject: change.subject, description: change.description, status: change.status })
83 return added ? [...items, added] : (items as Item[])
84 }
85 let next: Item | null = { ...current }
86 if (change.subject !== undefined) {
87 const parsed = itemFromTask({ id, subject: change.subject })
88 next = parsed && { ...parsed, created: current.created }
89 }
90 if (!next) return items.filter(one => one !== current)
91 if (change.description !== undefined) next.description = change.description
92 else next.description = current.description
93 next.status = change.status ? asStatus(change.status) : current.status
94 return items.map(one => (one === current ? (next as Item) : one))
95}
96
97/** An item completed with a dated ruling line added to its description. */
98export function settle(item: Item, ruling: string, date: string): Item {
99 return {
100 ...item,
101 status: 'completed',
102 description: [item.description, `Ruling (${date}): ${ruling}`].filter(Boolean).join('\n'),
103 }
104}
105
106/**
107 * A settled item whose ruling stopped holding, marked with a dated "Superseded" line naming the
108 * item that replaces it. It stays completed; the line is what shows it superseded.
109 */
110export function supersede(item: Item, by: string, why: string, date: string): Item {
111 const line = `Superseded (${date}) by ${by}${why ? `: ${why}` : ''}`
112 return { ...item, description: [item.description, line].filter(Boolean).join('\n') }
113}
114
115/** The settled item `label` replaces, by the Superseded line on it; undefined when there's none. */
116export function replaces(items: readonly Item[], label: string): Item | undefined {
117 if (!/^[DA]\d+$/.test(label)) return undefined
118 return items.filter(item => supersededIn(item.description)?.by === label).at(-1)
119}
120
121/** What an item replaces, as its card and the listing say it: "D2: <its ruling, or its question>". */
122export function replacedText(old: Item): string {
123 const ruling = rulingIn(old.description)
124 return `${old.label}: ${ruling ? rulingText(ruling) : splitBody(old.body).question}`
125}
126
127/**
128 * An open item revised in place: a new body if given, and a dated "Revised" line appended to the
129 * description, which says what changed. A changed body is recorded on that line too, so the
130 * description keeps what the user was shown before.
131 */
132export function revise(item: Item, change: { body?: string; note?: string }, date: string): Item {
133 const body = change.body ?? item.body
134 const note = change.note?.trim() || 'revised'
135 const was = body !== item.body ? ` (was: ${item.body})` : ''
136 return {
137 ...item,
138 body,
139 description: [item.description, `Revised (${date}): ${note}${was}`].filter(Boolean).join('\n'),
140 }
141}
142
143/**
144 * The queue rebuilt at session start or after compaction, merging rather than replacing:
145 * - task items come from the task files, or from `current` when they couldn't be read;
146 * - an item `closed` records as settled stays settled while its task file still shows it open,
147 * keeps the ruling and Superseded line the plugin recorded, and stays in the queue if its task
148 * file has gone (Claude Code deletes a list's task files once every task in it is completed);
149 * - ledger items are the stored ledger and the ones already in `current`, the latter winning.
150 */
151export function mergeHydrated(
152 fromFiles: readonly Item[] | null,
153 current: readonly Item[],
154 stored: { ledger: readonly Item[]; closed: Readonly<Record<string, Item>> },
155): Item[] {
156 const tasks = (fromFiles ?? current.filter(item => item.source === 'tasks')).map(item => {
157 const settled = stored.closed[item.id]
158 if (!settled) return item
159 // The task file may lack the ruling decision_close kept, and a Superseded line decision_supersede added.
160 const ruling = rulingIn(settled.description)
161 const marked = settled.description.split('\n').reverse().find(line => line.startsWith('Superseded ('))
162 let description = item.description
163 if (ruling && !rulingIn(description)) description = [description, ruling].filter(Boolean).join('\n')
164 if (marked && !description.split('\n').includes(marked)) description = [description, marked].filter(Boolean).join('\n')
165 return { ...item, status: isOpen(item) ? settled.status : item.status, description }
166 })
167 const gone = Object.values(stored.closed).filter(
168 item => item.source === 'tasks' && !tasks.some(task => task.id === item.id),
169 )
170 const ledger = current.filter(item => item.source === 'ledger')
171 for (const item of stored.ledger) {
172 if (item.source === 'ledger' && !ledger.some(one => one.id === item.id)) ledger.push(item)
173 }
174 return [...tasks, ...gone, ...ledger]
175}
176
177/**
178 * What a TaskUpdate's new subject does to the queue, decided before the tool runs:
179 * - `pass`: not a decision subject; the update goes through as written.
180 * - `subject`: go through with this subject, which keeps or carries the item's label.
181 * - `assign`: the task becomes a new item (or changes kind), so it needs a fresh label.
182 * - `deny`: refuse the update, for this reason.
183 */
184export type Retitle =
185 | { kind: 'pass' }
186 | { kind: 'subject'; subject: string }
187 | { kind: 'assign'; draft: Draft }
188 | { kind: 'deny'; reason: string }
189
190export function retitle(items: readonly Item[], taskId: string, subject: string): Retitle {
191 const draft = parseDraft(subject)
192 if (!draft) return { kind: 'pass' }
193 const found = problems(draft)
194 if (found.length) return { kind: 'deny', reason: found.join('; ') }
195 const id = String(taskId)
196 const current = items.find(one => one.source === 'tasks' && one.id === id)
197 // An item the hook never labelled ("D?") takes a label like a new one.
198 const known = current && labelNumber(current.label) > 0 ? current : undefined
199 const labelled = parseLabel(subject)
200 if (labelled) {
201 const label = `${labelled.letter}${labelled.number}`
202 if (known && label !== known.label) {
203 return { kind: 'deny', reason: `task ${id} is ${known.label}; keep its label or drop it and the hook adds it` }
204 }
205 if (labelled.letter !== LETTER[labelled.kind]) {
206 return { kind: 'deny', reason: `${label} can't be a ${labelled.kind} item; drop the label and the hook adds the right one` }
207 }
208 const holder = items.find(one => one.label === label && !(one.source === 'tasks' && one.id === id))
209 if (holder) return { kind: 'deny', reason: `${label} is already in use; drop the label and the hook adds one` }
210 return { kind: 'subject', subject }
211 }
212 if (known && known.label[0] === LETTER[draft.kind]) return { kind: 'subject', subject: formatSubject(known.label, draft) }
213 return { kind: 'assign', draft }
214}
215
216/** Items in the order they were asked, oldest first; unknown times sort first, by label. */
217export function ordered(items: readonly Item[]): Item[] {
218 return [...items].sort(
219 (a, b) =>
220 (a.created ?? 0) - (b.created ?? 0) ||
221 a.label[0]!.localeCompare(b.label[0]!) ||
222 labelNumber(a.label) - labelNumber(b.label),
223 )
224}
225
226export const subjectOf = (item: Item): string => `${item.label} ${item.kind}: ${item.body}`
227
228export function age(created: number | undefined, now: number): string {
229 if (!created) return ''
230 let minutes = Math.max(0, Math.floor((now - created) / 60_000))
231 if (minutes < 60) return `waiting ${minutes}m`
232 let hours = Math.floor(minutes / 60)
233 minutes %= 60
234 if (hours < 24) return `waiting ${hours}h ${minutes}m`
235 const days = Math.floor(hours / 24)
236 hours %= 24
237 return `waiting ${days}d ${hours}h`
238}
239
240/** The `/decisions` listing: open items, or with `all` every item and its ruling. */
241export function listing(items: readonly Item[], now: number, all = false): string {
242 const shown = ordered(items).filter(item => all || isOpen(item))
243 if (shown.length === 0) return all ? 'No decisions or actions this session.' : 'No open decisions or actions.'
244 const lines: string[] = []
245 for (const item of shown) {
246 const tags = item.source === 'ledger' ? ['ledger'] : []
247 const superseded = isOpen(item) ? null : supersededIn(item.description)
248 const tag = isOpen(item) ? age(item.created, now) : superseded ? 'superseded' : item.status
249 if (tag) tags.push(tag)
250 const revised = isOpen(item) ? revisedIn(item.description) : null
251 if (revised) tags.push(`revised ${revised}`)
252 lines.push(subjectOf(item) + (tags.length ? ` (${tags.join(', ')})` : ''))
253 const ruling = rulingIn(item.description)
254 if (ruling) lines.push(` ${ruling}`)
255 if (superseded) lines.push(` Superseded (${superseded.date}) by ${superseded.by}${superseded.why ? `: ${superseded.why}` : ''}`)
256 const old = replaces(items, item.label)
257 if (old) lines.push(` replaces ${replacedText(old)}`)
258 }
259 return lines.join('\n')
260}
261
262/** What the model is told after compaction or resume; null when nothing is open. */
263export function reminder(items: readonly Item[]): string | null {
264 const open = ordered(items).filter(isOpen)
265 if (open.length === 0) return null
266 const lines = ["Open items in this session's decision queue, still waiting on the user:"]
267 for (const item of open) {
268 lines.push(`- ${subjectOf(item)}${item.source === 'ledger' ? ' (fallback ledger)' : ''}`)
269 }
270 return lines.join('\n')
271}
272
273/**
274 * The prompt draft with one answer line per label: `lines` replace any line already answering
275 * the same label and are appended otherwise, so several presses build one message of answers.
276 */
277export function mergeAnswers(draft: string, lines: readonly string[]): string {
278 const out = draft.replace(/\s+$/, '').split('\n').filter((line, i, all) => line !== '' || i < all.length - 1)
279 if (out.length === 1 && out[0] === '') out.pop()
280 for (const line of lines) {
281 const label = line.slice(0, line.indexOf(':') + 1)
282 const at = out.findIndex(one => one.startsWith(label))
283 if (at < 0) out.push(line)
284 else out[at] = line
285 }
286 return out.join('\n')
287}
288hooks/lineage.ts 90 lines1// What the conversation itself says about its decision queue, read from its transcript, so a
2// session that comes back under a new id (a resume that changes it, a restart, a fork) can find
3// the stored record it came from. Nothing here touches `$`, so it's tested directly.
4
5import type { Item, SessionRecord } from '../types'
6import { isOpen } from './queue'
7import { parseLabel } from './subject'
8
9/** The parts of a `$.session.messages()` row this module reads. */
10export type Message = {
11 text?: string
12 toolUses?: readonly { tool: string; result?: unknown; text?: string; isError?: true }[]
13}
14
15/** One fallback-ledger item as the conversation saw it: every body it had, and whether it was closed. */
16export type Seen = { bodies: string[]; closed: boolean }
17
18/**
19 * What the transcript shows of the queue: the ledger items decision_add, decision_update and
20 * decision_close reported, by label, and every label the conversation has used, task-list ones
21 * included, so numbering never hands one out again.
22 */
23export type Trail = { ledger: Map<string, Seen>; labels: string[] }
24
25const CLOSED = /^([DA]\d+) closed$/
26const REMINDER_HEAD = "Open items in this session's decision queue"
27const REMINDER_LINE = /^- ([DA]\d+ (?:DECIDE|ACTION): [\s\S]*?) \(fallback ledger\)$/
28
29/** A tool's answer as text: the stored record when it's a string, otherwise what the model read. */
30function answer(use: { result?: unknown; text?: string }): string {
31 return (typeof use.result === 'string' ? use.result : (use.text ?? '')).trim()
32}
33
34const named = (tool: string, name: string) => tool === name || tool.endsWith(`__${name}`)
35
36export function trailOf(messages: readonly Message[]): Trail {
37 const ledger = new Map<string, Seen>()
38 const labels = new Set<string>()
39 const saw = (label: string, body: string) => {
40 labels.add(label)
41 const seen = ledger.get(label) ?? { bodies: [], closed: false }
42 if (!seen.bodies.includes(body)) seen.bodies.push(body)
43 ledger.set(label, seen)
44 }
45 for (const message of messages) {
46 const text = message.text ?? ''
47 if (text.includes(REMINDER_HEAD)) {
48 for (const line of text.split('\n')) {
49 const found = parseLabel(REMINDER_LINE.exec(line.trim())?.[1] ?? '')
50 if (found) saw(`${found.letter}${found.number}`, found.body)
51 }
52 }
53 for (const use of message.toolUses ?? []) {
54 if (use.isError) continue
55 if (named(use.tool, 'decision_add') || named(use.tool, 'decision_update')) {
56 const found = parseLabel(answer(use))
57 if (found) saw(`${found.letter}${found.number}`, found.body)
58 } else if (named(use.tool, 'decision_close')) {
59 const label = CLOSED.exec(answer(use))?.[1]
60 const seen = label ? ledger.get(label) : undefined
61 if (seen) seen.closed = true
62 } else if (use.tool === 'TaskCreate') {
63 const subject = (use.result as { task?: { subject?: unknown } } | undefined)?.task?.subject
64 const found = typeof subject === 'string' ? parseLabel(subject) : null
65 if (found) labels.add(`${found.letter}${found.number}`)
66 }
67 }
68 }
69 return { ledger, labels: [...labels] }
70}
71
72/**
73 * Whether a stored record is the one this conversation's ledger items came from: it holds every
74 * ledger item the transcript reported, by label, closed wherever the transcript saw it closed, and
75 * at least one word for word as the transcript has it. A label survives decision_update, so an
76 * item the other session revised later still matches; the word-for-word one keeps two sessions
77 * whose ledgers both start at D1 apart. Null when the transcript reports no ledger items, which
78 * says nothing either way.
79 */
80export function ledgerMatches(record: SessionRecord, trail: Trail): boolean | null {
81 if (trail.ledger.size === 0) return null
82 let exact = false
83 for (const [label, seen] of trail.ledger) {
84 const item: Item | undefined = record.ledger.find(one => one.source === 'ledger' && one.label === label)
85 if (!item || (seen.closed && isOpen(item))) return false
86 if (seen.bodies.includes(item.body)) exact = true
87 }
88 return exact
89}
90hooks/markdown.ts 123 lines1// Markdown in item text, for the places a card can't draw it: one-line rows, chips and toasts.
2// Nothing here touches `$`, so it's tested directly.
3
4const FENCE = /```[^\n]*\n([\s\S]*?)```/g
5const INLINE_CODE = /(`+)([\s\S]*?[^`])\1(?!`)/g
6
7/**
8 * Emphasis markers and link syntax dropped from text that holds no code. With `urls`, a link keeps
9 * its target after its text, `text (url)`, unless the text already reads as the url.
10 */
11function stripProse(text: string, urls = false): string {
12 return text
13 .replace(/!?\[([^\]]*)\]\(([^)\s]*)(?:\s+"[^"]*")?\)/g, (_, label: string, url: string) => {
14 if (!urls || !url) return label
15 return label.trim() && label.trim() !== url ? `${label} (${url})` : url
16 })
17 .replace(/<((?:https?|mailto):[^\s<>]+)>/gi, urls ? '$1' : '$&')
18 .replace(/\*\*(?=\S)([\s\S]*?\S)\*\*/g, '$1')
19 .replace(/(^|[^\w])__(?=\S)([\s\S]*?\S)__(?!\w)/g, '$1$2')
20 .replace(/~~(?=\S)([\s\S]*?\S)~~/g, '$1')
21 .replace(/(^|[^\w*])\*(?=[^\s*])([^*]*?[^\s*])\*(?![\w*])/g, '$1$2')
22 .replace(/(^|[^\w])_(?=[^\s_])([^_]*?[^\s_])_(?!\w)/g, '$1$2')
23}
24
25/**
26 * Markdown as the plain text it reads as: no `**`, `__`, `*`, `_` or `~~` around emphasis, no
27 * backticks around code (whose contents stay as written), and `[text](url)` as `text`, or with
28 * `urls` as `text (url)`.
29 */
30export function plainText(markdown: string, urls = false): string {
31 // Code stands aside as private-use placeholders while the markers go, so `**`x`**` loses both.
32 const code: string[] = []
33 const held = markdown
34 .replace(/[]/g, '')
35 .replace(FENCE, (_, body: string) => `${code.push(body.trimEnd()) - 1}`)
36 .replace(INLINE_CODE, (_, _ticks: string, body: string) => `${code.push(body.trim()) - 1}`)
37 return stripProse(held, urls).replace(/(\d+)/g, (_, n: string) => code[Number(n)] ?? '')
38}
39
40/** The code in markdown, fenced blocks first and then inline spans, each once and trimmed. */
41export function codeSpans(markdown: string): string[] {
42 const found: string[] = []
43 const add = (code: string | undefined) => {
44 const text = (code ?? '').trim()
45 if (text && !found.includes(text)) found.push(text)
46 }
47 for (const match of markdown.matchAll(FENCE)) add(match[1])
48 for (const match of markdown.replace(FENCE, '').matchAll(INLINE_CODE)) add(match[2])
49 return found
50}
51
52/**
53 * A link token as an href a `Link` element accepts (an `https:` URL or `http://localhost`, printable
54 * ASCII, no `@` or credentials, at most 2048 characters), spelled as `new URL` spells it; null for
55 * anything else, such as `#12` or `owner/repo#3`, which stays text.
56 */
57export function linkHref(token: string | null): string | null {
58 if (!token || !/^https?:\/\//i.test(token)) return null
59 let url: URL
60 try {
61 url = new URL(token)
62 } catch {
63 return null
64 }
65 const href = url.href
66 const local = url.protocol === 'http:' && url.hostname === 'localhost'
67 if (url.protocol !== 'https:' && !local) return null
68 if (url.username || url.password || href.includes('@')) return null
69 return href.length <= 2048 && /^[\x21-\x7e]+$/.test(href) ? href : null
70}
71
72/** A link token short enough to sit at the end of a card's button row: `#12`, `!4`, `owner/repo#3`. */
73export function isShortLink(token: string): boolean {
74 return /^(?:[\w.-]+\/[\w.-]+)?[#!]\d+$/.test(token)
75}
76
77// First path segments of github.com that aren't an owner.
78const GITHUB_PAGES = new Set(['apps', 'enterprise', 'features', 'login', 'marketplace', 'notifications', 'orgs', 'search', 'settings', 'sponsors', 'topics'])
79
80/**
81 * A github.com issue or pull request URL as `owner/repo#N`, a repository URL as `owner/repo`; null
82 * for any other URL, which a card shows whole.
83 */
84export function githubShort(href: string): string | null {
85 let url: URL
86 try {
87 url = new URL(href)
88 } catch {
89 return null
90 }
91 if (url.protocol !== 'https:' || !/^(www\.)?github\.com$/i.test(url.hostname)) return null
92 const [owner, repo, kind, number] = url.pathname.split('/').filter(Boolean)
93 if (!owner || !repo || GITHUB_PAGES.has(owner.toLowerCase())) return null
94 const name = `${owner}/${repo.replace(/\.git$/, '')}`
95 if (kind === undefined) return name
96 return (kind === 'issues' || kind === 'pull') && number && /^\d+$/.test(number) ? `${name}#${number}` : null
97}
98
99/**
100 * Markdown as plain text that keeps its line breaks, which tells a description with something to
101 * read from one of only blank lines and markers: lines,
102 * blank lines and list items (`- `, `1. `) stay where they are, `*` and `+` bullets become `- `,
103 * headings lose their `#`, emphasis and code markers go, and a link reads `text (url)`. Runs of
104 * blank lines squeeze to one.
105 */
106export function descriptionText(markdown: string): string {
107 let fenced = false
108 const shaped = markdown
109 .replace(/\r\n?/g, '\n')
110 .split('\n')
111 .map(line => {
112 if (/^\s*```/.test(line)) fenced = !fenced
113 else if (!fenced) return line.replace(/^(\s*)[*+](\s+)/, '$1-$2').replace(/^ {0,3}#{1,6}\s+(.*?)(?:\s+#+)?\s*$/, '$1')
114 return line
115 })
116 return plainText(shaped.join('\n'), true)
117 .split('\n')
118 .map(line => line.trimEnd())
119 .join('\n')
120 .replace(/\n{3,}/g, '\n\n')
121 .replace(/^\n+|\s+$/g, '')
122}
123hooks/more.ts 95 lines1// What the details view shows beyond an open card, and where a card's `[more]` goes.
2// Nothing here touches `$`, so it's tested directly.
3
4import { type Forge, refHref } from './forge'
5import { codeSpans, descriptionText, plainText } from './markdown'
6import { type BodyParts, shortRecommendation } from './subject'
7
8export const MORE = '[more]'
9
10/**
11 * The link and command the details view offers for an item: the link as a URL (as written, or a
12 * reference resolved on the repository's forge) for its `Link:` line and Copy link, and the first
13 * code span of the question or description for its Copy option; null for each it doesn't offer.
14 */
15export function detailsExtras(
16 parts: BodyParts,
17 description: string,
18 forge: Forge | null,
19): { url: string | null; code: string | null } {
20 const url = parts.link && /^https?:\/\//i.test(parts.link) ? parts.link : refHref(parts.link, forge)
21 return { url, code: codeSpans(`${parts.question}\n${description}`)[0] ?? null }
22}
23
24/**
25 * Whether a card cuts its recommendation short: the tag beside the label shortens the choice and
26 * the qualifier under the question doesn't carry the whole of it. The tag is cut from the plain
27 * text and the qualifier from the markdown, as the card draws them.
28 */
29export function recommendationCut(recommendation: string): boolean {
30 // shortRecommendation makes the qualifier the whole text exactly when it cuts the choice.
31 const whole = (text: string) => shortRecommendation(text).qualifier === text.trim()
32 return whole(plainText(recommendation)) && !whole(recommendation)
33}
34
35/**
36 * Whether the details view shows something an open card doesn't, so the card ends its text
37 * with `[more]`: a description, a recommendation the card cuts short, a link the details view spells out
38 * as a URL and offers to copy, or a command it offers to copy. With none of them the card is the
39 * whole item.
40 */
41export function hasMore(item: { parts: BodyParts; description: string }, forge: Forge | null): boolean {
42 if (descriptionText(item.description)) return true
43 if (item.parts.recommendation && recommendationCut(item.parts.recommendation)) return true
44 const extras = detailsExtras(item.parts, item.description, forge)
45 return extras.url !== null || extras.code !== null
46}
47
48/**
49 * Where `[more]` goes after a card's last line of text, `markdown`, drawn `width` columns wide: on
50 * that line's last row, one space after the text, when it fits there, or null for a row of its own.
51 * The line comes back split in two, `head` for the rows above (empty when it takes one row) and
52 * `tail` for its last row, which the card draws with `[more]` beside it; each part is whole
53 * markdown, so a split inside a span of emphasis or code gives null instead.
54 *
55 * The rows are worked out the way a terminal wraps plain words. A line whose drawn width can't be
56 * told from its text (a link, which a terminal without hyperlinks spells out, or anything outside
57 * printable ASCII), a word longer than a row, and an unknown width give null. A width that's off
58 * moves where the rows break, never draws `[more]` over the text.
59 */
60export function moreSplit(markdown: string, width: number | null): { head: string; tail: string } | null {
61 if (width === null || !Number.isFinite(width) || width <= MORE.length) return null
62 const source = markdown.trim()
63 const text = plainText(source)
64 if (!text || text !== plainText(source, true) || !/^[\x20-\x7e]*$/.test(text)) return null
65 const rows = wrapWords(text, width)
66 const last = rows?.at(-1)
67 if (!rows || last === undefined || last.length + 1 + MORE.length > width) return null
68 if (rows.length === 1) return { head: '', tail: source }
69 const words = source.split(/ +/)
70 const count = last.split(' ').length
71 const head = words.slice(0, -count).join(' ')
72 const tail = words.slice(-count).join(' ')
73 // Each part must read as its share of the line, so no marker is left open in either.
74 const same = (a: string, b: string) => a.replace(/ +/g, ' ') === b.replace(/ +/g, ' ')
75 return same(plainText(head), rows.slice(0, -1).join(' ')) && same(plainText(tail), last) ? { head, tail } : null
76}
77
78/** `line`'s rows when it wraps at word boundaries in `width` columns; null when a word won't fit a row. */
79function wrapWords(line: string, width: number): string[] | null {
80 const rows: string[] = []
81 let row = ''
82 for (const word of line.split(/ +/)) {
83 if (!word) continue
84 if (word.length > width) return null
85 if (!row) row = word
86 else if (row.length + 1 + word.length <= width) row += ` ${word}`
87 else {
88 rows.push(row)
89 row = word
90 }
91 }
92 if (row) rows.push(row)
93 return rows
94}
95hooks/forge.ts 220 lines1// Issue and merge or pull request references (`#12`, `!4`, `owner/repo#12`) as URLs on the forge
2// the session's repository lives on. Nothing here touches `$`, so it's tested directly.
3
4import { linkHref } from './markdown'
5
6export type ForgeKind = 'github' | 'gitlab' | 'forgejo'
7
8/**
9 * A repository on a forge whose URL scheme is known: its kind, host, and path (`owner/repo`).
10 * `root` is the forge's web root when it isn't `https://<host>` (another scheme, a port, a subpath).
11 */
12export type Forge = { kind: ForgeKind; host: string; repo: string; root?: string }
13
14/** Hosts the person named a forge kind for (the `forge_hosts` option), lowercase. */
15export type ForgeHosts = Readonly<Record<string, ForgeKind>>
16
17const KINDS: Readonly<Record<string, ForgeKind>> = { github: 'github', gitlab: 'gitlab', forgejo: 'forgejo', gitea: 'forgejo' }
18const HOST = /^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)*$/
19
20/**
21 * The `forge_hosts` option, `host=kind` entries split by commas or whitespace, as hosts and their
22 * kinds (`gitea` is read as `forgejo`, whose URLs it shares), with a note for each entry it can't
23 * use. A host named twice takes its last kind.
24 */
25export function parseForgeHosts(option: unknown): { hosts: ForgeHosts; notes: string[] } {
26 const hosts: Record<string, ForgeKind> = {}
27 const notes: string[] = []
28 const text = Array.isArray(option) ? option.join(',') : typeof option === 'string' ? option : ''
29 for (const entry of text.replace(/\s*=\s*/g, '=').split(/[\s,]+/).filter(Boolean)) {
30 const at = entry.indexOf('=')
31 const host = (at < 0 ? '' : entry.slice(0, at)).toLowerCase()
32 const name = entry.slice(at + 1).toLowerCase()
33 const kind = Object.hasOwn(KINDS, name) ? KINDS[name] : undefined
34 if (at < 0) notes.push(`"${entry}" is not host=kind`)
35 else if (!HOST.test(host)) notes.push(`"${entry}": "${host}" is not a host name`)
36 else if (!kind) notes.push(`"${entry}": the kind is github, gitlab, forgejo or gitea`)
37 else hosts[host] = kind
38 }
39 return { hosts, notes }
40}
41
42// Only hosts whose kind can be told from the name alone: a self-hosted forge on any other name
43// could be any of the three, and a wrong guess makes a link that goes somewhere else.
44function kindOf(host: string): ForgeKind | null {
45 if (host === 'github.com') return 'github'
46 if (host === 'gitlab.com' || host.startsWith('gitlab.')) return 'gitlab'
47 if (host === 'codeberg.org' || host.startsWith('forgejo.') || host.startsWith('gitea.')) return 'forgejo'
48 return null
49}
50
51const SEGMENT = /^[\w.-]+$/
52
53/** A repository path as `a/b` when each segment is safe and the forge allows that many. */
54function repoPath(kind: ForgeKind, path: string): string | null {
55 const segments = path.replace(/^\/+|\/+$/g, '').replace(/\.git$/i, '').split('/')
56 if (segments.some(one => !SEGMENT.test(one) || one === '.' || one === '..')) return null
57 // GitLab nests groups; GitHub and Forgejo have an owner and a name.
58 if (kind === 'gitlab' ? segments.length < 2 : segments.length !== 2) return null
59 return segments.join('/')
60}
61
62/**
63 * The forge a git remote URL points at: `https://host/owner/repo(.git)`, `ssh://[user@]host[:port]/owner/repo`
64 * or `user@host:owner/repo`. `hosts` names the kind of a host it lists, before the built-in rules,
65 * and `kind`, when given, wins over both. Null for a host none of them names the kind of, or a
66 * path it can't use.
67 */
68export function forgeOf(remote: string, hosts: ForgeHosts = {}, kind?: ForgeKind): Forge | null {
69 const text = remote.trim()
70 let host: string
71 let path: string
72 const scp = /^(?:[\w.-]+@)?([\w.-]+):(?!\/\/)(.+)$/.exec(text)
73 if (/^[a-z][a-z0-9+.-]*:\/\//i.test(text)) {
74 let url: URL
75 try {
76 url = new URL(text)
77 } catch {
78 return null
79 }
80 if (!['https:', 'http:', 'ssh:', 'git:', 'git+ssh:', 'ssh+git:'].includes(url.protocol)) return null
81 host = url.hostname
82 path = url.pathname
83 } else if (scp) {
84 host = scp[1] ?? ''
85 path = scp[2] ?? ''
86 } else {
87 return null
88 }
89 host = host.toLowerCase()
90 const named = kind ?? hostKind(host, hosts)
91 if (!named) return null
92 const repo = repoPath(named, path)
93 return repo ? { kind: named, host, repo } : null
94}
95
96function hostKind(host: string, hosts: ForgeHosts): ForgeKind | null {
97 return (Object.hasOwn(hosts, host) ? hosts[host] : undefined) ?? kindOf(host)
98}
99
100/**
101 * The per-repository override, as git config keys (set per clone with `git config`). The names
102 * aren't this plugin's own so that forge-tracker, which asks the same question, can read them too.
103 */
104export const OVERRIDE_KEYS = { forge: 'tracker.forge', web: 'tracker.web' } as const
105
106/** A repository's own answer to which forge its references link to. */
107export type ForgeOverride = { kind?: ForgeKind; web?: string }
108
109/**
110 * The override from `git config --get-regexp` output (`key value` lines), with a note for each
111 * value it can't use. A key set twice takes its last value, as `git config --get` does.
112 */
113export function parseOverride(config: string): { override: ForgeOverride; notes: string[] } {
114 const values = new Map<string, string>()
115 for (const line of config.split('\n')) {
116 const match = /^(\S+)[ \t]*(.*)$/.exec(line.trim())
117 if (match?.[1]) values.set(match[1].toLowerCase(), (match[2] ?? '').trim())
118 }
119 const override: ForgeOverride = {}
120 const notes: string[] = []
121 const forge = values.get(OVERRIDE_KEYS.forge)
122 if (forge !== undefined) {
123 const name = forge.toLowerCase()
124 const kind = Object.hasOwn(KINDS, name) ? KINDS[name] : undefined
125 if (kind) override.kind = kind
126 else notes.push(`${OVERRIDE_KEYS.forge} "${forge}": the kind is github, gitlab, forgejo or gitea`)
127 }
128 const web = values.get(OVERRIDE_KEYS.web)
129 if (web !== undefined) {
130 if (webParts(web)) override.web = web
131 else notes.push(`${OVERRIDE_KEYS.web} "${web}" is not the https URL of a repository`)
132 }
133 return { override, notes }
134}
135
136/** A web URL as its parsed form and its path segments, when each segment is safe; else null. */
137function webParts(web: string): { url: URL; segments: string[] } | null {
138 let url: URL
139 try {
140 url = new URL(web.trim())
141 } catch {
142 return null
143 }
144 if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash) return null
145 if (!HOST.test(url.hostname)) return null
146 const segments = url.pathname.replace(/^\/+|\/+$/g, '').replace(/\.git$/i, '').split('/')
147 if (segments.length < 2 || segments.some(one => !SEGMENT.test(one) || one === '.' || one === '..')) return null
148 return { url, segments }
149}
150
151/**
152 * The forge a repository's web URL names, as `kind`. GitHub and Forgejo take the last two path
153 * segments as the repository and anything before them as the forge's subpath. GitLab's groups
154 * nest, so there the whole path is the project and the forge sits at the host's root.
155 */
156export function webForge(web: string, kind: ForgeKind): Forge | null {
157 const parts = webParts(web)
158 if (!parts) return null
159 const { url, segments } = parts
160 const split = kind === 'gitlab' ? 0 : segments.length - 2
161 const host = url.hostname
162 const repo = segments.slice(split).join('/')
163 const root = [url.origin, ...segments.slice(0, split)].join('/')
164 return root === `https://${host}` ? { kind, host, repo } : { kind, host, repo, root }
165}
166
167/**
168 * The session repository's forge. With `web` overridden, that URL is the repository and `kind` (or
169 * else what `hosts` and the built-in rules say of its host) the forge. With only `kind`, the
170 * remote's host and path on that kind of forge. With neither, the remote as `forgeOf` reads it.
171 */
172export function resolveForge(remote: string, hosts: ForgeHosts, override: ForgeOverride = {}): Forge | null {
173 if (override.web) {
174 const host = webParts(override.web)?.url.hostname ?? ''
175 const kind = override.kind ?? hostKind(host, hosts)
176 return kind ? webForge(override.web, kind) : null
177 }
178 return remote ? forgeOf(remote, hosts, override.kind) : null
179}
180
181const REF = /^(?:([\w.-]+(?:\/[\w.-]+)+))?([#!])(\d+)$/
182
183/**
184 * A reference as its URL on `forge`: `#N` an issue (GitHub and Forgejo send an issue URL on to a
185 * pull request with that number), `!N` a merge or pull request, and `owner/repo#N` the same in
186 * another repository on that host. Null with no forge, or for anything else.
187 */
188export function refHref(token: string | null, forge: Forge | null): string | null {
189 if (!token || !forge) return null
190 const match = REF.exec(token)
191 if (!match) return null
192 const repo = match[1] ? repoPath(forge.kind, match[1]) : forge.repo
193 if (!repo) return null
194 const isIssue = match[2] === '#'
195 const number = match[3]
196 const where =
197 forge.kind === 'github'
198 ? isIssue ? 'issues' : 'pull'
199 : forge.kind === 'gitlab'
200 ? isIssue ? '-/work_items' : '-/merge_requests'
201 : isIssue ? 'issues' : 'pulls'
202 return linkHref(`${forge.root ?? `https://${forge.host}`}/${repo}/${where}/${number}`)
203}
204
205// What a reference in prose must not be part of: code, a markdown link, an autolink or a bare URL,
206// each kept as it is. Then a reference standing on its own: not inside a word, a path, an HTML
207// entity (`{`) or a markdown image (`![`).
208const PROSE_REF =
209 /(```[\s\S]*?```|(`+)[\s\S]*?\2|!?\[[^\]]*\]\([^)]*\)|<[^>\s]+>|https?:\/\/[^\s<>]+)|(?<![\w/&#!\]])((?:[\w.-]+\/[\w.-]+)?[#!]\d+)(?![\w#!/[])/g
210
211/** Markdown with each reference in its prose written as a link to it on `forge`. */
212export function linkRefs(markdown: string, forge: Forge | null): string {
213 if (!forge) return markdown
214 return markdown.replace(PROSE_REF, (whole: string, kept: string | undefined, _ticks, ref: string | undefined) => {
215 if (kept !== undefined || !ref) return whole
216 const href = refHref(ref, forge)
217 return href ? `[${ref}](${href})` : whole
218 })
219}
220hooks/handoff.ts 250 lines1// Find the lines of a reply that hand work back to the user without a queue entry.
2//
3// A reply that ends with "left for you: merge #12, run this on each host" and queues none of it is
4// the slip the skill's rule can't catch on its own. The misses that matter most are ACTION items
5// described in prose: a secret only the user can put in Vault, a prompt only they can approve, an
6// offer to go ahead once they say so. Those never block the assistant, so nothing in its own loop
7// notices them. The check looks for phrases that defer work to the user or say the assistant can't
8// do a step, skips anything conditional, negated, quoted, in code, describing what some other
9// agent or document will say, or talking about this check itself, and treats a line as queued
10// when it names a label in the queue or matches an item already there. A label the reply names
11// that isn't in the queue at all ("A24 is in the queue") is flagged on its own: it is the reply
12// asserting an item the assistant never created.
13
14import type { Item } from '../types'
15
16// A heading or lead-in line that introduces a list of what's left for the user: the phrase, then
17// at most a few words ("Left for you (both repos)").
18const HEADING =
19 /^(?:(?:still |what's )?left (?:for|to) you|(?:still )?(?:needs?|waiting on|blocked on) (?:from )?you|for you to (?:do|handle|run|merge|review|decide)|your (?:turn|call|move|to-?dos?|action items?)|(?:action items?|next steps?|to-?dos?|manual steps?|steps?) (?:for|left for|only) you(?: can do| to do)?|what (?:you(?:'ll| will)?|still) need(?:s)? (?:to do|from you)|over to you|you(?:'ll| will)? need to(?: do)?|only you can do|on your (?:end|side))\b[^.!?]{0,30}$/i
20
21// Steps that only the user can take: access, secrets, prompts, accounts, money, hardware.
22const USER_STEP =
23 'merge|run|approve|deploy|push|restart|rotate|log ?in|sign ?in|re-?auth\\w*|install|enable|grant|provision|upload|create|add|set|configure|decide|choose|pick|confirm|review|update|apply|reboot|redeploy|put|store|paste|enter|answer|unlock|accept|touch|tap|press|click|share|invite|pay|buy|order|plug|call|email|contact|request|register|renew|verify|authori[sz]e|authenticate|generate|revoke|sign'
24
25// Something a prompt, a key or an account asks the user to act on.
26const PROMPTED = '(?:prompts?|dialogs?|requests?|notifications?|pop-?ups?|keys?|yubikey|passkey|2fa|mfa|otp|codes?|push(?:es)?)'
27const SECRET = '(?:secrets?|tokens?|passwords?|passphrases?|credentials?|(?:api |ssh |deploy |private )?keys?)'
28
29// Where a sentence starts, or an imperative is plainly addressed to the reader.
30const IMPERATIVE = "(?:^|[.;:!]\\s+|\\b(?:please|just|then)\\s+)"
31
32// A phrase anywhere in a line that hands a step to the user.
33const INLINE: readonly RegExp[] = [
34 /\b(?:left|leaving (?:it|this|that|these|those|them)) (?:for|to) you\b/i,
35 /\bover to you\b/i,
36 // "only you can approve the merge", but not "the questions only you can answer".
37 /\bonly you can\b(?! (?:answer|know|say|tell|judge|weigh|decide|settle)\b(?:\s+(?:below|above|here|later))?\s*(?:[.,;:!?)]|$|(?:and|or|but)\b))/i,
38 /\byour call\b/i,
39 new RegExp(`\\bfor you to (?:${USER_STEP})\\b`, 'i'),
40 new RegExp(`\\byou(?:['’]ll| will)? (?:need|have) to (?:${USER_STEP})\\b`, 'i'),
41 new RegExp(`\\bplease (?:${USER_STEP})\\b`, 'i'),
42 /\brun (?:this|these|it|that|the (?:following|commands?|script)(?: below)?) on (?:each|every|all|your|both)\b/i,
43 // What's blocked on the user, said as a fact rather than a request.
44 /\bthe (?:only|one|last) thing (?:blocking|holding up|standing between|in the way of|stopping|gating|left before)\b/i,
45 // "The build is waiting on you", but not "what's waiting on you" or "everything it's waiting on
46 // you for", which describe a list rather than hand anything over.
47 /(?<!\bwhat)(?:\s(?:is|are)|['’](?:s|re)) (?:still |now )?(?:waiting|blocked) (?:on|for) (?:you\b(?!\s+for\b)|your (?!own\b))/i,
48 /\bneeds? your (?:[\w-]+ ){0,2}(?:approval|sign-?off|credentials?|password|passphrase|token|key|login|touch|go-?ahead|ok|okay|confirmation|answer|decision|input)\b/i,
49 // The assistant can't do the step, so the user has to.
50 /\bI (?:can(?:no|['’])?t|cannot|can not|am unable to|have no way to)\b[^.;!?]{0,60}\bfor you\b/i,
51 /\bI (?:can(?:no|['’])?t|cannot|can not|am unable to) (?:access|reach|write to|log ?in(?: ?to)?|sign ?in(?: ?to)?|ssh (?:in)?to|unlock|answer|approve)\b/i,
52 /\bI (?:(?:don['’]t|do not) have|have no) (?:the )?(?:access|permissions?|credentials?|rights)\b/i,
53 // An offer that waits on the user's word.
54 /\b(?:say the word|give me the (?:go-?ahead|green light|word))\b/i,
55 // An imperative step only the user can take: a prompt to approve, a secret to put somewhere.
56 new RegExp(`${IMPERATIVE}(?:approve|answer|accept|confirm|unlock|touch|tap)\\s+(?:the |that |this |each |every |your )?(?:[\\w-]+\\s+){0,3}${PROMPTED}\\b`, 'i'),
57 new RegExp(`${IMPERATIVE}(?:put|store|add|paste|set|save|write|load)\\s+(?:the |that |this |your |a |an |both )?(?:[\\w-]+\\s+){0,3}${SECRET}\\b[^.;]{0,40}\\b(?:in|into|to|under)\\b`, 'i'),
58]
59
60// The phrase is hedged or negated: "if you need to roll back", "you won't need to", "no longer".
61const HEDGE = /\b(?:if|unless|in case|should|whenever|until|before|after)\b[^.;:]*$|(?:\b\w+n['’]t|\bno longer|\bnever|\bnot|\bnothing)\s+(?:\w+\s+){0,2}$/i
62
63// A sentence about what another agent, a document or a tool will produce, which hands nothing to
64// the user however it words that output: "It'll lay out ... the questions only you can answer",
65// "The report lists the steps you'll need to run". A future that waits on the user ("it'll need
66// your approval", "that'll be your call") still counts.
67const DESCRIBED =
68 /^\s*(?:it|they|this|that|the [\w-]+(?: [\w-]+){0,2})(?:(?:['’]ll| will| would|['’]d) (?!need\b|have to\b|require|wait|block|be (?:left|waiting|blocked|up to|your|on you|over))|\s+(?:lists|lays out|covers|includes|describes|explains|names|shows|asks|outlines|summari[sz]es|gives|proposes|recommends|contains|mentions|flags|prints|writes|reports|returns|produces|generates|outputs|emits|suggests|offers|drafts)\b)/i
69
70// A line about the hand-off check itself, such as a note on a false alarm.
71const ABOUT_CHECK = /\bhand-?offs? (?:check|warning|nudge|reminder|toast|alarm)|\bfalse (?:positive|alarm)|\bnot queued:/i
72
73const LABEL = /\b[DA]\d+\b/
74// A queue label as a word of its own: not "D3.js", "A4-size" or a path.
75const LABELS = /(?<![\w./#-])[DA]\d{1,3}(?![\w-]|\.\w)/g
76const LIST_ITEM = /^\s*(?:[-*+]|\d+[.)])\s+/
77const FENCE = /^\s*(?:```|~~~)/
78// Quoted and code spans: straight and curly double quotes, curly single quotes, backticks, and
79// straight single quotes that open and close a span rather than an apostrophe.
80const QUOTED = /"[^"\n]*"|“[^”\n]*”|‘[^’\n]*’|`[^`\n]*`|(?<![\w'])'[^'\n]+'(?![\w'])/g
81const REF = /(?:[\w.-]+\/[\w.-]+)?[#!]\d+|https?:\/\/[^\s)\]>]+/g
82const STOP = new Set(
83 'that this with from have your them they then than when what will would could should there their these those about into once each also just only still need needs here been were which while after before being does done make sure'.split(' '),
84)
85
86const words = (text: string): string[] =>
87 [...new Set((text.toLowerCase().match(/[a-z][a-z0-9-]{3,}/g) ?? []).filter(word => !STOP.has(word)))]
88const refs = (text: string): string[] => (text.match(REF) ?? []).map(ref => ref.replace(/[.,;:]+$/, '').toLowerCase())
89
90/** The line with list markers, emphasis, heading marks and a trailing colon taken off. */
91function bare(line: string): string {
92 return line
93 .replace(LIST_ITEM, '')
94 .replace(/^#{1,6}\s+/, '')
95 .replace(/[*_`]/g, '')
96 .replace(/\s*:\s*$/, '')
97 .trim()
98}
99
100/** The line with its quoted and code spans blanked out, so a phrase inside one doesn't count. */
101function unquoted(line: string): string {
102 return line.replace(QUOTED, ' … ')
103}
104
105/** Whether most of a line is quotation; a code span is a command to run, not a quotation. */
106function mostlyQuoted(line: string): boolean {
107 const quoted = (line.match(QUOTED) ?? []).filter(span => !span.startsWith('`')).join('').replace(/\s/g, '').length
108 return quoted * 2 >= line.replace(/\s/g, '').length
109}
110
111/** The sentence of `line` that the phrase at `index` sits in, up to the phrase. */
112function sentenceBefore(line: string, index: number): string {
113 const before = line.slice(0, index)
114 return before.slice(Math.max(before.lastIndexOf('. '), before.lastIndexOf('? '), before.lastIndexOf('! ')) + 1)
115}
116
117/** Whether the phrase at `index` in `line` is hedged or negated in its own sentence. */
118function hedged(line: string, index: number): boolean {
119 return HEDGE.test(sentenceBefore(line, index))
120}
121
122/** Whether the phrase's sentence describes what some other agent, document or tool will say. */
123function described(line: string, index: number): boolean {
124 // The verb after "will" can be the phrase itself ("it'll need your approval"), so read on past it.
125 return DESCRIBED.test(sentenceBefore(line, index) + line.slice(index))
126}
127
128/** Whether a sentence holding the phrase is a question, which asks rather than hands off. */
129function asked(line: string, index: number): boolean {
130 const rest = line.slice(index)
131 const end = rest.search(/[.!?](?:\s|$)/)
132 return end >= 0 && rest[end] === '?'
133}
134
135/** Whether `line` (trimmed, its markup intact) hands a step over by itself. */
136function handsOff(line: string): boolean {
137 if (ABOUT_CHECK.test(line) || mostlyQuoted(line.replace(LIST_ITEM, '').replace(/[*_]/g, ''))) return false
138 const text = bare(unquoted(line))
139 for (const pattern of INLINE) {
140 const found = pattern.exec(text)
141 if (found && !hedged(text, found.index) && !asked(text, found.index) && !described(text, found.index)) return true
142 }
143 return false
144}
145
146/** The queue labels a line names outside its quoted and code spans. */
147function labelsIn(line: string): string[] {
148 return unquoted(line).match(LABELS) ?? []
149}
150
151/**
152 * Whether an item in the queue already covers the line: one shares a reference (`#12`, `!4`, a
153 * URL) with it, or at least half its words, and two or more.
154 */
155function covered(line: string, queue: readonly Item[]): boolean {
156 const lineRefs = refs(line)
157 const lineWords = words(line)
158 return queue.some(item => {
159 const text = `${item.body}\n${item.description}`
160 const itemRefs = refs(text)
161 if (lineRefs.some(ref => itemRefs.includes(ref))) return true
162 const itemWords = new Set(words(text))
163 const shared = lineWords.filter(word => itemWords.has(word)).length
164 return shared >= 2 && shared * 2 >= lineWords.length
165 })
166}
167
168/** The prose lines of a reply, with code blocks and quoted lines left out. */
169function* prose(reply: string): Generator<string> {
170 let fenced = false
171 for (const raw of (reply ?? '').split('\n')) {
172 if (FENCE.test(raw)) {
173 fenced = !fenced
174 continue
175 }
176 if (fenced || /^\s*>/.test(raw)) continue
177 yield raw
178 }
179}
180
181export type Options = {
182 /**
183 * Every label in the session's queue, settled items included. When given, a line counts as
184 * queued only by a label in it, and a line naming a label that isn't is flagged. Without it,
185 * any label counts.
186 */
187 known?: readonly string[]
188 /** At most this many lines come back. */
189 limit?: number
190}
191
192/**
193 * The lines of `reply` that hand work to the user with no label and no matching item in `queue`:
194 * the items listed under a hand-off heading ("Left for you:"), lines that hand a step over
195 * themselves ("You'll need to merge #12", "I can't write to Vault for you"), and, with `known`,
196 * lines naming a label that isn't in the queue. Code blocks and quotes are skipped.
197 */
198export function handoffs(reply: string, queue: readonly Item[], options: Options = {}): string[] {
199 const { known, limit = 5 } = options
200 const found: string[] = []
201 let section = false
202 for (const raw of prose(reply)) {
203 const line = raw.trim()
204 if (!line) continue
205 const text = bare(line)
206 const isItem = LIST_ITEM.test(raw)
207 // A section runs from its heading through the list under it, blank lines and indented
208 // continuations included, and ends at the first unindented line that isn't a list item.
209 if (section && !isItem && !/^\s/.test(raw)) section = false
210 if (!isItem && text.length <= 80 && HEADING.test(text) && (/:\s*$/.test(line) || /^#{1,6}\s/.test(line) || /^\*\*.*\*\*:?$/.test(line))) {
211 section = true
212 continue
213 }
214 const named = labelsIn(line)
215 if (known && named.some(label => !known.includes(label))) {
216 found.push(text)
217 } else {
218 const candidate = (section && isItem) || handsOff(line)
219 const labelled = known ? named.length > 0 : LABEL.test(line)
220 if (!candidate || labelled || covered(text, queue)) continue
221 found.push(text)
222 }
223 if (found.length >= limit) break
224 }
225 return found
226}
227
228/** The labels `reply` names, outside code and quotes, that aren't in `known`. */
229export function unknownLabels(reply: string, known: readonly string[]): string[] {
230 const missing = new Set<string>()
231 for (const raw of prose(reply)) for (const label of labelsIn(raw)) if (!known.includes(label)) missing.add(label)
232 return [...missing]
233}
234
235/** What the model is told on its next turn about the hand-offs its last reply left unqueued. */
236export function nudge(lines: readonly string[], missing: readonly string[] = []): string {
237 const named =
238 missing.length === 0
239 ? []
240 : [
241 `Your reply named ${missing.join(', ')}, but ${missing.length === 1 ? 'no such item is' : 'none of those are'} in the queue: the item was never created. Create it now (the hook picks its label, which may differ, so correct the reference in your next message), and from here on make the tool call before writing the sentence that names a label.`,
242 ]
243 return [
244 'session-decisions: your last reply handed these to the user without a queue entry:',
245 ...lines.map(line => `- ${line}`),
246 ...named,
247 'Anything still waiting on the user goes in the decision queue, even when it never blocks your own work and even when you could do it if asked: a secret or credential to put somewhere, a prompt or key to approve, access only they have, a merge, a step on their hosts, a decision. Describing it in prose, or in a summary, does not queue it. TaskCreate (a deferred tool; load it with ToolSearch first), or decision_add only when TaskCreate is not in this session. Ignore a line that is not a hand-off, or one the user has already dealt with.',
248 ].join('\n')
249}
250hooks/reconcile.ts 111 lines1// The reconcile pass: what the assistant is handed to check every open item against the session
2// and propose closing, revising or keeping each in one table. The plugin gathers the facts (the
3// open items with their age and link, and the lines of the person's own messages that name them);
4// judging the evidence and asking is the assistant's, as the skill describes. Nothing here touches
5// `$`, so it's tested directly.
6
7import type { Item } from '../types'
8import { age, isOpen, ordered, replacedText, replaces } from './queue'
9import { revisedIn, splitBody } from './subject'
10
11/** The parts of a `$.session.messages()` row this module reads. */
12export type Said = { role?: string; text?: string }
13
14/** The prompt `/decisions reconcile` sends, ahead of the brief. It names no label of its own. */
15export const RECONCILE = `Reconcile this session's decision queue, as the session-decisions skill describes. Check every open item in the queue brief above (call decision_list if it isn't there) against this session for evidence that it's settled: my own words answering it, by label or by subject; a merged pull request or closed issue it links to, which you check now; or a later item that supersedes it. Propose in one table, one row per item, close (with my words quoted, or the forge state named, as the ruling), update (the new subject, when the question or recommendation has drifted), or keep, which is the answer whenever the evidence is ambiguous. Change nothing until I answer; then apply what I approve in one message, every call together, and report what changed.`
16
17// User-role rows the person didn't write: the plugin's own reminder and the prompts
18// `/decisions reconcile` and `/decisions wrap` send, which quote the queue and earlier answers, and
19// the summary compaction leaves in place of the conversation it replaced.
20const NOT_THEIRS = [
21 /Open items in this session's decision queue/,
22 /^(?:Reconcile|Wrap up) this session's decision queue/,
23 /^This session is being continued from a previous conversation/,
24]
25// A line that only repeats the queue: a listing line (`D3 DECIDE: ...`) or a table row.
26const QUEUE_LINE = /^\s*(?:[-*]\s+)?(?:[DA]\d+ (?:DECIDE|ACTION):|\|)/
27const MAX_LINE = 200
28
29const cell = (text: string) => text.replace(/\s+/g, ' ').replace(/\|/g, '\\|').trim()
30
31/** The label as a word of its own: `D3` but not `D31`, `D3.js` or `#D3`. */
32function labelPattern(label: string): RegExp {
33 return new RegExp(`(?<![\\w./#-])${label}(?![\\w-]|\\.\\w)`)
34}
35
36/**
37 * The open items as a markdown table: label (marked when it's a fallback-ledger item, which closes
38 * with decision_close), kind, how long it has waited and when it was last revised, its link, and
39 * its text with the recommendation, and the settled item it replaces, when it supersedes one.
40 * `items` may hold settled items too; only the open ones get a row.
41 */
42export function inventory(items: readonly Item[], now: number): string {
43 const open = ordered(items).filter(isOpen)
44 if (open.length === 0) return 'No open decisions or actions.'
45 const rows = ['| Label | Kind | Waiting | Link | Item |', '| --- | --- | --- | --- | --- |']
46 for (const item of open) {
47 const parts = splitBody(item.body)
48 const waited = age(item.created, now).replace('waiting ', '') || 'unknown'
49 const revised = revisedIn(item.description)
50 const asked = parts.recommendation ? `${parts.question} (recommend ${parts.recommendation})` : parts.question
51 // An item that replaces a settled one whose ruling stopped holding says which, and what it said.
52 const old = replaces(items, item.label)
53 const text = old ? `${asked} (supersedes ${replacedText(old)})` : asked
54 rows.push(
55 `| ${item.label}${item.source === 'ledger' ? ' (ledger)' : ''} | ${item.kind} | ${waited}${revised ? `, revised ${revised}` : ''} | ${cell(parts.link ?? 'none')} | ${cell(text)} |`,
56 )
57 }
58 return rows.join('\n')
59}
60
61/**
62 * The lines of the person's own messages that name each label, oldest first, the newest `max` per
63 * label; a label nothing names is left out. These are the "D3: go with X" and "A2: done" lines the
64 * queue's buttons write, and anything else the person typed about an item by its label.
65 */
66export function mentions(messages: readonly Said[], labels: readonly string[], max = 3): Map<string, string[]> {
67 const found = new Map<string, string[]>()
68 // An item the hook never labelled ("D?") has no label the person could have written.
69 const patterns = labels.filter(label => /^[DA]\d+$/.test(label)).map(label => [label, labelPattern(label)] as const)
70 for (const message of messages) {
71 if (message.role !== 'user') continue
72 const text = message.text ?? ''
73 if (NOT_THEIRS.some(pattern => pattern.test(text))) continue
74 for (const raw of text.split('\n')) {
75 const line = raw.trim()
76 if (!line || QUEUE_LINE.test(line)) continue
77 for (const [label, pattern] of patterns) {
78 if (!pattern.test(line)) continue
79 const lines = found.get(label) ?? []
80 lines.push(line.length > MAX_LINE ? `${line.slice(0, MAX_LINE - 1)}…` : line)
81 found.set(label, lines.slice(-max))
82 }
83 }
84 }
85 return found
86}
87
88/** What a reconcile pass starts from: the open items, then what the person wrote that names them. */
89export function brief(items: readonly Item[], messages: readonly Said[], now: number): string {
90 const open = ordered(items).filter(isOpen)
91 if (open.length === 0) return 'No open decisions or actions.'
92 const said = mentions(
93 messages,
94 open.map(item => item.label),
95 )
96 // A label two open items share (as two unlabelled "D?" items do) is listed once.
97 const seen = new Set<string>()
98 const lines = [`Open items (${open.length}):`, '', inventory(items, now), '']
99 if (said.size === 0) {
100 lines.push("The user's messages name none of these labels; look for answers by subject.")
101 } else {
102 lines.push("Lines of the user's messages that name them, oldest first:")
103 for (const item of open) {
104 if (seen.has(item.label)) continue
105 seen.add(item.label)
106 for (const line of said.get(item.label) ?? []) lines.push(`- ${item.label}: "${line}"`)
107 }
108 }
109 return lines.join('\n')
110}
111hooks/version.ts 40 lines1/**
2 * The oldest Claude Code this plugin runs on. CI runs the tests on this release as well as the
3 * current one, and reads it from this line, so keep it a plain string literal.
4 *
5 * 2.1.295 is the first release whose Button takes Text children (the accent `[more]`); 2.1.300 is
6 * the release the README and the comments describe. Raise it whenever the plugin should use
7 * something a newer release adds, rather than working around older ones.
8 */
9export const MIN_CLAUDE_CODE = '2.1.300'
10
11/** `2.1.300`, `2.1.300-dev` or `2.1.300-dev.20260920...` as [2, 1, 300]; null for anything else. */
12export function parseVersion(version: string): [number, number, number] | null {
13 const found = /^(\d+)\.(\d+)\.(\d+)(?:[-+.\s]|$)/.exec(version.trim())
14 return found ? [Number(found[1]), Number(found[2]), Number(found[3])] : null
15}
16
17/** Whether `version` is older than `minimum`; null when either isn't spelled as a release. */
18export function isOlder(version: string, minimum: string = MIN_CLAUDE_CODE): boolean | null {
19 const have = parseVersion(version)
20 const need = parseVersion(minimum)
21 if (!have || !need) return null
22 for (let i = 0; i < 3; i++) {
23 if (have[i]! !== need[i]!) return have[i]! < need[i]!
24 }
25 return false
26}
27
28/**
29 * Why the plugin stays off on the engine `version` reports, or null when it can run. A version not
30 * spelled as a release (a build from source) runs; one older than the minimum doesn't, and neither
31 * does null, an engine whose `$.session.version()` failed.
32 */
33export function refusal(version: string | null): string | null {
34 if (version === null) {
35 return `needs Claude Code ${MIN_CLAUDE_CODE} or newer and couldn't read this one's version; its pane, footer, /decisions and checks are off. Run claude update.`
36 }
37 if (isOlder(version) !== true) return null
38 return `needs Claude Code ${MIN_CLAUDE_CODE} or newer; this is ${version}. Its pane, footer, /decisions and checks are off until you run claude update.`
39}
40hooks/subject.ts 205 lines1// Parse, validate and format the subjects of decision items.
2//
3// A labelled subject is "<label> <KIND>: <body>", for example
4// "D3 DECIDE: retire the old deploy script? (recommend yes) [#812]".
5// The assistant writes "DECIDE: ..." or "ACTION: ..."; the TaskCreate hook adds the label.
6
7import type { Kind, Letter } from '../types'
8
9export const LETTER: Record<Kind, Letter> = { DECIDE: 'D', ACTION: 'A' }
10
11// An optional label the assistant typed ("D12 ", "D7: ", "[D7] ", "(A2) ", "D7 - "), the kind
12// keyword, a colon, then the body. The label is dropped, so the hook numbers the item itself. The
13// keyword is case-sensitive, so an ordinary task titled "Action: refactor the parser" isn't a
14// decision item.
15const DRAFT = /^\s*(?:[[(]?[DA]\d+[\])]?[\s:.\-\u2013\u2014]*)?(DECIDE|ACTION)\s*:\s*([\s\S]*?)\s*$/
16const LABELLED = /^([DA])(\d+) (DECIDE|ACTION): ([\s\S]*)$/
17// The link is the bracketed token at the very end of the body, in one of the forms the skill
18// lists: #123, !45, owner/repo#123 (or !45), an http(s) URL, or "no link". Any other trailing
19// bracket, such as "press [Enter]", isn't a link.
20const LINK =
21 /\[\s*(#\d+|!\d+|[\w.-]+(?:\/[\w.-]+)+[#!]\d+|https?:\/\/[^\s[\]]+|no\s+link)\s*\]$/i
22const NO_LINK = /^no\s+link$/i
23// "(recommend <choice>" or "(recommend: <choice>", up to the start of the choice.
24const RECOMMEND = /\(recommend(?:\s*:\s*|\s+)(?=\S)/gi
25
26export type Draft = { kind: Kind; body: string }
27export type Label = { letter: Letter; number: number; kind: Kind; body: string }
28
29/** The draft when the subject is a decision item; null for any other task. */
30export function parseDraft(subject: string): Draft | null {
31 const match = DRAFT.exec(subject ?? '')
32 if (!match) return null
33 return { kind: match[1] as Kind, body: match[2] ?? '' }
34}
35
36/** What's wrong with a draft, as short instructions; empty when it's well formed. */
37export function problems(draft: Draft): string[] {
38 if (!draft.body) return ['write the question or action after the colon']
39 const found: string[] = []
40 if (!LINK.test(draft.body)) {
41 found.push(
42 'end the subject with one link token: [#123], [!45], [owner/repo#123], [<url>] or [no link]',
43 )
44 }
45 if (draft.kind === 'DECIDE' && !findRecommendation(withoutLink(draft.body))) {
46 found.push('a DECIDE item needs a recommendation, written as (recommend <choice>)')
47 }
48 return found
49}
50
51export function formatSubject(label: string, draft: Draft): string {
52 return `${label} ${draft.kind}: ${draft.body}`
53}
54
55/** A subject the hook has already labelled; null for anything else. */
56export function parseLabel(subject: string): Label | null {
57 const match = LABELLED.exec(subject ?? '')
58 if (!match) return null
59 return {
60 letter: match[1] as Letter,
61 number: Number(match[2]),
62 kind: match[3] as Kind,
63 body: match[4] ?? '',
64 }
65}
66
67type Found = { start: number; end: number; choice: string; closed: boolean }
68
69/** The body without its trailing link token. */
70function withoutLink(body: string): string {
71 const linked = LINK.exec(body.trim())
72 return linked ? body.trim().slice(0, linked.index).trimEnd() : body
73}
74
75/** Where the parenthesis opened at `from - 1` closes, by depth; the end of the text when it never does. */
76function closeOf(text: string, from: number): { at: number; closed: boolean } {
77 let depth = 1
78 let at = from
79 for (; at < text.length && depth > 0; at++) {
80 if (text[at] === '(') depth++
81 else if (text[at] === ')') depth--
82 }
83 return { at, closed: depth === 0 }
84}
85
86/**
87 * The item's own "(recommend <choice>)" in a body (without its link token): the last one outside
88 * any other parentheses, so a "(recommend ...)" an option note carries earlier in the question
89 * doesn't stand in for the item's. Returns where it starts and ends, the choice, and whether it's
90 * closed. Closing parentheses are found by depth, so "(recommend B (cheaper, (mostly)))" keeps the
91 * whole choice; an unclosed one runs to the end of the body. When parentheses elsewhere never
92 * balance and no recommendation sits at the top level, the last one at any depth is used.
93 */
94function findRecommendation(text: string): Found | null {
95 const found = (start: number, open: string): Found | null => {
96 const from = start + open.length
97 const { at, closed } = closeOf(text, from)
98 const choice = text.slice(from, closed ? at - 1 : at).trim()
99 return choice ? { start, end: at, choice, closed } : null
100 }
101 let top: Found | null = null
102 let depth = 0
103 for (let at = 0; at < text.length; at++) {
104 if (text[at] === ')') depth = Math.max(0, depth - 1)
105 if (text[at] !== '(') continue
106 if (depth === 0) {
107 RECOMMEND.lastIndex = at
108 const match = RECOMMEND.exec(text)
109 const hit = match?.index === at ? found(at, match[0]) : null
110 if (hit) {
111 top = hit
112 at = hit.end - 1
113 continue
114 }
115 }
116 depth++
117 }
118 if (top) return top
119 let last: Found | null = null
120 RECOMMEND.lastIndex = 0
121 for (let match = RECOMMEND.exec(text); match; match = RECOMMEND.exec(text)) last = found(match.index, match[0]) ?? last
122 return last
123}
124
125/** The recommended choice of a DECIDE body, for the Accept button; null when there isn't one. */
126export function recommendation(body: string): string | null {
127 return splitBody(body).recommendation
128}
129
130/** The last "Ruling (...)" line of a description, which records how the item was settled. */
131export function rulingIn(description: string): string | null {
132 const lines = description.split('\n').reverse()
133 return lines.find(line => line.startsWith('Ruling (')) ?? null
134}
135
136export type Supersession = { date: string; by: string; why: string }
137
138const SUPERSEDED = /^Superseded \(([^)]*)\) by ([DA]\d+)(?::\s*(.*))?$/
139
140/**
141 * The last "Superseded (<date>) by D<m>: <why>" line of a description, which records that a settled
142 * item's ruling stopped holding and which item replaced it; null when there's none.
143 */
144export function supersededIn(description: string): Supersession | null {
145 for (const line of description.split('\n').reverse()) {
146 const match = SUPERSEDED.exec(line.trim())
147 if (match) return { date: match[1] ?? '', by: match[2] ?? '', why: (match[3] ?? '').trim() }
148 }
149 return null
150}
151
152/** The text of a ruling line without its "Ruling (<date>): " head. */
153export function rulingText(line: string): string {
154 return line.replace(/^Ruling \([^)]*\):\s*/, '')
155}
156
157/** The date of the last "Revised (<date>): ..." line of a description; null when there's none. */
158export function revisedIn(description: string): string | null {
159 const lines = description.split('\n').reverse()
160 const line = lines.find(one => one.startsWith('Revised ('))
161 return line ? (/^Revised \(([^)]*)\)/.exec(line)?.[1] ?? null) : null
162}
163
164export type BodyParts = { question: string; recommendation: string | null; link: string | null }
165
166/** A body split for display: the question alone, the recommended choice, and the link token. */
167export function splitBody(body: string): BodyParts {
168 let rest = body.trim()
169 let link: string | null = null
170 const linked = LINK.exec(rest)
171 if (linked) {
172 const token = linked[1] ?? ''
173 link = NO_LINK.test(token) ? null : token
174 rest = rest.slice(0, linked.index).trim()
175 }
176 const found = findRecommendation(rest)
177 if (!found?.closed) return { question: rest, recommendation: null, link }
178 rest = `${rest.slice(0, found.start)} ${rest.slice(found.end)}`.replace(/\s{2,}/g, ' ').trim()
179 return { question: rest, recommendation: found.choice, link }
180}
181
182/** The first comma or semicolon outside parentheses; -1 when there's none. */
183function topLevelBreak(text: string): number {
184 let depth = 0
185 for (let at = 0; at < text.length; at++) {
186 const ch = text[at]
187 if (ch === '(') depth++
188 else if (ch === ')') depth = Math.max(0, depth - 1)
189 else if (depth === 0 && (ch === ',' || ch === ';')) return at
190 }
191 return -1
192}
193
194/**
195 * A recommendation as a card shows it: the choice for the tag beside the label (up to the first
196 * comma or semicolon outside parentheses, at most `max` characters) and the qualifier after it, if any.
197 */
198export function shortRecommendation(text: string, max = 24): { choice: string; qualifier: string | null } {
199 const cut = topLevelBreak(text)
200 const head = (cut < 0 ? text : text.slice(0, cut)).trim()
201 const qualifier = cut < 0 ? null : text.slice(cut + 1).trim() || null
202 const choice = head.length > max ? `${head.slice(0, max - 1).trimEnd()}…` : head
203 return { choice, qualifier: head.length > max ? text.trim() : qualifier }
204}
205types/index.d.ts 70 lines1export type Kind = 'DECIDE' | 'ACTION'
2export type Letter = 'D' | 'A'
3export type Status = 'pending' | 'in_progress' | 'completed'
4
5/**
6 * One decision or action. `id` is the task id for a task-list item and the label for a ledger
7 * item. `created` is milliseconds since the epoch, absent for items made before this plugin saw
8 * them.
9 */
10export type Item = {
11 id: string
12 source: 'tasks' | 'ledger'
13 label: string
14 kind: Kind
15 body: string
16 status: Status
17 description: string
18 created?: number
19}
20
21export type Counters = { D: number; A: number }
22
23/**
24 * The item the queue pane shows in full, by `<source>:<id>`, in place of the list; `owns` is true
25 * when the pane opened for it, so its actions close the pane instead of going back to the list.
26 */
27export type Details = { item: string; owns: boolean }
28
29/**
30 * What the plugin knows of a subagent's loop, by its agent id: spawned in the background or the
31 * foreground (as its `agent.spawn` said), or seen calling a task tool. `$.tool.list()` answers the
32 * main loop's tools inside a subagent, so this is how decision_close tells whether the loop that
33 * called it has TaskUpdate.
34 */
35export type Loop = 'background' | 'foreground' | 'tasks'
36
37/**
38 * What `$.store` keeps per session, so a resumed session continues its numbering and ledger: under
39 * `list:<CLAUDE_CODE_TASK_LIST_ID>` when that is set, `session:<session id>` otherwise. `closed` holds the settled task-list items by task id: completed with TaskUpdate, settled by
40 * `decision_close` while TaskUpdate wasn't available (their task files still show them open), or
41 * marked by `decision_supersede`. It keeps them after Claude Code deletes the task files of a list
42 * whose tasks are all completed.
43 */
44export type SessionRecord = {
45 counters: Counters
46 created: Record<string, number>
47 ledger: Item[]
48 closed: Record<string, Item>
49 touched: number
50}
51
52declare module 'claude-code' {
53 interface PluginState {
54 'session-decisions': {
55 items: Item[]
56 counters: Counters
57 created: Record<string, number>
58 closed: Record<string, Item>
59 loops: Record<string, Loop>
60 turnStarted: number
61 handoffNudge: string
62 showSettled: boolean
63 paneDismissed: boolean
64 autoOpened: boolean
65 details: Details | null
66 ascii: boolean
67 }
68 }
69}
70