SLOPSHOPPER

fankeel

Development discipline for long-running projects: a seven-stage pipeline restated on every prompt and after every answer with the shape its report takes, a…

panebandcommandtoastprocesstimer
v0.111.49no licenseupdated 2026-10-20FanFantom9452/FanKeel
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · fankeel
│ ┃ fankeel ✕ › fix the failing auth test and add an audit log call │ ┃ 這個 session 沒有進行中的任務 │ ┃ /fankeel 開一個 ⏺ Read(src/auth.ts) │ ┃ station 未啟動 ⎿ Read 6 lines │ ⏺ 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 │ │ › /fankeel-panel │ ⎿ fankeel: fankeel 面板已開啟。 │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · fankeel
這個 session 沒有進行中的任務 /fankeel 開一個 station 未啟動
README

FanKeel

A keel is the one structural member a hull cannot lose.

fankeel is a Claude Code plugin that carries a development discipline and states it on every prompt — and again on every answer — rather than once at the top of a session. It holds a task, moves it along a route it picked through seven stages, keeps a capped note of what has been tried, and shows which other live sessions are in the same files.

It exists because long-running projects rot in ways that are invisible from inside any one session: components rebuilt because nobody knew an equivalent existed, design documents piling up after the work they described has shipped, conventions that hold for a month and then quietly stop, and two terminals editing one file because neither knows the other is there.

Install

claude plugin marketplace add FanFantom9452/FanKeel
claude plugin install fankeel@fankeel

Restart Claude Code afterwards. Nothing else is installed: no dependencies, and the tests run on node --test, which is built in. Then, in any project:

/fankeel

It looks before it asks — what is under this directory, which of them is a repository, which was touched today — and then asks at most two questions with the options already on screen: which project, skipped when there is only one, and what the task is, read from the project's TODO — its todo folder, or a root TODO.md. It never asks which files you will touch; those are recorded as the edits land.

The repository is FanKeel and everything you type is fankeel. Plugin and marketplace ids have to be kebab-case — Claude Code accepts anything else, and the Claude.ai marketplace sync does not — so the id, the command, the badge word and the .fankeel/ directory are all lowercase.

It is also one of the plugins claude-kit installs, if you would rather take a whole machine's worth in one command — and that kit wires up TokenBar, which is what draws the badge.

Update

claude plugin marketplace update fankeel
claude plugin update fankeel@fankeel

Restart Claude Code afterwards, the same as installing. The marketplace line comes first because plugin update compares against the listing already on disk — skip it and there is nothing newer to find. Given no name, marketplace update refreshes every marketplace at once. Re-running claude plugin install is not the update path: the plugin is already installed, and what needs refreshing is the marketplace listing behind it.

Uninstall

claude plugin uninstall fankeel@fankeel
claude plugin marketplace remove fankeel

.fankeel/ is left in place — it is the project's, not the plugin's. Delete it by hand if you want it gone. Stale ~/.claude/modes/<session_id>/fankeel flags are pruned after 30 days while the plugin is installed; after uninstalling, remove any that remain.

The pipeline

Seven stages, each named for what it produces rather than how it feels:

flowchart LR
    S["<b>survey</b><br/>search the code, read the docs —<br/>does this already exist?"]
    D["<b>design</b><br/>one approach, its trade-offs,<br/>and the test that settles it"]
    P["<b>plan</b><br/>split into tasks you can test<br/>and review one at a time"]
    B["<b>build</b><br/>write it, test it, commit it —<br/>one review per task"]
    V["<b>verify</b><br/>run the tests, check that what<br/>you changed actually changed"]
    A["<b>audit</b><br/>find the pages that stopped<br/>being true"]
    L["<b>land</b><br/>close the TODOs, rewrite the map,<br/>then merge, PR, or keep"]

    S --> D --> P --> B --> V --> A --> L

A route is the stages one task actually needs, in order. Not every task is seven. A class picks one when the task starts, and every prompt from then on carries it with your position bracketed, so a two-stage task is never reported as permanently unfinished at 2 of 7:

spike          route: [survey] → build                                          (1 of 2)
bounded        route: survey → design → [build] → verify → land                 (3 of 5)
architectural  route: survey → design → plan → [build] → verify → audit → land  (4 of 7)

Only the current stage's rules are sent, and they are sent again every turn — a pointer is only as strong as the salience of what it points at. What each stage produces, what happens inside one, and how a class picks a route are in docs/pipeline.md.

Every stage ends at a gate

flowchart LR
    W["do the work"] --> R["report in this<br/>stage's shape"]
    R --> Q{"AskUserQuestion"}
    Q -- "1 · approve, move on" --> N["next stage<br/>on the route"]
    Q -- "1 · at the last stage" --> D["stand the task down"]
    Q -- "2 · stay here" --> W
    Q -- "3 · pause" --> P["next is written down;<br/>the task outlives the session"]
    N --> W

The gate is not conditional on there being something to decide: finishing a stage is the moment the next decision exists, and the answer being predictable is not the same as it having been given. Picking option one is the approval, so its description says what is being approved — after design, that is the approach itself. Each stage also ships the shape of its report, not only a description of one — the shape build ships:

- path +12/-3 — what changed
- path (new) — what it is

done: <n> of <m> — ledger or file table
docs-check: clean, or <n> fixed and <n> left
deferred: <heading> — <TODO entry, or omit this line>
then AskUserQuestion

The badge, and the station

fankeel writes one word to ~/.claude/modes/<session_id>/fankeel, and TokenBar renders any flag it finds there — so the two work together with no wiring on either side:

[FANKEEL:BUILD] | Opus 5 | my-project | main ↑2 +42/-7 ?1
ctx ███▊░░░░░░  38%    ·    5h ██████▌░░░  66%   ↻ 1h 46m    ·    7d █████▊░░░░  58%

The word is the stage, not an intensity. clash takes the slot when another live session is in your files, and init is the gap between /fankeel being submitted and a task existing. The seven stage colours ship with TokenBar from v1.4.0 on; the palette, both config formats and what each colour is doing are in docs/statusline.md.

Every session this machine has run, live or abandoned or stood down, is one page: the station — less any project whose profile sets station.hide, which appears on no row, in no total and in no detail file. node scripts/station.js --open opens the newest, and serve in place of that is the live form — docs/station.md.

The five scanners

node scripts/docs-check.jsEvery reference still resolves. A second to run, and the verify and audit rules call for it.
node scripts/residue.jsWhat is in this tree that nobody decided about: untracked and unignored, a worktree whose branch is merged and has nothing uncommitted, an environment nothing can rebuild or run, the weight of what is ignored, directories holding no files. It never deletes.
node scripts/docs-audit.jsThe fortnightly deep pass: which pages have stopped being true, and which two of them disagree. /fankeel-audit is the whole sweep — it runs all five, reads the shortlist they produce, then offers the cleanup.
node scripts/memory-check.jsClaude Code's own memory for this project: the index and the directory agreeing, cited paths that still exist, path:line inside its file.
node scripts/input-check.jsEvery file loaded into every session's input — global and project CLAUDE.md, each project's MEMORY.md — largest first with bytes and estimated tokens, then what could be trimmed. Lists, never fails, never edits.

None of them decides that two documents contradict each other, because nothing mechanical can. What the cap is, and why comparing two runs beats comparing two headline counts, is in docs/documents.md.

Where to find things

I want to knowPage
What /fankeel asks me, the seven stages, and how a route is chosendocs/pipeline.md
What .fankeel/map.md holds, and why a page marked design-intent is not driftdocs/pipeline.md
What gets written to disk, what is committed, and what notes and next are fordocs/registry.md
What [FANKEEL:CLASH] means, and how to stop a collision raising a promptdocs/collisions.md
What docs.json declares, and why an archive naming deleted code is not a bugdocs/documents.md
What a subagent is told when it starts, and when /fankeel-ask is worth the moneydocs/subagents.md
The badge word, and how to colour each stagedocs/statusline.md
Every session on this machine on one page, and how to put an abandoned one downdocs/station.md
Why fankeel ships no output style, and where its voice lives insteaddocs/decisions/2026-09-13-no-output-styles.md
How the plugin is built and checked, and the four scripts that stop a claim driftingdocs/development.md
How to run the behaviour eval, and what to do when claude plugin eval says early accessdocs/evals.md
Why any of it was built this waydocs/decisions/fankeel-shell.md

The full index, question by question, is docs/README.md.

What lives where

One row per directory, and under the three that run, every hook and the lib/ and scripts/ files worth opening first: hooks/ is what Claude Code calls, scripts/ is what a person or a skill runs, and lib/ is what both of them call. node scripts/layout.js prints the half of this a listing can derive; the right-hand column is the half it cannot.

