SLOPSHOPPER

x-mod-stash

dima's command center above the prompt, one row: orbit ๐Ÿช (the session's asks, ticked in the board instead of pasted, and its ๐ŸŒ” phases), the 5h and ctxโ€ฆ

panebandrowsguardcommandprompt
A shopper browsing a rack in a slop shop
Preview ยท a replayed session in a sandbox
claude ยท ~/work/app ยท x-mod-stash
โ”‚ โ”ƒ ๐Ÿšฆ board โœ• โ€บ fix the failing auth test and add an audit log call โ”‚ โ”ƒ no live sessions โ”‚ โ”ƒ โบ Read(src/auth.ts) โ”‚ โ”ƒ โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ โŽฟ Read 6 lines โ”‚ โ”ƒ โ”‚ ๐Ÿช orbit ๐Ÿ“‚ โ”‚ โบ Update(src/auth.ts) โ”‚ โ”ƒ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ โŽฟ Added 2 lines, removed 1 line โ”‚ โ”ƒ โบ Bash(bun test) โ”‚ โ”ƒ โŽฟ 3 pass, 1 fail โ”‚ โ”ƒ โ”‚ โ”ƒ โ— Done. refresh now rejects expired claims and logs an audit event. โ”‚ โ”ƒ โ”‚ โ”ƒ โœป Worked for 42s ยท done 4:20 PM โ”‚ โ”ƒ โ”‚ โ”ƒ โ€บ /board โ”‚ โ”ƒ โŽฟ x-mod-stash: fleet board opened โ”‚ โ”ƒ โ”‚ โ”ƒ โ”‚ โ”ƒ โ”‚ โ”ƒ โ”‚ โ”ƒ โ”‚ โ”ƒ โ”‚ โ”ƒ โ”‚ โ”ƒ โ”‚ โ”ƒ โ”‚ โ”ƒ โ”‚ โ”ƒ ๐Ÿช 0 ๐ŸŒ” 0 ๐Ÿ”‹ +NaN% โณ NaNh NaNm ๐Ÿ”ญ not waiting ๐Ÿช„ ๐Ÿฆโ€๐Ÿ”ฅ ๐Ÿ”ฅ โฐ ๐Ÿ’จ ๐ŸŽ›๏ธ [ ๐Ÿšฆ ] โŸจClaude Code's own drawingโŸฉ โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ โ€บ ? for shortcuts

Draws

