@lamemind/loom-deck 0.13.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -51,9 +51,17 @@ senza collisioni:
51
51
  | `⏎` | azione primaria del pane | Tasks → spawna la task selezionata · Sessions → riprende (`claude --resume`) la sessione selezionata |
52
52
  | **MAIUSCOLA** | **apre un modale** | cattura tutti i tasti; `esc` annulla, non esce |
53
53
  | minuscola | azione immediata, one-shot | |
54
+ | `CTRL`+lettera | idiomi universali e toggle dentro i modali di testo | `^F` = find, come ovunque |
54
55
  | `1`…`9` | voce `launch` n-esima del progetto | da `.claude/loom-works.json` |
55
56
  | `q` `esc` | esce dal deck | in un modale `esc` annulla soltanto |
56
57
 
58
+ `CTRL` è il terzo livello, aggiunto quando è arrivata la ricerca. Serve perché
59
+ un modale con **campi di testo** mangia ogni lettera nuda: là dentro nessun
60
+ comando può essere una lettera semplice. `CTRL+X` e `x` nudo condividono lo
61
+ stesso `input` e si distinguono solo per `key.ctrl`, quindi in modalità normale
62
+ il ramo `CTRL` è valutato **per primo** e chiude l'intera classe — senza,
63
+ `CTRL+F` cadrebbe nel ramo `f` e forkerebbe una sessione invece di cercare.
64
+
57
65
  Assegnazioni correnti:
58
66
 
59
67
  | | Tasto | Cosa fa |
@@ -62,6 +70,7 @@ Assegnazioni correnti:
62
70
  | modale | `E` | edit priorità/stato della task selezionata (salva + commit) |
63
71
  | modale | `S` | sort chain |
64
72
  | modale | `F` | filtri |
73
+ | modale | `^F` | **ricerca full-text** nelle conversazioni del progetto |
65
74
  | immediata | `f` | **forka** la sessione selezionata (solo col focus sul pane Sessions) |
66
75
  | immediata | `t` | terminale @project-root (surface standard launch) |
67
76
  | immediata | `c` | sessione Claude **nuda**: nessuna task, nessun prompt iniziale |
@@ -107,6 +116,69 @@ pannello di dettaglio; la sua tab Ptyxis titola `<label> · <task> · fork`.
107
116
  > `codium`/`idea` non hanno più una lettera dedicata (erano `C`/`I` hardcoded):
108
117
  > ora sono voci `launch` del file config, raggiunte per indice `1`…`9`.
109
118
 
119
+ ### `^F` — cercare dentro le conversazioni
120
+
121
+ Il navigator trova una conversazione per **metadati** (titolo, data, turni). `^F`
122
+ la trova per **contenuto**: «l'IA me l'ha detto 150k di testo fa, ricordo mezza
123
+ parola». Claude Code non ha un find-in-conversation, ma i transcript sono tutti
124
+ su disco e il deck li legge già.
125
+
126
+ Due campi, `tab` per passare dall'uno all'altro:
127
+
128
+ - **hash** — prefisso del `sessionId` (gli 8 char della statusline bastano),
129
+ restringe a una conversazione. Vuoto = **tutte** quelle del progetto.
130
+ - **chiave** — il termine cercato. La ricerca è **eager**: si aggiorna a ogni
131
+ carattere, da 3 in su.
132
+
133
+ Sei toggle, tutti su `CTRL` perché i campi di testo occupano le lettere nude.
134
+ Lo stato si legge da `[x]`/`[ ]`, non dal solo colore:
135
+
136
+ | Tasto | Toggle | Default |
137
+ |---|---|---|
138
+ | `^R` | la chiave è una **regex** invece che testo letterale | off |
139
+ | `^A` | **case-sensitive** | off |
140
+ | `^W` | solo **parole intere** | off |
141
+ | `^B` | cerca nel testo **dell'IA** | **on** |
142
+ | `^T` | cerca nei **tool** (`tool_use` / `tool_result`) | off |
143
+ | `^U` | cerca nei prompt **umani** | off |
144
+
145
+ Non esiste un toggle *thinking*: quei blocchi sono persistiti **senza testo**
146
+ (il transcript porta la sola firma crittografica), quindi sarebbe una casella
147
+ che non può mai produrre un risultato.
148
+
149
+ Con l'hash vuoto la lista è **raggruppata per conversazione**; `⏎` è contestuale
150
+ alla riga selezionata — su una riga-conversazione **riprende** la sessione
151
+ (come dal pane Sessions), su una riga-occorrenza apre il **reader**. La selezione
152
+ parte dalla prima *occorrenza*, non dalla riga di gruppo: quella è un segnaposto
153
+ di navigazione, raggiungibile con le frecce ma non una destinazione.
154
+
155
+ L'estratto attorno al match **si allarga col terminale**: a 190 colonne sono
156
+ ~170 caratteri di contesto, non i 50 di un valore fisso — ed è il contesto la
157
+ ragione per cui si legge la riga invece di aprire il reader.
158
+
159
+ Sotto la lista, un **pannello di anteprima** mostra il contesto attorno
160
+ all'occorrenza selezionata e si aggiorna navigando con le frecce. Prende solo le
161
+ righe che la lista non usa: con pochi risultati riempie il terminale, con molti
162
+ sparisce e la lista se le riprende — quando c'è tanto da scorrere la priorità è
163
+ vedere più occorrenze, il contesto è il premio per una ricerca già stretta.
164
+
165
+ Il reader mostra il messaggio intero, aperto già **posizionato sull'occorrenza**
166
+ col match evidenziato: `↑↓` riga, `PgUp`/`PgDn` pagina, `g`/`G` estremi, `esc`
167
+ torna alla lista senza perdere query, toggle e selezione. (Gli estremi stanno su
168
+ lettera e non su `Home`/`End` perché Ink non espone quei due tasti: arrivano
169
+ indistinguibili da qualunque tasto ignoto.)
170
+
171
+ I toggle e la query sono **volatili**: sopravvivono alla chiusura del modale,
172
+ non al riavvio del deck — comporre una ricerca non tocca il disco.
173
+
174
+ **Come fa a essere istantanea.** I corpi dei messaggi restano in RAM dentro la
175
+ cache mtime-keyed che il deck usa già per la lista sessioni: quei file venivano
176
+ comunque deserializzati per turni e titoli, e i corpi buttati. Trattenerli non
177
+ aggiunge I/O, aggiunge memoria — e ne aggiunge poca, perché un JSONL è per l'85%
178
+ overhead (misurato su un progetto reale: 57 MB su disco = 9,8 MB di testo
179
+ cercabile). Cercarci dentro costa 1-9 ms; un prefiltro `grep` sugli stessi file
180
+ ne costerebbe 26, perché rileggerebbe il volume pieno a ogni battuta.
181
+
110
182
  ## Vista: filtri e ordinamenti
111
183
 
112
184
  La lista è una **vista** sulla `tasks.md`: si filtra e si ordina senza toccare il file.
package/dist/cli.js CHANGED
@@ -9,10 +9,11 @@ import { fileURLToPath } from 'node:url';
9
9
  import { dirname, join } from 'node:path';
10
10
  import { resolveTasksPath, resolveTasksDir, loadTasks, loadTaskDetail, } from './tasks.js';
11
11
  import { discoverProjectSessions } from './sessions.js';
12
+ import { buildRows, firstRowKey, moveRowSelection, rowIndexOfKey, searchSessions, selectedRow, DEFAULT_OPTIONS, MIN_QUERY, } from './search.js';
12
13
  import { appendPin, appendSessionRecord, appendTaskBinding, loadSessionIndex, } from './task-index.js';
13
14
  import { assembleSessionList, firstSelectableId, moveSelection, rowIndexOf, selectedSession, } from './session-list.js';
14
15
  import { launchLegend, loadIdentity, loadLaunch } from './config.js';
15
- import { layoutBudget, normalizeEmoji, windowRange, wrapLines, } from './viewport.js';
16
+ import { isCompact, layoutBudget, normalizeEmoji, readerCapacity, searchListCapacity, searchPreviewCapacity, windowRange, wrapLines, wrapWithOffsets, } from './viewport.js';
16
17
  import { applyView, cycleSort, describeSort, priName, progName, toggleHidden, PRI_ENTRIES, PROG_ENTRIES, } from './view.js';
17
18
  import { initialDetail, progressText, writeTaskEdit, PRI_GLYPH, PRI_LABEL, PROG_GLYPH, } from './task-edit.js';
18
19
  import { loadView, saveView, viewFilePath } from './view-store.js';
@@ -30,6 +31,25 @@ const SPOT = Symbol('spot');
30
31
  // Modale sort a grammatica libera: un tasto per chiave, pressioni successive
31
32
  // ciclano asc → desc → fuori dalla chain.
32
33
  const SORT_TASTI = { p: 'pri', s: 'prog', i: 'id' };
34
+ // T52 — toggle del modale ricerca, tutti su CTRL (D2).
35
+ //
36
+ // I due campi di testo mangiano ogni lettera nuda, quindi un toggle non può
37
+ // essere una lettera semplice: resterebbero i caratteri della query. CTRL è
38
+ // l'unico livello che convive con la digitazione senza modi né navigazione.
39
+ //
40
+ // Le mnemoniche ovvie sono precluse dall'ASCII, non da una scelta di design:
41
+ // `^I` È il Tab (0x09) e `^H` È il Backspace (0x08) — stesso byte, nessuna
42
+ // distinzione possibile a valle. Quindi niente I=IA e niente H=human. Bruciati
43
+ // per lo stesso motivo `^M` (Enter), `^J` (LF), `^[` (Esc). Tutto il resto passa
44
+ // pulito, `^S`/`^Q` inclusi: il raw mode di Ink disattiva il flow-control XON/XOFF
45
+ // che altrimenti se li mangerebbe il terminale.
46
+ const SEARCH_TOGGLE_KEYS = {
47
+ r: 'regex',
48
+ a: 'caseSensitive',
49
+ w: 'wholeWord',
50
+ };
51
+ const SEARCH_KIND_KEYS = { b: 'ai', t: 'tool', u: 'human' };
52
+ const KIND_LABEL = { ai: 'IA', tool: 'tools', human: 'human' };
33
53
  // T41 — ordine dei valori nel modale edit. Deliberatamente DIVERSO da
34
54
  // PRI_ENTRIES/PROG_ENTRIES (che seguono il rango di sort): qui si sceglie un
35
55
  // valore, non si ordina, quindi vince l'ordine del CICLO DI VITA — da fare →