fankeel/
├── .claude-plugin/    plugin.json — the skills, the agents, every hook and its timeout — and marketplace.json
├── .fankeel/          this repository's own settings: docs.json files each page, profile.json answers gates, .gitignore; and, generated and ignored, .fankeel/station.bat and station.sh, which open this machine's station
├── agents/            every subagent the stages dispatch, one file each — reader, reviewer, verifier, judge, fixer, brain, implementer, mover, mutator, writer, render-reviewer, mockup and the rest — with its tools and model
├── assets/            station/, the station page: index.html, station.css and station.js, copied beside every page a write produces, and tour.html, tour.css and tour*.js, the one-minute promo film; tune/overlay.js, which scripts/tune.js serve injects into every page it sends
├── bench/             the fixed inputs and two-sided controls scripts/bench.js runs: add-feature/, fix-bug/ and review-planted/, the whole tasks `run` compares arms on; roles/, one directory per role, each holding twelve items in three tiers; drift/, the long task the drift 2×2 checks step by step
├── docs/              reference pages by audience: 01-guide/, 02-architecture/, 03-decisions/, and 90-agent/ (reference/, plans/, reports/, judgements/) with 99-archive/ for what it retires
├── evals/             behaviour eval cases, one directory each, graded by scripts/eval.js with claude -p
├── hooks/             every hook Claude Code runs; each reads stdin, exits 0 on every path and leaves the work to lib/. Six are not rowed below: agent-end.js (SubagentStop and SubagentStart: when each subagent stopped, in .fankeel/build/agents-<session>.json, for the Pane's agent tree; a start takes the stop away; a stop whose final message runs past 3000 characters is refused once, the judge excepted), title.js (PreToolUse on Agent|Task: a dispatch's description opens with its model, version and effort, and a profile override's pinned model is swapped in), dispatch-gate.js (PreToolUse on Agent|Task: the fifth Agent or Task dispatch in one assistant message asks first, with a cost estimate), budget.js (PreToolUse and PostToolUse, subagents only: a soft context threshold nudges a handoff, the hard one refuses all but it, and a SubagentHandback is refused while an agent that subagent dispatched has not stopped), gate-write.js (PostToolUse on Write: a stage agent's handoff gate is checked the moment it is written) and relay-cap.js (PreToolUse on SendMessage and the session send_message tool: a message over 2000 characters is refused, and a file path asked for instead)
│   ├── inject.js      UserPromptSubmit: the block on every prompt, the init block on /fankeel, the badge
│   ├── resume.js      PostToolUse on AskUserQuestion: the stage's rules again once a gate is answered
│   ├── gate.js        PreToolUse on AskUserQuestion: stamps when a gate opened, so the wait can be timed; on a controlled stage it also validates that the controller's own question copies the handoff's gate word for word, denying a botched attempt or a malformed file gate; with `gate.station` set, it first waits that many seconds for the station's answer; it also carries `gate.away` (past 200k tokens in play, a `/compact` hint, and with `ask` one more question; once that one is answered 要離開 the work goes on, the next question that needs the user is held back instead of asked, the turn ends, and compact.ts compacts)
│   ├── guard.js       PreToolUse on writes, shells and subagent dispatches: the scope guard, read-only agents kept read-only, and no fankeel-brain for a stage stage.agents does not name; and every git commit scanned for the words in .fankeel/sensitive.txt
│   ├── touch.js       PostToolUse on Edit, Write, NotebookEdit: the files this task touched
│   ├── brief.js       SubagentStart: what a subagent is told about the task it was sent from
│   ├── carry.js       SessionStart on clear or fork: offers the task a /clear left behind
│   ├── compact.ts     not a command hook: an engine module that hooks/mod.ts, declared in hooks/hooks.json, registers, compacting the main session at the profile's `compact.at` (450k tokens by default, `off` never), or at the end of the turn in which hooks/gate.js held a question back from a user who answered 要離開 (`awayAt`), while it owns an active fankeel task, in an interactive session where the module was enabled; pane.ts beside it, with pane-bar.ts, pane-band.ts, pane-status.ts, pane-gate.ts and pane-svg.ts, is the same module's two drawings: two rows above the prompt while the session owns a task (the stage, the route as dots, tasks N/M and the minutes, with a badge and a countdown while a gate waits; then context, the 5h quota and the 7d quota as bars, and a count of the live sessions in the same files), and the Pane, opened by itself while the session owns a task and toggled by /fankeel-panel (the task and next in full with the route row, the files a live session shares and who shares them, the plan's tasks, a row each with its status and who it went to — the subagent whose description names task N, with its model, minutes and tokens, or before one goes out the plan's Dispatch model — the task's subagents as a tree, context against the compact threshold, the three newest notes, while a station is up the project's open TODO entries under four buttons — Ready, Needs a decision, Blocked and Watch, each with its count — the one pressed listing up to six of its titles, each a button that opens the station's TODO panel on that entry, then 還有 N 條 for the rest, and a foot with the session id and a button that opens the station; the route, tasks, agents and TODO each sit under a ▾ head button that folds the block to that one row, and a new session starts with every block open; tasks, TODO, agents, context and notes on one grey rail); on Claude Desktop the band's two rows and the Pane's route and clash are drawn as Svg from the same rows, and every other surface draws the text; Remote Control and the mobile app draw neither, and Claude Desktop runs the snapshot taken at install, so a new version shows there only after claude plugin update fankeel@fankeel
│   └── leave.js       SessionEnd: how the session ended and what it spent, and the station rewritten
├── lib/               the logic, as functions tested directly; nothing here reaches into scripts/ or hooks/
│   ├── registry.js    one entry per session under .fankeel/sessions/, written by rename so no read is torn
│   ├── stages.js      the seven stages, the three classes and their routes, every stage's rules and output shape
│   ├── render.js      the injected blocks: every prompt, after a gate, on /fankeel, when a task is renamed, for a subagent, after /clear
│   ├── live.js        which sessions are running, read from Claude Code's own sessions/<pid>.json; overlap.js is which of them have touched the same files
│   ├── guard.js       the scope guard's answer to an edit in another live session's files: nothing, ask or deny
│   ├── badge.js       the statusline word and lead line TokenBar draws
│   ├── map.js         .fankeel/map.md: the signpost, the filing, this tree, the planned and retired pages
│   ├── docs.js        docs.json: buckets, roles, and which pages may be out of date
│   ├── onboard.js     the three cheap onboarding checks task.js start runs on a task's project
│   ├── sensitive.js   the words in .fankeel/sensitive.txt, found in what a commit carries
│   ├── station.js     the station's model: finding every registry, the rows, the data and detail scripts; detail.js takes one session apart, cached by its files' size and mtime
│   ├── usage.js       what a transcript spent: requests, models, agents and every dispatch; replay.js is a session's events in time order, and one agent's own steps
│   ├── plantasks.js   a plan's tasks, and which of them may run at once
│   ├── handoff.js     a stage agent's report and the user's answer, under .fankeel/build/task-<started>/
│   └── profile.js     the project and machine profile: the standing answers to a gate
├── scripts/           the command line, thin wrappers over lib/
│   ├── task.js        start a task, move its stage, note, pause, stand it down
│   ├── orient.js      what is under this directory, before /fankeel asks anything
│   ├── map.js         writes .fankeel/map.md
│   ├── onboard.js     prints the onboarding checks, pass or fail; --full adds docs-check and drift
│   ├── layout.js      prints the half of this tree a listing can derive
│   ├── survey.js      what already exists here, for the survey stage
│   ├── ledger.js      the build ledger: init, complete, groups, lint, brief
│   ├── station.js     writes the station page, or serves it live
│   ├── docs-check.js  every reference in the documents still resolves
│   ├── docs-audit.js  which pages stopped being true, and which two disagree
│   ├── residue.js     what is in the tree that nobody decided about
│   ├── todo-check.js  whether the TODO entries are still an index
│   ├── upgrade.js     which migrations an older project still needs, and --apply for the safe one
│   └── version.js     the release number, in every place that carries it
├── skills/            one directory per skill — fankeel, one per stage, ask, explain, init, station, upgrade — and registry.json
└── tests/             node --test, one file per module or behaviour; tmp.js is where every scratch directory comes from

Development

npm test
claude plugin validate .

Run one npm test at a time. Some tests used to share fixed temp file names, so concurrent suites unlinked each other's files; that is fixed in tests/sensitive.test.js and tests/render.test.js. A few tests still time real work against budgets the code itself promises — the station's first scan of the drives (tests/station-cli.test.js), the 2.5 seconds a prompt waits for git status (lib/dirty.js), and the /fankeel probe of a busy station (tests/inject.test.js) — and three suites at once can starve those of CPU, so one of them fails with nothing wrong. Those bounds are the product's own, so they are not loosened to let parallel runs pass — with one exception: the git timeout (gitTimeout in lib/guard.js, used by lib/dirty.js) reads FANKEEL_GIT_TIMEOUT in milliseconds, 2500 when unset, and the tests that need git's answer rather than its timing (tests/dirty.test.js, tests/inject.test.js, tests/worktree-paths.test.js) set it to 30000. A different failure shares the symptom: two full suites at once on a machine short of commit memory fail with VirtualAlloc failed, exit 0xC0000409, 0xC000012D (STATUS_COMMITMENT_LIMIT) or git's Out of memory — that is Windows running out of commit, not a failing test, and one suite alone passes, which is why two suites are never run at once.

Every synchronous subprocess a test starts has a timeout even when the test names none: npm test and npm run test:fast load tests/subprocess-timeout.js with --require, which gives execFileSync, spawnSync and execSync a default of 120000 milliseconds, or FANKEEL_TEST_SUBPROCESS_TIMEOUT when it is set. A child that never exits turns its own test red with ETIMEDOUT instead of hanging the run. Running one file with a bare node --test tests/<file> skips it; add --require ./tests/subprocess-timeout.js to get it there too.

node scripts/suite.js --session <id> queues on its own: a second run on the same machine waits for the first and prints whose run it is waiting on. npm run test:fast skips the tests named @slow; npm test runs them all.

lib/ is pure logic, tested directly; hooks/ is where stdin, stdout and process exit live, and every hook exits 0 on every path, because a hook that throws blocks the thing it was called for and a plugin that can wedge your terminal is worse than no plugin. todo-check.js, version.js, skills-check.js and stage-registry.js each hold one written claim to the code it describes, and docs/development.md says what each of them checks. The behaviour eval and its runner are in docs/evals.md.

Source 9 files
hooks/mod.ts 55 lines
1import type { Register, EngineInterface } from 'claude-code'
2import { register as compact, parentOf } from './compact.ts'
3import { register as pane } from './pane.ts'
4
5// hooks/brief.js reads this record (hooks/brief.js spawnRecord): a subagent has
6// neither transcript nor meta file while its SubagentStart hook runs, and the
7// mod sees what the hook cannot. Same name rule on both sides.
8const SPAWN_ID = /^[\w.-]+$/
9const PROMPT_MAX = 200
10
11// The registry root the way hooks/pane.ts findEntry finds it, written again: the
12// engine follows $ only into a function of this file. The nearest ancestor of the
13// session's root that holds this session's registry file; null where there is none.
14async function spawnRoot($: EngineInterface): Promise<string | null> {
15  const id = await $.session.id()
16  let dir: string | null = await $.session.root()
17  while (dir) {
18    const root = dir.replace(/[\\/]+$/, '')
19    if (await $.fs.exists(`${root}/.fankeel/sessions/${id}.json`)) return root
20    dir = parentOf(dir)
21  }
22  return null
23}
24
25export const register: Register = (on, options) => {
26  compact(on, options)
27  pane(on, options)
28
29  // A write that cannot happen is said once; the spawn goes on either way.
30  let said = false
31  on('agent.spawn', async ($, e, next) => {
32    const out = await next(e)
33    const agentId = out.agentId
34    if (!agentId || !SPAWN_ID.test(agentId)) return out
35    try {
36      const root = await spawnRoot($)
37      if (!root) return out
38      const first = String(e.prompt ?? '').split(/\r?\n/, 1)[0]
39      const record = {
40        prompt: [...first].slice(0, PROMPT_MAX).join(''),
41        subagentType: e.subagentType ?? '',
42        parentAgentId: e.parentAgentId ?? '',
43        at: new Date().toISOString(),
44      }
45      await $.fs.write(`${root}/.fankeel/build/spawn/${agentId}.json`, JSON.stringify(record))
46    } catch (err) {
47      if (!said) {
48        said = true
49        $.ui.log(`fankeel spawn: record of ${agentId} not written, ${String(err)}`, { to: 'debug' })
50      }
51    }
52    return out
53  })
54}
55
hooks/compact.ts 187 lines
1import type { Register, EngineInterface } from 'claude-code'
2
3// Compacts the main conversation once its context reaches the profile's
4// compact.at (HARD where nothing sets one, never when it is off), but only in a
5// session that owns an active fankeel task: the user's own autoCompactEnabled
6// is false, and other sessions keep that choice.
7// The engine runs this module; it cannot require lib/, so HARD is written
8// again here and tests/compact.test.js pins it to lib/context.js HARD.
9export const HARD = 450000
10
11// lib/registry.js SESSION_ID: the registry file is named by this id.
12export const SESSION_ID = /^[0-9a-fA-F][0-9a-fA-F-]{7,63}$/
13
14type Entry = { project?: unknown; configDir?: unknown; task?: unknown; stage?: unknown; class?: unknown; active?: unknown; awayAt?: unknown }
15
16export function parentOf(dir: string): string | null {
17  const trimmed = dir.replace(/[\\/]+$/, '')
18  const cut = Math.max(trimmed.lastIndexOf('/'), trimmed.lastIndexOf('\\'))
19  if (cut < 0) return null
20  if (cut === 0) return trimmed.length > 1 ? '/' : null
21  return trimmed.slice(0, cut)
22}
23
24// hooks/inject.js:106-107: active is exactly true, and an entry that only ran
25// /fankeel (stage init, no task) is not in the mode yet.
26export function isActive(entry: Entry | null): boolean {
27  if (!entry || entry.active !== true) return false
28  return !(entry.stage === 'init' && !entry.task)
29}
30
31export function instructionsFor(id: string, entry: Entry, pluginRoot: string): string {
32  // hooks/gate.js held a question back from a user who is away (awayAt):
33  // hooks/inject.js asks it again on the user's next message, from the summary.
34  const held = typeof entry.awayAt === 'number'
35    ? ['- the question held back while the user was away, word for word with its options: ask it again on the user\'s next message']
36    : []
37  return [
38    'fankeel: this session is running a fankeel task. The summary must keep, word for word:',
39    `- session ${id} (every task.js call needs --session ${id})`,
40    `- task: ${String(entry.task)}`,
41    `- stage: ${String(entry.stage)}, class: ${String(entry.class ?? 'unknown')}`,
42    '- the plan file path, the build group in progress, and every task already recorded complete',
43    '- the agentId of every dispatched agent that has not returned yet, and what it was sent to do',
44    '- the last handoff and commit file paths named in the conversation',
45    '- the design.md and context.md paths under .fankeel/build/, when the conversation named them',
46    ...held,
47    `- the plugin scripts live under ${pluginRoot}/scripts`,
48  ].join('\n')
49}
50
51// The registry root is the nearest ancestor holding .fankeel/sessions
52// (lib/registry.js findStateRoot); looking for this session's own file there
53// also skips a machine-wide registry that does not hold it.
54async function findEntry($: EngineInterface, id: string): Promise<{ entry: Entry; root: string } | null> {
55  let dir: string | null = await $.session.root()
56  while (dir) {
57    const root = dir.replace(/[\\/]+$/, '')
58    const file = `${root}/.fankeel/sessions/${id}.json`
59    if (await $.fs.exists(file)) {
60      try {
61        return { entry: JSON.parse(String(await $.fs.read(file))) as Entry, root }
62      } catch (err) {
63        $.ui.log(`fankeel compact: unreadable session file ${file}: ${err}`, { to: 'debug' })
64        return null
65      }
66    }
67    dir = parentOf(dir)
68  }
69  return null
70}
71
72// lib/profile.js KEYS['compact.at'] values; anything else in a file is read as absent.
73const COMPACT_AT = /^(350000|450000|600000|1000000|off)$/
74
75async function profileAt(io: ThresholdIo, file: string): Promise<string | null> {
76  try {
77    if (!(await io.exists(file))) return null
78    const v = (JSON.parse(String(await io.read(file)).replace(/^/, '')) as Record<string, unknown>)['compact.at']
79    // lib/profile.js parseValue reads String(raw), so a hand-written number counts.
80    const at = typeof v === 'string' || typeof v === 'number' ? String(v).trim().toLowerCase() : ''
81    return COMPACT_AT.test(at) ? at : null
82  } catch (err) {
83    io.log(`fankeel compact: unreadable profile ${file}: ${err}`)
84    return null
85  }
86}
87
88// lib/docs.js projectRootsFor: the first segment of the entry's project, when
89// that is a directory under the registry root; otherwise the root itself.
90async function projectRootOf(io: ThresholdIo, root: string, project: unknown): Promise<string> {
91  if (typeof project !== 'string') return root
92  const p = project.replace(/\\/g, '/').replace(/^\.\//, '')
93  if (p.startsWith('/') || p.includes('..')) return root
94  const head = p.split('/')[0]
95  if (!head) return root
96  try {
97    return (await io.stat(`${root}/${head}`)).kind === 'dir' ? `${root}/${head}` : root
98  } catch {
99    return root
100  }
101}
102
103// The file and env reads the threshold needs, as plain functions: the engine refuses $ passed to an imported function, so hooks/pane.ts builds this from its own $.
104export type ThresholdIo = {
105  compactAt(): Promise<string | undefined>
106  exists(path: string): Promise<boolean>
107  read(path: string): Promise<string>
108  stat(path: string): Promise<{ kind: string }>
109  log(text: string): void
110}
111
112// lib/profile.js: the project file under the entry's project root, then the
113// machine file under the entry's configDir.
114export async function thresholdWith(io: ThresholdIo, found: { entry: Entry; root: string } | null): Promise<number> {
115  const raw = Number(await io.compactAt())
116  if (Number.isFinite(raw) && raw > 0) return raw
117  if (found) {
118    const { entry, root } = found
119    const project = await projectRootOf(io, root, entry.project)
120    const machine = typeof entry.configDir === 'string' && entry.configDir ? `${entry.configDir.replace(/[\\/]+$/, '')}/fankeel/profile.json` : null
121    const at = (await profileAt(io, `${project}/.fankeel/profile.json`)) ?? (machine ? await profileAt(io, machine) : null)
122    if (at === 'off') return Infinity
123    if (at) return Number(at)
124  }
125  return HARD
126}
127
128// Not awaited by the hook: compact rejects while a turn runs, and the turn may
129// still count as running until this hook returns. Three tries, a second apart; tests/compact.test.js pins the three.
130async function compactWithRetry($: EngineInterface, instructions: string): Promise<boolean> {
131  for (let attempt = 1; attempt <= 3; attempt++) {
132    try {
133      const res = await $.session.compact({ instructions })
134      $.ui.log(`fankeel compact: attempt ${attempt} ${res && res.skip ? 'skipped by a hook' : 'done'}`, { to: 'debug' })
135      return true
136    } catch (err) {
137      $.ui.log(`fankeel compact: attempt ${attempt} rejected: ${String(err)}`, { to: 'debug' })
138      await $.clock.sleep(1000)
139    }
140  }
141  return false
142}
143
144export const register: Register = (on) => {
145  let pending = false
146  let awayDone = 0
147  // The module's one turn.complete: the engine refuses a second without a matcher.
148  on('turn.complete', async ($, e, next) => {
149    const out = await next(e)
150    if (e.agentId !== undefined || pending) return out
151    try {
152      const { context } = await $.session.usage()
153      const id = await $.session.id()
154      if (!SESSION_ID.test(id)) return out
155      const found = await findEntry($, id)
156      const at = await thresholdWith(
157        {
158          compactAt: () => $.env.get('FANKEEL_COMPACT_AT'),
159          exists: (path) => $.fs.exists(path),
160          read: async (path) => String(await $.fs.read(path)),
161          stat: (path) => $.fs.stat(path),
162          log: (text) => $.ui.log(text, { to: 'debug' }),
163        },
164        found,
165      )
166      if (!found || !isActive(found.entry)) return out
167      // hooks/gate.js sets awayAt when it holds a question back from a user who answered 要離開 (gate.away): compact now, whatever compact.at says.
168      // Only an awayAt newer than the last one acted on: nothing here clears it, inject.js does on the user's next prompt.
169      const awayAt = found.entry.awayAt
170      const away = typeof awayAt === 'number' && awayAt > awayDone
171      if (typeof context.tokens !== 'number' || (context.tokens < at && !away)) return out
172      const entry = found.entry
173      pending = true
174      $.ui.log(away ? `fankeel compact: user is away, ${context.tokens} tokens, compacting` : `fankeel compact: ${context.tokens} tokens >= ${at}, compacting`, { to: 'debug' })
175      void compactWithRetry($, instructionsFor(id, entry, $.plugin.root)).then((ok) => {
176        // A failed compaction leaves awayDone alone: the next turn.complete retries this awayAt.
177        if (ok && away) awayDone = awayAt
178      }).finally(() => {
179        pending = false
180      })
181    } catch (err) {
182      $.ui.log(`fankeel compact: skipped, ${String(err)}`, { to: 'debug' })
183    }
184    return out
185  })
186}
187
hooks/pane.ts 716 lines
1import type { Register, EngineInterface, UiPressArgument } from 'claude-code'
2import { parentOf, isActive, SESSION_ID, thresholdWith } from './compact.ts'
3import { statusRows, ledgerDoneIds, planTasks } from './pane-status.ts'
4import type { Entry, Other, PlanInfo, PlanTask, Seg as StatusSeg, Row as StatusRow, StatusInput, Fold, TodoEntry } from './pane-status.ts'
5import type { Context, Limit } from './pane-bar.ts'
6import { taskDir, pendingName, parsePending } from './pane-gate.ts'
7import type { Pending } from './pane-gate.ts'
8import { agentTree, agentTokens, modelAlias } from './pane-agents.ts'
9import type { AgentFile, AgentNode } from './pane-agents.ts'
10import { bandRows } from './pane-band.ts'
11import type { Seg as BandSeg, BandInput } from './pane-band.ts'
12import { bandRow1Svg, bandRow2Svg, paneParts, altOf, SVG_MAX } from './pane-svg.ts'
13
14// The fankeel mod's two drawings: two rows above the prompt for what is always
15// wanted, and the Pane for what is looked up. The Pane opens itself while the
16// session owns a task; /fankeel-panel toggles it. docs/90-agent/plans/2026-10-12-pane-band-design.md
17// is the design. Nothing here runs unless the module was enabled, and nothing
18// outside it depends on it.
19export const PANE = 'fankeel'
20export const COMMAND = 'fankeel-panel'
21export const POLL_MS = 250
22
23// The surfaces measured to draw a Pane. Remote Control attaches none of them, and the mobile app draws no mod.
24const PLACES = ['terminal', 'desktop']
25
26type Seen = {
27  id: string
28  entry: Entry | null
29  others: Other[]
30  pending: Pending | null
31  context: Context | null
32  limits: Limit[]
33  plan: PlanInfo | null
34  // Whether Remote Control is connected, from Claude Code's own session file.
35  remote: boolean
36  // What probeOf read, or null while FANKEEL_PANE_PROBE is unset.
37  probe: string | null
38  // This task's subagents as a tree, from Claude Code's subagents files (agentsOf).
39  agents: AgentNode[]
40  // The station's url from serve.json (stationOf), or null when none is up.
41  station: string | null
42  // The station's key for this task's project (lib/station.js pkeyOf), and its open TODO entries while a station is up (todosOf).
43  pkey: string
44  todos: TodoEntry[]
45  // The session's model alias, read each tick; the effort the last main-loop turn.step carried, which only that observer sets.
46  model: string | null
47  effort: string | null
48}
49
50// What a file last parsed to, and the time and size it had then: the tick runs
51// four times a second in every session that enabled the mod, and a neighbour's
52// registry file or a plan file that has not moved is not read again. The
53// session's own registry file, the pending file and the ledger are read every tick.
54type Cache = Map<string, { stamp: string; value: unknown }>
55
56const blank = (id: string): Seen => ({ id, entry: null, others: [], pending: null, context: null, limits: [], plan: null, remote: false, probe: null, agents: [], station: null, pkey: '', todos: [], model: null, effort: null })
57
58// The last message each silent catch logged: the tick runs four times a second, and a failure that stays is said once.
59type Logged = { context: string; plan: string; open: string; registry: string; neighbour: string; gate: string; live: string; remote: string; bandSvg: string; paneSvg: string; agents: string; station: string; todo: string; model: string }
60
61// A registry file that is there and does not parse: told apart so `tick` can wait it out for a while, then give up on it.
62class Unreadable extends Error {}
63
64// Five seconds at POLL_MS: how many ticks in a row a registry file may stay unreadable before it counts as no task.
65const UNREADABLE_TICKS = 20
66
67function logOnce($: EngineInterface, logged: Logged, key: keyof Logged, text: string): void {
68  if (logged[key] === text) return
69  logged[key] = text
70  $.ui.log(text, { to: 'debug' })
71}
72
73async function readJson($: EngineInterface, file: string): Promise<Entry | null> {
74  try {
75    const got = JSON.parse(String(await $.fs.read(file)))
76    return got && typeof got === 'object' && !Array.isArray(got) ? (got as Entry) : null
77  } catch {
78    return null
79  }
80}
81
82// hooks/compact.ts findEntry, written again: the engine follows $ only into a
83// function of this file, never across an import.
84async function findEntry($: EngineInterface, id: string): Promise<{ entry: Entry; root: string } | null> {
85  let dir: string | null = await $.session.root()
86  while (dir) {
87    const root = dir.replace(/[\\/]+$/, '')
88    const file = `${root}/.fankeel/sessions/${id}.json`
89    if (await $.fs.exists(file)) {
90      const entry = await readJson($, file)
91      // A file that is there and does not parse is one caught mid-write, not a task that ended: `tick` waits for it.
92      if (!entry) throw new Unreadable('registry file unreadable: ' + file)
93      return { entry, root }
94    }
95    dir = parentOf(dir)
96  }
97  return null
98}
99
100// The tokens in play against the count hooks/compact.ts compacts at — its own
101// `thresholdWith`, so FANKEEL_COMPACT_AT, the profile's compact.at and HARD are read
102// in one place, and `off` is Infinity — and the rate limits the same call
103// reports: `five_hour` and `seven_day` are the two drawn.
104// No context while the engine has no count; neither when it cannot be asked.
105async function contextOf($: EngineInterface, logged: Logged, found: { entry: Entry; root: string }): Promise<{ context: Context | null; limits: Limit[] }> {
106  try {
107    const usage = await $.session.usage()
108    const limits = Array.isArray(usage.rateLimits) ? (usage.rateLimits as Limit[]) : []
109    if (typeof usage.context.tokens !== 'number') return { context: null, limits }
110    const window = usage.context.window
111    const io = {
112      compactAt: () => $.env.get('FANKEEL_COMPACT_AT'),
113      exists: (path: string) => $.fs.exists(path),
114      read: async (path: string) => String(await $.fs.read(path)),
115      stat: (path: string) => $.fs.stat(path),
116      log: (text: string) => $.ui.log(text, { to: 'debug' }),
117    }
118    return { context: { tokens: usage.context.tokens, at: await thresholdWith(io, found), ...(typeof window === 'number' && Number.isFinite(window) && window > 0 ? { window } : {}) }, limits }
119  } catch (err) {
120    logOnce($, logged, 'context', `fankeel pane: no token count, ${String(err)}`)
121    return { context: null, limits: [] }
122  }
123}
124
125// Where the engine says the session draws, read only while FANKEEL_PANE_PROBE is set: the mod API has no
126// Remote Control field, and whether these two answers move when it is switched on is what the probe is for.
127async function probeOf($: EngineInterface): Promise<string | null> {
128  if (!(await $.env.get('FANKEEL_PANE_PROBE'))) return null
129  try {
130    return `surfaces [${(await $.session.surfaces()).join(', ')}] · surface ${String(await $.session.surface())}`
131  } catch (err) {
132    return `surfaces ? · ${String(err)}`
133  }
134}
135
136// The newest plan this task claimed that has a build ledger of its own: the
137// ledger is where lib/ledger.js ledgerPath puts it, and ledgerDoneIds refuses
138// one whose first line names another plan. The tasks are the plan's own headings.
139async function planOf($: EngineInterface, root: string, entry: Entry, cache: Cache, logged: Logged): Promise<PlanInfo | null> {
140  const claims = Array.isArray(entry.claims) ? entry.claims : []
141  for (let i = claims.length - 1; i >= 0; i--) {
142    const claim = claims[i]
143    if (typeof claim !== 'string' || !claim.endsWith('.md')) continue
144    const name = claim.slice(Math.max(claim.lastIndexOf('/'), claim.lastIndexOf('\\')) + 1, -3)
145    const file = `${root}/.fankeel/build/${name}/progress.md`
146    if (!(await $.fs.exists(file))) continue
147    const ledger = String(await $.fs.read(file))
148    const done = ledgerDoneIds(ledger, claim)
149    if (done === null) continue
150    let tasks: PlanTask[] = []
151    try {
152      const planFile = `${root}/${claim}`
153      const stat = await $.fs.stat(planFile)
154      const stamp = `${stat.mtimeMs}:${stat.size}`
155      let hit = cache.get(planFile)
156      if (!hit || hit.stamp !== stamp) {
157        hit = { stamp, value: planTasks(String(await $.fs.read(planFile))) }
158        cache.set(planFile, hit)
159      }
160      tasks = hit.value as PlanTask[]
161    } catch (err) {
162      logOnce($, logged, 'plan', `fankeel pane: plan file unreadable, ${String(err)}`)
163    }
164    return tasks.length > 0 ? { name, done, tasks } : null
165  }
166  return null
167}
168
169// The neighbours hooks/inject.js found running at this session's last prompt
170// (`.fankeel/build/live.json`), or null where that cannot be told: no file, one
171// that does not parse, no `at`, or `ids` that is no list — lib/live.js writes
172// null there when it could not tell. The mod has no pid to signal, so this file
173// is all it knows of who is alive. Read every tick: it is one short line.
174async function liveOf($: EngineInterface, root: string, logged: Logged): Promise<{ at: number; ids: string[] } | null> {
175  const file = `${root}/.fankeel/build/live.json`
176  try {
177    if (!(await $.fs.exists(file))) return null
178    const got = JSON.parse(String(await $.fs.read(file))) as { at?: unknown; ids?: unknown } | null
179    if (!got || typeof got.at !== 'number' || !Number.isFinite(got.at) || !Array.isArray(got.ids)) return null
180    return { at: got.at, ids: got.ids.filter((x): x is string => typeof x === 'string') }
181  } catch (err) {
182    logOnce($, logged, 'live', `fankeel pane: live list does not parse, ${file}, ${String(err)}`)
183    return null
184  }
185}
186
187// The config directory this session runs under: the one its entry recorded, else ~/.claude; '' when neither is known.
188async function configDirOf($: EngineInterface, entry: Entry): Promise<string> {
189  const home = (await $.env.get('HOME')) || (await $.env.get('USERPROFILE'))
190  const configDir = typeof entry.configDir === 'string' && entry.configDir ? entry.configDir : home ? `${home}/.claude` : ''
191  return configDir.replace(/[\\/]+$/, '')
192}
193
194// Whether Remote Control is on for this session: Claude Code writes <configDir>/sessions/<pid>.json with
195// the session's `sessionId`, and a `bridgeSessionId` that is a non-empty string while it is connected
196// (null once switched off, absent if it never was; measured on 2.1.295). The file for this session is
197// found by its sessionId, not by its name. A directory or file that cannot be read counts as not connected.
198async function remoteOf($: EngineInterface, entry: Entry, id: string, cache: Cache, logged: Logged): Promise<boolean> {
199  try {
200    const configDir = await configDirOf($, entry)
201    if (!configDir) return false
202    const dir = `${configDir}/sessions`
203    if (!(await $.fs.exists(dir))) return false
204    // Several files can name this session (a dead pid leaves its own behind): the newest one is the truth.
205    let newest = -Infinity
206    let remote = false
207    const listed = new Set<string>()
208    for (const file of await $.fs.list(dir)) {
209      if (!file.name.endsWith('.json')) continue
210      const path = `${dir}/${file.name}`
211      listed.add(path)
212      const stamp = `${file.mtimeMs}:${file.size}`
213      let hit = cache.get(path)
214      if (!hit || hit.stamp !== stamp) {
215        // A file caught mid-write keeps its last good reading, and is read again next tick.
216        const fresh = await readJson($, path)
217        if (fresh) {
218          hit = { stamp, value: fresh }
219          cache.set(path, hit)
220        } else hit = { stamp, value: hit ? hit.value : null }
221      }
222      const got = hit.value as { sessionId?: unknown; bridgeSessionId?: unknown } | null
223      if (got && got.sessionId === id && file.mtimeMs >= newest) {
224        const on = typeof got.bridgeSessionId === 'string' && got.bridgeSessionId !== ''
225        // On an equal mtime connected wins, so the answer does not depend on the listing's order.
226        remote = file.mtimeMs === newest ? remote || on : on
227        newest = file.mtimeMs
228      }
229    }
230    for (const key of cache.keys()) if (key.startsWith(`${dir}/`) && !listed.has(key)) cache.delete(key)
231    logged.remote = ''
232    return remote
233  } catch (err) {
234    logOnce($, logged, 'remote', `fankeel pane: Remote Control state unreadable, ${String(err)}`)
235    return false
236  }
237}
238
239// How long a session with no subagents directory yet waits before projects/ is listed again.
240const SUB_RETRY_MS = 10000
241
242// This task's subagents, from Claude Code's own files under
243// <configDir>/projects/<slug>/<session>/subagents (hooks/pane-agents.ts) and
244// the stops hooks/agent-end.js wrote. The session's directory is found by its
245// name under projects/ and kept; a meta, prefix or transcript file is read again only
246// when it moved. Anything unreadable is no agents.
247async function agentsOf($: EngineInterface, entry: Entry, id: string, root: string, cache: Cache, logged: Logged): Promise<AgentNode[]> {
248  try {
249    const started = Date.parse(String(entry.started))
250    if (!Number.isFinite(started)) return []
251    const key = `subagents:${id}`
252    const known = cache.get(key)
253    let sub = known && typeof known.value === 'string' ? known.value : ''
254    if (!sub) {
255      if (known && Date.now() - Number(known.stamp) < SUB_RETRY_MS) return []
256      const configDir = await configDirOf($, entry)
257      const projects = `${configDir}/projects`
258      if (configDir && (await $.fs.exists(projects))) {
259        for (const dir of await $.fs.list(projects)) {
260          const at = `${projects}/${dir.name}/${id}/subagents`
261          if (await $.fs.exists(at)) {
262            sub = at
263            break
264          }
265        }
266      }
267      cache.set(key, { stamp: String(Date.now()), value: sub })
268      if (!sub) return []
269    }
270    let listed: Awaited<ReturnType<EngineInterface['fs']['list']>>
271    try {
272      listed = await $.fs.list(sub)
273    } catch (err) {
274      // The cached directory is gone: look for it again next tick.
275      cache.delete(key)
276      throw err
277    }
278    const stamps = new Map(listed.map((f) => [f.name, `${f.mtimeMs}:${f.size}`]))
279    const read = async (name: string): Promise<Record<string, unknown> | null> => {
280      const stamp = stamps.get(name)
281      if (!stamp) return null
282      const path = `${sub}/${name}`
283      let hit = cache.get(path)
284      if (!hit || hit.stamp !== stamp) {
285        hit = { stamp, value: await readJson($, path) }
286        // A file caught mid-write is read again next tick.
287        if (hit.value) cache.set(path, hit)
288      }
289      return (hit.value as Record<string, unknown> | null) ?? null
290    }
291    // The transcript's token count, kept by its stamp: a running agent's file grows each request.
292    const spent = async (name: string): Promise<number | null> => {
293      const stamp = stamps.get(name)
294      if (!stamp) return null
295      const path = `${sub}/${name}`
296      const hit = cache.get(path)
297      if (hit && hit.stamp === stamp) return typeof hit.value === 'number' ? hit.value : null
298      let text: string
299      try {
300        text = String(await $.fs.read(path))
301      } catch {
302        // Gone or locked between the listing and the read: no tokens this tick, tried again the next.
303        return null
304      }
305      const tokens = agentTokens(text)
306      cache.set(path, { stamp, value: tokens })
307      return tokens
308    }
309    const files: AgentFile[] = []
310    for (const f of listed) {
311      const m = /^agent-(.+)\.meta\.json$/.exec(f.name)
312      if (!m || f.mtimeMs < started) continue
313      files.push({ id: m[1], at: f.mtimeMs, meta: await read(f.name), prefix: await read(`agent-${m[1]}.prefix.json`), tokens: await spent(`agent-${m[1]}.jsonl`) })
314    }
315    const ends = await readJson($, `${root}/.fankeel/build/agents-${id}.json`)
316    const ended: Record<string, number> = {}
317    if (ends && ends.ended && typeof ends.ended === 'object') {
318      for (const [k, v] of Object.entries(ends.ended)) if (typeof v === 'number' && Number.isFinite(v)) ended[k] = v
319    }
320    logged.agents = ''
321    return agentTree(files, ended, started)
322  } catch (err) {
323    logOnce($, logged, 'agents', `fankeel pane: agents unreadable, ${String(err)}`)
324    return []
325  }
326}
327
328// What a station's url looks like: scripts/station.js binds 127.0.0.1. Anything
329// else in serve.json draws no button, since pressing it hands the url to a shell's `start`.
330const STATION_URL = /^http:\/\/127\.0\.0\.1:\d{1,5}\/?$/
331
332// The station's url as <configDir>/fankeel/serve.json records it (lib/serve.js),
333// or null when there is none. With no entry the config directory is
334// CLAUDE_CONFIG_DIR, else ~/.claude.
335async function stationOf($: EngineInterface, entry: Entry | null, logged: Logged): Promise<string | null> {
336  try {
337    const recorded = !!entry && typeof entry.configDir === 'string' && !!entry.configDir
338    const configDir = recorded && entry ? await configDirOf($, entry) : ((await $.env.get('CLAUDE_CONFIG_DIR')) || (await configDirOf($, {}))).replace(/[\\/]+$/, '')
339    if (!configDir) return null
340    const file = `${configDir}/fankeel/serve.json`
341    if (!(await $.fs.exists(file))) return null
342    const got = await readJson($, file)
343    return got && typeof got.url === 'string' && STATION_URL.test(got.url) ? got.url : null
344  } catch (err) {
345    logOnce($, logged, 'station', `fankeel pane: station record unreadable, ${String(err)}`)
346    return null
347  }
348}
349
350// lib/todo.js STATES, the open ones in the order the station's TODO panel files them; any other state but `done` comes after.
351const TODO_ORDER = ['ready', 'decision', 'blocked', 'watch']
352
353// One frontmatter field of an entry file, as lib/docs.js frontmatter reads it: a `key: value` line between the opening `---` fences, quotes trimmed.
354function field(text: string, key: string): string {
355  const fm = /^---\r?\n([\s\S]*?)\r?\n---/.exec(text)
356  const kv = fm ? new RegExp(`^${key}\\s*:\\s*(.*)$`, 'mi').exec(fm[1]) : null
357  return kv ? kv[1].trim().replace(/^["']|["']$/g, '') : ''
358}
359
360// The project's open TODO entries: the `todo` bucket `<dir>/.fankeel/docs.json` declares (lib/todo.js bucketPath), each
361// `.md` file in it one entry, its id the file name, every state but `done` open, as lib/station.js todoOf counts them;
362// Ready first, then by id. A file is read again only when its listing stamp moved. Anything unreadable is no entries.
363async function todosOf($: EngineInterface, dir: string, cache: Cache, logged: Logged): Promise<TodoEntry[]> {
364  try {
365    const conf = await readJson($, `${dir}/.fankeel/docs.json`)
366    const buckets = conf && Array.isArray(conf.buckets) ? (conf.buckets as unknown[]) : []
367    const bucket = buckets.find((b): b is Record<string, unknown> => !!b && typeof b === 'object' && (b as Record<string, unknown>).role === 'todo')
368    if (!bucket || typeof bucket.path !== 'string') return []
369    const folder = `${dir}/${bucket.path}`
370    if (!(await $.fs.exists(folder))) return []
371    const todos: TodoEntry[] = []
372    const listed = new Set<string>()
373    for (const f of await $.fs.list(folder)) {
374      if (!f.name.endsWith('.md')) continue
375      const path = `${folder}/${f.name}`
376      listed.add(path)
377      const stamp = `${f.mtimeMs}:${f.size}`
378      let hit = cache.get(path)
379      if (!hit || hit.stamp !== stamp) {
380        const text = String(await $.fs.read(path))
381        hit = { stamp, value: { id: f.name.slice(0, -3), title: field(text, 'title'), state: field(text, 'state') } }
382        cache.set(path, hit)
383      }
384      const t = hit.value as TodoEntry
385      if (t.state !== 'done') todos.push({ ...t, title: t.title || t.id })
386    }
387    for (const key of cache.keys()) if (key.startsWith(`${folder}/`) && !listed.has(key)) cache.delete(key)
388    const rank = (state: string): number => (TODO_ORDER.includes(state) ? TODO_ORDER.indexOf(state) : TODO_ORDER.length)
389    logged.todo = ''
390    return todos.sort((a, b) => rank(a.state) - rank(b.state) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))
391  } catch (err) {
392    logOnce($, logged, 'todo', `fankeel pane: TODO entries unreadable, ${String(err)}`)
393    return []
394  }
395}
396
397// Opens the station's page in the host's browser: `start` on Windows, else
398// `open`, then `xdg-open`. When none of them runs, the url is copied instead,
399// and when that fails too a toast says so with the url in it.
400async function openStation($: EngineInterface, url: string, surface: UiPressArgument['surface']): Promise<void> {
401  const windows = (await $.env.get('OS')) === 'Windows_NT'
402  const tries = windows ? [['cmd', '/c', 'start', '', url]] : [['open', url], ['xdg-open', url]]
403  for (const argv of tries) {
404    try {
405      const done = await $.process.run(argv, { timeoutMs: 10000 })
406      if (done.exitCode === 0) return
407    } catch {
408      // `$.process.run` is CLI only: on another engine it rejects, and the next try or the copy follows.
409    }
410  }
411  try {
412    if ((await $.ui.copy({ text: url, surface })).isCopied) return
413  } catch {
414    // Said by the toast below, the same as a copy the surface declined.
415  }
416  $.ui.toast(`station:開不了瀏覽器,也複製不了網址 ${url}`)
417}
418
419// Everything both drawings show: this session's entry, the other active
420// entries beside it, the gate hooks/gate.js is holding, the context count and
421// the plan's ledger; the neighbours and the plan file are read again only when
422// their mtimeMs or size changes. The neighbours are read whether or not the
423// Pane is up, because the band's flag needs them. A neighbour the live list says has gone is left out of both.
424async function look($: EngineInterface, cache: Cache, logged: Logged): Promise<Seen> {
425  const id = await $.session.id()
426  if (!SESSION_ID.test(id)) return blank(id)
427  const found = await findEntry($, id)
428  if (!found || !isActive(found.entry)) return { ...blank(id), station: await stationOf($, null, logged) }
429  const entry = found.entry as Entry
430
431  const alive = await liveOf($, found.root, logged)
432  const others: Other[] = []
433  const unreadable: string[] = []
434  const sessions = `${found.root}/.fankeel/sessions`
435  for (const file of await $.fs.list(sessions)) {
436    if (!file.name.endsWith('.json') || file.name === `${id}.json`) continue
437    const path = `${sessions}/${file.name}`
438    const stamp = `${file.mtimeMs}:${file.size}`
439    let hit = cache.get(path)
440    if (!hit || hit.stamp !== stamp) {
441      hit = { stamp, value: await readJson($, path) }
442      // A file that did not parse may be one caught mid-write: it is read again next tick.
443      if (hit.value) cache.set(path, hit)
444    }
445    const other = hit.value as Entry | null
446    if (!other) unreadable.push(path)
447    // Unknown means live, and so does a registry file that moved after the list was written:
448    // a clash shown for a session that has gone is noise, one hidden is two terminals overwriting each other.
449    const sid = file.name.slice(0, -5)
450    if (other && isActive(other) && (!alive || alive.ids.includes(sid) || file.mtimeMs > alive.at)) others.push({ id: sid, entry: other })
451  }
452  // All the paths in one line, so two files that stay unreadable do not take turns being logged.
453  if (unreadable.length) logOnce($, logged, 'neighbour', `fankeel pane: neighbour registry file unreadable, ${unreadable.join(', ')}`)
454  else logged.neighbour = ''
455
456  let pending: Pending | null = null
457  const dir = taskDir(found.root, entry)
458  if (dir && (await $.fs.exists(dir))) {
459    const name = pendingName((await $.fs.list(dir)).map((f) => f.name), String(entry.stage))
460    if (name) {
461      const pendingFile = `${dir}/${name}`
462      const text = String(await $.fs.read(pendingFile))
463      pending = parsePending(text, Date.now())
464      if (!pending) {
465        // parsePending says null for a gate that expired or has no questions too: only a file that is not JSON is logged.
466        try {
467          JSON.parse(text)
468          logged.gate = ''
469        } catch {
470          logOnce($, logged, 'gate', `fankeel pane: pending file does not parse, ${pendingFile}`)
471        }
472      } else logged.gate = ''
473    }
474  }
475
476  const { context, limits } = await contextOf($, logged, found)
477  const plan = await planOf($, found.root, entry, cache, logged)
478  const probe = await probeOf($)
479  const remote = await remoteOf($, entry, id, cache, logged)
480  const agents = await agentsOf($, entry, id, found.root, cache, logged)
481  const station = await stationOf($, entry, logged)
482  // lib/station.js pkeyOf: the registry root, and the entry's project under it when it names one.
483  const pkey = typeof entry.project === 'string' && entry.project ? `${found.root}/${entry.project}` : found.root
484  const todos = station ? await todosOf($, pkey, cache, logged) : []
485  let model: string | null = null
486  try {
487    const m = await $.session.model()
488    model = m ? modelAlias(String(m)) : null
489    logged.model = ''
490  } catch (err) {
491    logOnce($, logged, 'model', `fankeel pane: session model unreadable, ${String(err)}`)
492  }
493  return { id, entry, others, pending, context, limits, plan, remote, probe, agents, station, pkey, todos, model, effort: null }
494}
495
496type State = {
497  seen: Seen
498  print: string
499  // Whether the pane up now is the mod's, opened for the task, and so the mod's to close when the task ends.
500  mine: false | 'task'
501  // Whether a task was there the last time the opens and closes for it went through.
502  edge: { task: boolean }
503  // Ticks in a row the registry file was unreadable.
504  bad: number
505  busy: boolean
506  cache: Cache
507  logged: Logged
508  // The blocks folded to their head row: memory only, so a new session starts with every block open.
509  folded: Partial<Record<Fold, boolean>>
510  // The TODO state whose entries the Pane lists, or null: memory only, as the folds are.
511  todoOpen: string | null
512}
513
514// An unplaced pane (narrow terminal) is registered but not drawn: not open.
515async function isOpen($: EngineInterface): Promise<boolean> {
516  return (await $.ui.panes()).some((pane) => pane.id === PANE && pane.isPlaced)
517}
518
519// Declared up here, not inside register: the engine refuses a module that hands $ to a closure.
520async function tick($: EngineInterface, state: State): Promise<void> {
521  if (state.busy) return
522  state.busy = true
523  try {
524    let next: Seen
525    try {
526      next = await look($, state.cache, state.logged)
527      state.bad = 0
528      state.logged.registry = ''
529    } catch (err) {
530      if (!(err instanceof Unreadable)) throw err
531      state.bad += 1
532      logOnce($, state.logged, 'registry', `fankeel pane: ${err.message}`)
533      // Caught mid-write: wait, with nothing changed. One that stays unreadable is no task.
534      if (state.bad < UNREADABLE_TICKS) return
535      next = blank(state.seen.id)
536    }
537    // The minute is in the key so the minutes, the neighbours' ages and the reset countdowns move while
538    // nothing else does; while a gate waits the second is too, for the seconds it has left.
539    next.effort = state.seen.effort
540    const clock = next.entry ? await $.clock.now() : 0
541    const minute = Math.floor(clock / 60000)
542    const second = next.pending ? Math.floor(clock / 1000) : 0
543    const now = JSON.stringify([next.entry, next.others, next.context, next.limits, next.plan, next.remote, next.probe, next.agents, next.station, next.pkey, next.todos, next.model, next.effort, minute, second])
544    // The opens and closes have their own memory, `edge`, which moves only when they all went through: a rejected
545    // one is met again next tick as the same edge, while `seen` and the redraw below never wait on them.
546    try {
547      // Asked here, after `look`: /fankeel-panel may have opened or closed the pane while it read files.
548      // A task appears: the pane opens, once; a pane the user then closes stays closed. No toast: the band shows the task.
549      if (!state.edge.task && next.entry && !(await isOpen($))) {
550        await $.ui.open({ id: PANE, title: 'fankeel' })
551        state.mine = 'task'
552      }
553      if (state.edge.task && !next.entry && state.mine) {
554        // Not asked whether it is open: a pane registered but not placed (a narrow terminal) is still the mod's to close.
555        await $.ui.close({ id: PANE })
556        state.mine = false
557      }
558      state.edge = { task: !!next.entry }
559      state.logged.open = ''
560    } catch (err) {
561      logOnce($, state.logged, 'open', `fankeel pane: pane not opened or closed, ${String(err)}`)
562    }
563    state.seen = next
564    if (now !== state.print) {
565      state.print = now
566      $.ui.invalidate('ui.render')
567    }
568  } catch (err) {
569    $.ui.log(`fankeel pane: tick skipped, ${String(err)}`, { to: 'debug' })
570  } finally {
571    state.busy = false
572  }
573}
574
575export const register: Register = (on) => {
576  const state: State = {
577    seen: blank(''), print: '', mine: false, edge: { task: false }, bad: 0, busy: false, cache: new Map(),
578    logged: { context: '', plan: '', open: '', registry: '', neighbour: '', gate: '', live: '', remote: '', bandSvg: '', paneSvg: '', agents: '', station: '', todo: '', model: '' },
579    folded: {}, todoOpen: null,
580  }
581
582  on('session.start', async ($, e, next) => {
583    await $.command.register({ name: COMMAND, description: 'fankeel 面板:任務、撞檔、tasks、用量額度與 notes' })
584    $.clock.every(POLL_MS, () => tick($, state))
585    return next(e)
586  })
587
588  // Observe only: the main loop's effort, a level or a budget, is what the band shows.
589  on('turn.step', async function* ($, e, next) {
590    if (!e.agentId) state.seen.effort = e.effort === undefined ? null : String(e.effort)
591    return yield* next(e)
592  })
593
594  on('command.run', { command: COMMAND }, async ($) => {
595    state.mine = false
596    if (await isOpen($)) {
597      await $.ui.close({ id: PANE })
598      return { text: 'fankeel 面板已關閉。' }
599    }
600    const opened = await $.ui.open({ id: PANE, title: 'fankeel' })
601    await tick($, state)
602    if (opened.isPlaced) return { text: 'fankeel 面板已開啟。' }
603    const surfaces = await $.session.surfaces()
604    if (!surfaces.some((surface) => PLACES.includes(surface))) return { text: 'fankeel 面板開不了:這裡畫不了面板,請在終端或 Claude Desktop 開。' }
605    return { text: opened.reason ? `fankeel 面板開不了:${opened.reason}` : 'fankeel 面板開不了:終端太窄。' }
606  })
607
608  // Two rows while the session owns a task; otherwise the band is the next hook's, and with none it is not drawn.
609  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
610    const seen = state.seen
611    const props = (e.props ?? {}) as { hasSurvey?: boolean; bodyColumns?: number }
612    if (props.hasSurvey) return next(e)
613    // 5: the cells the engine keeps at the band's right end, where no surface has measured the body.
614    const cols = Math.max(20, props.bodyColumns ?? (e.viewport?.columns ?? 85) - 5)
615    const plan = seen.plan
616    const now = Date.now()
617    const band: BandInput = {
618      entry: seen.entry,
619      others: seen.others,
620      gateUntil: seen.pending ? seen.pending.until : null,
621      gateAt: seen.pending ? (seen.pending.at ?? now) : null,
622      context: seen.context,
623      limits: seen.limits,
624      tasks: plan ? { done: plan.tasks.filter((t) => plan.done.includes(t.n)).length, total: plan.tasks.length } : null,
625      remote: seen.remote,
626      model: seen.model,
627      effort: seen.effort,
628      cols,
629      now,
630    }
631    const rows = bandRows(band)
632    if (!rows) return next(e)
633    // Claude Desktop draws each row as one Svg, its alt the row as text; every other surface draws the text.
634    // A drawing that throws, or comes back empty or over the engine's limit, falls through to the text rows.
635    if (e.surface === 'desktop') {
636      try {
637        const { Box, Svg } = $.ui.resolve(e)
638        const sources = rows.map((_, i) => (i === 0 ? bandRow1Svg(band) : bandRow2Svg(band)))
639        if (sources.some((source) => !source || source.length > SVG_MAX)) throw new Error('a band row drew empty or over the limit')
640        return h(Box, { flexDirection: 'column' }, ...sources.map((source, i) => h(Svg, { source, alt: altOf([rows[i]]) })))
641      } catch (err) {
642        logOnce($, state.logged, 'bandSvg', `fankeel pane: band Svg not drawn, ${String(err)}`)
643      }
644    }
645    const { Box, Text } = $.ui.resolve(e)
646    const cell = (seg: BandSeg) => {
647      const text = h(Text, { color: seg.color, backgroundColor: seg.backgroundColor, bold: seg.bold, wrap: 'truncate-end' }, seg.text)
648      return seg.gap ? [h(Text, {}, ' '.repeat(seg.gap)), text] : [text]
649    }
650    return h(Box, { flexDirection: 'column' }, ...rows.map((row) => h(Box, { flexDirection: 'row' }, ...row.flatMap(cell))))
651  })
652
653  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
654    const { Box, Text, Button } = $.ui.resolve(e)
655    const seen = state.seen
656    const props = (e.props ?? {}) as { bodyColumns?: number; scroll?: { bodyRows?: number } }
657    // The body's own cells where the surface measured them (41 by 32 on Claude Desktop); the viewport is the whole surface.
658    const cols = Math.max(20, props.bodyColumns ?? (e.viewport?.columns ?? 44) - 2)
659    const room = Math.max(1, props.scroll?.bodyRows ?? (e.viewport?.rows ?? 24) - 4)
660    // One reading for the whole drawing, so the status block's minutes are of the same moment.
661    const now = Date.now()
662    const input: StatusInput = {
663      id: seen.id,
664      entry: seen.entry,
665      others: seen.others,
666      plan: seen.plan,
667      cols,
668      room,
669      now,
670      probe: seen.probe,
671      gateAt: seen.pending ? (seen.pending.at ?? now) : null,
672      agents: seen.agents,
673      station: seen.station,
674      folded: state.folded,
675      todos: seen.todos,
676      pkey: seen.pkey,
677      todoOpen: state.todoOpen,
678    }
679    const status = statusRows(input)
680    const blankRow = () => h(Text, {}, ' ')
681    // A row's segments touch: each carries its own colour, and its own space where it wants one.
682    const piece = (seg: StatusSeg) => {
683      const url = seen.station
684      if (seg.press === 'station' && url) return h(Button, { key: 'station', label: seg.text, hotkey: 's', onPress: (press: UiPressArgument) => openStation($, url, press.surface) })
685      const to = seg.to
686      if (seg.press === 'todo' && to && url) return h(Button, { key: to, label: seg.text, onPress: (press: UiPressArgument) => openStation($, url + to, press.surface) })
687      const which = seg.state
688      if (seg.press === 'todoState' && which) {
689        return h(Button, { key: `todo-${which}`, label: seg.text, onPress: () => {
690          state.todoOpen = state.todoOpen === which ? null : which
691          $.ui.invalidate('ui.render')
692        } })
693      }
694      const fold = seg.fold
695      if (seg.press === 'fold' && fold) {
696        return h(Button, { key: `fold-${fold}`, label: seg.text, onPress: () => {
697          state.folded[fold] = !state.folded[fold]
698          $.ui.invalidate('ui.render')
699        } })
700      }
701      return h(Text, { color: seg.color, bold: seg.bold, wrap: 'truncate-end' }, seg.text)
702    }
703    const line = (row: StatusRow) => (row.segs.length === 0 ? blankRow() : h(Box, { flexDirection: 'row' }, ...row.segs.map(piece)))
704    // Claude Desktop draws the route and the clash as Svg; every other surface draws the text.
705    if (e.surface === 'desktop') {
706      try {
707        const { Svg } = $.ui.resolve(e)
708        return h(Box, { flexDirection: 'column' }, ...paneParts(input, status).flatMap((part) => ('rows' in part ? part.rows.map(line) : [h(Svg, part)])))
709      } catch (err) {
710        logOnce($, state.logged, 'paneSvg', `fankeel pane: Pane Svg not drawn, ${String(err)}`)
711      }
712    }
713    return h(Box, { flexDirection: 'column' }, ...status.map(line))
714  })
715}
716
hooks/pane-status.ts 471 lines
1// The status half of the fankeel Pane: a registry entry and the engine's
2// numbers in, rows out. No engine call here, so tests/pane-status.test.js runs
3// it under plain node. What each block holds is
4// docs/90-agent/plans/2026-10-12-pane-band-design.md section 3.
5
6import { WHERE, FLAG, GUARD, TODO, claimsOf } from './pane-band.ts'
7import { str, list, width, cut, WIDE, DIM, minutes } from './pane-bar.ts'
8import { tokenLabel } from './pane-agents.ts'
9import type { AgentNode } from './pane-agents.ts'
10
11// Kept as exports of this file: hooks/pane.ts imports them from here.
12export { str, list, width, cut, WIDE }
13
14export type Entry = Record<string, unknown>
15export type Other = { id: string; entry: Entry }
16// `color` is a hex, or absent for the terminal's own. The segments of a row
17// touch: one that wants a space before it carries the space in its text.
18// `press` makes the segment a Button on the Pane (hooks/pane.ts piece): 'station' opens the station's page,
19// 'fold' folds or opens the block `fold` names, 'todo' opens the station at the hash `to`, and
20// 'todoState' lists or closes the TODO entries in the state `state`.
21export type Seg = { text: string; color?: string; bold?: boolean; press?: 'station' | 'fold' | 'todo' | 'todoState'; fold?: Fold; to?: string; state?: string }
22// The blocks a head row folds; docs/90-agent/plans/2026-10-17-pane-fold-todo-design.md sections 1 and 2.
23export type Fold = 'route' | 'tasks' | 'todo' | 'agents'
24// One open entry of the project's TODO bucket (hooks/pane.ts todosOf): its file name without `.md`, its title, its state.
25export type TodoEntry = { id: string; title: string; state: string }
26// One drawn row. No segments is the blank row above a block. `who` is the
27// neighbour a clash row names: hooks/pane.ts counts them against the band's flag.
28export type Row = { block: string; segs: Seg[]; who?: string }
29// A task of the plan: its number, its heading, whether it is the user's to do, and its
30// first `**Dispatch:**` line up to its ` — ` (`implementer, sonnet`), '' where it has none.
31export type PlanTask = { n: number; name: string; user: boolean; dispatch?: string }
32// A plan's build ledger: its basename, the task numbers recorded complete, the tasks it has.
33export type PlanInfo = { name: string; done: number[]; tasks: PlanTask[] }
34export type StatusInput = {
35  id: string
36  entry: Entry | null
37  others: Other[]
38  plan: PlanInfo | null
39  cols: number
40  room: number
41  now: number
42  probe?: string | null
43  // When the question the pending file holds went out; the band reads the same, so both stop together.
44  gateAt?: number | null
45  // This task's subagents as a tree (hooks/pane-agents.ts agentTree); absent or empty draws no block.
46  agents?: AgentNode[]
47  // The station's url, from <configDir>/fankeel/serve.json (hooks/pane.ts stationOf); absent or null when none is up.
48  station?: string | null
49  // The blocks folded to their head row (hooks/pane.ts state); absent is every block open.
50  folded?: Partial<Record<Fold, boolean>>
51  // The project's open TODO entries, Ready first (hooks/pane.ts todosOf), and the station's key for the project.
52  todos?: TodoEntry[]
53  pkey?: string
54  // The TODO state whose entries the block lists (hooks/pane.ts state), or none listed.
55  todoOpen?: string | null
56}
57
58// Each block's rail, a fixed colour whatever the stage, on its first drawn row;
59// an alarm (ALARMS) carries it on every row. The task block has
60// no colour: its rail is the terminal's own.
61export const RAILS: Record<string, string> = {
62  clash: FLAG,
63  tasks: WHERE,
64  agents: WHERE,
65  notes: WHERE,
66  todo: WHERE,
67  foot: DIM,
68}
69
70const rail = (block: string): Seg => (Object.hasOwn(RAILS, block) ? { text: '▌', color: RAILS[block] } : { text: '▌' })
71// A drawn row: the rail, then the segments that have text. statusRows swaps the rail for a space on a section's later rows.
72const row = (block: string, ...segs: Seg[]): Row => ({ block, segs: [rail(block), ...segs.filter((seg) => seg.text)] })
73// A block's name, bold in its rail colour.
74const title = (block: string, text: string): Seg => ({ text, color: RAILS[block], bold: true })
75const record = (v: unknown): Record<string, unknown> => (v && typeof v === 'object' ? (v as Record<string, unknown>) : {})
76// Labels and secondary text.
77const dim = (text: string): Seg => ({ text, color: WHERE })
78// A fold head: ▾ while the block under it is open, ▸ while it is folded, drawn as a Button.
79const head = (fold: Fold, folded: boolean, text: string): Seg => ({ text: `${folded ? '▸' : '▾'} ${text}`, color: WHERE, bold: true, press: 'fold', fold })
80
81// The tail of `s` that fits: a path is told apart by its end.
82function tail(s: string, cols: number): string {
83  if (width(s) <= cols) return s
84  let out = ''
85  for (const ch of [...s].reverse()) {
86    if (width(ch + out) > cols - 1) break
87    out = ch + out
88  }
89  return '…' + out
90}
91
92// `s` whole, in rows of at most `cols` cells: a row that fills inside a word of
93// narrow characters breaks at its last space, any other where it is full.
94function wrap(s: string, cols: number): string[] {
95  const rows: string[] = []
96  let row = ''
97  for (const ch of s) {
98    if (width(row + ch) <= cols) {
99      row += ch
100      continue
101    }
102    const at = row.lastIndexOf(' ')
103    const word = row.slice(at + 1)
104    if (ch !== ' ' && at > 0 && !WIDE.test(word + ch)) {
105      rows.push(row.slice(0, at).trimEnd())
106      row = word + ch
107    } else {
108      rows.push(row.trimEnd())
109      row = ch === ' ' ? '' : ch
110    }
111  }
112  if (row) rows.push(row)
113  return rows
114}
115
116// Whole minutes, or `?` where the registry has no reading.
117const mins = (ms: unknown): string => (typeof ms === 'number' && Number.isFinite(ms) ? String(minutes(ms)) : '?')
118
119const LEDGER = '# fankeel build ledger — plan: '
120// lib/ledger.js HEADER_PREFIX, owns and completed: the tasks the ledger records
121// complete, ascending, or null when its first line names another plan.
122export function ledgerDoneIds(text: string, claim: string): number[] | null {
123  const lines = text.split(/\r?\n/)
124  if (lines[0] !== LEDGER + claim) return null
125  const done = new Set<number>()
126  for (const line of lines) {
127    const m = /^Task (\d+): complete\b/.exec(line.trim())
128    if (m) done.add(Number(m[1]))
129  }
130  return [...done].sort((a, b) => a - b)
131}
132
133// lib/plantasks.js parsePlan: the `## Task N:` headings of a plan, a fenced one
134// not counted, each with whether its first `**Dispatch:**` line names the user.
135// Any other `## ` heading ends the tasks.
136export function planTasks(text: string): PlanTask[] {
137  const tasks: PlanTask[] = []
138  let task: PlanTask | null = null
139  let said = false
140  let fence = 0
141  for (const raw of text.split(/\r?\n/)) {
142    const line = raw.trim()
143    const t = fence ? null : /^##\s+Task\s+(\d+):\s*(.*)$/.exec(line)
144    if (t) {
145      task = { n: Number(t[1]), name: t[2].trim(), user: false, dispatch: '' }
146      said = false
147      tasks.push(task)
148      continue
149    }
150    if (!fence && /^##\s/.test(line)) task = null
151    const f = /^`{3,}/.exec(line)
152    if (f) {
153      if (fence === 0) fence = f[0].length
154      else if (f[0].length >= fence) fence = 0
155      continue
156    }
157    if (fence || !task || said) continue
158    const d = /^\*\*Dispatch:\*\*\s*(.*)$/.exec(line)
159    if (!d) continue
160    said = true
161    task.dispatch = d[1].split(' — ')[0].trim()
162    const word = /^([a-z][a-z-]*)/i.exec(d[1])
163    task.user = !!word && word[1].toLowerCase() === 'user'
164  }
165  return tasks
166}
167
168// `inner` is the cells a row has after its rail.
169function taskBlock(entry: Entry, inner: number, folded: boolean): Row[] {
170  const rows = wrap(str(entry.task) || '—', inner).map((text) => row('task', { text, bold: true }))
171  const next = str(entry.next)
172  // 5: the cells of `next:`, which opens the first row.
173  wrap(next ? `next: ${next}` : '', inner).forEach((text, i) => {
174    rows.push(i ? row('task', { text }) : row('task', dim(text.slice(0, 5)), { text: text.slice(5) }))
175  })
176  // The stations behind the stage are green, the stage is the terminal's own and bold, those ahead are grey.
177  const route = list(entry.route)
178  const at = route.indexOf(str(entry.stage))
179  // The route opens with its head row, `▾ route 2/6`; folded, the head alone, with the stage after it.
180  if (at >= 0) rows.push(row('task', head('route', folded, `route ${at + 1}/${route.length}${folded ? ` ${route[at]}` : ''}`)))
181  if (at >= 0 && !folded) {
182    let cur: Seg[] = []
183    let used = 0
184    route.forEach((name, i) => {
185      const station: Seg = i < at ? { text: name, color: DONE } : i === at ? { text: name, bold: true } : { text: name, color: TODO }
186      // 3: the cells of ` › `.
187      if (cur.length && used + 3 + width(name) > inner) {
188        rows.push(row('task', ...cur))
189        cur = []
190        used = 0
191      }
192      if (cur.length) {
193        cur.push({ text: ' › ', color: TODO })
194        used += 3
195      }
196      cur.push(station)
197      used += width(name)
198    })
199    rows.push(row('task', ...cur))
200  }
201  return rows
202}
203
204// `12m`, `3h`, or '' where `updated` does not parse.
205export function ago(updated: unknown, now: number): string {
206  const at = typeof updated === 'string' ? Date.parse(updated) : NaN
207  if (!Number.isFinite(at)) return ''
208  const m = Math.max(0, Math.floor((now - at) / 60000))
209  return m >= 60 ? `${Math.floor(m / 60)}h` : `${m}m`
210}
211
212// Each file this session holds that a neighbour holds too, then one row a
213// neighbour holding it: its task, its stage, and how long since it moved.
214function clashBlock(entry: Entry, others: Other[], inner: number, now: number): Row[] {
215  const rows: Row[] = []
216  for (const file of claimsOf(entry)) {
217    const holders = others.filter((other) => claimsOf(other.entry).includes(file))
218    if (!holders.length) continue
219    // 2: the cells of `⚑ `, and of the indent under it.
220    rows.push(row('clash', { text: `⚑ ${tail(file, Math.max(4, inner - 2))}`, color: FLAG, bold: true }))
221    for (const other of holders) {
222      const age = ago(other.entry.updated, now)
223      const meta = ` @ ${str(other.entry.stage) || '?'}${age ? ` · ${age}` : ''}`
224      const name = cut(str(other.entry.task) || other.id.slice(0, 8), Math.max(4, inner - 2 - width(meta)))
225      rows.push({ ...row('clash', { text: `  ${name}` }, dim(meta)), who: other.id })
226    }
227  }
228  return rows
229}
230
231// A task complete, and an agent out on one.
232export const DONE = '#87af5f'
233export const OUT = '#af87d7'
234// The minutes an agent is out before its row turns amber.
235const LONG = 20
236// A plan of more tasks than this folds into a window.
237const WHOLE = 6
238
239// The subagent a task's row reads its model, minutes and tokens from: the newest
240// in the whole tree whose title names `task <n>` — lib/detail.js TASK_REF ties a
241// dispatch to a task the same way, and by nothing else.
242const TASK_REF = /\btask\s+(\d+)\b/i
243export function agentOf(nodes: AgentNode[], n: number): AgentNode | null {
244  const all = (list: AgentNode[]): AgentNode[] => list.flatMap((a) => [a, ...all(a.kids)])
245  let best: AgentNode | null = null
246  for (const a of all(nodes)) {
247    const m = TASK_REF.exec(a.title || '')
248    if (!m || Number(m[1]) !== n) continue
249    // A reviewer's title can name the task too; the row is the implementer's.
250    const rank = /implementer$/.test(a.type || '') ? 1 : 0
251    const held = best ? (/implementer$/.test(best.type || '') ? 1 : 0) : -1
252    if (rank > held || (rank === held && a.at > best!.at)) best = a
253  }
254  return best
255}
256
257// The model a plan's Dispatch line names: `implementer, sonnet, high` is sonnet;
258// `in-session` is itself; any other line is ''.
259export function dispatchModel(dispatch: string): string {
260  const m = /^implementer,\s*([a-z][a-z0-9.-]*)/i.exec(dispatch)
261  if (m) return m[1]
262  return /^in-session\b/i.test(dispatch) ? 'in-session' : ''
263}
264
265// The plan's tasks against its ledger. Six or fewer are listed; more fold to
266// the count done, the first open task and the two after it, and how many are
267// left — six rows at most. Each row names who it went to: the subagent whose
268// title names the task (agentOf) with its model, minutes and tokens, running
269// while that agent runs; before one has gone out, the plan's Dispatch model.
270// `inflight` is one mark, or a list of them once two agents are out
271// (lib/registry.js inflights); with no agent tied to an open task by name, the
272// mark is drawn on the first open task that is not the user's. With no ledger, a
273// mark on this stage is one row of its own.
274function tasksBlock(entry: Entry, plan: PlanInfo | null, agents: AgentNode[], inner: number, now: number, folded: boolean): Row[] {
275  if (!plan || !plan.tasks.length) return []
276  const stage = str(entry.stage)
277  const marks = Array.isArray(entry.inflight) ? entry.inflight : [entry.inflight]
278  const mark = marks.map(record).find((m) => m.stage === stage)
279  const known = !!mark && typeof mark.at === 'number' && Number.isFinite(mark.at)
280  const out = mark ? mins(known ? now - (mark.at as number) : null) : ''
281  const late = known && Number(out) >= LONG
282  const done = new Set(plan.done)
283  const open = plan.tasks.filter((t) => !done.has(t.n))
284  const count = plan.tasks.length - open.length
285  const live = (t: PlanTask): boolean => {
286    const a = agentOf(agents, t.n)
287    return !!a && a.end === null
288  }
289  const running = mark && !open.some(live) ? open.find((t) => !t.user) : undefined
290  // Numbers right-aligned to the widest one.
291  const pad = String(Math.max(...plan.tasks.map((t) => t.n))).length
292  const one = (t: PlanTask): Row => {
293    const label = ` ${String(t.n).padStart(pad)} `
294    // 1: the mark every task row opens with.
295    const name = (after: string): string => label + cut(t.name, Math.max(4, inner - 1 - width(label) - width(after)))
296    const agent = agentOf(agents, t.n)
297    const spent = agent && typeof agent.tokens === 'number' ? ` · ${tokenLabel(agent.tokens)}` : ''
298    const model = dispatchModel(str(t.dispatch))
299    const by = agent ? ` · ${agent.model} · ${mins((agent.end ?? now) - agent.at)} 分${spent}` : model ? ` · ${model}` : ''
300    if (done.has(t.n)) return row('tasks', { text: '●', color: DONE }, dim(name(by) + by))
301    if (agent && agent.end === null) return row('tasks', { text: '◉', color: OUT }, { text: name(by), bold: true }, { text: by, color: OUT })
302    if (t === running) {
303      const after = ` · 出去 ${out} 分`
304      return row('tasks', { text: '◉', color: OUT }, { text: name(after), bold: true }, { text: after, color: late ? GUARD : OUT })
305    }
306    if (t.user) return row('tasks', { text: '◐', color: GUARD }, { text: name(' · 你的') }, dim(' · 你的'))
307    return row('tasks', { text: '○', color: TODO }, { text: name(by) }, dim(by))
308  }
309  const top = row('tasks', head('tasks', folded, `tasks ${count}/${plan.tasks.length}`))
310  if (folded) return [top]
311  if (plan.tasks.length <= WHOLE) return [top, ...plan.tasks.map(one)]
312  const rows = [top]
313  if (count) rows.push(row('tasks', { text: '✓', color: DONE }, dim(` 完成 ${count}`)))
314  rows.push(...open.slice(0, 3).map(one))
315  const rest = open.slice(3)
316  if (rest.length) {
317    const yours = rest.filter((t) => t.user).length
318    rows.push(row('tasks', { text: '○', color: TODO }, dim(` 還有 ${rest.length} 個${yours ? `,${yours} 個是你的` : ''}`)))
319  }
320  return rows
321}
322
323// The station, the foot's last row: a button that opens its page and the whole
324// url beside it, or grey words saying none is up. The terminal draws the
325// button as `[ label ]`, four cells wider than its label; a Pane narrower than
326// the url cuts the url's end.
327function stationRow(url: string | null | undefined, inner: number): Row {
328  if (!url) return row('foot', dim(cut('station 未啟動', inner)))
329  const label = '開啟 station'
330  return row('foot', { text: label, press: 'station' }, dim(cut(` ${url}`, Math.max(4, inner - width(label) - 4))))
331}
332
333// The most TODO titles the block lists.
334const TODO_ROWS = 6
335
336// lib/todo.js STATES, the four the TODO block has a Button for, in the station panel's order, each with its label.
337export const TODO_STATES: [string, string][] = [['ready', 'Ready'], ['decision', 'Needs a decision'], ['blocked', 'Blocked'], ['watch', 'Watch']]
338
339// The project's open TODO entries under a fold head that counts them, then a
340// Button a state with its count, two a row — a state with none is grey words —
341// and under them the titles of the state pressed (`open`): a title a row, each a
342// Button opening the station's TODO panel on that entry, and past TODO_ROWS a
343// grey Button opening the whole panel. The terminal draws a Button four cells
344// wider than its label. No entries, no block.
345function todoBlock(todos: TodoEntry[], pkey: string, inner: number, folded: boolean, open: string | null): Row[] {
346  if (!todos.length) return []
347  const at = `#/p/${encodeURIComponent(pkey)}/todo`
348  const rows = [row('todo', head('todo', folded, `TODO ${todos.length}`))]
349  if (folded) return rows
350  const keys = TODO_STATES.map(([state, label]): Seg => {
351    const n = todos.filter((t) => t.state === state).length
352    if (!n) return dim(`${label} 0`)
353    const seg: Seg = { text: `${label} ${n}`, press: 'todoState', state }
354    if (state === open) seg.bold = true
355    return seg
356  })
357  rows.push(row('todo', keys[0], { text: ' ' }, keys[1]), row('todo', keys[2], { text: ' ' }, keys[3]))
358  const shown = open ? todos.filter((t) => t.state === open) : []
359  for (const t of shown.slice(0, TODO_ROWS)) rows.push(row('todo', { text: cut(t.title, Math.max(4, inner - 4)), press: 'todo', to: `${at}/${encodeURIComponent(t.id)}` }))
360  if (shown.length > TODO_ROWS) rows.push(row('todo', { text: `還有 ${shown.length - TODO_ROWS} 條`, color: WHERE, press: 'todo', to: at }))
361  return rows
362}
363
364// A row cut to `cols` cells: the segment that crosses the edge is cut, and the ones after it go.
365function fit(r: Row, cols: number): Row {
366  let left = cols
367  const segs: Seg[] = []
368  for (const seg of r.segs) {
369    // The terminal draws a Button four cells wider than its label.
370    const extra = seg.press ? 4 : 0
371    if (left - extra <= 0) break
372    const w = width(seg.text)
373    segs.push(w + extra <= left ? seg : { ...seg, text: cut(seg.text, left - extra) })
374    left -= w + extra
375  }
376  return { ...r, segs }
377}
378
379// The most roots the agents block lists, and the most agents under each.
380const AGENT_ROOTS = 6
381const AGENT_KIDS = 3
382
383// This task's subagents: a fold head, `▾ agents` with how many run and how many
384// stopped, then a row an agent — ○ running in OUT, ● stopped in DONE — its title, its
385// model, its effort, its minutes, out so far or out in all, and the tokens it
386// spent where its transcript was there to read. An agent's
387// own agents sit under it behind ├ and └, one level drawn; the counts in the
388// head row include every descendant, drawn or not. Folded, the head row alone.
389function agentsBlock(nodes: AgentNode[], inner: number, now: number, folded: boolean): Row[] {
390  if (!nodes.length) return []
391  const all = (list: AgentNode[]): AgentNode[] => list.flatMap((n) => [n, ...all(n.kids)])
392  const every = all(nodes)
393  const running = every.filter((n) => n.end === null).length
394  const one = (n: AgentNode, lead: string): Row => {
395    const spent = typeof n.tokens === 'number' ? ` · ${tokenLabel(n.tokens)}` : ''
396    const after = ` · ${n.model} · ${n.effort} · ${mins((n.end ?? now) - n.at)} 分${spent}`
397    const name = cut(n.title || n.type || n.id, Math.max(4, inner - width(lead) - 2 - width(after)))
398    const mark: Seg = n.end === null ? { text: '○', color: OUT } : { text: '●', color: DONE }
399    return row('agents', { text: lead }, mark, n.end === null ? { text: ` ${name}`, bold: true } : dim(` ${name}`), dim(after))
400  }
401  const rows = [row('agents', head('agents', folded, 'agents'), dim(`  ${running} 在跑 · ${every.length - running} 完成`))]
402  if (folded) return rows
403  for (const n of nodes.slice(0, AGENT_ROOTS)) {
404    rows.push(one(n, ''))
405    const kids = n.kids.slice(0, AGENT_KIDS)
406    const folded = n.kids.length > AGENT_KIDS
407    kids.forEach((k, i) => rows.push(one(k, i === kids.length - 1 && !folded ? ' └ ' : ' ├ ')))
408    if (folded) rows.push(row('agents', dim(` └ 還有 ${n.kids.length - AGENT_KIDS} 個`)))
409  }
410  if (nodes.length > AGENT_ROOTS) rows.push(row('agents', dim(`還有 ${nodes.length - AGENT_ROOTS} 個`)))
411  return rows
412}
413
414// Given up in this order when the rows do not fit, after the agents' own agents: `todo`, `agents` and `tasks` keep their head rows.
415// The task, the clash and the foot never go.
416const DROP = ['todo', 'notes', 'agents', 'tasks']
417// The blocks that are alarms, not sections: every row of one keeps its rail.
418const ALARMS = ['clash']
419
420export function statusRows(input: StatusInput): Row[] {
421  const { id, entry, others, cols, room, now } = input
422  if (!entry) {
423    return [
424      { block: 'empty', segs: [{ text: cut('這個 session 沒有進行中的任務', cols) }] },
425      { block: 'empty', segs: [dim(cut('/fankeel 開一個', cols))] },
426      // The station row with its rail left off, as the two above have none.
427      { block: 'empty', segs: stationRow(input.station, cols).segs.slice(1) },
428    ]
429  }
430  // 1: the cell every drawn row opens with, its block's rail or the space under it.
431  const inner = Math.max(4, cols - 1)
432  const folded = input.folded ?? {}
433  const blocks: Row[][] = [taskBlock(entry, inner, !!folded.route)]
434  const clash = clashBlock(entry, others, inner, now)
435  if (clash.length) blocks.push(clash)
436  const tasks = tasksBlock(entry, input.plan, input.agents ?? [], inner, now, !!folded.tasks)
437  if (tasks.length) blocks.push(tasks)
438  const agents = agentsBlock(input.agents ?? [], inner, now, !!folded.agents)
439  if (agents.length) blocks.push(agents)
440
441  // The registry keeps the newest note last.
442  const notes = list(entry.notes).slice(-3)
443  if (notes.length) blocks.push([row('notes', title('notes', 'notes')), ...notes.map((note) => row('notes', { text: cut(`· ${note}`, inner) }))])
444
445  // With no station up nothing opens a TODO: the foot's `station 未啟動` stands for both.
446  const todo = input.station ? todoBlock(input.todos ?? [], input.pkey ?? '', inner, !!folded.todo, input.todoOpen ?? null) : []
447  if (todo.length) blocks.push(todo)
448
449  // The probe is asked for by hand (hooks/pane.ts probeOf): it is drawn whole, in the block that never drops.
450  const probed = input.probe ? wrap(input.probe, inner).map((text) => row('foot', dim(text))) : []
451  blocks.push([...probed, row('foot', dim(cut(`${id.slice(0, 8)} · /fankeel-panel 關閉`, inner))), stationRow(input.station, inner)])
452
453  // Every block but the first costs a blank row above it.
454  const size = (): number => blocks.reduce((n, block) => n + block.length, blocks.length - 1)
455  // Before any block goes, the agents' own agents do: their rows open with ├ or └.
456  const ag = blocks.findIndex((block) => block[0].block === 'agents')
457  if (size() > room && ag >= 0) blocks[ag] = blocks[ag].filter((r) => !/^ [├└] /.test(r.segs[1]?.text ?? ''))
458  for (const name of DROP) {
459    if (size() <= room) break
460    const at = blocks.findIndex((block) => block[0].block === name)
461    if (at < 0) continue
462    if (name === 'notes') blocks.splice(at, 1)
463    // A head cut down to itself says so: its ▾ is the fold's, and would read as open and empty.
464    else if (blocks[at].length > 1) blocks[at] = [{ ...blocks[at][0], segs: [...blocks[at][0].segs, dim(' · 列數不夠')] }]
465  }
466  // A section's rail is on its first drawn row alone: the rows under it open
467  // with one plain space instead, so `inner` holds and no wrap or cut moves.
468  const railed = blocks.map((block) => (ALARMS.includes(block[0].block) ? block : block.map((r, i) => (i ? { ...r, segs: [{ text: ' ' }, ...r.segs.slice(1)] } : r))))
469  return railed.flatMap((block, i) => (i ? [{ block: block[0].block, segs: [] }, ...block] : block)).map((r) => fit(r, cols))
470}
471
hooks/pane-bar.ts 194 lines
1// What the band (hooks/pane-band.ts) and the Pane (hooks/pane-status.ts) both
2// draw with: cell widths, the eighths bar, TokenBar's ramp as hex and the colour
3// rule of each meter. No engine call and no import, so tests/pane-bar.test.js
4// runs it under plain node. docs/90-agent/plans/2026-10-12-pane-band-design.md, section 2.
5
6// The context tokens in play, the count hooks/compact.ts compacts at and the model's context window in tokens, when the engine reports one.
7export type Context = { tokens: number; at: number; window?: number }
8// One window of the engine's session.usage().rateLimits.
9export type Limit = { kind: string; percentUsed: number; resetsAt?: string }
10// `mark` is the warning sign drawn after the number, or ''.
11export type Paint = { color: string; bold: boolean; mark: string }
12
13export const WIDE = /[ᄀ-ᅟ⺀-꓏가-힣豈-﫿︰-﹏＀-⦆¢-₩]/
14// 💥 and 💀 are here. ⚠ (U+26A0) is not: it is counted one cell.
15const EMOJI = /[\u{1F300}-\u{1FAFF}]/u
16
17export const str = (v: unknown): string => (typeof v === 'string' ? v : '')
18export const list = (v: unknown): string[] => (Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string') : [])
19
20// Terminal cells: a CJK, full-width or emoji character takes two.
21export function width(s: string): number {
22  let n = 0
23  for (const ch of s) n += WIDE.test(ch) || EMOJI.test(ch) ? 2 : 1
24  return n
25}
26
27// The head of `s` that fits `cols` cells, ending in an ellipsis when cut.
28export function cut(s: string, cols: number): string {
29  if (width(s) <= cols) return s
30  let out = ''
31  for (const ch of s) {
32    if (width(out + ch) > cols - 1) break
33    out += ch
34  }
35  return out + '…'
36}
37
38// xterm 240: labels, the bar's track and the separators.
39export const DIM = '#585858'
40
41// TokenBar's ramp (F:/ymlab/TokenBar/statusline.sh), each xterm number as its hex.
42const XTERM: Record<number, string> = {
43  46: '#00ff00', 83: '#5fff5f', 120: '#87ff87', 157: '#afffaf', 194: '#d7ffd7',
44  193: '#d7ffaf', 192: '#d7ff87', 191: '#d7ff5f', 190: '#d7ff00', 226: '#ffff00',
45  220: '#ffd700', 214: '#ffaf00', 208: '#ff8700', 202: '#ff5f00', 196: '#ff0000',
46  197: '#ff005f', 198: '#ff0087', 199: '#ff00af', 200: '#ff00d7', 201: '#ff00ff',
47}
48
49// [from, xterm, bold]: the last step whose `from` is at or under the value wins.
50type Step = [number, number, boolean?]
51// Percent of the compact threshold: TokenBar's tier for a window of 500k or less.
52const CTX: Step[] = [[0, 46], [8, 83], [16, 120], [24, 157], [32, 194], [36, 190], [40, 226], [45, 220], [50, 214], [55, 208],
53  [60, 196, true], [65, 198, true], [70, 199, true], [75, 200, true], [80, 201, true]]
54// Percent of the five-hour window used.
55const FIVE: Step[] = [[0, 46], [10, 83], [20, 120], [30, 157], [40, 194], [45, 193], [50, 192], [55, 190], [60, 226], [65, 220], [70, 214], [75, 208],
56  [80, 196, true], [85, 197, true], [90, 199, true], [95, 201, true]]
57// The seven-day window's deviation from an even pace, in points.
58const DEV: Step[] = [[-999, 46], [-10, 83], [-7, 120], [-3, 157], [0, 194], [1, 193], [2, 192], [3, 191], [4, 190], [5, 226], [6, 214], [7, 202],
59  [8, 196], [9, 197], [10, 198], [11, 199], [12, 200], [13, 201], [14, 201, true]]
60
61function step(steps: Step[], value: number): { color: string; bold: boolean } {
62  let hit = steps[0]
63  for (const s of steps) if (s[0] <= value) hit = s
64  return { color: XTERM[hit[1]], bold: hit[2] === true }
65}
66
67// The percent of the compact threshold from which a compact is near: the band marks its meter from here.
68const NEAR = 80
69// Integer comparison, so a threshold needs no rounding.
70export const nearCompact = (tokens: number, at: number): boolean => tokens * 100 >= NEAR * at
71
72export function ctxPaint(tokens: number, at: number): Paint {
73  const percent = at > 0 ? (tokens * 100) / at : 0
74  return { ...step(CTX, percent), mark: at > 0 && nearCompact(tokens, at) ? '⚠' : '' }
75}
76
77// TokenBar's CTX_TIERS as [largest window the tier covers, purple from percent, ramp], the ramp in percent of the window itself.
78const TIERS: [number, number, Step[]][] = [
79  [200000, 85, [[0, 46], [10, 83], [20, 120], [30, 157], [40, 194], [45, 190], [50, 226], [55, 220], [60, 214], [65, 208], [70, 196, true], [75, 198, true], [80, 200, true]]],
80  [500000, 80, [[0, 46], [8, 83], [16, 120], [24, 157], [32, 194], [36, 190], [40, 226], [45, 220], [50, 214], [55, 208], [60, 196, true], [65, 198, true], [70, 199, true], [75, 200, true]]],
81  [800000, 80, [[0, 46], [6, 83], [12, 120], [18, 157], [24, 194], [27, 190], [30, 226], [36, 220], [42, 214], [48, 208], [55, 196, true], [62, 198, true], [70, 199, true], [75, 200, true]]],
82  [Infinity, 80, [[0, 46], [5, 83], [10, 120], [15, 157], [20, 194], [25, 193], [30, 192], [35, 190], [40, 226], [45, 214], [50, 196, true], [55, 197, true], [60, 198, true], [65, 199, true], [70, 200, true], [75, 201, true]]],
83]
84// CTX_MARKS: only windows above 800k carry the ladder; a smaller one gets a single ⚠ at its purple threshold.
85const LADDER: [number, string][] = [[50, '⚠'], [65, '💥'], [75, '💥💥'], [85, '💥💥💥'], [90, '💀']]
86
87// TokenBar's rule for the band's ctx meter: percent of the context window, not of the compact threshold.
88export function ctxWindowPaint(tokens: number, window: number): Paint {
89  const [, purple, ramp] = TIERS.find((t) => window <= t[0]) ?? TIERS[TIERS.length - 1]
90  // Integer-safe: tokens/window*100 >= from  <=>  tokens*100 >= from*window.
91  const reached = (from: number): boolean => tokens * 100 >= from * window
92  let hit = ramp[0]
93  for (const s of ramp) if (reached(s[0])) hit = s
94  const purpled = reached(purple)
95  const color = purpled ? XTERM[201] : XTERM[hit[1]]
96  let mark = ''
97  if (window > 800000) for (const [from, glyph] of LADDER) { if (reached(from)) mark = glyph }
98  else if (purpled) mark = '⚠'
99  return { color, bold: purpled || hit[2] === true, mark }
100}
101
102export function fivePaint(used: number): Paint {
103  return { ...step(FIVE, used), mark: used >= 95 ? '⚠' : '' }
104}
105
106const devMark = (dev: number): string => (dev >= 14 ? '💀' : dev >= 10 ? '💥' : dev >= 7 ? '⚠' : '')
107
108// The deviation alone colours the seven-day meter, whatever was used; from 95
109// percent used it is purple either way. With no deviation (no `resetsAt`) the
110// colour is the five-hour rule on percent used, and there is no mark.
111export function weekPaint(used: number, dev: number | null): Paint {
112  if (dev === null) return { ...step(FIVE, used), mark: '' }
113  if (used >= 95) return { color: XTERM[201], bold: true, mark: devMark(dev) }
114  return { ...step(DEV, dev), mark: devMark(dev) }
115}
116
117const PART = ['', '▏', '▎', '▍', '▌', '▋', '▊', '▉']
118
119// `cells` cells of bar: `fill` is the used part in eighths of a cell, rounded
120// down, and `track` the rest. Either may be ''.
121export function bar(part: number, whole: number, cells: number): { fill: string; track: string } {
122  const eighths = whole > 0 ? Math.floor((Math.max(0, Math.min(part, whole)) * cells * 8) / whole) : 0
123  const full = Math.floor(eighths / 8)
124  const last = PART[eighths % 8]
125  return { fill: '█'.repeat(full) + last, track: '░'.repeat(cells - full - (last ? 1 : 0)) }
126}
127
128// `bar` with cell `floor(mark / whole * cells)`, clamped to the bar, drawn as `│` over fill or track: the cells in runs of one kind.
129export function markedBar(part: number, whole: number, cells: number, mark: number): { text: string; kind: 'fill' | 'track' | 'mark' }[] {
130  const { fill, track } = bar(part, whole, cells)
131  const kinds = [...[...fill].map(() => 'fill' as const), ...[...track].map(() => 'track' as const)]
132  const at = Math.max(0, Math.min(cells - 1, Math.floor((mark * cells) / whole)))
133  const chars = [...fill, ...track]
134  chars[at] = '│'
135  kinds[at] = 'mark'
136  const runs: { text: string; kind: 'fill' | 'track' | 'mark' }[] = []
137  chars.forEach((ch, i) => {
138    const last = runs[runs.length - 1]
139    if (last && last.kind === kinds[i]) last.text += ch
140    else runs.push({ text: ch, kind: kinds[i] })
141  })
142  return runs
143}
144
145// The instant the window resets, epoch milliseconds, or null.
146export function resetMs(limit: Limit): number | null {
147  const at = typeof limit.resetsAt === 'string' ? Date.parse(limit.resetsAt) : NaN
148  return Number.isFinite(at) ? at : null
149}
150
151export const WEEK = 7 * 24 * 3600 * 1000
152export const FIVE_HOURS = 5 * 3600 * 1000
153
154// The share of a `span`-long window already gone by, 0 to 1, or null with no `resetsAt`.
155export function elapsed(limit: Limit, now: number, span: number): number | null {
156  const reset = resetMs(limit)
157  return reset === null ? null : Math.max(0, Math.min(1, 1 - (reset - now) / span))
158}
159
160// Percent used less the share of the seven days already gone by, in whole
161// points, rounded half away from zero as TokenBar does. Null with no `resetsAt`.
162export function deviation(limit: Limit, now: number): number | null {
163  const gone = elapsed(limit, now, WEEK)
164  if (gone === null) return null
165  const raw = limit.percentUsed - gone * 100
166  // `|| 0`: never -0.
167  return (raw >= 0 ? Math.floor(raw + 0.5) : Math.ceil(raw - 0.5)) || 0
168}
169
170// `1h 46m`, or `2d 12h 30m` where `days` is asked for; `now` once it is past.
171export function countdown(ms: number, days: boolean): string {
172  if (!(ms > 0)) return 'now'
173  const total = Math.floor(ms / 60000)
174  const two = (n: number): string => String(n).padStart(2, '0')
175  const hours = Math.floor(total / 60)
176  if (days) return `${Math.floor(hours / 24)}d ${two(hours % 24)}h ${two(total % 60)}m`
177  return `${hours}h ${two(total % 60)}m`
178}
179
180// Whole minutes in `ms`, never under zero: the band's stage minutes and the Pane's agent minutes are both this.
181export const minutes = (ms: number): number => Math.max(0, Math.floor(ms / 60000))
182// Whole seconds until `until`, a part second counted whole, never under zero: the band's badge counts down with it.
183export const secondsLeft = (until: number, now: number): number => Math.max(0, Math.ceil((until - now) / 1000))
184
185// ` 66%`: three cells of number, so a column of them lines up.
186export const pct = (n: number): string => `${String(Math.round(n)).padStart(3)}%`
187export const kilo = (n: number): string => (n >= 1e6 && n % 1e6 === 0 ? `${n / 1e6}M` : `${Math.round(n / 1000)}k`)
188export const signed = (dev: number): string => `${dev > 0 ? '+' : ''}${dev}%`
189
190// The window of that kind (`five_hour`, `seven_day`), or null; one with no number is no window.
191export function limitOf(limits: Limit[], kind: string): Limit | null {
192  return limits.find((l) => !!l && l.kind === kind && typeof l.percentUsed === 'number' && Number.isFinite(l.percentUsed)) ?? null
193}
194
hooks/pane-gate.ts 47 lines
1// Reading the pending file hooks/gate.js writes, for the band's gate badge. The
2// engine cannot require lib/, so the rules of lib/handoff.js are written again
3// here and tests/pane-gate.test.js pins each one to the function it copies.
4
5export type Question = { question: string; header?: string; multiSelect?: boolean; options: { label: string; description?: string }[] }
6export type Pending = { questions: Question[]; until: number; at: number | null }
7
8// lib/handoff.js dirFor.
9export function taskDir(root: string, entry: Record<string, unknown>): string | null {
10  const started = typeof entry.started === 'string' ? entry.started : ''
11  const stamp = started.replace(/[-:]/g, '').slice(0, 15)
12  if (!root || !/^\d{8}T\d{6}$/.test(stamp)) return null
13  return `${root.replace(/\\/g, '/').replace(/\/+$/, '')}/.fankeel/build/task-${stamp}`
14}
15
16// lib/handoff.js fileFor names the first lap `<stage>-pending.json` and the
17// n-th `<stage>-<n>-pending.json`; the newest lap is the one being waited on.
18export function pendingName(names: string[], stage: string): string | null {
19  let best: string | null = null
20  let lap = 0
21  for (const name of names) {
22    if (!name.startsWith(stage) || !name.endsWith('-pending.json')) continue
23    const mid = name.slice(stage.length, -'-pending.json'.length)
24    if (mid !== '' && !/^-\d+$/.test(mid)) continue
25    const n = mid === '' ? 1 : Number(mid.slice(1))
26    if (n > lap) {
27      lap = n
28      best = name
29    }
30  }
31  return best
32}
33
34// lib/handoff.js readPending: no questions array or an `until` already past is no gate;
35// `at` is when the wait began, or null.
36export function parsePending(text: string, now: number): Pending | null {
37  let got: unknown
38  try {
39    got = JSON.parse(text)
40  } catch {
41    return null
42  }
43  const g = got as { questions?: unknown; until?: unknown; at?: unknown } | null
44  if (!g || typeof g !== 'object' || !Array.isArray(g.questions) || !(typeof g.until === 'number' && g.until > now)) return null
45  return { questions: g.questions as Question[], until: g.until, at: typeof g.at === 'number' && Number.isFinite(g.at) ? g.at : null }
46}
47
hooks/pane-agents.ts 92 lines
1// The Pane's agent tree: Claude Code's own files about this session's
2// subagents in, a tree out. <configDir>/projects/<slug>/<session>/subagents/
3// holds agent-<id>.meta.json (agentType, description, parentAgentId) from the
4// dispatch on, and agent-<id>.prefix.json (state.model, state.effortValue)
5// from the agent's first request; when one stopped is in
6// .fankeel/build/agents-<session>.json (lib/agentends.js). No engine call
7// here, so tests/pane-agents.test.js runs it under plain node.
8
9export type AgentFile = { id: string; at: number; meta: Record<string, unknown> | null; prefix: Record<string, unknown> | null; tokens?: number | null }
10export type AgentNode = { id: string; title: string; type: string; model: string; effort: string; at: number; end: number | null; tokens: number | null; kids: AgentNode[] }
11
12const record = (v: unknown): Record<string, unknown> => (v && typeof v === 'object' ? (v as Record<string, unknown>) : {})
13const str = (v: unknown): string => (typeof v === 'string' ? v : '')
14
15// The prefix hooks/title.js opens a description with: `sonnet 5.5 · medium: `.
16const TITLED = /^([a-z]+(?: [\d.]+)?) · ([a-z]+): ([\s\S]*)$/
17
18// A model id as the title hook writes it: claude-sonnet-5-5 is sonnet 5.5; a
19// date and a context suffix such as [1m] are dropped; anything else stays as it is.
20export function modelAlias(id: string): string {
21  const m = /^claude-([a-z]+)-(\d+)(?:-(\d{1,2}))?(?:-\d{8})?(?:\[[^\]]*\])?$/.exec(id)
22  if (!m) return id
23  return m[3] ? `${m[1]} ${m[2]}.${m[3]}` : `${m[1]} ${m[2]}`
24}
25
26// What an agent's transcript spent: input, cache writes and output, cache
27// reads left out. A request is written as several lines under one requestId,
28// so each counts once and its last line wins; a line with none counts on its
29// own, as lib/usage.js does. No usage line at all is null, never 0.
30export function agentTokens(text: string): number | null {
31  const by = new Map<string, number>()
32  let loose = 0
33  for (const line of text.split('\n')) {
34    if (!line.trim()) continue
35    let e: Record<string, unknown>
36    try {
37      e = record(JSON.parse(line))
38    } catch {
39      continue
40    }
41    if (e.type !== 'assistant') continue
42    const usage = record(record(e.message).usage)
43    if (!Object.keys(usage).length) continue
44    const n = (k: string): number => (typeof usage[k] === 'number' && Number.isFinite(usage[k]) ? (usage[k] as number) : 0)
45    by.set(str(e.requestId) || `line-${loose++}`, n('input_tokens') + n('cache_creation_input_tokens') + n('output_tokens'))
46  }
47  if (!by.size) return null
48  let sum = 0
49  for (const v of by.values()) sum += v
50  return sum
51}
52
53// A token count the width of a minutes figure: 892, 79.4k, 1.7M.
54export function tokenLabel(n: number): string {
55  if (n < 1000) return String(n)
56  if (n < 1000000) return `${(n / 1000).toFixed(1)}k`
57  return `${(n / 1000000).toFixed(1)}M`
58}
59
60// Every subagent dispatched at or after `since`, hung under its parentAgentId;
61// one whose parent is not in the list is a root. The model is the prefix
62// file's, else the title's, else the meta's, else ?; the effort the prefix
63// file's, else the title's, else ?. Each list puts first an agent that runs or has one running under it, then the newest.
64export function agentTree(files: AgentFile[], ended: Record<string, number>, since: number): AgentNode[] {
65  const nodes = new Map<string, { node: AgentNode; parent: string }>()
66  for (const f of files) {
67    if (!f.meta || !(f.at >= since)) continue
68    const description = str(f.meta.description)
69    const titled = TITLED.exec(description)
70    const state = record(record(f.prefix).state)
71    const model = str(state.model) ? modelAlias(str(state.model)) : titled ? titled[1] : str(f.meta.model) || '?'
72    const effort = str(state.effortValue) || (titled ? titled[2] : '') || '?'
73    const end = typeof ended[f.id] === 'number' && Number.isFinite(ended[f.id]) ? ended[f.id] : null
74    const tokens = typeof f.tokens === 'number' && Number.isFinite(f.tokens) ? f.tokens : null
75    const node: AgentNode = { id: f.id, title: titled ? titled[3] : description, type: str(f.meta.agentType), model, effort, at: f.at, end, tokens, kids: [] }
76    nodes.set(f.id, { node, parent: str(f.meta.parentAgentId) })
77  }
78  const roots: AgentNode[] = []
79  for (const { node, parent } of nodes.values()) {
80    const up = parent ? nodes.get(parent) : undefined
81    if (up) up.node.kids.push(node)
82    else roots.push(node)
83  }
84  const live = (n: AgentNode): boolean => n.end === null || n.kids.some(live)
85  const order = (list: AgentNode[]): AgentNode[] => {
86    for (const n of list) order(n.kids)
87    list.sort((a, b) => (live(a) !== live(b) ? (live(a) ? -1 : 1) : b.at - a.at))
88    return list
89  }
90  return order(roots)
91}
92
hooks/pane-band.ts 231 lines
1// The two rows above the prompt: which station this session is at, then how
2// much is left of the context, the five-hour window and the seven-day one. An
3// entry and the engine's numbers in, segments out; no engine call here, so
4// tests/pane-band.test.js runs it under plain node.
5// docs/90-agent/plans/2026-10-12-pane-band-design.md sections 1 and 2.
6
7import { str, list, width, bar, markedBar, ctxPaint, ctxWindowPaint, fivePaint, weekPaint, deviation, elapsed, FIVE_HOURS, WEEK, limitOf, pct, kilo, signed, minutes, secondsLeft, DIM } from './pane-bar.ts'
8import type { Context, Limit, Paint } from './pane-bar.ts'
9
10// `gap` is the cells of space before the segment; without one it sits against the last.
11export type Seg = { text: string; color?: string; backgroundColor?: string; bold?: boolean; gap?: number }
12type Entry = Record<string, unknown>
13// `gateUntil` is the `until` of the gate that is waiting, or null, and `gateAt` the
14// `at` its pending file names, when the wait began: only the desktop's ring reads it.
15// `tasks` is the plan's ledger count, or null.
16export type BandInput = {
17  entry: Entry | null
18  others: { entry: Entry }[]
19  gateUntil: number | null
20  gateAt?: number | null
21  context: Context | null
22  limits: Limit[]
23  tasks: { done: number; total: number } | null
24  // Whether Remote Control is connected: Claude Code's session file has a bridgeSessionId.
25  remote?: boolean
26  // The session's model alias and effort; row one ends with them when there is a model.
27  model?: string | null
28  effort?: string | null
29  cols: number
30  now: number
31}
32
33// TokenBar's fankeel ramp (xterm 60 62 67 68 75 78 81), as hex.
34export const RAMP: Record<string, string> = {
35  survey: '#5f5f87',
36  design: '#5f5fd7',
37  plan: '#5f87af',
38  build: '#5f87d7',
39  verify: '#5fafff',
40  audit: '#5fd787',
41  land: '#5fd7ff',
42}
43// The stations still ahead, and a task not begun.
44export const TODO = '#767676'
45export const GUARD = '#d7af5f'
46export const FLAG = '#ff5f5f'
47export const WHERE = '#8a8a8a'
48export const CLASH = '#ff0000'
49export const INK = '#000000'
50// The ✓ of 遠端: the green of a finished task in the Pane.
51export const CONNECTED = '#87af5f'
52
53// A stage off the ramp (init, or one a later version adds) is drawn as secondary text.
54export const stageColor = (stage: string): string => (Object.hasOwn(RAMP, stage) ? RAMP[stage] : WHERE)
55
56export const claimsOf = (entry: Entry): string[] => list(entry.claims ?? entry.scope)
57
58// How many other sessions hold a file this one holds.
59export function clashes(entry: Entry, others: { entry: Entry }[]): number {
60  const mine = claimsOf(entry)
61  return others.filter((other) => claimsOf(other.entry).some((file) => mine.includes(file))).length
62}
63
64// When this visit to `stage` began: the last move into it, else the stage's
65// first clock mark. `clock` keeps one pair a stage, so a route-back reads
66// there as one long visit.
67export function since(entry: Entry, stage: string): number | null {
68  const moves = Array.isArray(entry.moves) ? entry.moves : []
69  for (let i = moves.length - 1; i >= 0; i--) {
70    const move = moves[i]
71    if (Array.isArray(move) && move[0] === stage && typeof move[1] === 'number') return move[1]
72  }
73  const clock = (entry.clock && typeof entry.clock === 'object' ? entry.clock : {}) as Record<string, unknown>
74  const pair = clock[stage]
75  return Array.isArray(pair) && typeof pair[0] === 'number' ? pair[0] : null
76}
77
78function inked(text: string, paint: Paint, gap = 0): Seg {
79  const seg: Seg = { text, color: paint.color }
80  if (paint.bold) seg.bold = true
81  if (gap) seg.gap = gap
82  return seg
83}
84
85// One way of drawing the second row. They are tried in this order and the first
86// that fits is drawn: the space round `│` closes up, then the bars shorten
87// together, then the 7d meter goes, then the 5h one. No reset is drawn here at
88// any width, and the Pane draws none either.
89type Shape = { five: boolean; week: boolean; sp: number; cells: number }
90function shapes(): Shape[] {
91  const out: Shape[] = [{ five: true, week: true, sp: 2, cells: 10 }]
92  for (const [five, week] of [[true, true], [true, false], [false, false]]) {
93    for (let cells = 10; cells >= 5; cells--) out.push({ five, week, sp: 1, cells })
94  }
95  return out
96}
97
98export function bandRows(input: BandInput): Seg[][] | null {
99  const { entry, others, gateUntil, context, limits, tasks, cols, now } = input
100  if (!entry) return null
101  const stage = str(entry.stage)
102  const route = list(entry.route)
103  const at = route.indexOf(stage)
104  const flags = clashes(entry, others)
105  const colour = stageColor(stage)
106  const rail: Seg = { text: '▌', color: flags ? CLASH : colour }
107  const used = (segs: Seg[]): number => segs.reduce((n, seg) => n + (seg.gap ?? 0) + width(seg.text), 0)
108
109  const head: Seg[] = [rail, { text: `FANKEEL ${stage.toUpperCase()}`, color: colour, bold: true }]
110  if (at >= 0) head.push({ text: '●'.repeat(at + 1), color: colour, gap: 2 })
111  if (route.length - at - 1 > 0) {
112    const ahead: Seg = { text: '○'.repeat(route.length - at - 1), color: TODO }
113    if (at < 0) ahead.gap = 2
114    head.push(ahead)
115  }
116  const count: Seg[] = tasks && tasks.total > 0
117    ? [{ text: 'tasks', color: WHERE, gap: 2 }, { text: `${Math.max(0, Math.min(tasks.done, tasks.total))}/${tasks.total}`, gap: 1 }]
118    : []
119  const started = since(entry, stage)
120  const here: Seg[] = started === null
121    ? []
122    : [{ text: '本站', color: WHERE, gap: 2 }, { text: String(minutes(now - started)), gap: 1 }, { text: '分', color: WHERE, gap: 1 }]
123  const waits = (entry.waited && typeof entry.waited === 'object' ? entry.waited : {}) as Record<string, unknown>
124  const wait = waits[stage]
125  const waited = typeof wait === 'number' && Number.isFinite(wait) ? minutes(wait) : 0
126  const gate: Seg[] = gateUntil === null
127    ? []
128    : [
129        { text: ' gate 在等 ', backgroundColor: GUARD, color: INK, bold: true, gap: 2 },
130        { text: `還 ${secondsLeft(gateUntil, now)} 秒`, color: GUARD, bold: true, gap: 2 },
131      ]
132  const yours: Seg[] = gateUntil === null
133    ? [{ text: '等你', color: WHERE, gap: 2 }, { text: String(waited), gap: 1 }, { text: '分', color: WHERE, gap: 1 }]
134    : [{ text: `等你 ${waited} 分`, color: GUARD, gap: 2 }]
135  // Follows the stage groups on row one and is the second group dropped, after the model: ✓ in green while Remote Control is connected, ✗ in the grey text colour when not (off is normal, not an alarm).
136  const remote: Seg[] = [{ text: '遠端', color: WHERE, gap: 2 }, input.remote ? { text: '✓', color: CONNECTED, gap: 1 } : { text: '✗', color: WHERE, gap: 1 }]
137  const model: Seg[] = input.model ? [{ text: input.effort ? `${input.model} · ${input.effort}` : input.model, color: WHERE, gap: 2 }] : []
138  // `drop` is how many of the five droppable groups are gone: the model, then 遠端, then the stage minutes, then the wait, then tasks.
139  const firstAt = (drop: number): Seg[] => {
140    const a = drop < 5 ? count : []
141    const b = drop < 4 ? yours : []
142    const c = drop < 3 ? here : []
143    const r = drop < 2 ? remote : []
144    const m = drop < 1 ? model : []
145    return gateUntil === null ? [...head, ...a, ...c, ...b, ...r, ...m] : [...head, ...a, ...gate, ...b, ...c, ...r, ...m]
146  }
147  let first = firstAt(0)
148  for (let drop = 1; drop <= 5 && used(first) > cols; drop++) first = firstAt(drop)
149
150  const five = limitOf(limits, 'five_hour')
151  const week = limitOf(limits, 'seven_day')
152  const secondAt = (shape: Shape): Seg[] => {
153    const row: Seg[] = [rail]
154    // A meter after the first is parted from it by `│`, with `sp` cells either side.
155    const open = (label: string): void => {
156      if (row.length === 1) {
157        row.push({ text: label, color: DIM })
158        return
159      }
160      row.push({ text: '│', color: DIM, gap: shape.sp }, { text: label, color: DIM, gap: shape.sp })
161    }
162    const draw = (part: number, whole: number, paint: Paint): void => {
163      const { fill, track } = bar(part, whole, shape.cells)
164      if (fill) row.push(inked(fill, paint))
165      if (track) row.push({ text: track, color: DIM })
166    }
167    const marked = (part: number, whole: number, at: number, paint: Paint, markSeg: (text: string) => Seg): void => {
168      for (const p of markedBar(part, whole, shape.cells, at)) {
169        if (p.kind === 'fill') row.push(inked(p.text, paint))
170        else row.push(p.kind === 'mark' ? markSeg(p.text) : { text: p.text, color: DIM })
171      }
172    }
173    if (context) {
174      const { window } = context
175      const sized = typeof window === 'number' && Number.isFinite(window) && window > 0
176      // With a window the colour and mark follow TokenBar's tiers by percent of that window; with none they follow the compact threshold. The white line is still the compact threshold.
177      const paint = sized ? ctxWindowPaint(context.tokens, window) : ctxPaint(context.tokens, context.at)
178      open('ctx ')
179      if (sized) {
180        // The white line sits at the compact threshold, when that is a point inside the window.
181        if (context.at < window) {
182          marked(context.tokens, window, context.at, paint, (text) => ({ text, color: '#ffffff', bold: true }))
183        } else {
184          draw(context.tokens, window, paint)
185        }
186        row.push(inked(kilo(context.tokens), paint, 1), { text: `/${kilo(window)}`, color: WHERE })
187      } else if (Number.isFinite(context.at)) {
188        draw(context.tokens, context.at, paint)
189        row.push(inked(kilo(context.tokens), paint, 1), { text: `/${kilo(context.at)}`, color: WHERE })
190      } else {
191        // No window, and compact.at off is an infinite threshold: the count alone, with nothing to measure it against.
192        row.push(inked(kilo(context.tokens), paint))
193      }
194      if (paint.mark) row.push(inked(paint.mark, paint, 1))
195    }
196    if (five && shape.five) {
197      const paint = fivePaint(five.percentUsed)
198      open('5h ')
199      // The even pace: a `│` at the share of the five hours gone by, as on the 7d meter of TokenBar.
200      const gone = elapsed(five, now, FIVE_HOURS)
201      if (gone === null) draw(five.percentUsed, 100, paint)
202      else {
203        marked(five.percentUsed, 100, gone * 100, paint, (text) => ({ text, color: WHERE }))
204      }
205      row.push(inked(pct(five.percentUsed), paint, 1))
206      if (paint.mark) row.push(inked(paint.mark, paint, 1))
207    }
208    if (week && shape.week) {
209      const dev = deviation(week, now)
210      const paint = weekPaint(week.percentUsed, dev)
211      open('7d ')
212      const gone = elapsed(week, now, WEEK)
213      if (gone === null) draw(week.percentUsed, 100, paint)
214      else {
215        marked(week.percentUsed, 100, gone * 100, paint, (text) => ({ text, color: WHERE }))
216      }
217      row.push(inked(pct(week.percentUsed), paint, 1))
218      if (dev !== null) {
219        row.push(inked(signed(dev), paint, 2))
220        if (paint.mark) row.push(inked(paint.mark, paint, 1))
221      }
222    }
223    if (flags) row.push({ text: `⚑${flags}`, color: FLAG, bold: true, gap: 2 })
224    return row
225  }
226  const tried = shapes().map(secondAt)
227  const second = tried.find((row) => used(row) <= cols) ?? tried[tried.length - 1]
228  // A second row with nothing but its rail is not drawn.
229  return second.length > 1 ? [first, second] : [first]
230}
231
hooks/pane-svg.ts 402 lines
1// The desktop drawings of the band and the Pane: the data hooks/pane-band.ts
2// and hooks/pane-status.ts turn into rows, turned into `<svg>` strings for the
3// engine's Svg element. No engine call here, so tests/pane-svg.test.js runs it
4// under plain node. docs/90-agent/plans/2026-10-14-pane-svg-design.md is the
5// design; the approved drawing is the mockup .fankeel/build/2026-10-14-pane-svg/gen.mjs wrote.
6
7import { TODO, GUARD, CONNECTED, FLAG, WHERE, CLASH, INK, stageColor, since, clashes, claimsOf } from './pane-band.ts'
8import type { BandInput } from './pane-band.ts'
9import { str, list, kilo, cut, ctxPaint, ctxWindowPaint, fivePaint, weekPaint, deviation, elapsed, FIVE_HOURS, limitOf, signed, minutes, secondsLeft, DIM } from './pane-bar.ts'
10import { ago, DONE } from './pane-status.ts'
11import type { Entry, Other, Row, StatusInput } from './pane-status.ts'
12
13// The engine's bound on SvgProps.source, in characters.
14export const SVG_MAX = 131072
15// One terminal cell in CSS pixels: the Pane's 41 cells are 328px, the band's 80 are 640px.
16const CELL_PX = 8
17const FONT = 'ui-monospace, SFMono-Regular, Menlo, Consolas, monospace'
18// The characters a 12px monospace face draws a full em wide: hooks/pane-bar.ts WIDE, and ⚑.
19const WIDE_PX = /[ᄀ-ᅟ⺀-꓏가-힣豈-﫿︰-﹏＀-⦆¢-₩⚑]/
20
21const esc = (s: string): string => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
22// The drawn width of `s` at `size` px: a wide character is one em, any other three fifths of one.
23const px = (s: string, size = 12): number => [...s].reduce((n, ch) => n + (WIDE_PX.test(ch) ? size : size * 0.6), 0)
24const r1 = (n: number): number => Math.round(n * 10) / 10
25const record = (v: unknown): Record<string, unknown> => (v && typeof v === 'object' ? (v as Record<string, unknown>) : {})
26
27// The head of `s` that fits `room` px, ending in an ellipsis when cut.
28function fitPx(s: string, room: number): string {
29  if (px(s) <= room) return s
30  let out = ''
31  for (const ch of s) {
32    if (px(out + ch + '…') > room) break
33    out += ch
34  }
35  return out + '…'
36}
37
38// The tail of `s` that fits: a path is told apart by its end.
39function tailPx(s: string, room: number): string {
40  if (px(s) <= room) return s
41  let out = ''
42  for (const ch of [...s].reverse()) {
43    if (px('…' + ch + out) > room) break
44    out = ch + out
45  }
46  return '…' + out
47}
48
49function svgDoc(w: number, h: number, body: string, extra = ''): string {
50  return `<svg xmlns="http://www.w3.org/2000/svg" width="${r1(w)}" height="${r1(h)}" viewBox="0 0 ${r1(w)} ${r1(h)}" font-family="${FONT}" font-size="12"${extra}>${body}</svg>`
51}
52
53// Text is grey unless `fill` says otherwise: the Svg is drawn as an image and cannot see the theme.
54function text(x: number, y: number, s: string, o: { fill?: string; bold?: boolean; anchor?: string } = {}): string {
55  const a = [`x="${r1(x)}"`, `y="${r1(y)}"`, `fill="${o.fill ?? WHERE}"`]
56  if (o.bold) a.push('font-weight="700"')
57  if (o.anchor) a.push(`text-anchor="${o.anchor}"`)
58  return `<text ${a.join(' ')}>${esc(s)}</text>`
59}
60
61// What an Svg says to a reader that cannot see it: the rows it stands for as the
62// terminal draws them, without the rail each row opens with, one line a row.
63export function altOf(rows: { text: string; gap?: number }[][]): string {
64  return rows.map((segs) => segs.slice(1).map((seg) => ' '.repeat(seg.gap ?? 0) + seg.text).join('')).join('\n')
65}
66
67// The band's rows are this tall, and a row's text sits on y 15.
68const BAND_H = 22
69
70// The band's first row: the badge, the route as dots (done filled in its
71// station's colour, here one hollow ring in it, ahead hollow grey), the tasks as small
72// cells, the gate's countdown ring, the wait and the stage minutes.
73export function bandRow1Svg(input: BandInput): string {
74  const { entry, others, gateUntil, tasks, cols, now } = input
75  if (!entry) return ''
76  const gateAt = input.gateAt ?? null
77  const stage = str(entry.stage)
78  const route = list(entry.route)
79  const at = route.indexOf(stage)
80  const colour = stageColor(stage)
81  let b = `<rect x="0" y="2" width="3" height="18" fill="${clashes(entry, others) ? CLASH : colour}"/>`
82  let x = 10
83  const head = `FANKEEL ${stage.toUpperCase()}`
84  b += text(x, 15, head, { fill: colour, bold: true })
85  x += px(head) + 6
86  if (route.length) {
87    const step = 14
88    const x0 = x + 6
89    const rad = (i: number): number => (i === at ? 5.75 : 4)
90    for (let i = 0; i < route.length - 1; i++) {
91      const a = x0 + step * i + rad(i) + 1
92      const z = x0 + step * (i + 1) - rad(i + 1) - 1
93      b += `<line x1="${r1(a)}" y1="11" x2="${r1(z)}" y2="11" stroke="${i < at ? WHERE : TODO}" stroke-width="${i < at ? 1.5 : 1}"/>`
94    }
95    route.forEach((name, i) => {
96      const c = stageColor(name)
97      const cx = r1(x0 + step * i)
98      if (i < at) b += `<circle cx="${cx}" cy="11" r="3.5" fill="${c}"/>`
99      else if (i === at) b += `<circle cx="${cx}" cy="11" r="5" fill="none" stroke="${c}" stroke-width="2"/>`
100      else b += `<circle cx="${cx}" cy="11" r="3.25" fill="none" stroke="${TODO}" stroke-width="1.5"/>`
101    })
102    x = x0 + step * (route.length - 1) + 7 + 12
103  }
104  if (tasks && tasks.total > 0) {
105    const done = Math.max(0, Math.min(tasks.done, tasks.total))
106    b += text(x, 15, 'tasks')
107    x += px('tasks') + 6
108    if (tasks.total <= 10) {
109      // Six px a cell while a cell a task still reads.
110      for (let i = 0; i < tasks.total; i++) {
111        b += `<rect x="${r1(x + i * 6)}" y="7" width="4" height="8" rx="1" fill="${i < done ? DONE : DIM}"/>`
112      }
113      x += tasks.total * 6 + 4
114    } else {
115      // Past ten, one bar on the 5h meter's track, so the band stops growing with the plan.
116      b += well(x, done / tasks.total, DONE)
117      x += WELL + 6
118    }
119    const n = `${done}/${tasks.total}`
120    b += text(x, 15, n, { bold: true })
121    x += px(n) + 12
122  }
123  const waits = record(entry.waited)
124  const wait = waits[stage]
125  const waited = typeof wait === 'number' && Number.isFinite(wait) ? minutes(wait) : 0
126  const started = since(entry, stage)
127  const here = started === null ? null : minutes(now - started)
128  const hereAt = (x0: number): string =>
129    here === null ? '' : text(x0, 15, '本站') + text(x0 + px('本站 '), 15, String(here), { bold: true }) + text(x0 + px(`本站 ${here} `), 15, '分')
130  if (gateUntil !== null) {
131    const label = 'gate 在等'
132    const w = px(label) + 12
133    b += `<rect x="${r1(x)}" y="2" width="${r1(w)}" height="18" rx="3" fill="${GUARD}"/>`
134    b += text(x + 6, 15, label, { fill: INK, bold: true })
135    x += w + 10
136    // The ring is full at the gate's whole wait (gate.station), from `at` to `until`.
137    const left = secondsLeft(gateUntil, now)
138    const whole = gateAt !== null && gateUntil > gateAt ? (gateUntil - gateAt) / 1000 : left
139    const share = whole > 0 ? Math.min(1, left / whole) : 0
140    const r = 6.5
141    const c = 2 * Math.PI * r
142    b += `<circle cx="${r1(x)}" cy="11" r="${r}" fill="none" stroke="${DIM}" stroke-width="2.5"/>`
143    b += `<circle cx="${r1(x)}" cy="11" r="${r}" fill="none" stroke="${GUARD}" stroke-width="2.5" stroke-dasharray="${r1(c * share)} ${r1(c)}" transform="rotate(-90 ${r1(x)} 11)"/>`
144    x += 11
145    b += text(x, 15, `${left} 秒`, { fill: GUARD, bold: true })
146    x += px(`${left} 秒`) + 12
147    b += text(x, 15, `等你 ${waited} 分`, { fill: GUARD })
148    x += px(`等你 ${waited} 分`) + 12
149    b += hereAt(x)
150    if (here !== null) x += px(`本站 ${here} 分`) + 12
151  } else {
152    b += hereAt(x)
153    if (here !== null) x += px(`本站 ${here} 分`) + 14
154    b += text(x, 15, '等你') + text(x + px('等你 '), 15, String(waited), { bold: true }) + text(x + px(`等你 ${waited} `), 15, '分')
155    x += px(`等你 ${waited} 分`) + 12
156  }
157  b += text(x, 15, '遠端') + text(x + px('遠端 '), 15, input.remote ? '✓' : '✗', input.remote ? { fill: CONNECTED } : {})
158  return svgDoc(cols * CELL_PX, BAND_H, b)
159}
160
161// A meter: a DIM well, the used part in its paint, then any marks over it.
162const WELL = 96
163function well(x0: number, share: number, color: string, marks = ''): string {
164  let s = `<rect x="${r1(x0)}" y="6" width="${WELL}" height="10" rx="2" fill="${DIM}"/>`
165  const fw = Math.max(0, Math.min(1, share)) * (WELL - 2)
166  if (fw > 0) s += `<rect x="${r1(x0 + 1)}" y="7" width="${r1(fw)}" height="8" rx="1.5" fill="${color}"/>`
167  return s + marks
168}
169
170// The band's second row: ctx, 5h and 7d as meters parted by a grey rule, then ⚑N.
171// The same choices as hooks/pane-band.ts bandRows: ctx is measured against the
172// window where the engine reports one, with a grey line at the compact point
173// inside it, else against the threshold; with neither, the count alone. ''
174// where the row has nothing to draw.
175export function bandRow2Svg(input: BandInput): string {
176  const { entry, others, context, limits, now, cols } = input
177  if (!entry) return ''
178  const flags = clashes(entry, others)
179  const rail = `<rect x="0" y="2" width="3" height="18" fill="${flags ? CLASH : stageColor(str(entry.stage))}"/>`
180  // One pass over the row. `flagFirst` puts ⚑N right after the rail instead of last.
181  const layout = (flagFirst: boolean): { b: string; x: number; drawn: number } => {
182    let b = rail
183    let x = 10
184    let drawn = 0
185    const open = (label: string): void => {
186      if (drawn++) {
187        x += 14
188        b += `<line x1="${r1(x)}" y1="4" x2="${r1(x)}" y2="18" stroke="${DIM}" stroke-width="1"/>`
189        x += 10
190      }
191      b += text(x, 15, label)
192      x += px(label) + 6
193    }
194    const after = (s: string, o: { fill?: string; bold?: boolean } = {}, gap = 0): void => {
195      b += text(x + gap, 15, s, o)
196      x += gap + px(s)
197    }
198    if (flags && flagFirst) {
199      after(`⚑${flags}`, { fill: FLAG, bold: true })
200      drawn++
201    }
202    if (context) {
203      const window = context.window
204      const sized = typeof window === 'number' && Number.isFinite(window) && window > 0
205      const finite = Number.isFinite(context.at)
206      const paint = sized ? ctxWindowPaint(context.tokens, window as number) : ctxPaint(context.tokens, context.at)
207      const whole = sized ? (window as number) : finite ? context.at : 0
208      open('ctx')
209      if (whole > 0) {
210        const mark = sized && finite && context.at < whole
211          ? `<rect x="${r1(x + 1 + (context.at / whole) * (WELL - 2) - 1)}" y="2" width="2" height="18" rx="1" fill="${WHERE}"/>`
212          : ''
213        b += well(x, context.tokens / whole, paint.color, mark)
214        x += WELL + 6
215      }
216      after(kilo(context.tokens), { bold: true })
217      if (whole > 0) after(`/${kilo(whole)}`)
218      if (paint.mark) after(paint.mark, { fill: paint.color, bold: true }, 6)
219    }
220    const five = limitOf(limits, 'five_hour')
221    if (five) {
222      const paint = fivePaint(five.percentUsed)
223      open('5h')
224      // The even pace: the share of the five hours gone by, the same thin grey tick as 7d.
225      const gone = elapsed(five, now, FIVE_HOURS)
226      const pace = gone === null ? '' : `<rect x="${r1(x + 1 + gone * (WELL - 2) - 0.75)}" y="3" width="1.5" height="16" fill="${WHERE}"/>`
227      b += well(x, five.percentUsed / 100, paint.color, pace)
228      x += WELL + 6
229      after(`${Math.round(five.percentUsed)}%`, { bold: true })
230      if (paint.mark) after(paint.mark, { fill: paint.color, bold: true }, 6)
231    }
232    const week = limitOf(limits, 'seven_day')
233    if (week) {
234      const dev = deviation(week, now)
235      const paint = weekPaint(week.percentUsed, dev)
236      open('7d')
237      // The even pace: the share of the seven days gone by, a thin grey tick.
238      const pace = dev === null
239        ? ''
240        : `<rect x="${r1(x + 1 + (Math.max(0, Math.min(100, week.percentUsed - dev)) / 100) * (WELL - 2) - 0.75)}" y="3" width="1.5" height="16" fill="${WHERE}"/>`
241      b += well(x, week.percentUsed / 100, paint.color, pace)
242      x += WELL + 6
243      after(`${Math.round(week.percentUsed)}%`, { bold: true })
244      if (dev !== null) after(signed(dev), {}, 6)
245      if (paint.mark) after(paint.mark, { fill: paint.color, bold: true }, 6)
246    }
247    if (flags && !flagFirst) after(`⚑${flags}`, { fill: FLAG, bold: true }, drawn ? 14 : 0)
248    return { b, x, drawn }
249  }
250  // Last first. Only when the row as drawn ends past the Svg's width, and there
251  // is something for the flag to move ahead of, does it go to the front.
252  let row = layout(false)
253  if (flags && row.drawn && row.x > cols * CELL_PX) row = layout(true)
254  return row.drawn || flags ? svgDoc(cols * CELL_PX, BAND_H, row.b) : ''
255}
256
257// The Pane's width in px: one cell is CELL_PX.
258const paneW = (cols: number): number => cols * CELL_PX
259
260type Station = { name: string; state: 'done' | 'here' | 'ahead'; min: number | null; wait: number }
261
262// The route under the task title: a column a station, its dot (done green, here
263// one hollow ring in its station's colour, ahead hollow grey), a bar of the minutes it took from the entry's
264// `clock` against the longest, and the minutes its gate waited (`waited`) in
265// amber at the bar's end. '' when the stage is not on the route.
266export function routeSvg(entry: Entry, now: number, cols: number): string {
267  const route = list(entry.route)
268  const at = route.indexOf(str(entry.stage))
269  if (at < 0) return ''
270  const W = paneW(cols)
271  const clock = record(entry.clock)
272  const waits = record(entry.waited)
273  const stations: Station[] = route.map((name, i): Station => {
274    if (i > at) return { name, state: 'ahead', min: null, wait: 0 }
275    const pair = clock[name]
276    const from = Array.isArray(pair) && typeof pair[0] === 'number' ? pair[0] : null
277    const to = i === at ? now : Array.isArray(pair) && typeof pair[1] === 'number' ? pair[1] : null
278    const wait = waits[name]
279    return {
280      name,
281      state: i < at ? 'done' : 'here',
282      min: from !== null && to !== null ? minutes(to - from) : null,
283      wait: typeof wait === 'number' && Number.isFinite(wait) ? minutes(wait) : 0,
284    }
285  })
286  const n = stations.length
287  const slot = W / n
288  const cx = (i: number): number => slot * i + slot / 2
289  const max = Math.max(1, ...stations.map((s) => s.min ?? 0))
290  let b = ''
291  stations.forEach((s, i) => {
292    b += text(cx(i), 12, fitPx(s.name, slot - 2), { anchor: 'middle', bold: s.state === 'here', fill: s.state === 'ahead' ? TODO : WHERE })
293  })
294  b += `<line x1="${r1(cx(0))}" y1="26" x2="${r1(cx(at))}" y2="26" stroke="${DONE}" stroke-width="2"/>`
295  b += `<line x1="${r1(cx(at))}" y1="26" x2="${r1(cx(n - 1))}" y2="26" stroke="${TODO}" stroke-width="1"/>`
296  stations.forEach((s, i) => {
297    const x = r1(cx(i))
298    if (s.state === 'done') b += `<circle cx="${x}" cy="26" r="4" fill="${DONE}"/>`
299    else if (s.state === 'here') b += `<circle cx="${x}" cy="26" r="6" fill="none" stroke="${stageColor(s.name)}" stroke-width="2.5"/>`
300    else b += `<circle cx="${x}" cy="26" r="3.75" fill="none" stroke="${TODO}" stroke-width="1.5"/>`
301  })
302  const full = slot - 10
303  stations.forEach((s, i) => {
304    if (s.min === null) return
305    const w = Math.max(3, (s.min / max) * full)
306    const ww = s.wait ? Math.min(w, Math.max(2, (s.wait / max) * full)) : 0
307    const x0 = cx(i) - w / 2
308    if (w - ww > 0) b += `<rect x="${r1(x0)}" y="38" width="${r1(w - ww)}" height="4" rx="1" fill="${s.state === 'done' ? DONE : WHERE}"/>`
309    if (ww) b += `<rect x="${r1(x0 + w - ww)}" y="38" width="${r1(ww)}" height="4" rx="1" fill="${GUARD}"/>`
310    b += text(cx(i), 56, `${s.min}分`, { anchor: 'middle', bold: s.state === 'here' })
311    if (s.wait) b += text(cx(i), 72, `等${s.wait}`, { anchor: 'middle', fill: GUARD })
312  })
313  return svgDoc(W, 78, b)
314}
315
316// The clash as a small graph: the files this session shares on the left, the
317// sessions holding them on the right, a red line for each hold; under each
318// session its station's colour, its stage and how long since it moved. ''
319// where no file is shared.
320export function clashSvg(entry: Entry, others: Other[], now: number, cols: number): string {
321  const files = claimsOf(entry).filter((file) => others.some((other) => claimsOf(other.entry).includes(file)))
322  if (!files.length) return ''
323  const holders = others.filter((other) => claimsOf(other.entry).some((file) => files.includes(file)))
324  const W = paneW(cols)
325  const fileY = (i: number): number => 16 + i * 26
326  const whoY = (j: number): number => 14 + j * 40
327  const h = Math.max(fileY(files.length - 1) + 14, whoY(holders.length - 1) + 30)
328  // 10, 174 and 218 of the mockup's 328px.
329  const L = 10
330  const LW = Math.round(W * 0.53)
331  const RX = L + LW + 34
332  let b = `<rect x="0" y="0" width="3" height="${h}" fill="${FLAG}"/>`
333  files.forEach((file, i) => {
334    b += text(L, fileY(i), '⚑', { fill: FLAG, bold: true })
335    b += text(L + 16, fileY(i), tailPx(file, LW - 16), { fill: FLAG, bold: true })
336    holders.forEach((other, j) => {
337      if (!claimsOf(other.entry).includes(file)) return
338      const y1 = fileY(i) - 4
339      const y2 = whoY(j) - 4
340      b += `<path d="M ${L + LW + 4} ${y1} C ${L + LW + 22} ${y1}, ${RX - 20} ${y2}, ${RX - 6} ${y2}" fill="none" stroke="${FLAG}" stroke-width="1.5"/>`
341    })
342    b += `<circle cx="${L + LW + 4}" cy="${fileY(i) - 4}" r="2.5" fill="${FLAG}"/>`
343  })
344  holders.forEach((other, j) => {
345    const stage = str(other.entry.stage) || '?'
346    const age = ago(other.entry.updated, now)
347    b += `<circle cx="${RX - 6}" cy="${whoY(j) - 4}" r="2.5" fill="${FLAG}"/>`
348    b += text(RX, whoY(j), fitPx(str(other.entry.task) || other.id.slice(0, 8), W - RX - 2), { bold: true })
349    b += `<circle cx="${RX + 4}" cy="${whoY(j) + 13}" r="3.5" fill="${stageColor(stage)}"/>`
350    b += text(RX + 12, whoY(j) + 17, age ? `${stage} · ${age}` : stage)
351  })
352  return svgDoc(W, h, b)
353}
354
355// One piece of the desktop Pane, top to bottom: rows drawn as Text, as the
356// terminal draws them, or one Svg.
357export type Part = { rows: Row[] } | { source: string; alt: string; isInteractive?: boolean }
358
359// The desktop Pane from the rows statusRows drew for the same input: the task
360// title, `next:`, the tasks, the agents, notes and the foot stay rows; the route
361// rows and the clash become one Svg each, whose alt is those rows' text. A
362// drawing with nothing in it, or one over SVG_MAX, stays rows.
363export function paneParts(input: StatusInput, rows: Row[]): Part[] {
364  const parts: Part[] = []
365  const keep = (rs: Row[]): void => {
366    if (!rs.length) return
367    const last = parts[parts.length - 1]
368    if (last && 'rows' in last) last.rows.push(...rs)
369    else parts.push({ rows: [...rs] })
370  }
371  const draw = (source: string, rs: Row[], isInteractive: boolean): void => {
372    if (!source || source.length > SVG_MAX || !rs.length) return keep(rs)
373    const alt = altOf(rs.map((r) => r.segs))
374    parts.push(isInteractive ? { source, alt, isInteractive } : { source, alt })
375  }
376  // A block opens with the blank row above it, but for the first.
377  const blocks: Row[][] = []
378  for (const r of rows) {
379    if (!r.segs.length || !blocks.length) blocks.push([r])
380    else blocks[blocks.length - 1].push(r)
381  }
382  const { entry, now, cols } = input
383  for (const block of blocks) {
384    const lead = block[0].segs.length ? [] : [block[0]]
385    const body = block.slice(lead.length)
386    keep(lead)
387    const name = body.length ? body[0].block : ''
388    if (!entry) keep(body)
389    else if (name === 'task') {
390      // The route rows end the block: each holds only station names and ` › `.
391      const route = list(entry.route)
392      const isRoute = (r: Row): boolean => r.segs.length > 1 && r.segs.slice(1).every((seg) => route.includes(seg.text) || seg.text === ' › ')
393      let from = body.length
394      while (from > 0 && isRoute(body[from - 1])) from--
395      keep(body.slice(0, from))
396      draw(routeSvg(entry, now, cols), body.slice(from), false)
397    } else if (name === 'clash') draw(clashSvg(entry, input.others, now, cols), body, false)
398    else keep(body)
399  }
400  return parts
401}
402