teamsmith 0.0.0-stage → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (245) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +158 -2
  3. package/bin/team.mjs +59 -0
  4. package/install.sh +94 -0
  5. package/package.json +37 -4
  6. package/skills/teamsmith/CHANGELOG.md +763 -0
  7. package/skills/teamsmith/SKILL.md +312 -0
  8. package/skills/teamsmith/extension/team-bg.ts +435 -0
  9. package/skills/teamsmith/extension/team-inbox-watch.ts +1412 -0
  10. package/skills/teamsmith/extension/team-notify.ts +663 -0
  11. package/skills/teamsmith/references/agent-adapters.md +643 -0
  12. package/skills/teamsmith/references/config.md +477 -0
  13. package/skills/teamsmith/references/meeting.md +124 -0
  14. package/skills/teamsmith/references/memory.md +133 -0
  15. package/skills/teamsmith/references/migration.md +227 -0
  16. package/skills/teamsmith/references/openspec.md +222 -0
  17. package/skills/teamsmith/references/philosophy.md +95 -0
  18. package/skills/teamsmith/references/protocol.md +712 -0
  19. package/skills/teamsmith/references/troubleshooting.md +1384 -0
  20. package/skills/teamsmith/references/workflows.md +448 -0
  21. package/skills/teamsmith/scripts/lib/cmd-agents.sh +1709 -0
  22. package/skills/teamsmith/scripts/lib/cmd-bg.sh +284 -0
  23. package/skills/teamsmith/scripts/lib/cmd-bootstrap.sh +311 -0
  24. package/skills/teamsmith/scripts/lib/cmd-config.sh +1156 -0
  25. package/skills/teamsmith/scripts/lib/cmd-death.sh +562 -0
  26. package/skills/teamsmith/scripts/lib/cmd-docs.sh +149 -0
  27. package/skills/teamsmith/scripts/lib/cmd-draft.sh +124 -0
  28. package/skills/teamsmith/scripts/lib/cmd-init.sh +212 -0
  29. package/skills/teamsmith/scripts/lib/cmd-meeting.sh +904 -0
  30. package/skills/teamsmith/scripts/lib/cmd-outbox.sh +196 -0
  31. package/skills/teamsmith/scripts/lib/cmd-project.sh +642 -0
  32. package/skills/teamsmith/scripts/lib/cmd-review.sh +1393 -0
  33. package/skills/teamsmith/scripts/lib/cmd-status.sh +1399 -0
  34. package/skills/teamsmith/scripts/lib/cmd-update.sh +191 -0
  35. package/skills/teamsmith/scripts/lib/cmd-watch.sh +1681 -0
  36. package/skills/teamsmith/scripts/lib/common.sh +4964 -0
  37. package/skills/teamsmith/scripts/lib/draft-entry.sh +51 -0
  38. package/skills/teamsmith/scripts/lib/outbox.sh +2042 -0
  39. package/skills/teamsmith/scripts/lib/tmux-argv.sh +165 -0
  40. package/skills/teamsmith/scripts/monitor.mjs +616 -0
  41. package/skills/teamsmith/scripts/panel/README.md +192 -0
  42. package/skills/teamsmith/scripts/panel/build.sh +47 -0
  43. package/skills/teamsmith/scripts/panel/bun.lock +109 -0
  44. package/skills/teamsmith/scripts/panel/draft-send.sh +68 -0
  45. package/skills/teamsmith/scripts/panel/package.json +24 -0
  46. package/skills/teamsmith/scripts/panel/panel.js +388 -0
  47. package/skills/teamsmith/scripts/panel/src/App.tsx +2150 -0
  48. package/skills/teamsmith/scripts/panel/src/clipboard.ts +154 -0
  49. package/skills/teamsmith/scripts/panel/src/compose.ts +691 -0
  50. package/skills/teamsmith/scripts/panel/src/data.ts +555 -0
  51. package/skills/teamsmith/scripts/panel/src/format.ts +50 -0
  52. package/skills/teamsmith/scripts/panel/src/layout.ts +2562 -0
  53. package/skills/teamsmith/scripts/panel/src/main.tsx +894 -0
  54. package/skills/teamsmith/scripts/panel/src/markdown.ts +340 -0
  55. package/skills/teamsmith/scripts/panel/src/sanitize.ts +42 -0
  56. package/skills/teamsmith/scripts/panel/src/settings.ts +154 -0
  57. package/skills/teamsmith/scripts/panel/src/strings/en.ts +416 -0
  58. package/skills/teamsmith/scripts/panel/src/strings/index.ts +65 -0
  59. package/skills/teamsmith/scripts/panel/src/strings/types.ts +9 -0
  60. package/skills/teamsmith/scripts/panel/src/strings/zh.ts +414 -0
  61. package/skills/teamsmith/scripts/panel/src/theme.ts +116 -0
  62. package/skills/teamsmith/scripts/panel/src/types.ts +652 -0
  63. package/skills/teamsmith/scripts/panel/src/width.ts +105 -0
  64. package/skills/teamsmith/scripts/panel/tsconfig.json +16 -0
  65. package/skills/teamsmith/scripts/shim/signal-gate +156 -0
  66. package/skills/teamsmith/scripts/shim/tmux +403 -0
  67. package/skills/teamsmith/scripts/team +143 -0
  68. package/skills/teamsmith/templates/AGENTS.section.md.tmpl +147 -0
  69. package/skills/teamsmith/templates/BOARD.md.tmpl +18 -0
  70. package/skills/teamsmith/templates/DECISIONS.md.tmpl +22 -0
  71. package/skills/teamsmith/templates/OWNERSHIP.md.tmpl +25 -0
  72. package/skills/teamsmith/templates/PROTOCOL.md.tmpl +84 -0
  73. package/skills/teamsmith/templates/ROADMAP.md.tmpl +29 -0
  74. package/skills/teamsmith/templates/config.sh.tmpl +106 -0
  75. package/skills/teamsmith/templates/memory-seed.md.tmpl +46 -0
  76. package/skills/teamsmith/templates/pm-prompt.md.tmpl +110 -0
  77. package/skills/teamsmith/templates/report.md.tmpl +36 -0
  78. package/skills/teamsmith/templates/task.md.tmpl +65 -0
  79. package/skills/teamsmith/templates/threads-README.md +17 -0
  80. package/skills/teamsmith/tests/bg-ledger-harness.mjs +682 -0
  81. package/skills/teamsmith/tests/bg-ledger.sh +307 -0
  82. package/skills/teamsmith/tests/checkout-shape-probe.sh +800 -0
  83. package/skills/teamsmith/tests/config-cli.sh +1562 -0
  84. package/skills/teamsmith/tests/container-tmux.sh +493 -0
  85. package/skills/teamsmith/tests/coverage-inventory.sh +173 -0
  86. package/skills/teamsmith/tests/death-cause.sh +564 -0
  87. package/skills/teamsmith/tests/delivery-truth.sh +1231 -0
  88. package/skills/teamsmith/tests/fake-tui.py +450 -0
  89. package/skills/teamsmith/tests/fixtures/delivery-truth-real/README.md +60 -0
  90. package/skills/teamsmith/tests/fixtures/delivery-truth-real/judge-second.py +139 -0
  91. package/skills/teamsmith/tests/fixtures/delivery-truth-real/mock-server.py +29 -0
  92. package/skills/teamsmith/tests/fixtures/delivery-truth-real/observe.ts +20 -0
  93. package/skills/teamsmith/tests/fixtures/delivery-truth-real/run-case.sh +79 -0
  94. package/skills/teamsmith/tests/fixtures/delivery-truth-real/scenario.sh +175 -0
  95. package/skills/teamsmith/tests/fixtures/p55/flip-p49.sh +229 -0
  96. package/skills/teamsmith/tests/fixtures/p71-incident/README.md +22 -0
  97. package/skills/teamsmith/tests/fixtures/p71-incident/dev2.seen +8 -0
  98. package/skills/teamsmith/tests/fixtures/p71-incident/dev2.wake +9 -0
  99. package/skills/teamsmith/tests/fixtures/p71-incident/pm-nudges.wake +3 -0
  100. package/skills/teamsmith/tests/fixtures/signal-lint-cases.txt +40 -0
  101. package/skills/teamsmith/tests/flip-glue.sh +162 -0
  102. package/skills/teamsmith/tests/flip-m12-26c.sh +129 -0
  103. package/skills/teamsmith/tests/flip-m12.sh +185 -0
  104. package/skills/teamsmith/tests/flip-m16.sh +166 -0
  105. package/skills/teamsmith/tests/flip-m17.sh +204 -0
  106. package/skills/teamsmith/tests/flip-m33.sh +284 -0
  107. package/skills/teamsmith/tests/flip-m34.sh +96 -0
  108. package/skills/teamsmith/tests/flip-m37.sh +185 -0
  109. package/skills/teamsmith/tests/flip-m4.3.sh +375 -0
  110. package/skills/teamsmith/tests/flip-m43.sh +128 -0
  111. package/skills/teamsmith/tests/flip-m44.sh +262 -0
  112. package/skills/teamsmith/tests/flip-m45.sh +244 -0
  113. package/skills/teamsmith/tests/flip-m46.sh +238 -0
  114. package/skills/teamsmith/tests/flip-m48.sh +304 -0
  115. package/skills/teamsmith/tests/flip-m6.2.sh +205 -0
  116. package/skills/teamsmith/tests/flip-m6.3.sh +283 -0
  117. package/skills/teamsmith/tests/flip-m6.4.sh +267 -0
  118. package/skills/teamsmith/tests/flip-m6.5.sh +113 -0
  119. package/skills/teamsmith/tests/flip-m7.1.sh +135 -0
  120. package/skills/teamsmith/tests/flip-m7.2.sh +321 -0
  121. package/skills/teamsmith/tests/flip-p144.sh +112 -0
  122. package/skills/teamsmith/tests/flip-p156.sh +133 -0
  123. package/skills/teamsmith/tests/flip-p158.sh +301 -0
  124. package/skills/teamsmith/tests/flip-p160.sh +182 -0
  125. package/skills/teamsmith/tests/flip-p171.sh +249 -0
  126. package/skills/teamsmith/tests/flip-p18.1.sh +95 -0
  127. package/skills/teamsmith/tests/flip-p20.sh +286 -0
  128. package/skills/teamsmith/tests/flip-p201.sh +249 -0
  129. package/skills/teamsmith/tests/flip-p210.sh +239 -0
  130. package/skills/teamsmith/tests/flip-p211.sh +152 -0
  131. package/skills/teamsmith/tests/flip-p217.sh +288 -0
  132. package/skills/teamsmith/tests/flip-p22.sh +123 -0
  133. package/skills/teamsmith/tests/flip-p23.sh +239 -0
  134. package/skills/teamsmith/tests/flip-p25.sh +165 -0
  135. package/skills/teamsmith/tests/flip-p71.sh +184 -0
  136. package/skills/teamsmith/tests/flip-p72.sh +202 -0
  137. package/skills/teamsmith/tests/frames/README.md +176 -0
  138. package/skills/teamsmith/tests/frames/p78-conversation-rule-below-box.txt +6 -0
  139. package/skills/teamsmith/tests/frames/p78-cursor-mid-draft.txt +6 -0
  140. package/skills/teamsmith/tests/frames/p78-draft-rule-below-cursor-line.txt +6 -0
  141. package/skills/teamsmith/tests/frames/p78-draft-rule-below-cursor.txt +6 -0
  142. package/skills/teamsmith/tests/frames/p78-draft-rule-blank-region.txt +6 -0
  143. package/skills/teamsmith/tests/frames/p78-draft-rule-only.txt +5 -0
  144. package/skills/teamsmith/tests/frames/p78-spinner-row-below-cursor.txt +6 -0
  145. package/skills/teamsmith/tests/frames/p78-wider-rule-below-cursor.txt +6 -0
  146. package/skills/teamsmith/tests/frames/p86-f1-mixed-width-disjoint-box.txt +8 -0
  147. package/skills/teamsmith/tests/frames/p86-f1-narrower-width-disjoint-box.txt +8 -0
  148. package/skills/teamsmith/tests/frames/p86-f1-spinner-top-disjoint-box.txt +8 -0
  149. package/skills/teamsmith/tests/frames/pi-0.85.1-update-banner.txt +30 -0
  150. package/skills/teamsmith/tests/frames/pi-0.87.0-draft-half-sentence.txt +30 -0
  151. package/skills/teamsmith/tests/frames/pi-0.87.0-empty-box.txt +30 -0
  152. package/skills/teamsmith/tests/frames/pi-0.87.0-one-line-draft.txt +30 -0
  153. package/skills/teamsmith/tests/frames/pi-0.87.0-project-trust-prompt.txt +30 -0
  154. package/skills/teamsmith/tests/frames/pi-0.99.2-empty-editor.txt +32 -0
  155. package/skills/teamsmith/tests/frames/pi-0.99.2-human-draft.txt +32 -0
  156. package/skills/teamsmith/tests/frames/pi-1.0.0-git-error-in-box.txt +32 -0
  157. package/skills/teamsmith/tests/gate-guard.sh +112 -0
  158. package/skills/teamsmith/tests/guard-matrix.sh +233 -0
  159. package/skills/teamsmith/tests/install-shape.sh +731 -0
  160. package/skills/teamsmith/tests/ledger-ban.sh +612 -0
  161. package/skills/teamsmith/tests/lib/box-judge.sh +68 -0
  162. package/skills/teamsmith/tests/lib/checkout-shape.sh +129 -0
  163. package/skills/teamsmith/tests/lib/loop-scan.awk +114 -0
  164. package/skills/teamsmith/tests/lib/pty-wait.sh +676 -0
  165. package/skills/teamsmith/tests/lib/section-guard.sh +855 -0
  166. package/skills/teamsmith/tests/lib/shell-lex.pl +261 -0
  167. package/skills/teamsmith/tests/lib/tmp-root.sh +528 -0
  168. package/skills/teamsmith/tests/lib/tmux-cap.sh +35 -0
  169. package/skills/teamsmith/tests/lib/tmux-iso-call-probe.sh +81 -0
  170. package/skills/teamsmith/tests/lib/tmux-iso-probe.sh +46 -0
  171. package/skills/teamsmith/tests/lib/tmux-iso.sh +381 -0
  172. package/skills/teamsmith/tests/load-experiment.sh +290 -0
  173. package/skills/teamsmith/tests/loop-inventory.tsv +84 -0
  174. package/skills/teamsmith/tests/panel-b2-slow-stub.sh +19 -0
  175. package/skills/teamsmith/tests/panel-b2.sh +1183 -0
  176. package/skills/teamsmith/tests/panel-b3-pty-mouse.py +240 -0
  177. package/skills/teamsmith/tests/panel-b3-pty-tmux-mouse.py +138 -0
  178. package/skills/teamsmith/tests/panel-b3-stub.sh +279 -0
  179. package/skills/teamsmith/tests/panel-b3.sh +1301 -0
  180. package/skills/teamsmith/tests/panel-choices.sh +572 -0
  181. package/skills/teamsmith/tests/panel-clipboard-model.ts +187 -0
  182. package/skills/teamsmith/tests/panel-compose-model.ts +290 -0
  183. package/skills/teamsmith/tests/panel-contrast.mjs +81 -0
  184. package/skills/teamsmith/tests/panel-cpu-premise.sh +173 -0
  185. package/skills/teamsmith/tests/panel-cpu.sh +391 -0
  186. package/skills/teamsmith/tests/panel-flip-m54.sh +207 -0
  187. package/skills/teamsmith/tests/panel-flip-p123.sh +278 -0
  188. package/skills/teamsmith/tests/panel-flip-p125.sh +318 -0
  189. package/skills/teamsmith/tests/panel-flip-p128.sh +259 -0
  190. package/skills/teamsmith/tests/panel-keyprobe-pty.py +99 -0
  191. package/skills/teamsmith/tests/panel-keyprobe-stub.sh +41 -0
  192. package/skills/teamsmith/tests/panel-keyprobe.sh +82 -0
  193. package/skills/teamsmith/tests/panel-keyprobe.tsx +116 -0
  194. package/skills/teamsmith/tests/panel-knobs.sh +83 -0
  195. package/skills/teamsmith/tests/panel-p21.sh +2181 -0
  196. package/skills/teamsmith/tests/panel-snapshots.sh +802 -0
  197. package/skills/teamsmith/tests/panel-strings.mjs +195 -0
  198. package/skills/teamsmith/tests/perf.sh +740 -0
  199. package/skills/teamsmith/tests/pm-box-real.sh +350 -0
  200. package/skills/teamsmith/tests/pulse-nudge-key.sh +563 -0
  201. package/skills/teamsmith/tests/routes.sh +1652 -0
  202. package/skills/teamsmith/tests/section-budgets.tsv +150 -0
  203. package/skills/teamsmith/tests/section-guard.sh +231 -0
  204. package/skills/teamsmith/tests/section-needs-audit.sh +94 -0
  205. package/skills/teamsmith/tests/section-paths.tsv +142 -0
  206. package/skills/teamsmith/tests/section-select.sh +655 -0
  207. package/skills/teamsmith/tests/signal-gate.sh +366 -0
  208. package/skills/teamsmith/tests/signal-lint-legacy.txt +14 -0
  209. package/skills/teamsmith/tests/signal-lint.pl +416 -0
  210. package/skills/teamsmith/tests/skill-load.mjs +65 -0
  211. package/skills/teamsmith/tests/smoke.sh +19711 -0
  212. package/skills/teamsmith/tests/snapshots/zh-dark-120-detail.txt +32 -0
  213. package/skills/teamsmith/tests/snapshots/zh-dark-120-p4.txt +32 -0
  214. package/skills/teamsmith/tests/snapshots/zh-dark-120.txt +32 -0
  215. package/skills/teamsmith/tests/snapshots/zh-dark-160-p4.txt +32 -0
  216. package/skills/teamsmith/tests/snapshots/zh-dark-160.txt +32 -0
  217. package/skills/teamsmith/tests/snapshots/zh-dark-59-detail.txt +32 -0
  218. package/skills/teamsmith/tests/snapshots/zh-dark-59-p4.txt +32 -0
  219. package/skills/teamsmith/tests/snapshots/zh-dark-59.txt +32 -0
  220. package/skills/teamsmith/tests/snapshots/zh-dark-99-p4.txt +32 -0
  221. package/skills/teamsmith/tests/snapshots/zh-dark-99.txt +32 -0
  222. package/skills/teamsmith/tests/snapshots/zh-light-120-detail.txt +32 -0
  223. package/skills/teamsmith/tests/snapshots/zh-light-120-p4.txt +32 -0
  224. package/skills/teamsmith/tests/snapshots/zh-light-120.txt +32 -0
  225. package/skills/teamsmith/tests/snapshots/zh-light-160-p4.txt +32 -0
  226. package/skills/teamsmith/tests/snapshots/zh-light-160.txt +32 -0
  227. package/skills/teamsmith/tests/snapshots/zh-light-59-detail.txt +32 -0
  228. package/skills/teamsmith/tests/snapshots/zh-light-59-p4.txt +32 -0
  229. package/skills/teamsmith/tests/snapshots/zh-light-59.txt +32 -0
  230. package/skills/teamsmith/tests/snapshots/zh-light-99-p4.txt +32 -0
  231. package/skills/teamsmith/tests/snapshots/zh-light-99.txt +32 -0
  232. package/skills/teamsmith/tests/spec-ledger-refs.tsv +78 -0
  233. package/skills/teamsmith/tests/spec-refs.sh +826 -0
  234. package/skills/teamsmith/tests/task-header-model.sh +267 -0
  235. package/skills/teamsmith/tests/team-bg-flip.sh +239 -0
  236. package/skills/teamsmith/tests/team-bg-harness.mjs +392 -0
  237. package/skills/teamsmith/tests/team-bg-stop.sh +434 -0
  238. package/skills/teamsmith/tests/team-inbox-watch-flip.sh +191 -0
  239. package/skills/teamsmith/tests/team-inbox-watch-harness.mjs +1559 -0
  240. package/skills/teamsmith/tests/tmp-hygiene.sh +1190 -0
  241. package/skills/teamsmith/tests/tmux-lint-legacy.txt +31 -0
  242. package/skills/teamsmith/tests/tmux-lint.pl +604 -0
  243. package/skills/teamsmith-init/SKILL.md +100 -0
  244. package/skills/teamsmith-init/references/bootstrap.md +74 -0
  245. package/skills/teamsmith-init/templates/bootstrap-prompt.md.tmpl +46 -0