@@ -414,6 +434,22 @@ function Deck({ cwd, tasksPath, tasksDir }) {
414
434
  // T41 — bozza dell'edit (null fuori dal modale) e riga attiva della griglia.
415
435
  const [edit, setEdit] = useState(null);
416
436
  const [editRow, setEditRow] = useState(0);
437
+ // T52 — stato del modale ricerca. VOLATILE per decisione (D4): vive in
438
+ // memoria, quindi riaprendo il modale ritrovi query e toggle come li avevi
439
+ // lasciati, ma un riavvio del deck riporta ai default. Niente schema nuovo su
440
+ // `deck-view.json` e nessuna scrittura implicita su disco — che
441
+ // contraddirebbe la regola T39 «il disco si tocca solo su `w`», qui non
442
+ // trasportabile perché dentro il modale `w` è un carattere digitabile.
443
+ const [searchHash, setSearchHash] = useState('');
444
+ const [searchQuery, setSearchQuery] = useState('');
445
+ const [searchField, setSearchField] = useState('query');
446
+ const [searchOpts, setSearchOpts] = useState(DEFAULT_OPTIONS);
447
+ const [searchSelKey, setSearchSelKey] = useState(null);
448
+ // Occorrenza aperta nel reader; null = reader chiuso. Tenerla separata dalla
449
+ // selezione della lista è ciò che permette a `esc` di tornare indietro
450
+ // trovando la lista esattamente com'era.
451
+ const [readerRow, setReaderRow] = useState(null);
452
+ const [readerTop, setReaderTop] = useState(0);
417
453
  // Dimensioni vive del terminale: sono l'input del budget d'altezza sotto.
418
454
  const { rows, columns } = useTerminalSize();
419
455
  // Voci launch del progetto (T32): lette una volta, raggiunte per indice 1..9.
@@ -455,6 +491,32 @@ function Deck({ cwd, tasksPath, tasksDir }) {
455
491
  const assembled = useMemo(() => assembleSessionList(childSessions, sessions, pinned, MAX_SESSIONS), [childSessions, sessions, pinned]);
456
492
  const sessionRows = assembled.rows;
457
493
  const selSessionObj = selectedSession(sessionRows, selSessionId);
494
+ // T52 — ricerca EAGER: rigira a ogni carattere digitato, non su ⏎. È
495
+ // sostenibile perché i corpi sono già in RAM dentro la cache mtime-keyed
496
+ // dell'adapter (D5): misurato su questo progetto, 0,8 ms sui soli corpi IA e
497
+ // ≤9 ms su tutti i tipi — sotto il tempo fra due battute. Il memo evita di
498
+ // rifarla sui re-render che non toccano né query né opzioni (il poll delle
499
+ // sessioni ogni 1,5s è già filtrato dalla signature in `useSessions`).
500
+ const searchResult = useMemo(() => searchSessions(sessions, searchHash, searchQuery, searchOpts, searchExcerptWidth(columns)), [sessions, searchHash, searchQuery, searchOpts, columns]);
501
+ // Con l'hash valorizzato la conversazione è una sola e già nominata nel campo:
502
+ // la riga-sessione ripeterebbe un dato costante rubando una riga per gruppo.
503
+ const searchFlat = searchHash.trim().length > 0;
504
+ const searchRows = useMemo(() => buildRows(searchResult, searchFlat), [searchResult, searchFlat]);
505
+ // T52 — riga selezionata e, se è un'occorrenza, il suo corpo wrappato per
506
+ // l'anteprima sotto la lista. Memoizzato per (testo, larghezza): navigando
507
+ // con le frecce si ri-wrappa solo quando cambia davvero l'occorrenza.
508
+ const searchSelRow = useMemo(() => selectedRow(searchRows, searchSelKey), [searchRows, searchSelKey]);
509
+ const searchPreviewWidth = Math.max(20, (columns || 80) - 8);
510
+ const searchPreviewBody = useMemo(() => searchSelRow?.kind === 'hit'
511
+ ? wrapWithOffsets(searchSelRow.hit.text, searchPreviewWidth)
512
+ : [], [searchSelRow, searchPreviewWidth]);
513
+ // T52 — corpo del messaggio aperto nel reader, wrappato UNA volta per (testo,
514
+ // larghezza). Senza memo ogni pressione di freccia rifarebbe l'a-capo di un
515
+ // messaggio che nella coda lunga arriva a 150k char.
516
+ const readerWidth = Math.max(20, (columns || 80) - 6);
517
+ const readerLines = useMemo(() => (readerRow?.kind === 'hit' ? wrapWithOffsets(readerRow.hit.text, readerWidth) : []), [readerRow, readerWidth]);
518
+ const readerCap = readerCapacity(rows);
519
+ const readerMaxTop = Math.max(0, readerLines.length - readerCap);
458
520
  // T39 — selezione stabile sotto trasformazione. Se la task selezionata esce
459
521
  // dalla vista (filtro appena attivato, oppure sparita da tasks.md), si cade
460
522
  // sulla prima visibile — fallback deterministico, mai una posizione a caso.
@@ -472,6 +534,15 @@ function Deck({ cwd, tasksPath, tasksDir }) {
472
534
  setSelSessionId(firstSelectableId(sessionRows));
473
535
  }
474
536
  }, [sessionRows, selSessionId]);
537
+ // T52 — stessa invariante sulla lista occorrenze, dove è ancora più stretta:
538
+ // la lista si RICOSTRUISCE a ogni carattere digitato, quindi la chiave
539
+ // selezionata sparisce continuamente. Persa → prima riga, mai una posizione
540
+ // ereditata (che qui punterebbe a un'altra conversazione, non a un'altra riga).
541
+ useEffect(() => {
542
+ if (rowIndexOfKey(searchRows, searchSelKey) < 0) {
543
+ setSearchSelKey(firstRowKey(searchRows));
544
+ }
545
+ }, [searchRows, searchSelKey]);
475
546
  // T30: submit dell'input box. Il taskId nasce DOPO create-task (lo assegna la
476
547
  // skill scrivendo tasks.md) → non è noto allo spawn. Il sessionId invece è
477
548
  // pinnato qui: snapshot degli id PRIMA, poi al completamento re-leggo tasks.md
@@ -571,7 +642,175 @@ function Deck({ cwd, tasksPath, tasksDir }) {
571
642
  const next = Math.max(0, Math.min(viewTasks.length, selIndex + delta));
572
643
  setSelId(next === 0 ? null : viewTasks[next - 1]?.id ?? null);
573
644
  }
