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,894 @@
1
+ // teamsmith pulse panel — the Ink front end over the data layer.
2
+ //
3
+ // panel.js [--root DIR] [--print | --json | --once] [--width N] [--height N]
4
+ // [--activity | --no-activity] [--events N] [--refresh N] [--no-pulse] [--version]
5
+ // [--headless] [--snapshot] [--palette] [--theme dark|light] [--page 1|2|3|4] [--lang zh|en]
6
+ // [--overlay] [--detail ID]
7
+ //
8
+ // Modes (the `panel` contract):
9
+ // --print one plain-text frame (the overview), no escape sequence, writes nothing, never ticks
10
+ // --json {"panel": {...}, "activity": [...]}, writes nothing, never ticks
11
+ // --once one frame through the renderer selection, keeps today's tick semantics
12
+ // (default) the TUI in a terminal; stdout not a TTY selects the plain-text path unless
13
+ // TEAM_MONITOR_UI=tui forces the renderer
14
+ // --headless the tick loop only (no renderer) — the shape the console collapses into
15
+ // --snapshot one themed frame with SGR bytes (the snapshot suite's deterministic exit);
16
+ // `--overlay` opens the settings overlay in that frame (the overlay's column plan)
17
+ // --palette the declared palettes + their contrast pairs as JSON (the gate script's input)
18
+ //
19
+ // Everything on screen comes from `team __panel-data`; the tick is `team watch --once`.
20
+ // `--print`/`--json` never read `state/panel.conf` or the page file: the machine exits are frozen.
21
+
22
+ import React from 'react'
23
+ import { writeSync, appendFileSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'
24
+ import { Writable } from 'node:stream'
25
+ import { spawn } from 'node:child_process'
26
+ import { homedir } from 'node:os'
27
+ import { dirname, join } from 'node:path'
28
+ import { render } from 'ink'
29
+ import chalk from 'chalk'
30
+ import { App, frameSignature } from './App.js'
31
+ import type { PanelApi } from './App.js'
32
+ import { clockOf } from './format.js'
33
+ import { dispWidth } from './width.js'
34
+ import type { Palette } from './theme.js'
35
+ import type { Segment } from './types.js'
36
+ import { BLOCK_NAMES, MACHINE_BLOCKS, cleanIdentityEnv, createPanelCache, findTeamCli, loadPanelData, panelDirOf, runTick } from './data.js'
37
+ import type { DataOptions, DataResult, PanelCache } from './data.js'
38
+ import { normalizeNewlines, parseSendResult, mapReceipt, DRAFT_FILE } from './compose.js'
39
+ import type { Receipt } from './compose.js'
40
+ import { createClipboardRunner, readClipboard, writePasteFile } from './clipboard.js'
41
+ import { buildJson, layout, renderAnsi, renderPlain } from './layout.js'
42
+ import type { LayoutInput } from './layout.js'
43
+ import { fill, stringsFor } from './strings/index.js'
44
+ import { PANEL_CONF_FILE, PANEL_PAGE_FILE, readPage, readSettings, writePage, writeSettings } from './settings.js'
45
+ import type { Settings } from './settings.js'
46
+ import { contrastPairs, PALETTES, resolveTheme } from './theme.js'
47
+ import type { FrameInput, PageId, ViewState } from './types.js'
48
+
49
+ /** The Kitty keyboard protocol's pop/push pair, written around the editor handoff (design §6). */
50
+ const KITTY_POP = '\u001b[<u'
51
+ const KITTY_PUSH = '\u001b[>1u'
52
+
53
+ declare const __PIN_INK__: string | undefined
54
+ declare const __PIN_REACT__: string | undefined
55
+ declare const __BUILD_CMD__: string | undefined
56
+
57
+ const PANEL_VERSION = '1.0.0'
58
+ const PIN_INK = typeof __PIN_INK__ === 'undefined' ? 'dev' : __PIN_INK__
59
+ const PIN_REACT = typeof __PIN_REACT__ === 'undefined' ? 'dev' : __PIN_REACT__
60
+ const BUILD_CMD =
61
+ typeof __BUILD_CMD__ === 'undefined'
62
+ ? 'bun install --frozen-lockfile && bash skills/teamsmith/scripts/panel/build.sh'
63
+ : __BUILD_CMD__
64
+
65
+ /**
66
+ * Ink's own cursor bookkeeping assumes a frame that ends with a newline, but the console fills the
67
+ * pane (the bounded frame pads to the terminal height), so Ink writes a fullscreen frame with no
68
+ * trailing newline and its `useCursor` lands one row high; its cursor-only path (an arrow key that
69
+ * moves the point without changing the text) then drifts upward a row per move (measured on the
70
+ * pinned ink 7.1.1). This stream forwards every Ink write to the real stdout and re-asserts the
71
+ * insertion point absolutely (CUP is 1-based) in the same write call — the one place that also
72
+ * sees Ink's throttled frames. `null` means "not composing": the cursor is hidden.
73
+ */
74
+ function cursorAwareStdout(base: NodeJS.WriteStream, cursorOf: () => { x: number; y: number } | null): NodeJS.WriteStream {
75
+ const out = new Writable({
76
+ write(chunk: Buffer | string, _encoding: BufferEncoding, callback: (error?: Error | null) => void) {
77
+ const pos = cursorOf()
78
+ const suffix = pos ? `\u001b[?25h\u001b[${pos.y + 1};${pos.x + 1}H` : '\u001b[?25l'
79
+ try {
80
+ base.write(typeof chunk === 'string' ? chunk + suffix : Buffer.concat([chunk, Buffer.from(suffix)]))
81
+ } catch {
82
+ /* a closed stdout must not kill the panel */
83
+ }
84
+ callback()
85
+ },
86
+ }) as unknown as NodeJS.WriteStream
87
+ ;(out as { isTTY?: boolean }).isTTY = Boolean(base.isTTY)
88
+ Object.defineProperty(out, 'columns', { get: () => process.stdout.columns })
89
+ Object.defineProperty(out, 'rows', { get: () => process.stdout.rows })
90
+ return out
91
+ }
92
+
93
+ function argOf(name: string): string | undefined {
94
+ const i = process.argv.indexOf(`--${name}`)
95
+ if (i === -1) return undefined
96
+ const v = process.argv[i + 1]
97
+ return v && !v.startsWith('--') ? v : undefined
98
+ }
99
+
100
+ const has = (name: string): boolean => process.argv.includes(`--${name}`)
101
+
102
+ /** Machine-readable output must not be lost to an async pipe write. */
103
+ function out(text: string): void {
104
+ writeSync(1, text)
105
+ }
106
+ function fail(message: string): never {
107
+ writeSync(2, `✗ ${message}\n`)
108
+ process.exit(1)
109
+ }
110
+
111
+ const root = argOf('root') || process.cwd()
112
+ const teamCli = argOf('team-cli') || findTeamCli(panelDirOf(import.meta.url)) || undefined
113
+ const events = Number(argOf('events') ?? 4) || 4
114
+ const refresh = Math.max(1, Number(argOf('refresh') ?? 3) || 3)
115
+ const tickEvery = Number(argOf('tick-every') ?? 0) || 0
116
+ const noPulse = has('no-pulse') || has('no-watchdog')
117
+ const once = has('once')
118
+ const wantJson = has('json')
119
+ const wantPrint = has('print')
120
+ const wantSnapshot = has('snapshot')
121
+ const wantOverlay = has('overlay')
122
+ const wantPalette = has('palette')
123
+ const headless = has('headless')
124
+ const widthArg = Number(argOf('width') ?? 0)
125
+ const heightArg = Number(argOf('height') ?? 0)
126
+ const ui = String(process.env.TEAM_MONITOR_UI || argOf('ui') || 'auto')
127
+ const noActivity = has('no-activity')
128
+ const yesActivity = has('activity')
129
+ const activityPinned = yesActivity || noActivity
130
+ const activityFlag = yesActivity ? true : noActivity ? false : null
131
+ const envActivity = String(process.env.TEAM_MONITOR_ACTIVITY ?? '1') !== '0'
132
+ const rawActivityOn = activityFlag ?? envActivity
133
+ const themeArg = argOf('theme')
134
+ const pageArg = argOf('page')
135
+ const langArg = argOf('lang')
136
+ /** `--detail <ID>`: render the read-only detail view in a snapshot (the overlay's sibling exit). */
137
+ const detailArg = argOf('detail') || ''
138
+
139
+ if (has('version')) {
140
+ out(`teamsmith panel ${PANEL_VERSION} · ink ${PIN_INK} · react ${PIN_REACT}\nbuilt by: ${BUILD_CMD}\n`)
141
+ process.exit(0)
142
+ }
143
+ if (has('help')) {
144
+ out(
145
+ 'usage: panel.js [--root DIR] [--state-dir DIR] [--print|--json|--once|--headless|--snapshot|--palette]\n' +
146
+ ' [--width N] [--height N] [--activity|--no-activity] [--events N] [--refresh N]\n' +
147
+ ' [--no-pulse] [--theme dark|light] [--page 1|2|3|4] [--lang zh|en] [--overlay] [--detail ID] [--version]\n',
148
+ )
149
+ process.exit(0)
150
+ }
151
+
152
+ // The console's own state files live in the project's state directory. The launcher passes it
153
+ // explicitly; the tick log path and the project root are the fallbacks, so a direct `panel.js`
154
+ // invocation still finds it.
155
+ const tickLogArg = argOf('tick-log') || ''
156
+ const stateDir = argOf('state-dir') || (tickLogArg ? dirname(tickLogArg) : join(root, '.pi/team/state'))
157
+ const draftFile = join(stateDir, DRAFT_FILE)
158
+ const confFile = join(stateDir, PANEL_CONF_FILE)
159
+ const pageFile = join(stateDir, PANEL_PAGE_FILE)
160
+
161
+ // M40 — the panel's identity is its own root (`--root`, else cwd), never an inherited `TEAM_*`.
162
+ // An inherited value that names another project is not honoured silently: one line before any frame
163
+ // is drawn (stderr = the pulse window, which is this long-running process's log) plus a durable line
164
+ // in the project's own state/panel.log. ASCII only: visible text belongs to the i18n tables and the
165
+ // CJK-literal gate covers the whole source tree.
166
+ const inheritedRoot = process.env.TEAM_ROOT
167
+ if (inheritedRoot) {
168
+ const envRoot = inheritedRoot.replace(/\/+$/, '')
169
+ if (envRoot && envRoot !== root.replace(/\/+$/, '')) {
170
+ const line = `! TEAM_IDENTITY_CONFLICT (panel): rendering --root/cwd='${root}', ignoring inherited TEAM_ROOT='${inheritedRoot}'\n`
171
+ try {
172
+ writeSync(2, line)
173
+ } catch {
174
+ /* a stderr that cannot be written must not kill the panel */
175
+ }
176
+ try {
177
+ mkdirSync(stateDir, { recursive: true })
178
+ appendFileSync(join(stateDir, 'panel.log'), `${new Date().toISOString()} ${line}`)
179
+ } catch {
180
+ /* a state directory that cannot be written must not kill the panel either */
181
+ }
182
+ }
183
+ }
184
+
185
+ type Mode = 'text' | 'json' | 'tui'
186
+ function pickMode(): Mode {
187
+ if (wantJson) return 'json'
188
+ if (wantPrint) return 'text'
189
+ if (ui === 'text') return 'text'
190
+ if (ui === 'tui') return 'tui'
191
+ return process.stdout.isTTY ? 'tui' : 'text'
192
+ }
193
+
194
+ const mode: Mode | 'snapshot' | 'palette' | 'headless' = wantPalette
195
+ ? 'palette'
196
+ : wantSnapshot
197
+ ? 'snapshot'
198
+ : headless
199
+ ? 'headless'
200
+ : pickMode()
201
+ const stdoutColumns = process.stdout.columns || 0
202
+ const stdoutRows = process.stdout.rows || 0
203
+
204
+ // ---------------------------------------------------------------- machine-only exits
205
+ if (mode === 'palette') {
206
+ out(
207
+ `${JSON.stringify(
208
+ {
209
+ palettes: PALETTES,
210
+ pairs: { dark: contrastPairs(PALETTES.dark), light: contrastPairs(PALETTES.light) },
211
+ },
212
+ null,
213
+ 2,
214
+ )}\n`,
215
+ )
216
+ process.exit(0)
217
+ }
218
+
219
+ // ---------------------------------------------------------------- the tick loop (owned here)
220
+ let lastTick = 0
221
+ const tickLog = argOf('tick-log') || `${root}/.pi/team/state/watchdog.tick.log`
222
+
223
+ function tickDue(): boolean {
224
+ if (noPulse || tickEvery <= 0) return false
225
+ const now = Date.now()
226
+ if (lastTick === 0 || now - lastTick >= tickEvery * 1000) {
227
+ lastTick = now
228
+ return true
229
+ }
230
+ return false
231
+ }
232
+
233
+ async function runTickIfDue(): Promise<void> {
234
+ if (!tickDue()) return
235
+ if (!teamCli) return
236
+ await runTick(teamCli, root, tickLog)
237
+ }
238
+
239
+ function frameOf(res: DataResult, activity: boolean, scroll?: number): FrameInput {
240
+ return {
241
+ panel: res.data ?? { project: '', timestamp: '', interval: 0 },
242
+ activityBlocks: activity ? res.activity ?? [] : [],
243
+ blocks: res.blocks ?? {},
244
+ degraded: res.degraded ?? [],
245
+ width: widthArg || stdoutColumns || 100,
246
+ height: heightArg || stdoutRows || 0,
247
+ activity,
248
+ }
249
+ }
250
+
251
+ /** A frame where every block failed is not a frame: fail loudly like the old data path did. */
252
+ function frameOrFail(res: DataResult, activity: boolean, wanted: readonly string[] = BLOCK_NAMES): FrameInput {
253
+ const allDown = wanted.every((name) => (res.degraded ?? []).includes(name as never))
254
+ if (!res.ok || !res.data || allDown) {
255
+ const first = res.error || Object.values(res.errors ?? {})[0] || 'panel: data read failed'
256
+ fail(res.error || `panel: every block failed (${first})`)
257
+ }
258
+ return frameOf(res, activity)
259
+ }
260
+
261
+ function defaultView(lang: string, page: PageId): ViewState {
262
+ return {
263
+ page,
264
+ density: 'comfortable',
265
+ lang,
266
+ mouseOn: false,
267
+ tui: false,
268
+ overlay: false,
269
+ overlayIndex: 0,
270
+ viewEntry: null,
271
+ scroll: 0,
272
+ detailIndex: 0,
273
+ detailScroll: 0,
274
+ }
275
+ }
276
+
277
+ /** The compose insertion point main.tsx's cursor-aware stdout re-asserts after every Ink write. */
278
+ let composeCursor: { x: number; y: number } | null = null
279
+
280
+ async function main(): Promise<void> {
281
+ if (mode === 'json') {
282
+ const res = await loadPanelData({ root, teamCli, activity: rawActivityOn, events, blocks: MACHINE_BLOCKS })
283
+ out(`${JSON.stringify(buildJson(frameOrFail(res, rawActivityOn, MACHINE_BLOCKS), refresh))}\n`)
284
+ process.exit(0)
285
+ }
286
+
287
+ if (mode === 'snapshot') {
288
+ // One themed frame, deterministic: the snapshot suite pins the tier × theme matrix through this
289
+ // exit. It is not `--print` (which must stay escape-free), so the SGR bytes are expected.
290
+ const settings = readSettings(confFile)
291
+ const themeName = themeArg === 'dark' || themeArg === 'light' ? themeArg : resolveTheme(settings.theme)
292
+ const lang = langArg === 'en' || langArg === 'zh' ? langArg : settings.lang
293
+ const page = pageArg === '1' || pageArg === '2' || pageArg === '3' || pageArg === '4' ? (Number(pageArg) as PageId) : settings.defaultPage
294
+ const res = await loadPanelData({ root, teamCli, activity: rawActivityOn, events, detailId: detailArg || null })
295
+ const frame = frameOrFail(res, rawActivityOn)
296
+ const view: ViewState = {
297
+ ...defaultView(lang, page),
298
+ tui: true,
299
+ mouseOn: settings.mouse,
300
+ density: settings.density,
301
+ overlay: wantOverlay,
302
+ detail: detailArg || null,
303
+ // P123: the snapshot is the TUI's own render path, so it reads the fold keys (the machine exits
304
+ // stay on `defaultView` and never look at them).
305
+ boardFold: settings.boardFold,
306
+ boardShow: settings.boardShow,
307
+ boardEmptyFold: settings.boardEmptyFold,
308
+ }
309
+ const themed = layout({
310
+ ...frame,
311
+ strings: stringsFor(lang),
312
+ height: heightArg || 0,
313
+ view,
314
+ } as LayoutInput)
315
+ if (has('targets')) {
316
+ // The click-target map of the same frame the snapshot renders: one entry per documented key
317
+ // (and per page tab / queue row). The gate asserts the set, so a key without a target fails.
318
+ out(`${JSON.stringify(themed.targets.map((t) => ({ row: t.row, action: t.hit.action })))}\n`)
319
+ process.exit(0)
320
+ }
321
+ out(`${renderAnsi(themed, PALETTES[themeName], { truecolor: true }).join('\n')}\n`)
322
+ process.exit(0)
323
+ }
324
+
325
+ if (mode === 'headless') {
326
+ // The tick loop with no renderer. `team monitor --headless` is the bash loop (lock + drift
327
+ // reexec); this branch serves a direct bundle invocation and keeps the same cadence.
328
+ for (;;) {
329
+ await runTickIfDue()
330
+ sleepSync(Math.max(1, tickEvery || refresh) * 1000)
331
+ }
332
+ }
333
+
334
+ if (mode === 'text') {
335
+ // `--page` is honoured here too (P123's machine-frame identity fixture renders page 4); absent,
336
+ // the machine frame stays the overview it always was.
337
+ const machinePage: PageId =
338
+ pageArg === '1' || pageArg === '2' || pageArg === '3' || pageArg === '4' ? (Number(pageArg) as PageId) : 1
339
+ if (once || wantPrint) {
340
+ // One frame; `--once` then keeps today's tick semantics, `--print` (the observer) never ticks.
341
+ const frame = frameOrFail(await loadPanelData({ root, teamCli, activity: rawActivityOn, events, blocks: MACHINE_BLOCKS }), rawActivityOn, MACHINE_BLOCKS)
342
+ const themed = layout({ ...frame, strings: stringsFor('zh'), view: defaultView('zh', machinePage) } as LayoutInput)
343
+ out(`${renderPlain(themed).join('\n')}\n`)
344
+ if (once) await runTickIfDue()
345
+ process.exit(0)
346
+ }
347
+ // Plain-text run: the old loop's semantics (a frame per TEAM_MONITOR_REFRESH, a tick per the
348
+ // tick period) with the control bytes removed — a redirected `team monitor` no longer clears the
349
+ // caller's output. One frame per iteration, no clear, never a TUI escape sequence.
350
+ for (;;) {
351
+ const frame = frameOrFail(await loadPanelData({ root, teamCli, activity: rawActivityOn, events, blocks: MACHINE_BLOCKS }), rawActivityOn, MACHINE_BLOCKS)
352
+ const themed = layout({ ...frame, strings: stringsFor('zh'), view: defaultView('zh', machinePage) } as LayoutInput)
353
+ out(`${renderPlain(themed).join('\n')}\n`)
354
+ await runTickIfDue()
355
+ sleepSync(Math.max(1, refresh) * 1000)
356
+ }
357
+ }
358
+
359
+ // TUI: the run owns the loop — one frame per TEAM_MONITOR_REFRESH, one tick per the tick period,
360
+ // no second window and no background worker. The data assembly is asynchronous and cached: a
361
+ // refresh in flight never delays a keystroke, and only the blocks whose TTL expired are rebuilt.
362
+ const settings = readSettings(confFile)
363
+ const effectiveLang = settings.lang
364
+ const s = stringsFor(effectiveLang)
365
+ const palette = PALETTES[resolveTheme(settings.theme)]
366
+ // Activity precedence inside the TUI: CLI flag > panel.conf > TEAM_MONITOR_ACTIVITY.
367
+ const activityOn = activityPinned ? rawActivityOn : settings.activity
368
+ const opts: DataOptions = { root, teamCli, activity: activityOn, events }
369
+ const cache: PanelCache = createPanelCache(opts)
370
+ const first = await cache.refresh({ force: true })
371
+ let current = frameOrFail(first, activityOn)
372
+ /** The signature of the frame Ink last drew; an unchanged frame must not repaint. */
373
+ let renderedSig = frameSignature(current)
374
+ let app: ReturnType<typeof render> | undefined
375
+ /** True while an external program (the editor relay) owns the terminal. */
376
+ let editorActive = false
377
+ let mouseEnabled = settings.mouse
378
+ const panelDir = panelDirOf(import.meta.url)
379
+ const clipRunner = createClipboardRunner()
380
+ const bridge = existsSync(join(panelDir, 'draft-send.sh'))
381
+ ? join(panelDir, 'draft-send.sh')
382
+ : join(panelDir, '..', 'draft-send.sh')
383
+ const page = readPage(pageFile, settings.defaultPage)
384
+
385
+ const panelElement = (): React.ReactElement =>
386
+ React.createElement(App, {
387
+ frame: current,
388
+ refresh,
389
+ reload,
390
+ once,
391
+ api,
392
+ settings,
393
+ page,
394
+ palette,
395
+ activityPinned,
396
+ })
397
+
398
+ const adopt = (res: DataResult): void => {
399
+ if (!res.ok || !res.data || BLOCK_NAMES.every((name) => (res.degraded ?? []).includes(name))) return
400
+ const next = frameOf(res, activityPinned ? rawActivityOn : opts.activity, current.height)
401
+ const sig = frameSignature(next)
402
+ const changed = sig !== renderedSig
403
+ current = next
404
+ renderedSig = sig
405
+ // The render callback is explicitly gated while `$EDITOR` owns the terminal: Ink must not
406
+ // touch the screen between the handoff and the editor's exit. A frame that did not change must
407
+ // not repaint either: Ink reconciles the whole element tree on `rerender`, and at a 3s cadence
408
+ // that alone is several times the console's CPU budget.
409
+ if (editorActive || !changed) return
410
+ try {
411
+ app?.rerender(panelElement())
412
+ } catch {
413
+ /* rerender is best effort; the next refresh redraws anyway */
414
+ }
415
+ }
416
+
417
+ const reload = (): FrameInput => {
418
+ void runTickIfDue()
419
+ void cache.refresh().then(adopt)
420
+ return current
421
+ }
422
+ const refreshNow = (): void => {
423
+ void cache.refresh({ force: true }).then(adopt)
424
+ }
425
+
426
+ // ---------------------------------------------------------------- the console's actions
427
+ function readDraft(): string {
428
+ try {
429
+ return normalizeNewlines(readFileSync(draftFile, 'utf8'))
430
+ } catch {
431
+ return ''
432
+ }
433
+ }
434
+ function writeDraft(text: string): void {
435
+ try {
436
+ mkdirSync(stateDir, { recursive: true })
437
+ writeFileSync(draftFile, String(text ?? ''))
438
+ } catch {
439
+ /* a state directory the console cannot write must not kill the panel */
440
+ }
441
+ }
442
+
443
+ /** Run one subprocess to completion; resolves with rc + combined output. Never throws. */
444
+ function run(
445
+ argv: string[],
446
+ env: NodeJS.ProcessEnv = process.env,
447
+ ): Promise<{ rc: number; out: string; err: string }> {
448
+ return new Promise((resolve) => {
449
+ let child: ReturnType<typeof spawn>
450
+ try {
451
+ child = spawn('bash', argv, { cwd: root, env: cleanIdentityEnv(env), stdio: ['ignore', 'pipe', 'pipe'] })
452
+ } catch (e) {
453
+ resolve({ rc: 127, out: '', err: (e as Error).message })
454
+ return
455
+ }
456
+ let stdout = ''
457
+ let stderr = ''
458
+ let settled = false
459
+ const timer = setTimeout(() => {
460
+ try {
461
+ child.kill('SIGKILL')
462
+ } catch {
463
+ /* already gone */
464
+ }
465
+ finish(124, 'timed out')
466
+ }, 120000)
467
+ const finish = (rc: number, tail: string): void => {
468
+ if (settled) return
469
+ settled = true
470
+ clearTimeout(timer)
471
+ if (tail) stderr = `${stderr}\n${tail}`
472
+ resolve({ rc, out: stdout, err: stderr })
473
+ }
474
+ child.stdout?.on('data', (d: Buffer) => {
475
+ stdout += String(d)
476
+ })
477
+ child.stderr?.on('data', (d: Buffer) => {
478
+ stderr += String(d)
479
+ })
480
+ child.on('error', (e) => finish(127, e.message))
481
+ child.on('close', (code) => finish(code ?? 1, ''))
482
+ })
483
+ }
484
+
485
+ /** First useful line of a command's output, for the one-line receipt. */
486
+ function firstLine(text: string): string {
487
+ const line = String(text ?? '')
488
+ .split('\n')
489
+ .map((l) => l.trim())
490
+ .find((l) => l.length > 0)
491
+ return line ?? ''
492
+ }
493
+
494
+ async function send(text: string): Promise<Receipt> {
495
+ writeDraft(text)
496
+ const res = await run([bridge, draftFile])
497
+ const parsed = parseSendResult(res.out)
498
+ const detail = firstLine(res.err)
499
+ if (!parsed) {
500
+ return { state: 'error', token: `rc=${res.rc} no-token`, detail: detail || s.sendUnconfirmed }
501
+ }
502
+ const receipt = mapReceipt(parsed.rc, parsed.outcome, parsed.result, detail)
503
+ refreshNow()
504
+ return receipt
505
+ }
506
+
507
+ async function flushQueue(): Promise<{ ok: boolean; line: string }> {
508
+ if (!teamCli) return { ok: false, line: `✗ ${s.noTeamCli}` }
509
+ const res = await run([teamCli, '--root', root, 'outbox', 'flush'])
510
+ const line = firstLine(res.err) || firstLine(res.out)
511
+ refreshNow()
512
+ return {
513
+ ok: res.rc === 0,
514
+ line: res.rc === 0 ? fill(s.flushOk, { detail: line }) : fill(s.flushFail, { detail: line }),
515
+ }
516
+ }
517
+
518
+ /**
519
+ * One `team config set` invocation (P22/B3): the console never opens the contract itself — it
520
+ * spawns the owning command and maps its exit code to an honest receipt in the App. `--dry-run`
521
+ * writes neither the contract nor an audit line (the validation call is a read).
522
+ */
523
+ async function setSetting(
524
+ key: string,
525
+ value: string,
526
+ o: { dryRun?: boolean; fingerprint?: string | null; allowDanger?: boolean },
527
+ ): Promise<{ code: number; line: string }> {
528
+ if (!teamCli) return { code: 127, line: s.noTeamCli }
529
+ const args = [teamCli, '--root', root, 'config', 'set', key, value, '--actor', 'panel']
530
+ if (o.dryRun) args.push('--dry-run')
531
+ else args.push('--yes')
532
+ if (o.fingerprint) args.push('--fingerprint', o.fingerprint)
533
+ if (o.allowDanger) args.push('--allow-danger')
534
+ const res = await run(args)
535
+ const line = firstLine(res.err) || firstLine(res.out)
536
+ // On a settle the view re-reads the settings block (the list and the audit footer) in the
537
+ // background; a validation changes nothing.
538
+ if (!o.dryRun) refreshSettingsSoon()
539
+ return { code: res.rc, line }
540
+ }
541
+
542
+ /** One `team config set-agent-model <seat> <model|->` invocation (P22/B4). */
543
+ async function setSeatModel(
544
+ seat: string,
545
+ model: string,
546
+ o: { dryRun?: boolean; fingerprint?: string | null },
547
+ ): Promise<{ code: number; line: string }> {
548
+ if (!teamCli) return { code: 127, line: s.noTeamCli }
549
+ const args = [teamCli, '--root', root, 'config', 'set-agent-model', seat, model || '-', '--actor', 'panel']
550
+ if (o.dryRun) args.push('--dry-run')
551
+ else args.push('--yes')
552
+ if (o.fingerprint) args.push('--fingerprint', o.fingerprint)
553
+ const res = await run(args)
554
+ const line = firstLine(res.err) || firstLine(res.out)
555
+ if (!o.dryRun) refreshSettingsSoon()
556
+ return { code: res.rc, line }
557
+ }
558
+
559
+ /**
560
+ * The background half of a settle (M65/D11): rebuild only the settings block and adopt it when
561
+ * it lands. Nothing on the interaction path awaits this — the receipt was drawn from the
562
+ * command's own result, and this read only refreshes what the next interaction sees.
563
+ */
564
+ function refreshSettingsSoon(): void {
565
+ void cache.refresh({ force: true, only: ['settings'] }).then(adopt)
566
+ }
567
+
568
+ async function setStandby(on: boolean, reason: string): Promise<{ ok: boolean; line: string }> { if (!teamCli) return { ok: false, line: `✗ ${s.noTeamCli}` }
569
+ const args = on
570
+ ? [teamCli, '--root', root, 'standby', 'on', '--reason', reason || '-']
571
+ : [teamCli, '--root', root, 'standby', 'off']
572
+ const res = await run(args)
573
+ const line = firstLine(res.err) || firstLine(res.out)
574
+ refreshNow()
575
+ return {
576
+ ok: res.rc === 0,
577
+ line:
578
+ res.rc === 0
579
+ ? on
580
+ ? fill(s.standbyOkOn, { reason: reason || '-' })
581
+ : s.standbyOkOff
582
+ : fill(s.standbyFail, { detail: line }),
583
+ }
584
+ }
585
+
586
+ /**
587
+ * `C-e`: hand the terminal to `$EDITOR` and come back to an intact frame. The draft is written
588
+ * to `state/draft.md` first (the editor edits the real file), the render callback is gated for
589
+ * the whole handoff, and the editor's exit restores raw mode before one fresh frame is drawn.
590
+ */
591
+ async function editDraft(text: string): Promise<string> {
592
+ editorActive = true
593
+ writeDraft(text)
594
+ // The re-render triggered by the relay key commits asynchronously and Ink's throttled write can
595
+ // trail it by up to one render frame (≤34ms): the editor must not start before the panel's last
596
+ // frame is on screen, or that trailing write erases the editor's own first lines (measured: an
597
+ // editor that prints immediately lost `EDITOR-ACTIVE` to the panel's frame). Wait for the
598
+ // commit, then outlive one throttle window.
599
+ try {
600
+ await app?.waitUntilRenderFlush?.()
601
+ } catch {
602
+ /* the flush is best effort; the grace below still covers the trailing write */
603
+ }
604
+ await new Promise((resolve) => setTimeout(resolve, 60))
605
+ return new Promise((resolve) => {
606
+ const editor = process.env.TEAM_PANEL_EDITOR || process.env.EDITOR || process.env.VISUAL || 'vi'
607
+ // The Kitty keyboard protocol is on (design §6): the editor did not ask for it, so pop it
608
+ // before the handoff and push it again after — `CSI < u` / `CSI > 1 u`. The pop is a no-op
609
+ // on a terminal that never answered Ink's query, and the push is the flag Ink itself enables.
610
+ writeSync(1, KITTY_POP)
611
+ try {
612
+ process.stdin.setRawMode?.(false)
613
+ } catch {
614
+ /* not a tty: the fixture always gives us one */
615
+ }
616
+ try {
617
+ process.stdin.pause?.()
618
+ } catch {
619
+ /* ignore */
620
+ }
621
+ let child: ReturnType<typeof spawn>
622
+ try {
623
+ child = spawn('bash', ['-c', 'exec ${TEAM_PANEL_EDITOR:?} "$1"', '_', draftFile], {
624
+ cwd: root,
625
+ env: cleanIdentityEnv({ ...process.env, TEAM_PANEL_EDITOR: editor }),
626
+ stdio: 'inherit',
627
+ })
628
+ } catch {
629
+ editorActive = false
630
+ writeSync(1, KITTY_PUSH)
631
+ resolve(text)
632
+ return
633
+ }
634
+ const done = (): void => {
635
+ editorActive = false
636
+ writeSync(1, KITTY_PUSH)
637
+ try {
638
+ process.stdin.setRawMode?.(true)
639
+ } catch {
640
+ /* ignore */
641
+ }
642
+ try {
643
+ process.stdin.resume?.()
644
+ } catch {
645
+ /* ignore */
646
+ }
647
+ // The editor drew over the panel: wipe the screen and Ink's line bookkeeping, then draw
648
+ // one fresh frame. The frame must be intact when the relay returns.
649
+ try {
650
+ writeSync(1, '\x1b[2J\x1b[3J\x1b[H')
651
+ app?.clear()
652
+ app?.rerender(panelElement())
653
+ } catch {
654
+ /* best effort; the next refresh redraws anyway */
655
+ }
656
+ resolve(readDraft())
657
+ }
658
+ child.on('error', done)
659
+ child.on('close', done)
660
+ })
661
+ }
662
+
663
+ /** `q`: rebuild this very window as the headless tick loop (`team pulse collapse`). */
664
+ async function collapse(): Promise<{ ok: boolean; line: string }> {
665
+ if (mouseEnabled) {
666
+ try {
667
+ writeSync(1, '\u001b[?1000l\u001b[?1006l')
668
+ } catch {
669
+ /* ignore */
670
+ }
671
+ }
672
+ if (!teamCli) return { ok: false, line: `✗ ${s.noTeamCli}` }
673
+ if (!process.env.TMUX) {
674
+ // Not inside a tmux window (a direct bundle run): there is nothing to respawn.
675
+ exitSoon()
676
+ return { ok: true, line: '' }
677
+ }
678
+ const res = await run([teamCli, '--root', root, 'pulse', 'collapse'])
679
+ if (res.rc !== 0) return { ok: false, line: fill(s.flushFail, { detail: firstLine(res.err) || firstLine(res.out) }) }
680
+ exitSoon()
681
+ return { ok: true, line: '' }
682
+ }
683
+
684
+ let exiting = false
685
+ function exitSoon(): void {
686
+ if (exiting) return
687
+ exiting = true
688
+ setTimeout(() => process.exit(0), 150)
689
+ }
690
+
691
+ // The title band's live clock (V15/F2). A full Ink commit per second to advance one row costs a
692
+ // whole frame's reconcile + Yoga layout + rewrite — measured on the real tree: 0.72% → 1.37% of
693
+ // one core, over the <1% red line. So the clock ticks OUTSIDE React: the App registers row 0's
694
+ // segments + palette, this writer paints just the 8-column clock field in place (save cursor →
695
+ // absolute position → colored stamp → restore cursor), and the App renders the same stamp from
696
+ // the shared `clockNow` ref, so Ink's own (rare, signature-gated) repaints never revert it.
697
+ // Coloring goes through the same `chalk.hex` Ink's colorize uses, byte-identical. While the
698
+ // editor owns the terminal not one byte is written (the 2.3 handoff fixture measures that).
699
+ let clockRowState: { row: Segment[]; palette: Palette } | null = null
700
+ const clockNow = { ms: 0 }
701
+ const tickClock = (): void => {
702
+ if (!app || editorActive || !clockRowState) return
703
+ const ms = Date.now()
704
+ const stamp = clockOf(new Date(ms).toISOString())
705
+ if (clockNow.ms > 0 && stamp === clockOf(new Date(clockNow.ms).toISOString())) return
706
+ clockNow.ms = ms
707
+ let col = 1
708
+ let clockSeg: Segment | null = null
709
+ for (const seg of clockRowState.row) {
710
+ if (seg.clock) {
711
+ clockSeg = seg
712
+ break
713
+ }
714
+ col += dispWidth(seg.text)
715
+ }
716
+ if (!clockSeg) return // a degraded frame block keeps its `—`; no clock that would mask it
717
+ writeSync(1, `\x1b7\x1b[1;${col}H${chalk.hex(clockRowState.palette.tones[clockSeg.tone])(stamp)}\x1b8`)
718
+ }
719
+
720
+ const api: PanelApi = {
721
+ readDraft,
722
+ writeDraft,
723
+ clearDraft: () => writeDraft(''),
724
+ send,
725
+ flushQueue,
726
+ setStandby,
727
+ editDraft,
728
+ /**
729
+ * `C-v`'s probe (design §8): the bounded runner, the wayland-first order and the temp-file write
730
+ * live in `clipboard.ts`; this only maps the result to the App's three shapes.
731
+ */
732
+ pasteClipboard: async () => {
733
+ const read = await readClipboard(clipRunner)
734
+ if (!read) return { kind: 'none' as const, value: '' }
735
+ if (read.kind === 'text') return { kind: 'text' as const, value: read.text }
736
+ const file = writePasteFile(read.bytes, read.mime)
737
+ if (!file) return { kind: 'none' as const, value: '' }
738
+ return { kind: 'path' as const, value: file }
739
+ },
740
+ refreshNow,
741
+ suspended: () => editorActive,
742
+ clockNowMs: () => clockNow.ms,
743
+ registerClockRow: (row, palette) => {
744
+ clockRowState = row ? { row, palette } : null
745
+ },
746
+ saveSettings: (next: Settings) => {
747
+ mouseEnabled = next.mouse
748
+ writeSettings(confFile, next)
749
+ },
750
+ savePage: (next: PageId) => {
751
+ writePage(pageFile, next)
752
+ },
753
+ setActivity: (on: boolean) => {
754
+ if (activityPinned) return
755
+ opts.activity = on
756
+ refreshNow()
757
+ },
758
+ setDetail: (id: string | null, file?: string | null) => {
759
+ const nextId = id ?? null
760
+ const nextFile = nextId ? file ?? null : null
761
+ if ((opts.detailId ?? null) === nextId && (opts.detailFile ?? null) === nextFile) return
762
+ opts.detailId = nextId
763
+ opts.detailFile = nextFile
764
+ // The detail block is off the tick path: only the view's own open/tab-switch forces a build.
765
+ if (!nextId) return
766
+ // The cached block already serves this file (the open returns the first file without
767
+ // `--file`): record the option and rebuild nothing, so the effect can stay idempotent.
768
+ const cached = cache.snapshot().blocks?.detail
769
+ if (cached?.id === nextId && nextFile && cached.file === nextFile) return
770
+ void cache.refresh({ force: true, only: ['detail'] }).then(adopt)
771
+ },
772
+ collapse,
773
+ setSetting,
774
+ setSeatModel,
775
+ /**
776
+ * The path kind's existence mark (M55): resolved against the project root (`~` honoured), the
777
+ * rule from the command's own note. `not-exec` is only reachable for `exec` — a directory is
778
+ * never a `file`/`exec` target, and a missing path is `missing` whatever the rule says.
779
+ */
780
+ pathMark: (value: string, rule: string) => {
781
+ const raw = String(value ?? '').trim()
782
+ if (raw === '') return 'missing' as const
783
+ const abs = raw.startsWith('~/') ? join(homedir(), raw.slice(2)) : raw.startsWith('/') ? raw : join(root, raw)
784
+ try {
785
+ const st = statSync(abs)
786
+ if (rule === 'dir') return st.isDirectory() ? ('exists' as const) : ('missing' as const)
787
+ if (rule === 'any') return 'exists' as const
788
+ if (!st.isFile()) return 'missing' as const
789
+ if (rule === 'exec' && (st.mode & 0o111) === 0) return 'not-exec' as const
790
+ return 'exists' as const
791
+ } catch {
792
+ return 'missing' as const
793
+ }
794
+ },
795
+ refreshSettingsSoon,
796
+ setSettingsOpen: (open: boolean) => {
797
+ if (Boolean(opts.settingsOpen) === open) return
798
+ opts.settingsOpen = open
799
+ // The settings reader is off the tick path: only the view's own open forces a build.
800
+ if (!open) return
801
+ void cache.refresh({ force: true, only: ['settings'] }).then(adopt)
802
+ },
803
+ setComposeCursor: (position) => {
804
+ composeCursor = position
805
+ },
806
+ }
807
+
808
+ /** stdin/stdout are set up by the caller; `resize` is emitted by Node's tty stream. */
809
+ const onResize = (handler: () => void): void => {
810
+ if (typeof process.stdout.on === 'function') process.stdout.on('resize', handler)
811
+ }
812
+
813
+ app = render(panelElement(), {
814
+ exitOnCtrlC: false,
815
+ patchConsole: false,
816
+ // M47: Ink 7 treats ANY CI environment (`is-in-ci`) as non-interactive and then silently
817
+ // drops every frame — in that mode only <Static> output is written, so a pulse window on a
818
+ // runner (or in any container that inherits CI) stays blank while the process looks healthy.
819
+ // A tmux pane is a real terminal regardless of CI, and the panel's own contract is TTY-based
820
+ // (`--ui auto`: non-TTY → plain text / `--print`), so pin `interactive` to the TTY fact
821
+ // instead of Ink's CI heuristic. Flip evidence: smoke 26-m's `CI=1` pane case goes red again
822
+ // when this option is removed.
823
+ interactive: Boolean(process.stdout.isTTY),
824
+ // Kitty keyboard support is opt-in: `shift+enter` exists only if the terminal reports it
825
+ // (auto mode never enables the protocol on a terminal that does not answer the query).
826
+ kittyKeyboard: { mode: 'auto' },
827
+ // The cursor-aware stdout re-asserts the compose insertion point after every Ink write
828
+ // (including the throttled ones), which is what makes the placement exact in a full pane.
829
+ stdout: cursorAwareStdout(process.stdout, () => composeCursor),
830
+ })
831
+ if (!once) {
832
+ const clockTimer = setInterval(tickClock, 1000)
833
+ clockTimer.unref?.()
834
+ }
835
+
836
+ // A shrinking pane is the one terminal event Ink's relative cursor arithmetic cannot survive on a normal
837
+ // screen: the frame it wrote before the resize is now scrolled out, so the next frame lands off-screen and
838
+ // the pane looks blank (measured: 50x200 → 120x29 left 29 empty rows while the log showed full frames).
839
+ // Reset the screen and Ink's own line bookkeeping, then draw a fresh frame at the top.
840
+ onResize(() => {
841
+ if (editorActive) return
842
+ try {
843
+ writeSync(1, '\x1b[2J\x1b[3J\x1b[H')
844
+ app?.clear()
845
+ } catch {
846
+ /* a terminal that rejects the reset must not kill the panel */
847
+ }
848
+ try {
849
+ app?.rerender(panelElement())
850
+ } catch {
851
+ /* rerender is best effort; the next refresh redraws anyway */
852
+ }
853
+ })
854
+
855
+ const restoreTerminal = (): void => {
856
+ if (!mouseEnabled) return
857
+ try {
858
+ writeSync(1, '\u001b[?1000l\u001b[?1006l')
859
+ } catch {
860
+ /* ignore */
861
+ }
862
+ }
863
+ process.on('exit', restoreTerminal)
864
+ process.on('SIGTERM', () => {
865
+ restoreTerminal()
866
+ process.exit(143)
867
+ })
868
+ process.on('SIGHUP', () => {
869
+ restoreTerminal()
870
+ process.exit(129)
871
+ })
872
+
873
+ if (once) await runTickIfDue()
874
+ await app.waitUntilExit()
875
+ restoreTerminal()
876
+ cache.dispose()
877
+ process.exit(0)
878
+ }
879
+
880
+
881
+ void main()
882
+
883
+ function sleepSync(ms: number): void {
884
+ // Blocking sleep on the main thread; no child process, no busy loop. Only the plain-text and
885
+ // headless runs (a machine consumer with no input line) use it.
886
+ try {
887
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms)
888
+ } catch {
889
+ const end = Date.now() + ms
890
+ while (Date.now() < end) {
891
+ /* fallback if Atomics.wait is unavailable in this runtime */
892
+ }
893
+ }
894
+ }