SLOPSHOPPER

ather-board

Ather Board: the team's intents as a project board. /board shows what is stuck, every intent by owner, area or stage, the open acceptance items and each…

panecommandtoastmodelprocesstimer
v0.3.1no licenseupdated 2026-10-26AskTinNguyen/ather-mods/ather-board
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · ather-board
│ ┃ board ✕ › fix the failing auth test and add an audit log call │ ┃ Ather Board reads a repository’s intents │ ┃ (its docs/intent folder), and this one has ⏺ Read(src/auth.ts) │ ┃ none. Open the session in a checkout that ⎿ Read 6 lines │ ┃ has them. ⏺ Update(src/auth.ts) │ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /board │ ⎿ ather-board: Ather Board reads a repository’s intents (its docs/ │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · board
Ather Board reads a repository’s intents (its docs/intent folder), and this one has none. Open the session in a checkout that has them.
README

Ather Board

The team's intents as a project board that helps you act: what is yours to do now, what is stuck team-wide, where everything stands, how intents map onto the game's modules, and each person's and area's load. It reads every intent on origin/main (and the checkout's own drafts) the way Ather Automata does. It changes nothing itself: every action is handed to the session, which asks you before it writes, commits or messages anyone.

In 30 seconds

  • /board opens the board in the session on For you: what is yours to act on, and Sonnet's suggestions for you and the team. Triage, Modules, Table, Open items, People and Areas are a tab away.
  • See what collides before it hurts. Triage's Colliding lists open intents whose branches change the same lines as main or as each other: which two, which files and lines, and each side's version. Press one for what to do (bring main in, or a drafted note to the other owner).
  • Ask it anything in the box at the top ("what is blocking combat?"): Sonnet answers in a line or two and cuts the board to what it means. /board ask <question> does the same.
  • Press an intent to open it in place: its decisions with their options as buttons, and its next action (answer, close, unstick, give a reason, write the checklist, fix the header, ask the owner) ready to hand to the session.
  • /board open writes the full page (the brief, a kanban by stage, the Map of intents on the game's modules, the weekly pulse, the timeline, every view with filters) and opens it in your browser.
  • /board publish writes the same page and has the session publish it to the team's shared site, for leads and producers who do not run Claude Code.

Install

claude plugin install ather-board@ather --scope user

Then type /board in a session opened in a checkout with intents (a docs/intent folder). Ather Automata is not needed alongside it.

The views

ViewWhat it answers
For you (pane)What needs you, by your git user.name: your intents waiting on your decision, ready for you to close, stuck, needing a checklist or a tidy header; then the rest of your open work. Above it, Suggested: Sonnet's brief (a headline and up to five suggestions, each naming real intents and one action) and the board's own (close your ready ones together, answer your oldest decision, the teammates' intents waiting on a decision). A suggestion is a press.
Modules (pane), Map (page)The intents on the game's core modules: S2's main character locomotion, combat, nine-tail abilities and look; enemy locomotion, AI and abilities; bosses; quests; environment presets and levels; VFX, cinematics, audio, UI, performance and tooling. The pane groups intents by module; the page draws the network, modules as hubs and intents as dots (lime where someone is needed, bigger with more items open, dashed lines where one intent names another).
TriageWhat needs someone, team-wide, grouped by reason, the worst first: decisions waiting on an owner or director, Colliding (below), ready to close (every item met, not closed), no change for 5 days or more, parked without a reason, no acceptance checklist. Each intent sits under its worst reason; its row names any others. Below it, Data hygiene: intents whose files the board could not fully read (a Status that is a sentence or another word than active, parked or completed; no Owner line; an area outside the list).
TableEvery intent, grouped by owner, area, stage or not at all, each group with a one-line rollup ("4 intents · 3 done · 6 open items · 2d"). Sort by recent, stalest, closest to done or most open items. Filter by words, area, owner and stage; done intents are hidden unless shown.
Open itemsEvery acceptance item not yet met, of every intent not done, grouped by area or owner, the biggest pile first. Parked intents' items count: they are still owed.
People, AreasOne line each: open, parked and done intents, open items, decisions waiting, stale intents, last change. Pick a name to see its intents in the table, or a count to see what it counts: its parked or done intents in the table, its open items, or Triage for its decisions and stale intents.
Board (page)A kanban, a column for each stage that has intents: Plan, Building, Proving, Ready to close, Parked, Done.
Pulse (page)Intents opened and closed per week, from the first week anything happened, and how many are in each stage.
Timeline (page)The last 12 weeks, a lane per owner: each intent a bar from its folder's first commit to its last (to now while open), its stage's glyph and name on it; ink while it moves, outlined when ready to close or not begun, quiet once done, dashed while parked. Pick a bar for that intent in the table. Filters apply.

Every row reads the same on both surfaces, as Ather's list does: stage glyph, name and its warnings (decisions waiting, stale, parked without a reason), the checklist bar (▰▱) and count, age, owner. Both use Ather's look: lime only for what needs someone, amber for a warning, ink and quiet grey for the rest; the page in light and dark.

Pressing an intent in the session opens it in place with what can be done about it, its next action first. On your own intents that is answering its decisions (each option a button, Ather's own decision prompt behind it), closing it, unsticking it, giving a parked one its reason, writing its checklist or fixing its header; on a teammate's, asking the owner (a drafted message, never sent) or where it stands. Each press hands the session one prompt; nothing changes until you agree there. On the page, clicking one opens its goal, open items, PRs and issue in place. The page keeps its view and filters in the address, so a link to "Table, VFX, stalest first" opens just that.

Stages are the ones Ather's list uses: Building while an item is open, Proving once every item is met and its PRs are not merged, Ready to close once every item is met with no PR named, Plan with no checklist, Parked, and Done for a Status of completed. The board does not ask GitHub about PRs.

Sonnet's help, and what it costs

The brief, the ask box and the module map use Sonnet through the mod's own model calls. The brief runs once when the board opens and again only when origin/main moves, or on ↻. Each intent's modules are asked once and kept (in the mod's store, per repository) until the intent's title, area or goal changes, or the list of modules does; about 150 intents take three requests the first time and none after. Every reply is checked against what the board read: an intent or a module it does not know, or an action it does not have, is dropped.

The modules are S2's list for an Unreal checkout. A repository can name its own in .ather/board.json:

{ "modules": [{ "key": "mc-locomotion", "name": "Main character locomotion", "hint": "movement, sprint, dodge, traversal" }] }

Without either, the modules are the intents' Areas, and no model is asked.

Colliding: work that changes the same lines

An open intent with a - Branch: line is compared, on that branch, with the base branch and with the other open intents' branches. Two that would conflict when merged are a collision, one row in Triage after the decisions: ◐ dodge-cancel ⇄ main ▲ 3 overlaps, the first file, when the base last changed those files, and the owners.

  • Pressed, a row opens in place: what happened ("hitstop-retune changed these lines on origin/main 6m ago (Lena Park)": the intent whose pull request brought the change, when that pull request touched its intent folder), each place as file:line with each side's first changed line, a binary file (a map, an asset) as "binary, both changed", and what can be done. On your own intent against main: Bring main into <intent> (the session merges in a worktree, resolves each place, runs the gates, and shows you the diff before committing; nothing is pushed until you say), and a drafted note to whoever changed it. On two intents: a drafted note to the other owner, or to both owners asking who goes first, and where both stand. Nothing is sent: every note is a draft.
  • Everywhere else, an intent in a collision warns "overlaps <what>" on its row, and For you lists your own collisions after your decisions.
  • How: git merge-tree --write-tree merges each pair with no working tree or index (git 2.38 or later; with an older git, Colliding says so and stays empty). Two intents are merged only when their branches change a file in common. Each result is kept by the branch tips, so a pair nobody moved is never merged again. The check runs in the background after each read, in runs of at most 15 seconds of new git work: the board draws first, and the rows appear as they are found.
  • The branches: with each fetch of the base (every ten minutes at most), the board asks origin where the open intents' branches are (git ls-remote) and fetches those that moved, the same way it fetches the base (no tags, no automatic gc). It writes only their remote-tracking refs. Intents without a Branch line, done and parked ones, and branches origin does not have are not compared.

Where it reads, and how fresh

The board reads origin/main (or the branch the team merges into: baseBranch in .ather/profile.json, else the clone's default) through git, without taking git's lock, plus the checkout's own intent folders that are newer. When the pane is drawn it fetches that branch in the background at most every ten minutes (no tags, no automatic gc); f fetches now. The line under the title says how fresh the list is.

The shared page

/board publish writes the page to <checkout>/<local folder>/board/index.html (in S2, Saved/AtherAutomata/board/index.html) and hands the session one prompt: publish that file through the vesper-sites MCP server, updating the earlier page in place. The page is one self-contained HTML file: no network, the data inside, light and dark, usable on a phone.

Add the studio's Sites MCP once, under that name, with the address the studio shares internally (it is not written here, as this repository is public):

claude mcp add --transport http vesper-sites <Sites MCP address>

Then sign in to it from /mcp in a Claude Code terminal. Without it, the session stops and says so.

Changes

  • 0.3.1 No change to what you see: the page opens through Ather's shared system opener (opener.mjs, also behind Ather Automata's Go to session, ather-automata 0.6.8). A page path with a character cmd would read as a second command (&, %, " and the like) is no longer handed to start: the board says where the page was written instead.
  • 0.3.0 Counts that open: in People and Areas each count is a press (Enter in the pane, a click on the page) that opens what it counts. The page gains Timeline, a lane per owner over the last 12 weeks. A count of one open item now reads "1 item".
  • 0.2.2 No change to what you see: a collision's words and actions come from Ather's collide.mjs, shared with Ather Automata's Needs you (ather-automata 0.5.0), and the check runs through its shared background job.
  • 0.2.1 Colliding names the intent behind a change on main ("hitstop-retune changed these lines on origin/main 6m ago (Lena Park)"), read from the pull request's merge or squash commit that brought it. A large first check runs in short runs and shows collisions as they are found.
  • 0.2.0 Colliding: open intents whose branches change the same lines as the base branch or as each other, found with git merge-tree (Ather Automata 0.4.1's overlap check), shown second in Triage, one row a pair, opened in place with the files, lines and each side's version, and what to do (bring the base in, or a drafted note). The intents warn "overlaps …" on their rows, For you lists yours, and the page shows the same. The board now fetches the open intents' branches with the base. An opened row no longer shows a thin gap above its details on the page.
  • 0.1.1 A done intent shows how many of its items were met: the board now reads the progress of completed intents, which Ather's reader leaves out (they read as none met before). Done's glyph is ■, no longer close to Ready to close's ✓.
  • 0.1.0 First release: /board opens on For you (what is yours to act on, with Sonnet's suggestions), then Triage, Modules, Table, Open items, People and Areas, with filters, sorts and groups; an ask box; intents opened in place with their decisions and next action, every action handed to the session; /board open (the full page with the brief, Board, Map and Pulse); /board publish (through the vesper-sites MCP server).

Maintainers

The board reads intents with Ather Automata's own modules, copied into hooks/ather/ by node dev/sync-shared.mjs ather-board (the entry modules are named in shared.json); never edit those copies. After a change to them in ather-automata/hooks/, run the sync; node dev/test-all.mjs fails while the copies differ, and runs the board's unit tests (tests/*.test.mjs). Then claude plugin validate ather-board and claude plugin test ather-board, bump version in .claude-plugin/plugin.json and the repository's .claude-plugin/marketplace.json, and add a line under Changes.

Source 31 files
hooks/index.mjs 373 lines
1// @ts-check
2// Ather Board: the engine half. /board opens the pane (pane.mjs), /board open writes the page
3// (page.mjs) and opens it in the browser, /board publish writes it and asks the session to publish
4// it through the team's Sites MCP. Read-only: it reads intents with Ather's reader (snapshot.mjs)
5// and fetches origin's base branch the way Ather does (team.mjs: no tags, never the index lock).
6// The pane opens on For you (D8) with the brief (assist.mjs) above it; every action is a prompt handed
7// to the session, which asks before it changes anything (D6). After each read, the overlap check
8// (Ather's overlap.mjs) runs in the background and Triage shows what collides.
9// Everything here catches its own failures: the board never fails a command or a drawing.
10
11import { ACTION_LABELS, batchPrompt, decisionPrompt } from './act.mjs'
12import { ask, askState, briefState, clearAsk, mapState, runBrief, runMapping } from './assist.mjs'
13import { modulesFor } from './modules.mjs'
14import { answerLook } from './brief.mjs'
15import { mergeSuggestions, plainSuggestions } from './focus.mjs'
16import { choosePack } from './ather/packs/index.mjs'
17import { GIT_ENV, NO_SYNC, baseOf, canFetchNow, fetchMain, isFetchDue, syncError, syncText } from './ather/team.mjs'
18import { fetchBranches, overlapJob, readOverlaps } from './ather/overlap.mjs'
19import { openWith } from './ather/opener.mjs'
20import { sidesOf, withCollisions } from './records.mjs'
21import { boardPane } from './pane.mjs'
22import { renderPage } from './page.mjs'
23import { EMPTY_BOARD_CACHE, readBoard } from './snapshot.mjs'
24import { DEFAULT_LOOK, GROUP_KEYS, NO_FILTER, SORT_KEYS, pickLook } from './views.mjs'
25
26/**
27 * @typedef {import('claude-code').EngineInterface} Engine
28 * @typedef {import('./snapshot.mjs').Board} Board
29 * @typedef {import('./snapshot.mjs').BoardCache} BoardCache
30 * @typedef {import('./views.mjs').Look} Look
31 * @typedef {import('./ather/team.mjs').Repo} Repo
32 * @typedef {import('./ather/team.mjs').Sync} Sync
33 * @typedef {import('./ather/packs/index.mjs').Pack} Pack
34 * @typedef {{ root: string, isRepo: boolean, pack: Pack, base: string, repoName: string, repoUrl: string, me: string, settings: Record<string, any> | null }} Lane
35 *   the checkout the board reads; `me`: its git user.name; `settings`: its .ather/board.json (the modules), null for none
36 */
37
38const PANE_ID = 'board'
39// The board is read again when drawn at most this often, and at once after a fetch moved origin.
40const READ_EVERY_MS = 60 * 1000
41// A prompt goes out after the command hook returns: the engine refuses one queued from inside a hook.
42const AFTER_HOOK_MS = 50
43// How long writing the page waits for the brief and the module map.
44const MODEL_WAIT_MS = 60 * 1000
45// The MCP server the page is published through, as /mcp lists it (README: adding it).
46const SITES_SERVER = 'vesper-sites'
47
48/** @type {Look} */
49let look = { ...DEFAULT_LOOK, view: 'foryou' }
50// The intent opened in place in the pane ('' none).
51let opened = ''
52/** @type {Promise<Lane> | null} */
53let lane = null
54/** @type {Board | null} */
55let board = null
56/** @type {BoardCache} */
57let cache = EMPTY_BOARD_CACHE
58/** @type {Promise<void> | null} */
59let reading = null
60// A forced read asked for while one runs: one more read follows it, so it sees what the fetch brought.
61let isAgain = false
62/** @type {Sync} */
63let sync = NO_SYNC
64// A line under the tabs: what the last press did (the page written, a publish handed over).
65let note = ''
66// The overlap check, one run at a time; `.last()` is its last answer.
67const overlaps = overlapJob()
68
69/** @param {Engine} $ @param {string} root @returns {Repo} */
70const repoOf = ($, root) => ({
71  git: (args, { stdin, timeoutMs = 60000 } = {}) =>
72    $.process.run(['git', '-C', root, ...args], { cwd: root, env: GIT_ENV, timeoutMs, ...(stdin === undefined ? {} : { stdin }) }).catch(error => ({ exitCode: -1, stdout: '', stderr: String(error), isAborted: /aborted$/.test(String(error)) })),
73  read: path => $.fs.read(path).then(text => (typeof text === 'string' ? text : null), () => null),
74  list: path => $.fs.list(path),
75  mtime: path => $.fs.stat(path).then(stat => stat.mtimeMs, () => 0),
76  real: async folder => (await $.fs.stat(folder, { resolve: true })).realPath ?? folder,
77})
78
79// "git@github.com:sipherxyz/s2.git" or "https://github.com/sipherxyz/s2.git" → its web address; '' for another host.
80/** @param {string} remote */
81export const webOf = remote => {
82  const match = /github\.com[:/]([^/\s]+)\/([^/\s]+?)(?:\.git)?\/?$/.exec(remote.trim())
83  return match ? `https://github.com/${match[1]}/${match[2]}` : ''
84}
85
86// The checkout the session runs in, its pack and the branch its team merges into. Once per module load;
87// a lookup that failed is tried again next time.
88/** @param {Engine} $ @returns {Promise<Lane>} */
89const laneOf = $ =>
90  (lane ??= (async () => {
91    const start = (await $.session.root()).replace(/\\/g, '/')
92    const top = await $.process.run(['git', 'rev-parse', '--show-toplevel'], { cwd: start, env: GIT_ENV, timeoutMs: 10000 }).catch(() => undefined)
93    const isRepo = top?.exitCode === 0
94    const root = isRepo ? (top?.stdout ?? '').trim().replace(/\\/g, '/') : start
95    const io = { read: (/** @type {string} */ path) => $.fs.read(path).then(text => (typeof text === 'string' ? text : null), () => null), exists: (/** @type {string} */ path) => $.fs.exists(path).catch(() => false), list: (/** @type {string} */ path) => $.fs.list(path), sessionId: () => $.session.id() }
96    const chosen = await choosePack(io, root)
97    const remote = isRepo ? await $.process.run(['git', 'config', '--get', 'remote.origin.url'], { cwd: root, env: GIT_ENV, timeoutMs: 10000 }).catch(() => undefined) : undefined
98    const repoUrl = webOf(remote?.stdout ?? '')
99    const user = await $.process.run(['git', 'config', 'user.name'], { cwd: root, env: GIT_ENV, timeoutMs: 10000 }).catch(() => undefined)
100    const settings = await io.read(`${root}/.ather/board.json`).then(text => { try { return text ? JSON.parse(text) : null } catch { return null } })
101    return { root, isRepo, pack: chosen.pack, base: baseOf(chosen.profile, chosen.defaultBranch), repoName: repoUrl.split('/').pop() || root.split('/').pop() || '', repoUrl, me: (user?.stdout ?? '').trim(), settings }
102  })().catch(error => {
103    lane = null
104    throw error
105  }))
106
107/** @param {Engine} $ */
108const hasIntents = async $ => (await $.fs.exists(`${(await laneOf($)).root}/docs/intent`).catch(() => false))
109
110// Reads the board again, one read at a time; `force` skips the minute's wait, and while a read runs
111// asks for one more after it.
112/** @param {Engine} $ @param {boolean} [force] */
113const refresh = ($, force = false) => {
114  if (reading) {
115    isAgain ||= force
116    return reading
117  }
118  if (!force && board && Date.now() - board.readAt < READ_EVERY_MS) return Promise.resolve()
119  reading = (async () => {
120    try {
121      const at = await laneOf($)
122      do {
123        isAgain = false
124        const read = await readBoard(repoOf($, at.root), at.root, { pack: at.pack, base: at.base, cache, now: Date.now() })
125        board = read.board
126        cache = read.cache
127        sync = { ...sync, isRepo: read.board.isRepo, hasMain: read.board.sha !== '', base: at.base }
128      } while (isAgain)
129    } catch (error) {
130      $.ui.log(`Ather Board: reading the intents failed: ${String(error)}`, { to: 'debug' })
131    } finally {
132      reading = null
133      $.ui.invalidate('ui.render')
134    }
135    void checkOverlaps($)
136  })()
137  return reading
138}
139
140// The overlap check over the last read (overlap-check D6), in the background: the board draws without waiting,
141// and draws again after each run. Unchanged branches cost one git call (overlap.mjs keeps the rest by their tips).
142/** @param {Engine} $ */
143const checkOverlaps = async $ => {
144  if (!board) return
145  const at = await laneOf($)
146  await overlaps
147    .run(cache => readOverlaps(repoOf($, at.root), { base: at.base, sides: sidesOf(board?.records ?? []), cache }), () => $.ui.invalidate('ui.render'))
148    .catch(error => $.ui.log(`Ather Board: the overlap check failed: ${String(error)}`, { to: 'debug' }))
149}
150
151// The records as drawn: the last read, with the overlaps they are a side of.
152/** @param {string} base */
153const recordsNow = base => withCollisions(board?.records ?? [], overlaps.last().overlaps, base)
154
155// Fetches origin's base in the background when due (or at once for ↻), then reads the board again.
156/** @param {Engine} $ @param {boolean} [now] */
157const syncMain = async ($, now = false) => {
158  const at = await laneOf($)
159  if (!(now ? canFetchNow(sync, Date.now()) : isFetchDue(sync, Date.now()))) return
160  sync = { ...sync, isFetching: true, triedAt: Date.now() }
161  $.ui.invalidate('ui.render')
162  const fetched = await fetchMain(repoOf($, at.root), at.base).catch(error => ({ error: String(error), lock: '', moved: false }))
163  // The open intents' branches too, for the overlap check (overlap-check D6): a failure here is the check's
164  // own, logged; the sync line speaks for the base alone.
165  const branches = fetched.error ? '' : await fetchBranches(repoOf($, at.root), sidesOf(board?.records ?? []).map(one => one.branch)).catch(error => String(error))
166  if (branches) $.ui.log(`Ather Board: fetching the intents' branches failed: ${branches}`, { to: 'debug' })
167  const time = Date.now()
168  sync = fetched.error ? { ...sync, isFetching: false, failedAt: time, error: fetched.error, lock: fetched.lock } : { ...sync, isFetching: false, fetchedAt: time, error: '', lock: '' }
169  if (fetched.moved) await refresh($, true)
170  else {
171    $.ui.invalidate('ui.render')
172    void checkOverlaps($)
173  }
174}
175
176// The page, written where the pack keeps local files (S2: Saved/AtherAutomata/board/index.html).
177/** @param {Engine} $ @returns {Promise<string>} */
178const writePage = async $ => {
179  const at = await laneOf($)
180  await refresh($, true)
181  await checkOverlaps($)
182  if (!board) throw new Error('the intents could not be read')
183  // The page carries the brief and the map: both are waited for, up to a limit (each runs once per read,
184  // so usually done); past it the page has what is in, and the next write has the rest.
185  const io = assistIo($, at.repoName)
186  const set = modulesFor(at.pack.id, at.settings, board.records)
187  await Promise.race([Promise.all([runBrief(io, board, at.me), runMapping(io, board, set)]), new Promise(resolve => $.clock.after(MODEL_WAIT_MS, () => resolve(undefined)))])
188  const [css, client] = await Promise.all([$.fs.read(`${$.plugin.root}/page/board.css`), $.fs.read(`${$.plugin.root}/page/client.js`)])
189  const path = `${at.root}/${at.pack.localDir}/board/index.html`
190  await $.fs.write(path, renderPage({ ...board, records: recordsNow(at.base) }, { overlapNote: overlaps.last().note, now: Date.now(), repoName: at.repoName, repoUrl: at.repoUrl, css: String(css), client: String(client), brief: briefState().value, briefAt: briefState().at, modules: set.modules, mapping: mapState().value.mapping }))
191  return path
192}
193
194// Opens a file with the system's own handler (ather/opener.mjs): a drive-letter path is Windows's, given with backslashes.
195/** @param {Engine} $ @param {string} path */
196const openFile = ($, path) => {
197  const isWindows = /^[A-Za-z]:/.test(path)
198  return openWith(argv => $.process.run(argv, { timeoutMs: 15000 }), isWindows ? path.replace(/\//g, '\\') : path, isWindows)
199}
200
201// What the session is asked to do with the written page.
202/** @param {string} path @param {string} repoName */
203export const publishPrompt = (path, repoName) =>
204  `Publish the Ather Board page at ${path} to the team's shared site through the ${SITES_SERVER} MCP server. It is one self-contained HTML file: publish it as it is, without editing it. If a site for "${repoName || 'the'} intents" was published before, update that one in place rather than creating another. If the ${SITES_SERVER} server is not connected, stop and tell me to add it (ather-board's README says how). Reply with the page's address. Change nothing in the repository.`
205
206/** @param {Engine} $ @param {string} text */
207const deliver = ($, text) => $.clock.after(AFTER_HOOK_MS, () => void $.prompt.submit({ text }).catch(error => $.ui.toast(`Ather Board: could not hand that to the session: ${String(error)}`)))
208
209/** @param {Engine} $ */
210const openPage = async $ => {
211  try {
212    const path = await writePage($)
213    note = (await openFile($, path)) ? `Page written and opened: ${path}` : `Page written: ${path} (open it in a browser)`
214  } catch (error) {
215    note = `The page could not be written: ${String(error)}`
216  }
217  $.ui.invalidate('ui.render')
218  return note
219}
220
221/** @param {Engine} $ */
222const publish = async $ => {
223  try {
224    const path = await writePage($)
225    deliver($, publishPrompt(path, (await laneOf($)).repoName))
226    note = `Page written: ${path}. The session publishes it through ${SITES_SERVER}.`
227  } catch (error) {
228    note = `The page could not be written: ${String(error)}`
229  }
230  $.ui.invalidate('ui.render')
231  return note
232}
233
234/** @param {Engine} $ */
235const openPane = async $ => {
236  await $.ui.open({ id: PANE_ID, title: 'ATHER BOARD', focus: true, closeOnEscape: true, rows: 24 })
237  $.ui.invalidate('ui.render')
238}
239
240/** @template {string} T @param {readonly T[]} keys @param {T} current */
241const nextOf = (keys, current) => keys[(keys.indexOf(current) + 1) % keys.length] ?? current
242
243// The model, the redraw and the kept module answers, as the brief, the ask box and the mapping take them
244// (assist.mjs). The answers are kept per repository in the mod's store.
245/** @param {Engine} $ @param {string} repoName @returns {import('./assist.mjs').Io} */
246const assistIo = ($, repoName) => ({
247  load: async () => /** @type {import('./modules.mjs').Kept | null} */ ((await $.store.get(`modules:${repoName}`).catch(() => undefined)) ?? null),
248  save: kept => $.store.set(`modules:${repoName}`, kept).catch(() => undefined),
249  complete: async (request, signal) => {
250    const reply = await $.model.complete(request, { signal })
251    if (reply.isAnswered) return { text: reply.text, error: '' }
252    return { text: '', error: reply.reason === 'api-error' ? `the model call failed (${reply.error}${reply.status ? `, ${reply.status}` : ''})` : `the model gave no answer (${reply.reason})` }
253  },
254  redraw: () => $.ui.invalidate('ui.render'),
255})
256
257// A question to the model, its answer cutting the board (the ask box, /board ask).
258/** @param {Engine} $ @param {string} question */
259const askBoard = async ($, question) => {
260  const at = await laneOf($)
261  if (board) await ask(assistIo($, at.repoName), question, board, at.me, answer => setLook($, answerLook(answer, look.view)))
262}
263
264// Hands the session one prompt and says so under the tabs.
265/** @param {Engine} $ @param {string} prompt @param {string} what */
266const handOver = ($, prompt, what) => {
267  deliver($, prompt)
268  note = `Handed to the session: ${what}. It asks before changing anything.`
269  $.ui.invalidate('ui.render')
270}
271
272/** @param {Engine} $ @param {Partial<Look>} patch */
273const setLook = ($, patch) => {
274  look = { ...look, ...patch }
275  $.ui.invalidate('ui.render')
276}
277
278/** @param {Engine} $ @param {any} e */
279const drawPane = async ($, e) => {
280  const el = $.ui.resolve(e)
281  if (!(await hasIntents($))) return el.Text({ wrap: 'wrap', children: NOT_HERE })
282  void syncMain($)
283  if (!board) await refresh($)
284  else void refresh($)
285  const at = await laneOf($)
286  const now = Date.now()
287  const records = recordsNow(at.base)
288  // The brief once per read of origin (D7); its suggestions merged with the board's own.
289  const io = assistIo($, at.repoName)
290  const set = modulesFor(at.pack.id, at.settings, records)
291  if (board) {
292    void runBrief(io, board, at.me)
293    void runMapping(io, board, set)
294  }
295  const brief = briefState()
296  const suggestions = mergeSuggestions(brief.value?.suggestions ?? [], plainSuggestions(records, at.me, now))
297  const named = (/** @type {readonly string[]} */ keys) => records.filter(one => keys.includes(one.key))
298  return boardPane(
299    el,
300    { records, look, width: e.props?.bodyColumns ?? 80, isDesktop: e.surface !== 'terminal', now, title: `${at.repoName || 'Team'} intents`, fresh: syncText(sync, now), error: syncError(sync), note, me: at.me, base: at.base, overlapNote: overlaps.last().note, opened, suggestions, brief, asked: askState(), modules: set.modules, mapped: mapState() },
301    {
302      onView: view => () => setLook($, { view }),
303      onFilter: patch => setLook($, { filter: { ...look.filter, ...patch } }),
304      onPick: (by, value, count) => setLook($, pickLook(look, by, value, count)),
305      onSort: () => setLook($, { sort: nextOf(SORT_KEYS, look.sort) }),
306      onGroup: () => setLook($, { group: nextOf(GROUP_KEYS, look.group) }),
307      onBy: () => setLook($, { by: look.by === 'area' ? 'owner' : 'area' }),
308      onRow: record => () => {
309        opened = opened === record.key ? '' : record.key
310        $.ui.invalidate('ui.render')
311      },
312      onPair: collision => () => {
313        opened = opened === collision.key ? '' : collision.key
314        $.ui.invalidate('ui.render')
315      },
316      onCollision: action => handOver($, action.prompt, action.label.toLowerCase()),
317      onAction: (kind, list) => handOver($, batchPrompt(kind, list, at.base), `${ACTION_LABELS[kind].toLowerCase()}, ${list.map(one => one.slug).join(', ')}`),
318      onDecide: (record, call, letter) => handOver($, decisionPrompt(record, call, letter), letter ? `${call.id} on ${record.slug}: ${letter}` : `explain ${call.id} on ${record.slug}`),
319      onSuggestion: one => (one.action === 'show' ? setLook($, { view: 'table', filter: { ...NO_FILTER, keys: one.keys } }) : handOver($, batchPrompt(one.action, named(one.keys), at.base), one.title)),
320      onBriefAgain: () => { if (board) void runBrief(io, board, at.me, true) },
321      onMapAgain: () => { if (board) void runMapping(io, board, set, true) },
322      onAsk: question => void askBoard($, question),
323      onClearAsk: () => {
324        clearAsk()
325        setLook($, { filter: NO_FILTER })
326      },
327      onOpenPage: () => void openPage($),
328      onPublish: () => void publish($),
329      onSync: () => void syncMain($, true),
330    },
331  )
332}
333
334const NOT_HERE = 'Ather Board reads a repository’s intents (its docs/intent folder), and this one has none. Open the session in a checkout that has them.'
335const HELP = '/board opens the board, on what is yours to act on. /board ask <question> asks Sonnet and cuts the board to the answer. /board open writes the full page and opens it in your browser. /board publish writes it and has the session publish it to the team’s shared site.'
336
337/** @param {import('claude-code').On} on */
338export function register(on) {
339  on('session.start', async ($, e, next) => {
340    await $.command.register({ name: 'board', description: 'The team’s intents as a board: triage, table, open items, people and areas', argumentHint: '[open | publish | ask <question>]' }).catch(error => $.ui.log(`Ather Board: /board not registered: ${String(error)}`, { to: 'debug' }))
341    return next(e)
342  })
343
344  on('command.run', { command: 'board' }, async ($, e) => {
345    try {
346      if (!(await hasIntents($))) return { text: NOT_HERE }
347      const word = e.args.trim().toLowerCase()
348      if (word === 'open') return { text: await openPage($) }
349      if (word === 'publish') return { text: await publish($) }
350      if (word.startsWith('ask ')) {
351        await openPane($)
352        await refresh($)
353        void askBoard($, e.args.trim().slice(4))
354        return { text: 'Asked Sonnet; the answer shows on the board.' }
355      }
356      if (word !== '') return { text: HELP }
357      await openPane($)
358      return { text: 'Board opened.' }
359    } catch (error) {
360      return { text: `Ather Board: ${String(error)}` }
361    }
362  })
363
364  on('ui.render', { component: 'Pane', requestId: PANE_ID }, async ($, e) => {
365    try {
366      return await drawPane($, e)
367    } catch (error) {
368      $.ui.log(`Ather Board: the pane failed to draw: ${String(error)}`, { to: 'debug' })
369      return $.ui.resolve(e).Text({ children: 'Ather Board could not draw. /board tries again.' })
370    }
371  })
372}
373
hooks/act.mjs 111 lines
1// @ts-check
2// Ather Board: what can be done about an intent from the board, and what each press hands the session.
3// The board never changes anything itself (D6): every action is one prompt the session acts on with its
4// own tools, asking before it writes, commits or messages anyone. Answering a decision uses Ather's own
5// prompts (decide.mjs), so a decision taken here is recorded the intent skill's way, as in /ather.
6// Pure: no `$`.
7
8import { decidePrompt, explainPrompt } from './ather/decide.mjs'
9import { aboutIntentPrompt, andList, checklistPrompt, closePrompt, plural } from './ather/model.mjs'
10import { HYGIENE, isReason } from './views.mjs'
11
12/**
13 * @typedef {import('./views.mjs').BoardRecord} BoardRecord
14 * @typedef {import('./views.mjs').Call} Call
15 * @typedef {'decide' | 'close' | 'unstick' | 'reason' | 'checklist' | 'tidy' | 'ping' | 'about'} ActionKind
16 */
17
18// What each action's button says.
19export const ACTION_LABELS = /** @type {const} */ ({
20  decide: 'Answer its decisions',
21  close: 'Close it',
22  unstick: 'Unstick it',
23  reason: 'Give a reason',
24  checklist: 'Write the checklist',
25  tidy: 'Fix its header',
26  ping: 'Ask the owner',
27  about: 'Where it stands',
28})
29export const ACTION_KINDS = /** @type {readonly ActionKind[]} */ (Object.keys(ACTION_LABELS))
30
31// The owner's actions, by the flag that calls for each, worst first: an intent's next action is the first
32// whose flag it has. A teammate's intent offers asking its owner instead, when anything needs someone.
33// Only an intent's owner is offered these (OWNER_ACTIONS); the brief turns one suggested for a teammate's into show.
34const OWN = /** @type {const} */ ([
35  ['decisions', 'decide'],
36  ['met', 'close'],
37  ['unparked', 'reason'],
38  ['stale', 'unstick'],
39  ['plan', 'checklist'],
40  ['status', 'tidy'],
41  ['owner', 'tidy'],
42  ['area', 'tidy'],
43])
44
45/**
46 * Every action an intent offers, its next action first and "Where it stands" last. Done intents offer
47 * only that. `isMine`: the person at the keyboard owns it.
48 * @param {BoardRecord} record @param {boolean} isMine @returns {ActionKind[]}
49 */
50export const actionsFor = (record, isMine) => {
51  if (record.stage === 'done') return ['about']
52  const kinds = new Set(record.flags.map(flag => flag.kind))
53  /** @type {ActionKind[]} */
54  const offered = isMine ? OWN.filter(([flag]) => kinds.has(flag)).map(([, action]) => action) : record.flags.some(isReason) ? ['ping'] : []
55  return [...new Set([...offered, /** @type {ActionKind} */ ('about')])]
56}
57
58export const OWNER_ACTIONS = /** @type {readonly ActionKind[]} */ ([...new Set(OWN.map(([, action]) => action))])
59
60/** @param {BoardRecord} record @param {boolean} isMine */
61export const nextAction = (record, isMine) => actionsFor(record, isMine)[0] ?? 'about'
62
63// Reading an intent wherever it is: this checkout's copy, else origin's, never changing either.
64/** @param {string} slug @param {string} base */
65const readIt = (slug, base) => `Read intent ${slug} from docs/intent/${slug}/; if this checkout lacks it or is behind, read it from origin/${base} with git show (GIT_OPTIONAL_LOCKS=0), without fetching or checking anything out.`
66
67// What every writing prompt asks first: the checkout's copy is the one to change.
68/** @param {string} slug @param {string} base */
69const inCheckout = (slug, base) => `Work in docs/intent/${slug}/ of this checkout; if it is missing or behind origin/${base}, say so and stop before changing anything.`
70
71/**
72 * The one prompt an action hands the session. `base`: the branch the team merges into.
73 * @param {ActionKind} kind @param {BoardRecord} record @param {string} base
74 */
75export const actionPrompt = (kind, record, base) => {
76  const { slug } = record
77  const flags = record.flags.map(flag => flag.label)
78  switch (kind) {
79    case 'decide':
80      return `Walk me through the ${plural(record.calls.length, 'open decision')} on intent ${slug} (${record.calls.map(call => call.id).join(', ')}), one at a time: what each is about, its options and your recommendation. Record each answer I give the intent skill's way (.agents/skills/intent/SKILL.md, the decision step). ${inCheckout(slug, base)}`
81    case 'close':
82      return `${closePrompt(slug, record.prs, 'show me the diff before committing as the skill says')} ${inCheckout(slug, base)}`
83    case 'unstick':
84      return `Intent ${slug} has had no change for a while. ${readIt(slug, base)} Tell me, in under eight lines, what it is waiting on and the one next step that would move it, then offer to take that step. Change nothing until I say.`
85    case 'reason':
86      return `Intent ${slug} is parked with no reason on its Status line. Read its files and propose a one-line reason (what it waits on, or why it stopped) as "Status: parked: <reason>"; show me the line and edit prompt.md only once I agree. ${inCheckout(slug, base)}`
87    case 'checklist':
88      return `${checklistPrompt(slug)} ${inCheckout(slug, base)}`
89    case 'tidy':
90      return `The header of intent ${slug} does not read cleanly: ${andList(record.flags.filter(flag => HYGIENE.includes(flag.kind)).map(flag => flag.label))}. Propose the fix the intent skill's way (Status one word: active, parked or completed, a parked reason after it; an Owner line naming a person; an Area from docs/intent/README.md), show me the diff, and change nothing until I agree. ${inCheckout(slug, base)}`
91    case 'ping':
92      return `Draft a short, friendly message to ${record.owner || 'the owner'} about their intent ${slug}: ${flags.length ? andList(flags) : 'where it stands'}. ${readIt(slug, base)} Name the one thing that would help. Show me the draft; do not send it.`
93    case 'about':
94      return aboutIntentPrompt(slug, record.source === 'main', '', base)
95  }
96}
97
98// One action over several intents (closing every ready one, say): each one's own prompt, in turn.
99/** @param {ActionKind} kind @param {readonly BoardRecord[]} records @param {string} base */
100export const batchPrompt = (kind, records, base) =>
101  records.length === 1 && records[0]
102    ? actionPrompt(kind, records[0], base)
103    : [`Take these ${records.length} intents one at a time, finishing each before the next:`, ...records.map((one, index) => `${index + 1}. ${actionPrompt(kind, one, base)}`)].join('\n')
104
105// A decision answered in place: an option chosen, or Explain. Ather's own wording (decide.mjs).
106/** @param {BoardRecord} record @param {Call} call @param {string} letter '' explains it */
107export const decisionPrompt = (record, call, letter) => {
108  const option = call.options.find(one => one.letter === letter)
109  return option ? decidePrompt(record.slug, call.id, `${option.letter} — ${option.text}`) : explainPrompt(record.slug, call.id)
110}
111
hooks/assist.mjs 147 lines
1// @ts-check
2// Ather Board: the engine half of the model's help (brief.mjs and modules.mjs build the requests and check
3// the replies). Three jobs, each run by one `latestJob`: the brief, once per read of origin/<base> (its
4// commit, or the local folders when there is none) and again on ↻ (D7); a question, when asked; and the
5// module mapping, once per read and list of modules. A newer run of a job cancels the older; a failed run
6// says why and keeps what the job last had. The engine comes in as closures (Io), built in index.mjs
7// where `$` lives.
8
9import { askRequest, briefRequest, parseAnswer, parseBrief } from './brief.mjs'
10import { BATCH, keep, listKey, mappingOf, mappingRequest, parseMapping } from './modules.mjs'
11
12/**
13 * @typedef {{
14 *   complete: (request: { model: string, system: string, prompt: string, maxTokens: number }, signal: AbortSignal) => Promise<{ text: string, error: string }>,
15 *   redraw: () => void, load: () => Promise<import('./modules.mjs').Kept | null>, save: (kept: import('./modules.mjs').Kept) => Promise<void>,
16 * }} Io `complete`: one model completion, its text or why it gave none; `redraw`: draw the pane again;
17 *   `load`, `save`: the module answers kept across sessions
18 * @typedef {import('./snapshot.mjs').Board} Board
19 * @typedef {import('./brief.mjs').Brief} Brief
20 * @typedef {import('./brief.mjs').Answer} Answer
21 * @typedef {{ mapping: import('./modules.mjs').Mapping, missing: number }} Mapped `missing`: intents still to sort
22 */
23
24/**
25 * Where a job stands: `key` what it was run for (a commit, a question), `value` its last result
26 * (kept through a failed run), `at` when that came in.
27 * @template T
28 * @typedef {{ state: 'idle' | 'running' | 'ready' | 'failed', key: string, value: T, error: string, at: number }} Job
29 */
30
31/**
32 * One job that keeps only its latest run. `run` starts `work` unless a run for the same key is already
33 * in or under way (then it returns that one; `force` starts anew), cancelling an older one; `work` gets
34 * the run's signal and `show`, to publish a partial value. A run resolves once it is over.
35 * @template T @param {T} empty
36 */
37const latestJob = empty => {
38  /** @type {Job<T>} */
39  let job = { state: 'idle', key: '', value: empty, error: '', at: 0 }
40  /** @type {AbortController | null} */
41  let stop = null
42  /** @type {Promise<void>} */
43  let running = Promise.resolve()
44  return {
45    get: () => job,
46    /** @param {Io} io @param {string} key @param {boolean} force @param {(signal: AbortSignal, show: (value: T) => void) => Promise<T>} work */
47    run: (io, key, force, work) => {
48      if (!force && job.key === key && job.state !== 'idle') return running
49      stop?.abort()
50      const mine = new AbortController()
51      stop = mine
52      job = { ...job, state: 'running', key, error: '' }
53      io.redraw()
54      const show = (/** @type {T} */ value) => {
55        if (mine.signal.aborted) return
56        job = { ...job, value }
57        io.redraw()
58      }
59      running = (async () => {
60        try {
61          const value = await work(mine.signal, show)
62          if (!mine.signal.aborted) job = { ...job, state: 'ready', value, at: Date.now() }
63        } catch (error) {
64          if (!mine.signal.aborted) job = { ...job, state: 'failed', error: error instanceof Error ? error.message : String(error) }
65        } finally {
66          if (stop === mine) stop = null
67          io.redraw()
68        }
69      })()
70      return running
71    },
72    clear: () => {
73      stop?.abort()
74      stop = null
75      job = { state: 'idle', key: '', value: empty, error: '', at: 0 }
76    },
77  }
78}
79
80// A completion's checked result, or a failure that says why there is none.
81/** @template T @param {{ text: string, error: string }} reply @param {(text: string) => T | null} parse @param {string} what @returns {T} */
82const resultOf = (reply, parse, what) => {
83  if (reply.error) throw new Error(reply.error)
84  const read = parse(reply.text)
85  if (read === null) throw new Error(`the reply held no ${what}`)
86  return read
87}
88
89const brief = latestJob(/** @type {Brief | null} */ (null))
90const asked = latestJob(/** @type {Answer | null} */ (null))
91const mapped = latestJob(/** @type {Mapped} */ ({ mapping: {}, missing: 0 }))
92
93export const briefState = brief.get
94export const askState = asked.get
95export const mapState = mapped.get
96
97// What a read of the board is: the commit read, or the checkout's own folders by their count and last change.
98/** @param {Board} board */
99const keyOf = board => board.sha || `local:${board.records.length}:${Math.max(0, ...board.records.map(one => one.updatedAt))}`
100
101/**
102 * The brief for this read of the board; `force` asks again. Resolves once it is in (or failed).
103 * @param {Io} io @param {Board} board @param {string} me @param {boolean} [force]
104 */
105export const runBrief = (io, board, me, force = false) =>
106  brief.run(io, keyOf(board), force, async signal => resultOf(await io.complete(briefRequest(board.records, me, Date.now()), signal), text => parseBrief(text, board.records, me), 'brief'))
107
108/**
109 * Asks the model a question about the board; `onAnswer` applies the cut of the board it picked.
110 * @param {Io} io @param {string} question @param {Board} board @param {string} me @param {(answer: Answer) => void} onAnswer
111 */
112export const ask = (io, question, board, me, onAnswer) =>
113  question.trim() === ''
114    ? Promise.resolve()
115    : asked.run(io, question.trim(), true, async signal => {
116        const answer = resultOf(await io.complete(askRequest(question, board.records, me, Date.now()), signal), text => parseAnswer(text, board.records), 'answer')
117        if (!signal.aborted) onAnswer(answer)
118        return answer
119      })
120
121// Puts the question away (and stops one still running).
122export const clearAsk = asked.clear
123
124/**
125 * Which intents work on which modules: what was kept for them, then Sonnet for the rest, a batch at a
126 * time, each answer kept as it comes so a later session does not ask again. Once per read of the board
127 * and list of modules; `force` asks again for those still missing.
128 * @param {Io} io @param {Board} board @param {import('./modules.mjs').Modules} set @param {boolean} [force]
129 */
130export const runMapping = (io, board, set, force = false) =>
131  mapped.run(io, `${keyOf(board)}|${listKey(set.modules)}`, force, async (signal, show) => {
132    let kept = await io.load()
133    const { mapping, missing } = mappingOf(board.records, set, kept)
134    /** @type {Mapped} */
135    let now = { mapping, missing: missing.length }
136    show(now)
137    for (let at = 0; at < missing.length && !signal.aborted; at += BATCH) {
138      const batch = missing.slice(at, at + BATCH)
139      const answered = resultOf(await io.complete(mappingRequest(batch, set.modules), signal), text => parseMapping(text, batch, set.modules), 'mapping')
140      kept = keep(kept, set.modules, batch, answered)
141      await io.save(kept)
142      now = { mapping: { ...now.mapping, ...answered }, missing: now.missing - Object.keys(answered).length }
143      show(now)
144    }
145    return now
146  })
147
hooks/modules.mjs 125 lines
1// @ts-check
2// Ather Board: the game's core modules, and which intents work on which. The modules come from the
3// repository's .ather/board.json ("modules": [{ "key", "name", "hint" }]), else S2's default list for an
4// Unreal checkout, else the intents' own Areas. Sonnet sorts intents into modules (one to three each);
5// each answer is kept with the intent's fingerprint (title, area, goal) and asked again only when that
6// changes, or when the list of modules does. Modules made from Areas need no model: an intent sits in its
7// area. Pure: no `$`; assist.mjs makes the calls and keeps the answers.
8
9import { MODEL, jsonOf } from './brief.mjs'
10
11/**
12 * @typedef {import('./views.mjs').BoardRecord} BoardRecord
13 * @typedef {{ key: string, name: string, hint: string }} Module what the model reads: `hint` says what belongs in it
14 * @typedef {{ modules: Module[], byArea: boolean }} Modules `byArea`: made from the Areas, so no model is asked
15 * @typedef {Record<string, string[]>} Mapping intent key → its module keys
16 * @typedef {{ list: string, entries: Record<string, { print: string, modules: string[] }> }} Kept what is kept across sessions: the module list it was asked against, and each intent's answer with its fingerprint
17 */
18
19// S2's core modules: the game's systems and the work around them, in the order the map rings them.
20export const S2_MODULES = /** @type {readonly Module[]} */ ([
21  { key: 'mc-locomotion', name: 'Main character locomotion', hint: 'movement, sprint, dodge, traversal, jumps, camera follow' },
22  { key: 'mc-combat', name: 'Main character combat', hint: 'attacks, combos, parry, hit reactions, lock-on, damage' },
23  { key: 'mc-ninetails', name: 'Nine-tail abilities', hint: 'the main character’s tails, tail skills and transformations' },
24  { key: 'mc-look', name: 'Main character look', hint: 'model, materials, customization, body, animation art' },
25  { key: 'enemy-locomotion', name: 'Enemy locomotion', hint: 'how enemies move, navigate and animate' },
26  { key: 'enemy-ai', name: 'Enemy AI', hint: 'behaviour trees, perception, decisions, encounter logic' },
27  { key: 'enemy-abilities', name: 'Enemy abilities', hint: 'enemy attacks, projectiles, skills, hitboxes' },
28  { key: 'bosses', name: 'Bosses', hint: 'boss fights, phases, boss abilities' },
29  { key: 'quests', name: 'Quests and encounters', hint: 'quests, encounter design, scripted events, level scripting' },
30  { key: 'env-presets', name: 'Environment presets', hint: 'weather, time of day, fog, lighting and look presets' },
31  { key: 'env-levels', name: 'Environment levels', hint: 'level layout, world building, HLOD, streaming, foliage' },
32  { key: 'vfx', name: 'VFX', hint: 'Niagara and visual effects' },
33  { key: 'cinematics', name: 'Cinematics', hint: 'cutscenes, sequences, shots' },
34  { key: 'audio', name: 'Audio', hint: 'sound, music, audio tools' },
35  { key: 'ui', name: 'UI', hint: 'HUD, menus, front end' },
36  { key: 'performance', name: 'Performance', hint: 'optimization, profiling, memory, platform budgets' },
37  { key: 'tooling', name: 'Tooling', hint: 'editor tools, validators, pipeline, automation, agent tooling' },
38])
39
40// The one module of an intent's own Area, for modules made from Areas.
41/** @param {string} area */
42const areaKey = area => area.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'unsorted'
43
44/**
45 * The modules of a repository: its own list from .ather/board.json (`settings`), else S2's for the Unreal
46 * pack, else the Areas its intents use.
47 * @param {string} packId @param {Record<string, any> | null} settings @param {readonly BoardRecord[]} records @returns {Modules}
48 */
49export const modulesFor = (packId, settings, records) => {
50  const own = Array.isArray(settings?.modules) ? settings.modules.filter((/** @type {any} */ one) => typeof one?.key === 'string' && typeof one?.name === 'string').map((/** @type {any} */ one) => ({ key: one.key, name: one.name, hint: typeof one.hint === 'string' ? one.hint : '' })) : []
51  if (own.length > 0) return { modules: own, byArea: false }
52  if (packId === 'unreal') return { modules: [...S2_MODULES], byArea: false }
53  return { modules: [...new Set(records.map(one => one.area))].sort().map(area => ({ key: areaKey(area), name: area, hint: '' })), byArea: true }
54}
55
56// What a module answer depends on: when the intent says something else of itself, it is asked again.
57/** @param {BoardRecord} record */
58export const fingerprint = record => `${record.title}|${record.area}|${record.goal}`
59
60/** @param {readonly Module[]} modules */
61export const listKey = modules => modules.map(one => one.key).join(',')
62
63/**
64 * Every intent's modules: by area when the modules are the Areas, else what was kept for it while its
65 * fingerprint holds. `missing`: the intents to ask the model about.
66 * @param {readonly BoardRecord[]} records @param {Modules} set @param {Kept | null} kept
67 * @returns {{ mapping: Mapping, missing: BoardRecord[] }}
68 */
69export const mappingOf = (records, set, kept) => {
70  /** @type {Mapping} */
71  const mapping = {}
72  /** @type {BoardRecord[]} */
73  const missing = []
74  const valid = kept && kept.list === listKey(set.modules) ? kept.entries : {}
75  for (const record of records) {
76    const entry = valid[record.key]
77    if (set.byArea) mapping[record.key] = [areaKey(record.area)]
78    else if (entry && entry.print === fingerprint(record)) mapping[record.key] = entry.modules
79    else missing.push(record)
80  }
81  return { mapping, missing }
82}
83
84// How many intents one request sorts: about 60 lines of digest in, a short JSON object out.
85export const BATCH = 60
86
87/** @param {readonly BoardRecord[]} records @param {readonly Module[]} modules */
88export const mappingRequest = (records, modules) => ({
89  model: MODEL,
90  maxTokens: 4000,
91  system: 'You sort a game studio’s work items ("intents") into the game’s core modules. Pick the one to three modules each intent mainly works on, most central first. Use only the module keys given; never invent one. An intent about a tool for a module belongs to that module and to tooling.',
92  prompt: `The modules (key: name, what belongs in it):\n${modules.map(one => `${one.key}: ${one.name}${one.hint ? `, ${one.hint}` : ''}`).join('\n')}\n\nThe intents (key | title | area | goal):\n${records.map(one => [one.key, one.title, one.area, one.goal].join(' | ')).join('\n')}\n\nReply with JSON only, no prose around it: {"<intent key>": ["<module key>", ...], ...} for every intent above.`,
93})
94
95/**
96 * The model's sorting, checked: known intents and modules only, at most three each, once each. An
97 * intent the reply leaves out stays missing, to be asked again.
98 * @param {string} text @param {readonly BoardRecord[]} records @param {readonly Module[]} modules @returns {Mapping}
99 */
100export const parseMapping = (text, records, modules) => {
101  const reply = jsonOf(text)
102  if (!reply) return {}
103  const known = new Set(modules.map(one => one.key))
104  /** @type {Mapping} */
105  const mapping = {}
106  for (const record of records) {
107    const value = reply[record.key]
108    const picked = Array.isArray(value) ? [...new Set(value.filter(key => typeof key === 'string' && known.has(key)))].slice(0, 3) : []
109    if (picked.length > 0) mapping[record.key] = picked
110  }
111  return mapping
112}
113
114// What is kept once the model has answered for some intents.
115/** @param {Kept | null} kept @param {readonly Module[]} modules @param {readonly BoardRecord[]} records @param {Mapping} answered @returns {Kept} */
116export const keep = (kept, modules, records, answered) => {
117  const list = listKey(modules)
118  const entries = kept && kept.list === list ? { ...kept.entries } : {}
119  for (const record of records) {
120    const answer = answered[record.key]
121    if (answer) entries[record.key] = { print: fingerprint(record), modules: answer }
122  }
123  return { list, entries }
124}
125
hooks/brief.mjs 142 lines
1// @ts-check
2// Ather Board: the model's help (D7, D9). The brief: Sonnet reads a digest of the open intents and says
3// what matters, as a headline and a few suggestions that each name intents and one action. Ask: a
4// question typed in the pane comes back as a short answer and a cut of the board. Every reply is checked
5// against what the board read: an intent it does not know, or an action it does not have, is dropped,
6// so a suggestion on the board always acts on real intents. Pure: no `$`; index.mjs makes the calls.
7
8import { ACTION_KINDS, OWNER_ACTIONS } from './act.mjs'
9import { isMine } from './ather/model.mjs'
10import { NO_FILTER, PANE_VIEWS, STAGES, ageText } from './views.mjs'
11
12/**
13 * @typedef {import('./views.mjs').BoardRecord} BoardRecord
14 * @typedef {import('./views.mjs').View} View
15 * @typedef {import('./views.mjs').Filter} Filter
16 * @typedef {import('./focus.mjs').Suggestion} Suggestion
17 * @typedef {{ headline: string, suggestions: Suggestion[] }} Brief
18 * @typedef {{ answer: string, view: View | '', area: string, owner: string, stage: string, keys: string[] }} Answer a cut of the board: '' leaves that part as it is; `keys`: only these intents
19 */
20
21export const MODEL = 'sonnet'
22export const MAX_SUGGESTIONS = 5
23
24// One line per open intent, what a model needs to judge it and nothing more (a digest of ~80 intents is ~6k tokens).
25/** @param {readonly BoardRecord[]} records @param {string} me @param {number} now */
26export const digest = (records, me, now) =>
27  records
28    .filter(one => one.stage !== 'done')
29    .map(one =>
30      [
31        one.key,
32        STAGES.find(stage => stage.key === one.stage)?.label ?? one.stage,
33        one.area,
34        `${one.owner || 'no owner'}${isMine(one, me) ? ' (me)' : ''}`,
35        one.total ? `${one.done}/${one.total} met` : 'no checklist',
36        `changed ${ageText(one.updatedAt, now) || '?'} ago`,
37        one.flags.length ? `flags: ${one.flags.map(flag => flag.label).join(', ')}` : '',
38        one.calls.length ? `decisions: ${one.calls.map(call => `${call.id} ${call.title}`).join('; ')}` : '',
39        one.goal,
40      ]
41        .filter(Boolean)
42        .join(' | '),
43    )
44    .join('\n')
45
46// The views an answer may pick: the pane's, less For you (which takes no filter).
47const VIEWS = PANE_VIEWS.filter(view => view !== 'foryou')
48
49const ROLE = `You help a game studio's team cut through its list of "intents" (features, each a folder with a goal, an acceptance checklist and open decisions). The board is read-only; every action you suggest is handed to a Claude Code session that asks the person before changing anything. Be concrete and brief: name intents by their key exactly as given, never invent one. Prefer what unblocks the most work: decisions waiting, work ready to close, stale or stuck work, then hygiene.`
50
51const ACTIONS = `Actions: ${ACTION_KINDS.join(', ')}, or show (cut the board to the intents named). ${OWNER_ACTIONS.join(', ')} are for the person's own intents (marked "(me)"); for a teammate's, use ping, about or show.`
52
53/** @param {readonly BoardRecord[]} records @param {string} me @param {number} now */
54export const briefRequest = (records, me, now) => ({
55  model: MODEL,
56  maxTokens: 1500,
57  system: `${ROLE}\n${ACTIONS}`,
58  prompt: `The person at the keyboard is ${me || 'unknown'}. The open intents, one per line (key | stage | area | owner | checklist | last change | flags | decisions | goal):\n\n${digest(records, me, now)}\n\nWrite the brief: what matters most right now, for this person first, then for the team. Reply with JSON only, no prose around it:\n{"headline": "<one sentence>", "suggestions": [{"title": "<imperative, under 12 words>", "why": "<one short sentence>", "action": "<action>", "intents": ["<key>", ...]}]}\nAt most ${MAX_SUGGESTIONS} suggestions.`,
59})
60
61/** @param {string} question @param {readonly BoardRecord[]} records @param {string} me @param {number} now */
62export const askRequest = (question, records, me, now) => ({
63  model: MODEL,
64  maxTokens: 800,
65  system: `${ROLE}\nYou answer a question about the board and pick the cut of it that shows the answer. Views: ${VIEWS.join(', ')} (items: open acceptance items; modules: the game's modules). Stages: ${STAGES.map(stage => stage.key).join(', ')}.`,
66  prompt: `The person at the keyboard is ${me || 'unknown'}. The open intents, one per line (key | stage | area | owner | checklist | last change | flags | decisions | goal):\n\n${digest(records, me, now)}\n\nTheir question: ${question.trim()}\n\nReply with JSON only, no prose around it:\n{"answer": "<at most three sentences>", "view": "<a view, or empty>", "area": "<an area exactly as listed, or empty>", "owner": "<an owner exactly as listed, or empty>", "stage": "<a stage, or empty>", "intents": ["<key>", ...]}\nList intents only when the answer is a particular set of them; leave the rest empty.`,
67})
68
69// The first JSON object in a reply (a model may wrap it in a code fence); null when there is none.
70/** @param {string} text @returns {Record<string, unknown> | null} */
71export const jsonOf = text => {
72  const start = text.indexOf('{')
73  const end = text.lastIndexOf('}')
74  if (start < 0 || end <= start) return null
75  try {
76    const value = JSON.parse(text.slice(start, end + 1))
77    return value && typeof value === 'object' && !Array.isArray(value) ? value : null
78  } catch {
79    return null
80  }
81}
82
83/** @param {unknown} value @param {number} max */
84const words = (value, max) => (typeof value === 'string' ? value.replace(/\s+/g, ' ').trim().slice(0, max) : '')
85
86// The keys a reply names that the board read, in its order, once each.
87/** @param {unknown} value @param {readonly BoardRecord[]} records @returns {string[]} */
88const knownKeys = (value, records) => {
89  const known = new Set(records.map(one => one.key))
90  return Array.isArray(value) ? [...new Set(value.filter(key => typeof key === 'string' && known.has(key)))] : []
91}
92
93// What a suggestion may ask for: an action, or show.
94/** @type {Suggestion['action'][]} */
95const PICKS = ['show', ...ACTION_KINDS]
96
97// A brief from the model's reply; null when the reply has no brief in it. A suggestion naming no known
98// intent, or an unknown action, is dropped; an action only the owner may take, suggested for a
99// teammate's intent, becomes show.
100/** @param {string} text @param {readonly BoardRecord[]} records @param {string} me @returns {Brief | null} */
101export const parseBrief = (text, records, me) => {
102  const reply = jsonOf(text)
103  if (!reply) return null
104  const list = Array.isArray(reply.suggestions) ? reply.suggestions : []
105  /** @type {Suggestion[]} */
106  const suggestions = list.flatMap((/** @type {unknown} */ item, /** @type {number} */ index) => {
107    const one = item && typeof item === 'object' ? /** @type {Record<string, unknown>} */ (item) : {}
108    const keys = knownKeys(one.intents, records)
109    const action = PICKS.find(kind => kind === words(one.action, 20))
110    if (keys.length === 0 || !action) return []
111    const isOwn = keys.every(key => records.some(record => record.key === key && isMine(record, me)))
112    return [{ key: `brief-${index}`, title: words(one.title, 90) || keys.join(', '), why: words(one.why, 200), action: action !== 'show' && OWNER_ACTIONS.some(kind => kind === action) && !isOwn ? 'show' : action, keys }]
113  })
114  return { headline: words(reply.headline, 240), suggestions: suggestions.slice(0, MAX_SUGGESTIONS) }
115}
116
117// An answer from the model's reply; null when there is none. A view, area, owner or stage the board
118// does not have is left as it is ('').
119/** @param {string} text @param {readonly BoardRecord[]} records @returns {Answer | null} */
120export const parseAnswer = (text, records) => {
121  const reply = jsonOf(text)
122  if (!reply) return null
123  const answer = words(reply.answer, 600)
124  const pick = (/** @type {unknown} */ value, /** @type {readonly string[]} */ allowed) => { const one = words(value, 80); return allowed.includes(one) ? one : '' }
125  return {
126    answer,
127    view: VIEWS.find(view => view === words(reply.view, 20)) ?? '',
128    area: pick(reply.area, [...new Set(records.map(one => one.area))]),
129    owner: pick(reply.owner, [...new Set(records.map(one => one.owner))]),
130    stage: pick(reply.stage, STAGES.map(stage => stage.key)),
131    keys: knownKeys(reply.intents, records),
132  }
133}
134
135// The cut of the board an answer picked: its view (the table when it names intents and no view; For you,
136// which has no filters, gives way to Triage), and its filters over a clean slate.
137/** @param {Answer} answer @param {View} current @returns {{ view: View, filter: Filter }} */
138export const answerLook = (answer, current) => ({
139  view: answer.view || (answer.keys.length > 0 ? 'table' : current === 'foryou' ? 'triage' : current),
140  filter: { ...NO_FILTER, area: answer.area, owner: answer.owner, stage: answer.stage, keys: answer.keys },
141})
142
hooks/focus.mjs 104 lines
1// @ts-check
2// Ather Board: For you (D8). What the person at the keyboard can act on, before the team's views:
3// their intents grouped by what each needs from them, worst first, then the rest of their open work;
4// and the suggestions the board can make without a model (the brief adds the model's, brief.mjs).
5// Pure: no `$`.
6
7import { isMine } from './ather/model.mjs'
8import { nextAction } from './act.mjs'
9import { moduleSections } from './map.mjs'
10import { DAY_MS, WARNINGS, pairCount, recordsFor, rowOf, sectionsOf, sortRecords, withColliding } from './views.mjs'
11
12/**
13 * @typedef {import('./views.mjs').BoardRecord} BoardRecord
14 * @typedef {import('./views.mjs').Section} Section
15 * @typedef {import('./views.mjs').IntentGroup} IntentGroup
16 * @typedef {import('./act.mjs').ActionKind} ActionKind
17 * @typedef {{ key: string, title: string, why: string, action: ActionKind | 'show', keys: string[] }} Suggestion
18 *   one thing worth doing: `action` over the intents `keys` (`show`: cut the board to them)
19 */
20
21// What each of the person's open intents needs from them, in this order; an intent sits in the first that fits.
22const NEEDS = /** @type {const} */ ([
23  { key: 'decide', title: 'Waiting on your decision', actions: ['decide'] },
24  { key: 'close', title: 'Ready for you to close', actions: ['close'] },
25  { key: 'stuck', title: 'Stuck', actions: ['reason', 'unstick'] },
26  { key: 'tidy', title: 'Needs a checklist or a tidy header', actions: ['checklist', 'tidy'] },
27])
28
29/** @param {string} key @param {string} title @param {string} empty @param {readonly BoardRecord[]} list @returns {IntentGroup} */
30const group = (key, title, empty, list) => ({ kind: 'intents', key, title, meta: String(list.length), empty, hide: 'owner', rows: list.map(record => rowOf(record, WARNINGS)) })
31
32/**
33 * For you as sections: a lime label over what needs the person, then their other open work.
34 * `me`: their git name ('' when unknown).
35 * @param {readonly BoardRecord[]} records @param {string} me @returns {Section[]}
36 */
37export const forYou = (records, me) => {
38  if (me === '') return [{ kind: 'label', key: 'label-you', title: 'For you', meta: '', isLoud: true, groups: [group('you-none', '', 'Set git user.name in this checkout so the board knows which intents are yours. Triage shows the team’s.', [])] }]
39  const mine = sortRecords(records.filter(one => one.stage !== 'done' && isMine(one, me)), 'stale')
40  const needs = NEEDS.map(need => ({ need, list: mine.filter(one => need.actions.some(action => action === nextAction(one, true))) })).filter(one => one.list.length > 0)
41  // Your work that collides, after your decisions (overlap-check D5); an intent in a pair is placed by it.
42  const groups = withColliding(needs.map(({ need, list }) => group(`you-${need.key}`, need.title, '', list)), mine, { key: 'you-colliding', note: '', isDecisions: one => one.key === 'you-decide' })
43  const placed = new Set([...needs.flatMap(one => one.list.map(record => record.key)), ...mine.filter(one => one.collisions.length > 0).map(one => one.key)])
44  const rest = sortRecords(mine.filter(one => !placed.has(one.key)), 'recent')
45  const count = needs.reduce((sum, one) => sum + one.list.length, 0) + pairCount(groups)
46  return [
47    { kind: 'label', key: 'label-you', title: 'For you', meta: String(count), isLoud: true, groups: groups.length > 0 ? groups : [group('you-none', '', mine.length > 0 ? 'Nothing of yours needs you now.' : 'You own no open intents. Triage shows the team’s.', [])] },
48    ...(rest.length > 0 ? [/** @type {Section} */ ({ kind: 'label', key: 'label-yours', title: 'Your other open work', meta: String(rest.length), isLoud: false, groups: [group('yours', '', '', rest)] })] : []),
49  ]
50}
51
52// The brief's suggestions, then the board's own that the brief did not already make (the same action on the same intents).
53/** @param {readonly Suggestion[]} brief @param {readonly Suggestion[]} plain */
54export const mergeSuggestions = (brief, plain) => {
55  const said = new Set(brief.map(one => `${one.action}:${[...one.keys].sort().join(',')}`))
56  return [...brief, ...plain.filter(one => !said.has(`${one.action}:${[...one.keys].sort().join(',')}`))]
57}
58
59/**
60 * What the board suggests without a model, most useful first, at most four: close every ready intent of
61 * yours at once, answer your oldest decision, tidy your headers, and see the teammates' intents that wait on a decision.
62 * @param {readonly BoardRecord[]} records @param {string} me @param {number} now @returns {Suggestion[]}
63 */
64export const plainSuggestions = (records, me, now) => {
65  const open = records.filter(one => one.stage !== 'done')
66  const mine = open.filter(one => isMine(one, me))
67  const days = (/** @type {BoardRecord} */ one) => Math.max(0, Math.floor((now - one.updatedAt) / DAY_MS))
68  const ready = mine.filter(one => one.stage === 'met')
69  const [oldest] = sortRecords(mine.filter(one => one.calls.length > 0), 'stale')
70  const untidy = mine.filter(one => nextAction(one, true) === 'tidy')
71  const waiting = open.filter(one => !isMine(one, me) && one.calls.length > 0)
72  /** @type {Suggestion[]} */
73  const all = [
74    ...(ready.length === 0 ? [] : [{ key: 'close-ready', title: ready.length === 1 ? `Close ${ready[0]?.slug}` : `Close your ${ready.length} ready intents`, why: 'Every acceptance item is met.', action: /** @type {const} */ ('close'), keys: ready.map(one => one.key) }]),
75    ...(oldest ? [{ key: 'decide-oldest', title: `Answer ${oldest.calls.length === 1 ? 'the decision' : `the ${oldest.calls.length} decisions`} on ${oldest.slug}`, why: `Waiting ${days(oldest)} ${days(oldest) === 1 ? 'day' : 'days'}; the work cannot go on until then.`, action: /** @type {const} */ ('decide'), keys: [oldest.key] }] : []),
76    ...(untidy.length === 0 ? [] : [{ key: 'tidy-mine', title: untidy.length === 1 ? `Fix the header of ${untidy[0]?.slug}` : `Fix the headers of your ${untidy.length} intents`, why: 'The team’s views cannot place them as written.', action: /** @type {const} */ ('tidy'), keys: untidy.map(one => one.key) }]),
77    ...(waiting.length === 0 ? [] : [{ key: 'show-waiting', title: `${waiting.length} teammates’ intents wait on a decision`, why: 'Answering, or nudging their owners, unblocks the most work.', action: /** @type {const} */ ('show'), keys: waiting.map(one => one.key) }]),
78  ]
79  return all.slice(0, 4)
80}
81
82/**
83 * What each of the pane's views draws besides its sections: the search and the pickers (`filters`), the
84 * suggestions (`brief`, For you), and where the module mapping stands (`mapping`, Modules).
85 * @typedef {{ filters: boolean, brief: boolean, mapping: boolean }} Extras
86 */
87/** @type {Extras} */
88const PLAIN = { filters: true, brief: false, mapping: false }
89/** @type {Partial<Record<import('./views.mjs').View, Extras>>} */
90const EXTRAS = { foryou: { filters: false, brief: true, mapping: false }, modules: { filters: true, brief: false, mapping: true } }
91
92/**
93 * What a pane view shows: the records it sees, its sections (For you's, the modules', or the shared
94 * views'), and its extras. The one place the pane's views are told apart.
95 * @param {readonly BoardRecord[]} records @param {import('./views.mjs').Look} look
96 * @param {{ me: string, modules: readonly import('./modules.mjs').Module[], mapping: import('./modules.mjs').Mapping, now: number, note?: string }} context
97 * `note`: why the overlap check could not run, for Triage
98 */
99export const paneView = (records, look, { me, modules, mapping, now, note = '' }) => {
100  const shown = recordsFor(records, look)
101  const parts = look.view === 'foryou' ? forYou(records, me) : look.view === 'modules' ? moduleSections(shown, modules, mapping, look.sort, now) : sectionsOf(shown, look, now, note)
102  return { shown, parts, extras: EXTRAS[look.view] ?? PLAIN }
103}
104
hooks/ather/packs/index.mjs 129 lines
1// @ts-check
2// Ather Automata: which pack serves a repository, and the shape every pack has.
3// The core (intents, Plan → Build → Prove → Ship, Next, away windows, issues,
4// the squad) is the same everywhere; a pack says what proof, traps, held
5// actions and words fit the kind of project. Pure apart from the Io it is given.
6//
7// Selection (D3): the repository's .ather/profile.json, then markers (*.uproject
8// → unreal; package.json or pyproject.toml → web), then the core alone. Read once
9// per session and root, and cached.
10
11import { gitDirOf, isAbsolute, normalFolder } from '../workspace.mjs'
12import { core } from './core.mjs'
13import { unreal } from './unreal.mjs'
14import { makeWebPack } from './web.mjs'
15
16/**
17 * @typedef {{ state: 'none' | 'pass' | 'fail', detail: string, at?: number, by?: string }} Rung `at`, `by`: when, and by which session (its first 8 hex), the record was written
18 * @typedef {{ rungs: { rung: string, value: Rung, gates?: RungGates }[], context: string[], toasts: { text: string, timeoutMs?: number }[], bumps: string[] }} ShellReading
19 * @typedef {{ ran: string[], all: string[] }} RungGates on a rung that gates declare: the gates a command ran (none: a command that is no gate), of all that declare it
20 * @typedef {{ id: string, pattern: RegExp, title: string, fix: string, rule?: { file: string, text: string } }} PackTrap
21 * @typedef {{ name: string, verb: string, isGlobal?: boolean }} CreateItem
22 * @typedef {{ isHeld: boolean, isFree: boolean, holder: string, until: string }} EditorState
23 * @typedef {{ command: string, proofs: string[], id?: string, proves?: string, passOn?: 'exit' | 'counts' }} Gate `passOn`: how its tests and ui proofs pass, on its exit code (also without the field) or on test counts
24 * @typedef {{ host: string, branch: string, deployment: string, url: string, expectStatus: number }} Production
25 * @typedef {{ files?: readonly string[], defaultBranch?: string }} Found what else was read of a repository where its pack is chosen: the names of the files at its root, and the default branch its clone knows
26 * @typedef {{ pack: Pack, held: readonly string[], isProven: boolean, base?: string }} HeldAt what a folder's own checkout holds, when that is not the session's; `base`: the branch its team merges into, when not main
27 * @typedef {{ isProven?: boolean, scripts?: Record<string, string>, base?: string, at?: (folder: string | null) => HeldAt | null }} HeldContext `base`: the branch the session's checkout merges into, when not main
28 * @typedef {{
29 *   id: 'unreal' | 'web' | 'core',
30 *   roles: readonly string[], roleLabels: Record<string, string>, roleDescriptions: Record<string, string>,
31 *   roleWords: string, roleHelp: string, roleFallback: string, roleKey: string, parseRole: (text: string) => string | null,
32 *   owners: string, areas: readonly string[], normalizeArea: (text: string) => string,
33 *   rungLabels: Record<string, string>, proofWords: Record<string, string>, emptyEvidence: () => Record<string, Rung>,
34 *   requiredRungs: (role: string) => string[], isProven: (evidence: Record<string, Rung>, role: string) => boolean, anyProofText: string,
35 *   localDir: string, debriefPath: (slug: string) => string,
36 *   lockFile: string | null, parseLock: (raw: string | null, nowMinutes: number) => import('./unreal.mjs').EditorLock, lockRoles: readonly string[],
37 *   lockLine?: (command: string, raw: string) => string,
38 *   ownCheck: { role: string, after: string, rung: string, label: string, hint: string, proveHint: string, detail: string, reply: string } | null,
39 *   traps: readonly PackTrap[],
40 *   held: { labels: Record<string, string>, nouns: Record<string, string>, kinds: readonly string[], defaults: readonly string[] },
41 *   heldSegment: (segment: string, held: readonly string[], context: HeldContext) => string | null,
42 *   mergePolicy: 'hold' | 'with-proof', mergeRungs?: readonly string[], rungGates?: Readonly<Record<string, string[]>>,
43 *   baseBranch?: string,
44 *   isAssetSave: (input: string) => boolean, readShell: (command: string, text: string, ran: { isError?: boolean, deny?: string }) => ShellReading,
45 *   mcpKind: (input: string) => 'write' | 'read' | 'pie' | null, binaryAssets: RegExp | null, briefPaths: RegExp,
46 *   skillGroups: readonly { group: string, names: readonly string[] }[], createGroups: readonly { group: string, items: readonly CreateItem[] }[],
47 *   createOrder: Record<string, readonly string[]>, createTitle: string, createMeta: (editor: EditorState) => string, createPrompt: (verb: string, name: string, editor: EditorState) => string,
48 *   prompts: { brief: (role: string, slug: string) => string, prove: (role: string, slug: string) => string, ship: (role: string, slug: string) => string, shipHint: (role: string) => string, briefHint: string, tour: string, tourToast: string, ask: (question: string) => string },
49 *   mandate: { flags: string, allowed: string, merge: string, away: string, pane: string, panes: string },
50 *   statusWhat: string, notHere: string, gates: readonly Gate[], production: Production | null, scripts?: Record<string, string>,
51 *   teams?: Readonly<Record<string, string>>, names?: import('../worklist.mjs').NameRules,
52 *   [key: string]: unknown
53 * }} Pack
54 */
55
56/**
57 * What selection reads: closures over the engine, as state.mjs's Io.
58 * @typedef {{ read: (path: string) => Promise<string | null>, exists: (path: string) => Promise<boolean>, list: (path: string) => Promise<{ name: string, kind: string }[]>, sessionId: () => Promise<string> }} PackIo
59 */
60
61/** @param {string | null} text */
62const json = text => {
63  if (!text) return null
64  try {
65    const value = JSON.parse(text)
66    return value && typeof value === 'object' ? value : null
67  } catch {
68    return null
69  }
70}
71
72// The default branch a clone knows: where refs/remotes/origin/HEAD points, in the git folder its worktrees share.
73// Read from the files, with no git call; '' when it cannot be told.
74/** @param {PackIo} io @param {string} root */
75const defaultBranchOf = async (io, root) => {
76  const named = await gitDirOf(io, root)
77  if (!named) return ''
78  // A worktree's .git file may name its git folder from the worktree.
79  const gitDir = named === `${root}/.git` || isAbsolute(named) ? named : normalFolder(`${root}/${named}`)
80  const common = ((await io.read(`${gitDir}/commondir`)) ?? '').trim()
81  const shared = common === '' ? gitDir : isAbsolute(common) ? common : normalFolder(`${gitDir}/${common}`)
82  return /^ref:\s*refs\/remotes\/origin\/(.+)/.exec((await io.read(`${shared}/refs/remotes/origin/HEAD`)) ?? '')?.[1]?.trim() ?? ''
83}
84
85/**
86 * Which pack a repository gets, and why, with the default branch its clone knows ('' when it cannot be told).
87 * Pure over what it reads.
88 * @param {PackIo} io @param {string} root
89 * @returns {Promise<{ pack: Pack, source: 'profile' | 'marker' | 'none', profile: Record<string, any> | null, defaultBranch: string }>}
90 */
91export const choosePack = async (io, root) => {
92  const profile = json(await io.read(`${root}/.ather/profile.json`))
93  const packageJson = json(await io.read(`${root}/package.json`))
94  const defaultBranch = await defaultBranchOf(io, root).catch(() => '')
95  const named = typeof profile?.pack === 'string' ? profile.pack.toLowerCase() : ''
96  if (named === 'unreal') return { pack: unreal, source: 'profile', profile, defaultBranch }
97  if (named === 'core') return { pack: core, source: 'profile', profile, defaultBranch }
98  const entries = await io.list(root).catch(() => [])
99  const files = entries.filter(entry => entry.kind === 'file' && typeof entry.name === 'string').map(entry => entry.name)
100  const web = () => makeWebPack(profile, packageJson, { files, defaultBranch })
101  if (named === 'web') return { pack: web(), source: 'profile', profile, defaultBranch }
102  if (entries.some(entry => entry.kind === 'file' && /\.uproject$/i.test(entry.name))) return { pack: unreal, source: 'marker', profile, defaultBranch }
103  if (packageJson || entries.some(entry => entry.kind === 'file' && /^(package\.json|pyproject\.toml)$/i.test(entry.name))) return { pack: web(), source: 'marker', profile, defaultBranch }
104  return { pack: core, source: 'none', profile, defaultBranch }
105}
106
107/** @type {Map<string, ReturnType<typeof choosePack>>} */
108const chosen = new Map()
109
110// Once per session and root: a profile edited mid-session takes effect in the next session.
111/** @param {PackIo} io @param {string} root */
112export const packFor = async (io, root) => {
113  const key = `${await io.sessionId().catch(() => '')}|${root}`
114  const hit = chosen.get(key)
115  if (hit) return hit
116  const read = choosePack(io, root)
117  chosen.set(key, read)
118  return read
119}
120
121// A repository that got its intents mid-session has a profile now: its pack is chosen again.
122/** @param {Pick<PackIo, 'sessionId'>} io @param {string} root */
123export const forgetPack = async (io, root) => void chosen.delete(`${await io.sessionId().catch(() => '')}|${root}`)
124
125// Tests only: forget what was chosen.
126export const forgetPacks = () => chosen.clear()
127
128export { core, unreal, makeWebPack }
129
hooks/ather/team.mjs 312 lines
1// @ts-check
2// Ather Automata: the team's intents as origin/main has them (or origin/<base>, where the team
3// merges into another branch), each dated by its folder's last commit there, merged with the
4// folders only this checkout has (D1-D3). Pure: git
5// and the files come through a Repo of closures built where `$` lives (console.mjs).
6// Every git call here reads, and never the working tree or the index; the fetch writes
7// only the remote-tracking ref.
8
9import { branchNamed } from './shell.mjs'
10
11/**
12 * `isAborted`: the app took the run back before it ended (it never ran to an exit code).
13 * @typedef {{ exitCode: number, stdout: string, stderr?: string, isAborted?: boolean }} Ran
14 * @typedef {{
15 *   git: (args: readonly string[], options?: { stdin?: string, timeoutMs?: number }) => Promise<Ran>,
16 *   read: (path: string) => Promise<string | null>,
17 *   list: (path: string) => Promise<readonly { name: string, kind: string }[]>,
18 *   mtime: (path: string) => Promise<number>,
19 *   real?: (folder: string) => Promise<string>,
20 * }} Repo `git` runs in the checkout with GIT_ENV; one that could not start or ran out of time answers exit code -1, the reason in stderr.
21 *   `real`: the folder a path really lands in, behind any symbolic link; without it folders are compared as given
22 * @typedef {{ files: string[], at: number, firstAuthor: string, prompt: string, progress: string, findings: string }} MainFolder `at`: the folder's last commit, ms
23 * @typedef {{ sha: string, folders: Map<string, MainFolder> }} MainSnapshot what origin/main held at `sha`
24 * @typedef {{ key: string, dirty: Set<string>, committed: Set<string> }} LocalState which folders are uncommitted, and which this branch committed since main, as of `key`
25 * @typedef {{ main: MainSnapshot | null, local: LocalState | null }} TeamCache what the last read learned; each part is read again only when what it depends on moved
26 * @typedef {import('./model.mjs').IntentFiles} IntentFiles
27 */
28
29// Every git call Ather makes reads without taking the index lock, and never asks for a password (D2).
30export const GIT_ENV = { GIT_OPTIONAL_LOCKS: '0', GIT_TERMINAL_PROMPT: '0' }
31// The remote-tracking ref of the branch a checkout's team merges into (its base).
32/** @param {string} base */
33const refOf = base => `origin/${base}`
34export const MAIN = refOf('main')
35export const INTENTS = 'docs/intent'
36// The fetch (D2): origin's base into origin/<base> by an explicit refspec (a narrowed remote.origin.fetch
37// would not move it otherwise), no tags, no FETCH_HEAD, no submodules, and no automatic gc or
38// maintenance: a background fetch in a shared checkout must not start a repack.
39// Several branches in one fetch, each into its own remote-tracking ref (the overlap check's, overlap.mjs).
40/** @param {...string} branches */
41export const fetchArgs = (...branches) => ['-c', 'gc.auto=0', '-c', 'maintenance.auto=false', 'fetch', '--no-tags', '--no-write-fetch-head', '--no-recurse-submodules', 'origin', ...branches.map(branch => `+refs/heads/${branch}:refs/remotes/${refOf(branch)}`)]
42export const FETCH_ARGS = fetchArgs('main')
43export const FETCH_EVERY_MS = 10 * 60 * 1000
44// As long as the engine lets a process run: a slow fetch is not a failed one.
45export const FETCH_TIMEOUT_MS = 10 * 60 * 1000
46export const EMPTY_CACHE = /** @type {TeamCache} */ ({ main: null, local: null })
47
48// The branch a checkout's team merges into: `baseBranch` in its .ather/profile.json when it reads as a branch name, else the default
49// branch its clone knows (`defaultBranch`: packs/index.mjs choosePack; '' when it cannot be told), else main.
50/** @param {Record<string, any> | null} profile @param {string} defaultBranch */
51export const baseOf = (profile, defaultBranch) => branchNamed(profile?.baseBranch) || branchNamed(defaultBranch) || 'main'
52
53/** @param {string} text */
54const lf = text => text.replace(/\r\n/g, '\n')
55
56// The intent folder a repository path is in: "docs/intent/lead-vfx/prompt.md" → "lead-vfx".
57/** @param {string} path */
58export const slugOf = path => /^docs\/intent\/([^/]+)\/./.exec(path.trim())?.[1] ?? ''
59
60// `git ls-tree -r --name-only` under docs/intent: each folder with the names of its files.
61/** @param {string} text @returns {Map<string, string[]>} */
62export const parseTree = text => {
63  /** @type {Map<string, string[]>} */
64  const folders = new Map()
65  for (const line of lf(text).split('\n')) {
66    const slug = slugOf(line)
67    if (!slug) continue
68    folders.set(slug, [...(folders.get(slug) ?? []), line.trim().slice(`${INTENTS}/${slug}/`.length)])
69  }
70  return folders
71}
72
73// `git log --format=%x00%ct%x09%an --name-only` under docs/intent, newest first: each folder's
74// last commit time (ms) and the author of its first commit.
75/** @param {string} text @returns {Map<string, { at: number, firstAuthor: string }>} */
76export const parseLog = text => {
77  /** @type {Map<string, { at: number, firstAuthor: string }>} */
78  const folders = new Map()
79  for (const record of lf(text).split('\0').slice(1)) {
80    const [head = '', ...paths] = record.split('\n')
81    const [seconds = '', author = ''] = head.split('\t')
82    const at = Number(seconds) * 1000
83    if (!Number.isFinite(at) || at <= 0) continue
84    for (const slug of new Set(paths.map(slugOf).filter(Boolean))) folders.set(slug, { at: folders.get(slug)?.at ?? at, firstAuthor: author.trim() })
85  }
86  return folders
87}
88
89// `git cat-file --batch` output, one entry per object asked for: its text, or null when missing.
90// Sizes count bytes, so the text is walked as UTF-8.
91/** @param {string} text @param {number} count @returns {(string | null)[]} */
92export const parseBatch = (text, count) => {
93  const bytes = new TextEncoder().encode(text)
94  const decoder = new TextDecoder()
95  /** @type {(string | null)[]} */
96  const out = []
97  let at = 0
98  while (out.length < count && at < bytes.length) {
99    const end = bytes.indexOf(10, at)
100    if (end < 0) break
101    const head = decoder.decode(bytes.subarray(at, end))
102    at = end + 1
103    const blob = / blob (\d+)$/.exec(head)
104    if (!blob) {
105      out.push(null)
106      continue
107    }
108    const size = Number(blob[1])
109    out.push(decoder.decode(bytes.subarray(at, at + size)))
110    at += size + 1
111  }
112  while (out.length < count) out.push(null)
113  return out
114}
115
116// `git status --porcelain=v1 -z` under docs/intent: the folders with uncommitted or untracked files.
117/** @param {string} text */
118export const parseStatus = text => new Set(text.split('\0').map(entry => slugOf(entry.replace(/^.. /, ''))).filter(Boolean))
119
120/** @param {string} prompt */
121const isCompleted = prompt => /^\s*-\s*Status:\s*completed/im.test(prompt)
122
123// The text of each file at `sha`, in order; null for one that is missing (one `git cat-file --batch`).
124/** @param {Repo} repo @param {string} sha @param {readonly string[]} paths */
125export const blobs = async (repo, sha, paths) => {
126  if (paths.length === 0) return []
127  const ran = await repo.git(['cat-file', '--batch'], { stdin: paths.map(path => `${sha}:${path}\n`).join('') })
128  return ran.exitCode === 0 ? parseBatch(ran.stdout, paths.length) : paths.map(() => null)
129}
130
131/** @param {string} a @param {string} b */
132const isSamePath = (a, b) => {
133  const norm = (/** @type {string} */ path) => path.trim().replace(/\\/g, '/').replace(/\/+$/, '').toLowerCase()
134  return norm(a) === norm(b)
135}
136
137/** @param {Repo} repo @param {string} ref */
138const shaOf = async (repo, ref) => {
139  const ran = await repo.git(['rev-parse', '--verify', '--quiet', `${ref}^{commit}`])
140  return ran.exitCode === 0 ? ran.stdout.trim() : ''
141}
142
143// What origin/main (origin/<base>) holds under docs/intent: every folder's files, last commit and first
144// author, its prompt.md, and the progress and findings of open ones. Read again only when the ref moved:
145// `previous` is returned as it is while the ref is still at its commit. null: no such ref.
146/** @param {Repo} repo @param {MainSnapshot | null} previous @param {string} [base] @returns {Promise<MainSnapshot | null>} */
147export const readMain = async (repo, previous, base = 'main') => {
148  const sha = await shaOf(repo, refOf(base))
149  if (!sha) return null
150  if (previous?.sha === sha) return previous
151  const [tree, log] = await Promise.all([repo.git(['ls-tree', '-r', '--name-only', sha, '--', INTENTS]), repo.git(['log', sha, '--format=%x00%ct%x09%an', '--name-only', '--', INTENTS])])
152  if (tree.exitCode !== 0 || log.exitCode !== 0) return previous
153  const files = parseTree(tree.stdout)
154  const dates = parseLog(log.stdout)
155  const slugs = [...files.keys()].filter(slug => files.get(slug)?.includes('prompt.md'))
156  const prompts = await blobs(repo, sha, slugs.map(slug => `${INTENTS}/${slug}/prompt.md`))
157  const open = slugs.filter((_, index) => !isCompleted(prompts[index] ?? ''))
158  const more = await blobs(repo, sha, open.flatMap(slug => [`${INTENTS}/${slug}/progress.md`, `${INTENTS}/${slug}/findings.md`]))
159  /** @type {Map<string, MainFolder>} */
160  const folders = new Map()
161  slugs.forEach((slug, index) => {
162    const at = open.indexOf(slug)
163    folders.set(slug, {
164      files: files.get(slug) ?? [],
165      at: dates.get(slug)?.at ?? 0,
166      firstAuthor: dates.get(slug)?.firstAuthor ?? '',
167      prompt: lf(prompts[index] ?? ''),
168      progress: at < 0 ? '' : lf(more[at * 2] ?? ''),
169      findings: at < 0 ? '' : lf(more[at * 2 + 1] ?? ''),
170    })
171  })
172  return { sha, folders }
173}
174
175// Which local folders are uncommitted, and which this branch committed since main. Both calls load
176// the whole index of a large checkout, so readTeam asks only when `key` (main, HEAD and the intent
177// files' times) moved.
178/** @param {Repo} repo @param {string} sha @param {string} key @returns {Promise<LocalState>} */
179const readLocal = async (repo, sha, key) => {
180  const [status, ahead] = await Promise.all([repo.git(['status', '--porcelain=v1', '-z', '--untracked-files=all', '--', INTENTS]), repo.git(['log', `${sha}..HEAD`, '--format=%x00%ct%x09%an', '--name-only', '--', INTENTS])])
181  return { key, dirty: parseStatus(status.exitCode === 0 ? status.stdout : ''), committed: new Set(parseLog(ahead.exitCode === 0 ? ahead.stdout : '').keys()) }
182}
183
184// The checkout's copy of an intent main has too wins when it says something else and is newer:
185// uncommitted, or committed on this branch since main (D1). Main's progress and findings count only
186// where main kept them (for open intents).
187/** @param {{ prompt: string, progress: string, findings: string }} local @param {MainFolder} onMain @param {boolean} isNewer */
188export const localWins = (local, onMain, isNewer) =>
189  isNewer && (local.prompt !== onMain.prompt || (onMain.progress !== '' && local.progress !== onMain.progress) || (onMain.findings !== '' && local.findings !== onMain.findings))
190
191// The intents to show: origin/main's, and the checkout's own folders. A folder on both is read from
192// main unless the checkout's copy wins (localWins); the tracked one (`pinned`) always from the
193// checkout, where its session writes. Main's are dated by their last commit there, the checkout's by
194// their files (D3). `isRepo` false: not a git checkout of its own, so only its folders are read, untagged.
195// `base`: the branch the checkout's team merges into, when that is not main; "main" above is then origin/<base>.
196/**
197 * @param {Repo} repo @param {string} root
198 * @param {{ cache: TeamCache, pinned: string | null, base?: string }} options
199 * @returns {Promise<{ isRepo: boolean, cache: TeamCache, intents: IntentFiles[] }>}
200 */
201export const readTeam = async (repo, root, { cache, pinned, base = 'main' }) => {
202  const top = await repo.git(['rev-parse', '--show-toplevel'])
203  // Git names the checkout's real folder; the session may have reached it through a link (macOS /var, /tmp).
204  const isRepo = top.exitCode === 0 && (isSamePath(top.stdout, root) || (repo.real !== undefined && isSamePath(top.stdout, await repo.real(root).catch(() => root))))
205  const main = isRepo ? await readMain(repo, cache.main, base) : null
206  const folders = []
207  for (const entry of await repo.list(`${root}/${INTENTS}`).catch(() => [])) {
208    if (entry.kind !== 'dir') continue
209    const dir = `${root}/${INTENTS}/${entry.name}`
210    const prompt = await repo.read(`${dir}/prompt.md`)
211    if (prompt === null) continue
212    const isOpen = !isCompleted(prompt)
213    const [progress, findings] = await Promise.all([repo.read(`${dir}/progress.md`), repo.read(`${dir}/findings.md`)])
214    const times = await Promise.all(['prompt.md', 'progress.md', 'findings.md', 'log.md'].map(name => repo.mtime(`${dir}/${name}`)))
215    const text = { prompt: lf(prompt), progress: isOpen || entry.name === pinned ? lf(progress ?? '') : '', findings: isOpen ? lf(findings ?? '') : '' }
216    folders.push({ slug: entry.name, dir, text, times })
217  }
218  const key = main ? [main.sha, await shaOf(repo, 'HEAD'), ...folders.map(one => `${one.slug}:${one.times.join(',')}`)].join('|') : ''
219  const local = !main ? null : cache.local?.key === key ? cache.local : await readLocal(repo, main.sha, key)
220  /** @type {Map<string, IntentFiles>} */
221  const out = new Map()
222  for (const [slug, folder] of main?.folders ?? []) {
223    out.set(slug, { slug, prompt: folder.prompt, progress: folder.progress, findings: folder.findings, files: folder.files, hasDebrief: false, updatedAt: folder.at, source: 'main', firstAuthor: folder.firstAuthor })
224  }
225  for (const { slug, dir, text, times } of folders) {
226    const onMain = main?.folders.get(slug)
227    if (onMain && slug !== pinned && !localWins(text, onMain, Boolean(local && (local.dirty.has(slug) || local.committed.has(slug))))) continue
228    const [prompt = 0, progress = 0, , log = 0] = times
229    out.set(slug, {
230      slug,
231      ...text,
232      files: slug === pinned ? (await repo.list(dir).catch(() => [])).map(one => one.name) : [],
233      hasDebrief: false,
234      updatedAt: Math.max(prompt, progress, log),
235      source: 'local',
236      firstAuthor: onMain?.firstAuthor ?? '',
237    })
238  }
239  return { isRepo, cache: { main, local }, intents: [...out.values()] }
240}
241
242/**
243 * Where the background fetch stands, for the sync line. `lock`: the git lock a failed fetch ran into.
244 * `base`: the branch fetched, when the checkout's team does not merge into main.
245 * @typedef {{ isRepo: boolean, hasMain: boolean, isFetching: boolean, triedAt: number, fetchedAt: number, failedAt: number, error: string, lock: string, base?: string }} Sync
246 */
247
248/** @type {Sync} */
249export const NO_SYNC = { isRepo: false, hasMain: false, isFetching: false, triedAt: 0, fetchedAt: 0, failedAt: 0, error: '', lock: '' }
250
251// A fetch may start on its own: a git checkout, none running, the last try at least ten minutes ago (or never).
252/** @param {Sync} sync @param {number} now */
253export const isFetchDue = (sync, now) => sync.isRepo && !sync.isFetching && (sync.triedAt === 0 || now - sync.triedAt >= FETCH_EVERY_MS)
254
255// ↻ fetches at once, except after a fetch that ran into a git lock: that one waits for its next due time.
256/** @param {Sync} sync @param {number} now */
257export const canFetchNow = (sync, now) => sync.isRepo && !sync.isFetching && (!sync.lock || isFetchDue(sync, now))
258
259// The lock a failed git call names ("refs/remotes/origin/main.lock", "index.lock"), inside .git; '' when none.
260/** @param {string} text */
261export const lockOf = text => {
262  const path = (/([^\s'"]+\.lock)\b/.exec(text)?.[1] ?? '').replace(/\\/g, '/')
263  return path.includes('/.git/') ? path.slice(path.lastIndexOf('/.git/') + 6) : path.split('/').pop() ?? ''
264}
265
266// What a git run that failed says: its last line of complaint, else its exit code.
267/** @param {Ran} ran @param {string} command */
268export const complaintOf = (ran, command) => ((ran.stderr ?? '').trim().split('\n').pop() || `${command} exited with ${ran.exitCode}`).slice(0, 200)
269
270// Fetches origin's main, or the `base` given. Synced means git said so and origin/<base> resolves after it (`moved`: it moved).
271// On a failure: git's last line of complaint, and the lock it ran into, if any. `isAborted`: the app took the
272// run back, so nothing was tried.
273/** @param {Repo} repo @param {string} [base] @returns {Promise<{ error: string, lock: string, moved: boolean, isAborted?: true }>} */
274export const fetchMain = async (repo, base = 'main') => {
275  const before = await shaOf(repo, refOf(base))
276  const ran = await repo.git(base === 'main' ? FETCH_ARGS : fetchArgs(base), { timeoutMs: FETCH_TIMEOUT_MS })
277  const after = await shaOf(repo, refOf(base))
278  if (ran.exitCode === 0 && after) return { error: '', lock: '', moved: after !== before }
279  return { error: complaintOf(ran, 'git fetch'), lock: lockOf(ran.stderr ?? ''), moved: false, ...(ran.isAborted ? { isAborted: /** @type {const} */ (true) } : {}) }
280}
281
282// One sync line for several checkouts: a failed fetch in any of them, else one running, else the least
283// recently synced (never synced counts as the least). One checkout's is its own.
284/** @param {readonly Sync[]} syncs @returns {Sync} */
285export const syncSummary = syncs => {
286  const repos = syncs.filter(one => one.isRepo)
287  const failed = repos.find(one => one.failedAt > one.fetchedAt && !one.isFetching)
288  return failed ?? repos.find(one => one.isFetching) ?? [...repos].sort((a, b) => a.fetchedAt - b.fetchedAt)[0] ?? syncs[0] ?? NO_SYNC
289}
290
291/** @param {number} ms */
292const agoText = ms => {
293  const minutes = Math.floor(Math.max(0, ms) / 60000)
294  return minutes < 1 ? 'just now' : minutes < 60 ? `${minutes} min ago` : `${Math.floor(minutes / 60)} h ago`
295}
296
297// "synced 4 min ago ↻": how fresh the list is. A failed fetch says so, naming the git lock it ran
298// into, and keeps the last good time.
299/** @param {Sync} sync @param {number} now */
300export const syncText = (sync, now) => {
301  if (!sync.isRepo) return ''
302  if (sync.isFetching) return 'syncing…'
303  const synced = sync.fetchedAt ? `synced ${agoText(now - sync.fetchedAt)}` : ''
304  if (sync.failedAt > sync.fetchedAt) return `${sync.lock ? `sync waits on ${sync.lock}` : 'sync failed'}${synced ? ` · ${synced}` : ''} ↻`
305  if (synced) return `${synced} ↻`
306  return sync.hasMain ? 'not synced yet ↻' : `no ${refOf(sync.base ?? 'main')} ↻`
307}
308
309// What git said when the last fetch failed, for the line under "sync failed"; a named lock says enough on its own line.
310/** @param {Sync} sync */
311export const syncError = sync => (sync.failedAt > sync.fetchedAt && !sync.isFetching && !sync.lock ? sync.error : '')
312
hooks/ather/overlap.mjs 314 lines
1// @ts-check
2// Ather Automata: open work that changes the same lines (overlap-check D1-D6). Which open intents'
3// branches to compare, with the base branch and with each other, and what `git merge-tree` says of
4// each pair: the files in conflict, where in them, and each side's first changed line. Ather Board
5// draws it, and so does Needs you for this checkout's own branch (collide.mjs words both). Pure: git
6// comes through a Repo (team.mjs) built where `$` lives. Every call here reads, never the working tree
7// or the index; the one fetch writes only remote-tracking refs.
8
9import { FETCH_TIMEOUT_MS, INTENTS, complaintOf, fetchArgs, slugOf } from './team.mjs'
10
11/**
12 * @typedef {import('./team.mjs').Repo} Repo
13 * @typedef {{ key: string, branch: string, tip?: string }} Side a piece of open work and the branch it is on: an intent, or this checkout's
14 *   branch with its own `tip` (collision-alert), which needs no copy on origin
15 * @typedef {{ path: string, line: number, kind: 'lines' | 'binary' | 'deleted', ours: string, theirs: string }} Spot one place both sides changed.
16 *   'lines': `line` is where it starts in the first side's file, `ours` and `theirs` each side's first changed line;
17 *   'binary': a file git cannot merge by lines; 'deleted': one side deleted the file the other changed (`ours`, `theirs`: 'changed' or 'deleted')
18 * @typedef {{ who: string, at: number, via: string[] }} BaseChange when the first side is the base: its last author and commit time on
19 *   the files, and the intent folders the change that brought that commit into the base also wrote (overlap-hardening D2)
20 * @typedef {{ files: string[], spots: Spot[], count: number, base: BaseChange | null }} Merge what merging two tips conflicts on:
21 *   `count` every place, `spots` the first SPOTS_KEPT; `base`: null for two intents
22 * @typedef {Merge & { key: string, a: string, b: string }} Overlap two sides that conflict: `a` an intent's key, or '' for the base branch
23 *   (the base is always `a`), `b` an intent's key; `key`: pairKey(a, b)
24 * @typedef {{ version: string, files: Map<string, string[]>, merges: Map<string, Merge | null> }} OverlapCache what earlier reads learned:
25 *   git's version, each branch's changed files by "<base tip>...<tip>", each merge by "<tip>..<tip>" (null: it merges cleanly)
26 * @typedef {{ overlaps: Overlap[], note: string, cache: OverlapCache, isPartial: boolean, compared: string[] }} OverlapRead `note`: why nothing could be checked,
27 *   '' when it ran; `isPartial`: the time budget ran out first, so another run goes on from where this one stopped (overlap-hardening D1);
28 *   `compared`: the sides this run merged with the base, so one with no overlap there merges cleanly (ship-pill D1)
29 */
30
31/** @type {OverlapCache} */
32export const EMPTY_OVERLAPS = { version: '', files: new Map(), merges: new Map() }
33
34// `git merge-tree --write-tree`, a merge with no working tree or index, arrived in git 2.38 (D4).
35export const MIN_GIT = /** @type {const} */ ([2, 38])
36// The places kept per pair; `count` says how many there are.
37export const SPOTS_KEPT = 6
38// How long one run may start new git work (overlap-hardening D1): past it, the run returns what it has and the next goes on.
39export const BUDGET_MS = 15000
40
41// "git version 2.43.0.windows.1" → [2, 43]; null when it is not git's answer.
42/** @param {string} text @returns {[number, number] | null} */
43export const gitVersion = text => {
44  const found = /git version (\d+)\.(\d+)/.exec(text)
45  return found ? [Number(found[1]), Number(found[2])] : null
46}
47
48/** @param {[number, number] | null} version */
49export const canMergeTree = version => version !== null && (version[0] > MIN_GIT[0] || (version[0] === MIN_GIT[0] && version[1] >= MIN_GIT[1]))
50
51// One key per pair whichever way round, the base's side ('') first.
52/** @param {string} a @param {string} b */
53export const pairKey = (a, b) => (a === '' || a < b ? `${a}|${b}` : `${b}|${a}`)
54
55/**
56 * Which pairs to merge (D3): every side whose branch changed something, against the base; two sides only
57 * when their branches change a file in common, so the merges stay near one per side. Two intents on one
58 * branch are one piece of work.
59 * @param {readonly Side[]} sides @param {ReadonlyMap<string, readonly string[]>} files each side's changed files, by its key
60 * @returns {{ a: string, b: string }[]}
61 */
62export const pairsToCheck = (sides, files) => {
63  const busy = sides.filter(side => (files.get(side.key) ?? []).length > 0)
64  const across = busy.flatMap((one, at) => {
65    const changed = new Set(files.get(one.key))
66    return busy.slice(at + 1).filter(other => other.branch !== one.branch && (files.get(other.key) ?? []).some(path => changed.has(path))).map(other => (one.key < other.key ? { a: one.key, b: other.key } : { a: other.key, b: one.key }))
67  })
68  return [...busy.map(side => ({ a: '', b: side.key })), ...across]
69}
70
71/**
72 * `git merge-tree --write-tree` output: the merged tree, each conflicted file's stages ("<mode> <sha> <stage>\t<path>":
73 * 2 the first side, 3 the second), a blank line, then git's messages, which name the binary files it could not merge.
74 * @param {string} text
75 */
76export const parseMergeTree = text => {
77  const [head = '', ...rest] = text.replace(/\r\n/g, '\n').split('\n')
78  const blank = rest.indexOf('')
79  /** @type {Map<string, Set<number>>} */
80  const stages = new Map()
81  for (const line of blank < 0 ? rest : rest.slice(0, blank)) {
82    const staged = /^\d+ [0-9a-f]+ ([123])\t(.+)$/.exec(line)
83    if (staged?.[2]) stages.set(staged[2], (stages.get(staged[2]) ?? new Set()).add(Number(staged[1])))
84  }
85  const binary = new Set((blank < 0 ? [] : rest.slice(blank + 1)).flatMap(line => /Cannot merge binary files: (.+) \(.+ vs\. .+\)$/.exec(line)?.slice(1, 2) ?? []))
86  return { tree: head.trim(), stages, binary }
87}
88
89/** @param {readonly string[]} lines */
90const firstLine = lines => (lines.find(line => line.trim() !== '') ?? '').trim().slice(0, 160)
91
92/**
93 * The places a conflicted file's markers mark, each with its line in the first side's file and each side's
94 * first changed line. A diff3-style base section ("||||||| ") is skipped.
95 * @param {string} path @param {string} text @returns {Spot[]}
96 */
97export const spotsIn = (path, text) => {
98  /** @type {Spot[]} */
99  const spots = []
100  /** @type {Record<'ours' | 'base' | 'theirs', string[]>} */
101  let parts = { ours: [], base: [], theirs: [] }
102  /** @type {'' | keyof typeof parts} */
103  let part = ''
104  let line = 0
105  let start = 0
106  for (const one of text.replace(/\r\n/g, '\n').split('\n')) {
107    if (one.startsWith('<<<<<<< ')) [part, parts, start] = ['ours', { ours: [], base: [], theirs: [] }, line + 1]
108    else if (part && one.startsWith('||||||| ')) part = 'base'
109    else if (part && one === '=======') part = 'theirs'
110    else if (part && one.startsWith('>>>>>>> ')) {
111      spots.push({ path, line: start, kind: 'lines', ours: firstLine(parts.ours), theirs: firstLine(parts.theirs) })
112      part = ''
113    } else {
114      if (part) parts[part].push(one)
115      // The first side's own lines count: outside a block, and its part of one.
116      if (part === '' || part === 'ours') line += 1
117    }
118  }
119  return spots
120}
121
122// Branch tips from lines of a tip then a name ("<sha> <name>", "<sha>\trefs/heads/<name>"): name → tip.
123/** @param {string} text @param {RegExp} line its tip and name in groups 1 and 2 @returns {Map<string, string>} */
124const tipsIn = (text, line) =>
125  new Map(
126    text.split('\n').flatMap(one => {
127      const found = line.exec(one.trim())
128      return found?.[1] && found[2] && found[2] !== 'HEAD' ? [/** @type {[string, string]} */ ([found[2], found[1]])] : []
129    }),
130  )
131
132// The branches origin has as this clone last fetched them.
133/** @param {Repo} repo */
134const remoteTips = async repo => {
135  const ran = await repo.git(['for-each-ref', '--format=%(objectname) %(refname:strip=3)', 'refs/remotes/origin'])
136  return tipsIn(ran.exitCode === 0 ? ran.stdout : '', /^([0-9a-f]+) (.+)$/)
137}
138
139// What a branch changed since it left the base: the files of "<base>...<tip>".
140/** @param {Repo} repo @param {string} base @param {string} tip */
141const changedFiles = async (repo, base, tip) => {
142  const ran = await repo.git(['diff', '--name-only', '-z', `${base}...${tip}`])
143  return ran.exitCode === 0 ? ran.stdout.split('\0').filter(Boolean) : []
144}
145
146/**
147 * Merges two tips with no working tree: null when they merge cleanly (or cannot be merged at all, such as
148 * unrelated histories); else the places they conflict. `brought`: `ours` is the base, whose last change is named;
149 * the intents behind each commit, kept for the run (several branches often collide with one change).
150 * @param {Repo} repo @param {string} ours @param {string} theirs @param {Map<string, Promise<string[]>> | null} brought @returns {Promise<Merge | null>}
151 */
152const mergeOf = async (repo, ours, theirs, brought) => {
153  const ran = await repo.git(['merge-tree', '--write-tree', ours, theirs])
154  if (ran.exitCode !== 1) return null
155  const { tree, stages, binary } = parseMergeTree(ran.stdout)
156  /** @type {Spot[]} */
157  const spots = []
158  for (const [path, staged] of stages) {
159    if (!staged.has(2) || !staged.has(3)) spots.push({ path, line: 0, kind: 'deleted', ours: staged.has(2) ? 'changed' : 'deleted', theirs: staged.has(3) ? 'changed' : 'deleted' })
160    else {
161      const merged = binary.has(path) ? null : await repo.git(['cat-file', '-p', `${tree}:${path}`])
162      const found = merged?.exitCode === 0 ? spotsIn(path, merged.stdout) : []
163      spots.push(...(found.length > 0 ? found : [{ path, line: 0, kind: /** @type {const} */ ('binary'), ours: '', theirs: '' }]))
164    }
165  }
166  if (spots.length === 0) return null
167  const files = [...stages.keys()]
168  const kept = { files, spots: spots.slice(0, SPOTS_KEPT), count: spots.length }
169  if (!brought) return { ...kept, base: null }
170  const last = await repo.git(['log', '-1', '--format=%H%x09%an%x09%ct', ours, '--', ...files])
171  const [sha = '', who = '', at = '0'] = last.exitCode === 0 ? last.stdout.trim().split('\t') : []
172  if (sha && !brought.has(sha)) brought.set(sha, broughtBy(repo, sha, ours))
173  return { ...kept, base: { who, at: Number(at) * 1000, via: sha ? await (brought.get(sha) ?? []) : [] } }
174}
175
176// The intent folders a list of paths names, each once ("docs/intent/hitstop-retune/progress.md" → "hitstop-retune").
177/** @param {string} text one path a line */
178export const intentsIn = text => [...new Set(text.split('\n').map(slugOf).filter(Boolean))]
179
180// Where a commit reached the base's own line: the commit itself when it is on that line (the tip, or the line's next
181// commit is its child), else the first commit of the line that contains it (a pull request's merge). '' when neither.
182/** @param {string} sha @param {string} base @param {readonly string[][]} steps the line after it, oldest first, each with its parents @param {ReadonlySet<string>} descendants */
183const landingOf = (sha, base, steps, descendants) => {
184  const isOnLine = sha === base || steps[0]?.[1] === sha
185  return isOnLine ? sha : (steps.find(([one = '']) => descendants.has(one))?.[0] ?? '')
186}
187
188/**
189 * The intents that brought a commit into the base (overlap-hardening D2): the change on the base's own line that
190 * brought it there (a pull request's merge, or the commit itself when it is on that line, a squash), and the intent
191 * folders that change also wrote. A pull request that moved its intent's progress names it.
192 * @param {Repo} repo @param {string} sha @param {string} base the base's tip
193 */
194const broughtBy = async (repo, sha, base) => {
195  // The base's own line after the commit, oldest first, each with its parents; and every descendant of the commit.
196  const [line, after] = await Promise.all([repo.git(['rev-list', '--first-parent', '--reverse', '--parents', `${sha}..${base}`]), repo.git(['rev-list', '--ancestry-path', `${sha}..${base}`])])
197  const descendants = new Set(after.exitCode === 0 ? after.stdout.split('\n').map(one => one.trim()) : [])
198  const steps = line.exitCode === 0 ? line.stdout.split('\n').map(one => one.trim().split(' ')).filter(one => one[0]) : []
199  const landed = landingOf(sha, base, steps, descendants)
200  if (!landed) return []
201  const changed = await repo.git(['diff', '--name-only', `${landed}^1`, landed, '--', INTENTS])
202  return changed.exitCode === 0 ? intentsIn(changed.stdout) : []
203}
204
205/**
206 * The overlaps among the sides and the base branch, from what this clone has fetched (D3, D6). A branch
207 * origin does not have (unless its side brings its own tip), or the base itself, is not compared. Each branch's files and each merge are kept by
208 * their tips, so an unchanged pair is never merged twice. The git calls run one after another on purpose:
209 * this runs in the background beside the person's own git, and a large checkout should feel none of it.
210 * New git work starts only within `budgetMs` (overlap-hardening D1), counted from the first of it, so each run makes
211 * some: past it, what was found is returned with `isPartial`, and the next run, given this run's cache, goes on.
212 * @param {Repo} repo @param {{ base: string, sides: readonly Side[], cache: OverlapCache, budgetMs?: number, now?: () => number }} input
213 * @returns {Promise<OverlapRead>}
214 */
215export const readOverlaps = async (repo, { base, sides, cache, budgetMs = BUDGET_MS, now = Date.now }) => {
216  const version = cache.version || (await repo.git(['version'])).stdout.trim()
217  const known = gitVersion(version)
218  if (!canMergeTree(known)) return { overlaps: [], note: known ? `git ${known.join('.')} cannot check overlaps (needs ${MIN_GIT.join('.')})` : '', cache: { ...cache, version: known ? version : '' }, isPartial: false, compared: [] }
219  const tips = await remoteTips(repo)
220  const baseTip = tips.get(base)
221  const present = sides.filter(side => side.branch !== base && (side.tip || tips.has(side.branch)))
222  if (!baseTip || present.length === 0) return { overlaps: [], note: '', cache: { version, files: new Map(), merges: new Map() }, isPartial: false, compared: [] }
223  /** @type {Map<string, string>} each side's tip, and the base's under '' */
224  const tipOf = new Map([['', baseTip], ...present.map(side => /** @type {[string, string]} */ ([side.key, side.tip || (tips.get(side.branch) ?? '')]))])
225  const tip = (/** @type {string} */ key) => tipOf.get(key) ?? ''
226  const started = now()
227  const isOver = () => now() - started > budgetMs
228  // Each side's changed files, from the cache or read while the budget lasts; the sides read are the ones compared.
229  const files = new Map()
230  /** @type {Map<string, string[]>} */
231  const byKey = new Map()
232  for (const side of present) {
233    const id = `${baseTip}...${tip(side.key)}`
234    const list = cache.files.get(id) ?? (isOver() ? null : await changedFiles(repo, baseTip, tip(side.key)))
235    if (list) {
236      files.set(id, list)
237      byKey.set(side.key, list)
238    }
239  }
240  const pairs = pairsToCheck(present.filter(side => byKey.has(side.key)), byKey)
241  const merges = new Map()
242  /** @type {Map<string, Promise<string[]>>} */
243  const brought = new Map()
244  /** @type {Overlap[]} */
245  const overlaps = []
246  /** @type {string[]} */
247  const compared = []
248  for (const { a, b } of pairs) {
249    const id = `${tip(a)}..${tip(b)}`
250    if (!cache.merges.has(id) && isOver()) continue
251    const merged = cache.merges.has(id) ? (cache.merges.get(id) ?? null) : await mergeOf(repo, tip(a), tip(b), a === '' ? brought : null)
252    merges.set(id, merged)
253    if (a === '') compared.push(b)
254    if (merged) overlaps.push({ key: pairKey(a, b), a, b, ...merged })
255  }
256  return { overlaps, note: '', cache: { version, files, merges }, isPartial: byKey.size < present.length || merges.size < pairs.length, compared }
257}
258
259/**
260 * The overlap check as a background job, one run at a time (D6): asked for while one runs, one more follows it,
261 * with the newest ask's `read` and `onRun`; a run that ran out of time (overlap-hardening D1) is followed by the
262 * next. Each run goes on from the last one's cache, and `onRun` hears it (to draw what it found). The promise
263 * settles with the last run's answer once no run is left, or with the error that stopped it.
264 * @returns {{ run: (read: (cache: OverlapCache) => Promise<OverlapRead>, onRun: (read: OverlapRead) => void) => Promise<OverlapRead>, last: () => OverlapRead }}
265 */
266export const overlapJob = () => {
267  /** @type {OverlapRead} */
268  let last = { overlaps: [], note: '', cache: EMPTY_OVERLAPS, isPartial: false, compared: [] }
269  /** @type {Promise<OverlapRead> | null} */
270  let running = null
271  /** @type {{ read: (cache: OverlapCache) => Promise<OverlapRead>, onRun: (read: OverlapRead) => void } | null} */
272  let asked = null
273  return {
274    run: (read, onRun) => {
275      if (running) {
276        asked = { read, onRun }
277        return running
278      }
279      running = (async () => {
280        try {
281          for (let ask = { read, onRun }; ; ask = asked ?? ask) {
282            asked = null
283            last = await ask.read(last.cache)
284            ask.onRun(last)
285            if (!asked && !last.isPartial) return last
286          }
287        } finally {
288          running = null
289        }
290      })()
291      return running
292    },
293    last: () => last,
294  }
295}
296
297/**
298 * Brings the open intents' branches up to date in their remote-tracking refs: asks origin where each is
299 * (one ls-remote), then fetches the ones that moved in one fetch, with the base's flags (no tags, no
300 * FETCH_HEAD, no gc). A branch origin does not have is left alone. '' when done, else git's last line.
301 * @param {Repo} repo @param {readonly string[]} branches
302 */
303export const fetchBranches = async (repo, branches) => {
304  if (branches.length === 0) return ''
305  const listed = await repo.git(['ls-remote', '--heads', 'origin'], { timeoutMs: FETCH_TIMEOUT_MS })
306  if (listed.exitCode !== 0) return complaintOf(listed, 'git ls-remote')
307  const origin = tipsIn(listed.stdout, /^([0-9a-f]+)\trefs\/heads\/(.+)$/)
308  const local = await remoteTips(repo)
309  const moved = [...new Set(branches)].filter(branch => origin.has(branch) && origin.get(branch) !== local.get(branch))
310  if (moved.length === 0) return ''
311  const ran = await repo.git(fetchArgs(...moved), { timeoutMs: FETCH_TIMEOUT_MS })
312  return ran.exitCode === 0 ? '' : complaintOf(ran, 'git fetch')
313}
314
hooks/ather/opener.mjs 37 lines
1// @ts-check
2// Ather Automata: opening a file or a link with the system's own handler, for every plugin that opens one (Ather
3// Board's page, Needs you's Go to session). Pure: the command runs through a closure built where `$` lives, and the
4// caller says whether the host is Windows (the engine names no platform; each caller has its own sign of it).
5
6/**
7 * Runs an argument vector (no shell) and resolves its exit code; it may reject when the command cannot start.
8 * @typedef {(argv: readonly string[]) => Promise<{ exitCode: number }>} Run
9 */
10
11// cmd reads these inside `start`'s argument too: a target carrying one is not handed to it.
12const CMD_SPECIAL = /["%^&|<>\r\n]/
13
14// Whether `start` may be handed `target`: it carries nothing cmd would read as more than one argument or command.
15/** @param {string} target */
16export const isStartable = target => !CMD_SPECIAL.test(target)
17
18// The commands that open `target`, tried in order: `start` through cmd on Windows, else `open` (macOS), then `xdg-open`.
19/** @param {string} target @param {boolean} isWindows @returns {string[][]} */
20export const openerTries = (target, isWindows) => {
21  if (isWindows) return isStartable(target) ? [['cmd', '/c', 'start', '', target]] : []
22  return [['open', target], ['xdg-open', target]]
23}
24
25// Whether one of them opened it (exit code 0). Never rejects: a command that cannot start (a rejection or a throw) is the
26// next one's turn.
27/** @param {Run} run @param {string} target @param {boolean} isWindows */
28export const openWith = async (run, target, isWindows) => {
29  for (const argv of openerTries(target, isWindows)) {
30    const ran = await Promise.resolve()
31      .then(() => run(argv))
32      .catch(() => undefined)
33    if (ran?.exitCode === 0) return true
34  }
35  return false
36}
37
hooks/records.mjs 118 lines
1// @ts-check
2// Ather Board: one record per intent, read the way Ather reads it (model.mjs parseIntent, worklist.mjs
3// listStage and ownerName), with the flags Triage sorts by. Pure: no `$`.
4
5import { directorCalls, parseIntent, plural } from './ather/model.mjs'
6import { listStage, ownerName } from './ather/worklist.mjs'
7import { collisionsFor } from './ather/collide.mjs'
8import { DAY_MS, STALE_DAYS } from './views.mjs'
9
10/**
11 * @typedef {import('./views.mjs').BoardRecord} BoardRecord
12 * @typedef {import('./views.mjs').Flag} Flag
13 * @typedef {import('./views.mjs').Stage} Stage
14 * @typedef {import('./ather/model.mjs').IntentFiles} IntentFiles
15 * @typedef {import('./ather/packs/index.mjs').Pack} Pack
16 * @typedef {import('./views.mjs').Party} Party
17 * @typedef {import('./ather/overlap.mjs').Overlap} Overlap
18 */
19
20// The words the intent skill writes on a Status line; anything else is read by its first word and flagged.
21const STATUS_WORDS = ['active', 'parked', 'completed']
22
23// Done when completed; Plan while it has no checklist; else where Ather's list puts it.
24/** @param {ReturnType<typeof parseIntent>} intent @returns {Stage} */
25const stageOf = intent => (intent.status === 'completed' ? 'done' : intent.status === 'parked' ? 'parked' : intent.acceptanceTotal === 0 ? 'plan' : listStage(intent))
26
27/**
28 * What Triage and the hygiene list say of an intent, in a row's few words: stale says no more than that, as
29 * the row's age has the days (STALE_DAYS or more); parked says it as Ather's list does. Done intents carry
30 * only hygiene flags.
31 * @param {ReturnType<typeof parseIntent>} intent @param {Stage} stage @param {Pack} pack @param {number} now
32 * @returns {Flag[]}
33 */
34const flagsOf = (intent, stage, pack, now) => {
35  /** @type {Flag[]} */
36  const flags = []
37  const isOpen = stage !== 'done'
38  const calls = directorCalls(intent).length
39  if (isOpen && calls > 0) flags.push({ kind: 'decisions', label: `${plural(calls, 'decision')} waiting` })
40  if (stage === 'met') flags.push({ kind: 'met', label: 'every item met, not closed' })
41  const idle = Math.floor((now - intent.updatedAt) / DAY_MS)
42  if (isOpen && stage !== 'parked' && intent.updatedAt > 0 && idle >= STALE_DAYS) flags.push({ kind: 'stale', label: 'stale' })
43  if (stage === 'parked' && !intent.statusNote) flags.push({ kind: 'unparked', label: 'parked, no reason' })
44  if (stage === 'plan') flags.push({ kind: 'plan', label: 'no acceptance checklist' })
45  if (!STATUS_WORDS.includes(intent.status)) flags.push({ kind: 'status', label: intent.status === 'unknown' ? 'no Status line' : `status "${intent.status}" is not active, parked or completed` })
46  else if (intent.statusNote && intent.status !== 'parked') flags.push({ kind: 'status', label: 'status line is a sentence' })
47  if (!intent.owner) flags.push({ kind: 'owner', label: 'no Owner line' })
48  if (pack.areas.length > 0 && !pack.areas.includes(intent.area)) flags.push({ kind: 'area', label: 'area not in the list' })
49  return flags
50}
51
52// The other intents an intent's files name (its prompt, progress and findings): every hyphenated word in
53// them that is another intent's folder name. How intents relate on the map, read from what they say.
54/** @param {IntentFiles} files @param {ReadonlySet<string>} slugs */
55export const mentionsOf = (files, slugs) => [...new Set(`${files.prompt}
56${files.progress}
57${files.findings}`.toLowerCase().match(/[a-z0-9]+(?:-[a-z0-9]+)+/g) ?? [])].filter(word => word !== files.slug && slugs.has(word)).sort()
58
59/**
60 * @param {IntentFiles} files @param {{ pack: Pack, createdAt: number, now: number, slugs?: ReadonlySet<string> }} context
61 * `createdAt`: when its folder was first committed (0: not known, its last change stands in); `slugs`: every intent's folder name, for its mentions
62 * @returns {BoardRecord}
63 */
64export const toRecord = (files, { pack, createdAt, now, slugs = new Set() }) => {
65  const intent = parseIntent(files, pack)
66  const stage = stageOf(intent)
67  return {
68    key: intent.key,
69    slug: intent.slug,
70    title: intent.title,
71    goal: intent.goal,
72    area: intent.area,
73    owner: ownerName(intent.owner, intent.firstAuthor, { teams: pack.teams, names: pack.names }),
74    stage,
75    status: intent.status,
76    statusNote: intent.statusNote,
77    done: intent.acceptanceDone,
78    total: intent.acceptanceTotal,
79    openItems: stage === 'done' ? [] : intent.openItems,
80    prs: intent.prs,
81    issue: intent.issue,
82    calls: stage === 'done' ? [] : directorCalls(intent).map(call => ({ id: call.id, title: call.title, options: call.options.map(({ letter, label, text, isRecommended }) => ({ letter, label, text, isRecommended })) })),
83    updatedAt: intent.updatedAt,
84    createdAt: createdAt || intent.updatedAt,
85    source: intent.source,
86    mentions: mentionsOf(files, slugs),
87    flags: flagsOf(intent, stage, pack, now),
88    branch: intent.branch,
89    collisions: [],
90  }
91}
92
93// The open intents whose branches the overlap check compares (overlap-check D2): not done, not parked, with a Branch line.
94/** @param {readonly BoardRecord[]} records */
95export const sidesOf = records => records.filter(one => one.stage !== 'done' && one.stage !== 'parked' && one.branch !== '').map(one => ({ key: one.key, branch: one.branch }))
96
97/**
98 * The records with the overlaps they are a side of (overlap-check D5), each named by its intents, or by the
99 * base branch and its last author there, and a "colliding" warning naming what it overlaps.
100 * @param {readonly BoardRecord[]} records @param {readonly Overlap[]} overlaps @param {string} base
101 * @returns {BoardRecord[]}
102 */
103export const withCollisions = (records, overlaps, base) => {
104  const byKey = new Map(records.map(one => [one.key, one]))
105  /** @param {string} key @returns {Party | null} */
106  const party = key => {
107    const one = byKey.get(key)
108    return one ? { key, slug: one.slug, owner: one.owner, stage: one.stage, branch: one.branch } : null
109  }
110  const collisions = collisionsFor(overlaps, party, base)
111  return records.map(record => {
112    const its = collisions.filter(one => one.a.key === record.key || one.b.key === record.key)
113    if (its.length === 0) return record
114    const others = its.map(one => (one.a.key === record.key ? one.b.slug : one.a.slug))
115    return { ...record, collisions: its, flags: [...record.flags, { kind: /** @type {const} */ ('colliding'), label: `overlaps ${others.join(', ')}` }] }
116  })
117}
118
hooks/pane.mjs 314 lines
1// @ts-check
2// Ather Board: the pane's look. It draws the sections views.mjs says a view shows, with the elements
3// it is handed (`el`) and Ather's own look: a label in spaced-out capitals (lime for what needs someone),
4// each group under it a bold title with its rollup, and Ather's row anatomy (rows.mjs workLine: glyph,
5// title, warning, bar, count, age, owner). For you leads (focus.mjs), the suggestions above it; the ask
6// box sits over every view; a row opens in place with what can be done about it (act.mjs).
7// Pure: no `$`; every press arrives as a closure from index.mjs.
8
9import { AMBER, LIME, QUIET, fit, label, section, statusLine, workLine } from './ather/rows.mjs'
10import { BAR_CELLS, ageText, miniBar, rowColumns } from './ather/worklist.mjs'
11import { ACTION_LABELS, actionsFor } from './act.mjs'
12import { collisionActions } from './ather/collide.mjs'
13import { isMine } from './ather/model.mjs'
14import { paneView } from './focus.mjs'
15import { GROUPS, PANE_VIEWS, SORTS, STAGES, VIEW_LABELS, choices, collisionFact, collisionOwners, moreText, overlapCount, sideLine, spotLabel, summaryText } from './views.mjs'
16
17/**
18 * @typedef {import('./views.mjs').BoardRecord} BoardRecord
19 * @typedef {import('./views.mjs').Filter} Filter
20 * @typedef {import('./views.mjs').Look} Look
21 * @typedef {import('./views.mjs').Section} Section
22 * @typedef {import('./views.mjs').IntentGroup} IntentGroup
23 * @typedef {import('./views.mjs').PairGroup} PairGroup
24 * @typedef {import('./views.mjs').Collision} Collision
25 * @typedef {ReturnType<typeof rowColumns>} Columns
26 * @typedef {import('./views.mjs').View} View
27 * @typedef {{
28 *   onView: (view: View) => () => void, onFilter: (patch: Partial<Filter>) => void, onSort: () => void, onGroup: () => void, onBy: () => void,
29 *   onPick: (by: 'owner' | 'area', value: string, count: import('./views.mjs').CountKind) => void, onRow: (record: BoardRecord) => () => void, onOpenPage: () => void, onPublish: () => void, onSync: () => void,
30 *   onAction: (kind: import('./act.mjs').ActionKind, records: readonly BoardRecord[]) => void, onDecide: (record: BoardRecord, call: import('./views.mjs').Call, letter: string) => void,
31 *   onSuggestion: (suggestion: Suggestion) => void, onBriefAgain: () => void, onMapAgain: () => void, onAsk: (question: string) => void, onClearAsk: () => void,
32 *   onPair: (collision: Collision) => () => void, onCollision: (action: { label: string, prompt: string }) => void,
33 * }} Actions
34 * @typedef {import('./focus.mjs').Suggestion} Suggestion
35 * @typedef {{
36 *   records: BoardRecord[], look: Look, width: number, isDesktop: boolean, now: number, title: string, fresh: string, error: string, note: string,
37 *   me: string, base: string, overlapNote: string, opened: string, suggestions: Suggestion[], modules: import('./modules.mjs').Module[],
38 *   brief: import('./assist.mjs').Job<import('./brief.mjs').Brief | null>, asked: import('./assist.mjs').Job<import('./brief.mjs').Answer | null>,
39 *   mapped: import('./assist.mjs').Job<import('./assist.mjs').Mapped>,
40 * }} PaneModel `opened`: the key of the intent or collision opened in place ('' none); `base`: the branch the team merges into;
41 *   `overlapNote`: why the overlap check could not run ('' when it did);
42 *   `suggestions`: the brief's and the board's own, merged;
43 *   `brief`, `asked`, `mapped`: the model's jobs (assist.mjs)
44 */
45
46// A list longer than this ends in a line pointing at the page, which shows them all.
47export const ROW_CAP = 60
48
49/** @param {string} stage */
50const glyphOf = stage => STAGES.find(one => one.key === stage)?.glyph ?? '·'
51
52// A heading and its meta beside it, quiet: a label spaced out, or a group's title in bold (D7 of Ather's look).
53/** @param {any} el @param {string} key @param {any} head @param {string} meta */
54const withMeta = (el, key, head, meta) => el.Box({ key, flexDirection: 'row', gap: 2, children: [head, ...(meta ? [el.Text({ key: `${key}-meta`, color: QUIET, wrap: 'truncate', children: meta })] : [])] })
55
56// A row's cells as Ather's list has them; in a group of one owner, that column shows the area.
57/** @param {PaneModel} model @param {IntentGroup} part @param {import('./views.mjs').Row} one @returns {import('./ather/worklist.mjs').RowCells} */
58const cellsOf = (model, part, { record, flags }) => ({
59  glyph: glyphOf(record.stage),
60  title: record.slug,
61  warn: flags.map(flag => flag.label).join(' · '),
62  repo: '',
63  bar: miniBar(record.done, record.total),
64  count: record.total ? `${record.done}/${record.total}` : '',
65  age: ageText(record.updatedAt, model.now),
66  owner: part.hide === 'owner' ? record.area : record.owner,
67})
68
69// A collision as a row (overlap-check D5): the intent's glyph and the pair, the places in amber, the first file
70// quiet beside them (left out in a narrow pane, where the pair's names need the room; opened, the row lists every
71// file), then the base's last change and the owners, in the columns every row has.
72/** @param {PaneModel} model @param {Collision} collision @returns {import('./ather/worklist.mjs').RowCells} */
73const pairCells = (model, collision) => ({
74  glyph: glyphOf(collision.b.stage),
75  title: `${collision.b.slug} ⇄ ${collision.a.key === '' ? collision.a.slug : `${glyphOf(collision.a.stage)} ${collision.a.slug}`}`,
76  warn: overlapCount(collision.count),
77  repo: model.width < 90 ? '' : `${(collision.files[0] ?? '').split('/').pop()}${collision.files.length > 1 ? ` +${collision.files.length - 1}` : ''}`,
78  bar: '',
79  count: '',
80  age: collision.base?.at ? ageText(collision.base.at, model.now) : '',
81  owner: collisionOwners(collision),
82})
83
84// A collision opened in place: what happened, each place with both sides' first changed line, and what can be done.
85/** @param {any} el @param {PaneModel} model @param {Actions} actions @param {Collision} collision @param {string} at */
86const pairOpened = (el, model, actions, collision, at) => {
87  const { a, b } = collision
88  const key = `${at}-${collision.key}-open`
89  const [next, ...rest] = collisionActions(collision, model.me, model.base)
90  const width = Math.max(a.slug.length, b.slug.length)
91  return el.Box({
92    key,
93    flexDirection: 'column',
94    width: '100%',
95    paddingLeft: 2,
96    marginBottom: 1,
97    children: [
98      el.Text({ key: `${key}-fact`, color: QUIET, wrap: 'wrap', children: collisionFact(collision, model.now) }),
99      ...collision.spots.flatMap((spot, index) => [
100        el.Text({ key: `${key}-spot-${index}`, bold: true, wrap: 'truncate', children: spotLabel(collision, spot) }),
101        ...(spot.kind === 'lines' ? [[a.slug, spot.ours], [b.slug, spot.theirs]].map(([who = '', line = ''], side) => el.Text({ key: `${key}-spot-${index}-${side}`, color: side === 0 ? QUIET : undefined, wrap: 'truncate', children: fit(`  ${who.padEnd(width)}  ${sideLine(line)}`, model.width - 2) })) : []),
102      ]),
103      ...(moreText(collision) ? [el.Text({ key: `${key}-more`, color: QUIET, children: moreText(collision) })] : []),
104      el.Box({ key: `${key}-acts`, flexDirection: 'row', flexWrap: 'wrap', gap: 2, marginTop: 1, children: [
105        ...(next ? [el.Button({ key: `collide-${collision.key}-${next.key}`, label: next.label, variant: 'primary', onPress: () => actions.onCollision(next) })] : []),
106        ...rest.map(one => el.Button({ key: `collide-${collision.key}-${one.key}`, label: one.label, plain: true, dimColor: true, onPress: () => actions.onCollision(one) })),
107      ] }),
108    ],
109  })
110}
111
112// The collisions as lines: the head, then a row a pair, opened in place on a press; the note when none could be checked.
113/** @param {any} el @param {PaneModel} model @param {Actions} actions @param {PairGroup} part @param {Columns} cols */
114const pairLines = (el, model, actions, part, cols) => [
115  withMeta(el, `${part.key}-head`, el.Text({ key: `${part.key}-title`, bold: true, children: part.title }), part.meta),
116  ...part.pairs.flatMap(collision => [
117    workLine(el, { key: `${part.key}-${collision.key}`, cells: pairCells(model, collision), cols, width: model.width, ownerColour: QUIET, onPress: actions.onPair(collision), isClicked: model.isDesktop }),
118    ...(model.opened === collision.key ? [pairOpened(el, model, actions, collision, part.key)] : []),
119  ]),
120  ...(part.pairs.length === 0 && part.empty ? [el.Text({ key: `${part.key}-empty`, color: QUIET, wrap: 'wrap', children: part.empty })] : []),
121]
122
123// A group of intents as lines: its head, then one anatomy, the right-hand columns (`cols`) lined up across
124// every group the view shows; Open items lists each intent's items under its row.
125/** @param {any} el @param {PaneModel} model @param {Actions} actions @param {IntentGroup} part @param {Columns} cols */
126const groupLines = (el, model, actions, part, cols) => {
127  const shown = part.rows.slice(0, ROW_CAP)
128  const more = part.rows.length - shown.length
129  return [
130    ...(part.title ? [withMeta(el, `${part.key}-head`, el.Text({ key: `${part.key}-title`, bold: true, children: fit(part.title, Math.max(8, model.width - part.meta.length - 2)) }), part.meta)] : []),
131    ...shown.flatMap(one => [
132      workLine(el, { key: `${part.key}-${one.record.key}`, cells: cellsOf(model, part, one), cols, width: model.width, ownerColour: QUIET, onPress: actions.onRow(one.record), isClicked: model.isDesktop }),
133      ...(model.opened === one.record.key ? [opened(el, model, actions, one.record, part.key)] : []),
134      ...one.items.map(item => el.Text({ key: `${part.key}-${one.record.key}-${item.id}`, color: QUIET, wrap: 'truncate', children: fit(`   ${item.id} ${item.text}`, model.width) })),
135    ]),
136    ...(more > 0 ? [el.Text({ key: `${part.key}-more`, color: QUIET, children: `+${more} more: o opens the page with every one` })] : []),
137    ...(part.rows.length === 0 && part.empty ? [el.Text({ key: `${part.key}-empty`, color: QUIET, children: part.empty })] : []),
138  ]
139}
140
141// An intent opened in place: its goal, its decisions with their options (the owner's own to answer), and
142// what can be done about it, its next action first. Every press hands the session one prompt (act.mjs).
143/** @param {any} el @param {PaneModel} model @param {Actions} actions @param {BoardRecord} record @param {string} at */
144const opened = (el, model, actions, record, at) => {
145  const isOwn = isMine(record, model.me)
146  const key = `${at}-${record.key}-open`
147  const [next, ...rest] = actionsFor(record, isOwn)
148  return el.Box({
149    key,
150    flexDirection: 'column',
151    width: '100%',
152    paddingLeft: 2,
153    marginBottom: 1,
154    children: [
155      ...(record.goal ? [el.Text({ key: `${key}-goal`, color: QUIET, wrap: 'wrap', children: record.goal })] : []),
156      ...(isOwn
157        ? record.calls.map(call =>
158            el.Box({ key: `${key}-${call.id}`, flexDirection: 'column', marginTop: 1, children: [
159              el.Text({ key: `${key}-${call.id}-title`, color: AMBER, wrap: 'wrap', children: `${call.id} ${call.title}` }),
160              el.Box({ key: `${key}-${call.id}-options`, flexDirection: 'row', flexWrap: 'wrap', gap: 2, children: [
161                ...call.options.map(option => el.Button({ key: `decide-${record.key}-${call.id}-${option.letter}`, label: `${option.letter}: ${option.label}${option.isRecommended ? ' (recommended)' : ''}`, plain: true, onPress: () => actions.onDecide(record, call, option.letter) })),
162                el.Button({ key: `decide-${record.key}-${call.id}-explain`, label: 'Explain', plain: true, dimColor: true, onPress: () => actions.onDecide(record, call, '') }),
163              ] }),
164            ] }),
165          )
166        : []),
167      el.Box({ key: `${key}-acts`, flexDirection: 'row', flexWrap: 'wrap', gap: 2, marginTop: 1, children: [
168        ...(next ? [el.Button({ key: `act-${record.key}-${next}`, label: ACTION_LABELS[next], variant: 'primary', onPress: () => actions.onAction(next, [record]) })] : []),
169        ...rest.map(kind => el.Button({ key: `act-${record.key}-${kind}`, label: ACTION_LABELS[kind], plain: true, dimColor: true, onPress: () => actions.onAction(kind, [record]) })),
170      ] }),
171    ],
172  })
173}
174
175// The ask box, over every view: a question to the model, and its answer while the board shows its cut.
176/** @param {any} el @param {PaneModel} model @param {Actions} actions */
177const askBox = (el, model, actions) => {
178  const { asked } = model
179  const said = asked.state === 'running' ? 'Reading the board…' : asked.state === 'ready' ? (asked.value?.answer ?? '') : asked.state === 'failed' ? `No answer: ${asked.error}` : ''
180  return el.Box({ key: 'ask-box', flexDirection: 'column', width: '100%', marginTop: 1, children: [
181    el.Input({ key: 'ask', label: 'Ask', placeholder: 'what is blocking combat? whose decisions are oldest?', value: asked.key, submitLabel: 'ask Sonnet', onSubmit: (/** @type {string} */ question) => actions.onAsk(question) }),
182    ...(said ? [el.Box({ key: 'ask-said', flexDirection: 'row', gap: 2, children: [
183      el.Box({ key: 'ask-said-words', flexGrow: 1, flexShrink: 1, children: [el.Text({ key: 'ask-said-text', color: asked.state === 'ready' ? undefined : QUIET, wrap: 'wrap', children: said })] }),
184      ...(asked.state === 'running' ? [] : [el.Button({ key: 'ask-clear', label: 'Clear', hotkey: 'x', plain: true, dimColor: true, onPress: actions.onClearAsk })]),
185    ] })] : []),
186  ] })
187}
188
189// The brief and the board's own suggestions, each a press that acts or cuts the board.
190/** @param {any} el @param {PaneModel} model @param {Actions} actions */
191const briefSection = (el, model, actions) => {
192  const { brief } = model
193  const status = brief.state === 'running' ? 'Sonnet is reading the board…' : brief.state === 'failed' ? `No brief: ${brief.error}` : brief.state === 'ready' ? `Sonnet, ${ageText(brief.at, model.now) || 'just now'}` : ''
194  const headline = brief.value?.headline ?? ''
195  return section(el, 'brief', [
196    el.Box({ key: 'brief-head', flexDirection: 'row', gap: 2, children: [
197      label(el, 'brief-label', 'Suggested', Math.max(9, model.width - status.length - 8)),
198      el.Button({ key: 'brief-again', label: '↻', hotkey: 'r', plain: true, dimColor: true, onPress: actions.onBriefAgain }),
199      ...(status ? [el.Text({ key: 'brief-status', color: QUIET, wrap: 'truncate', children: status })] : []),
200    ] }),
201    ...(headline ? [el.Text({ key: 'brief-headline', wrap: 'wrap', children: headline })] : []),
202    ...model.suggestions.map(one =>
203      el.Box({ key: `suggest-${one.key}`, flexDirection: 'column', children: [
204        el.Button({ key: `suggest-${one.key}-press`, label: `› ${one.title}`, plain: true, onPress: () => actions.onSuggestion(one) }),
205        ...(one.why ? [el.Text({ key: `suggest-${one.key}-why`, color: QUIET, wrap: 'wrap', children: `  ${one.why}` })] : []),
206      ] }),
207    ),
208    ...(model.suggestions.length === 0 && brief.state !== 'running' ? [el.Text({ key: 'brief-none', color: QUIET, children: 'Nothing to suggest right now.' })] : []),
209  ])
210}
211
212// A top-level label over its groups, with no blank line between them.
213/** @param {any} el @param {PaneModel} model @param {Actions} actions @param {Extract<Section, { kind: 'label' }>} part @param {Columns} cols */
214const labelSection = (el, model, actions, part, cols) =>
215  section(el, part.key, [
216    withMeta(el, `${part.key}-head`, label(el, `${part.key}-label`, part.title, model.width - part.meta.length - 2, part.isLoud ? LIME : undefined), part.meta),
217    ...part.groups.map(group => el.Box({ key: group.key, flexDirection: 'column', width: '100%', children: group.kind === 'pairs' ? pairLines(el, model, actions, group, cols) : groupLines(el, model, actions, group, cols) })),
218  ])
219
220// People or Areas: a line each. The name opens the table of its intents; each count opens what it counts
221// (board-counts D1), those that need someone at full strength, the rest dim.
222/** @param {any} el @param {Actions} actions @param {Extract<Section, { kind: 'lines' }>} part */
223const lineSection = (el, actions, part) => {
224  const width = Math.min(28, Math.max(4, ...part.lines.map(line => line.title.length)))
225  return section(el, part.key, part.lines.map(line =>
226    el.Box({
227      key: `${part.key}-${line.key}`,
228      flexDirection: 'row',
229      gap: 2,
230      children: [
231        el.Box({ key: `${part.key}-${line.key}-name`, width, flexShrink: 0, children: [el.Button({ key: `${part.key}-${line.key}-press`, label: fit(line.title, width), plain: true, onPress: () => actions.onPick(part.by, line.key, 'open') })] }),
232        ...line.counts.map(count => el.Button({ key: `${part.key}-${line.key}-${count.kind}`, label: count.text, plain: true, dimColor: !count.isWarn, onPress: () => actions.onPick(part.by, line.key, count.kind) })),
233        el.Text({ key: `${part.key}-${line.key}-age`, color: QUIET, wrap: 'truncate', children: line.age }),
234      ],
235    }),
236  ))
237}
238
239// The search field, the pickers, and the toggles of the view in hand.
240/** @param {any} el @param {PaneModel} model @param {Actions} actions */
241const filters = (el, model, actions) => {
242  const { filter, view } = model.look
243  const all = choices(model.records)
244  /** @param {string} key @param {string} text @param {readonly string[]} values @param {string} current @param {(value: string) => void} onSelect @param {(value: string) => string} [name] */
245  const pick = (key, text, values, current, onSelect, name = value => value) =>
246    el.Select({ key, label: text, value: current, options: [{ key: `${key}-any`, value: '', label: 'any' }, ...values.map(value => ({ key: `${key}-${value}`, value, label: name(value) }))], onSelect })
247  const toggles = [
248    ...(view === 'table' ? [el.Button({ key: 'sort', label: `Sort: ${SORTS[model.look.sort]}`, hotkey: 's', plain: true, onPress: actions.onSort }), el.Button({ key: 'group', label: `Group: ${GROUPS[model.look.group]}`, hotkey: 'g', plain: true, onPress: actions.onGroup })] : []),
249    ...(view === 'items' ? [el.Button({ key: 'by', label: `By ${model.look.by}`, hotkey: 'g', plain: true, onPress: actions.onBy })] : []),
250    ...(view === 'table' ? [el.Button({ key: 'done', label: filter.showDone ? 'Done shown' : 'Done hidden', hotkey: 'd', plain: true, dimColor: !filter.showDone, onPress: () => actions.onFilter({ showDone: !filter.showDone }) })] : []),
251  ]
252  return el.Box({
253    key: 'filters',
254    flexDirection: 'column',
255    width: '100%',
256    marginTop: 1,
257    children: [
258      el.Input({ key: 'words', label: 'Search', placeholder: 'words from a name, title, area or owner', value: filter.words, onInput: (/** @type {string} */ words) => actions.onFilter({ words }), onSubmit: (/** @type {string} */ words) => actions.onFilter({ words }) }),
259      el.Box({
260        key: 'pickers',
261        flexDirection: 'row',
262        flexWrap: 'wrap',
263        gap: 2,
264        children: [
265          pick('area', 'Area', all.areas, filter.area, area => actions.onFilter({ area })),
266          pick('owner', 'Owner', all.owners, filter.owner, owner => actions.onFilter({ owner })),
267          pick('stage', 'Stage', STAGES.map(stage => stage.key), filter.stage, stage => actions.onFilter({ stage }), key => STAGES.find(stage => stage.key === key)?.label ?? key),
268          ...toggles,
269        ],
270      }),
271    ],
272  })
273}
274
275/** @param {any} el @param {PaneModel} model @param {Actions} actions */
276export const boardPane = (el, model, actions) => {
277  const { look } = model
278  const { shown: records, parts, extras } = paneView(model.records, look, { me: model.me, modules: model.modules, mapping: model.mapped.value.mapping, now: model.now, note: model.overlapNote })
279  const { mapped } = model
280  const mapStatus = mapped.state === 'running' ? `Sonnet is mapping ${mapped.value.missing} intents onto the modules\u2026` : mapped.state === 'failed' ? `Mapping stopped: ${mapped.error}` : ''
281  const groups = parts.flatMap(part => (part.kind === 'label' ? part.groups : part.kind === 'intents' ? [part] : []))
282  const cols = rowColumns(groups.flatMap(group => (group.kind === 'pairs' ? group.pairs.map(one => pairCells(model, one)) : group.rows.slice(0, ROW_CAP).map(one => cellsOf(model, group, one)))), model.width < 90 ? 12 : 22)
283  return el.Box({
284    flexDirection: 'column',
285    width: '100%',
286    children: [
287      label(el, 'title', model.title, model.width),
288      statusLine(el, { text: summaryText(model.records, model.now), fresh: model.fresh, width: model.width, hotkey: 'f', onPress: actions.onSync, error: model.error }),
289      el.Box({
290        key: 'tabs',
291        flexDirection: 'row',
292        flexWrap: 'wrap',
293        gap: 2,
294        marginTop: 1,
295        children: [
296          ...PANE_VIEWS.map((view, index) => el.Button({ key: `tab-${view}`, label: VIEW_LABELS[view], hotkey: String(index + 1), plain: true, dimColor: view !== look.view, onPress: actions.onView(view) })),
297          // The views, then apart from them what acts beyond the pane.
298          el.Text({ key: 'tabs-apart', color: QUIET, children: '│' }),
299          el.Button({ key: 'open-page', label: 'Open the page', hotkey: 'o', plain: true, dimColor: true, onPress: actions.onOpenPage }),
300          el.Button({ key: 'publish', label: 'Publish', hotkey: 'p', plain: true, dimColor: true, onPress: actions.onPublish }),
301        ],
302      }),
303      askBox(el, model, actions),
304      ...(extras.filters ? [filters(el, model, actions)] : []),
305      ...(model.note ? [el.Text({ key: 'note', color: QUIET, wrap: 'wrap', children: model.note })] : []),
306      ...(records.length !== model.records.length ? [el.Text({ key: 'shown', color: QUIET, children: `${records.length} of ${model.records.length} shown` })] : []),
307      ...(extras.brief ? [briefSection(el, model, actions)] : []),
308      ...(extras.mapping && mapStatus ? [el.Box({ key: 'map-status', flexDirection: 'row', gap: 2, marginTop: 1, children: [el.Text({ key: 'map-status-text', color: QUIET, wrap: 'wrap', children: mapStatus }), el.Button({ key: 'map-again', label: '\u21bb', plain: true, dimColor: true, onPress: actions.onMapAgain })] })] : []),
309      ...parts.map(part => (part.kind === 'label' ? labelSection(el, model, actions, part, cols) : part.kind === 'lines' ? lineSection(el, actions, part) : section(el, part.key, groupLines(el, model, actions, part, cols)))),
310      el.Text({ key: 'legend', color: QUIET, wrap: 'wrap', children: `${STAGES.map(stage => `${stage.glyph} ${stage.label}`).join('  ')}  ·  bar: ${'▰'.repeat(BAR_CELLS)} items met` }),
311    ],
312  })
313}
314