645
+ // T52 — `⏎` contestuale al TIPO di riga: la lista ne mescola due e l'azione
646
+ // giusta dipende da quale è selezionata. Riga sessione → resume, identico al
647
+ // `⏎` della lista sessioni (stessa funzione, T49). Riga occorrenza → reader.
648
+ function submitSearchRow() {
649
+ const row = selectedRow(searchRows, searchSelKey);
650
+ if (!row) {
651
+ setNote(searchResult.error ? '⚠ regex non valida' : 'nessuna occorrenza selezionata');
652
+ return;
653
+ }
654
+ if (row.kind === 'session') {
655
+ const bound = bindings.get(row.session.sessionId) ?? null;
656
+ const child = spawnDeckResume(bound, cwd, row.session.sessionId);
657
+ child.on('error', () => setNote(`⚠ resume fallito (${DECK_RUN})`));
658
+ setNote(`⏎ resume ${row.session.sessionId.slice(0, 8)} → tab CC${bound ? ` (${bound})` : ' (spot)'}`);
659
+ return;
660
+ }
661
+ // D8 — il reader si apre POSIZIONATO sull'occorrenza, non in cima. Il 94%
662
+ // dei messaggi entra in una schermata e la differenza non si vede; è sul 6%
663
+ // lungo (p99 ≈ 88 righe, max ≈ 1547) che aprire in cima costringerebbe a
664
+ // rifare a mano la ricerca appena fatta — cioè proprio il lavoro che questa
665
+ // feature esiste per evitare.
666
+ const lines = wrapWithOffsets(row.hit.text, readerWidth);
667
+ const cap = readerCapacity(rows);
668
+ const matchLine = lines.findIndex((l) => l.end > row.hit.matchStart);
669
+ const maxTop = Math.max(0, lines.length - cap);
670
+ setReaderRow(row);
671
+ setReaderTop(Math.max(0, Math.min(maxTop, Math.max(0, matchLine) - Math.floor(cap / 2))));
672
+ setNote('');
673
+ setMode('reader');
674
+ }
675
+ function scrollReader(delta) {
676
+ setReaderTop((t) => Math.max(0, Math.min(readerMaxTop, t + delta)));
677
+ }
678
+ // T52 — toggle di tipo messaggio. Spegnerli tutti è uno stato lecito (lista
679
+ // vuota, nessun errore): è l'utente che ha chiuso ogni canale, non un guasto.
680
+ function toggleKind(kind) {
681
+ setSearchOpts((o) => ({ ...o, kinds: { ...o.kinds, [kind]: !o.kinds[kind] } }));
682
+ }
683
+ function editSearchField(fn) {
684
+ // La nota racconta l'esito di un'AZIONE su una lista che, con l'eager, si
685
+ // ricostruisce a ogni carattere: appena la query cambia è già scaduta.
686
+ // Lasciarla lì la fa leggere come se descrivesse lo stato corrente — nello
687
+ // specifico «nessuna occorrenza selezionata» sopra una lista con una riga
688
+ // visibilmente selezionata, cioè una contraddizione a schermo.
689
+ setNote('');
690
+ if (searchField === 'hash')
691
+ setSearchHash(fn);
692
+ else
693
+ setSearchQuery(fn);
694
+ }
695
+ // `useInput` consegna il CHUNK letto da stdin, non un tasto: un incollaggio —
696
+ // o una raffica di tasti piu' veloce di una read — arriva come stringa unica,
697
+ // byte di controllo compresi. Due conseguenze, entrambe verificate su pty:
698
+ //
699
+ // 1. I byte di controllo finiscono DENTRO il campo se non li si filtra. Non
700
+ // si vedono, ma Ink li conta nella larghezza della riga e nessun match li
701
+ // soddisfa -> la ricerca smette di trovare senza dire perche'. Le newline
702
+ // diventano spazio invece di sparire: incollare due righe deve separare
703
+ // le parole, non fonderle.
704
+ //
705
+ // 2. Un TAB digitato subito dopo una lettera (~60 ms, cioe' battitura veloce
706
+ // normale) arriva incollato ad essa: `key.tab` resta falso e il ramo del
707
+ // cambio campo non scatta mai. Trattarlo come testo lo renderebbe uno
708
+ // spazio, per giunta nel campo sbagliato — e' cosi' che `70897aff` + Tab
709
+ // + `congelat` finiva tutto quanto nel campo hash.
710
+ //
711
+ // Si spezza quindi il chunk SUL TAB applicando il cambio campo in mezzo: il
712
+ // risultato e' identico alla battitura lenta. Stessa lezione del modale sort
713
+ // (T39), che cicla sui caratteri del chunk invece di leggerlo intero.
714
+ function typeIntoField(chunk) {
715
+ setNote('');
716
+ const clean = (s) => s.replace(/[\r\n]/g, ' ').replace(/[\u0000-\u001f\u007f]/g, '');
717
+ const parts = chunk.split('\t');
718
+ let field = searchField;
719
+ const add = { hash: '', query: '' };
720
+ for (let k = 0; k < parts.length; k++) {
721
+ if (k > 0)
722
+ field = field === 'hash' ? 'query' : 'hash';
723
+ add[field] += clean(parts[k]);
724
+ }
725
+ if (add.hash)
726
+ setSearchHash((v) => v + add.hash);
727
+ if (add.query)
728
+ setSearchQuery((v) => v + add.query);
729
+ setSearchField(field);
730
+ }
731
+ const searchCap = searchListCapacity(rows, Boolean(note));
574
732
  useInput((input, key) => {
733
+ // T52 — MODALE DENTRO IL MODALE. `useInput` in Ink è globale e non ha
734
+ // focus-trap: non esiste un meccanismo che confini l'input a un componente.
735
+ // La cattura È l'ordine dei rami — quindi il reader va PRIMA della ricerca,
736
+ // e mentre è aperto il modale ricerca resta montato sotto con la sua
737
+ // selezione intatta, pronto a riprendere il controllo su `esc`.
738
+ if (mode === 'reader') {
739
+ if (key.escape) {
740
+ setMode('search');
741
+ setReaderRow(null);
742
+ }
743
+ else if (key.upArrow) {
744
+ scrollReader(-1);
745
+ }
746
+ else if (key.downArrow) {
747
+ scrollReader(1);
748
+ }
749
+ else if (key.pageUp) {
750
+ scrollReader(-readerCap);
751
+ }
752
+ else if (key.pageDown) {
753
+ scrollReader(readerCap);
754
+ }
755
+ else if (input === 'g') {
756
+ // Estremi su lettera e non su Home/End: Ink RICONOSCE quelle due (le
757
+ // mappa a 'home'/'end' nel parser) ma NON le espone — `nonAlphanumericKeys`
758
+ // azzera l'input e nessun flag le rappresenta, quindi arrivano
759
+ // indistinguibili da qualunque tasto ignoto. Verificato su pty reale.
760
+ // Nel reader non c'è input di testo, quindi le lettere sono libere.
761
+ setReaderTop(0);
762
+ }
763
+ else if (input === 'G') {
764
+ setReaderTop(readerMaxTop);
765
+ }
766
+ return;
767
+ }
768
+ // T52 — modale ricerca. I due campi di testo mangiano ogni lettera nuda:
769
+ // ogni comando che deve restare vivo MENTRE si digita passa da CTRL, dai
770
+ // tasti freccia o da Tab. `esc` chiude il modale, non il deck.
771
+ if (mode === 'search') {
772
+ if (key.escape) {
773
+ setMode('normal');
774
+ setNote('');
775
+ return;
776
+ }
777
+ if (key.ctrl) {
778
+ const flag = SEARCH_TOGGLE_KEYS[input];
779
+ if (flag) {
780
+ setSearchOpts((o) => ({ ...o, [flag]: !o[flag] }));
781
+ return;
782
+ }
783
+ const kind = SEARCH_KIND_KEYS[input];
784
+ if (kind)
785
+ toggleKind(kind);
786
+ return; // ogni altra combo ctrl (^F incluso: siamo già dentro) = no-op
787
+ }
788
+ if (key.tab) {
789
+ setSearchField((f) => (f === 'hash' ? 'query' : 'hash'));
790
+ }
791
+ else if (key.upArrow) {
792
+ setSearchSelKey((k) => moveRowSelection(searchRows, k, -1));
793
+ }
794
+ else if (key.downArrow) {
795
+ setSearchSelKey((k) => moveRowSelection(searchRows, k, 1));
796
+ }
797
+ else if (key.pageUp) {
798
+ setSearchSelKey((k) => moveRowSelection(searchRows, k, -Math.max(1, searchCap)));
799
+ }
800
+ else if (key.pageDown) {
801
+ setSearchSelKey((k) => moveRowSelection(searchRows, k, Math.max(1, searchCap)));
802
+ }
803
+ else if (key.return) {
804
+ submitSearchRow();
805
+ }
806
+ else if (key.backspace || key.delete) {
807
+ editSearchField((s) => s.slice(0, -1));
808
+ }
809
+ else if (input && !key.meta) {
810
+ typeIntoField(input);
811
+ }
812
+ return;
813
+ }
575
814
  // T30: in modalità create l'handler cattura il testo e corto-circuita la
576
815
  // navigazione normale (incl. q/esc → quit: qui esc annulla, non esce).
577
816
  if (mode === 'create') {
@@ -688,6 +927,21 @@ function Deck({ cwd, tasksPath, tasksDir }) {
688
927
  }
689
928
  return;
690
929
  }
930
+ // T52/D1 — il ramo CTRL sta PRIMA di quelli su lettera nuda e li chiude
931
+ // tutti. `CTRL+F` e `f` nudo arrivano con lo STESSO `input` ('f'),
932
+ // distinguibili solo da `key.ctrl`: senza questa precedenza `CTRL+F`
933
+ // cadrebbe nel ramo fork e spawnerebbe una sessione invece di aprire la
934
+ // ricerca. Non è un caso isolato della `f` — `^Q` finirebbe nel quit, `^T`
935
+ // aprirebbe un terminale, `^C` … ogni lettera legata a un'azione ha la sua
936
+ // combo omonima. Chiudere qui l'intera classe è più solido che ricordarsi
937
+ // un `!key.ctrl` su ognuno dei rami, oggi e a ogni tasto aggiunto domani.
938
+ if (key.ctrl) {
939
+ if (input === 'f') {
940
+ setNote('');
941
+ setMode('search');
942
+ }
943
+ return;
944
+ }
691
945
  if (key.leftArrow || key.rightArrow || key.tab) {
692
946
  setFocus((f) => (f === 'tasks' ? 'sessions' : 'tasks'));
693
947
  }
@@ -856,6 +1110,50 @@ function Deck({ cwd, tasksPath, tasksDir }) {
856
1110
  // Larghezza dal medesimo hook che dà l'altezza: dopo un resize la legenda si
857
1111
  // ricalcola con lo stesso re-render che ridimensiona i pane.
858
1112
  const legend = launchLegend(launch, columns);
1113
+ // ── T52 · schermate sostitutive ─────────────────────────────────────────
1114
+ // Ricerca e reader sono gli unici modali che NON stanno in flusso sopra i
1115
+ // pane: una lista di occorrenze non entra in un box da 4 righe. Prendono
1116
+ // l'intero frame, quindi escono di qui — il budget dei due pane sotto non
1117
+ // serve nemmeno calcolarlo, e la loro altezza la distribuiscono
1118
+ // `searchListCapacity` / `readerCapacity`.
1119
+ if (mode === 'search' || mode === 'reader') {
1120
+ const hit = mode === 'reader' && readerRow?.kind === 'hit' ? readerRow.hit : null;
1121
+ // Terminale sotto la cornice: riga singola invece del box, per lo stesso
1122
+ // motivo del `budget.compact` del deck — un frame più alto di `rows` fa
1123
+ // pulire lo schermo a Ink a ogni redraw, e il poll lo versa nello scrollback.
1124
+ if (isCompact(hit ? readerCap : searchCap)) {
1125
+ return (_jsxs(Text, { wrap: "truncate-end", children: [_jsx(Text, { bold: true, color: "cyan", children: "loom-deck" }), _jsxs(Text, { dimColor: true, children: [' ', "\u00B7 ", hit ? 'reader' : 'ricerca', " \u00B7 terminale ", rows, "\u00D7", columns, ": troppo basso, allarga \u00B7", ' ', "esc ", hit ? 'torna' : 'chiude'] })] }));
1126
+ }
1127
+ if (hit) {
1128
+ // Niente `windowRange`: quella centra la finestra su una SELEZIONE, qui
1129
+ // la posizione è lo scroll che l'utente muove a mano. Il clamp serve
1130
+ // comunque — un resize può accorciare il testo sotto uno scroll già dato.
1131
+ const start = Math.min(readerTop, readerMaxTop);
1132
+ return (_jsx(ReaderScreen, { hit: hit, lines: readerLines.slice(start, start + readerCap), top: start, total: readerLines.length, capacity: readerCap, bound: bindings.get(hit.sessionId) ?? null }));
1133
+ }
1134
+ const selIdx = rowIndexOfKey(searchRows, searchSelKey);
1135
+ const win = windowRange(searchRows.length, selIdx, searchCap);
1136
+ // Anteprima dell'occorrenza selezionata: prende le righe che la lista non
1137
+ // usa. Con molti risultati `spare` è 0 e il pannello non esiste — la lista
1138
+ // se le riprende tutte, che è la priorità giusta quando c'è molto da
1139
+ // scorrere. La finestra si CENTRA sul match (`windowRange`), così il
1140
+ // contesto arriva da entrambi i lati.
1141
+ const spare = searchPreviewCapacity(searchCap, win.end - win.start);
1142
+ let preview = null;
1143
+ if (spare >= 1 && searchSelRow?.kind === 'hit') {
1144
+ const h = searchSelRow.hit;
1145
+ const mline = Math.max(0, searchPreviewBody.findIndex((l) => l.end > h.matchStart));
1146
+ const pw = windowRange(searchPreviewBody.length, mline, spare);
1147
+ preview = {
1148
+ hit: h,
1149
+ lines: searchPreviewBody.slice(pw.start, pw.end),
1150
+ from: pw.start,
1151
+ total: searchPreviewBody.length,
1152
+ ts: sessions.find((s) => s.sessionId === h.sessionId)?.ts ?? 0,
1153
+ };
1154
+ }
1155
+ return (_jsx(SearchScreen, { preview: preview, hash: searchHash, query: searchQuery, field: searchField, opts: searchOpts, result: searchResult, rows: searchRows.slice(win.start, win.end), selectedKey: searchSelKey, selectedKind: selectedRow(searchRows, searchSelKey)?.kind ?? null, above: win.start, below: searchRows.length - win.end, capacity: searchCap, bindings: bindings, pinned: pinned, projectCore: identity ? `${identity.owner} ${identity.name}` : null, columns: columns, note: note }));
1156
+ }
859
1157
  // ── Budget d'altezza ────────────────────────────────────────────────────
860
1158
  // Il frame deve restare sotto `rows`, sempre: oltre quella soglia Ink smette
861
1159
  // di aggiornare per differenza e pulisce lo schermo a ogni redraw, che su
@@ -894,7 +1192,7 @@ function Deck({ cwd, tasksPath, tasksDir }) {
894
1192
  if (budget.compact) {
895
1193
  return (_jsxs(Text, { wrap: "truncate-end", children: [_jsx(Text, { bold: true, color: "cyan", children: "loom-deck" }), _jsxs(Text, { dimColor: true, children: [' ', "\u00B7 ", viewTasks.length, " task \u00B7 sel ", selectedTaskId ?? 'spot', " \u00B7 terminale ", rows, "\u00D7", columns, ": troppo basso, allarga"] })] }));
896
1194
  }
897
- return (_jsxs(Box, { flexDirection: "column", borderStyle: "round", borderColor: "cyan", paddingX: 1, children: [_jsx(Text, { bold: true, color: "cyan", children: "loom-deck" }), mode === 'create' ? (_jsxs(Text, { dimColor: true, wrap: "truncate-end", children: ["nuova task \u00B7 ", _jsx(Text, { color: "yellow", children: "\u23CE" }), " crea \u00B7 ", _jsx(Text, { color: "yellow", children: "esc" }), " annulla"] })) : mode === 'sort' ? (_jsxs(Text, { dimColor: true, wrap: "truncate-end", children: ["sort \u00B7 ", _jsx(Text, { color: "yellow", children: "p" }), " pri ", _jsx(Text, { color: "yellow", children: "s" }), " stato", ' ', _jsx(Text, { color: "yellow", children: "i" }), " id (asc\u2192desc\u2192off) \u00B7 ", _jsx(Text, { color: "yellow", children: "\u23CE" }), " ok \u00B7", ' ', _jsx(Text, { color: "yellow", children: "esc" }), " annulla"] })) : mode === 'filter' ? (_jsxs(Text, { dimColor: true, wrap: "truncate-end", children: ["filtri \u00B7 ", _jsx(Text, { color: "yellow", children: "\u2191\u2193\u2190\u2192" }), " naviga \u00B7 ", _jsx(Text, { color: "yellow", children: "spazio" }), ' ', "mostra/nascondi \u00B7 ", _jsx(Text, { color: "yellow", children: "\u23CE" }), " ok \u00B7 ", _jsx(Text, { color: "yellow", children: "esc" }), " annulla"] })) : mode === 'edit' ? (_jsxs(Text, { dimColor: true, wrap: "truncate-end", children: ["edit \u00B7 ", _jsx(Text, { color: "yellow", children: "\u2191\u2193" }), " campo \u00B7 ", _jsx(Text, { color: "yellow", children: "\u2190\u2192" }), " valore \u00B7", ' ', _jsx(Text, { color: "yellow", children: "\u23CE" }), " salva+commit \u00B7 ", _jsx(Text, { color: "yellow", children: "esc" }), " annulla"] })) : (_jsxs(Text, { dimColor: true, wrap: "truncate-end", children: ["\u2191\u2193 naviga \u00B7 \u2190\u2192 pane \u00B7 \u23CE ", canSpawn ? 'spawn' : canResume ? 'resume' : '—', canResume ? ' · f fork' : '', canPin ? ' · p pin' : '', " \u00B7 C nuova \u00B7 E edit \u00B7 S sort \u00B7 F filtri \u00B7 w salva \u00B7 t term \u00B7 c claude \u00B7 q esci \u00B7 focus:", ' ', _jsx(Text, { color: "cyan", children: focus })] })), mode === 'normal' && launch.length > 0 ? (_jsxs(Text, { dimColor: true, wrap: "truncate-end", children: ["launch ", legend.shown, legend.overflow > 0 ? (_jsxs(Text, { color: "yellow", children: [" \u00B7 +", legend.overflow, " fuori riga"] })) : null, legend.unreachable > 0 ? (_jsxs(Text, { color: "yellow", children: [" \u00B7 ", legend.unreachable, " oltre la 9\u00AA (non raggiungibili)"] })) : null] })) : null, mode === 'create' ? (_jsxs(Box, { borderStyle: "round", borderColor: "yellow", paddingX: 1, marginTop: 1, children: [_jsx(Text, { color: "yellow", children: "C \u203A " }), _jsx(Text, { children: draft }), _jsx(Text, { inverse: true, children: " " })] })) : null, mode === 'sort' ? _jsx(SortModal, { sort: view.sort }) : null, mode === 'filter' ? _jsx(FilterModal, { view: view, cursor: filterCursor }) : null, mode === 'edit' && edit && selTask ? (_jsx(EditModal, { id: selTask.id, draft: edit, row: editRow })) : null, _jsxs(Box, { flexDirection: "row", marginTop: 1, children: [_jsx(TasksPane, { tasks: windowTasks, filtered: viewTasks.length, total: tasks.length, hidden: hiddenTasks, view: view, selected: selIndex, spotCount: spotCount, childCount: childCount, focused: focus === 'tasks', loadError: loadError, detail: detail, windowStart: taskWin.start, above: taskWin.start, below: viewTasks.length - taskWin.end, detailLines: budget.detailLines, columns: columns }), _jsx(SessionsPane, { parentLabel: parentLabel, isSpot: isSpot, rows: windowRows, total: assembled.pinnedCount + assembled.contextTotal, pinnedCount: assembled.pinnedCount, hidden: assembled.contextHidden, selectedId: selSessionId ?? undefined, focused: focus === 'sessions', above: sessionWin.start, below: sessionRows.length - sessionWin.end, detail: budget.sessionDetail ? selSessionObj : null, firstLines: budget.sessionFirstLines, lastLines: budget.sessionLastLines, columns: columns, forkOf: forkOf })] }), note ? _jsx(Text, { color: "green", wrap: "truncate-end", children: normalizeEmoji(note) }) : null] }));
1195
+ return (_jsxs(Box, { flexDirection: "column", borderStyle: "round", borderColor: "cyan", paddingX: 1, children: [_jsx(Text, { bold: true, color: "cyan", children: "loom-deck" }), mode === 'create' ? (_jsxs(Text, { dimColor: true, wrap: "truncate-end", children: ["nuova task \u00B7 ", _jsx(Text, { color: "yellow", children: "\u23CE" }), " crea \u00B7 ", _jsx(Text, { color: "yellow", children: "esc" }), " annulla"] })) : mode === 'sort' ? (_jsxs(Text, { dimColor: true, wrap: "truncate-end", children: ["sort \u00B7 ", _jsx(Text, { color: "yellow", children: "p" }), " pri ", _jsx(Text, { color: "yellow", children: "s" }), " stato", ' ', _jsx(Text, { color: "yellow", children: "i" }), " id (asc\u2192desc\u2192off) \u00B7 ", _jsx(Text, { color: "yellow", children: "\u23CE" }), " ok \u00B7", ' ', _jsx(Text, { color: "yellow", children: "esc" }), " annulla"] })) : mode === 'filter' ? (_jsxs(Text, { dimColor: true, wrap: "truncate-end", children: ["filtri \u00B7 ", _jsx(Text, { color: "yellow", children: "\u2191\u2193\u2190\u2192" }), " naviga \u00B7 ", _jsx(Text, { color: "yellow", children: "spazio" }), ' ', "mostra/nascondi \u00B7 ", _jsx(Text, { color: "yellow", children: "\u23CE" }), " ok \u00B7 ", _jsx(Text, { color: "yellow", children: "esc" }), " annulla"] })) : mode === 'edit' ? (_jsxs(Text, { dimColor: true, wrap: "truncate-end", children: ["edit \u00B7 ", _jsx(Text, { color: "yellow", children: "\u2191\u2193" }), " campo \u00B7 ", _jsx(Text, { color: "yellow", children: "\u2190\u2192" }), " valore \u00B7", ' ', _jsx(Text, { color: "yellow", children: "\u23CE" }), " salva+commit \u00B7 ", _jsx(Text, { color: "yellow", children: "esc" }), " annulla"] })) : (_jsxs(Text, { dimColor: true, wrap: "truncate-end", children: ["\u2191\u2193 naviga \u00B7 \u2190\u2192 pane \u00B7 \u23CE ", canSpawn ? 'spawn' : canResume ? 'resume' : '—', canResume ? ' · f fork' : '', canPin ? ' · p pin' : '', " \u00B7 ^F cerca \u00B7 C nuova \u00B7 E edit \u00B7 S sort \u00B7 F filtri \u00B7 w salva \u00B7 t term \u00B7 c claude \u00B7 q esci \u00B7 focus:", ' ', _jsx(Text, { color: "cyan", children: focus })] })), mode === 'normal' && launch.length > 0 ? (_jsxs(Text, { dimColor: true, wrap: "truncate-end", children: ["launch ", legend.shown, legend.overflow > 0 ? (_jsxs(Text, { color: "yellow", children: [" \u00B7 +", legend.overflow, " fuori riga"] })) : null, legend.unreachable > 0 ? (_jsxs(Text, { color: "yellow", children: [" \u00B7 ", legend.unreachable, " oltre la 9\u00AA (non raggiungibili)"] })) : null] })) : null, mode === 'create' ? (_jsxs(Box, { borderStyle: "round", borderColor: "yellow", paddingX: 1, marginTop: 1, children: [_jsx(Text, { color: "yellow", children: "C \u203A " }), _jsx(Text, { children: draft }), _jsx(Text, { inverse: true, children: " " })] })) : null, mode === 'sort' ? _jsx(SortModal, { sort: view.sort }) : null, mode === 'filter' ? _jsx(FilterModal, { view: view, cursor: filterCursor }) : null, mode === 'edit' && edit && selTask ? (_jsx(EditModal, { id: selTask.id, draft: edit, row: editRow })) : null, _jsxs(Box, { flexDirection: "row", marginTop: 1, children: [_jsx(TasksPane, { tasks: windowTasks, filtered: viewTasks.length, total: tasks.length, hidden: hiddenTasks, view: view, selected: selIndex, spotCount: spotCount, childCount: childCount, focused: focus === 'tasks', loadError: loadError, detail: detail, windowStart: taskWin.start, above: taskWin.start, below: viewTasks.length - taskWin.end, detailLines: budget.detailLines, columns: columns }), _jsx(SessionsPane, { parentLabel: parentLabel, isSpot: isSpot, rows: windowRows, total: assembled.pinnedCount + assembled.contextTotal, pinnedCount: assembled.pinnedCount, hidden: assembled.contextHidden, selectedId: selSessionId ?? undefined, focused: focus === 'sessions', above: sessionWin.start, below: sessionRows.length - sessionWin.end, detail: budget.sessionDetail ? selSessionObj : null, firstLines: budget.sessionFirstLines, lastLines: budget.sessionLastLines, columns: columns, forkOf: forkOf })] }), note ? _jsx(Text, { color: "green", wrap: "truncate-end", children: normalizeEmoji(note) }) : null] }));
898
1196
  }
899
1197
  const SORT_UI = { pri: 'pri', prog: 'stato', id: 'id' };
900
1198
  // Modali resi IN FLUSSO (come l'input box di create), non in overlay assoluto:
@@ -924,6 +1222,145 @@ function EditModal({ id, draft, row }) {
924
1222
  const mark = (r) => (row === r ? CARET : CARET_OFF);
925
1223
  return (_jsxs(Box, { flexDirection: "column", borderStyle: "round", borderColor: "yellow", paddingX: 1, marginTop: 1, children: [_jsxs(Text, { color: "yellow", children: ["E \u203A ", id, " \u00B7 priorit\u00E0 e stato"] }), _jsxs(Text, { children: [mark(0), _jsx(Text, { dimColor: true, children: "pri " }), EDIT_PRI.map((p) => (_jsxs(Text, { inverse: draft.pri === p, color: draft.pri === p ? 'green' : 'gray', children: [' ', forceEmojiWidth(PRI_GLYPH[p]), " ", PRI_LABEL[p]] }, p)))] }), _jsxs(Text, { children: [mark(1), _jsx(Text, { dimColor: true, children: "stato" }), EDIT_PROG.map((p) => (_jsxs(Text, { inverse: draft.prog === p, color: draft.prog === p ? 'green' : 'gray', children: [' ', forceEmojiWidth(PROG_GLYPH[p]), " ", p] }, p)))] }), _jsxs(Text, { children: [mark(2), _jsx(Text, { dimColor: true, children: "prog " }), _jsxs(Text, { children: [' ', draft.detail] }), row === 2 ? _jsx(Text, { inverse: true, children: " " }) : null, !draft.detail && row !== 2 ? _jsx(Text, { dimColor: true, children: "(default)" }) : null] }), _jsxs(Text, { dimColor: true, wrap: "truncate-end", children: ["\u21B3 ", normalizeEmoji(progressText(draft.prog, draft.detail))] })] }));
926
1224
  }
1225
+ // T52 — marcatore compatto del tipo di corpo sulla riga-occorrenza. Due
1226
+ // caratteri ASCII e non un'emoji: con più toggle accesi la colonna deve
1227
+ // allinearsi, e i glifi BMP larghi 2 sono proprio la classe che Ink e il
1228
+ // terminale misurano diversamente (vedi normalizeEmoji).
1229
+ const KIND_TAG = { ai: 'ai', tool: 'tl', human: 'hu' };
1230
+ const KIND_COLOR = { ai: 'cyan', tool: 'gray', human: 'green' };
1231
+ /**
1232
+ * Larghezza dell'estratto, DERIVATA dalle colonne del terminale.
1233
+ *
1234
+ * Una costante qui è spazio buttato a ogni riga: su un terminale a 190 colonne
1235
+ * un estratto fisso a 50 lascia il match con ~20 caratteri di contesto per lato
1236
+ * quando potrebbe averne 80 — e il contesto attorno al match è l'unica ragione
1237
+ * per cui si legge la riga invece di aprire il reader.
1238
+ *
1239
+ * Scomposizione delle colonne consumate dalla cornice e dal prefisso di riga:
1240
+ * 4 box esterno (2 bordi + 2 padding)
1241
+ * 4 box lista (2 bordi + 2 padding)
1242
+ * 2 caret
1243
+ * 4 indice del record
1244
+ * 3 spazio + tag del kind + spazio
1245
+ * Prudente per costruzione: sottostimare tronca un carattere in più,
1246
+ * sovrastimare manderebbe la riga a capo e sfonderebbe il budget d'altezza.
1247
+ */
1248
+ function searchExcerptWidth(columns) {
1249
+ return Math.max(30, (columns || 80) - 17);
1250
+ }
1251
+ /** Titolo della conversazione sulla riga-gruppo: prende ciò che avanza dopo le
1252
+ * colonne a larghezza fissa (caret, pin, hash, task, conteggio, data). */
1253
+ function searchTitleWidth(columns) {
1254
+ return Math.max(24, (columns || 80) - 56);
1255
+ }
1256
+ /**
1257
+ * Cosa scrivere sulla riga-gruppo per distinguere una conversazione dall'altra.
1258
+ *
1259
+ * Non basta `session.title`: quel titolo è la label della tab Ptyxis, cioè
1260
+ * `<emoji> <owner> <name>` più un eventuale suffisso. Su una lista tutta dello
1261
+ * stesso progetto (D3) è una COLONNA COSTANTE — tre righe su quattro
1262
+ * identiche, che è esattamente il difetto che la riga-gruppo doveva evitare.
1263
+ *
1264
+ * Si toglie quindi il core `<owner> <name>` (noto dal file config), e se ciò
1265
+ * che resta è vuoto o duplica la task già mostrata nella sua colonna, si
1266
+ * ripiega sul primo prompt — l'unica cosa che davvero identifica quella
1267
+ * conversazione e non un'altra.
1268
+ */
1269
+ function conversationLabel(s, core, bound) {
1270
+ let t = s.title;
1271
+ if (core) {
1272
+ const at = t.indexOf(core);
1273
+ if (at >= 0)
1274
+ t = t.slice(at + core.length);
1275
+ }
1276
+ t = t.replace(/^[\s·]+/, '').trim();
1277
+ if (bound && t === bound)
1278
+ t = '';
1279
+ return t || s.firstPrompt || '(senza titolo)';
1280
+ }
1281
+ /**
1282
+ * Riga di toggle del modale ricerca.
1283
+ *
1284
+ * La mappa tasto→significato è SEMPRE a schermo: `^R` da solo è opaco quanto lo
1285
+ * era il range `1-9` delle launch prima di T43.
1286
+ *
1287
+ * Lo stato acceso/spento passa da `[x]`/`[ ]`, non dal solo colore — stessa
1288
+ * convenzione del modale filtri. Il colore è ridondanza, non l'informazione: su
1289
+ * un terminale monocromo, o in una cattura di testo, sei toggle tutti uguali
1290
+ * non direbbero più quali sono attivi.
1291
+ */
1292
+ function ToggleHint({ opts }) {
1293
+ const flag = (on, key, label) => (_jsxs(Text, { color: on ? 'green' : 'gray', dimColor: !on, bold: on, children: [' ', key, "[", on ? 'x' : ' ', "] ", label] }, key));
1294
+ return (_jsxs(Text, { wrap: "truncate-end", children: [flag(opts.regex, '^R', 'regex'), flag(opts.caseSensitive, '^A', 'Aa'), flag(opts.wholeWord, '^W', 'word'), _jsx(Text, { dimColor: true, children: ' │' }), flag(opts.kinds.ai, '^B', 'IA'), flag(opts.kinds.tool, '^T', 'tools'), flag(opts.kinds.human, '^U', 'human')] }));
1295
+ }
1296
+ /** Intestazione della lista: dice sempre quanto NON si sta vedendo (regex rotta,
1297
+ * query troppo corta, occorrenze tagliate dal cap, righe fuori finestra). */
1298
+ function SearchListHeader({ result, query, above, below, }) {
1299
+ if (result.error) {
1300
+ return (_jsxs(Text, { color: "red", wrap: "truncate-end", children: [WARN, " regex non valida \u00B7 ", result.error] }));
1301
+ }
1302
+ if (result.idle) {
1303
+ return (_jsx(Text, { dimColor: true, wrap: "truncate-end", children: query.length === 0
1304
+ ? 'digita la chiave da cercare'
1305
+ : `almeno ${MIN_QUERY} caratteri (${query.length})` }));
1306
+ }
1307
+ if (result.shown === 0) {
1308
+ return (_jsx(Text, { color: "yellow", wrap: "truncate-end", children: "nessuna occorrenza" }));
1309
+ }
1310
+ return (_jsxs(Text, { bold: true, wrap: "truncate-end", children: [result.shown, " occorrenze in ", result.sessionCount, " conversazioni", result.hidden > 0 ? _jsxs(Text, { color: "yellow", children: [" \u00B7 +", result.hidden, " oltre il cap"] }) : null, above > 0 ? _jsxs(Text, { dimColor: true, children: [" \u00B7 \u2191", above] }) : null, below > 0 ? _jsxs(Text, { dimColor: true, children: [" \u00B7 \u2193", below] }) : null] }));
1311
+ }
1312
+ function SearchScreen({ preview, hash, query, field, opts, result, rows, selectedKey, selectedKind, above, below, capacity, bindings, pinned, projectCore, columns, note, }) {
1313
+ const enter = selectedKind === 'session' ? 'resume' : selectedKind === 'hit' ? 'leggi' : '—';
1314
+ return (_jsxs(Box, { flexDirection: "column", borderStyle: "round", borderColor: "cyan", paddingX: 1, children: [_jsx(Text, { bold: true, color: "cyan", children: "loom-deck" }), _jsxs(Text, { dimColor: true, wrap: "truncate-end", children: ["ricerca \u00B7 ", _jsx(Text, { color: "yellow", children: "tab" }), " campo \u00B7 ", _jsx(Text, { color: "yellow", children: "\u2191\u2193" }), " naviga \u00B7", ' ', _jsx(Text, { color: "yellow", children: "\u23CE" }), " ", enter, " \u00B7 ", _jsx(Text, { color: "yellow", children: "esc" }), " chiudi"] }), _jsxs(Box, { flexDirection: "column", borderStyle: "round", borderColor: "yellow", paddingX: 1, marginTop: 1, children: [_jsxs(Text, { wrap: "truncate-end", children: [_jsx(Text, { dimColor: true, children: "hash " }), _jsx(Text, { color: field === 'hash' ? 'yellow' : undefined, children: hash }), field === 'hash' ? _jsx(Text, { inverse: true, children: " " }) : null, !hash ? _jsx(Text, { dimColor: true, children: " (vuoto = tutte le conversazioni)" }) : null] }), _jsxs(Text, { wrap: "truncate-end", children: [_jsx(Text, { dimColor: true, children: "chiave " }), _jsx(Text, { color: field === 'query' ? 'yellow' : undefined, children: query }), field === 'query' ? _jsx(Text, { inverse: true, children: " " }) : null] }), _jsx(ToggleHint, { opts: opts })] }), _jsxs(Box, { flexDirection: "column", borderStyle: "single", borderColor: "gray", paddingX: 1, marginTop: 1, children: [_jsx(SearchListHeader, { result: result, query: query, above: above, below: below }), rows.slice(0, Math.max(0, capacity)).map((row) => {
1315
+ const sel = row.key === selectedKey;
1316
+ if (row.kind === 'session') {
1317
+ const s = row.session;
1318
+ const bound = bindings.get(s.sessionId);
1319
+ return (_jsxs(Text, { inverse: sel, wrap: "truncate-end", children: [sel ? CARET : CARET_OFF, pinned.has(s.sessionId) ? _jsx(Text, { color: "yellow", children: "\uD83D\uDCCC" }) : _jsx(Text, { dimColor: true, children: "\u25CB" }), ' ', _jsx(Text, { color: "cyan", children: s.sessionId.slice(0, 8) }), _jsx(Text, { dimColor: true, children: " \u00B7 " }), bound ?? _jsx(Text, { dimColor: true, children: "spot" }), _jsx(Text, { dimColor: true, children: " \u00B7 " }), truncate(conversationLabel(s, projectCore, bound), searchTitleWidth(columns)), _jsxs(Text, { dimColor: true, children: [' ', "(", row.hitCount, row.hidden > 0 ? `+${row.hidden}` : '', ") ", fmtDateTime(s.ts)] })] }, row.key));
1320
+ }
1321
+ const h = row.hit;
1322
+ return (_jsxs(Text, { inverse: sel, wrap: "truncate-end", children: [sel ? CARET : CARET_OFF, _jsx(Text, { dimColor: true, children: String(h.idx).padStart(4) }), ' ', _jsx(Text, { color: KIND_COLOR[h.kind], children: KIND_TAG[h.kind] }), " ", h.excerpt] }, row.key));
1323
+ })] }), preview ? _jsx(SearchPreviewPane, { p: preview }) : null, note ? _jsx(Text, { color: "green", wrap: "truncate-end", children: normalizeEmoji(note) }) : null] }));
1324
+ }
1325
+ /**
1326
+ * Anteprima dell'occorrenza selezionata, sotto la lista.
1327
+ *
1328
+ * Riempie le righe che la lista non usa: con pochi risultati il terminale
1329
+ * resterebbe vuoto per tre quarti, e il contesto attorno al match è proprio
1330
+ * ciò che serve per decidere se è l'occorrenza giusta. Nel caso comune evita
1331
+ * del tutto di aprire il reader.
1332
+ *
1333
+ * Si aggiorna navigando con le frecce, e la finestra è centrata sul match:
1334
+ * stessa `windowRange` della lista, stessa evidenziazione del reader
1335
+ * (`ReaderLine`) — nessuna primitiva nuova.
1336
+ */
1337
+ function SearchPreviewPane({ p }) {
1338
+ const last = Math.min(p.total, p.from + p.lines.length);
1339
+ return (_jsxs(Box, { flexDirection: "column", borderStyle: "single", borderColor: "gray", paddingX: 1, marginTop: 1, children: [_jsxs(Text, { dimColor: true, wrap: "truncate-end", children: ["record ", p.hit.idx, " \u00B7 ", KIND_LABEL[p.hit.kind], p.ts ? ` · ${fmtDateTime(p.ts)}` : '', " \u00B7 righe ", p.from + 1, "-", last, " di ", p.total, " \u00B7", ' ', _jsx(Text, { color: "yellow", children: "\u23CE" }), " apre il reader"] }), p.lines.map((l, i) => (_jsx(ReaderLine, { line: l, from: p.hit.matchStart, to: p.hit.matchEnd }, p.from + i)))] }));
1340
+ }
1341
+ /**
1342
+ * Reader fullscreen (T52 · D8).
1343
+ *
1344
+ * Mostra il messaggio INTERO che contiene l'occorrenza, aperto già posizionato
1345
+ * sul match e con il match evidenziato. È un `mode` a sé, catturato prima del
1346
+ * ramo `search`: il modale ricerca resta montato sotto e su `esc` si ritrova
1347
+ * con query, toggle e selezione intatti.
1348
+ */
1349
+ function ReaderScreen({ hit, lines, top, total, capacity, bound, }) {
1350
+ const last = Math.min(total, top + capacity);
1351
+ return (_jsxs(Box, { flexDirection: "column", borderStyle: "round", borderColor: "cyan", paddingX: 1, children: [_jsx(Text, { bold: true, color: "cyan", children: "loom-deck" }), _jsxs(Text, { dimColor: true, wrap: "truncate-end", children: ["reader \u00B7 ", _jsx(Text, { color: "cyan", children: hit.sessionId.slice(0, 8) }), " \u00B7 record ", hit.idx, " \u00B7", ' ', KIND_LABEL[hit.kind], bound ? ` · ${bound}` : '', " \u00B7 righe ", total === 0 ? 0 : top + 1, "-", last, " di ", total] }), _jsxs(Text, { dimColor: true, wrap: "truncate-end", children: [_jsx(Text, { color: "yellow", children: "\u2191\u2193" }), " riga \u00B7 ", _jsx(Text, { color: "yellow", children: "PgUp/PgDn" }), " pagina \u00B7", ' ', _jsx(Text, { color: "yellow", children: "g" }), " inizio \u00B7 ", _jsx(Text, { color: "yellow", children: "G" }), " fine \u00B7", ' ', _jsx(Text, { color: "yellow", children: "esc" }), " torna alla lista"] }), _jsx(Box, { flexDirection: "column", borderStyle: "single", borderColor: "gray", paddingX: 1, marginTop: 1, children: lines.map((l, i) => (_jsx(ReaderLine, { line: l, from: hit.matchStart, to: hit.matchEnd }, top + i))) })] }));
1352
+ }
1353
+ /** Una riga del reader, con la sola porzione di match evidenziata. Gli offset
1354
+ * sono quelli del testo sorgente, quindi un match a cavallo dell'a-capo si
1355
+ * colora su entrambe le righe senza casi speciali. */
1356
+ function ReaderLine({ line, from, to }) {
1357
+ const a = Math.max(0, Math.min(line.text.length, from - line.start));
1358
+ const b = Math.max(0, Math.min(line.text.length, to - line.start));
1359
+ if (b <= a) {
1360
+ return _jsx(Text, { wrap: "truncate-end", children: line.text || ' ' });
1361
+ }
1362
+ return (_jsxs(Text, { wrap: "truncate-end", children: [line.text.slice(0, a), _jsx(Text, { backgroundColor: "yellow", color: "black", children: line.text.slice(a, b) }), line.text.slice(b)] }));
1363
+ }
927
1364
  function TasksPane({ tasks, filtered, total, hidden, view, selected, spotCount, childCount, focused, loadError, detail, windowStart, above, below, detailLines, columns, }) {
928
1365
  const spotSelected = selected === 0;
929
1366
  return (_jsxs(Box, { flexDirection: "column", width: "50%", marginRight: 1, borderStyle: "single", borderColor: focused ? 'cyan' : 'gray', paddingX: 1, children: [_jsxs(Text, { bold: true, color: focused ? 'cyan' : undefined, wrap: "truncate-end", children: ["Tasks (", hidden > 0 ? `${filtered}/${total}` : filtered, ")", hidden > 0 ? _jsxs(Text, { color: "yellow", children: [" \u00B7 ", hidden, " nascoste"] }) : null, above > 0 ? _jsxs(Text, { dimColor: true, children: [" \u00B7 \u2191", above] }) : null, below > 0 ? _jsxs(Text, { dimColor: true, children: [" \u00B7 \u2193", below] }) : null] }), _jsxs(Text, { dimColor: true, wrap: "truncate-end", children: ["sort: ", describeSort(view.sort), view.hiddenPri.length + view.hiddenProg.length > 0 ? (_jsxs(Text, { children: [' ', "\u00B7 filtri:", ' ', [
package/dist/search.js ADDED
@@ -0,0 +1,262 @@
1
+ // T52 — Core della ricerca full-text nelle conversazioni del progetto.
2
+ //
3
+ // Modulo PURO, gemello di `session-list.ts`: nessun import da ink/react, nessun
4
+ // I/O, nessuno stato globale. Prende in ingresso le `Session` già parsate
5
+ // dall'adapter (con i `bodies` trattenuti dalla cache mtime-keyed) e restituisce
6
+ // le righe da renderizzare. Tutto ciò che è testabile senza terminale sta qui.
7
+ //
8
+ // Invarianti (decisioni congelate al preflight):
9
+ // - D3: perimetro = SOLO le sessioni del progetto corrente. Il modulo cerca su
10
+ // ciò che gli viene passato, e chi lo chiama passa `discoverProjectSessions`.
11
+ // - D5: ricerca IN MEMORIA sui corpi, nessun prefiltro esterno. Un solo motore
12
+ // di regex (`RegExp` JS) sia in modalità literal sia in `^R` → non esiste il
13
+ // caso "il prefiltro scarta un file che contiene un'occorrenza reale".
14
+ // - D6: tre kind (ai · tool · human). Il `thinking` non è persistito.
15
+ // - D7: la riga-occorrenza porta l'indice del record; la data sta una volta
16
+ // sola sulla riga-sessione.
17
+ // - Trap T39/T50: la selezione è keyed su una CHIAVE DISCRIMINATA, mai su
18
+ // indice posizionale — la lista si riordina a ogni carattere digitato.
19
+ /** Sotto questa soglia non si cerca: 1-2 char matchano ovunque e la lista
20
+ * sarebbe rumore. Stato lecito, non un errore. */
21
+ export const MIN_QUERY = 3;
22
+ /** Larghezza di ripiego dell'estratto, usata solo quando il chiamante non
23
+ * conosce le colonne del terminale (test, uso non-TUI). In UI la larghezza
24
+ * arriva SEMPRE da `columns`: inchiodarla qui sprecherebbe tutto lo spazio di
25
+ * un terminale largo — su 190 colonne significa ~140 buttate per riga. */
26
+ export const EXCERPT_WIDTH = 50;
27
+ /** Cap per singola conversazione. Serve a tenere leggibile un gruppo, non a
28
+ * proteggere la memoria: una query corta può matchare centinaia di volte nello
29
+ * stesso transcript e sommergere tutte le altre conversazioni. */
30
+ export const MAX_HITS_PER_SESSION = 20;
31
+ /** Cap globale. Oltre, la lista non è più navigabile a mano: la risposta giusta
32
+ * è restringere la query, e il contatore delle nascoste lo dice. */
33
+ export const MAX_TOTAL_HITS = 400;
34
+ export const DEFAULT_OPTIONS = {
35
+ regex: false,
36
+ caseSensitive: false,
37
+ wholeWord: false,
38
+ // D4/§Filtro: il testo IA è il caso d'uso che ha generato la task («l'IA me
39
+ // l'ha detto 150k fa»); tools e human si accendono a mano.
40
+ kinds: { ai: true, tool: false, human: false },
41
+ };
42
+ const EMPTY = {
43
+ groups: [],
44
+ shown: 0,
45
+ hidden: 0,
46
+ sessionCount: 0,
47
+ error: '',
48
+ idle: true,
49
+ };
50
+ function escapeLiteral(s) {
51
+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
52
+ }
53
+ /**
54
+ * Compila la query nel matcher.
55
+ *
56
+ * Ritorna `{re: null, error}` invece di lanciare: con la ricerca eager la regex
57
+ * viene ricompilata a ogni carattere, e uno stato intermedio invalido (`[a-`,
58
+ * `(`) è la NORMA durante la digitazione, non un caso limite. Deve degradare a
59
+ * lista vuota con segnalazione inline, mai a un crash della TUI.
60
+ */
61
+ export function buildMatcher(query, opts) {
62
+ if (query.length < MIN_QUERY)
63
+ return { re: null, error: '' };
64
+ let source = opts.regex ? query : escapeLiteral(query);
65
+ // Il gruppo non-catturante è obbligatorio: senza, `\b` si legherebbe al solo
66
+ // primo/ultimo ramo di un'alternativa (`\bfoo|bar\b` ≠ `\b(?:foo|bar)\b`).
67
+ if (opts.wholeWord)
68
+ source = `\\b(?:${source})\\b`;
69
+ const flags = opts.caseSensitive ? 'g' : 'gi';
70
+ try {
71
+ return { re: new RegExp(source, flags), error: '' };
72
+ }
73
+ catch (e) {
74
+ return { re: null, error: e.message };
75
+ }
76
+ }
77
+ /**
78
+ * Estratto centrato sul match.
79
+ *
80
+ * Il testo è RAW (newline incluse) e gli offset sono suoi: si affetta prima e si
81
+ * collassa il whitespace dopo, su ciascun pezzo separatamente. Collassare prima
82
+ * sposterebbe gli offset; collassare l'intera finestra insieme fonderebbe i
83
+ * confini del match con il contesto.
84
+ *
85
+ * Degrada ai bordi: match a inizio o fine messaggio prende tutto il contesto
86
+ * disponibile dal lato che ce l'ha, invece di lasciare metà estratto vuoto.
87
+ */
88
+ export function excerptAround(text, start, end, width = EXCERPT_WIDTH) {
89
+ const collapse = (s) => s.replace(/\s+/g, ' ');
90
+ // Un match più lungo dell'estratto: si tronca il match stesso, altrimenti la
91
+ // riga andrebbe a capo e sfonderebbe il budget d'altezza della lista.
92
+ if (end - start >= width) {
93
+ return collapse(text.slice(start, start + width - 1)).trimEnd() + '…';
94
+ }
95
+ const budget = width - (end - start);
96
+ // Metà per lato, poi il lato che non riesce a spendere la sua quota (match a
97
+ // ridosso di un bordo) la cede all'altro.
98
+ let before = Math.floor(budget / 2);
99
+ let after = budget - before;
100
+ const availBefore = start;
101
+ const availAfter = text.length - end;
102
+ if (before > availBefore) {
103
+ after += before - availBefore;
104
+ before = availBefore;
105
+ }
106
+ if (after > availAfter) {
107
+ before = Math.min(availBefore, before + (after - availAfter));
108
+ after = availAfter;
109
+ }
110
+ const from = start - before;
111
+ const to = end + after;
112
+ const head = collapse(text.slice(from, start));
113
+ const mid = collapse(text.slice(start, end));
114
+ const tail = collapse(text.slice(end, to));
115
+ return (from > 0 ? '…' : '') + head + mid + tail + (to < text.length ? '…' : '');
116
+ }
117
+ /**
118
+ * Scansiona un corpo: materializza al più `need` occorrenze, ma le CONTA tutte.
119
+ *
120
+ * I due numeri sono separati apposta. Fermare anche il conteggio al cap
121
+ * renderebbe silenziosa proprio la troncatura che il contatore deve dichiarare
122
+ * («+N occorrenze»), e il conteggio è la parte economica — costruire un Hit
123
+ * significa costruire un estratto, scorrere la stringa no.
124
+ *
125
+ * `re` deve avere il flag `g` (lo garantisce buildMatcher).
126
+ */
127
+ function scanBody(sessionId, body, re, need, excerptWidth) {
128
+ const hits = [];
129
+ let count = 0;
130
+ re.lastIndex = 0;
131
+ let m;
132
+ while ((m = re.exec(body.text)) !== null) {
133
+ count++;
134
+ if (hits.length < need) {
135
+ const start = m.index;
136
+ const end = start + m[0].length;
137
+ hits.push({
138
+ sessionId,
139
+ idx: body.idx,
140
+ kind: body.kind,
141
+ excerpt: excerptAround(body.text, start, end, excerptWidth),
142
+ matchStart: start,
143
+ matchEnd: end,
144
+ text: body.text,
145
+ });
146
+ }
147
+ // Una regex può matchare la stringa vuota (`a*`, `^`): senza avanzare a
148
+ // mano, `exec` resta fermo sullo stesso indice e il ciclo non termina mai.
149
+ if (m[0].length === 0)
150
+ re.lastIndex++;
151
+ }
152
+ return { hits, count };
153
+ }
154
+ /**
155
+ * Cerca su tutte le sessioni passate.
156
+ *
157
+ * `hashPrefix` restringe a una conversazione per PREFISSO del sessionId, non per
158
+ * uguaglianza: gli 8 char che la statusline mostra bastano a individuarla, e
159
+ * nessuno copia un uuid intero a mano.
160
+ */
161
+ export function searchSessions(sessions, hashPrefix, query, opts, excerptWidth = EXCERPT_WIDTH) {
162
+ const prefix = hashPrefix.trim().toLowerCase();
163
+ const scoped = prefix
164
+ ? sessions.filter((s) => s.sessionId.toLowerCase().startsWith(prefix))
165
+ : sessions;
166
+ const { re, error } = buildMatcher(query, opts);
167
+ if (error)
168
+ return { ...EMPTY, idle: false, error };
169
+ if (!re)
170
+ return EMPTY;
171
+ const groups = [];
172
+ let shown = 0;
173
+ let hidden = 0;
174
+ for (const session of scoped) {
175
+ const hits = [];
176
+ let found = 0;
177
+ for (const body of session.bodies) {
178
+ if (!opts.kinds[body.kind])
179
+ continue;
180
+ // Quanto ancora si può MATERIALIZZARE: il minore fra spazio nel gruppo e
181
+ // spazio nella lista. A zero la scansione prosegue lo stesso — serve il
182
+ // conteggio, che è ciò che alimenta «+N occorrenze».
183
+ const need = Math.max(0, Math.min(MAX_HITS_PER_SESSION - hits.length, MAX_TOTAL_HITS - shown - hits.length));
184
+ const r = scanBody(session.sessionId, body, re, need, excerptWidth);
185
+ found += r.count;
186
+ hits.push(...r.hits);
187
+ }
188
+ if (found === 0)
189
+ continue;
190
+ hidden += found - hits.length;
191
+ if (hits.length === 0)
192
+ continue; // tutte tagliate dal cap globale
193
+ groups.push({ session, hits, hidden: found - hits.length });
194
+ shown += hits.length;
195
+ }
196
+ return { groups, shown, hidden, sessionCount: groups.length, error: '', idle: false };
197
+ }
198
+ /** Chiave discriminata di una riga-occorrenza. `matchStart` è nella chiave
199
+ * perché due match nello stesso record sono righe distinte. */
200
+ function hitKey(h) {
201
+ return `hit:${h.sessionId}:${h.idx}:${h.kind}:${h.matchStart}`;
202
+ }
203
+ /**
204
+ * Appiattisce i gruppi in righe.
205
+ *
206
+ * Con `hashPrefix` valorizzato la lista è PIATTA: la conversazione è una sola e
207
+ * già nominata nel campo hash, quindi la riga-sessione ripeterebbe un dato
208
+ * costante rubando una riga per gruppo.
209
+ */
210
+ export function buildRows(result, flat) {
211
+ const rows = [];
212
+ for (const g of result.groups) {
213
+ if (!flat) {
214
+ rows.push({
215
+ kind: 'session',
216
+ key: `sess:${g.session.sessionId}`,
217
+ session: g.session,
218
+ hitCount: g.hits.length,
219
+ hidden: g.hidden,
220
+ });
221
+ }
222
+ for (const h of g.hits)
223
+ rows.push({ kind: 'hit', key: hitKey(h), hit: h });
224
+ }
225
+ return rows;
226
+ }
227
+ /**
228
+ * Riga su cui atterrare quando la selezione va ricostruita.
229
+ *
230
+ * Preferisce la prima **occorrenza**, non la prima riga in assoluto. In modalità
231
+ * raggruppata la lista si apre sempre con una riga-sessione, che è un
232
+ * segnaposto di navigazione e non una destinazione: atterrarci lascerebbe
233
+ * l'anteprima vuota all'apertura di ogni ricerca, e `⏎` prometterebbe un resume
234
+ * quando l'utente ha appena cercato delle occorrenze.
235
+ *
236
+ * Le righe-sessione restano raggiungibili con le frecce. null = lista vuota.
237
+ */
238
+ export function firstRowKey(rows) {
239
+ return (rows.find((r) => r.kind === 'hit') ?? rows[0])?.key ?? null;
240
+ }
241
+ /** Indice della riga con quella chiave; -1 se assente. */
242
+ export function rowIndexOfKey(rows, key) {
243
+ if (key === null)
244
+ return -1;
245
+ return rows.findIndex((r) => r.key === key);
246
+ }
247
+ /** Sposta la selezione di `delta` righe. Chiave persa (la lista è cambiata sotto)
248
+ * → prima riga; lista vuota → null. */
249
+ export function moveRowSelection(rows, currentKey, delta) {
250
+ if (rows.length === 0)
251
+ return null;
252
+ const cur = rowIndexOfKey(rows, currentKey);
253
+ if (cur < 0)
254
+ return rows[0].key;
255
+ return rows[Math.max(0, Math.min(rows.length - 1, cur + delta))].key;
256
+ }
257
+ /** Riga selezionata, o null. */
258
+ export function selectedRow(rows, key) {
259
+ if (key === null)
260
+ return null;
261
+ return rows.find((r) => r.key === key) ?? null;
262
+ }
package/dist/sessions.js CHANGED
@@ -45,6 +45,91 @@ function extractText(message) {
45
45
  }
46
46
  return '';
47
47
  }
48
+ // Un record `type:user` che porta SOLO questo testo è un evento di UI (l'utente
49
+ // ha premuto esc), non un messaggio scritto. Stesso `type` di un prompt vero:
50
+ // senza escluderlo comparirebbe come «primo prompt» della conversazione e
51
+ // gonfierebbe la ricerca sui messaggi umani. Prefisso e non uguaglianza —
52
+ // esistono varianti («…by user for tool use»).
53
+ const INTERRUPT_MARKER = '[Request interrupted by user';
54
+ function isInterrupt(text) {
55
+ return text.trimStart().startsWith(INTERRUPT_MARKER);
56
+ }
57
+ // T52 — estrae i corpi cercabili di UN record, uno per `kind` presente.
58
+ //
59
+ // Blocchi dello stesso kind nello stesso record vengono CONCATENATI, non emessi
60
+ // separatamente: il reader promette «il messaggio intero», e la coppia
61
+ // (idx, kind) resta così una chiave univoca per la riga-occorrenza.
62
+ //
63
+ // Mappatura dei blocchi, verificata sullo store:
64
+ // - assistant `text` → ai
65
+ // - assistant `tool_use` → tool (nome + input serializzato: il comando
66
+ // eseguito è ciò che si cerca, non il wrapper)
67
+ // - assistant `thinking` → SCARTATO: il campo `thinking` è SEMPRE ''
68
+ // (persistita solo la `signature`, la firma
69
+ // crittografica). Indicizzarlo produrrebbe una
70
+ // categoria che non può mai dare un risultato.
71
+ // - user stringa nuda / `text` → human
72
+ // - user `tool_result` → tool (viaggia come type:user, ma non è
73
+ // scritto da un umano)
74
+ //
75
+ // `isAssistant` arriva dal `type` del RECORD, non da `message.role`: è il campo
76
+ // su cui il resto del parser già dispatcha (i due combaciano sullo store attuale
77
+ // — verificato — ma dipendere da uno solo evita che divergano in silenzio).
78
+ function collectBodies(message, idx, isAssistant, out) {
79
+ if (!message || typeof message !== 'object')
80
+ return;
81
+ const content = message.content;
82
+ const parts = { ai: [], tool: [], human: [] };
83
+ if (typeof content === 'string') {
84
+ if (content)
85
+ parts[isAssistant ? 'ai' : 'human'].push(content);
86
+ }
87
+ else if (Array.isArray(content)) {
88
+ for (const block of content) {
89
+ if (!block || typeof block !== 'object')
90
+ continue;
91
+ const b = block;
92
+ if (b.type === 'text' && typeof b.text === 'string' && b.text) {
93
+ parts[isAssistant ? 'ai' : 'human'].push(b.text);
94
+ }
95
+ else if (b.type === 'tool_use') {
96
+ const name = typeof b.name === 'string' ? b.name : 'tool';
97
+ let input = '';
98
+ try {
99
+ input = JSON.stringify(b.input ?? {});
100
+ }
101
+ catch {
102
+ input = ''; // input ciclico/non serializzabile → resta il solo nome
103
+ }
104
+ parts.tool.push(`${name} ${input}`);
105
+ }
106
+ else if (b.type === 'tool_result') {
107
+ const r = b.content;
108
+ if (typeof r === 'string') {
109
+ if (r)
110
+ parts.tool.push(r);
111
+ }
112
+ else if (Array.isArray(r)) {
113
+ for (const rb of r) {
114
+ if (rb && typeof rb === 'object' && rb.type === 'text') {
115
+ const t = rb.text;
116
+ if (typeof t === 'string' && t)
117
+ parts.tool.push(t);
118
+ }
119
+ }
120
+ }
121
+ }
122
+ }
123
+ }
124
+ for (const kind of ['ai', 'tool', 'human']) {
125
+ const text = parts[kind].join('\n');
126
+ if (!text)
127
+ continue;
128
+ if (kind === 'human' && isInterrupt(text))
129
+ continue;
130
+ out.push({ idx, kind, text });
131
+ }
132
+ }
48
133
  // Cache mtime-keyed: re-parse solo i file cambiati. Steady-state di una TUI che
49
134
  // poll-a resta economico anche con decine di sessioni multi-MB. Lo stato vive
50
135
  // dentro l'adapter così l'invariante "unico modulo che tocca lo store" regge.
@@ -57,6 +142,18 @@ function parseSessionFile(path, mtime, sizeBytes) {
57
142
  catch {
58
143
  return null;
59
144
  }
145
+ return parseTranscript(content, path, mtime, sizeBytes);
146
+ }
147
+ /**
148
+ * Semantica del transcript, separata dalla lettura del file.
149
+ *
150
+ * L'I/O resta in `parseSessionFile` (l'invariante «unico modulo che tocca lo
151
+ * store» vale per QUESTO file, non per la funzione): qui c'è solo la parte non
152
+ * ovvia — cosa conta come turno, cosa è un corpo cercabile, quali record sono
153
+ * eventi di UI travestiti da messaggi. È anche l'unica parte che vale la pena
154
+ * testare, e su una stringa si testa senza inventare un finto `~/.claude`.
155
+ */
156
+ export function parseTranscript(content, path, mtime, sizeBytes) {
60
157
  let sessionId = basename(path).replace(/\.jsonl$/, '');
61
158
  let cwd = '';
62
159
  let gitBranch = '';
@@ -65,6 +162,8 @@ function parseSessionFile(path, mtime, sizeBytes) {
65
162
  let firstUserText = '';
66
163
  let lastAssistantText = '';
67
164
  let turns = 0;
165
+ const bodies = [];
166
+ let recordIdx = -1;
68
167
  for (const line of content.split('\n')) {
69
168
  if (!line.trim())
70
169
  continue;
@@ -75,6 +174,12 @@ function parseSessionFile(path, mtime, sizeBytes) {
75
174
  catch {
76
175
  continue;
77
176
  }
177
+ // Indice progressivo sui soli record VALIDI: è ciò che prefissa la
178
+ // riga-occorrenza, quindi deve contare come li conta chi legge il file.
179
+ recordIdx++;
180
+ if (d.type === 'user' || d.type === 'assistant') {
181
+ collectBodies(d.message, recordIdx, d.type === 'assistant', bodies);
182
+ }
78
183
  if (typeof d.sessionId === 'string' && d.sessionId)
79
184
  sessionId = d.sessionId;
80
185
  if (!cwd && typeof d.cwd === 'string' && d.cwd)
@@ -89,8 +194,11 @@ function parseSessionFile(path, mtime, sizeBytes) {
89
194
  if (d.type === 'user') {
90
195
  // T49: turno = prompt umano. I tool_result viaggiano anch'essi come
91
196
  // type:user ma senza blocchi text → extractText '' li esclude.
197
+ // T52: e nemmeno l'interruzione da esc è un prompt — stesso `type`, ma è
198
+ // un evento di UI. Senza il filtro gonfia i turni e può diventare il
199
+ // «primo prompt» mostrato nel detail pane.
92
200
  const t = extractText(d.message);
93
- if (t) {
201
+ if (t && !isInterrupt(t)) {
94
202
  turns++;
95
203
  if (!firstUserText)
96
204
  firstUserText = t;
@@ -120,6 +228,7 @@ function parseSessionFile(path, mtime, sizeBytes) {
120
228
  customTitle,
121
229
  firstPrompt: firstUserText,
122
230
  lastReply: lastAssistantText,
231
+ bodies,
123
232
  };
124
233
  }
125
234
  // Discovery read-only delle sessioni del SOLO progetto corrente (D2 preflight
package/dist/viewport.js CHANGED
@@ -78,6 +78,13 @@ export const MODAL_HEIGHT = {
78
78
  sort: 5, // marginTop + 2 bordi + titolo + 1 riga catena
79
79
  filter: 6, // marginTop + 2 bordi + titolo + 2 righe (pri, stato)
80
80
  edit: 8, // marginTop + 2 bordi + titolo + 3 campi + riga anteprima
81
+ // T52 — search e reader sono gli unici modali NON in flusso: sostituiscono i
82
+ // due pane invece di spingerli giù (una lista di occorrenze non entra in un
83
+ // box sopra il deck). Costo 0 nel budget dei pane perché quel budget non
84
+ // viene nemmeno calcolato: il render esce prima. La loro altezza la
85
+ // distribuiscono `searchListCapacity`/`readerCapacity`.
86
+ search: 0,
87
+ reader: 0,
81
88
  };
82
89
  /**
83
90
  * Distribuisce le righe disponibili fra lista task, lista sessioni e dettaglio.
@@ -164,6 +171,114 @@ export function layoutBudget(input) {
164
171
  compact: false,
165
172
  };
166
173
  }
174
+ // T52 — cornice fissa della schermata di ricerca. Stesso vincolo del deck
175
+ // normale (il frame non deve superare `rows`), contabilità separata perché la
176
+ // schermata è sostitutiva, non additiva.
177
+ //
178
+ // 2 bordi del box esterno
179
+ // 1 titolo "loom-deck"
180
+ // 1 riga hint/legenda tasti
181
+ // 1 marginTop del box query
182
+ // 2 bordi del box query
183
+ // 3 righe del box query: hash · chiave · toggle
184
+ // 1 marginTop del box lista
185
+ // 2 bordi del box lista
186
+ // 1 header della lista (conteggi)
187
+ const SEARCH_CHROME = 14;
188
+ /** Righe di lista occorrenze che entrano nel terminale. Zero = la cornice non
189
+ * ci sta nemmeno vuota → la schermata va sostituita (vedi `isCompact`). */
190
+ export function searchListCapacity(rows, noteLine) {
191
+ return Math.max(0, (rows || 24) - SLACK - SEARCH_CHROME - (noteLine ? 1 : 0));
192
+ }
193
+ // T52 — cornice del reader fullscreen.
194
+ // 2 bordi del box esterno
195
+ // 1 titolo "loom-deck"
196
+ // 1 riga meta (sessione · record · tipo · posizione)
197
+ // 1 riga hint
198
+ // 1 marginTop del box corpo
199
+ // 2 bordi del box corpo
200
+ const READER_CHROME = 8;
201
+ /** Righe di testo del messaggio che entrano nel terminale. */
202
+ export function readerCapacity(rows) {
203
+ return Math.max(0, (rows || 24) - SLACK - READER_CHROME);
204
+ }
205
+ // T52 — cornice del pannello di anteprima sotto la lista occorrenze:
206
+ // marginTop + 2 bordi + riga meta.
207
+ const SEARCH_PREVIEW_CHROME = 4;
208
+ /**
209
+ * Righe di contesto concesse all'anteprima dell'occorrenza selezionata.
210
+ *
211
+ * Prende SOLO ciò che avanza: la lista si dimensiona sul contenuto e, quando i
212
+ * risultati sono pochi, il resto del terminale resterebbe vuoto. Con molti
213
+ * risultati lo spazio torna alla lista e il pannello sparisce da sé — la
214
+ * priorità è vedere quante più occorrenze possibile, il contesto è il premio
215
+ * per una ricerca già stretta.
216
+ *
217
+ * Restituisce 0 quando non c'è spazio nemmeno per una riga utile: un pannello
218
+ * di sola cornice ruberebbe 4 righe per non mostrare nulla.
219
+ */
220
+ export function searchPreviewCapacity(capacity, listRows) {
221
+ return Math.max(0, capacity - listRows - SEARCH_PREVIEW_CHROME);
222
+ }
223
+ /**
224
+ * Il terminale non ospita nemmeno la cornice della schermata: va sostituita da
225
+ * una riga singola, come fa `Budget.compact` per il deck.
226
+ *
227
+ * Non è una comodità estetica ed è lo stesso ragionamento del layout a box: un
228
+ * frame più alto di `rows` fa cadere Ink nel ramo `clearTerminal`, che su
229
+ * VTE/Ptyxis riversa ogni redraw nello scrollback. Un terminale basso è proprio
230
+ * la condizione che innesca quel ramo, quindi qui il fallback È il fix.
231
+ */
232
+ export function isCompact(capacity) {
233
+ return capacity < 1;
234
+ }
235
+ /**
236
+ * A-capo che PRESERVA la struttura del testo e traccia gli offset.
237
+ *
238
+ * Distinto da `wrapLines`, che collassa tutto in un flusso unico: lì serviva una
239
+ * preview compatta di 2-4 righe, qui si legge un messaggio intero — appiattire
240
+ * le newline renderebbe illeggibile qualunque blocco di codice o elenco.
241
+ *
242
+ * Ogni riga prodotta è una FETTA CONTIGUA del sorgente: è ciò che permette di
243
+ * intersecarla con l'intervallo del match e colorare solo la parte giusta,
244
+ * anche quando il match cade a cavallo di due righe.
245
+ *
246
+ * Taglia sull'ultimo spazio disponibile; una parola più larga della riga viene
247
+ * spezzata a forza, altrimenti l'a-capo lo farebbe il terminale — fuori dal
248
+ * conteggio delle righe, cioè di nuovo un frame più alto di `rows`.
249
+ */
250
+ export function wrapWithOffsets(text, width) {
251
+ const out = [];
252
+ if (width <= 0)
253
+ return out;
254
+ let base = 0;
255
+ for (const raw of text.split('\n')) {
256
+ // Tab e CR diventano UN singolo spazio, non quattro: la sostituzione deve
257
+ // conservare la lunghezza, o gli offset delle righe smettono di indicizzare
258
+ // il sorgente e il match verrebbe evidenziato spostato. Un tab lasciato
259
+ // passare sarebbe l'errore opposto — lo conteremmo 1 e il terminale 8.
260
+ const line = raw.replace(/[\t\r]/g, ' ');
261
+ if (line.length === 0) {
262
+ out.push({ text: '', start: base, end: base });
263
+ }
264
+ let pos = 0;
265
+ while (pos < line.length) {
266
+ if (line.length - pos <= width) {
267
+ out.push({ text: line.slice(pos), start: base + pos, end: base + line.length });
268
+ break;
269
+ }
270
+ let brk = line.lastIndexOf(' ', pos + width);
271
+ if (brk <= pos)
272
+ brk = pos + width; // parola più lunga della riga
273
+ out.push({ text: line.slice(pos, brk), start: base + pos, end: base + brk });
274
+ pos = brk;
275
+ while (line[pos] === ' ')
276
+ pos++; // lo spazio del taglio non apre la riga dopo
277
+ }
278
+ base += raw.length + 1; // +1 = il '\n' consumato dallo split
279
+ }
280
+ return out;
281
+ }
167
282
  /**
168
283
  * Finestra scorrevole su una lista più lunga della capienza.
169
284
  *
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lamemind/loom-deck",
3
- "version": "0.13.0",
3
+ "version": "0.15.0",
4
4
  "description": "Deck TUI Ink per-progetto della famiglia loom: legge tasks.md e spawna sessioni Claude Code bound via LOOM_TASK",
5
5
  "type": "module",
6
6
  "bin": {