@@ -0,0 +1,2562 @@
1
+ // The frame: four pages (the board page is a kanban over the board's states; the focused card's
2
+ // read-only markdown detail view replaces it while open), a settings overlay, four width tiers —
3
+ // and nothing else.
4
+ //
5
+ // This module is pure (no I/O, no timers, no clock): the same width, height, data and view state
6
+ // produce the same `Frame` byte for byte. The Ink renderer, the plain-text `--print` path and the
7
+ // snapshot suite all consume the same `layout()` result; `renderPlain` and `renderAnsi` only turn
8
+ // the tone-carrying segments into text (with or without SGR).
9
+ //
10
+ // Layout model (design `docs/team/designs/pulse-console.md`, spec "The layout is a pure function of
11
+ // geometry with four width tiers"):
12
+ //
13
+ // ≥160 columns two columns
14
+ // 100–159 columns two compact columns (the right one narrowed, long text truncated)
15
+ // <100 columns one column, blocks stacked
16
+ // <60 columns the minimal form: table columns dropped, times to the clock, states shortened
17
+ //
18
+ // The documented degradation order is: side-by-side blocks become one column → a block folds into
19
+ // one summary line when the height runs out → blocks collapse entirely, and the minimal tier drops
20
+ // table columns / abbreviates states. Blocks whose source has no data collapse and yield the space.
21
+
22
+ import { fmtAge, fmtMB, GLYPH, clockOf, shortBranch, sparkline } from './format.js'
23
+ import { markdownMemo } from './markdown.js'
24
+ import { fill, keyLabel, OVERLAY_LABEL_W } from './strings/index.js'
25
+ import type { Strings } from './strings/index.js'
26
+ import { BOARD_LANES } from './types.js'
27
+ import type {
28
+ Action,
29
+ ActivityBlock,
30
+ BoardRow,
31
+ ChangeRow,
32
+ Density,
33
+ DetailBlock,
34
+ DetailWindow,
35
+ FocusRef,
36
+ Frame,
37
+ FrameInput,
38
+ Hit,
39
+ LaneWindow,
40
+ Line,
41
+ PageId,
42
+ PanelAgent,
43
+ PanelBlocks,
44
+ PanelData,
45
+ PlacedLine,
46
+ PrefName,
47
+ QueueEntry,
48
+ Impediment,
49
+ Segment,
50
+ SettingsBlock,
51
+ SettingsChoiceEntry,
52
+ SettingsKey,
53
+ SettingsSeat,
54
+ SettingsWindow,
55
+ Tone,
56
+ ViewState,
57
+ } from './types.js'
58
+ import { toneSgr, type Palette } from './theme.js'
59
+ import { cell, dispWidth, rule, truncateW, truncateWStart } from './width.js'
60
+
61
+ export const WIDTH_TWO_WIDE = 160
62
+ export const WIDTH_TWO_COMPACT = 100
63
+ export const WIDTH_MINIMAL = 60
64
+
65
+ /** Column ratios per two-column tier (left share of the usable track). */
66
+ const LEFT_SHARE_WIDE = 0.56
67
+ const LEFT_SHARE_COMPACT = 0.64
68
+ const COLUMN_GAP = 3
69
+
70
+ type Part = Segment | string | null | undefined
71
+
72
+ const seg = (text: string, tone: Tone = 'text'): Segment => ({ text: String(text), tone })
73
+
74
+ /** Adjacent segments with the same tone become one: Ink renders one node per segment, and frame
75
+ * reconciliation is a real cost at a 3s cadence (the red line is <1% of one core). */
76
+ function mergeSegments(line: Segment[]): Line {
77
+ const out: Segment[] = []
78
+ for (const s of line) {
79
+ const prev = out[out.length - 1]
80
+ if (prev && prev.tone === s.tone && !prev.clock && !s.clock) prev.text += s.text
81
+ else out.push({ ...s })
82
+ }
83
+ return out
84
+ }
85
+
86
+ const ln = (...parts: Part[]): Line =>
87
+ mergeSegments(
88
+ parts
89
+ .filter((p): p is Segment | string => p !== null && p !== undefined && p !== '')
90
+ .map((p) => (typeof p === 'string' ? seg(p) : p)),
91
+ )
92
+
93
+ const textOf = (line: Line): string => line.map((s) => s.text).join('')
94
+ const widthOf = (line: Line): number => dispWidth(textOf(line))
95
+
96
+ /** Cut a segment line to `width` display columns (never wider, ellipsis when cut). */
97
+ function truncLine(line: Line, width: number): Line {
98
+ if (width <= 0) return []
99
+ if (widthOf(line) <= width) return line
100
+ const room = width - 1
101
+ const out: Line = []
102
+ let used = 0
103
+ for (const s of line) {
104
+ if (used >= room) break
105
+ let text = ''
106
+ for (const ch of s.text) {
107
+ const w = dispWidth(ch)
108
+ if (used + w > room) break
109
+ text += ch
110
+ used += w
111
+ }
112
+ if (text) out.push({ text, tone: s.tone })
113
+ }
114
+ out.push(seg('…', out[out.length - 1]?.tone ?? 'text'))
115
+ return out
116
+ }
117
+
118
+ /** Append spaces so the line occupies exactly `width` columns (used for the left column). */
119
+ function padLine(line: Line, width: number): Line {
120
+ const d = width - widthOf(line)
121
+ return d > 0 ? [...line, seg(' '.repeat(d), 'text')] : line
122
+ }
123
+
124
+ /**
125
+ * Truncate a line and clip its hit spans to the *rendered* coordinates (V15/F4): when the line
126
+ * is cut, the ellipsis owns the last column and every target reaching into it is invisible — a
127
+ * click on the `…` must fire nothing. Targets are therefore generated from the line as rendered,
128
+ * never from the untruncated text.
129
+ */
130
+ function placedWithHits(line: Line, hits: Hit[] | undefined, width: number): PlacedLine {
131
+ const rendered = truncLine(line, width)
132
+ if (!hits?.length) return { line: rendered }
133
+ const cut = widthOf(line) > width
134
+ const room = cut ? Math.max(0, width - 1) : width
135
+ const clipped: Hit[] = []
136
+ for (const h of hits) {
137
+ const start = Math.min(h.start, room)
138
+ const end = Math.min(h.end, room)
139
+ if (end > start) clipped.push({ ...h, start, end })
140
+ }
141
+ return clipped.length ? { line: rendered, hits: clipped } : { line: rendered }
142
+ }
143
+
144
+ function isFramed(ctx: Ctx): boolean {
145
+ return ctx.view.tui && ctx.view.density === 'comfortable'
146
+ }
147
+
148
+ function cardTop(title: string, width: number): Line {
149
+ if (width <= 1) return ln(seg(BOX_TL, 'dim'))
150
+ if (width === 2) return ln(seg(BOX_TL + BOX_TR, 'dim'))
151
+ const inner = width - 2
152
+ if (!title) return ln(seg(BOX_TL + BOX_H.repeat(inner) + BOX_TR, 'dim'))
153
+ // ╭─ title ──…──╮ (title in heading, border dim). Inner = ─ + ' ' + title + ' ' + ─…
154
+ const labelW = dispWidth(title)
155
+ if (1 + 1 + labelW + 1 > inner) {
156
+ const room = Math.max(0, inner - 1)
157
+ return ln(seg(BOX_TL + BOX_H, 'dim'), ...truncLine(ln(seg(title, 'heading')), room), seg(BOX_TR, 'dim'))
158
+ }
159
+ const fill = inner - (1 + 1 + labelW + 1) // ─ space title space ─…
160
+ return ln(
161
+ seg(BOX_TL + BOX_H + ' ', 'dim'),
162
+ seg(title, 'heading'),
163
+ seg(' ' + BOX_H.repeat(Math.max(0, fill)), 'dim'),
164
+ seg(BOX_TR, 'dim'),
165
+ )
166
+ }
167
+
168
+ function cardBottom(width: number): Line {
169
+ if (width <= 1) return ln(seg(BOX_BL, 'dim'))
170
+ if (width === 2) return ln(seg(BOX_BL + BOX_BR, 'dim'))
171
+ return ln(seg(BOX_BL + BOX_H.repeat(width - 2) + BOX_BR, 'dim'))
172
+ }
173
+
174
+ function cardBody(placed: PlacedLine, width: number): PlacedLine {
175
+ const inner = Math.max(0, width - 4) // │␠ content ␠│
176
+ const rendered = truncLine(placed.line, inner)
177
+ const pad = Math.max(0, inner - widthOf(rendered))
178
+ const hits: Hit[] = []
179
+ for (const h of placed.hits ?? []) {
180
+ const start = Math.min(h.start + 2, 2 + inner)
181
+ const end = Math.min(h.end + 2, 2 + inner)
182
+ if (end > start) hits.push({ ...h, start, end })
183
+ }
184
+ const line = ln(seg(`${BOX_V} `, 'dim'), ...rendered, pad > 0 ? seg(' '.repeat(pad), 'text') : null, seg(` ${BOX_V}`, 'dim'))
185
+ return hits.length ? { line, hits } : { line }
186
+ }
187
+
188
+ function ruleTitle(title: string, width: number, tone: Tone = 'heading'): Line {
189
+ if (width <= 0) return []
190
+ if (!title) return ln(seg(rule(width, BOX_H), 'dim'))
191
+ const labelW = dispWidth(title)
192
+ if (labelW + 4 >= width) return truncLine(ln(seg(BOX_H + BOX_H + ' ', 'dim'), seg(title, tone)), width)
193
+ const left = 2
194
+ const right = width - left - 1 - labelW // ── title ─…
195
+ return ln(seg(rule(left, BOX_H) + ' ', 'dim'), seg(title, tone), seg(' ' + rule(Math.max(0, right - 1), BOX_H), 'dim'))
196
+ }
197
+
198
+ function wrapBlock(block: Block, width: number, chrome: Chrome): PlacedLine[] {
199
+ const title = block.title
200
+ if (!title || chrome === 'plain') {
201
+ if (title && chrome === 'plain' && block.id !== 'agents') {
202
+ return [{ line: truncLine(ln(seg(` ${title}`, 'heading')), width) }, ...block.lines]
203
+ }
204
+ return block.lines
205
+ }
206
+ if (chrome === 'rule') {
207
+ return [{ line: ruleTitle(title, width) }, ...block.lines.map((l) => ({ line: truncLine(l.line, width), hits: l.hits }))]
208
+ }
209
+ return [{ line: cardTop(title, width) }, ...block.lines.map((l) => cardBody(l, width)), { line: cardBottom(width) }]
210
+ }
211
+
212
+ function pickChrome(block: Block, remaining: number, framed: boolean): Chrome | 'summary' | null {
213
+ const n = block.lines.length
214
+ if (!framed || !block.title) {
215
+ if (remaining >= n) return 'plain'
216
+ if ((block.summary || block.title) && remaining >= 1) return 'summary'
217
+ return null
218
+ }
219
+ if (remaining >= n + 2) return 'card'
220
+ if (remaining >= n + 1) return 'rule'
221
+ if (remaining >= 1) return 'summary'
222
+ return null
223
+ }
224
+
225
+ function summaryLine(block: Block, width: number): PlacedLine {
226
+ if (block.summary) return { line: truncLine(block.summary.line, width), hits: block.summary.hits }
227
+ return { line: truncLine(ln(seg(` ${block.title ?? ''}`, 'heading')), width) }
228
+ }
229
+
230
+ interface Block {
231
+ id: string
232
+ full?: boolean
233
+ right?: boolean
234
+ priority: number
235
+ lines: PlacedLine[]
236
+ /** Card / rule / title-line chrome; omitted on chrome rows (title band, tabs, keys). */
237
+ title?: string
238
+ /** The one-line degradation used when the height budget is tight. */
239
+ summary?: PlacedLine
240
+ /** A separator is inserted before the block under the comfortable density. */
241
+ separator?: 'rule' | 'blank' | 'none'
242
+ /** The board page's lane windows as rendered (the App clamps its arrows and wheel against them). */
243
+ lanes?: LaneWindow[]
244
+ /** The detail view's document window as rendered (the App clamps its arrows and wheel). */
245
+ detail?: DetailWindow
246
+ /** The project-settings view's row window as rendered (P22/B2). */
247
+ settings?: SettingsWindow
248
+ /** The work page's board rows in the order it drew them (P20/B5: the App's `↑`/`↓` walk this). */
249
+ order?: FocusRef[]
250
+ }
251
+
252
+ const BOX_TL = '╭'
253
+ const BOX_TR = '╮'
254
+ const BOX_BL = '╰'
255
+ const BOX_BR = '╯'
256
+ const BOX_H = '─'
257
+ const BOX_V = '│'
258
+
259
+ type Chrome = 'card' | 'rule' | 'plain'
260
+
261
+ interface Ctx {
262
+ s: Strings
263
+ input: LayoutInput
264
+ width: number
265
+ minimal: boolean
266
+ compact: boolean
267
+ twoColumn: boolean
268
+ leftWidth: number
269
+ rightWidth: number
270
+ deg: Set<string>
271
+ panel: PanelData
272
+ blocks: PanelBlocks
273
+ view: ViewState
274
+ activity: ActivityBlock[]
275
+ /** History rows the board keeps visible before folding (default `BOARD_DONE_KEEP`; a flush
276
+ * column raises it so the spare height shows real history instead of blank card space). */
277
+ boardDoneKeep?: number
278
+ /** Card rows the board page's lanes may show (the assembly hands over its real budget; the
279
+ * default keeps a standalone layout honest). */
280
+ laneRows?: number
281
+ /** Document rows the detail view may show (the assembly's real budget for the open document). */
282
+ detailRows?: number
283
+ /** Card rows / document lines the project-settings view may draw below its card frame (the
284
+ * assembly's real budget: the view spends it on the row window, its tail and blank fill, so the
285
+ * card fills the pane — P32). */
286
+ settingsRows?: number
287
+ }
288
+
289
+ export interface LayoutInput extends FrameInput {
290
+ strings: Strings
291
+ view: ViewState
292
+ }
293
+
294
+ // ------------------------------------------------------------------ small renderers
295
+
296
+ /** One column of the agents table. Header and data share this plan (display-width aligned). */
297
+ interface AgentCol {
298
+ id: 'name' | 'state' | 'task' | 'branch' | 'session'
299
+ header: string
300
+ width: number
301
+ }
302
+
303
+ function stateCellText(a: PanelAgent, s: Strings, minimal: boolean): string {
304
+ if (minimal) {
305
+ const stateText = a.state === 'running' ? s.agentRunning : a.state === 'exited' ? s.agentExited : s.agentAbsent
306
+ return `${GLYPH[a.state] ?? '?'}${[...stateText][0] ?? ''}`
307
+ }
308
+ return agentStateText(a, s)
309
+ }
310
+
311
+ /**
312
+ * Single source for the agents table: header and every data row use this plan.
313
+ * Session column width is the max display width of the header and every `session_text` — the
314
+ * value is never truncated. When the table cannot fit, columns drop in order: branch → task
315
+ * → session last (a time-format column is not part of this table; clocks live on other blocks).
316
+ */
317
+ function agentColumnPlan(width: number, minimal: boolean, agents: PanelAgent[], s: Strings): AgentCol[] {
318
+ const nameW = Math.max(10, dispWidth(s.agentsHeader))
319
+ let stateW = dispWidth(s.tableState)
320
+ for (const a of agents) stateW = Math.max(stateW, dispWidth(stateCellText(a, s, minimal)))
321
+ let sessionW = dispWidth(s.tableSession)
322
+ for (const a of agents) sessionW = Math.max(sessionW, dispWidth(String(a.session_text || s.dash)))
323
+ const taskW = Math.max(7, dispWidth(s.tableTask))
324
+ const name: AgentCol = { id: 'name', header: s.agentsHeader, width: nameW }
325
+ const state: AgentCol = { id: 'state', header: s.tableState, width: stateW }
326
+ const session: AgentCol = { id: 'session', header: s.tableSession, width: sessionW }
327
+ const reserved = nameW + stateW + sessionW
328
+ const rest = width - reserved
329
+ if (minimal || rest < 7) return [name, state, session]
330
+ const task: AgentCol = { id: 'task', header: s.tableTask, width: taskW }
331
+ if (rest >= taskW + 8) {
332
+ return [name, state, task, { id: 'branch', header: s.tableBranch, width: rest - taskW }, session]
333
+ }
334
+ if (rest >= taskW) return [name, state, task, session]
335
+ return [name, state, session]
336
+ }
337
+
338
+ function agentLine(plan: AgentCol[], cells: { text: string; tone: Tone }[]): Line {
339
+ return ln(...plan.map((c, i) => seg(cell(cells[i]?.text ?? '', c.width), cells[i]?.tone ?? 'text')))
340
+ }
341
+
342
+ function agentStateText(a: PanelAgent, s: Strings): string {
343
+ const glyph = GLYPH[a.state] ?? '?'
344
+ const text = a.state === 'running' ? s.agentRunning : a.state === 'exited' ? s.agentExited : s.agentAbsent
345
+ // agent-death-reason: the full state cell carries the classified cause (`▲ 已死 signal=9 · quota`);
346
+ // the minimal layout drops it together with the state text (stateCellText's minimal branch).
347
+ const cause = a.cause ? ` · ${a.cause}` : ''
348
+ return `${glyph} ${text}${cause}`
349
+ }
350
+
351
+ function pmStateText(pm: PanelData['pm'], s: Strings): string {
352
+ switch (pm?.state) {
353
+ case 'running':
354
+ return s.pmRunning
355
+ case 'starting':
356
+ return s.pmStarting
357
+ case 'foreign':
358
+ return s.pmForeign
359
+ case 'unknown':
360
+ return s.pmUnknown
361
+ default:
362
+ return s.pmAbsent
363
+ }
364
+ }
365
+
366
+ // ------------------------------------------------------------------ header / banner blocks
367
+
368
+ function titleBlock(ctx: Ctx): Block {
369
+ const { s, panel } = ctx
370
+ const project = panel.project || s.dash
371
+ const left = `${s.appTitle} · ${project}`
372
+ const standby = !panel.standby
373
+ ? s.standbyDash
374
+ : fill(panel.standby.on ? s.standbyOn : s.standbyOff, { reason: panel.standby.reason || '-' })
375
+ const stamp = panel.timestamp ? clockOf(panel.timestamp) : s.dash
376
+ const right = ` ${fill(s.patrolSeconds, { n: panel.interval || '—' })} · ${standby}`
377
+ const room = ctx.width - dispWidth(left) - 2
378
+ const line =
379
+ room >= dispWidth(`${stamp}${right}`)
380
+ ? ln(seg(left, 'title'), seg(' '), { text: stamp, tone: 'dim', clock: true }, seg(right, 'dim'))
381
+ : ln(seg(`${left} ${stamp}${right}`, 'title'))
382
+ return { id: 'title', full: true, priority: 0, lines: [{ line: truncLine(line, ctx.width) }], separator: 'none' }
383
+ }
384
+
385
+ function statusBlock(ctx: Ctx): Block {
386
+ const { s, panel, deg } = ctx
387
+ const pmText = !panel.pm || deg.has('pm')
388
+ ? `${s.pmLabel} ${s.dash}`
389
+ : `${s.pmLabel} ${panel.pm.state}${panel.pm.detail ? `(${panel.pm.detail})` : ''} · ${pmStateText(panel.pm, s)}`
390
+ const pend = !panel.pending || deg.has('pending') ? `${s.pendingLabel} ${s.dash}` : `${s.pendingLabel} ${panel.pending.text || s.pendingNone}`
391
+ const ob = panel.outbox
392
+ const queue =
393
+ !ob || deg.has('outbox')
394
+ ? `${s.outboxLabel} ${s.dash}`
395
+ : `${s.outboxLabel} ${ob.queued}${ob.held > 0 ? fill(s.outboxHeldSuffix, { n: ob.held }) : ''}${ob.impeded && ob.impeded > 0 ? ` ${fill(s.outboxImpededSuffix, { n: ob.impeded })}` : ''}`
396
+ const lines: PlacedLine[] = [
397
+ { line: truncLine(ln(seg(' '), seg(pmText), seg(' '), seg(pend), seg(' '), seg(queue, 'accent')), ctx.width) },
398
+ ]
399
+ // M46: a degraded delivery lane gets its own line (text token, not colour alone): the PM card
400
+ // itself cannot carry it, and "messages still go through the paste path" is actionable.
401
+ const delivery = !panel.pm || deg.has('pm') ? '' : (panel.pm.delivery_warning || '')
402
+ if (delivery) {
403
+ lines.push({ line: truncLine(ln(seg(' '), seg(fill(s.pmDeliveryWarning, { reason: delivery }), 'warn')), ctx.width) })
404
+ }
405
+ // delivery-truth D2: the machine reasons ride the status band so the plain-text exit (the
406
+ // overview) names the same count/reasons as the TUI's messages page.
407
+ if (ob && !deg.has('outbox') && ob.impeded && ob.impeded > 0) {
408
+ const reasons = Array.from(new Set((ob.impediments ?? []).map((i) => i.reason))).join(' · ') || s.dash
409
+ lines.push({ line: truncLine(ln(seg(' '), seg(fill(s.queueImpededLine, { n: ob.impeded, reasons }), 'warn')), ctx.width) })
410
+ }
411
+ return {
412
+ id: 'status',
413
+ full: true,
414
+ priority: 1,
415
+ lines,
416
+ separator: 'none',
417
+ }
418
+ }
419
+
420
+ function capacityBlock(ctx: Ctx): Block {
421
+ const { s, panel, deg } = ctx
422
+ const c = panel.capacity
423
+ if (!c || deg.has('capacity')) {
424
+ return { id: 'capacity', title: s.capacityLabel, full: true, priority: 2, lines: [{ line: ln(seg(` ${s.dash}`, 'dim')) }] }
425
+ }
426
+ const spark0 = Math.min(18, Math.max(0, ctx.width - 60))
427
+ // P144: one reading per judged filesystem, the `—` fallback for a figure that cannot be read or
428
+ // an inode table the filesystem does not report. The spark keeps its width rule minus what the
429
+ // readings take (the band is one line: RAM, swap, the estimate, the filesystems, the chart).
430
+ const diskSegs = (c.disk ?? []).flatMap((d) => [
431
+ seg(' | ', 'dim'),
432
+ seg(
433
+ fill(s.capacityDisk, {
434
+ path: d.path,
435
+ mb: d.avail_mb == null ? s.dash : fmtMB(d.avail_mb),
436
+ ino: d.free_inodes == null ? s.dash : String(d.free_inodes),
437
+ }),
438
+ ),
439
+ ])
440
+ const diskW = diskSegs.reduce((n, x) => n + dispWidth(x.text), 0)
441
+ const spark = sparkline(c.spark, Math.max(0, spark0 - diskW))
442
+ const line = ln(
443
+ seg(fill(s.capacityRam, { mb: fmtMB(c.ram_avail_mb) })),
444
+ seg(' | ', 'dim'),
445
+ seg(fill(s.capacitySwap, { mb: fmtMB(c.swap_free_mb) })),
446
+ seg(' | ', 'dim'),
447
+ seg(fill(s.capacityAgents, { n: c.agents })),
448
+ ...diskSegs,
449
+ spark ? seg(` ${spark}`, 'accent') : null,
450
+ )
451
+ return { id: 'capacity', title: s.capacityLabel, full: true, priority: 2, lines: [{ line: truncLine(line, ctx.width) }] }
452
+ }
453
+
454
+ function progressBlock(ctx: Ctx): Block {
455
+ const { s, panel, deg, blocks } = ctx
456
+ const board = blocks.board
457
+ const parts: Part[] = []
458
+ if (board && !deg.has('board')) {
459
+ const c = board.counts ?? {}
460
+ const counts = [
461
+ [s.taskTodo, c.todo ?? 0],
462
+ [s.taskWip, c.wip ?? 0],
463
+ [s.taskReview, c.review ?? 0],
464
+ [s.taskBlocked, c.blocked ?? 0],
465
+ [s.taskDone, c.done ?? 0],
466
+ ]
467
+ .map(([label, n]) => fill(s.countPair, { label, n }))
468
+ .join(' · ')
469
+ parts.push(seg(fill(s.progressTasks, { parts: counts })))
470
+ } else {
471
+ parts.push(seg(fill(s.progressTasks, { parts: s.dash }), 'dim'))
472
+ }
473
+ const sep = seg(' | ', 'dim')
474
+ parts.push(sep)
475
+ if (blocks.changes && !deg.has('changes')) parts.push(seg(fill(s.progressChanges, { n: blocks.changes.count })))
476
+ else parts.push(seg(`${s.progressChanges.replace('{n}', s.dash)}`, 'dim'))
477
+ parts.push(sep)
478
+ if (blocks.specs && !deg.has('specs')) {
479
+ parts.push(seg(fill(s.progressSpecs, { specs: blocks.specs.count, reqs: blocks.specs.requirements })))
480
+ } else parts.push(seg(`${s.specsHeading} ${s.dash}`, 'dim'))
481
+ parts.push(sep)
482
+ if (blocks.decisions && !deg.has('decisions')) parts.push(seg(fill(s.progressDecisions, { n: blocks.decisions.count })))
483
+ else parts.push(seg(`${s.progressDecisions.replace('{n}', s.dash)}`, 'dim'))
484
+ return {
485
+ id: 'progress',
486
+ title: s.progressLabel,
487
+ full: true,
488
+ priority: 5,
489
+ lines: [{ line: truncLine(ln(...parts), ctx.width) }],
490
+ summary: { line: truncLine(ln(seg(` ${s.progressLabel}`, 'heading')), ctx.width) },
491
+ }
492
+ }
493
+
494
+ function deliveriesBlock(ctx: Ctx): Block | null {
495
+ const { s, deg, blocks } = ctx
496
+ const board = blocks.board
497
+ if (!board || deg.has('board')) return null
498
+ const rows = board.deliveries ?? []
499
+ if (!rows.length) {
500
+ return { id: 'deliveries', title: s.deliveriesLabel, full: true, priority: 6, lines: [{ line: ln(seg(` ${s.deliveriesEmpty}`, 'dim')) }] }
501
+ }
502
+ const lines: PlacedLine[] = [
503
+ ...rows.slice(0, 3).map((d) => ({
504
+ line: truncLine(
505
+ ln(
506
+ seg(' '),
507
+ seg(fill(s.deliveryLine, { id: d.id, agent: d.agent, time: d.at ? clockOf(d.at) : s.dash })),
508
+ ),
509
+ ctx.width,
510
+ ),
511
+ })),
512
+ ]
513
+ return {
514
+ id: 'deliveries',
515
+ title: s.deliveriesLabel,
516
+ full: true,
517
+ priority: 6,
518
+ lines,
519
+ summary: { line: truncLine(ln(seg(` ${s.deliveriesLabel}`, 'heading')), ctx.width) },
520
+ }
521
+ }
522
+
523
+ // ------------------------------------------------------------------ body blocks (page 1)
524
+
525
+ function agentsBlock(ctx: Ctx): Block | null {
526
+ const { s, panel, deg, width, minimal } = ctx
527
+ const agents = !panel.agents || deg.has('agents') ? [] : (panel.agents ?? [])
528
+ const framed = isFramed(ctx)
529
+ const tableW = framed && width > 8 ? width - 4 : width
530
+ const plan = agentColumnPlan(tableW, minimal, agents, s)
531
+ if (!panel.agents || deg.has('agents')) {
532
+ return {
533
+ id: 'agents',
534
+ title: s.agentsHeader,
535
+ priority: 10,
536
+ lines: [{ line: ln(seg(` ${s.dash}`, 'dim')) }],
537
+ summary: { line: truncLine(ln(seg(` ${s.agentsHeader} ${s.dash}`, 'heading')), width) },
538
+ }
539
+ }
540
+ const header = plan.map((c) => ({ text: c.header, tone: 'heading' as Tone }))
541
+ const lines: PlacedLine[] = [{ line: agentLine(plan, header) }]
542
+ if (!agents.length) lines.push({ line: ln(seg(` ${s.agentEmpty}`, 'dim')) })
543
+ for (const a of agents) {
544
+ const cells = plan.map((c) => {
545
+ switch (c.id) {
546
+ case 'name':
547
+ return { text: String(a.name ?? '?'), tone: 'text' as Tone }
548
+ case 'state':
549
+ return { text: stateCellText(a, s, minimal), tone: stateTone(a.state) }
550
+ case 'task':
551
+ return { text: String(a.task || s.dash), tone: 'text' as Tone }
552
+ case 'branch': {
553
+ const flags = `${a.dirty ? ' *' : ''}${a.ahead ? ` +${a.ahead}` : ''}`
554
+ return { text: `${shortBranch(String(a.branch ?? ''), Math.max(1, c.width - dispWidth(flags)))}${flags}`, tone: 'text' as Tone }
555
+ }
556
+ case 'session':
557
+ return { text: String(a.session_text || s.dash), tone: 'text' as Tone }
558
+ }
559
+ })
560
+ lines.push({ line: agentLine(plan, cells) })
561
+ }
562
+ return {
563
+ id: 'agents',
564
+ title: s.agentsHeader,
565
+ priority: 10,
566
+ lines,
567
+ summary: { line: truncLine(ln(seg(` ${s.agentsHeader} (${agents.length})`, 'heading')), width) },
568
+ }
569
+ }
570
+
571
+ function stateTone(state: string): Tone {
572
+ return state === 'running' ? 'ok' : state === 'exited' ? 'warn' : 'dim'
573
+ }
574
+
575
+ function eventsBlock(ctx: Ctx): Block | null {
576
+ const { s, panel, deg, activity, width, view } = ctx
577
+ if (!ctx.input.activity) return null
578
+ const lines: PlacedLine[] = []
579
+ if (deg.has('activity') || !panel.activity_source) {
580
+ lines.push({ line: ln(seg(` ${s.dash}`, 'dim')) })
581
+ } else {
582
+ const label = `${s.activitySource.replace('{path}', '')}`.trim()
583
+ const path = truncateWStart(panel.activity_source, width - dispWidth(label) - 3)
584
+ lines.push({ line: truncLine(ln(seg(' '), seg(label, 'dim'), seg(' '), seg(path, 'dim')), width) })
585
+ const evs = activityLines(activity).slice(Math.max(0, view.scroll))
586
+ if (!evs.length) lines.push({ line: ln(seg(` ${s.activityEmpty}`, 'dim')) })
587
+ for (const e of evs) lines.push({ line: truncLine(ln(seg(` ${e}`)), width) })
588
+ }
589
+ return { id: 'events', title: s.activityHeading, right: true, priority: 11, lines, summary: { line: truncLine(ln(seg(` ${s.activityHeading}`, 'heading')), width) } }
590
+ }
591
+
592
+ function recentBlock(ctx: Ctx): Block | null {
593
+ const { s, panel, deg, width } = ctx
594
+ const recent = panel.recent ?? []
595
+ if (deg.has('recent') || !panel.recent) {
596
+ return { id: 'recent', title: s.recentHeading, right: true, priority: 12, lines: [{ line: ln(seg(` ${s.dash}`, 'dim')) }] }
597
+ }
598
+ const lines: PlacedLine[] = []
599
+ const tail = recent.slice(-6)
600
+ if (!tail.length) lines.push({ line: ln(seg(` ${s.recentEmpty}`, 'dim')) })
601
+ for (const r of tail) lines.push({ line: truncLine(ln(seg(` ${r}`, 'dim')), width) })
602
+ return { id: 'recent', title: s.recentHeading, right: true, priority: 12, lines, summary: { line: truncLine(ln(seg(` ${s.recentHeading}`, 'heading')), width) } }
603
+ }
604
+
605
+ export function activityLines(activity: ActivityBlock[]): string[] {
606
+ const out: string[] = []
607
+ for (const block of activity ?? []) {
608
+ const name = String(block?.name ?? '?')
609
+ const events = Array.isArray(block?.events) ? block.events : []
610
+ if (!events.length) continue
611
+ for (const ev of events) {
612
+ const ts = ev?.ts ? String(ev.ts) : ''
613
+ const clock = ts && ts.includes('T') ? ts.slice(11, 19) : ts
614
+ const text = String(ev?.text ?? '')
615
+ out.push(` ${name}${clock ? ` ${clock}` : ''} ${text}`.trimEnd())
616
+ }
617
+ }
618
+ return out
619
+ }
620
+
621
+ // ------------------------------------------------------------------ body blocks (page 2)
622
+
623
+ const BOARD_STATE_TONE: Record<string, Tone> = {
624
+ todo: 'dim',
625
+ wip: 'accent',
626
+ review: 'warn',
627
+ blocked: 'err',
628
+ done: 'ok',
629
+ dropped: 'dim',
630
+ }
631
+
632
+ function boardStateText(state: string, s: Strings): string {
633
+ switch (state) {
634
+ case 'done':
635
+ return s.taskDone
636
+ case 'wip':
637
+ return s.taskWip
638
+ case 'review':
639
+ return s.taskReview
640
+ case 'blocked':
641
+ return s.taskBlocked
642
+ case 'todo':
643
+ return s.taskTodo
644
+ case 'dropped':
645
+ return s.taskDropped
646
+ default:
647
+ return state
648
+ }
649
+ }
650
+
651
+ function changePhaseText(phase: string, s: Strings): string {
652
+ switch (phase) {
653
+ case 'explore':
654
+ return s.changePhaseExplore
655
+ case 'propose':
656
+ return s.changePhasePropose
657
+ case 'verify':
658
+ return s.changePhaseVerify
659
+ case 'archive':
660
+ return s.changePhaseArchive
661
+ default:
662
+ return s.changePhaseApply
663
+ }
664
+ }
665
+
666
+ /** History rows the board keeps visible before folding the rest into one counted line. */
667
+ const BOARD_DONE_KEEP = 5
668
+
669
+ /** How many done/dropped rows the board folds away at the current history limit. */
670
+ function boardFoldedRows(ctx: Ctx): number {
671
+ if (ctx.deg.has('board')) return 0
672
+ const rows = ctx.blocks.board?.rows ?? []
673
+ let history = 0
674
+ for (const r of rows) if (r.state === 'done' || r.state === 'dropped') history++
675
+ return Math.max(0, history - Math.max(1, ctx.boardDoneKeep ?? BOARD_DONE_KEEP))
676
+ }
677
+
678
+ function boardBlock(ctx: Ctx): Block | null {
679
+ const { s, blocks, deg, width } = ctx
680
+ const board = blocks.board
681
+ if (!board) return null
682
+ if (deg.has('board')) {
683
+ return { id: 'board', title: s.boardHeading, priority: 10, lines: [{ line: ln(seg(` ${s.dash}`, 'dim')) }] }
684
+ }
685
+ const rows = board.rows ?? []
686
+ if (!rows.length) {
687
+ return { id: 'board', title: s.boardHeading, priority: 10, lines: [{ line: ln(seg(` ${s.boardEmpty}`, 'dim')) }] }
688
+ }
689
+ const counts = board.counts ?? {}
690
+ const lines: PlacedLine[] = [
691
+ {
692
+ line: truncLine(
693
+ ln(
694
+ seg(
695
+ ` ${fill(s.boardCounts, {
696
+ todo: counts.todo ?? 0,
697
+ wip: counts.wip ?? 0,
698
+ review: counts.review ?? 0,
699
+ blocked: counts.blocked ?? 0,
700
+ done: counts.done ?? 0,
701
+ })}`,
702
+ 'dim',
703
+ ),
704
+ ),
705
+ width,
706
+ ),
707
+ },
708
+ ]
709
+ // `done` and `dropped` rows are history: only the newest `keep` render, the rest fold into one
710
+ // counted line (the design's done-collapse, extended to dropped rows so the live board stays
711
+ // small). `boardDoneKeep` lets the assembly raise that limit when the column has spare height.
712
+ const doneRows = rows.filter((r) => r.state === 'done' || r.state === 'dropped')
713
+ const keep = Math.max(1, ctx.boardDoneKeep ?? BOARD_DONE_KEEP)
714
+ const keepDone = new Set(doneRows.slice(-keep).map((r) => r.id))
715
+ const folded = doneRows.filter((r) => !keepDone.has(r.id)).length
716
+ // M34 (the user's call after a live look at the work page): the card reads active work first.
717
+ // Every todo/wip/review/blocked row keeps its BOARD.md order above the history, and the kept
718
+ // done/dropped rows follow in the same file order the kanban page renders its lanes in (the file
719
+ // lists oldest -> newest, so the newest kept row sits directly under the active rows and the
720
+ // folded count — the older ones — stays last). Only the row order changes: the counts row, the
721
+ // keep window and the fold are untouched.
722
+ const rendered = [
723
+ ...rows.filter((r) => r.state !== 'done' && r.state !== 'dropped'),
724
+ ...rows.filter((r) => (r.state === 'done' || r.state === 'dropped') && keepDone.has(r.id)),
725
+ ]
726
+ // The focus the rows are drawn with (P20/B5): the shared row focus when it is among the drawn
727
+ // rows, otherwise the first drawn row — the requirement's "the focused row is always among
728
+ // the rows the block renders". An empty or degraded board has no drawn row, hence no focus.
729
+ // M48: the focus names a **row**, not a bare id — two rows may share one id, and matching by id
730
+ // highlights both at once and freezes the `↑`/`↓` walk on the first of them.
731
+ const ordinals = dupOrdinals(rows)
732
+ const named = focusRow(rows, ctx.view.focus)
733
+ const focusedRow = named && rendered.includes(named) ? named : (rendered[0] ?? null)
734
+ const order = rendered.map((r) => refFor(r, ordinals))
735
+ for (const r of rendered) {
736
+ const focused = r === focusedRow
737
+ const row = ln(
738
+ seg(focused ? `${FOCUS_CURSOR} ` : ' ', focused ? 'selected' : 'dim'),
739
+ seg(`${GLYPH[r.state] ?? '·'} `, BOARD_STATE_TONE[r.state] ?? 'text'),
740
+ seg(cell(r.id, 10), focused ? 'selected' : 'accent'),
741
+ seg(cell(r.agent, 8), 'dim'),
742
+ seg(cell(boardStateText(r.state, s), 8), BOARD_STATE_TONE[r.state] ?? 'text'),
743
+ seg(r.title),
744
+ )
745
+ const action: Action = focused ? { kind: 'open-focused', lane: r.state } : { kind: 'focus', lane: r.state, id: r.id, nth: ordinals.get(r) ?? 0 }
746
+ lines.push(placedWithHits(row, ctx.view.tui ? [{ start: 0, end: widthOf(row), action }] : undefined, width))
747
+ }
748
+ if (folded > 0) lines.push({ line: truncLine(ln(seg(` ${fill(s.boardDoneCollapsed, { n: folded })}`, 'dim')), width) })
749
+ return {
750
+ id: 'board',
751
+ title: fill(s.boardHeadingCount, { n: board.total ?? rows.length }),
752
+ priority: 10,
753
+ lines,
754
+ order,
755
+ summary: { line: truncLine(ln(seg(` ${fill(s.boardHeadingCount, { n: board.total ?? rows.length })}`, 'heading')), width) },
756
+ }
757
+ }
758
+
759
+ // ------------------------------------------------------------------ the board page (kanban, P18/B2)
760
+
761
+ /** The six lanes, in the order BOARD.md's own header legend declares — the file is the contract. */
762
+ const LANES: readonly string[] = BOARD_LANES
763
+ /** The state glyph a card carries; the state's name lives in the lane header. */
764
+ const LANE_GLYPH: Record<string, string> = { todo: '·', wip: '▸', review: '◆', done: '✓', blocked: '✗', dropped: '—' }
765
+ /** Columns between two lanes side by side. */
766
+ const LANE_GAP = 1
767
+ /** Card rows a lane shows when nobody handed the block a height budget (standalone layout). */
768
+ const LANE_KEEP_DEFAULT = 4
769
+ /** Card slots a lane reserves for its two edge counters (an edge that hides cards shows their count). */
770
+ const LANE_MARKER_SLOTS = 2
771
+ /** Rows a lane column spends outside its card slots: the header border and the bottom border. */
772
+ const LANE_CHROME_ROWS = 2
773
+ /** The cursor in front of the focused card: a glyph, never color alone. */
774
+ const FOCUS_CURSOR = '›'
775
+ /** The folded lane's marker; an unfolded lane's header carries the mirror marker (P123). */
776
+ const FOLD_MARKER = '▸'
777
+ const UNFOLD_MARKER = '▾'
778
+ /** P125: the side-by-side folded lane's three-column frame (border, ellipsis column, border). */
779
+ const FOLD_FRAME_W = 3
780
+ /** P125: the frame's middle-column glyphs — the horizontal ellipsis, its vertical twin. */
781
+ const FOLD_ELLIPSIS = '…'
782
+ const FOLD_VERT_ELLIPSIS = '⋮'
783
+ /** The grouped form's pseudo-lane key for the single page window (`< 100` columns). */
784
+ const GROUPED_WINDOW = '\u0000page'
785
+
786
+ /** The history lanes anchor their window on the newest cards. */
787
+ function laneAnchorsNewest(lane: string): boolean {
788
+ return lane === 'done' || lane === 'dropped'
789
+ }
790
+
791
+ function laneLabel(lane: string, s: Strings): string {
792
+ return boardStateText(lane, s)
793
+ }
794
+
795
+ /** The cards of one lane, in BOARD.md order (the file lists oldest → newest). */
796
+ function laneCards(rows: BoardRow[], lane: string): BoardRow[] {
797
+ return rows.filter((r) => r.state === lane)
798
+ }
799
+
800
+ /**
801
+ * The board page's effective fold state for one lane (P123). An explicit fold wins over an explicit
802
+ * show (the explicit hide is the stronger statement); a lane nobody named folds only while it is
803
+ * empty and the empty default is on. The default is recomputed per frame, so an empty lane unfolds
804
+ * by itself as soon as it holds a card, while an explicit state survives emptiness and restarts.
805
+ */
806
+ function laneFolded(view: ViewState, lane: string, empty: boolean): boolean {
807
+ if ((view.boardFold ?? []).includes(lane)) return true
808
+ if ((view.boardShow ?? []).includes(lane)) return false
809
+ return empty && (view.boardEmptyFold ?? true)
810
+ }
811
+
812
+ /** The folded lane's marker + label + count; the folded token is the line's dim tail. */
813
+ function foldedLaneHead(s: Strings, lane: string, count: number): string {
814
+ return `${FOLD_MARKER} ${laneLabel(lane, s)} ${count}`
815
+ }
816
+
817
+ /**
818
+ * A folded lane renders as exactly this one line: the marker, the label, the count and the folded
819
+ * token, truncated to the width it was given. When the focused card lives in the lane the line
820
+ * carries the cursor glyph and the selected tone. The line owns the lane's click/wheel region
821
+ * (clicking it toggles the fold; the wheel stays this lane's and never reaches the page behind it).
822
+ *
823
+ * P125: this is the grouped tier's form, where folding saves rows. In the side-by-side tier the
824
+ * folded lane takes the three-column frame instead (`foldedLaneFrame`), so the columns the frame
825
+ * does not use go to the unfolded lanes.
826
+ *
827
+ * P128: the in-place line sits in the column its own card lines use — the grouped card rows are
828
+ * `' '` + cursor + glyph, so the folded line takes the same leading indent and the focus cursor's
829
+ * column, its fold marker landing in the cards' state-glyph column. The lane header keeps its own
830
+ * marker column, which is why the old line looked grouped with the header instead of the cards.
831
+ */
832
+ function foldedLaneLine(ctx: Ctx, lane: string, count: number, width: number, focused: boolean): PlacedLine {
833
+ const { s } = ctx
834
+ const line = ln(
835
+ seg(' '),
836
+ seg(focused ? `${FOCUS_CURSOR} ` : ' ', focused ? 'selected' : 'dim'),
837
+ seg(foldedLaneHead(s, lane, count), focused ? 'selected' : 'heading'),
838
+ seg(s.laneFolded, 'dim'),
839
+ )
840
+ const hits: Hit[] | undefined = ctx.view.tui ? [{ start: 0, end: Math.max(1, width), action: { kind: 'lane-fold', lane } }] : undefined
841
+ return { line: truncLine(line, width), hits }
842
+ }
843
+
844
+ /**
845
+ * P125: a folded lane in the side-by-side tier is a three-column frame that keeps the lane's
846
+ * position in the fixed lane order — a rounded corner at each of its four corners (the panel's own
847
+ * glyphs), a vertical border on each side and the ellipsis in the middle column, drawn down the
848
+ * lane's height (the vertical ellipsis marks the middle row). The frame alone says which lane it is
849
+ * because the order never moves. When the focused card lives in the lane its first body row carries
850
+ * the focus cursor and the selected tone — exactly one cursor in the frame. Every row owns the
851
+ * lane's click/wheel region: a click toggles the fold and the wheel stays this lane's, never the
852
+ * page behind it.
853
+ */
854
+ function foldedLaneFrame(ctx: Ctx, lane: string, focused: boolean, height: number): PlacedLine[] {
855
+ const body = Math.max(1, Math.floor(height) - 2)
856
+ const mid = Math.floor((body - 1) / 2)
857
+ const hit = (): Hit[] | undefined =>
858
+ ctx.view.tui ? [{ start: 0, end: FOLD_FRAME_W, action: { kind: 'lane-fold', lane } }] : undefined
859
+ const out: PlacedLine[] = [{ line: ln(seg(BOX_TL + BOX_H + BOX_TR, 'dim')), hits: hit() }]
860
+ for (let i = 0; i < body; i++) {
861
+ const cursor = focused && i === 0
862
+ const glyph = cursor ? FOCUS_CURSOR : i === mid ? FOLD_VERT_ELLIPSIS : FOLD_ELLIPSIS
863
+ out.push({ line: ln(seg(BOX_V, 'dim'), seg(glyph, cursor ? 'selected' : 'dim'), seg(BOX_V, 'dim')), hits: hit() })
864
+ }
865
+ out.push({ line: ln(seg(BOX_BL + BOX_H + BOX_BR, 'dim')), hits: hit() })
866
+ return out
867
+ }
868
+
869
+ /**
870
+ * Every row's duplicate ordinal: which occurrence of its id it is (0-based, in BOARD.md order).
871
+ * One pass over the rows, so no view pays a full scan per card for the M48 row identity.
872
+ */
873
+ function dupOrdinals(rows: BoardRow[]): Map<BoardRow, number> {
874
+ const seen = new Map<string, number>()
875
+ const out = new Map<BoardRow, number>()
876
+ for (const r of rows) {
877
+ const nth = seen.get(r.id) ?? 0
878
+ out.set(r, nth)
879
+ seen.set(r.id, nth + 1)
880
+ }
881
+ return out
882
+ }
883
+
884
+ /** The focus reference naming one row, given the board's duplicate ordinals. */
885
+ function refFor(row: BoardRow, ordinals: Map<BoardRow, number>): FocusRef {
886
+ return { lane: row.state, id: row.id, nth: ordinals.get(row) ?? 0 }
887
+ }
888
+
889
+ /**
890
+ * The exact row a focus names (M48): the `nth` occurrence of its id in BOARD.md order. A focus
891
+ * without `nth` names the first occurrence, so an older focus or a hand-made fixture still
892
+ * resolves; an id whose duplicates shrank falls through to null and the caller applies the
893
+ * existing fallback.
894
+ */
895
+ export function focusRow(rows: BoardRow[], focus?: { id: string; nth?: number } | null): BoardRow | null {
896
+ if (!focus) return null
897
+ const want = Math.max(0, focus.nth ?? 0)
898
+ let nth = 0
899
+ for (const r of rows) {
900
+ if (r.id !== focus.id) continue
901
+ if (nth === want) return r
902
+ nth++
903
+ }
904
+ return null
905
+ }
906
+
907
+ /** The focus reference for one row (the App sets the focus from a click or a `←`/`→` step). */
908
+ export function focusRefOf(rows: BoardRow[], row: BoardRow): FocusRef {
909
+ return refFor(row, dupOrdinals(rows))
910
+ }
911
+
912
+ /**
913
+ * The focused card resolved against the current board. An id that left the board lands on its lane's
914
+ * first card (and a lane that emptied, on the first card of the first non-empty lane); a null focus
915
+ * starts there too. Pure and shared with the App, which owns the focus state — the layout only
916
+ * renders and windows it.
917
+ */
918
+ export function resolveFocus(
919
+ rows: BoardRow[],
920
+ focus?: FocusRef | null,
921
+ ): FocusRef | null {
922
+ return resolveFocusWith(rows, dupOrdinals(rows), focus)
923
+ }
924
+
925
+ /** `resolveFocus` with the board's ordinals already built (the frame path builds them once per frame). */
926
+ function resolveFocusWith(
927
+ rows: BoardRow[],
928
+ ordinals: Map<BoardRow, number>,
929
+ focus?: FocusRef | null,
930
+ ): FocusRef | null {
931
+ if (focus) {
932
+ const named = focusRow(rows, focus)
933
+ if (named) return refFor(named, ordinals)
934
+ // The named duplicate left the board: the id's first row keeps the focus (a reordered board
935
+ // must not lose the entry).
936
+ const first = rows.find((r) => r.id === focus.id)
937
+ if (first) return refFor(first, ordinals)
938
+ const sameLane = laneCards(rows, focus.lane)[0]
939
+ if (sameLane) return refFor(sameLane, ordinals)
940
+ }
941
+ for (const lane of LANES) {
942
+ const card = laneCards(rows, lane)[0]
943
+ if (card) return refFor(card, ordinals)
944
+ }
945
+ return null
946
+ }
947
+
948
+ /**
949
+ * One lane's visible window. `size` is the number of card rows the frame can spend, the offset is
950
+ * clamped to the lane, and the focused card (when it lives in this lane) always stays inside — the
951
+ * window follows the focus, while the wheel's own offset may scroll away from it.
952
+ */
953
+ function laneWindow(
954
+ ctx: Ctx,
955
+ lane: string,
956
+ cards: BoardRow[],
957
+ size: number,
958
+ target: BoardRow | null,
959
+ offsetKey = lane,
960
+ ): { start: number; end: number; above: number; below: number } {
961
+ const span = Math.max(1, Math.floor(size))
962
+ const count = cards.length
963
+ const maxStart = Math.max(0, count - span)
964
+ const explicit = ctx.view.laneOffset?.[offsetKey]
965
+ let start = explicit == null || Number.isNaN(explicit) ? (laneAnchorsNewest(lane) ? maxStart : 0) : explicit
966
+ start = Math.max(0, Math.min(maxStart, Math.floor(start)))
967
+ // The window follows the focus only while the lane has no offset of its own: once the wheel (or a
968
+ // card move) set one, that offset wins — otherwise the wheel could never scroll away from the
969
+ // focus, which is exactly what the mouse requirement asks it to do.
970
+ if (explicit == null && target && target.state === lane) {
971
+ const idx = cards.indexOf(target)
972
+ if (idx >= 0) {
973
+ if (idx < start) start = idx
974
+ else if (idx >= start + span) start = Math.min(maxStart, idx - span + 1)
975
+ }
976
+ }
977
+ return { start, end: Math.min(count, start + span), above: start, below: Math.max(0, count - (start + span)) }
978
+ }
979
+
980
+ /**
981
+ * One card's line: cursor, state glyph, id, title — truncated to the lane's width. P123: the agent
982
+ * and the phase never render here; the focused card's pair rides the key band instead, so the title
983
+ * is the line's last truncation and no width exists at which a card drops its title to keep them.
984
+ */
985
+ function cardLine(ctx: Ctx, card: BoardRow, width: number, focused: boolean): Line {
986
+ const { minimal } = ctx
987
+ const glyph = LANE_GLYPH[card.state] ?? '·'
988
+ const tone = BOARD_STATE_TONE[card.state] ?? 'text'
989
+ const cursorTone: Tone = focused ? 'selected' : 'dim'
990
+ const idTone: Tone = focused ? 'selected' : 'accent'
991
+ const cursor = focused ? `${FOCUS_CURSOR} ` : ' '
992
+ if (minimal) {
993
+ // Under 60 columns a card is one line: glyph, id, title (the demoted pair drops first).
994
+ return truncLine(ln(seg(cursor, cursorTone), seg(`${glyph} `, tone), seg(`${cell(card.id, 6)} `, idTone), seg(card.title)), width)
995
+ }
996
+ return truncLine(ln(seg(cursor, cursorTone), seg(`${glyph} `, tone), seg(`${card.id} `, idTone), seg(card.title)), width)
997
+ }
998
+
999
+ /**
1000
+ * The click target of a card: the focused card opens, any other card takes the focus. While the
1001
+ * detail view is open the cards keep **no** targets (the replaced-blocks rule the settings overlay
1002
+ * follows too) — the view renders on top of this page in the detail batch.
1003
+ */
1004
+ function cardAction(card: BoardRow, focused: boolean, nth: number): Action {
1005
+ return focused ? { kind: 'open-focused', lane: card.state } : { kind: 'focus', lane: card.state, id: card.id, nth }
1006
+ }
1007
+
1008
+ /** The wheel's lane target: any spot inside a lane that is not a card resolves to this lane. */
1009
+ function laneHover(lane: string): Action {
1010
+ return { kind: 'lane-scroll', lane, delta: 0 }
1011
+ }
1012
+
1013
+ /** One lane as a column of cards; `slots` card rows plus the two borders keep the lanes aligned. */
1014
+ function laneColumn(
1015
+ ctx: Ctx,
1016
+ lane: string,
1017
+ width: number,
1018
+ slots: number,
1019
+ target: BoardRow | null,
1020
+ ordinals: Map<BoardRow, number>,
1021
+ windows: LaneWindow[],
1022
+ folded: boolean,
1023
+ ): PlacedLine[] {
1024
+ const { s } = ctx
1025
+ const cards = laneCards(ctx.blocks.board?.rows ?? [], lane)
1026
+ if (folded) {
1027
+ // P123: the fold branch returns before the window loop, so not one card line (nor an edge
1028
+ // counter, nor the empty marker) is built — the bounded-frame promise can only get cheaper.
1029
+ // The window record reports nothing to scroll; the frame keeps the lane body's height so the
1030
+ // board keeps its shape when every lane folds.
1031
+ // P125: in the side-by-side tier the folded lane is the three-column frame — the columns it
1032
+ // does not use are handed to the unfolded lanes by the width algorithm in `kanbanBlock`.
1033
+ windows.push({ lane, offset: 0, visible: 0, count: 0 })
1034
+ const focused = target != null && target.state === lane
1035
+ return foldedLaneFrame(ctx, lane, focused, slots + 2)
1036
+ }
1037
+ const win = laneWindow(ctx, lane, cards, slots - LANE_MARKER_SLOTS, target)
1038
+ windows.push({ lane, offset: win.start, visible: win.end - win.start, count: cards.length })
1039
+ // Everything in the lane that is not a card resolves to the lane itself, so the wheel scrolls the
1040
+ // lane under the cursor (the card hits win the lookup where a card is — `.find()` takes the first).
1041
+ const hover: Hit[] | undefined = ctx.view.tui ? [{ start: 0, end: width, action: laneHover(lane) }] : undefined
1042
+ // P123: the lane's header line (this top border) is the `c` key's click target; the wheel over it
1043
+ // is this lane's too (the App's wheel branch accepts the same action).
1044
+ const headerHit: Hit[] | undefined = ctx.view.tui ? [{ start: 0, end: width, action: { kind: 'lane-fold', lane } }] : undefined
1045
+ const out: PlacedLine[] = [{ line: cardTop(`${UNFOLD_MARKER} ${laneLabel(lane, s)} ${cards.length}`, width), hits: headerHit }]
1046
+ if (win.above > 0) out.push(cardBody({ line: ln(seg(` ${fill(s.laneHiddenAbove, { n: win.above })}`, 'dim')) }, width))
1047
+ if (!cards.length) out.push(cardBody({ line: ln(seg(` ${s.kanbanEmptyLane}`, 'dim')) }, width))
1048
+ for (let i = win.start; i < win.end; i++) {
1049
+ const card = cards[i]
1050
+ const focused = card === target
1051
+ const line = cardLine(ctx, card, Math.max(0, width - 4), focused)
1052
+ const hits: Hit[] | undefined =
1053
+ ctx.view.tui && !ctx.view.detail
1054
+ ? [{ start: 0, end: Math.max(1, Math.min(width - 4, widthOf(line))), action: cardAction(card, focused, ordinals.get(card) ?? 0) }]
1055
+ : undefined
1056
+ out.push(cardBody({ line, hits }, width))
1057
+ }
1058
+ if (win.below > 0) out.push(cardBody({ line: ln(seg(` ${fill(s.laneHiddenBelow, { n: win.below })}`, 'dim')) }, width))
1059
+ while (out.length < slots + 1) out.push(cardBody({ line: [] }, width))
1060
+ out.push({ line: cardBottom(width) })
1061
+ const placed = out.slice(0, slots + 2)
1062
+ if (hover) for (const l of placed) if (!l.hits?.length) l.hits = hover
1063
+ return placed
1064
+ }
1065
+
1066
+ /** Merge equally-sized lane columns into rows, carrying each column's hits at its own offset. */
1067
+ function mergeLaneColumns(cols: PlacedLine[][], widths: number[]): PlacedLine[] {
1068
+ const rows: PlacedLine[] = []
1069
+ const height = cols.reduce((n, col) => Math.max(n, col.length), 0)
1070
+ for (let i = 0; i < height; i++) {
1071
+ const line: Line = []
1072
+ const hits: Hit[] = []
1073
+ let x = 0
1074
+ cols.forEach((col, ci) => {
1075
+ const cellW = widths[ci]
1076
+ if (ci > 0) {
1077
+ line.push(seg(' '.repeat(LANE_GAP)))
1078
+ x += LANE_GAP
1079
+ }
1080
+ const placed = col[i]
1081
+ if (placed) {
1082
+ line.push(...padLine(placed.line, cellW))
1083
+ for (const h of placed.hits ?? []) hits.push({ ...h, start: h.start + x, end: h.end + x })
1084
+ } else {
1085
+ line.push(seg(' '.repeat(cellW)))
1086
+ }
1087
+ x += cellW
1088
+ })
1089
+ rows.push(hits.length ? { line, hits } : { line })
1090
+ }
1091
+ return rows
1092
+ }
1093
+
1094
+ /** Under 100 columns the page is one column grouped by state, one window for the whole page. */
1095
+ function kanbanGrouped(
1096
+ ctx: Ctx,
1097
+ rows: BoardRow[],
1098
+ target: BoardRow | null,
1099
+ ordinals: Map<BoardRow, number>,
1100
+ ): { lines: PlacedLine[]; lanes: LaneWindow[] } {
1101
+ const { s } = ctx
1102
+ const width = ctx.width
1103
+ const all: PlacedLine[] = []
1104
+ const focusLine = { i: -1 }
1105
+ for (const lane of LANES) {
1106
+ const cards = laneCards(rows, lane)
1107
+ if (laneFolded(ctx.view, lane, !cards.length)) {
1108
+ // P123: a folded lane is its one line here too — no cards, no empty marker, no card rows.
1109
+ const focused = target != null && target.state === lane
1110
+ if (focused) focusLine.i = all.length
1111
+ all.push(foldedLaneLine(ctx, lane, cards.length, width, focused))
1112
+ continue
1113
+ }
1114
+ const head: Hit[] | undefined = ctx.view.tui
1115
+ ? [{ start: 0, end: width, action: { kind: 'lane-fold', lane, scroll: GROUPED_WINDOW } }]
1116
+ : undefined
1117
+ all.push({ line: truncLine(ln(seg(` ${UNFOLD_MARKER} ${laneLabel(lane, s)} ${cards.length}`, 'heading')), width), hits: head })
1118
+ if (!cards.length) all.push({ line: truncLine(ln(seg(` ${s.kanbanEmptyLane}`, 'dim')), width) })
1119
+ for (const card of cards) {
1120
+ const focused = card === target
1121
+ if (focused) focusLine.i = all.length
1122
+ const line = cardLine(ctx, card, Math.max(0, width - 2), focused)
1123
+ const hits: Hit[] | undefined =
1124
+ ctx.view.tui && !ctx.view.detail
1125
+ ? [{ start: 1, end: 1 + Math.max(1, widthOf(line)), action: cardAction(card, focused, ordinals.get(card) ?? 0) }]
1126
+ : undefined
1127
+ all.push({ line: truncLine(ln(seg(' '), ...line.slice(0)), width), hits })
1128
+ }
1129
+ }
1130
+ const span = Math.max(1, (ctx.laneRows ?? LANE_KEEP_DEFAULT) + LANE_MARKER_SLOTS)
1131
+ const maxStart = Math.max(0, all.length - span)
1132
+ let start = ctx.view.laneOffset?.[GROUPED_WINDOW] ?? 0
1133
+ start = Math.max(0, Math.min(maxStart, Math.floor(start) || 0))
1134
+ if (focusLine.i >= 0) {
1135
+ if (focusLine.i < start) start = focusLine.i
1136
+ else if (focusLine.i >= start + span) start = Math.min(maxStart, focusLine.i - span + 1)
1137
+ }
1138
+ const hover: Hit[] | undefined = ctx.view.tui ? [{ start: 0, end: width, action: laneHover(GROUPED_WINDOW) }] : undefined
1139
+ const win: PlacedLine[] = []
1140
+ if (start > 0) win.push({ line: truncLine(ln(seg(` ${fill(s.laneHiddenAbove, { n: start })}`, 'dim')), width) })
1141
+ for (let i = start; i < Math.min(all.length, start + span); i++) win.push(all[i])
1142
+ const below = Math.max(0, all.length - (start + span))
1143
+ if (below > 0) win.push({ line: truncLine(ln(seg(` ${fill(s.laneHiddenBelow, { n: below })}`, 'dim')), width) })
1144
+ if (hover) for (const l of win) if (!l.hits?.length) l.hits = hover
1145
+ return {
1146
+ lines: win,
1147
+ lanes: [{ lane: GROUPED_WINDOW, offset: start, visible: Math.min(span, Math.max(0, all.length - start)), count: all.length }],
1148
+ }
1149
+ }
1150
+
1151
+ /** The board page: six lanes side by side (>= 100 columns) or one grouped column under it. */
1152
+ function kanbanBlock(ctx: Ctx): Block | null {
1153
+ const { s, blocks, deg } = ctx
1154
+ const board = blocks.board
1155
+ if (!board) return null
1156
+ const one = (lines: PlacedLine[]): Block => ({
1157
+ id: 'kanban',
1158
+ full: true,
1159
+ priority: 1,
1160
+ separator: 'none',
1161
+ lines,
1162
+ summary: { line: truncLine(ln(seg(` ${s.boardHeadingCount}`.replace('{n}', String(board.total ?? 0)), 'heading')), ctx.width) },
1163
+ })
1164
+ if (deg.has('board')) return one([{ line: truncLine(ln(seg(` ${s.dash}`, 'dim')), ctx.width) }])
1165
+ const rows = board.rows ?? []
1166
+ if (!rows.length) return one([{ line: truncLine(ln(seg(` ${s.boardEmpty}`, 'dim')), ctx.width) }])
1167
+ const ordinals = dupOrdinals(rows)
1168
+ const focus = resolveFocusWith(rows, ordinals, ctx.view.focus)
1169
+ // M48: one row object is the focus; every `card === target` below is O(1) and two rows sharing an
1170
+ // id never both light up. The duplicate ordinals are built once per frame and shared by the
1171
+ // focus/actions (no per-lane or per-card rescan of the board).
1172
+ const target = focusRow(rows, focus)
1173
+ if (!ctx.twoColumn) {
1174
+ const grouped = kanbanGrouped(ctx, rows, target, ordinals)
1175
+ return { ...one(grouped.lines), lanes: grouped.lanes }
1176
+ }
1177
+ const slots = Math.max(2, Math.floor(ctx.laneRows ?? LANE_KEEP_DEFAULT) + LANE_MARKER_SLOTS)
1178
+ const windows: LaneWindow[] = []
1179
+ // P125: folding changes the width share, not the lane order. In the side-by-side tier a folded
1180
+ // lane is the three-column frame (`foldedLaneFrame`), so it takes exactly `FOLD_FRAME_W` columns
1181
+ // and the whole rest goes to the unfolded lanes, each never under the documented lane floor —
1182
+ // folding gives columns back and the lane row never renders wider than the usable width. The
1183
+ // verdict is computed from the width itself (the layout's own two-column tier), never a
1184
+ // hardcoded threshold here.
1185
+ const usable = Math.max(0, ctx.width - LANE_GAP * (LANES.length - 1))
1186
+ const foldOf = (lane: string): boolean => laneFolded(ctx.view, lane, !laneCards(rows, lane).length)
1187
+ const foldedLanes = LANES.filter(foldOf)
1188
+ const shownLanes = LANES.filter((lane) => !foldOf(lane))
1189
+ const widths = new Map<string, number>()
1190
+ if (!foldedLanes.length) {
1191
+ // Nobody folded: the historical even share, so an all-unfolded board keeps its exact geometry.
1192
+ const laneW = Math.max(8, Math.floor(usable / LANES.length))
1193
+ for (const lane of LANES) widths.set(lane, laneW)
1194
+ } else if (!shownLanes.length) {
1195
+ // Everybody folded: the row is six three-column frames (the free width has no lane to take).
1196
+ for (const lane of foldedLanes) widths.set(lane, FOLD_FRAME_W)
1197
+ } else {
1198
+ for (const lane of foldedLanes) widths.set(lane, FOLD_FRAME_W)
1199
+ const eachShown = Math.max(8, Math.floor((usable - FOLD_FRAME_W * foldedLanes.length) / shownLanes.length))
1200
+ for (const lane of shownLanes) widths.set(lane, eachShown)
1201
+ }
1202
+ const cols = LANES.map((lane) => laneColumn(ctx, lane, widths.get(lane) ?? 8, slots, target, ordinals, windows, foldedLanes.includes(lane)))
1203
+ return { ...one(mergeLaneColumns(cols, LANES.map((lane) => widths.get(lane) ?? 8))), lanes: windows }
1204
+ }
1205
+
1206
+ // ------------------------------------------------------------------ the detail view (markdown, P18/B3)
1207
+
1208
+ /** Document rows a standalone detail layout shows (no assembly budget available). */
1209
+ const DETAIL_KEEP_DEFAULT = 16
1210
+
1211
+ /**
1212
+ * The detail view's content width: inside a card the chrome eats four columns (`│ ` + ` │`), so the
1213
+ * document is wrapped to what the frame will really show at that density.
1214
+ */
1215
+ function blockInnerW(ctx: Ctx): number {
1216
+ return Math.max(1, isFramed(ctx) ? ctx.width - 4 : ctx.width)
1217
+ }
1218
+
1219
+ /** The file tab row of the detail view: the active tab in the accent tone, every tab clickable. */
1220
+ function detailTabs(ctx: Ctx, files: DetailBlock['files'], active: number, width: number): PlacedLine {
1221
+ const line: Line = [seg(' ')]
1222
+ const hits: Hit[] = []
1223
+ let x = 1
1224
+ files.forEach((file, i) => {
1225
+ if (i > 0) {
1226
+ line.push(seg(' '))
1227
+ x += 2
1228
+ }
1229
+ const text = i === active ? `[${file.tab}]` : file.tab
1230
+ const start = x
1231
+ line.push(seg(text, i === active ? 'accent' : 'dim'))
1232
+ x += dispWidth(text)
1233
+ if (ctx.view.tui) hits.push({ start, end: x, action: { kind: 'detail-tab', index: i } })
1234
+ })
1235
+ return placedWithHits(line, hits, width)
1236
+ }
1237
+
1238
+ /**
1239
+ * The detail view: the entry's associated files as tabs plus the open document, read-only. It
1240
+ * replaces the kanban on page 4 exactly the way the settings overlay replaces a page's blocks —
1241
+ * the title band, the page tabs and the key band stay (V16 F-V16-4's replacement rule). The
1242
+ * document rows are windowed against the height the assembly hands over (the bounded-frame rule:
1243
+ * more pane means more document, never more blank).
1244
+ */
1245
+ function detailBlock(ctx: Ctx): Block | null {
1246
+ const { s, blocks, deg } = ctx
1247
+ const id = ctx.view.detail ?? ''
1248
+ const width = blockInnerW(ctx)
1249
+ const title = fill(s.detailTitle, { id })
1250
+ const one = (lines: PlacedLine[], detail?: DetailWindow): Block => ({
1251
+ id: 'detail',
1252
+ full: true,
1253
+ priority: 1,
1254
+ separator: 'none',
1255
+ title,
1256
+ lines,
1257
+ detail,
1258
+ summary: { line: truncLine(ln(seg(` ${title}`, 'heading')), ctx.width) },
1259
+ })
1260
+ if (deg.has('detail')) return one([{ line: truncLine(ln(seg(` ${s.dash}`, 'dim')), width) }])
1261
+ const data = blocks.detail
1262
+ if (!data) {
1263
+ // The block has not arrived yet (the open was just requested): say so instead of claiming the
1264
+ // entry has no files.
1265
+ return one([{ line: truncLine(ln(seg(` ${s.detailLoading}`, 'dim')), width) }], { index: 0, total: 0, visible: 0, offset: 0 })
1266
+ }
1267
+ const files = data.files ?? []
1268
+ if (!files.length) return one([{ line: truncLine(ln(seg(` ${s.detailNoFiles}`, 'dim')), width) }])
1269
+ const detail = data as DetailBlock
1270
+ const index = Math.max(0, Math.min(files.length - 1, Math.floor(ctx.view.detailIndex ?? 0) || 0))
1271
+ const active = files[index]
1272
+ const rows: PlacedLine[] = [detailTabs(ctx, files, index, width)]
1273
+ if (active.truncated) rows.push({ line: truncLine(ln(seg(` ${s.detailTruncated}`, 'warn')), width) })
1274
+ if (detail.file !== active.path) {
1275
+ // The tab was switched and its text has not arrived yet: the tabs stay live, the body says why.
1276
+ rows.push({ line: truncLine(ln(seg(` ${s.detailLoading}`, 'dim')), width) })
1277
+ return one(rows, { index, total: 0, visible: 0, offset: 0 })
1278
+ }
1279
+ const doc = markdownMemo(active.path, detail.text, width)
1280
+ const budget = Math.max(1, ctx.detailRows ?? DETAIL_KEEP_DEFAULT)
1281
+ const available = Math.max(1, budget - rows.length)
1282
+ const maxStart = Math.max(0, doc.length - available)
1283
+ const offset = Math.max(0, Math.min(maxStart, Math.floor(ctx.view.detailScroll ?? 0) || 0))
1284
+ for (let i = offset; i < Math.min(doc.length, offset + available); i++) rows.push(doc[i])
1285
+ // The bounded-frame rule's last resort: a document shorter than the pane keeps the blank space
1286
+ // *inside* the card, so the card fills the height and the key band stays the last row.
1287
+ while (rows.length < budget) rows.push({ line: [] })
1288
+ return one(rows, { index, total: doc.length, visible: Math.min(available, Math.max(0, doc.length - offset)), offset })
1289
+ }
1290
+
1291
+ // ------------------------------------------------------------------ project settings (P22/B2)
1292
+ //
1293
+ // The view is a listing of the contract: one row per schema key plus one per key the file carries
1294
+ // that the schema does not know, grouped by the functional domain the **command** reports on the
1295
+ // row's `group` (P30 — the console owns no second table), then the model seats block. Rows, groups
1296
+ // and classes come from the `settings` block's JSON at render time; a key added to the command's
1297
+ // schema shows up without rebuilding `panel.js`. The list is windowed against the height the
1298
+ // assembly hands over (the bounded-frame rule: more pane means more rows, never more blank).
1299
+
1300
+ // The row's identity column is a **label** (M49), not the key name: the table's labels are human
1301
+ // sentences, so the column only has to hold the longest of them (zh is the wide language here;
1302
+ // a longer en label is cut by `cell()`, the same rule the key names followed).
1303
+ const SETTINGS_LABEL_W = 22
1304
+ const SETTINGS_AUDIT_LINES = 3
1305
+ // The tail the block draws under its row window: the CLI hint, a blank, the audit heading and up to
1306
+ // `SETTINGS_AUDIT_LINES` audit lines (the heading always has one line under it — a dash when the
1307
+ // command's log is empty), plus `SETTINGS_COUNT_ROWS`, the pessimistic reservation for the two
1308
+ // hidden-row counts (`↑n`/`↓n`). Reserving **both** counts is what keeps the block inside the frame
1309
+ // once the list is longer than the window: with only the tail reserved, a full window plus a full
1310
+ // audit tail overflowed and the whole view degraded to its one-line summary (measured in M55's
1311
+ // pairlist route: the seats block the route had just focused disappeared from the frame).
1312
+ //
1313
+ // P32 (the user's second report, 2026-09-22): the reservation is a *ceiling*, not a fixed cost. The
1314
+ // window spends what the tail does not need (a count line is only drawn when the window really
1315
+ // hides rows at that edge), and the block pads its card to the lines it was handed — so the pane's
1316
+ // height shows contract rows instead of the page's blank space.
1317
+ const SETTINGS_COUNT_ROWS = 2
1318
+
1319
+ /**
1320
+ * The sum M55 calibrated: the two count lines, the CLI hint, a blank, the audit heading and the audit
1321
+ * tail. The row list treats it as a ceiling and hands back what it does not draw (P32); the two pickers
1322
+ * keep it as the bound of their own *paged* list (title + interval + the two hidden-count lines + blank
1323
+ * + hint, then the entries) — a long vocabulary shows a `↑n`/`↓n` window that scrolls instead of
1324
+ * flooding the pane, which is what the archived `choices` fixture calibrates its twenty-eight model
1325
+ * records against. Their cards still fill (the pad below), so the key band stays the frame's last row.
1326
+ */
1327
+ const SETTINGS_TAIL_ROWS = SETTINGS_COUNT_ROWS + 1 + 1 + 1 + SETTINGS_AUDIT_LINES
1328
+
1329
+ /** One drawn row of the project-settings view (group headings are not focusable). */
1330
+ export type SettingsRow =
1331
+ | { kind: 'group'; label: string; tone: Tone }
1332
+ | { kind: 'key'; key: SettingsKey }
1333
+ | { kind: 'seat-group'; label: string }
1334
+ | { kind: 'seat'; seat: SettingsSeat }
1335
+
1336
+ export function settingsClassLabel(s: Strings, cls: string): string {
1337
+ if (cls === 'restart') return s.settingsBadgeRestart
1338
+ if (cls === 'refuse') return s.settingsBadgeRefuse
1339
+ return s.settingsBadgeApply
1340
+ }
1341
+
1342
+ /**
1343
+ * The effect class's tone (P30/D4): the *badge*'s tone, never the whole row's. `restart` is the one
1344
+ * class that warns, `refuse` recedes, and `apply` stays the plain text tone — 48 of 111 rows would
1345
+ * shout in green while the user's question is "does this need a restart?". Colour is never the only
1346
+ * channel: the badge's word always carries the class (the panel's standing rule).
1347
+ */
1348
+ function settingsClassTone(cls: string): Tone {
1349
+ if (cls === 'restart') return 'warn'
1350
+ if (cls === 'refuse') return 'dim'
1351
+ return 'text'
1352
+ }
1353
+
1354
+ /**
1355
+ * A functional group's heading label: `group_<token>` from the tables, falling back to the raw
1356
+ * token when the table has none (a schema freshly edited against the committed bundle) — the same
1357
+ * visible fallback `keyLabel` uses for an unknown key. Nothing here maps a key to a group.
1358
+ */
1359
+ function groupLabel(s: Strings, token: string): string {
1360
+ const label = s[`group_${token}`]
1361
+ return typeof label === 'string' && label.length > 0 ? label : token
1362
+ }
1363
+
1364
+ /** The CLI's own three source labels (the console invents no fourth state). */
1365
+ export function settingsSourceLabel(s: Strings, source: string): string {
1366
+ if (source === 'explicit') return s.seatSourceExplicit
1367
+ if (source === 'record') return s.seatSourceRecord
1368
+ return s.seatSourceConfig
1369
+ }
1370
+
1371
+ /**
1372
+ * The view's filtered row list: the contract's keys grouped by the **record's** `group` (P30/D1-D3),
1373
+ * in the read's own order, then the seats. Pure and exported: the App walks exactly this list when
1374
+ * it moves the focus, so the keys can never disagree with what is on screen.
1375
+ *
1376
+ * The bundle owns no key→group table and no group list: the walk opens a heading whenever the
1377
+ * token changes, so a key (or a whole group) added to the command's schema appears under its
1378
+ * reported heading with the committed bundle. Rows whose token is empty — a schema row that
1379
+ * declares none, or a key the file carries and the schema does not know — are never dropped: they
1380
+ * collect into one visible trailing fallback heading, before the seats block.
1381
+ */
1382
+ export function settingsViewRows(block: SettingsBlock | undefined, filter: string, s: Strings): SettingsRow[] {
1383
+ const out: SettingsRow[] = []
1384
+ if (!block || !Array.isArray(block.keys)) return out
1385
+ const needle = String(filter ?? '').trim().toLowerCase()
1386
+ const match = (...parts: string[]): boolean =>
1387
+ needle === '' || parts.some((p) => String(p ?? '').toLowerCase().includes(needle))
1388
+ // The label first (what the row shows), then the raw key and the value — the three inputs a
1389
+ // user may type into `/` (the label's words, `TEAM_…`, or the value on screen).
1390
+ const shown = block.keys.filter((k) =>
1391
+ match(keyLabel(s, k.name), k.name, k.value, k.default, k.comment, k.warning, k.route ?? ''),
1392
+ )
1393
+ const ungrouped: SettingsKey[] = []
1394
+ let openToken: string | null = null
1395
+ for (const k of shown) {
1396
+ const token = String(k.group ?? '')
1397
+ if (!token) {
1398
+ ungrouped.push(k)
1399
+ continue
1400
+ }
1401
+ if (token !== openToken) {
1402
+ out.push({ kind: 'group', label: groupLabel(s, token), tone: 'heading' })
1403
+ openToken = token
1404
+ }
1405
+ out.push({ kind: 'key', key: k })
1406
+ }
1407
+ if (ungrouped.length) {
1408
+ out.push({ kind: 'group', label: s.settingsGroupUngrouped, tone: 'heading' })
1409
+ for (const k of ungrouped) out.push({ kind: 'key', key: k })
1410
+ }
1411
+ const seats = (block.models?.seats ?? []).filter((x) =>
1412
+ match(x.agent, x.model, settingsSourceLabel(s, x.source)),
1413
+ )
1414
+ if (seats.length) {
1415
+ out.push({ kind: 'seat-group', label: s.settingsGroupSeats })
1416
+ for (const x of seats) out.push({ kind: 'seat', seat: x })
1417
+ }
1418
+ return out
1419
+ }
1420
+
1421
+ /**
1422
+ * The badge + value column shared by a key row and a seat row. The class tone covers the **badge
1423
+ * only** (P30/D4): the value beside it stays in the plain text tone, because a class meaning is
1424
+ * not a property of the value. A row with no badge (the seats) keeps its single-tone right column.
1425
+ */
1426
+ function settingsRight(ctx: Ctx, text: string, badge: string, tone: Tone, innerW: number): Line {
1427
+ const shown = truncateW(text, Math.max(6, innerW - SETTINGS_LABEL_W - 14))
1428
+ return badge === '' ? ln(seg(` ${shown}`, tone)) : ln(seg(` ${shown} · `, 'text'), seg(badge, tone))
1429
+ }
1430
+
1431
+ function settingsKeyLine(ctx: Ctx, row: SettingsKey, focused: boolean, innerW: number): PlacedLine {
1432
+ const { s } = ctx
1433
+ const known = row.known !== false
1434
+ const valueText =
1435
+ row.set || row.value !== ''
1436
+ ? row.value === ''
1437
+ ? '\"\"'
1438
+ : row.value
1439
+ : fill(s.settingsUnset, { value: row.default || s.dash })
1440
+ const badge = known ? settingsClassLabel(s, row.class) : s.settingsUnknownBadge
1441
+ const tone: Tone = known ? settingsClassTone(row.class) : 'dim'
1442
+ const line = ln(
1443
+ seg(`${focused ? s.settingsCursor : ' '} `, 'accent'),
1444
+ // The row's main text is the human label; the raw key is not repeated here (it stays in the
1445
+ // editor's title, the confirmation line and the view's CLI hint — the places where the user
1446
+ // types the key into `team config set`). An unknown key has no label → its raw name (M49).
1447
+ seg(cell(keyLabel(s, row.name), SETTINGS_LABEL_W), focused ? 'selected' : known ? 'heading' : 'dim'),
1448
+ ...settingsRight(ctx, valueText, badge, tone, innerW).map((x) => x),
1449
+ )
1450
+ const note = (row.warning || row.route || row.comment || '').trim()
1451
+ if (note) line.push(seg(` ${truncateW(note, Math.max(8, innerW - dispWidth(textOf(line)) - 2))}`, row.warning ? 'warn' : row.route && !known ? 'warn' : 'dim'))
1452
+ return { line }
1453
+ }
1454
+
1455
+ function settingsSeatLine(ctx: Ctx, seat: SettingsSeat, focused: boolean, innerW: number): PlacedLine {
1456
+ const { s } = ctx
1457
+ const model = seat.model || s.dash
1458
+ const policy = seat.override ? s.seatOverride : s.seatFallback
1459
+ const line = ln(
1460
+ seg(`${focused ? s.settingsCursor : ' '} `, 'accent'),
1461
+ seg(cell(seat.agent, SETTINGS_LABEL_W), focused ? 'selected' : 'heading'),
1462
+ ...settingsRight(ctx, `${model} · ${settingsSourceLabel(s, seat.source)} · ${policy}`, '', 'dim', innerW).map((x) => x),
1463
+ )
1464
+ return { line }
1465
+ }
1466
+
1467
+ /**
1468
+ * The focused row as the command line names it (M49): the row's label is for reading, the raw key
1469
+ * is what the user types — this line is the CLI-alignment half of the pair. A key the command does
1470
+ * not know (schema unknown) and a read-only key are said out loud rather than offered as a command
1471
+ * that would be refused; a seat gets its own `set-agent-model` route. '' when nothing is focusable.
1472
+ */
1473
+ function settingsCliHint(s: Strings, rows: SettingsRow[], focus: number): string {
1474
+ const focusable = rows.filter(
1475
+ (r): r is { kind: 'key'; key: SettingsKey } | { kind: 'seat'; seat: SettingsSeat } => r.kind === 'key' || r.kind === 'seat',
1476
+ )
1477
+ const row = focusable[focus]
1478
+ if (!row) return ''
1479
+ if (row.kind === 'seat') return fill(s.settingsSeatHint, { seat: row.seat.agent })
1480
+ const key = row.key
1481
+ if (key.known === false) return fill(s.settingsUnknownHint, { key: key.name })
1482
+ if (key.class === 'refuse') return fill(s.settingsRefusedHint, { key: key.name })
1483
+ // The pairlist row is not composed here: its editor is the seats block, and the command line the
1484
+ // requirement names is the per-seat one (M55).
1485
+ if (String(key.kind ?? '') === 'pairlist') return s.settingsPairlistHint
1486
+ return fill(s.settingsCliHint, { key: key.name })
1487
+ }
1488
+
1489
+ /**
1490
+ * The project-settings block: it replaces the page's blocks exactly as the detail view does (the
1491
+ * title band, the page tabs and the key band stay). `ctx.settingsRows` is the lines the block may draw
1492
+ * below its own card frame — the assembly hands over what the page's other blocks leave (P32), and the
1493
+ * block spends it on the row window, its tail and the blank fill, so the card fills the pane (the
1494
+ * frame's own budget still wins: an over-long block degrades by the usual chrome rules).
1495
+ */
1496
+ function settingsBlock(ctx: Ctx): Block | null {
1497
+ const { s, blocks, deg } = ctx
1498
+ const width = blockInnerW(ctx)
1499
+ const one = (lines: PlacedLine[], settings?: SettingsWindow): Block => ({
1500
+ id: 'settings',
1501
+ full: true,
1502
+ priority: 1,
1503
+ separator: 'none',
1504
+ title: s.settingsViewTitle,
1505
+ lines,
1506
+ settings,
1507
+ summary: { line: truncLine(ln(seg(` ${s.settingsViewTitle}`, 'heading')), ctx.width) },
1508
+ })
1509
+ const block = blocks.settings
1510
+ if (deg.has('settings') || !block || !Array.isArray(block.keys) || !block.keys.length) {
1511
+ return one([
1512
+ placedWithHits(
1513
+ truncLine(ln(seg(` ${s.settingsViewTitle}`, 'heading'), seg(' '), seg(s.dash, 'dim')), width),
1514
+ undefined,
1515
+ width,
1516
+ ),
1517
+ ])
1518
+ }
1519
+ const rows = settingsViewRows(block, ctx.view.settingsFilter ?? '', s)
1520
+ let count = 0
1521
+ for (const r of rows) if (r.kind === 'key' || r.kind === 'seat') count += 1
1522
+ // P32: the block's budget is the **lines** it may draw below the card frame — the assembly hands
1523
+ // over everything the page's other blocks leave (`budget - fullRows - the frame's two rows`), and
1524
+ // the tail is spent out of that same budget, so what the tail does not need goes to real rows
1525
+ // instead of the page's blank space.
1526
+ const room = Math.max(3, ctx.settingsRows ?? 12)
1527
+ const focus = Math.max(0, Math.min(Math.max(0, count - 1), ctx.view.settingsFocus ?? 0))
1528
+ const explicitOffset = ctx.view.settingsOffset
1529
+ // The tail under the window: the CLI hint, a blank, the audit heading and its tail (the heading
1530
+ // always has one line under it — a dash when the command's log is empty).
1531
+ const audit = (block.audit ?? []).slice(-SETTINGS_AUDIT_LINES)
1532
+ const tailLines = 1 + 1 + 1 + Math.max(1, audit.length)
1533
+ // The row cap: each row costs at least its own line, and the tail is already spoken for.
1534
+ const desired = Math.max(1, Math.min(Math.max(1, count), Math.max(1, room - tailLines)))
1535
+ const maxOffset = Math.max(0, count - desired)
1536
+ // The first fit reserves both count lines (the M55 rule above); the growth below hands the one
1537
+ // the window does not draw back to it.
1538
+ const windowRoom = Math.max(1, room - tailLines - SETTINGS_COUNT_ROWS)
1539
+ // P30/D5 (measured while testing the wheel at the list's tail): the window is bounded by the
1540
+ // **lines** it draws, not by the row count. A group heading draws a line of its own, so a
1541
+ // heading-rich window used to overflow the space the assembly handed over — and the frame then
1542
+ // collapsed the whole block to its one-line rule/summary, leaving the wheel nothing to scroll.
1543
+ // The fit measures the rows it can really draw, so the window always fits and both hidden-row
1544
+ // counts stay honest.
1545
+ //
1546
+ // P32 (measured 2026-09-22 on a 111-key contract at 120×45): D5's price list charged a key row
1547
+ // with a note **two** lines, but `settingsKeyLine` appends the note to the row's own line — 15 of
1548
+ // the window's 17 drawn lines were billed double, which is exactly where 15 of the pane's 16
1549
+ // blank rows came from. The unit is one *focusable* row; its price is its own line plus the group
1550
+ // heading directly above it, which draws exactly when that row is inside the window.
1551
+ const units: { heading: number }[] = []
1552
+ let pendingHeading = 0
1553
+ for (const r of rows) {
1554
+ if (r.kind === 'group' || r.kind === 'seat-group') {
1555
+ pendingHeading = 1
1556
+ continue
1557
+ }
1558
+ units.push({ heading: pendingHeading })
1559
+ pendingHeading = 0
1560
+ }
1561
+ const spend = (start: number, n: number): number => {
1562
+ let cost = 0
1563
+ for (let i = start; i < Math.min(start + n, units.length); i += 1) cost += 1 + units[i].heading
1564
+ return cost
1565
+ }
1566
+ /** The rows a window starting at `start` can really draw inside the reserved window lines. */
1567
+ const fitForward = (start: number): number => {
1568
+ let visible = 0
1569
+ while (visible < desired && start + visible < units.length && spend(start, visible + 1) <= windowRoom) visible += 1
1570
+ return visible
1571
+ }
1572
+ /** The first row of the largest window that ends at the focused row (the focus never hides). */
1573
+ const fitBack = (row: number): number => {
1574
+ let start = row
1575
+ while (start > 0 && row - start + 1 < desired && spend(start - 1, row - start + 2) <= windowRoom) start -= 1
1576
+ return start
1577
+ }
1578
+ let offset: number
1579
+ let visible: number
1580
+ if (explicitOffset === undefined || explicitOffset === null) {
1581
+ // The focus-follow default: centre the focused row, then keep it inside the fitted window.
1582
+ offset = Math.max(0, Math.min(maxOffset, focus - Math.floor(desired / 2)))
1583
+ visible = fitForward(offset)
1584
+ if (focus >= offset + visible) {
1585
+ offset = fitBack(focus)
1586
+ visible = fitForward(offset)
1587
+ }
1588
+ } else {
1589
+ // The wheel's own offset (P30/D5): it wins — clamped to the row set, so a filter or a re-read
1590
+ // that shrinks the list clamps rather than losing the view. The focus is deliberately left
1591
+ // where it is; the focus keys push this offset back onto the focused row.
1592
+ offset = Math.max(0, Math.min(Math.max(0, count - 1), explicitOffset))
1593
+ visible = fitForward(offset)
1594
+ }
1595
+ if (visible === 0 && count > 0) visible = 1
1596
+
1597
+ // P32: the spare the first fit kept for the count lines goes back to the window as far as it
1598
+ // really helps. A count line is drawn only when the window hides rows at that edge — a window at
1599
+ // the top hides nothing above it — so a window that ends on the last row gets the line the `↓n`
1600
+ // reservation held, and the card fills with contract rows. Growth is **downward only**: growing
1601
+ // upward would move the window's first row against the offset the wheel set, and the tests (and
1602
+ // the user) read `↑n` as the wheel's own position.
1603
+ const drawn = (start: number, n: number): number =>
1604
+ spend(start, n) + (start > 0 ? 1 : 0) + (count > start + n ? 1 : 0)
1605
+ while (offset + visible < count && visible < desired && drawn(offset, visible + 1) + tailLines <= room) visible += 1
1606
+
1607
+ // The choice picker (M55): the command's own vocabulary, rendered in the view's own line budget
1608
+ // exactly like the seat picker below (same window/offset rules, one click action per entry, no
1609
+ // overlay, no width tier — the row list the snapshots pin is untouched). The entries are built
1610
+ // by the App from the key's `choices` object; this function only labels and windows them. The entry
1611
+ // window is the M55 bound (`SETTINGS_TAIL_ROWS`), not the row list's P32 budget: a long vocabulary
1612
+ // is *paged* here by design, while the card below still fills the pane.
1613
+ const choice = ctx.view.choicePicker
1614
+ if (choice) {
1615
+ const entries = choice.entries
1616
+ const sel = Math.max(0, Math.min(Math.max(0, entries.length - 1), choice.index))
1617
+ // title + interval + the two hidden-count lines + blank + hint: the entries get the rest.
1618
+ const entryBudget = Math.max(1, room - SETTINGS_TAIL_ROWS - 6)
1619
+ const entryVisible = Math.max(1, Math.min(entries.length, entryBudget))
1620
+ const entryOffset = Math.max(0, Math.min(Math.max(0, entries.length - entryVisible), sel - Math.floor(entryVisible / 2)))
1621
+ const lines: PlacedLine[] = []
1622
+ const put = (line: Line): void => {
1623
+ lines.push({ line: truncLine(line, width) })
1624
+ }
1625
+ const entryLabel = (e: SettingsChoiceEntry): string => {
1626
+ const base =
1627
+ e.kind === 'keep-unset'
1628
+ ? s.settingsChoiceKeepUnset
1629
+ : e.kind === 'clear'
1630
+ ? s.settingsChoiceClear
1631
+ : e.kind === 'free'
1632
+ ? s.settingsChoiceFree
1633
+ : choice.kind === 'bool' && (e.value === '1' || e.value === '0')
1634
+ ? e.value === '1'
1635
+ ? s.settingsBoolOn
1636
+ : s.settingsBoolOff
1637
+ : e.value
1638
+ const marks: string[] = []
1639
+ if (e.kind === 'current') marks.push(s.settingsChoiceCurrent)
1640
+ if (e.kind === 'default') marks.push(s.settingsChoiceDefault)
1641
+ if (e.mark) {
1642
+ marks.push(e.mark === 'exists' ? s.settingsPathExists : e.mark === 'not-exec' ? s.settingsPathNotExec : s.settingsPathMissing)
1643
+ }
1644
+ return marks.length ? `${base} · ${marks.join(' · ')}` : base
1645
+ }
1646
+ put(ln(seg(` ${fill(s.settingsChoiceTitle, { label: keyLabel(s, choice.key), key: choice.key })}`, 'heading')))
1647
+ if (choice.interval) {
1648
+ put(
1649
+ ln(
1650
+ seg(
1651
+ ` ${fill(s.settingsChoiceInterval, { min: choice.interval.min || '0', max: choice.interval.max || '∞' })}`,
1652
+ 'dim',
1653
+ ),
1654
+ ),
1655
+ )
1656
+ }
1657
+ if (entryOffset > 0) put(ln(seg(` ${fill(s.laneHiddenAbove, { n: String(entryOffset) })}`, 'dim')))
1658
+ entries.forEach((e, i) => {
1659
+ if (i < entryOffset || i >= entryOffset + entryVisible) return
1660
+ const label = entryLabel(e)
1661
+ const line = ln(
1662
+ seg(`${i === sel ? s.settingsCursor : ' '} `, 'accent'),
1663
+ seg(label, i === sel ? 'selected' : e.kind === 'value' || e.kind === 'current' || e.kind === 'default' ? 'text' : 'dim'),
1664
+ )
1665
+ const action: Action = { kind: 'choice-pick', index: i }
1666
+ const rowW = Math.max(2, Math.min(width, 1 + dispWidth(textOf(line))))
1667
+ lines.push(placedWithHits(line, ctx.view.tui ? [{ start: 1, end: rowW, action }] : undefined, width))
1668
+ })
1669
+ const entryHiddenBelow = Math.max(0, entries.length - (entryOffset + entryVisible))
1670
+ if (entryHiddenBelow > 0) put(ln(seg(` ${fill(s.laneHiddenBelow, { n: String(entryHiddenBelow) })}`, 'dim')))
1671
+ put(ln(seg('')))
1672
+ put(ln(seg(` ${s.settingsChoiceHint}`, 'dim')))
1673
+ // P32: a picker covers the row list, so what its own entries do not use stays inside the card
1674
+ // (the fill rule below); a short picker must not leave the pane half blank either.
1675
+ while (lines.length < room) put(ln(seg('')))
1676
+ return one(lines, { focus: sel, offset: entryOffset, visible: entryVisible, count: entries.length })
1677
+ }
1678
+
1679
+ // The seat picker (P22/B4): the models the command reports as known, then the removal and the
1680
+ // free-text line — the editor opens on whichever is chosen.
1681
+ const picker = ctx.view.seatPicker
1682
+ if (picker) {
1683
+ const options = [...picker.models, '-', '']
1684
+ const sel = Math.max(0, Math.min(options.length - 1, picker.index))
1685
+ const lines: PlacedLine[] = []
1686
+ const put = (line: Line): void => {
1687
+ lines.push({ line: truncLine(line, width) })
1688
+ }
1689
+ put(ln(seg(` ${fill(s.seatPickerTitle, { seat: picker.agent })}`, 'heading')))
1690
+ options.forEach((opt, i) => {
1691
+ const label = opt === '-' ? s.seatPickerRemove : opt === '' ? s.seatPickerFree : opt
1692
+ const row = ln(
1693
+ seg(`${i === sel ? s.settingsCursor : ' '} `, 'accent'),
1694
+ seg(label, i === sel ? 'selected' : opt === '' || opt === '-' ? 'dim' : 'text'),
1695
+ )
1696
+ const action: Action = { kind: 'seat-pick', index: i }
1697
+ const rowW = Math.max(2, Math.min(width, 1 + dispWidth(textOf(row))))
1698
+ lines.push(placedWithHits(row, ctx.view.tui ? [{ start: 1, end: rowW, action }] : undefined, width))
1699
+ })
1700
+ put(ln(seg('')))
1701
+ put(ln(seg(` ${s.seatPickerHint}`, 'dim')))
1702
+ while (lines.length < room) put(ln(seg('')))
1703
+ return one(lines, { focus: sel, offset: 0, visible: options.length, count: options.length })
1704
+ }
1705
+
1706
+ const lines: PlacedLine[] = []
1707
+ const hiddenAbove = offset
1708
+ const hiddenBelow = Math.max(0, count - (offset + visible))
1709
+ const put = (line: Line): void => {
1710
+ lines.push({ line: truncLine(line, width) })
1711
+ }
1712
+ if (hiddenAbove > 0) put(ln(seg(` ${fill(s.laneHiddenAbove, { n: String(hiddenAbove) })}`, 'dim')))
1713
+
1714
+ let idx = -1
1715
+ for (const r of rows) {
1716
+ if (r.kind === 'key' || r.kind === 'seat') {
1717
+ idx += 1
1718
+ if (idx < offset || idx >= offset + visible) continue
1719
+ const focused = idx === focus
1720
+ const placed = r.kind === 'key' ? settingsKeyLine(ctx, r.key, focused, width) : settingsSeatLine(ctx, r.seat, focused, width)
1721
+ // The whole row is a target: a click on an unfocused row moves the focus, a second click on
1722
+ // the focused row opens it (the kanban's rule).
1723
+ const action: Action = focused ? { kind: 'settings-open', index: idx } : { kind: 'settings-focus', index: idx }
1724
+ const rowW = Math.max(2, Math.min(width, 1 + dispWidth(textOf(placed.line))))
1725
+ lines.push(placedWithHits(placed.line, ctx.view.tui ? [{ start: 1, end: rowW, action }] : undefined, width))
1726
+ continue
1727
+ }
1728
+ // A heading draws only when the next focusable row is inside the window.
1729
+ const next = idx + 1
1730
+ if (next < offset || next >= offset + visible) continue
1731
+ if (r.kind === 'group' || r.kind === 'seat-group') {
1732
+ // P32 (the user's first report): a heading indented like a row reads as one more row. It is a
1733
+ // **section rule** instead — `── 身份与账本布局 ────…`, the shape the non-framed blocks already
1734
+ // use — so a heading and a key row cannot be confused in a monochrome capture either, and
1735
+ // consecutive groups are separated by their own headings without spending a second line.
1736
+ put(ruleTitle(r.label, width, r.kind === 'group' ? r.tone : 'accent'))
1737
+ }
1738
+ }
1739
+ if (hiddenBelow > 0) put(ln(seg(` ${fill(s.laneHiddenBelow, { n: String(hiddenBelow) })}`, 'dim')))
1740
+
1741
+ // The CLI-alignment line (M49): the row's label is for reading, the raw key is for typing.
1742
+ put(ln(seg(` ${settingsCliHint(s, rows, focus)}`, 'dim')))
1743
+
1744
+ // The audit footer: at most three lines, newest last (the CLI's own tail).
1745
+ put(ln(seg('')))
1746
+ put(ln(seg(` ${s.settingsAuditHeading}`, 'heading')))
1747
+ if (!audit.length) put(ln(seg(` ${s.dash}`, 'dim')))
1748
+ for (const a of audit) put(ln(seg(` ${a}`, 'dim')))
1749
+
1750
+ // P32 (the bounded-frame rule's last resort, the detail view's own): the space the rows did not
1751
+ // use stays **inside** the card, so the card fills the pane it was handed and the key band stays
1752
+ // the frame's last row. With a full list that is nothing; with a filter, the tail of the list or
1753
+ // a short pane it is what the user read as "the view does not use the window's height".
1754
+ while (lines.length < room) put(ln(seg('')))
1755
+
1756
+ return one(lines, { focus, offset, visible, count })
1757
+ }
1758
+
1759
+ /**
1760
+ * P45/B2: the token line under a change row (`M1 done · M2 wip · V1 PASS · +N`).
1761
+ *
1762
+ * It is rendered only when the whole line fits the block's width: a token line that would have to be
1763
+ * cut is dropped **whole** rather than truncated (`truncLine`) or wrapped — the block must not reflow
1764
+ * (a wrapped cell moves every row below it, and a board page that shifts when a task's status
1765
+ * changes is worse than a missing summary), and a half-shown token list is worse than none. The
1766
+ * reader's `+N` overflow count is part of the text, so the bound stays visible; the tone is the
1767
+ * same `dim` as the digest's own change section.
1768
+ */
1769
+ function changeTasksLine(ch: ChangeRow, width: number): PlacedLine | null {
1770
+ const tasks = ch.tasks ?? []
1771
+ if (!tasks.length) return null
1772
+ const parts = tasks.map((t) => `${t.id} ${t.board}`)
1773
+ if ((ch.tasks_more ?? 0) > 0) parts.push(`+${ch.tasks_more}`)
1774
+ const line = ln(seg(` ${parts.join(' · ')}`, 'dim'))
1775
+ return widthOf(line) <= width ? { line } : null
1776
+ }
1777
+
1778
+ function changesBlock(ctx: Ctx): Block | null {
1779
+ const { s, blocks, deg, width } = ctx
1780
+ const c = blocks.changes
1781
+ if (!c) return null
1782
+ if (deg.has('changes') || !c.available) {
1783
+ return { id: 'changes', title: s.changesHeading, right: true, priority: 11, lines: [{ line: ln(seg(` ${s.dash}`, 'dim')) }] }
1784
+ }
1785
+ if (!c.changes.length) return null // an empty block collapses and yields its space
1786
+ const lines: PlacedLine[] = []
1787
+ for (const ch of c.changes as ChangeRow[]) {
1788
+ lines.push({
1789
+ line: truncLine(
1790
+ ln(
1791
+ seg(' '),
1792
+ seg(cell(ch.id, 18), 'accent'),
1793
+ seg(fill(s.changeLine, { done: ch.done, total: ch.total, phase: changePhaseText(ch.phase, s) })),
1794
+ ),
1795
+ width,
1796
+ ),
1797
+ })
1798
+ const toks = changeTasksLine(ch, width)
1799
+ if (toks) lines.push(toks)
1800
+ }
1801
+ return { id: 'changes', title: fill(s.changesHeadingCount, { n: c.count }), right: true, priority: 11, lines, summary: { line: truncLine(ln(seg(` ${fill(s.changesHeadingCount, { n: c.count })}`, 'heading')), width) } }
1802
+ }
1803
+
1804
+ function specsBlock(ctx: Ctx): Block | null {
1805
+ const { s, blocks, deg, width } = ctx
1806
+ const sp = blocks.specs
1807
+ if (!sp) return null
1808
+ if (deg.has('specs') || !sp.available) {
1809
+ return { id: 'specs', title: s.specsHeading, right: true, priority: 13, lines: [{ line: ln(seg(` ${s.dash}`, 'dim')) }] }
1810
+ }
1811
+ const lines: PlacedLine[] = [
1812
+ { line: truncLine(ln(seg(fill(s.specsCount, { specs: sp.count, reqs: sp.requirements }), 'dim')), width) },
1813
+ ]
1814
+ for (const row of (sp.specs ?? []).slice(0, 6)) {
1815
+ lines.push({ line: truncLine(ln(seg(' '), seg(cell(row.name, Math.max(8, width - 10)), 'text'), seg(` ${row.requirements}`, 'dim')), width) })
1816
+ }
1817
+ return { id: 'specs', title: s.specsHeading, right: true, priority: 13, lines, summary: { line: truncLine(ln(seg(` ${s.specsHeading}`, 'heading')), width) } }
1818
+ }
1819
+
1820
+ function decisionsBlock(ctx: Ctx): Block | null {
1821
+ const { s, blocks, deg, width } = ctx
1822
+ const d = blocks.decisions
1823
+ if (!d) return null
1824
+ if (deg.has('decisions')) {
1825
+ return { id: 'decisions', title: s.decisionsHeading, right: true, priority: 14, lines: [{ line: ln(seg(` ${s.dash}`, 'dim')) }] }
1826
+ }
1827
+ const lines: PlacedLine[] = [
1828
+ { line: truncLine(ln(seg(fill(s.decisionsCountSuffix, { n: d.count }), 'dim')), width) },
1829
+ ]
1830
+ if (!d.recent.length) lines.push({ line: ln(seg(` ${s.decisionsEmpty}`, 'dim')) })
1831
+ for (const r of d.recent.slice(0, 3)) lines.push({ line: truncLine(ln(seg(` ${r}`, 'dim')), width) })
1832
+ return { id: 'decisions', title: s.decisionsHeading, right: true, priority: 14, lines, summary: { line: truncLine(ln(seg(` ${s.decisionsHeading}`, 'heading')), width) } }
1833
+ }
1834
+
1835
+ // ------------------------------------------------------------------ body blocks (page 3)
1836
+
1837
+ function queueBlock(ctx: Ctx): Block | null {
1838
+ const { s, blocks, deg, width, view } = ctx
1839
+ const q = blocks.outbox_list
1840
+ if (!q && !deg.has('outbox_list')) return null
1841
+ if (deg.has('outbox_list') || !q) {
1842
+ return { id: 'queue', title: s.queueHeading, priority: 10, lines: [{ line: ln(seg(` ${s.dash}`, 'dim')) }] }
1843
+ }
1844
+ if (view.viewEntry != null && q.entries[view.viewEntry]) {
1845
+ const e = q.entries[view.viewEntry]
1846
+ const lines: PlacedLine[] = [
1847
+ { line: truncLine(ln(seg(` ${fill(s.queueMeta, { kind: e.kind, target: e.target, from: e.from })}`, 'dim')), width) },
1848
+ { line: ln(seg(' ')) },
1849
+ ]
1850
+ for (const text of String(e.text ?? '').split('\n')) {
1851
+ for (const chunk of wrapText(text, Math.max(4, width - 2))) lines.push({ line: truncLine(ln(seg(` ${chunk}`)), width) })
1852
+ }
1853
+ lines.push({ line: ln(seg(''), seg(` ${s.queueBackHint}`, 'dim')) })
1854
+ return { id: 'queue', title: fill(s.queueFullHeading, { name: e.name }), priority: 10, lines, summary: { line: truncLine(ln(seg(` ${fill(s.queueFullHeading, { name: e.name })}`, 'heading')), width) } }
1855
+ }
1856
+ if (!q.entries.length) {
1857
+ return { id: 'queue', title: s.queueHeading, priority: 10, lines: [{ line: ln(seg(` ${s.queueEmpty}`, 'dim')) }] }
1858
+ }
1859
+ const lines: PlacedLine[] = []
1860
+ // delivery-truth D2:阻碍是**测量事实**(原因、观察时刻、诊断可否读),不是「有草稿」的暗示。
1861
+ const imps: Impediment[] = q.impediments ?? []
1862
+ if (q.impeded && q.impeded > 0) {
1863
+ const reasons = Array.from(new Set(imps.map((i) => i.reason))).join(' · ') || s.dash
1864
+ lines.push({ line: truncLine(ln(seg(` ${fill(s.queueImpededLine, { n: q.impeded, reasons })}`, 'warn')), width) })
1865
+ for (const im of imps.slice(0, 3)) {
1866
+ const when = im.diagnostic === 'available' && im.last_observed ? im.last_observed : s.queueImpededUnavailable
1867
+ lines.push({ line: truncLine(ln(seg(fill(s.queueImpededItem, { entry: im.entry, reason: im.reason, when }), 'warn')), width) })
1868
+ }
1869
+ }
1870
+ q.entries.slice(0, 20).forEach((e: QueueEntry, i: number) => {
1871
+ const state = e.state === 'held' ? s.queueStateHeld : s.queueStateQueued
1872
+ const row = ln(
1873
+ seg(' '),
1874
+ seg(fill(s.queueLine, { index: i + 1, state, name: e.name, age: fmtAge(e.age_s) }), e.state === 'held' ? 'warn' : 'text'),
1875
+ e.reason && e.reason !== '-' ? seg(` ${fill(s.queueHeldReason, { reason: e.reason })}`, 'dim') : null,
1876
+ )
1877
+ const placed: PlacedLine = placedWithHits(
1878
+ row,
1879
+ view.tui ? [{ start: 2, end: 2 + dispWidth(textOf(row)), action: { kind: 'view-entry', index: i } }] : undefined,
1880
+ width,
1881
+ )
1882
+ lines.push(placed)
1883
+ })
1884
+ if (ctx.view.tui) lines.push({ line: ln(seg(` ${s.queueViewHint}`, 'dim')) })
1885
+ return { id: 'queue', title: fill(s.queueHeadingCount, { queued: q.queued, held: q.held }), priority: 10, lines, summary: { line: truncLine(ln(seg(` ${fill(s.queueHeadingCount, { queued: q.queued, held: q.held })}`, 'heading')), width) } }
1886
+ }
1887
+
1888
+ function wrapText(text: string, width: number): string[] {
1889
+ if (!text) return ['']
1890
+ const out: string[] = []
1891
+ let cur = ''
1892
+ for (const ch of String(text)) {
1893
+ if (cur && dispWidth(cur + ch) > width) {
1894
+ out.push(cur)
1895
+ cur = ch
1896
+ } else cur += ch
1897
+ }
1898
+ out.push(cur)
1899
+ return out
1900
+ }
1901
+
1902
+ function inboxBlock(ctx: Ctx): Block | null {
1903
+ const { s, blocks, deg, width } = ctx
1904
+ const inbox = blocks.inbox
1905
+ if (!inbox) return null
1906
+ if (deg.has('inbox')) {
1907
+ return { id: 'inbox', title: s.inboxHeading, right: true, priority: 11, lines: [{ line: ln(seg(` ${s.dash}`, 'dim')) }] }
1908
+ }
1909
+ if (!inbox.agents.length) return null
1910
+ const lines: PlacedLine[] = []
1911
+ for (const a of inbox.agents.slice(0, 8)) {
1912
+ lines.push({
1913
+ line: truncLine(
1914
+ ln(
1915
+ seg(' '),
1916
+ seg(cell(a.agent, 10), 'accent'),
1917
+ seg(fill(s.inboxLine, { inbox: a.inbox_lines, thread: a.thread_lines, age: fmtAge(a.inbox_age_s) }), 'dim'),
1918
+ ),
1919
+ width,
1920
+ ),
1921
+ })
1922
+ }
1923
+ return { id: 'inbox', title: s.inboxHeading, right: true, priority: 11, lines, summary: { line: truncLine(ln(seg(` ${s.inboxHeading}`, 'heading')), width) } }
1924
+ }
1925
+
1926
+ function patrolBlock(ctx: Ctx): Block | null {
1927
+ const { s, blocks, deg, width, view } = ctx
1928
+ const p = blocks.patrol
1929
+ if (!p) return null
1930
+ if (deg.has('patrol')) {
1931
+ return { id: 'patrol', title: s.patrolHeading, right: true, priority: 12, lines: [{ line: ln(seg(` ${s.dash}`, 'dim')) }] }
1932
+ }
1933
+ if (!p.lines.length) return null
1934
+ const lines: PlacedLine[] = []
1935
+ for (const l of p.lines.slice(-12).slice(Math.max(0, view.scroll))) lines.push({ line: truncLine(ln(seg(` ${l}`, 'dim')), width) })
1936
+ return { id: 'patrol', title: s.patrolHeading, right: true, priority: 12, lines, summary: { line: truncLine(ln(seg(` ${s.patrolHeading}`, 'heading')), width) } }
1937
+ }
1938
+
1939
+ function trendBlock(ctx: Ctx): Block | null {
1940
+ const { s, panel, deg, width } = ctx
1941
+ const c = panel.capacity
1942
+ if (!c || deg.has('capacity')) return null
1943
+ const spark = sparkline(c.spark, Math.max(8, width - 8))
1944
+ if (!spark) return null
1945
+ return {
1946
+ id: 'trend',
1947
+ title: s.trendHeading,
1948
+ right: true,
1949
+ priority: 13,
1950
+ lines: [
1951
+ { line: ln(seg(fill(s.trendLine, { mb: fmtMB(c.ram_avail_mb), swap: fmtMB(c.swap_free_mb) }), 'dim')) },
1952
+ { line: truncLine(ln(seg(' '), seg(spark, 'accent')), width) },
1953
+ ],
1954
+ summary: { line: truncLine(ln(seg(` ${s.trendHeading}`, 'heading')), width) },
1955
+ }
1956
+ }
1957
+
1958
+ function healthBlock(ctx: Ctx): Block | null {
1959
+ const { s, blocks, deg, width } = ctx
1960
+ const h = blocks.health
1961
+ if (!h) return null
1962
+ if (deg.has('health')) {
1963
+ return { id: 'health', title: s.healthHeading, right: true, priority: 14, lines: [{ line: ln(seg(` ${s.dash}`, 'dim')) }] }
1964
+ }
1965
+ const doctor =
1966
+ h.doctor === 'ok'
1967
+ ? s.healthDoctorOk
1968
+ : h.doctor === 'warn'
1969
+ ? s.healthDoctorWarn
1970
+ : h.doctor === 'fail'
1971
+ ? s.healthDoctorFail
1972
+ : s.healthDoctorNA
1973
+ const tone: Tone = h.doctor === 'ok' ? 'ok' : h.doctor === 'fail' ? 'err' : 'warn'
1974
+ return {
1975
+ id: 'health',
1976
+ title: s.healthHeading,
1977
+ right: true,
1978
+ priority: 14,
1979
+ lines: [
1980
+ {
1981
+ line: truncLine(
1982
+ ln(seg(fill(s.healthLine, { version: h.version || s.dash, doctor, gates: h.gates || s.dash }), h.doctor === 'ok' ? 'text' : tone)),
1983
+ width,
1984
+ ),
1985
+ },
1986
+ ],
1987
+ }
1988
+ }
1989
+
1990
+ // ------------------------------------------------------------------ footer and overlay
1991
+
1992
+ /**
1993
+ * P123: the focused card's demoted `agent · phase` pair, which the board page's key band renders in
1994
+ * the width its chips leave free. Only the card line hides these fields; the pair is built only
1995
+ * while the kanban is on screen (the detail view and the settings surfaces replace the page's
1996
+ * blocks, so no card is focused on screen there). `null` when the board page has no focused card.
1997
+ */
1998
+ function demotedPair(ctx: Ctx): { full: string; phase: string } | null {
1999
+ const { s } = ctx
2000
+ if (ctx.view.page !== 4 || ctx.view.detail || ctx.view.overlay || ctx.view.settings) return null
2001
+ const rows = ctx.blocks.board?.rows ?? []
2002
+ if (!rows.length) return null
2003
+ const card = focusRow(rows, resolveFocus(rows, ctx.view.focus))
2004
+ if (!card) return null
2005
+ // P125: in the side-by-side tier the folded lane is the three-column frame, which cannot carry
2006
+ // its label — the band names the lane it holds the focus for (its label and card count) exactly
2007
+ // where the demoted pair would render. In the grouped tier the folded line still carries them,
2008
+ // so the pair stays as it was.
2009
+ if (ctx.twoColumn && laneFolded(ctx.view, card.state, !laneCards(rows, card.state).length)) {
2010
+ const text = `${laneLabel(card.state, s)} ${laneCards(rows, card.state).length}`
2011
+ return { full: text, phase: text }
2012
+ }
2013
+ const phase = card.phase && card.phase !== '-' ? card.phase : s.dash
2014
+ // No cursor glyph here: the frame carries exactly one `›` (the focused card's), and the pair is
2015
+ // data, not a marker — the design's example glyph would have made every board frame carry two.
2016
+ return { full: `${card.agent} · ${phase}`, phase }
2017
+ }
2018
+
2019
+ function keyBandBlock(ctx: Ctx, rowsAvailable = true): Block {
2020
+ const { s, width } = ctx
2021
+ const actions: { text: string; action: Action }[] = [
2022
+ { text: s.keyCompose, action: { kind: 'compose' } },
2023
+ { text: s.keyFlush, action: { kind: 'flush' } },
2024
+ { text: s.keyStandby, action: { kind: 'standby' } },
2025
+ { text: s.keySettings, action: { kind: 'settings' } },
2026
+ ]
2027
+ // The board page's nav chips carry its own keys: the lane/card moves and Enter (every documented
2028
+ // key has a target — `r` stays keyboard-only, V16 F-V16-5). While the detail view is open the same
2029
+ // chips become its keys — it adds no action, and `q` is the documented back-out, not a collapse.
2030
+ const nav: { text: string; action: Action }[] = ctx.view.settings
2031
+ ? ctx.view.choicePicker
2032
+ ? [
2033
+ { text: s.keyRows, action: { kind: 'choice-move', delta: 1 } },
2034
+ { text: s.keyOpen, action: { kind: 'choice-pick', index: -1 } },
2035
+ { text: s.keyDetailClose, action: { kind: 'choice-close' } },
2036
+ ]
2037
+ : ctx.view.seatPicker
2038
+ ? [
2039
+ { text: s.keyRows, action: { kind: 'seat-move', delta: 1 } },
2040
+ { text: s.keySeatPick, action: { kind: 'seat-pick', index: -1 } },
2041
+ { text: s.keyDetailClose, action: { kind: 'settings-close' } },
2042
+ ]
2043
+ : [
2044
+ { text: s.keyRows, action: { kind: 'settings-scroll', delta: 1 } },
2045
+ { text: s.keyOpen, action: { kind: 'settings-open', index: -1 } },
2046
+ { text: s.keyFilter, action: { kind: 'settings-filter' } },
2047
+ { text: s.keyDetailClose, action: { kind: 'settings-close' } },
2048
+ ]
2049
+ : ctx.view.detail
2050
+ ? [
2051
+ { text: s.keyDetailClose, action: { kind: 'detail-close' } },
2052
+ { text: s.keyDetailTabs, action: { kind: 'detail-tab-move', delta: 1 } },
2053
+ { text: s.keyDetailScroll, action: { kind: 'detail-scroll', delta: 1 } },
2054
+ { text: s.keyPages, action: { kind: 'page-cycle' } },
2055
+ ]
2056
+ : ctx.view.page === 2 && rowsAvailable
2057
+ ? [
2058
+ { text: s.keyRows, action: { kind: 'card-move', delta: 1 } },
2059
+ { text: s.keyOpen, action: { kind: 'open-focused', lane: 'todo' } },
2060
+ { text: s.keyPages, action: { kind: 'page-cycle' } },
2061
+ { text: s.keyQuit, action: { kind: 'quit' } },
2062
+ ]
2063
+ : ctx.view.page === 4
2064
+ ? [
2065
+ { text: s.keyLanes, action: { kind: 'lane-move', delta: 1 } },
2066
+ { text: s.keyCards, action: { kind: 'card-move', delta: 1 } },
2067
+ {
2068
+ text: s.keyFold,
2069
+ action: { kind: 'lane-fold', lane: resolveFocus(ctx.blocks.board?.rows ?? [], ctx.view.focus)?.lane ?? '' },
2070
+ },
2071
+ {
2072
+ text: s.keyOpen,
2073
+ action: { kind: 'open-focused', lane: resolveFocus(ctx.blocks.board?.rows ?? [], ctx.view.focus)?.lane ?? 'todo' },
2074
+ },
2075
+ { text: s.keyPages, action: { kind: 'page-cycle' } },
2076
+ { text: s.keyQuit, action: { kind: 'quit' } },
2077
+ ]
2078
+ : [
2079
+ { text: s.keyPages, action: { kind: 'page-cycle' } },
2080
+ { text: s.keyScroll, action: { kind: 'scroll', delta: 1 } },
2081
+ { text: s.keyQuit, action: { kind: 'quit' } },
2082
+ ]
2083
+ const line: Line = []
2084
+ const hits: Hit[] = []
2085
+ let x = 1
2086
+ const chip = isFramed(ctx)
2087
+ const push = (text: string, action: Action, asChip: boolean, dim: boolean): void => {
2088
+ if (asChip) {
2089
+ const inner = ` ${text} `
2090
+ const start = x
2091
+ line.push(seg('(', 'dim'), seg(inner, 'accent'), seg(')', 'dim'))
2092
+ x += dispWidth(`(${inner})`)
2093
+ if (ctx.view.tui) hits.push({ start, end: x, action })
2094
+ } else {
2095
+ const start = x
2096
+ line.push(seg(text, dim ? 'dim' : 'accent'))
2097
+ x += dispWidth(text)
2098
+ if (ctx.view.tui) hits.push({ start, end: x, action })
2099
+ }
2100
+ }
2101
+ actions.forEach((item, i) => {
2102
+ if (i > 0) {
2103
+ if (chip) {
2104
+ line.push(seg(' ', 'dim'))
2105
+ x += 1
2106
+ } else {
2107
+ line.push(seg(' · ', 'dim'))
2108
+ x += 3
2109
+ }
2110
+ }
2111
+ push(item.text, item.action, chip, false)
2112
+ })
2113
+ nav.forEach((item) => {
2114
+ line.push(seg(' · ', 'dim'))
2115
+ x += 3
2116
+ push(item.text, item.action, false, chip)
2117
+ })
2118
+ // P123: the focused card's demoted pair rides the free width the chips leave — right-aligned,
2119
+ // dim, no hit target (data, not an affordance). The agent drops before the phase, and the pair
2120
+ // disappears before it could push a documented chip out (the chips were laid out first).
2121
+ const pair = demotedPair(ctx)
2122
+ if (pair) {
2123
+ const free = width - x
2124
+ const text = dispWidth(pair.full) <= free ? pair.full : dispWidth(pair.phase) <= free ? pair.phase : ''
2125
+ if (text) {
2126
+ line.push(seg(' '.repeat(free - dispWidth(text)), 'dim'), seg(text, 'dim'))
2127
+ x += free
2128
+ }
2129
+ }
2130
+ return { id: 'keys', full: true, priority: 99, lines: [placedWithHits(ln(seg(' '), ...line), hits, width)], separator: 'none' }
2131
+ }
2132
+
2133
+ function pageTabsBlock(ctx: Ctx): Block | null {
2134
+ if (!ctx.view.tui) return null
2135
+ const { s } = ctx
2136
+ const line: Line = []
2137
+ const hits: Hit[] = []
2138
+ let x = 1
2139
+ const tabs: { page: PageId; text: string }[] = [
2140
+ { page: 1, text: s.pageOverview },
2141
+ { page: 2, text: s.pageWork },
2142
+ { page: 3, text: s.pageMessages },
2143
+ { page: 4, text: s.pageBoard },
2144
+ ]
2145
+ const boxed = isFramed(ctx)
2146
+ for (const tab of tabs) {
2147
+ const active = ctx.view.page === tab.page
2148
+ const text = active
2149
+ ? boxed
2150
+ ? `[${tab.text}]`
2151
+ : fill(s.pageTabActive, { name: tab.text })
2152
+ : fill(s.pageTab, { name: tab.text })
2153
+ const start = x
2154
+ line.push(seg(text, active ? 'accent' : 'dim'))
2155
+ x += dispWidth(text)
2156
+ hits.push({ start, end: x, action: { kind: 'page', page: tab.page } })
2157
+ line.push(seg(' '))
2158
+ x += 1
2159
+ }
2160
+ return { id: 'tabs', full: true, priority: 0.5, lines: [placedWithHits(ln(seg(' '), ...line), hits, ctx.width)], separator: 'none' }
2161
+ }
2162
+
2163
+ function overlayPrefs(ctx: Ctx): { pref: string; label: string; value: string }[] {
2164
+ const { s, input } = ctx
2165
+ const st = input.view
2166
+ return [
2167
+ { pref: 'lang', label: s.prefLang, value: st.lang === 'zh' ? s.langNameZh : s.langNameEn },
2168
+ { pref: 'defaultPage', label: s.prefDefaultPage, value: pageName(st.page, s) },
2169
+ { pref: 'activity', label: s.prefActivity, value: input.activity ? s.toggleOn : s.toggleOff },
2170
+ { pref: 'mouse', label: s.prefMouse, value: st.mouseOn ? s.toggleOn : s.toggleOff },
2171
+ { pref: 'density', label: s.prefDensity, value: st.density === 'compact' ? s.densityCompact : s.densityComfortable },
2172
+ // P22/B2: the overlay's one navigation row — not a preference: it opens the project-settings
2173
+ // view, changes no preference and writes no file (the MODIFIED settings requirement).
2174
+ { pref: '', label: s.prefProjectSettings, value: s.prefNavArrow },
2175
+ ]
2176
+ }
2177
+
2178
+ function pageName(page: PageId, s: Strings): string {
2179
+ return page === 1 ? s.pageOverview : page === 2 ? s.pageWork : page === 3 ? s.pageMessages : s.pageBoard
2180
+ }
2181
+
2182
+ /** The overlay's cursor column (` › ` / ` `) and the separator that keeps the two columns apart. */
2183
+ const OVERLAY_CURSOR_W = 4
2184
+ const OVERLAY_GAP_W = 2
2185
+ /** `│ ` + ` │`: the border and padding the comfortable card chrome adds around a block's rows. */
2186
+ const OVERLAY_CHROME_W = 4
2187
+
2188
+ /**
2189
+ * The settings overlay's column plan. The key column is `OVERLAY_LABEL_W` — the widest of the five
2190
+ * labels in *either* language — so zh and en put their values in the same column, and the two
2191
+ * columns are separated by a real gap instead of the key cell ending exactly where the value
2192
+ * starts (V16's user report: `default pageoverview` and `activity co…on` came from a hardcoded
2193
+ * 12-cell key cell with no separator). Degradation: below the full plan the key column shrinks
2194
+ * first — a key that does not fit is cut with `…` and still keeps the gap — while the value keeps
2195
+ * at least one column of its own. The plan budgets for the card chrome (the comfortable framed
2196
+ * style draws a border and a one-column padding on each side), so the frame's own truncation never
2197
+ * eats the value column at narrow widths.
2198
+ */
2199
+ function overlayCols(ctx: Ctx): { keyW: number; valueW: number } {
2200
+ const avail = Math.max(1, ctx.width - (isFramed(ctx) ? OVERLAY_CHROME_W : 0))
2201
+ const keyW = Math.max(1, Math.min(OVERLAY_LABEL_W, avail - OVERLAY_CURSOR_W - OVERLAY_GAP_W - 1))
2202
+ return { keyW, valueW: Math.max(1, avail - OVERLAY_CURSOR_W - keyW - OVERLAY_GAP_W) }
2203
+ }
2204
+
2205
+ function overlayBlock(ctx: Ctx): Block {
2206
+ const { s, width } = ctx
2207
+ const prefs = overlayPrefs(ctx)
2208
+ const { keyW, valueW } = overlayCols(ctx)
2209
+ const lines: PlacedLine[] = []
2210
+ prefs.forEach((p, i) => {
2211
+ const row = ln(
2212
+ seg(` ${i === ctx.view.overlayIndex ? s.settingsCursor : ' '} `, 'accent'),
2213
+ seg(cell(p.label, keyW), 'heading'),
2214
+ seg(' '.repeat(OVERLAY_GAP_W)),
2215
+ seg(truncateW(p.value, valueW)),
2216
+ )
2217
+ lines.push(
2218
+ placedWithHits(
2219
+ row,
2220
+ ctx.view.tui
2221
+ ? [
2222
+ {
2223
+ start: 2,
2224
+ end: 2 + dispWidth(textOf(row)),
2225
+ action: p.pref ? { kind: 'toggle', pref: p.pref as PrefName } : { kind: 'settings-open-view' },
2226
+ },
2227
+ ]
2228
+ : undefined,
2229
+ width,
2230
+ ),
2231
+ )
2232
+ })
2233
+ lines.push({ line: ln(seg('')) })
2234
+ lines.push({ line: truncLine(ln(seg(` ${s.settingsHint}`, 'dim')), width) })
2235
+ return { id: 'overlay', title: s.settingsTitle, full: true, priority: 0, lines, separator: 'none' }
2236
+ }
2237
+
2238
+ // ------------------------------------------------------------------ assembly
2239
+
2240
+ function pageDefinitions(ctx: Ctx): Block[] {
2241
+ const left = (): Ctx => (ctx.twoColumn ? { ...ctx, width: ctx.leftWidth } : ctx)
2242
+ const right = (): Ctx => (ctx.twoColumn ? { ...ctx, width: ctx.rightWidth } : ctx)
2243
+ const blocks: (Block | null)[] = [titleBlock(ctx), pageTabsBlock(ctx)]
2244
+ // P22/B2: the project-settings view replaces the page's blocks; the overlay it was opened from
2245
+ // stays behind it, so `esc` lands back on that overlay row. Title band, tabs and key band stay.
2246
+ if (ctx.view.settings) {
2247
+ const settings = settingsBlock(ctx)
2248
+ return [...blocks.filter((b): b is Block => b !== null), ...(settings ? [settings] : []), keyBandBlock(ctx)]
2249
+ }
2250
+ if (ctx.view.overlay) return [...blocks.filter((b): b is Block => b !== null), overlayBlock(ctx), keyBandBlock(ctx)]
2251
+ switch (ctx.view.page) {
2252
+ case 1:
2253
+ blocks.push(
2254
+ statusBlock(ctx),
2255
+ capacityBlock(ctx),
2256
+ progressBlock(ctx),
2257
+ deliveriesBlock(ctx),
2258
+ agentsBlock(left()),
2259
+ eventsBlock(right()),
2260
+ recentBlock(right()),
2261
+ )
2262
+ break
2263
+ case 2:
2264
+ // The detail view replaces the work page's blocks exactly as it replaces the kanban's.
2265
+ blocks.push(
2266
+ ctx.view.detail ? detailBlock(ctx) : boardBlock(left()),
2267
+ ...(ctx.view.detail ? [] : [changesBlock(right()), specsBlock(right()), decisionsBlock(right())]),
2268
+ )
2269
+ break
2270
+ case 3:
2271
+ blocks.push(queueBlock(left()), inboxBlock(right()), patrolBlock(right()), trendBlock(right()), healthBlock(right()))
2272
+ break
2273
+ case 4:
2274
+ // The detail view replaces the kanban's blocks (the title band, tabs and key band stay).
2275
+ blocks.push(ctx.view.detail ? detailBlock(ctx) : kanbanBlock(ctx))
2276
+ break
2277
+ default:
2278
+ blocks.push(queueBlock(left()), inboxBlock(right()), patrolBlock(right()), trendBlock(right()), healthBlock(right()))
2279
+ break
2280
+ }
2281
+ blocks.push(keyBandBlock(ctx))
2282
+ return blocks.filter((b): b is Block => b !== null)
2283
+ }
2284
+
2285
+ function separatorFor(block: Block, density: Density): PlacedLine[] {
2286
+ if (!block.separator || block.separator === 'none') return []
2287
+ if (block.separator === 'blank') return density === 'comfortable' ? [{ line: [] }] : []
2288
+ return []
2289
+ }
2290
+
2291
+ /**
2292
+ * Build the frame. `height <= 0` means "no cap" (the `--print` path without geometry overrides).
2293
+ * Every row is ≤ `width` columns, the array is ≤ `height` rows, and the footer (the key band) is
2294
+ * always the last row unless even one row does not fit.
2295
+ */
2296
+ export function layout(input: LayoutInput): Frame {
2297
+ const width = Math.max(1, Math.floor(input.width) || 1)
2298
+ const height = Math.floor(input.height) || 0
2299
+ const minimal = width < WIDTH_MINIMAL
2300
+ const twoColumn = width >= WIDTH_TWO_COMPACT
2301
+ const wide = width >= WIDTH_TWO_WIDE
2302
+ const leftWidth = twoColumn ? Math.max(16, Math.floor((width - COLUMN_GAP) * (wide ? LEFT_SHARE_WIDE : LEFT_SHARE_COMPACT))) : width
2303
+ const rightWidth = twoColumn ? Math.max(8, width - leftWidth - COLUMN_GAP) : width
2304
+ const ctx: Ctx = {
2305
+ s: input.strings,
2306
+ input,
2307
+ width,
2308
+ minimal,
2309
+ compact: input.view.density === 'compact',
2310
+ twoColumn,
2311
+ leftWidth,
2312
+ rightWidth,
2313
+ deg: new Set(input.degraded ?? []),
2314
+ panel: input.panel,
2315
+ blocks: input.blocks ?? {},
2316
+ view: input.view,
2317
+ activity: input.activityBlocks ?? [],
2318
+ }
2319
+
2320
+ const blocks = pageDefinitions(ctx)
2321
+ const title = blocks.find((b) => b.id === 'title') ?? blocks[0]
2322
+ const footer = blocks[blocks.length - 1]
2323
+ const middle = blocks.slice(1, -1)
2324
+
2325
+ const rows: PlacedLine[] = []
2326
+ const add = (lines: PlacedLine[]): void => {
2327
+ for (const l of lines) rows.push(l)
2328
+ }
2329
+
2330
+ add(title.lines)
2331
+
2332
+ const budget = height > 0 ? Math.max(0, height - title.lines.length - footer.lines.length) : Number.POSITIVE_INFINITY
2333
+
2334
+ const fullBlocks = middle.filter((b) => b.full)
2335
+ const leftBlocks = middle.filter((b) => !b.full && !b.right)
2336
+ const rightBlocks = middle.filter((b) => !b.full && b.right)
2337
+
2338
+ const framed = isFramed(ctx)
2339
+ let boardOrder: FocusRef[] | undefined
2340
+ const place = (block: Block, remaining: number, colWidth: number): PlacedLine[] => {
2341
+ const kind = pickChrome(block, remaining, framed)
2342
+ if (kind === null) return []
2343
+ if (kind === 'summary') return [summaryLine(block, colWidth)]
2344
+ // The order is only reported for a block that really draws its rows: a block degraded to its
2345
+ // summary line has no row to focus (P20/B5).
2346
+ if (block.order) boardOrder = block.order
2347
+ return wrapBlock(block, colWidth, kind)
2348
+ }
2349
+
2350
+ const fullRows: PlacedLine[] = []
2351
+ let laneWindows: LaneWindow[] | undefined
2352
+ let detailWindow: DetailWindow | undefined
2353
+ let settingsWindow: SettingsWindow | undefined
2354
+ for (const b of fullBlocks) {
2355
+ // The board page's lanes are told how many rows they may use (the frame is bounded): the lane
2356
+ // windows then grow with the pane instead of showing blank card space (the bounded-frame rule).
2357
+ const block =
2358
+ // A lane column is `THREE` rows taller than its card slots (title + bottom + marker slots), so
2359
+ // the budget handed over is what is left minus that chrome — otherwise the block overflows and
2360
+ // degrades to its one-line summary.
2361
+ height > 0 && b.id === 'kanban'
2362
+ ? (kanbanBlock({ ...ctx, laneRows: Math.max(1, budget - fullRows.length - LANE_MARKER_SLOTS - LANE_CHROME_ROWS) }) ?? b)
2363
+ : // The detail view spends the same budget on document rows: more pane = more of the file.
2364
+ height > 0 && b.id === 'detail'
2365
+ ? (detailBlock({ ...ctx, detailRows: Math.max(2, budget - fullRows.length - (framed ? 2 : 0)) }) ?? b)
2366
+ : height > 0 && b.id === 'settings'
2367
+ ? (settingsBlock({ ...ctx, settingsRows: Math.max(3, budget - fullRows.length - (framed ? 2 : 0)) }) ?? b)
2368
+ : b
2369
+ if (block.id === 'kanban' && block.lanes) laneWindows = block.lanes
2370
+ if (block.id === 'detail' && block.detail) detailWindow = block.detail
2371
+ if (block.id === 'settings' && block.settings) settingsWindow = block.settings
2372
+ const chunk = place(block, budget - fullRows.length, width)
2373
+ for (const l of chunk) fullRows.push(l)
2374
+ }
2375
+ add(fullRows)
2376
+
2377
+ const bodyBudget = budget === Number.POSITIVE_INFINITY ? Number.POSITIVE_INFINITY : Math.max(0, budget - fullRows.length)
2378
+ if (bodyBudget > 0) {
2379
+ if (twoColumn) {
2380
+ const leftW = leftWidth
2381
+ const rightW = rightWidth
2382
+ // One placement pass over the page's body blocks; `cards` is re-derived so pass 2 can carry a
2383
+ // board with more history visible.
2384
+ const placeColumns = (cards: Block[]): [PlacedLine[], PlacedLine[]] => {
2385
+ const columns: [PlacedLine[], PlacedLine[]] = [[], []]
2386
+ const ordered = [
2387
+ ...cards.filter((b) => !b.right).map((b) => ({ b, slot: 0 as 0 | 1 })),
2388
+ ...cards.filter((b) => b.right).map((b) => ({ b, slot: 1 as 0 | 1 })),
2389
+ ].sort((x, y) => x.b.priority - y.b.priority)
2390
+ for (const { b, slot } of ordered) {
2391
+ const colW = slot === 0 ? leftW : rightW
2392
+ // The body budget is **per column** (P18.1): the two columns stack side by side, so a tall
2393
+ // left card (the board's B1 growth fills the whole body height) used to consume the right
2394
+ // column's budget as well — its cards got `remaining = 0` and vanished, although the frame
2395
+ // had a full column of empty width. `pickChrome` keeps every column within `bodyBudget`, so
2396
+ // the flush below still ends both columns on the same row.
2397
+ const used = columns[slot].length
2398
+ const chunk = place(b, bodyBudget - used, colW)
2399
+ for (const l of chunk) columns[slot].push(l)
2400
+ }
2401
+ return columns
2402
+ }
2403
+ let bodyCards: Block[] = [...leftBlocks, ...rightBlocks]
2404
+ let columns = placeColumns(bodyCards)
2405
+ if (height > 0) {
2406
+ // The board's folded history relaxes into the column's allotment (the flush bottom): the
2407
+ // spare height shows real rows instead of blank card space. Only when the frame is bounded
2408
+ // — the uncapped `--print` path keeps its pre-console shape byte for byte.
2409
+ const board = bodyCards.find((b) => b.id === 'board')
2410
+ const folded = board ? boardFoldedRows(ctx) : 0
2411
+ const boardSlot: 0 | 1 = board?.right ? 1 : 0
2412
+ // B1: the relax is bounded by the *available* body height, not by the neighbour column's
2413
+ // height — otherwise a taller pane grows nothing and the spare becomes blank card space.
2414
+ const target = Math.max(columns[0].length, Math.max(columns[1].length, bodyBudget))
2415
+ const extra = Math.min(folded, Math.max(0, target - columns[boardSlot].length))
2416
+ if (board && extra > 0) {
2417
+ const grown = boardBlock({ ...ctx, width: board.right ? rightW : leftW, boardDoneKeep: Math.max(1, ctx.boardDoneKeep ?? BOARD_DONE_KEEP) + extra })
2418
+ if (grown) {
2419
+ bodyCards = bodyCards.map((b) => (b === board ? grown : b))
2420
+ columns = placeColumns(bodyCards)
2421
+ }
2422
+ }
2423
+ // Flush the two column bottoms: a column shorter than its neighbour grows its *last* card
2424
+ // (blank content area), so the body ends on one row instead of trailing blank page. Only
2425
+ // cards can be grown; a degraded chrome (`rule`/`summary`) keeps its natural height and the
2426
+ // merge below pads it as before.
2427
+ const flush = Math.max(columns[0].length, columns[1].length)
2428
+ for (const slot of [0, 1] as const) {
2429
+ const col = columns[slot]
2430
+ const colW = slot === 0 ? leftW : rightW
2431
+ const slack = flush - col.length
2432
+ const last = col[col.length - 1]
2433
+ if (slack <= 0 || !last) continue
2434
+ if (textOf(last.line) !== textOf(cardBottom(colW))) continue
2435
+ col.pop()
2436
+ for (let i = 0; i < slack; i++) col.push(cardBody({ line: [] }, colW))
2437
+ col.push(last)
2438
+ }
2439
+ }
2440
+ const bodyRows = Math.min(bodyBudget, Math.max(columns[0].length, columns[1].length))
2441
+ for (let i = 0; i < bodyRows; i++) {
2442
+ const l = columns[0][i]
2443
+ const r = columns[1][i]
2444
+ if (l && r) {
2445
+ const merged: PlacedLine = {
2446
+ line: [...padLine(l.line, leftW), seg(' '), ...r.line].map((sg) => ({ ...sg })),
2447
+ hits: [
2448
+ ...(l.hits ?? []),
2449
+ ...(r.hits ?? []).map((h) => ({ ...h, start: h.start + leftW + COLUMN_GAP, end: h.end + leftW + COLUMN_GAP })),
2450
+ ],
2451
+ }
2452
+ rows.push(merged)
2453
+ } else if (l) rows.push(l)
2454
+ else if (r) rows.push({ line: [seg(' '.repeat(leftW + COLUMN_GAP)), ...r.line], hits: (r.hits ?? []).map((h) => ({ ...h, start: h.start + leftW + COLUMN_GAP, end: h.end + leftW + COLUMN_GAP })) })
2455
+ }
2456
+ } else {
2457
+ const columnW = width
2458
+ let used = 0
2459
+ const ordered = [...leftBlocks, ...rightBlocks].sort((x, y) => x.priority - y.priority)
2460
+ for (const b of ordered) {
2461
+ const chunk = place(b, bodyBudget - used, columnW)
2462
+ for (const l of chunk) rows.push({ line: truncLine(l.line, columnW), hits: l.hits })
2463
+ used += chunk.length
2464
+ }
2465
+ if (height > 0) {
2466
+ // B1: the single-column tiers get the two-column flush bottom too — the spare height grows
2467
+ // the *last card's* blank content area, so a single-column page ends on one row instead of
2468
+ // trailing blank page. Only a card can grow; any remainder is filled by the assembly below.
2469
+ const spare = Math.max(0, height - footer.lines.length - rows.length)
2470
+ const last = rows[rows.length - 1]
2471
+ if (spare > 0 && last && textOf(last.line) === textOf(cardBottom(columnW))) {
2472
+ rows.pop()
2473
+ for (let i = 0; i < spare; i++) rows.push(cardBody({ line: [] }, columnW))
2474
+ rows.push(last)
2475
+ }
2476
+ }
2477
+ }
2478
+ }
2479
+
2480
+ // The work page's row chips are rebuilt after placement: they exist only while the board block
2481
+ // really draws rows, so a degraded work page has no clickable row key that cannot open anything
2482
+ // (P20/B5). Both variants are one line, so the budget above is unaffected.
2483
+ const footerShown =
2484
+ ctx.view.page === 2 && !ctx.view.detail && !ctx.view.overlay && !boardOrder ? keyBandBlock(ctx, false) : footer
2485
+
2486
+ // The footer is the last row; when the height cannot even hold it, it is the only row kept.
2487
+ if (height > 0 && rows.length + footerShown.lines.length > height) {
2488
+ const room = Math.max(0, height - footerShown.lines.length)
2489
+ rows.length = Math.min(rows.length, room)
2490
+ }
2491
+ // B1 (the bounded-frame red line): a bounded frame fills its height. Whatever the content did not
2492
+ // naturally use becomes blank *content* rows directly above the footer, so the key band is the
2493
+ // frame's last row and no blank row follows it. The uncapped `--print` path (height <= 0) never
2494
+ // reaches this branch, so its bytes stay identical.
2495
+ if (height > 0 && rows.length + footerShown.lines.length < height) {
2496
+ const spare = height - footerShown.lines.length - rows.length
2497
+ for (let i = 0; i < spare; i++) rows.push({ line: [] })
2498
+ }
2499
+ add(footerShown.lines)
2500
+
2501
+ const trimmed = rows.slice(0, height > 0 ? height : rows.length)
2502
+ const targets: { row: number; hit: Hit }[] = []
2503
+ const renderedRows = trimmed.map((l, i) => {
2504
+ if (l.hits?.length) {
2505
+ // The same clipping as placedWithHits, for rows only this final pass cuts (merged
2506
+ // two-column rows and builder lines that were never truncated): a target that reaches the
2507
+ // rendered ellipsis is invisible and must not fire (V15/F4).
2508
+ const room = widthOf(l.line) > width ? Math.max(0, width - 1) : width
2509
+ for (const h of l.hits) {
2510
+ const start = Math.min(h.start, room)
2511
+ const end = Math.min(h.end, room)
2512
+ if (end > start) targets.push({ row: i, hit: { ...h, start, end } })
2513
+ }
2514
+ }
2515
+ return truncLine(l.line, width)
2516
+ })
2517
+ return {
2518
+ rows: renderedRows,
2519
+ targets,
2520
+ ...(laneWindows ? { lanes: laneWindows } : {}),
2521
+ ...(detailWindow ? { detail: detailWindow } : {}),
2522
+ ...(settingsWindow ? { settings: settingsWindow } : {}),
2523
+ ...(boardOrder ? { boardOrder } : {}),
2524
+ }
2525
+ }
2526
+
2527
+ function add2(into: PlacedLine[], a: PlacedLine[], b: PlacedLine[]): void {
2528
+ for (const l of a) into.push(l)
2529
+ for (const l of b) into.push(l)
2530
+ }
2531
+
2532
+ /** One plain-text frame (the `--print` contract: no escape sequence, no color). */
2533
+ /** The row's content key: identical keys mean the row would render identically. */
2534
+ export function rowKey(line: Line): string {
2535
+ let key = ''
2536
+ for (const s of line) key += `${s.tone}\u0000${s.text}\u0001`
2537
+ return key
2538
+ }
2539
+
2540
+ export function renderPlain(frame: Frame): string[] {
2541
+ return frame.rows.map((line) => textOf(line).replace(/\s+$/, ''))
2542
+ }
2543
+
2544
+ /** One frame with the theme's SGR sequences; deterministic, so the snapshot suite can pin it. */
2545
+ export function renderAnsi(frame: Frame, palette: Palette, opts: { color?: boolean; truecolor?: boolean } = {}): string[] {
2546
+ const color = opts.color !== false
2547
+ const truecolor = opts.truecolor !== false
2548
+ if (!color) return renderPlain(frame)
2549
+ return frame.rows.map((line) =>
2550
+ line
2551
+ .map((s) => {
2552
+ if (!s.text) return s.text
2553
+ return `\u001b[${toneSgr(s.tone, palette, truecolor)}m${s.text}\u001b[0m`
2554
+ })
2555
+ .join(''),
2556
+ )
2557
+ }
2558
+
2559
+ /** One JSON object with the panel fields plus the untouched activity blocks. */
2560
+ export function buildJson(input: FrameInput, refreshS: number): Record<string, unknown> {
2561
+ return { panel: { ...input.panel, refresh_s: refreshS }, activity: input.activity ? input.activityBlocks : [] }
2562
+ }