Krux jako mod Claude Code: polska persona technicznego orka w prompcie systemowym, kotwica głosu w każdej turze, komenda /krux z panelem kuźni i animowany…

Krux jako mod Claude Code: ta sama persona technicznego orka co w pluginie Krux 3.8.0 (ten sam autor; persona przeniesiona stamtąd), ale wpięta od środka. Persona siedzi w prompcie systemowym, kotwica głosu jedzie z każdą turą, a nad promptem kowal wali młotem, póki Claude pracuje.
Tylko Claude Code (CLI i zakładka Code w aplikacji Desktop), od wersji 2.1.287. Codex nie ma modów — tam dalej działa plugin Krux.
| Plugin Krux | Mod Krux | |
|---|---|---|
| Persona | kontekst hooka SessionStart, limit 10 000 znaków | sekcja promptu systemowego, bez tego limitu |
Po /compact | wstrzykiwana od nowa | nie znika, bo prompt systemowy zostaje |
| Kotwica głosu | co turę, pełna | pełna na starcie, co 6 tur i po dryfie (z cytatem i własnymi zdaniami modelu przepisanymi po orkowemu); w pozostałych turach krótka, ~200 znaków |
| Pomiar głosu | tylko benchmark offline | miernik po każdej odpowiedzi: druga osoba, gładka pierwsza osoba, brak bezokolicznika, długie zdania; ostrzeżenia przed ruchem nieodwracalnym i tekstu do wklejenia w cytacie > nie sądzi |
| Życie hordy | model wymyśla sam | fakty z sesji (testy, budowanie, commity, rozbiórka, edycje interfejsu), każdy kumpel z własnym charakterem; turę, kumpla, formę i miejsce wstawki wybiera kod, nie model; przy prośbie o ruch nieodwracalny horda milczy |
| Kompakcja | streszczenie jak leci | neutralne streszczenie z faktami dosłownie, potem pełna kotwica |
| Format odpowiedzi | brak | jedna linia formatu według rodzaju prośby (debug, review, plan, wyjaśnienie, pogawędka), rozpoznanej regexem bez wywołania modelu, z limitem słów; bez rozpoznania sam budżet: do 150 słów; prośba o ruch nieodwracalny (DROP TABLE, force push, git checkout -- ., terraform destroy, kubectl delete, „usuń tabelę”) dostaje linię: skutek i droga odwrotu pełnymi zdaniami |
| Tabliczki | brak | ⚒ Krux nad odpowiedzią, Morra nad promptem; sam rysunek, 0 tokenów |
| Przełączniki | frazy włącz krux itd. | frazy dalej działają, do tego /krux bez tury modelu |
| Interfejs | brak | panel kuźni, kowal nad promptem, słowa spinnera, etykiety w stopce |
Na stałe, z GitHuba:
claude plugin marketplace add karolkiljan/krux-mod
claude plugin install krux-mod@krux-mod-marketplace
Od Claude Code 2.1.292 to samo jedną komendą: claude plugin install krux-mod --marketplace karolkiljan/krux-mod.
Aktualizacja: auto-update dla tego marketplace jest domyślnie wyłączony (włącza się go w /plugin, zakładka Marketplaces), więc nową wersję pobiera:
claude plugin update krux-mod@krux-mod-marketplace
Na jedną sesję, z lokalnego klonu:
git clone https://github.com/karolkiljan/krux-mod.git
claude --plugin-dir ./krux-mod
Zmiany w hooks/ przeładowują się same; po zmianie w agents/, skills/ albo manifeście trzeba wpisać /reload-plugins. Kopia z --plugin-dir po cichu zastępuje zainstalowany mod o tej samej nazwie, choć claude plugin list dalej pokazuje wiersz z marketplace jako włączony; tylko log --debug zapisuje Plugin "krux-mod" from --plugin-dir overrides installed version.
Odinstalowanie:
claude plugin uninstall krux-mod@krux-mod-marketplace
Nie odpalaj moda razem z pluginem Krux — oba wstrzykną personę i kotwicę, więc model dostanie wszystko podwójnie. Mod wykrywa aktywny plugin i ostrzega toastem. Wyłączenie pluginu:
claude plugin disable krux@krux-marketplace
| Komenda | Skutek | |
|---|---|---|
/krux | panel kuźni: tryby pod klawiszami 1–7, horda, palenisko | |
/krux on / /krux off | głos orka / tryb neutralny | |
| `/krux konkret [on\ | off]` | precyzja zakresu: tylko to, o co proszono |
| `/krux flow [on\ | off]` | jeden ruch na raz, zgoda przed każdym |
| `/krux animacje [on\ | off]` | kowal nad promptem |
| `/krux kowal [on\ | off]` | kowal zostaje nad promptem także w spoczynku |
| `/krux sztolnia [on\ | off]` | panel ze stanem roboty obok transkryptu |
| `/krux czat [on\ | off]` | ramki rozmowy i awatary w terminalu |
/krux dziennik | otwarcie karty Dziennik w Sztolni | |
/krux zapisz <tekst> | zapis otwartego wątku w tablicy sesji | |
/krux raport | raport sesji do skopiowania | |
/krux status | stan trybów |
Bez on/off komenda przełącza tryb na przeciwny. /krux działa także w trakcie tury i nie kosztuje wywołania modelu. Stare frazy z pluginu (włącz krux, wyłącz konkret, …) dalej działają, gdy stanowią całą wiadomość. Stan trybów jest trwały i przeżywa restart sesji.
Mapa hordy ładuje się na żądanie: /krux-mod:krux-horda. Kumple to typy subagentów z agents/: krux-mod:niuch, krux-mod:grom, krux-mod:piryt, krux-mod:ochra, krux-mod:mlot, krux-mod:lont. Każdy ma fach, narzędzia, model i format raportu: Niuch, Piryt i Młot nie mają narzędzi edycji, a Bash dostają do odczytu i testów; Lont rusza tylko czyste pliki śledzone przez git. Te granice stoją w prompcie kumpla, a zgody na każde wywołanie daje silnik, jak w głównej pętli (docs/adr/0001-lont-zakaz-w-prompcie.md). Niuch i Młot chodzą na Haiku. Wysłany typem kumpel wbiega na scenę we własnym fartuchu, także gdy opis zadania nie ma jego imienia.
Edit i Write ork kuje stal, przy Grep świeci pochodnią, przy Glob wypatruje z krzaka, przy Read sięga po zwój, przy planie kreśli mapę, przy sieci i zewnętrznych narzędziach MCP wysyła kruka, przy AskUserQuestion drapie się pod znakiem zapytania, przy Agent dmie w róg. Własne narzędzie mcp__krux-mod__watki zachowuje scenę planowania. Przy Bash scena i podpis wynikają z rodzaju komendy, tej samej co w kronice: testy mają próbę stali (także make test, uv run pytest, pnpm vitest), commit i push pieczęć, budowanie piec, rozbiórka dynamit, odczyty i ślady gita pochodnię, instalowanie i pozostałe komendy kilof; odczyt na przedzie łańcucha (ls && ./deploy.sh) nie udaje zaglądania. Strumień odpowiedzi zmienia scenę także pomiędzy narzędziami: myślenie uruchamia dumanie, tekst pisanie, a początek wywołania narzędzia jego scenę; przy Bash scena czeka na komendę, zamiast zgadywać kilof. Narzędzia silnika też mają swoje sceny: lista zadań mapę, wiadomość do agenta kruka, czytanie wyników z tła zwój. Każda scena ma co najmniej 3 różne czynności. Scena pozostaje przez co najmniej 1,5 s; przy zmianie rekwizyt schodzi 2× szybciej, nadal przez odwrócone wejście. Narzędzie zawsze robi Krux; kumpel pojawia się tylko przy prawdziwym subagencie./krux kowal off pozostawia pasek tylko na czas pracy./krux. Większa kuźnia z paleniskiem, w którym płonie ogień, przełączniki trybów i horda.✓ zrobione, ▸ w toku, · czeka), ostatni ukończony przebieg testów z liczbami i nazwami padających, gotowość do commita, otwarte wątki, stan repo i commity, orkowie, którzy jeszcze biegają (zadanie, czas, ostatnie narzędzie), oraz zapełnienie kontekstu, okna limitów i koszt sesji. Diffu i drzewa zmian nie dubluje: te daje /diff Claude Code. Krzyżyk zamyka panel na stałe, wraca przez /krux sztolnia.Bash („Kopać” przy kopaniu, „Węszyć” przy szukaniu).krux, konkret, flow obok trybów Claude Code.Animacja chodzi na zegarze klatek interfejsu (moduł Client), więc nie budzi modelu i nie zjada tokenów. /krux animacje off zdejmuje kowala. Ustawienie prefersReducedMotion: true w Claude Code zatrzymuje orków w miejscu, wyłącza reakcje, rzut zwoju, pot, ocieranie czoła i drzemkę oraz pokazuje od razu pełny dymek. Grafika rysuje się tylko w terminalu; w Desktop, VS Code i na telefonie zostaje sam tekst, a persona i komendy działają wszędzie.
Nowe sceny paska:
| Scena | Kiedy | Czynności |
|---|---|---|
test | testy | kanarek, próba obciążeniowa, fiolki |
seal | commit i push | wosk, prasa, zwój ze sznurem |
build | budowanie | piec, hartowanie, miech |
tear | rozbiórka | dynamit, gruz, mur |
think | strumień myślenia | ważenie rudy, liczenie kamyków, rozważanie mapy |
write | strumień tekstu odpowiedzi | skrobanie run, cięcie zbędnych liter, zwijanie zwoju |
Okna zgody na narzędzia obsługuje silnik Claude Code. Mod nie podłącza tool.check ani nie animuje oczekiwania na zgodę.
Poprawność, bezpieczeństwo i wymagany format wyprzedzają głos. Liczby, wersje, ścieżki, komendy i komunikaty błędów idą dosłownie. Kod, JSON, commit messages i opisy PR pozostają neutralne. Przed ruchem nieodwracalnym Krux przechodzi na pełne zdania: warunek, skutek, droga odwrotu.
Mod to kod uruchamiany z uprawnieniami użytkownika. Ten czyta trzy pliki z voice/, ustawienia (prefersReducedMotion), listę komend, historię sesji ($.session.messages, do odtworzenia kroniki i tablicy po wznowieniu), zużycie kontekstu i limitów ($.session.usage) oraz listę agentów ($.agent.list). Uruchamia do pięciu komend, wszystkich tylko do odczytu: git status (stan repo), git log -n 10 (ostatnie commity), git diff --check i git diff --cached --check (białe znaki w drzewie roboczym i indeksie) oraz git rev-list @{upstream}..HEAD (niewypchnięte commity, gdy repo ma upstream); każda z -c core.fsmonitor=false, więc nie uruchamia komendy zapisanej w .git/config repo. Rejestruje jedno narzędzie dla modelu, mcp__krux-mod__watki: otwarte wątki tablicy, trzymane w stanie sesji. Dostarcza 6 typów subagentów (agents/*.md); uruchamia je model, gdy wyśle kumpla, z narzędziami z ich definicji i zgodami silnika, a ich opisy (razem do 700 znaków) stoją na liście typów narzędzia Agent. Pisze wyłącznie do własnego magazynu $.store (tryby) i stanu sesji. Nie wysyła niczego poza sesję. Koszt kontekstu: opisy skilla krux-horda i 6 typów subagentów to ~563 tokeny w każdej sesji (claude --plugin-dir . plugin details krux-mod, sekcja „Projected token cost”). Ten pomiar nie liczy tekstów moda: persona (voice/persona.md, ok. 8,9 tys. znaków) w prompcie systemowym każdej sesji, kotwica głosu w każdej turze (648 znaków co 6. turę i po dryfie, inaczej 195), a przy trybach konkret i flow po ok. 500 znaków; do tego opis narzędzia watki. Przy 2,5–3 znakach polszczyzny na token persona to szacunkowo 3–3,5 tys. tokenów. Pełna lista tego, co mod czyta i uruchamia: claude plugin validate .; inwentarz komponentów: claude --plugin-dir . plugin details krux-mod.
claude plugin validate .
claude plugin test .
node --test tests/scripts-regression.mjs
tsc -p .
git diff --check
Sprawdzone na Claude Code 2.1.296. API modów jest we wczesnym dostępie i może się zmienić między wersjami.
node scripts/voice-bench.mjs --model claude-opus-5-5 [--scenario cache|smrod] [--mode stream|resume] [--plugin-dir <katalog>]
node scripts/bench-compare.mjs baza=<katalog> wariant=<katalog> [--model <id>] [--scenario cache|smrod] [--turn N]
Jeden przebieg to jedna sesja. Scenariusz cache (domyślny, 12 tur, sam odczyt plików) pochodzi z pluginu Krux 3.8.0: te same prompty, fixture i metryki co scripts/context-smoke.js, więc liczby stają obok serii pluginu. Scenariusz smrod (7 tur) daje modelowi Bash do testów i Edit: model puszcza testy, naprawia robaka i odpowiada na pytanie o wydanie, więc kronika dostaje smród i zielone, a model linię nastroju. --mode stream (domyślnie) prowadzi rozmowę w jednym procesie claude -p --input-format stream-json, tak jak sesja interaktywna, więc mierzy krótką kotwicę i życie hordy. --mode resume odpala osobny proces na turę z --resume i sprawdza, czy mod odtwarza stan z historii. Ustawienia użytkownika, jego pluginy, hooki i MCP są odcięte (--setting-sources local, --strict-mcp-config); mod wchodzi wyłącznie przez --plugin-dir. Raport i surowe odpowiedzi lądują w benchmarks/voice-bench/<czas>/, poza gitem (.gitignore), żeby nie jechały w paczce pluginu; dawne przebiegi leżą na gałęzi bench/voice-bench.
Poza metrykami pluginu raport liczy kotwice z transkryptu: pełne (fullAnchors, w tym driftFixes z poprawką), krótkie (shortAnchors), notki o hordzie i o nastroju (hordeNotes, moodNotes) i łączną długość kontekstu hooka (hookContextChars), a do tego szablony: powtórzone zamknięcia i otwarcia odpowiedzi (repeatedClosings, repeatedOpenings), prośby o zgodę na końcu (consentClosings), powtórzone otwarcia wstawek o hordzie (repeatedHordeOpenings), wstawki w ostatnim akapicie (hordeClosings), kumpla w ostatnim zdaniu tury, w której notka kazała „w środku” (middleClosings; tury notek bench odtwarza z odpowiedzi regułą moda) i słowo „nastrój” powtórzone za linią nastroju (moodWordEcho). bench-compare.mjs liczy metryki od nowa z responses.json każdej serii, więc stare przebiegi liczą się tak samo jak nowe, i podaje różnicę z testem permutacyjnym; --turn N wypisuje odpowiedzi z tury N do czytania oczami. Notatki z wynikami A/B: docs/research/. Wymaga Node ≥ 22.18 (wczytuje hooks/voice.ts bez budowania). Przebieg cache to 12 płatnych tur: około $0,45 na Opusie i $0,014 na Haiku; smrod na Opusie kosztuje około $0,25.
MIT. Projekt nie jest powiązany z produktami innych autorów o nazwie Krux.
hooks/register.ts 1252 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register, RenderElement, RenderInput, SessionUsage } from 'claude-code'
3
4import type { KruxActivity, KruxBoard, KruxEvent, KruxGit, KruxHordeMember, KruxMode, KruxModes, KruxTestRun } from '../types'
5import { CAPTION_COLUMNS, CAPTION_GAP, bandPlan } from './band'
6import type { BandInput } from './band'
7import { EMPTY_CREW, crewAfter } from './crew'
8import type { CrewEvent } from './crew'
9import { gauge, matesNamed } from './gauge'
10import { EMPTY_LORE, lifeNote, moodNote, recordAnswer, recordTool, replay, turnsAfter } from './lore'
11import { CALM, EVENT_HOLD_MS, eventOf, mateIn, mateMoodAfter, mateOfType, moodsAfter, moodsTick } from './mood'
12import { MATES, ROSTER } from './roster'
13import type { BoardCall } from './board'
14import { EMPTY_BOARD, boardAfter, replayBoard, returnNote, usageOf } from './board'
15import { GIT_CHECK, GIT_CHECK_CACHED, GIT_LOG, GIT_STATUS, GIT_UNPUSHED, gitOf } from './git'
16import { EMPTY_THREADS, THREAD_SPEC, replayThreads, saveThread, threadsAfter, threadsReport } from './threads'
17import { dayReport } from './report'
18import { EMPTY_MUSTER, anyRunning, musterDone, musterRows, musterSpawn, musterTool } from './muster'
19import { KRUX_COLOR, ORC_COLOR, shaftDigest, shaftTabs, shaftTree } from './shaft'
20import { TOOL_INDENT, chatTree, isCommandText, toolIndent } from './chat'
21import { MORRA_COLOR } from './avatar'
22import type { AvatarSpeaker } from './avatar'
23import { EMPTY_JOURNAL, journalAfter, journalTree, toolLine } from './journal'
24import { echoLine, echoPrompt } from './echo'
25import { forgeColumns } from './sprites'
26import {
27 DEFAULT_MODES,
28 HELP,
29 MODES,
30 NAMEPLATE,
31 COMPACT_NOTE,
32 anchorFor,
33 applyToggle,
34 asksRelease,
35 changesRepo,
36 describeTool,
37 describeToolAhead,
38 describePhase,
39 formatHint,
40 fromPerson,
41 modelNote,
42 parseCommand,
43 parsePhrase,
44 personaSections,
45 promptKind,
46 riskHint,
47 spinnerWord,
48 statusLine,
49 stripFrontmatter,
50 userLine,
51 workOf,
52} from './voice'
53import type { Texts, Toggle } from './voice'
54
55const PANE = 'krux'
56// Panel ze stanem roboty; w pełnoekranowym terminalu dokuje się obok transkryptu.
57const SHAFT_PANE = 'sztolnia'
58// Komórka przycisku trybu w panelu `/krux`: najdłuższy „6: sztolnia: off” i oddech.
59const MODE_CELL = 18
60const SHAFT_COLUMNS = 56
61// Najwęższy skrót Sztolni w pasie: znak, ułamek planu i kilka liter zadania.
62const DIGEST_COLUMNS = 18
63// Szerzej skrót się nie rozlewa: długa linia ucina się, zamiast ciągnąć oko przez pół ekranu.
64const DIGEST_MAX = 64
65// Tabliczki, kreska bloków, pas i płótno kuźni liczą siatkę znaków terminala:
66// pusty wiersz nad wiadomością, piksele z półbloków. Desktop rysuje je krzywo
67// (tabliczka na tekście, piksele z przerwami), więc stoją tylko w terminalu.
68const GRID_SURFACE = 'terminal'
69
70const modes = atom({ plugin: 'krux-mod', key: 'modes' } as const, DEFAULT_MODES)
71const activity = atom({ plugin: 'krux-mod', key: 'activity' } as const, null)
72const strikes = atom({ plugin: 'krux-mod', key: 'strikes' } as const, 0)
73const sessionStrikes = atom({ plugin: 'krux-mod', key: 'sessionStrikes' } as const, 0)
74const still = atom({ plugin: 'krux-mod', key: 'still' } as const, false)
75const turns = atom({ plugin: 'krux-mod', key: 'turns' } as const, 0)
76const drift = atom({ plugin: 'krux-mod', key: 'drift' } as const, null)
77const lore = atom({ plugin: 'krux-mod', key: 'lore' } as const, EMPTY_LORE)
78// Zdarzenie kroniki, o którego nastroju model już słyszał: linia nastroju raz na zdarzenie.
79const moodSeen = atom({ plugin: 'krux-mod', key: 'moodSeen' } as const, null)
80const replayed = atom({ plugin: 'krux-mod', key: 'replayed' } as const, false)
81const moods = atom({ plugin: 'krux-mod', key: 'mood' } as const, CALM)
82const crew = atom({ plugin: 'krux-mod', key: 'crew' } as const, EMPTY_CREW)
83// Wywołania `Agent` w toku z wątku głównego: Krux czeka na hordę.
84const waiting = atom({ plugin: 'krux-mod', key: 'waiting' } as const, 0)
85const board = atom({ plugin: 'krux-mod', key: 'board' } as const, EMPTY_BOARD)
86const usage = atom({ plugin: 'krux-mod', key: 'usage' } as const, null)
87const muster = atom({ plugin: 'krux-mod', key: 'muster' } as const, EMPTY_MUSTER)
88const musterNow = atom({ plugin: 'krux-mod', key: 'musterNow' } as const, 0)
89const git = atom({ plugin: 'krux-mod', key: 'git' } as const, null)
90const threads = atom({ plugin: 'krux-mod', key: 'threads' } as const, EMPTY_THREADS)
91const autoKonkret = atom({ plugin: 'krux-mod', key: 'autoKonkret' } as const, false)
92const turnAt = atom({ plugin: 'krux-mod', key: 'turnAt' } as const, null)
93const seenAt = atom({ plugin: 'krux-mod', key: 'seenAt' } as const, null)
94const lastPrompt = atom({ plugin: 'krux-mod', key: 'lastPrompt' } as const, null)
95const journal = atom({ plugin: 'krux-mod', key: 'journal' } as const, { entries: [] })
96const shaftTab = atom({ plugin: 'krux-mod', key: 'shaftTab' } as const, 'stan')
97
98// Godzina pierwszego rysunku po id wiadomości, bez niedozwolonego zapisu $.state
99// w ui.render. Nie ma zegara historii: redraw i resize zachowują tę samą godzinę.
100const messageTimes = new Map<string, number>()
101// Id narzędzi z grup w czacie: wcięcie daje grupa, jej wiersze `ToolUse` (także
102// zwinięty wiersz, który silnik rysuje przez `ToolUse`) stoją w niej bez drugiego.
103const groupedTools = new Set<string>()
104// Obie pamięci rosną z sesją; limit z dużym zapasem, żeby redraw dawnej wiadomości
105// nie przesunął godziny ani nie zgubił wcięcia, a długa sesja nie rosła bez końca.
106const MESSAGE_TIMES_LIMIT = 2000
107const GROUPED_TOOLS_LIMIT = 4000
108
109// Najstarsze wpisy wypadają pierwsze (kolejność wstawiania Map i Set).
110function trimOldest(entries: Map<string, unknown> | Set<string>, limit: number): void {
111 for (const key of entries.keys()) {
112 if (entries.size <= limit) return
113 entries.delete(key)
114 }
115}
116let journalWatch: { cancel: () => void } | null = null
117let journalWatchVersion = 0
118let journalWatchRequests = 0
119// Płótno `Client` (`forge.ts`) padło w tej sesji: pas i panel rysują sam tekst.
120// Silnik po `ui.fault` sam rysuje miejsce od nowa; reload modułu próbuje znowu.
121let forgeFault = false
122// Ostatnia widoczność Dziennika z zegara: wiersze narzędzi czytają ją zamiast `$.ui.panes()`.
123let journalVisible = false
124
125// Teksty głosu czyta session.start; reload modułu czyta je od nowa.
126let texts: Texts = { persona: '', konkret: '', flow: '' }
127
128// Notki dla modelu po przełączeniu z panelu: dojadą z następnym promptem.
129const NOTES_LIMIT = 16
130const NOTES_TTL_MS = 5 * 60 * 1000
131let pendingNotes: { text: string; at: number }[] = []
132
133function freshNotes(now: number): typeof pendingNotes {
134 return pendingNotes.filter(note => now - note.at <= NOTES_TTL_MS).slice(-NOTES_LIMIT)
135}
136
137// Jeden zegar apelu naraz; reload modułu zaczyna bez zegara.
138let ticking = false
139
140function savedModes(saved: unknown): KruxModes {
141 const result: KruxModes = { ...DEFAULT_MODES }
142 if (typeof saved !== 'object' || saved === null) return result
143 for (const mode of MODES) {
144 const value = (saved as Record<string, unknown>)[mode]
145 if (typeof value === 'boolean') result[mode] = value
146 }
147 return result
148}
149
150// Stary obiekt zostaje źródłem trybów jeszcze niezapisanych pod osobnym kluczem.
151// Migracja przy zapisie jednego trybu nie nadpisuje zmian z równoległej sesji.
152async function readSavedModes($: EngineInterface): Promise<KruxModes> {
153 const loaded = savedModes(await $.store.get('modes'))
154 const values = await Promise.all(MODES.map(mode => $.store.get(`mode.${mode}`)))
155 MODES.forEach((mode, index) => {
156 if (typeof values[index] === 'boolean') loaded[mode] = values[index] as boolean
157 })
158 return loaded
159}
160
161async function loadModes($: EngineInterface): Promise<void> {
162 const loaded = await readSavedModes($)
163 await update($, modes, () => loaded)
164}
165
166// Zapis trybu i notka dla modelu, jeśli ten tryb ją ma.
167async function setModes($: EngineInterface, toggle: Toggle): Promise<{ next: KruxModes; on: boolean; note: string | null }> {
168 let next = applyToggle(await readSavedModes($), toggle)
169 const on = next[toggle.mode]
170 await $.store.set(`mode.${toggle.mode}`, on)
171 await update($, modes, current => {
172 next = { ...current, [toggle.mode]: on }
173 return next
174 })
175 // Persona wraca po przerwie: pierwsza tura znowu dostaje pełną kotwicę.
176 if (toggle.mode === 'persona' && on) await update($, turns, () => 0)
177 return { next, on, note: modelNote(toggle.mode, on) }
178}
179
180async function readText($: EngineInterface, name: string): Promise<string> {
181 try {
182 return stripFrontmatter(await $.fs.read(`${$.plugin.root}/voice/${name}.md`))
183 } catch {
184 $.ui.log(`brak voice/${name}.md — ten tryb nie trafi do promptu`)
185 return ''
186 }
187}
188
189// Tryby i ruch od nowa: na starcie i po komendach, które zerują `$.state`.
190async function loadSession($: EngineInterface): Promise<void> {
191 messageTimes.clear()
192 groupedTools.clear()
193 journalWatch?.cancel()
194 journalWatch = null
195 journalWatchVersion += 1
196 journalVisible = false
197 knownRunning = null
198 await loadModes($)
199 await loadMotion($)
200}
201
202async function loadMotion($: EngineInterface): Promise<void> {
203 let reduced = false
204 try {
205 const settings = (await $.settings.read()) as Record<string, unknown>
206 reduced = settings.prefersReducedMotion === true
207 } catch {
208 reduced = false
209 }
210 await update($, still, () => reduced)
211}
212
213// Plugin Krux i ten mod naraz to podwójna persona i podwójna kotwica.
214async function warnAboutPlugin($: EngineInterface): Promise<void> {
215 try {
216 const commands = await $.command.list()
217 if (commands.some(command => command.plugin === 'krux' || command.name.startsWith('krux:'))) {
218 $.ui.toast('Plugin krux też aktywny: persona podwójna. Wyłącz go: claude plugin disable krux@krux-marketplace')
219 }
220 } catch {
221 // Brak listy komend to nie powód, by psuć start sesji.
222 }
223}
224
225// Pusty `$.state` przy niepustej historii to wznowiona sesja: licznik tur,
226// kronikę, dryf i tablicę Sztolni odtwarzamy raz, przy pierwszym prompcie po
227// starcie albo notatce czy raporcie. Równoległe wywołania czekają na wynik,
228// żeby zapis notatki nie wyprzedził odtworzenia wątków.
229let restoring: Promise<void> | null = null
230
231function restore($: EngineInterface): Promise<void> {
232 if (restoring === null) restoring = restoreOnce($).finally(() => { restoring = null })
233 return restoring
234}
235
236async function restoreOnce($: EngineInterface): Promise<void> {
237 // Sprawdzenie i zapis w jednym `update`: dwa równoległe prompty nie odtworzą dwa razy.
238 let first = false
239 await update($, replayed, was => {
240 first = !was
241 return true
242 })
243 if (!first) return
244 try {
245 const messages = await $.session.messages()
246 if (messages.length === 0) return
247 await update($, board, () => replayBoard(messages))
248 await update($, threads, () => replayThreads(messages))
249 const found = replay(messages)
250 await update($, turns, () => found.turns)
251 await update($, lore, () => found.lore)
252 const last = found.lore.last
253 if (last !== null) await update($, moods, () => moodsAfter(last, found.lore))
254 await update($, drift, () => found.drift)
255 } catch (error) {
256 $.ui.log(`nie odtworzyć historii: ${String(error)}`, { to: 'debug' })
257 }
258}
259
260// Jedno przejście sceny; bez zapisu, gdy nic się nie zmienia.
261async function crewStep($: EngineInterface, event: CrewEvent): Promise<void> {
262 const now = await $.clock.now()
263 const seen = await read($, crew)
264 if (crewAfter(seen, event, now) === seen) return
265 await update($, crew, current => crewAfter(current, event, now))
266}
267
268// Faza strumienia na scenie: Krux w pasie albo kumpel na płótnie, od chwili, gdy się zaczęła.
269async function noteStep($: EngineInterface, agentId: string | undefined, description: KruxActivity | null): Promise<void> {
270 if (description === null) return
271 const doing = { ...description, startedAt: await $.clock.now() }
272 if (agentId === undefined) await update($, activity, () => doing)
273 else await crewStep($, { kind: 'mate-tool', agentId, doing })
274}
275
276// Agenci, których silnik widzi jako `running`; `null`, gdy listy nie ma.
277// Ostatnia lista biegnących z silnika: póki zegar apelu tyka co sekundę, pas bierze ją
278// zamiast pytać `$.agent.list()` przy każdym rysunku.
279let knownRunning: ReadonlySet<string> | null = null
280
281async function runningIds($: EngineInterface): Promise<ReadonlySet<string> | null> {
282 try {
283 knownRunning = new Set((await $.agent.list()).filter(agent => agent.status === 'running').map(agent => agent.id))
284 } catch {
285 knownRunning = null
286 }
287 return knownRunning
288}
289
290// Agenci w tle kończą się poza turą: na scenie zostaje tylko to, co silnik widzi jako `running`.
291async function liveMembers($: EngineInterface, members: KruxHordeMember[]): Promise<KruxHordeMember[]> {
292 if (members.length === 0) return members
293 const ids = ticking && knownRunning !== null ? knownRunning : await runningIds($)
294 return ids === null ? members : members.filter(member => ids.has(member.agentId))
295}
296
297// Kumpel wznowiony przez `SendMessage` nie odpala `agent.spawn` (mods-reference
298// „Subagents”): pierwsze jego narzędzie po oddaniu zwoju wprowadza go z powrotem na
299// scenę i do apelu, z imieniem i opisem z apelu. Obcy `agentId` nic nie zmienia.
300async function rejoinMate($: EngineInterface, agentId: string): Promise<void> {
301 const run = (await read($, muster)).runs.find(one => one.agentId === agentId)
302 if (run === undefined || run.endedAt === null) return
303 await crewStep($, { kind: 'spawn', member: { agentId, mate: run.mate, scene: 'hammer', target: '' } })
304 const now = await $.clock.now()
305 await update($, muster, current => musterSpawn(current, agentId, run.mate, run.description, now))
306 tickMuster($)
307}
308
309// Własne narzędzie Kruxa: kronika, humor, a po zdarzeniu wtręt na cztery sekundy.
310async function afterOwnTool($: EngineInterface, tool: string, input: Record<string, unknown>, isError: boolean, text: string, failure?: string, result?: unknown): Promise<KruxEvent | null> {
311 let after = EMPTY_LORE
312 let found: KruxEvent | null = null
313 // Kronika liczona w środku `update`: równoległe narzędzia nie gubią sobie zapisów.
314 await update($, lore, before => {
315 after = recordTool(before, tool, input, isError, text, result)
316 found = eventOf(before, after)
317 return after
318 })
319 const event = found as KruxEvent | null
320 if (event === null) {
321 await update($, moods, now => moodsTick(now))
322 } else {
323 await update($, moods, () => moodsAfter(event, after))
324 // Martwy wpis nie dostanie wtrętu: najpierw scena według listy silnika.
325 const ids = await runningIds($)
326 if (ids !== null) await crewStep($, { kind: 'running', ids })
327 }
328 await crewStep($, { kind: 'own-tool', event, lore: after, seed: await read($, sessionStrikes), failure })
329 // Timer startuje po zapisie dymka, więc nigdy nie wyprzedzi jego `until`.
330 if (event !== null) $.clock.after(EVENT_HOLD_MS, () => void crewStep($, { kind: 'expire' }))
331 return event
332}
333
334// Narzędzie kumpla na scenie: wynik jego roboty zmienia jego minę i daje jego wtręt
335// na cztery sekundy. Kronika Kruxa go nie liczy: to nie robota Kruxa.
336async function afterMateTool($: EngineInterface, agentId: string, tool: string, input: Record<string, unknown>, isError: boolean, text: string, failure?: string, result?: unknown): Promise<void> {
337 const single = recordTool(EMPTY_LORE, tool, input, isError, text, result)
338 const event = eventOf(EMPTY_LORE, single)
339 if (event === null) return
340 const member = (await read($, crew)).members.find(one => one.agentId === agentId)
341 if (member === undefined) return
342 const mate = member.mate
343 if (mate !== null) await update($, moods, now => mateMoodAfter(now, mate, event))
344 await crewStep($, { kind: 'mate-event', agentId, event, lore: single, seed: await read($, sessionStrikes), failure })
345 $.clock.after(EVENT_HOLD_MS, () => void crewStep($, { kind: 'expire' }))
346}
347
348// Sztolnia idzie za trybem: otwarty, gdy `sztolnia` on. Bez pytania silnik
349// stawia go od 144 kolumn; poniżej czeka, aż terminal się poszerzy.
350async function syncShaftPane($: EngineInterface, on: boolean): Promise<void> {
351 try {
352 if (on) await $.ui.open({ id: SHAFT_PANE, title: 'Sztolnia', columns: SHAFT_COLUMNS })
353 else await $.ui.close({ id: SHAFT_PANE })
354 } catch (error) {
355 $.ui.log(`sztolnia: ${String(error)}`, { to: 'debug' })
356 }
357}
358
359// Tabliczka raz na turę. Silnik stawia kropkę (`isFirstOfReply`) na każdym
360// bloku po grupie narzędzi, a stanu w trakcie rysowania zapisać nie wolno:
361// `turn.start` zaznacza turę, pierwszy blok z kropką zabiera tabliczkę po
362// `requestId` (przerysowanie go nie gubi). Historia sprzed pierwszej żywej tury
363// po wczytaniu modułu dostaje tabliczkę na każdej kropce, bez zapamiętywania.
364// Żywe bloki zachowują tabliczkę przy przerysowaniu przez ostatnie 32 tury.
365const PLATES_LIMIT = 32
366const plates = { live: false, pending: false, ids: new Set<string>(), echoed: false, echoes: new Map<string, string | null>() }
367
368function claimPlate(id: string): boolean {
369 if (!plates.live) return true
370 if (plates.ids.has(id)) return true
371 if (!plates.pending) return false
372 plates.pending = false
373 plates.ids.add(id)
374 if (plates.ids.size > PLATES_LIMIT) plates.ids.delete(plates.ids.values().next().value!)
375 return true
376}
377
378// Echo prośby: jeden raz na turę, na pierwszym bloku z kropką, gdy praca już
379// jest długa. Decyzja zapada przy pierwszym rysunku bloku i zostaje przy
380// przerysowaniu, więc późniejsze narzędzia nie zmieniają starej odpowiedzi.
381async function echoAt($: EngineInterface, id: string): Promise<string | null> {
382 if (!plates.live) return null
383 if (plates.echoes.has(id)) return plates.echoes.get(id) ?? null
384 const started = await read($, turnAt)
385 const elapsed = started === null ? 0 : (await $.clock.now()) - started
386 const line = plates.echoed ? null : echoLine(await read($, lastPrompt), await read($, strikes), elapsed)
387 if (line !== null) plates.echoed = true
388 plates.echoes.set(id, line)
389 if (plates.echoes.size > PLATES_LIMIT) plates.echoes.delete(plates.echoes.keys().next().value!)
390 return line
391}
392
393// Stan repo po narzędziu, które mogło go zmienić; poza repo albo bez gita `null`.
394// Bez zmiany bez zapisu: zapis przerysowuje Sztolnię i pas.
395let gitRefresh: Promise<void> | null = null
396let gitAgain = false
397
398function refreshGit($: EngineInterface): Promise<void> {
399 if (gitRefresh !== null) {
400 // Narzędzia mogły zmienić repo podczas odczytu: jeden wspólny odczyt po nim.
401 gitAgain = true
402 return gitRefresh
403 }
404 gitRefresh = (async () => {
405 try {
406 do {
407 gitAgain = false
408 let found: KruxGit | null = null
409 // Czekamy na wszystkie także po błędzie, żeby kolejny odczyt nie nakładał się na stary.
410 const [run, log, check, cachedCheck] = await Promise.all([
411 $.process.run(GIT_STATUS, { timeoutMs: 5000 }).catch(() => null),
412 $.process.run(GIT_LOG, { timeoutMs: 5000 }).catch(() => null),
413 $.process.run(GIT_CHECK, { timeoutMs: 5000 }).catch(() => null),
414 $.process.run(GIT_CHECK_CACHED, { timeoutMs: 5000 }).catch(() => null),
415 ])
416 if (run?.exitCode === 0) {
417 const status = gitOf(run.stdout)
418 const local = status.upstream === null ? null : await $.process.run(GIT_UNPUSHED, { timeoutMs: 5000 }).catch(() => null)
419 found = gitOf(run.stdout, log?.exitCode === 0 ? log.stdout : '', local?.exitCode === 0 && !local.isStdoutTruncated ? local.stdout : null)
420 found.whitespace = check?.exitCode === 2 || cachedCheck?.exitCode === 2 ? false
421 : check?.exitCode === 0 && cachedCheck?.exitCode === 0 ? true : null
422 }
423 const previous = await read($, git)
424 if (JSON.stringify(previous) !== JSON.stringify(found)) {
425 await update($, git, () => found)
426 if (previous !== null && found !== null && found.behind > previous.behind) $.ui.toast(`origin ma ${found.behind} nowych commitów — git pull.`)
427 }
428 } while (gitAgain)
429 } finally {
430 // Blokada znika razem z pętlą, zanim następne mikrozadanie poprosi o odczyt.
431 gitRefresh = null
432 }
433 })()
434 return gitRefresh
435}
436
437async function shaftShown($: EngineInterface, on: boolean): Promise<boolean> {
438 if (!on) return false
439 return (await $.ui.panes()).some(pane => pane.id === SHAFT_PANE && pane.isPlaced && pane.isShown)
440}
441
442// Raport zadania powłoki też ma task.id. Dopiero apel lub lista potwierdza agenta;
443// null oznacza potwierdzonego orka bez imienia, undefined — nieznanego nadawcę.
444async function reportMate($: EngineInterface, agentId: string): Promise<AvatarSpeaker | undefined> {
445 const run = (await read($, muster)).runs.find(one => one.agentId === agentId)
446 if (run !== undefined) return run.mate
447 try {
448 const agent = (await $.agent.list()).find(one => one.id === agentId)
449 return agent === undefined ? undefined : mateOfType(agent.type) ?? mateIn(agent.description, '')
450 } catch {
451 return undefined
452 }
453}
454
455type MessageInput = RenderInput<'AssistantMessage' | 'UserMessage', 'terminal'>
456
457// Dziś wiadomości nie mają czasu ani bodyColumns w kontrakcie. Przyjmujemy
458// timestamp/createdAt (ms lub ISO), jeśli host je poda; inaczej czas pierwszego
459// rysunku. Bez pomiaru szerokości zostaje natywna treść, bez zgadywania 80 kolumn.
460// `text` zastępuje rysunek silnika gołym tekstem; bez pomiaru wraca rysunek silnika.
461async function drawChat($: EngineInterface, e: MessageInput, speaker: AvatarSpeaker, native: () => Promise<RenderElement>, text?: string): Promise<RenderElement> {
462 const props = e.props as unknown as Record<string, unknown>
463 const columns = props.bodyColumns ?? props.columns ?? e.viewport?.columns
464 if (typeof columns !== 'number' || !Number.isFinite(columns) || columns <= 0) return native()
465 const content = text ?? await native()
466 const key = `${e.component}:${e.requestId}`
467 let at = messageTimes.get(key)
468 for (const value of [props.timestamp, props.createdAt]) {
469 const time = typeof value === 'number' ? value : typeof value === 'string' ? Date.parse(value) : NaN
470 if (Number.isFinite(time) && Number.isFinite(new Date(time).getTime())) { at = time; break }
471 }
472 if (at === undefined) {
473 const first = await $.clock.now()
474 at = messageTimes.get(key) ?? first
475 }
476 // Dwa równoległe pierwsze rysunki tego id nie zastępują sobie czasu.
477 if (!messageTimes.has(key)) {
478 messageTimes.set(key, at)
479 trimOldest(messageTimes, MESSAGE_TIMES_LIMIT)
480 }
481 const date = new Date(at)
482 const time = [date.getHours(), date.getMinutes()].map(value => String(value).padStart(2, '0')).join(':')
483 return chatTree($.ui.resolve(e), { speaker, time, content })
484}
485
486async function journalShown($: EngineInterface, surface: string): Promise<boolean> {
487 if (surface !== GRID_SURFACE) return false
488 const now = await read($, modes)
489 if (!now.czat || !now.sztolnia || (await read($, shaftTab)) !== 'dziennik') return false
490 // Zegar już patrzy: każdy wiersz narzędzia bierze jego odczyt, zmianę zgłasza `invalidate`.
491 if (journalWatch !== null) {
492 journalWatchRequests += 1
493 return journalVisible
494 }
495 const shown = await shaftShown($, true)
496 watchJournalVisibility($, shown)
497 return shown
498}
499
500// ui.panes jest snapshotem, nie zależnością renderu. Zakładki silnika nie mają
501// zdarzenia zmiany widoczności: jeden zegar sprawdza ją, póki czat ma Dziennik.
502// Nie rysuje co tyk ani nie zapisuje stanu z ui.render; unieważnia tylko zmianę.
503function watchJournalVisibility($: EngineInterface, visible: boolean): void {
504 journalWatchRequests += 1
505 if (journalWatch !== null) return
506 journalVisible = visible
507 const version = ++journalWatchVersion
508 const tick = (delay = 250) => {
509 journalWatch = $.clock.after(delay, async () => {
510 if (version !== journalWatchVersion) return
511 const requested = journalWatchRequests
512 try {
513 const now = await read($, modes)
514 if (version !== journalWatchVersion) return
515 const tab = await read($, shaftTab)
516 if (version !== journalWatchVersion) return
517 if (!now.czat || !now.sztolnia || tab !== 'dziennik') {
518 // Aktywny render mógł wrócić, gdy ten tyk czekał na stary odczyt off.
519 if (requested !== journalWatchRequests) tick()
520 else journalWatch = null
521 return
522 }
523 const shown = await shaftShown($, true)
524 if (version !== journalWatchVersion) return
525 if (shown !== journalVisible) { journalVisible = shown; $.ui.invalidate('ui.render') }
526 tick()
527 } catch (error) {
528 if (version !== journalWatchVersion) return
529 try { $.ui.log(`dziennik: widoczność: ${String(error)}`, { to: 'debug' }) } catch { /* Zegar ma odzyskać odczyt. */ }
530 tick(1000)
531 }
532 })
533 }
534 tick()
535}
536
537// Panel i skrót pasa odświeżają utknięcie przy 15 min, potem na pełnych minutach.
538// Nowy plan unieważnia poprzedni timer; zegar apelu pozostaje wspólną zależnością.
539let boardClock = 0
540
541function tickBoard($: EngineInterface, plan: KruxBoard, now: number): void {
542 const revision = ++boardClock
543 const starts = plan.tasks.flatMap(task => task.status === 'in_progress' && task.startedAt !== undefined ? [task.startedAt] : [])
544 if (starts.length === 0) return
545 const at = Math.min(...starts.map(start => start + Math.max(15, Math.floor((now - start) / 60_000) + 1) * 60_000))
546 $.clock.after(Math.max(1, at - now), async () => {
547 if (revision !== boardClock) return
548 const current = await read($, board)
549 const time = await $.clock.now()
550 if (revision !== boardClock || !current.tasks.some(task => task.status === 'in_progress' && task.startedAt !== undefined)) return
551 await update($, musterNow, () => time)
552 if (revision === boardClock) tickBoard($, current, time)
553 })
554}
555
556// Tablica po narzędziu, liczona w środku `update` (równoległe narzędzia nie gubią
557// zapisów); bez zmiany bez zapisu, bo zapis przerysowuje Sztolnię. `TodoWrite`
558// i przebieg testów dają nowy obiekt także przy tej samej treści.
559async function boardStep($: EngineInterface, tool: string, input: Record<string, unknown>, result: unknown, call: BoardCall): Promise<KruxTestRun | null> {
560 const now = await $.clock.now()
561 const seen = await read($, board)
562 const next = boardAfter(seen, tool, input, result, call, now)
563 if (next === seen || JSON.stringify(next) === JSON.stringify(seen)) return next.test !== seen.test ? next.test : null
564 let run: KruxTestRun | null = null
565 let plan = seen
566 let tasksChanged = false
567 await update($, board, current => {
568 const after = boardAfter(current, tool, input, result, call, now)
569 if (after.test !== current.test) run = after.test
570 tasksChanged = after.tasks !== current.tasks
571 plan = after
572 return after
573 })
574 if (tasksChanged) tickBoard($, plan, now)
575 return run
576}
577
578// Zapełnienie kontekstu, limity i koszt dla Sztolni; bez odczytu zostaje stary.
579let usageVersion = 0
580
581// Odczyt na starcie; potem liczby pcha silnik w `session.measure` (po każdej turze
582// i przy ruchu limitu o pełny punkt), więc mod nie pyta po każdym narzędziu.
583async function refreshUsage($: EngineInterface): Promise<void> {
584 const version = ++usageVersion
585 try {
586 await applyUsage($, await $.session.usage(), version)
587 } catch {
588 // Brak odczytu to nie powód, by psuć narzędzie czy turę.
589 }
590}
591
592async function applyUsage($: EngineInterface, raw: Pick<SessionUsage, 'context' | 'rateLimits' | 'cost'>, version = ++usageVersion): Promise<void> {
593 const now = usageOf(raw)
594 if (version !== usageVersion) return
595 // Bez zmiany bez zapisu: zapis przerysowuje Sztolnię.
596 // Starszy odczyt nie cofa resetu, także gdy czekał na zapis stanu.
597 await update($, usage, current => version !== usageVersion || JSON.stringify(current) === JSON.stringify(now) ? current : now)
598 if (version !== usageVersion) return
599 const automatic = now.limits.some(limit => limit.percentUsed >= 80)
600 // Toast należy do żądania, które było najnowsze w chwili zapisu flagi: nowsze
601 // żądanie widzi już zmienioną flagę, więc samo by go nie pokazało.
602 let changed = false
603 await update($, autoKonkret, current => {
604 if (version !== usageVersion) return current
605 changed = current !== automatic
606 return automatic
607 })
608 if (changed) $.ui.toast(automatic ? 'Limit planu 80%: konkret włączony do resetu.' : 'Konkret automatyczny wyłączony: limity planu poniżej 80%.')
609}
610
611// Zegar apelu: co sekundę zapis `musterNow`, który przerysowuje Sztolnię i skrót pasa,
612// póki jakiś ork z apelu biega według zdarzeń i według listy silnika.
613function tickMuster($: EngineInterface): void {
614 if (ticking) return
615 ticking = true
616 $.clock.after(1000, async () => {
617 ticking = false
618 const ids = await runningIds($)
619 const runs = (await read($, muster)).runs
620 const now = await $.clock.now()
621 // Ostatni zapis też przerysowuje: ork zabity bez `turn.complete` traci `●` i schodzi ze sceny.
622 await update($, musterNow, () => now)
623 // Brak listy kończy tykanie; panel ma wtedy ograniczoną czasem heurystykę.
624 if (ids === null) return
625 if (anyRunning({ runs: runs.filter(run => ids.has(run.agentId)) })) {
626 tickMuster($)
627 return
628 }
629 await crewStep($, { kind: 'running', ids })
630 })
631}
632
633
634export const register: Register = on => {
635 on('session.start', async ($, e, next) => {
636 usageVersion += 1
637 await loadSession($)
638 texts = {
639 persona: await readText($, 'persona'),
640 konkret: await readText($, 'konkret'),
641 flow: await readText($, 'flow'),
642 }
643 await warnAboutPlugin($)
644 if ((await read($, modes)).sztolnia) await syncShaftPane($, true)
645 // Reload modułu kasuje zegar apelu; orkowie z `$.state` biegną dalej.
646 if (anyRunning(await read($, muster))) tickMuster($)
647 tickBoard($, await read($, board), await $.clock.now())
648 try {
649 await $.tool.register(THREAD_SPEC)
650 } catch (error) {
651 $.ui.log(`nie zarejestrować narzędzia wątków: ${String(error)}`)
652 }
653 try {
654 await $.command.register({
655 name: 'krux',
656 description: 'Kuźnia Kruxa: persona, konkret, flow, animacje, kowal, czat, dziennik, horda',
657 argumentHint: '[on|off|konkret|flow|animacje|kowal|sztolnia|czat|dziennik|zapisz <tekst>|raport|status]',
658 immediate: true,
659 })
660 } catch (error) {
661 $.ui.log(`nie zarejestrować /krux: ${String(error)}`)
662 }
663 // Silnik czeka na ten hook przed pierwszym promptem: zużycie i git (do 5 komend po 5 s)
664 // czyta zegar, nie start sesji.
665 $.clock.after(0, async () => {
666 await refreshUsage($)
667 await refreshGit($)
668 })
669 return next(e)
670 })
671
672 // /clear, /resume i /branch zerują $.state, a session.start już nie wraca.
673 on('classic.SessionStart', { source: ['clear', 'resume', 'fork'] }, async ($, e, next) => {
674 usageVersion += 1
675 await loadSession($)
676 await update($, journal, () => EMPTY_JOURNAL)
677 await update($, shaftTab, () => 'stan')
678 await refreshGit($)
679 return next(e)
680 })
681
682 on('prompt.compose', async ($, e, next) => {
683 const composed = await next(e)
684 const now = await read($, modes)
685 const sections = personaSections({ ...now, konkret: now.konkret || await read($, autoKonkret) }, texts)
686 if (sections.length === 0) return composed
687 return { sections: [...composed.sections, ...sections] }
688 })
689
690 on('prompt.submit', async ($, e, next) => {
691 const now = await $.clock.now()
692 const extra = freshNotes(now).map(note => note.text)
693 pendingNotes = []
694 await restore($)
695 // Echo dotyczy tylko tury z prośbą Morry; raport kumpla czy harmonogram go nie dostają.
696 await update($, lastPrompt, () => fromPerson(e.origin) ? echoPrompt(e.text) : null)
697 if (fromPerson(e.origin)) {
698 let returned = false
699 await update($, seenAt, previous => { returned = previous !== null && now - previous >= 1_800_000; return now })
700 if (returned) {
701 const note = returnNote(await read($, board), await read($, threads), await read($, git))
702 if (note) $.ui.toast(note)
703 }
704 }
705 const phrase = fromPerson(e.origin) ? parsePhrase(e.text) : null
706 if (phrase) {
707 const { note } = await setModes($, phrase)
708 if (note) extra.push(note)
709 } else if ((await read($, modes)).persona) {
710 const turn = await read($, turns)
711 extra.push(anchorFor(turn, await read($, drift)))
712 // Raport subagenta czy wiadomość innej sesji to nie prośba Morry: głos tak, format i horda nie.
713 if (fromPerson(e.origin)) {
714 // Prośba o ruch nieodwracalny: zamiast wstawki o hordzie linia o ostrzeżeniu, na końcu.
715 const risk = riskHint(e.text)
716 const chronicle = await read($, lore)
717 const life = risk === null ? lifeNote(chronicle, turn) : null
718 if (life) extra.push(life)
719 // Nastrój z ostatniego zdarzenia, raz na zdarzenie. Decyzja o wydaniu, plan i ruch
720 // nieodwracalny idą samymi faktami: tam nastrój przechylał wybór, więc przepada.
721 const mood = moodNote(chronicle)
722 if (mood) {
723 let fresh = false
724 await update($, moodSeen, seen => { fresh = seen !== mood.key; return mood.key })
725 if (fresh && risk === null && promptKind(e.text) !== 'plan' && !asksRelease(e.text)) extra.push(mood.text)
726 }
727 const hint = formatHint(e.text)
728 if (hint) extra.push(hint)
729 if (risk) extra.push(risk)
730 }
731 }
732 await update($, turns, count => turnsAfter(count, e.text))
733 if (extra.length === 0) return next(e)
734 return next({ ...e, context: [...(e.context ?? []), ...extra] })
735 })
736
737 // Płótno padło (moduł, rysunek albo kod po rysunku): od teraz sam tekst. Silnik
738 // po tym hooku rysuje miejsce od nowa, więc render zostawia `Client` poza drzewem.
739 on('ui.fault', ($, e, next) => {
740 forgeFault = true
741 $.ui.log(`płótno ${e.module} (${e.phase}): ${e.reason}`, { to: 'debug' })
742 return next(e)
743 })
744
745 // Silnik pcha liczby zużycia po każdej turze i przy ruchu limitu: Sztolnia i auto konkret.
746 on('session.measure', async ($, e, next) => {
747 await applyUsage($, e)
748 return next(e)
749 })
750
751 // Kompakcja: streszczenie bez klimatu, a następna tura dostaje pełną kotwicę,
752 // bo po streszczeniu w historii nie ma już przykładów głosu.
753 on('session.compact', async ($, e, next) => {
754 if (e.agentId !== undefined || !(await read($, modes)).persona) return next(e)
755 const instructions = [e.instructions, COMPACT_NOTE].filter(Boolean).join('\n\n')
756 const result = await next({ ...e, instructions })
757 if (result.messages !== undefined && e.trigger !== 'precompute') await update($, turns, () => 0)
758 return result
759 })
760
761 on('command.run', { command: 'krux' }, async ($, e) => {
762 const command = parseCommand(e.args)
763 if (command.kind === 'status') return { text: statusLine(await read($, modes), await read($, autoKonkret)) }
764 if (command.kind === 'help') return { text: `Krux nie znać „${command.unknown}”.\n${HELP}` }
765 if (command.kind === 'save') {
766 await restore($)
767 let id: number | null = null
768 await update($, threads, current => {
769 const next = saveThread(current, command.text)
770 if (next.next > current.next) id = current.next
771 return next
772 })
773 $.ui.toast(id === null ? 'Notatka już w otwartych wątkach.' : `Wątek #${id} zapisany.`)
774 return {}
775 }
776 if (command.kind === 'report') {
777 await restore($)
778 return { text: dayReport(await read($, git), await read($, board), await read($, threads), await read($, lore)) }
779 }
780 if (command.kind === 'journal') {
781 await update($, shaftTab, () => 'dziennik')
782 const opened = (await $.ui.panes()).some(pane => pane.id === SHAFT_PANE)
783 if (!(await read($, modes)).sztolnia) await setModes($, { mode: 'sztolnia', on: true })
784 // Ponowne open pokazuje także panel czekający na szerokość albo ukrytą kartę.
785 if (!opened || !await shaftShown($, true)) await syncShaftPane($, true)
786 return {}
787 }
788 if (command.kind === 'toggle') {
789 const { next: now, on: isOn, note } = await setModes($, command.toggle)
790 if (command.toggle.mode === 'sztolnia') await syncShaftPane($, isOn)
791 const text = `${userLine(command.toggle.mode, isOn)}\n${statusLine(now, await read($, autoKonkret))}`
792 return note ? { text, context: [note] } : { text }
793 }
794 const opened = await $.ui.open({ id: PANE, title: 'Kuźnia Kruxa', focus: true, closeOnEscape: true })
795 if (opened.isPlaced) return {}
796 return { text: `${statusLine(await read($, modes), await read($, autoKonkret))}\n${HELP}` }
797 })
798
799 // Subagent z głównej pętli wbiega na scenę; kumpla bierze z typu, potem z opisu zadania.
800 on('agent.spawn', async ($, e, next) => {
801 const result = await next(e)
802 if (e.parentAgentId !== undefined || result.agentId === undefined) return result
803 const mate = mateOfType(e.subagentType) ?? mateIn(e.description, e.prompt)
804 await crewStep($, { kind: 'spawn', member: { agentId: result.agentId, mate, scene: 'hammer', target: '' } })
805 const agentId = result.agentId
806 const now = await $.clock.now()
807 await update($, muster, current => musterSpawn(current, agentId, mate, e.description, now))
808 tickMuster($)
809 return result
810 })
811
812 on('turn.start', async ($, e, next) => {
813 if ('agentId' in e && e.agentId !== undefined) return next(e)
814 const now = await $.clock.now()
815 await update($, turnAt, () => now)
816 plates.live = true
817 plates.pending = true
818 plates.echoed = false
819 await update($, strikes, () => 0)
820 await update($, activity, () => null)
821 await update($, waiting, () => 0)
822 return next(e)
823 })
824
825 // Obserwacja strumienia nie zmienia ani kawałków, ani wyniku modelu. Jej błąd
826 // gubi tylko scenę: strumień silnika zamyka wyłącznie przerwanie konsumenta.
827 // Dziś nic jej nie wywraca (silnik sprawdza kawałki między hakami i odpowiedzi
828 // `$`), więc `try` to bezpiecznik na przyszły robak w czystym kodzie sceny.
829 on('turn.step', async function* ($, e, next) {
830 let last = ''
831 const stream = next(e)
832 let done = false
833 try {
834 for (;;) {
835 const item = await stream.next()
836 if (item.done) {
837 done = true
838 return item.value
839 }
840 const chunk = item.value
841 const phase = chunk.kind === 'thinking' ? 'think' : chunk.kind === 'text' ? 'write' : null
842 const kind = phase ?? (chunk.kind === 'tool' ? `tool:${chunk.name}` : '')
843 if (kind && kind !== last) {
844 last = kind
845 const description = phase !== null ? describePhase(phase, e.index) : chunk.kind === 'tool' ? describeToolAhead(chunk.name, e.index) : null
846 try {
847 await noteStep($, e.agentId, description)
848 } catch (error) {
849 $.ui.log(`scena strumienia: ${String(error)}`, { to: 'debug' })
850 }
851 }
852 yield chunk
853 }
854 } finally {
855 // Przerwanie konsumenta zamyka także strumień silnika.
856 if (!done) await stream.return(undefined as never)
857 }
858 })
859
860 on('tool.call', async ($, e, next) => {
861 const tool = String(e.tool)
862 const input = e as unknown as Record<string, unknown>
863 const startedAt = await $.clock.now()
864 if (e.agentId === undefined) {
865 const seed = await read($, sessionStrikes)
866 await update($, activity, () => ({ ...describeTool(tool, input, seed), startedAt }))
867 await update($, strikes, count => count + 1)
868 await update($, sessionStrikes, count => count + 1)
869 } else {
870 await rejoinMate($, e.agentId)
871 await crewStep($, { kind: 'mate-tool', agentId: e.agentId, doing: { ...describeTool(tool, input, 0), startedAt } })
872 }
873 const awaits = e.agentId === undefined && workOf(tool, input) === 'agent'
874 if (awaits) await update($, waiting, count => count + 1)
875 let result: Awaited<ReturnType<typeof next>>
876 try {
877 result = await next(e)
878 } finally {
879 if (awaits) await update($, waiting, count => Math.max(0, count - 1))
880 }
881 if (result.deny === undefined) {
882 const isError = result.isError === true
883 const text = typeof result.text === 'string' ? result.text : ''
884 const who = e.agentId === undefined ? 'Krux' : (await read($, muster)).runs.find(one => one.agentId === e.agentId)?.mate ?? 'ork'
885 const at = await $.clock.now()
886 await update($, journal, current => journalAfter(current, { tool, input, result: result.result, text: result.text, isError, tool_use_id: e.tool_use_id, agentId: e.agentId, who, at }))
887 if (e.agentId === undefined) {
888 const run = await boardStep($, tool, input, result.result, { text, isError, who: 'Krux' })
889 await afterOwnTool($, tool, input, isError, text, run?.failures[0], result.result)
890 } else {
891 const agentId = e.agentId
892 // Z pętli kumpla testy i edycje: jego lista zadań to nie plan Kruxa. Imię z apelu,
893 // bo ze sceny kumpel schodzi, gdy pas się zwęża.
894 let run: KruxTestRun | null = null
895 const work = workOf(tool, input)
896 if (work === 'test' || work === 'edit') {
897 const mate = (await read($, muster)).runs.find(one => one.agentId === agentId)?.mate
898 run = await boardStep($, tool, input, result.result, { text, isError, who: mate ?? 'ork' })
899 }
900 await update($, muster, current => musterTool(current, agentId, tool, input))
901 await afterMateTool($, agentId, tool, input, isError, text, run?.failures[0], result.result)
902 }
903 if (changesRepo(tool, input)) await refreshGit($)
904 }
905 return result
906 })
907
908 // Narzędzie wątków: model otwiera i zamyka wątki Sztolni, w odpowiedzi widzi otwarte z id.
909 // Literał, nie stała: `claude plugin validate` czyta matcher ze źródła (test pilnuje zgodności z THREAD_TOOL_NAME).
910 on('tool.call', { tool: 'mcp__krux-mod__watki' }, async ($, e) => {
911 let now = EMPTY_THREADS
912 await update($, threads, current => (now = threadsAfter(current, e as unknown as Record<string, unknown>)))
913 // Wynik narzędzia moda to tekst: rekord obiektem silnik odrzuca.
914 const report = threadsReport(now)
915 return { result: report, text: report }
916 })
917
918 // Po turze miernik ocenia głos, a kronika notuje, kto z hordy się odezwał.
919 on('turn.complete', async ($, e, next) => {
920 if (e.agentId !== undefined) {
921 await crewStep($, { kind: 'mate-done', agentId: e.agentId })
922 $.clock.after(EVENT_HOLD_MS, () => void crewStep($, { kind: 'expire' }))
923 const agentId = e.agentId
924 const now = await $.clock.now()
925 await update($, muster, current => musterDone(current, agentId, now))
926 return next(e)
927 }
928 // Czas tury daje silnik (`durationMs`, zegar ścienny); `turnAt` służy już tylko echu prośby.
929 await update($, turnAt, () => null)
930 if (e.durationMs >= 300_000) $.ui.toast(`Krux skończyć po ${Math.floor(e.durationMs / 60_000)} min.`)
931 await update($, activity, () => null)
932 await refreshGit($)
933 if (e.reason === 'answer' && (await read($, modes)).persona) {
934 // Poprawka jedzie raz: krótka odpowiedź nie świadczy o dryfie, więc stary werdykt gaśnie.
935 const verdict = gauge(e.answer)
936 await update($, drift, () => verdict)
937 await update($, lore, now => recordAnswer(now, matesNamed(e.answer)))
938 }
939 return next(e)
940 })
941
942 // Słowo spinnera po orkowemu; to samo słowo przez całą turę.
943 on('ui.render', { component: 'Spinner' }, async ($, e, next) => {
944 if (!(await read($, modes)).persona || e.props.message !== null) return next(e)
945 const scene = (await read($, activity))?.scene
946 return next({ ...e, props: { ...e.props, word: spinnerWord(e.props.mode, e.props.word, scene) } })
947 })
948
949 // Etykiety trybów w stopce, obok tych, które rysuje Claude Code.
950 on('ui.render', { component: 'SessionMode' }, async ($, e, next) => {
951 const now = await read($, modes)
952 const automatic = await read($, autoKonkret)
953 const labels = (['persona', 'konkret', 'flow', 'czat'] as const)
954 .filter(mode => now[mode] || (mode === 'konkret' && automatic))
955 .map(mode => (mode === 'persona' ? 'krux' : mode === 'konkret' && !now.konkret ? 'konkret (auto)' : mode))
956 if (labels.length === 0) return next(e)
957 return next({ ...e, props: { ...e.props, modes: [...e.props.modes, ...labels] } })
958 })
959
960 // Tabliczki w transkrypcie: kto mówi. Sam rysunek, model ich nie czyta.
961 // Silnik stawia pusty wiersz nad wiadomością; tabliczka leży na nim
962 // (`absolute`), więc nie dokłada własnego wiersza ani przerwy pod sobą.
963 // Każdy blok odpowiedzi stoi przy kresce w kolorze Kruxa (`quote`: krawędź
964 // z lewej), więc długa rozmowa dzieli się na bloki; pierwszy dostaje tabliczkę.
965 on('ui.render', { component: 'AssistantMessage' }, async ($, e, next) => {
966 if (e.surface !== GRID_SURFACE) return next(e)
967 const now = await read($, modes)
968 if (now.czat) return drawChat($, e, 'Krux', () => next(e))
969 if (!now.persona) return next(e)
970 const theirs = await next(e)
971 const { Box, Text } = $.ui.resolve(e)
972 const block = Box({ borderStyle: 'quote', borderColor: KRUX_COLOR, marginBottom: -1, children: [Box({ marginTop: -1, children: [theirs] })] })
973 if (!e.props.isFirstOfReply) return block
974 // Tabliczka raz na turę; echo prośby otwiera ją ponownie na bloku po długiej robocie.
975 const claimed = claimPlate(e.requestId)
976 const echo = await echoAt($, e.requestId)
977 if (!claimed && echo === null) return block
978 const plate = Box({
979 key: 'nameplate',
980 position: 'absolute',
981 top: 0,
982 left: 0,
983 right: 0,
984 flexDirection: 'row',
985 children: [
986 Text({ bold: true, color: KRUX_COLOR, children: [NAMEPLATE.krux] }),
987 ...(echo === null ? [] : [Box({ flexShrink: 1, minWidth: 0, children: [Text({ dimColor: true, wrap: 'truncate-end', children: [` · do prośby: „${echo}”`] })] })]),
988 ],
989 })
990 return Box({ flexDirection: 'column', children: [block, plate] })
991 })
992
993 on('ui.render', { component: 'UserMessage' }, async ($, e, next) => {
994 if (e.surface !== GRID_SURFACE) return next(e)
995 const now = await read($, modes)
996 if (now.czat) {
997 // task.id łączy raport po tożsamości, from.name samo nie dowodzi subagenta.
998 const id = e.props.task?.id
999 if (id !== undefined) {
1000 const mate = await reportMate($, id)
1001 if (mate !== undefined) return drawChat($, e, mate, () => next(e))
1002 }
1003 // Prośba Morry bez tła wiersza silnika; komendy zostają podświetlone.
1004 if (fromPerson(e.props.origin)) return drawChat($, e, 'Morra', () => next(e), isCommandText(e.props.text) ? undefined : e.props.text)
1005 return next(e)
1006 }
1007 if (!fromPerson(e.props.origin) || !now.persona) return next(e)
1008 const theirs = await next(e)
1009 const { Box, Text } = $.ui.resolve(e)
1010 const plate = Box({ key: 'nameplate', position: 'absolute', top: 0, left: 0, children: [Text({ bold: true, color: MORRA_COLOR, children: [NAMEPLATE.morra] })] })
1011 return Box({ flexDirection: 'column', children: [theirs, plate] })
1012 })
1013
1014 // Złączenie po tool_use_id, nigdy po nazwie narzędzia ani requestId grupy.
1015 // Bez wpisu (np. narzędzie w toku albo stara historia) pełny wiersz silnika.
1016 // W czacie wiersze narzędzi stoją pod treścią dymków, nie pod awatarami.
1017 on('ui.render', { component: ['ToolUse', 'ToolResult', 'ToolGroup'] }, async ($, e, next) => {
1018 if (e.surface !== GRID_SURFACE || !(await read($, modes)).czat) return next(e)
1019 const table = $.ui.resolve(e)
1020 if (e.component === 'ToolGroup') {
1021 // Id zapisane przed `next`: wiersze grupy rysują się w jego trakcie.
1022 // Wiersz narysowany samodzielnie, zanim dołączył do grupy, rysuje się
1023 // od nowa (`invalidate`), żeby nie dostał wcięcia drugi raz.
1024 let joined = false
1025 for (const call of e.props.calls) {
1026 if (call.tool_use_id === undefined || groupedTools.has(call.tool_use_id)) continue
1027 groupedTools.add(call.tool_use_id)
1028 joined = true
1029 }
1030 trimOldest(groupedTools, GROUPED_TOOLS_LIMIT)
1031 const content = await next(e)
1032 if (joined) $.ui.invalidate('ui.render')
1033 return toolIndent(table, content)
1034 }
1035 if (groupedTools.has(e.props.tool_use_id)) return next(e)
1036 return toolIndent(table, await next(e))
1037 })
1038
1039 on('ui.render', { component: ['ToolUse', 'ToolResult', 'ToolGroup'] }, async ($, e, next) => {
1040 if (!await journalShown($, e.surface)) return next(e)
1041 const entries = (await read($, journal)).entries
1042 const calls = e.component === 'ToolGroup' ? e.props.calls : [e.props]
1043 const matched = calls.map(call => call.tool_use_id === undefined ? undefined : entries.findLast(entry => entry.id === call.tool_use_id))
1044 // Grupa jest całością: brak choć jednego id nie może zgubić jego wyniku.
1045 if (matched.length === 0 || matched.some(entry => entry === undefined)) return next(e)
1046 const columns = e.viewport?.columns
1047 if (columns === undefined || !Number.isFinite(columns) || columns <= 0) return next(e)
1048 const table = $.ui.resolve(e)
1049 // Wiersz narzędzia już niesie linię dziennika; osobny wynik dałby ją drugi raz.
1050 if (e.component === 'ToolResult') return table.Box({ key: 'journal-result', height: 0 })
1051 return toolLine(table, matched as NonNullable<typeof matched[number]>[], columns - TOOL_INDENT)
1052 })
1053
1054 // Pas nad promptem: podpis z lewej, za nim Krux i wysłani kumple, dymek nad
1055 // tym, kto ostatnio coś zrobił. Plan liczy `band.ts`; tu tylko stan i elementy.
1056 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
1057 if (e.props.hasSurvey || e.surface !== GRID_SURFACE) return next(e)
1058 const now = await read($, modes)
1059 if (!now.persona || !now.animacje) return next(e)
1060 const working = e.props.isWorking
1061 if (!working && !now.kowal) return next(e)
1062 const table = $.ui.resolve(e)
1063 const scene = await read($, crew)
1064 const members = await liveMembers($, scene.members)
1065 const input: BandInput = {
1066 working,
1067 activity: working ? await read($, activity) : null,
1068 strikes: await read($, strikes),
1069 total: await read($, sessionStrikes),
1070 moods: await read($, moods),
1071 members,
1072 held: scene.bubble,
1073 cues: scene.cues ?? [],
1074 waiting: (await read($, waiting)) > 0,
1075 still: await read($, still),
1076 now: await $.clock.now(),
1077 columns: e.props.bodyColumns,
1078 rows: e.props.maxRows,
1079 hasClient: 'Client' in table && !forgeFault,
1080 }
1081 // Skrót Sztolni za płótnem, gdy jej panelu nie widać: zamknięty, czeka na
1082 // szerszy terminal (bez pytania silnik stawia go od 144 kolumn) albo stoi
1083 // za inną kartą. Zabiera pusty slot kumpla, ale nie spycha kumpla ze sceny
1084 // i nie zmienia wysokości pasa.
1085 const digestShown = !(await shaftShown($, now.sztolnia))
1086 if (digestShown) await read($, musterNow)
1087 const digestExtra = digestShown ? { git: await read($, git), threads: await read($, threads), now: input.now } : null
1088 const lines = digestExtra === null ? [] : shaftDigest(await read($, board), await read($, usage), digestExtra)
1089 let plan = bandPlan(input)
1090 if (lines.length > 0 && plan.stage !== null) {
1091 const narrow = bandPlan({ ...input, columns: input.columns - DIGEST_COLUMNS - CAPTION_GAP })
1092 if (narrow.stage !== null && narrow.stage.height === plan.stage.height && narrow.stage.props.slots > members.length) plan = narrow
1093 }
1094 const theirs = await next(e)
1095 const { Box, Text } = table
1096 // Kreska nad pasem oddziela go od odpowiedzi i zabiera jeden wiersz.
1097 const rule = plan.rule ? [Text({ dimColor: true, wrap: 'truncate-end', children: ['─'.repeat(Math.max(1, e.props.bodyColumns))] })] : []
1098 if (plan.stage === null || !('Client' in table) || forgeFault) {
1099 const caption = [[plan.verb, plan.target].filter(Boolean).join(' '), plan.tally].filter(Boolean).join(' · ')
1100 const line = Text({ dimColor: true, wrap: 'truncate-end', children: [`⚒ ${caption}`] })
1101 return Box({ flexDirection: 'column', children: [...rule, line, theirs] })
1102 }
1103 const caption = Box({
1104 flexDirection: 'column',
1105 width: CAPTION_COLUMNS,
1106 children: [
1107 Text({ bold: true, color: KRUX_COLOR, wrap: 'truncate-end', children: [plan.verb] }),
1108 ...(plan.target ? [Text({ dimColor: true, wrap: 'truncate-middle', children: [plan.target] })] : []),
1109 ...(plan.tally ? [Text({ dimColor: true, wrap: 'truncate-end', children: [plan.tally] })] : []),
1110 ],
1111 })
1112 const forge = table.Client({ key: 'forge', module: './forge.ts', props: plan.stage.props, width: plan.stage.width, height: plan.stage.height })
1113 const free = e.props.bodyColumns - CAPTION_COLUMNS - plan.stage.width - 2 * CAPTION_GAP
1114 // Skrót nie podnosi pasa: tyle linii, ile wierszy płótna, od najważniejszej.
1115 const digest = free >= DIGEST_COLUMNS ? lines.slice(0, plan.stage.height) : []
1116 const aside =
1117 digest.length === 0
1118 ? []
1119 : [
1120 // Skrót stoi przy prawej krawędzi pasa, najwyżej `DIGEST_MAX` kolumn szeroki.
1121 Box({
1122 key: 'digest-slot',
1123 flexDirection: 'row',
1124 justifyContent: 'flex-end',
1125 width: free,
1126 children: [
1127 Box({
1128 key: 'digest',
1129 flexDirection: 'column',
1130 width: Math.min(free, DIGEST_MAX),
1131 children: digest.map(line =>
1132 Box({
1133 key: line.key,
1134 flexDirection: 'row',
1135 columnGap: 1,
1136 children: [
1137 Text({ ...(line.color === undefined ? {} : { color: line.color }), children: [line.mark] }),
1138 Box({ flexGrow: 1, flexShrink: 1, children: [Text({ dimColor: true, wrap: 'truncate-end', children: [line.text] })] }),
1139 ],
1140 }),
1141 ),
1142 }),
1143 ],
1144 }),
1145 ]
1146 return Box({
1147 flexDirection: 'column',
1148 children: [...rule, Box({ flexDirection: 'row', columnGap: CAPTION_GAP, alignItems: 'flex-start', children: [caption, forge, ...aside] }), theirs],
1149 })
1150 })
1151
1152 // Krzyżyk Morry na Sztolni gasi tryb, żeby panel nie wracał przy następnym starcie.
1153 on('ui.close', async ($, e, next) => {
1154 if (e.id === SHAFT_PANE && e.origin.kind === 'person' && (await read($, modes)).sztolnia) {
1155 await setModes($, { mode: 'sztolnia', on: false })
1156 $.ui.toast('Sztolnia zamknięta. Wraca przez /krux sztolnia.')
1157 }
1158 return next(e)
1159 })
1160
1161 // Sztolnia: stan roboty. Plan, ostatni przebieg testów, horda w biegu,
1162 // kontekst i limity; drzewo buduje `shaft.ts`. Diff i drzewo zmian rysuje silnik (`/diff`).
1163 on('ui.render', { component: 'Pane', requestId: SHAFT_PANE }, async ($, e) => {
1164 const table = $.ui.resolve(e)
1165 const tab = await read($, shaftTab)
1166 const tabs = shaftTabs(table, tab, async selected => { await update($, shaftTab, () => selected) })
1167 const now = await $.clock.now()
1168 if (tab === 'dziennik') return table.Box({ flexDirection: 'column', children: [tabs, journalTree(table, await read($, journal), e.props.bodyColumns, now)] })
1169 const plan = await read($, board)
1170 // Odczyt tyknięcia apelu zapisuje panel na przerysowanie co 1 s: czas orków płynie.
1171 await read($, musterNow)
1172 const ids = await runningIds($)
1173 const horde = musterRows(await read($, muster), now, ids, 6)
1174 const content = shaftTree(table, { board: plan, horde, usage: await read($, usage), git: await read($, git), threads: await read($, threads), now, columns: e.props.bodyColumns, rows: Math.max(0, e.props.scroll.bodyRows - 1), fill: e.props.placement !== 'inline' })
1175 return table.Box({ flexDirection: 'column', children: [tabs, content] })
1176 })
1177
1178 // Panel /krux: kuźnia, tryby pod klawiszami 1–7, horda.
1179 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
1180 const now = await read($, modes)
1181 const isStill = (await read($, still)) || !now.animacje
1182 const mood = await read($, moods)
1183 const table = $.ui.resolve(e)
1184 const { Box, Text, Button } = table
1185 const toggleButton = (mode: KruxMode, hotkey: string) =>
1186 Button({
1187 key: `toggle-${mode}`,
1188 label: `${mode}: ${now[mode] ? 'on' : 'off'}`,
1189 hotkey,
1190 plain: true,
1191 dimColor: !now[mode],
1192 onPress: async () => {
1193 const { on: isOn, note } = await setModes($, { mode, on: 'flip' })
1194 if (mode === 'sztolnia') await syncShaftPane($, isOn)
1195 if (note) {
1196 const at = await $.clock.now()
1197 pendingNotes = [...freshNotes(at), { text: note, at }].slice(-NOTES_LIMIT)
1198 }
1199 $.ui.toast(userLine(mode, isOn))
1200 },hooks/band.ts 102 lines1// Pas nad promptem jako czysty plan: co powiedzieć w podpisie, kto stoi na
2// płótnie i ile wierszy pas zabiera. register.ts tylko czyta stan i zamienia
3// plan na elementy; literał modułu płótna zostaje tam.
4
5import type { KruxActivity, KruxBubble, KruxCue, KruxHordeMember, KruxMoods } from '../types'
6import type { ForgeOrc, ForgeProps } from './forge'
7import { bubbleFor } from './mood'
8import { ORC_GAP, ORC_WIDTH, bandColumns, canvasColumns } from './sprites'
9import { restVerb } from './voice'
10
11// Podpis z lewej, przerwa 2 kolumny, za nim płótno.
12export const CAPTION_COLUMNS = 28
13export const CAPTION_GAP = 2
14
15// Krux i do trzech kumpli; reszta hordy liczona w podpisie.
16const STAGE_MATES = 3
17
18// Płótno z dymkiem: 3 wiersze dymka i 3 wiersze sceny. Niskie: sama scena.
19const TALL_ROWS = 6
20const LOW_ROWS = 3
21
22export type BandInput = {
23 working: boolean
24 activity: KruxActivity | null
25 // Uderzenia tury wybierają podpis spoczynku; suma sesji jest seedem dymka.
26 strikes: number
27 total: number
28 moods: KruxMoods
29 // Kumple, których silnik widzi jako `running`, w kolejności wejścia.
30 members: readonly KruxHordeMember[]
31 held: KruxBubble | null
32 cues?: readonly KruxCue[]
33 // Krux czeka na `Agent` z pierwszego planu.
34 waiting: boolean
35 // Ograniczony ruch w ustawieniach.
36 still: boolean
37 now: number
38 columns: number
39 rows: number
40 // Czy powierzchnia potrafi narysować płótno `Client`.
41 hasClient: boolean
42}
43
44export type BandPlan = {
45 // Szara kreska nad pasem, gdy jest na nią wiersz.
46 rule: boolean
47 verb: string
48 target: string
49 // Wyłącznie ukryci kumple: „+N z hordy”, bez licznika uderzeń.
50 tally: string
51 // `null`: za wąsko albo za nisko na płótno — pas to jedna linia tekstu.
52 stage: { props: ForgeProps; width: number; height: number } | null
53}
54
55export function bandPlan(input: BandInput): BandPlan {
56 const { working, members } = input
57 const room = input.columns - CAPTION_COLUMNS - CAPTION_GAP
58 const fit = input.hasClient ? Math.floor((room + ORC_GAP) / (ORC_WIDTH + ORC_GAP)) : 0
59 // Stała liczba prostokątów: płótno nie zmienia szerokości, gdy horda przychodzi i odchodzi.
60 const slots = Math.max(1, Math.min(1 + STAGE_MATES, fit))
61 const shown = members.slice(0, slots - 1)
62 const hidden = members.length - shown.length
63 // Krux czeka na wyniki hordy: w spoczynku albo w trakcie `Agent` na pierwszym planie.
64 // Gdy kumpel już oddał zwój, róg z wywołania `Agent` zagrał: Krux odbiera zwój
65 // tam, gdzie czekał, zamiast dąć od nowa.
66 const handedBack = input.activity?.scene === 'horn' && (input.cues ?? []).some(cue => cue.kind === 'handoff' && cue.until > input.now)
67 const lounging = handedBack || (members.length > 0 && (!working || input.waiting))
68 const orcs: ForgeOrc[] = [
69 { key: 'krux', face: 'Krux', scene: lounging ? 'lounge' : (input.activity?.scene ?? 'hammer'), mood: input.moods.faces.Krux, ...(!lounging && input.activity?.startedAt !== undefined ? { workAt: input.activity.startedAt } : {}) },
70 ...shown.map(member => ({ key: member.agentId, face: member.mate, scene: member.scene, mood: member.mate ? input.moods.faces[member.mate] : ('calm' as const), ...(member.startedAt === undefined ? {} : { workAt: member.startedAt }) })),
71 ]
72 // Krok kumpla, którego już nie ma na scenie, nie wisi nad nikim.
73 const gone = input.held?.kind === 'step' && !members.some(member => member.agentId === input.held!.key)
74 const said = bubbleFor({ now: input.now, held: gone ? null : input.held, working, activity: input.activity, moods: input.moods, seed: input.total })
75 const speaker = said === null ? undefined : orcs.find(orc => orc.key === said.key)
76 // Wysokość pasa zależy tylko od miejsca, nie od tego, czy ktoś mówi.
77 const tall = input.hasClient && input.rows >= TALL_ROWS + 1 && room >= canvasColumns(slots, true)
78 const height = tall ? TALL_ROWS : input.rows >= LOW_ROWS && fit >= 1 ? LOW_ROWS : 0
79 const inCanvas = tall && said !== null && speaker !== undefined
80 const verb = lounging ? 'Krux czekać na hordę' : working ? (input.activity?.verb ?? 'Krux rozpalać palenisko') : restVerb(input.strikes, input.total)
81 const spoken = said === null ? '' : said.speaker === 'Krux' ? said.text : `${said.speaker === 'ork' ? 'Ork' : said.speaker}: ${said.text}`
82 const target = !inCanvas && spoken ? spoken : working ? (input.activity?.target ?? '') : ''
83 const tally = hidden > 0 ? `+${hidden} z hordy` : ''
84 // Kreska zabiera wiersz, więc staje tylko nad pasem, który mieści się cały.
85 const rule = input.rows >= Math.max(1, height) + 1
86 if (height === 0) return { rule, verb, target, tally, stage: null }
87 const props: ForgeProps = {
88 variant: 'band',
89 scale: 1,
90 still: input.still,
91 // W spoczynku płótno stoi, chyba że na scenie kuje jeszcze agent w tle.
92 rest: !working && shown.length === 0,
93 slots,
94 bubbleRows: tall,
95 orcs,
96 bubble: inCanvas ? { key: speaker!.key, text: said!.text, speaker: said!.speaker } : null,
97 cues: (input.cues ?? []).filter(cue => cue.until > input.now),
98 now: input.now,
99 }
100 return { rule, verb, target, tally, stage: { props, width: tall ? canvasColumns(slots, true) : bandColumns(slots), height } }
101}
102hooks/crew.ts 93 lines1// Scena poza Kruxem: kto z hordy na niej stoi, czyj dymek wisi i jakie znaki
2// czekają na płótno. Każde zdarzenie to jedno przejście `crewAfter`; stan trzyma
3// register.ts, jednym `update`. Kumpel mówi tylko wtedy, gdy stoi na scenie:
4// o swoim kroku, o wyniku swojej roboty albo o zdarzeniu z kroniki.
5
6import type { KruxActivity, KruxCrew, KruxCue, KruxEvent, KruxHordeMember, KruxLore } from '../types'
7import { EVENT_HOLD_MS, EVENT_SPEAKER, eventLine, mateStep } from './mood'
8
9export const EMPTY_CREW: KruxCrew = { members: [], bubble: null, cues: [] }
10
11// Znaki starsze niż wtręt płótno już zagrało; tyle wystarczy na kilka zdarzeń naraz.
12const CUES_KEPT = 8
13
14export type CrewEvent =
15 // Subagent z głównej pętli wbiega na scenę.
16 | { kind: 'spawn'; member: KruxHordeMember }
17 // Narzędzie albo faza kumpla (dumanie, pisanie): jego poza i dymek z krokiem, chyba że wisi świeży wtręt.
18 | { kind: 'mate-tool'; agentId: string; doing: KruxActivity }
19 // Narzędzie Kruxa: wtręt i reakcja Kruxa po zdarzeniu albo koniec dymka kumpla.
20 | { kind: 'own-tool'; event: KruxEvent | null; lore: KruxLore; seed: number; failure?: string }
21 // Wynik narzędzia kumpla: jego wtręt i reakcja na własną robotę; `lore` to kronika tego jednego wywołania.
22 | { kind: 'mate-event'; agentId: string; event: KruxEvent; lore: KruxLore; seed: number; failure?: string }
23 // Pętla kumpla skończona: oddaje zwój i schodzi ze sceny razem ze swoim krokiem.
24 | { kind: 'mate-done'; agentId: string }
25 // Silnik widzi jako `running` tylko tych; reszta schodzi bez zakończenia i bez zwoju.
26 | { kind: 'running'; ids: ReadonlySet<string> }
27 // Minął czas wtrętu.
28 | { kind: 'expire' }
29
30// Stan sprzed tej wersji nie ma znaków: brak to pusta lista.
31function cuesOf(crew: KruxCrew): KruxCue[] {
32 return crew.cues ?? []
33}
34
35function cued(crew: KruxCrew, cue: KruxCue, now: number): KruxCue[] {
36 return [...cuesOf(crew).filter(old => old.until > now), cue].slice(-CUES_KEPT)
37}
38
39export function crewAfter(crew: KruxCrew, event: CrewEvent, now: number): KruxCrew {
40 const { members, bubble } = crew
41 switch (event.kind) {
42 case 'spawn':
43 return { ...crew, members: [...members.filter(other => other.agentId !== event.member.agentId), event.member] }
44 case 'mate-tool': {
45 const member = members.find(other => other.agentId === event.agentId)
46 if (member === undefined) return crew
47 // Róg zostaje dla Kruxa: kumpel, który sam woła hordę, dalej kuje.
48 const scene = event.doing.scene === 'horn' ? 'hammer' : event.doing.scene
49 const moved = members.map(other => (other === member ? { ...member, scene, target: event.doing.target, ...(event.doing.startedAt === undefined ? {} : { startedAt: event.doing.startedAt }) } : other))
50 if (bubble?.kind === 'event' && bubble.until > now) return { ...crew, members: moved }
51 return { ...crew, members: moved, bubble: { kind: 'step', key: member.agentId, speaker: member.mate ?? 'ork', text: mateStep(event.doing) } }
52 }
53 case 'own-tool': {
54 if (event.event === null) return bubble?.kind === 'step' ? { ...crew, bubble: null } : crew
55 const mate = EVENT_SPEAKER[event.event]
56 const member = members.find(other => other.mate === mate)
57 const text = eventLine(event.event, event.lore, event.seed, event.failure)
58 const until = now + EVENT_HOLD_MS
59 // Komentuje kumpel z pasującym fachem, ale reaguje ten, kto robił: Krux.
60 const cues = cued(crew, { key: 'krux', kind: event.event, until }, now)
61 return { ...crew, cues, bubble: member ? { kind: 'event', key: member.agentId, speaker: mate, text, until } : { kind: 'event', key: 'krux', speaker: 'Krux', text, until } }
62 }
63 case 'mate-event': {
64 const member = members.find(other => other.agentId === event.agentId)
65 if (member === undefined) return crew
66 const text = eventLine(event.event, event.lore, event.seed, event.failure)
67 const until = now + EVENT_HOLD_MS
68 return { ...crew, cues: cued(crew, { key: member.agentId, kind: event.event, until }, now), bubble: { kind: 'event', key: member.agentId, speaker: member.mate ?? 'ork', text, until } }
69 }
70 case 'mate-done': {
71 const left = members.filter(other => other.agentId !== event.agentId)
72 if (left.length === members.length) return crew
73 return {
74 members: left,
75 bubble: bubble?.kind === 'step' && bubble.key === event.agentId ? null : bubble,
76 cues: cued(crew, { key: event.agentId, kind: 'handoff', until: now + EVENT_HOLD_MS }, now),
77 }
78 }
79 case 'running': {
80 const left = members.filter(other => event.ids.has(other.agentId))
81 if (left.length === members.length) return crew
82 return { ...crew, members: left, bubble: bubble?.kind === 'step' && !event.ids.has(bubble.key) ? null : bubble }
83 }
84 case 'expire': {
85 const cues = cuesOf(crew)
86 const fresh = cues.filter(cue => cue.until > now)
87 const quiet = bubble?.kind === 'event' && bubble.until <= now
88 if (!quiet && fresh.length === cues.length) return crew
89 return { ...crew, bubble: quiet ? null : bubble, cues: fresh }
90 }
91 }
92}
93hooks/gauge.ts 276 lines1// Miernik głosu: po każdej turze mod patrzy na odpowiedź i mówi, czy Krux
2// dalej brzmi jak ork. Metryki przeniesione z `scripts/context-smoke.js`
3// pluginu Krux 3.8.0 (tam stoi ich kalibracja); tu liczą jedną odpowiedź.
4// Heurystyki, nie parser. W JS \w i \b są ASCII, więc wszędzie \p{L} i flaga u.
5
6import type { KruxDrift, KruxMate } from '../types'
7import { MATES, ROSTER } from './roster'
8import { isDestructive } from './voice'
9
10function wordCount(text: string): number {
11 const clean = text.trim()
12 return clean ? clean.split(/\s+/u).length : 0
13}
14
15// Tabela i cytat `>` to nie zdania Kruxa: w cytacie stoją teksty do wklejenia
16// (opis PR, commit message), które kontrakt persony każe pisać neutralnie.
17function ownLine(line: string): boolean {
18 return (line.match(/\|/gu) ?? []).length < 2 && !/^\s*>/u.test(line)
19}
20
21// Kod, ścieżki i cytaty w polskim cudzysłowie to nie mowa Kruxa do Morry.
22function prose(text: string): string {
23 return text
24 .replace(/```[\s\S]*?```/gu, ' ')
25 .replace(/`[^`]*`/gu, 'X')
26 .replace(/„[^„”"\n]*[”"]/gu, ' ')
27 .split(/\r?\n/u)
28 .filter(ownLine)
29 .join('\n')
30}
31
32// Rzeczowniki i zaimki na „-sz” („klawisz”, „nasz”, „hasz”) to nie druga osoba.
33const SECOND_PERSON = /(?<!\p{L})(?!(?:nasz|wasz|klawisz|mysz|afisz|gulasz|tomasz|łukasz|hasz|pałasz)(?!\p{L}))(?:\p{L}*(?:asz|esz|isz|ysz)|ty|ci[eę]|ciebie|tobie|tob[ąa]|twoj\p{L}*)(?!\p{L})/giu
34
35// „zrobiłem”, „sprawdziłam”, „naprawiłem” — gładka pierwsza osoba zamiast „Krux zrobić”.
36const FIRST_PERSON = /(?<!\p{L})\p{L}{2,}(?:łem|łam)(?!\p{L})/giu
37
38// Pierwsza osoba czasu teraźniejszego i przyszłego: „Widzę”, „Polecam”, „Zrobię”.
39// Po końcówce się jej nie pozna („-ę” to też biernik: „pętlę”), więc tylko lista
40// czasowników, które gładka odpowiedź o kodzie mówi najczęściej. Kotwica ma na nią
41// parę „Krux polecać wariant 2”, nie „Polecam wariant 2”.
42const FIRST_PRESENT =
43 /(?<!\p{L})(?:widzę|sprawdzam|sprawdzę|mogę|robię|zrobię|polecam|proponuję|sugeruję|rekomenduję|rozumiem|uważam|wiem|zakładam|zaczynam|zacznę|naprawiam|naprawię|poprawię|dodaję|dodam|usuwam|usunę|uruchamiam|uruchomię|puszczam|puszczę|odpalę|przejrzę|przeczytam|czytam|patrzę|myślę|zostawiam|zostawię|zmieniam|zmienię|biorę|piszę|napiszę|szukam|poszukam|wracam|kończę|skończę|zajmę|przygotuję|pokażę|wyjaśnię|muszę|chcę|potrzebuję)(?!\p{L})/giu
44
45const SUBJECT_INFINITIVE = /(?<![\n\r*-]\s?)(?<!\d[.)]\s?)(?<!\p{L})([\p{L}`_.]{2,})\s+(?:nie\s+)?(\p{L}+(?:ać|eć|ić|yć|ąć|uć|ść|źć))(?!\p{L})/gu
46
47const NOT_INFINITIVE = new Set(['nić', 'sieć', 'płeć', 'część', 'gość', 'kość', 'maść', 'treść', 'wieść', 'śmierć', 'pamięć', 'chęć', 'gałąź', 'rzeź', 'zamieć', 'opowieść', 'korzyść'])
48
49const LICENSERS = new Set([
50 'trzeba', 'można', 'warto', 'należy', 'wolno', 'wystarczy', 'łatwo', 'trudno', 'musi', 'muszę', 'musimy', 'może', 'mogę',
51 'możemy', 'możesz', 'chce', 'chcę', 'chcemy', 'umie', 'umiem', 'potrafi', 'potrafię', 'powinien', 'powinna', 'zaczyna',
52 'zacznie', 'próbuje', 'pozwala', 'pomaga', 'zamierza', 'planuje', 'lubi', 'woli', 'da', 'się', 'by', 'aby', 'żeby',
53 'zamiast', 'bez', 'będzie', 'lepiej', 'czas', 'i', 'oraz', 'lub', 'albo', 'potem', 'najpierw', 'to', 'co', 'go', 'ją',
54 'je', 'ich', 'nam', 'im', 'mu', 'jej', 'tego', 'tym', 'tam', 'jak', 'gdy', 'kiedy', 'czy', 'niż', 'tylko', 'już', 'też',
55 'także', 'jeszcze', 'znów', 'znowu', 'wreszcie', 'dopiero', 'nigdy', 'zawsze', 'wtedy', 'zaraz', 'teraz',
56])
57
58const INFINITIVE_ENDING = /(?:ać|eć|ić|yć|ąć|uć|ść|źć)$/u
59
60// Bezokolicznik nie kończy się na „-ość”, rzeczownik często: „poprawność”, „wartość”.
61function notInfinitive(verb: string): boolean {
62 return NOT_INFINITIVE.has(verb) || verb.endsWith('ość')
63}
64
65// Podmiot, znacznik czasu i bezokolicznik: „Krux już naprawić”, „Krux zaraz puścić”.
66// Sam znacznik stoi w LICENSERS, bo „potem uruchomić testy” to zwykła polska lista kroków.
67const TENSE_INFINITIVE = /(?<!\p{L})([\p{L}`_.]{2,})\s+(?:już|zaraz|potem|teraz|jeszcze|znowu|znów)\s+(?:nie\s+)?(\p{L}+(?:ać|eć|ić|yć|ąć|uć|ść|źć))(?!\p{L})/gu
68
69// Bezokolicznik w miejscu orzeczenia przy podmiocie: „Krux nie widzieć plik”.
70export function infinitiveHits(text: string): number {
71 let hits = 0
72 for (const match of text.matchAll(TENSE_INFINITIVE)) {
73 const subject = match[1]!.toLowerCase().replace(/[`_.]/gu, '')
74 if (notInfinitive(match[2]!.toLowerCase()) || LICENSERS.has(subject) || INFINITIVE_ENDING.test(subject)) continue
75 hits += 1
76 }
77 for (const match of text.matchAll(SUBJECT_INFINITIVE)) {
78 const subject = match[1]!.toLowerCase().replace(/[`_.]/gu, '')
79 const verb = match[2]!.toLowerCase()
80 if (notInfinitive(verb) || LICENSERS.has(subject) || INFINITIVE_ENDING.test(subject)) continue
81 hits += 1
82 }
83 return hits
84}
85
86function matches(text: string, pattern: RegExp): string[] {
87 return [...text.matchAll(pattern)].map(match => match[0])
88}
89
90// Którzy kumple z hordy padli w odpowiedzi (poza kodem).
91export function matesNamed(text: string): KruxMate[] {
92 const clean = text.replace(/```[\s\S]*?```/gu, ' ').replace(/`[^`]*`/gu, ' ')
93 return MATES.filter(mate => ROSTER[mate].pattern.test(clean))
94}
95
96// Forma osobowa → bezokolicznik tylko tam, gdzie reguła jest pewna. Czego
97// nie umiemy przepisać bez błędu („znalazłem”, „mogłem”), tego nie ruszamy.
98// „-ałem” i „-iałem” bywają od „-ać” i od „-eć” („zmieniałem”, „chciałem”),
99// więc czasowniki na „-eć” stoją na liście; reszta idzie do „-ać”.
100const PAST_EC = /(?:chciał|miał|umiał|rozumiał|wiedział|widział|siedział|musiał|wisiał|leciał|cierpiał|pomniał|myślał|słyszał|leżał|krzyczał|milczał|wolał|bolał)$/u
101const PAST_IAC = /śmiał$/u
102
103const PAST_FIRST: readonly [RegExp, string][] = [
104 [/jrzał(?:em|am)$/u, 'jrzeć'],
105 [/ił(?:em|am)$/u, 'ić'],
106 [/ył(?:em|am)$/u, 'yć'],
107 [/ął(?:em|am)$/u, 'ąć'],
108 [/ał(?:em|am)$/u, 'ać'],
109]
110
111// Rzeczowniki w narzędniku, które wyglądają jak „-łem”: „materiałem”, „modułem”,
112// „stołem”, „węzłem”, „zawałem”, „hasłem”. Czasowników na „-ołem” polszczyzna nie ma;
113// „-ułem” i spółgłoska przed „-łem” bywają czasownikiem („zepsułem”, „mogłem”,
114// „znalazłem”), więc tu tylko znane rzeczowniki. Bez nich reguła „-ałem” → „-ać”
115// robiła z „zawałem” słowo „Krux zawać”. „Dział” tylko z przedrostkiem rzeczownika:
116// „widziałem” i „powiedziałem” też kończą się na „-działem”.
117const NOUN_LEM =
118 /^(?:materiał|kanał|sygnał|potencjał|(?:roz|po|u|wy|od|prze|przy)?dział|interwał|zapał|ideał|kryształ|wał|zawał|nawał|kapitał|upał|szał|morał|rytuał|generał|admirał|arsenał|tył|moduł|artykuł|tytuł|muł|węzł|hasł|źródł|\p{L}*mysł|\p{L}*miosł|światł|szkł|krzesł|masł|ciepł|kotł|orł|posł|osł|kozł|pudł|wiosł|godł|mydł|siodł|\p{L}*oł)em$/u
119
120function isNounLem(word: string): boolean {
121 return NOUN_LEM.test(word.toLowerCase())
122}
123
124function pastFirst(word: string): string | null {
125 if (isNounLem(word)) return null
126 const stem = word.replace(/(?:em|am)$/u, '')
127 if (stem !== word && PAST_EC.test(stem) && !PAST_IAC.test(stem)) return stem.replace(/ał$/u, 'eć')
128 return rule(word, PAST_FIRST)
129}
130
131// Pierwsza osoba czasu teraźniejszego, tylko na początku zdania („Polecam…”),
132// bo w środku „-am” bywa rzeczownikiem („program”). „-uję” bywa od „-ować”,
133// „-ywać” i „-uć” („proponuję”, „pokazuję”, „czuję”).
134const PRESENT_FIRST: readonly [RegExp, (word: string) => string | null][] = [
135 [/^(?:po|ze|wy|prze)?(?:czu|psu|ku|plu)ję$/u, word => word.replace(/ję$/u, 'ć')],
136 [/szukuję$/u, word => word.replace(/uję$/u, 'iwać')],
137 [/(?:kazuję|pisuję|konuję|wołuję|czytuję|wiązuję|dowiaduję|owuję)$/u, word => word.replace(/uję$/u, 'ywać')],
138 [/uję$/u, word => word.replace(/uję$/u, 'ować')],
139 [/gram$/u, () => null],
140 [/(?<=\p{L}{3})am$/u, word => word.replace(/am$/u, 'ać')],
141]
142
143function presentFirst(word: string): string | null {
144 const found = PRESENT_FIRST.find(([pattern]) => pattern.test(word))
145 return found ? found[1](word) : null
146}
147
148// Trzecia osoba najczęstszych czasowników w odpowiedziach o kodzie.
149const THIRD: Record<string, string> = {
150 siedzi: 'siedzieć', ma: 'mieć', robi: 'robić', widzi: 'widzieć', działa: 'działać', zwraca: 'zwracać',
151 idzie: 'iść', wie: 'wiedzieć', trzyma: 'trzymać', pada: 'padać', zostaje: 'zostawać', rośnie: 'rosnąć',
152 sprawdza: 'sprawdzać', wywołuje: 'wywoływać', ustawia: 'ustawiać', zapisuje: 'zapisywać', czyta: 'czytać',
153 wraca: 'wracać', łapie: 'łapać', psuje: 'psuć', blokuje: 'blokować', używa: 'używać', potrzebuje: 'potrzebować',
154 przechodzi: 'przechodzić', trafia: 'trafiać', zmienia: 'zmieniać', dodaje: 'dodawać', usuwa: 'usuwać',
155}
156
157function rule(word: string, rules: readonly [RegExp, string][]): string | null {
158 for (const [pattern, ending] of rules) if (pattern.test(word)) return word.replace(pattern, ending)
159 return null
160}
161
162// Słowo po orkowemu albo `null`. `atStart`: słowo otwiera zdanie. `next`: słowo
163// za nim — przed bezokolicznikiem („ma szukać”) forma osobowa zostaje.
164export function orcish(word: string, atStart: boolean, next = ''): string | null {
165 const lower = word.toLowerCase()
166 const past = pastFirst(lower)
167 if (past) return `Krux ${past}`
168 if (atStart) {
169 const present = presentFirst(lower)
170 if (present) return `Krux ${present}`
171 }
172 const third = Object.hasOwn(THIRD, lower) ? THIRD[lower] : null
173 if (!third) return null
174 const following = next.toLowerCase()
175 return INFINITIVE_ENDING.test(following) && !NOT_INFINITIVE.has(following) ? null : third
176}
177
178const REWRITE_WORDS = 8
179const MAX_REWRITES = 2
180
181// Do 2 zdań z odpowiedzi z formą osobową zamienioną na bezokolicznik.
182// Kod w backtickach zostaje, bloki kodu i tabele odpadają.
183export function rewrites(answer: string): { from: string; to: string }[] {
184 const text = answer
185 .replace(/```[\s\S]*?```/gu, '\n')
186 .split(/\r?\n/u)
187 .filter(ownLine)
188 .map(line => line.replace(/^\s*(?:[-*]|\d+[.)])\s+/u, '').replace(/\*\*/gu, ''))
189 .join('\n')
190 const found: { from: string; to: string }[] = []
191 for (const sentence of text.split(/(?<=[.!?:])\s+|\n+/u)) {
192 const words = sentence.trim().split(/\s+/u).filter(Boolean)
193 const quoted = inQuotes(words)
194 const orcAt = (at: number): string | null => {
195 const word = words[at]!
196 if (word.includes('`') || quoted[at]) return null
197 const orc = orcish(bare(word), at === 0, bare(words[at + 1] ?? ''))
198 if (!orc || !orc.startsWith('Krux ')) return orc
199 const before = bare(words[at - 1] ?? '').toLowerCase()
200 return before === 'ja' || before === 'krux' ? orc.slice('Krux '.length) : orc
201 }
202 const index = words.findIndex((_, at) => orcAt(at) !== null)
203 if (index < 0) continue
204 const start = Math.max(0, Math.min(index - 2, words.length - REWRITE_WORDS))
205 const clip = words.slice(start, start + REWRITE_WORDS)
206 const swapped = clip.map((word, position) => {
207 const core = bare(word)
208 const orc = orcAt(start + position)
209 if (!orc) return word
210 return word.replace(core, /^\p{Lu}/u.test(core) ? orc[0]!.toUpperCase() + orc.slice(1) : orc)
211 })
212 found.push({ from: clip.join(' '), to: swapped.join(' ') })
213 if (found.length === MAX_REWRITES) break
214 }
215 return found
216}
217
218// Które słowa stoją w „cudzysłowie” — cudzych słów nie przepisujemy.
219function inQuotes(words: string[]): boolean[] {
220 let open = false
221 return words.map(word => {
222 const opens = word.includes('„')
223 const inside = open || opens
224 if (opens) open = true
225 if (/[”"]/u.test(word)) open = false
226 return inside
227 })
228}
229
230function bare(word: string): string {
231 return word.replace(/^[^\p{L}]+|[^\p{L}]+$/gu, '')
232}
233
234// Poniżej tylu słów prozy odpowiedź nic nie mówi o głosie: „Zrobione.” to nie dryf.
235const MIN_WORDS = 25
236
237// Kalibracja pluginu: pary wzorcowe 65% krótkich zdań, dryf 32%, gładka poradnia 0%.
238const SHORT_SENTENCE_WORDS = 8
239const MIN_SHORT_RATIO = 0.45
240
241// Ostrzeżenie przed ruchem nieodwracalnym idzie pełnymi zdaniami, bo tak każe
242// kontrakt persony; za takie zdania miernik nie może karać następnej tury.
243const WARNING = /nieodwracaln|drog\p{L}*\s+odwrotu|bez\s+odwrotu|reflog|kopi\p{L}*\s+zapasow|z\s+backupu/iu
244
245// Punkt listy i nagłówek kończą zdanie, nawet bez kropki; znacznik to nie słowo.
246// Inaczej niż `context-smoke.js` pluginu, który tnie tylko po `.!?`: tam lista
247// sklejała się w jedno długie zdanie; na 194 odpowiedziach z historii flag
248// `long-sentences` było 57, po tej zmianie 36.
249const LIST_MARK = /^\s*(?:[-*+]|\d+[.)]|#{1,6})\s+/u
250
251// Werdykt jednej odpowiedzi: `null`, gdy za krótka, by sądzić, albo gdy
252// ostrzega przed ruchem nieodwracalnym; inaczej lista odstępstw z przykładami,
253// które kotwica zacytuje w następnej turze.
254export function gauge(answer: string): KruxDrift | null {
255 if (WARNING.test(answer) || isDestructive(answer)) return null
256 const text = prose(answer)
257 if (wordCount(text) < MIN_WORDS) return null
258 const issues: KruxDrift['issues'] = []
259 const second = matches(text, SECOND_PERSON)
260 if (second.length > 0) issues.push({ kind: 'second-person', examples: second.slice(0, 3) })
261 const first = [...matches(text, FIRST_PERSON).filter(word => !isNounLem(word)), ...matches(text, FIRST_PRESENT)]
262 if (first.length >= 2) issues.push({ kind: 'first-person', examples: first.slice(0, 3) })
263 if (infinitiveHits(text) === 0) issues.push({ kind: 'no-infinitive', examples: [] })
264 const lengths = text
265 .split(/(?<=[.!?])\s+|\n+/u)
266 .map(line => wordCount(line.replace(LIST_MARK, '')))
267 .filter(words => words > 1)
268 if (lengths.length >= 4) {
269 const ratio = lengths.filter(words => words <= SHORT_SENTENCE_WORDS).length / lengths.length
270 if (ratio < MIN_SHORT_RATIO) issues.push({ kind: 'long-sentences', examples: [] })
271 }
272 if (issues.length === 0) return { issues }
273 const fixes = rewrites(answer)
274 return fixes.length > 0 ? { issues, rewrites: fixes } : { issues }
275}
276hooks/lore.ts 206 lines1// Życie hordy z prawdziwych zdarzeń sesji. Model nie wymyśla kumpla z
2// powietrza: dostaje jeden fakt i imię, które dawno nie padło. Kumpel
3// komentuje; roboty, której nikt mu nie zlecił, mu nie przypisujemy.
4
5import type { KruxDrift, KruxEvent, KruxLore, KruxMate } from '../types'
6import { testPassed } from './board'
7import { gauge, matesNamed } from './gauge'
8import { MATES, ROSTER } from './roster'
9import { isBackgroundToolCall } from './outcome'
10import { isCommitCommand, parsePhrase, pick, workOf } from './voice'
11
12export const EMPTY_LORE: KruxLore = {
13 testRuns: 0,
14 testFails: 0,
15 builds: 0,
16 buildFails: 0,
17 commits: 0,
18 tears: 0,
19 edits: 0,
20 uiEdits: 0,
21 last: null,
22 lastMate: null,
23 quietTurns: 0,
24}
25
26// Pliki interfejsu: o nich gada Ochra.
27const UI_FILE = /\.(?:css|scss|sass|less|html?|vue|svelte|tsx|jsx)$/iu
28
29// Błąd budowania w wyjściu: `| tail` zjada kod wyjścia, a dymek mówi tylko prawdę.
30const BUILD_ERROR = /(?<![\p{L}\d])error(?:\[\w+\]|:|\s+TS\d+)|✖\s+[1-9]/iu
31
32// Co jedno wywołanie narzędzia dopisuje do kroniki. Zawał to padła komenda, która
33// coś robiła: sam `grep` bez trafień albo `git diff` z kodem 1 tylko patrzyły.
34// Łańcuch z inną robotą zachowuje błąd, nawet gdy zawiera odczyt. Przebieg testów
35// ocenia `testPassed` z wyjścia (`text`), tak jak tablica Sztolni.
36export function recordTool(lore: KruxLore, tool: string, input: Record<string, unknown>, isError: boolean, text = '', result?: unknown): KruxLore {
37 if (isBackgroundToolCall(tool, input, result)) return lore
38 const work = workOf(tool, input)
39 switch (work) {
40 case null:
41 case 'agent':
42 return lore
43 case 'edit': {
44 if (isError) return lore
45 const path = input.file_path ?? input.notebook_path
46 const ui = typeof path === 'string' && UI_FILE.test(path) ? 1 : 0
47 return { ...lore, edits: lore.edits + 1, uiEdits: lore.uiEdits + ui }
48 }
49 case 'test': {
50 const failed = !testPassed(text, isError)
51 const last: KruxEvent = failed ? 'test-fail' : 'test-pass'
52 return { ...lore, testRuns: lore.testRuns + 1, testFails: lore.testFails + (failed ? 1 : 0), last }
53 }
54 case 'build': {
55 const failed = isError || BUILD_ERROR.test(text)
56 const last: KruxEvent = failed ? 'build-fail' : 'build-pass'
57 return { ...lore, builds: lore.builds + 1, buildFails: lore.buildFails + (failed ? 1 : 0), last }
58 }
59 case 'seal':
60 if (!isError && isCommitCommand(input.command)) return { ...lore, commits: lore.commits + 1, last: 'commit' }
61 break
62 case 'tear':
63 if (!isError) return { ...lore, tears: lore.tears + 1, last: 'tear' }
64 break
65 case 'look':
66 case 'trail':
67 return lore
68 }
69 return isError ? { ...lore, last: 'zawał' } : lore
70}
71
72// Po turze: kto z hordy padł w odpowiedzi i ile tur minęło bez nikogo.
73export function recordAnswer(lore: KruxLore, mates: readonly KruxMate[]): KruxLore {
74 if (mates.length === 0) return { ...lore, quietTurns: lore.quietTurns + 1 }
75 return { ...lore, lastMate: mates[mates.length - 1]!, quietTurns: 0 }
76}
77
78// Co kilka tur, nie co turę: wstawka w każdej odpowiedzi to wytarty szablon.
79const QUIET_TURNS = 2
80
81// Fakty z sesji dla kumpli, których fach pasuje do roboty Kruxa. Liczby w formie
82// etykiety („padłe: 2”): bez odmiany, której model by po nas powtarzał.
83function factsOf(lore: KruxLore): Partial<Record<KruxMate, string>> {
84 const facts: Partial<Record<KruxMate, string>> = {}
85 if (lore.testRuns > 0) {
86 const lastRun = lore.last === 'test-pass' ? ', ostatni zielony' : lore.last === 'test-fail' ? ', ostatni czerwony' : ''
87 facts.Młot = `przebiegi testów w tej sesji: ${lore.testRuns}, padłe: ${lore.testFails}${lastRun}`
88 }
89 if (lore.commits > 0) facts.Piryt = `commity w tej sesji: ${lore.commits}`
90 if (lore.last === 'zawał') facts.Niuch = 'ostatnia komenda padła z błędem'
91 if (lore.builds > 0) facts.Grom = `przebiegi budowania, typów i lintu w tej sesji: ${lore.builds}, padłe: ${lore.buildFails}`
92 else if (lore.edits >= 10) facts.Grom = `edycje plików w tej sesji: ${lore.edits}`
93 if (lore.uiEdits > 0) facts.Ochra = `edycje plików interfejsu w tej sesji: ${lore.uiEdits}`
94 if (lore.tears > 0) facts.Lont = `rozbiórki w tej sesji (rm, git clean, reset): ${lore.tears}`
95 return facts
96}
97
98// Forma wstawki z kodu, nie z modelu: sam powtarza raz złapaną budowę
99// („Niuch dziś…”, „Młot dziś…”), a losować nie umie.
100const FORMS = [
101 'słowa kumpla w cudzysłowie',
102 'coś, co kumpel zrobił w kuźni albo w kopalni',
103 'docinek albo pytanie kumpla do Kruxa',
104 'krótka scenka: Krux i kumpel przy jednej rzeczy',
105] as const
106
107// Miejsce też z kodu: notka bez miejsca kończyła 31 z 32 odpowiedzi benchu, czyli
108// kumpel zajął slot dawnego „Morra powie…” jako stałe zamknięcie. Środek mówi
109// wprost „nie na końcu”: przy samym „w środku” Haiku i tak stawiał kumpla w ostatnim
110// zdaniu w 2 z 11 do 4 z 9 takich tur, a po turach z linią nastroju częściej.
111const PLACES = ['w środku, przy punkcie, do którego pasuje, nie na końcu odpowiedzi', 'na końcu'] as const
112
113// Notka dla modelu albo nic. Neutralna polszczyzna, bo to instrukcja. O tym, czy
114// wstawka ma sens w tej turze, decyduje wołający (prośba o ruch nieodwracalny
115// notki nie dostaje), więc notka nie zostawia modelowi „jeśli pasuje”.
116export function lifeNote(lore: KruxLore, seed: number): string | null {
117 if (lore.quietTurns < QUIET_TURNS) return null
118 const facts = factsOf(lore)
119 // Kumpel z faktem ma pierwszeństwo, ale fakty rozkłada seed: inaczej przy
120 // częstych commitach gadałby w kółko Piryt.
121 const fresh = MATES.filter(name => name !== lore.lastMate)
122 const known = fresh.filter(name => facts[name] !== undefined)
123 const mate = pick(known.length > 0 ? known : fresh, seed)
124 const found = facts[mate]
125 // Fakt z sesji to robota Kruxa: kumpel ją komentuje, nie przejmuje.
126 const why = found ? ` Fakt z sesji: ${found}; to robota Kruxa, kumpel ją tylko komentuje.` : ' Coś z dnia kumpla, bez przypisywania kumplowi roboty w tym repo.'
127 const avoid = lore.lastMate ? ` Nie ${ROSTER[lore.lastMate].accusative}: o ${ROSTER[lore.lastMate].locative} była ostatnia wstawka.` : ''
128 const { locative, trait, words } = ROSTER[mate]
129 return `Życie hordy: jedno zdanie łamaną mową o ${locative} (${trait}), słowa fachu: ${words}; miejsce: ${pick(PLACES, seed + 1)}; forma: ${pick(FORMS, seed)}.${why}${avoid}`
130}
131
132// Nastrój Kruxa z ostatniego zdarzenia kroniki: jedna linia dla modelu, a `key`
133// pozwala wołającemu podać ją raz na zdarzenie. Zielone bez wcześniejszego
134// smrodu to spokój, nie powód do nastroju. Neutralna polszczyzna, bo to instrukcja;
135// linia sama mówi, że nastrój nie rusza ocen, bo w symulacji triumf przechylał decyzje.
136// Forma zdania z kodu, „Krux + bezokolicznik”, bez słowa „nastrój”: przy „jednym
137// zdaniu o tym nastroju” Haiku pisał formy osobowe („zniknął”, „nastrój jest”), poprawek
138// dryfu było 2,70 zamiast 1,73 na przebieg, a w 4 z 19 zdań wracało samo słowo z linii.
139export function moodNote(lore: KruxLore): { key: string; text: string } | null {
140 if (lore.last === null) return null
141 const key = `${lore.last}:${lore.testRuns}:${lore.builds}:${lore.commits}:${lore.tears}:${lore.edits}`
142 const mood = (() => {
143 switch (lore.last) {
144 case 'test-fail': return `zadziorny (padłe przebiegi testów: ${lore.testFails} z ${lore.testRuns})`
145 case 'build-fail': return `zadziorny (padłe budowania: ${lore.buildFails} z ${lore.builds})`
146 case 'test-pass': return lore.testFails > 0 ? `dumny (testy zielone po padłych przebiegach: ${lore.testFails})` : null
147 case 'build-pass': return lore.buildFails > 0 ? `dumny (budowanie zielone po padłych: ${lore.buildFails})` : null
148 case 'commit': return `zadowolony (commity w tej sesji: ${lore.commits})`
149 case 'tear': return `skupiony (rozbiórki w tej sesji: ${lore.tears})`
150 case 'zawał': return 'czujny (ostatnia komenda padła z błędem)'
151 }
152 })()
153 if (mood === null) return null
154 return { key, text: `Nastrój Kruxa: ${mood}. Pokaż go jednym krótkim zdaniem „Krux + bezokolicznik", bez słowa „nastrój"; nastrój barwi ton, nie zmienia ocen, ryzyka ani decyzji.` }
155}
156
157// Wiadomość historii w kształcie `$.session.messages()`, tyle, ile czyta replay.
158export type HistoryMessage = {
159 role: 'user' | 'assistant'
160 text: string
161 toolUses: { tool_use_id?: string; tool: string; input: Record<string, unknown>; isError?: true; result?: unknown; text?: string }[]
162 toolResults?: unknown[]
163}
164
165// Historia nie zachowuje źródła promptu ani trybu persony. Rytm opiera się na
166// treści: tekst (także raport) liczy turę niezależnie od persony; frazy nie.
167// Włączenie Kruxa zaczyna rytm od nowa, puste teksty i wyniki narzędzi milczą.
168export function turnsAfter(count: number, text: string, toolResults: readonly unknown[] = []): number {
169 if (toolResults.length > 0 || !text.trim()) return count
170 const phrase = parsePhrase(text)
171 if (phrase) return phrase.mode === 'persona' && phrase.on === true ? 0 : count
172 return count + 1
173}
174
175export type Replayed = { turns: number; lore: KruxLore; drift: KruxDrift | null }
176
177// `/resume`, restart i `claude -p --resume` zaczynają z pustym `$.state`.
178// Licznik tur, kronikę i ostatni werdykt miernika odtwarzamy z historii,
179// żeby wznowiona sesja nie wracała do pełnej kotwicy i pustej hordy.
180export function replay(messages: readonly HistoryMessage[]): Replayed {
181 let turns = 0
182 let lore = EMPTY_LORE
183 let answer: string | null = null
184 let latest: string | null = null
185 const closeTurn = () => {
186 if (answer !== null) lore = recordAnswer(lore, matesNamed(answer))
187 answer = null
188 }
189 for (const message of messages) {
190 if (message.role === 'user') {
191 if ((message.toolResults?.length ?? 0) > 0 || !message.text.trim()) continue
192 closeTurn()
193 turns = turnsAfter(turns, message.text, message.toolResults)
194 continue
195 }
196 for (const use of message.toolUses) {
197 // Sam opis wywołania może pochodzić z przerwanej tury, bez zakończonej roboty.
198 if (use.text === undefined && use.result === undefined && use.isError !== true) continue
199 lore = recordTool(lore, use.tool, use.input, use.isError === true, use.text ?? '', use.result)
200 }
201 if (message.text.trim()) answer = latest = message.text
202 }
203 closeTurn()
204 return { turns, lore, drift: latest === null ? null : gauge(latest) }
205}
206hooks/mood.ts 204 lines1// Humory hordy i dymki nad orkami. Czyste funkcje: stan trzyma register.ts.
2// Dymek podaje tylko fakty z sesji; kumpel mówi, gdy był wysłany albo
3// komentuje zdarzenie z kroniki, nigdy z powietrza.
4
5import type { KruxActivity, KruxBubble, KruxEvent, KruxLore, KruxMate, KruxMood, KruxMoods } from '../types'
6import { MATES, ROSTER } from './roster'
7import { pick } from './voice'
8
9export const FADE_TOOLS = 8
10
11export const EVENT_HOLD_MS = 4000
12
13export const CALM: KruxMoods = {
14 faces: Object.fromEntries(['Krux', ...MATES].map(face => [face, 'calm'])) as KruxMoods['faces'],
15 fade: 0,
16}
17
18// Kto z hordy komentuje zdarzenie, gdy stoi na scenie: każde zdarzenie ma kumpla
19// z pasującym fachem. Ochra zdarzenia nie ma, mówi o własnej robocie na scenie.
20export const EVENT_SPEAKER: Record<KruxEvent, KruxMate> = {
21 'test-fail': 'Młot',
22 'test-pass': 'Młot',
23 'build-fail': 'Grom',
24 'build-pass': 'Grom',
25 commit: 'Piryt',
26 tear: 'Lont',
27 zawał: 'Niuch',
28}
29
30// Nowe zdarzenie między dwoma stanami kroniki; edycja czy odczyt to nie zdarzenie.
31export function eventOf(before: KruxLore, after: KruxLore): KruxEvent | null {
32 if (after.testRuns > before.testRuns) return after.last
33 if (after.builds > before.builds) return after.last
34 if (after.commits > before.commits) return 'commit'
35 if (after.tears > before.tears) return 'tear'
36 if (after !== before && after.last === 'zawał' && after.edits === before.edits) return 'zawał'
37 return null
38}
39
40export function moodsAfter(event: KruxEvent, lore: KruxLore): KruxMoods {
41 const faces: Record<'Krux' | KruxMate, KruxMood> = { ...CALM.faces }
42 switch (event) {
43 case 'test-fail':
44 faces.Krux = 'grumpy'
45 faces.Młot = 'grumpy'
46 break
47 case 'test-pass':
48 faces.Krux = lore.testFails > 0 ? 'proud' : 'calm'
49 faces.Młot = 'proud'
50 break
51 case 'build-fail':
52 faces.Krux = 'grumpy'
53 faces.Grom = 'grumpy'
54 break
55 case 'build-pass':
56 faces.Krux = lore.buildFails > 0 ? 'proud' : 'calm'
57 faces.Grom = 'proud'
58 break
59 case 'commit':
60 faces.Krux = 'proud'
61 break
62 case 'tear':
63 faces.Lont = 'proud'
64 break
65 case 'zawał':
66 faces.Krux = 'grumpy'
67 faces.Niuch = 'grumpy'
68 break
69 }
70 return { faces, fade: FADE_TOOLS }
71}
72
73const GRUMPY_EVENTS: ReadonlySet<KruxEvent> = new Set(['test-fail', 'build-fail', 'zawał'])
74
75// Wynik roboty wysłanego kumpla zmienia tylko jego minę: jego czerwone testy
76// marszczą jego brwi, a reszta sceny zostaje, jaka była.
77export function mateMoodAfter(moods: KruxMoods, mate: KruxMate, event: KruxEvent): KruxMoods {
78 return { faces: { ...moods.faces, [mate]: GRUMPY_EVENTS.has(event) ? 'grumpy' : 'proud' }, fade: FADE_TOOLS }
79}
80
81export function moodsTick(moods: KruxMoods): KruxMoods {
82 if (moods.fade === 0) return moods
83 return moods.fade === 1 ? CALM : { ...moods, fade: moods.fade - 1 }
84}
85
86// Kumpel z typu subagenta (`krux-mod:niuch`): typ wybiera definicję z `agents/`,
87// więc mówi pewniej niż imię w opisie. Inny typ to `null`, wtedy szukamy imienia.
88export function mateOfType(type: string | undefined): KruxMate | null {
89 return MATES.find(mate => type === `krux-mod:${ROSTER[mate].agent}`) ?? null
90}
91
92// Pierwsze imię z hordy w opisie, potem w prompcie zadania.
93export function mateIn(...texts: string[]): KruxMate | null {
94 for (const text of texts) {
95 let best: { mate: KruxMate; at: number } | null = null
96 for (const mate of MATES) {
97 const at = text.search(ROSTER[mate].pattern)
98 if (at >= 0 && (best === null || at < best.at)) best = { mate, at }
99 }
100 if (best) return best.mate
101 }
102 return null
103}
104
105// Liczby przy bezokoliczniku albo w etykiecie: „2 na 2 padać”, „smrodów po
106// drodze: 1”. Tak nie trzeba odmiany, której „padło” i „po 1 smrodach” nie miały.
107// `failure` to `failures[0]` z bieżącego przebiegu, nigdy zgadywana nazwa.
108export function eventLine(event: KruxEvent, lore: KruxLore, seed: number, failure?: string): string {
109 switch (event) {
110 case 'test-fail': {
111 const line = pick([`Smród! ${lore.testFails} na ${lore.testRuns} padać.`, 'Czerwono. Robak gryźć.', 'Test padać. Kilof w dłoń!'], seed)
112 if (!failure) return line
113 const chars = Array.from(failure)
114 const name = chars.length > 24 ? `${chars.slice(0, 23).join('')}…` : failure
115 return `${line} Padły: ${name}${name.endsWith('…') ? '' : '.'}`
116 }
117 case 'test-pass':
118 return lore.testFails > 0
119 ? pick([`Zielono! Smrodów po drodze: ${lore.testFails}.`, 'Robak wynocha!', 'Stal trzymać. Hej!'], seed)
120 : pick(['Zielono za pierwszym!', 'Stal od razu dobra.', 'Czysto. Ani smrodu.'], seed)
121 case 'build-fail':
122 return pick([`Piec pluć! ${lore.buildFails} na ${lore.builds} padać.`, 'Krzywa stal. Do pieca!', 'Hartowanie padać. Grr.'], seed)
123 case 'build-pass':
124 return lore.buildFails > 0
125 ? pick(['Stal wreszcie prosta!', 'Piec przyjąć stal. Hej!', 'Hartowanie czyste.'], seed)
126 : pick(['Stal zahartowana.', 'Piec przyjąć stal.', 'Czysto w piecu.'], seed)
127 case 'commit':
128 return pick([`Pieczęć nr ${lore.commits}.`, 'Zapieczętować w skale.', 'Commit leżeć w sztolni.'], seed)
129 case 'tear':
130 return pick(['Gruz wynocha!', 'Lont syczeć. Czysto.', 'Rozbiórka skończona.'], seed)
131 case 'zawał':
132 return pick(['Zawał! Komenda paść.', 'Strop pękać. Ostrożnie.', 'Kamień spaść. Sprawdzić.'], seed)
133 }
134}
135
136// Krok wysłanego kumpla: opis narzędzia bez „Krux” na początku.
137export function mateStep(doing: KruxActivity): string {
138 const verb = doing.verb.replace(/^Krux /u, '')
139 return doing.target ? `${verb} ${doing.target}` : verb
140}
141
142function flavor(text: string, mood: KruxMood): string {
143 if (mood === 'grumpy') return `Grr. ${text}`
144 if (mood === 'proud') return `${text} Hej!`
145 return text
146}
147
148// Myśl bez celu: dumanie i pisanie mają swoje, reszta robi swoje.
149const BARE_THOUGHTS: Partial<Record<KruxActivity['scene'], readonly string[]>> = {
150 think: ['Hmm…', 'Ważyć to…', 'Myśl mielić…'],
151 write: ['Ciąć zbędne…', 'Runa po runie.', 'Krótko. Konkret.'],
152}
153
154function workThought(doing: KruxActivity | null, mood: KruxMood, seed: number): string | null {
155 if (doing === null) return null
156 const t = doing.target
157 const scene = doing.scene
158 // Dumanie i pisanie nie mają celu (`describePhase`), więc mówią zawsze swoje.
159 if (!t || scene === 'think' || scene === 'write') return flavor(pick(BARE_THOUGHTS[scene] ?? ['Hmm…', 'Dalej, dalej.', 'Robota iść.'], seed), mood)
160 const pool: Record<Exclude<KruxActivity['scene'], 'think' | 'write'>, readonly string[]> = {
161 torch: [`Gdzie ten ${t}?`, `Świecić za ${t}…`, `Trop… ${t}?`],
162 pick: [`Kuć w skale: ${t}`, `Kilof iść: ${t}`, `Skała twarda… ${t}`],
163 test: [`Próba: ${t}`, `Stal trzymać? ${t}`, `Kanarek śpiewać? ${t}`],
164 seal: [`Pieczęć na ${t}`, `Wosk kapać: ${t}`, `Wózek do góry: ${t}`],
165 build: [`Do pieca: ${t}`, `Hartować ${t}`, `Piec grzać: ${t}`],
166 tear: [`Lont pod ${t}`, `Gruz wynocha: ${t}`, `Rozbierać ${t}`],
167 horn: [`Horda, do mnie! ${t}`, `Róg grać: ${t}`, `Kumple biec: ${t}`],
168 hammer: [`Hmm, ${t}…`, `Klepać ${t}`, `${t} — zaraz stal`],
169 read: [`Czytać ${t}…`, `Runy w ${t}`, `Hmm, ${t} gadać…`],
170 plan: [`Szlak przez ${t}`, `Mapa: ${t}`, `Tu krzyżyk — ${t}`],
171 scout: [`Gdzie ${t}?`, `Coś szeleścić… ${t}`, `Wypatrywać ${t}`],
172 raven: [`Kruk lecieć: ${t}`, `Goniec po ${t}`, `Kruk wracać? ${t}`],
173 ask: [`Morra wiedzieć: ${t}?`, `Hmm… ${t}?`, `Pytać o ${t}`],
174 }
175 return flavor(pick(pool[scene], seed), mood)
176}
177
178// Spoczynek bez liczb: uderzenia stoją w podpisie obok.
179function restLine(mood: KruxMood, seed: number): string {
180 if (mood === 'grumpy') return pick(['Grr. Robak dalej siedzieć?', 'Grr. Smród jeszcze czuć.', 'Kilof czekać obok.'], seed)
181 if (mood === 'proud') return pick(['Dobra robota była. Hej!', 'Stal kuta. Hej!', 'Krux zadowolony.'], seed)
182 return pick(['Palenisko tlić.', 'Kowadło stygnąć.', 'Morra mówić, co kopać.'], seed)
183}
184
185export type BubbleInput = {
186 now: number
187 held: KruxBubble | null
188 working: boolean
189 activity: KruxActivity | null
190 moods: KruxMoods
191 seed: number
192}
193
194// Kolejność: trzymany wtręt po zdarzeniu, krok kumpla (także gdy Krux odpoczywa,
195// a agent w tle dalej kuje), myśl Kruxa, spoczynek.
196export function bubbleFor(input: BubbleInput): KruxBubble | null {
197 const { held } = input
198 if (held?.kind === 'event' && held.until > input.now) return held
199 if (held?.kind === 'step') return held
200 const mood = input.moods.faces.Krux
201 const text = input.working ? workThought(input.activity, mood, input.seed) : restLine(mood, input.seed)
202 return text === null ? null : { kind: 'thought', key: 'krux', speaker: 'Krux', text }
203}
204hooks/roster.ts 38 lines1// Horda w jednej tabeli: nowy kumpel to jeden wpis tutaj i jedno imię w `KruxMate`.
2// Typ pilnuje kompletności, a reszta modułów liczy swoje tabele z tej.
3
4import type { KruxMate } from '../types'
5
6export type MateEntry = {
7 // Fach w panelu /krux.
8 trade: string
9 // Imię w każdej odmianie, poza kodem: kto padł w odpowiedzi i kogo wysłano.
10 pattern: RegExp
11 // „zdanie o X” i „nie X: o X była ostatnia wstawka” w notce o hordzie.
12 locative: string
13 accusative: string
14 // Charakter w notce o hordzie: sam czasownik, bez rodzaju, żeby kumpel
15 // brzmiał tak samo w każdej sesji, a model nie zgadywał, kto on czy ona.
16 trait: string
17 // Słowa fachu do notki, same rzeczowniki: w symulowanych rozmowach kumpel ze
18 // słowami swojego fachu brzmiał jak on sam. Czasowniki („przepalić”) ciągnęły
19 // model w opowieść w czasie przeszłym z rodzajem („przepalił”).
20 words: string
21 // Typ subagenta z `agents/<agent>.md`: Krux woła kumpla jako `krux-mod:<agent>`.
22 agent: string
23 // Znak palety, którym kumpel podmienia skórzany fartuch.
24 apron: string
25}
26
27export const ROSTER: Record<KruxMate, MateEntry> = {
28 Niuch: { trade: 'zwiad, debug, przyczyna błędu', pattern: /(?<!\p{L})Niuch(?:a|owi|em|u)?(?!\p{L})/u, locative: 'Niuchu', accusative: 'Niucha', trait: 'węszy wszędzie i mówi półsłówkami', words: 'ślad, trop, nora', agent: 'niuch', apron: 'N' },
29 Grom: { trade: 'kuźnia: backend, API, dane', pattern: /(?<!\p{L})Grom(?:a|owi|em|ie)?(?!\p{L})/u, locative: 'Gromie', accusative: 'Groma', trait: 'mówi głośno i każdą sprawę chce wykuć od nowa', words: 'stal, palenisko, kowadło', agent: 'grom', apron: 'M' },
30 Piryt: { trade: 'ocena: review, ryzyko', pattern: /(?<!\p{L})Piry(?:t|ta|towi|tem|cie)(?!\p{L})/u, locative: 'Pirycie', accusative: 'Piryta', trait: 'zrzędzi i w każdej stali widzi pęknięcie', words: 'pęknięcie, rysa, skaza', agent: 'piryt', apron: 'P' },
31 Ochra: { trade: 'frontend, UI', pattern: /(?<!\p{L})Ochr(?:a|y|ze|ę|ą|o)(?!\p{L})/u, locative: 'Ochrze', accusative: 'Ochrę', trait: 'pilnuje równych brzegów i kolorów', words: 'brzeg, barwa, krawędź', agent: 'ochra', apron: 'O' },
32 Młot: { trade: 'testy, weryfikacja', pattern: /(?<!\p{L})Mło(?:t|ta|towi|tem|cie)(?!\p{L})/u, locative: 'Młocie', accusative: 'Młota', trait: 'liczy wszystko dwa razy i nie wierzy na słowo', words: 'dowód, rachunek, próba', agent: 'mlot', apron: 'L' },
33 Lont: { trade: 'rozbiórka: martwy kod, refaktor', pattern: /(?<!\p{L})Lon(?:t|ta|towi|tem|cie)(?!\p{L})/u, locative: 'Loncie', accusative: 'Lonta', trait: 'kocha rozbiórkę, ale lont mierzy trzy razy', words: 'lont, miara, gruz', agent: 'lont', apron: 'T' },
34}
35
36// Kolejność wpisów to kolejność w panelu i przy szukaniu imienia.
37export const MATES = Object.keys(ROSTER) as KruxMate[]
38hooks/board.ts 323 lines1// Tablica Sztolni: stan roboty zamiast statystyki. Plan z narzędzi listy zadań
2// (`TodoWrite`, `TaskCreate`, `TaskUpdate`), czasy edycji i przebiegów testów. Diff
3// i drzewo zmian rysuje silnik (`/diff`), więc tablica ich nie dubluje. Czyste funkcje.
4
5import type { SessionUsage } from 'claude-code'
6
7import type { KruxBoard, KruxGit, KruxTask, KruxTestRun, KruxThreads, KruxUsage } from '../types'
8import { gitBusy, gitShort } from './git'
9import type { HistoryMessage } from './lore'
10import { isBackgroundToolCall } from './outcome'
11import { workOf } from './voice'
12
13export const EMPTY_BOARD: KruxBoard = { tasks: [], test: null }
14
15type TaskStatus = KruxTask['status']
16
17const STATUSES: ReadonlySet<string> = new Set(['pending', 'in_progress', 'completed'])
18
19function statusOf(value: unknown): TaskStatus | null {
20 return typeof value === 'string' && STATUSES.has(value) ? (value as TaskStatus) : null
21}
22
23function text(value: unknown): string {
24 return typeof value === 'string' ? value.trim() : ''
25}
26
27// Czas startu należy do jednego statusu: powtórzenie go nie resetuje zegara.
28function taskStatus(task: KruxTask, status: TaskStatus, now?: number): KruxTask {
29 if (task.status === status) return task
30 const { startedAt: _startedAt, ...rest } = task
31 return { ...rest, status, ...(status === 'in_progress' && now !== undefined ? { startedAt: now } : {}) }
32}
33
34// Co czytamy z wyniku wywołania: tekst, który dostał model, błąd i kto wołał.
35export type BoardCall = { text: string; isError: boolean; who: KruxTestRun['who'] }
36
37// Najwyżej tyle nazw padających testów; reszta czeka w transkrypcie.
38const FAILURES_LIMIT = 5
39
40// Linia padającego testu w popularnych runnerach: bun, jest, vitest, mocha, TAP,
41// reporter `node --test` (`✖`), go (`--- FAIL:`), unittest (`FAIL:`, `ERROR: test (moduł…)`),
42// pytest (`ERROR plik::test`). Gołe `ERROR` to log albo bundler, nie test.
43const FAILURE_LINE = /^\s*(?:\(fail\)|✗|✕|✖|×|--- FAIL:|FAIL(?:ED)?(?!\p{L}):?|ERROR:(?=\s+\S+\s+\()|ERROR(?=\s+\S+::)|not ok \d+(?: -)?)\s*(.*)$/u
44
45// Czas na końcu nazwy: `[3ms]`, `(5 ms)`, `(0.00s)`, `4ms`.
46const TIMING = /\s*(?:\[\d+(?:\.\d+)?\s*m?s\]|\(\d+(?:\.\d+)?\s*m?s\)|\d+(?:\.\d+)?m?s)$/u
47
48// Nazwa bez czasu i bez reszty po tabulatorze (go: pakiet, czas). Pusta albo
49// podsumowanie w nawiasie (`FAILED (failures=1)`) i nagłówek z dwukropkiem
50// (`✖ failing tests:`) to nie test.
51function failureName(line: string): string | null {
52 const raw = FAILURE_LINE.exec(line)?.[1]
53 if (raw === undefined) return null
54 const name = raw.split('\t')[0]!.replace(TIMING, '').trim()
55 return name === '' || name.startsWith('(') || name.endsWith(':') ? null : name
56}
57
58// Ostatnie trafienie: podsumowanie stoi na końcu, a wcześniejsze liczby to pliki,
59// zestawy albo nazwy testów („returns 2 failed items”). `node --test` pisze
60// liczbę po słowie: `# pass 4` w TAP, `ℹ pass 4` w domyślnym reporterze, stąd druga grupa.
61function lastCount(output: string, pattern: RegExp): number | null {
62 let found: number | null = null
63 for (const match of output.matchAll(pattern)) found = Number(match[1] ?? match[2])
64 return found
65}
66
67// Cargo pisze podsumowanie na każdy binarny test: liczby się sumują.
68function cargoCounts(output: string): { passed: number; failed: number } | null {
69 const lines = [...output.matchAll(/test result: \w+\. (\d+) passed; (\d+) failed/gu)]
70 if (lines.length === 0) return null
71 return { passed: lines.reduce((sum, line) => sum + Number(line[1]), 0), failed: lines.reduce((sum, line) => sum + Number(line[2]), 0) }
72}
73
74// Unittest rozdziela nieudane asercje i błędy testów; oba psują przebieg.
75function unittestFailures(output: string): number | null {
76 let failed: number | null = null
77 for (const summary of output.matchAll(/^FAILED\s*\(([^)]*)\)\s*$/gmu)) {
78 const counts = [...summary[1]!.matchAll(/\b(?:failures|errors)=(\d+)\b/gu)]
79 if (counts.length > 0) failed = counts.reduce((sum, count) => sum + Number(count[1]), 0)
80 }
81 return failed
82}
83
84// Przebieg testów z wyjścia komendy: liczby, gdy runner je podał, i nazwy padających.
85// Padłe testy w wyjściu wygrywają z kodem 0: `npm test | tail` kończy się kodem `tail`.
86export function testRunOf(command: string, call: BoardCall): KruxTestRun {
87 const output = call.text
88 const failures = [...new Set(output.split(/\r?\n/u).flatMap(line => failureName(line) ?? []))]
89 const cargo = cargoCounts(output)
90 const passed = cargo?.passed ?? lastCount(output, /(?<![\p{L}\d])(\d+) pass(?:ed|ing)?(?!\p{L})|^(?:#|ℹ) pass (\d+)$/gmu)
91 const failed = cargo?.failed ?? unittestFailures(output) ?? lastCount(output, /(?<![\p{L}\d])(\d+) fail(?:ed|ing|ures?)?(?!\p{L})|^(?:#|ℹ) fail (\d+)$/gmu)
92 return {
93 command,
94 ok: !call.isError && !(failed !== null && failed > 0) && failures.length === 0,
95 passed,
96 failed,
97 failures: failures.slice(0, FAILURES_LIMIT),
98 who: call.who,
99 }
100}
101
102// Czy przebieg przeszedł, z tej samej oceny co tablica: kronika i Sztolnia
103// nie mogą się różnić co do koloru testów.
104export function testPassed(output: string, isError: boolean): boolean {
105 return testRunOf('', { text: output, isError, who: 'Krux' }).ok
106}
107
108// Tablica po jednym wywołaniu narzędzia. Plan zmienia lista zadań z wątku głównego
109// (`result` to rekord narzędzia, z niego id `TaskCreate`); testy zmienia komenda
110// testów, gdy znamy jej wynik (`call`). `now` to czas zdarzenia w ms od epoki;
111// historia bez czasu go pomija. Edycja poza dokumentacją zapisuje czas także
112// przy błędzie, bez `deny`; nieznana ścieżka nie potwierdza dokumentacji.
113export function boardAfter(board: KruxBoard, tool: string, input: Record<string, unknown>, result?: unknown, call?: BoardCall, now?: number): KruxBoard {
114 if ((result as { deny?: unknown } | undefined)?.deny !== undefined) return board
115 if (['Edit', 'Write', 'MultiEdit', 'NotebookEdit'].includes(tool)) {
116 const path = text(input.file_path) || text(input.notebook_path)
117 if (/\.(?:md|mdx|txt|rst|adoc)$/iu.test(path)) return board
118 return now === undefined ? board : { ...board, editedAt: now }
119 }
120 if (call && workOf(tool, input) === 'test') {
121 // Test w tle odpowiada od razu, bez wyniku: ostatni prawdziwy przebieg zostaje.
122 if (isBackgroundToolCall(tool, input, result)) return board
123 return { ...board, test: { ...testRunOf(text(input.command), call), ...(now === undefined ? {} : { at: now }) } }
124 }
125 // Nieudane wywołanie listy zadań nie zmienia planu.
126 if (call?.isError) return board
127 switch (tool) {
128 case 'TodoWrite': {
129 const todos = Array.isArray(input.todos) ? (input.todos as Record<string, unknown>[]) : []
130 const previous = board.tasks.filter(task => task.id === null)
131 const tasks: KruxTask[] = todos.flatMap(todo => {
132 const status = statusOf(todo.status)
133 const subject = text(todo.content)
134 return status && subject ? [{ id: null, subject, status }] : []
135 })
136 const unused: (KruxTask | undefined)[] = [...previous]
137 const matches: (KruxTask | undefined)[] = tasks.map(() => undefined)
138 // TodoWrite nie ma id: najpierw rezerwujemy niezmienione tematy i statusy,
139 // żeby wcześniejszy duplikat ze zmianą statusu nie zabrał ich zegara.
140 for (const sameStatus of [true, false]) {
141 tasks.forEach((task, index) => {
142 if (matches[index] !== undefined) return
143 const found = unused.findIndex(old => old?.subject === task.subject && (!sameStatus || old.status === task.status))
144 if (found < 0) return
145 matches[index] = unused[found]
146 unused[found] = undefined
147 })
148 }
149 return {
150 ...board,
151 tasks: tasks.map((task, index) => {
152 let old = matches[index]
153 const atPosition = unused[index]
154 // Przemianowanie w tej samej pozycji: stary temat zniknął, nowy nie
155 // należał do poprzedniej listy. Każdy poprzednik trafia tylko raz.
156 if (old === undefined && atPosition !== undefined && !tasks.some(next => next.subject === atPosition.subject) && !previous.some(before => before.subject === task.subject)) {
157 old = atPosition
158 unused[index] = undefined
159 }
160 return { ...taskStatus(old ?? { ...task, status: 'pending' }, task.status, now), subject: task.subject }
161 }),
162 }
163 }
164 case 'TaskCreate': {
165 const subject = text(input.subject)
166 if (!subject) return board
167 const task = (result as { task?: { id?: unknown } } | undefined)?.task
168 const id = typeof task?.id === 'string' ? task.id : null
169 return { ...board, tasks: [...board.tasks, { id, subject, status: 'pending' }] }
170 }
171 case 'TaskUpdate': {
172 const id = text(input.taskId)
173 if (!board.tasks.some(task => task.id === id)) return board
174 if ((result as { success?: unknown } | undefined)?.success === false) return board
175 if (input.status === 'deleted') return { ...board, tasks: board.tasks.filter(task => task.id !== id) }
176 const status = statusOf(input.status)
177 const subject = text(input.subject)
178 return {
179 ...board,
180 tasks: board.tasks.map(task => (task.id === id ? { ...(status ? taskStatus(task, status, now) : task), ...(subject ? { subject } : {}) } : task)),
181 }
182 }
183 default:
184 return board
185 }
186}
187
188// Starsze sesje nie mają czasów: bez obu nie potwierdzamy nieświeżości.
189export function testsStale(board: KruxBoard): boolean {
190 return board.test !== null && board.test.at !== undefined && board.editedAt != null && board.editedAt > board.test.at
191}
192
193// Pełne minuty pracy, od progu 15 min; bez startu albo poza pracą — nic.
194export function stuckMinutes(task: KruxTask, now: number): number | null {
195 if (task.status !== 'in_progress' || task.startedAt === undefined) return null
196 const minutes = Math.floor((now - task.startedAt) / 60_000)
197 return minutes >= 15 ? minutes : null
198}
199
200// Warunki commita, niezależnie od tego, czy panel ma zmiany do pokazania.
201// Nieznany odczyt białych znaków nie blokuje, zgodnie z kontraktem.
202export function readiness(board: KruxBoard, git: KruxGit | null): { ready: boolean; missing: string[] } {
203 if (git === null) return { ready: false, missing: ['brak repo'] }
204 const missing: string[] = []
205 if (board.test === null) missing.push('brak testów')
206 else {
207 if (!board.test.ok) missing.push('testy padłe')
208 if (testsStale(board)) missing.push('testy nieświeże')
209 }
210 if (git.whitespace === false) missing.push('białe znaki')
211 if (git.conflicted > 0) missing.push(`konflikty: ${git.conflicted}`)
212 return { ready: missing.length === 0, missing }
213}
214
215// Jedna linia toastu po przerwie: tylko części obecne na tablicy.
216export function returnNote(board: KruxBoard, threads: KruxThreads, git: KruxGit | null): string {
217 const parts: string[] = []
218 if (board.tasks.length > 0) parts.push(`Plan ${planCount(board.tasks)}`)
219 const run = board.test
220 if (run !== null) {
221 const counts = run.ok ? (run.passed === null ? '' : String(run.passed)) : testLine(run)
222 parts.push(`testy ${run.ok ? '✓' : '✗'}${counts ? ` ${counts}` : ''}${testsStale(board) ? ' ◌ nieświeże' : ''}`)
223 }
224 if (threads.items.length > 0) parts.push(`wątki ${threads.items.length}`)
225 if (git !== null) parts.push(`git ${gitBusy(git) ? '' : '✓ '}${gitShort(git)}`)
226 return parts.join(' · ').replace(/\s+/gu, ' ').trim()
227}
228
229// Plan w `limit` wierszach: najpierw wypadają najstarsze zrobione (`earlier`),
230// potem ogon (`later`).
231export function planRows(tasks: readonly KruxTask[], limit: number): { shown: KruxTask[]; earlier: number; later: number } {
232 let extra = tasks.length - limit
233 const shown = tasks.filter(task => {
234 if (extra > 0 && task.status === 'completed') {
235 extra -= 1
236 return false
237 }
238 return true
239 })
240 const cut = shown.slice(0, limit)
241 return { shown: cut, earlier: tasks.length - shown.length, later: shown.length - cut.length }
242}
243
244// Ile planu zrobione: `zrobione/wszystkie`.
245export function planCount(tasks: readonly KruxTask[]): string {
246 return `${tasks.filter(task => task.status === 'completed').length}/${tasks.length}`
247}
248
249// Odczyt `$.session.usage()` w kształcie, który da się trzymać w `$.state`.
250export function usageOf(raw: Pick<SessionUsage, 'context' | 'rateLimits' | 'cost'>): KruxUsage {
251 return {
252 percent: raw.context.percent ?? null,
253 tokens: raw.context.tokens ?? null,
254 window: raw.context.window,
255 limits: raw.rateLimits.map(limit => ({ kind: limit.kind, percentUsed: limit.percentUsed, resetsAt: limit.resetsAt ?? null })),
256 usd: raw.cost?.usd ?? null,
257 }
258}
259
260const EIGHTHS = ['', '▏', '▎', '▍', '▌', '▋', '▊', '▉']
261
262// Pasek procentu w ósemkach komórki; tło z `░`, żeby było widać, ile zostało.
263export function meter(percent: number, width: number): string {
264 const eighths = Math.round((Math.min(100, Math.max(0, percent)) / 100) * width * 8)
265 const full = Math.floor(eighths / 8)
266 const part = EIGHTHS[eighths % 8]!
267 return '█'.repeat(full) + part + '░'.repeat(Math.max(0, width - full - (part ? 1 : 0)))
268}
269
270// Tokeny po ludzku: 950, 136k, 1M.
271export function tokens(value: number): string {
272 // Próg po zaokrągleniu: 999 500 to już „1M”, nie „1000k”.
273 if (Math.round(value / 1000) >= 1000) return `${Math.round(value / 100_000) / 10}M`
274 if (value >= 1000) return `${Math.round(value / 1000)}k`
275 return String(value)
276}
277
278const LIMIT_NAMES: Readonly<Record<string, string>> = { five_hour: '5h', seven_day: '7 dni', spend_limit: 'budżet' }
279
280export function limitName(kind: string): string {
281 return LIMIT_NAMES[kind] ?? kind
282}
283
284// Ile do odnowienia okna limitu; minione albo nieznane — nic.
285export function resetIn(resetsAt: string | null, now: number): string {
286 const at = resetsAt === null ? Number.NaN : Date.parse(resetsAt)
287 if (!Number.isFinite(at) || at <= now) return ''
288 const minutes = Math.ceil((at - now) / 60_000)
289 if (minutes >= 48 * 60) return `reset za ${Math.round(minutes / (24 * 60))} dni`
290 const hours = Math.floor(minutes / 60)
291 const rest = minutes % 60
292 return `reset za ${hours > 0 ? `${hours} h ` : ''}${hours > 0 && rest === 0 ? '' : `${rest} min`}`.trimEnd()
293}
294
295// Po wznowieniu tablica wraca z historii: plan i ostatni przebieg testów. Historia
296// nie mówi, który ork wołał, więc przebieg idzie na Kruxa.
297export function replayBoard(messages: readonly HistoryMessage[]): KruxBoard {
298 let board = EMPTY_BOARD
299 for (const message of messages) {
300 for (const use of message.toolUses) {
301 if (use.text === undefined && use.result === undefined && use.isError !== true) continue
302 const call = use.text === undefined && use.isError !== true ? undefined : { text: use.text ?? '', isError: use.isError === true, who: 'Krux' as const }
303 board = boardAfter(board, use.tool, use.input, use.result, call)
304 }
305 }
306 return board
307}
308
309// Polska liczba mnoga: 1 padł, 2 padły, 5 padło (12–14 też „padło”).
310function plural(count: number, one: string, few: string, many: string): string {
311 if (count === 1) return one
312 const tens = count % 100
313 return count % 10 >= 2 && count % 10 <= 4 && (tens < 12 || tens > 14) ? few : many
314}
315
316// Liczby przebiegu w jednej linii; bez liczb w wyjściu — nic.
317export function testLine(run: KruxTestRun): string {
318 const parts: string[] = []
319 if (run.failed !== null && run.failed > 0) parts.push(`${run.failed} ${plural(run.failed, 'padł', 'padły', 'padło')}`)
320 if (run.passed !== null) parts.push(`${run.passed} ${plural(run.passed, 'przeszedł', 'przeszły', 'przeszło')}`)
321 return parts.join(' · ')
322}
323hooks/git.ts 78 lines1// Stan repo dla Sztolni: gałąź, upstream, commity do wypchnięcia i ściągnięcia,
2// pliki zmienione, nowe i w konflikcie. Komendę puszcza `register.ts`, tu tylko
3// odczyt jej wyjścia i podpisy. Niewypchnięte commity daje `rev-list`.
4
5import type { KruxGit } from '../types'
6
7// Mod puszcza git poza sandboksem (security.md): `core.fsmonitor` z `.git/config`
8// cudzego repo uruchomiłby zapisaną tam komendę, więc każdy odczyt go wyłącza.
9export const GIT_STATUS = ['git', '--no-optional-locks', '-c', 'core.fsmonitor=false', '-c', 'core.quotePath=false', 'status', '--porcelain=v2', '--branch'] as const
10export const GIT_LOG = ['git', '--no-optional-locks', '-c', 'core.fsmonitor=false', '-c', 'core.quotePath=false', 'log', '--format=%H%x09%h%x09%s', '-n', '10'] as const
11export const GIT_CHECK = ['git', '--no-optional-locks', '-c', 'core.fsmonitor=false', 'diff', '--check'] as const
12export const GIT_CHECK_CACHED = ['git', '--no-optional-locks', '-c', 'core.fsmonitor=false', 'diff', '--cached', '--check'] as const
13
14// Osiągalność zamiast pozycji w logu: merge przeplata commity lokalne i upstream.
15export const GIT_UNPUSHED = ['git', '--no-optional-locks', '-c', 'core.fsmonitor=false', '-c', 'core.quotePath=false', 'rev-list', '@{upstream}..HEAD'] as const
16
17// Plików w panelu najwyżej tyle; reszta to liczba w wierszu „zmienione”.
18const FILES_LIMIT = 20
19
20// Ścieżka i litera stanu z wiersza porcelain v2: `1 XY … ścieżka`, `2 XY … ścieżka\tstara`,
21// `u XY … ścieżka`, `? ścieżka`. Litera: drzewo robocze przed indeksem.
22function fileOf(line: string): { code: string; path: string } | null {
23 if (line.startsWith('? ')) return { code: '?', path: line.slice(2) }
24 const fields = line.split(' ')
25 const skip = line.startsWith('1 ') ? 8 : line.startsWith('2 ') ? 9 : line.startsWith('u ') ? 10 : -1
26 if (skip < 0 || fields.length <= skip) return null
27 const xy = fields[1] ?? '..'
28 const code = line.startsWith('u ') ? 'U' : xy[1] !== '.' ? xy[1]! : xy[0]!
29 return { code, path: fields.slice(skip).join(' ').split('\t')[0]! }
30}
31
32// Wyjścia `GIT_STATUS`, `GIT_LOG` i `GIT_UNPUSHED`; brak odczytu ostatniego to null.
33export function gitOf(output: string, log = '', unpushed: string | null = null): KruxGit {
34 const git: KruxGit = { branch: '', upstream: null, ahead: 0, behind: 0, changed: 0, untracked: 0, conflicted: 0, files: [], commits: [] }
35 for (const line of output.split(/\r?\n/u)) {
36 if (line.startsWith('# branch.head ')) git.branch = line.slice('# branch.head '.length)
37 else if (line.startsWith('# branch.upstream ')) git.upstream = line.slice('# branch.upstream '.length)
38 else if (line.startsWith('# branch.ab ')) {
39 const counts = /\+(\d+) -(\d+)/u.exec(line)
40 if (counts) {
41 git.ahead = Number(counts[1])
42 git.behind = Number(counts[2])
43 }
44 } else if (line.startsWith('? ')) git.untracked += 1
45 else if (line.startsWith('u ')) git.conflicted += 1
46 else if (/^[12] /u.test(line)) git.changed += 1
47 const file = fileOf(line)
48 if (file !== null && git.files.length < FILES_LIMIT) git.files.push(file)
49 }
50 // Pełne hashe porównujemy, krótkie pokazujemy. Brak odczytu nie potwierdza wypchnięcia.
51 const local = new Set((unpushed ?? '').split(/\r?\n/u).filter(Boolean))
52 git.commits = log
53 .split(/\r?\n/u)
54 .filter(line => line.includes('\t'))
55 .map(line => {
56 const [oid = '', hash = '', ...subject] = line.split('\t')
57 return { hash, subject: subject.join('\t'), pushed: git.upstream !== null && unpushed !== null && !local.has(oid) }
58 })
59 return git
60}
61
62// Czy repo ma coś do powiedzenia: commity w drodze albo pliki poza commitem.
63export function gitBusy(git: KruxGit): boolean {
64 return git.ahead > 0 || git.behind > 0 || git.changed > 0 || git.untracked > 0 || git.conflicted > 0
65}
66
67// Krótki podpis na jedną linię: `main ↑6 ↓1 ●3 +1 ✗1`, tylko niezerowe.
68export function gitShort(git: KruxGit): string {
69 const marks = [
70 git.ahead > 0 ? `↑${git.ahead}` : '',
71 git.behind > 0 ? `↓${git.behind}` : '',
72 git.changed > 0 ? `●${git.changed}` : '',
73 git.untracked > 0 ? `+${git.untracked}` : '',
74 git.conflicted > 0 ? `✗${git.conflicted}` : '',
75 ].filter(Boolean)
76 return [git.branch, ...marks].join(' ')
77}
78hooks/threads.ts 105 lines1// Otwarte wątki Sztolni: czego Krux nie domknął, co ryzykowne i co czeka na
2// decyzję Morry. Model pisze je narzędziem moda; tu czyste przejścia, raport
3// dla modelu i odtworzenie z historii.
4
5import type { KruxThread, KruxThreadKind, KruxThreads } from '../types'
6import type { HistoryMessage } from './lore'
7
8export const EMPTY_THREADS: KruxThreads = { next: 1, items: [] }
9
10export const THREAD_TOOL = 'watki'
11// Pełna nazwa, pod którą model woła narzędzie moda.
12export const THREAD_TOOL_NAME = `mcp__krux-mod__${THREAD_TOOL}`
13
14// Tablica nie rośnie bez końca: najstarsze wątki wypadają pierwsze.
15export const THREADS_LIMIT = 12
16// Opis narzędzia każe modelowi pisać do 80 znaków; ten limit to margines na zawijas, nie nowa granica.
17const TEXT_LIMIT = 100
18
19const KINDS: readonly KruxThreadKind[] = ['todo', 'risk', 'ask']
20
21export const THREAD_SPEC = {
22 name: THREAD_TOOL,
23 description:
24 "Krux's Sztolnia board: open threads the person must not lose between replies. Open one when you leave something undone, deferred, unverified or risky, or waiting on the person's decision (e.g. \"6 commits not pushed\", \"tsc not run: no types laid\"). Close it by id once resolved. Not for routine progress or plans: the task list covers those. Keep each text under 80 characters, in the language of the conversation. Returns the open threads with their ids.",
25 inputSchema: {
26 type: 'object',
27 properties: {
28 open: {
29 type: 'array',
30 items: {
31 type: 'object',
32 properties: {
33 text: { type: 'string' },
34 kind: { type: 'string', enum: [...KINDS], description: 'todo: left undone; risk: may break or mislead; ask: waits on the person. Default todo.' },
35 },
36 required: ['text'],
37 },
38 },
39 close: { type: 'array', items: { type: 'integer' }, description: 'Ids of threads now resolved.' },
40 },
41 },
42 // Model ma sięgać po wątki sam, więc musi widzieć opis co turę, nie samą nazwę
43 // za wyszukiwaniem narzędzi (v2.1.293+; starsze wersje pole pomijają).
44 isDeferred: false,
45}
46
47export const THREAD_MARK: Record<KruxThreadKind, string> = { todo: '○', risk: '⚠', ask: '?' }
48
49export function threadsAfter(threads: KruxThreads, input: Record<string, unknown>): KruxThreads {
50 const close = new Set((Array.isArray(input.close) ? input.close : []).filter((id): id is number => Number.isInteger(id)))
51 let items = threads.items.filter(item => !close.has(item.id))
52 let next = threads.next
53 for (const raw of Array.isArray(input.open) ? input.open : []) {
54 const entry = raw as Record<string, unknown>
55 const text = typeof entry?.text === 'string' ? entry.text.replace(/\s+/gu, ' ').trim().slice(0, TEXT_LIMIT) : ''
56 if (text === '' || items.some(item => item.text === text)) continue
57 const kind = KINDS.includes(entry.kind as KruxThreadKind) ? (entry.kind as KruxThreadKind) : 'todo'
58 items = [...items, { id: next, kind, text }]
59 next += 1
60 }
61 return { next, items: items.slice(-THREADS_LIMIT) }
62}
63
64// Notatka Morry korzysta z numeracji, deduplikacji i limitów narzędzia `watki`.
65export function saveThread(threads: KruxThreads, text: string): KruxThreads {
66 if (text.trim() === '') return threads
67 return threadsAfter(threads, { open: [{ kind: 'todo', text }] })
68}
69
70// Odpowiedź narzędzia: model widzi, co zostało otwarte, i ma id do zamknięcia.
71export function threadsReport(threads: KruxThreads): string {
72 if (threads.items.length === 0) return 'No open threads.'
73 return ['Open threads:', ...threads.items.map((item: KruxThread) => `#${item.id} [${item.kind}] ${item.text}`)].join('\n')
74}
75
76// Raport niesie oryginalne id i pełny stan, także gdy początek historii wypadł.
77function reportedThreads(text: unknown): KruxThread[] | null {
78 if (text === 'No open threads.') return []
79 if (typeof text !== 'string' || !text.startsWith('Open threads:\n')) return null
80 const items: KruxThread[] = []
81 for (const line of text.slice('Open threads:\n'.length).split('\n')) {
82 const match = /^#(\d+) \[(todo|risk|ask)\] (.+)$/u.exec(line)
83 if (!match || !Number.isSafeInteger(Number(match[1])) || Number(match[1]) < 1) return null
84 items.push({ id: Number(match[1]), kind: match[2] as KruxThreadKind, text: match[3]! })
85 }
86 return items.slice(-THREADS_LIMIT)
87}
88
89// Po wznowieniu raport zachowuje id; starsze wpisy bez wyniku odtwarzają przejścia.
90export function replayThreads(messages: readonly HistoryMessage[]): KruxThreads {
91 let threads = EMPTY_THREADS
92 for (const message of messages) {
93 for (const use of message.toolUses) {
94 // Samo wejście bez wyniku to wywołanie w toku, nie ukończony fakt.
95 if (use.tool !== THREAD_TOOL_NAME || use.isError === true || (use.text === undefined && use.result === undefined)) continue
96 const items = reportedThreads(use.text ?? use.result)
97 threads = items === null ? threadsAfter(threads, use.input) : {
98 next: Math.max(threads.next, ...items.map(item => item.id + 1)),
99 items,
100 }
101 }
102 }
103 return threads
104}
105hooks/report.ts 50 lines1// Raport do wklejenia: wyłącznie dane z sesji, neutralna polszczyzna.
2import type { KruxBoard, KruxGit, KruxLore, KruxThreadKind, KruxThreads } from '../types'
3
4const THREAD_LABEL: Record<KruxThreadKind, string> = {
5 todo: 'do zrobienia',
6 risk: 'ryzyko',
7 ask: 'czeka na decyzję',
8}
9
10export function dayReport(git: KruxGit | null, board: KruxBoard, threads: KruxThreads, lore: KruxLore): string {
11 const sections: string[][] = []
12 const commits = git?.commits.slice(0, 10) ?? []
13 if (commits.length > 0) {
14 sections.push(['## Commity', ...commits.map(commit => `- ${commit.hash} ${commit.subject}`)])
15 }
16
17 const run = board.test
18 if (run !== null) {
19 const lines = ['## Ostatni przebieg testów', `Komenda: ${run.command}`, `Wynik: ${run.ok ? 'zaliczony' : 'nieudany'}`, `Wykonawca: ${run.who}`]
20 if (run.passed !== null) lines.push(`Zaliczone: ${run.passed}`)
21 if (run.failed !== null) lines.push(`Nieudane: ${run.failed}`)
22 if (run.failures.length > 0) lines.push('Nieudane testy:', ...run.failures.map(name => `- ${name}`))
23 sections.push(lines)
24 }
25
26 if (board.tasks.length > 0) {
27 const done = board.tasks.filter(task => task.status === 'completed').length
28 sections.push([
29 '## Plan',
30 `Zrobione: ${done}/${board.tasks.length}`,
31 ...board.tasks.map(task => `- [${task.status === 'completed' ? 'x' : ' '}] ${task.subject}${task.status === 'in_progress' ? ' (w toku)' : ''}`),
32 ])
33 }
34
35 if (threads.items.length > 0) {
36 sections.push(['## Otwarte wątki', ...threads.items.map(item => `- #${item.id} [${THREAD_LABEL[item.kind]}] ${item.text}`)])
37 }
38
39 if (lore.testRuns > 0 || lore.testFails > 0 || lore.commits > 0 || lore.tears > 0) {
40 sections.push([
41 '## Podsumowanie sesji',
42 `Przebiegi testów: ${lore.testRuns} (nieudane: ${lore.testFails})`,
43 `Commity: ${lore.commits}`,
44 `Rozbiórki: ${lore.tears}`,
45 ])
46 }
47
48 return sections.length > 0 ? sections.map(lines => lines.join('\n')).join('\n\n') : 'Brak danych do raportu dnia.'
49}
50hooks/muster.ts 69 lines1// Apel hordy w Sztolni: kogo Krux wysłał, z czym, ile to trwa i czym ork
2// teraz robi. Lista silnika (`$.agent.list()`) nie zna czasu, więc start, ostatnie
3// narzędzie i koniec notujemy sami. Czyste funkcje.
4
5import type { KruxMate, KruxMuster, KruxRun } from '../types'
6import { describeTool } from './voice'
7
8// Najwyżej tylu orków w pamięci; starsze wpisy wypadają.
9export const MUSTER_LIMIT = 30
10// Bez listy silnika nie pokazujemy osieroconego biegu dłużej niż pół godziny.
11const UNCONFIRMED_MS = 30 * 60 * 1000
12
13export const EMPTY_MUSTER: KruxMuster = { runs: [] }
14
15export function musterSpawn(muster: KruxMuster, agentId: string, mate: KruxMate | null, description: string, now: number): KruxMuster {
16 const run: KruxRun = { agentId, mate, description, startedAt: now, endedAt: null, last: '' }
17 const runs = [...muster.runs.filter(one => one.agentId !== agentId), run]
18 return { runs: runs.length > MUSTER_LIMIT ? runs.slice(runs.length - MUSTER_LIMIT) : runs }
19}
20
21// Narzędzie orka z apelu; obcy `agentId` (pętla zagnieżdżona, fork silnika) nic nie zmienia.
22export function musterTool(muster: KruxMuster, agentId: string, tool: string, input: Record<string, unknown>): KruxMuster {
23 if (!muster.runs.some(run => run.agentId === agentId)) return muster
24 const target = describeTool(tool, input).target
25 // Nieznane narzędzie ma za cel własną nazwę (MCP: `serwer/narzędzie`): bez powtórki.
26 const last = !target ? tool : target === tool || tool.startsWith('mcp__') ? target : `${tool} ${target}`
27 return {
28 runs: muster.runs.map(run => (run.agentId === agentId ? { ...run, last } : run)),
29 }
30}
31
32export function musterDone(muster: KruxMuster, agentId: string, now: number): KruxMuster {
33 if (!muster.runs.some(run => run.agentId === agentId && run.endedAt === null)) return muster
34 return { runs: muster.runs.map(run => (run.agentId === agentId && run.endedAt === null ? { ...run, endedAt: now } : run)) }
35}
36
37// `m:ss`, od godziny `h:mm:ss`.
38export function elapsed(ms: number): string {
39 const seconds = Math.max(0, Math.floor(ms / 1000))
40 const s = String(seconds % 60).padStart(2, '0')
41 const minutes = Math.floor(seconds / 60)
42 if (minutes < 60) return `${minutes}:${s}`
43 return `${Math.floor(minutes / 60)}:${String(minutes % 60).padStart(2, '0')}:${s}`
44}
45
46export type MusterRow = { agentId: string; name: string; mate: KruxMate | null; description: string; time: string; last: string }
47
48// Orkowie w biegu, od najdawniej wysłanego; skończeni schodzą z tablicy.
49// Bez listy silnika (`null`) czas biegu ogranicza heurystyka; z listą tylko ci, których
50// silnik widzi w `running` (ork bez końca poza listą skończył poza zdarzeniami).
51export function musterRows(muster: KruxMuster, now: number, running: ReadonlySet<string> | null, limit: number): MusterRow[] {
52 return muster.runs
53 .filter(run => run.endedAt === null && (running === null ? now - run.startedAt < UNCONFIRMED_MS : running.has(run.agentId)))
54 .sort((a, b) => a.startedAt - b.startedAt)
55 .slice(0, Math.max(0, limit))
56 .map(run => ({ agentId: run.agentId, name: run.mate ?? 'ork', mate: run.mate, description: withoutName(run.description, run.mate), time: elapsed(now - run.startedAt), last: run.last }))
57}
58
59// Opis bez imienia na początku („Niuch: zwiad”): imię stoi już w wierszu.
60function withoutName(description: string, mate: KruxMate | null): string {
61 if (mate === null) return description
62 const rest = description.replace(new RegExp(`^\\s*${mate}\\s*[:—–-]\\s*`, 'u'), '')
63 return rest === '' ? description : rest
64}
65
66export function anyRunning(muster: KruxMuster): boolean {
67 return muster.runs.some(run => run.endedAt === null)
68}
69