SLOPSHOPPER

atlas

A map of the work beside the transcript: goal, current step, facts, glossary, pipeline stages with iris samples, and a trail of results and decisions.

panebandrowsguardcommandtoast
★ 4v0.1.0MITupdated 2026-10-19braininahat/brains-in-a-hat/atlas
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · atlas
│ ┃ atlas ✕ › fix the failing auth test and add an audit log call │ ┃ [ Map ] [ Pipeline ] [ Glossary ] [ Trail ] │ ┃ No map for this project yet. Claude starts ⏺ Read(src/auth.ts) │ ┃ one with atlas_update once the work has a ⎿ Read 6 lines │ ┃ goal and steps. ⏺ Update(src/auth.ts) │ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /atlas │ ⎿ atlas: atlas pane opened. │ │ atlas: no map for this project yet. [ Build map ] Not now ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
atlas: no map for this project yet. [ Build map ] Not now
Pane · atlas
[ Map ] [ Pipeline ] [ Glossary ] [ Trail ] No map for this project yet. Claude starts one with atlas_update once the work has a goal and steps.
README

atlas

A Claude Code mod that keeps a map of the work beside the transcript, so long sessions keep their way back to the top-level plan.

  • Plan tree with a focus path. Steps can grow sub-steps and detours; finishing one rolls up to its parent. The band above the prompt shows the breadcrumb (▶ 3 Training › 3.2 Learning-rate sweep), pinned facts and parked items.
  • Watchdog. After every turn a small model (Haiku) files the turn into the tree and refreshes a recap (where we are, what was learned, what is next). When work drifts, the band offers Return, Keep going and Park. /atlas recap runs a deeper recap on Sonnet.
  • Keeper. A background Sonnet agent (atlas:keeper, hidden from the main model) does the upkeep nobody should have to ask for: it renders missing pipeline-stage samples from real data into .claude/atlas/samples/, checks pinned facts against the repository, and fills the glossary. It starts on its own when there is upkeep to do, at most every ten minutes, and writes only inside .claude/atlas/. Renders shown with iris id stage-<name> link to their stage automatically.
  • Pane (/atlas): a route picture of the plan, Now and Recap cards, the plan tree, parked tangents, facts, pipeline stages with iris thumbnails (marked Seen once Claude has read the render), glossary and trail.
  • Cold start. In a project with history, /atlas init (or Build map in the band) digests every past transcript of the project (scripts/digest.py: what was said plus one line per tool call, in dated chunks), hands each chunk to an atlas:historian agent (Haiku, read-only) in parallel, and has the session's Claude build the map from those summaries, the project's memory notes, the conversation and the repository. Contradictions become trail notes starting "Open question:". Expect about a dollar for a project with weeks of history.
  • One map per project, many sessions. Every session in the project shares .claude/atlas/map.json; each change re-reads the file and merges, and each session picks up the others' changes within a few seconds. Writes take a lock (scripts/maplock.py; test: scripts/maplock.test.sh, 20 parallel writers) and replace the file in one rename, so no change is lost and no session reads half a file. Each session keeps its own place in the plan, and the Map tab shows a Sessions card with where the others are.
  • Each project's map lives in that project's repo, as .claude/atlas/map.json plus a readable map.md, so it travels with git clone and reads the same on any machine. Commit it like any file (check your .gitignore does not exclude .claude/). /atlas project <path> shows another project's map.

Needs: Claude Code ≥ 2.1.287, the iris mod, ImageMagick for the route picture.

