SLOPSHOPPER

polis

A project dashboard and isometric city map: progress, tasks, agents, resources, processes and skills

panebandguardcommandtoaststatus
v0.2.0MITupdated 2026-10-22SashimmyUni/polis
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · polis
│ ┃ Polis ✕ › fix the failing auth test and add an audit ╭─────────────────────╮ │ ┃ ◆ POLIS app │ polis │ │ ┃ [ Overview ] [ Project ] [ City ] [ Tasks ] ● polis: polis: turn.start: TypeError: undefi│ Check failed: tests │ │ ┃ ctx 97k ⏺ Read(src/auth.ts) ╰─────────────────────╯ │ ┃ [ Full city ] ⎿ Read 6 lines │ ┃ ⏺ Update(src/auth.ts) │ ┃ CITY ⎿ Added 2 lines, removed 1 line │ ┃ ◆ city hall your turn ⏺ Bash(bun test) │ ┃ No districts yet: they appear with the first ⎿ 3 pass, 1 fail │ ┃ tasks. │ ┃ ● Done. refresh now rejects expired claims and logs an audit event. │ ┃ ⚡ power █████ ░░░░░ context 49% │ ┃ ◈ works: 0 running ✦ library: 0 skills used ✻ Worked for 42s · done 4:20 PM │ ┃ ▣ checks: tests ✘ │ ┃ ◇ your turn › /city │ ⎿ polis: Polis opened. │ │ ctx 97k [ City ] [ Hide ] ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts ⚠ polis: ctx 97k

Draws

