Optional heads-up display beside the status line, as a mod (function hooks, Claude Code 2.1.293 or later): a Tasks pane with the open epics of kodflow-hooks'…

An optional heads-up display beside the status line. One pane and a few toasts, nothing else: the status line keeps the context gauge, the epics' pills and everything it already draws, and this mod shows only what it does not.
waiting), a task gone silent: at most one per task and per state.It is a mod: a hooks module (hooks/mod/register.tsx) the engine loads from hooks/hooks.json → modules. It needs Claude Code 2.1.293 or later (tested on 2.1.296, the version the CI pins) and reads the task list that kodflow-hooks keeps; without kodflow-hooks the Tasks pane says there is no list.
The subagents have no pane of their own: Claude Code lists them under the prompt, and the tree names the one at work on each task. An older version had an « Agents » tab; it said the same as the engine's list, and as a second pane it kept coming in front of « Tâches » (below).
/plugin install kodflow-hud@kodflow
scripts/install.sh at the repository root installs it with the others. claude plugin disable kodflow-hud@kodflow turns it off without touching the rest.
| Command | Effect |
|---|---|
/hud (/hud tasks, tâches) | opens the Tasks pane, or shows it when it is up, with the keyboard |
/hud off (close) | closes it |
/hud agents | says the Agents tab is gone (a toast and the command's answer) |
With autoOpen on (the default) the Tasks pane opens when a session starts. A session that starts with the pane still up (a reload, a restart) keeps it; an « Agents » tab an older version left up is closed then, once: a close shows the pane left, never brings a new one in front. Every poll (3 s) the tab is retitled when its count moved.
Why one pane: in the engine (2.1.309) the tabs stand in the order the panes were opened (a new one goes last, a retitle keeps its place, and $.ui.open takes no index); a NEW pane is shown unless a pane holds the keyboard; and a mod cannot show a pane already up except with focus, which the engine grants only while no pane holds the keyboard and which hands the pane the keyboard. So a second tab that opened with the first subagent came in front of « Tâches », and with « Tâches » opened first it could not be brought back without taking the keyboard. /hud uses focus, at the person's command.
The tab holds still under a click, as the tree's rows do: its title is always its name and its count, one width from 0 to 99 (« Tâches (0) », a figure space after a single digit), so a tab of another plugin beside it does not move from under the pointer; and a retitle never changes the tab shown.
The engine seats a pane nobody asked for only where it has room — from 144 columns, docked beside the transcript in the fullscreen layout — and keeps it waiting below that; /hud seats it at any width.
Captures in text of the drawn tree, read back by the tests at the pane's minimum: 90 columns with its frame (88 of body) by 20 rows. Colour is the text's alone, and always one of the theme's own colours, which the engine shades for a light or a dark theme: merged (purple) the epic and the critical path, warning (amber) the task under way, success (green) done, planMode (teal) ready, permission the tasks waiting on the person, error (red) blocked or frozen, ide (blue) the model, claude the main loop. Each subagent has one mid-tone colour of its own for the session (eight, picked from its id, none a state's), on every row it works. No cell paints a background, so a transparent terminal shows through.
R12, the tree (the view a pane opens on):
─ #1 Routage model/effort ──────────────────────────────────────────────────────────────
TÂCHE AGENT MODÈLE ÂGE LIENS
◆ #1 Routage model/effort 7/15 1 h 52
├▸ ✓ T0 Événements réels ◉ principal opus 2 h ⇢ C6 C7
├▸ ✓ C1–C5 Policy et routage ◉ principal opus 1 h 20 ⇢ C9
┃ ├▾ ● C6 Porte Fable ↳ mkt-routi… · general opus·xhigh 12 min ⇢ C9
│ ├─ ✓ agent.spawn ◉ principal opus 20 min
┃ │ ├▾ ● Grant de session ↳ mkt-routi… · general opus·xhigh 3 min ⇢ #10
│ │ ├─ ✓ Test resume ◉ principal opus 8 min
┃ │ │ └─ ⊘ Test parallèle ⇠ #8
│ └─ ○ Repli shell
┃ ├─ ◇ C7 Feedback agents toi 6 min ⇢ C9
┃ ├▸ ▶ C8 Spécialistes ×5 prête ⇢ C9
┃ └─ ⊘ C9 CI et PR ⇠ C6 C7 C8
┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
┃ chemin critique C6 → C9 · C7 → C9 · C8 → C9 · #8 → #10 bloqué par toi (C7)
● C6 Porte Fable mkt-routing-pr · general-purpose · opus·xhigh · 12 min · ⇢ C9 · figé
Le mod juge, il ne réécrit jamais e.model
────────────────────────────────────────────────────────────────────────────────────────
Arbre Graphe Refus (0) Documents (0) ↑↓ choisir · ⏎ plier · tab vue
R4, the graph (tab, or a click on « Graphe »):
─ #1 Routage model/effort ──────────────────────────────────────────────────────────────
FAIT · PRÊT EN COURS · ATTENTE BLOQUÉ
✓ T0 Événements réels ──┬─▶ ● C6 Porte Fable ───────┐
principal · opus · 2 h │ mkt-routing-pr · 12 min │
└─▶ ◇ C7 Feedback agents ───┤
attend toi · 6 min │
✓ C1–C5 Policy et routage ────────────────────────────────┼─▶ ⊘ C9 CI et PR
principal · 1 h 20 │ attend C6 C7 C8
▶ C8 Spécialistes ×5 ──────────────────────────────────┘
prête · personne dessus
┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄
prochaine action ▶ C8 prête, personne dessus t'attend ◇ C7 · 6 min
┃ chemin critique C6 → C9 · C7 → C9 · C8 → C9 · #8 → #10
livrable ⊘ C9 CI et PR · attend C6 C7 C8
────────────────────────────────────────────────────────────────────────────────────────
Arbre Graphe Refus (0) Documents (0) ↑↓ choisir · ⏎ plier · tab vue
Every column is a Box of a fixed width, a gap of 2 between them; what goes in one is cut to it first, counted in terminal cells (string-width's count: wide characters and emoji two, the ambiguous glyphs ✓ ● ◆ ▶ ┃ ⇢ one), so nothing is lined up with spaces and a long title never shifts a column.
| Column | Cells | What |
|---|---|---|
| margin | 2 | ┃ for a task on the critical path |
| tree | 30 | 3 a level, the glyph 2, the ref 7 (top level), the title 17, cut with … |
| agent | 22 | ◉ principal (the main loop, theme colour claude), ↳ name · role (a subagent in its own colour, the role its type short: general, a specialist's topic; the name cut first, the role keeping up to seven cells; no role when the type is unknown), toi for the person's, prête for a ready task |
| model | 10 | opus·xhigh, sonnet·med: the family and the effort, shortened to fit |
| age | 6 | right-aligned: 45 s, 12 min, 1 h 20, 2 h, 3 j; red when silent |
| links | 10 | ⇠ C6 C7 C8 what it waits on, else ⇢ C9 what it unblocks, then +n |
An epic's line carries no agent and no model: its title runs over those columns, followed by its progress, 7/15 (green once every task is done). The tasks filed under no epic sit under a quiet ◌ Hors épopée, with no number, no progress and no age. The section's title never repeats the tab's name: the epic when one is open (#1 Routage model/effort), else how many (2 épopées ouvertes), then the tasks under no epic (1 tâche hors épopée).
Glyphs: ✓ done, ● under way, ◇ waiting on the person, ▶ ready — pending, every blocker done, nobody on it —, ⊘ blocked — pending with a blocker left —, ○ a subtask left to do under a task not done (whoever takes the task takes it). ▸/▾ a task with subtasks, folded or not. The critical path is the longest blockedBy chain of tasks not done, down to the epic's final tasks; every task on a chain of that length gets the margin, the footer names the chains and the task that waits on the person (« bloqué par toi » when it is on the path).
Rows, at 20: the title, the headers, the epic (done/total, its age), 11 tasks, a rule, the critical path, two lines on the selection (its glyph, ref, title, agent and role, model, age, links, CI, « figé » when silent, then its description) and the views' bar. One top-level task is open at a time.
Narrower than 88 cells of body the links go, then the model under 76, then the agent under 64: below that, the tree and the age. Fewer than 20 rows, the finished top-level branches fold into « ✓ fait (n) » first, then the detail drops to one line, then to none, then the list scrolls with the selection. The fold sits first under its epic, where the finished work mostly stood, the open tasks below it in their order, and only the last row of the epic turns └─:
◆ #3 Forgejo Raft 68/69 20 j
├─ ✓ fait (68)
┃ └─ ● F7 F7 observateur e… 8 min
Three columns of 26 — FAIT · PRÊT, EN COURS · ATTENTE, BLOQUÉ — and two gutters of 5; each top-level task on two rows, its title then its agent and age. A gutter joins its links on a vertical (┬ ┐ ┤ ┼ ┘ └), links that share no lane on stretches of their own; a task feeding the right-hand column directly runs on a lane the middle one leaves free, as a solid line, so no two lines cross. Links within a column, or leftwards, are not drawn (the tree shows them). The footer gives the next action (a ready task, on the path first), what waits on the person, the critical path and the deliverable (the epic's final task, and what it waits on). Narrower than 88 cells the three columns share what is left; under 40 a node no longer holds its glyph, ref and title, and the graph says so in place of its lanes.
| Key or click | Effect |
|---|---|
↑ ↓ | choose a task |
⏎ (or space) | fold or unfold it; opening a top-level task folds the other |
tab | the next view: Arbre, Graphe, Refus, Documents, then Arbre again |
| click on a task | choose it; on a task with subtasks, or a second click, fold it |
| click on « Arbre » / « Graphe » / « Refus » / « Documents » | that view |
The tree is a Client region (hooks/mod/client.tsx, a surface module): the engine hands it keys once a click has given it the focus (Escape gives the focus back) and every pointer event over it, in cells (ClientSurface.onKey, ClientSurface.onPointer in the engine's claude-code typings). The selection, the open branches and the view live in that instance's state, across redraws. The terminal and the desktop draw a Client; VS Code and the mobile app do not, and get the same tree drawn still, at its first state.
A click never moves the row it hit. The task chosen is pinned to the line it was clicked on (Ui.pin, hooks/mod/layout.tsx): the next screen scrolls, and picks the finished branches folded or not, so that it stays there. A click that opens a top-level task folds the ones below it, never one above. ↑ ↓ pin the task on its line too, so the list moves only when the selection leaves it, by one line. Before this, the list re-centred on the task chosen and opening a branch closed the one above it: the row moved from under the pointer, and a second click landed on another task.
What kodflow-hooks refused in this session, read from blocks.jsonl (the session's folder, beside tasks.json; one JSON line a blocking, 500 kept), newest first: the time, the kind (hook, classifier, permission, ci, agent), the tool, the summary and, when kodflow-hooks could deduce it, the permission rule that would have allowed the call. Above the list, what has piled up: the count of each kind in the last hour and since the session began, and the reason seen most often (a hook's motif, else the summary). The count in the bar is the last hour's.
The unlock. A click on a refusal that carries a rule (or ⏎ on it) shows that exact rule on the confirmation line, and where it would go:
Autoriser Bash(git push:*) dans .claude/settings.local.json ?
[ajouter] [copier] [annuler] a · c · n
Only « ajouter » (or a) writes: the rule joins permissions.allow of the project's .claude/settings.local.json (the session's root), every other key kept, written whole (a file beside it, then mv) or not at all, never over a file that is not a JSON object. « copier » puts the rule on the clipboard for /permissions; « annuler » closes the line. Why this road:
$.settings is read only) nor to open /permissions on a given rule: $.command.run would open the dialog, where the rule is still picked by hand, which is what the button is meant to spare.ui.message), and no tool, no hook and nothing the model says goes that way. The hooks module checks it again: the rule must be one a refusal of this session carries, in settings.json's shape, one line, at most 200 characters, and never one that hands over a whole shell or every write (Bash, Edit, Write, Bash(*), Edit(**)...).settings.local.json is the narrowest place a rule can live: this project, this machine, not committed. A broader one is still the person's to add with /permissions.A refusal with no rule (a classifier's, a CI run's) shows its detail and its link, nothing to add.
The project's documents as kodflow-hooks computes them (docs.json, the session's folder): one line each, ● green present, ● red missing, ○ grey ignored (with the manifest's reason), and its path. The count in the bar is the missing ones.
⏎) ignores the document, or brings it back: the project's docs/manifest.json (at the git root, the path docs.json names) is rewritten whole, its unknown keys kept, the documents in the catalogue's order, two spaces, a final newline; never over a file that is not a JSON object. The line changes at once, without waiting for kodflow-hooks to recompute docs.json.c), « Créer les manquants » (or t) put the docs prompt in the prompt box as a DRAFT, never sent: /kodflow-workflow:docs trd,flow --mode both, with no id for every missing one. The mode is chosen on the same line, ask, context or both (the default; m turns it). A box that already holds a draft is never overwritten: a toast says so. The draft is posed by $.prompt.fill; Escape gives the keyboard back to the prompt, ⏎ sends it.The tab strip shows the panes of every plugin, « Tâches » among them. What switches them is the engine's, not this mod's: a click on a tab, ctrl+x tab (the keyboard to the next pane, which is then shown), and the engine's pane:next / pane:previous actions ("show next/previous plugin pane"), bound to no key by default; binding one in ~/.claude/keybindings.json does it from the prompt, for example (ctrl+x n is free in 2.1.309):
{ "bindings": [{ "context": "Global", "bindings": { "ctrl+x n": "pane:next" } }] }
The letters a and t that once switched to « Agents » and back are gone with that tab. They could not have worked: a mod is handed keys only while its pane holds the keyboard, and 2.1.309 shows a pane already up only on focus, which it declines exactly then.
| Shown | Source |
|---|---|
| epics and tasks | <config>/kodflow/sessions/<session>/tasks.json (version 2, kodflow-hooks' file), re-read whenever its modification time moves, looked at every 3 s and right after a task_* call |
| worker, its state | the task's worker / worker_id, matched against $.agent.list(); kept once the task moves on (tasks.json drops it) |
| subtasks, links, ref | the task's parent, blockedBy, ref (kodflow-hooks' task_create / task_update) |
| ready, blocked, critical path | derived from those links, nothing typed |
| model · effort | a subagent's: the Agent call's effort and its result's resolvedModel, the model agent.spawn resolved, and kodflow-hooks' agent-models.tsv (its PostToolUse record); the main loop's: $.session.model(), no effort (none is said to a mod). A loop no source names has an empty cell, never a guess |
| time since it moved | the later of the task's updated and the last tool call of its loop (worker, else the agent that owns it) |
| silent | in progress, and its loop stopped, gone from the list, or quiet for silentMinutes |
toi | tasks with assignee: "human", when tasks.json carries the field |
| CI | gh pr checks <url> for the GitHub pull request URLs an open task cites, every 5 minutes at most |
Nothing is a second source of truth: the pane draws from $.state, which holds what was last read from tasks.json, $.agent.list() and, for each loop, the time of its last tool call; a reload of the module reads them again.
tool.call is observed after next: the result goes back as it came, even when the observation fails (.catch replays next). A refused call is not recorded.context; one system prompt section, the colour convention, and none with KODFLOW_COLORS=off. /hud answers one short line, as any command does.find, no fs.list. The only process it runs is gh pr checks, and only for cited pull requests.The model may wrap a few words of a reply in a mark; the transcript draws them in colour, bold, and the mark is not shown:
| Mark | Colour | Meaning |
|---|---|---|
{{r:words}} | red | what blocks |
{{o:words}} | orange | what needs attention |
{{v:words}} | green | what waits on the person, their answer or their action |
{{p:words}} | pink | a decision the person already made, cited with its date |
The convention reaches the model as one system prompt section, kodflow-hud:colors, added last by a prompt.compose hook on the session side of the cache boundary. It is composed afresh for every prompt, so it holds after a compaction. It says when to mark and how: a few words, a few marks a message at most, never in code, a command, a path or a table meant to be copied, and p only for a decision of the person's whose date is cited. It is left out where nothing draws the reply: a -p run (the print trait), --bare, a render with no surface.
A ui.render hook on AssistantMessage redraws a reply that holds a mark, paragraph by paragraph (paragraphs split on blank lines): a marked paragraph becomes coloured runs, every other one, and every fenced code block, goes back to the engine's Markdown. A mark inside a code block, an unclosed fence or inline code is shown as typed. A reply with no mark is the engine's own drawing, untouched. A failure while drawing falls back to the engine's (.catch replays next(e)).
KODFLOW_COLORS=off (or 0, false, no) turns off both the drawing and the prompt section.
Limits:
prompt.compose hook does not run (claude plugin validate says so): the drawing works, but the model is not told the convention.Set them in /config or under pluginConfigs["kodflow-hud"].options.
| Option | Default | Meaning |
|---|---|---|
silentMinutes | 10 | quiet time after which a task in progress is flagged silent |
autoOpen | true | open the Tasks pane when a session starts |
ci | true | ask gh pr checks about cited pull requests |
KODFLOW_HUD_TRACE=/absolute/path.json writes what the pane would draw to that file when the session ends: how a run with no pane (claude -p, a bench) shows what was collected.
claude -p: there is no screen; the hooks run (collection, trace), no pane is drawn and toasts go nowhere. Expected./hud or a wider window.The panes sit on an opaque grey block even when the terminal background is transparent. The mod is not the cause and cannot remove it: it draws no background of its own (grep backgroundColor hooks/mod finds nothing).
In Claude Code 2.1.300 the engine wraps the docked pane column in a box painted with the theme token composerSidebarBackground (rgb(38, 38, 38) in the dark preset, ansi256(235) once the terminal maps it). $.ui.open (PaneOpenArgs: id, title, focus, closeOnEscape, holdToasts, rows, columns) has no option for it, the Pane render props carry none, and a backgroundColor inside the tree is read only as rgb(), #hex, ansi256(), ansi:<name> or a theme key: nothing means "terminal default". The token is not in the documented list of custom theme overrides.
Workarounds, none of them in this plugin:
background-opacity-cells = true (available since 1.2.0). Per the Ghostty reference, the opacity then also applies to cells that carry an explicit background colour, which is the case of the grey block.~/.claude/themes/ can override composerSidebarBackground with the colour of your terminal background. The token is undocumented and read from the 2.1.300 bundle, not from the documentation, and the override is an opaque colour: it hides the grey without making the pane see-through.Until the engine offers a transparent or default-background pane surface, this stays one of its limits.
git commit written inside an echo counts, anhooks/mod/register.tsx 763 lines1// register.tsx — kodflow-hud's function hooks: wiring only.
2//
3// One pane and a few toasts, beside the status line and never in its place
4// (the context segment, the epics' pills and the rest stay there):
5// « Tâches » the open epics of tasks.json as a tree (subtasks, what each
6// task waits on, the critical path) or as a graph by state,
7// who works each task, on what model, how long since it moved,
8// the silent ones and the ones waiting on the person; the
9// only pane, its tab counting the tasks left.
10// Two more views in its bar: « Refus », what kodflow-hooks
11// refused (blocks.jsonl), and « Documents », the project's
12// documents (docs.json), panels.ts.
13// The subagents themselves are the engine's to show, under the prompt.
14// And a few words of each reply in colour (colors.ts): the transcript draws
15// `{{r:words}}` red, `{{o:…}}` orange, `{{v:…}}` green, `{{p:…}}` pink.
16//
17// Everything is read, nothing is decided: tasks.json is kodflow-hooks' file,
18// re-read whenever its modification time moves; the agents come from
19// `$.agent.list()`; each loop's last call from `tool.call`, observed after
20// `next` and handed back untouched. No tool, no context line, no refusal: this mod
21// can stop nothing, and adds one thing only to what the model reads, the
22// colour convention's system prompt section (off with KODFLOW_COLORS=off,
23// which also turns off the drawing). Every hook fails open.
24//
25// Three writes, each only on the person's own click or key in the pane
26// (`ui.message`, posted by the surface module and checked again here), never
27// on the model's word nor a hook's: a document ignored or brought back in
28// the project's docs/manifest.json; a permission rule, shown first and then
29// confirmed, added to the project's .claude/settings.local.json; the docs
30// prompt drafted in an EMPTY prompt box, never sent.
31//
32// The logic lives in the pure modules beside this file (board.ts, tree.ts,
33// layout.tsx, models.ts, alerts.ts, ci.ts); the
34// « Tâches » pane's selection and folding live in its surface module,
35// client.tsx; what is here reads `$`.
36
37import { atom, read, update } from "claude-code";
38import type { Register } from "claude-code";
39import type {
40 HudActivity,
41 HudAgent,
42 HudBlock,
43 HudBoard,
44 HudDoc,
45 HudDocs,
46 HudCi,
47 HudModel,
48 HudSeen,
49 HudTask,
50} from "../../types";
51import { MAIN, parseBoard, parseTasks, type Ctx } from "./board.ts";
52import { alertsFor, trimKeys } from "./alerts.ts";
53import { CI_EVERY_MS, ciState, prsToCheck } from "./ci.ts";
54import { configDir, sessionDir, tasksFile } from "./paths.ts";
55import { buildTree } from "./tree.ts";
56import { draw, initialUi } from "./layout.tsx";
57import { SETTINGS_LOCAL, viewScreen, type Extra } from "./panels.ts";
58import {
59 MODES,
60 NO_DOCS,
61 createPrompt,
62 manifestPath,
63 parseDocs,
64 toggleManifest,
65 type DocMode,
66} from "./docs.ts";
67import { addRule, parseBlocks, safeRule } from "./refusals.ts";
68import {
69 PROMPT_SECTION,
70 SECTION_ID,
71 blocks,
72 colorsOff,
73 drawn,
74 marked,
75} from "./colors.ts";
76import {
77 fromAgentCall,
78 keepSession,
79 merge,
80 modelKey,
81 parseModels,
82 seenFrom,
83} from "./models.ts";
84
85const boardAtom = atom(
86 { plugin: "kodflow-hud", key: "board" } as const,
87 {
88 found: false,
89 epics: [],
90 } as HudBoard,
91);
92const agentsAtom = atom(
93 { plugin: "kodflow-hud", key: "agents" } as const,
94 [] as HudAgent[],
95);
96const activityAtom = atom(
97 { plugin: "kodflow-hud", key: "activity" } as const,
98 {} as Record<string, HudActivity>,
99);
100const ciAtom = atom(
101 { plugin: "kodflow-hud", key: "ci" } as const,
102 {} as Record<string, HudCi>,
103);
104const toastedAtom = atom(
105 { plugin: "kodflow-hud", key: "toasted" } as const,
106 [] as string[],
107);
108const modelsAtom = atom(
109 { plugin: "kodflow-hud", key: "models" } as const,
110 {} as Record<string, HudModel>,
111);
112const seenAtom = atom(
113 { plugin: "kodflow-hud", key: "seen" } as const,
114 {} as Record<string, HudSeen>,
115);
116const docsAtom = atom(
117 { plugin: "kodflow-hud", key: "docs" } as const,
118 NO_DOCS as HudDocs,
119);
120const blocksAtom = atom(
121 { plugin: "kodflow-hud", key: "blocks" } as const,
122 [] as HudBlock[],
123);
124const primedAtom = atom({ plugin: "kodflow-hud", key: "primed" } as const, "");
125const tickAtom = atom({ plugin: "kodflow-hud", key: "tick" } as const, 0);
126
127export const TASKS_PANE = "hud-tasks";
128/**
129 * The pane an older version opened beside « Tâches »: the engine's own
130 * list of subagents under the prompt says the same. Closed once when a
131 * session starts, which leaves « Tâches » the tab shown.
132 */
133export const AGENTS_PANE = "hud-agents";
134
135/**
136 * « Tâches (2) »: a name and its count, always of one width up to 99 (a
137 * figure space after a single digit, the count even at 0). A tab that grew
138 * or shrank with its count would move the tab beside it from under the
139 * pointer.
140 */
141export const tabTitle = (name: string, n: number): string =>
142 `${name} (${n})${"\u2007".repeat(Math.max(0, 2 - String(n).length))}`;
143
144/** « Tâches (2) »: the tasks left to do across the open epics. */
145export const tasksTitle = (board: HudBoard): string =>
146 tabTitle(
147 "Tâches",
148 board.epics.flatMap((e) => e.tasks).filter((t) => t.status !== "completed")
149 .length,
150 );
151
152/** How often tasks.json's time and the agents are looked at. */
153export const POLL_MS = 3_000;
154/** The elapsed times redraw on this step, not on every poll. */
155const TICK_MS = 10_000;
156const TASK_TOOL = /^mcp__kodflow-hooks__task_(create|update|epic|focus)$/;
157
158// What the module keeps between polls. A reload starts these over, which
159// costs one re-read of tasks.json; everything drawn is in `$.state`.
160let polling = false;
161let checking = false;
162let syncing = false;
163let lastSession = "";
164let lastMtime: number | undefined = -1;
165let modelsMtime: number | undefined = -1;
166let modelsPath = "";
167let allTasks: HudTask[] = [];
168// tasks.json as last read: the board is judged again on every poll, since an
169// epic done 30 minutes ago leaves it without the file changing
170let lastText: string | undefined;
171let lastCi = 0;
172// docs.json and blocks.jsonl: re-read when their time moves
173const seenMtime: Record<string, number | undefined> = {};
174let home: string | undefined;
175
176// Atoms are written only when their value changed: every write redraws
177const same = (a: unknown, b: unknown): boolean =>
178 JSON.stringify(a) === JSON.stringify(b);
179
180async function tasksPath($: any, session: string): Promise<string | undefined> {
181 const cfg = configDir(await $.env.get("CLAUDE_CONFIG_DIR"), home);
182 return cfg ? tasksFile(sessionDir(cfg, session)) : undefined;
183}
184
185/** Fold what a source says of some loops into the models kept. */
186async function noteModels(
187 $: any,
188 said: Record<string, HudModel>,
189): Promise<void> {
190 const session = await $.session.id();
191 const fold = (before: Record<string, HudModel>) => {
192 const after = keepSession(before, session);
193 for (const [id, m] of Object.entries(said)) {
194 const key = modelKey(session, id);
195 after[key] = merge(after[key], m);
196 }
197 return after;
198 };
199 // Folded inside the update, on the latest record: two Agent results
200 // arriving together each keep the other's entry
201 const now = await read($, modelsAtom);
202 if (!same(now, fold(now))) await update($, modelsAtom, fold);
203}
204
205/**
206 * kodflow-hooks' agent-models.tsv, when its time moved, and the main loop's
207 * model: what the tree's model column reads beside the calls seen live.
208 */
209async function pollModels($: any, tasks: string): Promise<void> {
210 const path = tasks.replace(/tasks\.json$/, "agent-models.tsv");
211 const mtime = await $.fs.stat(path).then(
212 (s: { mtimeMs: number }) => s.mtimeMs,
213 () => undefined,
214 );
215 const said: Record<string, HudModel> = {};
216 // Another session's file is read afresh whatever its time says; a read
217 // that failed is not remembered as done, so the next poll tries again
218 if (mtime !== undefined && (path !== modelsPath || mtime !== modelsMtime)) {
219 const text: string | undefined = await $.fs
220 .read(path)
221 .catch(() => undefined);
222 if (text !== undefined) {
223 Object.assign(said, parseModels(text));
224 modelsMtime = mtime;
225 modelsPath = path;
226 }
227 } else if (mtime === undefined) {
228 modelsMtime = undefined;
229 modelsPath = path;
230 }
231 const main = await $.session.model().catch(() => undefined);
232 if (typeof main === "string" && main) said[MAIN] = { model: main };
233 if (Object.keys(said).length) await noteModels($, said);
234}
235
236function ctxOf(
237 now: number,
238 agents: HudAgent[],
239 activity: Record<string, HudActivity>,
240 silentMs: number,
241): Ctx {
242 return { now, agents, activity, silentMs };
243}
244
245/** A file of the session's folder, when its time moved: its text, or null. */
246async function changed(
247 $: any,
248 path: string,
249): Promise<string | undefined | null> {
250 const mtime = await $.fs.stat(path).then(
251 (s: { mtimeMs: number }) => s.mtimeMs,
252 () => undefined,
253 );
254 if (path in seenMtime && seenMtime[path] === mtime) return null;
255 const text =
256 mtime === undefined ? undefined : await $.fs.read(path).catch(() => null);
257 if (text === null) return null;
258 seenMtime[path] = mtime;
259 return text;
260}
261
262/** docs.json and blocks.jsonl, beside tasks.json, kodflow-hooks' too. */
263async function pollSide($: any, tasks: string): Promise<void> {
264 const dir = tasks.replace(/\/tasks\.json$/, "");
265 const docs = await changed($, `${dir}/docs.json`);
266 if (docs !== null) {
267 const parsed = parseDocs(docs);
268 if (!same(await read($, docsAtom), parsed))
269 await update($, docsAtom, () => parsed);
270 }
271 const blocks = await changed($, `${dir}/blocks.jsonl`);
272 if (blocks !== null) {
273 const parsed = parseBlocks(blocks);
274 if (!same(await read($, blocksAtom), parsed))
275 await update($, blocksAtom, () => parsed);
276 }
277}
278
279/**
280 * Writes `text` to `path` whole or not at all: a file beside it, then `mv`
281 * over it (a rename, atomic on one file system).
282 */
283async function writeWhole($: any, path: string, text: string): Promise<void> {
284 const tmp = `${path}.kodflow-hud.tmp`;
285 await $.fs.write(tmp, text);
286 const r = await $.process.run(["mv", "-f", tmp, path], { timeoutMs: 5_000 });
287 if (r.exitCode !== 0) throw new Error(r.stderr || `mv: ${r.exitCode}`);
288}
289
290/** Whether a document's path is there: a folder needs one .md in it. */
291async function present($: any, root: string, path: string): Promise<boolean> {
292 const abs = `${root.replace(/\/+$/, "")}/${path}`;
293 if (!path.endsWith("/")) return $.fs.exists(abs).catch(() => false);
294 const list: any[] = await $.fs.list(abs).catch(() => []);
295 return list.some((f) => f.kind === "file" && /\.md$/i.test(f.name));
296}
297
298/** A document ignored or brought back, in the project's manifest. */
299async function setIgnored($: any, id: string, ignore: boolean): Promise<void> {
300 const docs = await read($, docsAtom);
301 const doc = docs.docs.find((d) => d.id === id);
302 const path = manifestPath(docs);
303 if (!doc || !path) {
304 $.ui.toast("kodflow-hud : pas de manifeste à réécrire pour ce document.");
305 return;
306 }
307 const before: string | undefined = await $.fs
308 .read(path)
309 .catch(() => undefined);
310 const after = toggleManifest(before, id, ignore);
311 if (after === undefined) {
312 $.ui.toast(
313 `kodflow-hud : ${docs.manifest ?? "docs/manifest.json"} n'est pas un objet JSON, laissé tel quel.`,
314 );
315 return;
316 }
317 await writeWhole($, path, after);
318 // kodflow-hooks recomputes docs.json on its own clock: the line changes now
319 const state: HudDoc["state"] = ignore
320 ? "ignored"
321 : (await present($, docs.root!, doc.path))
322 ? "ok"
323 : "missing";
324 await update($, docsAtom, (d) => ({
325 ...d,
326 docs: d.docs.map((x): HudDoc => {
327 if (x.id !== id) return x;
328 const { reason: _r, ...rest } = x;
329 return ignore ? { ...rest, state, reason: "" } : { ...rest, state };
330 }),
331 }));
332}
333
334/** The docs prompt in the prompt box, as a draft: only where the box is empty. */
335async function draftCreate(
336 $: any,
337 ids: string[],
338 mode: DocMode,
339): Promise<void> {
340 const box = await $.prompt.read().catch(() => ({ text: "" }));
341 if (box.text.trim()) {
342 $.ui.toast(
343 "kodflow-hud : la zone de saisie a déjà un brouillon, vide-la puis reclique.",
344 );
345 return;
346 }
347 const r = await $.prompt.fill({ text: createPrompt(ids, mode) });
348 $.ui.toast(
349 r.isFilled
350 ? "kodflow-hud : brouillon prêt dans la zone de saisie (Échap, relis, puis ⏎)."
351 : "kodflow-hud : la zone de saisie n'a pas pris le brouillon.",
352 );
353}
354
355/**
356 * A rule the person confirmed, in the project's .claude/settings.local.json:
357 * only one a refusal of this session carries, and only one `safeRule` lets
358 * through.
359 */
360async function allowRule($: any, rule: string): Promise<void> {
361 const blocks = await read($, blocksAtom);
362 if (!safeRule(rule) || !blocks.some((b) => b.rule === rule)) {
363 $.ui.toast(
364 "kodflow-hud : règle refusée (trop large, ou d'aucun refus de la session).",
365 );
366 return;
367 }
368 const root = await $.session.root();
369 const path = `${String(root).replace(/\/+$/, "")}/${SETTINGS_LOCAL}`;
370 const before: string | undefined = await $.fs
371 .read(path)
372 .catch(() => undefined);
373 const after = addRule(before, rule);
374 if (after === undefined) {
375 $.ui.toast(
376 `kodflow-hud : ${SETTINGS_LOCAL} n'est pas un objet JSON, laissé tel quel.`,
377 );
378 return;
379 }
380 if (after !== before) await writeWhole($, path, after);
381 $.ui.toast(`kodflow-hud : ${rule} autorisé dans ${SETTINGS_LOCAL}.`);
382}
383
384/** What the pane's surface module posted, checked as input from code. */
385async function onMessage($: any, data: unknown): Promise<void> {
386 const d = data as Record<string, unknown> | null;
387 if (!d || typeof d !== "object") return;
388 const ids = (await read($, docsAtom)).docs.map((x) => x.id);
389 if (d.op === "ignore" && typeof d.id === "string" && ids.includes(d.id))
390 return setIgnored($, d.id, d.ignore === true);
391 if (d.op === "create" && Array.isArray(d.ids)) {
392 const mode = (MODES as readonly unknown[]).includes(d.mode)
393 ? (d.mode as DocMode)
394 : "both";
395 const missing = new Set(
396 (await read($, docsAtom)).docs
397 .filter((x) => x.state === "missing")
398 .map((x) => x.id),
399 );
400 const asked = d.ids.filter(
401 (x): x is string => typeof x === "string" && missing.has(x),
402 );
403 if (asked.length !== d.ids.length || (!asked.length && !missing.size))
404 return;
405 return draftCreate($, asked, mode);
406 }
407 if (d.op === "allow" && typeof d.rule === "string")
408 return allowRule($, d.rule);
409 if (d.op === "copy" && typeof d.rule === "string") {
410 const r = await $.ui.copy({ text: d.rule });
411 $.ui.toast(
412 r.isCopied
413 ? `kodflow-hud : ${d.rule} copié (/permissions, Ajouter une règle).`
414 : `kodflow-hud : copie impossible, la règle est ${d.rule}.`,
415 );
416 }
417}
418
419/** One look at the world: tasks.json, the agents, the TTLs, the toasts. */
420async function poll($: any, silentMs: number, ci: boolean): Promise<void> {
421 if (polling) return;
422 polling = true;
423 try {
424 const now = await $.clock.now();
425 const session = await $.session.id();
426 const path = await tasksPath($, session);
427 if (path) {
428 const mtime = await $.fs.stat(path).then(
429 (s: { mtimeMs: number }) => s.mtimeMs,
430 () => undefined,
431 );
432 if (session !== lastSession || mtime !== lastMtime) {
433 const text =
434 mtime === undefined
435 ? undefined
436 : await $.fs.read(path).catch(() => undefined);
437 let raw: unknown = undefined;
438 try {
439 raw = text === undefined ? undefined : JSON.parse(text);
440 } catch {
441 raw = undefined;
442 }
443 allTasks = parseTasks(raw);
444 lastText = text;
445 const seen = seenFrom(allTasks, await read($, seenAtom), session);
446 if (seen) await update($, seenAtom, () => seen);
447 lastSession = session;
448 lastMtime = mtime;
449 }
450 const board = parseBoard(lastText, now);
451 if (!same(await read($, boardAtom), board))
452 await update($, boardAtom, () => board);
453 await pollModels($, path);
454 await pollSide($, path);
455 }
456 const listed = await $.agent.list().catch(() => []);
457 const agents: HudAgent[] = listed.map((a: any) => ({
458 id: a.id,
459 // Its name, else the few words of its task: its type is its role,
460 // shown beside the name, so it does not stand in for one
461 label: a.name || a.description || a.type || a.id.slice(0, 8),
462 status: a.status,
463 ...(a.name && { name: String(a.name) }),
464 ...(a.type && { type: String(a.type) }),
465 }));
466 if (!same(await read($, agentsAtom), agents))
467 await update($, agentsAtom, () => agents);
468 await syncPanes($).catch(() => undefined);
469
470 const ctx = ctxOf(now, agents, await read($, activityAtom), silentMs);
471 const baseline = (await read($, primedAtom)) !== session;
472 const toasted = await read($, toastedAtom);
473 const { alerts, keys } = alertsFor(
474 session,
475 allTasks,
476 ctx,
477 new Set(toasted),
478 baseline,
479 );
480 if (keys.length)
481 await update($, toastedAtom, (k) => trimKeys([...k, ...keys]));
482 if (baseline) await update($, primedAtom, () => session);
483 for (const a of alerts) $.ui.toast(a.text);
484
485 const tick = Math.floor(now / TICK_MS);
486 if ((await read($, tickAtom)) !== tick)
487 await update($, tickAtom, () => tick);
488 if (ci && now - lastCi >= CI_EVERY_MS) {
489 lastCi = now;
490 void checkCi($);
491 }
492 } finally {
493 polling = false;
494 }
495}
496
497/** `gh pr checks` for each pull request an open task cites, one at a time. */
498async function checkCi($: any): Promise<void> {
499 if (checking) return;
500 checking = true;
501 try {
502 const prs = prsToCheck((await read($, boardAtom)).epics);
503 for (const pr of prs) {
504 const r = await $.process
505 .run(["gh", "pr", "checks", pr], { timeoutMs: 20_000 })
506 .catch(() => undefined);
507 const state = r ? ciState(r.exitCode, r.stdout, r.stderr) : "error";
508 const at = await $.clock.now();
509 await update($, ciAtom, (m) => ({ ...m, [pr]: { state, at } }));
510 }
511 } finally {
512 checking = false;
513 }
514}
515
516/** A finished tool call: its loop is alive now, whatever the call did. */
517async function record($: any, e: any): Promise<void> {
518 const loop: string = e.agentId ?? MAIN;
519 const now = await $.clock.now();
520 await update($, activityAtom, (m) => ({
521 ...m,
522 [loop]: { agentId: loop, last: now },
523 }));
524}
525
526/** « Tâches » retitled when its count moved: a retitle never moves a tab. */
527async function syncPanes($: any): Promise<void> {
528 if (syncing) return;
529 syncing = true;
530 try {
531 const panes: any[] = await $.ui.panes().catch(() => []);
532 if (!Array.isArray(panes)) return;
533 const title = tasksTitle(await read($, boardAtom));
534 const tasks = panes.find((p) => p.id === TASKS_PANE);
535 if (tasks && tasks.title !== title)
536 await $.ui.open({ id: TASKS_PANE, title });
537 } finally {
538 syncing = false;
539 }
540}
541
542/**
543 * Open « Tâches », or show it when it is up: `focus` is the engine's only
544 * way to show a pane already open, granted while no pane holds the
545 * keyboard (as after a command), and it hands the pane the keyboard.
546 */
547async function openTasks($: any): Promise<boolean> {
548 const r = await $.ui.open({
549 id: TASKS_PANE,
550 title: tasksTitle(await read($, boardAtom)),
551 focus: true,
552 });
553 return r.isPlaced;
554}
555
556/** Write what the pane would draw to KODFLOW_HUD_TRACE, when it is set. */
557async function trace($: any): Promise<void> {
558 const path = await $.env.get("KODFLOW_HUD_TRACE");
559 if (!path || !path.startsWith("/")) return;
560 await poll($, settings.silentMs, false);
561 const dump = {
562 board: await read($, boardAtom),
563 agents: await read($, agentsAtom),
564 activity: await read($, activityAtom),
565 };
566 await $.fs.write(path, JSON.stringify(dump, null, 1));
567}
568
569// The options, as register received them
570const settings = { silentMs: 10 * 60_000, ci: true };
571
572/** Poll now, in the background; a failure waits for the next period. */
573function kick($: any): void {
574 void poll($, settings.silentMs, settings.ci).catch(() => undefined);
575}
576
577export const register: Register = (on, options) => {
578 settings.silentMs = Math.max(1, Number(options.silentMinutes ?? 10)) * 60_000;
579 settings.ci = options.ci !== false;
580 const autoOpen = options.autoOpen !== false;
581
582 on("session.start", async ($, e, next) => {
583 home = await $.env.get("HOME");
584 await $.command.register({
585 name: "hud",
586 description: "kodflow-hud: open the Tasks pane (/hud off closes it)",
587 });
588 // Unasked, the engine seats a pane only where it has room (144 columns);
589 // below that it waits, and /hud seats it at any width. « Tâches » is the
590 // only pane, so the first tab and the one shown. An Agents tab an older
591 // version left up is closed: a close shows the pane left, never a new one
592 const up: any[] = await $.ui.panes().catch(() => []);
593 const has = (id: string) =>
594 Array.isArray(up) && up.some((p) => p.id === id);
595 if (has(AGENTS_PANE))
596 await $.ui.close({ id: AGENTS_PANE }).catch(() => undefined);
597 if (autoOpen || has(TASKS_PANE))
598 await $.ui
599 .open({ id: TASKS_PANE, title: tasksTitle(await read($, boardAtom)) })
600 .catch(() => undefined);
601 $.clock.every(POLL_MS, () => kick($));
602 kick($);
603 return next(e);
604 }).catch(($, e, next) => next(e));
605
606 // A run with no pane (`claude -p`, a bench) can still show what was
607 // collected: KODFLOW_HUD_TRACE names a file, written at the session's end
608 on("session.end", async ($, e, next) => {
609 await trace($);
610 return next(e);
611 }).catch(($, e, next) => next(e));
612
613 on("command.run", { command: "hud" }, async ($, e) => {
614 const arg = e.args.trim().toLowerCase();
615 if (arg === "off" || arg === "close") {
616 await $.ui.close({ id: TASKS_PANE }).catch(() => undefined);
617 return { text: "kodflow-hud: pane closed." };
618 }
619 if (arg === "agents") {
620 $.ui.toast(
621 "kodflow-hud : l'onglet Agents est retiré, les sous-agents sont sous le prompt.",
622 );
623 return {
624 text: "kodflow-hud: the Agents tab is gone; Claude Code lists the subagents under the prompt.",
625 };
626 }
627 kick($);
628 return {
629 text: (await openTasks($))
630 ? `kodflow-hud: ${tasksTitle(await read($, boardAtom)).trim()} open.`
631 : "kodflow-hud: no room to seat a pane here (a -p run or a host without panes).",
632 };
633 });
634
635 // Observation only: the call runs first, its result goes back as it came
636 on("tool.call", async ($, e, next) => {
637 const r: any = await next(e);
638 if (r?.deny === undefined) {
639 await record($, e).catch(() => undefined);
640 if (TASK_TOOL.test(String(e.tool))) kick($);
641 if (e.tool === "Agent" && !r?.isError) {
642 const said = fromAgentCall(e as { effort?: unknown }, r?.result);
643 if (said)
644 await noteModels($, { [said.id]: said.model }).catch(() => undefined);
645 }
646 }
647 return r;
648 }).catch(($, e, next) => next(e));
649
650 // The model core resolved for a subagent it started, whoever asked
651 on("agent.spawn", async ($, e, next) => {
652 const r: any = await next(e);
653 if (r?.deny === undefined && typeof r?.agentId === "string" && r.model)
654 await noteModels($, { [r.agentId]: { model: String(r.model) } }).catch(
655 () => undefined,
656 );
657 return r;
658 }).catch(($, e, next) => next(e));
659
660 on(
661 "ui.render",
662 { component: "Pane", requestId: TASKS_PANE },
663 async ($, e) => {
664 const els: any = $.ui.resolve(e);
665 await read($, tickAtom);
666 const [board, agents, activity, ciMap, models, seen] = await Promise.all([
667 read($, boardAtom),
668 read($, agentsAtom),
669 read($, activityAtom),
670 read($, ciAtom),
671 read($, modelsAtom),
672 read($, seenAtom),
673 ]);
674 const model = buildTree({
675 board,
676 ctx: ctxOf(await $.clock.now(), agents, activity, settings.silentMs),
677 ci: ciMap,
678 models,
679 seen,
680 session: await $.session.id(),
681 });
682 const width = e.props.bodyColumns;
683 const rows = e.props.scroll.bodyRows;
684 const extra: Extra = {
685 docs: await read($, docsAtom),
686 blocks: await read($, blocksAtom),
687 now: await $.clock.now(),
688 };
689 // Where the surface runs modules (terminal, desktop) the tree takes
690 // keys and clicks; elsewhere it is drawn still, at its first state
691 // (the table may name Client where the surface then drops it)
692 const { Client } = els;
693 if (Client && (e.surface === "terminal" || e.surface === "desktop"))
694 return (
695 <Client
696 key="tree"
697 module="./client.tsx"
698 props={{ model, width, rows, extra }}
699 width={width}
700 height={rows}
701 />
702 );
703 return draw(
704 els,
705 viewScreen(model, initialUi(model), width, rows, extra),
706 width,
707 );
708 },
709 );
710
711 // A click or a key in the pane: the only road to the three writes
712 on("ui.message", async ($, e, next) => {
713 if (e.requestId === TASKS_PANE && e.module.endsWith("client.tsx"))
714 await onMessage($, e.data).catch(() =>
715 $.ui.toast("kodflow-hud : l'écriture a échoué, rien n'a changé."),
716 );
717 return next(e);
718 }).catch(($, e, next) => next(e));
719
720 // The colour convention, on the session's side of the cache boundary: a
721 // section composed afresh for every prompt, so a compaction keeps it. Only
722 // where a transcript will draw the reply (no -p run, no --bare)
723 on("prompt.compose", async ($, e, next) => {
724 const r = await next(e);
725 if (colorsOff(await $.env.get("KODFLOW_COLORS")) || !drawn(e)) return r;
726 const sections = r.sections.filter((s) => s.id !== SECTION_ID);
727 return {
728 ...r,
729 sections: [
730 ...sections,
731 { id: SECTION_ID, text: PROMPT_SECTION, scope: "session" as const },
732 ],
733 };
734 }).catch(($, e, next) => next(e));
735
736 // A reply with a mark is redrawn paragraph by paragraph: a marked one as
737 // coloured runs, any other as the engine's markdown. No mark: the engine's
738 // own drawing. Any failure draws the engine's
739 on("ui.render", { component: "AssistantMessage" }, async ($, e, next) => {
740 if (colorsOff(await $.env.get("KODFLOW_COLORS"))) return next(e);
741 const parts = blocks(e.props.text);
742 if (!marked(parts)) return next(e);
743 const { Box, Text, Markdown }: any = $.ui.resolve(e);
744 return (
745 <Box flexDirection="column" gap={1}>
746 {parts.map((p, i) =>
747 "runs" in p ? (
748 <Text key={`t${i}`}>
749 {p.runs.map((r, j) => (
750 <Text key={`r${i}-${j}`} color={r.color} bold={r.bold}>
751 {r.text}
752 </Text>
753 ))}
754 </Text>
755 ) : (
756 <Markdown key={`m${i}`} text={p.markdown} />
757 ),
758 )}
759 </Box>
760 );
761 }).catch(($, e, next) => next(e));
762};
763hooks/mod/board.ts 225 lines1// board.ts — the task board read from tasks.json, and what each task's
2// worker is doing. Pure: no `$`, no I/O.
3//
4// tasks.json (version 2) is kodflow-hooks' file, a contract it shares with
5// the status line and lib/epics.jq; this module only reads it. An epic is
6// open as the status line counts it: a task left to do, or the agent's active
7// epic while it has no task yet; it stays listed 30 minutes after its last
8// task was done, so what was opened and closed in seconds is still seen. Tasks filed under no epic (epic 0) form one
9// more group, « Hors épopée », with no number (its id is 0): the pane's tab
10// already says « Tâches », so the group does not say it again.
11//
12// A task may also carry the tree's fields (kodflow-hooks writes them only
13// once set): `parent`, `blockedBy`, `ref`. A file without them is a flat
14// list, every task at the top.
15
16import type {
17 HudActivity,
18 HudAgent,
19 HudBoard,
20 HudEpic,
21 HudTask,
22} from "../../types";
23import { safe } from "./paths.ts";
24
25export const MAIN = "main";
26export const NO_EPIC_TITLE = "Hors épopée";
27/** How long an epic with nothing left to do stays on the board after its last task was done. */
28export const KEEP_DONE_MS = 30 * 60_000;
29/** What `$.agent.list()` reports for an agent whose loop still stands. */
30export const LIVE = new Set(["running", "waiting", "idle"]);
31
32type Obj = Record<string, any>;
33const isObj = (v: unknown): v is Obj =>
34 typeof v === "object" && v !== null && !Array.isArray(v);
35const text = (v: unknown): string =>
36 typeof v === "string" ? v : v === undefined || v === null ? "" : String(v);
37const num = (v: unknown): number =>
38 typeof v === "number" && Number.isFinite(v) ? v : 0;
39
40const PR_URL = /https:\/\/github\.com\/[\w.-]+\/[\w.-]+\/pull\/\d+/g;
41
42/** The pull request URLs a task cites, once each, in order. */
43export function prsOf(...texts: string[]): string[] {
44 const seen = new Set<string>();
45 for (const t of texts) for (const m of t.match(PR_URL) ?? []) seen.add(m);
46 return [...seen];
47}
48
49function toTask(raw: Obj): HudTask {
50 const task: HudTask = {
51 id: text(raw.id),
52 subject: text(raw.subject),
53 status: text(raw.status) || "pending",
54 epic: Number.isInteger(raw.epic) ? raw.epic : 0,
55 agent: text(raw.agent) || MAIN,
56 updated: num(raw.updated) || num(raw.created),
57 prs: prsOf(text(raw.subject), text(raw.description)),
58 };
59 if (raw.worker) task.worker = text(raw.worker);
60 if (raw.worker_id) task.workerId = text(raw.worker_id);
61 if (raw.assignee) task.assignee = text(raw.assignee);
62 if (raw.description) task.description = text(raw.description);
63 if (raw.parent) task.parent = text(raw.parent);
64 if (Array.isArray(raw.blockedBy)) {
65 const ids = raw.blockedBy.map(text).filter((id: string) => id !== "");
66 if (ids.length) task.blockedBy = ids;
67 }
68 if (raw.ref) task.ref = text(raw.ref);
69 return task;
70}
71
72/** Every task of the file, deleted ones being already gone from it. */
73export function parseTasks(raw: unknown): HudTask[] {
74 if (!isObj(raw) || !Array.isArray(raw.tasks)) return [];
75 return raw.tasks
76 .filter((t: unknown) => isObj(t) && Object.hasOwn(t, "id"))
77 .map(toTask)
78 .filter((t: HudTask) => t.status !== "deleted");
79}
80
81/**
82 * Whether a group with nothing left to do is still shown: its last task was
83 * done less than `KEEP_DONE_MS` ago. A completed task's `updated` (seconds)
84 * is when it was done, kodflow-hooks stamping it on the status change. With
85 * no clock given the board is what it was: finished groups go at once.
86 */
87function justDone(tasks: readonly HudTask[], now: number | undefined): boolean {
88 if (now === undefined || tasks.length === 0) return false;
89 const last = Math.max(...tasks.map((t) => t.updated));
90 return last > 0 && now - last * 1000 < KEEP_DONE_MS;
91}
92
93/**
94 * The board: the open epics, most recently touched first, then the tasks
95 * filed under no epic while one of them is left to do. With `now` (ms), an
96 * epic or the group under no epic whose last task was done less than 30
97 * minutes ago is kept too, after the ones with work left, so a question
98 * opened and closed in seconds is still seen.
99 */
100export function parseBoard(fileText: string | undefined, now?: number): HudBoard {
101 if (fileText === undefined) return { found: false, epics: [] };
102 let raw: unknown;
103 try {
104 raw = JSON.parse(fileText);
105 } catch {
106 return { found: true, epics: [] };
107 }
108 const tasks = parseTasks(raw);
109 const data: Obj = isObj(raw) ? raw : {};
110 const active: Obj = isObj(data.active) ? data.active : {};
111 const open: HudEpic[] = [];
112 const kept: HudEpic[] = [];
113 for (const e of Array.isArray(data.epics) ? data.epics : []) {
114 if (!isObj(e) || !Number.isInteger(e.id)) continue;
115 const agent = text(e.agent) || MAIN;
116 const own = tasks.filter((t) => t.epic === e.id && t.agent === agent);
117 const left = own.some((t) => t.status !== "completed");
118 const emptyActive = own.length === 0 && active[agent] === e.id;
119 const recent = !left && !emptyActive && justDone(own, now);
120 if (!left && !emptyActive && !recent) continue;
121 (recent ? kept : open).push({
122 id: e.id,
123 title: text(e.title),
124 agent,
125 created: num(e.created) || num(e.touched),
126 touched: num(e.touched),
127 tasks: own,
128 });
129 }
130 open.sort((a, b) => b.touched - a.touched);
131 kept.sort((a, b) => b.touched - a.touched);
132 const loose = tasks.filter((t) => t.epic === 0);
133 const looseLeft = loose.some((t) => t.status !== "completed");
134 if (looseLeft || justDone(loose, now)) {
135 const group: HudEpic = {
136 id: 0,
137 title: NO_EPIC_TITLE,
138 agent: MAIN,
139 created: Math.min(...loose.map((t) => t.updated)),
140 touched: 0,
141 tasks: loose,
142 };
143 (looseLeft ? open : kept).push(group);
144 }
145 return { found: true, epics: [...open, ...kept] };
146}
147
148/** What the board needs from the world to judge a task. */
149export type Ctx = {
150 /** Milliseconds since the epoch. */
151 now: number;
152 agents: readonly HudAgent[];
153 activity: Readonly<Record<string, HudActivity>>;
154 /** How long an in_progress task may stay without activity. */
155 silentMs: number;
156};
157
158export type Verdict = {
159 /** The loop working the task: its worker, else the agent that owns it. */
160 loop: string;
161 /** That loop's state as `$.agent.list()` gives it; "main" for the main loop. */
162 state: string;
163 /** The last sign of life: the task's own change or a tool call of the loop. */
164 last: number;
165 silent: boolean;
166 /** Why it is silent: the loop stopped, or nothing happened for too long. */
167 why?: "stopped" | "quiet";
168};
169
170const findAgent = (agents: readonly HudAgent[], id: string) =>
171 agents.find((a) => a.id === id) ??
172 agents.find((a) => safe(a.id) === safe(id));
173
174/** The activity recorded for a loop, by its id or its path-safe spelling. */
175export function activityOf(
176 activity: Readonly<Record<string, HudActivity>>,
177 loop: string,
178): HudActivity | undefined {
179 return (
180 activity[loop] ??
181 Object.values(activity).find((a) => safe(a.agentId) === safe(loop))
182 );
183}
184
185/**
186 * Who works a task, how that loop stands, and whether the task went silent:
187 * in progress with its loop stopped, or with nothing from it for `silentMs`.
188 */
189export function judge(task: HudTask, ctx: Ctx): Verdict {
190 const loop = task.workerId || task.agent;
191 const updated = task.updated * 1000;
192 const seen = activityOf(ctx.activity, loop)?.last ?? 0;
193 const last = Math.max(updated, seen);
194 let state = MAIN;
195 if (loop !== MAIN) state = findAgent(ctx.agents, loop)?.status ?? "absent";
196 const verdict: Verdict = { loop, state, last, silent: false };
197 if (task.status !== "in_progress") return verdict;
198 // A worker that was named and is gone is the clearest case: nobody is on it
199 if (loop !== MAIN && !LIVE.has(state)) {
200 verdict.silent = true;
201 verdict.why = "stopped";
202 } else if (ctx.now - last >= ctx.silentMs) {
203 verdict.silent = true;
204 verdict.why = "quiet";
205 }
206 return verdict;
207}
208
209/** The label of the loop a task belongs to, for the board's rows. */
210export function loopLabel(loop: string, agents: readonly HudAgent[]): string {
211 if (loop === MAIN) return "principal";
212 return findAgent(agents, loop)?.label ?? loop.slice(0, 8);
213}
214
215/** "45s", "3m", "1h02", "2j": how long ago, in the fewest cells. */
216export function ago(ms: number): string {
217 const s = Math.max(0, Math.floor(ms / 1000));
218 if (s < 60) return `${s}s`;
219 const m = Math.floor(s / 60);
220 if (m < 60) return `${m}m`;
221 const h = Math.floor(m / 60);
222 if (h < 24) return `${h}h${String(m % 60).padStart(2, "0")}`;
223 return `${Math.floor(h / 24)}j`;
224}
225hooks/mod/alerts.ts 63 lines1// alerts.ts — which tasks deserve a toast now. Pure.
2//
3// Three states are news: a task completed, a task blocked (waiting), a task
4// gone silent. Each is toasted at most once per task, keyed
5// `<session>:<task>:<state>`, the keys kept in `$.state` so a reload of the
6// module does not toast them again. The first board read in a session is the
7// baseline: what stands then is recorded without a toast, so opening a
8// session full of finished work does not fire a volley of them.
9
10import type { HudTask } from "../../types";
11import { judge, type Ctx } from "./board.ts";
12
13export type Alert = { key: string; text: string };
14
15/** The news state of a task, if it is in one. */
16export function newsOf(
17 task: HudTask,
18 ctx: Ctx,
19): "done" | "waiting" | "silent" | undefined {
20 if (task.status === "completed") return "done";
21 if (task.status === "waiting") return "waiting";
22 if (judge(task, ctx).silent) return "silent";
23 return undefined;
24}
25
26function line(task: HudTask, state: string, ctx: Ctx): string {
27 const head = `#${task.id} ${task.subject}`;
28 if (state === "done") return `${head} : terminée`;
29 if (state === "waiting") return `${head} : bloquée, en attente`;
30 const v = judge(task, ctx);
31 return v.why === "stopped"
32 ? `${head} : silencieuse, son worker est arrêté`
33 : `${head} : silencieuse, aucune activité depuis ${Math.round(ctx.silentMs / 60000)} min`;
34}
35
36/**
37 * The alerts to raise and the keys to record. With `baseline`, every key is
38 * recorded and nothing is raised.
39 */
40export function alertsFor(
41 session: string,
42 tasks: readonly HudTask[],
43 ctx: Ctx,
44 toasted: ReadonlySet<string>,
45 baseline: boolean,
46): { alerts: Alert[]; keys: string[] } {
47 const alerts: Alert[] = [];
48 const keys: string[] = [];
49 for (const task of tasks) {
50 const state = newsOf(task, ctx);
51 if (!state) continue;
52 const key = `${session}:${task.id}:${state}`;
53 if (toasted.has(key)) continue;
54 keys.push(key);
55 if (!baseline) alerts.push({ key, text: line(task, state, ctx) });
56 }
57 return { alerts, keys };
58}
59
60/** Keep the recorded keys bounded: the newest `max`. */
61export const trimKeys = (keys: readonly string[], max = 500): string[] =>
62 keys.length > max ? keys.slice(keys.length - max) : [...keys];
63hooks/mod/ci.ts 34 lines1// ci.ts — the CI state of the pull requests the tasks cite. Pure.
2//
3// Read by `gh pr checks <url>`, whose exit code says it: 0 every check
4// passed, 8 some still pending, 1 one failed (or gh itself failed, which its
5// output tells apart). Only the pull requests an open task cites are asked,
6// and no more often than every CI_EVERY_MS.
7
8import type { HudCiState, HudEpic } from "../../types";
9
10export const CI_EVERY_MS = 5 * 60_000;
11
12/** The pull requests to ask about: cited by a task not completed. */
13export function prsToCheck(epics: readonly HudEpic[]): string[] {
14 const seen = new Set<string>();
15 for (const e of epics)
16 for (const t of e.tasks)
17 if (t.status !== "completed") for (const pr of t.prs) seen.add(pr);
18 return [...seen];
19}
20
21/** What `gh pr checks` answered, as one state. */
22export function ciState(
23 exitCode: number,
24 stdout: string,
25 stderr: string,
26): HudCiState {
27 if (/no checks reported/i.test(stderr + stdout)) return "none";
28 if (exitCode === 0) return "pass";
29 if (exitCode === 8) return "pending";
30 // 1 is a failed check when gh printed the checks, an error otherwise
31 if (exitCode === 1 && /\bfail/i.test(stdout)) return "fail";
32 return "error";
33}
34hooks/mod/paths.ts 31 lines1// paths.ts — where a session's files are. Pure.
2//
3// configDir, safe and sessionDir are kodflow-hooks' own (hooks/mod/paths.ts),
4// copied rather than imported: a plugin is installed alone, and a link into
5// a sibling plugin is broken for every consumer. They must agree, since this
6// mod reads the tasks.json that one writes.
7
8/** CLAUDE_CONFIG_DIR, else ~/.claude; undefined unless absolute. */
9export function configDir(
10 claudeConfigDir: string | undefined,
11 home: string | undefined,
12): string | undefined {
13 const pick =
14 claudeConfigDir || (home ? `${home.replace(/\/+$/, "")}/.claude` : "");
15 if (!pick.startsWith("/")) return undefined;
16 return pick.length > 1 ? pick.replace(/\/+$/, "") : pick;
17}
18
19/** An identifier usable as a single path component (tasks.py's safe). */
20export function safe(value: unknown): string {
21 const chars = [...String(value)].map((c) =>
22 /^[\p{L}\p{N}_-]$/u.test(c) ? c : "-",
23 );
24 return chars.slice(0, 128).join("") || "default";
25}
26
27export const sessionDir = (config: string, session: string): string =>
28 `${config}/kodflow/sessions/${safe(session)}`;
29
30export const tasksFile = (dir: string): string => `${dir}/tasks.json`;
31hooks/mod/tree.ts 451 lines1// tree.ts — the task tree the « Tâches » pane draws, derived from the board.
2// Pure: no `$`, no I/O; what it returns is plain data, handed whole to the
3// pane's surface module (client.tsx) as its props.
4//
5// Nothing here is typed by anyone: the states the tree shows beyond
6// tasks.json's own statuses are read off the links kodflow-hooks keeps
7// (`parent`, `blockedBy`):
8// ready ▶ pending, every blocker completed, nobody on it: a task at the
9// top, or under a parent already completed;
10// blocked ⊘ pending, at least one blocker not completed;
11// todo ○ pending under a parent not completed: whoever takes the
12// parent takes it, so it is nobody's to pick up on its own.
13// The critical path is the longest blockedBy chain of tasks not completed,
14// down to the epic's final tasks (the ones nothing waits on); every task on
15// a chain of that length is on it. A list with no link has none.
16
17import type { HudBoard, HudCi, HudModel, HudSeen, HudTask } from "../../types";
18import { MAIN, judge, loopLabel, type Ctx } from "./board.ts";
19import { MAIN_NAME, colorOf, roleOf } from "./who.ts";
20import { cells, fit } from "./width.ts";
21import { modelKey, seenKey } from "./models.ts";
22
23export type NodeState =
24 "done" | "run" | "you" | "wait" | "ready" | "blocked" | "todo";
25
26/** One task as a row of the tree: every cell already worded. */
27export type TreeNode = {
28 id: string;
29 /** How links and footers name it: its ref, else #id. */
30 label: string;
31 title: string;
32 state: NodeState;
33 /** Who works it: a subagent's name, "principal", "toi", "prête"; "" for nobody. */
34 agent: string;
35 /** What `agent` names: the main loop, a subagent, the person, nobody yet. */
36 agentKind: "main" | "sub" | "you" | "ready" | "";
37 /** The subagent's role, its type short (who.ts); "" when unknown. */
38 role: string;
39 /** The loop's colour (who.ts), for the main loop and the subagents. */
40 agentColor?: string;
41 /** model·effort of that loop, "" when the session never said. */
42 model: string;
43 /** Since it last moved; "" for a task nobody has taken. */
44 age: string;
45 silent: boolean;
46 /** "⇠ C6 C7" what it waits on, else "⇢ C9" what it unblocks. */
47 links: string;
48 crit: boolean;
49 desc: string;
50 /** "CI ✓" and the like, for a cited pull request. */
51 ci: string;
52 kids: TreeNode[];
53};
54
55export type TreeEpic = {
56 id: number;
57 title: string;
58 done: number;
59 total: number;
60 age: string;
61 nodes: TreeNode[];
62 /** The critical path's chains, each a list of its tasks, top level first. */
63 chains: { label: string; state: NodeState }[][];
64 /** The task of the person's the epic waits on, and whether on the path. */
65 you?: { label: string; age: string; crit: boolean };
66 /** The first ready task, on the path first. */
67 next?: { label: string; title: string };
68 /** Where the epic ends: its final task on the path, else its last. */
69 goal?: { label: string; title: string; state: NodeState; note: string };
70 /** The graph's edges between top-level tasks, blocker first, by id. */
71 edges: [string, string][];
72};
73
74export type TreeModel = { found: boolean; epics: TreeEpic[] };
75
76export type TreeData = {
77 board: HudBoard;
78 ctx: Ctx;
79 ci: Readonly<Record<string, HudCi>>;
80 models: Readonly<Record<string, HudModel>>;
81 seen: Readonly<Record<string, HudSeen>>;
82 /** The session the board was read for: the `seen` keys carry it. */
83 session: string;
84};
85
86/** "45 s", "12 min", "1 h 20", "12 h", "3 j": six cells at most. */
87export function span(ms: number): string {
88 const s = Math.max(0, Math.floor(ms / 1000));
89 if (s < 60) return `${s} s`;
90 const m = Math.floor(s / 60);
91 if (m < 60) return `${m} min`;
92 const h = Math.floor(m / 60);
93 if (h < 10)
94 return m % 60 ? `${h} h ${String(m % 60).padStart(2, "0")}` : `${h} h`;
95 if (h < 24) return `${h} h`;
96 return `${Math.floor(h / 24)} j`;
97}
98
99const FAMILY = /\b(opus|sonnet|haiku|fable)\b/i;
100const EFFORT: Record<string, [string, string]> = {
101 low: ["low", "lo"],
102 medium: ["med", "med"],
103 high: ["high", "hi"],
104 xhigh: ["xhigh", "xhi"],
105 max: ["max", "max"],
106};
107export const MODEL_CELLS = 10;
108
109/** "opus·xhigh", "sonnet·hi", "haiku": a model id and an effort, in ten cells. */
110export function modelCell(m: HudModel | undefined): string {
111 if (!m?.model) return "";
112 const family = FAMILY.exec(m.model)?.[1]?.toLowerCase() ?? m.model;
113 if (!m.effort) return fit(family, MODEL_CELLS);
114 const [long, short] = EFFORT[m.effort] ?? [m.effort, m.effort];
115 const full = `${family}·${long}`;
116 if (cells(full) <= MODEL_CELLS) return full;
117 return fit(`${family}·${short}`, MODEL_CELLS);
118}
119
120const AGENT_PREFIX = /^[\w.-]+:(developer-)?/;
121export const AGENT_CELLS = 22;
122/** What the role keeps at least beside a long name, in the agent column. */
123const ROLE_MIN = 7;
124
125/** An agent's name, the plugin prefix of a type used as a name dropped. */
126export const agentName = (name: string): string =>
127 name.replace(AGENT_PREFIX, "");
128
129/** A role in the narrow agent column: a specialist's topic, a type's head. */
130export function roleCell(role: string): string {
131 if (!role) return "";
132 const topic = role.split(" · ").pop()!;
133 return topic === "general-purpose" ? "general" : topic;
134}
135
136/**
137 * The agent column's two parts, the name and the role, cut to share `room`
138 * cells around a « · » of three: the role keeps up to seven, the name the
139 * rest; a role with no room for four cells is left out.
140 */
141export function agentParts(
142 name: string,
143 role: string,
144 room: number,
145): { name: string; role: string } {
146 if (!role || cells(name) + 3 + cells(role) <= room)
147 return { name: fit(name, room), role: role && fit(role, room) };
148 const roleW = Math.min(cells(role), ROLE_MIN, room - 3 - 4);
149 if (roleW < 4) return { name: fit(name, room), role: "" };
150 const nameW = Math.min(cells(name), room - 3 - roleW);
151 return { name: fit(name, nameW), role: fit(role, room - 3 - nameW) };
152}
153
154export const LINK_CELLS = 10;
155
156/** "⇠ C6 C7 C8", three labels then "+n", in fourteen cells. */
157export function linkCell(arrow: string, labels: string[]): string {
158 if (!labels.length) return "";
159 const shown = labels.slice(0, 3);
160 const more = labels.length - shown.length;
161 let text = `${arrow} ${shown.join(" ")}${more ? ` +${more}` : ""}`;
162 while (cells(text) > LINK_CELLS && shown.length > 1) {
163 shown.pop();
164 text = `${arrow} ${shown.join(" ")} +${labels.length - shown.length}`;
165 }
166 return fit(text, LINK_CELLS);
167}
168
169const CI_TEXT: Record<string, string> = {
170 pass: "CI ✓",
171 fail: "CI ✗",
172 pending: "CI …",
173 error: "CI ?",
174};
175
176const done = (t: HudTask) => t.status === "completed";
177const labelOf = (t: HudTask) => t.ref || `#${t.id}`;
178
179/** The longest blockedBy chains of unfinished tasks, and who is on them. */
180function criticalPath(
181 tasks: readonly HudTask[],
182 byId: ReadonlyMap<string, HudTask>,
183): { onPath: Set<string>; chains: string[][] } {
184 const open = tasks.filter((t) => !done(t));
185 const openIds = new Set(open.map((t) => t.id));
186 const blockers = (t: HudTask) =>
187 (t.blockedBy ?? []).filter((id) => openIds.has(id) && id !== t.id);
188 const dependents = new Map<string, string[]>();
189 for (const t of open)
190 for (const b of blockers(t))
191 dependents.set(b, [...(dependents.get(b) ?? []), t.id]);
192 // Longest chain from a task down to a final one, and up to a first one;
193 // a cycle in a hand-edited file counts once, never forever
194 const memo = (next: (id: string) => string[]) => {
195 const got = new Map<string, number>();
196 const walk = (id: string, path: Set<string>): number => {
197 const known = got.get(id);
198 if (known !== undefined) return known;
199 if (path.has(id)) return 0;
200 path.add(id);
201 let best = 1;
202 for (const n of next(id)) best = Math.max(best, 1 + walk(n, path));
203 path.delete(id);
204 got.set(id, best);
205 return best;
206 };
207 return (id: string) => walk(id, new Set());
208 };
209 const down = memo((id) => dependents.get(id) ?? []);
210 const up = memo((id) => blockers(byId.get(id)!));
211 let longest = 0;
212 for (const t of open) longest = Math.max(longest, down(t.id));
213 const onPath = new Set<string>();
214 const chains: string[][] = [];
215 if (longest < 2) return { onPath, chains };
216 for (const t of open)
217 if (up(t.id) + down(t.id) - 1 === longest) onPath.add(t.id);
218 // The chains themselves, from each first task along the longest way down
219 const follow = (id: string, left: number, acc: string[]) => {
220 const here = [...acc, id];
221 if (left === 1) return void chains.push(here);
222 for (const n of dependents.get(id) ?? [])
223 if (onPath.has(n) && down(n) === left - 1 && chains.length < 8)
224 follow(n, left - 1, here);
225 };
226 for (const t of open)
227 if (onPath.has(t.id) && up(t.id) === 1) follow(t.id, longest, []);
228 const top = (id: string) => !byId.get(id)?.parent;
229 chains.sort((a, b) => Number(b.every(top)) - Number(a.every(top)));
230 return {
231 onPath,
232 chains,
233 };
234}
235
236/**
237 * The tree of every open epic: tasks under their parent (a parent from
238 * another epic, or none that exists, puts a task at the top), each with its
239 * derived state, its loop, its model, its age and its links.
240 */
241export function buildTree(data: TreeData): TreeModel {
242 const { board, ctx } = data;
243 const epics = board.epics.map((epic) => {
244 const tasks = epic.tasks;
245 const byId = new Map(tasks.map((t) => [t.id, t]));
246 const { onPath, chains: pathIds } = criticalPath(tasks, byId);
247 const unblocks = new Map<string, string[]>();
248 for (const t of tasks)
249 for (const b of t.blockedBy ?? [])
250 unblocks.set(b, [...(unblocks.get(b) ?? []), t.id]);
251 const waitsOn = (t: HudTask) =>
252 (t.blockedBy ?? []).filter((id) => byId.has(id) && !done(byId.get(id)!));
253 const parentOf = (t: HudTask) =>
254 t.parent && t.parent !== t.id ? byId.get(t.parent) : undefined;
255
256 const stateOf = (t: HudTask): NodeState => {
257 if (done(t)) return "done";
258 if (t.status === "in_progress") return "run";
259 // The person's task is theirs whatever its status says
260 if (t.assignee === "human" || t.status === "waiting")
261 return t.assignee === "human" ? "you" : "wait";
262 if (waitsOn(t).length) return "blocked";
263 const parent = parentOf(t);
264 return parent && !done(parent) ? "todo" : "ready";
265 };
266
267 const node = (t: HudTask, depth: number, path: Set<string>): TreeNode => {
268 const state = stateOf(t);
269 const v = judge(t, ctx);
270 const seen = data.seen[seenKey(data.session, t)];
271 const workerId = t.workerId || seen?.workerId;
272 const worker = t.worker || seen?.worker;
273 const loop = workerId || t.agent;
274 let agent = "";
275 let agentKind: TreeNode["agentKind"] = "";
276 let role = "";
277 if (state === "you") {
278 agent = "toi";
279 agentKind = "you";
280 } else if (state === "ready") {
281 agent = "prête";
282 agentKind = "ready";
283 } else if (state === "run" || state === "done" || state === "wait") {
284 // A worker named with no id is still a subagent, known by its name
285 if (loop === MAIN && (!worker || worker === MAIN)) {
286 agent = MAIN_NAME;
287 agentKind = "main";
288 } else {
289 const listed =
290 ctx.agents.find((a) => a.id === loop) ??
291 (loop === MAIN
292 ? ctx.agents.find((a) => a.name === worker)
293 : undefined);
294 agent = agentName(
295 listed?.name || worker || loopLabel(loop, ctx.agents),
296 );
297 role = roleOf(listed?.type);
298 agentKind = "sub";
299 }
300 }
301 const model =
302 state === "run" || state === "done" || state === "wait"
303 ? modelCell(data.models[modelKey(data.session, loop)])
304 : "";
305 let age = "";
306 if (state === "run") age = span(ctx.now - v.last);
307 else if (state === "done" || state === "you" || state === "wait")
308 age = span(ctx.now - t.updated * 1000);
309 const waits = waitsOn(t).map((id) => labelOf(byId.get(id)!));
310 const frees = (unblocks.get(t.id) ?? [])
311 .filter((id) => byId.has(id))
312 .map((id) => labelOf(byId.get(id)!));
313 const links = waits.length ? linkCell("⇠", waits) : linkCell("⇢", frees);
314 const ci =
315 t.prs
316 .map((pr) => CI_TEXT[data.ci[pr]?.state ?? ""] ?? "")
317 .find((c) => c) ?? "";
318 path.add(t.id);
319 const kids =
320 depth < 3
321 ? tasks
322 .filter(
323 (k) =>
324 parentOf(k) === t && !path.has(k.id) && !topIds.has(k.id),
325 )
326 .map((k) => node(k, depth + 1, path))
327 : [];
328 path.delete(t.id);
329 return {
330 id: t.id,
331 label: labelOf(t),
332 title: t.subject,
333 state,
334 agent,
335 agentKind,
336 role,
337 ...((agentKind === "main" || agentKind === "sub") && {
338 agentColor: colorOf(
339 agentKind === "sub" && loop === MAIN
340 ? (ctx.agents.find((a) => a.name === worker)?.id ??
341 `name:${worker}`)
342 : loop,
343 ),
344 }),
345 model,
346 age,
347 silent: v.silent,
348 links,
349 crit: onPath.has(t.id),
350 desc: t.description ?? "",
351 ci,
352 kids,
353 };
354 };
355
356 // A parent that is missing, in another epic or in a loop puts the task on top
357 const rooted = (t: HudTask) => {
358 const seen = new Set<string>([t.id]);
359 for (let p = parentOf(t); p; p = parentOf(p)) {
360 if (seen.has(p.id)) return false;
361 seen.add(p.id);
362 }
363 return true;
364 };
365 const tops = tasks.filter((t) => !parentOf(t) || !rooted(t));
366 const topIds = new Set(tops.map((t) => t.id));
367 const nodes = tops.map((t) => node(t, 1, new Set()));
368
369 const topOf = (t: HudTask): HudTask => {
370 const seen = new Set<string>();
371 let cur = t;
372 for (let p = parentOf(cur); p && !seen.has(p.id); p = parentOf(cur)) {
373 seen.add(cur.id);
374 cur = p;
375 }
376 return cur;
377 };
378 const edges: [string, string][] = [];
379 for (const t of tasks)
380 for (const b of t.blockedBy ?? []) {
381 const from = byId.get(b);
382 if (!from) continue;
383 const pair: [string, string] = [topOf(from).id, topOf(t).id];
384 if (
385 pair[0] !== pair[1] &&
386 !edges.some((e) => e[0] === pair[0] && e[1] === pair[1])
387 )
388 edges.push(pair);
389 }
390
391 const flat: TreeNode[] = [];
392 const walk = (list: TreeNode[]) =>
393 list.forEach((n) => (flat.push(n), walk(n.kids)));
394 walk(nodes);
395 const mine = flat.filter((n) => n.state === "you");
396 const youNode = mine.find((n) => n.crit) ?? mine[0];
397 const ready = flat.filter((n) => n.state === "ready");
398 const nextNode =
399 ready.find((n) => n.crit) ??
400 ready.find((n) => tops.some((t) => t.id === n.id)) ??
401 ready[0];
402 const finals = nodes.filter((n) => !edges.some((e) => e[0] === n.id));
403 const goalNode =
404 finals.find((n) => n.crit) ??
405 finals.find((n) => edges.some((e) => e[1] === n.id)) ??
406 nodes[nodes.length - 1];
407 let goal: TreeEpic["goal"];
408 if (goalNode) {
409 const note: Record<NodeState, string> = {
410 done: "fait",
411 run: "en cours",
412 you: "t'attend",
413 wait: "en attente",
414 ready: "prête",
415 blocked: goalNode.links.startsWith("⇠")
416 ? `attend ${goalNode.links.slice(2)}`
417 : "bloquée",
418 todo: "à faire",
419 };
420 goal = {
421 label: goalNode.label,
422 title: goalNode.title,
423 state: goalNode.state,
424 note: note[goalNode.state],
425 };
426 }
427 const doneCount = tasks.filter(done).length;
428 const out: TreeEpic = {
429 id: epic.id,
430 title: epic.title || `#${epic.id}`,
431 done: doneCount,
432 total: tasks.length,
433 age: epic.created ? span(ctx.now - epic.created * 1000) : "",
434 nodes,
435 chains: pathIds.map((c) =>
436 c.map((id) => ({
437 label: labelOf(byId.get(id)!),
438 state: stateOf(byId.get(id)!),
439 })),
440 ),
441 edges,
442 };
443 if (youNode)
444 out.you = { label: youNode.label, age: youNode.age, crit: youNode.crit };
445 if (nextNode) out.next = { label: nextNode.label, title: nextNode.title };
446 if (goal) out.goal = goal;
447 return out;
448 });
449 return { found: board.found, epics };
450}
451hooks/mod/layout.tsx 1277 lines1// layout.tsx — the « Tâches » pane's two views, laid out cell by cell.
2// Pure: no `$`. The surface module (client.tsx) draws them with its own
3// elements and keeps the selection; a surface with no `Client` gets the same
4// screen, still, from the hooks module.
5//
6// Alignment is the point. A screen is a list of lines, a line a row of cells
7// of a fixed width each, and every cell becomes a Box of exactly that width:
8// nothing is lined up with padding spaces, and what goes in a cell is cut to
9// it first, measured in terminal cells (width.ts), so a wide glyph never
10// shifts the next column. No cell paints a background: colour is the text's
11// alone, so a transparent terminal shows through everywhere.
12//
13// R12, the tree, at its full width (88 cells of body, 90 with the frame):
14// margin 2 · tree 30 (3 a level, glyph 2, ref 7, title 18) · agent 22 ·
15// model·effort 10 · age 6 (right) · links 10, a gap of 2 between them.
16// The agent column names who works the task: « ◉ principal » in the theme's
17// colour, « ↳ name · role » in the subagent's own (who.ts), « toi », « prête ».
18// Narrower, the links go first (under 88), then the model (under 76), then
19// the agent (under 64); the tree and the age stay. On 20 rows: title,
20// headers, the epic, 11 tasks, a rule, the critical path, two lines of
21// detail on the selection and the two lines of the views' bar. Shorter, the
22// finished branches fold into « ✓ fait (n) », first under the epic, then
23// the detail drops to one line, then to none, then the list scrolls with the
24// selection.
25//
26// R4, the graph: three columns of 26 (FAIT · PRÊT, EN COURS · ATTENTE,
27// BLOQUÉ) and two gutters of 5, each top-level task on two rows (its title,
28// then its agent and age). A gutter routes its links on a vertical with
29// ┬ ┐ ┤ ┼ ┘ └ junctions, links sharing no lane on stretches of their own; a
30// link that skips the middle column crosses it on a lane of its own, as a
31// solid line, so no two lines ever cross.
32
33import type { NodeState, TreeEpic, TreeModel, TreeNode } from "./tree.ts";
34import {
35 AGENT_CELLS,
36 LINK_CELLS,
37 MODEL_CELLS,
38 agentParts,
39 roleCell,
40} from "./tree.ts";
41import { cells, fit } from "./width.ts";
42
43/** The elements a screen is drawn with: any surface's table has them. */
44export type Els = { Box: any; Text: any };
45
46// Theme colours, never fixed shades: the engine gives each its tone for the
47// light and the dark themes alike, so the tree reads on either ground.
48export const MAUVE = "merged"; // the epics, the critical path, the views' bar
49export const AMBER = "warning"; // the task under way
50export const TEAL = "planMode"; // ready, nobody on it yet
51export const BLUE = "ide"; // the model
52export const YOU = "permission"; // waiting on the person, as a permission is
53export const GREEN = "success";
54export const RED = "error";
55
56export type Span = {
57 text: string;
58 color?: string;
59 dim?: boolean;
60 bold?: boolean;
61 underline?: boolean;
62};
63
64/** A cell: a fixed width, and either its text or a row of cells inside. */
65export type Cell = { w: number; spans?: Span[]; right?: boolean; row?: Cell[] };
66
67export type Screen = {
68 lines: Cell[][];
69 /** For each line, the task it shows, for a click to select. */
70 rowIds: (string | undefined)[];
71 /** The line of the views' bar, and where each view's name sits. */
72 tabsLine: number;
73 tabs: { x: number; w: number; view: View }[];
74 /** What a click on a line does beyond choosing it (« Refus », « Documents »). */
75 buttons?: { y: number; x: number; w: number; act: Act }[];
76 /** The tasks ↑ and ↓ walk, in the order shown. */
77 order: string[];
78 /** The lines the task list takes: the first, and how many. */
79 list: { top: number; rows: number };
80};
81
82export type View = "tree" | "graph" | "blocks" | "docs";
83export const VIEWS: readonly View[] = ["tree", "graph", "blocks", "docs"];
84
85/** The counts the views' bar shows beside « Refus » and « Documents ». */
86export type BarCounts = { blocks: number; docs: number };
87const NO_COUNTS: BarCounts = { blocks: 0, docs: 0 };
88
89/**
90 * A button of the « Refus » and « Documents » views. `allow`, `copy`,
91 * `create` and `ignore` go to the hooks module (`surface.post`); `pick`,
92 * `cancel` and `mode` stay in the surface module's state.
93 */
94export type Act =
95 | { op: "allow" | "copy"; rule: string }
96 | { op: "pick"; rule: string }
97 | { op: "cancel" }
98 | { op: "create"; ids: string[] }
99 | { op: "mode"; mode: "ask" | "context" | "both" }
100 | { op: "ignore"; id: string; ignore: boolean };
101
102/**
103 * What the person moved: kept by the surface module, across redraws. `pin`
104 * is the line the chosen task was on when the person last acted on it: the
105 * next screen keeps it there whenever it can, so a click never moves the
106 * row it hit and ↑↓ scroll only as far as they must.
107 */
108export type Ui = {
109 view: View;
110 sel?: string;
111 open: string[];
112 pin?: { id: string; y: number };
113 /** « Refus »: the refusal chosen, and the rule shown for confirmation. */
114 bsel?: string;
115 pick?: string;
116 /** « Documents »: the document chosen, and the mode « Créer » drafts. */
117 dsel?: string;
118 mode?: "ask" | "context" | "both";
119 /** The line the chosen refusal or document stays on, as `pin`. */
120 ppin?: { id: string; y: number };
121};
122
123export const FULL = { links: 88, model: 76, agent: 64 } as const;
124export const W = {
125 margin: 2,
126 tree: 30,
127 agent: AGENT_CELLS,
128 model: MODEL_CELLS,
129 age: 6,
130 links: LINK_CELLS,
131 gap: 2,
132 level: 3,
133 glyph: 2,
134 ref: 7,
135 title: 18,
136} as const;
137
138export const GLYPH: Record<
139 NodeState,
140 { glyph: string; color?: string; dim?: boolean }
141> = {
142 done: { glyph: "✓", color: GREEN },
143 run: { glyph: "●", color: AMBER },
144 you: { glyph: "◇", color: YOU },
145 wait: { glyph: "◇", color: YOU },
146 ready: { glyph: "▶", color: TEAL },
147 blocked: { glyph: "⊘", color: RED },
148 todo: { glyph: "○", dim: true },
149};
150
151const HINTS: Record<View, string> = {
152 tree: "↑↓ choisir · ⏎ plier · tab vue",
153 graph: "↑↓ choisir · ⏎ plier · tab vue",
154 blocks: "↑↓ choisir · ⏎ règle · tab vue",
155 docs: "⏎ ignorer · c créer · m mode · tab",
156};
157const HINT_SHORT = "↑↓ ⏎ tab";
158
159// --- cells ------------------------------------------------------------------------
160
161export const span = (text: string, style: Omit<Span, "text"> = {}): Span => ({
162 text,
163 ...style,
164});
165export const dim = (text: string): Span => ({ text, dim: true });
166
167/** Spans cut to `w` cells as one text: the cut falls in the span it reaches. */
168export function cut(spans: Span[], w: number): Span[] {
169 const whole = spans.map((s) => s.text).join("");
170 if (cells(whole) <= w) return spans;
171 const kept = fit(whole, w);
172 const out: Span[] = [];
173 let left = [...kept];
174 for (const s of spans) {
175 if (!left.length) break;
176 const n = [...s.text].length;
177 out.push({ ...s, text: left.slice(0, n).join("") });
178 left = left.slice(n);
179 }
180 if (left.length && out.length) out[out.length - 1]!.text += left.join("");
181 return out;
182}
183
184export const cell = (w: number, spans: Span[] = [], right = false): Cell =>
185 right ? { w, spans: cut(spans, w), right } : { w, spans: cut(spans, w) };
186export const row = (w: number, inner: Cell[]): Cell => ({ w, row: inner });
187const gap = (): Cell => ({ w: W.gap });
188export const rule = (w: number, ch: string): Cell[] => [
189 cell(w, [dim(ch.repeat(w))]),
190];
191
192/** Which of the optional columns a body of `width` cells keeps. */
193export function columnsFor(width: number) {
194 return {
195 links: width >= FULL.links,
196 model: width >= FULL.model,
197 agent: width >= FULL.agent,
198 tree: Math.max(8, Math.min(W.tree, width - W.margin - W.gap - W.age)),
199 };
200}
201
202// --- the tree's rows ----------------------------------------------------------------
203
204type Visible = {
205 node: TreeNode;
206 depth: number;
207 lasts: boolean[];
208 top: TreeNode;
209};
210
211/** The rows the tree shows, an open task's subtasks under it. */
212export function visible(nodes: TreeNode[], open: readonly string[]): Visible[] {
213 const out: Visible[] = [];
214 const walk = (
215 list: TreeNode[],
216 depth: number,
217 lasts: boolean[],
218 top?: TreeNode,
219 ) =>
220 list.forEach((node, i) => {
221 const here = [...lasts, i === list.length - 1];
222 out.push({ node, depth, lasts: here, top: top ?? node });
223 if (node.kids.length && open.includes(node.id))
224 walk(node.kids, depth + 1, here, top ?? node);
225 });
226 walk(nodes, 0, []);
227 return out;
228}
229
230const findNode = (model: TreeModel, id: string | undefined) => {
231 let hit:
232 | { node: TreeNode; epic: TreeEpic; top: TreeNode; parent?: TreeNode }
233 | undefined;
234 for (const epic of model.epics) {
235 const walk = (list: TreeNode[], top?: TreeNode, parent?: TreeNode) =>
236 list.forEach((n) => {
237 if (n.id === id)
238 hit = parent
239 ? { node: n, epic, top: top!, parent }
240 : { node: n, epic, top: n };
241 walk(n.kids, top ?? n, n);
242 });
243 walk(epic.nodes);
244 }
245 return hit;
246};
247
248/**
249 * Where the person starts: the first task under way, its branch open down to
250 * the running subtask; else the first task left to do; else the first.
251 */
252export function initialUi(model: TreeModel): Ui {
253 for (const epic of model.epics)
254 for (const top of epic.nodes) {
255 if (top.state !== "run") continue;
256 const open: string[] = [];
257 for (let n: TreeNode | undefined = top; n?.kids.length;) {
258 open.push(n.id);
259 n = n.kids.find((k) => k.state === "run" && k.kids.length);
260 }
261 return { view: "tree", sel: top.id, open };
262 }
263 const tops = model.epics.flatMap((e) => e.nodes);
264 const first = tops.find((n) => n.state !== "done") ?? tops[0];
265 return first
266 ? { view: "tree", sel: first.id, open: [] }
267 : { view: "tree", open: [] };
268}
269
270/**
271 * ⏎ on a task: fold or unfold it; one top-level branch open at a time. A
272 * click (`keepAbove`) closes only the branches below the one it opens: one
273 * above closing would pull the clicked row up from under the pointer.
274 */
275export function toggle(
276 model: TreeModel,
277 ui: Ui,
278 id: string,
279 keepAbove = false,
280): Ui {
281 const hit = findNode(model, id);
282 if (!hit || !hit.node.kids.length) return ui;
283 if (ui.open.includes(id))
284 return { ...ui, open: ui.open.filter((o) => o !== id) };
285 const order = model.epics.flatMap((e) => e.nodes.map((n) => n.id));
286 const at = order.indexOf(id);
287 const closes = (o: string) => {
288 const i = order.indexOf(o);
289 return i >= 0 && !(keepAbove && i < at);
290 };
291 const open = at >= 0 ? ui.open.filter((o) => !closes(o)) : ui.open;
292 return { ...ui, open: [...open, id] };
293}
294
295/** The task `id` pinned to the line it is shown on now, else to `y`. */
296export function pinAt(screen: Screen, ui: Ui, id: string, y?: number): Ui {
297 const shown = screen.rowIds.indexOf(id);
298 const line = shown >= 0 ? shown : y;
299 return line === undefined ? ui : { ...ui, pin: { id, y: line } };
300}
301
302/**
303 * ↑ or ↓: the previous or next task shown, at the ends it stays. It keeps
304 * its line when it is in view; out of it, it lands on the list's edge, so
305 * the list moves by one.
306 */
307export function step(screen: Screen, ui: Ui, by: number): Ui {
308 const i = ui.sel === undefined ? -1 : screen.order.indexOf(ui.sel);
309 const next =
310 screen.order[Math.max(0, Math.min(screen.order.length - 1, i + by))];
311 if (next === undefined) return ui;
312 const { top, rows } = screen.list;
313 const edge = by > 0 ? top + Math.max(0, rows - 1) : top;
314 return pinAt(screen, { ...ui, sel: next }, next, edge);
315}
316
317function treeCell(
318 v: Visible,
319 width: number,
320 selected: boolean,
321 open: boolean,
322): Cell {
323 const { node, depth } = v;
324 const inner: Cell[] = [];
325 // The ancestors' lines, then this task's own corner
326 for (const last of v.lasts.slice(0, -1))
327 inner.push(cell(W.level, [dim(last ? "" : "│")]));
328 const corner = v.lasts[v.lasts.length - 1] ? "└" : "├";
329 const mark = node.kids.length ? (open ? "▾" : "▸") : "─";
330 inner.push(
331 cell(W.level, [
332 dim(corner),
333 node.kids.length ? span(mark, { color: MAUVE }) : dim(mark),
334 ]),
335 );
336 const g = GLYPH[node.state];
337 inner.push(
338 cell(W.glyph, [
339 span(g.glyph, {
340 ...(g.color && { color: g.color }),
341 ...(g.dim && { dim: true }),
342 }),
343 ]),
344 );
345 const used = W.level * (depth + 1) + W.glyph;
346 const strong = node.state === "run";
347 const faint = node.state === "done" || node.state === "blocked";
348 if (depth === 0) {
349 inner.push(
350 cell(W.ref, [
351 span(node.label, strong ? { bold: true } : faint ? { dim: true } : {}),
352 ]),
353 );
354 }
355 const left = width - used - (depth === 0 ? W.ref : 0);
356 inner.push(
357 cell(Math.max(0, Math.min(W.title, left)), [
358 span(node.title, {
359 ...(strong && { bold: true }),
360 ...(faint && { dim: true }),
361 ...(selected && { underline: true }),
362 }),
363 ]),
364 );
365 return row(width, inner);
366}
367
368type Cols = ReturnType<typeof columnsFor>;
369
370/**
371 * Who works a task, in `w` cells: « ◉ principal » in the theme's colour,
372 * « ↳ name · role » in the subagent's own, the person « toi », « prête »
373 * when nobody took it yet. A finished task's is dimmed.
374 */
375export function agentSpans(n: TreeNode, w: number): Span[] {
376 if (!n.agent) return [];
377 const faint = n.state === "done";
378 const tone = (color: string | undefined): Omit<Span, "text"> => ({
379 ...(color && { color }),
380 ...(faint && { dim: true }),
381 });
382 switch (n.agentKind) {
383 case "you":
384 return [span(n.agent, tone(YOU))];
385 case "ready":
386 return [span(n.agent, tone(TEAL))];
387 case "main":
388 return [
389 span("◉ ", tone(n.agentColor)),
390 span(n.agent, tone(n.agentColor)),
391 ];
392 case "sub": {
393 const p = agentParts(n.agent, roleCell(n.role), Math.max(0, w - 2));
394 return [
395 span("↳ ", tone(n.agentColor)),
396 span(p.name, tone(n.agentColor)),
397 ...(p.role ? [dim(" · "), dim(p.role)] : []),
398 ];
399 }
400 default:
401 return [span(n.agent, faint ? { dim: true } : {})];
402 }
403}
404
405function taskLine(
406 v: Visible,
407 cols: Cols,
408 selected: boolean,
409 open: boolean,
410): Cell[] {
411 const n = v.node;
412 const out: Cell[] = [
413 cell(W.margin, n.crit ? [span("┃", { color: MAUVE })] : []),
414 treeCell(v, cols.tree, selected, open),
415 ];
416 if (cols.agent) out.push(gap(), cell(W.agent, agentSpans(n, W.agent)));
417 if (cols.model)
418 out.push(
419 gap(),
420 cell(
421 W.model,
422 n.model
423 ? [
424 span(
425 n.model,
426 n.state === "done" ? { dim: true } : { color: BLUE },
427 ),
428 ]
429 : [],
430 ),
431 );
432 const ageTone = n.silent
433 ? { color: RED, bold: true }
434 : n.state === "run"
435 ? { color: AMBER }
436 : n.state === "you" || n.state === "wait"
437 ? { color: YOU }
438 : { dim: true };
439 out.push(gap(), cell(W.age, n.age ? [span(n.age, ageTone)] : [], true));
440 if (cols.links)
441 out.push(
442 gap(),
443 cell(
444 W.links,
445 n.links
446 ? [
447 span(
448 n.links,
449 n.state === "blocked" ? { color: RED } : { dim: true },
450 ),
451 ]
452 : [],
453 ),
454 );
455 return out;
456}
457
458function headerLine(cols: Cols): Cell[] {
459 const hd = (t: string) => [dim(t)];
460 const out: Cell[] = [cell(W.margin), cell(cols.tree, hd("TÂCHE"))];
461 if (cols.agent) out.push(gap(), cell(W.agent, hd("AGENT")));
462 if (cols.model) out.push(gap(), cell(W.model, hd("MODÈLE")));
463 out.push(gap(), cell(W.age, hd("ÂGE"), true));
464 if (cols.links) out.push(gap(), cell(W.links, hd("LIENS")));
465 return out;
466}
467
468/** « 3/5 », done over total, in green once every task is done. */
469const progress = (epic: TreeEpic): Span =>
470 epic.total && epic.done === epic.total
471 ? span(`${epic.done}/${epic.total}`, { color: GREEN })
472 : dim(`${epic.done}/${epic.total}`);
473
474/**
475 * An epic's line: ◆, its number and title, its progress right after the
476 * title, its age. The agent and model columns stay empty: they speak of the
477 * tasks. The tasks filed under no epic sit under a quiet « Hors épopée »,
478 * with no number, no progress and no age.
479 */
480function epicLine(epic: TreeEpic, cols: Cols): Cell[] {
481 // The title runs over the agent and model columns, empty on this line
482 const span2 =
483 cols.tree +
484 (cols.agent ? W.gap + W.agent : 0) +
485 (cols.model ? W.gap + W.model : 0);
486 const titleW = Math.max(0, span2 - W.glyph - W.ref);
487 const loose = epic.id === 0;
488 const count = loose ? undefined : progress(epic);
489 const countW = count ? cells(count.text) + 2 : 0;
490 const nameW = Math.max(
491 0,
492 Math.min(cells(epic.title), titleW - (titleW > countW + 4 ? countW : 0)),
493 );
494 const out: Cell[] = [
495 cell(W.margin),
496 row(span2, [
497 cell(W.glyph, [loose ? dim("◌") : span("◆", { color: MAUVE })]),
498 cell(
499 W.ref,
500 loose ? [] : [span(`#${epic.id}`, { color: MAUVE, bold: true })],
501 ),
502 cell(nameW, [
503 loose
504 ? dim(epic.title)
505 : span(epic.title, { color: MAUVE, bold: true }),
506 ]),
507 cell(
508 Math.max(0, titleW - nameW),
509 count && titleW - nameW >= countW ? [dim(" "), count] : [],
510 ),
511 ]),
512 ];
513 out.push(gap(), cell(W.age, loose ? [] : [dim(epic.age)], true));
514 if (cols.links) out.push(gap(), cell(W.links));
515 return out;
516}
517
518/**
519 * The finished branches, folded: first under the epic, where they mostly
520 * stood, so « └─ » is its own only when nothing is left open after it.
521 */
522function foldLine(count: number, last: boolean, cols: Cols): Cell[] {
523 return [
524 cell(W.margin),
525 cell(cols.tree, [
526 dim(last ? "└─ " : "├─ "),
527 span("✓", { color: GREEN }),
528 dim(` fait (${count})`),
529 ]),
530 ];
531}
532
533const plural = (n: number, one: string, many: string) =>
534 `${n} ${n > 1 ? many : one}`;
535
536/**
537 * What the section is about, never the tab's own name again: the one epic
538 * open (« #1 Recette kodflow »), else how many (« 2 épopées ouvertes »),
539 * then the tasks under no epic (« 1 tâche hors épopée »).
540 */
541export function sectionTitle(
542 model: TreeModel,
543 epic: TreeEpic | undefined,
544): string {
545 const real = model.epics.filter((e) => e.id !== 0);
546 const loose = model.epics.find((e) => e.id === 0);
547 const left = loose ? loose.total - loose.done : 0;
548 const parts: string[] = [];
549 if (real.length === 1 && !left) {
550 const one = epic && epic.id !== 0 ? epic : real[0]!;
551 parts.push(`#${one.id} ${one.title}`);
552 } else if (real.length)
553 parts.push(plural(real.length, "épopée ouverte", "épopées ouvertes"));
554 if (left) parts.push(plural(left, "tâche hors épopée", "tâches hors épopée"));
555 return parts.join(" · ");
556}
557
558function titleLine(
559 model: TreeModel,
560 epic: TreeEpic | undefined,
561 width: number,
562): Cell[] {
563 const what = sectionTitle(model, epic);
564 const head: Cell[] = [cell(2, [dim("─ ")])];
565 const used = 2;
566 const wWhat = Math.min(cells(what), Math.max(0, width - used - 2));
567 head.push(cell(wWhat, [span(what, { color: MAUVE })]));
568 const rest = Math.max(0, width - used - wWhat);
569 if (rest > 1) head.push(cell(1), cell(rest - 1, [dim("─".repeat(rest - 1))]));
570 return head;
571}
572
573const stateTone = (s: NodeState): Omit<Span, "text"> => {
574 const g = GLYPH[s];
575 return g.color ? { color: g.color } : { dim: true };
576};
577
578function chainSpans(epic: TreeEpic | undefined): Span[] {
579 if (!epic?.chains.length) return [dim("aucun lien")];
580 const out: Span[] = [];
581 epic.chains.forEach((chain, i) => {
582 if (i) out.push(dim(" · "));
583 chain.forEach((t, j) => {
584 if (j) out.push(dim(" → "));
585 out.push(span(t.label, stateTone(t.state)));
586 });
587 });
588 return out;
589}
590
591/** "┃ chemin critique C6 → C9 · C7 → C9", and who it waits on, right. */
592function critLine(epic: TreeEpic | undefined, width: number): Cell[] {
593 const head = [
594 span("┃ ", { color: MAUVE }),
595 span("chemin critique ", { color: MAUVE }),
596 ];
597 const you = epic?.you;
598 const tail: Span[] = you
599 ? you.crit
600 ? [dim("bloqué par "), span(`toi (${you.label})`, { color: YOU })]
601 : [
602 dim("t'attend "),
603 span(`◇ ${you.label}`, { color: YOU }),
604 dim(you.age ? ` · ${you.age}` : ""),
605 ]
606 : [];
607 const headW = Math.min(19, width);
608 // The chains keep 8 cells before who waits is given any, and the gap of 2
609 const fits = width - headW - 8 - W.gap;
610 const tailW =
611 fits > 0 ? Math.min(cells(tail.map((s) => s.text).join("")), fits) : 0;
612 const midW = Math.max(0, width - headW - tailW - (tailW ? 2 : 0));
613 const out: Cell[] = [cell(headW, head), cell(midW, chainSpans(epic))];
614 if (tailW) out.push(cell(2), cell(tailW, tail));
615 return out;
616}
617
618function detailLines(
619 model: TreeModel,
620 ui: Ui,
621 width: number,
622 count: number,
623): Cell[][] {
624 if (count <= 0) return [];
625 const hit = findNode(model, ui.sel);
626 if (!hit)
627 return [[cell(width, [dim("Aucune tâche choisie")])], [cell(width)]].slice(
628 0,
629 count,
630 );
631 const n = hit.node;
632 const g = GLYPH[n.state];
633 const name = hit.parent ? n.title : `${n.label} ${n.title}`;
634 const meta = [
635 n.role ? `${n.agent} · ${n.role}` : n.agent,
636 n.model,
637 n.age,
638 n.links,
639 n.ci,
640 n.silent ? "figé" : "",
641 ]
642 .filter(Boolean)
643 .join(" · ");
644 const first: Span[] = [
645 span(`${g.glyph} `, g.color ? { color: g.color } : { dim: true }),
646 span(name, { bold: true }),
647 ];
648 if (meta) first.push(dim(` ${meta}`));
649 if (hit.parent) first.push(dim(` sous-tâche de ${hit.top.label}`));
650 const kids = n.kids.length
651 ? `${n.kids.length} sous-tâche${n.kids.length > 1 ? "s" : ""}${
652 ui.open.includes(n.id)
653 ? ""
654 : `, repliée${n.kids.length > 1 ? "s" : ""} (⏎ ou clic)`
655 }`
656 : "";
657 const second = n.desc || kids || "Aucune description";
658 const lines = [
659 [cell(width, first)],
660 [cell(W.gap), cell(Math.max(0, width - W.gap), [dim(second)])],
661 ];
662 return lines.slice(0, count);
663}
664
665/**
666 * The views' bar: « Arbre », « Graphe », « Refus (n) », « Documents (n) »,
667 * each count of one width up to 99 (a figure space after a single digit) so
668 * no name moves from under the pointer when a count does; the hint of the
669 * view shown on the right, where it fits. Narrower than 46 cells the counts
670 * go and « Documents » is « Docs ».
671 */
672export function tabsLines(
673 view: View,
674 width: number,
675 counts: BarCounts = NO_COUNTS,
676): { lines: Cell[][]; tabs: Screen["tabs"] } {
677 const on = (v: View): Omit<Span, "text"> =>
678 v === view ? { color: MAUVE, bold: true, underline: true } : { dim: true };
679 const n = (k: number) => {
680 const c = Math.min(99, Math.max(0, k));
681 return ` (${c})${"\u2007".repeat(2 - String(c).length)}`;
682 };
683 const wide = width >= 46;
684 const names: [View, string][] = wide
685 ? [
686 ["tree", "Arbre"],
687 ["graph", "Graphe"],
688 ["blocks", `Refus${n(counts.blocks)}`],
689 ["docs", `Documents${n(counts.docs)}`],
690 ]
691 : [
692 ["tree", "Arbre"],
693 ["graph", "Graphe"],
694 ["blocks", "Refus"],
695 ["docs", "Docs"],
696 ];
697 const sep = wide ? 3 : 1;
698 const line: Cell[] = [];
699 const tabs: Screen["tabs"] = [];
700 let x = 0;
701 names.forEach(([v, label], i) => {
702 if (i) {
703 line.push(cell(sep));
704 x += sep;
705 }
706 const w = cells(label);
707 line.push(cell(w, [span(label, on(v))]));
708 tabs.push({ x, w, view: v });
709 x += w;
710 });
711 const hint = width - x >= cells(HINTS[view]) + 2 ? HINTS[view] : HINT_SHORT;
712 const hintW = width - x >= cells(hint) + 1 ? cells(hint) : 0;
713 const rest = Math.max(0, width - x - hintW);
714 if (rest) line.push(cell(rest));
715 if (hintW) line.push(cell(hintW, [dim(hint)]));
716 return { lines: [rule(width, "─"), line], tabs };
717}
718
719// --- R12 ---------------------------------------------------------------------------------
720
721type Body = { line: Cell[]; id?: string; selectable?: string };
722
723/** The tree view, `width` cells by `rows` lines. */
724export function treeScreen(
725 model: TreeModel,
726 ui: Ui,
727 width: number,
728 rows: number,
729 counts: BarCounts = NO_COUNTS,
730): Screen {
731 const cols = columnsFor(width);
732 const sel = findNode(model, ui.sel);
733 const epic = sel?.epic ?? model.epics[0];
734
735 const bodyOf = (foldDone: boolean): Body[] => {
736 const out: Body[] = [];
737 for (const e of model.epics) {
738 out.push({ line: epicLine(e, cols) });
739 const finished = foldDone
740 ? e.nodes.filter((n) => n.state === "done" && n.id !== sel?.top.id)
741 : [];
742 // The rest drawn as siblings of their own: the corners say where each
743 // one really stands once the finished ones have left the list
744 const left = e.nodes.filter((n) => !finished.includes(n));
745 if (finished.length)
746 out.push({ line: foldLine(finished.length, !left.length, cols) });
747 for (const v of visible(left, ui.open)) {
748 const id = v.node.id;
749 out.push({
750 line: taskLine(v, cols, id === ui.sel, ui.open.includes(id)),
751 id,
752 selectable: id,
753 });
754 }
755 }
756 return out;
757 };
758
759 // What the rows hold, most kept first: the folds, then the detail, then
760 // the bar, the path and the headers give way, and the list scrolls
761 const fitFor = (length: number) => {
762 let detail = 2;
763 let bar = 2;
764 let foot = 2; // the rule and the critical path
765 let header = 1;
766 let title = 1;
767 const room = () => rows - title - header - foot - detail - bar;
768 while (length > room() && detail > 0) detail--;
769 while (room() < 1 + model.epics.length && bar > 0) bar = 0;
770 while (room() < 1 + model.epics.length && foot > 0) foot = 0;
771 if (room() < 2 && header) header = 0;
772 if (room() < 2 && title) title = 0;
773 return { detail, bar, foot, header, title, space: Math.max(0, room()) };
774 };
775 // Where the list starts in `body`: centred on the selection, or so that
776 // the pinned task stays on its line
777 const startOf = (body: Body[], fit: ReturnType<typeof fitFor>) => {
778 if (body.length <= fit.space) return 0;
779 const at = Math.max(
780 0,
781 body.findIndex((b) => b.id === ui.sel),
782 );
783 const want =
784 ui.pin?.id === ui.sel
785 ? at - (ui.pin!.y - fit.title - fit.header)
786 : at - Math.floor(fit.space / 2);
787 return Math.max(0, Math.min(body.length - fit.space, want));
788 };
789 const lineOf = (body: Body[], fit: ReturnType<typeof fitFor>) => {
790 const at = body.findIndex((b) => b.id === ui.sel);
791 return at < 0 ? -1 : fit.title + fit.header + at - startOf(body, fit);
792 };
793 const whole = bodyOf(false);
794 const folded = bodyOf(true);
795 const roomAtFirst = rows - 1 - 1 - 2 - 2 - 2;
796 let body = whole.length > roomAtFirst ? folded : whole;
797 // A pinned task keeps its line: with the finished branches folded or
798 // not, whichever keeps it there
799 if (
800 ui.pin &&
801 ui.pin.id === ui.sel &&
802 lineOf(body, fitFor(body.length)) !== ui.pin.y
803 ) {
804 const other = body === whole ? folded : whole;
805 if (lineOf(other, fitFor(other.length)) === ui.pin.y) body = other;
806 }
807 const { detail, bar, foot, header, title, space } = fitFor(body.length);
808 const start = startOf(body, { detail, bar, foot, header, title, space });
809 const shown = body.slice(start, start + space);
810
811 const lines: Cell[][] = [];
812 const rowIds: (string | undefined)[] = [];
813 const push = (line: Cell[], id?: string) => {
814 lines.push(line);
815 rowIds.push(id);
816 };
817 if (title) push(titleLine(model, epic, width));
818 if (header) push(headerLine(cols));
819 for (const b of shown) push(b.line, b.id);
820 while (lines.length < title + header + space) push([cell(width)]);
821 if (foot) {
822 push(rule(width, "┄"));
823 push(critLine(epic, width));
824 }
825 for (const d of detailLines(model, ui, width, detail)) push(d);
826 let tabsLine = -1;
827 let tabs: Screen["tabs"] = [];
828 if (bar) {
829 const t = tabsLines("tree", width, counts);
830 push(t.lines[0]!);
831 tabsLine = lines.length;
832 push(t.lines[1]!);
833 tabs = t.tabs;
834 }
835 return {
836 lines,
837 rowIds,
838 tabsLine,
839 tabs,
840 order: body.filter((b) => b.selectable).map((b) => b.selectable!),
841 list: { top: title + header, rows: space },
842 };
843}
844
845// --- R4 -----------------------------------------------------------------------------------
846
847const COLUMN: Record<NodeState, 0 | 1 | 2> = {
848 done: 0,
849 ready: 0,
850 run: 1,
851 you: 1,
852 wait: 1,
853 blocked: 2,
854 todo: 2,
855};
856
857export type Lanes = {
858 /** Lane of each top-level task, by id, and its column. */
859 at: Map<string, { col: 0 | 1 | 2; lane: number }>;
860 count: number;
861 /** The edges drawn: left column to a column on its right. */
862 edges: [string, string][];
863};
864
865/**
866 * Lanes for the graph's top-level tasks. The middle column takes the first
867 * lanes; on the left, the tasks feeding only the middle come first, those
868 * feeding the right one after every lane the middle uses (so their line
869 * crosses the middle on a free lane), the ones that also feed the middle
870 * before those that do not; on the right, each task at its sources'
871 * middle lane, or the next one free.
872 */
873export function lanesOf(epic: TreeEpic): Lanes {
874 const col = new Map(epic.nodes.map((n) => [n.id, COLUMN[n.state]]));
875 const edges = epic.edges.filter(
876 ([a, b]) => (col.get(a) ?? 0) < (col.get(b) ?? 0),
877 );
878 const at = new Map<string, { col: 0 | 1 | 2; lane: number }>();
879 const inCol = (c: number) => epic.nodes.filter((n) => col.get(n.id) === c);
880 const mid = inCol(1);
881 mid.forEach((n, lane) => at.set(n.id, { col: 1, lane }));
882 const to = (id: string, c: number) =>
883 edges.some(([a, b]) => a === id && col.get(b) === c);
884 const left = inCol(0);
885 const feedsMid = left.filter((n) => !to(n.id, 2));
886 const firstTarget = (id: string) =>
887 Math.min(
888 ...edges
889 .filter(([a]) => a === id)
890 .map(([, b]) => at.get(b)?.lane ?? Infinity),
891 Infinity,
892 );
893 feedsMid.sort((a, b) => firstTarget(a.id) - firstTarget(b.id));
894 feedsMid.forEach((n, lane) => at.set(n.id, { col: 0, lane }));
895 const skips = left.filter((n) => to(n.id, 2));
896 skips.sort((a, b) => Number(to(b.id, 1)) - Number(to(a.id, 1)));
897 const base = Math.max(feedsMid.length, mid.length);
898 skips.forEach((n, i) => at.set(n.id, { col: 0, lane: base + i }));
899 const taken = new Set<number>();
900 for (const n of inCol(2)) {
901 const sources = edges
902 .filter(([, b]) => b === n.id)
903 .map(([a]) => at.get(a)?.lane ?? 0);
904 // At its sources' middle lane, so its line splits them evenly
905 sources.sort((x, y) => x - y);
906 let lane = sources.length ? sources[Math.floor(sources.length / 2)]! : 0;
907 while (taken.has(lane)) lane++;
908 taken.add(lane);
909 at.set(n.id, { col: 2, lane });
910 }
911 let count = 0;
912 for (const v of at.values()) count = Math.max(count, v.lane + 1);
913 return { at, count, edges };
914}
915
916/** The junction for a row of a gutter's vertical. */
917function junction(
918 left: boolean,
919 right: boolean,
920 up: boolean,
921 down: boolean,
922): string {
923 const key = `${+left}${+right}${+up}${+down}`;
924 const table: Record<string, string> = {
925 "1111": "┼",
926 "1101": "┬",
927 "1110": "┴",
928 "1001": "┐",
929 "1010": "┘",
930 "0101": "┌",
931 "0110": "└",
932 "1011": "┤",
933 "0111": "├",
934 "1100": "─",
935 "0011": "│",
936 "1000": "─",
937 "0100": "─",
938 };
939 return table[key] ?? "";
940}
941
942type Gutter = { cells: Cell[][] };
943
944/**
945 * The vertical spans of a gutter: the lanes its links join, grouped so that
946 * links sharing no lane get a span each; spans that would overlap are one
947 * (they share the vertical, which is a merge, never a crossing).
948 */
949function spans(links: readonly [number, number][]): [number, number][] {
950 let out: [number, number][] = links.map(([a, b]) => [
951 Math.min(a, b),
952 Math.max(a, b),
953 ]);
954 out.sort((x, y) => x[0] - y[0]);
955 const merged: [number, number][] = [];
956 for (const s of out) {
957 const last = merged[merged.length - 1];
958 if (last && s[0] <= last[1]) last[1] = Math.max(last[1], s[1]);
959 else merged.push([s[0], s[1]]);
960 }
961 return merged;
962}
963
964/**
965 * One gutter's cells, two per lane: entries from the left (a task feeding the
966 * next column, or a line crossing the middle), exits to the right (a task
967 * fed), each group of links on its own stretch of the vertical.
968 */
969function gutter(
970 lanes: number,
971 links: readonly [number, number][],
972 passes: Set<number>,
973): Gutter {
974 const enters = new Set(links.map(([a]) => a));
975 const exits = new Set(links.map(([, b]) => b));
976 const stretches = spans(links);
977 const within = (lane: number) =>
978 stretches.find(([t, b]) => lane >= t && lane <= b);
979 const out: Cell[][] = [];
980 for (let lane = 0; lane < lanes; lane++) {
981 const l = enters.has(lane);
982 const r = exits.has(lane);
983 const p = passes.has(lane);
984 const span = within(lane);
985 const up = !!span && lane > span[0];
986 const down = !!span && lane < span[1];
987 // A line crossing on to the next column leaves the junction to the right
988 const j =
989 l || r ? junction(l, r || p, up, down) : p ? "─" : up && down ? "│" : "";
990 const tail = r ? "─▶" : p ? "───" : "";
991 out.push([
992 cell(1, l || p ? [dim("─")] : []),
993 cell(1, j ? [dim(j)] : []),
994 cell(3, tail ? [dim(tail)] : []),
995 ]);
996 out.push([cell(1), cell(1, down ? [dim("│")] : []), cell(3)]);
997 }
998 return { cells: out };
999}
1000
1001function graphNode(n: TreeNode, w: number, fills: boolean): Cell[][] {
1002 const g = GLYPH[n.state];
1003 const strong = n.state === "run";
1004 const idW = 6;
1005 const titleW = Math.min(
1006 cells(fit(n.title, Math.max(0, w - W.glyph - idW))),
1007 Math.max(0, w - W.glyph - idW),
1008 );
1009 const fillW = Math.max(0, w - W.glyph - idW - titleW);
1010 const first: Cell[] = [
1011 cell(W.glyph, [
1012 span(g.glyph, g.color ? { color: g.color } : { dim: true }),
1013 ]),
1014 cell(idW, [span(n.label, strong ? { bold: true } : {})]),
1015 cell(titleW, [span(n.title, strong ? { bold: true } : {})]),
1016 ];
1017 if (fillW)
1018 first.push(
1019 cell(fillW, fills && fillW > 1 ? [dim(` ${"─".repeat(fillW - 1)}`)] : []),
1020 );
1021 const meta: Span[] =
1022 n.state === "ready"
1023 ? [span("prête", { color: TEAL }), dim(" · personne dessus")]
1024 : n.state === "you"
1025 ? [
1026 span("attend toi", { color: YOU }),
1027 ...(n.age ? [dim(" · "), span(n.age, { color: YOU })] : []),
1028 ]
1029 : n.state === "blocked"
1030 ? [
1031 span(
1032 n.links.startsWith("⇠")
1033 ? `attend ${n.links.slice(2)}`
1034 : "bloquée",
1035 { color: RED },
1036 ),
1037 ]
1038 : [
1039 ...(n.agent
1040 ? [
1041 span(n.agent, {
1042 ...(n.agentColor && { color: n.agentColor }),
1043 ...(n.state === "done" && { dim: true }),
1044 }),
1045 ]
1046 : []),
1047 // The model only where the age still fits after it
1048 ...(n.model &&
1049 n.state === "done" &&
1050 cells(`${n.agent} · ${n.model} · ${n.age}`) <= w - W.gap
1051 ? [dim(` · ${n.model}`)]
1052 : []),
1053 ...(n.age
1054 ? [
1055 dim(n.agent ? " · " : ""),
1056 span(
1057 n.age,
1058 n.state === "run" ? { color: AMBER } : { dim: true },
1059 ),
1060 ]
1061 : []),
1062 ];
1063 return [
1064 [row(w, first)],
1065 [row(w, [cell(W.gap), cell(Math.max(0, w - W.gap), meta)])],
1066 ];
1067}
1068
1069/** The graph view, `width` cells by `rows` lines. */
1070export function graphScreen(
1071 model: TreeModel,
1072 ui: Ui,
1073 width: number,
1074 rows: number,
1075 counts: BarCounts = NO_COUNTS,
1076): Screen {
1077 const sel = findNode(model, ui.sel);
1078 const epic = sel?.epic ?? model.epics[0];
1079 const colW = width >= FULL.links ? 26 : Math.floor((width - 10) / 3);
1080 // Under 40 cells a node no longer holds its glyph, its ref and a title
1081 const fits = colW >= 10;
1082 const lines: Cell[][] = [];
1083 const push = (l: Cell[]) => lines.push(l);
1084 push(titleLine(model, epic, width));
1085 push(
1086 fits
1087 ? [
1088 cell(colW, [dim("FAIT · PRÊT")]),
1089 cell(5),
1090 cell(colW, [dim("EN COURS · ATTENTE")]),
1091 cell(5),
1092 cell(colW, [dim("BLOQUÉ")]),
1093 ]
1094 : [cell(width, [dim("le graphe veut 40 colonnes")])],
1095 );
1096 const footer = 6; // rule, three lines, the bar's two
1097 const room = Math.max(0, rows - 2 - footer);
1098 if (epic && fits) {
1099 const { at, count, edges } = lanesOf(epic);
1100 const byLane: (TreeNode | undefined)[][] = [[], [], []];
1101 for (const n of epic.nodes) {
1102 const p = at.get(n.id)!;
1103 byLane[p.col]![p.lane] = n;
1104 }
1105 const colOf = (id: string) => at.get(id)?.col;
1106 const laneOf = (id: string) => at.get(id)!.lane;
1107 const lanePair = ([a, b]: [string, string]): [number, number] => [
1108 laneOf(a),
1109 laneOf(b),
1110 ];
1111 const links0 = edges
1112 .filter(([a, b]) => colOf(a) === 0 && colOf(b) === 1)
1113 .map(lanePair);
1114 // A link from the left column to the right one crosses the middle on its
1115 // source's lane, and joins the second gutter there
1116 const links1 = edges.filter(([, b]) => colOf(b) === 2).map(lanePair);
1117 const skipping = new Set(
1118 edges
1119 .filter(([a, b]) => colOf(a) === 0 && colOf(b) === 2)
1120 .map(([a]) => laneOf(a)),
1121 );
1122 const g0 = gutter(count, links0, skipping);
1123 const g1 = gutter(count, links1, new Set());
1124 const fills = (id: string) => edges.some(([a]) => a === id);
1125 const lanesShown = Math.min(count, Math.floor(room / 2));
1126 for (let lane = 0; lane < lanesShown; lane++) {
1127 const parts = [0, 1, 2].map((c) => {
1128 const n = byLane[c]![lane];
1129 if (n) return graphNode(n, colW, fills(n.id));
1130 // A line crossing the middle column on a free lane
1131 if (c === 1 && skipping.has(lane))
1132 return [[cell(colW, [dim("─".repeat(colW))])], [cell(colW)]];
1133 return [[cell(colW)], [cell(colW)]];
1134 });
1135 for (const r of [0, 1])
1136 push([
1137 ...parts[0]![r]!,
1138 row(5, g0.cells[lane * 2 + r]!),
1139 ...parts[1]![r]!,
1140 row(5, g1.cells[lane * 2 + r]!),
1141 ...parts[2]![r]!,
1142 ]);
1143 }
1144 if (count > lanesShown && lines.length > 2) {
1145 lines.pop();
1146 push([
1147 cell(width, [dim(`… ${count - lanesShown + 1} couloir(s) de plus`)]),
1148 ]);
1149 }
1150 }
1151 while (lines.length < 2 + room) push([cell(width)]);
1152 push(rule(width, "┄"));
1153 // Footer: next action and who waits on you, the path, the deliverable
1154 const next: Span[] = [dim("prochaine action ")];
1155 if (epic?.next)
1156 next.push(
1157 span(`▶ ${epic.next.label}`, { color: TEAL }),
1158 dim(" prête, personne dessus"),
1159 );
1160 else next.push(dim("rien de prêt"));
1161 const you: Span[] = epic?.you
1162 ? [
1163 dim("t'attend "),
1164 span(`◇ ${epic.you.label}`, { color: YOU }),
1165 dim(epic.you.age ? ` · ${epic.you.age}` : ""),
1166 ]
1167 : [];
1168 const youW = Math.min(
1169 cells(you.map((s) => s.text).join("")),
1170 Math.max(0, width - 30),
1171 );
1172 const first: Cell[] = [cell(width - youW - (youW ? 2 : 0), next)];
1173 if (youW) first.push(cell(2), cell(youW, you));
1174 push(first);
1175 push([
1176 cell(19, [span("┃ ", { color: MAUVE }), dim("chemin critique ")]),
1177 cell(Math.max(0, width - 19), chainSpans(epic)),
1178 ]);
1179 const goal: Span[] = [dim("livrable ")];
1180 if (epic?.goal) {
1181 const g = GLYPH[epic.goal.state];
1182 goal.push(
1183 span(`${g.glyph} `, g.color ? { color: g.color } : { dim: true }),
1184 span(`${epic.goal.label} ${epic.goal.title}`),
1185 dim(` · ${epic.goal.note}`),
1186 );
1187 } else goal.push(dim("aucun"));
1188 push([cell(width, goal)]);
1189 const t = tabsLines("graph", width, counts);
1190 push(t.lines[0]!);
1191 const tabsLine = lines.length;
1192 push(t.lines[1]!);
1193 return {
1194 lines: lines.slice(0, Math.max(rows, 0)),
1195 rowIds: lines.map(() => undefined),
1196 tabsLine: tabsLine < rows ? tabsLine : -1,
1197 tabs: t.tabs,
1198 order: [],
1199 list: { top: 0, rows: 0 },
1200 };hooks/mod/panels.ts 532 lines1// panels.ts — the « Refus » and « Documents » views of the « Tâches » pane,
2// laid out cell by cell as layout.tsx lays out the tree, and `viewScreen`,
3// the one entry both the surface module and the hooks module draw from.
4// Pure: no `$`.
5//
6// « Refus »: what kodflow-hooks refused (blocks.jsonl), newest first, under
7// what has piled up in the last hour and since the session began. A refusal
8// that carries the permission rule that would have allowed it shows the
9// rule; a click shows it again on the confirmation line, and only a second
10// click, on « ajouter », asks the hooks module to write it.
11//
12// « Documents »: the project's documents as docs.json says (● present, ●
13// missing, ○ ignored). A click on a line ignores it or brings it back; «
14// créer » and « Créer les manquants » ask for the docs prompt in the prompt
15// box, never sent.
16
17import type { HudBlock, HudDoc, HudDocs } from "../../types";
18import type { TreeModel } from "./tree.ts";
19import { MODES, missingOf } from "./docs.ts";
20import { HOUR_MS, hhmm, tally } from "./refusals.ts";
21import {
22 BLUE,
23 GREEN,
24 MAUVE,
25 RED,
26 W,
27 YOU,
28 cell,
29 dim,
30 rule,
31 screenOf,
32 span,
33 tabsLines,
34 type Act,
35 type BarCounts,
36 type Cell,
37 type Screen,
38 type Span,
39 type Ui,
40} from "./layout.tsx";
41import { cells } from "./width.ts";
42
43/** What the two views read beside the tree: handed down with it. */
44export type Extra = { docs: HudDocs; blocks: HudBlock[]; now: number };
45
46export const NO_EXTRA: Extra = {
47 docs: { found: false, docs: [] },
48 blocks: [],
49 now: 0,
50};
51
52export const SETTINGS_LOCAL = ".claude/settings.local.json";
53
54/** The bar's counts: the refusals of the last hour, the documents missing. */
55export function countsOf(extra: Extra): BarCounts {
56 return {
57 blocks: extra.blocks.filter((b) => extra.now - b.at < HOUR_MS).length,
58 docs: missingOf(extra.docs).length,
59 };
60}
61
62/** A refusal's key: what a selection holds across redraws. */
63export const blockKey = (b: HudBlock): string =>
64 `${b.ts}|${b.kind}|${b.tool ?? ""}|${b.summary}`;
65
66/** The view the person chose, every view, or the tree's message. */
67export function viewScreen(
68 model: TreeModel,
69 ui: Ui,
70 width: number,
71 rows: number,
72 extra: Extra = NO_EXTRA,
73): Screen | string {
74 const counts = countsOf(extra);
75 if (ui.view === "blocks") return blocksScreen(extra, ui, width, rows, counts);
76 if (ui.view === "docs")
77 return docsScreen(extra.docs, ui, width, rows, counts);
78 const s = screenOf(model, ui, width, rows, counts);
79 // No tree: its message, and the bar, so the two other views stay reachable
80 if (typeof s !== "string" || rows < 4) return s;
81 return messageScreen(s, ui, width, rows, counts);
82}
83
84function messageScreen(
85 text: string,
86 ui: Ui,
87 width: number,
88 rows: number,
89 counts: BarCounts,
90): Screen {
91 const lines: Cell[][] = [[cell(width, [dim(text)])]];
92 while (lines.length < rows - 2) lines.push([cell(width)]);
93 const t = tabsLines(ui.view, width, counts);
94 lines.push(t.lines[0]!, t.lines[1]!);
95 return {
96 lines,
97 rowIds: lines.map(() => undefined),
98 tabsLine: rows - 1,
99 tabs: t.tabs,
100 order: [],
101 list: { top: 0, rows: 0 },
102 };
103}
104
105function titleOf(what: Span[], width: number): Cell[] {
106 const used = 2;
107 const text = what.map((s) => s.text).join("");
108 const w = Math.min(cells(text), Math.max(0, width - used - 2));
109 const out: Cell[] = [cell(2, [dim("─ ")]), cell(w, what)];
110 const rest = Math.max(0, width - used - w);
111 if (rest > 1) out.push(cell(1), cell(rest - 1, [dim("─".repeat(rest - 1))]));
112 return out;
113}
114
115/**
116 * Where a list of `keys` starts in `space` lines: from the top, or so the
117 * chosen one stays on the line it was acted on (`pin`), else in view.
118 */
119function startOf(
120 keys: string[],
121 sel: string | undefined,
122 pin: Ui["ppin"],
123 top: number,
124 space: number,
125): number {
126 if (keys.length <= space) return 0;
127 const at = sel === undefined ? -1 : keys.indexOf(sel);
128 if (at < 0) return 0;
129 const want =
130 pin?.id === sel ? at - (pin!.y - top) : at < space ? 0 : at - space + 1;
131 return Math.max(0, Math.min(keys.length - space, want));
132}
133
134/** Lays a view out: head lines, the list, two foot lines, then the bar. */
135function frame(
136 head: Cell[][],
137 list: { line: Cell[]; key: string }[],
138 foot: Cell[][],
139 footButtons: { line: number; x: number; w: number; act: Act }[],
140 rowButtons: Map<string, { x: number; w: number; act: Act }[]>,
141 sel: string | undefined,
142 pin: Ui["ppin"],
143 view: Ui["view"],
144 width: number,
145 rows: number,
146 counts: BarCounts,
147 empty: string,
148): Screen {
149 const bar = rows >= 6 ? 2 : 0;
150 const footN = rows >= 8 ? foot.length + 1 : 0;
151 const headN = Math.min(head.length, Math.max(0, rows - bar - footN - 1));
152 const space = Math.max(0, rows - headN - footN - bar);
153 const keys = list.map((l) => l.key);
154 const start = startOf(keys, sel, pin, headN, space);
155 const shown = list.slice(start, start + space);
156
157 const lines: Cell[][] = [];
158 const rowIds: (string | undefined)[] = [];
159 const buttons: NonNullable<Screen["buttons"]> = [];
160 const push = (line: Cell[], id?: string) => {
161 lines.push(line);
162 rowIds.push(id);
163 };
164 for (const h of head.slice(0, headN)) push(h);
165 for (const l of shown) {
166 for (const b of rowButtons.get(l.key) ?? [])
167 buttons.push({ y: lines.length, ...b });
168 push(l.line, l.key);
169 }
170 if (!list.length && space) push([cell(width, [dim(empty)])]);
171 while (lines.length < headN + space) push([cell(width)]);
172 if (footN) {
173 push(rule(width, "┄"));
174 const base = lines.length;
175 for (const f of foot) push(f);
176 for (const b of footButtons)
177 buttons.push({ y: base + b.line, x: b.x, w: b.w, act: b.act });
178 }
179 let tabsLine = -1;
180 let tabs: Screen["tabs"] = [];
181 if (bar) {
182 const t = tabsLines(view, width, counts);
183 push(t.lines[0]!);
184 tabsLine = lines.length;
185 push(t.lines[1]!);
186 tabs = t.tabs;
187 }
188 return {
189 lines,
190 rowIds,
191 tabsLine,
192 tabs,
193 buttons,
194 order: keys,
195 list: { top: headN, rows: space },
196 };
197}
198
199/** A line of buttons and text, with where each button sits. */
200function buttonLine(
201 parts: (Span | { button: string; act: Act; style?: Omit<Span, "text"> })[],
202 width: number,
203): { line: Cell[]; buttons: { x: number; w: number; act: Act }[] } {
204 const line: Cell[] = [];
205 const buttons: { x: number; w: number; act: Act }[] = [];
206 let x = 0;
207 for (const p of parts) {
208 const text = "button" in p ? p.button : p.text;
209 const w = Math.min(cells(text), Math.max(0, width - x));
210 if (!w) break;
211 if ("button" in p) {
212 line.push(cell(w, [span(text, p.style ?? { color: MAUVE })]));
213 buttons.push({ x, w, act: p.act });
214 } else line.push(cell(w, [p]));
215 x += w;
216 }
217 if (width - x > 0) line.push(cell(width - x));
218 return { line, buttons };
219}
220
221// --- « Refus » -----------------------------------------------------------------------
222
223const KIND_TONE: Record<string, Omit<Span, "text">> = {
224 hook: { color: RED },
225 classifier: { color: YOU },
226 permission: { color: YOU },
227 ci: { color: RED },
228 agent: { dim: true },
229};
230
231function countSpans(by: Record<string, number>): Span[] {
232 const kinds = Object.keys(by).filter((k) => by[k]);
233 if (!kinds.length) return [dim("aucun")];
234 const out: Span[] = [];
235 kinds
236 .sort((a, b) => by[b]! - by[a]!)
237 .forEach((k, i) => {
238 if (i) out.push(dim(" · "));
239 out.push(span(`${k} ${by[k]}`, KIND_TONE[k] ?? {}));
240 });
241 return out;
242}
243
244/** The « Refus » view, `width` cells by `rows` lines. */
245export function blocksScreen(
246 extra: Extra,
247 ui: Ui,
248 width: number,
249 rows: number,
250 counts: BarCounts,
251): Screen {
252 const t = tally(extra.blocks, extra.now);
253 const head: Cell[][] = [
254 titleOf(
255 [
256 span("Refus", { color: MAUVE }),
257 dim(
258 ` · ${t.hourTotal} dans la dernière heure, ${t.total} depuis le début`,
259 ),
260 ],
261 width,
262 ),
263 [cell(16, [dim("dernière heure")]), cell(width - 16, countSpans(t.hour))],
264 [cell(16, [dim("session")]), cell(width - 16, countSpans(t.all))],
265 [
266 cell(width, [
267 dim("motif le plus fréquent "),
268 ...(t.top
269 ? [span(t.top.what, { bold: true }), dim(` ×${t.top.n}`)]
270 : [dim("aucun")]),
271 ]),
272 ],
273 ];
274 const showTool = width >= 60;
275 const ruleW = width >= 76 ? Math.min(28, Math.floor(width / 3)) : 0;
276 const fixed = 5 + W.gap + 10 + W.gap + (showTool ? 10 + W.gap : 0);
277 const sumW = Math.max(4, width - fixed - (ruleW ? ruleW + W.gap : 0));
278 const header: Cell[] = [
279 cell(5, [dim("HEURE")]),
280 cell(W.gap),
281 cell(10, [dim("TYPE")]),
282 cell(W.gap),
283 ...(showTool ? [cell(10, [dim("OUTIL")]), cell(W.gap)] : []),
284 cell(sumW, [dim("RÉSUMÉ")]),
285 ...(ruleW ? [cell(W.gap), cell(ruleW, [dim("RÈGLE")])] : []),
286 ];
287 head.push(header);
288
289 const list = extra.blocks.map((b) => {
290 const key = blockKey(b);
291 const chosen = key === ui.bsel;
292 const line: Cell[] = [
293 cell(5, [dim(hhmm(b.at))]),
294 cell(W.gap),
295 cell(10, [span(b.kind, KIND_TONE[b.kind] ?? {})]),
296 cell(W.gap),
297 ...(showTool
298 ? [cell(10, [span(b.tool ?? "—", { dim: !b.tool })]), cell(W.gap)]
299 : []),
300 cell(sumW, [
301 span(b.summary || b.motif || "", chosen ? { underline: true } : {}),
302 ]),
303 ...(ruleW
304 ? [
305 cell(W.gap),
306 cell(ruleW, b.rule ? [span(b.rule, { color: BLUE })] : []),
307 ]
308 : []),
309 ];
310 return { line, key };
311 });
312
313 const chosen = extra.blocks.find((b) => blockKey(b) === ui.bsel);
314 const foot: Cell[][] = [];
315 const footButtons: { line: number; x: number; w: number; act: Act }[] = [];
316 if (ui.pick) {
317 foot.push([
318 cell(width, [
319 span("Autoriser ", { bold: true }),
320 span(ui.pick, { color: BLUE, bold: true }),
321 dim(` dans ${SETTINGS_LOCAL} ?`),
322 ]),
323 ]);
324 const b = buttonLine(
325 [
326 {
327 button: "[ajouter]",
328 act: { op: "allow", rule: ui.pick },
329 style: { color: GREEN, bold: true },
330 },
331 dim(" "),
332 { button: "[copier]", act: { op: "copy", rule: ui.pick } },
333 dim(" "),
334 { button: "[annuler]", act: { op: "cancel" }, style: { dim: true } },
335 dim(" a · c · n"),
336 ],
337 width,
338 );
339 foot.push(b.line);
340 for (const x of b.buttons) footButtons.push({ line: 1, ...x });
341 } else if (chosen) {
342 const who = [chosen.tool, chosen.agent, chosen.motif]
343 .filter(Boolean)
344 .join(" · ");
345 foot.push([
346 cell(width, [
347 span(
348 `${hhmm(chosen.at)} ${chosen.kind} `,
349 KIND_TONE[chosen.kind] ?? {},
350 ),
351 span(chosen.summary, { bold: true }),
352 dim(who ? ` ${who}` : ""),
353 ]),
354 ]);
355 foot.push([
356 cell(W.gap),
357 cell(
358 Math.max(0, width - W.gap),
359 chosen.rule
360 ? [
361 dim("⏎ ou clic : autoriser "),
362 span(chosen.rule, { color: BLUE }),
363 dim(", après confirmation"),
364 ]
365 : [
366 dim(
367 chosen.ref ??
368 "Aucune règle de permission déduite pour ce refus",
369 ),
370 ],
371 ),
372 ]);
373 } else {
374 foot.push([cell(width, [dim("Aucun refus choisi")])]);
375 foot.push([
376 cell(W.gap),
377 cell(Math.max(0, width - W.gap), [
378 dim(
379 "Un refus qui porte une règle : clic, puis « ajouter » pour l'autoriser",
380 ),
381 ]),
382 ]);
383 }
384 return frame(
385 head,
386 list,
387 foot,
388 footButtons,
389 new Map(),
390 ui.bsel,
391 ui.ppin,
392 "blocks",
393 width,
394 rows,
395 counts,
396 "Aucun refus dans cette session.",
397 );
398}
399
400// --- « Documents » ---------------------------------------------------------------------
401
402const DOC_GLYPH: Record<HudDoc["state"], Span> = {
403 ok: { text: "●", color: GREEN },
404 missing: { text: "●", color: RED },
405 ignored: { text: "○", dim: true },
406};
407
408/** The « Documents » view, `width` cells by `rows` lines. */
409export function docsScreen(
410 docs: HudDocs,
411 ui: Ui,
412 width: number,
413 rows: number,
414 counts: BarCounts,
415): Screen {
416 const missing = missingOf(docs);
417 const n = (s: HudDoc["state"]) =>
418 docs.docs.filter((d) => d.state === s).length;
419 const head: Cell[][] = [
420 titleOf(
421 [
422 span("Documents", { color: MAUVE }),
423 dim(
424 docs.found
425 ? ` · ${missing.length} manquant${missing.length > 1 ? "s" : ""} · ${n("ignored")} ignoré${n("ignored") > 1 ? "s" : ""} · ${n("ok")} présent${n("ok") > 1 ? "s" : ""}`
426 : "",
427 ),
428 ],
429 width,
430 ),
431 ];
432 const nameW = Math.min(26, Math.max(8, Math.floor((width - 2) / 3)));
433 const btnW = 7; // « [créer] »
434 const pathW = Math.max(4, width - 2 - nameW - W.gap - W.gap - btnW);
435 head.push([
436 cell(2),
437 cell(nameW, [dim("DOCUMENT")]),
438 cell(W.gap),
439 cell(pathW, [dim("CHEMIN")]),
440 ]);
441
442 const rowButtons = new Map<string, { x: number; w: number; act: Act }[]>();
443 const list = docs.docs.map((d) => {
444 const key = d.id;
445 const chosen = key === ui.dsel;
446 const path: Span[] = [
447 span(d.path, d.state === "ignored" ? { dim: true } : {}),
448 ];
449 if (d.state === "ignored")
450 path.push(dim(d.reason ? ` ignoré : ${d.reason}` : " ignoré"));
451 const line: Cell[] = [
452 cell(2, [DOC_GLYPH[d.state]]),
453 cell(nameW, [
454 span(d.name, {
455 ...(d.state === "ignored" && { dim: true }),
456 ...(chosen && { underline: true }),
457 }),
458 ]),
459 cell(W.gap),
460 cell(pathW, path),
461 cell(W.gap),
462 ];
463 if (d.state === "missing") {
464 line.push(cell(btnW, [span("[créer]", { color: MAUVE })]));
465 rowButtons.set(key, [
466 { x: width - btnW, w: btnW, act: { op: "create", ids: [d.id] } },
467 ]);
468 } else line.push(cell(btnW));
469 return { line, key };
470 });
471
472 const mode = ui.mode ?? "both";
473 const all = missing.length
474 ? `[Créer les manquants (${missing.length})]`
475 : "Aucun document manquant";
476 const parts: Parameters<typeof buttonLine>[0] = [
477 missing.length
478 ? {
479 button: all,
480 act: { op: "create", ids: [] },
481 style: { color: MAUVE, bold: true },
482 }
483 : dim(all),
484 dim(" mode "),
485 ];
486 MODES.forEach((m, i) => {
487 if (i) parts.push(dim(" · "));
488 parts.push({
489 button: m,
490 act: { op: "mode", mode: m },
491 style:
492 m === mode
493 ? { color: MAUVE, bold: true, underline: true }
494 : { dim: true },
495 });
496 });
497 const b = buttonLine(parts, width);
498 const chosen = docs.docs.find((d) => d.id === ui.dsel);
499 const foot: Cell[][] = [
500 b.line,
501 [
502 cell(W.gap),
503 cell(
504 Math.max(0, width - W.gap),
505 chosen?.why
506 ? [dim(`${chosen.name} : ${chosen.why}`)]
507 : [
508 dim(
509 "Clic : ignorer ou rétablir · le brouillon n'est jamais envoyé seul",
510 ),
511 ],
512 ),
513 ],
514 ];
515 return frame(
516 head,
517 list,
518 foot,
519 b.buttons.map((x) => ({ line: 0, ...x })),
520 rowButtons,
521 ui.dsel,
522 ui.ppin,
523 "docs",
524 width,
525 rows,
526 counts,
527 docs.found
528 ? "Aucun document dans docs.json."
529 : "Pas de docs.json pour cette session (kodflow-hooks le tient, dans un dépôt git).",
530 );
531}
532hooks/mod/docs.ts 150 lines1// docs.ts — the « Documents » view's data: docs.json as kodflow-hooks
2// computes it, the project's docs/manifest.json as a click rewrites it, and
3// the prompt a « Créer » button drafts. Pure.
4//
5// docs.json and the manifest are kodflow-hooks' contract (catalogue of 15
6// documents, `ok` | `missing` | `ignored`); this mod reads the first and
7// rewrites the second only on the person's click, keeping every key it does
8// not know, the documents in the catalogue's order, two spaces, a final
9// newline.
10
11import type { HudDoc, HudDocs } from "../../types";
12
13/** The catalogue's ids, in its order: the manifest's documents are sorted by it. */
14export const CATALOG = [
15 "prd",
16 "trd",
17 "flow",
18 "design",
19 "data",
20 "impl",
21 "adr",
22 "voice",
23 "glossary",
24 "quality",
25 "testing",
26 "threat",
27 "rgpd",
28 "ops",
29 "readme",
30] as const;
31
32export const MODES = ["ask", "context", "both"] as const;
33export type DocMode = (typeof MODES)[number];
34
35export const NO_DOCS: HudDocs = { found: false, docs: [] };
36
37const STATES = new Set(["ok", "missing", "ignored"]);
38const str = (v: unknown): string | undefined =>
39 typeof v === "string" ? v : undefined;
40
41/** docs.json's text as the view reads it; anything malformed is left out. */
42export function parseDocs(text: string | undefined): HudDocs {
43 if (text === undefined) return NO_DOCS;
44 let raw: any;
45 try {
46 raw = JSON.parse(text);
47 } catch {
48 return NO_DOCS;
49 }
50 if (!raw || typeof raw !== "object" || !Array.isArray(raw.docs))
51 return NO_DOCS;
52 const docs: HudDoc[] = [];
53 for (const d of raw.docs) {
54 const id = str(d?.id);
55 const path = str(d?.path);
56 if (!id || !path || !STATES.has(d.state)) continue;
57 docs.push({
58 id,
59 name: str(d.name) || id,
60 path,
61 state: d.state,
62 ...(str(d.reason) !== undefined && { reason: d.reason }),
63 ...(str(d.why) && { why: d.why }),
64 });
65 }
66 const root = str(raw.root);
67 const manifest = str(raw.manifest);
68 return {
69 found: true,
70 ...(root && { root }),
71 ...(manifest && { manifest }),
72 docs,
73 };
74}
75
76export const missingOf = (docs: HudDocs): HudDoc[] =>
77 docs.docs.filter((d) => d.state === "missing");
78
79/**
80 * Where the manifest is, absolute: under docs.json's root, at the path it
81 * names (docs/manifest.json by default). Undefined when the root is not
82 * absolute or the path climbs out of it.
83 */
84export function manifestPath(docs: HudDocs): string | undefined {
85 const root = docs.root;
86 if (!root || !root.startsWith("/")) return undefined;
87 const rel = docs.manifest || "docs/manifest.json";
88 if (rel.startsWith("/") || rel.split("/").includes("..")) return undefined;
89 return `${root.replace(/\/+$/, "")}/${rel}`;
90}
91
92/**
93 * The manifest with `id` ignored or brought back. `text` is the file as it
94 * stands (undefined: absent). Unknown keys stay; the documents follow the
95 * catalogue's order, ids it does not know after them as they stood. An
96 * ignored document keeps its `path`; brought back, an entry left empty goes.
97 * Undefined when the file is not a JSON object: it is never overwritten.
98 */
99export function toggleManifest(
100 text: string | undefined,
101 id: string,
102 ignore: boolean,
103 reason = "",
104): string | undefined {
105 let raw: any = {};
106 if (text !== undefined && text.trim()) {
107 try {
108 raw = JSON.parse(text);
109 } catch {
110 return undefined;
111 }
112 if (!raw || typeof raw !== "object" || Array.isArray(raw)) return undefined;
113 }
114 const docs: Record<string, any> =
115 raw.documents &&
116 typeof raw.documents === "object" &&
117 !Array.isArray(raw.documents)
118 ? { ...raw.documents }
119 : {};
120 const entry: Record<string, unknown> =
121 docs[id] && typeof docs[id] === "object" ? { ...docs[id] } : {};
122 if (ignore) entry.ignored = reason;
123 else delete entry.ignored;
124 if (Object.keys(entry).length) docs[id] = entry;
125 else delete docs[id];
126 const known = (k: string) => (CATALOG as readonly string[]).indexOf(k);
127 const keys = Object.keys(docs);
128 const sorted = [
129 ...keys.filter((k) => known(k) >= 0).sort((a, b) => known(a) - known(b)),
130 ...keys.filter((k) => known(k) < 0),
131 ];
132 const documents: Record<string, unknown> = {};
133 for (const k of sorted) documents[k] = docs[k];
134 // version first when the file had none, every other key where it stood
135 const out: Record<string, unknown> = "version" in raw ? {} : { version: 1 };
136 for (const [k, v] of Object.entries(raw))
137 out[k] = k === "documents" ? documents : v;
138 if (!("documents" in raw)) out.documents = documents;
139 return `${JSON.stringify(out, null, 2)}\n`;
140}
141
142/**
143 * What a « Créer » button drafts: the docs skill on the ids given (none:
144 * every missing one) and the mode chosen.
145 */
146export function createPrompt(ids: readonly string[], mode: DocMode): string {
147 const list = ids.length ? ` ${ids.join(",")}` : "";
148 return `/kodflow-workflow:docs${list} --mode ${mode}`;
149}
150hooks/mod/refusals.ts 157 lines1// refusals.ts — the « Refus » view's data: blocks.jsonl as kodflow-hooks
2// appends it (one blocking per line, 500 kept), what has piled up, and the
3// one write this mod may make for a refusal: a permission rule the person
4// confirmed, added to the project's .claude/settings.local.json. Pure.
5
6import type { HudBlock } from "../../types";
7
8export const KINDS = [
9 "hook",
10 "classifier",
11 "permission",
12 "ci",
13 "agent",
14] as const;
15export const HOUR_MS = 3_600_000;
16/** What the view is handed: the newest, enough to fill any pane. */
17export const KEEP = 200;
18
19const str = (v: unknown): string | undefined =>
20 typeof v === "string" && v ? v : undefined;
21
22/** blocks.jsonl's text, newest first; a line that is not one is skipped. */
23export function parseBlocks(text: string | undefined): HudBlock[] {
24 if (!text) return [];
25 const out: HudBlock[] = [];
26 for (const line of text.split("\n")) {
27 if (!line.trim()) continue;
28 let raw: any;
29 try {
30 raw = JSON.parse(line);
31 } catch {
32 continue;
33 }
34 const ts = str(raw?.ts);
35 const at = ts ? Date.parse(ts) : NaN;
36 if (
37 !ts ||
38 !Number.isFinite(at) ||
39 !(KINDS as readonly string[]).includes(raw.kind)
40 )
41 continue;
42 out.push({
43 ts,
44 at,
45 kind: raw.kind,
46 summary: str(raw.summary) ?? "",
47 ...(str(raw.tool) && { tool: raw.tool }),
48 ...(str(raw.motif) && { motif: raw.motif }),
49 ...(str(raw.agent) && { agent: raw.agent }),
50 ...(str(raw.ref) && { ref: raw.ref }),
51 ...(str(raw.rule) && { rule: raw.rule }),
52 });
53 }
54 // A stable sort: two at the same second keep the file's order, reversed
55 return out
56 .map((b, i) => ({ b, i }))
57 .sort((x, y) => y.b.at - x.b.at || y.i - x.i)
58 .map((x) => x.b)
59 .slice(0, KEEP);
60}
61
62export type Tally = {
63 hour: Record<string, number>;
64 all: Record<string, number>;
65 hourTotal: number;
66 total: number;
67 /** The reason seen most often: a hook's motif, else the summary. */
68 top?: { what: string; n: number };
69};
70
71/** How many of each kind in the last hour and since the session began. */
72export function tally(blocks: readonly HudBlock[], now: number): Tally {
73 const hour: Record<string, number> = {};
74 const all: Record<string, number> = {};
75 const why = new Map<string, number>();
76 let hourTotal = 0;
77 for (const b of blocks) {
78 all[b.kind] = (all[b.kind] ?? 0) + 1;
79 if (now - b.at < HOUR_MS) {
80 hour[b.kind] = (hour[b.kind] ?? 0) + 1;
81 hourTotal++;
82 }
83 const what = b.motif ?? b.summary;
84 if (what) why.set(what, (why.get(what) ?? 0) + 1);
85 }
86 let top: Tally["top"];
87 for (const [what, n] of why) if (!top || n > top.n) top = { what, n };
88 return { hour, all, hourTotal, total: blocks.length, ...(top && { top }) };
89}
90
91/** "11:41", local time, of an ISO stamp. */
92export function hhmm(at: number): string {
93 const d = new Date(at);
94 const p = (n: number) => String(n).padStart(2, "0");
95 return `${p(d.getHours())}:${p(d.getMinutes())}`;
96}
97
98// Tools a bare rule would hand over whole: a rule for one of them must say
99// what it allows, inside parentheses
100const WIDE = new Set([
101 "Bash",
102 "Write",
103 "Edit",
104 "MultiEdit",
105 "NotebookEdit",
106 "PowerShell",
107]);
108
109/**
110 * Whether `rule` may be offered: settings.json's shape (`Tool` or
111 * `Tool(content)`), one line, at most 200 characters, and never a rule that
112 * allows a whole shell or every write (`Bash`, `Bash(*)`, `Edit(**)`).
113 */
114export function safeRule(rule: unknown): rule is string {
115 if (typeof rule !== "string" || !rule || rule.length > 200) return false;
116 if (/[\u0000-\u001f\u007f]/.test(rule)) return false;
117 const m = /^([A-Za-z][A-Za-z0-9_-]*)(?:\((.+)\))?$/.exec(rule);
118 if (!m) return false;
119 const [, tool, content] = m;
120 if (content === undefined) return !WIDE.has(tool!);
121 return !/^[\s*:/.~]*$/.test(content);
122}
123
124/**
125 * settings.local.json with `rule` in permissions.allow. `text` is the file as
126 * it stands (undefined: absent). Every other key stays where it was; a rule
127 * already there changes nothing. Undefined when the file is not a JSON
128 * object: it is never overwritten.
129 */
130export function addRule(
131 text: string | undefined,
132 rule: string,
133): string | undefined {
134 let raw: any = {};
135 if (text !== undefined && text.trim()) {
136 try {
137 raw = JSON.parse(text);
138 } catch {
139 return undefined;
140 }
141 if (!raw || typeof raw !== "object" || Array.isArray(raw)) return undefined;
142 }
143 const perms =
144 raw.permissions &&
145 typeof raw.permissions === "object" &&
146 !Array.isArray(raw.permissions)
147 ? raw.permissions
148 : undefined;
149 if (raw.permissions !== undefined && !perms) return undefined;
150 if (perms && perms.allow !== undefined && !Array.isArray(perms.allow))
151 return undefined;
152 const allow: unknown[] = perms?.allow ?? [];
153 if (allow.includes(rule)) return text;
154 const permissions = { ...(perms ?? {}), allow: [...allow, rule] };
155 return `${JSON.stringify({ ...raw, permissions }, null, 2)}\n`;
156}
157hooks/mod/colors.ts 141 lines1// colors.ts — a few words of a reply in colour, never a whole paragraph.
2//
3// The model writes `{{r:words}}`; the transcript draws "words" in red, bold,
4// and the markup is gone. A paragraph with no markup, and every fenced code
5// block, is left to the engine's own markdown. The convention reaches the
6// model as one system prompt section (PROMPT_SECTION), on the session's side
7// of the cache boundary, so it holds after a compaction.
8//
9// Pure: no `$`, nothing read from the host. register.tsx wires it.
10
11/** The four marks and their colours. */
12export const COLORS: Record<string, string> = {
13 r: "red", // blocking
14 o: "#ff8c00", // needs attention
15 v: "green", // waits on the person: their attention or their answer
16 p: "#ff69b4", // a decision the person already made
17};
18
19export type Run = { text: string; color?: string; bold?: boolean };
20export type Block = { markdown: string } | { runs: Run[] };
21
22const MARK = /\{\{([rovp]):([^{}]+?)\}\}/g;
23const HAS_MARK = /\{\{[rovp]:[^{}]+?\}\}/;
24// Inline code, `like this`: a mark inside it is shown as typed
25// (CommonMark: a run of backticks closed by a run of the same length, a
26// shorter run inside it is code too)
27const INLINE_CODE = /(?<!`)(`+)(?!`)[\s\S]*?(?<!`)\1(?!`)/g;
28// A fence opens on three backticks or tildes or more and closes on a line
29// of the same character, at least as long, with nothing after it
30const FENCE_OPEN = /^ {0,3}(`{3,}|~{3,})/;
31
32/** Splits on blank lines; a fenced code block stays one block. */
33export function paragraphs(text: string): { text: string; code: boolean }[] {
34 const out: { text: string; code: boolean }[] = [];
35 let buf: string[] = [];
36 let fence = "";
37 const flush = (code: boolean) => {
38 if (buf.length) out.push({ text: buf.join("\n"), code });
39 buf = [];
40 };
41 const closes = (line: string): boolean => {
42 const m = /^ {0,3}(`+|~+)\s*$/.exec(line);
43 return !!m && m[1]![0] === fence[0] && m[1]!.length >= fence.length;
44 };
45 for (const line of text.split("\n")) {
46 if (fence) {
47 buf.push(line);
48 if (closes(line)) {
49 flush(true);
50 fence = "";
51 }
52 continue;
53 }
54 const open = FENCE_OPEN.exec(line);
55 if (open) {
56 flush(false);
57 buf.push(line);
58 fence = open[1]!;
59 continue;
60 }
61 if (line.trim() === "") {
62 flush(false);
63 continue;
64 }
65 buf.push(line);
66 }
67 // An unclosed fence is still code: never interpreted
68 flush(!!fence);
69 return out;
70}
71
72/** One paragraph as runs: coloured marks, **bold**, plain text. */
73export function runs(paragraph: string): Run[] {
74 const out: Run[] = [];
75 const plain = (s: string) => {
76 for (const [i, part] of s.split("**").entries())
77 if (part) out.push(i % 2 ? { text: part, bold: true } : { text: part });
78 };
79 const marks = (s: string) => {
80 let last = 0;
81 for (const m of s.matchAll(MARK)) {
82 plain(s.slice(last, m.index));
83 out.push({ text: m[2]!, color: COLORS[m[1]!], bold: true });
84 last = m.index! + m[0].length;
85 }
86 plain(s.slice(last));
87 };
88 let last = 0;
89 for (const c of paragraph.matchAll(INLINE_CODE)) {
90 marks(paragraph.slice(last, c.index));
91 out.push({ text: c[0] });
92 last = c.index! + c[0].length;
93 }
94 marks(paragraph.slice(last));
95 return out;
96}
97
98/** A reply as blocks: runs where a paragraph is marked, markdown elsewhere. */
99export function blocks(text: string): Block[] {
100 return paragraphs(text).map((p) =>
101 !p.code && HAS_MARK.test(p.text.replace(INLINE_CODE, ""))
102 ? { runs: runs(p.text) }
103 : { markdown: p.text },
104 );
105}
106
107/** True when the reply holds a mark the transcript would colour. */
108export const marked = (parts: Block[]): boolean =>
109 parts.some((p) => "runs" in p);
110
111/** KODFLOW_COLORS=off (or 0, false, no) turns off the colours and the section. */
112export const colorsOff = (value: string | undefined): boolean =>
113 /^(off|0|false|no)$/i.test((value ?? "").trim());
114
115export const SECTION_ID = "kodflow-hud:colors";
116
117/**
118 * The convention as the model reads it. Short on purpose: it rides on every
119 * request of the session.
120 */
121export const PROMPT_SECTION = [
122 "# Coloured words",
123 "",
124 "The terminal colours a few words of your replies when you wrap them in a mark; the mark itself is never shown:",
125 "- `{{r:words}}` red: what blocks (a failure, a refusal, a stop).",
126 "- `{{o:words}}` orange: what needs attention (a risk, a warning, a limit).",
127 "- `{{v:words}}` green: what waits on the user, their answer or their action.",
128 "- `{{p:words}}` pink: a decision the user already made; use it only when you cite that decision with its date.",
129 "",
130 "Colour two to five words at a time, never a sentence or a paragraph, and put at most a few marks in one message; most messages need none. Never put a mark in code, in a command, in a path or in a table meant to be copied, since it would be copied as typed. A paragraph holding a mark loses its other markdown except bold, so keep links, lists and inline code out of it.",
131].join("\n");
132
133/** Whether the prompt being composed is one the transcript will draw. */
134export function drawn(input: {
135 surfaces: readonly string[];
136 traits: readonly string[];
137}): boolean {
138 if (!input.surfaces.length) return false;
139 return !input.traits.some((t) => t === "print" || t === "bare");
140}
141hooks/mod/models.ts 110 lines1// models.ts — what each loop runs on, and who worked each task. Pure.
2//
3// The tree's model·effort column shows only what the session said, from
4// three places, the later filling what the earlier left out:
5// agent-models.tsv kodflow-hooks' record of every Agent call (its
6// PostToolUse: agent id, resolvedModel, the call's
7// effort, the type), read for the loops started before
8// this module loaded;
9// agent.spawn the model core resolved for the subagent it started;
10// tool.call Agent the call's `effort` and the result's resolvedModel.
11// The main loop's model is `$.session.model()`; its effort is said nowhere
12// a hooks module reads, so it stays absent. Nothing is guessed: a loop no
13// source names has an empty cell.
14
15import type { HudModel, HudSeen, HudTask } from "../../types";
16
17/**
18 * The models kept are keyed `<session>:<loop>`: "main" is every session's
19 * main loop, and only the current session's entries are kept.
20 */
21export const modelKey = (session: string, loop: string) => `${session}:${loop}`;
22
23/** A record keyed `<session>:…` with only that session's entries left. */
24export function keepSession<T>(
25 record: Readonly<Record<string, T>>,
26 session: string,
27): Record<string, T> {
28 const prefix = `${session}:`;
29 return Object.fromEntries(
30 Object.entries(record).filter(([k]) => k.startsWith(prefix)),
31 );
32}
33
34/** Fields of `b` that are set win over `a`'s. */
35export function merge(a: HudModel | undefined, b: HudModel): HudModel {
36 const out: HudModel = { ...a };
37 if (b.model) out.model = b.model;
38 if (b.effort) out.effort = b.effort;
39 return out;
40}
41
42const str = (v: unknown): string =>
43 typeof v === "string" ? v.trim() : typeof v === "number" ? String(v) : "";
44
45/** agent-models.tsv: `agentId \t resolvedModel \t effort \t type`, latest last. */
46export function parseModels(
47 text: string | undefined,
48): Record<string, HudModel> {
49 const out: Record<string, HudModel> = {};
50 for (const line of (text ?? "").split("\n")) {
51 const [id, model, effort] = line.split("\t");
52 if (!id) continue;
53 out[id] = merge(out[id], {
54 ...(model && { model }),
55 ...(effort && { effort }),
56 });
57 }
58 return out;
59}
60
61/** What an Agent call says of the loop it started: its id, model, effort. */
62export function fromAgentCall(
63 input: { effort?: unknown },
64 result: unknown,
65): { id: string; model: HudModel } | undefined {
66 const r = (result ?? {}) as { agentId?: unknown; resolvedModel?: unknown };
67 const id = str(r.agentId);
68 if (!id) return undefined;
69 const model: HudModel = {};
70 const m = str(r.resolvedModel);
71 const effort = str(input.effort);
72 if (m) model.model = m;
73 if (effort) model.effort = effort;
74 return { id, model };
75}
76
77/**
78 * The worker of every task in progress, added to what was seen before:
79 * tasks.json drops the link when a task leaves in_progress, the tree still
80 * names who did it. Keyed by session too, as task ids start over in each
81 * session's file; only the current session's are kept, so the record is
82 * bounded by one list. Undefined when nothing changed.
83 */
84export const seenKey = (session: string, t: Pick<HudTask, "agent" | "id">) =>
85 `${session}:${t.agent}:${t.id}`;
86
87export function seenFrom(
88 tasks: readonly HudTask[],
89 before: Readonly<Record<string, HudSeen>>,
90 session: string,
91): Record<string, HudSeen> | undefined {
92 const prefix = `${session}:`;
93 const stale = Object.keys(before).some((k) => !k.startsWith(prefix));
94 let out: Record<string, HudSeen> | undefined = stale
95 ? keepSession(before, session)
96 : undefined;
97 for (const t of tasks) {
98 if (t.status !== "in_progress" || !(t.worker || t.workerId)) continue;
99 const key = seenKey(session, t);
100 const was = (out ?? before)[key];
101 if (was?.worker === t.worker && was?.workerId === t.workerId) continue;
102 out ??= { ...before };
103 out[key] = {
104 ...(t.worker && { worker: t.worker }),
105 ...(t.workerId && { workerId: t.workerId }),
106 };
107 }
108 return out;
109}
110