Source 5 files
hooks/register.tsx 1270 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, ImageSource, Register, RenderChildren, Timer, ToolCallResult } from 'claude-code'
3
4import type { AtlasMap, AtlasNode, AtlasStage, AtlasTab, IrisImages } from '../types'
5import {
6  age,
7  applyPatch,
8  bandLine,
9  breadcrumb,
10  EMPTY,
11  focusLabel,
12  focusNodes,
13  isEmpty,
14  migrate,
15  RESEARCH_LIMIT,
16  toMarkdown,
17  type Patch,
18} from './model'
19import { hash, ROUTE_H, ROUTE_W, routeSvg } from './route'
20import { parseWatch, watchPrompt, WATCH_SYSTEM, type Turn } from './watch'
21
22const PANE = 'atlas'
23const TOOL = 'mcp__atlas__atlas_update'
24
25const mapAtom = atom({ plugin: 'atlas', key: 'map' } as const, EMPTY)
26const changes = atom({ plugin: 'atlas', key: 'changes' } as const, 0)
27const isStale = atom({ plugin: 'atlas', key: 'isStale' } as const, false)
28const tab = atom({ plugin: 'atlas', key: 'tab' } as const, 'map')
29const seen = atom({ plugin: 'atlas', key: 'seen' } as const, [])
30const isWatching = atom({ plugin: 'atlas', key: 'isWatching' } as const, false)
31const isInitDismissed = atom({ plugin: 'atlas', key: 'isInitDismissed' } as const, false)
32const isKeeping = atom({ plugin: 'atlas', key: 'isKeeping' } as const, false)
33// iris's state, read only: which figure the iris pane shows, and every figure's renders.
34const irisSel = atom({ plugin: 'iris', key: 'sel' } as const, null)
35const irisFigures = atom({ plugin: 'iris', key: 'figures' } as const, [])
36
37const RULES = `# atlas: keep the user oriented
38Long sessions drift: a big plan, a couple of steps done, then one step turns into its own search space and the session never returns to the top. The user may be a visual thinker who loses track of where things stand. The atlas map (goal, plan tree, facts, glossary, pipeline stages, parked tangents, trail) is shown beside the transcript and above the prompt. Keep it true with the atlas_update tool. The user is free to go anywhere; your job is to keep the books and the way back.
39- When work has a goal and more than one step, set the goal and steps.
40- When a step turns into its own problem, give it sub-steps (substeps with under: "3"). Steps are addressed by paths like "3.2".
41- When work leaves the step in focus, file it as a detour (with why). When a step or detour is finished, call done with a one-line outcome: atlas moves to the next step or back up to the parent. Then say where that leaves the top-level plan.
42- Park tangents (park) instead of chasing them, and offer the parked list when a branch finishes.
43- Record facts the user would otherwise ask about again: dataset and version, tensor shapes and dtypes, key paths, configs, checkpoints. Pin the two or three that matter most right now.
44- Do not coin abbreviations or nicknames. Write the full name. If a short form is unavoidable, add it to the glossary before its first use.
45- After any step that changes data or a figure, render a sample with the iris show tool, Read the PNG, and say what is visible before claiming success. Link the figure to its pipeline stage.
46- Add a trail item for each result, decision or dead end, in one line.
47- A watchdog also files each turn into the map automatically. If it filed something wrong, correct it.
48- Write visible text (titles, labels, captions) capitalised, never all lower case.`
49
50const MAP_SCHEMA = {
51  type: 'object',
52  properties: {
53    goal: { type: 'string', description: 'The overall goal, one line.' },
54    steps: { type: 'array', items: { type: 'string' }, description: 'Replace the top-level plan with these step titles.' },
55    current: { type: 'integer', minimum: 1, description: 'Top-level step now in progress (same as focus: "n").' },
56    focus: { type: 'string', description: 'Step path to put in focus, e.g. "3" or "3.2".' },
57    substeps: {
58      type: 'object',
59      description: 'Give a step its own sub-plan; the first sub-step takes focus.',
60      properties: { under: { type: 'string', description: 'Path of the parent step, e.g. "3".' }, steps: { type: 'array', items: { type: 'string' } } },
61      required: ['under', 'steps'],
62    },
63    detour: {
64      type: 'object',
65      description: 'File work that left the step in focus as a detour under it, and focus the detour.',
66      properties: { title: { type: 'string' }, why: { type: 'string' } },
67      required: ['title'],
68    },
69    done: {
70      type: 'object',
71      description: 'Finish a step (default: the one in focus); focus moves to its next sibling or back to its parent.',
72      properties: { path: { type: 'string' }, outcome: { type: 'string', description: 'One-line result.' } },
73    },
74    step_updates: {
75      type: 'array',
76      items: {
77        type: 'object',
78        properties: {
79          n: { type: 'integer', minimum: 1, description: 'Top-level step number.' },
80          path: { type: 'string', description: 'Or a path such as "3.2".' },
81          status: { type: 'string', enum: ['todo', 'doing', 'done', 'dropped'] },
82          outcome: { type: 'string', description: 'One-line result of the step.' },
83        },
84      },
85    },
86    facts: {
87      type: 'object',
88      additionalProperties: { type: 'string' },
89      description: 'Facts to set, e.g. {"Dataset": "UXTD v2", "Input shape": "(B, T, 1, 64, 128)"}. Empty string deletes.',
90    },
91    pin: { type: 'array', items: { type: 'string' }, description: 'Fact names to show above the prompt (replaces the list).' },
92    glossary: { type: 'object', additionalProperties: { type: 'string' }, description: 'Term to meaning. Empty string deletes.' },
93    stages: {
94      type: 'array',
95      description: 'Pipeline stages, upserted by name.',
96      items: {
97        type: 'object',
98        properties: {
99          name: { type: 'string' },
100          in: { type: 'string', description: 'Input shape or type.' },
101          out: { type: 'string', description: 'Output shape or type.' },
102          figure: { type: 'integer', description: 'iris figure number showing a sample of this stage.' },
103          sample: { type: 'string', description: 'A sample image already saved in the project, e.g. .claude/atlas/samples/crop.png.' },
104          note: { type: 'string' },
105        },
106        required: ['name'],
107      },
108    },
109    remove_stages: { type: 'array', items: { type: 'string' } },
110    park: { type: 'array', items: { type: 'string' }, description: 'Tangents to come back to later, one line each.' },
111    unpark: { type: 'array', items: { type: 'integer', minimum: 1 }, description: 'Parked items (1-based) picked up or dropped.' },
112    recap: {
113      type: 'object',
114      properties: { where: { type: 'string' }, learned: { type: 'string' }, next: { type: 'string' } },
115      required: ['where', 'learned', 'next'],
116    },
117    trail: {
118      type: 'array',
119      items: {
120        type: 'object',
121        properties: { kind: { type: 'string', enum: ['done', 'decision', 'deadend', 'note'] }, text: { type: 'string' } },
122        required: ['kind', 'text'],
123      },
124    },
125  },
126  additionalProperties: false,
127}
128
129const MAP_DESCRIPTION =
130  'Update the atlas map the user follows: goal, plan tree (sub-steps, detours, done with outcomes), facts, glossary, ' +
131  'pipeline stages with iris figures, parked tangents, recap, and a trail of results, decisions and dead ends. ' +
132  'Call it with no arguments to read the whole map.'
133
134const GREEN = '#59A14F'
135const ORANGE = '#F28E2B'
136const BLUE = '#4E79A7'
137const RED = '#E15759'
138const GREY = '#8C8C8C'
139const BROWN = '#9C755F'
140
141let projectRoot = '.'
142let sessionId = ''
143let sessionName = ''
144let fileMtime = 0
145const SESSION_MAX_AGE_MS = 14 * 86_400_000
146let workDir = '/tmp/atlas'
147let probedAt = 0
148// How the viewing terminal shows pictures (see IrisImages), kept outside $.state: a render may not set state.
149let images: IrisImages = 'unknown'
150let probedViewport = ''
151const dims = new Map<string, { w: number; h: number }>()
152// The last few main-thread turns, as the watchdog reads them. Rebuilt after a reload.
153const turns: Turn[] = []
154let pending: Turn = { prompt: '', actions: [], answer: '' }
155
156// Each project's map lives in its own repo, so it travels with git and reads the same on any machine.
157const mapFile = (root: string) => `${root}/.claude/atlas/map.json`
158const mapNotes = (root: string) => `${root}/.claude/atlas/map.md`
159
160/** The map as this session sees it: the shared plan, with this session's own position as the focus. */
161function withMyFocus(map: AtlasMap): AtlasMap {
162  const mine = map.sessions?.[sessionId]
163  return mine ? { ...map, focus: mine.focus } : map
164}
165
166const lockDir = (root: string) => `${root}/.claude/atlas/.lock`
167
168/** Runs scripts/maplock.py: the lock several sessions take before writing a project's map. */
169async function maplock($: EngineInterface, ...args: string[]): Promise<boolean> {
170  const out = await $.process.run(['python3', '-I', `${$.plugin.root}/scripts/maplock.py`, ...args], { timeoutMs: 10_000 }).catch(() => undefined)
171  return out?.exitCode === 0
172}
173
174/** Writes a file in one step (a temporary file renamed over it), so another session never reads half of it. */
175async function writeWhole($: EngineInterface, file: string, text: string) {
176  const tmp = `${file}.tmp-${sessionId || 'atlas'}`
177  await $.fs.write(tmp, text)
178  if (!(await maplock($, 'put', tmp, file))) await $.fs.write(file, text)
179}
180
181async function save($: EngineInterface, map: AtlasMap) {
182  const now = await $.clock.now()
183  const sessions = Object.fromEntries(Object.entries(map.sessions ?? {}).filter(([, v]) => now - v.t < SESSION_MAX_AGE_MS))
184  if (sessionId !== '') sessions[sessionId] = { name: sessionName || sessionId.slice(0, 8), focus: map.focus, t: now }
185  map = { ...map, sessions }
186  await update($, mapAtom, () => map)
187  const ignore = `${projectRoot}/.claude/atlas/.gitignore`
188  const ignored = (await $.fs.exists(ignore)) ? await $.fs.read(ignore) : ''
189  if (!ignored.includes('inbox/')) await $.fs.write(ignore, '# Written by atlas: the lock, the inbox and half-written files never belong in git.\n.lock/\ninbox/\n*.tmp-*\nmap.unreadable-*.json\n')
190  await writeWhole($, mapFile(projectRoot), `${JSON.stringify(map, null, 2)}\n`)
191  fileMtime = (await $.fs.stat(mapFile(projectRoot)).catch(() => undefined))?.mtimeMs ?? fileMtime
192  const notes = isEmpty(map) ? '' : toMarkdown(map, await read($, seen))
193  await writeWhole($, mapNotes(projectRoot), `<!-- Written by atlas; change it with /atlas or atlas_update. -->\n# atlas map\n\n${notes}\n`)
194}
195
196/** The newest map: re-read from disk when another session wrote it since we last did. */
197async function latest($: EngineInterface): Promise<AtlasMap> {
198  const st = await $.fs.stat(mapFile(projectRoot)).catch(() => undefined)
199  if (st && st.mtimeMs !== fileMtime) {
200    try {
201      const map = withMyFocus(migrate(JSON.parse(await $.fs.read(mapFile(projectRoot)))))
202      fileMtime = st.mtimeMs
203      await update($, mapAtom, () => map)
204      return map
205    } catch {
206      // A half-written file: keep what we have and try again next time.
207    }
208  }
209  return read($, mapAtom)
210}
211
212/**
213 * Every change goes through here, so changes from several sessions merge instead of overwriting:
214 * under the project's lock, read the file as it is now, apply the change, write it back.
215 * Keep `change` quick (no copying or rendering): other sessions wait while it runs.
216 */
217async function mutate($: EngineInterface, change: (map: AtlasMap) => AtlasMap): Promise<AtlasMap> {
218  const dir = lockDir(projectRoot)
219  // Without the lock (another writer stuck for 5 s), write anyway: atlas never blocks the session.
220  const isLocked = await maplock($, 'take', dir)
221  try {
222    fileMtime = -1
223    const next = change(await latest($))
224    await save($, next)
225    return next
226  } finally {
227    if (isLocked) await maplock($, 'drop', dir)
228  }
229}
230
231const inboxDir = (root: string) => `${root}/.claude/atlas/inbox`
232const PATCH_FIELDS = new Set(Object.keys(MAP_SCHEMA.properties))
233let isApplyingInbox = false
234
235/**
236 * Applies map changes queued as files in .claude/atlas/inbox/. A background agent's call to a plugin tool
237 * goes straight to the tool's server and skips this plugin's hooks, so the keeper writes files instead.
238 */
239async function applyInbox($: EngineInterface) {
240  if (isApplyingInbox) return
241  isApplyingInbox = true
242  try {
243    const dir = inboxDir(projectRoot)
244    const entries = await $.fs.list(dir).catch(() => [])
245    const files = entries.filter(f => f.kind === 'file' && f.name.endsWith('.json') && !f.name.startsWith('.')).sort((a, b) => a.name.localeCompare(b.name))
246    for (const f of files) {
247      const path = `${dir}/${f.name}`
248      let patch: Patch | undefined
249      try {
250        const raw: unknown = JSON.parse(await $.fs.read(path))
251        if (raw !== null && typeof raw === 'object' && !Array.isArray(raw) && Object.keys(raw).every(k => PATCH_FIELDS.has(k))) patch = raw as Patch
252      } catch {
253        // Not JSON: set aside below.
254      }
255      if (patch) {
256        const change = patch
257        const now = await $.clock.now()
258        await mutate($, m => applyPatch(m, change, now))
259        await $.process.run(['rm', '-f', path]).catch(() => undefined)
260      } else {
261        // Keep a bad file for a look, out of the way of the next pass.
262        await $.process.run(['mv', '-f', path, `${dir}/.rejected-${f.name}`]).catch(() => undefined)
263        $.ui.toast(`atlas: set aside ${f.name} from the inbox; it is not a map change.`)
264      }
265    }
266  } finally {
267    isApplyingInbox = false
268  }
269}
270
271/** This session's display name, from its transcript (custom title or agent name). */
272async function readSessionName($: EngineInterface, root: string, id: string): Promise<string> {
273  const file = `${(await $.env.get('HOME')) ?? ''}/.claude/projects/${root.replace(/[^A-Za-z0-9]/g, '-')}/${id}.jsonl`
274  const script = `grep -oE '"(customTitle|agentName)":"[^"]*"' "$1" 2>/dev/null | tail -1 | sed -E 's/.*":"//; s/"$//'`
275  const out = await $.process.run(['sh', '-c', script, 'atlas', file], { timeoutMs: 10_000 }).catch(() => undefined)
276  return out?.stdout.trim() ?? ''
277}
278
279/** A project's map: its repo file, else a map left in the old per-machine store (moved into the repo once). */
280async function load($: EngineInterface, root: string): Promise<AtlasMap> {
281  if (await $.fs.exists(mapFile(root))) {
282    for (let attempt = 0; attempt < 3; attempt++) {
283      try {
284        fileMtime = (await $.fs.stat(mapFile(root))).mtimeMs
285        return withMyFocus(migrate(JSON.parse(await $.fs.read(mapFile(root)))))
286      } catch {
287        await $.clock.sleep(300)
288      }
289    }
290    // Still unreadable (a git merge conflict, say): keep a copy so starting over loses nothing.
291    const copy = `${root}/.claude/atlas/map.unreadable-${await $.clock.now()}.json`
292    await $.process.run(['cp', mapFile(root), copy]).catch(() => undefined)
293    $.ui.toast(`atlas: map.json could not be read; kept a copy at ${copy} and started a new map.`)
294    return migrate(undefined)
295  }
296  const legacy = await $.store.get(`map:${root}`)
297  const map = migrate(legacy)
298  if (!isEmpty(map)) {
299    const previous = projectRoot
300    projectRoot = root
301    await save($, map)
302    projectRoot = previous
303  }
304  return map
305}
306
307const slug = (name: string) => name.toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'stage'
308const sampleRel = (name: string) => `.claude/atlas/samples/${slug(name)}.png`
309
310/** Copies each newly linked stage's iris render into the project, so the sample outlives the session. Returns stage name → sample path. */
311async function copySamples($: EngineInterface, linked: readonly { name: string; figure: number }[]): Promise<Map<string, string>> {
312  const copied = new Map<string, string>()
313  for (const { name, figure } of linked) {
314    const png = await irisPng($, figure)
315    if (!png) continue
316    const rel = sampleRel(name)
317    const out = await $.process.run(['sh', '-c', 'mkdir -p "$(dirname "$2")" && cp "$1" "$2"', 'atlas', png, `${projectRoot}/${rel}`])
318    if (out.exitCode === 0) {
319      dims.delete(`${projectRoot}/${rel}`)
320      copied.set(name, rel)
321    }
322  }
323  return copied
324}
325
326/** Points the copied stages at their stored samples. */
327function withSamples(map: AtlasMap, copied: ReadonlyMap<string, string>): AtlasMap {
328  if (copied.size === 0) return map
329  return { ...map, stages: map.stages.map(st => (copied.has(st.name) && st.figure !== undefined ? { ...st, sample: copied.get(st.name) } : st)) }
330}
331
332/** How to draw pictures for this viewer, as atlas's probe found; a new viewport may be a new viewer, so ask again. */
333function imageMode(viewport: { columns: number; rows: number } | undefined): IrisImages {
334  const vp = `${viewport?.columns}x${viewport?.rows}`
335  if (vp !== probedViewport) {
336    probedViewport = vp
337    images = 'unknown'
338  }
339  return images
340}
341
342/** An Image source for a PNG in the form this viewer reads. */
343async function sourceOf($: EngineInterface, png: string, how: IrisImages): Promise<ImageSource> {
344  return how === 'bytes' ? { png: (await $.fs.read(png, { as: 'bytes' })).base64 } : { file: png, format: 'png' }
345}
346
347/** Asks the renderer how an Image atlas drew came out (the session's environment is not its viewer's). */
348async function probeImages($: EngineInterface, key: string, source: ImageSource, columns: number, rows: number) {
349  const now = await $.clock.now()
350  if (now - probedAt < 2000) return
351  probedAt = now
352  await $.clock.sleep(300)
353  const r = await $.ui.blit({ requestId: PANE, key, source, columns, rows }).catch(() => ({ deny: 'failed' }))
354  const deny = r.deny ?? ''
355  const was = images
356  let next = was
357  if (deny === '') next = 'png' in source ? 'bytes' : 'file'
358  else if (/cannot read files/.test(deny)) next = 'bytes'
359  else if (/draws its alt|not drawn under a terminal/.test(deny) && !/in use/.test(deny)) next = 'none'
360  else if (/blit again/.test(deny)) probedAt = 0
361  if (next !== was) {
362    images = next
363    $.ui.invalidate('ui.render')
364  }
365}
366
367/** The iris PNG for figure `n`'s latest version and current page. */
368async function irisPng($: EngineInterface, n: number): Promise<string | undefined> {
369  const fig = (await read($, irisFigures)).find(f => f.n === n)
370  const version = fig?.versions[fig.versions.length - 1]
371  return fig && version ? version.png[String(fig.page)] : undefined
372}
373
374async function pngDims($: EngineInterface, png: string) {
375  let d = dims.get(png)
376  if (d === undefined) {
377    const out = await $.process.run(['magick', 'identify', '-format', '%w %h', `${png}[0]`], { timeoutMs: 10_000 })
378    const [w, h] = out.stdout.trim().split(/\s+/).map(Number)
379    d = { w: w || 1, h: h || 1 }
380    dims.set(png, d)
381  }
382  return d
383}
384
385async function remember<R extends ToolCallResult>($: EngineInterface, tool: string, query: string, run: () => Promise<R>): Promise<R> {
386  const map = await read($, mapAtom)
387  const before = map.research.find(r => r.query === query)
388  const result = await run()
389  if (result.deny !== undefined || result.isError) return result
390  const now = await $.clock.now()
391  const entry = { t: now, tool, query, summary: (result.text ?? '').replace(/\s+/g, ' ').slice(0, 300) }
392  await mutate($, m => ({ ...m, research: [...m.research.filter(r => r.query !== query), entry].slice(-RESEARCH_LIMIT) }))
393  if (!before) return result
394  return { ...result, context: [...(result.context ?? []), `atlas: the same lookup was made ${age(now, before.t)}: ${before.summary}`] }
395}
396
397/** The tool row's one line: what this call changed. */
398function summarize(p: Patch | undefined): string {
399  if (!p || Object.keys(p).length === 0) return 'Read the map'
400  const out: string[] = []
401  const n = (k: object | undefined) => (k ? Object.keys(k).length : 0)
402  if (p.goal !== undefined) out.push('Goal set')
403  if (p.steps) out.push(`${p.steps.length} steps`)
404  if (p.current !== undefined) out.push(`Step ${p.current} now`)
405  if (p.focus !== undefined) out.push(`Focus ${p.focus}`)
406  if (p.substeps) out.push(`${p.substeps.steps.length} sub-steps under ${p.substeps.under}`)
407  if (p.detour) out.push(`Detour: ${p.detour.title}`)
408  if (p.done) out.push(`Done${p.done.path ? ` ${p.done.path}` : ''}`)
409  if (p.step_updates?.length) out.push(`${p.step_updates.length} step updates`)
410  if (n(p.facts)) out.push(`${n(p.facts)} facts`)
411  if (p.pin) out.push(`${p.pin.length} pinned`)
412  if (n(p.glossary)) out.push(`${n(p.glossary)} terms`)
413  if (p.stages?.length) out.push(`${p.stages.length} stages`)
414  if (p.park?.length) out.push(`${p.park.length} parked`)
415  if (p.recap) out.push('Recap')
416  if (p.trail?.length) out.push(`${p.trail.length} trail items`)
417  return out.join(' · ') || 'Updated the map'
418}
419
420/** A route picture for one level of the plan, rendered once per distinct content. */
421// The desktop draws thumbnails as Svg; each embedded picture is kept small, as a pane redraw sends them all.
422const THUMB_LIMIT = 60_000
423const THUMB_TRIES = [
424  [700, 'png'],
425  [500, 'png'],
426  [700, 'jpg'],
427  [500, 'jpg'],
428  [350, 'jpg'],
429] as const
430const thumbDocs = new Map<string, string>()
431
432/** A sample image as a small SVG document for the desktop surface: the PNG embedded at the largest size that fits. */
433async function thumbSvg($: EngineInterface, png: string, w: number, h: number, mtimeMs: number): Promise<string | undefined> {
434  const cacheKey = `${png}:${mtimeMs}`
435  const known = thumbDocs.get(cacheKey)
436  if (known !== undefined) return known
437  for (const [width, kind] of THUMB_TRIES) {
438    const out = `${workDir}/thumb-${hash(cacheKey)}-${width}.${kind}`
439    const flatten = kind === 'jpg' ? ['-background', 'white', '-flatten', '-quality', '82'] : []
440    await $.process.run(['magick', png, '-resize', `${width}x>`, ...flatten, out], { timeoutMs: 20_000 }).catch(() => undefined)
441    const bytes = await $.fs.read(out, { as: 'bytes' }).catch(() => undefined)
442    if (bytes === undefined || bytes.base64.length + 300 > THUMB_LIMIT) continue
443    const ww = Math.min(width, w)
444    const hh = Math.max(1, Math.round((h * ww) / w))
445    const mime = kind === 'jpg' ? 'image/jpeg' : 'image/png'
446    const doc = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${ww} ${hh}" width="${ww}" height="${hh}"><image href="data:${mime};base64,${bytes.base64}" width="${ww}" height="${hh}"/></svg>`
447    thumbDocs.set(cacheKey, doc)
448    return doc
449  }
450  return undefined
451}
452
453async function routePng($: EngineInterface, steps: AtlasNode[], current: number, prefix: string): Promise<string> {
454  const svg = routeSvg(steps, current, prefix)
455  const png = `${workDir}/route-${hash(svg)}.png`
456  if (!(await $.fs.exists(png))) {
457    const src = png.replace(/\.png$/, '.svg')
458    await $.fs.write(src, svg)
459    const out = await $.process.run(['magick', '-density', '96', src, png], { timeoutMs: 20_000 })
460    if (out.exitCode !== 0) throw new Error(out.stderr)
461  }
462  return png
463}
464
465async function openPane($: EngineInterface) {
466  await $.ui.open({ id: PANE, title: 'atlas' })
467}
468
469/** After a turn: a small model files the turn into the map and refreshes the recap. */
470async function watch($: EngineInterface, model: string, recent: Turn[]) {
471  const map = await read($, mapAtom)
472  if (isEmpty(map) || recent.length === 0) return
473  await update($, isWatching, () => true)
474  try {
475    const reply = await $.model.complete({ model, system: WATCH_SYSTEM, prompt: watchPrompt(map, recent), maxTokens: 900 })
476    if (!reply.isAnswered) return
477    const patch = parseWatch(reply.text)
478    if (!patch) return
479    const now = await $.clock.now()
480    await mutate($, m => {
481      const next = applyPatch(m, patch, now)
482      if (patch.recap && next.recap) next.recap = { ...next.recap, by: model === 'haiku' ? 'Haiku' : 'Sonnet' }
483      return next
484    })
485  } finally {
486    await update($, isWatching, () => false)
487  }
488}
489
490const KEEPER_PROMPT = `You are the atlas keeper. You keep the project's atlas map true in the background so the user never has to ask for upkeep. The map is shown to a user who thinks visually and loses track of long sessions.
491
492Rules:
493- Read anything in the project. Write files only inside .claude/atlas/ (sample images). Never edit project code, configs or data; never run training, long jobs, installs, or git commands that change anything.
494- Finish within a few minutes of work. Do the tasks you are given and nothing else.
495- Change the map only by writing a JSON file into the inbox folder given in the task: one object with the same fields as the atlas_update tool, for example {"stages": [{"name": "Crop", "sample": ".claude/atlas/samples/crop.png", "note": "..."}]}. Write it under a name starting with a dot, then mv it to a name ending in .json, so it is never read half-written. The session applies it within a few seconds. (An atlas_update call from a background agent never reaches the map.) Use full names; capitalise the first word of every label.
496
497Rendering a stage sample:
498- Find one real example of the stage's output (the code, caches, run folders or result files tell you where). Draw it in the form that fits its shape: an image or frame, a signal trace (a few channels, a short window), a heat map for a matrix, a short table rendered as an image for scalars.
499- Use a short Python script run with: uv run --quiet --with matplotlib --with numpy python -I <script>. Put the script in /tmp, not in the project.
500- Save the PNG at the path given in the task, Read it, and only then write an inbox file with stages: [{name, sample: <path>, note: <one line saying what is visible>}].
501- If you cannot find real data within a few tries, say so in the note and stop; never draw made-up data.
502
503Checking facts: compare pinned facts and the newest facts with the repository (git log, result and registry files). Fix wrong ones with an inbox file setting facts, with a trail note saying what changed.
504
505Glossary: add any abbreviation, run-ID prefix or nickname from the recent turns that the glossary lacks.
506
507End with one short line saying what you did.`
508
509const KEEPER_EVERY_MS = 10 * 60_000
510const KEEPER_CHECK_TURNS = 15
511let keeperId: string | undefined
512let refreshTimer: Timer | undefined
513let lastKeeperAt = 0
514let turnsSinceKeeper = 0
515
516/** Upkeep the map needs now: stages without a sample, and a periodic fact and glossary check. */
517async function keeperTasks($: EngineInterface, map: AtlasMap, root: string): Promise<string[]> {
518  const tasks: string[] = []
519  const missing = []
520  // A stage needs a sample when it has none stored and its iris figure is gone (iris numbers do not outlive a session).
521  const found: string[] = []
522  for (const st of map.stages) {
523    if (st.sample !== undefined && (await $.fs.exists(`${root}/${st.sample}`))) continue
524    // A render already on disk (say, from a keeper whose map update was lost) is linked, not drawn again.
525    if (await $.fs.exists(`${root}/${sampleRel(st.name)}`)) {
526      found.push(st.name)
527      continue
528    }
529    if (st.figure !== undefined && (await irisPng($, st.figure))) continue
530    missing.push(st)
531  }
532  if (found.length > 0) {
533    await mutate($, m => ({ ...m, stages: m.stages.map(st => (found.includes(st.name) && st.sample === undefined ? { ...st, sample: sampleRel(st.name) } : st)) }))
534  }
535  for (const st of missing.slice(0, 2)) {
536    tasks.push(`Render a sample for the "${st.name}" stage${st.out ? ` (output ${st.out})` : ''} and save it at ${root}/${sampleRel(st.name)}.`)
537  }
538  if (turnsSinceKeeper >= KEEPER_CHECK_TURNS) tasks.push('Check the pinned facts against the repository, and add missing glossary entries from the recent turns.')
539  return tasks
540}
541
542async function startKeeper($: EngineInterface, tasks: string[]) {
543  if (tasks.length === 0 || (await read($, isKeeping))) return
544  const map = await read($, mapAtom)
545  const recent = turns.slice(-3).map((t, i) => `Turn ${i + 1}. User: ${t.prompt}\nActions: ${t.actions.join('; ')}\nAssistant: ${t.answer}`).join('\n\n')
546  const prompt = [
547    `Project root: ${projectRoot}`,
548    `Inbox folder: ${inboxDir(projectRoot)}`,
549    '',
550    'Tasks:',
551    ...tasks.map((t, i) => `${i + 1}. ${t}`),
552    '',
553    'The map now:',
554    toMarkdown(map, await read($, seen)),
555    '',
556    'Recent turns:',
557    recent || '(none)',
558  ].join('\n')
559  await update($, isKeeping, () => true)
560  lastKeeperAt = await $.clock.now()
561  turnsSinceKeeper = 0
562  try {
563    const r = await $.agent.spawn({ subagentType: 'atlas:keeper', prompt, description: 'atlas keeper' })
564    keeperId = r.agentId
565    if (!keeperId) await update($, isKeeping, () => false)
566  } catch {
567    await update($, isKeeping, () => false)
568  }
569}
570
571const HISTORIAN_PROMPT = `You are the atlas historian. You read one chunk of a project's past Claude Code conversations (the user's and Claude's words, plus one line per tool call; tool output is cut) and write down what happened, so the main session can rebuild the project's map without rereading everything.
572
573Read the whole chunk file you are given (in parts if it is long). Do not read anything else. Do not write or change any file.
574
575Reply with only these sections, dated where the chunk gives a time, in plain full words (no new abbreviations; explain any that the chunk uses):
576- Goals: what the user was trying to achieve, and any deadlines or targets.
577- Steps: the work done, in order, each with its result (numbers, scores, shapes, paths, run names exactly as written).
578- Decisions: what was chosen over what, and why.
579- Dead ends: what was tried and dropped, with the numbers that killed it.
580- Facts: datasets and versions, input and output shapes, splits, key paths, best scores and which run produced them.
581- Open threads: what was left unfinished, running, or waiting on the user at the end of the chunk.
582- Terms: abbreviations, run-ID prefixes and nicknames, with their meanings.
583- Conflicts: places where the conversation contradicts itself (say which came later).
584
585Keep it under 900 words. Leave out chat, tooling trouble and anything that did not change the project.`
586
587/** The cold-start instruction: rebuild the map from the conversation, past transcripts, memory and the repository. */
588function bootstrapText(history: { chunks: { file: string; from: string; to: string }[]; memory: string[]; transcripts: number } | undefined): string {
589  const past = history && history.chunks.length > 0
590    ? [
591        `2. Read the project's history. Its ${history.transcripts} past transcripts are digested into ${history.chunks.length} chunks, oldest first:`,
592        ...history.chunks.map((c, i) => `   ${i + 1}. ${c.file} (${c.from} to ${c.to})`),
593        '   Hand each chunk to its own atlas:historian agent (Agent tool, subagent_type "atlas:historian", prompt: the chunk path), several in one message so they run in parallel. Do not read the chunks yourself.',
594        ...(history.memory.length > 0 ? ['   Also read the project memory notes:', ...history.memory.map(m => `   - ${m}`)] : []),
595      ]
596    : ['2. There are no past transcripts for this project; skip to the repository.']
597  return [
598    'Build the atlas map for this project now (a cold start: the project already has history).',
599    '1. Start from what you already know in this conversation: the goal, what has been done, what is in progress, what was tried and dropped, and what is waiting on me.',
600    ...past,
601    '3. Check and fill gaps from the repository with a quick read: README or context docs, backlog or notes, recent git log and branches, run or result records, uncommitted changes. Do not read everything; aim for the shape of the project. Where history and the repository disagree, the newer source usually wins, but say so.',
602    '4. Write it with atlas_update, in a few calls. If the map already has content (call atlas_update with no arguments to see it), revise it instead of starting over: keep steps, sub-steps and outcomes that are right, correct the rest, and add only trail lines, facts and glossary entries that are not there yet.',
603    '   - goal (one line, with the target and deadline if there is one)',
604    '   - steps: the top-level plan with done and in-progress marked (step_updates with one-line outcomes for finished steps); then focus on where the work actually is now, with substeps for the branch the work drilled into, and detours for side work that left its step',
605    '   - facts: datasets and versions, input and output shapes and dtypes, splits, key paths, best scores and which run produced them, deadlines; pin the three that matter most right now',
606    '   - stages: the pipeline from raw data to the final artefact, with the shape or format in and out of each stage',
607    '   - glossary: every abbreviation, run-ID prefix and nickname in use, with its meaning',
608    '   - trail: decisions and dead ends, one line each, oldest first',
609    '   - park: open threads and tangents that are not the current focus',
610    '   - recap: where we are, the most useful thing learned, the next concrete step and how it leads back to the top-level plan',
611    '5. Where sources disagree and you cannot tell which is right, do not guess: add a trail note starting "Open question:" and list them for me at the end.',
612    'Then show me the plan, in a few lines, as a tree.',
613  ].join('\n')
614}
615
616/** Digest the project's past transcripts, then ask the main session to build the map from them. */
617async function startInit($: EngineInterface) {
618  const out = `${workDir}/history`
619  let history
620  try {
621    const r = await $.process.run(['python3', '-I', `${$.plugin.root}/scripts/digest.py`, projectRoot, out], { timeoutMs: 300_000 })
622    if (r.exitCode === 0) history = JSON.parse(await $.fs.read(`${out}/index.json`))
623  } catch {
624    // No history to read: build from the conversation and the repository alone.
625  }
626  await $.prompt.submit({ text: bootstrapText(history), asUser: true })
627}
628
629/** What the Look at it button sends. */
630function lookText(stage: AtlasStage): string {
631  const what = stage.sample ? `the sample at ${projectRoot}/${stage.sample}` : `iris figure #${stage.figure}`
632  return `Look at ${what} for the "${stage.name}" stage: Read the PNG and tell me what is actually visible and whether anything looks wrong.`
633}
634
635/** The instructions the drift buttons send, as if typed. */
636function returnText(map: AtlasMap): string {
637  const path = focusNodes(map)
638  const here = path[path.length - 1]
639  const parent = path[path.length - 2]
640  return `Wrap up "${here?.title ?? 'this detour'}": record what came of it with atlas_update (done, with a one-line outcome), then continue with ${parent ? `"${parent.title}"` : 'the top-level plan'} and tell me where that leaves the plan.`
641}
642
643function parkText(map: AtlasMap): string {
644  const here = focusNodes(map).pop()
645  return `Park "${here?.title ?? 'this tangent'}" with atlas_update (park, then done with outcome "Parked"), and return to the step it came from.`
646}
647
648export const register: Register = on => {
649  on('session.start', async ($, e, next) => {
650    projectRoot = await $.session.root()
651    sessionId = await $.session.id()
652    sessionName = await readSessionName($, projectRoot, sessionId)
653    workDir = `${(await $.env.get('TMPDIR')) ?? '/tmp'}/atlas-${sessionId}`
654    const loaded = await load($, projectRoot)
655    await update($, mapAtom, () => loaded)
656    await $.tool.register({ name: 'atlas_update', description: MAP_DESCRIPTION, inputSchema: MAP_SCHEMA, isDeferred: false })
657    await $.agent
658      .register({
659        name: 'keeper',
660        description: 'Keeps the atlas map true in the background: renders missing stage samples, checks facts, fills the glossary.',
661        prompt: KEEPER_PROMPT,
662        tools: ['Read', 'Glob', 'Grep', 'Bash'],
663        model: 'sonnet',
664        maxTurns: 30,
665        background: true,
666        omitClaudeMd: true,
667      })
668      .catch(() => undefined)
669    await $.agent
670      .register({
671        name: 'historian',
672        description: 'Summarises one chunk of a project\'s past transcripts for /atlas init: goals, steps with results, decisions, dead ends, facts, open threads, terms.',
673        prompt: HISTORIAN_PROMPT,
674        tools: ['Read'],
675        // Haiku kept every checked number on two cerebrov2 chunks and found more contradictions than Sonnet; the main session does the judgement.
676        model: 'haiku',
677        maxTurns: 12,
678        omitClaudeMd: true,
679      })
680      .catch(() => undefined)
681    await update($, isKeeping, () => false)
682    // Other sessions on this project write the same map; pick their changes up within a few seconds.
683    refreshTimer?.cancel()
684    refreshTimer = $.clock.every(3000, () => void latest($).then(() => applyInbox($)).catch(() => undefined))
685    await $.command.register({ name: 'atlas', description: 'Open the atlas map. /atlas init builds one for a project with history; /atlas reset clears it; /atlas recap runs a deep recap; /atlas project <path> switches project.', argumentHint: '[init | reset | recap | project <path>]' })
686
687    return next(e)
688  })
689
690  // The keeper is atlas's own: the main model never delegates to it.
691  on('agent.offer', { agent: 'atlas:keeper' }, () => ({ isOffered: false }))
692
693  // ---- the model's side ----
694
695  on('prompt.compose', async ($, e, next) => {
696    const result = await next(e)
697    return { sections: [...result.sections, { id: 'atlas:rules', text: RULES, scope: 'session' as const }] }
698  }).catch(($, e, next) => next(e))
699
700  on('prompt.submit', async ($, e, next) => {
701    const result = await next(e)
702    if (result.drop !== undefined) return result
703    pending = { prompt: result.text.slice(0, 700), actions: [], answer: '' }
704    const map = await read($, mapAtom)
705    const lines: string[] = []
706    if (isEmpty(map)) {
707      lines.push('atlas: no map yet for this project. When the work has a goal and steps, start one with atlas_update.')
708    } else {
709      const terms = Object.keys(map.glossary)
710      lines.push(`atlas: ${bandLine(map, false)}${terms.length > 0 ? ` · Glossary: ${terms.join(', ')}` : ''} · atlas_update with no arguments returns the full map.`)
711      if (map.recap) lines.push(`atlas recap: ${map.recap.where} Next: ${map.recap.next}`)
712      if (map.drift) lines.push(`atlas: drift note on the step in focus: ${map.drift.note}`)
713      const unsampled = map.stages.filter(st => st.figure === undefined && st.sample === undefined).map(st => st.name)
714      if (unsampled.length > 0) {
715        lines.push(`atlas: pipeline stages with no sample yet: ${unsampled.join(', ')}. When the work touches one of them, render one real example with iris and link it (stages[].figure).`)
716      }
717      if (await read($, isStale)) {
718        lines.push(`atlas: ${await read($, changes)} edits or commands since the map was last updated. Update the steps, facts and trail if they changed.`)
719      }
720    }
721    return { ...result, context: [...(result.context ?? []), ...lines] }
722  }).catch(($, e, next) => next(e))
723
724  on('tool.call', { tool: TOOL }, async ($, e) => {
725    const { tool: _t, tool_use_id: _id, ...patch } = e as unknown as Patch & { tool: string; tool_use_id: string }
726    if (Object.keys(patch).length === 0) return { result: toMarkdown(await latest($), await read($, seen)) }
727    const linked = (patch.stages ?? []).flatMap(st => (st.figure !== undefined ? [{ name: st.name, figure: st.figure }] : []))
728    const copied = await copySamples($, linked)
729    const now = await $.clock.now()
730    const next = await mutate($, m => withSamples(applyPatch(m, patch, now), copied))
731    await update($, changes, () => 0)
732    await update($, isStale, () => false)
733    return { result: `Map updated. Above the prompt: ${bandLine(next, false) || '(nothing pinned yet)'}` }
734  }).catch(() => ({ deny: 'atlas failed while updating the map.' }))
735
736  // Every main-thread call: note it for the watchdog, and count changes since the last map update.
737  on('tool.call', async ($, e, next) => {
738    const result = await next(e)
739    if (e.agentId !== undefined || result.deny !== undefined) return result
740    const args = e as unknown as Record<string, unknown>
741    const detail = [args.file_path, args.command, args.path, args.pattern, args.title, args.query, args.url].find(v => typeof v === 'string') as string | undefined
742    if (pending.actions.length < 30) pending.actions.push(`${e.tool}${detail ? ` ${detail.slice(0, 90)}` : ''}`)
743    if (!result.isReadOnly && (e.tool === 'Edit' || e.tool === 'Write' || e.tool === 'NotebookEdit' || e.tool === 'Bash')) {
744      await update($, changes, n => n + 1)
745    }
746    return result
747  })
748
749  // A Read of an iris render means Claude looked at that figure.
750  on('tool.call', { tool: 'Read' }, async ($, e, next) => {
751    const result = await next(e)
752    if (result.deny !== undefined) return result
753    const m = /\/iris-[^/]+\/(\d+)\/v\d+-p\d+\.png$/.exec(e.file_path)
754    const n = m ? Number(m[1]) : undefined
755    if (n !== undefined) await update($, seen, list => (list.includes(n) ? list : [...list, n]))
756    // Looking at a stage's render, or at its stored sample, marks that stage seen in the saved map.
757    const map = await latest($)
758    const now = await $.clock.now()
759    let isChanged = false
760    const stages = map.stages.map(st => {
761      const isThis =
762        (n !== undefined && st.figure === n) || e.file_path === `${projectRoot}/${st.sample ?? sampleRel(st.name)}`
763      if (!isThis) return st
764      isChanged = true
765      return { ...st, seenAt: now }
766    })
767    if (isChanged) {
768      const hit = new Set(stages.filter(st => st.seenAt === now).map(st => st.name))
769      await mutate($, m => ({ ...m, stages: m.stages.map(st => (hit.has(st.name) ? { ...st, seenAt: now } : st)) }))
770    }
771    return result
772  })
773
774  // A render shown with id "stage-<name>" (or titled like a stage) becomes that stage's sample at once.
775  on('tool.call', { tool: 'mcp__iris__show' }, async ($, e, next) => {
776    const result = await next(e)
777    if (result.deny !== undefined || result.isError) return result
778    const text = typeof result.result === 'string' ? result.result : (result.text ?? '')
779    const m = /as #(\d+) /.exec(text)
780    const args = e as unknown as { id?: string; title?: string }
781    if (!m) return result
782    const map = await latest($)
783    const stage = map.stages.find(
784      st => args.id === `stage-${st.name}` || args.id === `stage-${slug(st.name)}` || (args.title ?? '').toLowerCase() === st.name.toLowerCase(),
785    )
786    if (!stage) return result
787    const now = await $.clock.now()
788    const figure = Number(m[1])
789    const copied = await copySamples($, [{ name: stage.name, figure }])
790    await mutate($, mm => withSamples(applyPatch(mm, { stages: [{ name: stage.name, figure }] }, now), copied))
791    return result
792  })
793
794  // Research cache: remember lookups, and say so when one repeats.
795  on('tool.call', { tool: 'WebSearch' }, ($, e, next) => remember($, e.tool, e.query, () => next(e)))
796  on('tool.call', { tool: 'WebFetch' }, ($, e, next) => remember($, e.tool, `${e.url} ${e.prompt}`, () => next(e)))
797
798  on('turn.complete', async ($, e, next) => {
799    if (e.agentId !== undefined && e.agentId === keeperId) {
800      keeperId = undefined
801      await update($, isKeeping, () => false)
802      const line = e.answer.trim().split('\n').pop()?.slice(0, 160) ?? ''
803      if (line !== '') $.ui.toast(`atlas keeper: ${line}`)
804      return next(e)
805    }
806    if (e.agentId === undefined && !e.isAborted) {
807      turnsSinceKeeper += 1
808      if ((await read($, changes)) > 0 && !isEmpty(await read($, mapAtom))) await update($, isStale, () => true)
809      turns.push({ ...pending, answer: e.answer.slice(0, 900) })
810      if (turns.length > 12) turns.shift()
811      pending = { prompt: '', actions: [], answer: '' }
812      void watch($, 'haiku', turns.slice(-2)).catch(() => undefined)
813      const map = await read($, mapAtom)
814      if (!isEmpty(map) && (await $.clock.now()) - lastKeeperAt > KEEPER_EVERY_MS) {
815        void keeperTasks($, map, projectRoot).then(tasks => startKeeper($, tasks)).catch(() => undefined)
816      }
817    }
818    return next(e)
819  })
820
821  // ---- the user's side ----
822
823  on('command.run', { command: 'atlas' }, async ($, e) => {
824    const arg = e.args.trim()
825    if (arg === 'reset') {
826      await save($, migrate(undefined))
827      await update($, changes, () => 0)
828      await update($, isStale, () => false)
829      return { text: 'atlas: this project\'s map is cleared.' }
830    }
831    if (arg === 'init') {
832      void startInit($)
833      await openPane($)
834      return { text: 'atlas: building this project\'s map from past transcripts, memory notes, the conversation and the repository.' }
835    }
836    if (arg.startsWith('project')) {
837      const target = arg.slice('project'.length).trim()
838      const root = target === '' ? await $.session.root() : target.replace(/\/+$/, '').replace(/^~(?=\/)/, (await $.env.get('HOME')) ?? '~')
839      const loaded = await load($, root)
840      projectRoot = root
841      await update($, mapAtom, () => loaded)
842      await update($, changes, () => 0)
843      await update($, isStale, () => false)
844      turns.length = 0
845      await openPane($)
846      return { text: `atlas: now showing the map for ${root}.` }
847    }
848    if (arg === 'recap') {
849      void watch($, 'sonnet', turns.slice()).catch(() => undefined)
850      await openPane($)
851      return { text: 'atlas: deep recap running on Sonnet; it appears in the Recap card.' }
852    }
853    await openPane($)
854    return { text: 'atlas pane opened.' }
855  })
856
857  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
858    const map = await read($, mapAtom)
859    if (e.props.hasSurvey) return next(e)
860    if (isEmpty(map)) {
861      if (await read($, isInitDismissed)) return next(e)
862      const { Box, Text, Button } = $.ui.resolve(e)
863      return (
864        <Box flexDirection="row" columnGap={1}>
865          <Text dimColor>atlas: no map for this project yet.</Text>
866          <Button key="atlas-init" label="Build map" onPress={() => void startInit($)} />
867          <Button key="atlas-later" plain dimColor label="Not now" onPress={() => update($, isInitDismissed, () => true)} />
868        </Box>
869      )
870    }
871    const { Box, Text, Button } = $.ui.resolve(e)
872    const sel = await read($, irisSel)
873    const stale = await read($, isStale)
874    const watching = await read($, isWatching)
875    return (
876      <Box flexDirection="column">
877        <Box flexDirection="row" columnGap={1}>
878          <Text wrap="truncate-end">{bandLine(map, stale, sel?.n)}</Text>
879          {watching && <Text dimColor>◷</Text>}
880          {(await read($, isKeeping)) && <Text dimColor>⚙ Keeper</Text>}
881          <Button key="open-atlas" plain dimColor label="Map" onPress={() => openPane($)} />
882        </Box>
883        {map.drift && (
884          <Box flexDirection="row" columnGap={1}>
885            <Text color={RED} wrap="truncate-end">↯ {map.drift.note}</Text>
886            <Button key="drift-return" label="Return" onPress={() => $.prompt.submit({ text: returnText(map), asUser: true })} />
887            <Button
888              key="drift-keep"
889              label="Keep going"
890              onPress={async () => {
891                await mutate($, m => {
892                  const nodeId = m.drift?.nodeId
893                  return { ...m, drift: null, keepGoing: nodeId ? [...m.keepGoing, nodeId] : m.keepGoing }
894                })
895              }}
896            />
897            <Button key="drift-park" label="Park" onPress={() => $.prompt.submit({ text: parkText(map), asUser: true })} />
898          </Box>
899        )}
900      </Box>
901    )
902  })
903
904  on('ui.render', { component: 'ToolUse' }, async ($, e, next) => {
905    if (e.props.tool !== TOOL) return next(e)
906    const { Box, Text } = $.ui.resolve(e)
907    return (
908      <Box flexDirection="row">
909        <Text bold color={ORANGE}>atlas</Text>
910        <Text dimColor> · {summarize(e.props.input as Patch)}</Text>
911      </Box>
912    )
913  }).catch(($, e, next) => next(e))
914
915  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
916    const { Box, Text, Button } = $.ui.resolve(e)
917    const map = await read($, mapAtom)
918    const current = await read($, tab)
919    const looked = await read($, seen)
920    const width = Math.max(24, e.props.bodyColumns)
921    const inner = width - 4
922
923    const tabs: [AtlasTab, string, string][] = [
924      ['map', 'm', 'Map'],
925      ['pipeline', 'p', 'Pipeline'],
926      ['glossary', 'g', 'Glossary'],
927      ['trail', 't', 'Trail'],
928    ]
929    const header = (
930      <Box flexDirection="row" columnGap={1}>
931        {tabs.map(([id, key, label]) => (
932          <Button key={`tab-${id}`} hotkey={key} label={label} variant={id === current ? 'primary' : 'secondary'} onPress={() => update($, tab, () => id)} />
933        ))}
934      </Box>
935    )
936
937    if (isEmpty(map)) {
938      return (
939        <Box flexDirection="column">
940          {header}
941          <Text dimColor>No map for this project yet. Claude starts one with atlas_update once the work has a goal and steps.</Text>
942        </Box>
943      )
944    }
945
946    const chip = (label: string, colour: string) => (
947      <Text backgroundColor={colour} color="#FFFFFF" bold>
948        {` ${label} `}
949      </Text>
950    )
951    const card = (key: string, title: string, colour: string, children: RenderChildren) => (
952      <Box key={key} flexDirection="column" borderStyle="round" borderColor={colour} paddingX={1} width={width}>
953        <Text bold color={colour}>
954          {title}
955        </Text>
956        {children}
957      </Box>
958    )
959    const table = (rows: [string, string, boolean?][], keyPrefix: string) => {
960      const kw = Math.min(24, Math.max(...rows.map(([k]) => k.length)) + 2)
961      return rows.map(([k, v, isMarked]) => (
962        <Box key={`${keyPrefix}-${k}`} flexDirection="row">
963          <Box width={kw} flexShrink={0}>
964            <Text bold>{k}</Text>
965          </Box>
966          <Text color={isMarked ? ORANGE : undefined}>{v}</Text>
967        </Box>
968      ))
969    }
970    const how = e.surface === 'terminal' ? imageMode(e.viewport) : 'none'
971    const routeImage = async (key: string, steps: AtlasNode[], at: number, prefix: string) => {
972      if (steps.length === 0) return null
973      if (e.surface === 'desktop') {
974        const { Svg } = $.ui.resolve(e)
975        return <Svg key={key} source={routeSvg(steps, at, prefix)} alt="Plan route" />
976      }
977      if (how === 'none' || e.surface !== 'terminal') return null
978      const png = await routePng($, steps, at, prefix).catch(() => undefined)
979      if (!png) return null
980      const { Image } = $.ui.resolve(e)
981      const cols = Math.min(width, 255)
982      const rows = Math.max(3, Math.round((cols * ROUTE_H) / ROUTE_W / 2))
983      const id = `${key}-${png.slice(-14)}-${cols}x${rows}`
984      const source = await sourceOf($, png, how)
985      void probeImages($, id, source, cols, rows).catch(() => undefined)
986      return <Image key={id} source={source} columns={cols} rows={rows} alt="Plan route" />
987    }
988    const now = await $.clock.now()
989
990    let body
991    if (current === 'map') {
992      const path = focusNodes(map)
993      const here = path[path.length - 1]
994      const top = path[0]
995      const topRoute = await routeImage('route-top', map.plan, top ? map.plan.indexOf(top) : -1, '')
996      let branchRoute = null
997      if (path.length >= 2) {
998        const parent = path[path.length - 2]
999        const siblings = parent?.children ?? []
1000        const label = focusLabel(map).split('.').slice(0, -1).join('.')
1001        branchRoute = (
1002          <Box flexDirection="column">
1003            <Text dimColor>Inside {label} {parent?.title}</Text>
1004            {await routeImage('route-branch', siblings, here ? siblings.indexOf(here) : -1, `${label}.`)}
1005          </Box>
1006        )
1007      }
1008      const pinned = map.pinned.filter(k => map.facts[k]).map(k => [k, map.facts[k]?.value ?? ''] as [string, string])
1009      const others = Object.entries(map.facts)
1010        .filter(([k]) => !map.pinned.includes(k))
1011        .map(([k, f]) => {
1012          const isRecent = f.was !== undefined && now - f.changedAt < 10 * 60_000
1013          return [k, isRecent ? `${f.value}  (was ${f.was})` : f.value, isRecent] as [string, string, boolean]
1014        })
1015      const treeRows: RenderChildren[] = []
1016      const walk = (nodes: AtlasNode[], prefix: string, depth: number) => {
1017        nodes.forEach((n, i) => {
1018          const p = prefix === '' ? String(i + 1) : `${prefix}.${i + 1}`
1019          const isHere = n === here
1020          treeRows.push(
1021            <Box key={`node-${n.id}`} flexDirection="row" columnGap={1}>
1022              <Box flexGrow={1}>
1023                <Text bold={isHere} dimColor={n.status === 'todo' || n.status === 'dropped'} color={isHere ? ORANGE : undefined}>
1024                  {'  '.repeat(depth)}
1025                  {n.kind === 'detour' ? '↪ ' : ''}
1026                  {p}. {n.title}
1027                  {n.outcome ? <Text dimColor> · {n.outcome}</Text> : ''}
1028                </Text>
1029              </Box>
1030              {n.status === 'done' && chip('Done', GREEN)}
1031              {isHere && chip('Now', ORANGE)}
1032              {n.status === 'doing' && !isHere && chip('Open', BLUE)}
1033              {n.status === 'dropped' && chip('Dropped', GREY)}
1034            </Box>,
1035          )
1036          // Finished branches fold away; open ones stay expanded.
1037          if (n.status !== 'done' || path.includes(n)) walk(n.children, p, depth + 1)
1038        })
1039      }
1040      walk(map.plan, '', 0)
1041      const recap = map.recap
1042      // Other sessions working on this project, and where each one is in the shared plan.
1043      const otherSessions = Object.entries(map.sessions ?? {})
1044        .filter(([id]) => id !== sessionId)
1045        .sort((x, y) => y[1].t - x[1].t)
1046      body = (
1047        <Box flexDirection="column">
1048          {map.goal !== '' && <Text bold>{map.goal}</Text>}
1049          {topRoute}
1050          {branchRoute}
1051          {map.drift &&
1052            card(
1053              'drift',
1054              '↯ Drifting?',
1055              RED,
1056              <Box flexDirection="column">
1057                <Text>{map.drift.note}</Text>
1058                <Box flexDirection="row" columnGap={1}>
1059                  <Button key="pane-return" label="Return" onPress={() => $.prompt.submit({ text: returnText(map), asUser: true })} />
1060                  <Button
1061                    key="pane-keep"
1062                    label="Keep going"
1063                    onPress={async () => {
1064                      await mutate($, m => {
1065                        const nodeId = m.drift?.nodeId
1066                        return { ...m, drift: null, keepGoing: nodeId ? [...m.keepGoing, nodeId] : m.keepGoing }
1067                      })
1068                    }}
1069                  />
1070                  <Button key="pane-park" label="Park" onPress={() => $.prompt.submit({ text: parkText(map), asUser: true })} />
1071                </Box>
1072              </Box>,
1073            )}
1074          {here &&
1075            card(
1076              'now',
1077              `Now · ${breadcrumb(map)}`,
1078              ORANGE,
1079              <Box flexDirection="column">
1080                <Text bold>{here.title}</Text>
1081                {here.why && <Text dimColor>Why: {here.why}</Text>}
1082              </Box>,
1083            )}
1084          {otherSessions.length > 0 &&
1085            card(
1086              'sessions',
1087              `Sessions (${otherSessions.length + 1})`,
1088              GREY,
1089              otherSessions.map(([id, ss]) => (
1090                <Text key={`session-${id}`}>
1091                  <Text bold>{ss.name}</Text> · {breadcrumb({ ...map, focus: ss.focus }) || 'No step'} <Text dimColor>· {age(now, ss.t)}</Text>
1092                </Text>
1093              )),
1094            )}
1095          {recap &&
1096            card(
1097              'recap',
1098              'Recap',
1099              BLUE,
1100              <Box flexDirection="column">
1101                <Text>
1102                  <Text bold>Where we are </Text>
1103                  {recap.where}
1104                </Text>
1105                <Text>
1106                  <Text bold>Learned </Text>
1107                  {recap.learned}
1108                </Text>
1109                <Text>
1110                  <Text bold color={ORANGE}>Next </Text>
1111                  {recap.next}
1112                </Text>
1113                <Box flexDirection="row" columnGap={1}>
1114                  <Text dimColor>
1115                    {recap.by}, {age(now, recap.t)}
1116                  </Text>
1117                  <Button key="deep-recap" plain dimColor label="Deep recap" onPress={() => void watch($, 'sonnet', turns.slice()).catch(() => undefined)} />
1118                </Box>
1119              </Box>,
1120            )}
1121          {map.plan.length > 0 && card('plan', 'Plan', BLUE, treeRows)}
1122          {map.parked.length > 0 &&
1123            card(
1124              'parked',
1125              `Parked (${map.parked.length})`,
1126              BROWN,
1127              map.parked.map((p, i) => (
1128                <Text key={`parked-${i}`}>
1129                  {i + 1}. {p.text} <Text dimColor>· from {p.from}, {age(now, p.t)}</Text>
1130                </Text>
1131              )),
1132            )}
1133          {pinned.length > 0 && card('pinned', 'Pinned', ORANGE, table(pinned, 'pin'))}
1134          {others.length > 0 && card('facts', 'Facts', GREY, table(others, 'fact'))}
1135        </Box>
1136      )
1137    } else if (current === 'pipeline') {
1138      const cards = []
1139      for (const [i, s] of map.stages.entries()) {
1140        const hasSample = s.figure !== undefined || s.sample !== undefined
1141        const isSeen = s.seenAt !== undefined || (s.figure !== undefined && looked.includes(s.figure))
1142        const colour = !hasSample ? GREY : isSeen ? GREEN : ORANGE
1143        let thumb = null
1144        if (hasSample && e.surface === 'desktop') {
1145          const stored = s.sample ? `${projectRoot}/${s.sample}` : undefined
1146          const png = stored && (await $.fs.exists(stored)) ? stored : s.figure !== undefined ? await irisPng($, s.figure) : undefined
1147          const st = png ? await $.fs.stat(png).catch(() => undefined) : undefined
1148          const d = png ? await pngDims($, png).catch(() => undefined) : undefined
1149          const doc = png && d && st ? await thumbSvg($, png, d.w, d.h, st.mtimeMs) : undefined
1150          if (doc) {
1151            const { Svg } = $.ui.resolve(e)
1152            thumb = <Svg key={`thumb-${i}`} source={doc} alt={`${s.name} sample`} />
1153          }
1154        } else if (how === 'none' && hasSample && e.surface === 'terminal') {
1155          thumb = <Text dimColor>This terminal shows no pictures; Look at it describes the sample, or open {s.sample ?? `figure #${s.figure}`}.</Text>
1156        } else if (hasSample && e.surface === 'terminal') {
1157          const stored = s.sample ? `${projectRoot}/${s.sample}` : undefined
1158          const png = stored && (await $.fs.exists(stored)) ? stored : s.figure !== undefined ? await irisPng($, s.figure) : undefined
1159          const d = png ? await pngDims($, png).catch(() => undefined) : undefined
1160          if (png && d) {
1161            const { Image } = $.ui.resolve(e)
1162            let cols = Math.min(inner, 255)
1163            let rows = Math.max(1, Math.round((cols * d.h) / d.w / 2))
1164            if (rows > 14) {
1165              rows = 14
1166              cols = Math.max(1, Math.round((rows * 2 * d.w) / d.h))
1167            }
1168            const id = `thumb-${i}-${cols}x${rows}`
1169            const source = await sourceOf($, png, how)
1170            void probeImages($, id, source, cols, rows).catch(() => undefined)
1171            thumb = <Image key={id} source={source} columns={cols} rows={rows} alt={`${s.name} sample`} />
1172          }
1173        }
1174        if (i > 0) cards.push(<Text key={`arrow-${i}`} color={GREY}>{'  ↓'}</Text>)
1175        cards.push(
1176          card(
1177            `stage-${i}`,
1178            `${i + 1}. ${s.name}`,
1179            colour,
1180            <Box flexDirection="column">
1181              <Box flexDirection="row" columnGap={1}>
1182                {!hasSample ? chip('No sample', GREY) : isSeen ? chip('Seen ✓', GREEN) : chip('Not looked at', ORANGE)}
1183                {s.sample !== undefined ? <Text dimColor>{s.sample}</Text> : s.figure !== undefined && <Text dimColor>Figure #{s.figure}</Text>}
1184              </Box>
1185              {(s.in || s.out) && (
1186                <Text>
1187                  <Text dimColor>In </Text>
1188                  {s.in ?? '?'}
1189                  <Text dimColor>  →  Out </Text>
1190                  {s.out ?? '?'}
1191                </Text>
1192              )}
1193              {s.note && <Text dimColor>{s.note}</Text>}
1194              {!hasSample && (
1195                <Button
1196                  key={`sample-${i}`}
1197                  label="Generate sample"
1198                  onPress={() => startKeeper($, [`Render a sample for the "${s.name}" stage${s.out ? ` (output ${s.out})` : ''} and save it at ${projectRoot}/${sampleRel(s.name)}.`])}
1199                />
1200              )}
hooks/model.ts 365 lines
1// The map's pure logic: the plan tree and its focus, patches, the band line, and text views.
2
3import type { AtlasMap, AtlasNode, AtlasStage, AtlasStepStatus, AtlasTrailKind } from '../types'
4
5export const EMPTY: AtlasMap = {
6  goal: '',
7  plan: [],
8  focus: [],
9  nextId: 1,
10  facts: {},
11  pinned: [],
12  glossary: {},
13  stages: [],
14  trail: [],
15  research: [],
16  parked: [],
17  recap: null,
18  drift: null,
19  keepGoing: [],
20}
21
22export const TRAIL_LIMIT = 300
23export const RESEARCH_LIMIT = 100
24
25export type Patch = {
26  goal?: string
27  /** Replaces the top-level plan; the first step takes focus. */
28  steps?: string[]
29  /** 1-based top-level step now in progress (shorthand for focus: "n"). */
30  current?: number
31  /** Step path such as "3" or "3.2" to put in focus. */
32  focus?: string
33  /** Replaces the sub-steps of the step at `under` (a path); the first takes focus. */
34  substeps?: { under: string; steps: string[] }
35  /** Files a detour under the step in focus and focuses it. */
36  detour?: { title: string; why?: string }
37  /** Marks a step done (default: the one in focus) and moves on to its next sibling or back to its parent. */
38  done?: { path?: string; outcome?: string }
39  /** Updates by path ("3.2") or top-level number. */
40  step_updates?: { n?: number; path?: string; status?: AtlasStepStatus; outcome?: string }[]
41  facts?: Record<string, string>
42  pin?: string[]
43  glossary?: Record<string, string>
44  stages?: AtlasStage[]
45  remove_stages?: string[]
46  trail?: { kind: AtlasTrailKind; text: string }[]
47  /** Tangents to come back to later. */
48  park?: string[]
49  /** 1-based parked items to remove (picked up or dropped). */
50  unpark?: number[]
51  recap?: { where: string; learned: string; next: string }
52  /** A drift note for the step in focus; null clears it. */
53  drift?: { note: string } | null
54}
55
56// ---------- tree helpers ----------
57
58export function clone(map: AtlasMap): AtlasMap {
59  return JSON.parse(JSON.stringify(map)) as AtlasMap
60}
61
62/** Nodes from the top level down to the node at `path` ("3.2" -> [step 3, its step 2]). */
63export function nodesAtPath(plan: AtlasNode[], path: string): AtlasNode[] | undefined {
64  const parts = path.split('.').map(p => Number(p) - 1)
65  const out: AtlasNode[] = []
66  let level = plan
67  for (const i of parts) {
68    const node = level[i]
69    if (!node || !Number.isInteger(i)) return undefined
70    out.push(node)
71    level = node.children
72  }
73  return out.length > 0 ? out : undefined
74}
75
76/** Nodes along the focus path; stops at the first id that no longer exists. */
77export function focusNodes(map: AtlasMap): AtlasNode[] {
78  const out: AtlasNode[] = []
79  let level = map.plan
80  for (const id of map.focus) {
81    const node = level.find(n => n.id === id)
82    if (!node) break
83    out.push(node)
84    level = node.children
85  }
86  return out
87}
88
89/** "3.2"-style label of the focus path. */
90export function focusLabel(map: AtlasMap): string {
91  const labels: number[] = []
92  let level = map.plan
93  for (const id of map.focus) {
94    const i = level.findIndex(n => n.id === id)
95    if (i < 0) break
96    labels.push(i + 1)
97    level = level[i]?.children ?? []
98  }
99  return labels.join('.')
100}
101
102/** The siblings list that holds the last focus node, and its index there. */
103function focusSlot(map: AtlasMap): { siblings: AtlasNode[]; index: number } | undefined {
104  let level = map.plan
105  let slot: { siblings: AtlasNode[]; index: number } | undefined
106  for (const id of map.focus) {
107    const i = level.findIndex(n => n.id === id)
108    if (i < 0) break
109    slot = { siblings: level, index: i }
110    level = level[i]?.children ?? []
111  }
112  return slot
113}
114
115function newNode(map: AtlasMap, title: string, extra: Partial<AtlasNode> = {}): AtlasNode {
116  return { id: `s${map.nextId++}`, title: title.trim(), status: 'todo', children: [], ...extra }
117}
118
119function setFocusPath(map: AtlasMap, nodes: AtlasNode[]) {
120  map.focus = nodes.map(n => n.id)
121  for (const n of nodes) if (n.status === 'todo') n.status = 'doing'
122}
123
124export function isEmpty(map: AtlasMap): boolean {
125  return map.goal === '' && map.plan.length === 0 && Object.keys(map.facts).length === 0 && map.stages.length === 0
126}
127
128/** Accepts maps saved before the plan became a tree (flat steps + current). */
129export function migrate(raw: unknown): AtlasMap {
130  const m = { ...clone(EMPTY), ...((raw ?? {}) as Partial<AtlasMap>) } as AtlasMap & {
131    steps?: { title: string; status: AtlasStepStatus; outcome?: string }[]
132    current?: number
133  }
134  if (m.steps && (!m.plan || m.plan.length === 0)) {
135    m.plan = m.steps.map(s => newNode(m, s.title, { status: s.status, outcome: s.outcome }))
136    const cur = m.plan[m.current ?? -1]
137    m.focus = cur ? [cur.id] : []
138  }
139  delete m.steps
140  delete m.current
141  return m
142}
143
144// ---------- patches ----------
145
146export function applyPatch(map: AtlasMap, patch: Patch, now: number): AtlasMap {
147  const next = clone(map)
148  const trail = (kind: AtlasTrailKind, text: string) => next.trail.push({ t: now, kind, text })
149
150  if (patch.goal !== undefined) next.goal = patch.goal.trim()
151  if (patch.steps !== undefined) {
152    next.plan = patch.steps.map(t => newNode(next, t))
153    next.focus = []
154    if (next.plan[0]) setFocusPath(next, [next.plan[0]])
155  }
156  if (patch.current !== undefined) patch = { ...patch, focus: String(patch.current) }
157  if (patch.substeps !== undefined) {
158    const nodes = nodesAtPath(next.plan, patch.substeps.under)
159    const parent = nodes?.[nodes.length - 1]
160    if (nodes && parent) {
161      parent.children = patch.substeps.steps.map(t => newNode(next, t))
162      const first = parent.children[0]
163      if (first) setFocusPath(next, [...nodes, first])
164    }
165  }
166  if (patch.focus !== undefined) {
167    const nodes = nodesAtPath(next.plan, patch.focus)
168    if (nodes) {
169      // Moving along one level finishes the step left behind, as moving to the next station does.
170      const before = focusNodes(next)
171      const left = before[nodes.length - 1]
172      const target = nodes[nodes.length - 1]
173      if (left && target && left !== target && left.status === 'doing' && before.length >= nodes.length) {
174        const siblings = nodes.length === 1 ? next.plan : nodes[nodes.length - 2]?.children ?? []
175        if (siblings.indexOf(left) < siblings.indexOf(target)) left.status = 'done'
176      }
177      setFocusPath(next, nodes)
178    }
179  }
180  if (patch.detour !== undefined) {
181    const path = focusNodes(next)
182    const parent = path[path.length - 1]
183    const node = newNode(next, patch.detour.title, { kind: 'detour', why: patch.detour.why })
184    if (parent) parent.children.push(node)
185    else next.plan.push(node)
186    setFocusPath(next, [...path, node])
187    trail('note', `Detour${parent ? ` from "${parent.title}"` : ''}: ${node.title}${node.why ? ` (${node.why})` : ''}`)
188  }
189  if (patch.done !== undefined) {
190    const nodes = patch.done.path ? nodesAtPath(next.plan, patch.done.path) : focusNodes(next)
191    const node = nodes?.[nodes.length - 1]
192    if (nodes && node) {
193      node.status = 'done'
194      if (patch.done.outcome !== undefined) node.outcome = patch.done.outcome
195      trail('done', `${node.title}${node.outcome ? `: ${node.outcome}` : ''}`)
196      const focus = focusNodes(next)
197      if (focus.includes(node)) {
198        const parents = nodes.slice(0, -1)
199        const siblings = parents.length > 0 ? parents[parents.length - 1]?.children ?? [] : next.plan
200        const after = siblings.slice(siblings.indexOf(node) + 1).find(s => s.status === 'todo' || s.status === 'doing')
201        if (after) setFocusPath(next, [...parents, after])
202        else next.focus = parents.map(p => p.id)
203      }
204      if (next.drift && next.drift.nodeId === node.id) next.drift = null
205    }
206  }
207  for (const u of patch.step_updates ?? []) {
208    const nodes = u.path ? nodesAtPath(next.plan, u.path) : u.n !== undefined ? nodesAtPath(next.plan, String(u.n)) : undefined
209    const node = nodes?.[nodes.length - 1]
210    if (!node) continue
211    if (u.status !== undefined) node.status = u.status
212    if (u.outcome !== undefined) node.outcome = u.outcome
213  }
214  for (const [key, value] of Object.entries(patch.facts ?? {})) {
215    if (value === '') {
216      delete next.facts[key]
217      continue
218    }
219    const old = next.facts[key]
220    if (old?.value === value) continue
221    next.facts[key] = { value, changedAt: now, was: old?.value }
222  }
223  if (patch.pin !== undefined) next.pinned = patch.pin
224  next.pinned = next.pinned.filter(k => k in next.facts)
225  for (const [term, meaning] of Object.entries(patch.glossary ?? {})) {
226    if (meaning === '') delete next.glossary[term]
227    else next.glossary[term] = meaning
228  }
229  for (const stage of patch.stages ?? []) {
230    if (stage.name === '') continue
231    const at = next.stages.findIndex(s => s.name === stage.name)
232    const old = next.stages[at]
233    if (at < 0 || !old) next.stages.push({ ...stage })
234    else {
235      // A new sample has not been looked at yet.
236      const isNewSample = stage.figure !== undefined && stage.figure !== old.figure
237      next.stages[at] = { ...old, ...stage, ...(isNewSample ? { seenAt: undefined, sample: stage.sample } : {}) }
238    }
239  }
240  if (patch.remove_stages) next.stages = next.stages.filter(s => !patch.remove_stages?.includes(s.name))
241  for (const item of patch.trail ?? []) trail(item.kind, item.text)
242  const from = focusNodes(next).map(n => n.title).pop() ?? 'the plan'
243  for (const text of patch.park ?? []) next.parked.push({ t: now, text, from })
244  if (patch.unpark) next.parked = next.parked.filter((_, i) => !patch.unpark?.includes(i + 1))
245  if (patch.recap) next.recap = { t: now, by: 'claude', ...patch.recap }
246  if (patch.drift !== undefined) {
247    const at = focusNodes(next).pop()
248    if (patch.drift === null || !at) next.drift = null
249    else if (!next.keepGoing.includes(at.id)) {
250      next.drift = { since: next.drift?.nodeId === at.id ? next.drift.since : now, note: patch.drift.note, nodeId: at.id }
251    }
252  }
253  next.trail = next.trail.slice(-TRAIL_LIMIT)
254  return next
255}
256
257// ---------- views ----------
258
259export const STATUS_MARK: Record<AtlasStepStatus, string> = { done: '✓', doing: '▶', todo: '·', dropped: '✗' }
260export const TRAIL_MARK: Record<AtlasTrailKind, string> = { done: '✓', decision: '◆', deadend: '✗', note: '·', checkpoint: '◷' }
261
262/** A step's short name: the text before a colon, else the first three words. */
263export function shortName(title: string): string {
264  const head = title.includes(':') ? title.slice(0, title.indexOf(':')) : title.split(/\s+/).slice(0, 3).join(' ')
265  return head.trim()
266}
267
268/** "Build tools › 3 atlas › 3.2 Route picture" */
269export function breadcrumb(map: AtlasMap): string {
270  const parts: string[] = []
271  let level = map.plan
272  const nums: number[] = []
273  for (const id of map.focus) {
274    const i = level.findIndex(n => n.id === id)
275    const node = level[i]
276    if (!node) break
277    nums.push(i + 1)
278    parts.push(`${nums.join('.')} ${shortName(node.title)}`)
279    level = node.children
280  }
281  return parts.join(' › ')
282}
283
284/** The one line above the prompt. */
285export function bandLine(map: AtlasMap, isStale: boolean, lastFigure?: number): string {
286  const parts: string[] = []
287  const crumb = breadcrumb(map)
288  if (crumb !== '') parts.push(`▶ ${crumb}`)
289  else if (map.goal !== '') parts.push(map.goal)
290  for (const key of map.pinned) {
291    const fact = map.facts[key]
292    if (fact) parts.push(`${key}: ${fact.value}`)
293  }
294  if (lastFigure !== undefined) parts.push(`Figure #${lastFigure}`)
295  if (map.parked.length > 0) parts.push(`${map.parked.length} parked`)
296  if (isStale) parts.push('⚠ Map may be stale')
297  return parts.join('  ·  ')
298}
299
300/** The plan tree as indented text with paths, the focus marked. */
301export function treeText(map: AtlasMap): string {
302  const focus = new Set(map.focus)
303  const lines: string[] = []
304  const walk = (nodes: AtlasNode[], prefix: string, depth: number) => {
305    nodes.forEach((n, i) => {
306      const path = prefix === '' ? String(i + 1) : `${prefix}.${i + 1}`
307      const tag = n.kind === 'detour' ? ' [detour]' : ''
308      const here = focus.has(n.id) && map.focus[map.focus.length - 1] === n.id ? '   ← focus' : ''
309      lines.push(`${'  '.repeat(depth)}${path} [${n.status}]${tag} ${n.title}${n.outcome ? ` — ${n.outcome}` : ''}${here}`)
310      walk(n.children, path, depth + 1)
311    })
312  }
313  walk(map.plan, '', 0)
314  return lines.join('\n')
315}
316
317/** The whole map as markdown, for the model. */
318export function toMarkdown(map: AtlasMap, seen: readonly number[]): string {
319  if (isEmpty(map)) return 'The atlas map for this project is empty.'
320  const out: string[] = []
321  if (map.goal !== '') out.push(`Goal: ${map.goal}`)
322  if (map.plan.length > 0) out.push('', 'Plan (paths like 3.2 address steps):', treeText(map))
323  if (map.recap) out.push('', `Recap: where ${map.recap.where}; learned ${map.recap.learned}; next ${map.recap.next}`)
324  if (map.drift) out.push('', `Drift note: ${map.drift.note}`)
325  if (map.parked.length > 0) {
326    out.push('', 'Parked:')
327    map.parked.forEach((p, i) => out.push(`${i + 1}. ${p.text} (from ${p.from})`))
328  }
329  const facts = Object.entries(map.facts)
330  if (facts.length > 0) {
331    out.push('', 'Facts:')
332    for (const [k, f] of facts) out.push(`- ${k}: ${f.value}${f.was !== undefined ? ` (was ${f.was})` : ''}`)
333  }
334  if (map.stages.length > 0) {
335    out.push('', 'Pipeline stages:')
336    for (const s of map.stages) {
337      const shape = s.in || s.out ? ` ${s.in ?? '?'} → ${s.out ?? '?'}` : ''
338      const hasSample = s.figure !== undefined || s.sample !== undefined
339      const isSeen = s.seenAt !== undefined || (s.figure !== undefined && seen.includes(s.figure))
340      const where = s.sample ?? `figure #${s.figure}`
341      const look = !hasSample ? 'no sample shown' : isSeen ? `seen (${s.sample ?? `figure #${s.figure}`})` : `${where}, not looked at yet`
342      out.push(`- ${s.name}:${shape} [${look}]${s.note ? ` ${s.note}` : ''}`)
343    }
344  }
345  const terms = Object.entries(map.glossary)
346  if (terms.length > 0) {
347    out.push('', 'Glossary:')
348    for (const [k, v] of terms) out.push(`- ${k}: ${v}`)
349  }
350  if (map.trail.length > 0) {
351    out.push('', 'Recent trail:')
352    for (const item of map.trail.slice(-10)) out.push(`${TRAIL_MARK[item.kind]} ${item.text}`)
353  }
354  return out.join('\n')
355}
356
357/** "3m ago" style ages for the pane. */
358export function age(now: number, t: number): string {
359  const s = Math.max(0, Math.round((now - t) / 1000))
360  if (s < 60) return `${s}s ago`
361  if (s < 3600) return `${Math.round(s / 60)}m ago`
362  if (s < 86400) return `${Math.round(s / 3600)}h ago`
363  return `${Math.round(s / 86400)}d ago`
364}
365
hooks/route.ts 78 lines
1// The plan as a route line: one station per step, done green, current orange, upcoming grey.
2
3import type { AtlasNode } from '../types'
4
5export const ROUTE_W = 1200
6export const ROUTE_H = 210
7
8const COLOUR = { done: '#59A14F', doing: '#F28E2B', todo: '#BAB0AC', dropped: '#BAB0AC', ink: '#222222', muted: '#6B6B6B' }
9
10/** A station's short name: the text before a colon, else the first two words. */
11export function shortName(title: string): string {
12  const head = title.includes(':') ? title.slice(0, title.indexOf(':')) : title.split(/\s+/).slice(0, 2).join(' ')
13  return head.trim()
14}
15
16/** Splits a label into at most two lines of about `width` characters. */
17export function wrap2(text: string, width = 12): string[] {
18  const words = text.split(/\s+/)
19  const lines: string[] = []
20  let line = ''
21  for (const w of words) {
22    if (line === '' || (line + ' ' + w).length <= width) line = line === '' ? w : `${line} ${w}`
23    else {
24      lines.push(line)
25      line = w
26    }
27  }
28  if (line !== '') lines.push(line)
29  return lines.length <= 2 ? lines : [lines[0] ?? '', `${lines.slice(1).join(' ').slice(0, width - 1)}…`]
30}
31
32const esc = (s: string) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
33
34/** `prefix` numbers a sub-route's stations ("3." gives 3.1, 3.2, ...). */
35export function routeSvg(steps: readonly AtlasNode[], current: number, prefix = ''): string {
36  const n = Math.max(1, steps.length)
37  const margin = 115
38  const y = 78
39  const x = (i: number) => (n === 1 ? ROUTE_W / 2 : margin + (i * (ROUTE_W - 2 * margin)) / (n - 1))
40  const parts: string[] = [
41    // The font as an inherited attribute, not a <style> block, so a surface that scrubs stylesheets keeps it.
42    `<svg xmlns="http://www.w3.org/2000/svg" width="${ROUTE_W}" height="${ROUTE_H}" viewBox="0 0 ${ROUTE_W} ${ROUTE_H}" font-family="'TeX Gyre Heros', Helvetica, Arial, sans-serif">`,
43    `<rect width="100%" height="100%" fill="#FFFFFF"/>`,
44  ]
45  for (let i = 0; i < n - 1; i++) {
46    const isDone = steps[i]?.status === 'done' && steps[i + 1]?.status !== 'todo'
47    parts.push(`<line x1="${x(i)}" y1="${y}" x2="${x(i + 1)}" y2="${y}" stroke="${isDone ? COLOUR.done : COLOUR.todo}" stroke-width="10" stroke-linecap="round"/>`)
48  }
49  steps.forEach((s, i) => {
50    const isNow = i === current
51    const isDetour = s.kind === 'detour'
52    const fill = isNow ? COLOUR.doing : s.status === 'done' ? COLOUR.done : '#FFFFFF'
53    const stroke = isNow ? COLOUR.doing : s.status === 'done' ? COLOUR.done : COLOUR.todo
54    if (isNow) parts.push(`<circle cx="${x(i)}" cy="${y}" r="34" fill="none" stroke="${COLOUR.doing}" stroke-width="4" opacity="0.45"/>`)
55    parts.push(`<circle cx="${x(i)}" cy="${y}" r="${isNow ? 24 : 19}" fill="${fill}" stroke="${stroke}" stroke-width="6"/>`)
56    const numColour = isNow || s.status === 'done' ? '#FFFFFF' : COLOUR.muted
57    const num = `${prefix}${i + 1}`
58    const numSize = (isNow ? 26 : 22) - (num.length > 2 ? 6 : 0)
59    parts.push(`<text x="${x(i)}" y="${y + 8}" text-anchor="middle" font-size="${numSize}" font-weight="bold" fill="${numColour}">${num}</text>`)
60    const lines = wrap2(`${isDetour ? '↪ ' : ''}${shortName(s.title)}`)
61    lines.forEach((line, k) => {
62      const colour = isNow ? COLOUR.ink : s.status === 'done' ? COLOUR.ink : COLOUR.muted
63      parts.push(
64        `<text x="${x(i)}" y="${y + 70 + k * 30}" text-anchor="middle" font-size="25" font-weight="${isNow ? 'bold' : 'normal'}" fill="${colour}">${esc(line)}</text>`,
65      )
66    })
67  })
68  parts.push('</svg>')
69  return parts.join('\n')
70}
71
72/** A short stable hash, to name the rendered file after its content. */
73export function hash(text: string): string {
74  let h = 2166136261
75  for (let i = 0; i < text.length; i++) h = Math.imul(h ^ text.charCodeAt(i), 16777619)
76  return (h >>> 0).toString(36)
77}
78
hooks/watch.ts 102 lines
1// The watchdog: after each turn a small model files the turn into the plan tree and refreshes the recap.
2
3import type { AtlasMap } from '../types'
4import { breadcrumb, treeText, type Patch } from './model'
5
6export type Turn = { prompt: string; actions: string[]; answer: string }
7
8export const WATCH_SYSTEM = `You keep a work map for a user who thinks visually and loses track of long sessions. Work often drills from a big plan into one step that becomes its own search space and never returns to the top. Your job is bookkeeping, not judgement: the user may go anywhere. File the latest turns into the plan tree so the way back stays clear, and write a short recap.
9
10Reply with one JSON object and nothing else. Every field is optional; leave out anything that did not change.
11{
12  "focus": "3.2",                                   // the path of the step the latest work belongs to, if it moved
13  "substeps": {"under": "3", "steps": ["...", "..."]}, // only when a step clearly split into a sub-plan that the map lacks
14  "detour": {"title": "...", "why": "..."},         // when the work left the step in focus for something not in the plan
15  "done": {"path": "3.2", "outcome": "..."},        // when a step or detour clearly finished
16  "park": ["..."],                                  // tangents mentioned but deliberately not pursued
17  "recap": {"where": "...", "learned": "...", "next": "..."},
18  "drift": {"note": "..."} or null,                 // a note only when two or more turns went far from the focus step with no sign it was intended; null clears an old note
19  "trail": [{"kind": "decision" | "deadend" | "done" | "checkpoint", "text": "..."}]
20}
21
22Rules:
23- The assistant may already have updated the map during the turn; the map below is current. Do not repeat what it already says.
24- Prefer fewer structural changes. Never invent steps the work does not show. Never mark something done without evidence.
25- Recap: "where" names the step in focus and what state it is in; "learned" is the one most useful finding; "next" is the next concrete action and, if a branch is nearly done, how it returns to the top-level plan. Each under 25 words.
26- Full names, no abbreviations you invented. Capitalise the first word.`
27
28/** The prompt: the map as a tree with paths, then the latest turns. */
29export function watchPrompt(map: AtlasMap, turns: readonly Turn[]): string {
30  const parts = [
31    `Goal: ${map.goal || '(none)'}`,
32    `Focus: ${breadcrumb(map) || '(none)'}`,
33    '',
34    'Plan:',
35    treeText(map) || '(empty)',
36  ]
37  if (map.parked.length > 0) parts.push('', 'Parked:', ...map.parked.map((p, i) => `${i + 1}. ${p.text}`))
38  if (map.recap) parts.push('', `Previous recap: where ${map.recap.where} | learned ${map.recap.learned} | next ${map.recap.next}`)
39  if (map.drift) parts.push('', `Open drift note: ${map.drift.note}`)
40  parts.push('', 'Latest turns, oldest first:')
41  turns.forEach((t, i) => {
42    parts.push(
43      `--- Turn ${i + 1}`,
44      `User: ${t.prompt || '(no new message; a continuation)'}`,
45      `Actions: ${t.actions.length > 0 ? t.actions.join('; ') : '(none)'}`,
46      `Assistant said: ${t.answer || '(nothing)'}`,
47    )
48  })
49  return parts.join('\n')
50}
51
52const KINDS = new Set(['decision', 'deadend', 'done', 'checkpoint', 'note'])
53const str = (v: unknown, max = 200): string | undefined => (typeof v === 'string' && v.trim() !== '' ? v.trim().slice(0, max) : undefined)
54const isPath = (v: unknown): v is string => typeof v === 'string' && /^\d+(\.\d+)*$/.test(v)
55
56/** Reads the model's JSON reply into a patch, keeping only well-formed fields. */
57export function parseWatch(text: string): Patch | undefined {
58  const start = text.indexOf('{')
59  const end = text.lastIndexOf('}')
60  if (start < 0 || end <= start) return undefined
61  let raw: Record<string, unknown>
62  try {
63    raw = JSON.parse(text.slice(start, end + 1)) as Record<string, unknown>
64  } catch {
65    return undefined
66  }
67  const patch: Patch = {}
68  if (isPath(raw.focus)) patch.focus = raw.focus
69  const sub = raw.substeps as { under?: unknown; steps?: unknown } | undefined
70  if (sub && isPath(sub.under) && Array.isArray(sub.steps)) {
71    const steps = sub.steps.map(s => str(s, 120)).filter((s): s is string => s !== undefined)
72    if (steps.length > 0) patch.substeps = { under: sub.under, steps }
73  }
74  const det = raw.detour as { title?: unknown; why?: unknown } | undefined
75  const title = str(det?.title, 120)
76  if (title) patch.detour = { title, why: str(det?.why) }
77  const done = raw.done as { path?: unknown; outcome?: unknown } | undefined
78  if (done && (done.path === undefined || isPath(done.path))) patch.done = { path: done.path as string | undefined, outcome: str(done.outcome) }
79  if (Array.isArray(raw.park)) {
80    const park = raw.park.map(p => str(p, 160)).filter((p): p is string => p !== undefined)
81    if (park.length > 0) patch.park = park
82  }
83  const rc = raw.recap as { where?: unknown; learned?: unknown; next?: unknown } | undefined
84  const where = str(rc?.where)
85  const learned = str(rc?.learned)
86  const nxt = str(rc?.next)
87  if (where && learned && nxt) patch.recap = { where, learned, next: nxt }
88  if (raw.drift === null) patch.drift = null
89  else {
90    const note = str((raw.drift as { note?: unknown } | undefined)?.note)
91    if (note) patch.drift = { note }
92  }
93  if (Array.isArray(raw.trail)) {
94    const trail = raw.trail
95      .map(t => t as { kind?: unknown; text?: unknown })
96      .filter(t => typeof t.kind === 'string' && KINDS.has(t.kind) && str(t.text))
97      .map(t => ({ kind: t.kind as 'decision' | 'deadend' | 'done' | 'checkpoint' | 'note', text: str(t.text) as string }))
98    if (trail.length > 0) patch.trail = trail.slice(0, 4)
99  }
100  return Object.keys(patch).length > 0 ? patch : undefined
101}
102
types/index.d.ts 91 lines
1export type AtlasStepStatus = 'todo' | 'doing' | 'done' | 'dropped'
2
3/** One step of the plan; any step can open its own sub-plan. */
4export type AtlasNode = {
5  id: string
6  title: string
7  status: AtlasStepStatus
8  outcome?: string
9  /** A detour is work that left its parent step's path, filed under it. */
10  kind?: 'detour'
11  why?: string
12  children: AtlasNode[]
13}
14
15export type AtlasFact = { value: string; changedAt: number; was?: string }
16
17export type AtlasStage = {
18  name: string
19  in?: string
20  out?: string
21  /** iris figure number the sample came from (session-scoped; the sample file is what lasts). */
22  figure?: number
23  /** The sample image, copied into the project: a path relative to the project root. */
24  sample?: string
25  /** When Claude last read this stage's sample; cleared when the sample changes. */
26  seenAt?: number
27  note?: string
28}
29
30export type AtlasTrailKind = 'done' | 'decision' | 'deadend' | 'note' | 'checkpoint'
31
32export type AtlasTrailItem = { t: number; kind: AtlasTrailKind; text: string }
33
34export type AtlasResearch = { t: number; tool: string; query: string; summary: string }
35
36export type AtlasParked = { t: number; text: string; from: string }
37
38export type AtlasRecap = { t: number; where: string; learned: string; next: string; by: string }
39
40export type AtlasDrift = { since: number; note: string; nodeId: string }
41
42export type AtlasMap = {
43  goal: string
44  /** The top level of the plan. */
45  plan: AtlasNode[]
46  /** Node ids from the top level down to the step in focus; empty when none. */
47  focus: string[]
48  nextId: number
49  facts: Record<string, AtlasFact>
50  /** Fact keys shown in the band above the prompt. */
51  pinned: string[]
52  glossary: Record<string, string>
53  stages: AtlasStage[]
54  trail: AtlasTrailItem[]
55  research: AtlasResearch[]
56  parked: AtlasParked[]
57  recap: AtlasRecap | null
58  drift: AtlasDrift | null
59  /** Node ids the user chose to keep working in despite a drift note. */
60  keepGoing: string[]
61  /** Every session working on this project, by session id: its name and its own position in the plan. */
62  sessions?: Record<string, AtlasSession>
63}
64
65export type AtlasSession = { name: string; focus: string[]; t: number }
66
67export type AtlasTab = 'map' | 'pipeline' | 'glossary' | 'trail'
68
69/** How the viewing terminal shows an Image: from a file path, only as PNG bytes, not at all, or not asked yet. Mirrors iris's type. */
70export type IrisImages = 'unknown' | 'file' | 'bytes' | 'none'
71
72declare module 'claude-code' {
73  interface PluginState {
74    atlas: {
75      map: AtlasMap
76      /** Edits and commands since the last atlas_update. */
77      changes: number
78      isStale: boolean
79      tab: AtlasTab
80      /** iris figure numbers whose PNG Claude has read this session. */
81      seen: number[]
82      /** True while the watchdog is reading the last turn. */
83      isWatching: boolean
84      /** The person chose "Not now" on the empty-map band this session. */
85      isInitDismissed: boolean
86      /** True while the keeper agent is working in the background. */
87      isKeeping: boolean
88    }
89  }
90}
91