Band
ctx 97k [ City ] [ Hide ]
Pane · Polis
◆ POLIS app [ Overview ] [ Project ] [ City ] [ Tasks ] [ Agents ] [ Res ctx 97k [ Full city ] CITY ◆ city hall your turn No districts yet: they appear with the first tasks. ⚡ power █████ ░░░░░ context 49% ◈ works: 0 running ✦ library: 0 skills used ▣ checks: tests ✘ ◇ your turn
README

Polis

A Claude Code mod that keeps a complex project legible while Claude works on it: a band above the prompt, a pane with seven views, and an isometric city in which districts are the parts of the code being worked on, buildings are tasks and agents stand on what they are working on.

The user manual explains how to read every part of it.

What it shows

  • Band — only what to act on now, on one row: what needs you, a usage-limit warning while one fires, the smart zone (context in tokens) and tasks done.
  • Smart-zone warning — context measured in tokens against a smart-zone limit (150k by default, whatever the window): amber at the caution (80% of the limit), rose past it, with one toast per crossing. Claude is told too, by a note after your next prompt, to hand pieces to sub-agents or stop at the next phase boundary and recommend /clear or /compact.
  • Pane (/city, or the band's City button), with seven views:
  • Overview — what needs you, the project and this session, milestones, the current prompt's actual against expected, tasks and how the finished ones stand, checks, git, agents, background processes, recent activity, most-edited files.
  • Project — every session of the project, with the agents each ran and their sub-agents.
  • City — the map, at night and alive: a moon that fills with the project's progress, a canal with a boat and a lighthouse, street lamps, cars, fireworks when every task is done. A lot is a planned task, scaffolding is one in progress, lit windows are done; a pennant on the roof marks work something checked, a rose cross work that failed its check, and a pale quiet building work nobody checked. A rose barrier is blocked; dashed arcs show what waits on what. City Hall is the main session (rose flag and a speech bubble when Claude waits on you), the plant's tank is the context window, a signal mast has one lamp per check. Full city (f) adds everything the project has ever finished, from its archive: the newest work as quieter buildings, the oldest as an old town of towers with a count.
  • Tasks — the task tree with sub-tasks, owners, blockers, and the tasks earlier sessions left.
  • Agents — an icon per agent carrying the tools it uses most, with status, tokens and its task.
  • Resources — tokens, time and tool calls against expected; context window; rate limits, each with a forecast of whether it lasts until the reset; cost; what prompts usually cost in this project.
  • Skills — used, suggested for the work at hand, available.
  • Pages on disk — the city as self-refreshing HTML files in the project: .polis/city.html (current) and .polis/city-full.html (full), each linking to the other. Open one once in a browser or VS Code's Integrated Browser and leave it beside your editor; no server is needed. The header says what needs you, the smart-zone state and tasks done.

Commands

  • /city [overview|project|city|tasks|agents|resources|skills] — open the pane at a view. Where nothing can draw it, the command answers with the board as text, and /city project with the project's sessions as text.
  • /city report — the session as a Markdown report, as text. /city report save also writes it to polis-report.md in the working directory.
  • /city [overview|city|tasks|agents|resources|skills] — open the pane at a view. Where nothing can draw it, the command answers with the board as text.
  • /city page — reply with the paths and file:/// URLs of both pages on disk, and how to open one in VS Code's Integrated Browser.
  • /orchestrate <goal> — plan a goal into tasks and run them with parallel agents (polis:worker, polis:verifier).

Where it draws

HostWhat you get
Claude desktop app, Code tabEverything, with the city and agent icons as vector drawings.
claude in a terminal, including VS Code's integrated terminalEverything as text; the city is a row of blocks per district.
VS Code extension's chat panelThe pane, with City's top strip and the city as drawings, but no band; the status line stands in for it.

The pane adapts to its size. The city is cropped to what is built and drawn to the pane's shape, in one of three layouts (wide, avenue, or a one-block-wide column under 44 columns), with its key written on the buildings. Under 44 columns bars sit under their labels.

Options

Set in /config, or under pluginConfigs.polis.options in settings.

OptionDefaultMeaning
estimatebothHow a prompt's expected cost is sized: history (free, from this project's past turns), model (a small-model call per prompt), or both (history, plus the model for long prompts).
guidancetrueAdd a short standing instruction so Claude keeps tasks and milestones current, and offer it the mcp__polis__project tool.
autoOpentrueOpen the pane the first time tasks or agents appear in a session.
motiontrueLet the city move: its cars, its boat, its fireworks. false draws it still.
pagetrueWrite the city to .polis/city.html and the full city to .polis/city-full.html each time the board or archive changes.
smartZone150000The smart-zone limit in tokens. The caution comes at 80% of it; on a smaller window the limit is 80% of the window.

Install

From this repository, as a marketplace:

claude plugin marketplace add SashimmyUni/polis
claude plugin install polis@polis

Or from a local copy: name its folder in CLAUDE_CODE_PLUGIN_DIRS, in the env block of ~/.claude/settings.json. Sessions started after that load it.

Developing

claude here means the Claude Code binary (on this machine: %APPDATA%\Claude\claude-code\<version>\<hash>\claude.exe).

node tools/check.ts

The check command runs five stages: install (the pinned TypeScript and Node types of package.json, only when node_modules is missing or out of date; the mod itself has no dependencies), validation, type-check (hooks/, types/ and tests/ against the engine's types), tools type-check (tools/ against Node's types) and tests. It stops at the first stage that fails, names it and prints that stage's full output; tools/check.ts's header and stage list say what each one runs. Both type-checks need the engine-generated .claude-plugin/types/ (gitignored); when it is missing, the check command's message says how to produce it. .github/workflows/ci.yml has the engine write those types, then runs the check command, on pushes to main and on pull requests.

A tracked pre-commit hook in .githooks/ runs the same command and refuses the commit when it fails. Turn it on once per clone; it then applies to every worktree of that clone:

git config core.hooksPath .githooks

git commit --no-verify skips it for one commit.

Every call on the engine ($) and every piece of state lives in hooks/register.tsx; the validator requires it. The other files under hooks/ are pure: logic.ts (tracking, estimates, usage-limit forecasts, carried tasks), checks.ts (what counts as a test, lint, type or build run), codemap.ts (code areas, git), verify.ts (verdicts), projectlog.ts (the project's sessions), archive.ts (every finished task, for the full city), page.ts (the pages on disk), report.ts (the Markdown report), views.tsx (band and pane), city.ts and icons.ts (the drawings), theme.ts (palette). tools/preview.ts draws the city for made-up sessions into an HTML page for judging its look in a browser; tools/measure.ts reports at how many buildings a large city starts to shed detail (node --import ./tools/ts-resolve.mjs tools/measure.ts).

The mod records the room each surface gives its band and pane under the rooms key of its store, which is the first thing to read when a drawing looks wrong somewhere.

License

MIT. See LICENSE.

Source 20 files
hooks/register.tsx 1913 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, UiOpenResult } from 'claude-code'
3
4import type {
5  AgentRun,
6  AgentRunStatus,
7  CheckKind,
8  LiveSession,
9  Proc,
10  RateLimit,
11  Task,
12  Turn,
13  Ui,
14  Usage,
15  ViewName,
16  Wait,
17} from '../types'
18import { WRAP_UP, askOf } from './ask'
19import { CHECK_LABEL, checksOf, noteEdit, outcomeOf, recordChecks, stateOf } from './checks'
20import { GIT_DIFF, GIT_STATUS, areaOfPath, noteTouch, parseGit, taskOfEdit } from './codemap'
21import { CHANGE_MS, liveKeeper, liveSessionOf } from './live'
22import type { LiveKeeper } from './live'
23import {
24  ASKING,
25  SIZES,
26  SIZING_RUBRIC,
27  about,
28  addWait,
29  asHistory,
30  asProject,
31  asTracks,
32  bumpFamily,
33  carryTasks,
34  clip,
35  createTask,
36  endProc,
37  expectedFor,
38  fileUrl,
39  firstQuestion,
40  forecastText,
41  forecastsOf,
42  heuristicSize,
43  hitFile,
44  isBlocking,
45  isLive,
46  limitName,
47  limitToast,
48  matchTask,
49  mergeProject,
50  mergeTodos,
51  mergeTracks,
52  newProject,
53  patchTask,
54  pick,
55  projectName,
56  pushActivity,
57  recordLimit,
58  recordTasks,
59  reconcileProcs,
60  shouldAskModel,
61  SMART_ZONE,
62  smartZoneOf,
63  stampDone,
64  suggestSkills,
65  taskStats,
66  under,
67  upsertProc,
68  zoneCrossing,
69  zoneLimit,
70  zoneNote,
71  zoneOf,
72  zoneOwing,
73  zoneToast,
74} from './logic'
75import type { EstimateMode, SavedTasks } from './logic'
76import { EMPTY_ARCHIVE, asArchive, offBoard, syncArchive } from './archive'
77import { asProjectLog, projectHeadline, projectLines, sessionRecord, upsertSession } from './projectlog'
78import { REPORT_FILE, reportOf } from './report'
79import { PAGE_FILES, PAGE_REFRESH_SECONDS, cityPage } from './page'
80import { VIEWS, familyOf } from './theme'
81import { dropStaleVerdicts, isVerifier, judge, judgeByChecks, taskToJudge, verdictOf } from './verify'
82import { flowOf, stalledOf, workKind } from './flow'
83import { raise, sessionName, stallText, zoneText } from './notify'
84import { NO_PROGRESS, agentEnded, callBegan, callEnded, callOf, checkRan, progressed } from './stall'
85import { GH_TIMEOUT, asTracker, isDue, readTracker } from './frontier'
86import { band, pane, stripElements, summary } from './views'
87import type { Actions, Model, StripModel } from './views'
88
89const PANE = 'polis'
90const TITLE = 'Polis'
91const PROJECT_TOOL = 'mcp__polis__project'
92
93// The room the pane asks for where a surface lets a plugin say: enough for
94// the city at a readable size while the conversation keeps about half the
95// window. A request, not a grant: the person's own size wins, and a pane
96// left narrow gets the narrow layout instead.
97const ROOM = { rows: 46, columns: 68 } as const
98
99const IDLE: Turn = {
100  id: null,
101  isWorking: false,
102  startedAt: 0,
103  endedAt: 0,
104  expected: null,
105  tokens: 0,
106  outTokens: 0,
107  cacheRead: 0,
108  tools: 0,
109  steps: 0,
110  agents: 0,
111  hasWarned: false,
112  hasNeededYou: false,
113}
114
115const UNMEASURED: Usage = {
116  contextTokens: 0,
117  contextWindow: 0,
118  contextPercent: 0,
119  rateLimits: [],
120  costUsd: 0,
121  sessionTokens: 0,
122  mainFamilies: {},
123  zoneLimit: SMART_ZONE,
124  zoneAnnounced: 'inside',
125  zoneOwed: 'inside',
126}
127
128const tasks = atom({ plugin: 'polis', key: 'tasks' } as const, [])
129const agents = atom({ plugin: 'polis', key: 'agents' } as const, [])
130const procs = atom({ plugin: 'polis', key: 'procs' } as const, [])
131const turn = atom({ plugin: 'polis', key: 'turn' } as const, IDLE)
132const usage = atom({ plugin: 'polis', key: 'usage' } as const, UNMEASURED)
133const history = atom({ plugin: 'polis', key: 'history' } as const, [])
134const project = atom({ plugin: 'polis', key: 'project' } as const, null)
135const skills = atom({ plugin: 'polis', key: 'skills' } as const, {
136  available: [],
137  used: {},
138  suggested: [],
139})
140const ui = atom({ plugin: 'polis', key: 'ui' } as const, {
141  view: 'overview',
142  isBandHidden: false,
143  hasOpened: false,
144  cityView: 'current',
145})
146const activity = atom({ plugin: 'polis', key: 'activity' } as const, [])
147const files = atom({ plugin: 'polis', key: 'files' } as const, [])
148const waits = atom({ plugin: 'polis', key: 'waits' } as const, [])
149const limits = atom({ plugin: 'polis', key: 'limits' } as const, [])
150const checks = atom({ plugin: 'polis', key: 'checks' } as const, [])
151const git = atom({ plugin: 'polis', key: 'git' } as const, null)
152const log = atom({ plugin: 'polis', key: 'log' } as const, null)
153const archive = atom({ plugin: 'polis', key: 'archive' } as const, null)
154const tick = atom({ plugin: 'polis', key: 'tick' } as const, 0)
155const others = atom({ plugin: 'polis', key: 'others' } as const, [])
156const flow = atom({ plugin: 'polis', key: 'flow' } as const, null)
157const tracker = atom({ plugin: 'polis', key: 'tracker' } as const, null)
158const progress = atom({ plugin: 'polis', key: 'progress' } as const, NO_PROGRESS)
159
160const GUIDANCE = {
161  id: 'polis:guidance',
162  scope: 'session',
163  text: [
164    'The person watches a live project dashboard (Polis). For work of three or more steps,',
165    'record the steps with the task tool before starting, mark each one in progress as you',
166    'begin it and completed as soon as it is verified. When creating a task, set',
167    '`metadata.area` to the repository directory or package it mainly touches (for example',
168    "api, web, docs) and, for a sub-task, `metadata.parent` to its parent task's id. Where this session has no task",
169    `tool, record and update the same steps through the \`tasks\` of the ${PROJECT_TOOL} tool`,
170    `instead. For project-level work, record the project's milestones with ${PROJECT_TOOL}`,
171    'once the plan is known, and update them whenever a milestone starts or completes.',
172  ].join(' '),
173} as const
174
175const PROJECT_SPEC = {
176  name: 'project',
177  description: [
178    "Records this project's plan on the person's Polis dashboard: its milestones and the",
179    'current phase. Call it once the plan for project-level work is known, and again when a',
180    'milestone starts or completes. Milestones are matched by `id`: send only the ones that',
181    'changed. The record is kept across sessions for this project folder. In a session with',
182    'no task tool of its own, `tasks` records the steps of the work at hand the same way:',
183    'send each task once with its subject and area, then again by `id` as its status changes.',
184  ].join(' '),
185  inputSchema: {
186    type: 'object',
187    properties: {
188      name: { type: 'string', description: "The project's display name." },
189      phase: { type: 'string', description: 'A few words on what is happening now.' },
190      milestones: {
191        type: 'array',
192        items: {
193          type: 'object',
194          properties: {
195            id: { type: 'string', description: 'A short stable slug.' },
196            title: { type: 'string' },
197            status: { type: 'string', enum: ['planned', 'active', 'done'] },
198          },
199          required: ['id'],
200        },
201      },
202      tasks: {
203        type: 'array',
204        description: 'Only where the session has no task tool: the steps of the current work.',
205        items: {
206          type: 'object',
207          properties: {
208            id: { type: 'string', description: 'A short stable slug.' },
209            subject: { type: 'string' },
210            status: { type: 'string', enum: ['pending', 'in_progress', 'completed', 'deleted'] },
211            area: {
212              type: 'string',
213              description: 'The repository directory or package it mainly touches: api, web, docs.',
214            },
215            parent: { type: 'string', description: 'The id of the task this is a sub-task of.' },
216            owner: { type: 'string', description: 'The name of the agent working on it.' },
217            blockedBy: { type: 'array', items: { type: 'string' } },
218            activeForm: { type: 'string', description: 'Shown while in progress: "Running tests".' },
219          },
220          required: ['id'],
221        },
222      },
223    },
224  },
225  isDeferred: false,
226} as const
227
228const WORKER_PROMPT = [
229  'You are a worker in an orchestrated run. You are given one self-contained',
230  'task with the files or area it covers and what done looks like.',
231  'Do exactly that task and stay inside its scope: another worker may be',
232  'editing other files at the same time.',
233  'End with a short report: what you changed (paths), how you checked it,',
234  'and anything you could not finish or that looked wrong.',
235].join(' ')
236
237const VERIFIER_PROMPT = [
238  'You are the verifier in an orchestrated run. You are given a claim about',
239  'finished work. Check it against the actual files and by running the',
240  'relevant tests or commands; never take the claim on trust and never edit',
241  'files. Answer PASS or FAIL first, then the evidence: commands run, their',
242  'output, and each defect with its path and line.',
243].join(' ')
244
245const orchestrationBrief = (goal: string): string =>
246  [
247    'Act as the orchestrator for the goal below. I am asking for subagents here: use them.',
248    '',
249    `1. Plan. Break the goal into 3 to 8 tasks and record every one with the task tool before any work starts, each with \`metadata.area\` (where this session has no task tool, through the \`tasks\` of ${PROJECT_TOOL}, each with its \`area\`). Note which tasks depend on each other.`,
250    '2. Delegate. Start every independent task as its own Agent call, all in one message so they run in parallel. Give each a self-contained brief: the task, the files or area, what done looks like. Use `polis:worker` for implementation, `Explore` for read-only searching, `polis:verifier` for checking. Keep tiny or strictly sequential tasks for yourself, and never let two agents write the same files.',
251    '3. Track. Mark a task in progress as it starts and completed only once it is verified.',
252    '4. Verify. Treat each agent report as a claim: read the diff or run the tests before accepting it, and send failed work back with what was wrong.',
253    '5. Report. Finish with what was done, what failed and what is left.',
254    '',
255    `Goal: ${goal}`,
256  ].join('\n')
257
258// The tools whose result can name work left running, or work stopped.
259const BACKGROUND = new Set([
260  'Bash',
261  'PowerShell',
262  'Monitor',
263  'Workflow',
264  'CronCreate',
265  'CronDelete',
266  'TaskStop',
267])
268
269// The tools whose command line may run a check, and the ones that change a file.
270const SHELLS = new Set(['Bash', 'PowerShell'])
271const EDITS = new Set(['Edit', 'Write', 'NotebookEdit'])
272
273// Limits are the account's, shared by every session of every project: their
274// readings are kept under one key, whatever the project.
275const LIMITS_KEY = 'limits'
276
277// What is known of the session itself, for its record in the project's log.
278// Tokens are counted from where the session began: a /clear goes on in the
279// same process, whose count does not start over.
280type Here = {
281  id: string
282  root: string
283  startedAt: number
284  title: string
285  turns: number
286  tokensKept: number
287  tokensFrom: number
288}
289
290const NOWHERE: Here = {
291  id: '',
292  root: '',
293  startedAt: 0,
294  title: '',
295  turns: 0,
296  tokensKept: 0,
297  tokensFrom: 0,
298}
299
300// Whether the session is known by its id and its project: what a record
301// written under them needs.
302const isKnown = (here: Here): boolean => here.id !== '' && here.root !== ''
303
304const say = ($: EngineInterface, where: string, error: unknown): void => {
305  $.ui.log(`polis: ${where}: ${String(error)}`)
306}
307
308// The phase a flow skill or command starts; one off the table leaves the
309// phase as it was.
310const startPhase = async ($: EngineInterface, name: string): Promise<void> => {
311  try {
312    const started = flowOf(name)
313    if (started === undefined) return
314    await update($, flow, () => started)
315    await refresh($, false)
316  } catch (error) {
317    say($, 'reading the phase', error)
318  }
319}
320
321const note = async ($: EngineInterface, kind: string, text: string): Promise<void> => {
322  const at = await $.clock.now()
323  await update($, activity, list => pushActivity(list, { at, kind, text }))
324}
325
326const saveProject = async ($: EngineInterface): Promise<void> => {
327  const record = await read($, project)
328  if (record !== null) await $.store.set(`project:${record.root}`, record)
329}
330
331const openPane = ($: EngineInterface) => $.ui.open({ id: PANE, title: TITLE, ...ROOM })
332
333// The room each surface last gave the band and the pane, kept in the store
334// so a drawing that looks wrong somewhere can be explained from its numbers.
335let rooms: { [site: string]: string } = {}
336let hasNewRoom = false
337
338const measure = (site: string, room: object): void => {
339  const text = JSON.stringify(room)
340  if (rooms[site] === text) return
341  rooms = { ...rooms, [site]: text }
342  hasNewRoom = true
343}
344
345// Whether any surface has asked for the band: the engine raises `AbovePrompt`
346// on some surfaces only, and a session drawn on none of them has no band.
347let isBandAsked = false
348
349// The status line stands in for the band while the band is hidden, and where
350// no surface draws one: the band's strip as plain text, every element kept,
351// since the line has no width of its own. Where no surface draws the band or
352// the pane (an editor's chat panel) this line is all there is to see.
353const refresh = async ($: EngineInterface, shouldOpen: boolean): Promise<void> => {
354  const state = await read($, ui)
355  const model = await loadStrip($)
356  const strip = stripElements(model)
357  $.ui.status(
358    (isBandAsked && !state.isBandHidden) || strip.length === 0
359      ? undefined
360      : strip.map(element => element.text).join(' · '),
361  )
362  if (!shouldOpen || state.hasOpened) return
363
364  const stats = taskStats(model.tasks)
365  if (stats.total > 0 || (await read($, agents)).length > 0) {
366    await update($, ui, value => ({ ...value, hasOpened: true }))
367    void openPane($).catch(() => undefined)
368  }
369}
370
371// Only the stores the strip is made from: the status line follows every move
372// of the context, so it reads no more than it shows.
373const loadStrip = async ($: EngineInterface): Promise<StripModel> => ({
374  now: await $.clock.now(),
375  waits: await read($, waits),
376  limits: await read($, limits),
377  usage: await read($, usage),
378  tasks: await read($, tasks),
379  others: await read($, others),
380  turn: await read($, turn),
381  agents: await read($, agents),
382  flow: await read($, flow),
383  progress: await read($, progress),
384})
385
386// Something holds work up until the person acts. The turn remembers it was
387// put to the person, answered or not.
388const needYou = async ($: EngineInterface, wait: Wait): Promise<void> => {
389  await update($, waits, list => addWait(list, wait))
390  await update($, turn, value => (value.isWorking ? { ...value, hasNeededYou: true } : value))
391}
392
393// Why the work stalled, as the strip last said it: the clock draws again only
394// when that changes, so the stall's age moves and a cleared stall leaves.
395// Nothing while the work is not stalled.
396let stallSaid: string | undefined
397
398// This session as a notification names it; set once the mod registers.
399let nameHere = (): string => sessionName('', '')
400
401// Reads the stall rule now. A stall that begins where there was none is the
402// moment to tell the person; one that only changes its reason is the same
403// stall.
404const watchStall = async ($: EngineInterface): Promise<void> => {
405  const model = await loadStrip($)
406  const stall = stalledOf(model)
407  const said = stall === undefined ? undefined : `${about(model.now - stall.since)}: ${stall.why}`
408  if (said === stallSaid) return
409  const hasBegun = stall !== undefined && stallSaid === undefined
410  stallSaid = said
411  await refresh($, false)
412  if (!hasBegun) return
413  await note($, 'stall', `Stalled: ${stall.why}`)
414  await raise($, stallText(nameHere(), stall.why))
415}
416
417// Work moved (a step, a tool call or an agent event): the progress is
418// recorded, and a stall it begins or ends is shown and may be notified.
419const recordProgress = async ($: EngineInterface, change = progressed): Promise<void> => {
420  const now = await $.clock.now()
421  await update($, progress, value => change(value, now))
422  await watchStall($)
423}
424
425const rootOf = async ($: EngineInterface): Promise<string> => {
426  const repo = await $.session.repo().catch(() => null)
427
428  return repo?.root ?? (await $.session.cwd())
429}
430
431// The session as it is now. A /clear goes on under a new id with no
432// `session.start` raised for it: the first thing seen under the new id
433// begins its record.
434const whereabouts = async ($: EngineInterface, here: Here, now: number): Promise<Here> => {
435  const id = await $.session.id().catch(() => here.id)
436  const root = here.root === '' ? await rootOf($).catch(() => '') : here.root
437  if (id === here.id) return root === here.root ? here : { ...here, root }
438
439  return {
440    ...NOWHERE,
441    id,
442    root,
443    startedAt: now,
444    tokensFrom: (await read($, usage)).sessionTokens,
445  }
446}
447
448// A tool call that ended, however it ended, is waited on no longer.
449const endWaits = async (
450  $: EngineInterface,
451  tool: string,
452  agentId: string | undefined,
453): Promise<void> => {
454  const isOver = (wait: { tool?: string; agentId?: string }): boolean =>
455    wait.tool === tool && wait.agentId === agentId
456  if (!(await read($, waits)).some(isOver)) return
457  await update($, waits, list => list.filter(wait => !isOver(wait)))
458  await refresh($, false)
459}
460
461// Reopened work is no longer what was checked. Only the task whose status
462// moved is looked at: a verifier may have judged another before it was done.
463const reopen = (before: readonly Task[], after: readonly Task[]): Task[] =>
464  after.map(task => {
465    const was = before.find(one => one.id === task.id)
466
467    return was?.status === 'completed' && task.status !== 'completed'
468      ? (dropStaleVerdicts([task])[0] ?? task)
469      : task
470  })
471
472// One more reading of the limit windows, joined with what parallel sessions
473// read, and one toast for a window on course to run out before it resets.
474const trackLimits = async ($: EngineInterface, readings: readonly RateLimit[]): Promise<void> => {
475  const now = await $.clock.now()
476  const base = mergeTracks(await read($, limits), asTracks(await $.store.get(LIMITS_KEY)))
477  let tracks = [
478    ...readings.map(limit =>
479      recordLimit(
480        base.find(track => track.kind === limit.kind),
481        limit,
482        now,
483      ),
484    ),
485    ...base.filter(track => !readings.some(limit => limit.kind === track.kind)),
486  ]
487  for (const forecast of forecastsOf(readings, tracks, now)) {
488    const track = tracks.find(one => one.kind === forecast.kind)
489    if (forecast.outlook !== 'short' || track === undefined || track.hasWarned) continue
490    tracks = tracks.map(one => (one === track ? { ...one, hasWarned: true } : one))
491    $.ui.toast(limitToast(forecast, now))
492  }
493  const kept = tracks
494  await update($, limits, () => kept)
495  await $.store.set(LIMITS_KEY, kept)
496}
497
498// The working tree, asked of git itself. Any failure leaves what was known.
499const readGit = async ($: EngineInterface, root: string): Promise<void> => {
500  if (root === '') return
501  try {
502    const init = { cwd: root, timeoutMs: 5000 }
503    const status = await $.process.run(GIT_STATUS, init)
504    if (status.exitCode !== 0) return
505    // A repository with no commit yet has no HEAD to compare with: no lines counted.
506    const diff = await $.process.run(GIT_DIFF, init)
507    const next = parseGit(status.stdout, diff.exitCode === 0 ? diff.stdout : '', await $.clock.now())
508    if (next !== null) await update($, git, () => next)
509  } catch {
510    // Not a repository, no git, or a slow one.
511  }
512}
513
514// The wayfinder frontier, asked of `gh` at most every five minutes, the time
515// kept with it so that parallel sessions of the project share the wait.
516let isReadingTracker = false
517
518const readFrontier = async ($: EngineInterface, root: string): Promise<void> => {
519  if (root === '' || isReadingTracker) return
520  isReadingTracker = true
521  try {
522    const key = `tracker:${root}`
523    const now = await $.clock.now()
524    const held = await read($, tracker)
525    const last = asTracker(await $.store.get(key)) ?? held
526    if (!isDue(last, now)) {
527      if (held === null && last !== null) await update($, tracker, () => last)
528      return
529    }
530    const next = await readTracker(argv => $.process.run(argv, { cwd: root, timeoutMs: GH_TIMEOUT }), last, now)
531    await update($, tracker, () => next)
532    await $.store.set(key, next)
533  } catch {
534    // The store refused it: the frontier stays as it was.
535  } finally {
536    isReadingTracker = false
537  }
538}
539
540// The project's archive brought in line with the board. The stored archive
541// is read again just before, so that a parallel session's work is not lost.
542const saveArchive = async ($: EngineInterface, here: Here, board: readonly Task[]): Promise<void> => {
543  if (!isKnown(here)) return
544  const key = `archive:${here.root}`
545  const stored = asArchive(await $.store.get(key))
546  const next = syncArchive(stored, board, here.id)
547  await update($, archive, () => next)
548  if (next !== stored) await $.store.set(key, next)
549}
550
551// The board as the sessions that follow will find it.
552const saveTasks = async ($: EngineInterface, here: Here): Promise<void> => {
553  if (here.root === '') return
554  const at = await $.clock.now()
555  const list = await update($, tasks, value => stampDone(value, at))
556  const saved: SavedTasks = { sessionId: here.id, at, tasks: list }
557  await $.store.set(`tasks:${here.root}`, saved)
558  await saveArchive($, here, list)
559}
560
561// This session's record, written into the project's log. The stored log is
562// read again just before, so that a parallel session's record is not lost.
563const saveSession = async ($: EngineInterface, here: Here, isOver: boolean): Promise<void> => {
564  if (!isKnown(here)) return
565  const now = await $.clock.now()
566  // A finished session never shows a live agent.
567  const runs = isOver
568    ? await update($, agents, list =>
569        list.map(run => (isLive(run) ? { ...run, status: 'done' as const, endedAt: now } : run)),
570      )
571    : await read($, agents)
572  const measured = await read($, usage)
573  const record = sessionRecord({
574    id: here.id,
575    startedAt: here.startedAt,
576    now,
577    title: here.title,
578    turns: here.turns,
579    tokens: here.tokensKept + Math.max(0, measured.sessionTokens - here.tokensFrom),
580    costUsd: measured.costUsd,
581    // The tasks of earlier sessions are counted in their own records.
582    tasks: (await read($, tasks)).filter(task => task.sessionId === undefined),
583    filesEdited: (await read($, files)).length,
584    agents: runs,
585  })
586  const key = `log:${here.root}`
587  const next = upsertSession(asProjectLog(await $.store.get(key), here.root), record)
588  await update($, log, () => next)
589  await $.store.set(key, next)
590}
591
592// A verifier's final message, read for its answer and set on the task it was about.
593const settleVerdict = async ($: EngineInterface, agentId: string, message: string): Promise<void> => {
594  const run = (await read($, agents)).find(one => one.agentId === agentId)
595  if (run === undefined || !isVerifier(run.type)) return
596  const list = await read($, tasks)
597  const state = verdictOf(message)
598  const taskId = taskToJudge(list, run)
599  const task = list.find(one => one.id === taskId)
600  if (state === undefined || taskId === undefined || task === undefined) return
601  // The same answer reaches the mod twice: as the end of the agent's turn and as its stop.
602  const held = task.verdict
603  if (held?.by === 'verifier' && held.state === state && held.at >= run.startedAt) return
604  const at = await $.clock.now()
605  await update($, tasks, value => judge(value, taskId, state, 'verifier', at))
606  await note($, 'task', `Verifier ${state === 'passed' ? 'passed' : 'failed'}: ${task.subject}`)
607}
608
609// The session as Markdown, for a pull request or a stand-up note.
610const reportText = async ($: EngineInterface, here: Here): Promise<string> => {
611  const now = await $.clock.now()
612  const measured = await read($, usage)
613
614  return reportOf({
615    now,
616    project: await read($, project),
617    ...(here.root === '' ? {} : { root: here.root }),
618    tasks: await read($, tasks),
619    agents: await read($, agents),
620    files: await read($, files),
621    usage: measured,
622    turns: here.turns,
623    checks: (await read($, checks)).map(check => ({
624      kind: CHECK_LABEL[check.kind],
625      state: stateOf(check),
626      command: check.command,
627      at: check.at,
628    })),
629    git: await read($, git),
630    limits: forecastsOf(measured.rateLimits, await read($, limits), now).map(forecast => ({
631      label: `${limitName(forecast.kind)} limit`,
632      percentUsed: forecast.percentUsed,
633      note: forecastText(forecast, now),
634    })),
635  })
636}
637
638const countDone = async ($: EngineInterface, gained: number): Promise<void> => {
639  if (gained <= 0) return
640  await update($, project, record =>
641    record === null ? record : { ...record, tasksDone: record.tasksDone + gained },
642  )
643  await saveProject($)
644}
645
646const clearFinished = async ($: EngineInterface): Promise<void> => {
647  await update($, tasks, list => list.filter(task => task.status !== 'completed'))
648  await update($, agents, list => list.filter(isLive))
649  await update($, procs, list => list.filter(proc => proc.status === 'running'))
650  await refresh($, false)
651}
652
653const stopTurn = async ($: EngineInterface): Promise<void> => {
654  const { id, isWorking } = await read($, turn)
655  if (isWorking && id !== null) await $.turn.abort({ turnId: id })
656}
657
658const openAt = async ($: EngineInterface, view: ViewName | undefined): Promise<UiOpenResult> => {
659  // A pane that was closed opens on the current city, as does one whose
660  // state the engine cannot tell.
661  const isOpen = await $.ui.panes().then(
662    open => open.some(one => one.id === PANE),
663    () => false,
664  )
665  await update($, ui, value => ({
666    ...value,
667    isBandHidden: false,
668    hasOpened: true,
669    view: view ?? value.view,
670    cityView: isOpen ? value.cityView : 'current',
671  }))
672
673  return openPane($)
674}
675
676const actionsOf = ($: EngineInterface): Actions => ({
677  setView: view => update($, ui, value => ({ ...value, view })),
678  toggleCity: () =>
679    // Typed as Ui so the type check does not widen cityView to string.
680    update($, ui, (value): Ui => ({ ...value, cityView: value.cityView === 'full' ? 'current' : 'full' })),
681  openCity: () => openAt($, 'city'),
682  hideBand: async () => {
683    await update($, ui, value => ({ ...value, isBandHidden: true }))
684    await refresh($, false)
685  },
686  // A surface with a composer of its own takes no fill: say what to type.
687  orchestrate: async () => {
688    const filled = await $.prompt.fill({ text: '/orchestrate ', mode: 'replace' })
689    if (!filled.isFilled) $.ui.toast('Type /orchestrate <goal> to plan it and run it with agents')
690  },
691  clearFinished: () => clearFinished($),
692  stopTurn: () => stopTurn($),
693})
694
695// The session a model is loaded for; `here`, where known, gives this
696// session's own live record beside the others'.
697type ModelSession = Pick<Model, 'sessionId' | 'root' | 'isStill'> & { here?: Here }
698
699const load = async (
700  $: EngineInterface,
701  { here: at, ...session }: ModelSession,
702  columns: number,
703  aspect?: number,
704): Promise<Model> => {
705  await read($, tick)
706  const record = await read($, project)
707  const board = await read($, tasks)
708  const now = await $.clock.now()
709  const live = await read($, others)
710
711  return {
712    now,
713    columns,
714    aspect,
715    ...session,
716    ...(at === undefined || at.id === '' || live.length === 0 ? {} : { thisSession: stampLive(await liveOf($, at, now)) }),
717    // A session whose start was not seen is placed by its project's record.
718    root: session.root === '' ? (record?.root ?? '') : session.root,
719    limits: await read($, limits),
720    waits: await read($, waits),
721    checks: await read($, checks),
722    git: await read($, git),
723    log: await read($, log),
724    tasks: board,
725    archived: offBoard((await read($, archive)) ?? EMPTY_ARCHIVE, board, session.sessionId),
726    agents: await read($, agents),
727    procs: await read($, procs),
728    turn: await read($, turn),
729    usage: await read($, usage),
730    history: await read($, history),
731    project: record,
732    skills: await read($, skills),
733    ui: await read($, ui),
734    activity: await read($, activity),
735    files: await read($, files),
736    others: live,
737    flow: await read($, flow),
738    tracker: await read($, tracker),
739    progress: await read($, progress),
740  }
741}
742
743// This session's live record, kept in the store the other running sessions
744// read, and its reading of theirs; set once the session has started.
745let keeper: LiveKeeper | undefined
746
747const keepLive = async ($: EngineInterface, here: Here): Promise<void> => {
748  if (keeper === undefined || !isKnown(here)) return
749  const now = await $.clock.now()
750  await keeper.write(await liveOf($, here, now), now)
751}
752
753// This session's record with when it last changed, as the others read it.
754const stampLive = (record: LiveSession): LiveSession => keeper?.stamp(record) ?? record
755
756// This session's live record as it stands: what the others read of it.
757const liveOf = async ($: EngineInterface, here: Here, now: number): Promise<LiveSession> => {
758  const measured = await read($, usage)
759  const strip = await loadStrip($)
760  const stall = stalledOf(strip)
761  const kind = workKind(strip)
762
763  return liveSessionOf({
764    sessionId: here.id,
765    root: here.root,
766    title: here.title,
767    isWorking: (await read($, turn)).isWorking,
768    waits: await read($, waits),
769    tasks: await read($, tasks),
770    agents: await read($, agents),
771    usage: measured,
772    tokens: here.tokensKept + Math.max(0, measured.sessionTokens - here.tokensFrom),
773    flow: await read($, flow),
774    ...(kind === undefined ? {} : { workKind: kind }),
775    stall: stall?.why ?? '',
776    now,
777  })
778}
779
780// The others' records less their times: a heartbeat alone is no reason to
781// draw again.
782const withoutTimes = (list: readonly LiveSession[]): string =>
783  JSON.stringify(list.map(one => ({ ...one, updatedAt: 0 })))
784
785const readLive = async ($: EngineInterface, here: Here): Promise<void> => {
786  if (keeper === undefined || here.root === '') return
787  const found = await keeper.others(here.root, here.id, await $.clock.now())
788  if (withoutTimes(found) === withoutTimes(await read($, others))) return
789  await update($, others, () => found)
790  await refresh($, false)
791}
792
793// The pages on disk: what was last written to each, and whether a failure
794// to write them has been said already.
795let written = new Map<string, string>()
796let hasSaidPage = false
797
798// Writes the two cities, current and full, where a browser left open finds
799// them, each only when its picture changed: an idle session writes nothing.
800// Asked for outright (a session starting, `/city page`), it writes whatever
801// stands there, so a file since deleted comes back.
802const writePage = async (
803  $: EngineInterface,
804  session: Pick<Model, 'sessionId' | 'root' | 'isStill'>,
805  root: string,
806  isAsked: boolean,
807): Promise<{ current: string; full: string }> => {
808  const model = await load($, session, 80)
809  const name =
810    model.project !== null && model.project.name !== '' ? model.project.name : projectName(root)
811  const paths = {
812    current: under(root, '.polis', PAGE_FILES.current),
813    full: under(root, '.polis', PAGE_FILES.full),
814  }
815  const texts = [
816    [paths.current, cityPage(model, name)],
817    [paths.full, cityPage({ ...model, archive: model.archived ?? EMPTY_ARCHIVE }, name)],
818  ] as const
819  // The folder keeps itself out of `git status`.
820  const ignore = under(root, '.polis', '.gitignore')
821  if ((isAsked || !written.has(paths.current)) && !(await $.fs.exists(ignore))) {
822    await $.fs.write(ignore, '*\n')
823  }
824  for (const [path, text] of texts) {
825    if (!isAsked && written.get(path) === text) continue
826    await $.fs.write(path, text)
827    written.set(path, text)
828  }
829
830  return paths
831}
832
833// The mod's own write, at the start and on its timer: a folder that cannot
834// be written is said once, not every two seconds.
835const keepPage = async (
836  $: EngineInterface,
837  session: Pick<Model, 'sessionId' | 'root' | 'isStill'>,
838  root: string,
839  isAsked: boolean,
840): Promise<void> => {
841  try {
842    await writePage($, session, root, isAsked)
843    hasSaidPage = false
844  } catch (error) {
845    if (!hasSaidPage) say($, 'writing the page on disk', error)
846    hasSaidPage = true
847  }
848}
849
850export const register: Register = (on, options) => {
851  const mode: EstimateMode =
852    options.estimate === 'history' || options.estimate === 'model' ? options.estimate : 'both'
853  const hasGuidance = options.guidance !== false
854  const shouldAutoOpen = options.autoOpen !== false
855  const isStill = options.motion === false
856  const hasPage = options.page !== false
857  const smartZone = smartZoneOf(options.smartZone)
858  // What the person has asked for lately, for the skill suggestions.
859  let asked: string[] = []
860  let here: Here = NOWHERE
861  nameHere = () => sessionName(here.title, here.root)
862  // What the main loop's wrap-up call asked the person this turn, if anything.
863  let wrapUpAsk: string | undefined
864  // The project the page on disk is written under, once a session has started.
865  let pageRoot: string | null = null
866  const session = (): ModelSession => ({
867    sessionId: here.id,
868    root: here.root,
869    isStill,
870    here,
871  })
872
873  on('session.start', async ($, e, next) => {
874    await $.command.register({
875      name: 'city',
876      description:
877        'Open the Polis project dashboard and city map, or answer with a session report or the whole project as text',
878      argumentHint: '[overview|city|tasks|agents|resources|skills|report [save]|project|page]',
879    })
880    await $.command.register({
881      name: 'orchestrate',
882      description: 'Plan a goal into tasks and run them with parallel agents',
883      argumentHint: '<goal>',
884    })
885
886    try {
887      if (hasGuidance) await $.tool.register(PROJECT_SPEC)
888      await $.agent.register({
889        name: 'worker',
890        description:
891          'Carries out one self-contained task of an orchestrated run and reports what it changed',
892        prompt: WORKER_PROMPT,
893      })
894      await $.agent.register({
895        name: 'verifier',
896        description:
897          'Checks a claim about finished work against the files and tests, read-only, and answers PASS or FAIL with evidence',
898        prompt: VERIFIER_PROMPT,
899        tools: ['Read', 'Grep', 'Glob', 'Bash'],
900      })
901    } catch (error) {
902      say($, 'registering its tool and agent types', error)
903    }
904
905    try {
906      const now = await $.clock.now()
907      const repo = await $.session.repo().catch(() => null)
908      const root = repo?.root ?? e.cwd
909      pageRoot = root
910      const sessionId = await $.session.id()
911      // A reload runs this again while the session goes on: what the session
912      // already holds for this project is newer than what the store kept.
913      const held = await read($, project)
914      const saved =
915        held !== null && held.root === root
916          ? held
917          : asProject(await $.store.get(`project:${root}`), root, now)
918      const record =
919        saved.lastSessionId === sessionId
920          ? { ...saved, lastActive: now }
921          : { ...saved, lastActive: now, lastSessionId: sessionId, sessions: saved.sessions + 1 }
922      await update($, project, () => record)
923      await saveProject($)
924      const kept = await $.store.get('rooms')
925      if (typeof kept === 'object' && kept !== null) {
926        rooms = { ...(kept as { [site: string]: string }), ...rooms }
927      }
928      const past = asHistory(await $.store.get(`history:${root}`))
929      await update($, history, list => (list.length > past.length ? list : past))
930
931      const commands = await $.command.list()
932      const available = commands
933        .filter(command => command.source !== 'builtin' && command.plugin !== 'polis')
934        .slice(0, 120)
935        .map(command => ({
936          name: command.name,
937          description: clip(command.description, 160),
938          source: command.plugin ?? command.source,
939        }))
940      await update($, skills, value => ({ ...value, available }))
941
942      const measured = await $.session.usage()
943      const counted = await update($, usage, value => ({
944        ...value,
945        contextTokens: measured.context.tokens ?? value.contextTokens,
946        contextWindow: measured.context.window,
947        contextPercent: measured.context.percent ?? value.contextPercent,
948        costUsd: measured.cost?.usd ?? value.costUsd,
949        zoneLimit: zoneLimit(measured.context.window, smartZone),
950      }))
951
952      // The whole project, not this session alone: the log of its sessions,
953      // and the tasks the earlier ones left on the board.
954      const tracks = asTracks(await $.store.get(LIMITS_KEY))
955      await update($, limits, list => mergeTracks(list, tracks))
956      const was = asProjectLog(await $.store.get(`log:${root}`), root).sessions.find(
957        one => one.id === sessionId,
958      )
959      here = {
960        id: sessionId,
961        root,
962        startedAt: was?.startedAt ?? now,
963        title: was?.title ?? '',
964        turns: was?.turns ?? 0,
965        tokensKept: was?.tokens ?? 0,
966        tokensFrom: counted.sessionTokens,
967      }
968      if ((await read($, tasks)).length === 0) {
969        const carried = carryTasks(await $.store.get(`tasks:${root}`), sessionId, now)
970        if (carried.length > 0) await update($, tasks, () => carried)
971      }
972      // The finished work already on the board starts the archive.
973      await saveArchive($, here, await read($, tasks))
974      await saveSession($, here, false)
975      void readGit($, root)
976      void readFrontier($, root)
977      await refresh($, false)
978    } catch (error) {
979      say($, 'loading the project', error)
980    }
981
982    // The other running sessions of the project, and this one for them.
983    try {
984      keeper = liveKeeper({
985        get: key => $.store.get(key),
986        set: (key, value) => $.store.set(key, value),
987        delete: key => $.store.delete(key),
988        keys: () => $.store.keys(),
989      })
990      await keepLive($, here)
991      await readLive($, here)
992    } catch (error) {
993      say($, 'reading the live sessions', error)
994    }
995
996    // A pane left open across a reload asks again for its room: an open sets
997    // the size anew, and the person's own size still wins.
998    try {
999      const open = await $.ui.panes()
1000      if (open.some(one => one.id === PANE)) void openPane($).catch(() => undefined)
1001    } catch (error) {
1002      say($, 'reopening the pane', error)
1003    }
1004
1005    // Elapsed times in the pane move only while something is running.
1006    $.clock.every(5000, () => {
1007      void (async () => {
1008        const { isWorking } = await read($, turn)
1009        const runs = await read($, agents)
1010        if (isWorking || runs.some(isLive)) await update($, tick, count => count + 1)
1011        // Off the flow, a long turn turns to AFK work on the clock alone.
1012        if (isWorking && (await read($, flow)) === null) await refresh($, false)
1013        // Silence and a call that never ends stall work on the clock alone.
1014        await watchStall($)
1015        if (hasNewRoom) {
1016          hasNewRoom = false
1017          await $.store.set('rooms', rooms)
1018        }
1019      })().catch(() => undefined)
1020    })
1021
1022    // This session's record follows it within two seconds and beats every
1023    // thirty; the others' are read every five.
1024    $.clock.every(CHANGE_MS, () => {
1025      void keepLive($, here).catch(() => undefined)
1026    })
1027    $.clock.every(5000, () => {
1028      void readLive($, here).catch(() => undefined)
1029    })
1030
1031    // The page is there from the start, then follows the board.
1032    if (hasPage && pageRoot !== null) {
1033      const root = pageRoot
1034      hasSaidPage = false
1035      await keepPage($, session(), root, true)
1036      $.clock.every(2000, () => {
1037        void keepPage($, session(), root, false)
1038      })
1039    }
1040
1041    return next(e)
1042  })
1043
1044  on('session.end', async ($, e, next) => {
1045    try {
1046      // The others stop counting this session at once.
1047      if (keeper !== undefined && isKnown(here)) await keeper.end(here.root, here.id)
1048    } catch (error) {
1049      say($, 'ending the live record', error)
1050    }
1051    try {
1052      await saveSession($, here, true)
1053      await saveTasks($, here)
1054    } catch (error) {
1055      say($, 'session.end', error)
1056    }
1057    if (e.reason === 'clear') {
1058      // The conversation is over and the project is not: what is left to do
1059      // stays on the board, as an earlier session's.
1060      const now = await $.clock.now()
1061      const saved: SavedTasks = { sessionId: here.id, at: now, tasks: await read($, tasks) }
1062      await update($, tasks, () => carryTasks(saved, '', now))
1063      await update($, agents, () => [])
1064      await update($, procs, () => [])
1065      await update($, turn, () => IDLE)
1066      await update($, activity, () => [])
1067      await update($, files, () => [])
1068      await update($, waits, () => [])
1069      await update($, flow, () => null)
1070      await update($, progress, () => NO_PROGRESS)
1071      // The process goes on under an id not yet known.
1072      here = { ...NOWHERE, root: here.root }
1073      await refresh($, false)
1074    }
1075
1076    return next(e)
1077  })
1078
1079  // A slash command naming a flow skill starts its phase. With guidance on, a
1080  // smart-zone crossing reaches Claude once, beside the person's next prompt:
1081  // never through the system prompt (ADR 0001).
1082  on('prompt.submit', async ($, e, next) => {
1083    if (e.command !== undefined) await startPhase($, e.command.name)
1084    if (!hasGuidance) return next(e)
1085    try {
1086      const measured = await read($, usage)
1087      if (measured.zoneOwed !== 'inside') {
1088        const text = zoneNote(measured.zoneOwed, measured.contextTokens, measured.zoneLimit)
1089        await update($, usage, value => ({ ...value, zoneOwed: 'inside' as const }))
1090
1091        return next({ ...e, context: [...(e.context ?? []), text] })
1092      }
1093    } catch (error) {
1094      say($, 'prompt.submit', error)
1095    }
1096
1097    return next(e)
1098  })
1099
1100  if (hasGuidance) {
1101    on('prompt.compose', async ($, e, next) => {
1102      const composed = await next(e)
1103      // Where nothing draws there is no dashboard to keep current.
1104      if (e.surfaces.length === 0) return composed
1105
1106      return { sections: [...composed.sections, GUIDANCE] }
1107    })
1108
1109    // The mod's own tool writes nothing but the mod's own record.
1110    on('tool.check', { tool: PROJECT_TOOL }, () => ({ decision: 'allow' }))
1111
1112    on('tool.call', { tool: PROJECT_TOOL }, async ($, e) => {
1113      const now = await $.clock.now()
1114      const before = (await read($, project)) ?? newProject(await $.session.cwd(), now)
1115      const after = mergeProject(before, {
1116        name: e.name,
1117        phase: e.phase,
1118        milestones: e.milestones,
1119      })
1120      await update($, project, () => after)
1121      await saveProject($)
1122      const done = after.milestones.filter(one => one.status === 'done').length
1123      if (e.milestones !== undefined) {
1124        await note($, 'project', `Plan updated: ${done}/${after.milestones.length} milestones done`)
1125      }
1126
1127      // The steps of the work at hand, where the host has no task tool to watch.
1128      let steps = ''
1129      if (e.tasks !== undefined) {
1130        const had = taskStats(await read($, tasks)).done
1131        const list = await update($, tasks, value => reopen(value, recordTasks(value, e.tasks)))
1132        const stats = taskStats(list)
1133        await countDone($, stats.done - had)
1134        // Whoever owns a task in progress stands at its building.
1135        await update($, agents, runs =>
1136          runs.map(run => {
1137            const mine = list.find(
1138              task => task.status === 'in_progress' && task.owner !== undefined && task.owner === run.name,
1139            )
1140
1141            return isLive(run) && mine !== undefined ? { ...run, taskId: mine.id } : run
1142          }),
1143        )
1144        await refresh($, shouldAutoOpen)
1145        steps = ` Tasks: ${stats.done} done, ${stats.active} active, ${stats.waiting} waiting.`
1146      }
1147
1148      return {
1149        result: `Recorded. ${after.name}: ${done} of ${after.milestones.length} milestones done${
1150          after.phase === '' ? '' : `; phase: ${after.phase}`
1151        }.${steps}`,
1152      }
1153    })
1154  }
1155
1156  on('command.run', { command: 'city' }, async ($, e) => {
1157    const wanted = e.args.trim().toLowerCase()
1158    const [word = '', option = ''] = wanted.split(/\s+/)
1159    // The report and the project are text wherever they are asked for.
1160    if (word === 'report') {
1161      const text = await reportText($, here)
1162      if (option !== 'save') return { text }
1163      const path = `${(await $.session.cwd()).replace(/[\\/]+$/, '')}/${REPORT_FILE}`
1164      try {
1165        await $.fs.write(path, text)
1166
1167        return { text: `Saved to ${path}\n\n${text}` }
1168      } catch (error) {
1169        return { text: `Could not save the report to ${path}: ${String(error)}\n\n${text}` }
1170      }
1171    }
1172    // Where a surface draws, the word opens the Project view like any other.
1173    if (word === 'project' && (await $.session.surfaces()).length === 0) {
1174      const now = await $.clock.now()
1175      try {
1176        here = await whereabouts($, here, now)
1177        await saveSession($, here, false)
1178      } catch (error) {
1179        say($, 'writing the session into the project log', error)
1180      }
1181      const kept = await read($, log)
1182      if (kept === null || kept.sessions.length === 0) {
1183        return { text: 'Polis has no record of this project yet: one is written as a session starts.' }
1184      }
1185      const name = (await read($, project))?.name ?? 'Project'
1186      const lines = projectLines(kept, { now, liveId: here.id, columns: 80 })
1187
1188      return { text: [`${name} · ${projectHeadline(kept)}`, '', ...lines].join('\n') }
1189    }
1190    const view = VIEWS.find(one => one.name === wanted)?.name
1191    // The page on disk is opened in a browser, not in the pane.
1192    if (wanted === 'page') {
1193      if (!hasPage) {
1194        return { text: 'The page on disk is turned off. Set the `page` option to true to have Polis write it.' }
1195      }
1196      try {
1197        const root = pageRoot ?? (await read($, project))?.root ?? (await $.session.cwd())
1198        const paths = await writePage($, session(), root, true)
1199
1200        return {
hooks/ask.ts 32 lines
1// Whether a main-loop turn ended by asking the person something: read off the
2// turn's last words and its wrap-up call, with no model call.
3
4// The desktop app's wrap-up tool: its `ask` is a question put to the person.
5export const WRAP_UP = /^mcp__ccd_turn__wrap_up$/u
6
7/** What a turn asked of the person: a round of `count` questions, or one, with the ask itself. */
8export type Ask = { count: number; detail?: string }
9
10// A numbered question marker of a grilling round: ❓ or **Q<n>**.
11const MARKER = /❓|\*\*Q\d+/gu
12
13// Markup that may close a paragraph after its last word.
14const TRAILING = /[\s*_`~)\]"'”’>]+$/u
15
16// The ask, first match wins: the wrap-up's ask, a round of two or more
17// numbered questions, then a last paragraph that ends with a question mark.
18export const askOf = (answer: string, wrapUpAsk?: string): Ask | undefined => {
19  const asked = wrapUpAsk?.trim() ?? ''
20  if (asked !== '') return { count: 1, detail: asked }
21  const markers = answer.match(MARKER)?.length ?? 0
22  if (markers >= 2) return { count: markers }
23  const paragraphs = answer.trim().split(/\n\s*\n/u)
24  const last = (paragraphs.at(-1) ?? '').replace(TRAILING, '')
25
26  return last.endsWith('?') ? { count: 1 } : undefined
27}
28
29// The ask's wording on the strip.
30export const askText = (count: number | undefined): string =>
31  count !== undefined && count >= 2 ? `${count} questions for you` : 'a question for you'
32
hooks/checks.ts 383 lines
1import type { Check, CheckKind } from '../types'
2import { about, clip, elapsed } from './logic'
3
4export type { Check, CheckKind } from '../types'
5
6export type CheckState = 'passed' | 'failed' | 'stale'
7
8// The order the kinds are shown in.
9export const CHECK_KINDS: readonly CheckKind[] = ['test', 'lint', 'types', 'build']
10
11export const CHECK_LABEL: { [K in CheckKind]: string } = {
12  test: 'tests',
13  lint: 'lint',
14  types: 'types',
15  build: 'build',
16}
17
18export const CHECK_MARK: { [S in CheckState]: string } = {
19  passed: '✔',
20  failed: '✘',
21  stale: '◌',
22}
23
24// ------------------------------------------------------------------ commands
25
26// Where a script name or sub-command may sit: after flags, some of which take
27// a value, and after `run` or a workspace for the script runners.
28const FLAGS =
29  '(?:(?:--filter|--workspace|--prefix|--cwd|-F|-w|-C)\\s+\\S+\\s+|-\\S+\\s+|workspace\\s+\\S+\\s+)*'
30
31// A script of a runner (`npm run test:unit`, `yarn lint`, `bun test`): the
32// name starts with one of the words, so `testing` or `lint-staged` do not
33// count as `test` and `lint` only by their separator.
34const script = (names: string): RegExp =>
35  new RegExp(`^${FLAGS}(?:run(?:-script)?\\s+${FLAGS})?(?:${names})(?:[:._-]\\S*)?(?:\\s|$)`)
36
37// The first word that is no flag (or `+toolchain`): `cargo +nightly test`.
38const sub = (names: string): RegExp =>
39  new RegExp(`^(?:(?:\\+|-)\\S*\\s+)*(?:${names})(?:\\s|$)`)
40
41// A goal or target anywhere in the arguments, for tools that take several.
42const goal = (names: string): RegExp => new RegExp(`(?:^|\\s)(?:${names})(?:\\s|$)`)
43
44const target = (names: string): RegExp =>
45  new RegExp(`(?:^|\\s)(?:${names})(?:[:._-]\\S*)?(?:\\s|$)`)
46
47const RUNNERS = /^(npm|pnpm|yarn|bun|turbo)$/
48const MAVEN = /^(mvn|mvnw)$/
49const GRADLE = /^(gradle|gradlew)$/
50const MAKE = /^(make|gmake|just)$/
51
52type Rule = readonly [kind: CheckKind, executable: RegExp, args?: RegExp]
53
54// The one table of what counts as a check. The executable is its name alone,
55// lower case, without directory or `.exe`; the arguments, when given, must
56// match the words after it joined by spaces. Add a tool by adding a row.
57const RULES: readonly Rule[] = [
58  ['test', RUNNERS, script('test')],
59  ['lint', RUNNERS, script('lint')],
60  ['types', RUNNERS, script('typecheck|type-check|check-types|check:types|tsc')],
61  ['build', RUNNERS, script('build')],
62
63  ['test', /^(vitest|jest|mocha|ava|pytest|py\.test|tox|nox|unittest|rspec|phpunit|ctest)$/],
64  ['test', /^playwright$/, sub('test')],
65  ['test', /^cypress$/, sub('run')],
66  ['test', /^claude$/, /^plugin\s+test(?:\s|$)/],
67  ['test', /^cargo$/, sub('test|t|nextest')],
68  ['test', /^go$/, sub('test')],
69  ['test', /^dotnet$/, sub('test')],
70  ['test', MAVEN, goal('test|verify')],
71  ['test', GRADLE, goal('(?:[\\w-]*:)*test')],
72  ['test', /^(deno|swift|flutter|mix|composer)$/, sub('test')],
73  ['test', /^rake$/, sub('test|spec')],
74  ['test', /^php$/, /^artisan\s+test(?:\s|$)/],
75  ['test', MAKE, target('tests?|check')],
76
77  ['lint', /^(eslint|oxlint|stylelint|tslint|flake8|pylint|pycodestyle|rubocop|golangci-lint)$/],
78  ['lint', /^claude$/, /^plugin\s+validate(?:\s|$)/],
79  ['lint', /^ruff$/, sub('check')],
80  ['lint', /^biome$/, sub('lint|check|ci')],
81  ['lint', /^deno$/, sub('lint')],
82  ['lint', /^cargo$/, sub('clippy')],
83  ['lint', /^go$/, sub('vet')],
84  ['lint', MAKE, target('lint')],
85
86  ['types', /^(tsc|vue-tsc|tsgo|mypy|pyright|basedpyright|pyre)$/],
87  ['types', /^cargo$/, sub('check|c')],
88  ['types', /^deno$/, sub('check')],
89
90  ['build', /^(vite|next|ng|nuxt|nuxi|astro|swift|dotnet|go)$/, sub('build')],
91  ['build', /^cargo$/, sub('build|b')],
92  ['build', /^(webpack|rollup|tsup|esbuild)$/],
93  ['build', /^cmake$/, goal('--build')],
94  ['build', MAVEN, goal('package|compile')],
95  ['build', GRADLE, goal('(?:[\\w-]*:)*(?:build|assemble)')],
96  ['build', MAKE, target('build')],
97]
98
99// A command line cut into the words of each simple command in it. Quotes keep
100// a phrase in one word and hide the operators inside it, so that
101// `echo "npm test && x"` stays one command; a backslash is a path separator
102// here, as the mod is used on Windows too.
103const segmentsOf = (command: string): string[][] => {
104  const segments: string[][] = []
105  let words: string[] = []
106  let word = ''
107  let isOpen = false
108  let quote = ''
109  const endWord = (): void => {
110    if (isOpen) words.push(word)
111    word = ''
112    isOpen = false
113  }
114  const endSegment = (): void => {
115    endWord()
116    if (words.length > 0) segments.push(words)
117    words = []
118  }
119  for (let at = 0; at < command.length; at++) {
120    const char = command[at] ?? ''
121    const next = command[at + 1]
122    if (quote !== '') {
123      if (char === quote) quote = ''
124      else if (char === '\\' && quote === '"' && next === '"') {
125        word += '"'
126        at++
127      } else word += char
128      continue
129    }
130    if (char === '"' || char === "'") {
131      quote = char
132      isOpen = true
133    } else if (char === '\\' && (next === '\n' || next === '\r')) {
134      // A continued line is still one command.
135      at += next === '\r' && command[at + 2] === '\n' ? 2 : 1
136    } else if (char === '\n' || char === '\r' || ';|()'.includes(char)) {
137      endSegment()
138    } else if (char === '&') {
139      // `2>&1` and `&>` are redirections; any other `&` ends a command.
140      if (command[at - 1] === '>' || command[at - 1] === '<' || next === '>') {
141        word += char
142        isOpen = true
143      } else endSegment()
144    } else if (/\s/.test(char)) {
145      endWord()
146    } else {
147      word += char
148      isOpen = true
149    }
150  }
151  endSegment()
152
153  return segments
154}
155
156const exeOf = (word: string): string =>
157  (word.split(/[\\/]/).pop() ?? '').toLowerCase().replace(/\.(exe|cmd|bat|ps1)$/, '')
158
159const ASSIGNMENT = /^[A-Za-z_]\w*=/
160const KEYWORDS = new Set(['if', 'then', 'else', 'elif', 'do', 'while', 'until', '!', '{', '}'])
161// Words that only run what follows them.
162const PREFIXES = new Set(['sudo', 'time', 'nohup', 'command', 'exec', 'env', 'nice', 'call', 'cross-env'])
163const FETCHERS = new Set(['npx', 'bunx', 'pnpx'])
164const MANAGERS = new Set(['npm', 'pnpm', 'yarn', 'bun'])
165const ENVIRONMENTS = new Set(['uv', 'poetry', 'pipenv', 'pdm', 'hatch', 'rye'])
166
167// The words after leading flags, `--` included; a flag that takes a value
168// takes the next word too.
169const withoutFlags = (words: readonly string[], valued: readonly string[] = []): string[] => {
170  let at = 0
171  while ((words[at] ?? '').startsWith('-')) {
172    const flag = words[at] ?? ''
173    at += flag === '--' ? 1 : valued.includes(flag) ? 2 : 1
174    if (flag === '--') break
175  }
176
177  return words.slice(at)
178}
179
180// What a wrapper runs: `npx vitest`, `pnpm exec tsc`, `uv run pytest`,
181// `python -m pytest`. Undefined when the executable wraps nothing.
182const unwrap = (exe: string, args: readonly string[]): string[] | undefined => {
183  if (PREFIXES.has(exe)) return withoutFlags(args)
184  if (FETCHERS.has(exe)) return withoutFlags(args, ['-p', '--package', '-c'])
185  if (MANAGERS.has(exe) && ['exec', 'dlx', 'x'].includes(args[0] ?? '')) {
186    return withoutFlags(args.slice(1), ['-p', '--package'])
187  }
188  if (ENVIRONMENTS.has(exe) && args[0] === 'run') {
189    return withoutFlags(args.slice(1), ['--with', '-p', '--python'])
190  }
191  if (exe === 'bundle' && args[0] === 'exec') return withoutFlags(args.slice(1))
192  if (/^(python[\d.]*|py|pypy[\d.]*)$/.test(exe)) {
193    const at = args.indexOf('-m')
194
195    return at === -1 ? undefined : args.slice(at + 1)
196  }
197
198  return undefined
199}
200
201// The command line a shell is told to run: `bash -c "npm test"`.
202const inner = (exe: string, args: readonly string[]): string | undefined => {
203  if (/^(bash|sh|zsh|dash|ksh|fish)$/.test(exe)) {
204    const at = args.findIndex(word => /^-\w*c\w*$/.test(word))
205
206    return at === -1 ? undefined : args[at + 1]
207  }
208  if (/^(pwsh|powershell)$/.test(exe)) {
209    const at = args.findIndex(word => /^-c(ommand)?$/i.test(word))
210
211    return at === -1 ? undefined : args.slice(at + 1).join(' ')
212  }
213  if (exe === 'cmd') {
214    const at = args.findIndex(word => /^\/[ck]$/i.test(word))
215
216    return at === -1 ? undefined : args.slice(at + 1).join(' ')
217  }
218
219  return undefined
220}
221
222const scan = (command: string, depth: number): Set<CheckKind> => {
223  const found = new Set<CheckKind>()
224  for (const words of segmentsOf(command)) {
225    let rest = words
226    // A wrapper may wrap another: `CI=1 npx -y vitest`.
227    for (let hops = 0; hops < 8; hops++) {
228      while (rest.length > 0 && (ASSIGNMENT.test(rest[0] ?? '') || KEYWORDS.has(rest[0] ?? ''))) {
229        rest = rest.slice(1)
230      }
231      const exe = exeOf(rest[0] ?? '')
232      const args = rest.slice(1)
233      const wrapped = unwrap(exe, args)
234      if (wrapped !== undefined) {
235        rest = wrapped
236        continue
237      }
238      const text = inner(exe, args)
239      if (text !== undefined && depth < 3) {
240        for (const kind of scan(text, depth + 1)) found.add(kind)
241      }
242      const joined = args.join(' ')
243      for (const [kind, executable, pattern] of RULES) {
244        if (executable.test(exe) && (pattern === undefined || pattern.test(joined))) found.add(kind)
245      }
246      break
247    }
248  }
249
250  return found
251}
252
253// The checks a shell command runs, in display order. A command that only
254// mentions them (`echo "npm test"`, `git commit -m "fix tests"`) runs none.
255export const checksOf = (command: string): CheckKind[] => {
256  const found = scan(command, 0)
257
258  return CHECK_KINDS.filter(kind => found.has(kind))
259}
260
261// ------------------------------------------------------------------ outcomes
262
263const bag = (value: unknown): { [key: string]: unknown } | undefined =>
264  typeof value === 'object' && value !== null ? (value as { [key: string]: unknown }) : undefined
265
266// An error that says nothing of an exit code and tells of a stop instead.
267const STOPPED = /\b(interrupted|aborted|timed out)\b/i
268
269// Whether a finished shell call reads as a success. A denied call and an
270// error (a failing command reports `Exit code N`) read as failure; a call
271// that went to the background, was interrupted or has a shape not known
272// says nothing either way.
273export const outcomeOf = (answer: unknown, input?: unknown): boolean | undefined => {
274  const reply = bag(answer)
275  if (reply === undefined) return undefined
276  if (typeof reply.deny === 'string') return false
277  const text =
278    typeof reply.text === 'string' ? reply.text : typeof reply.result === 'string' ? reply.result : ''
279  if (reply.isError === true) {
280    if (/\bExit code \d+/.test(text)) return false
281
282    return STOPPED.test(text) ? undefined : false
283  }
284  if (bag(input)?.run_in_background === true) return undefined
285  const out = bag(reply.result)
286  if (out !== undefined) {
287    if (
288      out.interrupted === true ||
289      out.backgroundedByUser === true ||
290      typeof out.backgroundTaskId === 'string' ||
291      typeof out.timedOutAfterMs === 'number'
292    ) {
293      return undefined
294    }
295    if (typeof out.stdout === 'string' || typeof out.interrupted === 'boolean') return true
296  }
297  if (text === '' || /running in (the )?background/i.test(text)) return undefined
298
299  return true
300}
301
302// -------------------------------------------------------------------- state
303
304export const recordChecks = (
305  checks: readonly Check[],
306  kinds: readonly CheckKind[],
307  run: { hasPassed: boolean; at: number; ms: number; command: string },
308): Check[] => {
309  const kept = checks.filter(check => !kinds.includes(check.kind))
310  const added = kinds.map((kind): Check => ({ kind, ...run, editsSince: 0 }))
311  const all = [...kept, ...added]
312
313  return CHECK_KINDS.flatMap(kind => {
314    const one = all.find(check => check.kind === kind)
315
316    return one === undefined ? [] : [one]
317  })
318}
319
320// One more file was edited, so every result is one edit older. With no checks
321// the very array comes back, so that a store can skip the write.
322export const noteEdit = (checks: readonly Check[]): Check[] =>
323  checks.length === 0
324    ? (checks as Check[])
325    : checks.map(check => ({ ...check, editsSince: check.editsSince + 1 }))
326
327// A failure stays a failure however much is edited after it: only running the
328// check again can tell.
329export const stateOf = (check: Check): CheckState => {
330  if (!check.hasPassed) return 'failed'
331
332  return check.editsSince > 0 ? 'stale' : 'passed'
333}
334
335// ---------------------------------------------------------------------- text
336
337const checkOf = (checks: readonly Check[], kind: CheckKind): Check | undefined =>
338  checks.find(check => check.kind === kind)
339
340// For a band or a status row: only the kinds that have run.
341export const checksLine = (checks: readonly Check[]): string =>
342  CHECK_KINDS.flatMap(kind => {
343    const check = checkOf(checks, kind)
344
345    return check === undefined ? [] : [`${CHECK_LABEL[kind]} ${CHECK_MARK[stateOf(check)]}`]
346  }).join(' · ')
347
348const ago = (ms: number): string => (ms < 60_000 ? 'just now' : `${about(ms)} ago`)
349
350// Tenths under ten seconds, where they still tell runs apart.
351const took = (ms: number): string => {
352  if (ms < 1000) return `${Math.max(0, Math.round(ms))}ms`
353
354  return ms < 10_000 ? `${(ms / 1000).toFixed(1)}s` : elapsed(ms)
355}
356
357const edits = (n: number): string => `${n} ${n === 1 ? 'edit' : 'edits'}`
358
359// One line for each check that has run, for the Checks section.
360export const checkLines = (checks: readonly Check[], now: number): string[] =>
361  CHECK_KINDS.flatMap(kind => {
362    const check = checkOf(checks, kind)
363    if (check === undefined) return []
364    const state = stateOf(check)
365    const when = ago(now - check.at)
366    const said =
367      state === 'stale'
368        ? [`stale: ${edits(check.editsSince)} since it passed ${when}`]
369        : [`${state} ${when}`, took(check.ms)]
370    const label = CHECK_LABEL[kind].padEnd(5)
371
372    return [
373      `${CHECK_MARK[state]} ${label}   ${[...said, clip(check.command, 48)].filter(part => part !== '').join(' · ')}`,
374    ]
375  })
376
377// Tests that passed and have seen no edit since.
378export const hasFreshTests = (checks: readonly Check[]): boolean => {
379  const tests = checkOf(checks, 'test')
380
381  return tests !== undefined && tests.hasPassed && tests.editsSince === 0
382}
383
hooks/codemap.ts 171 lines
1import type { AgentRun, FileHit, GitState, Task } from '../types'
2import { clip, isLive } from './logic'
3
4export type { GitState } from '../types'
5
6// A task that knows where its area came from: the contract's own task now.
7export type CodeTask = Task
8
9// ---------------------------------------------------------------- code areas
10
11// Directories that only hold the real units of a project: the name of the unit
12// inside is the better district (`packages/web/...` is `web`, not `packages`).
13const CONTAINERS: ReadonlySet<string> = new Set([
14  'src', 'lib', 'app', 'apps', 'packages', 'libs', 'services', 'modules', 'crates',
15  'cmd', 'internal', 'pkg', 'components',
16])
17
18const isDrive = (path: string): boolean => /^[a-z]:/i.test(path)
19
20const isAbsolute = (path: string): boolean => isDrive(path) || /^[\\/]/.test(path)
21
22// The names in a path with `.` and `..` resolved, whichever separator it uses;
23// a `..` that climbs out of where the path starts leaves nothing to compare.
24const names = (path: string): string[] | undefined => {
25  const out: string[] = []
26  for (const part of path.split(/[\\/]+/)) {
27    if (part === '' || part === '.') continue
28    if (part !== '..') out.push(part)
29    else if (out.pop() === undefined) return undefined
30  }
31
32  return out
33}
34
35// The code area of a file: the directory or package its edits land in.
36export const areaOfPath = (path: string, root: string): string | undefined => {
37  const base = names(root)
38  const own = names(path)
39  if (base === undefined || own === undefined) return undefined
40  // Windows paths differ in case without meaning anything else.
41  const fold = (name: string | undefined): string | undefined =>
42    isDrive(root) ? name?.toLowerCase() : name
43  const inside = base.every((name, at) => fold(name) === fold(own[at]))
44  if (isAbsolute(path) && !inside) return undefined
45  const rel = isAbsolute(path) ? own.slice(base.length) : own
46  const first = rel[0]
47  if (first === undefined) return undefined
48  if (rel.length === 1) return 'root'
49  const unit = CONTAINERS.has(first.toLowerCase()) && rel.length > 2 ? (rel[1] ?? first) : first
50  const area = unit.toLowerCase().replace(/^\.+/, '').slice(0, 16)
51
52  return area === '' ? 'root' : area
53}
54
55const countOf = (touched: { [area: string]: number } | undefined, area: string): number =>
56  touched !== undefined && Object.hasOwn(touched, area) ? (touched[area] ?? 0) : 0
57
58// One more edit of `area` for a task. The task moves to the area it edits most,
59// unless a tag gave it its area: that one the model chose and stays.
60export const noteTouch = (
61  tasks: readonly CodeTask[],
62  taskId: string,
63  area: string,
64): CodeTask[] =>
65  tasks.map((task): CodeTask => {
66    if (task.id !== taskId) return task
67    const touched = { ...task.touched, [area]: countOf(task.touched, area) + 1 }
68    if (task.areaFrom === 'tag') return { ...task, touched }
69    const entries = Object.entries(touched)
70    const top = Math.max(...entries.map(([, count]) => count))
71    const leaders = entries.filter(([, count]) => count === top).map(([name]) => name)
72    // On a tie the district does not flip back and forth with every edit.
73    const next = leaders.includes(task.area) ? task.area : (leaders[0] ?? task.area)
74
75    return { ...task, area: next, areaFrom: 'code', touched }
76  })
77
78// The task an edit belongs to. A subagent's edit goes to the task its run was
79// matched to, else the one it recorded itself. The main loop's goes to the
80// in-progress task that is nobody else's: the last one when several are.
81export const taskOfEdit = (
82  tasks: readonly Task[],
83  agents: readonly AgentRun[],
84  agentId: string | undefined,
85): string | undefined => {
86  const live = agents.filter(isLive)
87  const active = tasks.filter(task => task.status === 'in_progress')
88  if (agentId !== undefined) {
89    const run = live.find(one => one.agentId === agentId && one.taskId !== undefined)
90
91    return run?.taskId ?? active.filter(task => task.agentId === agentId).at(-1)?.id
92  }
93  const claimed = new Set(live.map(run => run.taskId))
94
95  return active.filter(task => task.agentId === undefined && !claimed.has(task.id)).at(-1)?.id
96}
97
98export type AreaEdits = { area: string; files: number; edits: number }
99
100// The session's edited files grouped by area, the busiest area first. Files
101// outside the project (a note in a home directory, a temp file) are no district.
102export const areasOfFiles = (files: readonly FileHit[], root: string): AreaEdits[] => {
103  const groups = new Map<string, AreaEdits>()
104  for (const file of files) {
105    const area = areaOfPath(file.path, root)
106    if (area === undefined) continue
107    const group = groups.get(area) ?? { area, files: 0, edits: 0 }
108    group.files += 1
109    group.edits += file.edits
110    groups.set(area, group)
111  }
112
113  return [...groups.values()].sort((a, b) => b.edits - a.edits)
114}
115
116// ----------------------------------------------------------------------- git
117
118// Plain-text forms: `--porcelain=v2` is the one format git promises to keep.
119export const GIT_STATUS: readonly string[] = ['git', 'status', '--porcelain=v2', '--branch']
120
121export const GIT_DIFF: readonly string[] = ['git', 'diff', '--shortstat', 'HEAD']
122
123const toCount = (text: string | undefined): number => (text === undefined ? 0 : Number(text))
124
125// What the two commands said. A status with no branch line is not a
126// repository (or git failed): there is nothing to show then.
127export const parseGit = (status: string, diff: string, at: number): GitState | null => {
128  let branch: string | undefined
129  let ahead = 0
130  let behind = 0
131  let files = 0
132  let untracked = 0
133  for (const line of status.split(/\r?\n/)) {
134    if (line.startsWith('# branch.head ')) {
135      branch = line.slice('# branch.head '.length).trim()
136    } else if (line.startsWith('# branch.ab ')) {
137      const counts = /\+(\d+) -(\d+)/.exec(line)
138      ahead = toCount(counts?.[1])
139      behind = toCount(counts?.[2])
140    } else if (/^[12u] /.test(line)) {
141      files += 1
142    } else if (line.startsWith('? ')) {
143      untracked += 1
144    }
145  }
146  if (branch === undefined || branch === '') return null
147  // Git leaves a count out of the summary when it is zero.
148  const added = toCount(/(\d+) insertions?\(\+\)/.exec(diff)?.[1])
149  const removed = toCount(/(\d+) deletions?\(-\)/.exec(diff)?.[1])
150
151  return { branch, ahead, behind, files, added, removed, untracked, at }
152}
153
154// One row for the band: `main ↑1 ↓2 · 5 files +120 −34 · 2 untracked`.
155export const gitLine = (git: GitState): string => {
156  const where = [clip(git.branch, 24)]
157  if (git.ahead > 0) where.push(`↑${git.ahead}`)
158  if (git.behind > 0) where.push(`↓${git.behind}`)
159  const delta = `+${git.added} −${git.removed}`
160  const changed =
161    git.files > 0
162      ? `${git.files} ${git.files === 1 ? 'file' : 'files'} ${delta}`
163      : git.added + git.removed > 0
164        ? delta
165        : ''
166  const loose = git.untracked > 0 ? `${git.untracked} untracked` : ''
167  const parts = [where.join(' '), changed, loose].filter(part => part !== '')
168
169  return (changed === '' && loose === '' ? [...parts, 'clean'] : parts).join(' · ')
170}
171
hooks/live.ts 190 lines
1// Live sessions: every running session of a project keeps one record under
2// its own key, and reads the others'. The store is shared by every running
3// session of the mod: a value one sets, another gets on its next read
4// (checked with two concurrent sessions).
5import type { AgentRun, Flow, FlowKind, LiveSession, Task, Usage, Wait } from '../types'
6import { clip, isLive, sessionState, taskStats, topNeed, waitText } from './logic'
7
8// The part of the engine's store the records need. The seam where a store of
9// files would go in its place.
10export type LiveStore = {
11  get: (key: string) => Promise<unknown>
12  set: (key: string, value: unknown) => Promise<void>
13  delete: (key: string) => Promise<void>
14  keys: () => Promise<string[]>
15}
16
17// A record older than this is a session that ended without saying so.
18export const SILENT_MS = 120_000
19// A changed record is written no more often than this; an unchanged one this
20// often, so that the others know it is still there.
21export const CHANGE_MS = 2000
22export const HEARTBEAT_MS = 30_000
23
24const prefixOf =(root: string): string => `live:${root}:`
25
26// A session's own key: no two sessions share one.
27export const liveKey = (root: string, sessionId: string): string => `${prefixOf(root)}${sessionId}`
28
29const asLive = (value: unknown): LiveSession | undefined => {
30  const record = value as Partial<LiveSession> | null
31  if (typeof record !== 'object' || record === null) return undefined
32  if (typeof record.sessionId !== 'string' || typeof record.updatedAt !== 'number') return undefined
33
34  // A record from before movedAt was kept moved when it was last written.
35  return { ...record, movedAt: typeof record.movedAt === 'number' ? record.movedAt : record.updatedAt } as LiveSession
36}
37
38// What a record says, less its times: what a heartbeat leaves as it was.
39const bodyOf = (record: LiveSession): string => JSON.stringify({ ...record, updatedAt: 0, movedAt: 0 })
40
41// What a session last wrote: under which key, what (less the times), when,
42// and when what it says last changed.
43type Written = { key: string; body: string; at: number; movedAt: number }
44
45// One session's side of the records: its own, written on change and as a
46// heartbeat, and the others', read.
47export type LiveKeeper = ReturnType<typeof liveKeeper>
48
49export const liveKeeper = (store: LiveStore) => {
50  let last: Written | undefined
51
52  // The record with the time what it says last changed: kept from the last
53  // write while it says the same, else the record's own time.
54  const stamp = (record: LiveSession): LiveSession => {
55    const isSame =
56      last !== undefined && last.key === liveKey(record.root, record.sessionId) && last.body === bodyOf(record)
57
58    return isSame ? { ...record, movedAt: last?.movedAt ?? record.movedAt } : record
59  }
60
61  return {
62    stamp,
63
64    // Writes the session's record when it changed and the last write is
65    // CHANGE_MS old, or when the heartbeat is due; says whether it wrote.
66    write: async (record: LiveSession, now: number): Promise<boolean> => {
67      const key = liveKey(record.root, record.sessionId)
68      const body = bodyOf(record)
69      if (last !== undefined && last.key === key) {
70        const since = now - last.at
71        if (since < (body === last.body ? HEARTBEAT_MS : CHANGE_MS)) return false
72      }
73      const { movedAt } = stamp({ ...record, movedAt: now })
74      await store.set(key, { ...record, updatedAt: now, movedAt })
75      last = { key, body, at: now, movedAt }
76
77      return true
78    },
79
80    // The other live sessions of the project. A record silent for longer than
81    // a session's heartbeat allows is one whose session died: it goes.
82    others: async (root: string, sessionId: string, now: number): Promise<LiveSession[]> => {
83      const own = liveKey(root, sessionId)
84      const found: LiveSession[] = []
85      for (const key of await store.keys()) {
86        if (!key.startsWith(prefixOf(root)) || key === own) continue
87        const record = asLive(await store.get(key))
88        if (record === undefined) continue
89        if (now - record.updatedAt > SILENT_MS) await store.delete(key)
90        else found.push(record)
91      }
92
93      return found
94    },
95
96    end: async (root: string, sessionId: string): Promise<void> => {
97      if (last?.key === liveKey(root, sessionId)) last = undefined
98      await store.delete(liveKey(root, sessionId))
99    },
100  }
101}
102
103// The other sessions waiting on the person, the one waiting longest first.
104const waitingOn = (others: readonly LiveSession[]): (LiveSession & { wait: { text: string; at: number } })[] =>
105  others
106    .filter((one): one is LiveSession & { wait: { text: string; at: number } } =>
107      one.state === 'needs you' && one.wait !== null,
108    )
109    .sort((one, two) => one.wait.at - two.wait.at)
110
111const elsewhere = (count: number): string =>
112  count === 1 ? ' · +1 in another session' : count > 1 ? ` · +${count} in other sessions` : ''
113
114// What a session needs the person for, and since when.
115export type Need = { text: string; at: number }
116
117// Needs you as the strip shows it: of this session's need and the other
118// sessions', the one waiting longest, then how many others wait too. This
119// session's need is told plainly; another's, by its session's name.
120// Nothing when no session needs the person.
121export const needsYouMark = (own: Need | undefined, others: readonly LiveSession[]): string | undefined => {
122  const waiting = waitingOn(others)
123  const [first, ...rest] = waiting
124  if (own !== undefined && (first === undefined || own.at <= first.wait.at)) {
125    return `▲ needs you: ${own.text}${elsewhere(waiting.length)}`
126  }
127  if (first === undefined) return undefined
128  const where = first.title === '' ? 'another session' : `"${clip(first.title, 40)}"`
129
130  return `▲ needs you in ${where}: ${first.wait.text}${elsewhere(rest.length + (own === undefined ? 0 : 1))}`
131}
132
133// What a session's own record is made from.
134export type LiveParts = {
135  sessionId: string
136  root: string
137  title: string
138  isWorking: boolean
139  waits: readonly Wait[]
140  tasks: readonly Task[]
141  agents: readonly AgentRun[]
142  usage: Pick<Usage, 'contextTokens' | 'zoneLimit' | 'costUsd'>
143  tokens: number
144  /** The flow as the last flow skill set it; null off the flow. */
145  flow: Flow | null
146  /** The kind of the work running now, as live signals give it off the flow. */
147  workKind?: FlowKind
148  /** Why the session's work is stalled, in words; empty or left out while it is not. */
149  stall?: string
150  now: number
151}
152
153// Whether a session is moving, in the words the others read: a turn that
154// ended asking nothing is idle.
155const liveState = (isWorking: boolean, waits: readonly Wait[]): LiveSession['state'] => {
156  const state = sessionState(isWorking, waits)
157
158  return state === 'your turn' ? 'idle' : state
159}
160
161// This session's record as the others read it. Phase, kind and next step
162// come from the flow; off it, phase and next step are empty and the kind is
163// what live signals give.
164export const liveSessionOf = (parts: LiveParts): LiveSession => {
165  const need = topNeed(parts.waits)
166  const stats = taskStats(parts.tasks)
167
168  return {
169    sessionId: parts.sessionId,
170    root: parts.root,
171    title: parts.title,
172    state: liveState(parts.isWorking, parts.waits),
173    wait: need === undefined ? null : { text: waitText(need), at: need.at },
174    phase: parts.flow?.phase ?? '',
175    kind: parts.flow?.kind ?? parts.workKind ?? '',
176    nextStep: parts.flow?.next ?? '',
177    task: parts.tasks.find(task => task.status === 'in_progress')?.subject ?? '',
178    agents: parts.agents.filter(isLive).length,
179    tasksDone: stats.done,
180    tasksTotal: stats.total,
181    contextTokens: parts.usage.contextTokens,
182    zoneLimit: parts.usage.zoneLimit,
183    tokens: parts.tokens,
184    costUsd: parts.usage.costUsd,
185    stall: parts.stall ?? '',
186    updatedAt: parts.now,
187    movedAt: parts.now,
188  }
189}
190
hooks/logic.ts 1249 lines
1import type {
2  Activity,
3  AgentRun,
4  Expected,
5  FamilyCounts,
6  FileHit,
7  LimitSample,
8  LimitTrack,
9  Milestone,
10  MilestoneStatus,
11  Proc,
12  ProcKind,
13  Project,
14  Range,
15  RateLimit,
16  Size,
17  SkillInfo,
18  Task,
19  TaskStatus,
20  ToolFamily,
21  TurnRecord,
22  Wait,
23  WaitKind,
24  ZoneLevel,
25} from '../types'
26import { askText } from './ask'
27
28// ---------------------------------------------------------------- formatting
29
30export const elapsed = (ms: number): string => {
31  const seconds = Math.max(0, Math.round(ms / 1000))
32  if (seconds < 60) return `${seconds}s`
33  const minutes = Math.floor(seconds / 60)
34  if (minutes < 60) return `${minutes}m${String(seconds % 60).padStart(2, '0')}s`
35
36  return `${Math.floor(minutes / 60)}h${String(minutes % 60).padStart(2, '0')}m`
37}
38
39// A stretch of time to the minute, for a forecast: seconds would claim more
40// than a forecast knows.
41export const about = (ms: number): string => {
42  const minutes = Math.max(0, Math.round(ms / 60_000))
43  if (minutes < 1) return 'under 1m'
44  if (minutes < 60) return `${minutes}m`
45  const hours = Math.floor(minutes / 60)
46  if (hours < 24) return `${hours}h${String(minutes % 60).padStart(2, '0')}m`
47
48  return `${Math.floor(hours / 24)}d${hours % 24}h`
49}
50
51export const compact = (n: number): string => {
52  if (n < 1000) return String(Math.round(n))
53  if (n < 10_000) return `${(n / 1000).toFixed(1)}k`
54  if (n < 1_000_000) return `${Math.round(n / 1000)}k`
55
56  return `${(n / 1_000_000).toFixed(1)}M`
57}
58
59export const clip = (text: string, max: number): string => {
60  const flat = text.replace(/\s+/g, ' ').trim()
61
62  return flat.length <= max ? flat : `${flat.slice(0, Math.max(1, max - 1))}…`
63}
64
65export const bar = (done: number, total: number, width: number): [string, string] => {
66  const share = total <= 0 ? 0 : Math.min(1, Math.max(0, done / total))
67  const filled = Math.round(share * width)
68
69  return ['█'.repeat(filled), '░'.repeat(Math.max(0, width - filled))]
70}
71
72const words = (text: string): string[] =>
73  text
74    .toLowerCase()
75    .split(/[^a-z0-9]+/)
76    .filter(word => word.length >= 3 && !STOP.has(word))
77
78const STOP = new Set([
79  'the', 'and', 'for', 'with', 'that', 'this', 'from', 'into', 'when', 'use',
80  'used', 'using', 'any', 'all', 'are', 'not', 'can', 'will', 'should', 'have',
81  'has', 'its', 'their', 'your', 'you', 'user', 'users', 'wants', 'want', 'new',
82  'file', 'files', 'code', 'make', 'create', 'add', 'run', 'task', 'tasks',
83  'claude', 'also', 'such', 'other', 'them', 'then', 'than', 'each', 'one',
84])
85
86// --------------------------------------------------------------------- tasks
87
88const AREAS: readonly [RegExp, string][] = [
89  [/\b(test\w*|specs?|verif\w*|qa|coverage)\b/, 'tests'],
90  [/\b(docs?|readme|document\w*|write-?ups?|changelog)\b/, 'docs'],
91  [/\b(ui|ux|views?|pages?|css|styl\w*|design\w*|layouts?|component\w*|frontend)\b/, 'ui'],
92  [/\b(apis?|endpoints?|servers?|backend|databases?|db|schemas?|migrat\w*|quer\w*)\b/, 'backend'],
93  [/\b(research\w*|explor\w*|investigat\w*|audit\w*|review\w*|analy\w*|survey\w*|find\w*)\b/, 'research'],
94  [/\b(deploy\w*|releas\w*|ci|build\w*|config\w*|setup|install\w*|infra\w*|pipelines?)\b/, 'ops'],
95]
96
97export const inferArea = (subject: string): string => {
98  const text = subject.toLowerCase()
99  for (const [pattern, area] of AREAS) {
100    if (pattern.test(text)) return area
101  }
102
103  return 'general'
104}
105
106const field = (bag: unknown, key: string): string | undefined => {
107  if (typeof bag !== 'object' || bag === null) return undefined
108  const value = (bag as { [key: string]: unknown })[key]
109  if (typeof value !== 'string') return undefined
110  const trimmed = value.trim()
111
112  return trimmed === '' ? undefined : trimmed
113}
114
115export const areaOf = (metadata: unknown, subject: string): string => {
116  const given = field(metadata, 'area')
117
118  return given === undefined ? inferArea(subject) : given.toLowerCase().slice(0, 24)
119}
120
121export type TodoItem = { content: string; status: TaskStatus; activeForm?: string }
122
123// A todo list belongs to one loop: writing it replaces that loop's todos only.
124export const mergeTodos = (
125  list: readonly Task[],
126  todos: readonly TodoItem[],
127  agentId: string | undefined,
128  parentId: string | undefined,
129): Task[] => {
130  const loop = agentId ?? 'main'
131  // An earlier session's todos are that session's: this loop's list leaves them be.
132  const isOwn = (task: Task): boolean =>
133    task.source === 'todo' && task.sessionId === undefined && (task.agentId ?? 'main') === loop
134  const kept = list.filter(task => !isOwn(task))
135  const fresh = todos.map((todo, index): Task => {
136    // A todo written again is the same work: what was learnt of it stays.
137    const was = list.find(task => isOwn(task) && task.subject === todo.content)
138
139    return {
140      id: `todo:${loop}:${index}`,
141      subject: todo.content,
142      status: todo.status,
143      area: was?.area ?? inferArea(todo.content),
144      areaFrom: was?.areaFrom ?? 'title',
145      blockedBy: [],
146      source: 'todo',
147      ...(was?.touched === undefined ? {} : { touched: was.touched }),
148      // Reopened work is no longer what was checked.
149      ...(was?.verdict === undefined || (was.status === 'completed' && todo.status !== 'completed')
150        ? {}
151        : { verdict: was.verdict }),
152      ...(was?.doneAt === undefined ? {} : { doneAt: was.doneAt }),
153      ...(todo.activeForm === undefined ? {} : { activeForm: todo.activeForm }),
154      ...(agentId === undefined ? {} : { agentId }),
155      ...(parentId === undefined ? {} : { parentId }),
156    }
157  })
158
159  return [...kept, ...fresh].slice(-240)
160}
161
162export type TaskDraft = {
163  id: string
164  subject: string
165  activeForm?: string
166  metadata?: unknown
167  agentId?: string
168  parentId?: string
169}
170
171export const createTask = (list: readonly Task[], draft: TaskDraft): Task[] => {
172  const parentId = field(draft.metadata, 'parent') ?? draft.parentId
173  const parent = list.find(task => task.id === parentId)
174  const isTagged = field(draft.metadata, 'area') !== undefined
175  const task: Task = {
176    id: draft.id,
177    subject: draft.subject,
178    status: 'pending',
179    // A sub-task with no area of its own lives in its parent's district.
180    area: !isTagged && parent !== undefined ? parent.area : areaOf(draft.metadata, draft.subject),
181    areaFrom: isTagged ? 'tag' : (parent?.areaFrom ?? 'title'),
182    blockedBy: [],
183    source: 'task',
184    ...(draft.activeForm === undefined ? {} : { activeForm: draft.activeForm }),
185    ...(draft.agentId === undefined ? {} : { agentId: draft.agentId }),
186    ...(parentId === undefined ? {} : { parentId }),
187  }
188
189  return [...list.filter(one => one.id !== task.id), task].slice(-240)
190}
191
192export type TaskPatch = {
193  taskId: string
194  subject?: string
195  activeForm?: string
196  status?: TaskStatus | 'deleted'
197  owner?: string
198  addBlockedBy?: readonly string[]
199  addBlocks?: readonly string[]
200  metadata?: unknown
201}
202
203const union = (a: readonly string[], b: readonly string[]): string[] => [...new Set([...a, ...b])]
204
205export const patchTask = (list: readonly Task[], patch: TaskPatch): Task[] => {
206  if (patch.status === 'deleted') {
207    return list
208      .filter(task => task.id !== patch.taskId)
209      .map(task => ({ ...task, blockedBy: task.blockedBy.filter(id => id !== patch.taskId) }))
210  }
211  const { status } = patch
212  const area = field(patch.metadata, 'area')
213  const parentId = field(patch.metadata, 'parent')
214  const blocks = patch.addBlocks ?? []
215
216  return list.map(task => {
217    if (task.id !== patch.taskId) {
218      return blocks.includes(task.id)
219        ? { ...task, blockedBy: union(task.blockedBy, [patch.taskId]) }
220        : task
221    }
222
223    return {
224      ...task,
225      ...(patch.subject === undefined ? {} : { subject: patch.subject }),
226      ...(patch.activeForm === undefined ? {} : { activeForm: patch.activeForm }),
227      ...(status === undefined ? {} : { status }),
228      ...(patch.owner === undefined ? {} : { owner: patch.owner }),
229      ...(area === undefined ? {} : { area: area.toLowerCase().slice(0, 24), areaFrom: 'tag' as const }),
230      ...(parentId === undefined ? {} : { parentId }),
231      blockedBy: union(task.blockedBy, patch.addBlockedBy ?? []),
232    }
233  })
234}
235
236const TASK_STATUSES: readonly TaskStatus[] = ['pending', 'in_progress', 'completed']
237
238// Tasks as the model reports them through the mod's own tool, for a session
239// whose host gives it no task tool to watch: matched by id, made when new.
240export const recordTasks = (list: readonly Task[], notes: unknown): Task[] => {
241  let next = [...list]
242  for (const raw of Array.isArray(notes) ? notes.slice(0, 60) : []) {
243    const id = field(raw, 'id')
244    if (id === undefined) continue
245    const subject = field(raw, 'subject')
246    const stated = field(raw, 'status')
247    const status = stated === 'deleted' ? 'deleted' : TASK_STATUSES.find(one => one === stated)
248    const owner = field(raw, 'owner')
249    const activeForm = field(raw, 'activeForm')
250    const waits = (raw as { blockedBy?: unknown }).blockedBy
251    const metadata = { area: field(raw, 'area'), parent: field(raw, 'parent') }
252    if (!next.some(task => task.id === id)) {
253      if (subject === undefined || status === 'deleted') continue
254      next = createTask(next, { id, subject, metadata })
255    }
256    next = patchTask(next, {
257      taskId: id,
258      metadata,
259      addBlockedBy: Array.isArray(waits) ? waits.filter(one => typeof one === 'string') : [],
260      ...(subject === undefined ? {} : { subject }),
261      ...(status === undefined ? {} : { status }),
262      ...(owner === undefined ? {} : { owner }),
263      ...(activeForm === undefined ? {} : { activeForm }),
264    })
265  }
266
267  return next
268}
269
270// The blockers of a task that are still unfinished.
271export const openBlockers = (task: Task, list: readonly Task[]): string[] =>
272  task.blockedBy.filter(id => list.some(one => one.id === id && one.status !== 'completed'))
273
274export const isBlocked = (task: Task, list: readonly Task[]): boolean =>
275  task.status !== 'completed' && openBlockers(task, list).length > 0
276
277export type TaskStats = { done: number; active: number; waiting: number; total: number }
278
279export const taskStats = (list: readonly Task[]): TaskStats => {
280  const done = list.filter(task => task.status === 'completed').length
281  const active = list.filter(task => task.status === 'in_progress').length
282
283  return { done, active, waiting: list.length - done - active, total: list.length }
284}
285
286export type TaskRow = { task: Task; depth: number }
287
288// Top-level tasks in order, each followed by its sub-tasks.
289export const taskTree = (list: readonly Task[]): TaskRow[] => {
290  const ids = new Set(list.map(task => task.id))
291  const rows: TaskRow[] = []
292  const walk = (parent: string | undefined, depth: number): void => {
293    for (const task of list) {
294      const isRoot = task.parentId === undefined || !ids.has(task.parentId) || task.parentId === task.id
295      const isChild = parent === undefined ? isRoot : !isRoot && task.parentId === parent
296      if (!isChild || depth > 4) continue
297      rows.push({ task, depth })
298      walk(task.id, depth + 1)
299    }
300  }
301  walk(undefined, 0)
302
303  return rows
304}
305
306export type District = { area: string; tasks: Task[] }
307
308// Areas in the order their first task appeared.
309export const districtsOf = (list: readonly Task[]): District[] => {
310  const districts: District[] = []
311  for (const task of list) {
312    const found = districts.find(one => one.area === task.area)
313    if (found === undefined) districts.push({ area: task.area, tasks: [task] })
314    else found.tasks.push(task)
315  }
316
317  return districts
318}
319
320// -------------------------------------------------------------------- agents
321
322export const isLive = (run: AgentRun): boolean =>
323  run.status === 'starting' || run.status === 'running'
324
325// The task an agent's brief is most likely about: word overlap with the open
326// tasks, else the one task in progress when there is exactly one.
327export const matchTask = (label: string, list: readonly Task[]): string | undefined => {
328  const open = list.filter(task => task.status !== 'completed')
329  const wanted = new Set(words(label))
330  let best: { id: string; score: number } | undefined
331  for (const task of open) {
332    const have = words(task.subject)
333    if (have.length === 0 || wanted.size === 0) continue
334    const overlap = have.filter(word => wanted.has(word)).length
335    const score = overlap / Math.min(have.length, wanted.size) + (task.status === 'in_progress' ? 0.1 : 0)
336    if (overlap >= 1 && score >= 0.4 && (best === undefined || score > best.score)) {
337      best = { id: task.id, score }
338    }
339  }
340  if (best !== undefined) return best.id
341  const active = open.filter(task => task.status === 'in_progress')
342
343  return active.length === 1 ? active[0]?.id : undefined
344}
345
346export type AgentRow = { run: AgentRun; depth: number }
347
348// Agents in spawn order, each followed by the agents its own loop spawned.
349export const agentTree = (runs: readonly AgentRun[]): AgentRow[] => {
350  const ids = new Set(runs.map(run => run.agentId))
351  const rows: AgentRow[] = []
352  const walk = (parent: string | undefined, depth: number): void => {
353    for (const run of runs) {
354      const isRoot = run.parentAgentId === undefined || !ids.has(run.parentAgentId)
355      const isChild = parent === undefined ? isRoot : !isRoot && run.parentAgentId === parent
356      if (!isChild || depth > 6) continue
357      rows.push({ run, depth })
358      if (run.agentId !== undefined) walk(run.agentId, depth + 1)
359    }
360  }
361  walk(undefined, 0)
362
363  return rows
364}
365
366export const bumpFamily = (families: FamilyCounts, family: ToolFamily): FamilyCounts => ({
367  ...families,
368  [family]: (families[family] ?? 0) + 1,
369})
370
371// The families an agent has used most: its equipment. Planning and unknown
372// tools say little about what an agent does, so they come last.
373export const topFamilies = (families: FamilyCounts, limit: number): ToolFamily[] => {
374  const dull = (family: string): number => (family === 'plan' || family === 'other' ? 1 : 0)
375
376  return (Object.entries(families) as [ToolFamily, number][])
377    .filter(([, count]) => count > 0)
378    .sort((a, b) => dull(a[0]) - dull(b[0]) || b[1] - a[1])
379    .slice(0, limit)
380    .map(([family]) => family)
381}
382
383// ----------------------------------------------------------------- processes
384
385export const upsertProc = (list: readonly Proc[], proc: Proc): Proc[] =>
386  [...list.filter(one => one.id !== proc.id), proc].slice(-40)
387
388export const endProc = (
389  list: readonly Proc[],
390  id: string,
391  status: 'done' | 'stopped',
392  at: number,
393): Proc[] =>
394  list.map(proc =>
395    proc.id === id && proc.status === 'running' ? { ...proc, status, endedAt: at } : proc,
396  )
397
398export type Background = { id: string; type: string; description: string; command?: string }
399
400export type Cron = { id: string; schedule: string; prompt: string }
401
402const KIND_OF: { [type: string]: ProcKind } = {
403  shell: 'shell',
404  local_bash: 'shell',
405  monitor: 'monitor',
406  workflow: 'workflow',
407  local_workflow: 'workflow',
408  subagent: 'agent',
409  local_agent: 'agent',
410  remote_agent: 'agent',
411}
412
413// What the engine says is in flight is the truth: anything else we still hold
414// as running has ended.
415export const reconcileProcs = (
416  list: readonly Proc[],
417  background: readonly Background[],
418  crons: readonly Cron[],
419  at: number,
420): Proc[] => {
421  const live = new Map<string, Proc>()
422  for (const task of background) {
423    const kind = KIND_OF[task.type] ?? 'other'
424    if (kind === 'agent') continue
425    live.set(task.id, {
426      id: task.id,
427      kind,
428      label: clip(task.description === '' ? (task.command ?? task.type) : task.description, 80),
429      status: 'running',
430      startedAt: at,
431    })
432  }
433  for (const cron of crons) {
434    live.set(cron.id, {
435      id: cron.id,
436      kind: 'cron',
437      label: clip(`${cron.schedule} · ${cron.prompt}`, 80),
438      status: 'running',
439      startedAt: at,
440    })
441  }
442  const kept = list.map((proc): Proc => {
443    const now = live.get(proc.id)
444    live.delete(proc.id)
445    if (now !== undefined) return { ...proc, status: 'running' }
446
447    return proc.status === 'running' ? { ...proc, status: 'done', endedAt: at } : proc
448  })
449
450  return [...kept, ...live.values()].slice(-40)
451}
452
453// ------------------------------------------------------------------ estimate
454
455export const SIZES: readonly Size[] = ['S', 'M', 'L', 'XL']
456
457export const SIZE_LABEL: Record<Size, string> = {
458  S: 'small',
459  M: 'medium',
460  L: 'large',
461  XL: 'very large',
462}
463
464// Where a size class starts before this project has history of its own.
465export const DEFAULTS: Record<Size, { tokens: number; ms: number; tools: number }> = {
466  S: { tokens: 15_000, ms: 30_000, tools: 3 },
467  M: { tokens: 60_000, ms: 150_000, tools: 12 },
468  L: { tokens: 220_000, ms: 600_000, tools: 40 },
469  XL: { tokens: 700_000, ms: 1_800_000, tools: 120 },
470}
471
472const MIN_SAMPLES = 5
473
474const BIG = /\b(refactor\w*|implement\w*|build\w*|migrat\w*|rewrit\w*|redesign\w*|orchestrat\w*|end-to-end|across|entire|whole|every|all of)\b/i
475const ASK = /^(what|why|how|where|when|which|who|is|are|does|do|can|could|explain|show|tell)\b/i
476
477export const heuristicSize = (text: string): Size => {
478  const trimmed = text.trim()
479  const lines = trimmed.split('\n').filter(line => line.trim() !== '')
480  const items = lines.filter(line => /^\s*([-*•]|\d+[.)])\s+/.test(line)).length
481  let level = trimmed.length < 200 ? 0 : trimmed.length < 900 ? 1 : trimmed.length < 3500 ? 2 : 3
482  if (items >= 3) level = Math.max(level, 2)
483  if (items >= 8) level = 3
484  if (BIG.test(trimmed)) level += 1
485  if (level <= 1 && ASK.test(trimmed) && trimmed.length < 300 && !BIG.test(trimmed)) level = 0
486
487  return SIZES[Math.min(3, level)] ?? 'M'
488}
489
490export const quantile = (values: readonly number[], q: number): number => {
491  if (values.length === 0) return 0
492  const sorted = [...values].sort((a, b) => a - b)
493  const at = (sorted.length - 1) * q
494  const low = Math.floor(at)
495  const high = Math.ceil(at)
496  const a = sorted[low] ?? 0
497  const b = sorted[high] ?? a
498
499  return Math.round(a + (b - a) * (at - low))
500}
501
502const spread = (values: readonly number[]): Range => ({
503  low: quantile(values, 0.25),
504  high: Math.max(1, quantile(values, 0.8)),
505})
506
507export const expectedFor = (
508  size: Size,
509  source: 'heuristic' | 'model',
510  history: readonly TurnRecord[],
511): Expected => {
512  const same = history.filter(record => record.size === size)
513  if (same.length < MIN_SAMPLES) {
514    const base = DEFAULTS[size]
515
516    return {
517      size,
518      source,
519      tokens: { low: Math.round(base.tokens * 0.4), high: Math.round(base.tokens * 1.5) },
520      ms: { low: Math.round(base.ms * 0.4), high: Math.round(base.ms * 1.5) },
521      tools: { low: Math.round(base.tools * 0.4), high: Math.round(base.tools * 1.5) },
522      samples: same.length,
523    }
524  }
525
526  return {
527    size,
528    source,
529    tokens: spread(same.map(record => record.tokens)),
530    ms: spread(same.map(record => record.ms)),
531    tools: spread(same.map(record => record.tools)),
532    samples: same.length,
533  }
534}
535
536export type EstimateMode = 'both' | 'history' | 'model'
537
538// A small-model call costs a little on every prompt it sizes: under `both` it
539// is kept for prompts long or structured enough to be worth a second opinion.
540export const shouldAskModel = (mode: EstimateMode, text: string, size: Size): boolean => {
541  const trimmed = text.trim()
542  if (trimmed === '' || mode === 'history') return false
543  if (mode === 'model') return true
544
545  return trimmed.length >= 400 || trimmed.split('\n').length >= 4 || size === 'L' || size === 'XL'
546}
547
548export const SIZING_RUBRIC = [
549  'Classify how much agent work this coding request needs. Answer with the label alone.',
550  'S: a question, a lookup, or one small edit.',
551  'M: a focused change touching a few files, or a short investigation.',
552  'L: a multi-step feature, refactor or investigation across many files.',
553  'XL: a large multi-part project that needs planning and delegation.',
554  '',
555  'Request:',
556].join('\n')
557
558export type GaugeState = 'under' | 'within' | 'over'
559
560export const gaugeOf = (actual: number, range: Range): { share: number; state: GaugeState } => ({
561  share: range.high <= 0 ? 0 : actual / range.high,
562  state: actual > range.high ? 'over' : actual >= range.low ? 'within' : 'under',
563})
564
565export type SizeStat = { size: Size; count: number; tokens: number; ms: number }
566
567export const sizeStats = (history: readonly TurnRecord[]): SizeStat[] =>
568  SIZES.map(size => {
569    const same = history.filter(record => record.size === size)
570
571    return {
572      size,
573      count: same.length,
574      tokens: quantile(same.map(record => record.tokens), 0.5),
575      ms: quantile(same.map(record => record.ms), 0.5),
576    }
577  })
578
579// -------------------------------------------------------------------- limits
580
581const MINUTE = 60_000
582const HOUR = 60 * MINUTE
583
584// How far back a window's pace is read, and the shortest stretch of readings
585// a pace is told from. A five-hour window is judged by its last half hour; a
586// longer one by its last day, so that a night's rest counts toward its pace.
587const PACE: { [kind: string]: { lookback: number; least: number } } = {
588  five_hour: { lookback: 30 * MINUTE, least: 10 * MINUTE },
589  seven_day: { lookback: 24 * HOUR, least: 2 * HOUR },
590  spend_limit: { lookback: 24 * HOUR, least: 2 * HOUR },
591}
592
593const USUAL_PACE = { lookback: HOUR, least: 10 * MINUTE }
594
595const paceOf = (kind: string): { lookback: number; least: number } => PACE[kind] ?? USUAL_PACE
596
597const stamp = (iso: string | undefined): number | null => {
598  const at = iso === undefined ? NaN : Date.parse(iso)
599
600  return Number.isFinite(at) ? at : null
601}
602
603// Whether a reading belongs to another window than the one held: its reset
604// time moved, the held window's reset has passed, or, where no reset time
605// says, the figure fell.
606const isNewWindow = (track: LimitTrack, limit: RateLimit, at: number): boolean => {
607  const was = stamp(track.resetsAt)
608  const is = stamp(limit.resetsAt)
609  if (was !== null && is !== null) return Math.abs(is - was) > MINUTE
610  const last = track.samples[track.samples.length - 1]
611
612  return (was !== null && at >= was) || (last !== undefined && limit.percentUsed < last.percent)
613}
614
615// The readings a pace can still be told from: those inside the lookback, and
616// the newest one before it, which says where the window stood as it began.
617const trimSamples = (samples: readonly LimitSample[], since: number): LimitSample[] => {
618  const older = samples.filter(sample => sample.at <= since)
619
620  return [...older.slice(-1), ...samples.filter(sample => sample.at > since)].slice(-120)
621}
622
623// One more reading of a limit window. A level is kept from the first time it
624// was read; a reading of a new window starts over, its warning not yet given.
625export const recordLimit = (
626  track: LimitTrack | undefined,
627  limit: RateLimit,
628  at: number,
629): LimitTrack => {
630  const reading = { at, percent: limit.percentUsed }
631  const reset = limit.resetsAt === undefined ? {} : { resetsAt: limit.resetsAt }
632  if (track === undefined || isNewWindow(track, limit, at)) {
633    return { kind: limit.kind, samples: [reading], hasWarned: false, ...reset }
634  }
635  const last = track.samples[track.samples.length - 1]
636  const samples =
637    last !== undefined && last.percent === reading.percent ? track.samples : [...track.samples, reading]
638
639  return { ...track, ...reset, samples: trimSamples(samples, at - paceOf(limit.kind).lookback) }
640}
641
642// What the store handed back, held to the shape of the tracks.
643export const asTracks = (saved: unknown): LimitTrack[] => {
644  if (!Array.isArray(saved)) return []
645  const tracks: LimitTrack[] = []
646  for (const raw of saved.slice(0, 8)) {
647    const kind = field(raw, 'kind')
648    const samples = (raw as { samples?: unknown } | null)?.samples
649    if (kind === undefined || !Array.isArray(samples)) continue
650    const resetsAt = field(raw, 'resetsAt')
651    tracks.push({
652      kind,
653      samples: samples
654        .filter(
655          (one): one is LimitSample =>
656            typeof one === 'object' &&
657            one !== null &&
658            Number.isFinite((one as LimitSample).at) &&
659            Number.isFinite((one as LimitSample).percent),
660        )
661        .map(one => ({ at: one.at, percent: one.percent }))
662        .slice(-120),
663      hasWarned: (raw as { hasWarned?: unknown }).hasWarned === true,
664      ...(resetsAt === undefined ? {} : { resetsAt }),
665    })
666  }
667
668  return tracks
669}
670
671const newest = (track: LimitTrack): number => track.samples[track.samples.length - 1]?.at ?? 0
672
673// A window as two sessions read it, folded into one: their readings in
674// order, and a warning either of them gave counting for both. Of two
675// different windows of a kind the one read last stands.
676export const mergeTracks = (
677  held: readonly LimitTrack[],
678  kept: readonly LimitTrack[],
679): LimitTrack[] => {
680  const kinds = [...new Set([...held, ...kept].map(track => track.kind))]
681  const merged: LimitTrack[] = []
682  for (const kind of kinds) {
683    const mine = held.find(track => track.kind === kind)
684    const theirs = kept.find(track => track.kind === kind)
685    if (mine === undefined || theirs === undefined) {
686      const only = mine ?? theirs
687      if (only !== undefined) merged.push(only)
688      continue
689    }
690    const was = stamp(mine.resetsAt)
691    const is = stamp(theirs.resetsAt)
692    if (was === null || is === null || Math.abs(was - is) > MINUTE) {
693      merged.push(newest(theirs) > newest(mine) ? theirs : mine)
694      continue
695    }
696    const samples: LimitSample[] = []
697    for (const sample of [...mine.samples, ...theirs.samples].sort((a, b) => a.at - b.at)) {
698      if (samples[samples.length - 1]?.percent !== sample.percent) samples.push(sample)
699    }
700    merged.push({ ...mine, samples: samples.slice(-120), hasWarned: mine.hasWarned || theirs.hasWarned })
701  }
702
703  return merged
704}
705
706// `learning`: too few readings to tell a pace. `steady`: no rise lately.
707// `lasting`: on course to reach the reset. `short`: on course to run out
708// before it. `spent`: full already. `open`: a pace, but no reset time to
709// hold it against.
710export type LimitOutlook = 'learning' | 'steady' | 'lasting' | 'short' | 'spent' | 'open'
711
712export type LimitForecast = {
713  kind: string
714  percentUsed: number
715  /** When the window resets, where the engine says. */
716  resetsAt: number | null
717  /** Points of the window used an hour over the lookback, once it can be told. */
718  perHour: number | null
719  /** When the window would be full at that pace. */
720  exhaustsAt: number | null
721  outlook: LimitOutlook
722}
723
724// When a limit window runs out at its recent pace, against when it resets.
725// The pace is what the window gained over the lookback that ends now, so a
726// pause slows it and a long one ends the forecast.
727export const forecastLimit = (
728  limit: RateLimit,
729  track: LimitTrack | undefined,
730  now: number,
731): LimitForecast => {
732  const resetsAt = stamp(limit.resetsAt)
733  const unknown = {
734    kind: limit.kind,
735    percentUsed: limit.percentUsed,
736    resetsAt,
737    perHour: null,
738    exhaustsAt: null,
739  }
740  if (limit.percentUsed >= 100) return { ...unknown, outlook: 'spent' }
741  // Readings of a window that has reset since say nothing of the new one.
742  if (resetsAt !== null && resetsAt <= now) return { ...unknown, outlook: 'learning' }
743  const { lookback, least } = paceOf(limit.kind)
744  const samples = (track?.samples ?? []).filter(sample => sample.at <= now)
745  const since = now - lookback
746  const before = samples.filter(sample => sample.at <= since).slice(-1)[0]
747  const from = before === undefined ? samples[0] : { at: since, percent: before.percent }
748  if (from === undefined || now - from.at < least) return { ...unknown, outlook: 'learning' }
749  const gained = limit.percentUsed - from.percent
750  if (gained <= 0) return { ...unknown, outlook: 'steady' }
751  const span = now - from.at
752  const perHour = (gained * HOUR) / span
753  const exhaustsAt = Math.round(now + ((100 - limit.percentUsed) * span) / gained)
754
755  return {
756    ...unknown,
757    perHour,
758    exhaustsAt,
759    outlook: resetsAt === null ? 'open' : exhaustsAt < resetsAt ? 'short' : 'lasting',
760  }
761}
762
763export const forecastsOf = (
764  limits: readonly RateLimit[],
765  tracks: readonly LimitTrack[],
766  now: number,
767): LimitForecast[] =>
768  limits.map(limit => forecastLimit(limit, tracks.find(track => track.kind === limit.kind), now))
769
770const LIMIT_NAME: { [kind: string]: readonly [string, string] } = {
771  five_hour: ['5h', 'five-hour'],
772  seven_day: ['7d', 'seven-day'],
773  spend_limit: ['spend', 'spend'],
774}
775
776// A window's name, short for the band and whole for a sentence.
777export const limitName = (kind: string, isShort = false): string =>
778  LIMIT_NAME[kind]?.[isShort ? 0 : 1] ?? clip(kind.replace(/_/g, ' '), isShort ? 8 : 24)
779
780const rate = (perHour: number | null): string => `${Math.round((perHour ?? 0) * 10) / 10}%/h`
781
782// A forecast in a line, for the Resources view.
783export const forecastText = (forecast: LimitForecast, now: number): string => {
784  const { outlook, resetsAt } = forecast
785  const full = about((forecast.exhaustsAt ?? now) - now)
786  if (outlook === 'spent') {
787    return resetsAt === null || resetsAt <= now
788      ? 'limit reached'
789      : `limit reached · resets in ${about(resetsAt - now)}`
790  }
791  if (outlook === 'learning') return 'pace not known yet: it takes a few readings'
792  if (outlook === 'steady') return 'no rise lately: not on course to run out'
793  if (outlook === 'open') return `full in about ${full} at ${rate(forecast.perHour)} · no reset time reported`
794  if (outlook === 'lasting') return `at ${rate(forecast.perHour)} it lasts until the reset`
795  const early = about((resetsAt ?? now) - (forecast.exhaustsAt ?? now))
796
797  return `full in about ${full} at ${rate(forecast.perHour)}, ${early} before it resets`
798}
799
800// The window most worth a warning, in a few words for the band: one already
801// full, else the one on course to run out soonest before its reset.
802export const limitAlert = (forecasts: readonly LimitForecast[], now: number): string | undefined => {
803  const spent = forecasts.find(one => one.outlook === 'spent')
804  if (spent !== undefined) return `⚠ ${limitName(spent.kind, true)} limit reached`
805  const short = forecasts
806    .filter(one => one.outlook === 'short')
807    .sort((a, b) => (a.exhaustsAt ?? 0) - (b.exhaustsAt ?? 0))[0]
808
809  return short === undefined
810    ? undefined
811    : `⚠ ${limitName(short.kind, true)} limit out in ${about((short.exhaustsAt ?? now) - now)}`
812}
813
814// The one toast a window on course to run out early gets.
815export const limitToast = (forecast: LimitForecast, now: number): string => {
816  const full = about((forecast.exhaustsAt ?? now) - now)
817  const early = about((forecast.resetsAt ?? now) - (forecast.exhaustsAt ?? now))
818
819  return `The ${limitName(forecast.kind)} limit is on course to run out in about ${full}, ${early} before it resets`
820}
821
822// ---------------------------------------------------------------- smart zone
823
824// Where state-of-the-art models stop reasoning sharply, whatever the window.
825export const SMART_ZONE = 150_000
826
827// The `smartZone` option as given, or the default for anything unusable.
828export const smartZoneOf = (option: unknown): number =>
829  typeof option === 'number' && Number.isFinite(option) && option > 0 ? Math.round(option) : SMART_ZONE
830
831// The smart-zone limit: the option, or less on a window too small to hold it.
832// An unknown window leaves the option alone.
833export const zoneLimit = (window: number, smartZone: number): number =>
834  window > 0 ? Math.min(smartZone, Math.floor(window * 0.8)) : smartZone
835
836// The caution comes at 80% of the limit.
837export const zoneCaution = (limit: number): number => Math.floor(limit * 0.8)
838
839export const zoneOf = (tokens: number, limit: number): ZoneLevel =>
840  limit <= 0 ? 'inside' : tokens >= limit ? 'out' : tokens >= zoneCaution(limit) ? 'caution' : 'inside'
841
842const ZONE_RANK: Record<ZoneLevel, number> = { inside: 0, caution: 1, out: 2 }
843
844// What a new reading announces: only a climb past the level last announced.
845// Falling below the caution re-arms both warnings.
846export const zoneCrossing = (
847  announced: ZoneLevel,
848  level: ZoneLevel,
849): { announced: ZoneLevel; crossed?: ZoneLevel } => {
850  if (level === 'inside') return { announced: 'inside' }
851
852  return ZONE_RANK[level] > ZONE_RANK[announced] ? { announced: level, crossed: level } : { announced }
853}
854
855// The crossing owed to Claude after a reading: the higher of what was owed
856// and what was just crossed, nothing once context is back inside.
857export const zoneOwing = (owed: ZoneLevel, level: ZoneLevel, crossed: ZoneLevel | undefined): ZoneLevel => {
858  if (level === 'inside') return 'inside'
859  if (crossed === undefined) return owed
860
861  return ZONE_RANK[crossed] > ZONE_RANK[owed] ? crossed : owed
862}
863
864// What Claude reads after the person's next prompt, once per crossing: never
865// in the system prompt, whose cache a long session cannot afford to lose.
866export const zoneNote = (level: ZoneLevel, tokens: number, limit: number): string =>
867  level === 'out'
868    ? [
869        `Polis: this session's context is ${compact(tokens)}, past the smart-zone limit of ${compact(limit)}, beyond which reasoning is no longer at its sharpest.`,
870        'Stop at the next phase boundary (the gap between two chunks of work, such as grilling and implementing) and recommend the person clears or compacts:',
871        'recommend /clear, after writing down what the next phase needs, when the next phase does not depend on this conversation;',
872        'recommend /compact when it does and losing some detail will not hurt the work.',
873        'Until then, hand independent remaining pieces to sub-agents, which start with fresh context.',
874        'Never carry on past this point without saying so.',
875      ].join(' ')
876    : [
877        `Polis: this session's context is ${compact(tokens)}, past the smart-zone caution (${compact(zoneCaution(limit))} of a ${compact(limit)} limit).`,
878        'Plan how this work will stop while there is still room:',
879        'hand independent remaining pieces to sub-agents, which start with fresh context,',
880        'or aim to stop at the next phase boundary.',
881      ].join(' ')
882
883// The smart-zone state in a few words, for the status line and the page;
884// nothing inside the smart zone.
885export const zoneMark = (level: ZoneLevel, tokens: number): string | undefined =>
886  level === 'out'
887    ? `ctx ${compact(tokens)}: out of the smart zone`
888    : level === 'caution'
889      ? `ctx ${compact(tokens)}: smart-zone caution`
890      : undefined
891
892// The toast for a crossing, saying what to do about it.
893export const zoneToast = (level: ZoneLevel, tokens: number, limit: number): string =>
894  level === 'out'
895    ? `Out of the smart zone: context ${compact(tokens)} is past ${compact(limit)}. At the next phase boundary, /compact or /clear`
896    : `Smart-zone caution: context ${compact(tokens)} of ${compact(limit)}. Plan a stop: hand remaining pieces to sub-agents, or aim for the next phase boundary`
897
898// --------------------------------------------------------------------- waits
899
900// The tools whose call is itself a wait on the person, whatever the mode.
901export const ASKING: { [tool: string]: WaitKind } = {
902  AskUserQuestion: 'question',
903  ExitPlanMode: 'plan',
904}
905
906// One wait for each thing waited on: the same loop asking again for the same
907// tool takes the place of its earlier request.
908export const addWait = (list: readonly Wait[], wait: Wait): Wait[] =>
909  [
910    ...list.filter(
911      one => !(one.kind === wait.kind && one.tool === wait.tool && one.agentId === wait.agentId),
912    ),
913    wait,
914  ].slice(-12)
915
916// A wait that holds work up, where the end of a turn only hands it back.
917export const isBlocking = (wait: Wait): boolean => wait.kind !== 'turn'
918
919// What the person is needed for first: the oldest thing holding work up,
920// else the turn handed back to them.
921export const topWait = (list: readonly Wait[]): Wait | undefined =>
922  list.find(isBlocking) ?? list.find(wait => wait.kind === 'turn')
923
924// What holds work up until the person acts: the top wait when it blocks.
925export const topNeed = (list: readonly Wait[]): Wait | undefined => {
926  const top = topWait(list)
927
928  return top !== undefined && isBlocking(top) ? top : undefined
929}
930
931export const waitText = (wait: Wait): string => {
932  if (wait.kind === 'permission') return `permission for ${clip(wait.tool ?? 'a tool', 28)}`
933  if (wait.kind === 'question') return 'a question for you'
934  if (wait.kind === 'plan') return 'a plan to approve'
935  if (wait.kind === 'input') return `input for ${clip(wait.detail ?? 'a connector', 28)}`
936  if (wait.kind === 'asked') return askText(wait.count)
937
938  return wait.detail ?? 'your turn'
939}
940
941// A wait as the band and the status line mark it.
942export const waitMark = (wait: Wait): string =>
943  isBlocking(wait) ? `▲ needs you: ${waitText(wait)}` : `◇ ${waitText(wait)}`
944
945export type SessionState = 'needs you' | 'working' | 'your turn' | 'idle'
946
947// What the main session is doing: a wait on the person comes before the work
948// it holds up.
949export const sessionState = (isWorking: boolean, waits: readonly Wait[]): SessionState => {
950  const top = topWait(waits)
951  if (top !== undefined && isBlocking(top)) return 'needs you'
952  if (isWorking) return 'working'
953
954  return top === undefined ? 'idle' : 'your turn'
955}
956
957// The first question of an AskUserQuestion call, read loosely.
958export const firstQuestion = (input: unknown): string | undefined => {
959  const questions = (input as { questions?: unknown } | null)?.questions
960
961  return Array.isArray(questions) ? field(questions[0], 'question') : undefined
962}
963
964// -------------------------------------------------------------------- skills
965
966// Skills whose name or description shares words with what is being worked on.
967export const suggestSkills = (
968  available: readonly SkillInfo[],
969  used: { [name: string]: number },
970  corpus: string,
971): string[] => {
972  const wanted = new Set(words(corpus))
973  if (wanted.size === 0) return []
974
975  return available
976    .filter(skill => used[skill.name] === undefined)
977    .map(skill => {
978      const named = words(skill.name).filter(word => wanted.has(word)).length
979      const described = new Set(words(skill.description).filter(word => wanted.has(word))).size
980
981      return { name: skill.name, score: named * 3 + described }
982    })
983    .filter(one => one.score >= 3)
984    .sort((a, b) => b.score - a.score)
985    .slice(0, 5)
986    .map(one => one.name)
987}
988
989// ------------------------------------------------------------------- project
990
991export const projectName = (root: string): string => {
992  const parts = root.split(/[\\/]+/).filter(part => part !== '')
993  if (parts.includes('scratch-workspaces')) return 'Scratch'
994
995  return parts[parts.length - 1] ?? 'Project'
996}
997
998// A path under the root, joined the way the root itself is written.
999export const under = (root: string, ...parts: string[]): string => {
1000  const separator = root.includes('\\') && !root.includes('/') ? '\\' : '/'
1001
1002  return [root.replace(/[\\/]+$/, ''), ...parts].join(separator)
1003}
1004
1005// An absolute path as the address a browser opens: `C:\a\b` and `/a/b` alike.
1006export const fileUrl = (path: string): string => {
1007  const parts = path.split(/[\\/]+/).filter(part => part !== '')
1008  const hasDrive = /^[A-Za-z]:$/.test(parts[0] ?? '')
1009  const encoded = parts.map((part, index) =>
1010    index === 0 && hasDrive ? part : encodeURIComponent(part),
1011  )
1012  // A network share (`\\server\share`) names its server where a host goes.
1013  const isShare = /^(\\\\|\/\/)[^\\/]/.test(path)
1014
1015  return `${isShare ? 'file://' : 'file:///'}${encoded.join('/')}`
1016}
1017
1018export const newProject = (root: string, at: number): Project => ({
1019  root,
1020  name: projectName(root),
1021  phase: '',
1022  milestones: [],
1023  sessions: 0,
1024  lastSessionId: '',
1025  turns: 0,
1026  tokens: 0,
1027  tasksDone: 0,
1028  lastActive: at,
1029})
1030
1031// What the store handed back, held to the record's shape: a value written by
1032// other code, or none, starts the project over.
1033export const asProject = (saved: unknown, root: string, at: number): Project => {
1034  const fresh = newProject(root, at)
1035  if (typeof saved !== 'object' || saved === null) return fresh
1036  const bag = saved as { [key: string]: unknown }
1037  const count = (key: string): number => (typeof bag[key] === 'number' ? (bag[key] as number) : 0)
1038
1039  return mergeProject(
1040    {
1041      ...fresh,
1042      sessions: count('sessions'),
1043      lastSessionId: typeof bag.lastSessionId === 'string' ? bag.lastSessionId : '',
1044      turns: count('turns'),
1045      tokens: count('tokens'),
1046      tasksDone: count('tasksDone'),
1047    },
1048    { name: bag.name, phase: bag.phase, milestones: bag.milestones },
1049  )
1050}
1051
1052export const asHistory = (saved: unknown): TurnRecord[] => {
1053  if (!Array.isArray(saved)) return []
1054
1055  return saved
1056    .filter(
1057      (one): one is TurnRecord =>
1058        typeof one === 'object' &&
1059        one !== null &&
1060        SIZES.includes((one as TurnRecord).size) &&
1061        typeof (one as TurnRecord).tokens === 'number' &&
1062        typeof (one as TurnRecord).ms === 'number' &&
1063        typeof (one as TurnRecord).tools === 'number',
1064    )
1065    .slice(-300)
1066}
1067
1068// ------------------------------------------------------------- carried tasks
1069
1070/** The task list as the store keeps it between sessions. */
1071export type SavedTasks = { sessionId: string; at: number; tasks: Task[] }
1072
1073// How long finished work stays on the board of the sessions that follow.
1074export const KEEP_DONE = 7 * 24 * HOUR
1075
1076const finite = (value: unknown): number | undefined =>
1077  typeof value === 'number' && Number.isFinite(value) ? value : undefined
1078
1079// Finished tasks marked with when they were first saved so, and the mark
1080// taken off reopened ones: what a later session keeps them by.
1081export const stampDone = (list: readonly Task[], now: number): Task[] =>
1082  list.map(task => {
1083    if (task.status === 'completed') return task.doneAt === undefined ? { ...task, doneAt: now } : task
1084    if (task.doneAt === undefined) return task
1085    const { doneAt: _dropped, ...rest } = task
1086
1087    return rest
1088  })
1089
1090const strings = <K extends string>(raw: unknown, keys: readonly K[]): { [P in K]?: string } => {
1091  const out: { [P in K]?: string } = {}
1092  for (const key of keys) {
1093    const value = field(raw, key)
1094    if (value !== undefined) out[key] = value
1095  }
1096
1097  return out
1098}
1099
1100// One saved task, held to the contract's shape; one without an id, a subject
1101// or a known status is dropped.
1102const asTask = (raw: unknown): Task | undefined => {
1103  const id = field(raw, 'id')
1104  const subject = field(raw, 'subject')
1105  const status = TASK_STATUSES.find(one => one === field(raw, 'status'))
1106  if (id === undefined || subject === undefined || status === undefined) return undefined
1107  const bag = raw as { [key: string]: unknown }
1108  const areaFrom = (['tag', 'code', 'title'] as const).find(one => one === bag.areaFrom)
1109  const touched: { [area: string]: number } = {}
1110  if (typeof bag.touched === 'object' && bag.touched !== null) {
1111    for (const [area, count] of Object.entries(bag.touched).slice(0, 40)) {
1112      const edits = finite(count)
1113      if (edits !== undefined) touched[area] = edits
1114    }
1115  }
1116  const said = bag.verdict as { state?: unknown; by?: unknown; at?: unknown } | null | undefined
1117  const state = (['passed', 'failed'] as const).find(one => one === said?.state)
1118  const by = (['verifier', 'checks'] as const).find(one => one === said?.by)
1119  const doneAt = finite(bag.doneAt)
1120
1121  return {
1122    id,
1123    subject: clip(subject, 240),
1124    status,
1125    area: (field(raw, 'area') ?? 'general').slice(0, 24),
1126    blockedBy: Array.isArray(bag.blockedBy)
1127      ? bag.blockedBy.filter((one): one is string => typeof one === 'string').slice(0, 40)
1128      : [],
1129    source: bag.source === 'todo' ? 'todo' : 'task',
1130    ...(areaFrom === undefined ? {} : { areaFrom }),
1131    ...(Object.keys(touched).length === 0 ? {} : { touched }),
1132    ...(state === undefined || by === undefined
1133      ? {}
1134      : { verdict: { state, by, at: finite(said?.at) ?? 0 } }),
1135    ...(doneAt === undefined ? {} : { doneAt }),
1136    ...strings(raw, ['activeForm', 'parentId', 'owner', 'agentId', 'sessionId']),
1137  }
1138}
1139
1140// The tasks a session starts with: what the store kept of the project's
1141// board, less the work finished more than a week ago. Another session's tasks
1142// are marked as its own and renamed after it, since every session numbers its
1143// tasks from one; the same session resumed takes its list back as it was.
1144export const carryTasks = (saved: unknown, sessionId: string, now: number): Task[] => {
1145  const bag = saved as { at?: unknown; tasks?: unknown } | null | undefined
1146  if (typeof bag !== 'object' || bag === null || !Array.isArray(bag.tasks)) return []
1147  const from = field(saved, 'sessionId') ?? 'earlier'
1148  const at = finite(bag.at) ?? 0
1149  const all = bag.tasks.slice(-240).flatMap(raw => asTask(raw) ?? [])
1150  const kept = all.filter(
1151    task => task.status !== 'completed' || now - (task.doneAt ?? at) <= KEEP_DONE,
1152  )
1153  if (from === sessionId) return kept
1154  const mark = from.slice(0, 8)
1155  const ids = new Map(
1156    all.filter(task => task.sessionId === undefined).map(task => [task.id, `${mark}/${task.id}`] as const),
1157  )
1158
1159  return kept.map(task => {
1160    if (task.sessionId !== undefined) return task
1161    // The loop that recorded it ended with its session.
1162    const { agentId: _ended, parentId, ...rest } = task
1163
1164    return {
1165      ...rest,
1166      id: ids.get(task.id) ?? task.id,
1167      sessionId: from,
1168      blockedBy: task.blockedBy.map(id => ids.get(id) ?? id),
1169      ...(parentId === undefined ? {} : { parentId: ids.get(parentId) ?? parentId }),
1170    }
1171  })
1172}
1173
1174// A loose read of one string field off a tool's result, whatever the tool.
1175export const pick = (bag: unknown, key: string): string | undefined => field(bag, key)
1176
1177const STATUSES: readonly MilestoneStatus[] = ['planned', 'active', 'done']
1178
1179export type ProjectInput = { name?: unknown; phase?: unknown; milestones?: unknown }
1180
1181// What the model sent through the project tool, merged into the record:
1182// milestones are matched by id, new ones appended in the order given.
1183export const mergeProject = (project: Project, input: ProjectInput): Project => {
1184  const milestones = [...project.milestones]
1185  const given = Array.isArray(input.milestones) ? input.milestones : []
1186  for (const raw of given.slice(0, 40)) {
1187    const title = field(raw, 'title')
1188    const id = field(raw, 'id') ?? title?.toLowerCase().replace(/[^a-z0-9]+/g, '-').slice(0, 40)
1189    if (id === undefined) continue
1190    const stated = field(raw, 'status')
1191    const at = milestones.findIndex(one => one.id === id)
1192    const before = milestones[at]
1193    const status = STATUSES.find(one => one === stated) ?? before?.status ?? 'planned'
1194    const next: Milestone = { id, title: clip(title ?? before?.title ?? id, 80), status }
1195    if (at === -1) milestones.push(next)
1196    else milestones[at] = next
1197  }
1198
1199  return {
1200    ...project,
hooks/archive.ts 130 lines
1import type { Archive, ArchiveEntry, Task } from '../types'
2import { clip } from './logic'
3
4// A pure module: the project's archive, every task it has finished, kept in
5// the store under the project's root and read back by every later session.
6// The newest ARCHIVE_KEEP are kept in full; older ones fold into an exact
7// count per district (ADR 0002). Nothing here touches the engine.
8
9export type { Archive, ArchiveEntry } from '../types'
10
11export const ARCHIVE_KEEP = 2000
12
13export const EMPTY_ARCHIVE: Archive = { entries: [], folded: {} }
14
15// Bounds on what a saved archive may hold: it is read back untrusted.
16const MAX_AREAS = 200
17const MAX_COUNT = 1_000_000_000
18
19const text = (bag: { [key: string]: unknown }, key: string, max: number): string | undefined => {
20  const value = bag[key]
21  if (typeof value !== 'string') return undefined
22  const trimmed = value.trim()
23
24  return trimmed === '' ? undefined : trimmed.slice(0, max)
25}
26
27const asEntry = (raw: unknown): ArchiveEntry | undefined => {
28  if (typeof raw !== 'object' || raw === null) return undefined
29  const bag = raw as { [key: string]: unknown }
30  const id = text(bag, 'id', 80)
31  const subject = text(bag, 'subject', 240)
32  const sessionId = text(bag, 'sessionId', 80)
33  const doneAt = typeof bag.doneAt === 'number' && Number.isFinite(bag.doneAt) ? bag.doneAt : undefined
34  if (id === undefined || subject === undefined || sessionId === undefined || doneAt === undefined) {
35    return undefined
36  }
37  const verdict = (['passed', 'failed'] as const).find(one => one === bag.verdict)
38
39  return {
40    id,
41    subject: clip(subject, 240),
42    area: text(bag, 'area', 24) ?? 'general',
43    doneAt,
44    sessionId,
45    ...(verdict === undefined ? {} : { verdict }),
46  }
47}
48
49// The archive as the store kept it, held to the contract's shape: anything
50// malformed is dropped, never thrown on.
51export const asArchive = (saved: unknown): Archive => {
52  if (typeof saved !== 'object' || saved === null) return EMPTY_ARCHIVE
53  const bag = saved as { entries?: unknown; folded?: unknown }
54  const seen = new Set<string>()
55  const entries = (Array.isArray(bag.entries) ? bag.entries.slice(-ARCHIVE_KEEP) : [])
56    .flatMap(raw => asEntry(raw) ?? [])
57    .filter(entry => (seen.has(entry.id) ? false : (seen.add(entry.id), true)))
58  const folded: { [area: string]: number } = {}
59  if (typeof bag.folded === 'object' && bag.folded !== null) {
60    for (const [area, count] of Object.entries(bag.folded).slice(0, MAX_AREAS)) {
61      if (typeof count !== 'number' || !Number.isFinite(count) || count <= 0) continue
62      folded[area.slice(0, 24)] = Math.min(MAX_COUNT, Math.floor(count))
63    }
64  }
65
66  return { entries, folded }
67}
68
69// The id a task is archived under: the one a later session carries it as.
70// A session numbers its own tasks from one, so its own are marked with it.
71export const archivedId = (task: Task, sessionId: string): string =>
72  task.sessionId === undefined ? `${sessionId.slice(0, 8)}/${task.id}` : task.id
73
74// The oldest entries past the cap, folded into their districts' counts.
75export const foldArchive = (archive: Archive): Archive => {
76  if (archive.entries.length <= ARCHIVE_KEEP) return archive
77  const sorted = [...archive.entries].sort((a, b) => a.doneAt - b.doneAt)
78  const cut = sorted.length - ARCHIVE_KEEP
79  const folded = { ...archive.folded }
80  for (const entry of sorted.slice(0, cut)) folded[entry.area] = (folded[entry.area] ?? 0) + 1
81
82  return { entries: sorted.slice(cut), folded }
83}
84
85// The archive brought in line with the board: finished tasks added once,
86// reopened ones taken out (they show as open work instead), the oldest
87// folded. The same archive back when nothing changed, so a caller can skip
88// the write.
89export const syncArchive = (archive: Archive, board: readonly Task[], sessionId: string): Archive => {
90  const open = new Set(
91    board.filter(task => task.status !== 'completed').map(task => archivedId(task, sessionId)),
92  )
93  const kept = archive.entries.filter(entry => !open.has(entry.id))
94  const known = new Set(kept.map(entry => entry.id))
95  const added: ArchiveEntry[] = []
96  for (const task of board) {
97    if (task.status !== 'completed' || task.doneAt === undefined) continue
98    const id = archivedId(task, sessionId)
99    if (known.has(id)) continue
100    known.add(id)
101    added.push({
102      id,
103      subject: clip(task.subject, 240),
104      area: task.area.slice(0, 24),
105      doneAt: task.doneAt,
106      sessionId: task.sessionId ?? sessionId,
107      ...(task.verdict === undefined ? {} : { verdict: task.verdict.state }),
108    })
109  }
110  if (added.length === 0 && kept.length === archive.entries.length) return archive
111
112  return foldArchive({ entries: [...kept, ...added], folded: archive.folded })
113}
114
115// What the full city draws beside the board: the archive less the tasks
116// still on the board, so that none is drawn twice.
117export const offBoard = (archive: Archive, board: readonly Task[], sessionId: string): Archive => {
118  const shown = new Set(board.map(task => archivedId(task, sessionId)))
119
120  return { entries: archive.entries.filter(entry => !shown.has(entry.id)), folded: archive.folded }
121}
122
123// How many finished tasks the archive stands for, district by district.
124export const archiveCounts = (archive: Archive): { [area: string]: number } => {
125  const counts = { ...archive.folded }
126  for (const entry of archive.entries) counts[entry.area] = (counts[entry.area] ?? 0) + 1
127
128  return counts
129}
130
hooks/projectlog.ts 370 lines
1import type { AgentNode, AgentRun, AgentRunStatus, ProjectLog, SessionRecord, Task } from '../types'
2import { clip, compact } from './logic'
3
4// A pure module: the per-project log of sessions, kept in the store and read
5// back by every later session. Nothing here touches the engine.
6
7export type { AgentNode, ProjectLog, SessionRecord } from '../types'
8
9export type ProjectTotals = {
10  sessions: number
11  /** Agents spawned by a main loop. */
12  agents: number
13  /** Agents spawned by another agent, at any depth. */
14  subAgents: number
15  turns: number
16  tokens: number
17  costUsd: number
18  tasksDone: number
19}
20
21export const MAX_SESSIONS = 40
22
23// Sessions older than the newest few keep their top-level agents only, so the
24// stored log stays small however long the project runs.
25const FULL_SESSIONS = 10
26
27// Bounds on what a saved log may hold: it is read back untrusted.
28const MAX_DEPTH = 8
29const MAX_SIBLINGS = 60
30
31// ---------------------------------------------------------------- agent tree
32
33const nodeOf = (run: AgentRun): AgentNode => ({
34  key: run.key,
35  type: run.type,
36  label: run.label,
37  ...(run.name === undefined ? {} : { name: run.name }),
38  status: run.status,
39  tokens: run.tokens,
40  tools: run.tools,
41  startedAt: run.startedAt,
42  ...(run.endedAt === undefined ? {} : { endedAt: run.endedAt }),
43  children: [],
44})
45
46// The runs nested by who spawned them, oldest first at every level. A run
47// whose parent is absent, unknown or itself is top-level; a run caught in a
48// cycle of parents is taken as top-level at the point the walk meets it, so
49// that no run is lost and none is shown twice.
50export const agentTree = (agents: readonly AgentRun[]): AgentNode[] => {
51  const runs = [...agents].sort((a, b) => a.startedAt - b.startedAt)
52  const ids = new Set(runs.map(run => run.agentId))
53  const seen = new Set<AgentRun>()
54  const grow = (run: AgentRun): AgentNode => {
55    seen.add(run)
56    const node = nodeOf(run)
57    if (run.agentId !== undefined) {
58      for (const child of runs) {
59        if (child.parentAgentId === run.agentId && !seen.has(child)) node.children.push(grow(child))
60      }
61    }
62
63    return node
64  }
65  const roots: AgentNode[] = []
66  for (const run of runs) {
67    const parent = run.parentAgentId
68    if (parent === undefined || parent === run.agentId || !ids.has(parent)) roots.push(grow(run))
69  }
70  // What no top-level run reached sits in a cycle of parents.
71  for (const run of runs) {
72    if (!seen.has(run)) roots.push(grow(run))
73  }
74
75  return roots
76}
77
78export const sessionRecord = (input: {
79  id: string
80  startedAt: number
81  now: number
82  title: string
83  turns: number
84  tokens: number
85  costUsd: number
86  tasks: readonly Task[]
87  filesEdited: number
88  agents: readonly AgentRun[]
89}): SessionRecord => ({
90  id: input.id,
91  startedAt: input.startedAt,
92  lastActive: input.now,
93  title: clip(input.title, 80),
94  turns: input.turns,
95  tokens: input.tokens,
96  costUsd: input.costUsd,
97  tasksDone: input.tasks.filter(task => task.status === 'completed').length,
98  tasksTotal: input.tasks.length,
99  filesEdited: input.filesEdited,
100  agents: agentTree(input.agents),
101})
102
103// ----------------------------------------------------------------------- log
104
105export const emptyLog = (root: string): ProjectLog => ({ root, sessions: [] })
106
107const STATUSES: readonly AgentRunStatus[] = ['starting', 'running', 'done', 'failed']
108
109const bagOf = (value: unknown): { [key: string]: unknown } | undefined =>
110  typeof value === 'object' && value !== null && !Array.isArray(value)
111    ? (value as { [key: string]: unknown })
112    : undefined
113
114const count = (value: unknown): number =>
115  typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : 0
116
117const text = (value: unknown): string => (typeof value === 'string' ? value : '')
118
119// One saved agent, held to the node's shape; a node without a key or a known
120// status is dropped, and so is everything below it.
121const asNode = (raw: unknown, depth: number): AgentNode | undefined => {
122  const bag = bagOf(raw)
123  const status = STATUSES.find(one => one === bag?.status)
124  if (bag === undefined || typeof bag.key !== 'string' || status === undefined) return undefined
125  const endedAt = count(bag.endedAt)
126
127  return {
128    key: bag.key,
129    type: clip(text(bag.type), 60),
130    label: clip(text(bag.label), 120),
131    ...(typeof bag.name === 'string' && bag.name !== '' ? { name: clip(bag.name, 60) } : {}),
132    status,
133    tokens: count(bag.tokens),
134    tools: count(bag.tools),
135    startedAt: count(bag.startedAt),
136    ...(endedAt === 0 ? {} : { endedAt }),
137    children: asNodes(bag.children, depth + 1),
138  }
139}
140
141const asNodes = (raw: unknown, depth: number): AgentNode[] => {
142  if (!Array.isArray(raw) || depth > MAX_DEPTH) return []
143  const nodes: AgentNode[] = []
144  for (const one of raw.slice(0, MAX_SIBLINGS)) {
145    const node = asNode(one, depth)
146    if (node !== undefined) nodes.push(node)
147  }
148
149  return nodes
150}
151
152// One saved session; one with no id cannot be told from another and is dropped.
153const asSession = (raw: unknown): SessionRecord | undefined => {
154  const bag = bagOf(raw)
155  if (bag === undefined || typeof bag.id !== 'string' || bag.id === '') return undefined
156
157  return {
158    id: bag.id,
159    startedAt: count(bag.startedAt),
160    lastActive: count(bag.lastActive),
161    title: clip(text(bag.title), 80),
162    turns: count(bag.turns),
163    tokens: count(bag.tokens),
164    costUsd: count(bag.costUsd),
165    tasksDone: count(bag.tasksDone),
166    tasksTotal: count(bag.tasksTotal),
167    filesEdited: count(bag.filesEdited),
168    agents: asNodes(bag.agents, 0),
169  }
170}
171
172// Sessions in the order they began, the newest MAX_SESSIONS of them, and all
173// but the newest few cut down to their top-level agents.
174const settle = (sessions: readonly SessionRecord[]): SessionRecord[] => {
175  const kept = [...sessions].sort((a, b) => a.startedAt - b.startedAt).slice(-MAX_SESSIONS)
176  const old = kept.length - FULL_SESSIONS
177
178  return kept.map((session, at) =>
179    at < old
180      ? { ...session, agents: session.agents.map(agent => ({ ...agent, children: [] })) }
181      : session,
182  )
183}
184
185// What the store handed back, held to the log's shape: damage is dropped piece
186// by piece, and a log of another project, or none, starts the log over.
187export const asProjectLog = (saved: unknown, root: string): ProjectLog => {
188  const bag = bagOf(saved)
189  if (bag === undefined || bag.root !== root || !Array.isArray(bag.sessions)) return emptyLog(root)
190  const byId = new Map<string, SessionRecord>()
191  for (const raw of bag.sessions) {
192    const session = asSession(raw)
193    if (session !== undefined) byId.set(session.id, session)
194  }
195
196  return { root, sessions: settle([...byId.values()]) }
197}
198
199// The session with this id replaced, or added; the input is left as it was.
200export const upsertSession = (log: ProjectLog, record: SessionRecord): ProjectLog => ({
201  root: log.root,
202  sessions: settle([...log.sessions.filter(one => one.id !== record.id), record]),
203})
204
205// ------------------------------------------------------------------- totals
206
207export const countAgents = (nodes: readonly AgentNode[]): { agents: number; subAgents: number } => {
208  let subAgents = 0
209  const below = (list: readonly AgentNode[]): void => {
210    for (const node of list) {
211      subAgents += 1
212      below(node.children)
213    }
214  }
215  for (const node of nodes) below(node.children)
216
217  return { agents: nodes.length, subAgents }
218}
219
220export const totalsOf = (log: ProjectLog): ProjectTotals => {
221  const totals: ProjectTotals = {
222    sessions: log.sessions.length,
223    agents: 0,
224    subAgents: 0,
225    turns: 0,
226    tokens: 0,
227    costUsd: 0,
228    tasksDone: 0,
229  }
230  for (const session of log.sessions) {
231    const { agents, subAgents } = countAgents(session.agents)
232    totals.agents += agents
233    totals.subAgents += subAgents
234    totals.turns += session.turns
235    totals.tokens += session.tokens
236    totals.costUsd += session.costUsd
237    totals.tasksDone += session.tasksDone
238  }
239
240  return totals
241}
242
243// -------------------------------------------------------------------- lines
244
245// The marks of RUN_MARK in hooks/views.tsx, copied: that module is not for a
246// pure one to import.
247const RUN_MARK: Record<AgentRunStatus, string> = {
248  starting: '◌',
249  running: '●',
250  done: '✔',
251  failed: '✘',
252}
253
254// Most levels of agents shown under a session, and most top-level agents.
255const SHOWN_LEVELS = 4
256const SHOWN_AGENTS = 6
257
258const ago = (ms: number): string => {
259  const minutes = Math.floor(Math.max(0, ms) / 60_000)
260  if (minutes < 1) return 'now'
261  if (minutes < 60) return `${minutes}m ago`
262  const hours = Math.floor(minutes / 60)
263
264  return hours < 24 ? `${hours}h ago` : `${Math.floor(hours / 24)}d ago`
265}
266
267const dollars = (usd: number): string => `$${usd.toFixed(2)}`
268
269const plural = (n: number, noun: string): string => `${n} ${noun}${n === 1 ? '' : 's'}`
270
271// A line cut to the width; the indent is part of it, so the cut is made here
272// and not by `clip`, which would trim the indent away.
273const fit = (line: string, columns: number): string =>
274  line.length <= columns ? line : `${line.slice(0, Math.max(1, columns - 1))}…`
275
276const sessionLine = (session: SessionRecord, isLive: boolean, now: number, columns: number): string => {
277  const head = `${isLive ? '●' : '○'} ${ago(now - session.lastActive)}`
278  const full = [
279    plural(session.turns, 'turn'),
280    `${compact(session.tokens)} tokens`,
281    dollars(session.costUsd),
282    `${session.tasksDone}/${session.tasksTotal} tasks`,
283  ].join(' · ')
284  const short = [
285    `${session.turns}t`,
286    compact(session.tokens),
287    dollars(session.costUsd),
288    `${session.tasksDone}/${session.tasksTotal}`,
289  ].join(' · ')
290  // The figures have the right of way; the title takes what is left, and in a
291  // narrow pane the figures lose their words before the title is lost.
292  const room = (figures: string): number => columns - head.length - 5 - figures.length
293  const figures = room(full) >= 14 ? full : short
294  const title = session.title === '' ? 'untitled session' : session.title
295
296  return fit(`${head}  ${clip(title, Math.max(8, room(figures)))} — ${figures}`, columns)
297}
298
299const hiddenCount = (nodes: readonly AgentNode[]): number => {
300  const { agents, subAgents } = countAgents(nodes)
301
302  return agents + subAgents
303}
304
305const agentLine = (node: AgentNode, level: number, columns: number): string => {
306  const indent = ' '.repeat(level * 2)
307  const lead = node.name === undefined ? node.type : `${node.name} (${node.type})`
308  const figures = `${compact(node.tokens)} tok · ${plural(node.tools, 'tool')}`
309  const room = columns - indent.length - 4 - lead.length - 2 - figures.length - 3
310  const label = clip(node.label, Math.max(4, room))
311  const words = label === '' ? lead : `${lead}: ${label}`
312
313  return fit(`${indent}└ ${RUN_MARK[node.status]} ${words} · ${figures}`, columns)
314}
315
316const agentLines = (nodes: readonly AgentNode[], level: number, columns: number): string[] => {
317  const indent = ' '.repeat(level * 2)
318  if (level > SHOWN_LEVELS) {
319    return nodes.length === 0 ? [] : [fit(`${indent}└ … ${hiddenCount(nodes)} more below`, columns)]
320  }
321  // Of too many agents the heaviest are shown, in the order they began.
322  const shown =
323    level === 1 && nodes.length > SHOWN_AGENTS
324      ? new Set([...nodes].sort((a, b) => b.tokens - a.tokens).slice(0, SHOWN_AGENTS))
325      : undefined
326  const lines: string[] = []
327  for (const node of nodes) {
328    if (shown !== undefined && !shown.has(node)) continue
329    lines.push(agentLine(node, level, columns), ...agentLines(node.children, level + 1, columns))
330  }
331  if (shown !== undefined) lines.push(fit(`${indent}└ … ${nodes.length - shown.size} more agents`, columns))
332
333  return lines
334}
335
336// The whole project as lines for a terminal: the newest session first, each
337// with its agents under it, and the sub-agents under theirs.
338export const projectLines = (
339  log: ProjectLog,
340  options: { now: number; liveId?: string; columns: number; maxSessions?: number },
341): string[] => {
342  const columns = Math.max(20, Math.floor(options.columns))
343  const limit = Math.max(0, Math.floor(options.maxSessions ?? 8))
344  const newest = [...log.sessions].sort((a, b) => b.startedAt - a.startedAt)
345  const lines: string[] = []
346  for (const session of newest.slice(0, limit)) {
347    lines.push(
348      sessionLine(session, session.id === options.liveId, options.now, columns),
349      ...agentLines(session.agents, 1, columns),
350    )
351  }
352  const hidden = newest.length - limit
353  if (hidden > 0) lines.push(fit(`… and ${hidden} earlier session${hidden === 1 ? '' : 's'}`, columns))
354
355  return lines
356}
357
358// 12 sessions · 31 agents · 9 sub-agents · 4.2M tokens · $18.40
359export const projectHeadline = (log: ProjectLog): string => {
360  const totals = totalsOf(log)
361
362  return [
363    plural(totals.sessions, 'session'),
364    plural(totals.agents, 'agent'),
365    plural(totals.subAgents, 'sub-agent'),
366    `${compact(totals.tokens)} tokens`,
367    dollars(totals.costUsd),
368  ].join(' · ')
369}
370
hooks/report.ts 268 lines
1import type { AgentRun, FileHit, Project, Task, Usage } from '../types'
2import { clip, compact, hotFiles, taskStats, taskTree } from './logic'
3
4export type ReportInput = {
5  now: number
6  project: Project | null
7  /** The repository root, so paths print relative to it. */
8  root?: string
9  tasks: (Omit<Task, 'verdict'> & { verdict?: { state: 'passed' | 'failed'; by: string } })[]
10  agents: AgentRun[]
11  files: FileHit[]
12  usage: Usage
13  /** Prompts answered this session, when known. */
14  turns?: number
15  checks?: { kind: string; state: 'passed' | 'failed' | 'stale'; command: string; at: number }[]
16  git?: { branch: string; files: number; added: number; removed: number; untracked: number } | null
17  limits?: { label: string; percentUsed: number; note?: string }[]
18}
19
20// The name a saved report goes by.
21export const REPORT_FILE: string = 'polis-report.md'
22
23type Git = NonNullable<ReportInput['git']>
24type Check = NonNullable<ReportInput['checks']>[number]
25type Verdict = NonNullable<ReportInput['tasks'][number]['verdict']>
26type Row = ReturnType<typeof taskTree>[number]
27type Shelves = { done: Row[]; active: Row[]; waiting: Row[] }
28
29// A report is short enough to paste: the files it lists stop here.
30const MAX_FILES = 15
31
32// ---------------------------------------------------------------- formatting
33
34const count = (n: number, noun: string): string => `${n} ${noun}${n === 1 ? '' : 's'}`
35
36// UTC, as the date in `now` is: the same report reads the same anywhere.
37const dayOf = (at: number): string => {
38  const date = new Date(at)
39
40  return Number.isNaN(date.getTime()) ? '' : date.toISOString().slice(0, 10)
41}
42
43// How long before the report, as a person says it. `elapsed` counts a
44// duration to the second, which is too exact for "when did the tests run".
45const ago = (ms: number): string => {
46  const seconds = Math.max(0, Math.floor(ms / 1000))
47  if (seconds < 10) return 'just now'
48  if (seconds < 60) return `${seconds}s ago`
49  const minutes = Math.floor(seconds / 60)
50  if (minutes < 60) return `${minutes}m ago`
51  const hours = Math.floor(minutes / 60)
52
53  return hours < 24 ? `${hours}h ago` : `${Math.floor(hours / 24)}d ago`
54}
55
56// A path as a pull request shows it: from the root, forward slashes. A
57// Windows root ignores case, as the file system does.
58const relativeTo = (path: string, root: string | undefined): string => {
59  const flat = path.replace(/\\/g, '/')
60  const base = (root ?? '').replace(/\\/g, '/').replace(/\/+$/, '')
61  if (base === '') return flat
62  const head = flat.slice(0, base.length + 1)
63  const same = /^[a-z]:/i.test(base)
64    ? head.toLowerCase() === `${base}/`.toLowerCase()
65    : head === `${base}/`
66
67  return same ? flat.slice(base.length + 1) : flat
68}
69
70// A pipe would end a table cell early.
71const cell = (text: string): string => text.replace(/\|/g, '\\|')
72
73// Code in backticks, so `[id].tsx` and `my_file.ts` print as written.
74const code = (text: string): string => `\`${text.replace(/`/g, "'")}\``
75
76const dollars = (usd: number): string => `$${usd.toFixed(2)}`
77
78// ------------------------------------------------------------------- header
79
80const changeOf = (git: Git): string => {
81  const parts: string[] = []
82  if (git.files > 0) parts.push(`${count(git.files, 'file')} changed, +${git.added} -${git.removed}`)
83  if (git.untracked > 0) parts.push(`${git.untracked} untracked`)
84
85  return parts.length === 0 ? 'clean' : parts.join(', ')
86}
87
88const headerOf = (input: ReportInput): string[] => {
89  const { project } = input
90  const git = input.git ?? null
91  const name = project === null ? '' : clip(project.name, 60)
92  const branch = git === null ? '' : git.branch === '' ? 'detached HEAD' : `branch ${git.branch}`
93  const facts = [dayOf(input.now), git === null ? '' : `${branch} (${changeOf(git)})`].filter(
94    fact => fact !== '',
95  )
96
97  return [
98    name === '' ? '# Session report' : `# ${name} — session report`,
99    ...(facts.length === 0 ? [] : ['', facts.join(' · ')]),
100  ]
101}
102
103// -------------------------------------------------------------------- tasks
104
105// Each top-level task with its sub-tasks, filed by the top-level task's state:
106// a sub-task is read in its parent's company.
107const shelve = (rows: readonly Row[]): Shelves => {
108  const shelves: Shelves = { done: [], active: [], waiting: [] }
109  let shelf = shelves.waiting
110  for (const row of rows) {
111    if (row.depth === 0) {
112      shelf =
113        row.task.status === 'completed'
114          ? shelves.done
115          : row.task.status === 'in_progress'
116            ? shelves.active
117            : shelves.waiting
118    }
119    shelf.push(row)
120  }
121
122  return shelves
123}
124
125// A top-level task is a checkbox only under Done; a sub-task always shows its
126// own state, so a half-finished task reads as what is left of it.
127const taskLine = (row: Row, verdict: Verdict | undefined, isChecklist: boolean): string => {
128  const { task, depth } = row
129  const mark = depth > 0 || isChecklist ? (task.status === 'completed' ? '[x] ' : '[ ] ') : ''
130  const area = task.area === '' ? '' : ` (${task.area})`
131  const note =
132    verdict === undefined ? '' : verdict.state === 'passed' ? ' — verified' : ' — failed its check'
133
134  return `${'  '.repeat(depth)}- ${mark}${clip(task.subject, 100)}${area}${note}`
135}
136
137// ------------------------------------------------------------------- checks
138
139// The latest run of each kind: a check that ran twice is told by its second run.
140const latestChecks = (checks: readonly Check[]): Check[] => {
141  const latest = new Map<string, Check>()
142  for (const check of checks) {
143    const before = latest.get(check.kind)
144    if (before === undefined || check.at >= before.at) latest.set(check.kind, check)
145  }
146
147  return [...latest.values()]
148}
149
150const checksTable = (checks: readonly Check[], now: number): string[] =>
151  checks.length === 0
152    ? []
153    : [
154        '| Check | Result | Command | When |',
155        '| --- | --- | --- | --- |',
156        ...checks.map(
157          check =>
158            `| ${cell(check.kind)} | ${check.state} | ` +
159            `${check.command === '' ? '' : code(cell(clip(check.command, 60)))} | ${ago(now - check.at)} |`,
160        ),
161      ]
162
163// ------------------------------------------------------------------- report
164
165const block = (title: string, lines: readonly string[]): string[] =>
166  lines.length === 0 ? [] : [`## ${title}`, '', ...lines]
167
168const summaryOf = (
169  input: ReportInput,
170  roots: readonly Task[],
171  verdicts: ReadonlyMap<string, Verdict | undefined>,
172  checks: readonly Check[],
173): string[] => {
174  const stats = taskStats(roots)
175  const states = roots
176    .filter(task => task.status === 'completed')
177    .map(task => verdicts.get(task.id)?.state)
178  const verified = states.filter(state => state === 'passed').length
179  const failed = states.filter(state => state === 'failed').length
180  const outcome = [
181    ...(verified > 0 ? [`${verified} verified`] : []),
182    ...(failed > 0 ? [`${failed} ${failed === 1 ? 'failed its check' : 'failed their check'}`] : []),
183  ]
184  const tasks = [
185    `${stats.done} of ${stats.total} done${outcome.length === 0 ? '' : ` (${outcome.join(', ')})`}`,
186    ...(stats.active > 0 ? [`${stats.active} in progress`] : []),
187    ...(stats.waiting > 0 ? [`${stats.waiting} waiting`] : []),
188  ]
189  const edits = input.files.reduce((sum, file) => sum + file.edits, 0)
190  const cost = [
191    dollars(input.usage.costUsd),
192    `${compact(input.usage.sessionTokens)} tokens`,
193    input.agents.length === 0 ? 'no agents' : count(input.agents.length, 'agent'),
194    ...(input.turns === undefined ? [] : [count(input.turns, 'prompt')]),
195  ]
196
197  return [
198    ...(stats.total === 0 ? [] : [`- Tasks: ${tasks.join(' · ')}`]),
199    ...(input.files.length === 0
200      ? []
201      : [`- Files: ${count(input.files.length, 'file')} edited, ${count(edits, 'edit')}`]),
202    ...(checks.length === 0
203      ? []
204      : [`- Checks: ${checks.map(check => `${check.kind} ${check.state}`).join(' · ')}`]),
205    `- Cost: ${cost.join(' · ')}`,
206  ]
207}
208
209const filesOf = (input: ReportInput): string[] => {
210  const ranked = hotFiles(input.files, input.files.length)
211  const more = ranked.length - MAX_FILES
212
213  return [
214    ...ranked
215      .slice(0, MAX_FILES)
216      .map(file => `- ${code(relativeTo(file.path, input.root))} — ${count(file.edits, 'edit')}`),
217    // A bullet, so Markdown does not fold the line into the one above it.
218    ...(more > 0 ? [`- and ${more} more`] : []),
219  ]
220}
221
222const usageOf = (input: ReportInput): string[] => {
223  const { usage } = input
224  const held =
225    usage.contextWindow > 0
226      ? ` (${compact(usage.contextTokens)} of ${compact(usage.contextWindow)} tokens)`
227      : ''
228
229  return [
230    `- Context window: ${Math.round(usage.contextPercent)}%${held}`,
231    ...(input.limits ?? []).map(
232      limit =>
233        `- ${clip(limit.label, 40)}: ${Math.round(limit.percentUsed)}% used` +
234        `${limit.note === undefined || limit.note === '' ? '' : ` (${clip(limit.note, 60)})`}`,
235    ),
236    `- Session cost: ${dollars(usage.costUsd)} (${compact(usage.sessionTokens)} tokens)`,
237  ]
238}
239
240// The session as GitHub-flavoured Markdown, for a pull request or a stand-up
241// note. A section with nothing to say is left out.
242export const reportOf = (input: ReportInput): string => {
243  // The verdicts are read from their own map: the tree takes the tasks bare.
244  const rows = taskTree(input.tasks.map(({ verdict: _verdict, ...task }): Task => task))
245  const shelves = shelve(rows)
246  const verdicts = new Map(input.tasks.map(task => [task.id, task.verdict] as const))
247  const lines = (list: readonly Row[], isChecklist: boolean): string[] =>
248    list.map(row => taskLine(row, verdicts.get(row.task.id), isChecklist))
249  const checks = latestChecks(input.checks ?? [])
250  const roots = rows.filter(row => row.depth === 0).map(row => row.task)
251
252  const blocks = [
253    headerOf(input),
254    block('Summary', summaryOf(input, roots, verdicts, checks)),
255    block('Done', lines(shelves.done, true)),
256    block('In progress', lines(shelves.active, false)),
257    block('Not started', lines(shelves.waiting, false)),
258    block('Files changed', filesOf(input)),
259    block('Checks', checksTable(checks, input.now)),
260    block('Usage', usageOf(input)),
261  ]
262
263  return `${blocks
264    .filter(one => one.length > 0)
265    .map(one => one.join('\n'))
266    .join('\n\n')}\n`
267}
268
hooks/page.ts 87 lines
1import { cityAlt, renderCity } from './city'
2import type { CityInput } from './city'
3import { esc } from './icons'
4import { attentionOf, nextStepOf } from './flow'
5import { compact, sessionState, taskStats, zoneMark, zoneOf } from './logic'
6import { C } from './theme'
7
8// The city as a page on disk, for a browser or an editor's preview tab left
9// open beside the session. Nothing serves it: the page asks to be loaded
10// again every few seconds and so picks up whatever was last written.
11export const PAGE_REFRESH_SECONDS = 3
12
13// The widest the drawing grows, so a very large window does not blow it up.
14const MAX_WIDTH = 1100
15
16// `html` carries the background too, so a reload never flashes white.
17const STYLE =
18  `html,body{background:${C.bg}}` +
19  `body{margin:0;padding:12px 16px 20px;color:${C.text};font:13px/1.4 system-ui,-apple-system,'Segoe UI',sans-serif}` +
20  `header,main{max-width:${MAX_WIDTH}px;margin:0 auto}` +
21  `header{display:flex;flex-wrap:wrap;gap:2px 12px;align-items:baseline;padding:0 4px 8px}` +
22  `h1{margin:0;font-size:14px;font-weight:600}` +
23  `header span{color:${C.muted};white-space:nowrap}` +
24  `header .needs,header .out{color:${C.fail};font-weight:600}` +
25  `header .stalled{color:${C.fail}}` +
26  `header .caution{color:${C.run}}` +
27  `header a{color:${C.agent}}` +
28  `p{margin:0;color:${C.muted};flex-basis:100%}` +
29  `svg{display:block;width:100%;height:auto}`
30
31// The drawing comes at a fixed size: here it takes the window's width, and
32// its height follows from its viewBox.
33const fluid = (svg: string): string => svg.replace(/ width="[0-9]+" height="[0-9]+"/, ' width="100%"')
34
35// The facts a glance at the tab should give: what needs the person (or what
36// the session is doing), where the context stands against the smart zone,
37// and how many tasks are done.
38const facts = (m: CityInput): string => {
39  const flow = m.flow ?? null
40  const attention = attentionOf({ ...m, waits: m.waits ?? [], flow })
41  const step = nextStepOf(flow)
42  const spans: string[] = []
43  if (attention !== undefined && attention.tone !== 'work') {
44    spans.push(`<span class="${attention.tone}">${esc(attention.text)}</span>`)
45  } else {
46    spans.push(`<span>${esc(attention?.text ?? sessionState(m.turn.isWorking, m.waits ?? []))}</span>`)
47  }
48  if (step !== undefined) spans.push(`<span>${esc(step.text)}</span>`)
49  const tokens = m.usage.contextTokens
50  if (tokens > 0) {
51    const level = zoneOf(tokens, m.usage.zoneLimit)
52    const text = zoneMark(level, tokens) ?? `ctx ${compact(tokens)}`
53    spans.push(level === 'inside' ? `<span>${esc(text)}</span>` : `<span class="${level}">${esc(text)}</span>`)
54  }
55  const stats = taskStats(m.tasks)
56  if (stats.total > 0) spans.push(`<span>${stats.done}/${stats.total} tasks done</span>`)
57
58  return spans.join('')
59}
60
61// The two pages on disk: the current city, and the full one with the archive.
62export const PAGE_FILES = { current: 'city.html', full: 'city-full.html' } as const
63
64// The way to the other page, at the end of the header.
65const other = (isFull: boolean): string =>
66  isFull ? `<a href="${PAGE_FILES.current}">current city</a>` : `<a href="${PAGE_FILES.full}">full city</a>`
67
68// One whole document. The same input always gives the same text (the drawing's moving parts are set to a fixed clock,
69// nothing random), so the caller can skip a write that would change nothing. An
70// input with an archive is the full city's page.
71export const cityPage = (m: CityInput, name: string): string =>
72  `<!doctype html>\n` +
73  `<html lang="en">\n` +
74  `<head>\n` +
75  `<meta charset="utf-8">\n` +
76  `<meta name="viewport" content="width=device-width, initial-scale=1">\n` +
77  `<meta name="color-scheme" content="dark">\n` +
78  `<meta http-equiv="refresh" content="${PAGE_REFRESH_SECONDS}">\n` +
79  `<title>Polis · ${esc(name)}${m.archive === undefined ? '' : ' · full city'}</title>\n` +
80  `<style>${STYLE}</style>\n` +
81  `</head>\n` +
82  `<body>\n` +
83  `<header><h1>${esc(name)}</h1>${facts(m)}<span>${other(m.archive !== undefined)}</span><p>${esc(cityAlt(m))}</p></header>\n` +
84  `<main>${fluid(renderCity({ ...m, now: 0 }, 'avenue'))}</main>\n` +
85  `</body>\n` +
86  `</html>\n`
87
hooks/theme.ts 140 lines
1import type { ToolFamily } from '../types'
2
3// One soft dark palette, shared by the text views and the city.
4export const C = {
5  bg: '#14161c',
6  ground: '#1c2029',
7  tile: '#232834',
8  tileEdge: '#2b3140',
9  road: '#2b3140',
10  roadMark: '#3a4254',
11  text: '#c9cfdb',
12  muted: '#7b8496',
13  faint: '#4a5263',
14  done: '#8fbf9f',
15  run: '#e0c38c',
16  agent: '#8ea6e0',
17  fail: '#d98c9a',
18  skill: '#b39ddb',
19  proc: '#7fc8c2',
20} as const
21
22export const FAMILIES: readonly ToolFamily[] = [
23  'search',
24  'read',
25  'edit',
26  'shell',
27  'web',
28  'mcp',
29  'skill',
30  'delegate',
31  'plan',
32  'other',
33]
34
35export const FAMILY_LABEL: Record<ToolFamily, string> = {
36  search: 'search',
37  read: 'read',
38  edit: 'edit',
39  shell: 'shell',
40  web: 'web',
41  mcp: 'connectors',
42  skill: 'skills',
43  delegate: 'delegate',
44  plan: 'plan',
45  other: 'other',
46}
47
48// What a tool badge reads as where no icon can be drawn.
49export const FAMILY_GLYPH: Record<ToolFamily, string> = {
50  search: '⌕',
51  read: '▤',
52  edit: '✎',
53  shell: '❯',
54  web: '◍',
55  mcp: '⧉',
56  skill: '✦',
57  delegate: '⇄',
58  plan: '☰',
59  other: '·',
60}
61
62export const FAMILY_COLOR: Record<ToolFamily, string> = {
63  search: C.proc,
64  read: C.agent,
65  edit: C.run,
66  shell: C.done,
67  web: C.proc,
68  mcp: C.skill,
69  skill: C.skill,
70  delegate: C.agent,
71  plan: C.muted,
72  other: C.muted,
73}
74
75const FAMILY_OF: { [tool: string]: ToolFamily } = {
76  Read: 'read',
77  Grep: 'search',
78  Glob: 'search',
79  ToolSearch: 'search',
80  Edit: 'edit',
81  Write: 'edit',
82  NotebookEdit: 'edit',
83  Bash: 'shell',
84  PowerShell: 'shell',
85  Monitor: 'shell',
86  TaskStop: 'shell',
87  WebFetch: 'web',
88  WebSearch: 'web',
89  Skill: 'skill',
90  Agent: 'delegate',
91  Workflow: 'delegate',
92  SendMessage: 'delegate',
93  TodoWrite: 'plan',
94  TaskCreate: 'plan',
95  TaskUpdate: 'plan',
96  TaskList: 'plan',
97  TaskGet: 'plan',
98  EnterPlanMode: 'plan',
99  ExitPlanMode: 'plan',
100  AskUserQuestion: 'plan',
101}
102
103export const familyOf = (tool: string): ToolFamily =>
104  tool.startsWith('mcp__') ? 'mcp' : (FAMILY_OF[tool] ?? 'other')
105
106export type AgentLook = { color: string; glyph: string; icon: string }
107
108const LOOKS: { [type: string]: AgentLook } = {
109  main: { color: C.agent, glyph: '◆', icon: 'a-main' },
110  Explore: { color: C.proc, glyph: '◎', icon: 'a-explore' },
111  Plan: { color: C.skill, glyph: '▧', icon: 'a-plan' },
112  worker: { color: C.run, glyph: '⚒', icon: 'a-worker' },
113  verifier: { color: C.done, glyph: '✓', icon: 'a-verifier' },
114  'general-purpose': { color: C.agent, glyph: '●', icon: 'a-general' },
115  claude: { color: C.agent, glyph: '●', icon: 'a-general' },
116}
117
118const SPARE = [C.agent, C.proc, C.skill, C.run, C.done]
119
120// A plugin's agent type is `<plugin>:<name>`: its look goes by the name.
121export const lookOf = (type: string): AgentLook => {
122  const short = type.includes(':') ? type.slice(type.lastIndexOf(':') + 1) : type
123  const known = LOOKS[short]
124  if (known !== undefined) return known
125  let hash = 0
126  for (const char of short) hash = (hash * 31 + char.charCodeAt(0)) % 9973
127
128  return { color: SPARE[hash % SPARE.length] ?? C.agent, glyph: '●', icon: 'a-general' }
129}
130
131export const VIEWS = [
132  { name: 'overview', label: 'Overview' },
133  { name: 'project', label: 'Project' },
134  { name: 'city', label: 'City' },
135  { name: 'tasks', label: 'Tasks' },
136  { name: 'agents', label: 'Agents' },
137  { name: 'resources', label: 'Resources' },
138  { name: 'skills', label: 'Skills' },
139] as const
140
hooks/verify.ts 129 lines
1import type { AgentRun, Task, Verdict } from '../types'
2
3import { matchTask } from './logic'
4
5export type { Verdict } from '../types'
6
7// A task that may carry a verdict: the contract's own task now.
8export type JudgedTask = Task
9
10// "Claude said it is done" and "something checked it" are different things:
11// open work, work done but never checked, and work a check confirmed or refuted.
12export type Standing = 'open' | 'unchecked' | 'verified' | 'refuted'
13
14// ------------------------------------------------------------------ verifier
15
16// The part after the last colon is the agent's own name: `polis:verifier`.
17export const isVerifier = (type: string): boolean =>
18  /^verif/i.test(type.slice(type.lastIndexOf(':') + 1))
19
20// Whole upper-case words are how a verifier shouts its answer; the lower-case
21// form counts only after the word "verdict", so running prose ("passes",
22// "failure", "password") never reads as one.
23const PASSED = [/\bPASS(?:ED)?\b/, /\bverdict\W{1,4}pass(?:ed)?\b/i]
24const FAILED = [/\bFAIL(?:ED)?\b/, /\bverdict\W{1,4}fail(?:ed)?\b/i]
25
26const said = (message: string, patterns: readonly RegExp[]): boolean =>
27  patterns.some(pattern => pattern.test(message))
28
29// A verifier's final message, read for its answer. A fail anywhere wins: one
30// failed claim is enough to refute the work.
31export const verdictOf = (message: string): 'passed' | 'failed' | undefined => {
32  if (said(message, FAILED)) return 'failed'
33
34  return said(message, PASSED) ? 'passed' : undefined
35}
36
37// The task a verifier's verdict is about: the one it was given, else the best
38// match of its brief, finished work first since that is what gets verified.
39export const taskToJudge = (tasks: readonly Task[], run: AgentRun): string | undefined => {
40  if (run.taskId !== undefined && tasks.some(task => task.id === run.taskId)) return run.taskId
41  // matchTask reads only unfinished tasks, so the finished ones are shown to it as pending.
42  const finished = tasks
43    .filter(task => task.status === 'completed')
44    .map((task): Task => ({ ...task, status: 'pending' }))
45
46  return matchTask(run.label, finished) ?? matchTask(run.label, tasks)
47}
48
49// ------------------------------------------------------------------- verdicts
50
51// Any task may be judged: a verifier can report before the task is marked done.
52export const judge = (
53  tasks: readonly JudgedTask[],
54  taskId: string,
55  state: 'passed' | 'failed',
56  by: Verdict['by'],
57  at: number,
58): JudgedTask[] =>
59  tasks.map((task): JudgedTask => (task.id === taskId ? { ...task, verdict: { state, by, at } } : task))
60
61// A passing test run speaks for every finished task nobody has judged yet.
62// A verifier's word, passed or failed, stands, and an earlier run keeps its time.
63export const judgeByChecks = (tasks: readonly JudgedTask[], at: number): JudgedTask[] =>
64  tasks.map(
65    (task): JudgedTask =>
66      task.status === 'completed' && task.verdict === undefined
67        ? { ...task, verdict: { state: 'passed', by: 'checks', at } }
68        : task,
69  )
70
71const isStale = (task: JudgedTask): boolean => task.status !== 'completed' && task.verdict !== undefined
72
73// Reopened work is no longer what was checked. The same array comes back when
74// nothing was reopened, so a caller can tell by identity that nothing changed.
75export const dropStaleVerdicts = (tasks: readonly JudgedTask[]): JudgedTask[] => {
76  if (!tasks.some(isStale)) return tasks as JudgedTask[]
77
78  return tasks.map((task): JudgedTask => {
79    if (!isStale(task)) return task
80    const { verdict: _dropped, ...rest } = task
81
82    return rest
83  })
84}
85
86// ------------------------------------------------------------------ standing
87
88export const standingOf = (task: JudgedTask): Standing => {
89  if (task.status !== 'completed') return 'open'
90  if (task.verdict === undefined) return 'unchecked'
91
92  return task.verdict.state === 'passed' ? 'verified' : 'refuted'
93}
94
95// The mark builds on the done mark of the text views (✔): doubled when checked,
96// crossed like a failed run when refuted. The two-cell ✔✔ is the widest.
97export const STANDING: { [S in Standing]: { glyph: string; label: string } } = {
98  open: { glyph: '', label: 'open' },
99  unchecked: { glyph: '✔', label: 'done, not checked' },
100  verified: { glyph: '✔✔', label: 'verified' },
101  refuted: { glyph: '✘', label: 'failed its check' },
102}
103
104// Counts over the finished tasks; open work has no standing to count.
105export const standings = (
106  tasks: readonly JudgedTask[],
107): { verified: number; unchecked: number; refuted: number } => {
108  const counts = { verified: 0, unchecked: 0, refuted: 0 }
109  for (const task of tasks) {
110    const standing = standingOf(task)
111    if (standing !== 'open') counts[standing] += 1
112  }
113
114  return counts
115}
116
117const NOTE = {
118  verifier: { passed: 'verified by a verifier', failed: 'failed its verifier' },
119  checks: { passed: 'verified by tests', failed: 'failed its tests' },
120} as const
121
122// A few plain words for a tooltip or a report line.
123export const verdictNote = (task: JudgedTask): string => {
124  if (task.status !== 'completed') return ''
125  if (task.verdict === undefined) return 'not checked yet'
126
127  return NOTE[task.verdict.by][task.verdict.state]
128}
129