Ather Automata: what needs you and what is next in every S2 session and web app repository (Plan, Build, Prove, Ship), a newcomer tour, autonomy windows, and…

Working the S2 way with Claude Code: what needs you, what to do next, and a safe pair of hands while you are away.
/ather whenever you wonder what to do. What needs you comes first, then the next step for your work, ready to send./ather tour walks you through it in six short steps and ends with your first piece of work started. In a hurry, skip it; Ather just asks your role./away tonight (or 8h, until 9am, until done). The session keeps working; merges wait for you. When you are back, /ather → I'm back: see what happened.v on Home (or Simple view at its foot) for just what needs you and what is next. /ather advanced brings everything back; Ather remembers your choice.main touches the lines your branch changes, Needs you says so before the merge does: Bring origin/main into feat/x, with who changed them and where (▲ above the prompt too). A press hands the session the merge to do in your worktree, resolved and shown to you before anything is committed or pushed./warm on keeps the session's prompt cache warm while you are idle, so your next turn reads the context instead of paying to write it again. Off unless you turn it on.| Where | What |
|---|---|
| Terminal | /ather opens one pane: where your work is (Plan ✓ ─ Build ● ─ Prove ○ ─ Ship ○) and the proof so far, what needs you, then Next, then other work you could pick up. Enter hands a row to the session; a decision opens in place with its options as buttons, so you answer it where it is shown. |
| Desktop app | /ather opens the same pane in the side panel; click a row to hand it to the session. |
| Above the prompt | One line: what needs you, a running window, or the tracked intent's stage (● Build 1/2 · feat-x); then ☾ away, ◔ keep the prompt cache warm (on or off; ◔ 1/3 in amber while a read is due), ⤢ open the pane, ✕ hide it until something is new. |
| Status line | With /warm on and you idle: ◔ warm 1/3 · next 14:55, when the cache is read next and how many reads of the cap are done. |
| Pop-ups | A known trap with its fix, a build that really failed, a merge that dropped your edits, a worker gone quiet, a thin worker brief. |
On a machine that also runs week-calendar, the pane's line under the title adds this week's figures: PRs merged and productive agent time.
A press while the session is mid-turn waits. Claude Code starts a pane prompt's turn only once the running turn has ended, however long that takes. The pane says so: "Queued until this turn ends", the row reads ⏳ queued, and a pop-up says "Sent" with how long it waited once the session has it. Pressing it again while it waits sends nothing more.
Each session works on one intent. A new session offers to continue the one you last worked on. With nothing tracked, Ather offers one list: your open intents, then the GitHub issues assigned to you that have no intent yet (high priority first), then teammates' intents you could follow (read-only: their decisions stay theirs).
Tracking. Looking at an intent never tracks it: a row, or words that name one, opens its view, and Work on this here there makes it this session's intent (so do Next's Continue and Pick up, and /ather intent <exact name>). Stop tracking in the view, or /ather untrack, undoes it; the proof recorded so far stays with the intent. A session also tracks the intent it runs: writing that intent's prompt.md or log.md from the main conversation (a new prompt.md switches to the new intent); a worker's writes never do. Several sessions may track one intent; its view then says so ("Also tracked in 1 other session · active 5m ago"). After /clear, or when a new session takes over an away window, Ather says which intent is still tracked.
The right session. A session that tracks nothing lists every decision of yours, and each says where it is answered: in "Kawaii toolset" (the live session that tracks its intent, by its title in the app), in this session, or no session tracks it; an intent's several decisions say it on their row (▸ tower-stair-pcg · 4 decisions · in "Tower stairs"). When another live session tracks the intent, a press of the decision (its answer, Explain, Type an answer, or Ask about it) goes to that session as a message from this one, never into this chat, and the row says Sent to "Kawaii toolset". The opened decision also offers Go to session ›, that session's own app link: in the desktop app a press hands it to the system's opener, which opens the session (if it cannot, the row says to open it from the sidebar); in the terminal it is a link. An intent no live session tracks gets a best guess, labelled as one: probably in "Login worker" with its Go to session link, the most recently active open session that the app's transcript search finds for the intent's folder name (at most once per intent in ten minutes) and that works on it: its title carries most of the folder name's words as whole words, or the snippet of its transcript shows the intent's branch (intent/<slug>), its folder, or its prompt.md, progress.md, log.md or findings.md. A session that comes first for three or more untracked intents at once reads them all and is nobody's guess; a press of such a decision still goes here, as it does with no guess (no session tracks it).
Clicking an issue opens its card: Start an intent, Open on GitHub or Copy link. Starting one asks the session to check for overlapping work first (the issue preflight), then draft an intent linked to it (- Issue: #28887) and show you the plan before anything is built. Ather reads your issues with gh and never writes to GitHub. /ather issues lists them; /ather issue 28887 or #28887 starts one.
gh api) and pushes to main, however they are spelled. Each command is judged on the branch of the folder it runs in, so pushing your feature worktree is never held.develop; see The base branch, below), read that branch for main here: PRs are opened to it, and a push to it and a local merge into it are held as well as those to main.a ticks all, n none, a press on a row toggles it. A length then opens a window in each ticked session, of the same length, each with its own ledger, holds and review, and sends it the mandate as Needs you sends (the app's message where both run in the desktop app, else the engine's send). A session it cannot reach is named and its window closed again; one already away by then is named and sent nothing. /away 8h all does the same for the sessions ticked by default. /away 8h in enemy, playtest: finish the pass (or /away 8h @enemy @playtest finish the pass) for this session and those whose title, branch or intent contains each name; add only (only in enemy) to leave this session out. Other words are this session's goal: /away 8h sync never touches the sync conductor (words that start with in or @ are read as names, and a name that matches no live session starts nothing). A session not ticked by default is named only by its whole title, branch or intent.Claude Code keeps a session's context in the API's prompt cache for an hour after it was last read (five minutes when the account is in usage overage). Reading it costs a tenth of the input price; once it lapses, your next turn writes the whole context to the cache again at twice the price, and is slower. On a 150k-token session at $5 per million input tokens, that is about $0.08 to read and $1.50 to write again.
With keep-warm on, Ather reads the cache once just before it would lapse, 55 minutes after your last turn, and again 55 minutes after that, up to a cap (three hours by default). The read is a fork of the session's own last request with no tools. It adds nothing to your conversation and asks for a one-character reply. Each read that hits starts the hour again. Coming back within the cap, your first turn reads the cache. Not coming back costs the reads: about $0.23 for three hours on that session, against $1.50 to rebuild.
w), turns it on or off for this session. /warm on does the same, /warm 2h (or /warm 10 hours, /warm 90 min) sets the cap, /warm off stops it. The cacheKeepWarm setting turns it on for every session (on), or suggests it once per session (ask); cacheKeepWarmHours sets the cap (1 to 12 hours)./away 8h (or 4h, until 9am, any window with an end) keeps the cache warm for the window and an hour past it, until you have reviewed the window, unless you said /warm off in that session. /away until done does not: the return is unknown, and a day of reads costs more than the rewrite.◔ warm 1/3 · next 14:55, and the pane says "Kept warm: 1 of 3 reads done, the next at 14:55."claude -p, the SDK), before your second turn (Claude Code never reads a session's first request from the cache again, so there is nothing to keep yet), while a turn runs, for a context under 30k tokens (cheap to rebuild), past the cap, while an away window runs that ends after the cap (or runs until done), when a rate-limit window is over 85% used, or once the cache has already lapsed (the machine slept): a read then would pay the full write for nothing./model or /compact), and for the session if a turn shows the five-minute TTL./warm says whether it is on, when the next read is, what the last read took from the cache ("101,944 of 101,738 tokens from the cache (kept)"), and what keep-warm has done on this machine: reads, returns to a warm or a cold cache, dollars spent and the rewrite avoided (estimated), reads missed and wasted.Ather reads evidence from tool output, never from what the session says: an S2Editor build's own Result line, a test run whose tests passed (no tests, a failure or a non-zero exit is a fail), a started PIE or test simulation run, and a read-back from the server that was written to. A tech artist's own Editor check is /ather checked. Proof is kept with the intent for a day, so yesterday's build still counts this morning; each record names the session that produced it, and the Intent view names any other session's. Until you say your role, any role's proof counts. That is S2; in any other repository proof comes from the gates in its profile and the tools the web pack knows (see In a repository that is not S2).
| Command | Does | ||||
|---|---|---|---|---|---|
/ather | What needs you and what is next | ||||
/ather tour, /ather skip | The tour, or skip it and just say your role | ||||
/ather pick [words], /ather intent <name> | Everything open; an exact intent name works on it here, other words show the intent they match | ||||
/ather untrack | Stop tracking this session's intent (not while an away window runs) | ||||
/ather simple, /ather advanced | Home in Simple view (what needs you and Next) or Advanced (everything); remembered for you | ||||
/ather issues, /ather issue <number> | Your GitHub issues; start one | ||||
/ather role <in your words> | Your role: designer, tech artist or engineer in S2; engineer, designer or product in a web repository | ||||
/ather checked | Record your own Editor check (S2 only) | ||||
| `/away [8h \ | 30m \ | until 9am \ | tonight \ | until done] [goal]` | Hand over while you are away |
/away <length> all[: goal] or /away <length> [only] in <name>[, <name>][: goal] (or @name) | Hand over in several live sessions of this checkout: every one ticked by default, or this one and those named (only: those named alone) | ||||
/away stop (or "I'm back") | End the window, and the others opened with it | ||||
| `/warm [on \ | off \ | <n>h]` | Keep the prompt cache warm while you are idle (see Keeping the cache warm); alone, what it is doing |
Anything else you type after /ather or under Other goes to the session as a question.
Claude Code 2.1.287 or later. The commands are the same on macOS and Windows, and the mod works in any repository, not only an S2 checkout:
claude plugin marketplace add AskTinNguyen/ather-mods
claude plugin install ather-automata@ather --scope user
Settings: briefGate (warn, enforce or off) for worker briefs that lack paths, acceptance checks or the shared-tree rule; cacheKeepWarm (off, ask or on) and cacheKeepWarmHours for keeping the prompt cache warm (below).
A web app, a Python service, anything with a package.json or a pyproject.toml, or neither:
docs/intent, and a .ather/profile.json that names its gates (the commands that count as proof). Ather does not add it for you; "A repository without intents", below, says what Ather reads and where the intent skill is./ather.What differs from S2:
/ather role..ather/profile.json say which commands count and what each proves; a test runner, a linter, a type check or a build the web pack knows on sight counts too, also when it is not a gate, so a pass of one test file can stand as test proof. When that is not enough for you, name the full command as a gate and ask for it. There is no Editor check: /ather checked belongs to S2.baseBranch in the profile when it is there, else the default branch that the clone knows (origin/HEAD, read from the clone's files with no git call), else main. A clone whose origin/HEAD is not set, or is kept in git's reftable format, reads as main until the profile names baseBranch. The team's intents are read from it, it is the branch fetched, and a push to it is held while you are away. Where this page says main or origin/main, read your base branch.How a gate's command is matched. A command proves a gate when it is the gate's command or starts with it: npm test -- --watch=false proves a gate written npm test. An environment prefix (CI=1 npm test) is dropped first.
python3, pnpm) is proved by that program wherever it runs from: .venv/bin/python scripts/validate.py and a Windows python.exe prove python3 scripts/validate.py. python, python3 and python3.12 are one program../scripts/check.sh) is compared as written.cd web && pnpm test is proved by those two commands run one after the other, joined with &&.pnpm --dir web test is not pnpm test: when that is how you run it, write a gate for it.On macOS. Use the Node version the repository's .nvmrc names; a newer default Node can fail a test runner that passes in CI. A gate written python3 … is proved by the virtualenv's python too.
The pane shows the repository the session is opened in: the checkout holding the session folder and that clone's worktrees (git is asked, nothing is searched; up to 24). There is nothing to set up, and a sibling checkout beside it is not listed. A session opened in a folder that is in no checkout, such as a folder holding several checkouts, has no pane: open the session in the checkout you want to see.
A checkout and its worktrees share one origin/main, so main's intents are listed once and main is fetched once; a worktree adds only the intents it has changed or made itself, under its folder's name (/ather intent <folder>/login names one exactly).
cd ../web && npm test, or git -C ../web …, is read with web's pack: its proof counts for web, and while you are away it is held by web's rules as well as the window's (a production deploy in web is held even from an S2 session).prompt.md or log.md tracks it there: its view, proof, PRs, away ledger and peers come from that checkout, and the session shows as live there too.Ather works where a repository has intents (a docs/intent folder). In a repository without them, /ather and /away say so and do nothing else. Ather does not add the structure: each team adds it to its own repository.
What Ather reads once it is there:
| Piece | Where |
|---|---|
| The intents | docs/intent/<feature>/: prompt.md, log.md, progress.md and, when there are any, findings.md |
| The profile (optional): pack, gates, merge policy, areas | .ather/profile.json, in the format under Web projects |
| Local state, kept out of git | .ather/local/: add that line to .gitignore |
/intent init drafts the project contract (docs/intent/README.md: areas, proofs, merge authority) and asks you to confirm it. That repository's README says how to install it./ather opens the pane in the same session. A new session reads the profile when it starts, so restart the sessions that were already open in that repository.The same mod runs in web app repositories (Node and TypeScript first), piloted on Thính (AskTinNguyen/han-viet). The pane, Plan → Build → Prove → Ship, Next, away windows, the decision ledger, issues and the worker squad are the same; what counts as proof, what is held and what Next asks for come from a pack for the kind of project:
.ather/profile.json ("pack": "web" or "unreal"), else markers (*.uproject → Unreal; package.json or pyproject.toml → web), else the core alone. Read once per session. S2 checkouts get the Unreal pack and see exactly what they saw before.tests/ather-profile.test.mjs checks it): {
"version": 1,
"pack": "web",
"gates": [
{ "id": "test", "command": "npm test", "proofs": ["tests", "build"], "passOn": "counts", "proves": "the full suite" },
{ "id": "lint", "command": "npm run lint", "proofs": ["lint"], "passOn": "exit" },
{ "id": "build-next", "command": "npm run build:next", "proofs": ["build", "typecheck"], "passOn": "exit" },
{ "id": "ui", "command": "npm run ui:verify", "proofs": ["ui"], "passOn": "counts" }
],
"production": { "host": "vercel", "branch": "main", "deployment": "how the deployment is checked", "probe": { "url": "https://…", "expectStatus": 200 } },
"mergePolicy": "with-proof",
"devPorts": { "base": 3100, "perWorktree": 10, "env": "UI_VERIFY_PORT" }
}
Optional: "required" (the rungs a merge needs; default every declared proof but production), "areas" and "baseBranch" (the branch that pull requests go into, when it is not main). Without a profile, the test, lint, typecheck and build scripts stand in for gates, and they are named with the repository's package manager (packageManager in package.json, else the lockfile, else npm).
tests, lint (lint and typecheck), build, ui, prod. A run is a gate's command, an npm run script, or the tool itself (node --test, vitest, jest, Playwright, tsc, ESLint, next build, vinext and Vite builds). A failure count or a non-zero exit fails it. lint and build pass on exit 0. tests and ui pass on the runner's own pass counts, which the pack reads for node:test, vitest, jest and Playwright; a piped run is judged on its counts alone. Counts behind a workspace runner's line prefix (pnpm -r, turbo) are read too. A gate can say how it passes tests and ui, with passOn. With "passOn": "counts" only pass counts pass it. With "passOn": "exit" exit 0 also passes it when the output has no counts the pack reads; a failure the pack does read still fails it. Choose counts when the gate's output has the pass counts of node:test, vitest, jest or Playwright. Choose exit for anything else, in any language: go test, cargo test, pytest, a script that prints no counts. A gate without passOn reads as exit, so a profile written before the field works as it did. The exit code counts only when it is the gate's own: run such a gate by itself or after &&, not through a pipe, ; or ||. A command that is no gate (also a script that runs gates inside), and every command where there is no profile, is read on counts only for tests and ui. A call that was refused did not run, and nothing is read from it. Each gate keeps its own result: a rung that several gates declare passes only when every one of them has passed, and fails when one failed. In the profile above lint needs both npm run lint and npm run build:next, and Prove names both. On such a rung a command that runs none of its gates (a tool run directly, a script with no gate in it) cannot pass it; a failure it reads fails the rung until one of the rung's gates is run again, or a later such command reads no failure. Gates that one commahooks/ather.mjs 15 lines1// @ts-check
2// Ather Automata: one hooks module per plugin, made of two halves. watch.mjs
3// protects work silently; console.mjs shows what needs you. Each catches its own
4// failures, so one half failing never stops the other. They share state only
5// through state.mjs, its owner, which serializes every change.
6
7import { register as registerWatch } from './watch.mjs'
8import { register as registerConsole } from './console.mjs'
9
10/** @param {import('claude-code').On} on @param {import('claude-code').PluginOptions} options */
11export function register(on, options) {
12 registerWatch(on, options)
13 registerConsole(on)
14}
15hooks/watch.mjs 827 lines1// @ts-check
2// Ather Automata, the silent half: guards that protect work, the autonomy
3// window's holds and decision ledger, evidence read from tool output, and the
4// tools the model calls. Its only interface is toasts. Every hook passes the
5// call on and keeps its own failures to itself, except a held action, which it
6// refuses on purpose. Shared state changes only through state.mjs.
7//
8// The host reads on(...) and $.noun.method(...) from source, so they are
9// spelled literally, and helpers that take $ are top-level functions.
10
11import { awayReason, clampHours, isHolding, mandateText, offAway, windowEndText } from './away.mjs'
12import { briefIssues, explainGuard, forBase, gitFolders, heldKindsOf, heldLabel, heldNoun, heldShellAt, isMergeCommand, isSearchCommand, matchGotchas, mcpServer } from './guards.mjs'
13import { STAGE_LABELS, andList, currentStage, directorCalls, isPersonOrigin, localMinutes, parseIntent, parseTzOffset, prStatusList } from './model.mjs'
14import * as state from './state.mjs'
15import { recordHeard, recordSpawn, recordTool, resetWorkers, workerOf } from './workers.mjs'
16import { askingIn, during, isInFlight, isSilent, linkChild, markAsking, resetCalls } from './inflight.mjs'
17import { intentChanges, intentFileOf, orchestrationFileOf } from './changes.mjs'
18import { trackedByLine, untrackText } from './home.mjs'
19import { GIT_ENV } from './team.mjs'
20import { appSessionOf, appTool } from './handoff.mjs'
21import { withFolders } from './shell.mjs'
22import { checkoutOf, gitDirOf, normalFolder } from './workspace.mjs'
23import { IDLE_ENV, PING_PROMPT, initialWarm, stepWarm } from './warm.mjs'
24import * as warmStore from './warm-store.mjs'
25
26/** @typedef {import('claude-code').EngineInterface} Engine */
27
28const IDLE_MS = 10 * 60 * 1000
29// How often this session asks the desktop app for its own id and title (a title may change at any time).
30const APP_EVERY_MS = 5 * 60 * 1000
31
32let cwd = ''
33let briefGate = 'warn'
34// Traps already counted in this session: each counts once per session.
35const seenTraps = new Set()
36// Workers already warned about (quiet, or waiting on permission): each is warned once.
37const idleWarned = new Set()
38// When the person last typed a prompt: after an away window has ended, it means they are back.
39let lastPersonAt = 0
40// When this session started: a with-proof merge counts only proof seen since (D2: "passed in tool output this session").
41// A hot reload starts it again, which only makes the rule stricter.
42let sessionStartedAt = Date.now()
43
44// Keeping the prompt cache warm: its state (warm.mjs's stepWarm moves it on) and the timer it armed.
45let warm = initialWarm('off', 3)
46/** @type {import('claude-code').Timer | null} */
47let warmTimer = null
48
49// The store, files and session as closures: `$` cannot be handed to state.mjs itself.
50/** @param {Engine} $ @returns {import('./state.mjs').Io} */
51function io($) {
52 return {
53 get: key => $.store.get(key),
54 set: (key, value) => $.store.set(key, value),
55 remove: key => $.store.delete(key),
56 keys: () => $.store.keys(),
57 read: path => $.fs.read(path).then(text => (typeof text === 'string' ? text : null), () => null),
58 write: (path, text) => $.fs.write(path, text),
59 exists: path => $.fs.exists(path).catch(() => false),
60 sessionId: () => $.session.id(),
61 root: () => $.session.root(),
62 gitUser: async root => ((await $.process.run(['git', 'config', 'user.name'], { cwd: root || cwd || (await $.session.root()), timeoutMs: 10000 })).stdout ?? '').trim(),
63 gitEmail: async root => ((await $.process.run(['git', 'config', 'user.email'], { cwd: root || cwd || (await $.session.root()), timeoutMs: 10000 })).stdout ?? '').trim(),
64 redraw: () => $.ui.invalidate('ui.render'),
65 list: path => $.fs.list(path),
66 origin: root => readOrigin($, root),
67 repo: async () => (await laneOf($)).repo,
68 real: async folder => (await $.fs.stat(folder, { resolve: true })).realPath ?? folder,
69 worktrees: root => readWorktrees($, root),
70 }
71}
72
73// The origin URL of the checkout at `root` ('' without one), or null when git could not say: the lane asks again.
74/** @param {Engine} $ @param {string} root @returns {Promise<string | null>} */
75async function readOrigin($, root) {
76 const run = await $.process.run(['git', 'config', '--get', 'remote.origin.url'], { cwd: root, env: GIT_ENV, timeoutMs: 10000 }).catch(() => undefined)
77 // Exit 1: no such key.
78 return run?.exitCode === 0 ? (run.stdout ?? '').trim() : run?.exitCode === 1 ? '' : null
79}
80
81// What `git worktree list --porcelain` prints in the checkout at `root` ('' when git refused), or null when git
82// could not say (the app aborted the run, it ran out of time): the workspace asks again.
83/** @param {Engine} $ @param {string} root @returns {Promise<string | null>} */
84async function readWorktrees($, root) {
85 const run = await $.process.run(['git', 'worktree', 'list', '--porcelain'], { cwd: root, env: GIT_ENV, timeoutMs: 10000 }).catch(() => undefined)
86 return run === undefined ? null : run.exitCode === 0 ? (run.stdout ?? '') : ''
87}
88
89/** @param {Engine} $ */
90function laneOf($) {
91 return state.lane(io($), cwd)
92}
93
94/** @param {import('claude-code').On} on @param {import('claude-code').PluginOptions} options */
95export function register(on, options) {
96 briefGate = String(options?.briefGate ?? 'warn')
97 warm = initialWarm(options?.cacheKeepWarm, options?.cacheKeepWarmHours)
98
99 on('session.start', async ($, e, next) => {
100 const result = await next(e)
101 await startWarm($, e.isInteractive || e.surface !== null).catch(error => $.ui.log(`Ather warm: start failed: ${String(error)}`, { to: 'debug' }))
102 seenTraps.clear()
103 idleWarned.clear()
104 resetWorkers()
105 resetCalls()
106 lastPersonAt = 0
107 sessionStartedAt = Date.now()
108 state.markActive()
109 // The app is asked again at the next heartbeat: this session may run in another client than the last.
110 appAskedAt = 0
111 state.setAppSession(null)
112 cwd = e.cwd
113 try {
114 const { me, root, isS2, pack } = await laneOf($)
115 await registerTools($, pack)
116 // A repository set up in this session has a new pack: the tools are registered again under the
117 // same names, which replaces them, so they carry its areas, roles and held kinds.
118 state.onSetUp('watch', setUp => registerTools($, setUp))
119 // From the session's root, not the shell's folder: a `cd` before a resume must not move the workspace.
120 void state.workspace(io($), root || cwd, line => $.ui.log(line, { to: 'debug' })).catch(() => undefined)
121 await state.migrateRole(io($), me)
122 const adopted = isS2 && e.isInteractive ? await state.adoptWindow(io($), { me, root, isAlive: sid => isLaneAlive($, sid) }).catch(() => null) : null
123 if (isS2) void state.prune(io($), sid => isLaneGone($, sid)).catch(() => undefined)
124 if (adopted) $.ui.toast(adopted.isOver ? 'Ather: welcome back. Your away window has ended; merges stay held until you review it. Type /ather.' : 'Ather: your away window from an earlier session is still running. Type /ather to see it, or /away end.', { timeoutMs: 15000 })
125 if (adopted) await stillTracking($)
126 // The timezone probe starts a process; it must not hold the session's first prompt.
127 void detectTz($).catch(() => undefined)
128 $.clock.every(30000, () => void tick($).catch(() => undefined))
129 } catch (error) {
130 $.ui.log(`Ather watch: start failed: ${String(error)}`, { to: 'debug' })
131 }
132 return result
133 })
134
135 // The lane's heartbeat says it has ended, so peers stop listing it at once. After /clear
136 // the process goes on under a new session id (no session.start fires): the lane moves to it.
137 on('session.end', async ($, e, next) => {
138 await heartbeat($, true).catch(() => undefined)
139 endWarm($)
140 if (e.reason === 'clear') followClear($, e.sessionId, 25)
141 return next(e)
142 })
143
144 on('prompt.submit', async ($, e, next) => {
145 // The person is back (isPersonOrigin says who that is).
146 if (isPersonOrigin(e.origin)) lastPersonAt = Date.now()
147 // Any prompt, or any tool call below, is the lane's last activity (its heartbeat says when).
148 state.markActive()
149 // Delivered into a running turn, it starts none.
150 if (e.turnId === undefined) await warmDispatch($, { type: 'turnStart', isPerson: isPersonOrigin(e.origin) }).catch(() => '')
151 return next(e)
152 })
153
154 // A drawing client attached: the desktop app's sessions start as the SDK's do, with no surface yet.
155 on('session.attach', async ($, e, next) => {
156 await warmDispatch($, { type: 'attach' }).catch(() => '')
157 return next(e)
158 })
159
160 // Under two matchers that cover every turn: console.mjs holds the event's unmatched hook.
161 on('turn.complete', { isAborted: false }, turnEnded)
162 on('turn.complete', { isAborted: true }, turnEnded)
163
164 on('command.run', { command: 'warm' }, async ($, e) => ({ text: await warmDispatch($, { type: 'command', args: e.args, ledger: await warmStore.readWarmLedger(io($)) }).catch(error => `Keep-warm could not answer: ${String(error)}`) }))
165
166 on('tool.call', { tool: 'mcp__ather-automata__status' }, async $ => ({ result: await statusText($) }))
167 on('tool.call', { tool: 'mcp__ather-automata__away' }, async ($, e) => ({ result: await awayTool($, /** @type {Record<string, unknown>} */ (/** @type {unknown} */ (e))) }))
168 on('tool.call', { tool: 'mcp__ather-automata__profile' }, async ($, e) => ({ result: await profileTool($, /** @type {Record<string, unknown>} */ (/** @type {unknown} */ (e))) }))
169
170 on('prompt.compose', async ($, e, next) => {
171 const result = await next(e)
172 try {
173 // A session whose folder has no intents is still told about an intent it tracks in a workspace checkout.
174 const text = (await laneOf($)).isS2 || (await state.readTracked(io($))) !== null ? await laneText($) : ''
175 return text === '' ? result : { ...result, sections: [...result.sections, { id: 'ather-automata:lane', text, scope: /** @type {const} */ ('session') }] }
176 } catch {
177 return result
178 }
179 })
180
181 on('tool.call', { tool: 'Bash' }, async ($, e, next) => shell($, e.command, e, next))
182 // PowerShell is a tool on Windows only, so the engine's types written on another machine do not list
183 // it. It takes `command` as Bash does, and is typed as Bash here.
184 on('tool.call', { tool: /** @type {'Bash'} */ (/** @type {string} */ ('PowerShell')) }, async ($, e, next) => shell($, e.command, e, next))
185
186 on('tool.call', { tool: 'Agent' }, async ($, e, next) => {
187 const issues = briefGate === 'off' ? [] : briefIssues(e.prompt, e.subagent_type, (await laneOf($).catch(() => null))?.pack)
188 const missing = andList(issues)
189 if (issues.length > 0 && briefGate === 'enforce') {
190 $.ui.toast(`Ather brief gate: refused a worker brief missing ${missing}.`)
191 return { deny: `Ather Automata brief gate: this worker brief is missing ${missing}. Add them (template: .agents/skills/intent/assets/worker-brief.md) and dispatch again.` }
192 }
193 const ran = await next(e)
194 if (issues.length === 0 || ran.deny !== undefined) return ran
195 $.ui.toast(`Ather: worker "${e.description}" was briefed without ${missing}.`)
196 void state.bump(io($), 'briefsFlagged').catch(() => undefined)
197 return { ...ran, context: [...(ran.context ?? []), `Ather Automata: the brief for "${e.description}" did not name ${missing}. If the worker edits files or the Editor, message it the missing parts now.`] }
198 })
199
200 // From the start of an away window until its review, the model's questions go to the ledger instead of waiting.
201 on('tool.call', { tool: 'AskUserQuestion' }, async ($, e, next) => {
202 // Ather's own dialogs are the person answering, never deferred.
203 if (next.origin.plugin === $.plugin.name) return next(e)
204 const deferred = await state.deferQuestions(io($), e.questions, lastPersonAt).catch(() => null)
205 if (deferred === null) return next(e)
206 const { ids, away } = deferred
207 void state.bump(io($), 'decisionsLedgered').catch(() => undefined)
208 $.ui.toast(`Ather: ${ids.join(', ')} recorded for your review instead of waiting.`)
209 return {
210 deny: `${awayReason(away, await state.readTz(io($)))} (Ather autonomy window). Do not wait. Take the recommended option for ${ids.join(', ')}, complete ${ids.length === 1 ? 'its entry' : 'their entries'} in ${away.ledgerPath} (Choice, Why, Evidence, Revert), and continue. Exception: if the question is about a destructive, production, credential, cost or CI-global action, do not take it; set the entry's Choice to "parked for the director" and move on to other work.`,
211 }
212 })
213
214 on('agent.spawn', async ($, e, next) => {
215 const spawned = await next(e)
216 if (spawned.agentId) recordSpawn({ agentId: spawned.agentId, subagentType: e.subagentType, prompt: e.prompt, description: e.description, model: spawned.model, at: Date.now() })
217 // A foreground Agent call now waits on this worker: its loop's call in flight names it.
218 if (spawned.agentId) linkChild({ loop: e.parentAgentId ?? '', toolUseId: e.tool_use_id, childId: spawned.agentId, isBackground: e.background })
219 return spawned
220 })
221
222 // A permission dialog shown to the person (not tool.check's "ask", which in auto mode the classifier often
223 // settles at once): until it settles, that call waits on their decision, not running, and a long wait is what
224 // the toast is for. Watched only: the dialog's answer is never decided here.
225 on('classic.PermissionRequest', async ($, e, next) => {
226 markAsking({ loop: e.agent_id ?? '', tool: e.tool_name, input: e.tool_input, at: Date.now() })
227 return next(e)
228 })
229
230 on('tool.call', async ($, e, next) => {
231 // Ather's own calls of the desktop app's tools are neither the session's activity nor its work.
232 if (next.origin.plugin === $.plugin.name && String(e.tool).startsWith('mcp__ccd_')) return next(e)
233 const tool = String(e.tool)
234 state.markActive()
235 // A worker's tool call: what it is doing now, for its avatar and trail.
236 if (e.agentId) recordTool(e.agentId, tool, /** @type {Record<string, unknown>} */ (/** @type {unknown} */ (e)), Date.now())
237 const isMcp = tool.startsWith('mcp__') && !tool.startsWith('mcp__ather-automata__')
238 const input = JSON.stringify(e).slice(0, 4000)
239 if (isMcp && (await laneOf($)).pack.isAssetSave(input)) {
240 const denied = await hold($, 'asset-save', `${tool} ${input.slice(0, 300)}`).catch(() => null)
241 if (denied) return { deny: denied }
242 }
243 const path = /** @type {{ file_path?: unknown }} */ (e).file_path
244 const isWrite = /^(Write|Edit|MultiEdit)$/.test(tool)
245 // The session's own orchestration (its main thread, never a worker) writing an intent's prompt.md or log.md
246 // tracks that intent, in the checkout the write lands in, once the write has gone through; creating a
247 // prompt.md switches to the new intent.
248 const orchestrated = isWrite && e.agentId === undefined ? orchestrationFileOf(path) : null
249 const isNewIntent = orchestrated?.file === 'prompt.md' && !(await io($).exists(await fullPath($, String(path))))
250 // An edit to an intent's prompt, findings or progress: what it changed, read off the file before and after.
251 const intentFile = isWrite ? intentFileOf(path) : null
252 const before = intentFile ? ((await readFile($, String(path))) ?? '') : ''
253 // In flight until it settles (ran, refused or threw) or the dispatch aborts, in its loop (a worker's, or the
254 // main loop's); then heard from.
255 const settled = () => (e.agentId ? recordHeard(e.agentId, Date.now()) : undefined)
256 const ran = await during({ loop: e.agentId ?? '', toolUseId: String(e.tool_use_id ?? ''), tool, input: /** @type {Record<string, unknown>} */ (/** @type {unknown} */ (e)), at: Date.now() }, () => next(e), settled, next.signal)
257 const hasRun = ran.deny === undefined && ran.isError !== true
258 if (orchestrated && hasRun) void intentRootOf($, String(path)).then(root => state.track(io($), root, orchestrated.slug, { isAuto: true, onlyIfNone: !isNewIntent })).catch(() => undefined)
259 if (isMcp && ran.deny === undefined) void noteMcp($, tool, input, ran).catch(() => undefined)
260 if (intentFile && ran.deny === undefined) void noteIntentEdit($, intentFile, String(path), before).catch(() => undefined)
261 return ran
262 })
263}
264
265// ---------------------------------------------------------------- what an intent edit recorded
266
267// A tool's file path as written, or relative to the session folder.
268/** @param {Engine} $ @param {string} path */
269async function fullPath($, path) {
270 return /^([A-Za-z]:|[\\/])/.test(path) ? path : `${cwd || (await laneOf($)).root}/${path}`
271}
272
273// The folder holding the docs/intent an intent file is in: the checkout it lands in.
274/** @param {Engine} $ @param {string} path */
275async function intentRootOf($, path) {
276 return normalFolder((await fullPath($, path)).replace(/[\\/]docs[\\/]intent[\\/][^\\/]+[\\/][^\\/]+$/i, ''))
277}
278
279/** @param {Engine} $ @param {string} path */
280async function readFile($, path) {
281 return io($).read(await fullPath($, path))
282}
283
284/** @param {Engine} $ @param {{ slug: string, file: import('./changes.mjs').IntentFile }} target @param {string} path @param {string} before */
285async function noteIntentEdit($, target, path, before) {
286 const after = (await readFile($, path)) ?? ''
287 // The edited file's sibling, as it is now: prompt.md for findings and progress, progress.md for prompt.
288 const sibling = async (/** @type {string} */ name) => (await readFile($, path.replace(/[^\\/]+\.md$/i, name))) ?? ''
289 const intent = target.file === 'prompt.md' ? { progress: await sibling('progress.md') } : { prompt: await sibling('prompt.md') }
290 await state.noteChanges(io($), target.slug, intentChanges(target.file, before, after, intent), Date.now(), await intentRootOf($, path))
291}
292
293// ---------------------------------------------------------------- intents and the lane
294
295// The tracked intent's files, read in its own checkout with that checkout's pack.
296/** @param {Engine} $ @param {{ slug: string, lane: import('./state.mjs').Checkout }} tracked */
297async function readIntent($, { slug, lane }) {
298 const { root, pack } = lane
299 const dir = `${root}/docs/intent/${slug}`
300 const files = io($)
301 const prompt = await files.read(`${dir}/prompt.md`)
302 if (prompt === null) return undefined
303 return parseIntent({
304 slug,
305 prompt,
306 findings: (await files.read(`${dir}/findings.md`)) ?? '',
307 progress: (await files.read(`${dir}/progress.md`)) ?? '',
308 files: (await $.fs.list(dir).catch(() => [])).map(entry => entry.name),
309 hasDebrief: await files.exists(`${root}/${pack.debriefPath(slug)}`),
310 updatedAt: 0,
311 source: 'local',
312 firstAuthor: '',
313 }, pack)
314}
315
316/** @param {Engine} $ */
317// The branch checked out in a folder (null: the session's checkout); '' when it cannot be told.
318/** @param {Engine} $ @param {string | null} [folder] */
319async function readBranch($, folder = null) {
320 const { root } = await laneOf($)
321 const base = folder === null ? root : /^([A-Za-z]:[\\/]|[\\/])/.test(folder) ? folder : `${root}/${folder}`
322 const files = io($)
323 // The checkout the folder is in: `cd Plugins/X && git push` pushes the checkout's branch.
324 const checkout = await checkoutOf(files, base)
325 const gitDir = checkout === null ? null : await gitDirOf(files, checkout)
326 const head = gitDir === null ? null : await files.read(`${gitDir}/HEAD`)
327 return /ref:\s*refs\/heads\/(.+)/.exec(head ?? '')?.[1]?.trim() ?? (head ?? '').trim().slice(0, 12)
328}
329
330// The branch each git segment of a command runs on, read before the pure hold check.
331/** @param {Engine} $ @param {string} command */
332async function branchesFor($, command) {
333 const branches = new Map()
334 for (const folder of gitFolders(command)) branches.set(folder, await readBranch($, folder).catch(() => ''))
335 return (/** @type {string | null} */ folder) => branches.get(folder) ?? ''
336}
337
338// The heartbeat, in the session's checkout and in the tracked intent's when that is another. A session
339// whose folder has no intents (a parent folder) writes only to the tracked intent's checkout, and to the
340// checkouts it wrote to before.
341/** @param {Engine} $ @param {boolean} hasEnded */
342async function heartbeat($, hasEnded) {
343 await askApp($)
344 const { root, isS2, pack } = await laneOf($)
345 const tracked = await state.trackedLane(io($), cwd)
346 const other = tracked && !tracked.isOwn ? tracked.lane : null
347 if (!isS2 && !other && !state.hasHeartbeats()) return
348 const also = other ? { root: other.root, localDir: other.pack.localDir, branch: await readBranch($, other.root).catch(() => '') } : null
349 await state.writeHeartbeat(io($), { root: isS2 ? root : '', localDir: pack.localDir, branch: isS2 ? await readBranch($) : '', hasEnded, also })
350}
351
352// This session's id and title in the desktop app, from the app's session tool, for the heartbeats (A1): other
353// sessions name it by its title and send to it by that id. Outside the app the tool is absent and there is none.
354let appAskedAt = 0
355/** @param {Engine} $ */
356async function askApp($) {
357 if (Date.now() - appAskedAt < APP_EVERY_MS) return
358 appAskedAt = Date.now()
359 const asked = await appTool(() => $.tool.call({ tool: 'mcp__ccd_session_mgmt__get_session', session_id: 'self' }))
360 state.setAppSession(asked.isDone ? appSessionOf(asked.text) : null)
361}
362
363// A session this checkout can vouch has gone: its heartbeat is here and says ended, or is stale.
364// A session with no heartbeat here may be alive in another checkout, so it is left alone.
365/** @param {Engine} $ @param {string} sid */
366async function isLaneGone($, sid) {
367 const { root, pack } = await laneOf($)
368 const lane = await state.readLane(io($), root, pack.localDir, sid)
369 return lane !== null && !state.isLaneLive(lane)
370}
371
372// Another session is alive while its heartbeat is fresh and has not said it ended.
373/** @param {Engine} $ @param {string} sid */
374async function isLaneAlive($, sid) {
375 const { root, pack } = await laneOf($)
376 const lane = await state.readLane(io($), root, pack.localDir, sid)
377 return lane !== null && state.isLaneLive(lane)
378}
379
380// Where proof seen in the session's own checkout goes: the tracked intent when it lives here, else the session.
381/** @param {Engine} $ */
382async function scopeOf($) {
383 return state.checkoutScope(io($), { isOwn: true, repo: '' })
384}
385
386// The checkout a command's folder runs in (null: the session folder) and its lane. `isOwn`: it is the
387// session's own checkout, or in no checkout at all; both use the session's lane.
388/** @param {Engine} $ @param {string | null} folder @returns {Promise<{ lane: import('./state.mjs').Checkout, isOwn: boolean }>} */
389async function checkoutLane($, folder) {
390 return state.folderLane(io($), await laneOf($), folder)
391}
392
393// The other live sessions in a checkout: the session's own unless a lane is given.
394/** @param {Engine} $ @param {import('./state.mjs').Checkout} [lane] */
395async function peers($, lane) {
396 const { root, pack } = lane ?? (await laneOf($))
397 return state.readPeers(io($), root, pack.localDir)
398}
399
400// What every prompt is told about this lane: the tracked intent, the Editor lock, live peers, the window's mandate.
401/** @param {Engine} $ */
402async function laneText($) {
403 const { root, me, pack, base } = await laneOf($)
404 const lines = []
405 const tz = await state.readTz(io($))
406 const tracked = await state.trackedLane(io($), cwd)
407 const intent = tracked ? await readIntent($, tracked) : undefined
408 const live = await peers($)
409 if (tracked && intent) {
410 const { pack: its } = tracked.lane
411 const { role } = await state.readProfile(io($), me, its)
412 const prs = await state.readPrStates(io($), tracked.isOwn ? undefined : tracked.lane.repo)
413 const stage = STAGE_LABELS[currentStage(intent, await state.readEvidence(io($), await state.evidenceScope(io($)), its), role, prs, its)]
414 const folder = tracked.isOwn ? `docs/intent/${intent.slug}/` : `${tracked.lane.root}/docs/intent/${intent.slug}/`
415 lines.push(`Tracked intent: ${intent.slug} (${folder}), status ${intent.status}, stage ${stage} (Plan, Build, Prove, Ship), checklist ${intent.acceptanceDone}/${intent.acceptanceTotal}${intent.prs.length > 0 ? `, PRs ${prStatusList(intent, prs).join(', ')}` : ''}, open director calls ${directorCalls(intent).length}.`)
416 // Without the age the pane shows: the session keeps this text as first read for the whole
417 // conversation, so an age would soon be wrong.
418 const held = trackedByLine(tracked.isOwn ? live : await peers($, tracked.lane), intent.slug)
419 if (held) lines.push(`${held}.`)
420 }
421 const lock = pack.parseLock(pack.lockFile ? await io($).read(`${root}/${pack.lockFile}`) : null, localMinutes(Date.now(), tz))
422 if (lock.state === 'held') lines.push(`Editor owner lock: held by ${lock.holder || 'another lane'}${lock.until ? ` until ${lock.until}` : ''}.`)
423 if (live.length > 0) lines.push(`Live peer lanes on this checkout: ${live.map(lane => `${lane.intent ?? 'no intent'} on ${lane.branch}`).join('; ')}.`)
424 const away = await state.readAway(io($))
425 if (isHolding(away)) lines.push(mandateText(away, tz, pack, base))
426 return lines.length > 0 ? `Ather Automata lane state (live, read-only):\n${lines.join('\n')}` : ''
427}
428
429// While session.end runs the old id is still current: wait for the new one, then move the lane to it.
430/** @param {Engine} $ @param {string} oldSid @param {number} tries */
431function followClear($, oldSid, tries) {
432 $.clock.after(200, () => {
433 void $.session
434 .id()
435 .then(sid => {
436 if (sid !== oldSid) return state.moveLane(io($), oldSid, sid).then(() => stillTracking($))
437 if (tries > 0) return followClear($, oldSid, tries - 1)
438 $.ui.log('Ather watch: the session id did not change within 5 s of /clear; the lane stays under the old id.', { to: 'debug' })
439 })
440 .catch(() => undefined)
441 })
442}
443
444// After /clear or an adopted away window the session keeps the intent it tracked: say so, and how to stop.
445/** @param {Engine} $ */
446async function stillTracking($) {
447 const slug = await state.readPinned(io($))
448 if (slug) $.ui.toast(`Ather: Still tracking ${slug} · /ather untrack`, { timeoutMs: 12000 })
449}
450
451// Every 30 seconds: the heartbeat, quiet workers, and the end of an autonomy window.
452/** @param {Engine} $ */
453async function tick($) {
454 await heartbeat($, false)
455 const now = Date.now()
456 for (const agent of await $.agent.list().catch(() => [])) {
457 const seen = workerOf(agent.id)
458 if (agent.status !== 'running' || !seen?.lastTool || idleWarned.has(agent.id)) continue
459 // A call waiting on permission: warned once it has waited the threshold, whatever else is quiet.
460 const [asking] = askingIn(agent.id)
461 if (asking) {
462 if (asking.askedAt === undefined || now - asking.askedAt < IDLE_MS) continue
463 idleWarned.add(agent.id)
464 $.ui.toast(`Ather: worker "${agent.description}" asked permission to run ${asking.tool} ${Math.round((now - asking.askedAt) / 60000)} min ago and has not finished: ${asking.what}.`)
465 continue
466 }
467 // The same rule as the pane's: a call running (a long build, a PIE run, a foreground worker) is never quiet.
468 if (!isSilent({ isInFlight: isInFlight(agent.id), lastAt: seen.lastAt, now, quietMs: IDLE_MS })) continue
469 idleWarned.add(agent.id)
470 $.ui.toast(`Ather: worker "${agent.description}" has been quiet for ${Math.round((now - seen.lastAt) / 60000)} min after ${seen.lastTool}. Possibly a stuck permission prompt.`)
471 }
472 // A window ends at its time, or when the session reports the goal done; holds stay until the review.
473 const away = await state.readAway(io($))
474 if (away.phase === 'running' && now >= away.wakeAt && (await state.endAway(io($)))) $.ui.toast('Ather: the away window has ended; held actions stay held until you review it. Type /ather.', { timeoutMs: 15000 })
475}
476
477/** @param {Engine} $ */
478async function detectTz($) {
479 for (const argv of [['powershell', '-NoProfile', '-Command', "(Get-Date).ToString('zzz')"], ['date', '+%z']]) {
480 const run = await $.process.run(argv, { timeoutMs: 15000 }).catch(() => undefined)
481 const offset = run && run.exitCode === 0 ? parseTzOffset(run.stdout) : null
482 if (offset !== null) return state.setTz(io($), offset)
483 }
484}
485
486// ---------------------------------------------------------------- the model's tools
487
488// A held action, parked for the person's review; null when no window holds it. `heldHere`: the kinds
489// held where it runs, when that is more than the window's own. `base`: the branch the checkout it runs in
490// merges into, for what is said of it; the session's own checkout's unless given.
491/** @param {Engine} $ @param {import('./guards.mjs').HeldKind} kind @param {string} command @param {readonly string[]} [heldHere] @param {string} [base] */
492async function hold($, kind, command, heldHere, base) {
493 const held = await state.park(io($), kind, command, Date.now(), heldHere)
494 if (held === null) return null
495 void state.bump(io($), 'heldParked').catch(() => undefined)
496 const lane = await laneOf($).catch(() => undefined)
497 base ??= lane?.base
498 $.ui.toast(`Ather: held ${heldNoun(kind, lane?.pack, base)} until you review the away window (${held.parked.id}).`)
499 return `Held by the Ather away window until the user reviews it: ${heldLabel(kind, lane?.pack, base)}. Recorded as ${held.parked.id}. Do not retry it; continue with other work.`
500}
501
502/** @param {Engine} $ @param {Record<string, unknown>} input */
503async function awayTool($, input) {
504 const action = String(input.action ?? '')
505 const tz = await state.readTz(io($))
506 if (action === 'start') {
507 const { root, me, pack, base } = await laneOf($)
508 const held = Array.isArray(input.held) ? heldKindsOf(pack).filter(kind => /** @type {unknown[]} */ (input.held).includes(kind)) : undefined
509 const choice = { hours: clampHours(Number(input.hours) || 8), untilDone: input.untilDone === true, goal: typeof input.goal === 'string' ? input.goal.trim() : '', held }
510 const started = await state.startAway(io($), choice, { root, me, tz, now: Date.now(), pack, base })
511 if (started === null) return 'An away window is already running or waiting for the user\'s review.'
512 $.ui.toast(`Ather: away window running ${windowEndText(started, tz)}.`)
513 return `Autonomy window open ${windowEndText(started, tz)}. Allowed without asking: ${forBase(pack.mandate.allowed, base)}. Ledger: ${started.ledgerPath}. Held: ${started.held.map(kind => heldLabel(kind, pack, base)).join(', ')}. Questions to the user are now recorded in the ledger instead of asked.`
514 }
515 if (action === 'end') return (await state.endAway(io($))) ? 'Autonomy window ended; the user reviews it with /ather.' : 'No autonomy window is running.'
516 if (action === 'close') return (await state.closeAway(io($))) ? 'Autonomy window closed.' : 'No autonomy window to close.'
517 return 'Unknown action: use start, end or close.'
518}
519
520/** @param {Engine} $ @param {Record<string, unknown>} input */
521async function profileTool($, input) {
522 const { root, me, pack } = await laneOf($)
523 const done = []
524 const role = input.role === undefined ? undefined : String(input.role).toLowerCase()
525 if (role !== undefined && !pack.roles.includes(role)) return `Unknown role "${role}": use ${pack.roles.join(', ')}.`
526 const area = input.area === undefined ? undefined : pack.normalizeArea(String(input.area))
527 if (area === 'Unsorted') return `Unknown area "${String(input.area)}": use one of ${pack.areas.join(', ')}.`
528 if (role !== undefined || area !== undefined) {
529 await state.setProfile(io($), me, { role, area }, pack)
530 done.push([role ? `Role set to ${role}.` : '', area ? `Area set to ${area}.` : ''].filter(Boolean).join(' '))
531 }
532 if (typeof input.track === 'string' && input.track.trim().toLowerCase() === 'none') {
533 done.push(untrackText(await state.untrack(io($), me)))
534 } else if (typeof input.track === 'string' && input.track.trim() !== '') {
535 const slug = input.track.trim()
536 // `folder`: another checkout holding the intent, absolute or from the session folder.
537 const folder = typeof input.folder === 'string' ? input.folder.trim() : ''
538 const at = folder === '' ? root : normalFolder(/^([A-Za-z]:|[\\/])/.test(folder) ? folder : `${cwd || root}/${folder}`)
539 if (!(await state.track(io($), at, slug))) return `No intent named "${slug}" in ${folder === '' ? '' : `${folder}/`}docs/intent.`
540 done.push(`This session now tracks intent ${slug}.`)
541 }
542 return done.join(' ') || 'Nothing to change: pass role, area or track.'
543}
544
545/** @param {Engine} $ */
546async function statusText($) {
547 const { root, me, pack } = await laneOf($)
548 const tracked = await state.trackedLane(io($), cwd)
549 const intent = tracked ? await readIntent($, tracked) : undefined
550 // The tracked intent is read, staged and proved with its own checkout's pack.
551 const its = tracked?.lane.pack ?? pack
552 const { role, area } = await state.readProfile(io($), me, its)
553 const evidence = await state.readEvidence(io($), await state.evidenceScope(io($)), its)
554 const away = await state.readAway(io($))
555 const tz = await state.readTz(io($))
556 const prs = await state.readPrStates(io($), tracked && !tracked.isOwn ? tracked.lane.repo : undefined)
557 return JSON.stringify(
558 {
559 me,
560 role,
561 area,
562 tracked: intent
563 ? { slug: intent.slug, ...(tracked?.isOwn === false ? { checkout: tracked.lane.root } : {}), status: intent.status, stage: STAGE_LABELS[currentStage(intent, evidence, role || 'engineer', prs, its)], checklist: `${intent.acceptanceDone}/${intent.acceptanceTotal}`, prs: prStatusList(intent, prs), directorCalls: directorCalls(intent).map(one => `${one.id}: ${one.title}`) }
564 : null,
565 evidence,
566 ...(pack.lockFile ? { editorLock: pack.parseLock(await io($).read(`${root}/${pack.lockFile}`), localMinutes(Date.now(), tz)).raw } : {}),
567 // The tracked intent's checkout's gates and merge policy: what proves it.
568 ...(its.id === 'unreal' ? {} : { pack: its.id, gates: its.gates.map(gate => `${gate.command}: ${gate.proofs.join(', ')}`), mergePolicy: its.mergePolicy }),
569 peers: (await peers($)).map(lane => `${lane.intent ?? 'no intent'} on ${lane.branch}`),
570 away: { phase: away.phase, until: away.phase === 'off' ? '' : windowEndText(away, tz), ledger: away.ledgerPath, parked: away.parked.map(one => `${one.id}: ${one.command}`) },
571 recurringGotchas: (await state.readRecurring(io($), pack)).map(one => `${one.title} (${one.count} sessions)`),
572 caught: await state.readScore(io($)),
573 },
574 null,
575 1,
576 )
577}
578
579/** @param {Engine} $ @param {import('./packs/index.mjs').Pack} pack */
580async function registerTools($, pack) {
581 await $.tool.register({
582 name: 'status',
583 description: `Ather Automata: read the live state of ${pack.statusWhat} as JSON: tracked intent, its stage (Plan, Build, Prove, Ship), director calls, evidence read from tool output, ${pack.lockFile ? 'Editor owner lock' : 'the gates the profile names'}, peer lanes, autonomy window, recurring traps. Read-only.`,
584 inputSchema: { type: 'object', properties: {} },
585 })
586 await $.tool.register({
587 name: 'away',
588 description:
589 'Ather Automata: open, end or close an autonomy window. Open one (action "start") only when the user has said in their own words that they are going away and granting autonomy, for example "I am going to sleep for 8 hours, you have full autonomy". While it runs, questions to the user are written to a decision ledger instead of asked, and held actions are refused and parked for the user\'s review. "end" finishes it early; "close" closes the review.',
590 inputSchema: {
591 type: 'object',
592 properties: {
593 action: { type: 'string', enum: ['start', 'end', 'close'] },
594 hours: { type: 'number', description: 'Window length in hours (0.25 to 16). Default 8. Ignored with untilDone.' },
595 untilDone: { type: 'boolean', description: 'No fixed end: the window runs until the goal is done (call this tool with action "end" then), capped at 24 hours.' },
596 goal: { type: 'string', description: 'What to pursue while the user is away, in their words.' },
597 held: { type: 'array', items: { type: 'string', enum: heldKindsOf(pack) }, description: `Actions to refuse and park. Default: ${pack.held.defaults.join(', ')}.` },
598 },
599 required: ['action'],
600 },
601 })
602 await $.tool.register({
603 name: 'profile',
604 description: "Ather Automata: record the user's role and area when they state them, and which intent this session tracks when they choose one, for example during the Ather tour. The role shapes the next step Ather suggests and what Prove asks for; the area orders the intents Ather offers.",
605 inputSchema: {
606 type: 'object',
607 properties: {
608 role: { type: 'string', enum: [...pack.roles] },
609 ...(pack.areas.length > 0 ? { area: { type: 'string', enum: [...pack.areas] } } : { area: { type: 'string' } }),
610 track: { type: 'string', description: 'The folder name of an intent under docs/intent for this session to track, or "none" to stop tracking.' },
611 folder: { type: 'string', description: 'With track: another checkout holding that docs/intent, absolute or relative to the session folder. Default: this checkout.' },
612 },
613 },
614 })
615}
616
617// ---------------------------------------------------------------- shell and MCP calls
618
619/** @param {Engine} $ @param {string} command @param {any} e @param {any} next */
620async function shell($, command, e, next) {
621 const away = await state.readAway(io($)).catch(() => offAway())
622 const found = isHolding(away) ? await heldIn($, command, away.held) : null
623 if (found) {
624 const denied = await hold($, found.kind, command, found.held, found.base).catch(() => null)
625 if (denied) return { deny: denied }
626 }
627 const ran = await next(e)
628 try {
629 const context = await afterShell($, command, ran)
630 return context.length > 0 && ran.deny === undefined ? { ...ran, context: [...(ran.context ?? []), ...context] } : ran
631 } catch {
632 return ran
633 }
634}
635
636// What the window holds in a command, each segment judged by the checkout it runs in. Another checkout
637// holds the window's kinds and its own pack's defaults, so a window never holds less there than that
638// repository would, and counts only proof this session saw in that checkout. Resolves the kind held and the
639// base of the checkout it was held in, with every kind held across the command's checkouts for parking it, or null.
640/** @param {Engine} $ @param {string} command @param {readonly string[]} held @returns {Promise<{ kind: string, base: string, held: string[] } | null>} */
641async function heldIn($, command, held) {
642 const { pack, base } = await laneOf($)
643 /** @type {Map<string | null, import('./packs/index.mjs').HeldAt | null>} */
644 const at = new Map()
645 for (const { folder } of withFolders(command)) {
646 if (at.has(folder)) continue
647 const { lane, isOwn } = await checkoutLane($, folder)
648 if (isOwn) at.set(folder, null)
649 else at.set(folder, { pack: lane.pack, held: [...new Set([...held, ...lane.pack.held.defaults])], isProven: await isMergeProven($, lane.pack, await state.checkoutScope(io($), { isOwn, repo: lane.repo, root: lane.root })), base: lane.base })
650 }
651 const found = heldShellAt(command, held, await branchesFor($, command), pack, { isProven: await isMergeProven($, pack, await scopeOf($)), base, at: folder => at.get(folder) ?? null })
652 return found ? { ...found, held: [...new Set([...held, ...[...at.values()].flatMap(one => one?.held ?? [])])] } : null
653}
654
655// With-proof merges (D2): every rung the profile requires passed in tool output in this session, in `scope`.
656/** @param {Engine} $ @param {import('./packs/index.mjs').Pack} pack @param {string} scope */
657async function isMergeProven($, pack, scope) {
658 if (pack.mergePolicy !== 'with-proof') return false
659 const evidence = await state.readEvidence(io($), scope, pack)
660 const rungs = pack.mergeRungs ?? []
661 const seen = /** @type {Record<string, { state: string, at?: number }>} */ (evidence)
662 return rungs.length > 0 && rungs.every(rung => seen[rung]?.state === 'pass' && (seen[rung]?.at ?? 0) >= sessionStartedAt)
663}
664
665/** @param {Engine} $ @param {string} command @param {{ text?: string, deny?: string, isError?: boolean }} ran */
666async function afterShell($, command, ran) {
667 const context = []
668 const text = ran.text ?? ''
669 // The checkout the command ran in is its last segment's: its pack reads the output, and its proof is kept there.
670 const { lane, isOwn } = await checkoutLane($, withFolders(command).at(-1)?.folder ?? null)
671 const { pack } = lane
672 const scope = await state.checkoutScope(io($), { isOwn, repo: lane.repo, root: lane.root })
673 if (!isSearchCommand(command)) await noteTraps($, text, pack)
674 const guard = explainGuard(command)
675 if (guard !== null && (ran.deny !== undefined || ran.isError === true)) $.ui.toast(`Ather guard: ${guard}`, { timeoutMs: 12000 })
676 const reading = pack.readShell(command, text, ran)
677 for (const one of reading.rungs) await state.setRung(io($), scope, one.rung, one.value, one.gates)
678 context.push(...reading.context)
679 for (const toast of reading.toasts) $.ui.toast(toast.text, toast.timeoutMs === undefined ? undefined : { timeoutMs: toast.timeoutMs })
680 for (const key of reading.bumps) void state.bump(io($), key).catch(() => undefined)
681 if (isMergeCommand(command) && ran.deny === undefined && ran.isError !== true) {
682 const lost = await auditMerge($, lane.root, pack).catch(() => [])
683 if (lost.length > 0) {
684 await state.flagLost(io($), lost)
685 void state.bump(io($), 'lostWorkFlags').catch(() => undefined)
686 $.ui.toast(`Ather: the merge kept the other side of ${lost.length} binary asset(s); this branch's edits to them are gone.`, { timeoutMs: 15000 })
687 context.push(`Ather Automata merge audit: these binary assets are byte-identical to the merged-in side, so every edit this branch made to them is gone: ${lost.join(', ')}. Tell the user now, itemised, and mark each as a lost optimisation or a broken feature.`)
688 }
689 }
690 return context
691}
692
693/** @param {Engine} $ @param {string} text @param {import('./packs/index.mjs').Pack} pack */
694async function noteTraps($, text, pack) {
695 const fresh = matchGotchas(text, pack).filter(rule => !seenTraps.has(rule.id))
696 if (fresh.length === 0) return
697 for (const rule of fresh) {
698 seenTraps.add(rule.id)
699 $.ui.toast(`Ather gotcha: ${rule.title}. ${rule.fix}`, { timeoutMs: 10000 })
700 }
701 await state.countTraps(io($), fresh)
702}
703
704/** @param {Engine} $ @param {string} tool @param {string} input @param {{ text?: string, isError?: boolean }} ran */
705async function noteMcp($, tool, input, ran) {
706 const { pack } = await laneOf($)
707 const kind = pack.mcpKind(input)
708 if (kind) await state.noteMcp(io($), await scopeOf($), kind, mcpServer(tool), ran.isError !== true)
709 await noteTraps($, ran.text ?? '', pack)
710}
711
712// After a merge: binary assets byte-identical to the merged-in side lost this branch's edits.
713/** @param {Engine} $ @param {string} root the checkout merged in @param {import('./packs/index.mjs').Pack} pack */
714async function auditMerge($, root, pack) {
715 const binary = pack.binaryAssets
716 if (!binary) return []
717 const git = (/** @type {string[]} */ args) => $.process.run(['git', '-C', root, ...args], { env: GIT_ENV, timeoutMs: 30000 })
718 const [, ours = '', theirs = ''] = (await git(['rev-list', '--parents', '-n', '1', 'HEAD'])).stdout.trim().split(/\s+/)
719 if (theirs === '') return []
720 const base = (await git(['merge-base', ours, theirs])).stdout.trim()
721 if (base === '') return []
722 const touched = (await git(['diff', '--name-only', base, ours])).stdout.split(/\r?\n/).filter(path => binary.test(path)).slice(0, 300)
723 if (touched.length === 0) return []
724 const blobs = async (/** @type {string} */ rev) => {
725 const map = new Map()
726 for (let i = 0; i < touched.length; i += 50) {
727 for (const line of (await git(['ls-tree', rev, '--', ...touched.slice(i, i + 50)])).stdout.split(/\r?\n/)) {
728 const match = /^\d+\s+blob\s+([0-9a-f]+)\t(.+)$/.exec(line)
729 if (match?.[1] && match[2]) map.set(match[2], match[1])
730 }
731 }
732 return map
733 }
734 const [merged, mine, other] = await Promise.all([blobs('HEAD'), blobs(ours), blobs(theirs)])
735 return touched.filter(path => merged.get(path) !== undefined && merged.get(path) === other.get(path) && merged.get(path) !== mine.get(path))
736}
737
738// ---------------------------------------------------------------- keeping the prompt cache warm
739// warm.mjs decides (stepWarm); this section reads what each step needs and carries out what it returns.
740
741// A main-thread turn ended (a worker's reads its own cache, not the session's).
742/** @type {import('claude-code').Hook<'turn.complete'>} */
743async function turnEnded($, e, next) {
744 const result = await next(e)
745 if (e.agentId === undefined) void warmDispatch($, { type: 'turnEnd', usage: e.usage ?? null }).catch(() => '')
746 return result
747}
748
749/** @param {Engine} $ @param {boolean} attended */
750async function startWarm($, attended) {
751 await warmDispatch($, { type: 'start', attended, choice: await warmStore.readWarm(io($)) })
752 // The row's ◔ and the pane's button (console.mjs) turn it on and off through here, where it runs.
753 warmStore.onWarmToggle(isOn => warmDispatch($, { type: 'toggle', isOn }))
754 await $.command.register({ name: 'warm', description: 'Ather Automata: keep the prompt cache warm while you are idle', argumentHint: '[on | off | <n>h]' })
755}
756
757// At the session's end, without waiting on anything (F-1): its step needs nothing read, and its effects run behind it.
758/** @param {Engine} $ */
759function endWarm($) {
760 const { state: next, effects } = stepWarm(warm, { type: 'end' }, IDLE_ENV)
761 warm = next
762 for (const effect of effects) void runWarm($, effect).catch(() => undefined)
763}
764
765// What the session tells each step, read at once.
766/** @param {Engine} $ @returns {Promise<import('./warm.mjs').WarmEnv>} */
767async function warmEnv($) {
768 const [now, tz, away, usage] = await Promise.all([$.clock.now(), state.readTz(io($)), state.readAway(io($)).catch(() => null), $.session.usage().catch(() => null)])
769 return {
770 now,
771 tz,
772 away: { phase: away?.phase ?? 'off', untilDone: away?.untilDone ?? false, startedAt: away?.startedAt ?? 0, wakeAt: away?.wakeAt ?? 0 },
773 quota: Math.max(0, ...(usage?.rateLimits ?? []).map(one => one.percentUsed)),
774 context: usage?.context.tokens ?? 0,
775 }
776}
777
778// One event: the step decides, its effects are carried out in order, and its reply is what /warm and the ◔ say.
779/** @param {Engine} $ @param {import('./warm.mjs').WarmEvent} event @returns {Promise<string>} */
780async function warmDispatch($, event) {
781 const env = await warmEnv($)
782 const { state: next, effects, reply } = stepWarm(warm, event, env)
783 warm = next
784 for (const effect of effects) await runWarm($, effect).catch(error => $.ui.log(`Ather warm: ${effect.type}: ${String(error)}`, { to: 'debug' }))
785 return reply
786}
787
788/** @param {Engine} $ @param {import('./warm.mjs').WarmEffect} effect */
789async function runWarm($, effect) {
790 switch (effect.type) {
791 case 'cancel':
792 warmTimer?.cancel()
793 warmTimer = null
794 return
795 case 'arm':
796 warmTimer = $.clock.after(effect.delay, () => void warmDispatch($, { type: 'fire', id: effect.id }).catch(() => ''))
797 return
798 case 'fork':
799 // Not awaited: a read takes seconds, and the session's next event must not wait on it.
800 void readCache($, effect.id, effect.context).catch(error => $.ui.log(`Ather warm: read failed: ${String(error)}`, { to: 'debug' }))
801 return
802 case 'status':
803 return $.ui.status(effect.text)
804 case 'view':
805 return warmStore.showWarm(io($), effect.view)
806 case 'toast':
807 return $.ui.toast(`Ather: ${effect.text}`, { timeoutMs: effect.ms })
808 case 'note':
809 return warmStore.noteWarm(io($), effect.change)
810 case 'save':
811 return warmStore.setWarm(io($), effect.fields)
812 }
813}
814
815// Reads the cache once with a tool-less fork of the session's last request, which starts its hour again; what it cost
816// is the change in the session's cost around it.
817/** @param {Engine} $ @param {number} id @param {number} context */
818async function readCache($, id, context) {
819 const before = (await $.session.usage().catch(() => null))?.cost?.usd ?? 0
820 const reply = await $.model.fork({ prompt: PING_PROMPT })
821 const usd = Math.max(0, ((await $.session.usage().catch(() => null))?.cost?.usd ?? before) - before)
822 const usage = 'usage' in reply ? reply.usage : null
823 const reason = reply.isAnswered ? '' : reply.reason
824 $.ui.log(`Ather warm: read ${JSON.stringify({ ...usage, context, usd, reason })}`, { to: 'debug' })
825 await warmDispatch($, { type: 'read', id, context, usage, reason, usd })
826}
827hooks/console.mjs 2296 lines1// @ts-check
2// Ather Automata, the visible half: what needs me, and what is next.
3//
4// Terminal: a one-line hint above the prompt, only when something needs you;
5// /ather opens one pane. Desktop (no drawing surface): /ather asks one question,
6// never a loop. Either way, picking something hands it to the session, which
7// asks its own questions. Shared state changes only through state.mjs.
8//
9// The host reads on(...) and $.noun.method(...) from source, so they are
10// spelled literally, and helpers that take $ are top-level functions.
11
12import { AWAY_PRESETS, awayMessage, awaySessions, isStopWord, parseAwayArgs, pickedSessions, windowEndText } from './away.mjs'
13import { VIEW_LABELS, isShownIn, otherView, viewText, skillFolder, askPrompt, batchPrompt, buildHome, heldByLine, intentStands, parseWeek, proofLine, standsLines, trackConsequence, untrackText, dimColour, filterWork, personColours } from './home.mjs'
14import { issueId, issueLink, issueOrder, issuePrompt, parseIssues } from './issues.mjs'
15import { parsePrState, prsToRead } from './prs.mjs'
16import { STAGE_LABELS, aboutIntentPrompt, clockText, closestWord, currentStage, cutWords, directorCalls, localMinutes, nextStep, otherRoot, parseIntent, plural, searchIntents } from './model.mjs'
17import { unreal } from './packs/unreal.mjs'
18import * as state from './state.mjs'
19import { awayHours, warmBadge, warmPaneText } from './warm.mjs'
20import * as warmStore from './warm-store.mjs'
21import { crewOf } from './crew.mjs'
22import { crewSections } from './crew-rows.mjs'
23import { homeDir, resetTranscripts, sessionName } from './transcripts.mjs'
24import { recordEnd } from './workers.mjs'
25import { endLoop } from './inflight.mjs'
26import { EMPTY_CACHE, GIT_ENV, NO_SYNC, canFetchNow, fetchMain, isFetchDue, readTeam, syncError, syncSummary, syncText } from './team.mjs'
27import { checkoutNames, checkoutOf, normalFolder } from './workspace.mjs'
28import { overlapJob } from './overlap.mjs'
29import { checkBranch, isSameCheck } from './collide.mjs'
30import { forBase } from './guards.mjs'
31import { withFolders } from './shell.mjs'
32import { nextGroup, nextSort } from './worklist.mjs'
33import { LIME, QUIET, choiceRow, findingRows, fit, homePreview, label, masthead, mergeRow, metaRow, needsRows, section, stageRow, statusLine, summaryStrip } from './rows.mjs'
34import { awayPaneRows, awayRows, awayWindowRows, createRows, intentRows, issueRows, pickRows, skillsRows } from './modes.mjs'
35import { DECIDED_SHOWN_MS, FRESH_ANSWERS, callId, needsView, pruneDecided, withDecided } from './decide.mjs'
36import { NO_PLACE, appSessionOf, appTool, createGuesses, createOutbox, isSentReply, placeOf, routedText, toldText } from './handoff.mjs'
37import { openWith } from './opener.mjs'
38
39/** @typedef {import('claude-code').EngineInterface} Engine */
40/** @typedef {'home' | 'pick' | 'away' | 'skills' | 'issue' | 'intent' | 'create' | 'finding'} Mode */
41/** @typedef {ReturnType<typeof buildHome> & { sync: import('./team.mjs').Sync }} Home */
42/** @typedef {import('./home.mjs').Item} Item */
43/** @typedef {import('./home.mjs').Next} Next */
44/** @typedef {import('./home.mjs').Work} Work */
45
46const PANE_ID = 'ather'
47// The pane's rows when it opens (Heading off? asks for more with a long list: modes.mjs awayPaneRows).
48const PANE_ROWS = 22
49// The band's words when it has nothing else to say.
50const NAME = '◆ Ather Automata'
51// Queued work goes out after the command hook returns: a hook holds the turn,
52// and the engine refuses a prompt queued from inside it.
53const AFTER_HOOK_MS = 50
54// The drawn view is rebuilt when shared state changes, and at least this often for the lock file and workers.
55const VIEW_TTL_MS = 15000
56// GitHub is read in the background at this pace; a prompt never waits on it.
57const ISSUES_EVERY_MS = 15 * 60 * 1000
58
59let cwd = ''
60let me = ''
61/** @type {import('./model.mjs').Intent[]} */
62let intents = []
63// Items handed to the session in this session, shown as sent instead of offered twice.
64const sent = new Set()
65// Those the session does not have yet (handoff.mjs): a press while a turn runs waits for the turn's end.
66const outbox = createOutbox()
67// The model turn running now in the main conversation ('' between turns), as turn.start named it.
68let turnRunning = ''
69// Another of the person's live sessions, which tracks the intent a press is about (`slug`, in its checkout).
70/** @typedef {Extract<import('./handoff.mjs').Place, { kind: 'other' }>} Target */
71// Where each intent with a decision waiting is worked on (handoff.mjs placeOf), by its key, as last read.
72/** @type {Map<string, import('./handoff.mjs').Place>} */
73let places = new Map()
74// The guesses for intents no live session tracks (A3b, A7), each asked of the app at most every ten minutes.
75const guesses = createGuesses()
76let paneMode = /** @type {Mode} */ ('home')
77// Heading off?: the live sessions of this checkout as last read when it opened (away.mjs awaySessions), and the ids ticked.
78/** @type {import('./away.mjs').AwaySession[]} */
79let awayList = []
80/** @type {Set<string>} */
81let awayTicked = new Set()
82// Create groups opened past their first three.
83/** @type {Set<string>} */
84const createOpen = new Set()
85// Intent changes after this were not seen yet: they make the band's notice.
86let intentSeenAt = 0
87// The issue whose card is open (paneMode 'issue'), and the view to go back to.
88let issueShown = ''
89let issueBack = /** @type {'home' | 'pick'} */ ('home')
90// The intent whose view is open (paneMode 'intent'; its key, '' for the tracked one), and the view to go back to.
91let intentShown = ''
92let intentBack = /** @type {'home' | 'pick'} */ ('home')
93// The "Everything open" list: the words searched, its sort, how the teammates' intents are grouped
94// (read from the person's stored choice once a session), and the heads pressed to fold or unfold.
95let pickQuery = ''
96let pickSort = /** @type {import('./worklist.mjs').Sort} */ ('recent')
97// A choice remembered for the person (Group, Home's view): read from the store once a session; a press
98// made before the read lands is not undone by it.
99/** @template T @param {T} initial @param {(io: import('./state.mjs').Io, me: string) => Promise<T>} read @param {(io: import('./state.mjs').Io, me: string, value: T) => Promise<unknown>} write */
100const remembered = (initial, read, write) => {
101 let value = initial
102 let isRead = false
103 let presses = 0
104 return {
105 get value() {
106 return value
107 },
108 reset() {
109 value = initial
110 isRead = false
111 },
112 /** @param {import('./state.mjs').Io} store */
113 async readOnce(store) {
114 if (isRead) return
115 const before = presses
116 const stored = await read(store, me).catch(() => value)
117 if (presses === before) value = stored
118 isRead = true
119 },
120 /** @param {import('./state.mjs').Io} store @param {T} next */
121 pick(store, next) {
122 value = next
123 presses += 1
124 isRead = true
125 return write(store, me, next).catch(() => undefined)
126 },
127 }
128}
129const pickGroup = remembered(/** @type {import('./worklist.mjs').GroupBy} */ ('person'), state.readGroupBy, state.setGroupBy)
130const homeView = remembered(/** @type {import('./home.mjs').PaneView} */ ('advanced'), state.readPaneView, state.setPaneView)
131/** @type {Set<string>} */
132const pickFolded = new Set()
133// Needs you's intents opened to show each of their decisions.
134/** @type {Set<string>} */
135const callsOpen = new Set()
136// Answering in place (0.2.0, decide.mjs AnswerState): kept in this session only; this session's answers
137// stay until the files read them resolved. Then two view fields: the finding Open findings shows, and
138// whether Search's field is open.
139/** @type {import('./decide.mjs').AnswerState} */
140let answerState = { ...FRESH_ANSWERS }
141let findingShown = ''
142let isSearchOpen = false
143// Per checkout root: what the last read of its team's intents learned (team.mjs reads each part again
144// only when it moved), and where its background fetch stands. Both, and `intents`, change together, in readIntents.
145/** @type {Map<string, import('./team.mjs').TeamCache>} */
146const teamCaches = new Map()
147/** @type {Map<string, import('./team.mjs').Sync>} */
148const syncs = new Map()
149// Per checkout root, a fetch that ended (the `count`th), for the first read that began after it to apply with what it brought in.
150/** @type {Map<string, { count: number, sync: Partial<import('./team.mjs').Sync> }>} */
151const fetched = new Map()
152let fetchesEnded = 0
153// A fetch is running: one at a time over every checkout.
154let isSyncing = false
155// The pane's checkouts, as last read (paneLanes): the workspace checkouts that have intents.
156/** @type {import('./state.mjs').Checkout[]} */
157let checkouts = []
158// The workspace checkouts other than the session's own, read once per session (null: the session folder is in
159// no checkout, so there is no workspace): a read git could not answer in full is not kept, so the next one asks again.
160/** @type {Promise<string[] | null> | null} */
161let otherRoots = null
162// The read running now (resolving whether it drew again), and whether another was asked for while it ran.
163/** @type {Promise<boolean> | null} */
164let reading = null
165let isRereadAsked = false
166// The pane has been drawn: from then on the fetch runs on its own, at most every ten minutes.
167let isDrawn = false
168/** @type {{ name: string, description: string }[]} */
169let skills = []
170// The band's ✕: hidden until it has something new to say.
171let closedHint = /** @type {string | null} */ (null)
172let isIssuesWarned = false
173let isWhoWarned = false
174let issueRetries = 0
175// A PR read is running: the minute's refresh does not start a second.
176let isPrsReading = false
177// The ↻ button: true while a refresh it started is running.
178let isIssuesRefreshing = false
179/** @type {Promise<void> | null} */
180let isAwake = null
181// The view model (home), built or being built, by the state version and stale count it was begun at.
182/** @type {{ key: string, at: number, model: Promise<Home> } | null} */
183let view = null
184// What the last read of the intents found (readIntents), as text: a read that finds the same draws nothing again.
185let readPrint = ''
186// The band's hint as last drawn (bandOf); null while the band is not Ather's to draw (a survey shows).
187/** @type {string | null} */
188let bandDrawn = null
189// How many times the view was marked stale: a view begun before is built again.
190let staled = 0
191// The pack whose words the pane uses (packs/index.mjs, wordsLane); set whenever the view is rebuilt.
192/** @type {import('./packs/index.mjs').Pack} */
193let pack = unreal
194// The branch that lane's team merges into, for the pane's words about what waits.
195let paneBase = 'main'
196
197// The store, files and session as closures: `$` cannot be handed to state.mjs itself.
198/** @param {Engine} $ @returns {import('./state.mjs').Io} */
199function io($) {
200 return {
201 get: key => $.store.get(key),
202 set: (key, value) => $.store.set(key, value),
203 remove: key => $.store.delete(key),
204 keys: () => $.store.keys(),
205 read: path => $.fs.read(path).then(text => (typeof text === 'string' ? text : null), () => null),
206 write: (path, text) => $.fs.write(path, text),
207 exists: path => $.fs.exists(path).catch(() => false),
208 sessionId: () => $.session.id(),
209 root: () => $.session.root(),
210 gitUser: async root => ((await $.process.run(['git', 'config', 'user.name'], { cwd: root || cwd || (await $.session.root()), timeoutMs: 10000 })).stdout ?? '').trim(),
211 gitEmail: async root => ((await $.process.run(['git', 'config', 'user.email'], { cwd: root || cwd || (await $.session.root()), timeoutMs: 10000 })).stdout ?? '').trim(),
212 redraw: () => $.ui.invalidate('ui.render'),
213 list: path => $.fs.list(path),
214 origin: root => readOrigin($, root),
215 repo: async () => (await laneOf($)).repo,
216 real: async folder => (await $.fs.stat(folder, { resolve: true })).realPath ?? folder,
217 worktrees: root => readWorktrees($, root),
218 }
219}
220
221// The origin URL of the checkout at `root` ('' without one), or null when git could not say: the lane asks again.
222/** @param {Engine} $ @param {string} root @returns {Promise<string | null>} */
223async function readOrigin($, root) {
224 const run = await $.process.run(['git', 'config', '--get', 'remote.origin.url'], { cwd: root, env: GIT_ENV, timeoutMs: 10000 }).catch(() => undefined)
225 // Exit 1: no such key.
226 return run?.exitCode === 0 ? (run.stdout ?? '').trim() : run?.exitCode === 1 ? '' : null
227}
228
229// What `git worktree list --porcelain` prints in the checkout at `root` ('' when git refused), or null when git
230// could not say (the app aborted the run, it ran out of time): the workspace asks again.
231/** @param {Engine} $ @param {string} root @returns {Promise<string | null>} */
232async function readWorktrees($, root) {
233 const run = await $.process.run(['git', 'worktree', 'list', '--porcelain'], { cwd: root, env: GIT_ENV, timeoutMs: 10000 }).catch(() => undefined)
234 return run === undefined ? null : run.exitCode === 0 ? (run.stdout ?? '') : ''
235}
236
237// Git and the checkout's files for team.mjs: git runs in `root` with GIT_ENV. A run the app took back (the hook
238// call that started it was abandoned) is marked: the engine rejects it with a message ending in "aborted".
239/** @param {Engine} $ @param {string} root @returns {import('./team.mjs').Repo} */
240function repo($, root) {
241 return {
242 git: (args, { stdin, timeoutMs = 120000 } = {}) =>
243 $.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)) })),
244 read: path => $.fs.read(path).then(text => (typeof text === 'string' ? text : null), () => null),
245 list: path => $.fs.list(path),
246 mtime: path => $.fs.stat(path).then(stat => stat.mtimeMs, () => 0),
247 real: async folder => (await $.fs.stat(folder, { resolve: true })).realPath ?? folder,
248 }
249}
250
251// What transcripts.mjs and crew.mjs need of the engine.
252/** @param {Engine} $ @returns {import('./transcripts.mjs').Host} */
253function host($) {
254 return {
255 home: async () => (await $.env.get('USERPROFILE')) || (await $.env.get('HOME')) || '',
256 configDir: async () => (await $.env.get('CLAUDE_CONFIG_DIR')) || '',
257 list: path => $.fs.list(path),
258 read: path => $.fs.read(path).then(text => (typeof text === 'string' ? text : null), () => null),
259 exists: path => $.fs.exists(path).catch(() => false),
260 run: (argv, timeoutMs) => $.process.run(argv, { timeoutMs }).catch(() => undefined),
261 agents: () => $.agent.list().catch(() => []),
262 }
263}
264
265/** @param {Engine} $ */
266function laneOf($) {
267 return state.lane(io($), cwd)
268}
269
270// The pane's checkouts: the workspace checkouts that have intents, in workspace order, the session's own
271// (its lane) first.
272/** @param {Engine} $ @returns {Promise<import('./state.mjs').Checkout[]>} */
273async function paneLanes($) {
274 return (await workspaceLanes($)).filter(lane => lane.isS2)
275}
276
277/** @param {Engine} $ @param {string} root the session lane's root @returns {Promise<string[] | null>} */
278async function readOtherRoots($, root) {
279 const files = io($)
280 const own = new Set([normalFolder(root), normalFolder((await checkoutOf(files, root)) ?? root)])
281 // From the session's root, not the shell's folder: a `cd` before a resume must not move the workspace.
282 const { roots, isSure } = await state.workspace(files, root || cwd, line => $.ui.log(line, { to: 'debug' }))
283 if (!isSure) otherRoots = null
284 if (roots.length === 0) return null
285 // The session's lane is its folder's, which may be inside its checkout.
286 return roots.filter(one => !own.has(normalFolder(one)))
287}
288
289// The lane an intent's checkout has in the pane (the session's for its own).
290/** @param {Engine} $ @param {string} root */
291async function laneFor($, root) {
292 return checkouts.find(one => normalFolder(one.root) === normalFolder(root)) ?? (await laneOf($))
293}
294
295// The lane of the checkout a worker's shell command runs in: its last segment's, as its proof is read (watch.mjs afterShell).
296/** @param {Engine} $ @param {string} command */
297async function commandLane($, command) {
298 return (await state.folderLane(io($), await laneOf($), withFolders(command).at(-1)?.folder ?? null)).lane
299}
300
301// The lane whose pack gives the pane its words (Next, Create, Prove, the role): the tracked intent's
302// checkout, else the session's own when it has intents, else the first pane checkout.
303/** @param {Engine} $ */
304async function wordsLane($) {
305 const tracked = await state.trackedLane(io($), cwd)
306 const session = await laneOf($)
307 return tracked ? tracked.lane : session.isS2 ? session : (checkouts[0] ?? session)
308}
309
310// Whether a pane checkout is the session's own (the session lane is read again until git's answers are sure,
311// so it is matched by root, not by object).
312/** @param {import('./state.mjs').Checkout} session @param {import('./state.mjs').Checkout} lane */
313function isOwnLane(session, lane) {
314 return session.isS2 && normalFolder(lane.root) === normalFolder(session.root)
315}
316
317// An intent's key in the pane: its slug in the session's own checkout, `<its checkout's short name>/<slug>` in another.
318/** @param {string} name @param {boolean} isOwn @param {string} slug */
319function keyOf(name, isOwn, slug) {
320 return isOwn ? slug : `${name}/${slug}`
321}
322
323// The short name of each checkout the pane works with, by its folder: the workspace's checkouts in order, then
324// the tracked intent's when it is outside them. Each is different (checkoutNames), so keys and lookups by name agree;
325// the workspace's never change in a session, whatever is tracked, so a key built earlier still names its intent.
326/** @param {Engine} $ @returns {Promise<Map<string, string>>} */
327async function laneNames($) {
328 const lanes = await workspaceLanes($)
329 const tracked = await state.trackedLane(io($), cwd)
330 const outside = tracked && !lanes.some(one => normalFolder(one.root) === normalFolder(tracked.lane.root)) ? [tracked.lane] : []
331 const names = checkoutNames(lanes, outside)
332 return new Map([...lanes, ...outside].map((lane, at) => [normalFolder(lane.root), names[at] ?? '']))
333}
334
335/** @param {Engine} $ @param {import('./state.mjs').Checkout} lane */
336async function shortName($, lane) {
337 return (await laneNames($)).get(normalFolder(lane.root)) ?? ''
338}
339
340// The tracked intent's key, '' when nothing is tracked.
341/** @param {Engine} $ */
342async function trackedKey($) {
343 const tracked = await state.trackedLane(io($), cwd)
344 if (!tracked) return ''
345 return tracked.isOwn ? tracked.slug : keyOf(await shortName($, tracked.lane), false, tracked.slug)
346}
347
348/** @param {Engine} $ */
349async function hasIntents($) {
350 return (await paneLanes($)).length > 0
351}
352
353/** @param {import('claude-code').On} on */
354export function register(on) {
355 // A repository set up in this session: the console's work, skipped at the start, begins with the next wake.
356 // Where another checkout's intents began it already, it goes on and reads the new ones.
357 state.onSetUp('console', () => {
358 if (checkouts.length === 0) isAwake = null
359 })
360
361 // The desktop app runs sessions the way the SDK does: not interactive at start, no surface yet.
362 // So the commands are registered in every session, and the work behind the console (reading
363 // intents and issues on timers) starts the first time someone draws or uses it, never in a
364 // scripted run nobody watches.
365 on('session.start', { isInteractive: true }, async ($, e, next) => {
366 const result = await next(e)
367 await openConsole($, e.cwd)
368 await wake($)
369 return result
370 })
371
372 on('session.start', { isInteractive: false }, async ($, e, next) => {
373 const result = await next(e)
374 await openConsole($, e.cwd)
375 return result
376 })
377
378 // A prompt handed over while a turn runs is queued by the engine until the turn ends: the pane says so.
379 on('turn.start', async ($, e, next) => {
380 turnRunning = e.turnId
381 return next(e)
382 })
383
384 on('turn.complete', async ($, e, next) => {
385 if (!e.agentId && e.turnId === turnRunning) turnRunning = ''
386 if (!e.agentId) outbox.idle()
387 const result = await next(e)
388 // Read again in the background: the turn's end never waits on git.
389 if (!e.agentId && (await hasIntents($))) void refresh($).catch(() => undefined)
390 // A worker's turn ended: it finished now, not when the pane is next drawn.
391 if (e.agentId) recordEnd(e.agentId, Date.now())
392 // Its turn is over: nothing in its loop is in flight, whatever did not settle.
393 if (e.agentId) endLoop(e.agentId)
394 if (e.agentId) $.ui.invalidate('ui.render')
395 return result
396 })
397
398 on('command.run', { command: 'ather' }, async ($, e) => {
399 // A checkout without intents is read again: the person may have added them in this session. The
400 // pack's sentence is for a pane that would have nothing: another workspace checkout's intents open it.
401 await state.laneAgain(io($), cwd)
402 if (!(await hasIntents($))) return { text: (await laneOf($)).pack.notHere }
403 await wake($)
404 await refresh($).catch(() => undefined)
405 return { text: await atherCommand($, e.args.trim()) }
406 })
407
408 on('command.run', { command: 'away' }, async ($, e) => {
409 if (!(await hasIntents($))) return { text: (await laneOf($)).pack.notHere }
410 await wake($)
411 return { text: await awayCommand($, e.args.trim()) }
412 })
413
414 // Ather's own questions reach the dialog as labels ($.ui.ask): each choice gets back what it does before it is
415 // drawn, and a dialog that closed by itself is noted, since its result alone says so.
416 on('tool.call', { tool: 'AskUserQuestion' }, async ($, e, next) => {
417 if (next.origin.plugin !== $.plugin.name) return next(e)
418 const ran = await next({ ...e, questions: e.questions.map(question => ({ ...question, options: question.options.map(option => ({ ...option, description: option.description || describe(question.question, option.label) })) })) })
419 const result = /** @type {{ afkTimeoutMs?: unknown } | undefined} */ (ran.result)
420 for (const question of result?.afkTimeoutMs === undefined ? [] : e.questions) {
421 const open = asking.get(question.question)
422 if (open) open.isIdle = true
423 }
424 return ran
425 })
426
427 // Drawings of one site leave their hook in the order they were asked for (inOrder).
428 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => inOrder(e, next.signal, drawBand($, e).then(tree => tree ?? next(e))))
429
430 // Ather's own pane only (PANE_ID): a matcher without it would have every invalidate of Ather's redraw every
431 // plugin's pane, and lose the presses on its way there (see redrawAged).
432 on('ui.render', { component: 'Pane', requestId: 'ather' }, async ($, e, next) => inOrder(e, next.signal, drawPane($, e)))
433
434 on('ui.close', ($, e, next) => {
435 if (e.id === PANE_ID) {
436 // Only the view resets: this session's answers stay.
437 paneMode = 'home'
438 isSearchOpen = false
439 answerState = { ...answerState, typing: '' }
440 }
441 return next(e)
442 })
443}
444
445// ---------------------------------------------------------------- drawing
446
447// Each drawing of a site (the band, the pane) leaves its hook in the order it was asked for. Claude Code stamps a
448// drawing's press handles as it leaves the hook and retires the ones before them, while a surface shows the drawing
449// it asked for last. Drawings run side by side: one that read more (the Intent view's files) could leave after a
450// newer one, and then the only live handles would be in a drawing no surface shows, and every press there is lost.
451/** @type {Map<string, Promise<unknown>>} */
452const drawings = new Map()
453
454// `signal`: the hook's own (next.signal), aborted once the engine goes on without it.
455/** @template T @param {{ component: string, requestId: string }} e @param {AbortSignal} signal @param {Promise<T>} drawing @returns {Promise<T>} */
456function inOrder(e, signal, drawing) {
457 const site = `${e.component}:${e.requestId}`
458 const before = drawings.get(site) ?? Promise.resolve()
459 // Its turn is over once it ends, either way, or once the engine has gone on without it: watched from now on, so
460 // one that fails while it waits is never an unhandled rejection, and one given up on holds up none after it.
461 const done = new Promise(resolve => {
462 void drawing.then(resolve, resolve)
463 if (signal.aborted) resolve(undefined)
464 else signal.addEventListener('abort', () => resolve(undefined), { once: true })
465 })
466 drawings.set(site, before.then(() => done))
467 return before.then(() => drawing)
468}
469
470// The band above the prompt; null when it is not Ather's to draw (a survey shows, no intents, closed with ✕).
471/** @param {Engine} $ @param {import('claude-code').Frozen<import('claude-code').RenderInput<'AbovePrompt'>>} e */
472async function drawBand($, e) {
473 if (e.props.hasSurvey || !(await hasIntents($))) {
474 bandDrawn = null
475 return null
476 }
477 void wake($)
478 const { model, fresh, hint } = await bandOf($)
479 bandDrawn = hint
480 // Closed with ✕: stays away until there is something new to say.
481 if (closedHint !== null && (hint === '' || hint === closedHint)) return null
482 closedHint = null
483 const { Box, Text, Button } = $.ui.resolve(e)
484 const isAway = model.header.stage === 'Away'
485 // What needs you, in cyan; else the tracked intent's pill (ship-pill D2); else Ather's name, dim.
486 const words = hint || model.header.pill || NAME
487 const warm = warmBadge(warmStore.readWarmView())
488 return Box({
489 flexDirection: 'row',
490 gap: 2,
491 children: [
492 Box({ key: 'ather-band-words', flexGrow: 1, children: [Text({ color: hint ? 'cyan' : undefined, dimColor: words === NAME ? true : undefined, wrap: 'truncate', children: words })] }),
493 ...(fresh.length > 0 ? [Button({ key: 'ather-intent-see', label: 'See', plain: true, onPress: () => void seeIntent($) })] : []),
494 Button({ key: 'ather-away', label: '☾', plain: true, dimColor: isAway ? undefined : true, onPress: () => void openPane($, 'away') }),
495 // Keep the prompt cache warm while idle: on or off for this session; the count of reads, in amber, while one is due.
496 Box({ key: 'ather-warm', flexDirection: 'row', gap: 1, children: [
497 Button({ key: 'ather-warm-toggle', label: warm.label, plain: true, dimColor: warm.isDim ? true : undefined, onPress: () => void pressWarm($) }),
498 ...(warm.count ? [Box({ key: 'ather-warm-count', children: [Text({ color: 'yellow', children: warm.count })] })] : []),
499 ] }),
500 Button({ key: 'ather-open', label: '⤢', plain: true, dimColor: true, onPress: () => void openPane($, 'home') }),
501 Button({ key: 'ather-close', label: '✕', plain: true, dimColor: true, role: 'dismiss', onPress: () => {
502 closedHint = hint
503 intentSeenAt = Date.now()
504 $.ui.invalidate('ui.render')
505 $.ui.toast('Ather hidden until something needs you. /ather brings it back.')
506 } }),
507 ],
508 })
509}
510
511/** @param {Engine} $ @param {import('claude-code').Frozen<import('claude-code').RenderInput<'Pane'>>} e */
512async function drawPane($, e) {
513 void wake($)
514 isDrawn = true
515 void syncMain($)
516 if (paneMode === 'intent') await readIntentView($)
517 if (paneMode === 'pick') await pickGroup.readOnce(io($))
518 await homeView.readOnce(io($))
519 return paneView($.ui.resolve(e), $, await home($), e.props.bodyColumns ?? 80, e.surface, await crewOf(host($), (await laneOf($)).root, await state.sessionId(io($)), (await laneOf($)).pack, command => commandLane($, command)))
520}
521
522// ---------------------------------------------------------------- starting
523
524// Every session: fresh module state and the two commands.
525/** @param {Engine} $ @param {string} folder */
526async function openConsole($, folder) {
527 sent.clear()
528 outbox.reset()
529 // No turn has been seen to start in this session yet: one already running shows a late prompt as queued (LATE_MS).
530 turnRunning = ''
531 paneMode = 'home'
532 isIssuesWarned = false
533 isWhoWarned = false
534 issueRetries = 0
535 resetTranscripts()
536 isAwake = null
537 view = null
538 readPrint = ''
539 bandDrawn = null
540 closedHint = null
541 intentSeenAt = Date.now()
542 intentShown = ''
543 intentBack = 'home'
544 pickQuery = ''
545 pickSort = 'recent'
546 pickFolded.clear()
547 pickGroup.reset()
548 homeView.reset()
549 callsOpen.clear()
550 answerState = { ...FRESH_ANSWERS }
551 guesses.reset()
552 findingShown = ''
553 isSearchOpen = false
554 teamCaches.clear()
555 syncs.clear()
556 fetched.clear()
557 isSyncing = false
558 checkouts = []
559 otherRoots = null
560 fetchesEnded = 0
561 isDrawn = false
562 createOpen.clear()
563 cwd = folder
564 for (const command of [
565 { name: 'ather', description: 'Ather Automata: what needs you, and what is next', argumentHint: '[pick | find <words> | issues | issue <number> | tour | skip | role <role> | checked | intent <name> | untrack]' },
566 { name: 'away', description: 'Ather Automata: going away? hand over with full autonomy, decisions recorded', argumentHint: '[tonight | 8h | 30m | until 9am | until done] [all | in <session>, <session> [only]:] [goal] | stop' },
567 ]) {
568 // One refused command must not take the other, or anything after, with it.
569 await $.command.register(command).catch(error => $.ui.log(`Ather console: /${command.name} not registered: ${String(error)}`, { to: 'debug' }))
570 }
571}
572
573// Once someone is there (a REPL start, the first draw, the first command): read intents and
574// issues, keep them fresh, and tell a newcomer about the tour. Runs once per session.
575/** @param {Engine} $ @returns {Promise<void>} */
576function wake($) {
577 if (!isAwake) isAwake = startConsoleWork($).catch(error => $.ui.log(`Ather console: start failed: ${String(error)}`, { to: 'debug' }))
578 return isAwake
579}
580
581/** @param {Engine} $ */
582async function startConsoleWork($) {
583 const lane = await laneOf($)
584 await state.workspace(io($), lane.root || cwd, line => $.ui.log(line, { to: 'debug' }))
585 if (lane.me !== '') me = lane.me
586 pack = lane.pack
587 paneBase = lane.base
588 if (!(await hasIntents($))) return
589 await refresh($)
590 // The minute's read; when it drew nothing again, what time alone changed.
591 $.clock.every(60000, () => void refresh($).then(drew => (drew ? undefined : redrawAged($))).then(() => (isDrawn ? syncMain($) : undefined)).catch(() => undefined))
592 // The worker clock, and the fetches still due once the pane has been drawn: one the app took back with the draw
593 // that started it is asked again here.
594 $.clock.every(5000, () => {
595 if (isDrawn) void syncMain($).catch(() => undefined)
596 void redrawWorkers($).catch(() => undefined)
597 })
598 // watch.mjs may pick up last night's window just after this; show it.
599 $.clock.after(1500, () => void refresh($).catch(() => undefined))
600 void refreshIssues($).catch(() => undefined)
601 $.clock.every(ISSUES_EVERY_MS, () => void refreshIssues($).catch(() => undefined))
602 if ((await home($)).isNewcomer && !(await state.readProfile(io($), me)).isNudged) {
603 $.ui.toast(pack.prompts.tourToast, { timeoutMs: 12000 })
604 await state.setProfile(io($), me, { isNudged: true })
605 }
606}
607
608// ---------------------------------------------------------------- the view model
609
610// Re-reads the intents (origin/main's and this checkout's, team.mjs), one read at a time: a call while
611// one runs asks for one more after it and waits for that, so the last read to land is the newest.
612// The rest comes from shared state when the view is rebuilt. Resolves whether a read drew again.
613/** @param {Engine} $ @returns {Promise<boolean>} */
614function refresh($) {
615 if (reading) {
616 isRereadAsked = true
617 return reading
618 }
619 reading = (async () => {
620 let drew = false
621 try {
622 do {
623 isRereadAsked = false
624 drew = (await readIntents($)) || drew
625 } while (isRereadAsked)
626 } finally {
627 reading = null
628 }
629 void checkCollision($).catch(error => $.ui.log(`Ather: the overlap check failed: ${String(error)}`, { to: 'debug' }))
630 return drew
631 })()
632 return reading
633}
634
635/** @param {Engine} $ @returns {Promise<boolean>} whether it drew again */
636async function readIntents($) {
637 // Only a fetch that ended before this read began is applied with what this read finds.
638 const seen = fetchesEnded
639 const session = await laneOf($)
640 if (session.me !== me) stale()
641 me = session.me
642 const files = io($)
643 const lanes = await paneLanes($)
644 const tracked = await state.readTracked(files)
645 const names = await laneNames($)
646 const read = []
647 // What the first pane checkout on each base read of it: the other worktrees on the same base share it, and
648 // list only their own. A worktree whose team merges into another branch reads that branch for itself.
649 /** @type {Map<string, import('./team.mjs').MainSnapshot | null>} */
650 const mains = new Map()
651 for (const lane of lanes) {
652 const { root, pack: its, base } = lane
653 const isOwn = isOwnLane(session, lane)
654 const name = names.get(normalFolder(root)) ?? ''
655 // Its intents: one tracked in another checkout is not one of them.
656 const pinned = tracked && normalFolder(tracked.root) === normalFolder(root) ? tracked.slug : null
657 const isFirst = !mains.has(base)
658 const kept = teamCaches.get(root) ?? EMPTY_CACHE
659 const team = await readTeam(repo($, root), root, { cache: isFirst ? kept : { ...kept, main: mains.get(base) ?? kept.main }, pinned, base })
660 if (isFirst) mains.set(base, team.cache.main)
661 const tag = { root, repo: lane.repo, repoName: name, base }
662 for (const one of isFirst ? team.intents : team.intents.filter(listed => listed.source === 'local')) read.push(parseIntent({ ...one, ...tag, key: keyOf(name, isOwn, one.slug), hasDebrief: one.slug === pinned && (await files.exists(`${root}/${its.debriefPath(one.slug)}`)) }, its))
663 const ended = fetched.get(root)
664 const isApplied = ended !== undefined && ended.count <= seen
665 if (isApplied) fetched.delete(root)
666 teamCaches.set(root, team.cache)
667 syncs.set(root, { ...(syncs.get(root) ?? NO_SYNC), ...(isApplied ? ended.sync : {}), isRepo: team.isRepo, hasMain: team.cache.main !== null, base })
668 }
669 checkouts = lanes
670 intents = read.sort((a, b) => b.updatedAt - a.updatedAt)
671 places = await readPlaces($)
672 // This session's answers to decisions are kept until the files read them resolved; an answer to
673 // anything else (a rule) has no file to settle it, so it stays for the session.
674 const waiting = new Set(intents.flatMap(one => directorCalls(one).map(finding => callId(one.key, finding.id))))
675 answerState = { ...answerState, decided: pruneDecided(answerState.decided, id => waiting.has(id) || !id.startsWith('call:'), Date.now()) }
676 const { root, pack: chosen, base: its } = await wordsLane($)
677 pack = chosen
678 paneBase = its
679 // The listed skills that exist here, each with the first sentence of its own description.
680 const found = []
681 for (const name of new Set([...chosen.skillGroups.flatMap(one => one.names), ...chosen.createGroups.flatMap(one => one.items.filter(item => !item.isGlobal).map(item => item.name))])) {
682 const text = await files.read(`${root}/${skillFolder(name)}/SKILL.md`)
683 if (text === null) continue
684 const description = (/^description:\s*(.+)$/m.exec(text)?.[1] ?? '').trim().replace(/^["']|["']$/g, '')
685 found.push({ name, description: /^(.+?[.!?])(\s|$)/.exec(description)?.[1] ?? description })
686 }
687 skills = found
688 void refreshPrs($).catch(() => undefined)
689 // Drawn again only when the read found something new (see redrawAged): all a read sets that a drawing shows (the
690 // pack, the base and the checkouts follow from the intents and who is reading).
691 const print = JSON.stringify([me, intents, skills, syncShown(), [...places]])
692 if (print === readPrint) return false
693 readPrint = print
694 stale()
695 $.ui.invalidate('ui.render')
696 return true
697}
698
699// Whether the PRs of intents with every item met are merged, read with gh in the background.
700// Each PR is asked about at most once per PR_EVERY_MS, a merged one never again. Never writes to GitHub.
701/** @param {Engine} $ */
702async function refreshPrs($) {
703 if (isPrsReading) return
704 isPrsReading = true
705 try {
706 // Each checkout's intents: their PRs are its repository's, read with gh there.
707 for (const { root, repo: scope } of await paneLanes($)) {
708 const its = intents.filter(one => normalFolder(one.root) === normalFolder(root))
709 /** @type {Record<string, import('./model.mjs').PrState>} */
710 const read = {}
711 for (const number of prsToRead(its, await state.readPrRecords(io($), scope), Date.now())) {
712 const run = await $.process.run(['gh', 'pr', 'view', String(number), '--json', 'state,mergedAt'], { cwd: root, timeoutMs: 30000 }).catch(() => undefined)
713 read[number] = (run && run.exitCode === 0 ? parsePrState(run.stdout) : null) ?? 'UNREAD'
714 }
715 await state.setPrStates(io($), read, Date.now(), scope)
716 }
717 } finally {
718 isPrsReading = false
719 }
720}
721
722// Fetches the pane's origin main (its base, where the team merges into another branch) in the background (D2): once the pane is drawn, then at most
723// every ten minutes, or at once from ↻ (after a git lock, only at the next due time); one fetch at a time
724// over every checkout. The sync line says synced once the read after the fetch has landed; a failure keeps
725// the last list and says so. A fetch the app took back is no try: the sync stands as it stood and stays due.
726/** @param {Engine} $ @param {boolean} [isAsked] */
727async function syncMain($, isAsked = false) {
728 if (isSyncing) return
729 isSyncing = true
730 try {
731 const lanes = await paneLanes($)
732 for (const { root, base } of lanes) {
733 // A base is fetched once, in the first pane checkout on it: the outcome is that of every one of them.
734 const roots = lanes.filter(one => one.base === base).map(one => one.root)
735 if (roots[0] !== root) continue
736 const before = syncs.get(root) ?? NO_SYNC
737 if (!(isAsked ? canFetchNow : isFetchDue)(before, Date.now())) continue
738 for (const one of roots) syncs.set(one, { ...(syncs.get(one) ?? NO_SYNC), isFetching: true, triedAt: Date.now() })
739 stale()
740 $.ui.invalidate('ui.render')
741 const { error, lock, moved, isAborted } = await fetchMain(repo($, root), base)
742 const where = checkouts.length > 1 ? ` (${root})` : ''
743 if (isAborted) {
744 // No redraw here: a draw starts a fetch, and a newer draw is what takes one back.
745 for (const one of roots) syncs.set(one, { ...(syncs.get(one) ?? NO_SYNC), isFetching: false, triedAt: before.triedAt })
746 stale()
747 $.ui.log(`Ather: the app took the git fetch back${where}; it stays due.`, { to: 'debug' })
748 continue
749 }
750 $.ui.log(error ? `Ather: git fetch failed${where}: ${error}` : `Ather: origin/${base}${where} ${moved ? 'moved' : 'is up to date'}.`, { to: 'debug' })
751 fetchesEnded += 1
752 for (const one of roots) fetched.set(one, { count: fetchesEnded, sync: { isFetching: false, error, lock, ...(error ? { failedAt: Date.now() } : { fetchedAt: Date.now() }) } })
753 await refresh($).catch(() => undefined)
754 // The reads failed: the fetch's outcome is still said.
755 for (const one of roots) {
756 const ended = fetched.get(one)
757 if (!ended) continue
758 syncs.set(one, { ...(syncs.get(one) ?? NO_SYNC), ...ended.sync })
759 fetched.delete(one)
760 stale()
761 $.ui.invalidate('ui.render')
762 }
763 }
764 } finally {
765 isSyncing = false
766 }
767}
768
769// This checkout's own branch against origin's base (collision-alert), checked in the background after each read of
770// the intents (a turn's end, a fetch, /ather), one run at a time; Needs you and Home's merge line show what it last
771// found (ship-pill D1). Its own tip is compared, so commits not pushed yet count. Detached, on the base, or outside
772// git: nothing to check. A run that ran out of time leaves the last answer as it was.
773const collisions = overlapJob()
774/** @type {import('./collide.mjs').MergeCheck | null} */
775let merge = null
776
777/** @param {Engine} $ */
778async function checkCollision($) {
779 const { root, base } = await wordsLane($)
780 const key = await trackedKey($)
781 await checkBranch(repo($, root), collisions, { base, slug: intents.find(one => one.key === key)?.slug ?? '', owner: me }, found => showMerge($, found))
782}
783
784// What the check found, drawn again only when that changed; a check that found the same only moves "checked … ago".
785/** @param {Engine} $ @param {import('./collide.mjs').MergeCheck | null} found */
786function showMerge($, found) {
787 const isSame = isSameCheck(found, merge)
788 merge = found
789 if (isSame) return
790 stale()
791 $.ui.invalidate('ui.render')
792}
793
794// Where the pane's checkouts' fetches stand, as one: the sync line's.
795function syncShown() {
796 return syncSummary(checkouts.map(({ root }) => syncs.get(root) ?? NO_SYNC))
797}
798
799function stale() {
800 staled += 1
801}
802
803// The GitHub issues assigned to the person, read with gh. Without gh, or signed out, there are
804// simply none: one line in the debug log, never an error on screen. Never writes to GitHub.
805// The repository is read in the session's checkout, and its list kept under it.
806/** @param {Engine} $ @returns {Promise<string>} why the read failed, or '' when it worked */
807async function refreshIssues($) {
808 const { root, repo: scope } = await laneOf($)
809 const run = await $.process.run(['gh', 'issue', 'list', '--assignee', '@me', '--state', 'open', '--limit', '30', '--json', 'number,title,url,labels,updatedAt'], { cwd: root, timeoutMs: 30000 }).catch(() => undefined)
810 if (run && run.exitCode === 0) {
811 await state.setIssues(io($), me, parseIssues(run.stdout), scope)
812 issueRetries = 0
813 return ''
814 }
815 // Signed out: the last list may be stale, so none is shown.
816 if (/auth login|not logged in|authentication/i.test(run?.stderr ?? '')) await state.setIssues(io($), me, [], scope)
817 if (!isIssuesWarned) $.ui.log(`Ather: could not read your GitHub issues (is gh installed and signed in?) ${run?.stderr?.slice(0, 200) ?? ''}`, { to: 'debug' })
818 isIssuesWarned = true
819 // A slow first start or a network blip is tried again in a minute, three times at most:
820 // without gh at all, the 15-minute refresh is enough.
821 if (issueRetries < 3) {
822 issueRetries += 1
823 $.clock.after(60000, () => void refreshIssues($).catch(() => undefined))
824 }
825 return (run?.stderr || (run ? `gh exited with ${run.exitCode}` : 'gh could not be started (is it installed and on PATH?)')).trim().slice(0, 300)
826}
827
828// Every workspace checkout's lane, intents or not, the session's own first. A session folder in no checkout has
829// no workspace, whatever docs/intent it holds: no lane.
830/** @param {Engine} $ */
831async function workspaceLanes($) {
832 const session = await laneOf($)
833 if (!otherRoots) otherRoots = readOtherRoots($, session.root)
834 const roots = await otherRoots
835 if (roots === null) return []
836 const others = []
837 for (const root of roots) others.push(await state.laneAt(io($), root))
838 return [session, ...others]
839}
840
841// An issue as a checkout lists it: its key is its number in the session's own checkout and `<short name>#<number>` in another.
842/** @param {import('./issues.mjs').Issue} issue @param {import('./state.mjs').Checkout} lane @param {string} name @param {boolean} isOwn @returns {import('./issues.mjs').Issue} */
843function issueAt(issue, lane, name, isOwn) {
844 return { ...issue, root: lane.root, repo: lane.repo, repoName: name, key: isOwn ? String(issue.number) : `${name}#${issue.number}` }
845}
846
847// The assigned issues of the workspace's repository, each tagged with the session's checkout, which lists them.
848/** @param {Engine} $ @returns {Promise<import('./issues.mjs').Issue[]>} */
849async function paneIssues($) {
850 const session = await laneOf($)
851 const name = await shortName($, session)
852 return (await state.readIssues(io($), me, session.repo)).map(issue => issueAt(issue, session, name, true))
853}
854
855// Every pane checkout's PR states in one map: the session's own by number, another's by `<root>#<number>` (prKey).
856/** @param {Engine} $ @returns {Promise<import('./model.mjs').PrStates>} */
857async function panePrs($) {
858 const session = await laneOf($)
859 /** @type {Record<string, import('./model.mjs').PrState>} */
860 const all = {}
861 for (const lane of await paneLanes($)) {
862 const isOwn = normalFolder(lane.root) === normalFolder(session.root)
863 for (const [number, value] of Object.entries(await state.readPrStates(io($), lane.repo))) all[isOwn ? number : `${lane.root}#${number}`] = value
864 }
865 return all
866}
867
868// The view model, kept while shared state stands where it was when its build began and for VIEW_TTL_MS at most:
869// the drawings of one redraw (the band's, the pane's) share one build. A build that failed is not kept.
870/** @param {Engine} $ @returns {Promise<Home>} */
871function home($) {
872 const key = `${state.stateVersion()}:${staled}`
873 if (view?.key === key && Date.now() - view.at < VIEW_TTL_MS) return view.model
874 const kept = { key, at: Date.now(), model: buildView($) }
875 view = kept
876 kept.model.catch(() => {
877 if (view === kept) view = null
878 })
879 return kept.model
880}
881
882/** @param {Engine} $ @returns {Promise<Home>} */
883async function buildView($) {
884 const files = io($)
885 const { me: who } = await laneOf($)
886 // The tracked intent's checkout gives the stage its pack, the role and the Editor lock.
887 const { root, pack: chosen, base } = await wordsLane($)
888 pack = chosen
889 paneBase = base
890 if (who !== '') me = who
891 else if (!isWhoWarned && (isWhoWarned = true)) $.ui.log('Ather: git user.name could not be read; the pane treats nobody as you until it is.', { to: 'debug' })
892 const tz = await state.readTz(files)
893 const now = Date.now()
894 const away = await state.readAway(files)
895 const profile = await state.readProfile(files, me, chosen)
896 // The week-calendar plugin keeps this week's figures in ~/.calendar/latest.json.
897 const userHome = await homeDir(host($))
898 // The list and its sync line are taken together.
899 const sync = syncShown()
900 const built = buildHome({
901 intents,
902 pinned: (await trackedKey($)) || null,
903 me,
904 ...profile,
905 evidence: await state.readEvidence(files, await state.evidenceScope(files), chosen),
906 away,
907 ledger: away.phase === 'off' ? '' : ((await files.read(away.ledgerPath)) ?? ''),
908 lost: await state.readLost(files),
909 merge,
910 lock: await namedLock($, root, chosen.parseLock(chosen.lockFile ? await files.read(`${root}/${chosen.lockFile}`) : null, localMinutes(now, tz))),
911 recurring: await state.readRecurring(files, chosen),
912 issues: (await paneIssues($)).sort(issueOrder),
913 prs: await panePrs($),
914 week: userHome ? parseWeek(await files.read(`${userHome}/.calendar/latest.json`), now) : null,
915 last: await lastKey($),
916 sent: [...sent],
917 skills,
918 workers: (await $.agent.list().catch(() => [])).filter(agent => agent.status === 'running').length,
919 now,
920 tz,
921 pack: chosen,
922 })
923 return { ...built, sync }
924}
925
926// The intent the person last worked on, by key: the "Continue …" kept for each pane checkout,
927// the session's own first. With one checkout, its slug as kept.
928/** @param {Engine} $ */
929async function lastKey($) {
930 const session = await laneOf($)
931 if (checkouts.length <= 1 && session.isS2) return state.readLast(io($), me)
932 for (const lane of checkouts) {
933 const isOwn = isOwnLane(session, lane)
934 const slug = await state.readLast(io($), me, isOwn ? undefined : lane.root)
935 if (slug && intents.some(one => one.slug === slug && normalFolder(one.root) === normalFolder(lane.root))) return keyOf(await shortName($, lane), isOwn, slug)
936 }
937 return null
938}
939
940// A held lock that names a Claude session shows that session's name, as its tab shows it.
941/** @param {Engine} $ @param {string} root @param {import('./model.mjs').EditorLock} lock */
942async function namedLock($, root, lock) {
943 if (lock.state !== 'held' || !lock.session) return lock
944 const name = await sessionName(host($), root, lock.session).catch(() => '')
945 return { ...lock, holder: name ? `"${name}"` : `session ${lock.session}` }
946}
947
948// What the band above the prompt says: the tracked intent's changes this session has not shown, else what needs
949// you ('' for nothing). The hint is all it draws that changes with them (an away window's words say it is away).
950/** @param {Engine} $ */
951async function bandOf($) {
952 const model = await home($)
953 const fresh = model.header.stage === 'Away' || model.open.some(one => one.kind === 'review') ? [] : await unseenChanges($)
954 const hint = fresh.length > 0 ? `◆ Intent: ${fresh.slice(0, 2).map(one => one.text.split(' · ')[0].replace(/^./, first => first.toLowerCase())).join(' · ')}${fresh.length > 2 ? ` · +${fresh.length - 2}` : ''}` : bandHint(model)
955 return { model, fresh, hint }
956}
957
958// Claude Code gives each control a press handle per drawing, and a redraw hands out new ones: a desktop press
959// that names an older handle is answered "not handled" and lost. So Ather draws again only what changed: a read
960// that found something new (readIntents), a change to shared state (state.mjs), and the clocks below.
961
962// Once a minute, what time alone changes (ages such as "3m" and "synced 4 min ago", an Editor lock that lapsed),
963// read afresh: the pane is drawn again while it is up, the band only when its hint changed.
964/** @param {Engine} $ */
965async function redrawAged($) {
966 stale()
967 if (isPaneUp(await $.ui.panes()) || (bandDrawn !== null && (await bandOf($)).hint !== bandDrawn)) $.ui.invalidate('ui.render')
968}
969
970// A running worker's clock, every five seconds while Home shows it in the pane (the other views draw no workers).
971/** @param {Engine} $ */
972async function redrawWorkers($) {
973 const [panes, agents] = await Promise.all([$.ui.panes(), $.agent.list()])
974 // Asked after the reads: a press may have left Home meanwhile.
975 if (paneMode === 'home' && isPaneUp(panes) && agents.some(agent => agent.status === 'running')) $.ui.invalidate('ui.render')
976}
977
978/** @param {readonly import('claude-code').UiPane[]} panes */
979const isPaneUp = panes => panes.some(pane => pane.id === PANE_ID && pane.isShown)
980
981/** @param {Home} model */
982function bandHint(model) {
983 const { header } = model
984 if (header.stage === 'Away') return `🌙 Away ${header.progress} · ${header.sentence} · /ather`
985 if (model.open.some(one => one.kind === 'review')) return '☀ Welcome back · review the away window · /ather'
986 // Handed over while a turn runs: the session has not read it yet.
987 const queued = outbox.queued().length
988 if (queued > 0) return `⏳ ${queued === 1 ? 'Your press is' : `${queued} presses are`} queued until this turn ends · /ather`
989 const collide = model.open.find(one => one.kind === 'collide')
990 if (collide) return `▲ ${collide.question} · /ather`
991 if (model.isNewcomer) return '◆ New here? Take the tour'
992 if (model.open.length > 0) return `◆ ${header.title} · ${model.open.length} need${model.open.length === 1 ? 's' : ''} you · /ather`
993 return ''
994}
995
996// ---------------------------------------------------------------- handing things to the session
997
998// Resolves once the session has the prompt; never awaited from a command hook. If another
999// plugin refuses the timer it never settles: the item only looks sent in this session, and
1000// nothing persistent changes, because settling waits for delivery.
1001/** @param {Engine} $ @param {string} text @returns {Promise<void>} */
1002function deliver($, text) {
1003 return new Promise((resolve, reject) => {
1004 $.clock.after(AFTER_HOOK_MS, () => {
1005 $.prompt.submit({ text }).then(() => resolve(), reject)
1006 })
1007 })
1008}
1009
1010/** @param {Engine} $ @param {string} text */
1011function fill($, text) {
1012 $.clock.after(AFTER_HOOK_MS, () => {
1013 void $.prompt.fill({ text }).catch(error => $.ui.toast(`Ather: could not fill the prompt box: ${String(error)}`))
1014 })
1015}
1016
1017// What the outbox (handoff.mjs) needs of the engine, for one press.
1018/** @param {Engine} $ @returns {import('./handoff.mjs').Host} */
1019function outboxHost($) {
1020 return {
1021 submit: text => deliver($, text),
1022 after: (ms, run) => $.clock.after(ms, run),
1023 isBusy: () => turnRunning !== '',
1024 onChange: () => {
1025 stale()
1026 $.ui.invalidate('ui.render')
1027 },
1028 say: text => $.ui.toast(`Ather: ${text}`),
1029 log: line => $.ui.log(`Ather hand-off: ${line}`, { to: 'debug' }),
1030 }
1031}
1032
1033// The one way things go to the session: shown as sent, or as queued while a turn runs (the engine starts a
1034// prompt's turn only once the session is idle); `onDelivered` once the session has the prompt, offered
1035// again if delivery fails. A press for something that still waits sends nothing. Resolves what the press did.
1036/** @param {Engine} $ @param {readonly string[]} ids @param {string} text @param {() => Promise<unknown>} [onDelivered] @param {() => Promise<unknown>} [onFailed] */
1037function handOff($, ids, text, onDelivered, onFailed) {
1038 const handed = outbox.hand(outboxHost($), ids, text, onDelivered, async () => {
1039 for (const id of ids) sent.delete(id)
1040 await onFailed?.()
1041 })
1042 if (handed !== 'pending') for (const id of ids) sent.add(id)
1043 stale()
1044 return handed
1045}
1046
1047// To another of the person's sessions, by its id. The engine frames it there as a message from this session,
1048// in a turn of its own once that session is idle; `onDelivered` once it is queued there, offered again here
1049// when that session could not be reached. Resolves what the press says.
1050/** @param {Engine} $ @param {Target} target @param {readonly string[]} ids @param {string} text @param {() => Promise<unknown>} [onDelivered] @param {() => Promise<unknown>} [onFailed] */
1051async function sendTo($, target, ids, text, onDelivered, onFailed) {
1052 for (const id of ids) sent.add(id)
1053 stale()
1054 const result = await deliverTo($, target, routedText({ from: await ownName($), slug: target.slug, text }))
1055 $.ui.log(`Ather hand-off: to session ${target.sessionId} for intent ${target.slug}: ${result.isDelivered ? 'queued there' : `not delivered (${result.reason})`}`, { to: 'debug' })
1056 // What follows may take its time (an answered row settles after it has shown): the press does not wait on it.
1057 if (result.isDelivered) void Promise.resolve().then(() => onDelivered?.()).catch(error => $.ui.log(`Ather hand-off: after the send to ${target.sessionId}: ${String(error)}`, { to: 'debug' }))
1058 else {
1059 for (const id of ids) sent.delete(id)
1060 await onFailed?.()
1061 }
1062 stale()
1063 $.ui.invalidate('ui.render')
1064 return result.isDelivered ? `sent to ${target.name}, which tracks ${target.slug}. It reads it once its own turn ends.` : `could not reach ${target.name}: ${result.reason}. Nothing was sent; press it again to try once more.`
1065}
1066
1067// This session as another reads it: its app title, else its tab's name, else its short id; quoted.
1068/** @param {Engine} $ */
1069async function ownName($) {
1070 const own = await state.sessionId(io($))
1071 return `"${state.appSession()?.title || (await sessionName(host($), (await laneOf($)).root, own).catch(() => '')) || `session ${state.shortSession(own)}`}"`
1072}
1073
1074// Into the other session (A3): through the desktop app's session tool when both sessions run in the app (the other
1075// recorded its app id, and this one could ask the app for its own), else the engine's send by its CLI id.
1076/** @param {Engine} $ @param {Pick<Target, 'sessionId' | 'appId'>} target @param {string} message @returns {Promise<{ isDelivered: boolean, reason?: string }>} */
1077async function deliverTo($, target, message) {
1078 if (!target.appId || !state.appSession()) return $.session.send({ to: { sessionId: target.sessionId }, text: message }).catch(error => ({ isDelivered: false, reason: String(error) }))
1079 const sent = await appTool(() => $.tool.call({ tool: 'mcp__ccd_session_mgmt__send_message', session_id: target.appId, message }))
1080 return sent.isDone && isSentReply(sent.text) ? { isDelivered: true } : { isDelivered: false, reason: cutWords(sent.text, 200) || 'the app did not say why' }
1081}
1082
1083// A press handed to this session, or sent to the one that tracks its intent (whereTo): resolves what the press says,
1084// `words` when this session has it at once.
1085/** @param {Engine} $ @param {Target | 'here'} target @param {readonly string[]} ids @param {string} text @param {string} words @param {() => Promise<unknown>} [onDelivered] */
1086async function handTo($, target, ids, text, words, onDelivered) {
1087 return target === 'here' ? toldText(handOff($, ids, text, onDelivered), words) : sendTo($, target, ids, text, onDelivered)
1088}
1089
1090// Where an intent is worked on (A1). `tracked`: the key of the intent this session tracks; `peersOf`: the live
1091// sessions of a checkout.
1092/** @param {Engine} $ @param {import('./model.mjs').Intent} intent @param {string} tracked @param {(root: string, localDir: string) => Promise<import('./state.mjs').Lane[]>} peersOf */
1093async function placeFor($, intent, tracked, peersOf) {
1094 const { root, pack: chosen } = await laneFor($, intent.root)
1095 return placeOf(intent.slug, intent.key === tracked, await peersOf(root, chosen.localDir))
1096}
1097
1098// Where each intent with a decision waiting is worked on, what Needs you's rows say (A1): each checkout's live
1099// sessions read once.
1100/** @param {Engine} $ */
1101async function readPlaces($) {
1102 const tracked = await trackedKey($)
1103 /** @type {Map<string, Promise<import('./state.mjs').Lane[]>>} */
1104 const read = new Map()
1105 const peersOf = (/** @type {string} */ root, /** @type {string} */ localDir) => {
1106 const kept = read.get(root) ?? state.readPeers(io($), root, localDir)
1107 read.set(root, kept)
1108 return kept
1109 }
1110 const waiting = intents.filter(one => directorCalls(one).length > 0)
1111 const placed = await Promise.all(waiting.map(async one => ({ one, place: await placeFor($, one, tracked, peersOf) })))
1112 // For those no live session tracks, a guess (A3b, A7): shown with its link only; presses still go here.
1113 const untracked = placed.filter(({ place }) => place.kind === 'none').map(({ one }) => one)
1114 const app = {
1115 search: (/** @type {string} */ query) => appTool(() => $.tool.call({ tool: 'mcp__ccd_session_mgmt__search_session_transcripts', query, limit: 20 })),
1116 session: (/** @type {string} */ session_id) => appTool(() => $.tool.call({ tool: 'mcp__ccd_session_mgmt__get_session', session_id })),
1117 selfId: state.appSession()?.id ?? '',
1118 }
1119 const guessed = await guesses.placesOf(app, untracked)
1120 return new Map(placed.map(({ one, place }) => [one.key, guessed.get(one.key) ?? place]))
1121}
1122
1123// Opens the app's link to another session with the system's own opener (A6): on the desktop the pane's anchor does
1124// not open a claude:// link. Nothing is sent and no turn starts. Windows by its OS variable: the engine names no platform.
1125/** @param {Engine} $ @param {string} link */
1126async function openLink($, link) {
1127 const isWindows = (await $.env.get('OS').catch(() => undefined)) === 'Windows_NT'
1128 return openWith(argv => $.process.run(argv, { timeoutMs: 15000 }), link, isWindows)
1129}
1130
1131// Where a press about an intent goes (A3): to the live session that tracks it when that is another one, else here
1132// (this session tracks it, or none does). Never asked: a decision put into a session that does not track its
1133// intent has two sessions changing one intent folder. Read at the press, not from the rows' last read: a session
1134// may have ended, or started on the intent, since.
1135/** @param {Engine} $ @param {string} key the intent's key in the pane @returns {Promise<Target | 'here'>} */
1136async function whereTo($, key) {
1137 const intent = intents.find(one => one.key === key)
1138 const place = intent ? await placeFor($, intent, await trackedKey($), (root, localDir) => state.readPeers(io($), root, localDir)) : undefined
1139 return place?.kind === 'other' ? place : 'here'
1140}
1141
1142// The row's "Sent to <title>" once the session that tracks its intent has a press of it (A3).
1143/** @param {Engine} $ @param {string} id @param {Target} target */
1144function noteSent($, id, target) {
1145 answerState = { ...answerState, sentTo: { ...answerState.sentTo, [id]: { sessionId: target.sessionId, name: target.name } } }
1146 $.ui.invalidate('ui.render')
1147}
1148
1149// The row's "could not open it" once a Go to session press could not open the session, cleared once one does (A6).
1150/** @param {Engine} $ @param {string} id @param {boolean} isOpen */
1151function noteOpened($, id, isOpen) {
1152 const { [id]: _, ...unopened } = answerState.unopened
1153 answerState = { ...answerState, unopened: isOpen ? unopened : { ...unopened, [id]: true } }
1154 $.ui.invalidate('ui.render')
1155}
1156
1157// A question about an intent (its view's Ask about it, one of today's changes), sent where whereTo says.
1158/** @param {Engine} $ @param {string} key @param {string} text @param {string} words what the press says once sent */
1159async function askAbout($, key, text, words) {
1160 return handTo($, await whereTo($, key), [], text, words)
1161}
1162
1163// Explain, on a decision: nothing is decided; the session that explains is the one whereTo says.
1164/** @param {Engine} $ @param {Item} one @param {import('./decide.mjs').Answers} answers @param {string} words */
1165async function explainItem($, one, answers, words) {
1166 const target = one.kind === 'call' ? await whereTo($, one.slug) : 'here'
1167 return handTo($, target, [], answers.explain, words, target === 'here' ? undefined : async () => noteSent($, one.id, target))
1168}
1169
1170/** @param {Engine} $ @param {Item} one */
1171async function act($, one) {
1172 if (one.kind === 'away-end') return comeBack($)
1173 if (one.kind === 'review') {
1174 // The person is back: the rest of the window's group ends with this press (A3), and stays ended should the
1175 // hand-off fail and this window be put back.
1176 await state.comeBack(io($))
1177 // The review is the person walking through the window. The window closes when the session has the
1178 // review, not at the press: a press while a turn runs waits for that turn's end, and until then the
1179 // session has not read "I am back", so merges stay held and its questions still go to the ledger.
1180 const handed = handOff($, [one.id], one.prompt, () => state.closeAway(io($)))
1181 return handed === 'queued' ? `Queued until this turn ends. The away window stays as it is until the session has it: merges are still held.${(await hasPane($)) ? ' To send it now, stop the running turn here.' : ''}` : toldText(handed, 'Sent to the session.')
1182 }
1183 const target = one.kind === 'call' ? await whereTo($, one.slug) : 'here'
1184 return handTo($, target, [one.id], one.prompt, 'Sent to the session.', () => state.settleItem(io($), one))
1185}
1186
1187// "I'm back" waits behind a running turn: on the person's own press, and only then, that turn is stopped.
1188// The engine then starts the turn of the review that already waits; nothing is submitted a second time.
1189/** @param {Engine} $ */
1190async function sendNow($) {
1191 const turnId = turnRunning
1192 if (turnId === '') return 'No turn is running now: there is nothing to stop.'
1193 await $.turn.abort({ turnId })
1194 return 'Stopped the running turn: the session reads "I am back" now.'
1195}
1196
1197// The review waits behind a running turn: the pane stays, since it has the way to send it now.
1198function isReviewQueued() {
1199 return outbox.queued().some(id => id.startsWith('review:'))
1200}hooks/away.mjs 251 lines1// @ts-check
2// Ather Automata: the autonomy window's rules. What a window allows and holds,
3// its ledger text, and the mandate the session is given. Pure: no `$`; the one
4// place that changes a window is state.mjs.
5
6import { forBase, heldLabel } from './guards.mjs'
7import { untitledName } from './handoff.mjs'
8import { clockText, durationText } from './model.mjs'
9import { unreal } from './packs/unreal.mjs'
10
11/** @typedef {import('./packs/index.mjs').Pack} Pack */
12
13/**
14 * @typedef {{ id: string, kind: string, command: string, at: number }} Parked
15 * A window holds actions and records questions from the moment it starts until the person has reviewed it:
16 * 'running' while they are away, 'review' once it has ended and waits for them. `group`: the windows opened together
17 * from one Away dialog or /away share it, and the person's return in any of them ends them all.
18 * @typedef {{ phase: 'off' | 'running' | 'review', untilDone: boolean, goal: string, held: string[], startedAt: number, wakeAt: number, endedAt?: number, ledgerPath: string, parked: Parked[], person: string, root: string, group?: string }} Away
19 * @typedef {{ hours: number, untilDone: boolean, goal: string, held?: string[], group?: string }} WindowChoice
20 */
21
22/** @returns {Away} */
23export const offAway = () => ({ phase: 'off', untilDone: false, goal: '', held: ['merge', 'push-main'], startedAt: 0, wakeAt: 0, ledgerPath: '', parked: [], person: '', root: '' })
24
25// Held actions stay held until the person has reviewed the window, not only while it runs.
26/** @param {Away} away */
27export const isHolding = away => away.phase !== 'off'
28
29// The session's questions go to the ledger while the window runs, and after it ends until the person
30// is back: the first thing they type after the end (at `lastPersonAt`) means they can be asked again.
31/** @param {Away} away @param {number} lastPersonAt */
32export const isRecordingQuestions = (away, lastPersonAt) => away.phase === 'running' || (away.phase === 'review' && lastPersonAt < (away.endedAt ?? 0))
33
34// Presets (decided 2026-10-03). Each may push branches and open draft PRs and PRs to main;
35// merges and direct pushes to main stay held.
36export const AWAY_PRESETS = [
37 { label: 'Until done', hotkey: 'u', choice: { hours: 24, untilDone: true } },
38 { label: '8 hours', hotkey: 'o', choice: { hours: 8, untilDone: false } },
39 { label: '4 hours', hotkey: 'h', choice: { hours: 4, untilDone: false } },
40]
41
42/** @param {number} hours */
43export const clampHours = hours => Math.min(16, Math.max(0.25, hours))
44
45// "/away stop", "/away end now": ending, in the words people use.
46/** @param {string} args */
47export const isStopWord = args => /^((i'?m|i am)\s+)?(end|stop|off|cancel|quit|finish|back|home)(\s+now)?[.!]?$/i.test(args.trim())
48
49// "/away until done ship it", "/away 6h fix the pool", "30m", "until 9am", "tonight": how long, then the goal.
50// `nowMinutes` is the person's local time of day, for "until 9am" and "tonight" (until 09:00).
51/** @param {string} args @param {number} nowMinutes @returns {WindowChoice | null} */
52export const parseAwayArgs = (args, nowMinutes) => {
53 const text = args.trim()
54 const done = /^(until[\s-]*done|done)\b[\s,]*/i.exec(text)
55 if (done) return { hours: 24, untilDone: true, goal: text.slice(done[0].length).trim() }
56 const hours = /^(\d{1,2}(?:\.\d+)?)\s*h(?:ours?|rs?)?\b[\s,]*/i.exec(text)
57 if (hours) return { hours: clampHours(Number(hours[1])), untilDone: false, goal: text.slice(hours[0].length).trim() }
58 const minutes = /^(\d{1,3})\s*m(?:in(?:ute)?s?)?\b[\s,]*/i.exec(text)
59 if (minutes) return { hours: clampHours(Number(minutes[1]) / 60), untilDone: false, goal: text.slice(minutes[0].length).trim() }
60 const until = /^(?:until|till|til)\s+(\d{1,2})(?::(\d{2}))?\s*(am|pm)?\b[\s,]*/i.exec(text) ?? /^(tonight|overnight|tomorrow(?:\s+morning)?)\b[\s,]*/i.exec(text)
61 if (!until) return null
62 const isNamed = /^(tonight|overnight|tomorrow)/i.test(until[1] ?? '')
63 let hour = isNamed ? 9 : Number(until[1]) % 12 + (/pm/i.test(until[3] ?? '') ? 12 : 0)
64 if (!isNamed && !until[3] && Number(until[1]) >= 12) hour = Number(until[1])
65 const target = hour * 60 + (isNamed ? 0 : Number(until[2] ?? 0))
66 const ahead = (target - nowMinutes + 1440) % 1440 || 1440
67 return { hours: Math.min(24, ahead / 60), untilDone: false, goal: text.slice(until[0].length).trim() }
68}
69
70/** @param {Away} away @param {number} tz */
71export const windowEndText = (away, tz) => (away.untilDone ? 'until done (24 hours at most)' : `until ${clockText(away.wakeAt, tz)}`)
72
73// The same for the session to read: "until 17:30 local time", or "until the work is done (hard stop 13:45 local
74// time)" for a window with no set end, whose `wakeAt` is only its 24-hour limit, never when the person is back.
75/** @param {Pick<Away, 'untilDone' | 'wakeAt'>} away @param {number} tz */
76export const awayUntilText = (away, tz) => (away.untilDone ? `until the work is done (hard stop ${clockText(away.wakeAt, tz)} local time)` : `until ${clockText(away.wakeAt, tz)} local time`)
77
78// Why a question is not asked now: the person is away, or has not reviewed the window that ended.
79/** @param {{ phase: string, untilDone: boolean, wakeAt: number }} away @param {number} tz */
80export const awayReason = (away, tz) => (away.phase === 'review' ? 'The user has not reviewed the away window yet' : `The user is away ${awayUntilText(away, tz)}`)
81
82/** @param {WindowChoice} choice @param {number} now @param {string} ledgerPath @param {{ person: string, root: string }} owner @returns {Away} */
83export const newWindow = (choice, now, ledgerPath, owner) => ({
84 phase: 'running',
85 untilDone: choice.untilDone,
86 goal: choice.goal,
87 held: choice.held ?? ['merge', 'push-main'],
88 startedAt: now,
89 wakeAt: now + (choice.untilDone ? 24 : Math.min(24, Math.max(0.25, choice.hours))) * 3600000,
90 ledgerPath,
91 parked: [],
92 person: owner.person,
93 root: owner.root,
94 ...(choice.group ? { group: choice.group } : {}),
95})
96
97// `base`: the branch the checkout's team merges into; a window there says so where it says main (guards.mjs forBase).
98/** @param {Away} away @param {Pack} pack @param {string} [base] */
99const heldText = (away, pack, base) => away.held.map(kind => heldLabel(kind, pack, base)).join(', ') || 'nothing'
100
101// A ledger file with a new window appended (or started).
102/** @param {string} existing @param {Away} away @param {number} tz @param {Pack} [pack] @param {string} [base] */
103export const ledgerWithWindow = (existing, away, tz, pack = unreal, base = 'main') =>
104 [
105 existing === '' ? '# Autonomy Window Decisions\n' : existing.trimEnd(),
106 '',
107 `## Autonomy window from ${clockText(away.startedAt, tz)}, ${windowEndText(away, tz)}`,
108 '',
109 `- Goal: ${away.goal || '(see the session)'}`,
110 `- Allowed without asking: ${forBase(pack.mandate.allowed, base)}`,
111 `- Held: ${heldText(away, pack, base)}`,
112 '',
113 'Each decision taken for you while you were away. Entry format: Options, Choice, Why, Evidence, Revert, Status (provisional, kept, revert requested, reopened).',
114 '',
115 ].join('\n')
116
117/** @param {Away} away @param {number} tz @param {Pack} [pack] @param {string} [base] */
118export const mandateText = (away, tz, pack = unreal, base = 'main') =>
119 away.phase === 'review'
120 ? `AWAY WINDOW ENDED (Ather Automata): the user has not reviewed it yet. Until they do, do not retry held actions (${heldText(away, pack, base)}) and record any decision that would be theirs in ${away.ledgerPath} instead of asking.`
121 : [
122 `AUTONOMY WINDOW (Ather Automata): the user is away ${awayUntilText(away, tz)}.${away.untilDone ? ' When the goal is done, call the mcp__ather-automata__away tool with action "end" so the user gets the review.' : ''}`,
123 `Goal: ${away.goal || 'continue the active work'}.`,
124 `Allowed without asking for this window: ${forBase(pack.mandate.allowed, base)}. Use them on feature branches; ${pack.mandate.merge}.`,
125 `Do not stop to ask or wait for answers. On any decision that would be the user\'s, take the recommended option, prefer the reversible one, and ${pack.mandate.flags}.`,
126 `Record every such decision when you make it in ${away.ledgerPath} as "### D-<n> · <question>" with the lines Options, Choice, Why, Evidence, Revert, Status: provisional.`,
127 `Held until the user has reviewed the window (they will be refused and parked, do not retry them): ${heldText(away, pack, base)}.`,
128 'The AGENTS.md safety contract still applies in full. When blocked on one item, move to another instead of waiting.',
129 ].join(' ')
130
131/** @param {string} id @param {string} question @param {readonly string[]} options */
132export const pendingEntry = (id, question, options) =>
133 [`### ${id} · ${question.replace(/\s+/g, ' ').trim()}`, `- Options: ${options.length > 0 ? options.join('; ') : '(none given)'}`, '- Choice: pending (take the recommended option)', '- Why: ', '- Evidence: ', '- Revert: ', '- Status: provisional', ''].join('\n')
134
135// Decision ids continue from the ledger file itself, so nothing else has to count them.
136/** @param {string} markdown */
137export const nextLedgerId = markdown => Math.max(1, ...[...markdown.matchAll(/^###\s+D-(\d+)/gm)].map(match => Number(match[1]) + 1))
138
139/** @param {readonly Parked[]} parked */
140export const nextParkId = parked => `P-${Math.max(0, ...parked.map(one => Number(one.id.slice(2)) || 0)) + 1}`
141
142// The decisions recorded in the latest window of a ledger.
143/** @param {string} markdown */
144export const windowDecisions = markdown => {
145 const parts = markdown.split(/^(?=## Autonomy window from )/m)
146 return [...(parts[parts.length - 1] ?? '').matchAll(/^###\s+(D-\d+)\s*[·:\-–]?\s*(.*)$/gm)].map(match => ({ id: match[1] ?? '', question: (match[2] ?? '').trim() }))
147}
148
149// ---------------------------------------------------------------- heading off for several sessions
150
151// A word standing alone in a name: not inside another word, and not joined to one by - _ or / (an intent named
152// daily-login-reward is no schedule).
153/** @param {string} words */
154const alone = words => new RegExp(`(?:^|[\\s(\\[【「])(?:${words})(?=$|[\\s)\\]】」.,:;!])`, 'iu')
155const SYNC = alone('sync[\\s_-]*main')
156const SCHEDULED = [/\(\s*\d+\s*(?:tiếng|giờ|phút|h|m)\s*\/\s*lần\s*\)/iu, alone('h[ằà]ng ngày|daily|hourly|scheduled|every (?:\\d+\\s*\\w*|day|hour|morning|night|evening|week)')]
157
158// A session that runs on its own whoever is at the keyboard, so the Away dialog does not tick it by default (A1):
159// the sync conductor (a name starting with ♾, or naming "sync main") or a scheduled task (a name saying how often it
160// runs: "(4 tiếng/lần)", "Hằng ngày", "daily", "hourly", "scheduled", "every 2 hours", "every morning"; never a word
161// inside another, "every" alone or "nightly"). Read from its title in the desktop app, else its branch, as composed
162// characters (a title typed as decomposed ones reads the same).
163/** @param {string} name @returns {'sync' | 'scheduled' | ''} */
164export const sideKind = name => {
165 const text = name.normalize('NFC')
166 if (/^\s*♾/u.test(text) || SYNC.test(text)) return 'sync'
167 return SCHEDULED.some(rule => rule.test(text)) ? 'scheduled' : ''
168}
169
170/**
171 * One live session of the checkout as the Away dialog lists it (A1): its CLI id and app id (to send it the mandate),
172 * its title in the app ('' outside it), branch and tracked intent (what /away names match), the row's name and what it
173 * says beside it, and whether it is ticked when the dialog opens. `awayUntil`: the end of the window it is already in
174 * ('' for none); such a session is listed, never ticked.
175 * @typedef {{ sessionId: string, appId: string, title: string, branch: string, intent: string | null, name: string, detail: string, isSelf: boolean, isDefault: boolean, awayUntil: string }} AwaySession
176 * @typedef {import('./handoff.mjs').Peer & { window?: Away }} AwayPeer a live session of the checkout with its stored window
177 */
178
179/**
180 * The Away dialog's list: this session first; then the others, those ticked by default (each tracks an intent and is
181 * neither the sync conductor nor a scheduled task), then the rest, then those already away, each group the most
182 * recently active first. This session is always ticked.
183 * @param {{ sessionId: string, title: string, branch: string, intent: string | null }} self
184 * @param {readonly AwayPeer[]} peers @param {number} now @param {number} tz @returns {AwaySession[]}
185 */
186export const awaySessions = (self, peers, now, tz) => {
187 const others = peers
188 .filter(lane => typeof lane.sessionId === 'string' && lane.sessionId !== '' && lane.sessionId !== self.sessionId)
189 .map(lane => {
190 const title = lane.app?.title ?? ''
191 const branch = lane.branch ?? ''
192 const window = lane.window && isHolding(lane.window) ? lane.window : null
193 const side = sideKind(title || branch)
194 const ago = now - Number(lane.lastActiveAt ?? lane.updatedAt)
195 const detail = window ? `away ${windowEndText(window, tz)}` : side === 'scheduled' ? 'scheduled' : ago < 60000 ? 'active now' : `active ${durationText(ago)} ago`
196 /** @type {AwaySession} */
197 const row = { sessionId: lane.sessionId, appId: lane.app?.id ?? '', title, branch, intent: lane.intent, name: title || untitledName(branch), detail, isSelf: false, isDefault: !window && Boolean(lane.intent) && side === '', awayUntil: window ? windowEndText(window, tz) : '' }
198 return { row, rank: window ? 2 : row.isDefault ? 0 : 1, at: -ago }
199 })
200 .sort((a, b) => a.rank - b.rank || b.at - a.at)
201 .map(one => one.row)
202 const name = self.title || self.branch
203 return [{ sessionId: self.sessionId, appId: '', title: self.title, branch: self.branch, intent: self.intent, name: name ? `this session · ${name}` : 'this session', detail: '', isSelf: true, isDefault: true, awayUntil: '' }, ...others]
204}
205
206// Whether `name` (lowercase) names a session: a session ticked by default when its title, branch or intent contains it
207// (three letters at least); any other (the sync conductor, a scheduled task, one tracking nothing) only by its whole
208// title, branch or intent, so a word of a goal never reaches it.
209/** @param {AwaySession} one @param {string} name */
210const isNamed = (one, name) => {
211 const fields = [one.title, one.branch, one.intent ?? ''].filter(Boolean).map(field => field.normalize('NFC').toLowerCase())
212 return one.isDefault ? name.length >= 3 && fields.some(field => field.includes(name)) : fields.includes(name)
213}
214
215// The names a `[only] in <names>[ only][: goal]` or a `@name @name [only][:] goal` says, whether `only` was said, and
216// the goal; null for any other words.
217/** @param {string} text @returns {{ names: string[], isOnly: boolean, goal: string } | null} */
218const namesOf = text => {
219 const listed = /^(only\s+)?in\s+([^:]+?)(\s+only)?\s*(?::\s*([\s\S]*))?$/i.exec(text)
220 if (listed) return { names: (listed[2] ?? '').split(','), isOnly: Boolean(listed[1] || listed[3]), goal: listed[4] ?? '' }
221 const tagged = /^((?:@[^\s,:@]+[\s,]*)+)(only\b)?\s*(?::\s*)?([\s\S]*)$/iu.exec(text)
222 if (tagged) return { names: (tagged[1] ?? '').split(/[\s,@]+/), isOnly: Boolean(tagged[2]), goal: tagged[3] ?? '' }
223 return null
224}
225
226// "/away 8h all", "/away 8h in enemy, playtest: finish the pass", "/away 8h @enemy finish the pass": the sessions the
227// words after the length name (A4), only when they name them on purpose, so a goal is never read as names. `all` (alone,
228// or before a colon and the goal): the sessions ticked by default. `in <name>, <name>` (a goal after a colon) or
229// leading `@name`s: those sessions, and this one with them unless `only` is said ("only in …", "in … only", "@a only").
230// A session already away is never picked. Null for plain words: the goal of this session alone, as before. `unknown`:
231// the names that named no session (nothing is started then).
232/** @param {string} words @param {readonly AwaySession[]} sessions @returns {{ picked: AwaySession[], goal: string, unknown: string[] } | null} */
233export const pickedSessions = (words, sessions) => {
234 const text = words.normalize('NFC').trim()
235 const open = sessions.filter(one => one.awayUntil === '')
236 const all = /^all\s*(?::\s*([\s\S]*))?$/i.exec(text)
237 if (all) return { picked: open.filter(one => one.isDefault), goal: (all[1] ?? '').trim(), unknown: [] }
238 const named = namesOf(text)
239 if (!named) return null
240 const names = named.names.map(one => one.trim().toLowerCase()).filter(Boolean)
241 const matches = names.map(name => open.filter(one => isNamed(one, name)))
242 return { picked: open.filter(one => (one.isSelf && !named.isOnly) || matches.some(found => found.includes(one))), goal: named.goal.trim(), unknown: names.filter((_, index) => (matches[index] ?? []).length === 0) }
243}
244
245// What another session reads when the person heads off from this one (A2): that its window is open (it is, before this
246// is sent), and the mandate whole (its ledger, what is held). The engine frames it as a message from this session
247// (`from`, as its tab names it); while the window holds, that session's lane state carries the mandate too.
248/** @param {{ from: string, away: Away, tz: number, pack?: Pack, base?: string }} at */
249export const awayMessage = ({ from, away, tz, pack = unreal, base = 'main' }) =>
250 `From the Ather pane of ${from}: the person is heading off and opened an away window in your session too.\n\n${mandateText(away, tz, pack, base)}`
251hooks/guards.mjs 142 lines1// @ts-check
2// Ather Automata: what tool calls and their output mean. Shell commands that
3// must wait while the director is away, builds and tests read from their own
4// output, MCP calls that count as evidence, thin worker briefs, known traps.
5// Pure: no `$`.
6
7import { unreal } from './packs/unreal.mjs'
8import { WEB_HELD, makeWebPack } from './packs/web.mjs'
9import { isBaseBranch, pushTarget, withFolders } from './shell.mjs'
10
11/** @typedef {import('./packs/index.mjs').Pack} Pack */
12
13// Every pack's held actions, by kind: a parked action reads the same whichever pack parked it.
14const WEB = makeWebPack(null, null)
15/** @type {Record<string, string>} */
16export const HELD_LABELS = { merge: 'Merges', 'push-main': 'Pushes to main', ...unreal.held.labels, ...WEB.held.labels }
17// For one held action in a sentence: "held a merge until you are back".
18/** @type {Record<string, string>} */
19export const HELD_NOUNS = { merge: 'a merge', 'push-main': 'a push to main', ...unreal.held.nouns, ...WEB.held.nouns }
20/** @typedef {string} HeldKind merge, push-main, or one of a pack's held kinds */
21// What a held text says of main, for a checkout whose team merges into another branch: a push there is held
22// as one to main is ("Pushes to develop and main", "a push to develop or main", as the web pack words its
23// own), and PRs open against it. With base main the text is as it was.
24/** @param {string} text @param {string} [base] */
25export const forBase = (text, base = 'main') => (base === 'main' ? text : text.replace(/\b(push(es)? to) main\b/gi, (_, words, plural) => `${words} ${base} ${plural ? 'and' : 'or'} main`).replace(/\bPRs to main\b/g, `PRs to ${base}`))
26/** @param {Pack} pack @returns {string[]} */
27export const heldKindsOf = pack => ['merge', 'push-main', ...pack.held.kinds]
28// A kind's label and noun: as the pack words it when it does, else as every pack does; then for the
29// checkout's base (forBase), where the words still say main.
30/** @param {string} kind @param {Pack} [pack] @param {string} [base] */
31export const heldLabel = (kind, pack, base) => forBase(pack?.held.labels[kind] ?? HELD_LABELS[kind] ?? kind, base)
32/** @param {string} kind @param {Pack} [pack] @param {string} [base] */
33export const heldNoun = (kind, pack, base) => forBase(pack?.held.nouns[kind] ?? HELD_NOUNS[kind] ?? kind, base)
34export { WEB_HELD }
35
36// The Unreal pack's readers, kept here for the modules and tests that read them from the guards.
37export { automationResult, buildResult, isAssetSave, isAutomationCommand, isBuildCommand, isEditorBuild, isLogRead, mcpKind } from './packs/unreal.mjs'
38export { gitFolders, isPiped, isSearchCommand } from './shell.mjs'
39
40const GIT_REWRITE = /\bgit\b(?:\s+-[cC]\s+\S+)*\s+(stash(?!\s+(list|show)\b)|clean\b|reset\s+--hard|sparse-checkout(?!\s+(list|disable)\b)|checkout\b|switch\b|restore\b|rebase\b)/i
41
42// Why a refused tree-rewriting git command was refused, and the safe way.
43/** @param {string} command */
44export const explainGuard = command => {
45 const kind = GIT_REWRITE.exec(command)?.[1]?.split(/\s+/)[0]
46 if (!kind) return null
47 const safe = /\bgit\s+-C\s+\S+/.test(command)
48 ? 'Run it from a separate worktree (git worktree add, then git -C <worktree path> ...), never in the shared checkout.'
49 : 'Pin it: git -C <absolute worktree path> ..., with the path read back from git worktree list. Never after a cd.'
50 return `git ${kind} rewrites the working tree that other sessions share. ${safe}`
51}
52
53/** @param {string} command */
54// A merge or a pull (which merges); never `merge-base` or `merge --abort`.
55export const isMergeCommand = command => /\bgit\b(?:\s+-C\s+\S+)?\s+(merge(?![-\w])|pull\b)(?!.*--abort)/i.test(command)
56
57// A shell command the window holds, if any. `branchOf` gives the branch checked out in a folder
58// (null: the session's folder), or '' when it cannot be told; then only an explicit main is held.
59// main means main, master, or the checkout's base (`context.base`) when its team merges into another branch.
60// With the web pack's with-proof policy (D2), a merge passes once every gate the profile requires has passed:
61// `context.isProven` says so, read from this session's evidence by the caller.
62// `context.at` gives a folder in another checkout that checkout's pack, held kinds and proof; null keeps the session's.
63/**
64 * @param {string} command @param {readonly string[]} held @param {(folder: string | null) => string} branchOf
65 * @param {Pack} [pack] @param {import('./packs/index.mjs').HeldContext} [context] @returns {string | null}
66 */
67export const heldShell = (command, held, branchOf, pack = unreal, context = {}) => heldShellAt(command, held, branchOf, pack, context)?.kind ?? null
68
69// The same, with the base of the checkout the held segment ran in: what is said of it names that branch.
70/**
71 * @param {string} command @param {readonly string[]} held @param {(folder: string | null) => string} branchOf
72 * @param {Pack} [pack] @param {import('./packs/index.mjs').HeldContext} [context] @returns {{ kind: string, base: string } | null}
73 */
74export const heldShellAt = (command, held, branchOf, pack = unreal, context = {}) => {
75 for (const { segment, folder } of withFolders(command)) {
76 const here = context.at?.(folder) ?? null
77 const judged = here ? { ...here, scripts: here.pack.scripts } : { pack, held, isProven: context.isProven === true, scripts: context.scripts ?? pack.scripts, base: context.base }
78 const kind = heldSegmentIn(segment, branchOf(folder), judged)
79 if (kind) return { kind, base: judged.base ?? 'main' }
80 }
81 return null
82}
83
84// main and master in every repository, the branch the pack says pull requests go into, and the checkout's base.
85/** @param {string} branch @param {Pack} pack @param {string} [base] */
86const isProtected = (branch, pack, base) => isBaseBranch(branch, base) || (Boolean(pack.baseBranch) && branch.replace(/^refs\/heads\//, '') === pack.baseBranch)
87
88/** @param {string} segment @param {string} branch @param {{ pack: Pack, held: readonly string[], isProven: boolean, scripts?: Record<string, string>, base?: string }} judged */
89const heldSegmentIn = (segment, branch, { pack, held, isProven, scripts, base }) => {
90 const merges = !(pack.mergePolicy === 'with-proof' && isProven)
91 const isPrMerge = /^gh\s+pr\s+merge\b/i.test(segment) || /^gh\s+api\b.*\bpulls\/\d+\/merge\b/i.test(segment)
92 // A local merge matters only into a protected branch; merging main into a feature branch is ordinary work.
93 const isMainMerge = /^git\b(?:\s+-C\s+\S+)?\s+merge\s+(?!--abort)/i.test(segment) && isProtected(branch, pack, base)
94 if (held.includes('merge') && merges && (isPrMerge || isMainMerge)) return 'merge'
95 if (held.includes('push-main') && /^git\b(?:\s+-C\s+\S+)?\s+push\b/i.test(segment) && isProtected(pushTarget(segment, branch), pack, base)) return 'push-main'
96 const kind = pack.heldSegment(segment, held, { isProven, scripts })
97 return kind && (kind !== 'merge' || merges) ? kind : null
98}
99
100// "mcp__unreal-mcp__get_actor" → "unreal-mcp": a readback must read from the server that was written to.
101/** @param {string} tool */
102export const mcpServer = tool => tool.split('__')[1] ?? tool
103
104// Only briefs for workers that will change files or the Editor are checked.
105/** @param {string} prompt @param {string | undefined} type @param {Pack} [pack] */
106export const briefIssues = (prompt, type, pack = unreal) => {
107 if (type !== undefined && /^(Explore|Plan|statusline-setup|claude-code-guide)$/i.test(type)) return []
108 if (!/\b(edit|write|implement|fix|change|modify|refactor|add|create|delete|remove|rename|commit|save|build|compile|wire|author)\b/i.test(prompt) || /\bread-only\b|do not (edit|modify|change)|no edits/i.test(prompt)) return []
109 const issues = []
110 if (!pack.briefPaths.test(prompt)) issues.push('exact paths')
111 if (!/acceptance|accept when|done when|success criteria|verify|evidence|proof|report format|deliverable|final (message|report)|report back|return (a|the) (list|report|summary)/i.test(prompt)) issues.push('acceptance checks')
112 // A worker kept to its own folder, or told to leave git alone, already respects the shared tree.
113 if (!/shared (checkout|tree|worktree)|git -C|worktree|no commits|do not commit|don't commit|never (stash|switch|clean)|no git (changes|commands)|work only in|edit nothing (else|outside)/i.test(prompt)) issues.push('the shared-tree rule')
114 return issues
115}
116
117// ---------------------------------------------------------------- known traps
118
119/** @typedef {{ file: string, text: string }} WrittenRule */
120/** @typedef {{ id: string, title: string, fix: string, rule?: WrittenRule }} Trap */
121/** @typedef {Record<string, { title: string, fix: string, count: number }>} TrapHits */
122
123/** @param {string} text @param {Pack} [pack] */
124export const matchGotchas = (text, pack = unreal) => pack.traps.filter(rule => rule.pattern.test(text))
125
126// A trap hit in this many separate sessions becomes a "Needs you" item: make it a rule?
127const RULE_AFTER_SESSIONS = 3
128
129/** @param {TrapHits} hits @param {Trap} rule @returns {TrapHits} */
130export const countGotcha = (hits, rule) => ({ ...hits, [rule.id]: { title: rule.title, fix: rule.fix, count: (hits[rule.id]?.count ?? 0) + 1 } })
131
132// Only the pack's own traps: the counts are kept per machine, across every kind of repository.
133/** @param {TrapHits} hits @param {readonly string[]} ruled @param {Pack} [pack] */
134export const recurringGotchas = (hits, ruled, pack = unreal) =>
135 Object.entries(hits)
136 .filter(([id, hit]) => hit.count >= RULE_AFTER_SESSIONS && !ruled.includes(id) && pack.traps.some(trap => trap.id === id))
137 .map(([id, hit]) => ({ id, ...hit }))
138 .sort((a, b) => b.count - a.count)
139
140/** @param {string} id @param {Pack} [pack] @returns {WrittenRule | undefined} */
141export const writtenRuleOf = (id, pack = unreal) => pack.traps.find(one => one.id === id)?.rule
142hooks/model.mjs 705 lines1// @ts-check
2// Ather Automata: what the S2 workflow's files say. Intents, people, time, the
3// Editor lock, the four stages and the one next step. Pure: no `$`.
4
5import { unreal } from './packs/unreal.mjs'
6import { branchNamed } from './shell.mjs'
7
8// The Unreal pack's names, kept here for the modules and tests that read them from the model.
9export { ROLES, ROLE_LABELS, OWNERS, AREAS, parseRole, parseEditorLock } from './packs/unreal.mjs'
10
11/** @typedef {import('./packs/index.mjs').Pack} Pack */
12
13export const STAGE_LABELS = { plan: 'Plan', build: 'Build', prove: 'Prove', ship: 'Ship', close: 'Ready to close', shipped: 'Shipped' }
14
15// The issue an intent names: "#28887", "sipherxyz/S2#28887", a link ending "issues/28887", or "28887".
16/** @param {string} text */
17const issueNumber = text => {
18 const match = /#(\d+)|issues\/(\d+)/.exec(text) ?? /^\s*(\d+)\s*$/.exec(text)
19 return match ? Number(match[1] ?? match[2]) : null
20}
21
22/** @param {string} text @param {Pack} [pack] */
23export const normalizeArea = (text, pack = unreal) => pack.normalizeArea(text)
24
25// The key a person's stored records are filed under (personId). It drops accented letters ("Hoàng Vũ" is
26// "hongv"); kept so, since changing it would lose those records.
27/** @param {string} name */
28const personKey = name => name.toLowerCase().replace(/[^a-z0-9]/g, '')
29
30// The key two names are compared by: accents dropped, the letters kept ("Hoàng Vũ" is "hoangvu").
31/** @param {string} name */
32const matchKey = name => personKey(name.normalize('NFD').replace(/\p{M}/gu, '').replace(/[đĐ]/g, 'd'))
33
34// Other names a person goes by, by match key: git's email name ("vu.le" for "Hoàng Vũ"), learnt from the checkout.
35/** @type {Map<string, Set<string>>} */
36const aliases = new Map()
37
38/** @param {string} name @param {string} alias */
39export const addPersonAlias = (name, alias) => {
40 const key = matchKey(name)
41 const other = matchKey(alias)
42 if (key === '' || other === '' || key === other) return
43 aliases.set(key, new Set([...(aliases.get(key) ?? []), other]))
44}
45
46// "Tin Nguyen" matches "TinNguyen"; "TienPham" matches "TienPhamProducerAther"; "Hoàng Vũ" matches "Hoang Vu",
47// and "vu.le" once git's email says vu.le@… is Hoàng Vũ. An email name matches only whole: "tin@…" is not Tin Nguyen.
48/** @param {string} a @param {string} b */
49export const isSamePerson = (a, b) => {
50 const x = matchKey(a)
51 const y = matchKey(b)
52 return x !== '' && y !== '' && (x.startsWith(y) || y.startsWith(x) || Boolean(aliases.get(x)?.has(y)) || Boolean(aliases.get(y)?.has(x)))
53}
54
55// "a", "a and b", "a, b and c".
56/** @param {readonly string[]} items */
57export const andList = items => (items.length <= 1 ? items.join('') : `${items.slice(0, -1).join(', ')} and ${items[items.length - 1]}`)
58
59/** @param {number} count @param {string} one @param {string} [many] */
60export const plural = (count, one, many = `${one}s`) => `${count} ${count === 1 ? one : many}`
61
62// The closest of a few command words to a typo ("tuor" → "tour"), or null.
63/** @param {string} word @param {readonly string[]} words */
64export const closestWord = (word, words) => {
65 // Edits between two words, a swap of neighbours counting as one ("tuor" is one edit from "tour").
66 const distance = (/** @type {string} */ a, /** @type {string} */ b) => {
67 const d = Array.from({ length: a.length + 1 }, (_, i) => Array.from({ length: b.length + 1 }, (_, j) => (i === 0 ? j : j === 0 ? i : 0)))
68 const at = (/** @type {number} */ i, /** @type {number} */ j) => d[i]?.[j] ?? 0
69 for (let i = 1; i <= a.length; i += 1) {
70 for (let j = 1; j <= b.length; j += 1) {
71 const cost = a[i - 1] === b[j - 1] ? 0 : 1
72 let best = Math.min(at(i - 1, j) + 1, at(i, j - 1) + 1, at(i - 1, j - 1) + cost)
73 if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) best = Math.min(best, at(i - 2, j - 2) + 1)
74 const row = d[i]
75 if (row) row[j] = best
76 }
77 }
78 return at(a.length, b.length)
79 }
80 const ranked = words.map(candidate => ({ candidate, cost: distance(word.toLowerCase(), candidate) })).sort((x, y) => x.cost - y.cost)
81 return ranked[0] && ranked[0].cost <= 1 && word.length >= 3 ? ranked[0].candidate : null
82}
83
84/** @param {string} me */
85export const personId = me => personKey(me) || 'anyone'
86
87// ---------------------------------------------------------------- text
88
89/** @param {string} markdown */
90const plainText = markdown =>
91 markdown
92 .replace(/\*\*(.+?)\*\*/g, '$1')
93 .replace(/`([^`]+)`/g, '$1')
94 .replace(/\[([^\]]+)\]\([^)]+\)/g, '$1')
95 .replace(/\s+/g, ' ')
96 .trim()
97
98// A row title: plain text, no "Found:" label, the first sentence, cut at a word.
99/** @param {string} text @param {number} [max] */
100export const shortTitle = (text, max = 80) => {
101 const plain = plainText(text).replace(/^(found|finding|problem|issue|question|context|summary|note|observed)\s*:\s*/i, '')
102 if (plain === '') return ''
103 const capital = plain.charAt(0).toUpperCase() + plain.slice(1)
104 const sentence = (/^(.+?[.?!])(\s|$)/.exec(capital)?.[1] ?? capital).replace(/\.$/, '')
105 if (sentence.length <= max) return sentence
106 const cut = sentence.slice(0, max)
107 const space = cut.lastIndexOf(' ')
108 return `${(space > 20 ? cut.slice(0, space) : cut).replace(/[,;:\s]+$/, '')}…`
109}
110
111// A label cut at a word past `max`, ended with "…" when cut.
112/** @param {string} text @param {number} max */
113export const cutWords = (text, max) => (text.length <= max ? text : `${text.slice(0, max - 1).replace(/\s+\S*$/, '')}…`)
114
115// The same text whole, for a surface that wraps it: no label, every sentence, cut only past `max`.
116/** @param {string} text @param {number} [max] */
117export const fullTitle = (text, max = 400) => {
118 const plain = plainText(text).replace(/^(found|finding|problem|issue|question|context|summary|note|observed)\s*:\s*/i, '').trim()
119 const capital = plain.charAt(0).toUpperCase() + plain.slice(1)
120 return capital.length <= max ? capital : `${capital.slice(0, max - 1)}…`
121}
122
123// ---------------------------------------------------------------- intents
124
125/** @param {string} text @param {string} name */
126const field = (text, name) => new RegExp(`^\\s*-\\s*${name}:\\s*(.+)$`, 'mi').exec(text)?.[1]?.trim() ?? ''
127
128/** @param {string} text @param {string} heading */
129export const section = (text, heading) => {
130 const start = new RegExp(`^##\\s+${heading}\\b.*$`, 'mi').exec(text)
131 if (!start) return ''
132 const rest = text.slice(start.index + start[0].length)
133 const end = /^##\s+/m.exec(rest)
134 return end ? rest.slice(0, end.index) : rest
135}
136
137// Every section headed so, in order, each on its own: "## Acceptance" and a later "## Acceptance, rev 2" both count.
138/** @param {string} text @param {string} heading */
139const sections = (text, heading) =>
140 text
141 .split(/^(?=##\s)/m)
142 .filter(part => new RegExp(`^##\\s+${heading}\\b`, 'i').test(part))
143 .map(part => part.replace(/^.*$/m, ''))
144
145const CLOSED = /\b(accepted|rejected|resolved|closed|superseded|withdrawn|answered)\b/i
146
147// ---------------------------------------------------------------- a finding's options and resolution
148
149/** @typedef {{ letter: string, label: string, text: string, isRecommended: boolean }} FindingOption `label`: its first clause, cut to fit a button; `text`: the whole option, plain */
150
151// A clause that only sets the scene ("In the next C++ build", "After the import"): no action of its own.
152const LEADING = /^(in|on|at|after|before|when|whenever|if|once|until|unless|during|while|by|from|then|first)\b/i
153
154// An option's first clause ("keep it as is, with the confirmation (…)" → "Keep it as is"), at least
155// a few words long ("no, drops only" stays whole), cut at a word past `max`. A clause of fewer than
156// three words, or one that only sets the scene, says too little alone: the whole text is cut instead.
157/** @param {string} text @param {number} [max] */
158export const optionLabel = (text, max = 60) => {
159 const plain = plainText(text)
160 const end = [...plain.matchAll(/[,;:(]|\s[—–-]\s|\.(?=\s|$)/g)].map(match => match.index ?? 0).find(at => at >= 12) ?? plain.length
161 const first = plain.slice(0, end).trim()
162 const clause = LEADING.test(first) || first.split(/\s+/).length < 3 ? plain : first
163 const capital = clause.charAt(0).toUpperCase() + clause.slice(1)
164 if (capital.length <= max) return capital
165 const cut = capital.slice(0, max - 1)
166 const space = cut.lastIndexOf(' ')
167 return `${(space > 20 ? cut.slice(0, space) : cut).replace(/[,;:\s]+$/, '')}…`
168}
169
170// "Recommendation: (a)", "Recommendation: B": the letter, upper case, or ''.
171/** @param {string} body */
172const recommendationOf = body => (/\brecommendation\**[ \t]*:\**[ \t]*\(?([a-z])\)?(?![\w])/i.exec(body)?.[1] ?? '').toUpperCase()
173
174// The options a finding writes, in either of the two formats the findings use:
175// **Options:** or inline, in one paragraph or list item that
176// - A (recommended): prove both on a map … says Options or Recommendation:
177// - B: add a lab rig … Options: (a) keep it as is; (b) add a hook …
178// Recommendation: (a).
179// A finding updated later ("**Options now:**") is read from its last options heading. Lettered
180// evidence ("- (a) Before Kawaii: …") with neither word nearby is not options. The recommended one is
181// marked "(recommended)", named by a "Recommendation:" line, or (only when neither says) the one
182// option whose text says "recommended". Fewer than two found: [].
183/** @param {string} body @returns {FindingOption[]} */
184export const parseOptions = body => {
185 const lines = body.split(/\r?\n/)
186 /** @type {{ letter: string, text: string, isMarked: boolean }[]} */
187 let found = []
188 // The list format: an "Options:" line on its own, then "- <Letter>[ (recommended)]: <text>" items and their indented continuations.
189 const head = lines.findLastIndex(line => OPTIONS_HEAD.test(line))
190 if (head >= 0) {
191 for (const line of lines.slice(head + 1)) {
192 const item = /^\s*[-*]\s+\**\s*([A-Za-z])\b\s*(?:\(([^)]*)\))?\s*\**\s*[:.)]\s*\**\s*(.*)$/.exec(line)
193 const last = found[found.length - 1]
194 if (item) found.push({ letter: (item[1] ?? '').toUpperCase(), text: item[3] ?? '', isMarked: /recommended/i.test(item[2] ?? '') })
195 else if (last && /^\s{2,}\S/.test(line) && !/^\s*[-*]\s/.test(line)) last.text += ` ${line.trim()}`
196 else if (found.length > 0 || line.trim() !== '') break
197 }
198 }
199 // The inline format: "(a) … (b) …" in one paragraph or list item, its continuation lines joined.
200 if (found.length === 0) {
201 // Each "(a)" line's paragraph or list item, whole: back to where it starts, on to where the next begins.
202 const starts = (/** @type {string} */ line) => line.trim() === '' || /^\s?[-*]\s|^\s*#|^\s*\*\*\w/.test(line)
203 const paragraphs = lines.flatMap((line, at) => {
204 if (!/\(a\)\s/.test(line)) return []
205 let from = at
206 while (from > 0 && !starts(lines[from] ?? '') && (lines[from - 1] ?? '').trim() !== '') from -= 1
207 let to = at + 1
208 while (to < lines.length && !starts(lines[to] ?? '')) to += 1
209 return [lines.slice(from, to).join(' ').replace(/\s+/g, ' ')]
210 })
211 const paragraph = paragraphs.find(text => /\b(options?|recommendation)\b/i.test(text))
212 if (paragraph) {
213 const from = paragraph.slice(paragraph.indexOf('(a)')).replace(/\s*\brecommendation\**\s*:.*$/i, '')
214 const parts = from.split(/\(([a-z])\)\s+/).slice(1)
215 for (let index = 0; index + 1 < parts.length; index += 2) {
216 const letter = (parts[index] ?? '').toUpperCase()
217 const last = found[found.length - 1]
218 // Letters in order only: a later "(x)" inside an option's text stays in it.
219 if (letter.charCodeAt(0) !== 65 + found.length) {
220 if (last) last.text += ` (${parts[index]}) ${parts[index + 1] ?? ''}`
221 continue
222 }
223 found.push({ letter, text: parts[index + 1] ?? '', isMarked: false })
224 }
225 found = found.map(one => ({ ...one, text: one.text.replace(/[\s;,.]+(or|and)?\s*$/i, '').trim(), isMarked: /\(recommended\)/i.test(one.text) }))
226 }
227 }
228 if (found.length < 2) return []
229 const named = recommendationOf(body)
230 const marked = found.filter(one => one.isMarked)
231 const saying = found.filter(one => /\brecommended\b/i.test(one.text))
232 const pick = named || (marked.length === 1 ? (marked[0]?.letter ?? '') : saying.length === 1 ? (saying[0]?.letter ?? '') : '')
233 return found.map(one => {
234 const text = plainText(one.text.replace(/\s*\(recommended\)/i, ''))
235 return { letter: one.letter, label: optionLabel(text), text: text.charAt(0).toUpperCase() + text.slice(1), isRecommended: one.letter === pick }
236 })
237}
238
239// The intent template's "**Options:**" line, on its own above its lettered list.
240const OPTIONS_HEAD = /^\s*[-*]?\s*\**\s*options(?:\s+\w+)?\s*\**\s*:\s*\**\s*$/i
241
242// A finding's lines about itself: "Status: …", "**Resolution:** …", "- Resolution (orchestrator, 2026-10-05): …".
243const SELF_LINE = /^[ \t]*[-*]?[ \t]*\**[ \t]*(status|resolution)[ \t]*(?:\([^)\n]*\))?[ \t]*\**[ \t]*:[ \t]*\**[ \t]*(.*)$/gim
244
245// What a filled Resolution says when it settles nothing: "open; reported for …", "open (Q3).",
246// "partly addressed …", "not yet", "pending", "tbd", a template's "<pending owner>", "-".
247const UNSETTLED = /^(open|pending|partly|not yet|tbd)\b|^[<\-—–]/i
248
249// Every finding, open or not. Template heading: "## F-<n> (date, rev r) | blocking: yes|no | status: open (owner)".
250/** @param {string} findings @param {string} prompt */
251const readFindings = (findings, prompt) => {
252 const decisions = section(prompt, 'Decisions')
253 return findings
254 .split(/^(?=##\s+F)/m)
255 .filter(part => /^##\s+F[\w-]*\d/.test(part))
256 .map(part => {
257 const heading = /^##\s+(F[\w-]*)\s*(.*)$/m.exec(part)
258 const id = heading?.[1] ?? 'F?'
259 const rest = heading?.[2] ?? ''
260 const body = part.slice((heading?.[0] ?? '').length)
261 const headStatus = /status:\s*(\w+)(?:\s*\(([^)]*)\))?/i.exec(rest)
262 const headBlocking = /blocking:\s*(yes|no)\b/i.exec(rest)
263 const owner = headStatus?.[2]?.trim() ?? ''
264 const said = [...body.matchAll(SELF_LINE)].map(match => ({ kind: (match[1] ?? '').toLowerCase(), text: (match[2] ?? '').replace(/[*_`]/g, '').trim() })).filter(line => line.text !== '')
265 // A settled Resolution closes it, whatever the heading says; an unsettled one ("pending Director",
266 // often left behind) never reopens a heading that says it is closed ("status: resolved (…)").
267 // Without one, the heading's status, else a closing word in the heading or a Status line, else the Decisions.
268 const resolution = said.filter(line => line.kind === 'resolution').at(-1)
269 const statusLine = said.find(line => line.kind === 'status')
270 const isHeadClosed = headStatus !== null && (headStatus[1] ?? '').toLowerCase() !== 'open'
271 const isClosed = resolution
272 ? !UNSETTLED.test(resolution.text) || isHeadClosed
273 : headStatus
274 ? isHeadClosed
275 : CLOSED.test(rest) || (statusLine !== undefined && CLOSED.test(statusLine.text)) || new RegExp(`\\b${id.replace(/-/g, '\\-')}\\b`).test(decisions)
276 // "(open, not blocking)" and "non-blocking for this change" say it does not block.
277 const isBlocking = headBlocking ? headBlocking[1]?.toLowerCase() === 'yes' : /blocking:\s*yes/i.test(part) || (/\bblocking\b/i.test(rest) && !/\b(non|not)[\s-]+blocking\b/i.test(rest))
278 // Without a decider in the status, the template's Options list (written only when the user decides) or
279 // words naming a director's call make it one; inline "(a) … (b) …" choices are the worker's engineering notes.
280 const isDirectorCall = owner ? /director|producer|design|production|user/i.test(owner) : body.split(/\r?\n/).some(line => OPTIONS_HEAD.test(line)) || /director|design lead|production call/i.test(body)
281 const headTitle = shortTitle(rest.replace(/\|\s*(blocking|status):.*$/i, '').replace(/^\([^)]*\)\s*:?\s*/, '').replace(/^:\s*/, ''))
282 const bodyTitle = shortTitle(body.trim().split('\n').find(line => line.trim() !== '' && !line.trim().startsWith('#')) ?? '')
283 const headFull = fullTitle(rest.replace(/\|\s*(blocking|status):.*$/i, '').replace(/^\([^)]*\)\s*:?\s*/, '').replace(/^:\s*/, ''))
284 const bodyFull = fullTitle(body.trim().split('\n').find(line => line.trim() !== '' && !line.trim().startsWith('#')) ?? '')
285 // `source`: the finding as written (capped), for the pane's finding view.
286 return { id, title: headTitle || bodyTitle || id, full: headFull || bodyFull || id, isBlocking, isDirectorCall, options: parseOptions(body), source: part.trim().slice(0, 6000), isOpen: !isClosed }
287 })
288}
289
290/** @param {ReturnType<typeof readFindings>} all */
291const openOnes = all => all.filter(one => one.isOpen).map(({ isOpen: _open, ...one }) => one)
292
293// Open findings.
294/** @param {string} findings @param {string} prompt */
295export const parseFindings = (findings, prompt) => openOnes(readFindings(findings, prompt))
296
297// ---------------------------------------------------------------- acceptance and PRs
298//
299// One writer per fact (.agents/skills/intent/SKILL.md): prompt.md's Acceptance lists the items
300// ("- A1: ...", or rows "| A1 | ... | <proof> |"), progress.md's Acceptance table says which are met,
301// progress.md's "- PR:" line names the PRs. Intents from before that rule tick "- [x]" boxes in
302// prompt.md instead.
303
304// "A1", "B3", "SL15", "A12a": an acceptance id at the start of an item or a table cell.
305const ITEM_ID = /^\**([A-Z]{1,3}[0-9]+[a-z]?)\**(?=[\s:.(]|$)/
306// A verdict that counts as met: its leading word ("met on main", "Pass", "passed", "done", "✓", "✅").
307const MET = /^(met|pass|passed|done|✓|✔|✅)(?![\p{L}\p{N}])/iu
308
309// The table rows among some lines, each as its cells: "| A1 | Snow look. | Unit. |" → ['A1', 'Snow look.', 'Unit.'].
310/** @param {readonly string[]} lines */
311const tableRows = lines => lines.filter(line => /^\s*\|/.test(line)).map(line => line.trim().replace(/^\||\|$/g, '').split('|').map(cell => cell.trim()))
312
313// progress.md's Acceptance table as id → verdict, or null when it has none (or no rows yet).
314// The verdict column is the one headed Verdict, Status or Result, else the second.
315/** @param {string} progress */
316const acceptanceVerdicts = progress => {
317 const rows = tableRows(section(progress, 'Acceptance').split(/\r?\n/)).map(row => row.map(cell => plainText(cell)))
318 const header = rows[0]
319 if (!header) return null
320 const named = header.findIndex(cell => /^(verdict|status|result)$/i.test(cell))
321 const column = named < 0 ? 1 : named
322 /** @type {Map<string, string>} */
323 const verdicts = new Map()
324 for (const row of rows.slice(1)) {
325 const id = ITEM_ID.exec(row[0] ?? '')?.[1]
326 if (id) verdicts.set(id, row[column] ?? '')
327 }
328 return verdicts.size > 0 ? verdicts : null
329}
330
331/** @typedef {{ id: string, text: string, isDone: boolean }} AcceptanceItem `text` is what follows the id ('' id: a legacy box without one) */
332
333// "A2 (owed): Sand look." → { id: 'A2', text: '(owed): Sand look.' }
334/** @param {string} line */
335const splitItem = line => {
336 const match = ITEM_ID.exec(line)
337 return { id: match?.[1] ?? '', text: match ? line.slice(match[0].length).trim() : line }
338}
339
340// The acceptance items and which are done. Ids come from prompt.md's top-level items, or, in a
341// section with no list, from its table's rows (the id in the first cell, the text in the second);
342// each Acceptance section is read on its own, so a table in one and a list in a later one both
343// count. Met-ness comes from progress.md's table, whose rows for ids prompt.md does not list are
344// ignored. Without that table, legacy "- [x]" boxes count as before; without either, every listed
345// item is open.
346/** @param {string} prompt @param {string} progress @returns {AcceptanceItem[]} */
347export const acceptanceItems = (prompt, progress) => {
348 /** @type {Map<string, string>} */
349 const listed = new Map()
350 // What counts without a verdict table once any section has boxes: the boxes, and the rows of the sections written as tables.
351 /** @type {AcceptanceItem[]} */
352 const legacy = []
353 let hasBoxes = false
354 for (const part of sections(prompt, 'Acceptance')) {
355 const lines = part.split(/\r?\n/)
356 const items = lines.map(line => splitItem(/^-\s+(?:\[[ xX]\]\s*)?(.+)$/.exec(line)?.[1] ?? '')).filter(item => item.id !== '')
357 const boxes = lines.flatMap(line => {
358 const box = /^\s*-\s*\[( |x|X)\]\s*(.*)$/.exec(line)
359 return box ? [{ ...splitItem(box[2] ?? ''), isDone: box[1] !== ' ' }] : []
360 })
361 const isTable = items.length === 0 && boxes.length === 0
362 const rows = isTable ? tableRows(lines).map(row => ({ id: ITEM_ID.exec(row[0] ?? '')?.[1] ?? '', text: row[1] ?? '' })).filter(item => item.id !== '') : items
363 for (const item of rows) {
364 if (listed.has(item.id)) continue
365 listed.set(item.id, item.text)
366 if (isTable) legacy.push({ ...item, isDone: false })
367 }
368 legacy.push(...boxes)
369 hasBoxes ||= boxes.length > 0
370 }
371 const verdicts = acceptanceVerdicts(progress)
372 if (verdicts && listed.size > 0) return [...listed].map(([id, text]) => ({ id, text, isDone: MET.test(verdicts.get(id) ?? '') }))
373 if (hasBoxes) return legacy
374 return [...listed].map(([id, text]) => ({ id, text, isDone: false }))
375}
376
377// The text before a file's first "## " heading: where its "- Field:" lines live.
378/** @param {string} text */
379const headerOf = text => text.split(/^##\s/m)[0] ?? ''
380
381// The PR numbers on progress.md's "- PR:" line, then any on a legacy prompt.md one.
382// "- PR: #32372, #32398", "- PRs: sipherxyz/s2#1", "- PR: none yet".
383/** @param {string} progress @param {string} prompt @returns {number[]} */
384export const intentPrs = (progress, prompt) => {
385 const numbers = [progress, prompt].flatMap(text =>
386 [...headerOf(text).matchAll(/^\s*-\s*PRs?\s*:\s*(.+)$/gim)].flatMap(line => [...(line[1] ?? '').matchAll(/#(\d+)|pull\/(\d+)/g)].map(match => Number(match[1] ?? match[2]))),
387 )
388 return [...new Set(numbers)]
389}
390
391/**
392 * @typedef {'MERGED' | 'OPEN' | 'CLOSED' | 'UNREAD'} PrState what gh last said about a PR; UNREAD when it could not say
393 * @typedef {Readonly<Record<string, PrState>>} PrStates PR number (prKey) → its last read state
394 */
395
396// Open, with a checklist whose every item is met: the only intents whose PRs decide anything.
397/** @param {Intent} intent */
398export const isAllMet = intent => intent.status !== 'completed' && intent.acceptanceTotal > 0 && intent.acceptanceDone === intent.acceptanceTotal
399
400// Every item met and every named PR merged, yet not closed: the orchestrator's Close step is owed.
401// An intent with no PR named is not ready: nothing says the work has landed.
402/** @param {Intent} intent @param {PrStates} prs */
403export const isReadyToClose = (intent, prs) => isAllMet(intent) && intent.prs.length > 0 && intent.prs.every(number => prs[prKey(intent, number)] === 'MERGED')
404
405// "#32372 MERGED", "#32398 not read yet": each PR the intent names, with what gh last said.
406/** @param {Intent} intent @param {PrStates} prs */
407export const prStatusList = (intent, prs) =>
408 intent.prs.map(number => {
409 const state = prs[prKey(intent, number)]
410 return `#${number} ${state === 'UNREAD' ? 'could not be read' : (state ?? 'not read yet')}`
411 })
412
413// Where an intent's PR is in a PrStates that holds several checkouts' PRs: its number for the session's
414// own checkout, `<root>#<number>` for another (the same number names another PR in another repository).
415/** @param {{ slug: string, key: string, root: string }} intent @param {number} number */
416export const prKey = (intent, number) => (otherRoot(intent) ? `${otherRoot(intent)}#${number}` : String(number))
417
418/**
419 * @typedef {{ slug: string, prompt: string, findings: string, progress: string, files: readonly string[], hasDebrief: boolean, updatedAt: number, source: 'main' | 'local', firstAuthor: string,
420 * key?: string, root?: string, repo?: string, repoName?: string, base?: string }} IntentFiles
421 * `updatedAt`: when it last changed (its last commit on main, or its files'); `source`: where it was read; `firstAuthor`: who first committed its folder.
422 * Read from one of several checkouts: `key` names it in the pane (its slug in the session's own checkout,
423 * `<repoName>/<slug>` in another), `root` is the checkout holding it, `repo` its repository's id ('' unknown), `repoName` the short name of its repository,
424 * `base` the branch that checkout's team merges into (main unless said).
425 * @typedef {ReturnType<typeof parseIntent>} Intent
426 */
427
428// A "- Current step:" or "- Next step:" line of progress.md, short; '' for none, a template's "<none>" or a dash.
429/** @param {string} text */
430const stepNote = text => (/^(<|none\b|n\/a\b|[-–—]\s*$)/i.test(text) ? '' : shortTitle(text, 110))
431
432/** @param {IntentFiles} input @param {Pack} [pack] */
433export const parseIntent = (input, pack = unreal) => {
434 const { prompt, progress } = input
435 // "parked: weather presets merged…" is a status too: take the leading word.
436 const status = /^[a-z]+/.exec(field(prompt, 'Status').toLowerCase())?.[0] ?? 'unknown'
437 const items = acceptanceItems(prompt, progress)
438 const findings = readFindings(input.findings, prompt)
439 return {
440 slug: input.slug,
441 title: /^#\s+(.+)$/m.exec(prompt)?.[1]?.trim() ?? input.slug,
442 goal: shortTitle(/^(.+?[.!?])(\s|$)/.exec(section(prompt, 'Goal').replace(/\s+/g, ' ').trim())?.[1] ?? section(prompt, 'Goal').replace(/\s+/g, ' ').trim(), 110),
443 area: normalizeArea(field(prompt, 'Area'), pack),
444 owner: field(prompt, 'Owner'),
445 issue: issueNumber(field(prompt, 'Issue')),
446 // The branch its work is on ("- Branch: `intent/login`"); '' for none or a template's placeholder.
447 branch: branchNamed(field(prompt, 'Branch').replace(/`/g, '')),
448 status,
449 // Why it is parked (or blocked): what follows the status word.
450 statusNote: field(prompt, 'Status').replace(/^[a-z]+\s*[:\-–—]?\s*/i, '').trim(),
451 acceptanceDone: items.filter(item => item.isDone).length,
452 acceptanceTotal: items.length,
453 // What the intent's view says of where it stands, with no prompt to the session: the items not yet
454 // met ("A2 (owed): Sand look." and "A2: (owed) Sand look." both read "Sand look"), and progress.md's own
455 // lines for the step in hand and the one after.
456 openItems: items.filter(item => !item.isDone).map(item => ({ id: item.id, text: shortTitle(item.text.replace(/^[\s:]*(?:\([^)]*\)[\s:]*)?/, ''), 90) })),
457 currentStep: stepNote(field(progress, 'Current step')),
458 thenStep: stepNote(field(progress, 'Next step')),
459 prs: intentPrs(progress, prompt),
460 findings: openOnes(findings),
461 // The ids of its findings that are settled here: another checkout's copy may still say open (waitingCalls).
462 settled: findings.filter(one => !one.isOpen).map(one => one.id),
463 hasReview: input.files.some(name => /review/i.test(name)) || /\b(plan|opus|design)[- ]review\b|reviewed by|after (an? )?(opus )?review/i.test(prompt + progress.slice(0, 20000)),
464 hasWorker: /^\s*[-*]?\s*\**worker\**\s*[:=-]\s*\S/im.test(progress) || /^(###\s+S\d+|-\s+S\d+\b)/m.test(progress),
465 hasDebrief: input.hasDebrief,
466 updatedAt: input.updatedAt,
467 source: input.source,
468 firstAuthor: input.firstAuthor,
469 key: input.key ?? input.slug,
470 root: input.root ?? '',
471 repo: input.repo ?? '',
472 repoName: input.repoName ?? '',
473 base: input.base ?? 'main',
474 }
475}
476
477// The checkout an intent lives in when it is not the session's own (its key is not its slug), else ''.
478/** @param {{ slug: string, key: string, root: string }} intent */
479export const otherRoot = intent => (intent.key === intent.slug ? '' : intent.root)
480
481/** @param {Intent | undefined} intent */
482export const directorCalls = intent => (intent && intent.status !== 'completed' ? intent.findings.filter(one => one.isDirectorCall || one.isBlocking) : [])
483
484// The calls that wait, each once however many checkouts hold its intent. Copies of one intent (one repository,
485// one slug: each worktree whose branch changed it shows its own) share their findings: one settled in any copy
486// waits in none, and the rest are offered from the tracked copy, else the session's own checkout's, else the
487// freshest (`intents` comes freshest first).
488/** @param {readonly Intent[]} intents @param {string | null} pinned @returns {{ intent: Intent, finding: Intent['findings'][number] }[]} */
489export const waitingCalls = (intents, pinned) => {
490 const copyOf = (/** @type {Intent} */ one) => `${one.repo || one.root}|${one.slug}`
491 const settled = new Set(intents.flatMap(one => one.settled.map(id => `${copyOf(one)}|${id}`)))
492 const rank = (/** @type {Intent} */ one) => (one.key === pinned ? 0 : otherRoot(one) === '' ? 1 : 2)
493 /** @type {Map<string, { intent: Intent, finding: Intent['findings'][number] }>} */
494 const waiting = new Map()
495 for (const intent of [...intents].sort((a, b) => rank(a) - rank(b))) {
496 for (const finding of directorCalls(intent)) {
497 const id = `${copyOf(intent)}|${finding.id}`
498 if (!settled.has(id) && !waiting.has(id)) waiting.set(id, { intent, finding })
499 }
500 }
501 return [...waiting.values()]
502}
503
504/** @param {{ owner: string }} intent @param {string} me */
505export const isMine = (intent, me) => me !== '' && isSamePerson(intent.owner, me)
506
507// The open intents that are yours, the tracked one (by key) first.
508/** @param {readonly Intent[]} intents @param {string} me @param {string | null} pinned */
509export const ownedIntents = (intents, me, pinned) => {
510 const mine = intents.filter(one => one.status !== 'completed' && isMine(one, me))
511 return [...mine.filter(one => one.key === pinned), ...mine.filter(one => one.key !== pinned)]
512}
513
514// The Owner line of an intent's prompt.md.
515/** @param {string} prompt */
516export const intentOwner = prompt => field(prompt, 'Owner')
517
518// Who to offer first when picking: yours, then your area, then open decisions, then the most recent.
519/** @param {readonly Intent[]} intents @param {string} me @param {string} area */
520export const pickCandidates = (intents, me, area) => {
521 const rank = (/** @type {Intent} */ one) => (me !== '' && isSamePerson(one.owner, me) ? 0 : 4) + (area !== '' && one.area !== area ? 2 : 0) + (directorCalls(one).length > 0 ? 0 : 1)
522 return intents.filter(one => one.status === 'active' || one.status === 'parked').sort((a, b) => rank(a) - rank(b) || b.updatedAt - a.updatedAt)
523}
524
525/** @param {readonly Intent[]} intents @param {string} text */
526export const searchIntents = (intents, text) => {
527 const words = text.toLowerCase().split(/[^a-z0-9]+/).filter(word => word.length >= 3)
528 return intents.filter(one => {
529 const hay = `${one.key} ${one.title} ${one.area} ${one.owner}`.toLowerCase().split(/[^a-z0-9]+/)
530 return one.status !== 'completed' && words.length > 0 && words.every(word => hay.some(part => part.startsWith(word)))
531 })
532}
533
534/** @param {Intent} one @param {string} me @param {PrStates} [prs] */
535export const intentLabel = (one, me, prs = {}) => {
536 const mine = isMine(one, me)
537 const calls = mine ? directorCalls(one).length : 0
538 const progress = one.acceptanceTotal > 0 ? `${one.acceptanceDone}/${one.acceptanceTotal}${isReadyToClose(one, prs) ? ' · ready to close' : ''}` : 'no checklist'
539 return `${one.slug} · ${one.area} · ${progress}${calls > 0 ? ` · ${calls} need${calls === 1 ? 's' : ''} you` : ''}${!mine && one.owner ? ` · ${one.owner}` : ''}${one.status === 'parked' ? ` · parked${one.statusNote ? `: ${shortTitle(one.statusNote, 90)}` : ''}` : ''}`
540}
541
542// ---------------------------------------------------------------- time and the Editor lock
543
544/** @param {number} ms @param {number} tz */
545export const localMinutes = (ms, tz) => {
546 const local = new Date(ms + tz * 60000)
547 return local.getUTCHours() * 60 + local.getUTCMinutes()
548}
549
550/** @param {number} ms @param {number} tz */
551export const clockText = (ms, tz) => {
552 const minutes = localMinutes(ms, tz)
553 return `${String(Math.floor(minutes / 60)).padStart(2, '0')}:${String(minutes % 60).padStart(2, '0')}`
554}
555
556// A prompt the person sent: typed at the terminal or the desktop (`composer`), or from a phone over Remote Control
557// (`bridge`). Not a schedule, a wakeup, a task's notice, another session, or a plugin's own prompt (an away window's work).
558/** @param {{ kind: string } | undefined} origin */
559export const isPersonOrigin = origin => origin?.kind === 'composer' || origin?.kind === 'bridge'
560
561/** @param {number} ms */
562export const durationText = ms => {
563 const total = Math.max(0, Math.round(ms / 60000))
564 return total >= 60 ? `${Math.floor(total / 60)}h${String(total % 60).padStart(2, '0')}m` : `${total}m`
565}
566
567/** @param {string} text */
568export const parseTzOffset = text => {
569 const match = /([+-])(\d{2}):?(\d{2})/.exec(text.trim())
570 return match ? (match[1] === '-' ? -1 : 1) * (Number(match[2]) * 60 + Number(match[3])) : null
571}
572
573// Evening by the person's clock: when "Heading off?" is offered unasked.
574/** @param {number} ms @param {number} tz */
575export const isEvening = (ms, tz) => {
576 const hour = Math.floor(localMinutes(ms, tz) / 60)
577 return hour >= 20 || hour < 5
578}
579
580/** @typedef {import('./packs/unreal.mjs').EditorLock} EditorLock */
581
582// A session's name from Claude Code's record of it (the lines a grep for its titles found):
583// the last title the person or the session set, else the last one Claude Code generated.
584/** @param {string} lines @returns {string} */
585export const sessionTitle = lines => {
586 const rows = lines.split(/\r?\n/)
587 /** @param {string} kind */
588 const last = kind => {
589 for (let index = rows.length - 1; index >= 0; index -= 1) {
590 const found = new RegExp(`"${kind}":"([^"]*)"`).exec(rows[index] ?? '')
591 if (found) return found[1] ?? ''
592 }
593 return ''
594 }
595 const raw = last('customTitle') || last('aiTitle')
596 let title = raw
597 try {
598 title = JSON.parse(`"${raw}"`)
599 } catch {
600 // an escape grep cut in half: the raw text is close enough
601 }
602 return title.replace(/[\u0000-\u001f]+/g, ' ').trim().slice(0, 60)
603}
604
605// ---------------------------------------------------------------- stages and the next step
606
607/** @typedef {import('./packs/index.mjs').Rung} Rung */
608/** @typedef {Record<string, Rung>} Evidence the pack's rungs; the Unreal pack's are build, automation, readback, pie and editor */
609
610/** @param {Pack} [pack] @returns {Evidence} */
611export const emptyEvidence = (pack = unreal) => pack.emptyEvidence()
612
613// A Status of completed wins; then every item met with every PR merged is ready to close, whatever proof this session saw.
614/** @param {Intent | undefined} intent @param {Evidence} evidence @param {string} role @param {PrStates} [prs] @param {Pack} [pack] @returns {keyof typeof STAGE_LABELS} */
615export const currentStage = (intent, evidence, role, prs = {}, pack = unreal) => {
616 if (intent?.status === 'completed') return intent.hasDebrief ? 'shipped' : 'ship'
617 if (!intent || intent.acceptanceTotal === 0) return 'plan'
618 if (isReadyToClose(intent, prs)) return 'close'
619 if (intent.acceptanceDone < intent.acceptanceTotal) return 'build'
620 return pack.isProven(evidence, role) ? 'ship' : 'prove'
621}
622
623// Asking the session what an intent is and where it stands, changing nothing. One that this checkout
624// does not have (or has as it is on main) is read from origin/main itself, read-only. `root`: the checkout
625// holding it, when that is not the session's own; git and the files are then read there. `base`: the branch
626// its team merges into, read in place of main.
627/** @param {string} slug @param {boolean} fromMain @param {string} [root] @param {string} [base] */
628export const aboutIntentPrompt = (slug, fromMain, root = '', base = 'main') => {
629 const files = ['prompt.md', 'findings.md', 'progress.md', 'log.md']
630 const git = root ? `git -C ${root}` : 'git'
631 const read = fromMain
632 ? `Read it from GitHub ${base}, since this checkout may not have it or may be behind: use \`${git} show origin/${base}:docs/intent/${slug}/<file>\` for ${files.join(', ')} (those that exist) and \`${git} log -5 --format="%cs %an %s" origin/${base} -- docs/intent/${slug}\` for its recent history, with GIT_OPTIONAL_LOCKS=0. Do not fetch, pull, check out, track it or write anything.`
633 : `Read ${root ? `${root}/` : ''}docs/intent/${slug}/ only; change nothing.`
634 return `Tell me about intent ${slug}${root ? ` in the checkout at ${root}` : ''} in under ten lines: what it is for, who owns it, its status and stage (Plan, Build, Prove, Ship) and why, its checklist progress, which decisions are open and whose they are, and what the next step would be. ${read}`
635}
636
637// Closing an intent, step 5 of the intent skill: what was read (every item met, and the PRs it names
638// merged; none named, the items alone) is confirmed first. `commit`: how the close ends.
639/** @param {string} slug @param {readonly number[]} prs @param {string} [commit] */
640export const closePrompt = (slug, prs, commit = 'commit as the skill says') => {
641 const named = andList(prs.map(number => `#${number}`))
642 const merged = prs.length === 0 ? '' : ` and ${prs.length === 1 ? `PR ${named} as` : `PRs ${named} as`} merged`
643 return `Close intent ${slug} as step 5 (Close) of .agents/skills/intent/SKILL.md says. Ather reads every acceptance row in docs/intent/${slug}/progress.md as met${merged}: confirm ${prs.length === 0 ? 'it from the files' : 'both from the files and gh'} first, and stop and tell me if ${prs.length === 0 ? 'it is' : 'either is'} not so. Then set Status: completed in prompt.md, add the changelog line, and ${commit}.`
644}
645
646// Drafting an intent's "done" checklist, shown before any work starts.
647/** @param {string} slug */
648export const checklistPrompt = slug =>
649 `Draft the acceptance checklist for intent ${slug} in docs/intent/${slug}/prompt.md: items with ids (A1, A2, ...), each with the proof that will show it is done, and no checkboxes (whether an item is met lives in progress.md). Show it to me before the worker starts.`
650
651/**
652 * The one next step for the tracked intent and the person's role.
653 * @param {string} role @param {Intent | undefined} intent @param {Evidence} evidence @param {number} workers @param {string} me @param {PrStates} [prs] @param {Pack} [pack]
654 * `isLook`: a step that only reads where the intent stands. Its files answer it, so the pane shows the
655 * intent's view and nothing goes to the session; `prompt` is for a surface that cannot (the Paseo version).
656 * @returns {{ key: string, label: string, prompt: string, hint: string, isDraft?: boolean, isLook?: boolean } | undefined}
657 */
658export const nextStep = (role, intent, evidence, workers, me, prs = {}, pack = unreal) => {
659 if (!intent) return { key: 'start', label: 'Start an intent', prompt: '/intent ', hint: 'Type what you want after /intent; the intent skill takes it from there.', isDraft: true }
660 const slug = intent.slug
661 if (!isMine(intent, me)) {
662 return { key: 'follow', label: 'See where it stands', hint: `${intent.owner || 'Its owner'}'s intent: where it stands, nothing is changed.`, isLook: true, prompt: aboutIntentPrompt(slug, intent.source === 'main', otherRoot(intent), intent.base) }
663 }
664 const stage = currentStage(intent, evidence, role, prs, pack)
665 if (stage === 'close') {
666 const named = andList(intent.prs.map(number => `#${number}`))
667 return {
668 key: 'close',
669 label: 'Close the intent',
670 hint: `Every item is met and ${intent.prs.length === 1 ? `PR ${named} is` : `PRs ${named} are`} merged; the session closes it the intent skill's way.`,
671 prompt: closePrompt(slug, intent.prs),
672 }
673 }
674 if (stage === 'plan') {
675 return { key: 'checklist', label: 'Write the "done" checklist', hint: 'The session drafts it and shows you before any work starts.', prompt: checklistPrompt(slug) }
676 }
677 if (stage === 'build') {
678 if (!intent.hasReview && !intent.hasWorker && intent.acceptanceDone === 0 && workers === 0) {
679 return { key: 'review', label: 'Get the plan checked', hint: 'A second agent looks for gaps and wrong assumptions before anyone builds.', prompt: `Have an Opus agent review the plan for intent ${slug} (docs/intent/${slug}/prompt.md) against the repository before any worker starts: gaps, risks, wrong assumptions. Fold the accepted findings into the intent and show me what changed.` }
680 }
681 if (intent.hasWorker || workers > 0) {
682 return { key: 'progress', label: 'See how the work is going', hint: 'Where it stands against its checklist.', isLook: true, prompt: `Summarise intent ${slug} against its checklist: what is done with evidence, what is next, what is blocked. Five lines.` }
683 }
684 return { key: 'brief', label: 'Start the work', hint: pack.prompts.briefHint, prompt: pack.prompts.brief(role, slug) }
685 }
686 if (stage === 'prove') {
687 const missing = role === '' ? [pack.anyProofText] : pack.requiredRungs(role).filter(rung => evidence[rung]?.state !== 'pass').map(rung => pack.rungLabels[rung] ?? rung)
688 const prompt = pack.prompts.prove(role, slug)
689 const own = pack.ownCheck && role === pack.ownCheck.role ? pack.ownCheck.proveHint : ''
690 return { key: 'prove', label: 'Prove it works', hint: `Still needed: ${andList(missing)}. Ather reads this from tool output, not from what the session says.${own}`, prompt }
691 }
692 if (stage === 'ship' && intent.status === 'completed') {
693 return {
694 key: 'debrief',
695 label: 'Write up what was learned',
696 hint: 'What was proven, lost and decided, and rules worth keeping.',
697 prompt: `Debrief intent ${slug}. List what was proven and with what evidence, what was lost or overwritten (lost optimisation vs broken feature), every decision taken on my behalf, and the gotchas we hit. Write it to ${pack.debriefPath(slug)}, and propose which recurring gotchas should become a skill or AGENTS.md rule for the owners (${pack.owners}).`,
698 }
699 }
700 if (stage === 'ship') {
701 return { key: 'land', label: 'Ship it', hint: pack.prompts.shipHint(role), prompt: pack.prompts.ship(role, slug) }
702 }
703 return undefined
704}
705hooks/state.mjs 970 lines1// @ts-check
2// Ather Automata: the one owner of what the two halves share. The store keys,
3// how stored values are read back, and every change. Changes run one at a time
4// so no read-modify-write can interleave with another; reads never wait. Both
5// halves import this module, so its change queue and version are shared.
6//
7// It takes an Io (closures over `$`, built in each half) because `$` itself may
8// only be passed to functions in the file that holds it.
9
10import { isHolding, isRecordingQuestions, ledgerWithWindow, newWindow, nextLedgerId, nextParkId, offAway, pendingEntry } from './away.mjs'
11import { countGotcha, recurringGotchas, writtenRuleOf } from './guards.mjs'
12import { addPersonAlias, emptyEvidence, intentOwner, isSamePerson, personId } from './model.mjs'
13import { forgetPack, packFor } from './packs/index.mjs'
14import { unreal } from './packs/unreal.mjs'
15import { baseOf } from './team.mjs'
16import { checkoutId, checkoutOf, normalFolder, readWorkspace, repoId } from './workspace.mjs'
17import { groupByOf } from './worklist.mjs'
18import { paneViewOf } from './home.mjs'
19
20/**
21 * @typedef {{
22 * get: (key: string) => Promise<unknown>, set: (key: string, value: unknown) => Promise<void>, remove: (key: string) => Promise<void>, keys: () => Promise<string[]>,
23 * read: (path: string) => Promise<string | null>, write: (path: string, text: string) => Promise<void>, exists: (path: string) => Promise<boolean>,
24 * sessionId: () => Promise<string>, root: () => Promise<string>, gitUser: (root?: string) => Promise<string>, redraw: () => void,
25 * list?: (path: string) => Promise<{ name: string, kind: string, mtimeMs?: number }[]>,
26 * origin?: (root: string) => Promise<string | null>, repo?: () => Promise<string>,
27 * real?: (folder: string) => Promise<string>,
28 * worktrees?: (root: string) => Promise<string | null>, gitEmail?: (root?: string) => Promise<string>
29 * }} Io `gitUser`: git's user.name in the checkout at `root` (a repository may set its own), else in the session folder.
30 * `gitEmail`: git's user.email there, the same way; its name before @ is another name the person goes by
31 * (an intent's Owner may say "vu.le" for "Hoàng Vũ").
32 * `origin`: the remote.origin.url of the checkout at `root`, '' when it has none, null when git could not say.
33 * `repo`: the lane's repository id (repoId), which scopes what is kept per repository and, with the lane's folder,
34 * per checkout (checkoutId); without it the keys are unscoped (as before 0.2.5, and as the Paseo version still keeps them).
35 * `real`: the folder a path really lands in, behind any symbolic link; without it an id holds the folder as given.
36 * `worktrees`: what `git worktree list --porcelain` prints in the checkout at `root`, '' when git refused, null when
37 * git could not say (the workspace is then read again); without it the workspace holds only the session's checkout.
38 * @typedef {import('./packs/index.mjs').Pack} Pack
39 * @typedef {import('./away.mjs').Away} Away
40 * @typedef {import('./model.mjs').Evidence} Evidence
41 */
42
43// A key's id within one repository, or one checkout of it (checkoutId): the same slug or person in another is
44// another key. No repository (an Io without `repo`) keeps the unscoped key.
45/** @param {string} scope @param {string} id */
46const inScope = (scope, id) => (scope ? `${scope}|${id}` : id)
47
48const KEY = {
49 away: (/** @type {string} */ sid) => `away:${sid}`,
50 // The tracked intent: its slug in the session's own checkout, `{ slug, root }` in another.
51 pinned: (/** @type {string} */ sid) => `pinned:${sid}`,
52 evidence: (/** @type {string} */ sid) => `evidence:${sid}`,
53 lost: (/** @type {string} */ sid) => `lost:${sid}`,
54 // The intents this session stopped tracking: a write into one does not track it again.
55 untracked: (/** @type {string} */ sid) => `untracked:${sid}`,
56 // This session's keep-warm choice (/warm) and the TTL it learned.
57 warm: (/** @type {string} */ sid) => `warm:${sid}`,
58 // A pack's roles are its own: a tech artist in S2 is not a role in a web repository. The Unreal pack's key is unprefixed.
59 role: (/** @type {string} */ me, /** @type {string} */ prefix = '') => `role:${prefix}${personId(me)}`,
60 area: (/** @type {string} */ me) => `area:${personId(me)}`,
61 tour: (/** @type {string} */ me) => `tour:${personId(me)}`,
62 nudged: (/** @type {string} */ me) => `nudged:${personId(me)}`,
63 // How this person groups the teammates' intents in Everything open (person, area, stage or none).
64 groupBy: (/** @type {string} */ me) => `groupBy:${personId(me)}`,
65 // Home's view for this person: advanced or simple.
66 view: (/** @type {string} */ me) => `view:${personId(me)}`,
67 // The sessions holding an away window for this person, so a new session finds them without a scan.
68 windows: (/** @type {string} */ person) => `windows:${person}`,
69 // Kept per repository: gh reads a repository's issues and PRs, whichever of its checkouts asks.
70 issues: (/** @type {string} */ me, /** @type {string} */ repo) => `issues:${inScope(repo, personId(me))}`,
71 // Kept per checkout: two clones of one repository each have their own "Continue …" and their own files.
72 last: (/** @type {string} */ me, /** @type {string} */ checkout) => `last:${inScope(checkout, personId(me))}`,
73 // What edits recorded in an intent, newest last: shared by every session on that checkout.
74 changes: (/** @type {string} */ slug, /** @type {string} */ checkout) => `changes:${inScope(checkout, slug)}`,
75 // What gh last said about the PRs intents name: shared by every session on the machine.
76 prs: (/** @type {string} */ repo) => (repo ? `prStates:${repo}` : 'prStates'),
77 tz: 'tz',
78 hits: 'gotchaHits',
79 ruled: 'gotchaRuled',
80 score: 'score',
81 // What keeping the cache warm did on this machine.
82 warmLedger: 'warmLedger',
83}
84// What belongs to this lane and follows it to a new session id after /clear.
85const LANE_KEYS = [KEY.away, KEY.pinned, KEY.evidence, KEY.lost, KEY.untracked, KEY.warm]
86// Keep-warm's keys, for warm-store.mjs: the session's choice moves with its lane, the ledger is the machine's.
87export const WARM_KEYS = { choice: KEY.warm, ledger: KEY.warmLedger }
88
89let queue = Promise.resolve()
90// The one change queue: exported for warm-store.mjs, whose writes take their turn with every other change.
91/** @template T @param {() => Promise<T>} task @returns {Promise<T>} */
92export const serial = task => {
93 const run = queue.then(task)
94 queue = run.then(
95 () => undefined,
96 () => undefined,
97 )
98 return run
99}
100
101// An issue list older than this is not shown: gh may have stopped answering.
102const ISSUES_TTL_MS = 24 * 60 * 60 * 1000
103
104// Bumped on every change, so a drawing can tell its cached view is stale.
105let version = 0
106export const stateVersion = () => version
107/** @param {Io} io */
108const changed = io => {
109 version += 1
110 io.redraw()
111}
112
113// ---------------------------------------------------------------- the lane
114
115/** @typedef {{ root: string, repo: string, isS2: boolean, me: string, pack: Pack, base: string, isSure: boolean }} Checkout `base`: the branch its team merges into (team.mjs baseOf) */
116// The session's lane by its folder, and each checkout's by its root.
117/** @type {Map<string, Promise<Checkout>>} */
118const lanes = new Map()
119/** @type {Map<string, Promise<Checkout>>} */
120const rootLanes = new Map()
121// Where each folder really lands, asked once per folder.
122/** @type {Map<string, Promise<string>>} */
123const realFolders = new Map()
124
125// The folder an id is made from: where the path really lands, so a checkout reached through a symbolic link
126// (macOS's /tmp, a linked projects folder) has the id it has by its real path. Only for ids: files are read
127// and git is run in the folder as given. An Io that cannot say, or a folder it could not resolve, keeps it as given.
128/** @param {Io} io @param {string} folder */
129const realFolder = (io, folder) => {
130 const { real } = io
131 if (!real || folder === '') return Promise.resolve(folder)
132 const cached = realFolders.get(folder)
133 if (cached) return cached
134 const reading = real(folder).then(
135 found => found || folder,
136 () => {
137 // Asked again next time, never kept.
138 realFolders.delete(folder)
139 return folder
140 },
141 )
142 realFolders.set(folder, reading)
143 return reading
144}
145
146// Roots read without intents. One that has them at a later read got them in this session:
147// its profile is new, so its pack is chosen again and each half is told.
148/** @type {Set<string>} */
149const bare = new Set()
150/** @type {Map<string, (pack: Pack) => unknown>} */
151const setUpHandlers = new Map()
152
153// What a half does when a repository is set up mid-session; one handler per `who`, the last one kept.
154/** @param {string} who @param {(pack: Pack) => unknown} handler */
155export const onSetUp = (who, handler) => void setUpHandlers.set(who, handler)
156
157// Who and where, read once per checkout and shared by both halves. `isS2`: the repository runs intents
158// (a docs/intent folder), whatever its kind; `pack` says which kind (packs/index.mjs, once per session);
159// `repo` which repository it is (repoId), when the Io can say. `userRoot`: where git's user name is read,
160// none for the session's own lane, which reads it in the session folder as it always has.
161/** @param {Io} io @param {string} root @param {string} [userRoot] */
162const readCheckout = async (io, root, userRoot) => {
163 const list = io.list ?? (async () => [])
164 const { pack, profile, defaultBranch } = await packFor({ read: io.read, exists: io.exists, list, sessionId: io.sessionId }, root).catch(() => ({ pack: unreal, profile: null, defaultBranch: '' }))
165 const origin = io.origin ? await io.origin(root).catch(() => null) : ''
166 const me = await (userRoot === undefined ? io.gitUser() : io.gitUser(userRoot)).catch(() => '')
167 const email = io.gitEmail ? await (userRoot === undefined ? io.gitEmail() : io.gitEmail(userRoot)).catch(() => '') : ''
168 if (me !== '' && email.includes('@')) addPersonAlias(me, email.split('@')[0] ?? '')
169 return { root, repo: io.origin ? repoId(origin ?? '', await realFolder(io, root)) : '', isS2: await io.exists(`${root}/docs/intent`), me, pack, base: baseOf(profile, defaultBranch), isSure: me !== '' && origin !== null }
170}
171
172/** @param {typeof lanes} cache @param {string} key @param {() => Promise<Checkout>} read */
173const cachedLane = (cache, key, read) => {
174 const cached = cache.get(key)
175 if (cached) return cached
176 const reading = read()
177 cache.set(key, reading)
178 // A git name or origin that failed to read (a slow first start) is asked again next time, never kept.
179 void reading.then(found => {
180 if (!found.isSure && cache.get(key) === reading) cache.delete(key)
181 })
182 return reading
183}
184
185// The session's lane: the lane of its own folder's root, which need not be a checkout.
186/** @param {Io} io @param {string} cwd */
187export const lane = (io, cwd) =>
188 cachedLane(lanes, cwd, async () => {
189 const root = (await io.root().catch(() => cwd)) || cwd
190 const isS2 = await io.exists(`${root}/docs/intent`)
191 const isSetUp = isS2 && bare.delete(root)
192 if (!isS2) bare.add(root)
193 if (isSetUp) {
194 await forgetPack({ sessionId: io.sessionId }, root)
195 // The same folder read as a workspace checkout (laneAt) was kept without intents, with the old pack.
196 for (const kept of [...rootLanes.keys()]) {
197 if (normalFolder(kept) !== normalFolder(root)) continue
198 rootLanes.delete(kept)
199 await forgetPack({ sessionId: io.sessionId }, kept)
200 }
201 }
202 const found = { ...(await readCheckout(io, root)), isS2 }
203 // A handler that fails must not cost the reading.
204 if (isSetUp) for (const handler of setUpHandlers.values()) await Promise.resolve().then(() => handler(found.pack)).catch(() => undefined)
205 return found
206 })
207
208// Any checkout's lane, by its root: its own pack and repository.
209/** @param {Io} io @param {string} root */
210export const laneAt = (io, root) => cachedLane(rootLanes, root, () => readCheckout(io, root, root))
211
212// The checkout a command's folder is in (null: the session folder; a relative one is taken from the session's
213// root) and its lane. `isOwn`: it is the session's own checkout, or in no checkout at all; both use the session's lane.
214/** @param {Io} io @param {Checkout} session the session's lane @param {string | null} folder @returns {Promise<{ lane: Checkout, isOwn: boolean }>} */
215export const folderLane = async (io, session, folder) => {
216 if (folder === null) return { lane: session, isOwn: true }
217 const root = await checkoutOf(io, /^([A-Za-z]:[\\/]|[\\/])/.test(folder) ? folder : `${session.root}/${folder}`)
218 if (root === null || root === (await checkoutOf(io, session.root))) return { lane: session, isOwn: true }
219 return { lane: await laneAt(io, root), isOwn: false }
220}
221
222/** @typedef {{ roots: string[], left: string[], isSure: boolean }} Workspace */
223/** @type {Map<string, Promise<Workspace>>} */
224const workspaces = new Map()
225// What the debug log last heard of each workspace: a read that finds the same is not said again.
226/** @type {Map<string, string>} */
227const workspacesSaid = new Map()
228
229// The session's workspace (workspace.mjs), read once per session folder. A read git could not answer in full
230// (not sure) is shared by the callers waiting on it and then forgotten: the next call reads again.
231/** @param {Io} io @param {string} folder the session folder @param {(line: string) => void} log */
232const readWorkspaceOnce = (io, folder, log) => {
233 const key = normalFolder(folder)
234 const cached = workspaces.get(key)
235 if (cached) return cached
236 const { real, worktrees } = io
237 const files = { read: io.read, exists: io.exists, ...(worktrees ? { worktrees } : {}), ...(real ? { real: (/** @type {string} */ one) => realFolder(io, one) } : {}) }
238 const reading = readWorkspace(files, folder)
239 .catch(() => /** @type {Workspace} */ ({ roots: [], left: [], isSure: true }))
240 .then(found => {
241 if (!found.isSure && workspaces.get(key) === reading) workspaces.delete(key)
242 const lines = [`Ather: workspace ${found.roots.join(', ') || '(no checkout)'}`, ...(found.left.length > 0 ? [`Ather: workspace is full; left out ${found.left.join(', ')}`] : [])]
243 if (workspacesSaid.get(key) !== lines.join('\n')) for (const line of lines) log(line)
244 workspacesSaid.set(key, lines.join('\n'))
245 return found
246 })
247 workspaces.set(key, reading)
248 return reading
249}
250
251// The session's checkout and its clone's worktrees after it (`roots`), shared by both halves. `isSure` false: git
252// could not list the worktrees, and the next call reads again. `log` hears what the workspace holds and what
253// the limit left out, once per read that finds something new.
254/** @param {Io} io @param {string} folder the session folder @param {(line: string) => void} [log] @returns {Promise<{ roots: string[], isSure: boolean }>} */
255export const workspace = (io, folder, log = () => undefined) => readWorkspaceOnce(io, folder, log).then(({ roots, isSure }) => ({ roots, isSure }))
256
257/** @param {Io} io */
258const repoOf = io => (io.repo ? io.repo().catch(() => '') : Promise.resolve(''))
259
260/** @param {Io} io @param {string} root */
261const isSessionRoot = async (io, root) => normalFolder(root) === normalFolder(await io.root().catch(() => ''))
262
263// The checkout a folder holding docs/intent is, by its id: the session's own for its root, else that folder's.
264/** @param {Io} io @param {string} [root] */
265const checkoutAt = async (io, root) => (root === undefined || (await isSessionRoot(io, root)) ? checkoutId(await repoOf(io), await realFolder(io, await io.root().catch(() => ''))) : checkoutId((await laneAt(io, normalFolder(root))).repo, await realFolder(io, root)))
266
267// Before 0.2.5 a key had no repository in it. A scoped key not written yet reads the unscoped one, once
268// per upgrade: the next write goes to the scoped key, and the old one ages out on its own.
269/** @param {Io} io @param {string} scoped @param {string} legacy */
270const readScoped = async (io, scoped, legacy) => {
271 const value = await io.get(scoped)
272 return value !== undefined || scoped === legacy ? value : io.get(legacy)
273}
274
275// For /ather where there were no intents: the person may have added them in this session. A kept
276// reading without intents is dropped once the folder is there, and the checkout read again. A lane
277// that runs intents is kept as read.
278/** @param {Io} io @param {string} cwd */
279export const laneAgain = async (io, cwd) => {
280 const kept = lane(io, cwd)
281 const found = await kept
282 if (found.isS2 || !(await io.exists(`${found.root}/docs/intent`))) return found
283 if (lanes.get(cwd) === kept) lanes.delete(cwd)
284 return lane(io, cwd)
285}
286
287/** @param {Io} io */
288export const sessionId = io => io.sessionId()
289
290// After /clear the process goes on under a new session id and no session.start fires:
291// this lane's window, tracked intent, evidence, lost-edits flag and untracked intents move to it. Only
292// /clear moves them; a resume returns to another conversation, whose state is its own.
293/** @param {Io} io @param {string} from @param {string} to */
294export const moveLane = (io, from, to) =>
295 serial(async () => {
296 const away = /** @type {Away | undefined} */ (await io.get(KEY.away(from)))
297 for (const key of LANE_KEYS) {
298 const value = await io.get(key(from))
299 if (value === undefined) continue
300 if ((await io.get(key(to))) === undefined) await io.set(key(to), value)
301 await io.remove(key(from))
302 }
303 if (away?.person) await setIndex(io, away.person, list => [...list.filter(sid => sid !== from), to])
304 changed(io)
305 })
306
307/** @param {Io} io @param {string} person @param {(list: string[]) => string[]} change */
308const setIndex = async (io, person, change) => {
309 const list = /** @type {string[]} */ ((await io.get(KEY.windows(person))) ?? [])
310 const next = [...new Set(change(list))]
311 if (next.length === 0) await io.remove(KEY.windows(person))
312 else await io.set(KEY.windows(person), next)
313}
314
315// ---------------------------------------------------------------- reading
316
317// A session's stored window, off when it has none.
318/** @param {Io} io @param {string} sid @returns {Promise<Away>} */
319const awayOf = async (io, sid) => /** @type {Away} */ ({ ...offAway(), .../** @type {object} */ ((await io.get(KEY.away(sid))) ?? {}) })
320/** @param {Io} io */
321export const readAway = async io => awayOf(io, await io.sessionId())
322// Where evidence is kept: with the tracked intent, so yesterday's build and tests still count
323// today; with the session when nothing is tracked. Each record is good for a day (EVIDENCE_TTL_MS).
324/** @param {Io} io */
325export const evidenceScope = async io => {
326 const pin = await readPin(io)
327 return pin === null ? io.sessionId() : intentScope(io, pin.slug, pin.isOwn ? undefined : pin.root)
328}
329
330// Where a shell command's proof goes, by the checkout it ran in (`root`, its top folder): the tracked
331// intent's checkout proves the intent; otherwise it is this session's proof there, `<sid>` in its own
332// checkout and `<sid>|<checkout id>` in another.
333/** @param {Io} io @param {{ isOwn: boolean, repo: string, root?: string }} checkout */
334export const checkoutScope = async (io, checkout) => {
335 const pin = await readPin(io)
336 const isIntents = pin !== null && (checkout.isOwn ? pin.isOwn : !pin.isOwn && normalFolder(pin.root) === normalFolder(checkout.root ?? ''))
337 if (isIntents) return evidenceScope(io)
338 return checkout.isOwn ? io.sessionId() : `${await io.sessionId()}|${checkoutId(checkout.repo, await realFolder(io, checkout.root ?? ''))}`
339}
340
341// An intent's evidence scope: the intent in its checkout, as evidenceScope names it. `root`: the folder
342// holding its docs/intent, when that is not the session's.
343/** @param {Io} io @param {string} slug @param {string} [root] */
344export const intentScope = async (io, slug, root) => inScope(await checkoutAt(io, root), slug)
345
346// What is kept for a scope: an intent's from before 0.2.5 too, while its scoped record has none. Only an
347// intent in the session's own checkout: that proof was never another checkout's.
348/** @param {Io} io @param {string} scope */
349const storedEvidence = async (io, scope) => {
350 const own = await checkoutAt(io)
351 const legacy = own && scope.startsWith(`${own}|`) ? scope.slice(own.length + 1) : scope
352 return /** @type {Record<string, any>} */ ((await readScoped(io, KEY.evidence(scope), KEY.evidence(legacy))) ?? {})
353}
354
355// Proof older than this no longer counts: the code has likely moved on since.
356const EVIDENCE_TTL_MS = 24 * 60 * 60 * 1000
357
358// What is kept for a command that is no gate, on a rung that gates declare. No gate has this key.
359const NO_GATE = ''
360
361/**
362 * A rung that gates declare, from the result kept for each: passed when every gate passed, failed when one
363 * failed (or a command that is no gate did, since the rung's gates last ran), else not proven. A passed
364 * rung is as old as its oldest result, so proof from before a session is never taken for that session's.
365 * @param {Record<string, import('./model.mjs').Rung> | undefined} kept @param {readonly string[]} all the gates that declare the rung
366 * @returns {import('./model.mjs').Rung}
367 */
368const rungOfGates = (kept, all) => {
369 const fresh = [...all, NO_GATE].flatMap(key => {
370 const one = kept?.[key]
371 return one && Date.now() - (one.at ?? 0) < EVIDENCE_TTL_MS ? [{ key, ...one }] : []
372 })
373 const byAge = [...fresh].sort((a, b) => (a.at ?? 0) - (b.at ?? 0))
374 const stamp = (/** @type {typeof fresh[number] | undefined} */ one) => (one ? { at: one.at, by: one.by } : {})
375 const failed = byAge.filter(one => one.state === 'fail').at(-1)
376 if (failed) return { state: 'fail', detail: all.length > 1 && failed.key !== NO_GATE ? `${failed.key}: ${failed.detail}`.slice(0, 120) : failed.detail, ...stamp(failed) }
377 const passed = byAge.filter(one => one.state === 'pass' && one.key !== NO_GATE)
378 if (all.length === 1) {
379 const only = fresh.find(one => one.key !== NO_GATE)
380 return only ? { state: only.state, detail: only.detail, ...stamp(only) } : { state: 'none', detail: '' }
381 }
382 if (passed.length === all.length) return { state: 'pass', detail: `${all.length} gates passed`, ...stamp(passed[0]) }
383 return { state: 'none', detail: `${passed.length} of ${all.length} gates passed`, ...stamp(byAge.at(-1)) }
384}
385
386/** @param {Io} io @param {string} scope from evidenceScope @param {Pack} [pack] @returns {Promise<Evidence>} */
387export const readEvidence = async (io, scope, pack = unreal) => {
388 const stored = /** @type {Record<string, { state: string, detail: string, at?: number, gates?: Record<string, import('./model.mjs').Rung> }>} */ (await storedEvidence(io, scope))
389 const fresh = Object.fromEntries(Object.entries(stored).filter(([, rung]) => Date.now() - (rung.at ?? 0) < EVIDENCE_TTL_MS))
390 const gated = Object.fromEntries(Object.entries(pack.rungGates ?? {}).map(([rung, all]) => [rung, rungOfGates(stored[rung]?.gates, all)]))
391 return /** @type {Evidence} */ ({ ...emptyEvidence(pack), ...fresh, ...gated })
392}
393
394// A session as people see it named: the first 8 hex of its id, as the Editor lock and the tab list show it.
395/** @param {string} sid */
396export const shortSession = sid => sid.slice(0, 8)
397
398// Writes one scope's evidence, each record stamped with when it was seen and `by` the session that saw it.
399/** @param {Io} io @param {string} scope @param {Partial<Evidence>} change */
400const writeEvidence = async (io, scope, change) => {
401 const stored = await storedEvidence(io, scope)
402 const by = shortSession(await io.sessionId())
403 const stamped = Object.fromEntries(Object.entries(change).map(([rung, value]) => [rung, { ...value, at: Date.now(), by }]))
404 await io.set(KEY.evidence(scope), { ...stored, ...stamped })
405 changed(io)
406}
407// The tracked intent as stored: a plain slug is in the session's own root.
408/** @param {Io} io @returns {Promise<{ slug: string, root: string, isOwn: boolean } | null>} */
409const readPin = async io => {
410 const value = /** @type {unknown} */ (await io.get(KEY.pinned(await io.sessionId())))
411 if (typeof value === 'string') return { slug: value, root: await io.root().catch(() => ''), isOwn: true }
412 const pin = /** @type {{ slug?: unknown, root?: unknown } | null | undefined} */ (value)
413 return typeof pin?.slug === 'string' && typeof pin.root === 'string' ? { slug: pin.slug, root: pin.root, isOwn: false } : null
414}
415/** @param {Io} io @returns {Promise<string | null>} */
416export const readPinned = async io => (await readPin(io))?.slug ?? null
417// The tracked intent and the folder holding its docs/intent.
418/** @param {Io} io @returns {Promise<{ slug: string, root: string } | null>} */
419export const readTracked = async io => {
420 const pin = await readPin(io)
421 return pin && { slug: pin.slug, root: pin.root }
422}
423// The tracked intent with the lane its files are read with: the session's own lane, or its checkout's.
424/** @param {Io} io @param {string} cwd @returns {Promise<{ slug: string, isOwn: boolean, lane: Checkout } | null>} */
425export const trackedLane = async (io, cwd) => {
426 const pin = await readPin(io)
427 if (pin === null) return null
428 return { slug: pin.slug, isOwn: pin.isOwn, lane: pin.isOwn ? await lane(io, cwd) : await laneAt(io, pin.root) }
429}
430/** @param {Io} io @returns {Promise<{ paths: string[], isDisclosed: boolean } | null>} */
431export const readLost = async io => /** @type {any} */ ((await io.get(KEY.lost(await io.sessionId()))) ?? null)
432/** @param {Io} io */
433export const readTz = async io => Number(await io.get(KEY.tz)) || 0
434/** @param {Io} io @param {string} me @param {Pack} [pack] */
435export const readProfile = async (io, me, pack = unreal) => ({
436 role: String((await io.get(KEY.role(me, pack.roleKey))) ?? ''),
437 area: String((await io.get(KEY.area(me))) ?? ''),
438 tourDone: /** @type {{ isDone?: boolean } | undefined} */ (await io.get(KEY.tour(me)))?.isDone === true,
439 isNudged: (await io.get(KEY.nudged(me))) === true,
440})
441// A trap whose rule is already written in the checkout is not offered again, however many sessions hit it.
442/** @param {Io} io @param {Pack} [pack] */
443export const readRecurring = async (io, pack = unreal) => {
444 const recurring = recurringGotchas(/** @type {any} */ ((await io.get(KEY.hits)) ?? {}), /** @type {string[]} */ ((await io.get(KEY.ruled)) ?? []), pack)
445 if (recurring.length === 0) return recurring
446 const root = await io.root().catch(() => '')
447 const isWritten = await Promise.all(recurring.map(async one => {
448 const rule = writtenRuleOf(one.id, pack)
449 return Boolean(rule && root && (await io.read(`${root}/${rule.file}`))?.includes(rule.text))
450 }))
451 return recurring.filter((_, index) => !isWritten[index])
452}
453// The issues, PR records and PR states below are the session's repository's, or with `repo` that repository's.
454/** @param {Io} io @param {string} me @param {string} [repo] @returns {Promise<import('./issues.mjs').Issue[]>} */
455export const readIssues = async (io, me, repo) => {
456 const cached = /** @type {{ at?: number, list?: import('./issues.mjs').Issue[] } | undefined} */ (await io.get(KEY.issues(me, repo ?? (await repoOf(io)))))
457 return cached?.list && Date.now() - (cached.at ?? 0) < ISSUES_TTL_MS ? cached.list : []
458}
459/** @param {Io} io @param {string} [repo] @returns {Promise<Record<string, import('./prs.mjs').PrRecord>>} */
460export const readPrRecords = async (io, repo) => /** @type {Record<string, import('./prs.mjs').PrRecord>} */ ((await io.get(KEY.prs(repo ?? (await repoOf(io))))) ?? {})
461// PR number → its last read state, for the pure readers in model.mjs.
462/** @param {Io} io @param {string} [repo] @returns {Promise<import('./model.mjs').PrStates>} */
463export const readPrStates = async (io, repo) => Object.fromEntries(Object.entries(await readPrRecords(io, repo)).map(([number, record]) => [number, record.state]))
464// The person's "Continue …" in a checkout: the session's, or with `root` the one holding that docs/intent.
465/** @param {Io} io @param {string} me @param {string} [root] @returns {Promise<string | null>} */
466export const readLast = async (io, me, root) => {
467 const scoped = KEY.last(me, await checkoutAt(io, root))
468 // Only the session's own checkout reads through to the key from before 0.2.5.
469 const isOwn = root === undefined || (await isSessionRoot(io, root))
470 return /** @type {string | null} */ ((await readScoped(io, scoped, isOwn ? KEY.last(me, '') : scoped)) ?? null)
471}
472// The person's grouping for Everything open; Person until they choose another.
473/** @param {Io} io @param {string} me */
474export const readGroupBy = async (io, me) => groupByOf(await io.get(KEY.groupBy(me)))
475// The person's Home view; Advanced until they choose Simple.
476/** @param {Io} io @param {string} me */
477export const readPaneView = async (io, me) => paneViewOf(await io.get(KEY.view(me)))
478/** @param {Io} io */
479export const readScore = async io => /** @type {Record<string, number>} */ ((await io.get(KEY.score)) ?? {})
480
481// ---------------------------------------------------------------- changing
482
483// A setter whose write shows nothing new (the same issues read again, the same PR states) stamps its time and
484// draws nothing again: a redraw can lose a press on the desktop (console.mjs, redrawAged).
485
486/** @param {Io} io @param {string} me @param {import('./issues.mjs').Issue[]} issues @param {string} [repo] */
487export const setIssues = (io, me, issues, repo) =>
488 serial(async () => {
489 const shown = await readIssues(io, me, repo)
490 await io.set(KEY.issues(me, repo ?? (await repoOf(io))), { at: Date.now(), list: issues })
491 if (JSON.stringify(issues) !== JSON.stringify(shown)) changed(io)
492 })
493
494// A PR record not read again for this long is dropped: its intent has closed or moved on.
495const PRS_TTL_MS = 30 * 24 * 60 * 60 * 1000
496
497// What gh just said about some PRs ('UNREAD' when it could not say), each stamped `at`.
498/** @param {Io} io @param {import('./model.mjs').PrStates} states @param {number} at @param {string} [repo] */
499export const setPrStates = (io, states, at, repo) =>
500 serial(async () => {
501 if (Object.keys(states).length === 0) return
502 const scope = repo ?? (await repoOf(io))
503 const records = await readPrRecords(io, scope)
504 const kept = Object.entries(records).filter(([, record]) => at - record.at < PRS_TTL_MS)
505 await io.set(KEY.prs(scope), { ...Object.fromEntries(kept), ...Object.fromEntries(Object.entries(states).map(([number, value]) => [number, { state: value, at }])) })
506 if (kept.length < Object.keys(records).length || Object.entries(states).some(([number, value]) => records[number]?.state !== value)) changed(io)
507 })
508
509const CHANGES_KEPT = 20
510const CHANGES_TTL_MS = 36 * 60 * 60 * 1000
511
512/** @typedef {import('./changes.mjs').Change & { at: number }} Recorded */
513
514// The lines an intent gained, newest first, from `since` on (the start of the person's day).
515// `root`: the folder holding its docs/intent, when that is not the session's.
516/** @param {Io} io @param {string} slug @param {number} since @param {string} [root] @returns {Promise<Recorded[]>} */
517export const readChanges = async (io, slug, since, root) => (/** @type {Recorded[]} */ ((await io.get(KEY.changes(slug, await checkoutAt(io, root)))) ?? [])).filter(one => one.at >= since).reverse()
518
519// An edit's lines join the intent's, in the checkout edited (`root`, as readChanges);
520// the same line again (a re-tick, a rewrite) replaces the older one.
521/** @param {Io} io @param {string} slug @param {readonly import('./changes.mjs').Change[]} lines @param {number} at @param {string} [root] */
522export const noteChanges = (io, slug, lines, at, root) =>
523 serial(async () => {
524 if (lines.length === 0) return
525 const key = KEY.changes(slug, await checkoutAt(io, root))
526 const kept = /** @type {Recorded[]} */ ((await io.get(key)) ?? []).filter(one => at - one.at < CHANGES_TTL_MS && !lines.some(line => line.kind === one.kind && line.id === one.id))
527 await io.set(key, [...kept, ...lines.map(line => ({ ...line, at }))].slice(-CHANGES_KEPT))
528 changed(io)
529 })
530
531/** @param {Io} io @param {number} offset */
532export const setTz = (io, offset) => serial(() => io.set(KEY.tz, offset))
533
534// Before 0.9 the role was kept per machine under "coach"; it becomes this person's.
535/** @param {Io} io @param {string} me */
536export const migrateRole = (io, me) =>
537 serial(async () => {
538 const legacy = /** @type {{ role?: string } | undefined} */ (await io.get('coach'))
539 if (!legacy) return
540 if ((await io.get(KEY.role(me))) === undefined && legacy.role) await io.set(KEY.role(me), legacy.role)
541 await io.remove('coach')
542 })
543
544/** @param {Io} io @param {string} me @param {{ role?: string, area?: string, tourDone?: boolean, isNudged?: boolean }} fields @param {Pack} [pack] */
545export const setProfile = (io, me, fields, pack = unreal) =>
546 serial(async () => {
547 if (fields.role !== undefined) await io.set(KEY.role(me, pack.roleKey), fields.role)
548 if (fields.area !== undefined) await io.set(KEY.area(me), fields.area)
549 if (fields.tourDone !== undefined) await io.set(KEY.tour(me), { isDone: fields.tourDone })
550 if (fields.isNudged !== undefined) await io.set(KEY.nudged(me), fields.isNudged)
551 changed(io)
552 })
553
554/** @param {Io} io @param {string} me @param {import('./worklist.mjs').GroupBy} by */
555export const setGroupBy = (io, me, by) =>
556 serial(async () => {
557 await io.set(KEY.groupBy(me), by)
558 changed(io)
559 })
560
561/** @param {Io} io @param {string} me @param {import('./home.mjs').PaneView} view */
562export const setPaneView = (io, me, view) =>
563 serial(async () => {
564 await io.set(KEY.view(me), view)
565 changed(io)
566 })
567
568// Whether this checkout has the intent's folder: what tracking it needs (asking about it does not).
569/** @param {Io} io @param {string} root @param {string} slug */
570export const hasIntentFolder = (io, root, slug) => io.exists(`${root}/docs/intent/${slug}/prompt.md`)
571
572// A stop on tracking an intent: its plain slug in the session's own checkout, `{ slug, root }` in another,
573// so the same slug in two checkouts is stopped on its own.
574/** @typedef {string | { slug: string, root: string }} Stop */
575/** @param {Stop} stop @param {string} slug @param {string | null} root null: the session's own checkout */
576const isStopOf = (stop, slug, root) => (typeof stop === 'string' ? root === null && stop === slug : root !== null && stop?.slug === slug && stop.root === root)
577/** @param {Io} io @param {string} sid @returns {Promise<Stop[]>} */
578const readStops = async (io, sid) => /** @type {Stop[]} */ ((await io.get(KEY.untracked(sid))) ?? [])
579
580// Tracks an intent, if it exists. The one path for /ather, the profile tool and a write into an intent.
581// `root`: the folder holding its docs/intent, the session's own or another checkout's.
582// `isAuto`: a write into the intent, which never tracks one this session stopped tracking; tracking one
583// on purpose lifts that stop. `me`: the person's "Continue …" in its checkout moves to it too.
584/** @param {Io} io @param {string} root @param {string} slug @param {{ onlyIfNone?: boolean, isAuto?: boolean, me?: string }} [options] */
585export const track = (io, root, slug, options = {}) =>
586 serial(async () => {
587 const isOwn = await isSessionRoot(io, root)
588 const at = isOwn ? root : normalFolder(root)
589 if (!(await hasIntentFolder(io, at, slug))) return false
590 const sid = await io.sessionId()
591 const stopped = await readStops(io, sid)
592 const isStopped = stopped.some(one => isStopOf(one, slug, isOwn ? null : at))
593 if (options.isAuto && isStopped) return false
594 if (options.onlyIfNone && (await io.get(KEY.pinned(sid))) !== undefined) return false
595 await io.set(KEY.pinned(sid), isOwn ? slug : { slug, root: at })
596 if (options.me) {
597 const last = KEY.last(options.me, await checkoutAt(io, at))
598 await io.set(last, slug)
599 // Once the own checkout's scoped "Continue …" is written, the unscoped one from before 0.2.5 must not
600 // read through again. Tracking in another checkout leaves it: it is still the own checkout's.
601 if (isOwn && last !== KEY.last(options.me, '')) await io.remove(KEY.last(options.me, ''))
602 }
603 if (!options.isAuto && isStopped) await setList(io, KEY.untracked(sid), stopped.filter(one => !isStopOf(one, slug, isOwn ? null : at)))
604 await beat(io)
605 changed(io)
606 return true
607 })
608
609// Stops tracking: the session's pin, the person's "Continue …" when it names the same intent, and a
610// stop on a write tracking it again in this session. Proof recorded so far stays with the intent.
611// Refused while an away window runs: its mandate and ledger were set up for the tracked intent.
612/** @param {Io} io @param {string} me @returns {Promise<{ result: 'untracked' | 'none' | 'away', slug: string }>} */
613export const untrack = (io, me) =>
614 serial(async () => {
615 const sid = await io.sessionId()
616 const pin = await readPin(io)
617 if (pin === null) return { result: /** @type {const} */ ('none'), slug: '' }
618 const { slug } = pin
619 const away = await awayOf(io, sid)
620 if (away.phase === 'running') return { result: /** @type {const} */ ('away'), slug }
621 await io.remove(KEY.pinned(sid))
622 // The unscoped "Continue …" from before 0.2.5 goes too, or it would read through again.
623 for (const key of new Set([KEY.last(me, await checkoutAt(io, pin.isOwn ? undefined : pin.root)), ...(pin.isOwn ? [KEY.last(me, '')] : [])])) if ((await io.get(key)) === slug) await io.remove(key)
624 const stopped = (await readStops(io, sid)).filter(one => !isStopOf(one, slug, pin.isOwn ? null : pin.root))
625 await setList(io, KEY.untracked(sid), [...stopped, pin.isOwn ? slug : { slug, root: pin.root }])
626 await beat(io)
627 changed(io)
628 return { result: /** @type {const} */ ('untracked'), slug }
629 })
630
631/** @param {Io} io @param {string} key @param {Stop[]} list */
632const setList = async (io, key, list) => {
633 const kept = [...new Set(list)]
634 if (kept.length === 0) await io.remove(key)
635 else await io.set(key, kept)
636}
637
638// ---------------------------------------------------------------- lanes: the heartbeats of the sessions on this checkout
639
640// A heartbeat older than this, or one that says it ended, is no longer a live session.
641const LANE_STALE_MS = 10 * 60 * 1000
642
643/**
644 * One session's heartbeat, a file under the pack's local folder: what it tracks, on which branch,
645 * when it was written and when the session last took a prompt or ran a tool; `app`: its id and title in
646 * the desktop app, when it runs there (absent elsewhere, and in heartbeats written before 0.6.5); `root`: the
647 * session's own checkout ('' for a parent folder; absent before 0.6.6), which a heartbeat in another checkout
648 * (one whose intent it tracks) does not share.
649 * @typedef {{ sessionId: string, intent: string | null, branch: string, updatedAt: number, lastActiveAt?: number, away: string, hasEnded: boolean, app?: AppSession, root?: string }} Lane
650 * @typedef {import('./handoff.mjs').AppSession} AppSession
651 */
652
653// When this session last took a prompt or ran a tool; a hot reload starts it again.
654let activeAt = Date.now()
655/** @param {number} [at] */
656export const markActive = (at = Date.now()) => {
657 activeAt = at
658}
659
660// This session as the desktop app knows it (watch.mjs asks the app's session tool), written into every heartbeat
661// so other sessions can name it and send to it; null outside the app.
662/** @type {AppSession | null} */
663let appSelf = null
664/** @param {AppSession | null} app */
665export const setAppSession = app => {
666 appSelf = app
667}
668export const appSession = () => appSelf
669
670// The heartbeats last written. `isHome`: the session's own checkout's, which always names the tracked intent.
671/** @type {{ path: string, lane: Lane, isHome?: boolean }[]} */
672let lastBeats = []
673
674// Writes this session's heartbeat; after any change in hand, so it never undoes one. `also`: the tracked
675// intent's checkout, when it is not the session's, so its sessions see this one. A checkout written to
676// earlier keeps a live heartbeat (naming no intent) until the session ends: one that went stale or said
677// ended there would let its sessions take this one for gone and prune its lane. `root` '': the session
678// folder is no checkout with intents (a parent folder), so only `also` and earlier checkouts are written.
679/** @param {Io} io @param {{ root: string, localDir: string, branch: string, hasEnded: boolean, also?: { root: string, localDir: string, branch: string } | null }} at */
680export const writeHeartbeat = (io, at) =>
681 serial(async () => {
682 const sid = await io.sessionId()
683 const away = await readAway(io)
684 /** @type {Lane} */
685 const lane = { sessionId: sid, intent: await readPinned(io), branch: at.branch, updatedAt: Date.now(), lastActiveAt: activeAt, away: away.phase, hasEnded: at.hasEnded, root: at.root, ...(appSelf ? { app: appSelf } : {}) }
686 /** @type {typeof lastBeats} */
687 const beats = at.root ? [{ path: `${at.root}/${at.localDir}/lanes/${sid}.json`, lane, isHome: true }] : []
688 if (at.also) beats.push({ path: `${at.also.root}/${at.also.localDir}/lanes/${sid}.json`, lane: { ...lane, branch: at.also.branch } })
689 for (const old of lastBeats) {
690 if (old.lane.sessionId !== sid || beats.some(one => one.path === old.path) || !(await io.exists(old.path))) continue
691 beats.push({ path: old.path, lane: { ...lane, intent: null, branch: old.lane.branch } })
692 }
693 for (const one of beats) await io.write(one.path, JSON.stringify(one.lane))
694 lastBeats = beats
695 })
696
697// Whether this session has written a heartbeat anywhere yet.
698export const hasHeartbeats = () => lastBeats.length > 0
699
700// The heartbeat again, at once, when what the session tracks changes: peers see it before the next tick.
701/** @param {Io} io */
702const beat = async io => {
703 const sid = await io.sessionId()
704 const intent = await readPinned(io)
705 lastBeats = await Promise.all(lastBeats.map(async old => {
706 // Only over a heartbeat that is still there: never brings back one a cleanup removed. A checkout
707 // other than the session's names the intent only while it is the tracked intent's (the next tick says).
708 if (old.lane.sessionId !== sid || !(await io.exists(old.path))) return old
709 const lane = { ...old.lane, intent: old.isHome || old.lane.intent === intent ? intent : null, updatedAt: Date.now(), lastActiveAt: activeAt }
710 await io.write(old.path, JSON.stringify(lane)).catch(() => undefined)
711 return { ...old, lane }
712 }))
713}
714
715// One session's heartbeat on this checkout, or null when it has none here (it may live in another checkout).
716/** @param {Io} io @param {string} root @param {string} localDir @param {string} sid @returns {Promise<Lane | null>} */
717export const readLane = async (io, root, localDir, sid) => {
718 try {
719 return JSON.parse((await io.read(`${root}/${localDir}/lanes/${sid}.json`)) ?? '')
720 } catch {
721 return null
722 }
723}
724
725/** @param {Lane} lane */
726export const isLaneLive = lane => !lane.hasEnded && Date.now() - Number(lane.updatedAt) < LANE_STALE_MS
727
728// The other sessions alive on this checkout: a fresh heartbeat that has not said it ended.
729/** @param {Io} io @param {string} root @param {string} localDir @returns {Promise<Lane[]>} */
730export const readPeers = async (io, root, localDir) => {
731 const dir = `${root}/${localDir}/lanes`
732 const sid = await io.sessionId()
733 const list = io.list ?? (async () => [])
734 /** @type {Lane[]} */
735 const out = []
736 for (const entry of await list(dir).catch(() => [])) {
737 if (entry.kind !== 'file' || entry.name === `${sid}.json` || Date.now() - Number(entry.mtimeMs) > LANE_STALE_MS) continue
738 try {
739 const lane = JSON.parse((await io.read(`${dir}/${entry.name}`)) ?? '')
740 if (!lane.hasEnded) out.push(lane)
741 } catch {
742 // a half-written heartbeat; the next tick reads it
743 }
744 }
745 return out
746}
747
748// `gates`: on a rung that gates declare, the run replaces the result of each gate it ran and no other; a
749// command that is no gate is kept beside them until one of the rung's gates is next run.
750/** @param {Io} io @param {string} scope @param {keyof Evidence} rung @param {import('./model.mjs').Rung} value @param {import('./packs/index.mjs').RungGates} [gates] */
751export const setRung = (io, scope, rung, value, gates) =>
752 serial(async () => {
753 const result = { state: value.state, detail: value.detail.slice(0, 120) }
754 if (!gates) return writeEvidence(io, scope, { [rung]: result })
755 const stored = await storedEvidence(io, scope)
756 const stamped = { ...result, at: Date.now(), by: shortSession(await io.sessionId()) }
757 const before = Object.entries(/** @type {Record<string, import('./model.mjs').Rung>} */ (stored[rung]?.gates ?? {})).filter(([key]) => key !== NO_GATE)
758 const kept = Object.fromEntries([...before, ...(gates.ran.length > 0 ? gates.ran : [NO_GATE]).map(key => /** @type {[string, import('./model.mjs').Rung]} */ ([key, stamped]))])
759 await io.set(KEY.evidence(scope), { ...stored, [rung]: { ...rungOfGates(kept, gates.all), gates: kept } })
760 changed(io)
761 })
762
763// MCP evidence: a write waits for a read back on the same server; PIE counts when it started.
764/** @param {Io} io @param {string} scope @param {'write' | 'read' | 'pie'} kind @param {string} server @param {boolean} isOk */
765export const noteMcp = (io, scope, kind, server, isOk) =>
766 serial(async () => {
767 const evidence = { ...emptyEvidence(), ...(await storedEvidence(io, scope)) }
768 const pending = `pending readback on ${server}`
769 /** @type {Partial<Evidence>} */
770 let change = {}
771 if (kind === 'write' && isOk) change = { readback: { state: 'none', detail: pending } }
772 if (kind === 'read' && isOk && evidence.readback.detail === pending) change = { readback: { state: 'pass', detail: `read back on ${server}` } }
773 if (kind === 'pie') change = { pie: { state: isOk ? 'pass' : 'fail', detail: server } }
774 if (Object.keys(change).length === 0) return
775 await writeEvidence(io, scope, change)
776 })
777
778/** @param {Io} io @param {readonly import('./guards.mjs').Trap[]} traps traps first seen in this session */
779export const countTraps = (io, traps) =>
780 serial(async () => {
781 let hits = /** @type {import('./guards.mjs').TrapHits} */ ((await io.get(KEY.hits)) ?? {})
782 for (const trap of traps) hits = countGotcha(hits, trap)
783 await io.set(KEY.hits, hits)
784 changed(io)
785 })
786
787/** @param {Io} io @param {string[]} paths */
788export const flagLost = (io, paths) =>
789 serial(async () => {
790 await io.set(KEY.lost(await io.sessionId()), { paths, isDisclosed: false })
791 changed(io)
792 })
793
794/** @param {Io} io @param {string} key */
795export const bump = (io, key) =>
796 serial(async () => {
797 const score = /** @type {Record<string, number>} */ ((await io.get(KEY.score)) ?? {})
798 await io.set(KEY.score, { ...score, [key]: (score[key] ?? 0) + 1 })
799 })
800
801// What else changes once an item has been delivered to the session.
802/** @param {Io} io @param {import('./home.mjs').Item} item */
803export const settleItem = (io, item) =>
804 serial(async () => {
805 const sid = await io.sessionId()
806 if (item.kind === 'lost') await io.remove(KEY.lost(sid))
807 if (item.kind === 'rule') await io.set(KEY.ruled, [.../** @type {string[]} */ ((await io.get(KEY.ruled)) ?? []), ...item.ruleIds])
808 changed(io)
809 })
810
811// ---------------------------------------------------------------- the away window
812
813/** @param {Io} io @param {(away: Away) => Promise<{ away?: Away, result: T }>} change @template T @returns {Promise<T>} */
814const withAway = (io, change) =>
815 serial(async () => {
816 const sid = await io.sessionId()
817 const key = KEY.away(sid)
818 const away = await awayOf(io, sid)
819 const { away: next, result } = await change(away)
820 if (next) {
821 if (isHolding(next)) await io.set(key, next)
822 else await io.remove(key)
823 const person = next.person || away.person
824 if (person) await setIndex(io, person, list => (isHolding(next) ? [...list, sid] : list.filter(one => one !== sid)))
825 changed(io)
826 }
827 return result
828 })
829
830/**
831 * @typedef {{ root: string, tz: number, now: number, me: string, pack?: Pack, base?: string }} WindowAt where and when a window
832 * opens; `base`: the branch the checkout's team merges into, for what the ledger says is held
833 */
834
835// Another session's view through this one's Io: its own keys (its window, its tracked intent) and its checkout, so its
836// window is opened or ended from here. The store is the plugin's, one for every session on the machine, and each
837// session's hooks read their own window at every call.
838/** @param {Io} io @param {string} sid @param {string} root @returns {Io} */
839export const asSession = (io, sid, root) => ({ ...io, sessionId: async () => sid, root: async () => root })
840
841// The window the session would open now, nothing stored or written: its ledger is its tracked intent's decisions.md
842// when the intent is the person's own, else a file of its own under the checkout's local folder (named by the minute
843// and the session, so sessions heading off together never share one).
844/** @param {Io} io @param {import('./away.mjs').WindowChoice} choice @param {WindowAt} at @returns {Promise<Away>} */
845export const planAway = async (io, choice, at) => {
846 const pin = await readPin(io)
847 // The tracked intent's folder, in whichever checkout it lives.
848 const dir = pin ? `${pin.isOwn ? at.root : pin.root}/docs/intent/${pin.slug}` : ''
849 const owner = pin ? intentOwner((await io.read(`${dir}/prompt.md`)) ?? '') : ''
850 const stamp = new Date(at.now + at.tz * 60000).toISOString().slice(0, 16).replace(/[:T]/g, '-')
851 const ledgerPath = pin && isSamePerson(owner, at.me) ? `${dir}/decisions.md` : `${at.root}/${(at.pack ?? unreal).localDir}/away/${stamp}-${shortSession(await io.sessionId())}.md`
852 return newWindow({ ...choice, held: choice.held ?? [...(at.pack ?? unreal).held.defaults] }, at.now, ledgerPath, { person: personId(at.me), root: at.root })
853}
854
855// Opens a planned window, unless one is running or waiting for review: it holds from now. Its ledger is started apart
856// (startLedger), so a window closed again at once (another session the mandate never reached) leaves no file behind.
857/** @param {Io} io @param {Away} planned @returns {Promise<Away | null>} */
858export const openAway = (io, planned) => withAway(io, async away => (away.phase === 'off' ? { away: planned, result: planned } : { result: null }))
859
860// An open window's ledger: its section appended to the file, or the file begun.
861/** @param {Io} io @param {Away} away @param {WindowAt} at */
862export const startLedger = (io, away, at) => serial(async () => io.write(away.ledgerPath, ledgerWithWindow((await io.read(away.ledgerPath)) ?? '', away, at.tz, at.pack ?? unreal, at.base)))
863
864// Opens a window now, with its ledger, unless one is running or waiting for review.
865/** @param {Io} io @param {import('./away.mjs').WindowChoice} choice @param {WindowAt} at @returns {Promise<Away | null>} */
866export const startAway = async (io, choice, at) => {
867 const opened = await openAway(io, await planAway(io, choice, at))
868 if (opened) await startLedger(io, opened, at)
869 return opened
870}
871
872// Ends a running window; the review waits in "Needs you". Resolves whether it was running.
873/** @param {Io} io */
874export const endAway = io => withAway(io, async away => (away.phase === 'running' ? { away: { ...away, phase: /** @type {const} */ ('review'), endedAt: Date.now() }, result: true } : { result: false }))
875
876// Closes the window; with `which`, only while it is still that window (opened at the same moment).
877/** @param {Io} io @param {Away} [which] */
878export const closeAway = (io, which) => withAway(io, async away => (away.phase === 'off' || (which && away.startedAt !== which.startedAt) ? { result: false } : { away: { ...offAway(), person: away.person }, result: true }))
879
880// The person is back ("I'm back", /away stop, the review's press): this session's window ends if it runs, then every
881// other running window of its group (A3), each to its review in its own session. An ended window keeps its group.
882/** @param {Io} io @returns {Promise<{ isEnded: boolean, others: number }>} */
883export const comeBack = async io => {
884 const isEnded = await endAway(io)
885 const { group, person } = await readAway(io)
886 const own = await io.sessionId()
887 let others = 0
888 for (const sid of /** @type {string[]} */ (group ? ((await io.get(KEY.windows(person))) ?? []) : [])) {
889 const other = sid === own ? null : await awayOf(io, sid)
890 if (other && other.group === group && (await endAway(asSession(io, sid, other.root)))) others += 1
891 }
892 return { isEnded, others }
893}
894
895// Puts a window back, when the review that closed it could not be delivered.
896/** @param {Io} io @param {Away} saved */
897export const restoreAway = (io, saved) => withAway(io, async away => (isHolding(away) || !isHolding(saved) ? { result: false } : { away: saved, result: true }))
898
899// Records a held action; resolves the parked entry, or null when no running window holds this kind.
900// `held`: the kinds held where the command runs, when another checkout holds more than the window's own.
901/** @param {Io} io @param {string} kind @param {string} command @param {number} now @param {readonly string[]} [held] */
902export const park = (io, kind, command, now, held) =>
903 withAway(io, async away => {
904 if (!isHolding(away) || !(held ?? away.held).includes(kind)) return { result: null }
905 const parked = { id: nextParkId(away.parked), kind, command: command.slice(0, 400), at: now }
906 return { away: { ...away, parked: [...away.parked, parked] }, result: { parked, away } }
907 })
908
909// Writes the model's questions to the ledger instead of asking; resolves their ids, or null when the person
910// can be asked (no window, or back since it ended: `lastPersonAt` is when they last typed).
911/** @param {Io} io @param {readonly { question: string, options: readonly { label: string }[] }[]} questions @param {number} lastPersonAt */
912export const deferQuestions = (io, questions, lastPersonAt) =>
913 withAway(io, async away => {
914 if (!isRecordingQuestions(away, lastPersonAt)) return { result: null }
915 const text = (await io.read(away.ledgerPath)) ?? ''
916 const first = nextLedgerId(text)
917 const ids = questions.map((_, index) => `D-${first + index}`)
918 await io.write(away.ledgerPath, `${text.trimEnd()}\n\n${questions.map((one, index) => pendingEntry(ids[index] ?? '', one.question, one.options.map(option => option.label))).join('\n')}`)
919 return { result: { ids, away } }
920 })
921
922// A new session (the next morning, an app restart) picks up this person's window from an
923// earlier session that has ended, so its holds and its review are not lost. A window in a
924// session that is still alive stays where it is. Resolves the window taken over, or null.
925/** @param {Io} io @param {{ me: string, root: string, isAlive: (sid: string) => Promise<boolean> }} lane */
926export const adoptWindow = async (io, lane) => {
927 const sid = await io.sessionId()
928 if (isHolding(await awayOf(io, sid))) return null
929 /** @type {{ from: string, away: Away } | null} */
930 let found = null
931 for (const from of /** @type {string[]} */ ((await io.get(KEY.windows(personId(lane.me)))) ?? [])) {
932 if (from === sid) continue
933 const away = await awayOf(io, from)
934 if (!isHolding(away) || away.root !== lane.root) continue
935 if (await lane.isAlive(from)) continue
936 if (!found || away.startedAt > found.away.startedAt) found = { from, away }
937 }
938 if (!found) return null
939 await moveLane(io, found.from, sid)
940 const isOver = found.away.phase === 'review' || Date.now() >= found.away.wakeAt
941 if (found.away.phase === 'running' && isOver) await endAway(io)
942 return { away: found.away, isOver }
943}
944
945// Removes what sessions that have ended left behind (tracked intent, evidence, a lost-edits
946// flag, the intents it stopped tracking, an empty window), so the store stays small. The store spans every checkout on the
947// machine, so only sessions `isGone` can vouch for are touched (their heartbeat is in this
948// checkout and says ended or stale); a holding window is kept for adoption.
949// Runs in the background; reads every key once.
950/** @param {Io} io @param {(sid: string) => Promise<boolean>} isGone */
951export const prune = async (io, isGone) => {
952 const current = await io.sessionId()
953 /** @type {Map<string, string[]>} */
954 const bySession = new Map()
955 for (const key of await io.keys()) {
956 // `<sid>|<checkout id>` is a session's proof in another checkout and goes with it; `<checkout id>|<slug>` is
957 // an intent's (a checkout id has a / or a :) and belongs to no session.
958 const sid = /^(?:away|pinned|evidence|lost|untracked|warm):(.+)$/.exec(key)?.[1]?.split('|')[0]
959 if (sid && !/[/:]/.test(sid) && sid !== current) bySession.set(sid, [...(bySession.get(sid) ?? []), key])
960 }
961 for (const [sid, keys] of bySession) {
962 if (!(await isGone(sid))) continue
963 // A session that ended while its window still holds keeps its whole lane for adoption.
964 if (isHolding(await awayOf(io, sid))) continue
965 await serial(async () => {
966 for (const key of keys) await io.remove(key)
967 })
968 }
969}
970hooks/workers.mjs 83 lines1// @ts-check
2// Ather Automata: the background workers this session dispatched, as the watch half sees them
3// (spawned with this brief and model, called these tools) for the console half to draw. Held in
4// memory for the session: workers do not outlive it. Pure: no `$`.
5
6import { classifyWorker, kindOfAgent, propForTool } from './squad.mjs'
7
8/** @typedef {import('./squad.mjs').Kind} Kind */
9/** @typedef {import('./squad.mjs').Prop} Prop */
10/**
11 * `origin`: 'seen' when Ather saw it dispatched (its tool calls are all counted), 'adopted' when it
12 * was found running after Ather loaded (start and model from Claude Code's record; calls before then uncounted).
13 * `endedAt`: when its latest turn ended; a worker resumed afterwards is running again by its status.
14 * `lastAt`, `lastTool`: when it was last heard from (a call's start or end) and its latest call: the one clock
15 * the pane and the quiet-worker toast read.
16 * @typedef {{ id: string, title: string, kind: Kind, model: string, origin: Exclude<import('./squad.mjs').Origin, 'unknown'>, startedAt: number, lastAt: number,
17 * tools: number, lastTool: string, prop: Prop | null, trail: Prop[], endedAt?: number }} Worker
18 */
19
20/** @type {Map<string, Worker>} */
21const known = new Map()
22const MOST = 40
23const TRAIL = 6
24
25export const resetWorkers = () => known.clear()
26
27/** @param {Worker} worker */
28const remember = worker => {
29 known.set(worker.id, worker)
30 // A long session keeps the most recent workers only.
31 while (known.size > MOST) known.delete(/** @type {string} */ (known.keys().next().value))
32}
33
34// The kind is fixed here, from the dispatch: a worker never changes body while it runs.
35/** @param {{ agentId: string, subagentType: string, prompt: string, description: string, model: string, at: number }} spawn */
36export const recordSpawn = spawn =>
37 remember({ id: spawn.agentId, title: spawn.description || spawn.subagentType, kind: classifyWorker(spawn), model: spawn.model, origin: 'seen', startedAt: spawn.at, lastAt: spawn.at, tools: 0, lastTool: '', prop: null, trail: [] })
38
39// A worker found running after Ather loaded: its kind from its description, its start from
40// Claude Code's record. Nothing seen of it yet is not idleness, so it was last heard from now.
41/** @param {{ id: string, type: string, description: string, model: string, startedAt: number, now: number }} found */
42export const adoptWorker = found =>
43 remember({ id: found.id, title: found.description || found.type, kind: kindOfAgent(found.type, found.description), model: found.model, origin: 'adopted', startedAt: found.startedAt, lastAt: found.now, tools: 0, lastTool: '', prop: null, trail: [] })
44
45// One tool call inside a worker's loop: what it is doing now, and the step in its trail.
46/** @param {string} agentId @param {string} tool @param {Record<string, unknown>} input @param {number} at */
47export const recordTool = (agentId, tool, input, at) => {
48 const worker = known.get(agentId)
49 if (!worker) return
50 worker.tools += 1
51 worker.lastAt = at
52 worker.lastTool = tool
53 const prop = propForTool(tool, input)
54 if (!prop) return
55 worker.prop = prop
56 // The trail is the work done: a question to the person is not a step of it.
57 if (prop !== 'idle' && prop !== 'asking' && worker.trail.at(-1) !== prop) worker.trail = [...worker.trail, prop].slice(-TRAIL)
58}
59
60// One of its calls settled (it ran, was refused or threw): heard from now, so a long call's end
61// starts the quiet clock, not its start.
62/** @param {string} agentId @param {number} at */
63export const recordHeard = (agentId, at) => {
64 const worker = known.get(agentId)
65 if (worker) worker.lastAt = Math.max(worker.lastAt, at)
66}
67
68// A worker's turn ended (its answer): the end of its clock, until it is resumed.
69/** @param {string} agentId @param {number} at */
70export const recordEnd = (agentId, at) => {
71 const worker = known.get(agentId)
72 if (worker) worker.endedAt = at
73}
74
75// How long it has run: to now while it runs, to its last turn's end once finished; null for one
76// that finished without Ather seeing its turn end (before Ather loaded): its time is not known.
77/** @param {Worker} worker @param {boolean} isLive @param {number} now @returns {number | null} */
78export const workerElapsed = (worker, isLive, now) =>
79 isLive ? now - worker.startedAt : worker.endedAt === undefined ? null : worker.endedAt - worker.startedAt
80
81/** @param {string} agentId */
82export const workerOf = agentId => known.get(agentId)
83hooks/inflight.mjs 157 lines1// @ts-check
2// Ather Automata: the tool calls in flight, per model loop (a worker's, or the main loop's), as the
3// watch half sees them: what each call is, when it started, whether it waits on a permission
4// decision, and for a foreground Agent call the worker it started. A call is recorded when the
5// tool.call hook passes it on and cleared when that settles (it ran, was refused, or threw), when
6// the hook's dispatch is aborted, or when its loop's turn ends. So a long build is never read as a
7// quiet worker, and a call waiting on permission is never read as running. Pure: no `$`.
8
9/**
10 * `loop`: the worker's agent id, '' for the main loop. `what`: the call's own description, or a short
11 * form of its command. `childId`: the worker a foreground Agent call started, once agent.spawn reports it.
12 * `askedAt`: when a permission dialog for the call was shown (classic.PermissionRequest); kept until the call
13 * settles, since no event says the dialog was answered: words built on it say only that it was asked.
14 * @typedef {{ token: number, loop: string, toolUseId: string, tool: string, what: string, command: string, startedAt: number, childId?: string, askedAt?: number }} Call
15 */
16
17/** @type {Map<number, Call>} */
18const calls = new Map()
19let nextToken = 1
20// A runaway session keeps at most this many open calls (with aborts and turn ends clearing loops, rarely reached).
21const MOST = 200
22
23export const resetCalls = () => {
24 calls.clear()
25 nextToken = 1
26}
27
28// What a call is, in its own words: the description the model gave it, or its command's first line, cut.
29/** @param {string} tool @param {Record<string, unknown>} input */
30export const callWhat = (tool, input) => {
31 const description = String(input.description ?? '').trim()
32 if (description) return description
33 const command = String(input.command ?? '').split(/\r?\n/)[0]?.trim() ?? ''
34 return command ? (command.length <= 60 ? command : `${command.slice(0, 59)}…`) : tool
35}
36
37// Over the cap, the call let go first: the oldest still asking, else the oldest in the loop holding the most
38// calls (a leak piles up in one loop), so one long live call is never dropped for leaked ones.
39const evict = () => {
40 const open = [...calls.values()]
41 const asking = open.filter(one => one.askedAt !== undefined)
42 const perLoop = new Map()
43 for (const one of open) perLoop.set(one.loop, (perLoop.get(one.loop) ?? 0) + 1)
44 const busiest = [...perLoop.entries()].sort((a, b) => b[1] - a[1])[0]?.[0]
45 const victim = asking[0] ?? open.find(one => one.loop === busiest)
46 if (victim) calls.delete(victim.token)
47}
48
49// A call goes out; its token clears it.
50/** @param {{ loop?: string, toolUseId?: string, tool: string, input: Record<string, unknown>, at: number }} call @returns {number} */
51export const startCall = ({ loop = '', toolUseId = '', tool, input, at }) => {
52 const token = nextToken++
53 calls.set(token, { token, loop, toolUseId, tool, what: callWhat(tool, input), command: typeof input.command === 'string' ? input.command : '', startedAt: at })
54 while (calls.size > MOST) evict()
55 return token
56}
57
58/** @param {number} token */
59export const endCall = token => void calls.delete(token)
60
61// A loop's turn ended: nothing in it is in flight any more, whatever did not settle.
62/** @param {string} loop */
63export const endLoop = loop => {
64 for (const one of [...calls.values()]) if (one.loop === loop) calls.delete(one.token)
65}
66
67// The call `run` makes is in flight until it settles, whichever way (an answer, a refusal or a throw), or until
68// `signal` aborts (the person's Esc: a pending call is not sure to settle). `onSettled` runs after, also
69// whichever way, and never throws into the call.
70/** @template T @param {Parameters<typeof startCall>[0]} call @param {() => Promise<T>} run @param {() => void} [onSettled] @param {AbortSignal} [signal] @returns {Promise<T>} */
71export const during = async (call, run, onSettled, signal) => {
72 const token = startCall(call)
73 const onAbort = () => endCall(token)
74 signal?.addEventListener('abort', onAbort, { once: true })
75 if (signal?.aborted) endCall(token)
76 try {
77 return await run()
78 } finally {
79 endCall(token)
80 signal?.removeEventListener('abort', onAbort)
81 try {
82 onSettled?.()
83 } catch {
84 // Bookkeeping only: the call's own answer stands.
85 }
86 }
87}
88
89// A permission dialog was shown to the person (classic.PermissionRequest, which names no tool_use_id): the call it
90// is for waits on their decision, not running. It is the loop's newest call of that tool not yet asking, the one
91// with the same command when there is one. Nothing matches: nothing is marked.
92/** @param {{ loop?: string, tool: string, input: unknown, at: number }} dialog */
93export const markAsking = ({ loop = '', tool, input, at }) => {
94 const command = input && typeof input === 'object' && typeof (/** @type {{ command?: unknown }} */ (input)).command === 'string' ? String(/** @type {{ command: string }} */ (input).command) : ''
95 const open = callsIn(loop).filter(one => one.tool === tool && one.askedAt === undefined)
96 const call = (command ? open.filter(one => one.command === command).at(-1) : undefined) ?? open.at(-1)
97 if (call) call.askedAt = at
98}
99
100// agent.spawn reported the worker an Agent call started: the call that waits on it, by the call's id,
101// or else the loop's latest Agent call not yet linked. A background spawn is waited on by nobody.
102/** @param {{ loop?: string, toolUseId?: string, childId: string, isBackground?: boolean }} spawn */
103export const linkChild = ({ loop = '', toolUseId = '', childId, isBackground = false }) => {
104 if (isBackground || !childId) return
105 const open = [...calls.values()].filter(one => one.tool === 'Agent')
106 const call = (toolUseId ? open.find(one => one.toolUseId === toolUseId) : undefined) ?? open.filter(one => one.loop === loop && !one.childId).at(-1)
107 if (call) call.childId = childId
108}
109
110// The loop's calls in flight, oldest first, asking ones included.
111/** @param {string} [loop] @returns {Call[]} */
112export const callsIn = (loop = '') => [...calls.values()].filter(one => one.loop === loop).sort((a, b) => a.startedAt - b.startedAt)
113
114// The loop's calls waiting on a permission decision, oldest first.
115/** @param {string} [loop] */
116export const askingIn = (loop = '') => callsIn(loop).filter(one => one.askedAt !== undefined)
117
118// Something is running in the loop: a call in flight that is not waiting on permission.
119/** @param {string} [loop] */
120export const isInFlight = (loop = '') => [...calls.values()].some(one => one.loop === loop && one.askedAt === undefined)
121
122// The one rule for a quiet worker, in the pane and in the stuck-permission toast: nothing running,
123// and nothing heard for the threshold. A call running is never quiet, however long it runs.
124/** @param {{ isInFlight: boolean, lastAt: number, now: number, quietMs: number }} one */
125export const isSilent = ({ isInFlight, lastAt, now, quietMs }) => !isInFlight && now - lastAt > quietMs
126
127export const LONG_CALL_MS = 60000
128export const STUCK_CALL_MS = 25 * 60000
129
130// A shell or Monitor call running (not asking) for more than a minute, the oldest, if any.
131/** @param {readonly Call[]} open oldest first @param {number} now */
132export const longShell = (open, now) => open.find(one => one.askedAt === undefined && /^(Bash|PowerShell|Monitor)$/.test(one.tool) && now - one.startedAt > LONG_CALL_MS)
133
134/** @param {number} ms */
135const agoText = ms => (ms < 60000 ? 'just now' : `${Math.floor(ms / 60000)} min ago`)
136
137/**
138 * What a worker waits on, from facts only: `wait`, the amber ⏳ line (a call permission was asked for, and when;
139 * a foreground Agent call's worker; or a shell or Monitor call past a minute, quoted as described, with the pack's
140 * lock line when the command names its lock file); `stuck`, the ⚠ line when one call has gone on 25 minutes or more.
141 * @param {readonly Call[]} open the loop's calls in flight, oldest first @param {number} now
142 * @param {(childId: string) => string} titleOf @param {(command: string) => string} [lockOf]
143 * @returns {{ wait: string, stuck: string }}
144 */
145export const waitWords = (open, now, titleOf, lockOf = () => '') => {
146 const asking = open.find(one => one.askedAt !== undefined)
147 const running = open.filter(one => one.askedAt === undefined)
148 const agent = running.find(one => one.tool === 'Agent' && one.childId)
149 const shell = longShell(running, now)
150 const lock = shell && shell.command ? lockOf(shell.command) : ''
151 const wait = asking ? `⏳ asked permission ${agoText(now - (asking.askedAt ?? now))}: ${asking.what}` : agent?.childId ? `⏳ waiting on ${titleOf(agent.childId)}` : shell ? `⏳ ${shell.what}${lock ? ` · ${lock}` : ''}` : ''
152 // A call asked about is still a call: an approved build that runs on still warns.
153 const [oldest] = open
154 const stuck = oldest && now - oldest.startedAt >= STUCK_CALL_MS ? `⚠ one call running ${Math.floor((now - oldest.startedAt) / 60000)} min` : ''
155 return { wait, stuck }
156}
157hooks/changes.mjs 87 lines1// @ts-check
2// Ather Automata: what an edit to an intent changed, in one plain line each. Three kinds only:
3// done (an acceptance item met), yours (a decision now waiting on the person), changed (the
4// goal, the scope, or a decision taken). Notes and log entries are the detail behind these and
5// are not listed. Pure: no `$`.
6
7import { acceptanceItems, parseFindings, section, shortTitle } from './model.mjs'
8
9/** @typedef {{ kind: 'done' | 'yours' | 'changed', id: string, text: string }} Change */
10/** @typedef {'prompt.md' | 'findings.md' | 'progress.md'} IntentFile */
11
12// The acceptance items with an id, read the way the pane counts them (model.mjs acceptanceItems):
13// "A12 (proof…): Ice tracks keep their depth. More…" → { A12: { isDone, title: 'Ice tracks keep their depth' } }
14/** @param {string} prompt @param {string} progress */
15const checklist = (prompt, progress) => {
16 /** @type {Map<string, { isDone: boolean, title: string }>} */
17 const items = new Map()
18 for (const item of acceptanceItems(prompt, progress)) {
19 if (item.id === '') continue
20 const words = item.text.replace(/^\([^)]*\)\s*/, '').replace(/^[:.\-–—]\s*/, '')
21 items.set(item.id, { isDone: item.isDone, title: shortTitle(/^(.+?)[.:](\s|$)/.exec(words)?.[1] ?? words, 48) })
22 }
23 return items
24}
25
26// Items that went from open to done, as "<verb> A2 · Sand look".
27/** @param {Map<string, { isDone: boolean, title: string }>} was @param {Map<string, { isDone: boolean, title: string }>} now @param {string} verb @returns {Change[]} */
28const newlyDone = (was, now, verb) => [...now].filter(([id, item]) => item.isDone && was.get(id)?.isDone === false).map(([id, item]) => ({ kind: /** @type {const} */ ('done'), id, text: `${verb} ${id} · ${item.title}` }))
29
30const SCOPE_HEADINGS = ['Scope', 'Out of scope', 'Non-goals', 'Constraints']
31/** @param {string} text */
32const plain = text => text.replace(/\s+/g, ' ').trim()
33
34// A ticked legacy box reads "Ticked"; once progress.md has its table, prompt.md edits change no verdict.
35/** @param {string} before @param {string} after @param {string} progress @returns {Change[]} */
36const promptChanges = (before, after, progress) => {
37 const changes = newlyDone(checklist(before, progress), checklist(after, progress), 'Ticked')
38 if (before !== '' && plain(section(before, 'Goal')) !== plain(section(after, 'Goal'))) changes.push({ kind: 'changed', id: 'goal', text: 'Goal changed' })
39 if (before !== '' && SCOPE_HEADINGS.some(heading => plain(section(before, heading)) !== plain(section(after, heading)))) changes.push({ kind: 'changed', id: 'scope', text: 'Scope changed' })
40 return changes
41}
42
43/** @param {string} before @param {string} after @param {string} prompt @returns {Change[]} */
44const findingChanges = (before, after, prompt) => {
45 /** @type {Change[]} */
46 const changes = []
47 const wasOpen = new Map(parseFindings(before, prompt).map(one => [one.id, one]))
48 const isOpen = new Map(parseFindings(after, prompt).map(one => [one.id, one]))
49 for (const [id, one] of isOpen) {
50 const isNew = !new RegExp(`^##\\s+${id}\\b`, 'm').test(before)
51 if (isNew && one.isDirectorCall) changes.push({ kind: 'yours', id, text: `New decision ${id} · yours` })
52 }
53 for (const [id, one] of wasOpen) {
54 if (!isOpen.has(id) && new RegExp(`^##\\s+${id}\\b`, 'm').test(after)) changes.push({ kind: 'changed', id, text: `Decided ${id} · ${shortTitle(one.title, 40)}` })
55 }
56 return changes
57}
58
59// What one edit to an intent file changed. `intent` holds the intent's other files as they are now:
60// findings and progress rows are read against prompt.md (a decision recorded there closes its
61// finding; its ids name the rows), prompt.md against progress.md (its table says what is met).
62/** @param {IntentFile} file @param {string} before @param {string} after @param {{ prompt?: string, progress?: string }} [intent] @returns {Change[]} */
63export const intentChanges = (file, before, after, intent = {}) => {
64 if (before === after) return []
65 if (file === 'prompt.md') return promptChanges(before, after, intent.progress ?? '')
66 if (file === 'progress.md') return newlyDone(checklist(intent.prompt ?? '', before), checklist(intent.prompt ?? '', after), 'Met')
67 return findingChanges(before, after, intent.prompt ?? '')
68}
69
70// The intent file an edit touches: its folder name and which file, or null for anything else.
71/** @param {unknown} path @returns {{ slug: string, file: IntentFile } | null} */
72export const intentFileOf = path => {
73 const match = typeof path === 'string' ? /docs[\\/]intent[\\/]([^\\/]+)[\\/](prompt|findings|progress)\.md$/i.exec(path) : null
74 return match ? { slug: match[1], file: /** @type {IntentFile} */ (`${match[2].toLowerCase()}.md`) } : null
75}
76
77// The intent a session's own orchestration writes: its prompt.md or log.md (the orchestrator's files,
78// .agents/skills/intent/SKILL.md), as its folder name and which file; null for anything else.
79/** @param {unknown} path @returns {{ slug: string, file: 'prompt.md' | 'log.md' } | null} */
80export const orchestrationFileOf = path => {
81 const match = typeof path === 'string' ? /docs[\\/]intent[\\/]([^\\/]+)[\\/](prompt|log)\.md$/i.exec(path) : null
82 return match ? { slug: match[1], file: match[2].toLowerCase() === 'prompt' ? 'prompt.md' : 'log.md' } : null
83}
84
85/** @param {Change['kind']} kind */
86export const changeGlyph = kind => (kind === 'done' ? '✓' : kind === 'yours' ? '◆' : '✎')
87hooks/home.mjs 493 lines1// @ts-check
2// Ather Automata: what the console shows, and what the session is asked when
3// the person picks something. Pure: no `$`.
4
5import { windowDecisions } from './away.mjs'
6import { bringPrompt, collisionFact, moreText, overlapCount, spotLabel } from './collide.mjs'
7import { callId, findingAnswers, ruleAnswers, rulePrompt } from './decide.mjs'
8import { issueId, issueLabel, issuePrompt } from './issues.mjs'
9import { STAGE_LABELS, clockText, currentStage, cutWords, durationText, intentLabel, isEvening, isMine, nextStep, otherRoot, ownedIntents, pickCandidates, plural, prStatusList, shortTitle, waitingCalls } from './model.mjs'
10import { unreal } from './packs/unreal.mjs'
11import { PLAN_GLYPH, SHIPPED_GLYPH, STAGE_GLYPHS, ageText, isParkedBare, listStage, needsAttention, ownerName } from './worklist.mjs'
12
13/** @typedef {import('./packs/index.mjs').Pack} Pack */
14
15// The Unreal pack's lists and words, kept here for the modules and tests that read them from home.
16export { CREATE_GROUPS, SKILL_GROUPS, TOUR_PROMPT } from './packs/unreal.mjs'
17
18/** @typedef {import('./model.mjs').Intent} Intent */
19/** @typedef {import('./away.mjs').Away} Away */
20
21// ---------------------------------------------------------------- what the session is asked
22
23/** @param {Intent} intent @param {{ id: string }} finding */
24const callPrompt = (intent, finding) => {
25 const root = otherRoot(intent)
26 return `Walk me through decision ${finding.id} on intent ${intent.slug} (${root ? `${root}/` : ''}docs/intent/${intent.slug}/findings.md): what it is about, the options and your recommendation. Then ask me to choose with a question dialog, and record my answer in the intent.`
27}
28
29// How an answer given in place names the intent to the session: its key, with its findings file when it lives in another checkout.
30/** @param {Intent} intent */
31const callName = intent => {
32 const root = otherRoot(intent)
33 return root ? `${intent.key} (${root}/docs/intent/${intent.slug}/findings.md)` : intent.key
34}
35
36/** @param {Away} away @param {readonly { id: string, question: string }[]} decisions */
37const reviewPrompt = (away, decisions) =>
38 [
39 'I am back. Walk me through the away window, one item at a time with a question dialog each.',
40 decisions.length > 0 ? `Decisions taken for me (${away.ledgerPath}): ${decisions.map(one => `${one.id} ${one.question}`).join('; ')}. For each, show the choice and why, and ask me: keep it, undo it, or talk it through; then set its Status in the ledger.` : '',
41 away.parked.length > 0 ? `Actions held while I was away: ${away.parked.map(one => `${one.id} ${one.command}`).join('; ')}. For each, ask me: run it now, or drop it.` : '',
42 ]
43 .filter(Boolean)
44 .join(' ')
45
46export const NEW_INTENT_PROMPT =
47 'Start a new intent with the intent skill (.agents/skills/intent/SKILL.md). Interview me first, one question at a time and at most three: what I want to make or change, how I will know it is done, and what it must not break. Then start it with my area and my name as Owner, and show me its prompt.md before anything is built.'
48
49export const CREATE_SHOWN = 3
50// Home's preview of teammates' intents: four rows, then "+N more ›" (D7).
51export const TEAM_SHOWN = 4
52
53// Home in two views, remembered per person (simple-view D1-D5): Advanced draws every part; Simple only the
54// title and its status, Needs you, Needs attention, Next and the toggle. The rest stays a command away.
55/** @typedef {'advanced' | 'simple'} PaneView */
56// Home's parts, top to bottom.
57export const HOME_PARTS = /** @type {const} */ (['title', 'status', 'stages', 'meta', 'merge', 'strip', 'actions', 'needs', 'attention', 'next', 'crew', 'preview', 'away', 'warm', 'view'])
58/** @typedef {(typeof HOME_PARTS)[number]} HomePart */
59/** @param {unknown} value @returns {PaneView} */
60export const paneViewOf = value => (value === 'simple' ? 'simple' : 'advanced')
61/** @type {readonly HomePart[]} */
62export const SIMPLE_SHOWS = ['title', 'status', 'needs', 'attention', 'next', 'view']
63/** @param {PaneView} view @param {HomePart} part */
64export const isShownIn = (view, part) => view === 'advanced' || SIMPLE_SHOWS.includes(part)
65/** @param {PaneView} view @returns {PaneView} */
66export const otherView = view => (view === 'simple' ? 'advanced' : 'simple')
67// What choosing a view says, and how to go back.
68/** @param {PaneView} view */
69export const viewText = view => (view === 'simple' ? 'Simple view: what needs you and what is next. /ather advanced shows everything.' : 'Advanced view: everything Ather shows. /ather simple shows less.')
70/** @type {Record<PaneView, string>} */
71export const VIEW_LABELS = { simple: 'Simple view', advanced: 'Advanced view' }
72
73/** @param {string} name */
74export const skillFolder = name => (name.includes('/') ? name : `.agents/skills/${name}`)
75
76/** @param {string} name @param {string} target */
77const skillPrompt = (name, target) =>
78 `Run the ${name.split('/').pop()} skill (${skillFolder(name)}/SKILL.md)${target ? ` ${target}` : ''}: read it, tell me in two lines what it will do here, then follow it.`
79
80/** @param {string} question @param {Pack} [pack] */
81export const askPrompt = (question, pack = unreal) => pack.prompts.ask(question)
82
83// What working on an intent in this session means, said wherever a press tracks one without a view (D5).
84/** @param {Pack} [pack] */
85export const trackConsequence = (pack = unreal) =>
86 `This session gets its next step, your ${pack.id === 'unreal' ? 'builds and PIE' : 'tests and builds'} count as its proof, other sessions see you on it; /ather untrack undoes it.`
87
88// "fluid-snow-sand-look: Build, 8/17 done, Tin Nguyen's. Also tracked in 1 other session · active 3m ago.":
89// where an intent stands, in one line, for a surface without a pane.
90/** @param {Intent} intent @param {string} stage @param {string} me @param {string} [heldBy] */
91export const intentStands = (intent, stage, me, heldBy = '') =>
92 `${intent.slug}: ${stage}, ${intent.acceptanceTotal > 0 ? `${intent.acceptanceDone}/${intent.acceptanceTotal} done` : 'no checklist yet'}, ${isMine(intent, me) ? 'yours' : intent.owner ? `${intent.owner}'s` : 'no owner named'}.${heldBy ? ` ${heldBy}.` : ''}`
93
94// Where an intent stands, as its own files say it: the lines under "Where it stands" in its view, and
95// the reply on a surface without a pane. All of it is read from prompt.md, progress.md and findings.md
96// when the list was read, so showing it costs the session nothing. What is met is what progress.md says.
97/** @param {Intent} intent @param {string} stage @param {string} me @param {import('./model.mjs').PrStates} [prs] */
98export const standsLines = (intent, stage, me, prs = {}) => {
99 const checklist = intent.acceptanceTotal > 0 ? `${intent.acceptanceDone}/${intent.acceptanceTotal} met` : 'no checklist yet'
100 const whose = isMine(intent, me) ? 'yours' : intent.owner ? `${intent.owner}'s` : 'no owner named'
101 const parked = intent.status === 'parked' ? ` · parked${intent.statusNote ? `: ${shortTitle(intent.statusNote, 90)}` : ''}` : ''
102 /** @param {readonly string[]} all @param {number} shown */
103 const some = (all, shown) => `${all.slice(0, shown).join(' · ')}${all.length > shown ? ` · +${all.length - shown} more` : ''}`
104 return [
105 `${stage} · ${checklist} · ${whose}${parked}`,
106 intent.currentStep ? `Now: ${intent.currentStep}` : '',
107 intent.thenStep ? `Then: ${intent.thenStep}` : '',
108 intent.openItems.length > 0 ? `Still open: ${some(intent.openItems.map(one => [one.id, one.text].filter(Boolean).join(' ')), 4)}` : '',
109 intent.findings.length > 0 ? `Open decisions: ${some(intent.findings.map(one => `${one.id} ${cutWords(one.title, 48)}${one.isBlocking ? ' (blocking)' : ''}`), 3)}` : '',
110 intent.prs.length > 0 ? `PRs: ${prStatusList(intent, prs).join(', ')}` : '',
111 ].filter(line => line !== '')
112}
113
114// What stopping tracking said: done (proof stays with the intent), nothing tracked, or refused while away.
115/** @param {{ result: 'untracked' | 'none' | 'away', slug: string }} outcome */
116export const untrackText = outcome =>
117 outcome.result === 'untracked' ? `Stopped tracking ${outcome.slug}. Its proof so far stays with the intent.` : outcome.result === 'away' ? 'End the away window first.' : 'Nothing is tracked in this session.'
118
119/** @param {readonly Item[]} items */
120export const batchPrompt = items => `Take me through these one at a time, with a question dialog for each: ${items.map((one, index) => `(${index + 1}) ${one.prompt}`).join(' ')}`
121
122// ---------------------------------------------------------------- items
123
124/**
125 * What waits on the person. Every item goes to the session with its prompt; `kind`
126 * says what else changes once it has been delivered (see settleItem in state.mjs).
127 * @typedef {{ id: string, label: string, title: string, question: string, prompt: string, detail?: string, answers?: import('./decide.mjs').Answers }} ItemText `detail`: the pane's second line under `label`; `answers`: what answers it in place (0.2.0)
128 * A call's `slug` is its intent's key in the pane.
129 * @typedef {ItemText & ({ kind: 'call', slug: string } | { kind: 'review' } | { kind: 'lost' } | { kind: 'collide' } | { kind: 'editor' } | { kind: 'rule', ruleIds: string[] } | { kind: 'away-end' })} Item
130 */
131
132/** @typedef {import('./collide.mjs').MergeCheck} MergeCheck */
133
134// Whether this checkout's branch merges into origin's base, as Home's masthead says it (ship-pill D1): '' when it was
135// not compared (on the base, detached, nothing changed, origin's base not fetched).
136/** @param {MergeCheck | null} merge @param {number} now @returns {{ text: string, isWarn: boolean }} */
137export const mergeLine = (merge, now) => {
138 if (!merge) return { text: '', isWarn: false }
139 if (merge.collision) return { text: `${overlapCount(merge.collision.count)} with origin/${merge.base} · see Needs you`, isWarn: true }
140 const age = ageText(merge.at, now)
141 return { text: `Merges cleanly into origin/${merge.base} · checked ${age === '0m' ? 'just now' : `${age} ago`}`, isWarn: false }
142}
143
144// Each stage's glyph on the pill, the work list's (worklist.mjs): not begun, being built, half there, met, shipped.
145/** @type {Record<keyof typeof STAGE_LABELS, string>} */
146const PILL_GLYPHS = { plan: PLAN_GLYPH, build: STAGE_GLYPHS.build, prove: STAGE_GLYPHS.prove, ship: STAGE_GLYPHS.prove, close: STAGE_GLYPHS.met, shipped: SHIPPED_GLYPH }
147
148// The tracked intent as one pill above the prompt when nothing needs the person (ship-pill D2): its stage's glyph,
149// the stage (planned before anything is done or anyone works), the items met, and its name.
150/** @param {keyof typeof STAGE_LABELS} stage @param {boolean} isPlanned @param {string} label @param {Intent} intent */
151const stagePill = (stage, isPlanned, label, intent) =>
152 `${isPlanned ? PLAN_GLYPH : PILL_GLYPHS[stage]} ${label}${intent.acceptanceTotal > 0 && stage !== 'shipped' ? ` ${intent.acceptanceDone}/${intent.acceptanceTotal}` : ''} · ${intent.key}`
153
154/**
155 * @typedef {{ id: string, label: string, hint: string, prompt: string, isDraft?: boolean, isTour?: boolean, work?: Work, action?: 'checked', isLook?: boolean, look?: string }} Next
156 * `look`: the key of the intent whose view answers a step that only reads (model.mjs's `isLook`).
157 * Something to work on: an open intent to track, or an assigned GitHub issue to start an intent from.
158 * An intent's `owner` is its Owner line as written (people are matched on it), `who` the name shown,
159 * `stage` where it stands in the list, `source` where it was read (origin/main, or only this checkout), `key` its name
160 * in the pane (model.mjs's Intent), `repoName` its repository's short name when the list holds several checkouts' intents.
161 * @typedef {{ id: string, kind: 'intent', slug: string, key: string, root: string, repoName: string, label: string, hint: string, isMine: boolean, area: string, owner: string, who: string, updatedAt: number,
162 * stage: import('./worklist.mjs').ListStage, done: number, total: number, source: 'main' | 'local', warn: string }
163 * | { id: string, kind: 'issue', issue: import('./issues.mjs').Issue, repoName: string, label: string, hint: string, prompt: string, isMine: true, area: string, updatedAt: number, stage: '' }} Work
164 * @typedef {{
165 * intents: readonly Intent[], pinned: string | null, me: string, role: string, area: string, tourDone: boolean,
166 * evidence: import('./model.mjs').Evidence, away: Away, ledger: string, lost: { paths: string[], isDisclosed: boolean } | null,
167 * merge?: MergeCheck | null,
168 * lock: import('./model.mjs').EditorLock, recurring: readonly { id: string, title: string, fix: string, count: number }[],
169 * issues: readonly import('./issues.mjs').Issue[], last?: string | null, sent: readonly string[], workers: number, now: number, tz: number,
170 * skills?: readonly { name: string, description: string }[], prs?: import('./model.mjs').PrStates, week?: Week | null, pack?: Pack
171 * }} HomeInput `pinned` and `last`: intents' keys (the tracked one, and the one the person last worked on); `merge`: this checkout's
172 * branch as last compared with origin's base (collision-alert, ship-pill)
173 */
174
175/**
176 * This week's figures from the week-calendar plugin, when this PC runs it.
177 * @typedef {{ prsMerged: number, productive: number | null }} Week
178 */
179
180// ~/.calendar/latest.json, written by week-calendar: its figures while its week is still running.
181/** @param {string | null} text @param {number} now @returns {Week | null} */
182export const parseWeek = (text, now) => {
183 if (!text) return null
184 try {
185 const data = JSON.parse(text)
186 const start = Number(data?.week?.startMs), end = Number(data?.week?.endMs)
187 if (!(now >= start && now < end) || !data.metrics) return null
188 const productive = data.machineHours?.productiveUtilization
189 return { prsMerged: Number(data.metrics.prsMerged) || 0, productive: typeof productive === 'number' ? productive : null }
190 } catch {
191 return null
192 }
193}
194
195// "This week: 3 PRs merged · 68% productive"
196/** @param {Week | null | undefined} week */
197export const weekText = week =>
198 week ? [`This week: ${plural(week.prsMerged, 'PR')} merged`, week.productive === null ? '' : `${Math.round(week.productive * 100)}% productive`].filter(Boolean).join(' · ') : ''
199
200// What to work on, in one list: your open intents, then your GitHub issues that have no intent
201// yet (most urgent, then most recent), then teammates' intents you could follow. Intents and issues
202// from more than one checkout each carry their repository's short name.
203/** @param {readonly Intent[]} intents @param {readonly import('./issues.mjs').Issue[]} issues @param {string} me @param {string} area @param {number} now @param {string} [role] @param {import('./model.mjs').PrStates} [prs] @param {Pack} [pack] @returns {Work[]} */
204export const workList = (intents, issues, me, area, now, role = 'set', prs = {}, pack = unreal) => {
205 // An issue already started is hidden behind its intent: one in the same checkout.
206 const linked = new Set(intents.filter(one => one.issue).map(one => `${one.root}#${one.issue}`))
207 const ranked = pickCandidates(intents, me, area)
208 const isMany = new Set([...intents.map(one => one.root), ...issues.map(issue => issue.root ?? '')]).size > 1
209 /** @param {Intent} one @returns {Work} */
210 const toIntent = one => ({
211 id: `intent:${one.key}`, kind: 'intent', slug: one.slug, key: one.key, root: one.root, repoName: isMany ? one.repoName : '', label: one.slug, hint: intentLabel(one, me, prs), isMine: isMine(one, me), area: one.area,
212 owner: one.owner, who: ownerName(one.owner, one.firstAuthor, pack), updatedAt: one.updatedAt, stage: listStage(one, prs), done: one.acceptanceDone, total: one.acceptanceTotal, source: one.source,
213 warn: isParkedBare(one) ? 'parked, no reason' : '',
214 })
215 return [
216 ...ranked.filter(one => isMine(one, me)).map(toIntent),
217 ...issues
218 .filter(issue => !linked.has(`${issue.root ?? ''}#${issue.number}`))
219 .map(issue => (/** @type {Work} */ ({ id: issueId(issue), kind: 'issue', issue, repoName: isMany ? (issue.repoName ?? '') : '', label: `#${issue.number} ${issue.name}`, hint: issueLabel(issue, now), prompt: issuePrompt(issue, me, role, pack.roleWords), isMine: true, area: issue.area, updatedAt: issue.updatedAt, stage: '' }))),
220 ...ranked.filter(one => !isMine(one, me)).map(toIntent),
221 ]
222}
223
224// ---------------------------------------------------------------- the work list: sources, search, people
225
226// Where each piece of work comes from, in the order the list shows them. `key` is workGroup's answer.
227export const WORK_GROUPS = /** @type {const} */ ([
228 { key: 'mine', title: 'Your intents' },
229 { key: 'issues', title: 'Assigned issues' },
230 { key: 'others', title: "Teammates' intents" },
231])
232
233/** @param {Work} one @returns {'mine' | 'issues' | 'others'} */
234export const workGroup = one => (one.kind === 'issue' ? 'issues' : one.isMine ? 'mine' : 'others')
235
236// The work that matches every word of `query`: in its title, area, an issue's own title, or an intent's
237// owner as written or as shown, or its key.
238/** @param {readonly Work[]} work @param {string} query */
239export const filterWork = (work, query) => {
240 const words = query.toLowerCase().split(/\s+/).filter(Boolean)
241 return work.filter(one => {
242 const text = `${one.label} ${one.area} ${one.kind === 'issue' ? one.issue.title : `${one.owner} ${one.who} ${one.key}`}`.toLowerCase()
243 return words.every(word => text.includes(word))
244 })
245}
246
247// Eight colours that read on the pane's dark page: one per person, so a name is always the same colour.
248export const PEOPLE_COLOURS = ['#7aa2ff', '#ff8f6b', '#4fd1a5', '#d68cff', '#ffd166', '#5fd0e8', '#ff7eb6', '#a3d977']
249
250// A colour for each of these people: it starts at the hash of the name and steps on to the next free
251// colour when someone in the list already has it, so no two of them share one (up to eight).
252/** @param {readonly string[]} names @returns {Record<string, string>} */
253export const personColours = names => {
254 const taken = new Set()
255 /** @type {Record<string, string>} */
256 const out = {}
257 for (const name of [...new Set(names)].sort()) {
258 let hash = 0
259 for (const char of name.trim().toLowerCase()) hash = (hash * 31 + char.charCodeAt(0)) >>> 0
260 let at = hash % PEOPLE_COLOURS.length
261 for (let tries = 0; tries < PEOPLE_COLOURS.length && taken.has(at); tries += 1) at = (at + 1) % PEOPLE_COLOURS.length
262 taken.add(at)
263 out[name] = PEOPLE_COLOURS[at] ?? '#7aa2ff'
264 }
265 return out
266}
267
268// A colour dimmed by `amount` (0.3: 30%), blended toward the page it sits on: a terminal has no opacity.
269/** @param {string} hex '#rrggbb' @param {number} amount @param {string} [backdrop] */
270export const dimColour = (hex, amount, backdrop = '#1a1b1e') => {
271 const part = (/** @type {string} */ colour, /** @type {number} */ at) => parseInt(colour.slice(1 + at * 2, 3 + at * 2), 16)
272 return `#${[0, 1, 2].map(at => Math.round(part(hex, at) * (1 - amount) + part(backdrop, at) * amount).toString(16).padStart(2, '0')).join('')}`
273}
274
275/** @param {HomeInput} input */
276export const buildHome = input => {
277 const { intents, pinned, me, evidence, away, now, tz } = input
278 const prs = input.prs ?? {}
279 const pack = input.pack ?? unreal
280 // Unset ('') until the person says it: then any role's proof counts, and the Editor is assumed not needed.
281 const role = input.role
282 const intent = intents.find(one => one.key === pinned)
283 const owned = ownedIntents(intents, me, pinned)
284 // New until they take the tour, skip it or say their role, and while they own no intent.
285 const isNewcomer = me !== '' && !input.tourDone && input.role === '' && owned.length === 0
286 const stage = currentStage(intent, evidence, role, prs, pack)
287 const roleText = input.role ? `${pack.roleLabels[input.role] ?? input.role}` : isNewcomer ? '' : 'Role not set · /ather role'
288 const decisions = away.phase === 'off' ? [] : windowDecisions(input.ledger)
289 const lock = input.lock
290 const lockText = lock.state === 'free' ? 'Editor free' : lock.state === 'held' ? `Editor busy · ${lock.holder || 'another session'}${lock.until ? ` until ${lock.until}` : ''}` : ''
291
292 if (away.phase === 'running') {
293 const so = decisions.length + away.parked.length === 0 ? 'nothing for you yet' : `${plural(decisions.length, 'decision')} · ${away.parked.length} held`
294 /** @type {Item} */
295 const end = { kind: 'away-end', id: 'away-end', label: "I'm back: end the window", title: "End the window (I'm back)", question: `End the away window and review it (${so})`, prompt: '' }
296 const progress = away.untilDone ? 'until done' : `until ${clockText(away.wakeAt, tz)}`
297 return { actions: [], skills: [], create: [], editor: { isHeld: false, isFree: false, holder: '', until: '' }, header: { title: intent?.key ?? 'Ather', stage: 'Away', pill: '', progress, track: '', stages: [], proof: '', done: 0, total: 0, sentence: so, lock: lockText, role: roleText, week: weekText(input.week), merge: { text: '', isWarn: false } }, items: [end], open: [end], next: undefined, work: workList(intents, input.issues, me, input.area, now, 'set', {}, pack), own: [], teamPreview: { rows: [], total: 0 }, attention: [], isNewcomer: false, offerAway: false }
298 }
299
300 /** @type {Item[]} */
301 const items = []
302 if (away.phase === 'review') {
303 const what = [decisions.length > 0 ? plural(decisions.length, 'decision') : '', away.parked.length > 0 ? plural(away.parked.length, 'held action') : ''].filter(Boolean).join(', ') || 'nothing recorded'
304 items.push({ kind: 'review', id: `review:${away.startedAt}`, label: `Review: ${what}`, title: `Review what happened while you were away (${what})`, question: `While you were away: ${what}`, prompt: reviewPrompt(away, decisions) })
305 }
306 if (input.lost && !input.lost.isDisclosed) {
307 const paths = input.lost.paths
308 const named = `${(paths[0] ?? '').split('/').pop()?.replace(/\.(uasset|umap)$/i, '') ?? ''}${paths.length > 1 ? ` and ${plural(paths.length - 1, 'more')}` : ''}`
309 items.push({ kind: 'lost', id: 'lost', label: 'See what a merge lost', title: `A merge dropped your edits to ${named}`, question: `A merge dropped your edits to ${named}`, prompt: `The last merge kept the other side of these binary assets, so this branch's edits to them are gone: ${paths.join(', ')}. List them for me, itemised, each marked as a lost optimisation or a broken feature, and propose how to re-apply each.` })
310 }
311 // This checkout's branch no longer merges into origin's base: named by its places, the press brings the base in.
312 // Its id changes with the places, so one already handed over comes back only when they change.
313 const collision = input.merge?.collision
314 if (collision) {
315 const { a, b } = collision
316 const places = [...collision.spots.map(spot => spotLabel(collision, spot)), moreText(collision)].filter(Boolean).join(', ')
317 const name = `${b.branch} no longer merges cleanly into origin/${a.slug}`
318 items.push({ kind: 'collide', id: `collide:${b.branch}:${collision.files.join('|')}:${collision.count}`, label: `Bring origin/${a.slug} into ${b.branch}`, title: name, detail: `${overlapCount(collision.count)}: ${collisionFact(collision, now)} ${places}`, question: name, prompt: bringPrompt(collision) })
319 }
320 // A session that tracks an intent answers for that intent only: pressing another intent's call here would put it
321 // in this session's chat. With nothing tracked, every call of yours is offered, each named by its intent.
322 // Each call once across the checkouts holding a copy of its intent; tracked, the other copies only settle the tracked one's.
323 const calls = waitingCalls(owned, pinned).filter(call => !intent || call.intent.key === pinned)
324 for (const { intent: one, finding } of calls) {
325 items.push({ kind: 'call', slug: one.key, id: callId(one.key, finding.id), label: `Decide ${finding.id} on ${one.key}`, title: `${finding.id} · ${one.key === pinned ? '' : `${one.key} · `}${finding.title}`, detail: finding.full, question: `${finding.id} on ${one.key}: ${finding.title}`, prompt: callPrompt(one, finding), answers: findingAnswers(callName(one), finding) })
326 }
327 if (intent && pack.lockRoles.includes(role) && (stage === 'build' || stage === 'prove') && lock.state === 'held' && !lock.isStale) {
328 const holder = lock.holder || 'another lane'
329 items.push({ kind: 'editor', id: 'editor', label: 'Ask for the Editor', title: `Editor held by ${holder}${lock.until ? ` until ${lock.until}` : ''}: ask for a window`, question: `The Editor is held by ${holder}`, prompt: `Find the session that holds the Editor owner lock (${lock.raw}) and ask it for a short window for my next step. Wait for its answer before touching the Editor.` })
330 }
331 // Problems that keep coming back wait as one item, however many: eight rows of them buried the rest.
332 const recurring = input.recurring
333 if (recurring.length === 1) {
334 const [one] = recurring
335 items.push({
336 kind: 'rule',
337 ruleIds: [one.id],
338 id: `rule:${one.id}`,
339 label: 'Turn a repeated problem into a rule?',
340 title: `Keeps coming back: ${one.title}`,
341 detail: `"${one.title}" has come up in ${one.count} sessions.`,
342 answers: ruleAnswers([one], pack.owners),
343 question: `"${one.title}" has come up in ${one.count} sessions`,
344 prompt: rulePrompt([one], pack.owners),
345 })
346 } else if (recurring.length > 1) {
347 items.push({
348 kind: 'rule',
349 ruleIds: recurring.map(one => one.id),
350 id: `rule:${recurring.map(one => one.id).join('+')}`,
351 label: 'Turn repeated problems into rules?',
352 title: `${recurring.length} problems keep coming back: make them rules?`,
353 detail: `${recurring.length} problems have each come up in 3 or more sessions.`,
354 answers: ruleAnswers(recurring, pack.owners),
355 question: `${recurring.length} problems have each come up in 3 or more sessions`,
356 prompt: rulePrompt(recurring, pack.owners),
357 })
358 }
359 const open = items.filter(one => !input.sent.includes(one.id))
360 // Work handed to the session in this session (an issue being started) leaves the list.
361 const work = workList(intents, input.issues, me, input.area, now, role, prs, pack).filter(one => !input.sent.includes(one.id))
362 const step = nextStep(role, intent, evidence, input.workers, me, prs, pack)
363 const lastWork = work.find(one => one.kind === 'intent' && one.key === input.last && one.isMine)
364 /** @type {Next | undefined} */
365 let next
366 const own = pack.ownCheck
367 const isLostOpen = open.some(one => one.kind === 'lost')
368 if (isLostOpen) next = undefined
369 else if (isNewcomer && !intent) next = { id: 'next:tour', label: 'Take the tour', hint: 'Six short steps. Ends with your first intent started.', prompt: pack.prompts.tour, isTour: true }
370 // A tech artist with PIE proven has one proof left that only they can give: their own Editor check.
371 else if (intent && stage === 'prove' && own && role === own.role && evidence[own.after]?.state === 'pass' && evidence[own.rung]?.state !== 'pass') next = { id: `next:${intent.key}:checked`, label: own.label, hint: own.hint, prompt: '', action: 'checked' }
372 else if (intent && step) next = { id: `next:${intent.key}:${step.key}`, ...step, ...(step.isLook ? { look: intent.key } : {}) }
373 // Nothing tracked in this session: offer to continue the intent the person last worked on.
374 else if (!intent && lastWork?.kind === 'intent') next = { id: lastWork.id, label: `Continue ${lastWork.key}`, hint: lastWork.hint, prompt: '', work: lastWork }
375 else if (!intent && work[0]?.kind === 'intent') next = { id: work[0].id, label: `Pick up ${work[0].key}`, hint: work[0].hint, prompt: '', work: work[0] }
376 else if (!intent && work[0]?.kind === 'issue') next = { id: work[0].id, label: `Start issue #${work[0].issue.number}`, hint: `${work[0].issue.name} · ${work[0].hint}`, prompt: work[0].prompt, work: work[0] }
377 else if (step) next = { id: 'next:start', ...step }
378 // The quick actions under the header: start something new, or pick a skill from the short list.
379 const rest = work.filter(one => one !== next?.work)
380 const team = rest.filter(one => !one.isMine)
381 const present = new Map((input.skills ?? []).map(one => [one.name, one.description]))
382 const skills = pack.skillGroups.flatMap(({ group, names }) =>
383 names.filter(name => present.has(name)).map(name => ({ id: `skill:${name.split('/').pop()}`, group, name: name.split('/').pop() ?? name, description: present.get(name) ?? '', prompt: skillPrompt(name, intent ? `for intent ${intent.slug}` : '') })),
384 )
385 // The Editor's state decides what the session does first when making something there.
386 const editor = { isHeld: lock.state === 'held' && !lock.isStale, isFree: lock.state === 'free', holder: lock.holder, until: lock.until }
387 const order = pack.createOrder[role] ?? pack.createOrder[pack.roles[pack.roles.length - 1] ?? ''] ?? []
388 const create = [...pack.createGroups]
389 .sort((a, b) => order.indexOf(a.group) - order.indexOf(b.group))
390 .map(({ group, items }) => ({ group, items: items.filter(item => item.isGlobal || present.has(item.name)).map(item => ({ id: `create:${item.name.split('/').pop()}`, name: item.name.split('/').pop() ?? item.name, verb: item.verb, description: present.get(item.name) ?? '', prompt: pack.createPrompt(item.verb, item.name, editor) })) }))
391 .filter(one => one.items.length > 0)
392 /** @type {{ id: string, label: string, prompt?: string, opens?: 'skills' | 'create', isPrimary?: boolean }[]} */
393 const actions = [{ id: 'action:new-intent', label: '+ New intent', prompt: NEW_INTENT_PROMPT, isPrimary: true }]
394 if (skills.length > 0) actions.push({ id: 'action:skills', label: '▶ Skills', opens: 'skills' })
395 if (create.length > 0) actions.push({ id: 'action:create', label: '✦ Create', opens: 'create' })
396 // A checklist with nothing done and no one working yet is planned, not being built.
397 const isPlanned = !!intent && stage === 'build' && intent.acceptanceDone === 0 && !intent.hasWorker && input.workers === 0
398 const stageLabel = !intent ? '' : isPlanned ? 'Planned' : STAGE_LABELS[stage]
399 return {
400 actions,
401 skills,
402 create,
403 editor,
404 header: {
405 title: intent?.key ?? 'Ather',
406 stage: stageLabel,
407 pill: intent ? stagePill(stage, isPlanned, stageLabel, intent) : '',
408 progress: intent && intent.acceptanceTotal > 0 ? `${intent.acceptanceDone} of ${intent.acceptanceTotal} done` : '',
409 track: intent ? stageTrack(stage) : '',
410 stages: intent ? stageList(stage) : [],
411 proof: proofText(evidence, pack),
412 done: intent?.acceptanceDone ?? 0,
413 total: intent?.acceptanceTotal ?? 0,
414 sentence: away.phase === 'review' || isNewcomer ? '' : open.length > 0 ? 'waiting on you' : input.workers > 0 ? 'agents working' : intent ? '' : 'no intent yet',
415 lock: lockText,
416 role: roleText,
417 week: weekText(input.week),
418 merge: mergeLine(input.merge ?? null, now),
419 },
420 items,
421 open,
422 next,
423 work,
424 // With nothing tracked, the person's own other work after Next; for everyone, the team's first rows and how many (D7).
425 own: intent ? [] : rest.filter(one => one.isMine).slice(0, 5),
426 teamPreview: { rows: team.slice(0, TEAM_SHOWN), total: team.length },
427 // The person's own intents that want a press: every item met, or parked with no reason (D5).
428 attention: needsAttention(intents, me, prs).filter(one => !input.sent.includes(one.id)),
429 isNewcomer,
430 offerAway: !isNewcomer && away.phase === 'off' && (isEvening(now, tz) || (input.workers > 0 && open.length === 0)),
431 }
432}
433
434const STAGE_ORDER = ['plan', 'build', 'prove', 'ship']
435// How far along the four stages the work is; shipped, and ready to close, are past Ship.
436/** @param {string} stage */
437const stageIndex = stage => (stage === 'shipped' || stage === 'close' ? STAGE_ORDER.length : STAGE_ORDER.indexOf(stage))
438
439// Each stage with where the work is: done, now or to do; the pane colours them.
440/** @param {string} stage @returns {{ label: string, state: 'done' | 'now' | 'todo' }[]} */
441const stageList = stage => {
442 const at = stageIndex(stage)
443 return STAGE_ORDER.map((key, index) => ({ label: STAGE_LABELS[/** @type {keyof typeof STAGE_LABELS} */ (key)], state: index < at ? 'done' : index === at ? 'now' : 'todo' }))
444}
445
446// "Plan ✓ Build ✓ Prove ● Ship ○": where the work is, at a glance.
447/** @param {string} stage */
448const stageTrack = stage => {
449 const at = stageIndex(stage)
450 return STAGE_ORDER.map((key, index) => `${STAGE_LABELS[/** @type {keyof typeof STAGE_LABELS} */ (key)]} ${index < at ? '✓' : index === at ? '●' : '○'}`).join(' ')
451}
452
453// "build ✓ by session 1a2b3c4d · tests ✗": an intent's proof so far, each record another session wrote named
454// by that session (its title when known, `names`), so proof a helper produced is never taken for this one's.
455/** @param {import('./model.mjs').Evidence} evidence @param {Pack} pack @param {string} mine this session's first 8 hex @param {Readonly<Record<string, string>>} [names] */
456export const proofLine = (evidence, pack, mine, names = {}) =>
457 Object.entries(pack.proofWords)
458 .filter(([rung]) => (evidence[rung]?.state ?? 'none') !== 'none')
459 .map(([rung, word]) => {
460 const by = evidence[rung]?.by
461 const elsewhere = by && by !== mine ? ` by ${names[by] ? `"${names[by]}"` : `session ${by}`}` : ''
462 return `${word} ${evidence[rung]?.state === 'pass' ? '✓' : '✗'}${elsewhere}`
463 })
464 .join(' · ')
465
466// "Also tracked in 2 other sessions": the live sessions on this checkout that track the same intent;
467// '' when there are none. This is the line the session itself is told, so it carries no age: Claude Code
468// keeps the lane section as it first read it for the whole conversation (seen on 2.1.296), where
469// "active 4m ago" would stay long after it stopped being true.
470/** @param {readonly { intent: string | null }[]} peers @param {string} slug */
471export const trackedByLine = (peers, slug) => {
472 const same = peers.filter(lane => slug !== '' && lane.intent === slug)
473 return same.length === 0 ? '' : `Also tracked in ${plural(same.length, 'other session')}`
474}
475
476// "Also tracked in 2 other sessions · active 4m ago": the same line for a person, with when the latest
477// of those sessions last did something. For the pane and the dialogs, never for the session's prompt.
478/** @param {readonly { intent: string | null, updatedAt: number, lastActiveAt?: number }[]} peers @param {string} slug @param {number} now */
479export const heldByLine = (peers, slug, now) => {
480 const line = trackedByLine(peers, slug)
481 if (line === '') return ''
482 const ago = now - Math.max(...peers.filter(lane => lane.intent === slug).map(lane => Number(lane.lastActiveAt ?? lane.updatedAt) || 0))
483 return `${line} · ${ago < 60000 ? 'active now' : `active ${durationText(ago)} ago`}`
484}
485
486// "build ✓ · tests ✗": the proof seen so far, so a failed test is never hidden.
487/** @param {import('./model.mjs').Evidence} evidence @param {Pack} pack */
488const proofText = (evidence, pack) =>
489 Object.entries(pack.proofWords)
490 .filter(([rung]) => (evidence[rung]?.state ?? 'none') !== 'none')
491 .map(([rung, word]) => `${word} ${evidence[rung]?.state === 'pass' ? '✓' : '✗'}`)
492 .join(' · ')
493hooks/team.mjs 312 lines1// @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