Band
๐Ÿช 0 ๐ŸŒ” 0 ๐Ÿ”‹ +NaN% โณ NaNh NaNm ๐Ÿ”ญ not waiting ๐Ÿช„ ๐Ÿฆโ€๐Ÿ”ฅ ๐Ÿ”ฅ โฐ ๐Ÿ’จ ๐ŸŽ›๏ธ [ ๐Ÿšฆ ] โŸจClaude Code's own drawingโŸฉ
Pane ยท ๐Ÿšฆ board
no live sessions โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ โ”‚ ๐Ÿช orbit ๐Ÿ“‚ โ”‚ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ
Pane ยท stash-settings
โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ โ”‚ s โ”‚ โ”‚ s โ”‚ t โ”‚ โ”‚ t โ”‚ a โ”‚ โ”‚ a โ”‚ s โ”‚ โ”‚ s โ”‚ h โ”‚ โ”‚ h โ”‚ ยท โ”‚ โ”‚ ยท โ”‚ b โ”‚ โ”‚ k โ”‚ a โ”‚ โ”‚ n โ”‚ n โ”‚ โ”‚ o โ”‚ d โ”‚ โ”‚ b โ”‚ [ ๐Ÿช ๐ŸŒ” asks and phases chips ] โ”‚ โ”‚ s โ”‚ [ ๐Ÿ”‹ ๐Ÿชซ pace gap ] โ”‚ โ”‚ [ ๐ŸŽจ board c โ”‚ [ โณ time to the 5h reset ] โ”‚ โ”‚ ๐Ÿง  [ โ—ฏ ring ] โ”‚ [ ๐Ÿ”ญ wait line ] โ”‚ โ”‚ โ”‚ [ ๐Ÿช„ โช โฉ enhancer ] โ”‚ โ”‚ s โ”‚ [ ๐Ÿ”ฅ keep-hot ] โ”‚ โ”‚ e โ”‚ [ โฐ waker ] โ”‚ โ”‚ s โ”‚ [ ๐Ÿ’จ afk ] โ”‚ โ”‚ s โ”‚ [ ๐Ÿšฆ board button ] โ”‚ โ”‚ i โ”‚ [ ๐Ÿ”ฅ 5h bar (desktop) ] โ”‚ โ”‚ o โ”‚ [ ๐Ÿง  ctx bar (desktop) ] โ”‚ โ”‚ n โ”‚ [ while you were away ] โ”‚ โ”‚ s โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ โ”‚ : โ”‚ c โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ โ”‚ t โ”‚ s โ”‚ โ”‚ x โ”‚ t โ”‚ โ”‚ m โ”‚ a โ”‚ โ”‚ e โ”‚ s โ”‚ โ”‚ t โ”‚ h โ”‚ โ”‚ e โ”‚ ยท โ”‚ โ”‚ r โ”‚ b โ”‚ โ”‚ t โ”‚ o โ”‚ โ”‚ y โ”‚ a โ”‚ โ”‚ p โ”‚ r โ”‚ โ”‚ e โ”‚ d โ”‚ โ”‚ ๐ŸŒ” 7 l โ”‚ [ ๐Ÿช orbit asks ] โ”‚ โ”‚ i โ”‚ [ assumed section ] โ”‚ โ”‚ p n โ”‚ [ ๐Ÿ  catch ] โ”‚ โ”‚ h e โ”‚ [ ๐ŸŒ” phases ] โ”‚ โ”‚ a s โ”‚ [ ๐Ÿ›ผ glide ] โ”‚ โ”‚ s ( โ”‚ [ ๐Ÿ”Š โฏ๏ธ โน๏ธ speak buttons ] โ”‚ โ”‚ e 5 โ”‚ [ session rows: model, effort and wait ] โ”‚ โ”‚ l โ€“ โ”‚ [ ๐Ÿฆโ€๐Ÿ”ฅ second wind ] โ”‚ โ”‚ i 7 โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ โ”‚ n ) โ”‚ e โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ โ”‚ s โ”‚ s โ”‚ โ”‚ [ ๐Ÿ“จ undo ti โ”‚ t โ”‚ โ”‚ โ”‚ a โ”‚ โ”‚ โ”‚ s โ”‚ โ”‚ โ”‚ h โ”‚ โ”‚ โ”‚ ยท โ”‚ โ”‚ โ”‚ r โ”‚ โ”‚ โ”‚ e โ”‚ โ”‚ [ ๐Ÿ”Š read-al โ”‚ p โ”‚ โ”‚ [ ๐Ÿ›ก๏ธ guard no โ”‚ l โ”‚ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ โ”‚ i โ”‚ โ”‚ e โ”‚ โ”‚ s โ”‚ โ”‚ [ ยท-lists drawn as bullets ] โ”‚ โ”‚ [ fleet words bold with their badge ] โ”‚ โ”‚ [ โ‘ โ‘กโ‘ข drawn as numbered lines ] โ”‚ โ”‚ [ bare ticket ids drawn as links ] โ”‚ โ”‚ [ a ๐Ÿ”ญ line's (aside) dropped ] โ”‚ โ”‚ [ ๐Ÿ’ต cost questions read model-cards.md ] โ”‚ โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ โ”‚ ๐Ÿ”ฅ โ”‚ โ”‚ ๐Ÿคซ โ”‚ โ”‚ โ”‚ โ”‚ b โ”‚ โ”‚ q โ”‚ a โ”‚ โ”‚ u โ”‚ r โ”‚ โ”‚ i โ”‚ s โ”‚ โ”‚ e โ”‚ [ ๐Ÿ”ฅ bars breathe while a turn runs ] โ”‚ โ”‚ t โ”‚ [ ๐Ÿ”ฅ bars breathe all the time ] โ”‚ โ”‚ c โ”‚ ๐Ÿ”ฅ 0.5 ร— โ”‚ โ”‚ o โ”‚ ( โ”‚ โ”‚ m โ”‚ b 0 โ”‚ โ”‚ m โ”‚ r . โ”‚ โ”‚ s โ”‚ e 1 โ”‚ โ”‚ [ ๐Ÿคซ hold member โ”‚ a โ€“ โ”‚ โ”‚ ๐Ÿคซ 10 m โ”‚ t 5 โ”‚ โ”‚ i โ”‚ h ) โ”‚ โ”‚ h n โ”‚ s โ”‚ โ”‚ e ( โ”‚ p โ”‚ โ”‚ l 1 โ”‚ e โ”‚ โ”‚ d โ€“ โ”‚ e โ”‚ โ”‚ p 6 โ”‚ d โ”‚ โ”‚ i 0 โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฏ โ”‚ n ) โ”‚ g โ”‚ s โ”‚ w โ”‚ a โ”‚ i โ”‚ t โ•ฐโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
README

๐ŸŽž๏ธ the frame: a place where most of the machine's setup lives as data.

<a href="https://github.com/dvakatsiienko/frame/actions/workflows/ci.yml"><img src="https://raw.githubusercontent.com/dvakatsiienko/frame/badges/ci.svg" alt="ci"></a> <img src="assets/badges/tests.svg" alt="tests"> <img src="assets/badges/renovate.svg" alt="renovate"> <img src="assets/badges/node.svg" alt="node"> <img src="assets/badges/pnpm.svg" alt="pnpm"> <img src="assets/badges/skills.svg" alt="skills"> <img src="assets/badges/mirrored.svg" alt="mirrored">

<img src="assets/banner.svg" align="left" width="100%" alt="frame โ€” the inventory of one mac"> <img src="assets/mac.svg" align="right" width="36%" alt="an 80s mac showing ~ frame">

๐Ÿงญ toc

  • fleet โ€” skills, memory, sline, hotkeys
  • chords โ€” the keyboard map, live
  • mirror โ€” home/ is ~
  • machine โ€” brew, defaults, launchd
  • link it โ€” a fresh mac install

๐Ÿ›ธ fleet

home/.claude/ is the claude code setup every session reads: memories, rules, skills (plugin-x), hooks, output styles, and sline, the statusline. cclio/ is the coordinator's home, the session that plans and routes work to background coders. x/ is x, the agent-first cli in go + charm: one verb registry, json for agents and boards for humans (x lane commits and pushes from a sandboxed worktree). hotkeys/ maps every keyboard chord on the machine and serves chords, the map's app. x-speak (a schedule/ daemon) reads the selected text aloud on F4 (with nothing selected it pauses / resumes, as โ‡งF4 always does) and stops on F5, rewriting ids, versions, paths and code into something a voice can say; speak/ is its voice admin (pnpm speak:admin).

<img src="home/.claude/sline/showcase/sline.svg" width="100%" alt="sline, the statusline, as a session climbs from fresh to heavy">

๐ŸŽน chords

chords is a keyboard map app: every key binding on every modifier layer, how often each one fires, and which keys are still free. powered by launchd daemon that counts key presses.

<img src="hotkeys/chords/showcase.png" width="100%" alt="chords: the hyper layer on a NuPhy Air75, each bound key with its app and press count">

๐Ÿชž mirror

the mirror links dotfiles and configs. a path under home/ is the same path under ~. the link map is derived by walking the tree, so adding a file to home/ auto-tracks it.

pnpm frame:link                        # status
pnpm frame:link apply                  # link everything not linked yet
pnpm frame:link register ~/.foo        # move a file into the mirror and link it back
pnpm frame:link untrack ~/.gitconfig   # hand a file back to ~

<img src="assets/frame-link.gif" width="720" alt="pnpm frame:link, ending on everything mirrored">

๐Ÿ’ป machine

the mac's setup is kept as data, because data does not rot and scripts do: the Brewfile, the macos defaults, the duti file bindings, and the launchd jobs under schedule/.

pnpm macos:setup   # brew bundle, macos defaults, duti, vim-plug

๐Ÿ”— link it

on a fresh machine, install the command line tools first โ€” the clone itself needs git, and macos ships only a shim that opens the install dialog. then clone to ~/frame and run the seed, or hand it to an agent (ยซseed this mac from frameยป):

xcode-select --install      # stop 0: the dialog, ~2 min
git clone https://github.com/dvakatsiienko/frame ~/frame && cd ~/frame
script/seed.sh                     # command line tools โ†’ brew โ†’ fnm, pnpm, node โ†’ pnpm i โ†’ macos:setup โ†’ sline โ†’ claude cli โ†’ frame:link apply
script/seed.sh --claude            # the same, with ~/.claude linked
script/seed.sh --without-appstore  # skip the app store apps and their sign-in
script/seed.sh --dry-run           # what it would do, nothing changed

one status line per step, safe to re-run. it stops with needs your hands: โ€ฆ (exit 2) where only a human can act โ€” the command line tools dialog, the homebrew password, files in the way of a link, the app store and 1password sign-ins โ€” and the next run picks up from there. when it ends, open a new terminal: a shell opened before the seed never sources the zsh stubs it wrote.

Source 5 files
hooks/register.tsx 6885 lines
1/* @jsx h */
2import type { EngineInterface, Register, RenderElement } from 'claude-code';
3
4import type {
5    CatchCount,
6    LaneItem,
7    OrbitAsk,
8    OrbitAssumption,
9    OrbitCatch,
10    PublishedAsk,
11    QuietGap,
12    QuietLogLine,
13    QuietPing,
14    RemoteMark,
15    StashCap,
16    StashDigest,
17    StashEnhancer,
18    StashEntry,
19    StashLane,
20    StashMember,
21    StashMeter,
22    StashOrbit,
23    StashPlan,
24    StashQuiet,
25    StashView,
26    StashWind,
27} from '../types/stash.d.ts';
28import {
29    ASSUMED_MAX,
30    CATCH_SHOWN,
31    CHANGED_MARK,
32    ORBIT_TEXT_MAX,
33    ORBIT_TOOL,
34    PLAN_MAX,
35    SEND_MS,
36    halted,
37    hasPlanMark,
38    isDue,
39    isFresh,
40    isSending,
41    isThought,
42    joinText,
43    lockJoined,
44    lockThought,
45    moved,
46    oneLine,
47    orbitOp,
48    planTaken,
49    planText,
50    shelved,
51    steered,
52    steeredOrbit,
53    thinkText,
54    turnEnded,
55    wrongText,
56} from './orbit.ts';
57import {
58    LEDGER_SENDS,
59    backgroundWait,
60    backgroundWaits,
61    boldFleetWords,
62    bulletDots,
63    dropWaitAside,
64    isFleetName,
65    linkTickets,
66    numberCircled,
67    parseWait,
68    ticketOf,
69} from './parse.ts';
70import { cleanTree } from './tree.ts';
71
72// x-mod-stash: dima's command center above the prompt, one row; FTR.md lists every feature.
73// orbit: the session's asks to dima and its plan, written through its own tool, ticked in the board; its open asks are
74// mirrored into $.store (one key per session), so the board counts every session's.
75// afk: one switch every session polls; while it is on, every prompt carries an away note, and a flip reaches a running turn.
76// keep-hot: while on and idle, one ping 50 min after the last turn ended keeps the prompt cache warm; the switch lives in $.store, so a reload keeps it
77
78// label: the repo; name: the session's registry name, when it has one
79type Entry = StashEntry;
80// where an ask card's tick, replay and steer go, and the prefix its keys carry
81type AskDoor = {
82    prefix: string;
83    mark: (a: OrbitAsk, mark: 'accepted' | 'rejected') => void;
84    steer: (a: OrbitAsk, value: string) => void;
85};
86// a session's last reply: when it ended, its ๐Ÿ”ญ wait; `ended` once the session itself exited
87// waits: every background task's own name when the reply set no ๐Ÿ”ญ, so the board can list them all
88type Reply = {
89    at: number;
90    // a keep-hot ping's reply end: it warms the cache without being a reply dima reads
91    pingedAt?: number;
92    name?: string;
93    wait?: string;
94    waits?: string[];
95    ended?: number;
96};
97
98const PREFIX = 'asks:';
99// what the board draws from this session's $.state, kept per conversation in the store, so a session resumed in a new
100// process โ€” a mac reboot relaunches every one โ€” draws it again: $.state starts empty there (dima's โœจ wisps, 10-13 16:26
101// orbit and the sessions rows, 16:44 phases); kept past an exit, dropped after a week unused
102const KEPT = 'kept:';
103const KEPT_MS = 7 * 24 * 60 * 60 * 1000;
104// `succ:<old id>` โ†’ the id a /clear continued under, so a lane linked by a session id follows it (todo 21: a clear left
105// the l14 card on the coder's old id, its asks gone from the card); dropped a week after it was written
106const SUCC = 'succ:';
107// a glide card's mark on a member's ask, waiting for the member's own stash (FRM-385 exit 3); and when dima last prompted anywhere
108const MARKS = 'marks:';
109// ๐Ÿ›ผ a member's lane step from its plan op, one key per registry name, written only by that session (todo 6)
110const LANE_STEP = 'lane-step:';
111// the moves cclio's stash made from a coder's step, held for her next tool call or prompt
112const LANE_MOVES = 'lane-moves';
113const DIMA_AT = 'dima-at';
114// ๐Ÿ  catch's experiment counts, one store key per day, read at its keep-or-kill on 2026-10-17 (FRM-386)
115const CATCH_COUNT = 'catch-count:';
116// cclio's catch shelf, kept per coordinator so a compaction, a checkpoint or her next session draws the same pieces
117const CATCH_SHELF = 'catch-shelf:cclio';
118const AFK_KEY = 'afk';
119const AWAY_NOTE =
120    'dima is afk: nothing waits on him. take reversible steps and log them, park every ask in orbit for his return, send no ping.';
121const BACK_NOTE = 'dima is back from afk: orbit and pings reach him again.';
122const POLL_MS = 4000;
123// the fleet board: cc's registry gives each session's state; each session's stash adds its ๐Ÿ”ญ wait and context fill
124const BOARD = 'fleet-board';
125// ๐ŸŽ›๏ธ is a pane of its own, which the surface tabs beside ๐Ÿšฆ: the band is capped by cc, the list outgrew it (dima's pick a of
126// four homes, 16:20); a tab row inside a pane was proven too, kept as an idea in api-map.md
127const SETTINGS_PANE = 'stash-settings';
128const REPLY = 'reply:';
129const CONTEXT = 'context:';
130// the model and effort of a session's main loop, as its last model request named them
131const MODEL = 'model:';
132// the board's colour MVP: one fleet-wide switch, `/board colour`, off by default (FRM-329)
133const COLOUR = 'board-colour';
134// the row's ctx meter as a ring (C) or the % with a thin bar under it (B): dima keeps both, a ๐ŸŽ›๏ธ switch picks (10-13 17:00)
135const CTX_RING_KEY = 'ctx-ring';
136// `/board breathe`: the bars breathe idle too, while dima refines the look (2026-10-11 12:20); off by default, a try
137const BREATH_PREVIEW = 'breath-preview';
138// the ๐ŸŽ›๏ธ knobs (FRM-391 slice 06), fleet-wide in stash's store like the switches: a missing key is the default
139const BREATHE = 'breathe';
140const BREATH_SPEED = 'breath-speed';
141const PHASE_LINES = 'phase-lines';
142const SPEAK_ASSUMED = 'speak-assumed';
143// x-mod-guard reads this key from stash's store file: true drops its rewrite, hint and delegate notes, never a refusal
144const GUARD_SILENT = 'guard-silent';
145// quiet comms on or off, one switch for ๐ŸŽ›๏ธ and `/quiet` alike; on by default, `off` is the revert (dima, 16:53)
146const QUIET_ON = 'quiet-comms';
147// a tick, a replay or a phases change waits SEND_MS in ยซsendingยป, undoable; off, it is ready for the next turn at once
148// (dima, 10-13 17:49)
149const UNDO_WINDOW = 'undo-window';
150const SPEED = { max: 5, min: 0.1, of: 0.5 } as const;
151const LINES = { max: 7, min: 5 } as const;
152// how long held member pings wait before the hidden idle append, in minutes (dima, 16:53: 10 by default, maybe 15)
153const QUIET_WAIT = 'quiet-wait';
154// the undo window's length in seconds, set beside its switch (dima, 10-13 18:01)
155const UNDO_DELAY = 'undo-delay';
156const WAIT = { max: 60, min: 1 } as const;
157// every ๐ŸŽ›๏ธ knob in one table: its store key and its default; a number knob its range too. a missing or broken value reads
158// as the default, and every read and write goes through readSwitch, readNumber, flipKnob and setKnobNumber
159const SWITCHES = {
160    always: { key: BREATH_PREVIEW, of: false },
161    breathe: { key: BREATHE, of: true },
162    colour: { key: COLOUR, of: false },
163    quiet: { key: QUIET_ON, of: true },
164    ring: { key: CTX_RING_KEY, of: true },
165    silent: { key: GUARD_SILENT, of: false },
166    speak: { key: SPEAK_ASSUMED, of: true },
167    undo: { key: UNDO_WINDOW, of: true },
168} as const;
169const NUMBERS = {
170    lines: { key: PHASE_LINES, of: PLAN_MAX, range: LINES },
171    quietWait: { key: QUIET_WAIT, of: 10, range: WAIT },
172    speed: { key: BREATH_SPEED, of: SPEED.of, range: SPEED },
173    undoDelay: {
174        key: UNDO_DELAY,
175        of: SEND_MS / 1000,
176        range: { max: 30, min: 1 },
177    },
178} as const;
179type SwitchName = keyof typeof SWITCHES;
180type NumberName = keyof typeof NUMBERS;
181// the ๐ŸŽ›๏ธ settings (FRM-391 slice 05): one show/hide switch per part, in the store every session reads and the poll
182// re-reads, so a flip reaches every band within one poll; a missing key is shown
183const SHOWN = 'shown';
184// the parts dima approved (o2, 2026-10-11 13:15), grouped by where they draw; a mod's own parts, so a new one joins here
185export const PARTS = [
186    {
187        group: 'stash ยท band',
188        key: 'stash.chips',
189        label: '๐Ÿช ๐ŸŒ” asks and phases chips',
190    },
191    { group: 'stash ยท band', key: 'stash.pace', label: '๐Ÿ”‹ ๐Ÿชซ pace gap' },
192    {
193        group: 'stash ยท band',
194        key: 'stash.reset',
195        label: 'โณ time to the 5h reset',
196    },
197    { group: 'stash ยท band', key: 'stash.wait', label: '๐Ÿ”ญ wait line' },
198    {
199        group: 'stash ยท band',
200        key: 'stash.enhancer',
201        label: '๐Ÿช„ โช โฉ enhancer',
202    },
203    { group: 'stash ยท band', key: 'stash.hot', label: '๐Ÿ”ฅ keep-hot' },
204    { group: 'stash ยท band', key: 'stash.waker', label: 'โฐ waker' },
205    { group: 'stash ยท band', key: 'stash.afk', label: '๐Ÿ’จ afk' },
206    { group: 'stash ยท band', key: 'stash.board', label: '๐Ÿšฆ board button' },
207    { group: 'stash ยท band', key: 'stash.5h', label: '๐Ÿ”ฅ 5h bar (desktop)' },
208    { group: 'stash ยท band', key: 'stash.ctx', label: '๐Ÿง  ctx bar (desktop)' },
209    {
210        group: 'stash ยท band',
211        key: 'stash.digest',
212        label: 'while you were away',
213    },
214    { group: 'stash ยท board', key: 'stash.orbit', label: '๐Ÿช orbit asks' },
215    { group: 'stash ยท board', key: 'stash.assumed', label: 'assumed section' },
216    { group: 'stash ยท board', key: 'stash.catch', label: '๐Ÿ  catch' },
217    { group: 'stash ยท board', key: 'stash.phases', label: '๐ŸŒ” phases' },
218    { group: 'stash ยท board', key: 'stash.glide', label: '๐Ÿ›ผ glide' },
219    {
220        group: 'stash ยท board',
221        key: 'stash.speak',
222        label: '๐Ÿ”Š โฏ๏ธ โน๏ธ speak buttons',
223    },
224    {
225        group: 'stash ยท board',
226        key: 'stash.rowmeta',
227        label: 'session rows: model, effort and wait',
228    },
229    {
230        group: 'stash ยท board',
231        key: 'stash.second-wind',
232        label: '๐Ÿฆโ€๐Ÿ”ฅ second wind',
233    },
234    {
235        group: 'stash ยท replies',
236        key: 'stash.bullets',
237        label: 'ยท-lists drawn as bullets',
238    },
239    {
240        group: 'stash ยท replies',
241        key: 'stash.boldwords',
242        label: 'fleet words bold with their badge',
243    },
244    {
245        group: 'stash ยท replies',
246        key: 'stash.circled',
247        label: 'โ‘ โ‘กโ‘ข drawn as numbered lines',
248    },
249    {
250        group: 'stash ยท replies',
251        key: 'stash.tickets',
252        label: 'bare ticket ids drawn as links',
253    },
254    {
255        group: 'stash ยท replies',
256        key: 'stash.waitaside',
257        label: "a ๐Ÿ”ญ line's (aside) dropped",
258    },
259    {
260        group: 'stash ยท replies',
261        key: 'stash.cost',
262        label: '๐Ÿ’ต cost questions read model-cards.md',
263    },
264] as const;
265type PartKey = (typeof PARTS)[number]['key'];
266type IsPartOn = (key: PartKey) => boolean;
267// the registry names a short-lived headless run `t-` + hex (`t-70`); the board leaves those out (dima, 2026-10-05)
268const HEADLESS = /^t-[0-9a-f]+$/;
269// a session younger than this, counted from the registry's `startedAt`, is a probe: it gets no row until it outlives it
270const SHORT_MS = 60_000;
271const STALE_MS = 24 * 60 * 60 * 1000;
272// dima at the prompt, typing into a background job, on his phone or the web
273const DIMA_ORIGINS = ['composer', 'sdk', 'bridge'] as const;
274const HOT_MS = 50 * 60 * 1000;
275const HOT = 'hot:';
276// a reload keeps `$.state` and resets the module: what must outlive a mod save lives there (FRM-320)
277// what the band and the board draw: renders read it, and a write redraws them, no invalidate
278const VIEW = { key: 'view', plugin: 'x-mod-stash' } as const;
279// what only the board pane draws, its clock included: the band never reads it, so a tick never redraws the band
280const BOARD_VIEW = { key: 'board', plugin: 'x-mod-stash' } as const;
281// the running turn, so a mid-turn reload still knows it is busy
282const TURN = { key: 'turn', plugin: 'x-mod-stash' } as const;
283// when the last main turn ended: ๐Ÿ”ฅ switched on while idle counts its 50 min from here, so the ping lands inside the cache's hour
284const ENDED = { key: 'ended', plugin: 'x-mod-stash' } as const;
285// a ๐Ÿ“„ line's HH:MM โ€” the same shape reply-check.py reads
286const STAMP = /(๐Ÿ“„[^\n]*?\b)(\d{1,2}:\d{2})\b/g;
287const PING =
288    'x-mod-stash keep-hot ping: answer with one character, nothing else.';
289// the waker: one global switch, off by default; when on, a session stopped on the 5h cap gets one resume at the reset
290const WAKER_KEY = 'waker';
291const CAP = { key: 'cap', plugin: 'x-mod-stash' } as const;
292// the band's meters, written on every session.measure
293const METER = { key: 'meter', plugin: 'x-mod-stash' } as const;
294// the 5h cap ends the turn as an API error with this text; the weekly cap and spent credits read otherwise
295// (8 rows in the transcripts, 2026-10-08)
296const CAPPED = /hit your session limit/i;
297const RESUME =
298    'x-mod-stash waker: the 5h window reset. pick up where you stopped.';
299// a few seconds past the reset, so the window has turned before the resume goes out
300const WAKE_SLACK_MS = 5000;
301// the board's one palette, every card's colours read from it (dima's o107, 21:17): mid-tones at 3.2:1 or more on a light
302// pane and 4.2:1 on a dark one; `dim` is the theme's own gray; `calm` is the ctx meter's blue
303export const PALETTE = {
304    accent: '#d97757',
305    calm: '#4f83e0',
306    dim: 'inactive',
307    // each member's dot, by name: six mid-tones at 3.6:1 or more on white and 4.2:1 on the dark pane, none a state tint
308    // and no coral near the asks' orange; the 1st and 4th nudged off `calm` and `ok` (l13, `pnpm design:contrast`)
309    dots: ['#6b7bdc', '#2f8f8a', '#a87f12', '#3c9472', '#9a74c9', '#c4689f'],
310    hot: '#e5484d',
311    ok: '#47915a',
312    warn: '#d9661a',
313} as const;
314const ACCENT = PALETTE.accent;
315// ๐Ÿช orbit: the session's asks to dima, ticked in the board instead of pasted back; the session writes them through
316// its own tool, never a reply block
317const ORBIT = { key: 'orbit', plugin: 'x-mod-stash' } as const;
318// the phases guard, no extra turn and no Stop block: one line at the first prompt, one nudge in a turn's tool results (dima's o14)
319const PHASES_START = `phases are your live plan: set them with ${ORBIT_TOOL}'s plan op and keep them current as the work moves.`;
320const NUDGE_AT = 3;
321// a plan set in either of the last 2 turns still holds: a turn that did not move it gets no nudge (cclio's brief 8)
322const PLAN_QUIET_TURNS = 2;
323// mobile mode: mods draw nothing on the phone, so the session prints the open asks as the asks fence instead
324const MOBILE = { key: 'mobile', plugin: 'x-mod-stash' } as const;
325// a board card folded to its head row, per session (dima's o5, 17:16)
326const FOLDS = { key: 'folds', plugin: 'x-mod-stash' } as const;
327// ๐Ÿ›ผ glide (FRM-385): the fleet's lanes in one shelf file, written only by the session the registry names ๐Ÿฆ‰ cclio, read by
328// every board on its poll; at most 5 plain steps, each โ‰ค60 chars, stale after 8 of cclio's turns with nothing moved
329const LANES = { key: 'lanes', plugin: 'x-mod-stash' } as const;
330const LANE_ASKS = { key: 'laneAsks', plugin: 'x-mod-stash' } as const;
331// dima's steer on a lane's current step and its ๐Ÿ›Ž๏ธ tick, one store key per lane: any board writes it, so the shelf file
332// keeps its one writer, cclio's lane op
333const LANE_STEER = 'lane-steer:';
334// the retired glide reorder's store key (o84, dropped by o138): cclio's stash deletes any left behind
335const LANE_ORDER = 'lane-order:';
336// a lane steer typed before the rename sits under the old prefix: read as a steer, retired at its next write
337const LANE_STEER_OLD = 'lane-note:';
338const LANE_OWNER = '๐Ÿฆ‰ cclio';
339const LANE_ROLES = ['coder', 'verifier'] as const;
340const LANE_MAX = 7;
341const LANE_TEXT_MAX = 60;
342const LANE_STALE = 8;
343const LANE_TICKET = /^[A-Z]{2,5}-\d+$/;
344const MOBILE_SKILL = /(^|:)mobile-mode$/;
345// cclio's halt skill: an ask added with `dies: "halt"` leaves when it expands
346const HALT_SKILL = /(^|:)halt$/;
347const MOBILE_OFF = /ARGUMENTS:\s*off\b/i;
348const BACK_AT_MAC = /\bback at the mac\b/i;
349// the prompt enhancer: Haiku rewrites the box on a press; prev and new swap the two texts back with no call
350const ENHANCER = { key: 'enhancer', plugin: 'x-mod-stash' } as const;
351const ENHANCE_MODEL = 'claude-haiku-5-5';
352const ENHANCE_MS = 30_000;
353const WISPR_DB = 'Library/Application Support/Wispr Flow/flow.sqlite';
354let isEnhancing = false;
355const TICKET_ID_ALL = /(?<!\[)\b(?:FRM|BYT)-\d+\b(?!\])/g;
356const STALE_TURNS = 3;
357// a plan line's lead word, one short word before its colon
358const PLAN_LEAD = /^[a-z]{2,10}:/i;
359const PHASE_MOONS = ['๐ŸŒ•', '๐ŸŒ”', '๐ŸŒ“', '๐ŸŒ’', '๐ŸŒ‘'];
360// a quarter row between a block's lines: the desktop draws the fraction, the terminal rounds it away (dima, 21:22)
361const LINE_GAP = 0.25;
362// a closed ask's lead, read from its closing word: dropped ๐Ÿ—‘๏ธ, started or queued โ–ถ๏ธ, anything else done โœ… (dima, 20:37)
363export const closedMark = (word: string) =>
364    /^(drop|cut|cancel|superseded|declined)/i.test(word)
365        ? '๐Ÿ—‘๏ธ'
366        : /^(start|queued|running|in progress)/i.test(word)
367          ? 'โ–ถ๏ธ'
368          : 'โœ…';
369// the board's sections sit in cards, no colour (dima, 16:48 ยซcolors are uglyยป): the desktop a 30 % grey that reads the same on
370// light and dark, a touch softer than `subtle` (16:54 too faint, 17:00 ยซtoo hardยป, 17:08 ยซslightly lessยป); the terminal `subtle`
371const cardBorder = (surface: string) =>
372    surface === 'desktop' ? '#8080804d' : 'subtle';
373// a ticket id inside an ask or a phase; split keeps the id as every odd part
374const TICKET_IDS = /\b((?:FRM|BYT)-\d+)\b/;
375const ORBIT_ABOUT = [
376    'orbit: your asks to dima on the fleet board; an ask goes here, never into a reply. ๐Ÿ›Ž๏ธ tick = pick good to go, ๐Ÿ” replay = another round, plus his steer; marked asks reach you model-only. a --bg session has no board: its asks go to its coordinator.',
377    `op add, asks [{ text, pick, hiddenNote, link }]: text one line โ‰ค${ORBIT_TEXT_MAX} chars, subject first, readable alone (no ยซaboveยป, ยซthisยป); pick: your recommendation; hiddenNote: yours alone, its source and what a tick means; link: one https url or file path he opens in a click; dies: "halt" or N of dima's prompts unpicked, your own turns never count. irreversible (trash, push, close, merge) โ†’ lead with โš ๏ธ, name the exact target.`,
378    'op resolve, ids, words { id: closing word }: the asks answered this turn; they leave when it ends, a worded one shown dim a turn more.',
379    `op follow, id, text, pick: another round on an answered ask, same id and place, text โ‰ค${ORBIT_TEXT_MAX} chars, marked ${CHANGED_MARK}.`,
380    `op assume, texts: โ‰ค${ASSUMED_MAX} a turn, โ‰ค${ORBIT_TEXT_MAX} chars: unasked choices a wrong guess would cost a redo on, never routine; ๐Ÿ›Ž๏ธ clears, โ†ฉ๏ธ sends back with his steer.`,
381    'op catch, pieces [{ kind, text, hiddenNote }], clear [ids]: cclio only, her rules come from catch.md.',
382    `op plan, lines: your next ${PLAN_MAX} moves (now, next, then), each โ‰ค${ORBIT_TEXT_MAX} chars and readable alone; set at each turn end; untouched ${STALE_TURNS} turns reads stale. step: your lane step.`,
383    `op glide โ€” ${LANE_OWNER} only, every board draws it: act create, title, items [{ text, ticket, done }]: a lane's whole scope as 1โ€“${LANE_MAX} steps dima reads at a glance โ€” plain words, โ‰ค${LANE_TEXT_MAX} chars, no paths, op names or pr numbers; ticket is an optional id; the result names the lane id. act link, id, session, role (coder or verifier): a member's session id; a re-link of a role replaces the old one. act edit, id, title?, items?: the card refreshed in place, a step whose text stays keeps its done flag. act step, id, current: the step we are on, every step before it done; current = the step count marks the lane finished. act end, id: at the siesta or the halt after it finished. nothing moved for ${LANE_STALE} of your turns reads stale.`,
384].join('\n');
385
386let selfId: string | undefined;
387// the id a /clear left, until the next load reads the new one and writes the successor
388let clearedFrom: string | undefined;
389// this session's own second wind as the store holds it, read at each load for the band's button
390let selfWind: StashWind['state'] | undefined;
391let label = 'session';
392let isUserTurn = false;
393// what this session's last reply waits on, its ๐Ÿ”ญ line
394let wait: string | undefined;
395let pinged = false;
396let isPolling = false;
397let afk = false;
398let isWaker = false;
399let shown: Record<string, boolean> = {};
400let isSettingsOpen = false;
401// the main thread's tool calls this turn, and whether its one phases nudge went out
402// a field never redraws because of its own typing: the surface runs a keystroke ahead of this module, so any changed
403// `value` โ€” the stored steer, or even the latest text this module heard โ€” reset the field and threw the caret (dima,
404// 16:15 and 16:22). while typing, the field keeps drawing the value it showed; once typing has been quiet for
405// FIELD_QUIET_MS the stored text takes over. a change from outside (a steer cleared once it joined a turn) is drawn at
406// once; when it equals what is already drawn the surface would keep the typed text, so the field remounts under a new key
407export type FieldDraft = {
408    drawn: string;
409    sent: string[];
410    at: number;
411    isLanded: boolean;
412};
413// dima's o8, 17:14: ยซ1-2 s at leastยป โ€” a short pause no longer snaps a long field back to its start
414const FIELD_QUIET_MS = 3000;
415const FIELD_SAVE_MS = 1500;
416const pendingSaves = new Map<
417    string,
418    { save: () => unknown; timer: { cancel: () => void } }
419>();
420// a field was typed into within the quiet window: the poll holds its redraw till it passes
421export const isTypingAt = (typedAt: readonly number[], now: number) =>
422    typedAt.some((at) => now - at < FIELD_QUIET_MS);
423
424// every save still waiting on a pause runs now: before a press, a prompt or a tool call reads what was typed
425async function flushFields() {
426    const due = [...pendingSaves];
427    pendingSaves.clear();
428    for (const [, p] of due) p.timer.cancel();
429    await Promise.all(due.map(([, p]) => p.save()));
430}
431const drafts = new Map<string, FieldDraft>();
432const remounts = new Map<string, number>();
433export type FieldView =
434    | { kind: 'held'; draft: FieldDraft }
435    | { kind: 'saved' }
436    | { kind: 'outside'; isRemount: boolean };
437export function fieldView(
438    draft: FieldDraft | undefined,
439    saved: string,
440    now: number,
441): FieldView {
442    if (!draft) return { kind: 'saved' };
443    const isOwn = draft.sent.includes(saved);
444    const isLag = saved === draft.drawn && !draft.isLanded;
445    if (!isOwn && !isLag)
446        return { isRemount: saved === draft.drawn, kind: 'outside' };
447    if (now - draft.at >= FIELD_QUIET_MS) return { kind: 'saved' };
448    return {
449        draft: isOwn && !draft.isLanded ? { ...draft, isLanded: true } : draft,
450        kind: 'held',
451    };
452}
453export const typedInto = (
454    draft: FieldDraft | undefined,
455    drawn: string,
456    text: string,
457    now: number,
458): FieldDraft => ({
459    at: now,
460    drawn: draft?.drawn ?? drawn,
461    isLanded: draft?.isLanded ?? false,
462    sent: [...(draft?.sent ?? []).slice(-50), text],
463});
464// a steer field remounts on a clear it cannot otherwise show; a number field keeps its typed text beside its refusal line
465const isNumberField = (key: string) =>
466    key.startsWith('knob:') || key === 'compact-at';
467// a steer keeps its text as typed: a trimmed save was drawn back once typing went quiet, and the desktop field lost
468// what the trim cut (dima's wisp, 10-13 15:42); only spaces is no steer, and the model reads it trimmed
469const steerOf = (value: string) => (value.trim() ? value : undefined);
470function field($: EngineInterface, key: string, saved: string) {
471    // clock-ok: a field draws in a sync render, where $.clock.now() cannot be awaited
472    const view = fieldView(drafts.get(key), saved, Date.now());
473    if (view.kind === 'held') drafts.set(key, view.draft);
474    else drafts.delete(key);
475    if (view.kind === 'outside' && view.isRemount && !isNumberField(key))
476        remounts.set(key, (remounts.get(key) ?? 0) + 1);
477    const value = view.kind === 'held' ? view.draft.drawn : saved;
478    const gen = remounts.get(key);
479    return {
480        key: gen ? `${key}#${gen}` : key,
481        // the save waits for a pause: each save redraws the board, and a redraw mid-typing scrolled the field back to its
482        // start (dima's video, 16:40); a press, a prompt or a tool call flushes it first
483        type: (text: string, save: () => unknown) => {
484            drafts.set(
485                key,
486                // clock-ok: a keystroke lands in a sync handler, where $.clock.now() cannot be awaited
487                typedInto(drafts.get(key), value, text, Date.now()),
488            );
489            // a number is a few characters and never scrolls: it saves on each keystroke, as its refusal line needs
490            if (isNumberField(key)) return void save();
491            pendingSaves.get(key)?.timer.cancel();
492            pendingSaves.set(key, {
493                save,
494                timer: $.clock.after(FIELD_SAVE_MS, () => {
495                    pendingSaves.delete(key);
496                    void save();
497                }),
498            });
499        },
500        value,
501    };
502}
503
504let turnTools = 0;
505let isNudged = false;
506// the phases nudge fires only on a turn that did real work: an edit, a spawn or a stop, a commit, a lane move โ€” a q&a
507// turn keeps quiet and the 3-turn stale mark covers it (PK-70: 235 plan calls in a session, the nudge on every turn)
508let isWorkTurn = false;
509const WORK_TOOLS = new Set([
510    'Edit',
511    'Write',
512    'NotebookEdit',
513    'MultiEdit',
514    'Agent',
515]);
516const WORK_BASH =
517    /\b(claude\s+(--bg|-n\s+\S+.*--bg|stop|respawn)|git\s+commit|x\s+lane\s+(commit|push|pr-open|merge-main|seed)|x\s+mods\s+edit\s+push)\b/;
518export const isWork = (tool: string, command?: string) =>
519    WORK_TOOLS.has(tool) || (tool === 'Bash' && WORK_BASH.test(command ?? ''));
520let isPrimed = false;
521// catch.md owed to cclio: set at her first prompt, paid at the first one with ๐Ÿ  catch switched on
522let isCatchRulesDue = false;
523// the 5h reset as the last session.measure reported it, and this session's cap state
524let fiveHourResetsAt: number | undefined;
525// the dir the session started in: its project, whose .claude settings the threshold input writes
526let projectDir: string | undefined;
527let cap: StashCap | undefined;
528let capGen = 0;
529let turnAfk: boolean | undefined;
530let proc: Proc | undefined;
531// since: the turn end the next ping counts from; only dima's click turns it off, a 5h reset never does
532let hot: { since: number } | undefined;
533let endedAt: number | undefined;
534let isBusy = false;
535// the model label last written for this session, so a step writes the store only when it changes
536let modelSeen: string | undefined;
537// a turn start or a flip bumps it, so a ping armed before either never fires
538let hotGen = 0;
539
540// what the fleet did while dima was afk, shown in the band where he turned ๐Ÿ’จ off until his next prompt
541type Digest = StashDigest;
542let digest: Digest | undefined;
543
544const EMPTY_ORBIT: StashOrbit = { asks: [], next: 1, turns: 0 };
545// mirrors `$.state`'s orbit, which survives a reload: a get inside one dispatch reads the moment it began
546let orbit: StashOrbit = EMPTY_ORBIT;
547// false until this process read its orbit back, from $.state or the kept store; until then nothing is kept, so an
548// empty module copy never writes over the kept one
549let isOrbitLoaded = false;
550
551// one json line to x-speak's control socket; the text rides argv, never the shell's words
552// quiet comms (PK-93, dima's o17: an a/b mvp, one switch to revert): in cclio's thread a member's [progress] ping is
553// held, no turn; every other tag, and no tag, passes; held pings ride her next prompt as one hidden block, or an
554// idle append after 10 min. the a/b reads one log line per delivery from the store (docs/test-drive/quiet-comms.md)
555const QUIET = { key: 'quiet', plugin: 'x-mod-stash' } as const;
556const QUIET_HELD = 'quiet-held:';
557// ๐Ÿฆโ€๐Ÿ”ฅ second wind (todo 16): `wind:<sid>`, written by any board's press and read by that session's own stash at its next
558// turn, so the ask rides the turn and never starts one (dima's slipstream)
559const WIND = 'wind:';
560// dima asking cclio about cost: her context points at the price facts once, so she never answers from recall (o171; 10-13
561// she quoted a cache read at 1/10 of input, the file says 1/20)
562export const COST_WORDS =
563    /\b(?:tokens?|cach(?:e|ed|ing)|(?:ctx|context) costs?|pricing|mtok)\b/i;
564const COST_HINT =
565    "๐Ÿ’ต a cost question: read ~/frame/home/.claude/plugin-x/skills/crew-lead/references/model-cards.md before answering (each model's price line, and the ยซcache reads are where agents spendยป bullet), never from recall.";
566// the button's emoji per state; idle draws the bird
567export const WIND_EMOJI = {
568    asked: '๐Ÿฅš',
569    cancelled: 'โ†ฉ๏ธ',
570    idle: '๐Ÿฆโ€๐Ÿ”ฅ',
571    refreshing: '๐ŸŒ€',
572    writing: 'โœ๏ธ',
573} as const;
574const WIND_SAY = {
575    asked: 'asked, waits for its next turn',
576    cancelled: 'cancelled, tells it at its next turn',
577    refreshing: 'compacting onto its handoff',
578    writing: 'finishing its step, then its handoff',
579} as const;
580const WIND_HOW = `write your handoff with x:handoff (audience: your own role token, slug <lane or topic>-<n>); its first first-act is your role's init list โ€” every skill your role loads at its start and every file it reads whole (a coder: x:crew-coder, x:crew-dna read whole, the tree's AGENTS.md, and its lane's own, plugin-authoring for a mods coder; cclio: her boot), since a compact re-attaches only some of your skills. then call ${ORBIT_TOOL} op second-wind with its slug: at that turn's end the mod compacts this conversation and ingests the handoff, so your next turn starts fresh from it.`;
581const WIND_NOTE = `๐Ÿฆโ€๐Ÿ”ฅ second wind: dima asked you to refresh your context at a good stop. finish the step you are on, nothing interrupts it; a member mid-round (a verifier's loop, a designer's take) stops after that round or take. then ${WIND_HOW}`;
582// cclio's good stop is todo 16's nine steps (dima, 10-13)
583const WIND_NOTE_OWNER = `๐Ÿฆโ€๐Ÿ”ฅ second wind: dima asked you to checkpoint once the topic you are on is done โ€” no rush, no deadline. finish that topic whole first: every lane and agent it started lands, its findings fold, the distill, the print, the log and the commit; a topic is never split across a compact. take nothing new after it. then run cclio:checkpoint, tell the fleet, and put your ยซright after the pickup I'd do Xยป ask into orbit. then ${WIND_HOW}`;
584const WIND_CANCELLED =
585    '๐Ÿฆโ€๐Ÿ”ฅ second wind cancelled: dima took the refresh back. carry on; no handoff needed for it.';
586// the turn's end lets the engine settle before the compact runs
587const WIND_DELAY_MS = 1_000;
588const QUIET_LOG = 'quiet-log:';
589const QUIET_LOG_MAX = 500;
590const QUIET_TAG = /^\s*\[(done|blocked|ask|progress)\]/i;
591// the safety net (brief 6): the ledger's gaps, the canary's test ping, how long a held ping may wait past the idle wait
592const QUIET_GAP = 'quiet-gap';
593const QUIET_CANARY = /^\s*\[progress\]\s*quiet canary ([\w-]+)/i;
594const QUIET_STUCK_MS = 2 * 60_000;
595// a send younger than the grace may still be on its way, so the ledger counts it next minute
596const LEDGER_GRACE_MS = 2 * 60_000;
597const LEDGER_EVERY_MS = 60_000;
598// the alarms already raised, so each gap and each stuck hold notifies once, across reloads too
599const QUIET_ALARMED = 'quiet-alarmed';
600const QUIET_ALARMED_MAX = 50;
601const QUIET_ALARM_TITLE = '๐Ÿšจ quiet comms';
602// osascript's own argv, so no text is ever spliced into the script
603const NOTIFY_SCRIPT =
604    'on run argv\ndisplay notification (item 1 of argv) with title (item 2 of argv)\nend run';
605
606// every way a member addresses cclio in a SendMessage `to`: her name (any ref after it), the socket a reply copies from
607// her envelope's `from`, her session ids โ€” as one grep -E alternation, read wherever `to` sits in the input
608export function cclioAddress(ids: { pid?: number; sids: string[] }) {
609    const literal = (x: string) => x.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
610    const alts = [
611        'cclio',
612        ...(ids.pid ? [`cc-socks/${ids.pid}\\.sock`] : []),
613        ...ids.sids.filter(Boolean).map(literal),
614    ];
615    return `"to":"[^"]*(${alts.join('|')})`;
616}
617
618// only cclio's thread holds anything, known by her registry name โ€” never the cwd, which a Bash `cd` moves: her pings
619// passed unheld from 16:43, the hour she worked cd'd into ~/frame (cclio's wisp, 17:06)
620const isQuietHome = ($: EngineInterface) => isLaneOwner($);
621
622// a peer delivery's body and sender: a cli peer's envelope names it `from-name`, a desktop one `name` (probe, 14:49)
623export function peerPing(text: string) {
624    const from =
625        text.match(/\bfrom-name="([^"]*)"/)?.[1] ??
626        text.match(/\bname="([^"]*)"/)?.[1] ??
627        'a member';
628    const body = text
629        .replace(/^[\s\S]*?<cross-session-message[^>]*>\n?/, '')
630        .replace(/\n?<\/cross-session-message>\s*$/, '');
631    const tag = body.match(QUIET_TAG)?.[1]?.toLowerCase() ?? 'none';
632    const canary = body.match(QUIET_CANARY)?.[1];
633    return { body, from, tag, ...(canary ? { canary } : {}) };
634}
635
636async function quietOf($: EngineInterface): Promise<StashQuiet> {
637    return (
638        (await $.state.get(QUIET).catch(() => undefined))?.value ?? { held: [] }
639    );
640}
641
642// true once the held list is in the session's state; the store copy only feeds the board's row
643async function saveQuiet($: EngineInterface, q: StashQuiet) {
644    const isSaved = await $.state
645        .set(QUIET, q)
646        .then(() => true)
647        .catch(() => false);
648    const sid = await currentId($);
649    if (sid) await $.store.set(QUIET_HELD + sid, q.held).catch(() => undefined);
650    return isSaved;
651}
652
653// true once the line is in the day's log
654async function quietLog($: EngineInterface, line: QuietLogLine) {
655    const key = QUIET_LOG + new Date(line.at).toISOString().slice(0, 10);
656    const was = ((await $.store.get(key).catch(() => undefined)) ??
657        []) as QuietLogLine[];
658    return $.store
659        .set(key, [...was, line].slice(-QUIET_LOG_MAX))
660        .then(() => true)
661        .catch(() => false);
662}
663
664// each held ping that reached cclio's thread gets a `flushed` line, so a canary sees held โ†’ delivered
665async function quietFlushed($: EngineInterface, held: QuietPing[]) {
666    const at = await $.clock.now();
667    for (const p of held)
668        await quietLog($, {
669            arm: 'on',
670            at,
671            from: p.from,
672            startedTurn: false,
673            tag: 'progress',
674            verdict: 'flushed',
675            ...(p.canary ? { canary: p.canary } : {}),
676        });
677}
678
679// the ledger: each live member's sends to cclio, counted from its own transcript, against her quiet log's lines from
680// it; a member that sent more than the log holds lost a ping between the two. the window opens at the day's first log
681// line (before it quiet comms logged nothing) and at the member's start
682async function quietLedger($: EngineInterface, now: number) {
683    const day = new Date(now).toISOString().slice(0, 10);
684    const judged = (
685        ((await $.store.get(QUIET_LOG + day).catch(() => undefined)) ??
686            []) as QuietLogLine[]
687    ).filter((l) => l.verdict !== 'flushed');
688    const opened = judged.length
689        ? Math.min(...judged.map((l) => l.at))
690        : Date.parse(`${day}T00:00:00Z`);
691    const home = await $.env.get('HOME');
692    const me = await currentId($);
693    const pid = (await procNow($))?.pid;
694    const mine = (await $.fs
695        .read(`${home}/.claude/sessions/${pid}.json`)
696        .then((raw) => JSON.parse(raw) as Record<string, unknown>)
697        .catch(() => ({}))) as Record<string, unknown>;
698    const to = cclioAddress({
699        pid,
700        sids: [me, text(mine.hostSessionId)].filter(
701            (x): x is string => typeof x === 'string',
702        ),
703    });
704    const gaps: QuietGap[] = [];
705    for (const r of await registry($)) {
706        if (!r.isAlive || r.base.sid === me) continue;
707        const since = Math.max(opened, r.startedAt ?? 0);
708        // the transcript by its session id, never the cwd: the registry's cwd follows a Bash `cd`
709        const out = await $.process
710            .run(['sh', '-c', LEDGER_SENDS, 'sh', home ?? '', r.base.sid, to])
711            .catch(() => undefined);
712        if (!out) continue;
713        const sent = out.stdout
714            .split('\n')
715            .map((t) => Date.parse(t))
716            .filter((t) => t >= since && t <= now - LEDGER_GRACE_MS).length;
717        // the envelope names ccrow as the registry stores her (ยซ๐Ÿฆ โฌ›ยป, the joiner a space), the board as rejoined: bare both
718        const logged = judged.filter(
719            (l) => bare(l.from) === bare(r.base.name) && l.at >= since,
720        ).length;
721        if (sent > logged) gaps.push({ from: r.base.name, logged, sent });
722    }
723    return gaps;
724}
725
726// ccrow's wake, parked by her wake script for a desktop tab: cclio's thread sends the line itself, no tool call of
727// hers (brief 8 item 2), then marks it sent so her prompt hook starts the harvester; a failed send stays parked for the
728// next poll
729async function relayCcrowWake($: EngineInterface) {
730    if (!(await isLaneOwner($))) return;
731    const path = `${await $.env.get('HOME')}/.local/state/ccrow/relay.json`;
732    const raw = await $.fs.read(path).catch(() => undefined);
733    if (!raw) return;
734    let parked: Record<string, unknown> | null;
735    try {
736        parked = JSON.parse(raw) as Record<string, unknown> | null;
737    } catch {
738        return;
739    }
740    if (!parked || parked.isSent || typeof parked.line !== 'string') return;
741    const crow = memberOf(await registry($), `${CROW} ccrow`);
742    if (!crow) return;
743    const r = await $.session
744        .send({ text: parked.line, to: { sessionId: crow.base.sid } })
745        .catch(() => undefined);
746    if (!r?.isDelivered) return;
747    // a newer wake parked while this one went out stays as it is
748    if ((await $.fs.read(path).catch(() => undefined)) !== raw) return;
749    await $.fs
750        .write(path, JSON.stringify({ ...parked, isSent: true }))
751        .catch(() => undefined);
752}
753
754// one native notification per alarm key: `$.ui.notify` writes only through a terminal (the desktop answers no-surface),
755// so a not-sent one goes out through osascript; both failing leaves a log line, never a throw
756async function quietAlarm($: EngineInterface, key: string, text: string) {
757    const raised =
758        ((await $.store.get(QUIET_ALARMED)) as string[] | undefined) ?? [];
759    if (raised.includes(key)) return;
760    await $.store.set(
761        QUIET_ALARMED,
762        [...raised, key].slice(-QUIET_ALARMED_MAX),
763    );
764    const sent = await $.ui
765        .notify(text, { title: QUIET_ALARM_TITLE })
766        .catch((err: unknown) => ({
767            isSent: false as const,
768            reason: String(err),
769        }));
770    if (sent.isSent) return;
771    const r = await $.process
772        .run(['osascript', '-e', NOTIFY_SCRIPT, text, QUIET_ALARM_TITLE])
773        .catch(() => undefined);
774    if (r?.exitCode === 0) return;
775    await $.ui.log(
776        `x-mod-stash: quiet alarm not raised (notify: ${sent.reason}; osascript: ${r ? `exit ${r.exitCode}` : 'did not run'}): ${text}`,
777    );
778}
779
780// the ledger runs once a minute in cclio's thread; its gaps sit in the store for her board and the boot digest, and each
781// new gap or a held ping stuck past the idle wait + 2 min raises one native alarm beside the board's red row
782let ledgerAt = 0;
783async function quietBooks($: EngineInterface) {
784    if (!(await isQuietHome($))) return;
785    const now = await $.clock.now();
786    if (now - ledgerAt < LEDGER_EVERY_MS) return;
787    ledgerAt = now;
788    const gaps = await quietLedger($, now);
789    await $.store.set(QUIET_GAP, { at: now, gaps });
790    // a member's gap alarms once while it stays open; once it closes, its next gap alarms again
791    const raised =
792        ((await $.store.get(QUIET_ALARMED)) as string[] | undefined) ?? [];
793    const open = new Set(gaps.map((g) => `gap:${g.from}`));
794    const kept = raised.filter((k) => !k.startsWith('gap:') || open.has(k));
795    if (kept.length !== raised.length) await $.store.set(QUIET_ALARMED, kept);
796    for (const g of gaps)
797        await quietAlarm(
798            $,
799            `gap:${g.from}`,
800            `${g.from} sent cclio ${g.sent}, her quiet log holds ${g.logged}`,
801        );
802    const held = heldOf(await $.store.get(QUIET_HELD + (await currentId($))));
803    if (!held) return;
804    const oldest = held.reduce((a, b) => (b.at < a.at ? b : a));
805    const stuckMs =
806        (await readNumber($, 'quietWait')) * 60_000 + QUIET_STUCK_MS;
807    if (now - oldest.at > stuckMs)
808        await quietAlarm(
809            $,
810            `stuck:${oldest.at}`,
811            `${held.length} held ping${held.length === 1 ? '' : 's'} stuck ${Math.round((now - oldest.at) / 60_000)} min, oldest from ${oldest.from}`,
812        );
813}
814
815export const quietNote = (held: QuietPing[]) =>
816    [
817        `๐Ÿคซ quiet comms: ${held.length} held member ping${held.length === 1 ? '' : 's'}, [progress] only; read them, act only if one changes the plan, never relay them to dima.`,
818        ...held.map(
819            (p) =>
820                `- ${new Date(p.at).toTimeString().slice(0, 5)} ${p.from}: ${p.text}`,
821        ),
822    ].join('\n');
823
824// the held pings a session published, for its row; anything else reads as none
825const heldOf = (v: unknown): QuietPing[] | undefined =>
826    Array.isArray(v) && v.length
827        ? v.filter(
828              (p): p is QuietPing =>
829                  typeof p?.at === 'number' &&
830                  typeof p?.from === 'string' &&
831                  typeof p?.text === 'string',
832          )
833        : undefined;
834
835// held pings past 10 min while cclio is idle: one hidden row, no turn (probe Q2, 11:46:50)
836async function quietIdle($: EngineInterface) {
837    const q = await quietOf($);
838    if (!q.held.length) return;
839    if ((await $.state.get(TURN).catch(() => undefined))?.value?.isBusy) return;
840    const now = await $.clock.now();
841    const waitMs = (await readNumber($, 'quietWait')) * 60_000;
842    if (now - Math.min(...q.held.map((p) => p.at)) < waitMs) return;
843    const appended = await $.session
844        .append({
845            message: {
846                content: [{ text: quietNote(q.held), type: 'text' }],
847                type: 'user',
848            },
849        })
850        .catch(() => undefined);
851    if (!appended || 'deny' in appended) return;
852    await saveQuiet($, { ...q, held: [] });
853    await quietFlushed($, q.held);
854}
855
856// speak's own answer to `status`: reading and not paused draws โธ๏ธ on every play button, else โ–ถ๏ธ (dima, 15:51)
857const SPEAKING = { key: 'speaking', plugin: 'x-mod-stash' } as const;
858async function refreshSpeaking($: EngineInterface) {
859    const r = await speak($, { op: 'status' });
860    let isPlaying = false;
861    try {
862        const v = JSON.parse(r ?? '{}') as {
863            speaking?: unknown;
864            paused?: unknown;
865        };
866        isPlaying = v.speaking === true && v.paused !== true;
867    } catch {}
868    if ((await $.state.get(SPEAKING)).value !== isPlaying)
869        await $.state.set(SPEAKING, isPlaying).catch(() => undefined);
870}
871
872async function speak($: EngineInterface, request: Record<string, string>) {
873    const socket = `${await $.env.get('HOME')}/.local/share/x-speak/control.sock`;
874    const r = await $.process
875        .run([
876            'sh',
877            '-c',
878            'printf "%s\\n" "$1" | nc -U -w 2 "$2"',
879            'sh',
880            JSON.stringify(request),
881            socket,
882        ])
883        .catch(() => undefined);
884    if (!r || r.exitCode !== 0 || r.stdout.includes('"error"')) {
885        $.ui.log(
886            `x-mod-stash orbit: speak did not take ${request.op}: ${r?.stdout.trim() || r?.stderr.trim() || 'no answer'}`,
887        );
888        return undefined;
889    }
890    return r.stdout;
891}
892
893// a play press: pause or resume what reads, or read this row when nothing does; the status is read again after it
894async function playPress($: EngineInterface, text: string) {
895    const isPlaying = (await $.state.get(SPEAKING)).value === true;
896    const status = isPlaying ? undefined : await speak($, { op: 'status' });
897    const isPaused = status ? /"paused":true/.test(status) : false;
898    const isSpeaking = status ? /"speaking":true/.test(status) : false;
899    await speak(
900        $,
901        isPlaying || (isSpeaking && isPaused)
902            ? { op: 'pause' }
903            : { op: 'read', text },
904    );
905    await refreshSpeaking($);
906}
907
908// kept in $.state for this session, and its open asks mirrored into the store, where the board's `๐Ÿช n` and the away
909// digest count every session's
910async function saveOrbit($: EngineInterface, next: StashOrbit) {
911    orbit = next;
912    await $.state
913        .set(ORBIT, orbit)
914        .catch((err) =>
915            $.ui.log(`x-mod-stash: orbit was not kept: ${errorText(err)}`),
916        );
917    if (await isLaneOwner($))
918        await $.store
919            .set(CATCH_SHELF, orbit.caught ?? [])
920            .catch(() => undefined);
921    await keepState($, { orbit }).catch(() => undefined);
922    const sid = await currentId($);
923    if (!sid) return;
924    const open = orbit.asks.filter((a) => !a.isResolved);
925    const asks = open.map((a) => a.text);
926    if (asks.length)
927        await $.store
928            .set(PREFIX + sid, {
929                asks,
930                at: await $.clock.now(),
931                items: open.map((a) => ({
932                    id: a.id,
933                    pick: a.pick,
934                    text: a.text,
935                    ...(a.link ? { link: a.link } : {}),
936                    ...(a.mark ? { mark: a.mark } : {}),
937                    ...(a.sendAt ? { sendAt: a.sendAt } : {}),
938                    ...(a.steer ? { steer: a.steer } : {}),
939                    ...(a.isLocked ? { isLocked: true } : {}),
940                })),
941                label,
942                name: await sessionName($),
943            } satisfies Entry)
944            .catch(() => undefined);
945    else await $.store.delete(PREFIX + sid).catch(() => undefined);
946}
947
948// cclio's pieces: an empty orbit (a new session after a checkpoint or a handoff) takes her shelf from the store; a piece
949// kept before the kinds reads as a ๐Ÿ’ก; new ids count past the shelf's, so none collides
950async function shelfOrbit($: EngineInterface, o: StashOrbit) {
951    if (!(await isLaneOwner($))) return o;
952    const now = await $.clock.now();
953    const shelf = o.caught?.length
954        ? o.caught
955        : (((await $.store.get(CATCH_SHELF).catch(() => undefined)) ??
956              []) as OrbitCatch[]);
957    if (!shelf.length) return o;
958    const top = Math.max(0, ...shelf.map((x) => Number(x.id.slice(1)) || 0));
959    return {
960        ...o,
961        caught: shelf.map((x) => shelved(x, now)),
962        next: Math.max(o.next, top + 1),
963    };
964}
965
966// the orbit as $.state holds it now: a reload can run a hook before session.start reads it back, and a module copy
967// that never loaded would write an empty orbit over the kept one (FRM-381: ยซcoder wiped the orbitยป)
968async function currentOrbit($: EngineInterface) {
969    const kept = (await $.state.get(ORBIT).catch(() => undefined))?.value;
970    if (kept) orbit = steeredOrbit(kept);
971    // a new process whose first hook is a turn's end, before its start (an app restart mid-turn): the kept copy first
972    else if (!isOrbitLoaded)
973        orbit = await resumeState($).catch(() => EMPTY_ORBIT);
974    isOrbitLoaded = true;
975    return orbit;
976}
977
978// a glide card's marks on one member's asks: one store key per ask, `marks:<sid>:<ask id>`, so a board writes only its
979// own key and the member deletes only the keys it read โ€” a shared map lost or re-applied marks across sessions
980const markKey = (sid: string, askId: string) => `${MARKS}${sid}:${askId}`;
981
982async function marksOf($: EngineInterface, sid: string) {
983    const marks: Record<string, RemoteMark> = {};
984    const keys = (await $.store.keys().catch(() => [] as string[])).filter(
985        (k) => k.startsWith(`${MARKS}${sid}:`),
986    );
987    for (const key of keys) {
988        const m = (await $.store.get(key).catch(() => undefined)) as
989            | RemoteMark
990            | undefined;
991        if (m) marks[key.slice(`${MARKS}${sid}:`.length)] = steered(m);
992    }
993    return marks;
994}
995
996// marks dima made on another board's glide card join this session's own orbit, as if made here
997async function absorbMarks($: EngineInterface) {
998    const sid = await currentId($);
999    if (!sid) return;
1000    const marks = await marksOf($, sid);
1001    if (!Object.keys(marks).length) return;
1002    for (const id of Object.keys(marks))
1003        await $.store.delete(markKey(sid, id)).catch(() => undefined);
1004    const o = await currentOrbit($);
1005    const win = await sendWindow($);
1006    await saveOrbit($, {
1007        ...o,
1008        asks: o.asks.map((a) => {
1009            const m = marks[a.id];
1010            if (!m || a.isLocked || a.isResolved) return a;
1011            return {
1012                ...a,
1013                isChanged: false,
1014                mark: m.mark,
1015                markedAt: m.mark ? m.at : undefined,
1016                sendAt: m.mark ? (m.markAt ?? m.at) + win : undefined,
1017                steer: m.steer,
1018            };
1019        }),
1020    });
1021}
1022
1023// an idle session whose asks were marked from another board wakes once dima prompts anywhere after the marks: one turn
1024// carrying all of them. the submitted prompt skips this plugin's own prompt.submit hook, so the marks ride its text
1025async function wakeForMarks($: EngineInterface) {
1026    if (
1027        (await $.state.get(TURN).catch(() => undefined))?.value?.isBusy ??
1028        isBusy
1029    )
1030        return;
1031    if (!(await partsShown($))('stash.orbit')) return;
1032    const o = await currentOrbit($);
1033    const due = o.asks
1034        .filter(isDue(await $.clock.now()))
1035        .filter((a) => a.markedAt !== undefined);
1036    if (!due.length) return;
1037    const dimaAt = Number(await $.store.get(DIMA_AT).catch(() => 0)) || 0;
1038    if (dimaAt <= Math.min(...due.map((a) => a.markedAt ?? 0))) return;
1039    await saveOrbit($, lockJoined(o, due));
1040    void selfSubmit($, joinText(due)).catch(() => undefined);
1041}
1042
1043// a plan set this turn counts from the turn's end, so a prompt landing mid-turn would read it as -1
1044const planAge = (o: StashOrbit) =>
1045    o.plan === undefined ? undefined : Math.max(0, o.turns - o.plan.at);
1046
1047// the per-prompt note that keeps the habit through a compaction; none while orbit is empty
1048function orbitReminder(o: StashOrbit, isOn: IsPartOn) {
1049    const open = o.asks.filter((a) => !a.isResolved);
1050    const isPhasesOn = isOn('stash.phases');
1051    const age = isPhasesOn ? planAge(o) : undefined;
1052    const caught = isOn('stash.catch') ? (o.caught ?? []) : [];
1053    if (!open.length && age === undefined && !caught.length) return undefined;
1054    const asks = open.length
1055        ? `orbit holds ${open.length} open ask${open.length === 1 ? '' : 's'} (${open.map((a) => a.id).join(', ')})`
1056        : 'orbit holds no open ask';
1057    const plan = !isPhasesOn
1058        ? ''
1059        : age === undefined
1060          ? '; no plan set'
1061          : `; plan set ${age} turn${age === 1 ? '' : 's'} ago${age >= STALE_TURNS ? ', stale: set it again' : ''}`;
1062    // her held ids, so a compacted cclio can still clear a piece whose lifetime ended
1063    const held = caught.length
1064        ? `; ๐Ÿ  catch holds ${caught.map((x) => x.id).join(', ')}`
1065        : '';
1066    return `${asks}${plan}${held}. asks${isPhasesOn ? ' and the plan' : ''} go through ${ORBIT_TOOL}, never into a reply.`;
1067}
1068
1069// the one reply shape while no board reaches dima โ€” ๐Ÿ“ฑ mobile mode, where mods draw nothing, or ๐Ÿช orbit switched off โ€”
1070// the same text either way (dima's o162); x:mobile-mode keeps only its phone bits and points here
1071function noBoardReminder(o: StashOrbit, isOn: IsPartOn) {
1072    const open = o.asks.filter((a) => !a.isResolved);
1073    const ids = open.length ? ` (${open.map((a) => a.id).join(', ')})` : '';
1074    // the phases are gone off the board too: the plan's next 3 moves print under the fence (dima's o112, 2026-10-11)
1075    const isPhasesOn = isOn('stash.phases');
1076    const age = planAge(o);
1077    const stale =
1078        isPhasesOn && age !== undefined && age >= STALE_TURNS
1079            ? ` the plan is stale, untouched ${age} turns: set it again through ${ORBIT_TOOL}.`
1080            : '';
1081    const moves = isPhasesOn
1082        ? ", then ยซ๐ŸŒ” next:ยป and the plan's next 3 moves as bullets"
1083        : '';
1084    return `no board reaches dima: end the reply with the asks fence, ยซโณ waiting on your word:ยป, every open orbit ask${ids} with its id and pick, and each new ask as one โžก๏ธ line${moves}. his answers come back in his prompt; resolve the ones he answered by id through ${ORBIT_TOOL} while ๐Ÿช orbit is switched on.${stale}`;
1085}
1086
1087const enhancerOf = async ($: EngineInterface): Promise<StashEnhancer> =>
1088    (await $.state.get(ENHANCER)).value ?? { status: 'idle' };
1089const saveEnhancer = ($: EngineInterface, next: StashEnhancer) =>
1090    $.state.set(ENHANCER, next).catch(() => undefined);
1091
1092// what Haiku reads beside the prompt: the rules, every slash command by name, and dima's wispr dictionary
1093async function enhancerSystem($: EngineInterface) {
1094    const rules = await $.fs.read(`${$.plugin.root}/enhancer.md`);
1095    const commands = (await $.command.list().catch(() => []))
1096        .map((c) => `/${c.name} โ€” ${c.description}`)
1097        .join('\n');
1098    const dictionary = await $.process
1099        .run([
1100            'sqlite3',
1101            '-readonly',
1102            '-separator',
1103            ' โ†’ ',
1104            `${await $.env.get('HOME')}/${WISPR_DB}`,
1105            'select coalesce(isSnippet, 0), phrase, replacement from Dictionary where isDeleted = 0 and replacement is not null',
1106        ])
1107        .catch(() => undefined);
1108    // only the mishearing rows: wispr flags a snippet (a short cue for a long text), whose extra lines lead with no flag
1109    // (dima, 2026-10-11 11:11)
1110    const heard =
1111        dictionary?.exitCode === 0
1112            ? dictionary.stdout
1113                  .split('\n')
1114                  .filter((l) => l.startsWith('0 โ†’ '))
1115                  .map((l) => l.slice('0 โ†’ '.length))
1116                  .join('\n')
1117            : '(unreadable now)';
1118    return [
1119        { text: rules },
1120        { text: `the slash commands:\n${commands}` },
1121        {
1122            cache: true as const,
1123            text: `dima's dictionary, heard โ†’ meant:\n${heard}`,
1124        },
1125    ];
1126}
1127
1128// what each ticket a prompt names is, read through `x linear`, so the session starts with it instead of looking it up;
1129// x down or an unknown id adds nothing (dima's o14, 23:07)
1130async function ticketNote($: EngineInterface, text: string) {
1131    const ids = [...new Set(text.match(TICKET_ID_ALL) ?? [])];
1132    if (!ids.length) return undefined;
1133    const r = await $.process
1134        .run([
1135            `${await $.env.get('HOME')}/.local/bin/x`,
1136            'linear',
1137            'read',
1138            ...ids,
1139        ])
1140        .catch(() => undefined);
1141    if (r?.exitCode !== 0) return undefined;
1142    try {
1143        const tickets =
1144            (
1145                JSON.parse(r.stdout) as {
1146                    data?: {
1147                        tickets?: {
1148                            id?: string;
1149                            title?: string;
1150                            state?: string;
1151                            url?: string;
1152                        }[];
1153                    };
1154                }
1155            ).data?.tickets ?? [];
1156        const lines = tickets.flatMap((x) =>
1157            x.id && x.url
1158                ? [`${x.id}: ${x.title ?? ''} ยท ${x.state ?? ''} ยท ${x.url}`]
1159                : [],
1160        );
1161        return lines.length
1162            ? `the tickets this prompt names, read from linear:\n${lines.join('\n')}`
1163            : undefined;
1164    } catch {
1165        return undefined;
1166    }
1167}
1168
1169// one call per press; a keystroke while it runs keeps his text and drops the answer, an error leaves the box alone
1170async function enhance($: EngineInterface) {
1171    // set before any await, so a second press in the same moment finds it
1172    if (isEnhancing) return;
1173    isEnhancing = true;
1174    try {
1175        await enhanceOnce($);
1176    } finally {
1177        isEnhancing = false;
1178    }
1179}
1180
1181async function enhanceOnce($: EngineInterface) {
1182    const before = await enhancerOf($);
1183    const pressed = (await $.prompt.read()).text;
1184    if (!pressed.trim()) return;
1185    await saveEnhancer($, { ...before, error: undefined, status: 'running' });
1186    const stop = new AbortController();
1187    const timer = $.clock.after(ENHANCE_MS, () => stop.abort());
1188    let answer: string | undefined;
1189    let failure: string | undefined;
1190    try {
1191        const r = await $.model.complete(
1192            {
1193                maxTokens: 2048,
1194                model: ENHANCE_MODEL,
1195                prompt: pressed,
1196                system: await enhancerSystem($),
1197            },
1198            { signal: stop.signal },
1199        );
1200        if (r.isAnswered && r.text.trim()) answer = r.text.trim();
types/stash.d.ts 289 lines
1// one session's open asks, as its orbit holds them
2export type StashEntry = {
3    label: string;
4    name?: string;
5    asks: string[];
6    // the open asks whole, so a glide card on another board draws and marks them (FRM-385 exit 3)
7    items?: PublishedAsk[];
8    at: number;
9};
10
11export type PublishedAsk = {
12    id: string;
13    text: string;
14    pick: string;
15    link?: string;
16    mark?: 'accepted' | 'rejected';
17    steer?: string;
18    isLocked?: boolean;
19    // a mark still inside its 5 s sending window ends here (ms)
20    sendAt?: number;
21};
22
23// a mark or steer dima made on another board's glide card, waiting in the store for the member to take it in
24export type RemoteMark = {
25    mark?: 'accepted' | 'rejected';
26    steer?: string;
27    at: number;
28    // when the mark itself last changed, so a steer edit never restarts its sending window
29    markAt?: number;
30};
31
32// the session's last main turn stopped on the 5h cap: the reset it waits for, and the reset a resume already went for
33export type StashCap = { resetsAt?: number; sentFor?: number };
34
35// what the fleet did while dima was afk
36export type StashDigest = {
37    needs: { sid: string; name: string; asks: number }[];
38    done: { sid: string; name: string }[];
39};
40
41// one row of the fleet board
42export type StashMember = {
43    sid: string;
44    name: string;
45    status?: string;
46    statusSince?: number;
47    wait?: string;
48    // ccrow's row only: her newest ๐Ÿ‘€ ยซfor youยป tip, which takes the wait's place (PK-73)
49    tip?: string;
50    // cclio's row only: the member pings quiet comms holds for her next turn, opened from her row's ๐Ÿคซ n
51    held?: QuietPing[];
52    // a held ping older than the idle wait + 2 min: the ๐Ÿคซ n reads red
53    isHeldStuck?: boolean;
54    asks: number;
55    context?: number;
56    model?: string;
57    offPattern: boolean;
58    // second wind asked of this session from a board, and where it stands
59    wind?: StashWind;
60};
61
62// second wind for one session, a store key every board reads: asked from a board, writing once its turn carried the
63// note, refreshing once it named its handoff, cancelled when a second press took it back after the note went out
64export type StashWind = {
65    state: 'asked' | 'writing' | 'refreshing' | 'cancelled';
66    at: number;
67    slug?: string;
68};
69
70// the band's two meters: this session's context against its compaction point, and the account's 5h window;
71// `note` is the one line a refused threshold leaves
72export type StashMeter = {
73    context?: number;
74    compactAt?: number;
75    fiveHour?: { used: number; resetsAt?: number };
76    note?: string;
77    // the poll's minute, so an idle band's time left moves on its own
78    minute?: number;
79};
80
81// everything the band draws, written by the poll and the hooks; a render reads it and redraws on a write
82export type StashView = {
83    selfId?: string;
84    // what this session's last reply waits on, its ๐Ÿ”ญ line
85    wait?: string;
86    afk: boolean;
87    isHot: boolean;
88    isWaker: boolean;
89    digest?: StashDigest;
90    isBoardOpen: boolean;
91    // this session's own second wind, for the band's button
92    wind?: StashWind['state'];
93    // the settings view: open in this session, and each part's switch as every session reads it (a missing key is shown)
94    isSettingsOpen: boolean;
95    shown: Record<string, boolean>;
96};
97
98// what only the board pane draws, kept apart from the band's view: its clock moves every poll, and a band that read it
99// would redraw โ€” rebuilding the bars' svg (FRM-354)
100export type StashBoardView = {
101    members?: StashMember[];
102    isColour: boolean;
103    // the ctx meter drawn as a ring (C), else the % with a bar under it (B)
104    isRing: boolean;
105    // the poll's clock, so the board's ยซbusy 3mยป spans move on their own
106    at: number;
107    // cclio's board only: each dev-mods probe past its probe, ยซ<mod> (<session short id>)ยป
108    staleProbes?: string[];
109    // cclio's board only: the ledger's gaps, from the store's `quiet-gap`
110    quietGaps?: QuietGap[];
111};
112
113// the running turn, kept so a mid-turn reload still knows it: busy, dima's own, a keep-hot ping, afk as it began
114export type StashTurn = {
115    isBusy: boolean;
116    isUserTurn: boolean;
117    isPinged: boolean;
118    afk?: boolean;
119};
120
121// one ask to dima in orbit: what is asked and cclio's pick, the steer cclio keeps for herself, dima's mark and steer;
122// locked while the turn it joined runs, changed after a follow-up, resolved until that turn ends
123export type OrbitAsk = {
124    id: string;
125    text: string;
126    pick: string;
127    hiddenNote?: string;
128    // one https url or file path dima opens in a click (brief 8: proposals sat in scratch files he dug for)
129    link?: string;
130    mark?: 'accepted' | 'rejected';
131    steer?: string;
132    isLocked?: boolean;
133    isChanged?: boolean;
134    isResolved?: boolean;
135    // when a mark came in from another board: an idle session wakes once dima prompts anywhere after it
136    markedAt?: number;
137    // a fresh mark is ยซsendingยป until this time (ms): a second press before it unsends it, and no turn takes it yet
138    sendAt?: number;
139    // an expiry: ยซhaltยป leaves at cclio's halt, a number is dima's prompt count whose turn end takes it while still unmarked
140    dies?: 'halt' | number;
141    // the closing word a resolve gave it (ยซlandedยป, ยซdropped: superseded by o58ยป)
142    word?: string;
143    // resolved with a word in a turn that has ended: drawn dim for one more turn, then it leaves
144    isClosed?: boolean;
145};
146
147// one choice the session made without asking, that costs a redo if wrong: born at a turn count; dima's send-back
148// button marks it wrong, with his steer
149export type OrbitAssumption = {
150    id: string;
151    text: string;
152    at: number;
153    isWrong?: boolean;
154    steer?: string;
155};
156
157// ๐Ÿ  a piece of cclio's keep-in-mind shelf (FRM-386, PK-96): one of catch.md's seven kinds, born at `at` (ms); ๐Ÿค” asks
158// for it to be explained, locked while a turn takes it; it stays until dima or cclio clears it
159export type OrbitCatch = {
160    id: string;
161    // one of CATCH_KINDS; a piece kept before the kinds has none and reads as ๐Ÿ’ก
162    kind?: string;
163    text: string;
164    hiddenNote?: string;
165    steer?: string;
166    at: number;
167    isAsked?: boolean;
168    isLocked?: boolean;
169};
170
171// the ๐Ÿ  catch experiment's counts for one day, read at its keep-or-kill
172export type CatchCount = { thinks: number; clears: number; refused: number };
173
174// quiet comms (PK-93): a [progress] ping from a member, held off cclio's thread until her next turn
175// `canary`: the nonce of a `/quiet-canary` test ping, so its run finds its own log lines
176export type QuietPing = {
177    at: number;
178    from: string;
179    text: string;
180    canary?: string;
181};
182// the pings held for cclio's next turn; the on/off switch is a settings knob in the store
183export type StashQuiet = { held: QuietPing[] };
184// one delivery as the a/b reads it
185export type QuietLogLine = {
186    at: number;
187    from: string;
188    tag: string;
189    // failed-open: the hook threw, so the delivery passed unjudged
190    verdict: 'held' | 'passed' | 'flushed' | 'failed-open';
191    startedTurn: boolean;
192    arm: 'on' | 'off';
193    canary?: string;
194};
195// the ledger: a member whose transcript sent cclio more pings than her quiet log holds since the window opened
196export type QuietGap = { from: string; sent: number; logged: number };
197
198// the session's orbit: its asks oldest first, the next id's number, the main turns ended so far, and the plan with
199// the turn count it was set at
200export type StashOrbit = {
201    asks: OrbitAsk[];
202    assumed?: OrbitAssumption[];
203    caught?: OrbitCatch[];
204    next: number;
205    turns: number;
206    // dima's own prompts sent while ๐Ÿ’จ afk was not in effect: the clock an ask's `dies` counts on (o164/o165)
207    prompts?: number;
208    plan?: StashPlan;
209};
210
211// the session's phases: its next moves, the turn count they were set at, and what dima did to them on the board โ€” a
212// reorder, a tick on the order, his steer โ€” waiting, like an orbit tick, until `sendAt` before a turn takes it (o84)
213export type StashPlan = {
214    lines: string[];
215    at: number;
216    isMoved?: boolean;
217    mark?: 'accepted';
218    steer?: string;
219    sendAt?: number;
220};
221
222// ๐Ÿ›ผ glide (FRM-385): one live lane of the fleet, kept in one shelf file every board reads and only cclio writes;
223// โ‰ค5 plain steps, the pointer and what moved it; done steps stay listed
224export type LaneItem = { text: string; ticket?: string; isDone: boolean };
225export type LaneRole = 'coder' | 'verifier';
226export type StashLane = {
227    id: string;
228    title: string;
229    items: LaneItem[];
230    // the step we are on; items.length once every step is done
231    current: number;
232    // cclio's orbit turn count when the pointer or a done flag last moved
233    movedAt: number;
234    // the linked members as the registry names them (an id the registry did not know stays as given); a re-link of a
235    // role replaces the old one
236    members: Partial<Record<LaneRole, string>>;
237    // the board's view only: each member's session id now, resolved from its name at every draw
238    memberSids?: Partial<Record<LaneRole, string>>;
239    // dima's steer on the current step: a draft until his take, then it joins cclio's next prompt or running turn once
240    steer?: string;
241    isSteerTaken?: boolean;
242    // `by`: the linked coder whose plan step moved the pointer forward, written by cclio's stash
243    history: {
244        at: number;
245        act: string;
246        by?: string;
247        current: number;
248        done: number;
249    }[];
250    endedAt?: number;
251};
252
253// the prompt enhancer: the box at the last press and the enhanced text as last seen (his edits kept), the call's
254// state, and why the last press left the box alone
255export type StashEnhancer = {
256    original?: string;
257    latest?: string;
258    status: 'idle' | 'running';
259    error?: string;
260};
261
262declare module 'claude-code' {
263    interface PluginState {
264        'x-mod-stash': {
265            // speak is reading aloud and not paused: the board's play button reads pause (dima, 15:51)
266            speaking: boolean;
267            quiet: StashQuiet;
268            view: StashView;
269            board: StashBoardView;
270            turn: StashTurn;
271            meter: StashMeter;
272            // null: the last main turn did not stop on the cap
273            cap: StashCap | null;
274            // epoch ms of the last main turn end
275            ended: number;
276            orbit: StashOrbit;
277            // dima is on mobile: the reminder asks for the asks fence instead of orbit
278            mobile: boolean;
279            enhancer: StashEnhancer;
280            // the fleet's live lanes as this session last read the shelf file
281            lanes: StashLane[];
282            // each linked member's open asks, by session id, its pending remote marks laid over them
283            laneAsks: Record<string, PublishedAsk[]>;
284            // the board's cards folded to their head row, by card: sessions, orbit, phases
285            folds: Record<string, boolean>;
286        };
287    }
288}
289
hooks/orbit.ts 508 lines
1// orbit's rules as pure steps over one session's orbit: the tool's ops, dima's marks joining a turn, the turn's end.
2// register.tsx owns every $ call: it reads the orbit from $.state, applies a step here, and saves the result.
3import type {
4    OrbitAsk,
5    OrbitAssumption,
6    OrbitCatch,
7    StashOrbit,
8    StashPlan,
9} from '../types/stash.d.ts';
10
11export const ORBIT_TOOL = 'mcp__x-mod-stash__orbit';
12export const PLAN_MAX = 7;
13// a followed-up ask's mark, before its id so the text keeps the full width โ€” a try, dima may swap the glyph (o6)
14export const CHANGED_MARK = '๐Ÿ†•';
15// an ask, a follow-up or a phase reads at a glance in the narrow board (dima's o60, 22:13)
16export const ORBIT_TEXT_MAX = 90;
17// at most this many assumptions a turn, and on the board at once (FRM-382 exit 2: under one a turn on average)
18export const ASSUMED_MAX = 3;
19// an ask's one link: an https url, or an absolute or home path to a file
20export const ASK_LINK = /^(https:\/\/|\/|~\/)\S+$/;
21export const ASSUMED_TURNS = 3;
22// ๐Ÿ  catch v2 (PK-96): catch.md's seven kinds, a piece โ‰ค60 chars, 5 rows drawn and 7 held; the rules live in catch.md
23export const CATCH_KINDS = ['๐Ÿ“', '๐Ÿงท', 'โœ…', '๐ŸŽฏ', 'โฐ', '๐Ÿ’ก', '๐Ÿ“ฆ'] as const;
24export const CATCH_TEXT_MAX = 60;
25export const CATCH_SHOWN = 5;
26export const CATCH_HELD_MAX = 7;
27// the kind a full shelf drops first, oldest first: a fact can be found again, a receipt or a reminder cannot
28const CATCH_DROPS = '๐Ÿ’ก';
29
30export const oneLine = (v: unknown) =>
31    typeof v === 'string' ? v.replace(/\s+/g, ' ').trim() : '';
32const idsOf = (v: unknown) =>
33    Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string') : [];
34
35// a marked ask no turn has taken yet
36export const isFresh = (a: OrbitAsk) =>
37    Boolean(a.mark) && !a.isLocked && !a.isResolved;
38
39// PK-88: a tick or replay waits SEND_MS in a reversible ยซsendingยป state before a turn may take it
40export const SEND_MS = 5000;
41export const isSending = (
42    a: { mark?: unknown; sendAt?: number },
43    now: number,
44) => Boolean(a.mark) && a.sendAt !== undefined && now < a.sendAt;
45// a fresh mark whose sending window has passed
46export const isDue = (now: number) => (a: OrbitAsk) =>
47    isFresh(a) && !isSending(a, now);
48
49// a text kept under the fields' old name, ยซnoteยป, before the steer rename (dima's o57, 17:39): read once as its steer
50export function steered<T extends { steer?: string }>(x: T): T {
51    if (!('note' in x)) return x;
52    const { note, ...rest } = x as T & { note?: unknown };
53    return (
54        typeof note === 'string' && rest.steer === undefined
55            ? { ...rest, steer: note }
56            : rest
57    ) as T;
58}
59
60// an orbit kept before prompts counted holds each `dies` as a turn end: its turns left become prompts left
61const prompted = (o: StashOrbit): StashOrbit =>
62    o.prompts !== undefined
63        ? o
64        : {
65              ...o,
66              asks: o.asks.map((a) =>
67                  typeof a.dies === 'number'
68                      ? { ...a, dies: Math.max(1, a.dies - o.turns) }
69                      : a,
70              ),
71              prompts: 0,
72          };
73
74export const steeredOrbit = (kept: StashOrbit): StashOrbit => {
75    const o = prompted(kept);
76    return {
77        ...o,
78        asks: o.asks.map(steered),
79        ...(o.assumed ? { assumed: o.assumed.map(steered) } : {}),
80        ...(o.caught ? { caught: o.caught.map(steered) } : {}),
81    };
82};
83
84// a piece kept before catch v2 has no kind and a turn count in `at`: it reads as a ๐Ÿ’ก born at the load
85export const shelved = (x: OrbitCatch, now: number): OrbitCatch =>
86    x.kind ? x : { ...x, at: now, kind: CATCH_DROPS };
87
88// a steer the turn carried has gone out: its field clears for the next one, so a second tick never resends it
89const unsteer = <T extends { steer?: string }>(x: T): T => {
90    const { steer: _, ...rest } = x;
91    return rest as T;
92};
93
94// the asks a turn takes are locked to it until it ends; a remote mark's wake time is spent
95export function lockJoined(o: StashOrbit, asks: OrbitAsk[]): StashOrbit {
96    const ids = new Set(asks.map((a) => a.id));
97    return {
98        ...o,
99        asks: o.asks.map((a) =>
100            ids.has(a.id)
101                ? {
102                      ...a,
103                      isLocked: true,
104                      markedAt: undefined,
105                      sendAt: undefined,
106                  }
107                : a,
108        ),
109    };
110}
111
112// the turn's answers leave, one with a closing word drawn dim one turn more; a marked ask it never resolved unlocks
113// and rides dima's next prompt; an unmarked ask whose `dies` prompt came leaves; an unmarked assumption leaves at its third
114// turn end, the turn it was made in counted; one sent back waits for his prompt
115export function turnEnded(o: StashOrbit): StashOrbit {
116    return {
117        ...o,
118        asks: o.asks
119            .filter(
120                (a) =>
121                    !a.isClosed &&
122                    (!a.isResolved || a.word) &&
123                    !(
124                        typeof a.dies === 'number' &&
125                        !a.mark &&
126                        !a.isResolved &&
127                        (o.prompts ?? 0) >= a.dies
128                    ),
129            )
130            .map((a) => (a.isResolved ? { ...a, isClosed: true } : a))
131            .map((a) => (a.isLocked ? { ...unsteer(a), isLocked: false } : a)),
132        assumed: (o.assumed ?? []).filter(
133            (x) => x.isWrong || o.turns + 2 - x.at < ASSUMED_TURNS,
134        ),
135        caught: o.caught?.map((x) =>
136            x.isLocked ? { ...unsteer(x), isLocked: false } : x,
137        ),
138        turns: o.turns + 1,
139    };
140}
141
142// cclio's halt: every ask born to die there leaves, unless a running turn holds it
143export const halted = (o: StashOrbit): StashOrbit => ({
144    ...o,
145    asks: o.asks.filter((a) => a.dies !== 'halt' || a.isLocked),
146});
147
148// an ask's expiry as the tool takes it: ยซhaltยป, or 1โ€“DIES_MAX of dima's prompts unpicked, counted from its birth
149export const DIES_MAX = 20;
150function diesOf(v: unknown, born: number): OrbitAsk['dies'] | 'bad' {
151    if (v === undefined || v === null || v === '') return undefined;
152    if (v === 'halt') return 'halt';
153    const n = typeof v === 'string' ? Number(v) : v;
154    return typeof n === 'number' &&
155        Number.isInteger(n) &&
156        n >= 1 &&
157        n <= DIES_MAX
158        ? born + n
159        : 'bad';
160}
161
162const markWord = (mark: OrbitAsk['mark']) =>
163    mark === 'accepted' ? '๐Ÿ›Ž๏ธ accepted' : 'โ†ฉ๏ธ rejected';
164
165// what the session reads for each assumption dima sent back: the assumption and his steer
166export const wrongText = (wrong: OrbitAssumption[]) =>
167    [
168        `orbit: dima marked ${wrong.length === 1 ? 'an assumption' : `${wrong.length} assumptions`} wrong; take it into account in this reply.`,
169        ...wrong.map(
170            (x) =>
171                `- ${x.id} wrong assumption: ${x.text}` +
172                (x.steer ? ` ยท his steer: ยซ${x.steer.trim()}ยป` : ''),
173        ),
174    ].join('\n');
175
176// the ๐Ÿค” pieces no turn has taken yet
177export const isThought = (x: OrbitCatch) => Boolean(x.isAsked) && !x.isLocked;
178
179// a turn takes the ๐Ÿค” pieces once: they lock to it and stay held until dima clears them
180export function lockThought(o: StashOrbit, pieces: OrbitCatch[]): StashOrbit {
181    const ids = new Set(pieces.map((x) => x.id));
182    return {
183        ...o,
184        caught: o.caught?.map((x) =>
185            ids.has(x.id) ? { ...x, isAsked: false, isLocked: true } : x,
186        ),
187    };
188}
189
190// what the session reads for each ๐Ÿค”: the piece, its hidden note, his steer
191export const thinkText = (pieces: OrbitCatch[]) =>
192    [
193        `๐Ÿ  catch: dima pressed ๐Ÿค” on ${pieces.length === 1 ? 'a piece' : `${pieces.length} pieces`}: explain each in this reply, plainly, with the why. the piece stays until he clears it.`,
194        ...pieces.map(
195            (x) =>
196                `- ${x.id}: ${x.text}` +
197                (x.hiddenNote ? ` ยท your note: ยซ${x.hiddenNote}ยป` : '') +
198                (x.steer ? ` ยท his steer: ยซ${x.steer.trim()}ยป` : ''),
199        ),
200    ].join('\n');
201
202// what the session reads for each marked ask: the mark, the ask, its pick, both steers
203export function joinText(asks: OrbitAsk[]) {
204    const lines = asks.map(
205        (a) =>
206            `- ${a.id} ${markWord(a.mark)}: ${a.text} (your pick: ${a.pick})` +
207            (a.steer ? ` ยท his steer: ยซ${a.steer.trim()}ยป` : '') +
208            (a.hiddenNote ? ` ยท your note: ยซ${a.hiddenNote}ยป` : ''),
209    );
210    return [
211        `orbit: dima marked ${asks.length === 1 ? 'an ask' : `${asks.length} asks`}. answer each in this reply, then call ${ORBIT_TOOL}: resolve the answered ids, or follow one that needs another round.`,
212        ...lines,
213    ].join('\n');
214}
215
216// the first text over the cap, named with its length, so the session can shorten that one
217function overCap(op: string, texts: string[]) {
218    const long = texts.find((x) => [...x].length > ORBIT_TEXT_MAX);
219    return long === undefined
220        ? undefined
221        : {
222              deny: `orbit ${op}: ยซ${[...long].slice(0, 40).join('')}โ€ฆยป is ${[...long].length} chars; keep it โ‰ค${ORBIT_TEXT_MAX}, subject first, detail in hiddenNote`,
223          };
224}
225
226// the tool's ops on orbit; `isTurn` decides whether a plan set now counts from this turn's end or the last one
227export function orbitOp(
228    o: StashOrbit,
229    input: Record<string, unknown>,
230    isTurn: boolean,
231    planMax: number = PLAN_MAX,
232    now = 0,
233): { orbit: StashOrbit; result: string } | { deny: string } {
234    switch (input.op) {
235        case 'add': {
236            const raw = Array.isArray(input.asks) ? input.asks : [];
237            const added: OrbitAsk[] = [];
238            let next = o.next;
239            const born = o.prompts ?? 0;
240            for (const item of raw) {
241                const v = (item ?? {}) as Record<string, unknown>;
242                const text = oneLine(v.text);
243                if (!text) continue;
244                const hiddenNote = oneLine(v.hiddenNote);
245                const link = oneLine(v.link);
246                if (link && !ASK_LINK.test(link))
247                    return {
248                        deny: `orbit add: link ยซ${link.slice(0, 40)}ยป is neither an https url nor a file path (/โ€ฆ or ~/โ€ฆ)`,
249                    };
250                const dies = diesOf(v.dies, born);
251                if (dies === 'bad')
252                    return {
253                        deny: `orbit add: dies ยซ${String(v.dies).slice(0, 20)}ยป is neither "halt" nor a whole number of dima's prompts, 1โ€“${DIES_MAX}`,
254                    };
255                added.push({
256                    ...(dies === undefined ? {} : { dies }),
257                    hiddenNote: hiddenNote || undefined,
258                    id: `o${next++}`,
259                    ...(link ? { link } : {}),
260                    pick: oneLine(v.pick) || 'no pick',
261                    text,
262                });
263            }
264            if (!added.length)
265                return {
266                    deny: 'orbit add: asks needs one { text, pick } or more',
267                };
268            const tooLong = overCap(
269                'add',
270                added.map((a) => a.text),
271            );
272            if (tooLong) return tooLong;
273            return {
274                orbit: { ...o, asks: [...o.asks, ...added], next },
275                result: `added ${added.map((a) => a.id).join(', ')} to dima's orbit; never repeat them in the reply`,
276            };
277        }
278        case 'assume': {
279            const texts = (Array.isArray(input.texts) ? input.texts : [])
280                .map(oneLine)
281                .filter(Boolean);
282            if (!texts.length)
283                return { deny: 'orbit assume: texts needs one or more' };
284            const tooLong = overCap('assume', texts);
285            if (tooLong) return tooLong;
286            const born = isTurn ? o.turns + 1 : o.turns;
287            const kept = o.assumed ?? [];
288            const already = kept.filter((x) => x.at === born).length;
289            if (already + texts.length > ASSUMED_MAX)
290                return {
291                    deny: `orbit assume: at most ${ASSUMED_MAX} a turn, ${already} already; keep the ones that would cost a redo`,
292                };
293            let next = o.next;
294            const added: OrbitAssumption[] = texts.map((text) => ({
295                at: born,
296                id: `a${next++}`,
297                text,
298            }));
299            return {
300                orbit: {
301                    ...o,
302                    assumed: [...kept, ...added].slice(-ASSUMED_MAX),
303                    next,
304                },
305                result: `assumed ${added.map((x) => x.id).join(', ')}; dima sees them under orbit`,
306            };
307        }
308        case 'catch': {
309            const raw = Array.isArray(input.pieces) ? input.pieces : [];
310            const clear = idsOf(input.clear);
311            const was = o.caught ?? [];
312            const unknown = clear.filter((id) => !was.some((x) => x.id === id));
313            if (unknown.length)
314                return {
315                    deny: `orbit catch: no piece ${unknown.join(', ')}; held: ${was.map((x) => x.id).join(', ') || 'none'}`,
316                };
317            let next = o.next;
318            const added: OrbitCatch[] = [];
319            for (const item of raw) {
320                const v = (item ?? {}) as Record<string, unknown>;
321                const text = oneLine(v.text);
322                if (!text) continue;
323                const kind = oneLine(v.kind);
324                if (!(CATCH_KINDS as readonly string[]).includes(kind))
325                    return {
326                        deny: `orbit catch: kind ยซ${kind || 'none'}ยป is not one of ${CATCH_KINDS.join(' ')}; catch.md names them`,
327                    };
328                if ([...text].length > CATCH_TEXT_MAX)
329                    return {
330                        deny: `orbit catch: ยซ${[...text].slice(0, 40).join('')}โ€ฆยป is ${[...text].length} chars; keep it โ‰ค${CATCH_TEXT_MAX}, the why in hiddenNote`,
331                    };
332                const hiddenNote = oneLine(v.hiddenNote);
333                added.push({
334                    at: now,
335                    hiddenNote: hiddenNote || undefined,
336                    id: `c${next++}`,
337                    kind,
338                    text,
339                });
340            }
341            if (!added.length && !clear.length)
342                return {
343                    deny: 'orbit catch: pieces needs one { kind, text, hiddenNote } or more, or clear: [ids]',
344                };
345            // at the cap the oldest ๐Ÿ’ก leaves; with none to drop the add is refused and nothing moves
346            let kept = was.filter((x) => !clear.includes(x.id));
347            const dropped: string[] = [];
348            while (kept.length + added.length > CATCH_HELD_MAX) {
349                const fact = kept.find(
350                    (x) =>
351                        (x.kind ?? CATCH_DROPS) === CATCH_DROPS && !x.isLocked,
352                );
353                if (!fact)
354                    return {
355                        deny: `orbit catch: ${kept.length} held, the cap is ${CATCH_HELD_MAX} and no ${CATCH_DROPS} to drop; clear one first`,
356                    };
357                dropped.push(fact.id);
358                kept = kept.filter((x) => x !== fact);
359            }
360            return {
361                orbit: { ...o, caught: [...kept, ...added], next },
362                result: [
363                    added.length
364                        ? `caught ${added.map((x) => x.id).join(', ')}; dima sees them under ๐Ÿ  catch, never repeat them in the reply`
365                        : '',
366                    clear.length ? `cleared ${clear.join(', ')}` : '',
367                    dropped.length
368                        ? `the cap dropped the oldest ${CATCH_DROPS}: ${dropped.join(', ')}`
369                        : '',
370                ]
371                    .filter(Boolean)
372                    .join('; '),
373            };
374        }
375        case 'resolve': {
376            const ids = idsOf(input.ids);
377            const unknown = ids.filter(
378                (id) => !o.asks.some((a) => a.id === id),
379            );
380            const words =
381                input.words && typeof input.words === 'object'
382                    ? (input.words as Record<string, unknown>)
383                    : {};
384            const asks = o.asks.map((a) => {
385                if (!ids.includes(a.id)) return a;
386                const word = oneLine(words[a.id]);
387                return word
388                    ? { ...a, isResolved: true, word }
389                    : { ...a, isResolved: true };
390            });
391            return {
392                orbit: {
393                    ...o,
394                    // outside a turn the turn end already passed: a worded one lingers to the next, the rest leave
395                    asks: isTurn
396                        ? asks
397                        : asks
398                              .filter((a) => !a.isResolved || a.word)
399                              .map((a) =>
400                                  a.isResolved ? { ...a, isClosed: true } : a,
401                              ),
402                },
403                result: `resolved ${ids.filter((id) => !unknown.includes(id)).join(', ') || 'nothing'}${unknown.length ? `; no ask ${unknown.join(', ')}` : ''}`,
404            };
405        }
406        case 'follow': {
407            const id = typeof input.id === 'string' ? input.id : '';
408            const text = oneLine(input.text);
409            if (!o.asks.some((a) => a.id === id) || !text)
410                return {
411                    deny: `orbit follow: needs a known id and a text, got ยซ${id}ยป`,
412                };
413            const tooLong = overCap('follow', [text]);
414            if (tooLong) return tooLong;
415            return {
416                orbit: {
417                    ...o,
418                    asks: o.asks.map((a) =>
419                        a.id === id
420                            ? {
421                                  ...a,
422                                  isChanged: true,
423                                  isClosed: undefined,
424                                  // a new question is no longer the running turn's: dima's next tick on it must land (o88)
425                                  isLocked: undefined,
426                                  isResolved: false,
427                                  mark: undefined,
428                                  pick: oneLine(input.pick) || a.pick,
429                                  // his steer answered the old question
430                                  steer: undefined,
431                                  text,
432                                  word: undefined,
433                              }
434                            : a,
435                    ),
436                },
437                result: `${id} changed in place`,
438            };
439        }
440        case 'plan': {
441            const lines = (Array.isArray(input.lines) ? input.lines : [])
442                .map(oneLine)
443                .filter(Boolean)
444                .slice(0, planMax);
445            const tooLong = overCap('plan', lines);
446            if (tooLong) return tooLong;
447            return {
448                orbit: {
449                    ...o,
450                    // dima's steer outlives the session's new lines: dropping it cleared the box he was typing in, so the
451                    // field remounted and threw his text away (PK-149)
452                    plan: lines.length
453                        ? {
454                              at: isTurn ? o.turns + 1 : o.turns,
455                              lines,
456                              ...(o.plan?.steer ? { steer: o.plan.steer } : {}),
457                          }
458                        : undefined,
459                },
460                // the board shows the ๐ŸŽ›๏ธ phase lines (7 by default); a shorter plan leaves dima guessing past it (dima's o74)
461                result: lines.length
462                    ? `plan set, ${lines.length} line${lines.length === 1 ? '' : 's'}${lines.length < planMax ? ` โ€” plan has ${lines.length} of ${planMax}, fill to ${planMax}` : ''}`
463                    : 'plan cleared',
464            };
465        }
466        default:
467            return {
468                deny: `orbit: op is add, assume, catch, resolve, follow, plan or glide, got ยซ${String(input.op)}ยป`,
469            };
470    }
471}
472
473// o84: a row moves one place up or down; the list stays the same set
474export function moved<T>(list: readonly T[], i: number, by: -1 | 1): T[] {
475    const j = i + by;
476    if (i < 0 || j < 0 || i >= list.length || j >= list.length)
477        return [...list];
478    const out = [...list];
479    [out[i], out[j]] = [out[j] as T, out[i] as T];
480    return out;
481}
482
483// dima's hand on the phases card โ€” a reorder or a tick, his steer riding with them โ€” that a turn has not taken yet
484export const hasPlanMark = (p: StashPlan | undefined): p is StashPlan =>
485    Boolean(p && (p.isMoved || p.mark));
486
487// what the session reads once dima's phases mark joins a turn
488export function planText(p: StashPlan) {
489    return [
490        `๐ŸŒ” phases: dima ${
491            [
492                p.isMoved ? 'reordered your phases' : '',
493                p.mark ? '๐Ÿ›Ž๏ธ ticked their order' : '',
494            ]
495                .filter(Boolean)
496                .join(' and ') || 'left a steer on your phases'
497        }; take it into account in this reply.`,
498        ...(p.isMoved ? p.lines.map((l, i) => `${i + 1}. ${l}`) : []),
499        ...(p.steer ? [`his steer: ยซ${p.steer.trim()}ยป`] : []),
500    ].join('\n');
501}
502
503// the mark is spent once a turn takes it: the lines stay as dima left them
504export const planTaken = (p: StashPlan): StashPlan => ({
505    at: p.at,
506    lines: p.lines,
507});
508
hooks/parse.ts 271 lines
1// a ยท-joined list in prose, rewritten as bullets the way the output rules want it (reply-check blocks the dot);
2// fences, inline code and the ๐Ÿ“„ stamp line keep theirs
3export function bulletDots(text: string) {
4    let isFence = false;
5    return text
6        .split('\n')
7        .flatMap((line) => {
8            if (/^\s*```/.test(line)) isFence = !isFence;
9            if (isFence || line.includes('๐Ÿ“„')) return [line];
10            // inline code masked at the same length, so split offsets land on the real line
11            const masked = line.replace(/`[^`\n]*`/g, (m) =>
12                '\0'.repeat(m.length),
13            );
14            if (!/\S\sยท\s\S/.test(masked)) return [line];
15            const parts: string[] = [];
16            let from = 0;
17            for (const m of masked.matchAll(/\sยท\s/g)) {
18                parts.push(line.slice(from, m.index));
19                from = (m.index ?? 0) + m[0].length;
20            }
21            parts.push(line.slice(from));
22            const [indent, bullet, head] = (parts[0] ?? '')
23                .match(/^(\s*)(-\s+)?(.*)$/)
24                ?.slice(1) ?? ['', undefined, ''];
25            const pad = bullet ? `${indent}  ` : (indent ?? '');
26            // a label ends at the first item's last colon: `the crew: a ยท b` keeps `the crew:` as its line
27            const colon = (head ?? '').lastIndexOf(': ');
28            const label =
29                colon >= 0 ? (head ?? '').slice(0, colon + 1) : undefined;
30            const items = [
31                colon >= 0 ? (head ?? '').slice(colon + 2) : (head ?? ''),
32                ...parts.slice(1),
33            ];
34            const lines = items.map((i) => `${pad}- ${i.trim()}`);
35            if (label !== undefined)
36                return [`${indent}${bullet ?? ''}${label}`, ...lines];
37            return bullet ? [`${indent}${bullet}`.trimEnd(), ...lines] : lines;
38        })
39        .join('\n');
40}
41
42// each prose line of a reply, fences and the ๐Ÿ“„ stamp left whole, with its inline code masked at the same length so a
43// match's offsets land on the real line
44function proseLines(
45    text: string,
46    fix: (line: string, masked: string) => string,
47) {
48    let isFence = false;
49    return text
50        .split('\n')
51        .map((line) => {
52            if (/^\s*```/.test(line)) isFence = !isFence;
53            if (isFence || line.includes('๐Ÿ“„')) return line;
54            return fix(
55                line,
56                line.replace(/`[^`\n]*`/g, (m) => '\0'.repeat(m.length)),
57            );
58        })
59        .join('\n');
60}
61
62const CIRCLED = 'โ‘ โ‘กโ‘ขโ‘ฃโ‘คโ‘ฅโ‘ฆโ‘งโ‘จโ‘ฉโ‘ชโ‘ซโ‘ฌโ‘ญโ‘ฎโ‘ฏโ‘ฐโ‘ฑโ‘ฒโ‘ณ';
63
64// a run of โ‘ โ‘กโ‘ข in one line becomes one numbered line each (rules/fleet-output-format.md: ยซglyph run-onsยป); a lone
65// circled digit stays, it is no list
66export function numberCircled(text: string) {
67    return proseLines(text, (line, masked) => {
68        const at = [...masked.matchAll(/[โ‘ -โ‘ณ]/gu)];
69        if (at.length < 2) return line;
70        const head = line.slice(0, at[0]?.index).trimEnd();
71        const indent = line.match(/^\s*/)?.[0] ?? '';
72        const items = at.map((m, k) => {
73            const end = at[k + 1]?.index ?? line.length;
74            const n = CIRCLED.indexOf(m[0]) + 1;
75            return `${indent}${n}. ${line.slice((m.index ?? 0) + m[0].length, end).trim()}`;
76        });
77        return [...(head.trim() ? [head] : []), ...items].join('\n');
78    });
79}
80
81// a bare ticket id becomes its one-click link; one already in a link, a url or inline code stays
82export function linkTickets(text: string) {
83    return proseLines(text, (line, masked) => {
84        const hidden = masked
85            .replace(/\[[^\]\n]*\]\([^)\n]*\)/g, (m) => '\0'.repeat(m.length))
86            .replace(/https?:\/\/\S+/g, (m) => '\0'.repeat(m.length));
87        let out = '';
88        let from = 0;
89        for (const m of hidden.matchAll(
90            /(?<![\w/[-])(?:FRM|BYT)-\d+(?![\w-])/g,
91        )) {
92            out += `${line.slice(from, m.index)}[${m[0]}](https://linear.app/x-com/issue/${m[0]})`;
93            from = (m.index ?? 0) + m[0].length;
94        }
95        return out + line.slice(from);
96    });
97}
98
99// a ๐Ÿ”ญ line is ยซ๐Ÿ”ญ waiting on <who>ยป, nothing more: its (aside) is dropped; a link's url keeps its parens
100export function dropWaitAside(text: string) {
101    return proseLines(text, (line, masked) => {
102        if (!/^\s*(?:[-*]\s+)?๐Ÿ”ญ/u.test(masked)) return line;
103        const hidden = masked.replace(/\]\((?:[^()\n]|\([^()\n]*\))*\)/g, (m) =>
104            '\0'.repeat(m.length),
105        );
106        let out = '';
107        let from = 0;
108        for (const m of hidden.matchAll(/\s*\([^()\n]*\)/g)) {
109            out += line.slice(from, m.index);
110            from = (m.index ?? 0) + m[0].length;
111        }
112        return (out + line.slice(from)).trimEnd();
113    });
114}
115
116// a fleet word or member prints bold with its badge glued on (rules/fleet-output-format.md); a bare one in prose is fixed,
117// not policed. fences, quotes, inline code, bold text and links keep theirs; ยซwishยป only as a noun, after a determiner.
118// members are rules/fleet-identity.md's, minus the names that are plain english too (helper, retro, classifier,
119// explore, cc) โ€” those would badge a helper function or the retro file
120const MEMBERS = {
121    cclio: '๐Ÿฆ‰',
122    ccrow: '๐Ÿฆโ€โฌ›',
123    coder: '๐Ÿ”ง',
124    cw: '๐Ÿค',
125    designer: '๐ŸŽจ',
126    dima: '๐Ÿ™‹โ€โ™‚๏ธ',
127    'helper-lite': '๐Ÿชถ',
128    researcher: '๐Ÿ',
129    verifier: '๐Ÿ”Ž',
130} as const;
131const BADGES = {
132    ...MEMBERS,
133    freebie: '๐Ÿ€',
134    siesta: '๐ŸŒค๏ธ',
135    wish: '๐ŸŒ ',
136    wisp: 'โœจ',
137} as const;
138type FleetWord = keyof typeof BADGES;
139const WORD = new RegExp(
140    `(?<![\\w\\-/.])(?:(${Object.values(BADGES).join('|')}) )?(${Object.keys(BADGES).join('|')})(s|es)?(?![\\w\\-/]|[.:]\\w)`,
141    'giu',
142);
143const DETERMINER =
144    /(?:^|\s)(?:a|an|the|his|her|this|that|each|every|one|new|your|my|our|their|dima's)\s+(?:๐ŸŒ  )?$/i;
145
146export function boldFleetWords(text: string) {
147    const hits: Partial<Record<FleetWord, number>> = {};
148    let isFence = false;
149    const lines = text.split('\n').map((line) => {
150        if (/^\s*```/.test(line)) isFence = !isFence;
151        if (isFence || /^\s*>/.test(line)) return line;
152        // masked at the same length, so match offsets land on the real line; a ยซquoteยป stays as typed, and a session
153        // name (`โ˜•๏ธ ๐Ÿ”ง mods coder`) keeps its own role emoji
154        const masked = line.replace(
155            /`[^`\n]*`|\*\*[^*\n]+\*\*|\]\([^)\n]*\)|https?:\/\/\S+|ยซ[^ยป\n]*ยป|(?:โ˜•๏ธ?|๐ŸŽฏ) \S+ [^\n,;)ยป]*/gu,
156            (m) => '\0'.repeat(m.length),
157        );
158        let out = '';
159        let from = 0;
160        for (const m of masked.matchAll(WORD)) {
161            const at = m.index ?? 0;
162            const word = (m[2] ?? '').toLowerCase() as FleetWord;
163            if (word === 'wish' && !DETERMINER.test(masked.slice(0, at)))
164                continue;
165            const badge = BADGES[word];
166            // another word's badge before it is someone else's label: leave both
167            if (m[1] && m[1] !== badge) continue;
168            const shown = m[0].slice(m[1] ? m[1].length + 1 : 0);
169            out += `${line.slice(from, at)}**${badge} ${shown}**`;
170            from = at + m[0].length;
171            hits[word] = (hits[word] ?? 0) + 1;
172        }
173        return out + line.slice(from);
174    });
175    return { hits, text: lines.join('\n') };
176}
177
178// a reply line as a person reads it: links reduced to their labels, no bold or code marks, no list or heading marker
179function plain(line: string) {
180    return line
181        .replace(/\[([^\]]*)\]\([^)]*\)/g, '$1')
182        .replace(/\*\*|`/g, '')
183        .replace(/^\s*(?:[-*]|#+)\s+/, '')
184        .trim();
185}
186
187// What a reply says its session waits on: the ๐Ÿ”ญ lines that end it, joined; a ๐Ÿ”ญ quoted earlier, or in a fence, is not one.
188export function parseWait(reply: string): string | undefined {
189    const waits: string[] = [];
190    for (const line of reply.trimEnd().split('\n').reverse()) {
191        const l = line.trim();
192        if (!l) continue;
193        if (!l.startsWith('๐Ÿ”ญ')) break;
194        waits.unshift(plain(l.slice('๐Ÿ”ญ'.length)));
195    }
196    return waits.length ? waits.join('; ') : undefined;
197}
198
199// with no ๐Ÿ”ญ line, the session's own background work is what it waits on: the first task in three words at most,
200// ยซwaiting on <who>ยป, and +n for the rest (dima's o88: short, nothing more); cclio's standing pr/ci watches
201// (`watch-once.sh`) run all day and are no wait (dima's o52)
202const STANDING_WATCH = /^Arm the one-shot (?:pr|ci) watch/i;
203const isStandingWatch = (t: { description: string; command?: string }) =>
204    t.command?.includes('watch-once.sh') || STANDING_WATCH.test(t.description);
205// every background task the session waits on, by its own name or description: the board's row lists them all (dima's o75)
206export function backgroundWaits(
207    all:
208        | readonly { name?: string; description: string; command?: string }[]
209        | undefined,
210): string[] {
211    return (all ?? [])
212        .filter((t) => !isStandingWatch(t))
213        .map((t) => (t.name ?? t.description).trim());
214}
215
216// a fleet subagent is named by its badge and type, the way replies print a member (rules/fleet-identity.md)
217const AGENT_BADGE: Record<string, string> = {
218    helper: '๐Ÿœ',
219    'helper-lite': '๐Ÿชถ',
220    researcher: '๐Ÿ',
221    retro: '๐Ÿฆก',
222    scout: '๐Ÿฆ…',
223    wishkeeper: '๐Ÿฌ',
224};
225
226export function backgroundWait(
227    all:
228        | readonly {
229              name?: string;
230              description: string;
231              command?: string;
232              agent_type?: string;
233          }[]
234        | undefined,
235): string | undefined {
236    const tasks = all?.filter((t) => !isStandingWatch(t)) ?? [];
237    const first = tasks[0];
238    if (!first) return undefined;
239    const badge = first.agent_type && AGENT_BADGE[first.agent_type];
240    const who = badge
241        ? `${badge} ${first.agent_type}`
242        : (first.name ?? first.description)
243              .trim()
244              .split(/\s+/)
245              .slice(0, 3)
246              .join(' ');
247    const more = tasks.length > 1 ? ` +${tasks.length - 1}` : '';
248    return `waiting on ${who}${more}`;
249}
250
251export const ticketOf = (name: string) => name.match(/\b[A-Z]{2,5}-\d+\b/)?.[0];
252
253// `<mode> <role emoji> <ticket> <role word>: <what>` โ€” ยซโ˜•๏ธ ๐Ÿ”ง FRM-303 code: stash keep-hotยป; a standing member keeps
254// its own name, badge or not โ€” ยซ๐Ÿฆโ€โฌ› ccrowยป, which the registry writes with a space for the joiner
255const FLEET_NAME = /^(โ˜•๏ธ?|๐ŸŽฏ)\s+\S+\s+[A-Z]{2,5}-\d+\s+[\w-]+:\s+\S/u;
256export function isFleetName(name: string) {
257    return (
258        FLEET_NAME.test(name) ||
259        Object.hasOwn(MEMBERS, name.replace(/[^\w\s-]/gu, '').trim())
260    );
261}
262
263// the quiet ledger's count of one member's sends to cclio: `sh -c LEDGER_SENDS <home> <session id> <address regex>`
264// prints the timestamp of each SendMessage call whose `to` names her; a call its result answered `success:false`
265// (unreachable, refused by a plugin, a dead socket) never reached her, so it is left out
266export const LEDGER_SENDS = [
267    't=$(cat "$1"/.claude/projects/*/"$2".jsonl 2>/dev/null)',
268    `bad=$(printf '%s\\n' "$t" | grep -F '\\"success\\":false' | sed -n 's/.*"tool_use_id":"\\([^"]*\\)".*/\\1/p')`,
269    `printf '%s\\n' "$t" | grep -F '"name":"SendMessage"' | grep -E "$3" | { if [ -n "$bad" ]; then grep -v -F "$bad"; else cat; fi; } | sed -n 's/.*"timestamp":"\\([^"]*\\)".*/\\1/p'`,
270].join('\n');
271
hooks/tree.ts 18 lines
1// a Text's string may hold a newline and no other control character, or the engine refuses the whole tree: one control
2// character in one data row blanked every tab of a production mod (claude-code#91870, 10-16); a tab becomes a space
3// biome-ignore lint/suspicious/noControlCharactersInRegex: matching control characters is this regex's job
4const CONTROL = /[\u0000-\u0008\u000B-\u001F\u007F]/g;
5const clean = (s: string) => s.replace(/\t/g, ' ').replace(CONTROL, '');
6
7// every string in a render tree, children and props alike, with its control characters gone
8export function cleanTree<T>(node: T): T {
9    if (typeof node === 'string') return clean(node) as T;
10    if (Array.isArray(node)) return node.map(cleanTree) as T;
11    if (node && typeof node === 'object') {
12        const out: Record<string, unknown> = {};
13        for (const [k, v] of Object.entries(node)) out[k] = cleanTree(v);
14        return out as T;
15    }
16    return node;
17}
18