illumitech-forge-cli 1.6.0

Evidence-backed agent execution CLI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
use super::*;
use commands::{COMMANDS, matching};
use markdown::{ORANGE, TEAL};
use ratatui::{
    layout::Rect,
    text::Span,
    widgets::{BorderType, List, ListItem, ListState},
};

pub(super) const ASCII: &[&str] = &[
    r" _____ ___  ____   ____ _____",
    r"|  ___/ _ \|  _ \ / ___| ____|",
    r"| |_ | | | | |_) | |  _|  _|",
    r"|  _|| |_| |  _ <| |_| | |___",
    r"|_|   \___/|_| \_\\____|_____|",
];
pub(super) fn banner() -> Vec<Line<'static>> {
    let mut lines = vec![Line::styled(
        "ILLUMITECH FORGE",
        Style::default().fg(TEAL).bold(),
    )];
    lines.extend(
        ASCII
            .iter()
            .map(|s| Line::styled((*s).to_owned(), Style::default().fg(ORANGE))),
    );
    lines
}
fn title(text: &str) -> Line<'static> {
    Line::styled(text.to_owned(), Style::default().fg(ORANGE).bold())
}
fn block(name: &str) -> Block<'static> {
    Block::default()
        .borders(Borders::ALL)
        .border_type(BorderType::Rounded)
        .title(name.to_owned())
        .border_style(Style::default().fg(TEAL))
}
fn metric(value: &Value) -> String {
    value
        .as_u64()
        .map(|n| n.to_string())
        .unwrap_or_else(|| "não observado".into())
}
impl Chat {
    pub(super) fn draw(&mut self, f: &mut Frame, view: &View, root: &Path) {
        let area = f.area();
        if area.width < 40 || area.height < 16 {
            f.render_widget(
                Paragraph::new("FORGE · Amplie para 40 × 16. Ctrl+Q sai.")
                    .wrap(Wrap { trim: false }),
                area,
            );
            return;
        }
        let session = view.sessions.get(&self.selected);
        self.transcript.update(session, self.activities);
        self.activity_panel.update(session);
        let approval = view
            .approvals
            .values()
            .find(|a| a["params"]["threadId"] == self.selected);
        self.choosing = approval.cloned();
        let active = view.connected && session.is_some_and(|s| s.active_turn.is_some());
        if active {
            self.active_started
                .get_or_insert_with(std::time::Instant::now);
        } else {
            self.active_started = None;
        }
        let matches = if self.panel.is_none() && !self.palette_dismissed {
            matching(&self.editor.text)
        } else {
            Vec::new()
        };
        self.palette_selection = self.palette_selection.min(matches.len().saturating_sub(1));
        let compact = area.height < 22;
        let palette_height = if matches.is_empty() {
            0
        } else {
            (matches.len().min(if compact { 3 } else { 5 }) + 2) as u16
        };
        let approval_height = if approval.is_some() { 6 } else { 0 };
        let chunks = Layout::default()
            .direction(Direction::Vertical)
            .constraints([
                Constraint::Length(2),
                Constraint::Min(1),
                Constraint::Length(approval_height),
                Constraint::Length(palette_height),
                Constraint::Length(
                    (self
                        .editor
                        .text
                        .split('\n')
                        .count()
                        .clamp(1, if compact { 2 } else { 5 })
                        + 2) as u16,
                ),
                Constraint::Length(if view.error.is_some() || !self.notice.is_empty() {
                    3
                } else {
                    2
                }),
            ])
            .split(area);
        let model = session
            .and_then(|s| s.effective["model"].as_str())
            .unwrap_or("configuração nativa");
        f.render_widget(
            Paragraph::new(vec![
                Line::from(vec![
                    Span::styled("ILLUMITECH FORGE", Style::default().fg(ORANGE).bold()),
                    Span::styled(
                        format!("  v{} · LOCAL", env!("CARGO_PKG_VERSION")),
                        Style::default().fg(Color::Gray),
                    ),
                ]),
                Line::from(format!(
                    "{}  /  {}  /  {}",
                    display(&root.file_name().unwrap_or_default().to_string_lossy()),
                    display(model),
                    self.mode.label()
                )),
            ]),
            chunks[0],
        );
        // Native approval scope always takes precedence over decorative panels.
        if let Some(a) = approval.filter(|_| self.panel.is_none()) {
            let mut lines = vec![
                title("Revise a solicitação nativa"),
                Line::from("PgUp/PgDn percorrem o escopo completo."),
            ];
            lines.extend(
                display(&serde_json::to_string_pretty(&a["params"]).unwrap_or_default())
                    .lines()
                    .map(|s| Line::from(s.to_owned())),
            );
            self.approval_scroll.draw(
                f,
                &lines,
                chunks[1],
                &format!("{}:{}", self.selected, a["id"]),
                self.tick as u64,
            );
        } else if let Some(panel) = self.panel {
            self.render_panel(f, panel, view, root, chunks[1]);
        } else if self.transcript.lines.is_empty() {
            let mut lines = if chunks[1].height >= 12 && chunks[1].width >= 55 {
                banner()
            } else {
                vec![title("Bem-vindo ao Forge · /plan organiza uma tarefa")]
            };
            lines.extend([
                Line::default(),
                title("Uma ideia. Um plano. Evidências."),
                Line::from(self.mode.hint()),
                Line::default(),
                Line::from("/ comandos  ·  F1 ajuda  ·  F3 modos  ·  Ctrl+R histórico"),
                Line::from("Conta e permissões gerenciadas pelo cliente nativo."),
            ]);
            f.render_widget(Paragraph::new(lines).wrap(Wrap { trim: false }), chunks[1]);
        } else {
            self.scroll.draw(
                f,
                &self.transcript.lines,
                chunks[1],
                &self.selected,
                self.transcript.revision,
            );
        }
        if let Some(a) = approval {
            let options = approval_choices(a)
                .iter()
                .enumerate()
                .map(|(i, c)| format!("Alt+{} {}", i + 1, decision_label(c)))
                .collect::<Vec<_>>()
                .join("  ·  ");
            let text = format!(
                "{}\n{}\nDecisão explícita; não aprova uma release Forge.",
                display(
                    a["params"]["reason"]
                        .as_str()
                        .unwrap_or("O cliente solicita sua decisão")
                ),
                if options.is_empty() {
                    "Solicitação não suportada: bloqueada."
                } else {
                    &options
                }
            );
            f.render_widget(
                Paragraph::new(text)
                    .wrap(Wrap { trim: false })
                    .block(block("Permissão pendente")),
                chunks[2],
            );
        }
        if !matches.is_empty() {
            let rows = matches
                .iter()
                .map(|c| ListItem::new(format!("/{:<12} {}", c.name, c.description)))
                .collect::<Vec<_>>();
            let mut state = ListState::default().with_selected(Some(self.palette_selection));
            f.render_stateful_widget(
                List::new(rows)
                    .block(block("Comandos · ↑/↓ · Tab completa · Enter confirma"))
                    .highlight_symbol("› ")
                    .highlight_style(Style::default().fg(ORANGE).bold()),
                chunks[3],
                &mut state,
            );
        }
        let mut draft = self.editor.text.clone();
        draft.insert(self.editor.cursor, '▏');
        let name = if self.panel == Some(Panel::History) {
            "Busca ativa no painel · Esc volta ao rascunho"
        } else {
            self.mode.editor_label()
        };
        let paragraph = Paragraph::new(draft)
            .wrap(Wrap { trim: false })
            .block(block(name));
        let caret_lines = Paragraph::new(self.editor.text[..self.editor.cursor].to_owned())
            .wrap(Wrap { trim: false })
            .line_count(chunks[4].width.saturating_sub(2));
        let offset = caret_lines
            .saturating_sub(chunks[4].height.saturating_sub(2) as usize)
            .min(u16::MAX as usize) as u16;
        f.render_widget(paragraph.scroll((offset, 0)), chunks[4]);
        let status = if !self.busy.is_empty() {
            busy_label(&self.busy).to_owned()
        } else if !view.connected {
            "Desconectado · /reconnect para reconectar".into()
        } else if view.account["authenticated"] != true {
            "Login necessário no cliente nativo.".into()
        } else if session.is_some_and(|s| !s.loaded) {
            "Sessão salva · /resume para recuperar o histórico.".into()
        } else if approval.is_some() {
            "Aguardando sua decisão".into()
        } else if active {
            let seconds = self
                .active_started
                .map(|s| s.elapsed().as_secs())
                .unwrap_or(0);
            format!(
                "{} Respondendo · {:02}:{:02} · Esc interrompe",
                ['◐', '◓', '◑', '◒'][self.tick % 4],
                seconds / 60,
                seconds % 60
            )
        } else if self.workflow_running {
            "Workflow em execução · /tasks diagnostica · /report mostra evidências".into()
        } else {
            match self.mode {
                modes::Mode::Feature => "Pronto · Feature · planejar → revisar → executar",
                modes::Mode::Qa => "Pronto · QA planejamento · nenhum scan executado",
                modes::Mode::Conversation => {
                    "Pronto · somente leitura · aprovação nativa sob demanda"
                }
            }
            .into()
        };
        let notice = view.error.as_deref().unwrap_or(&self.notice);
        let usage = session
            .and_then(|s| s.usage["total"]["totalTokens"].as_u64())
            .map(|n| format!("{n} tokens observados"))
            .unwrap_or_else(|| "Tokens ainda não observados".into());
        let reading = !self.scroll.following && !self.transcript.lines.is_empty();
        let mut footer = vec![
            Line::styled(
                if reading {
                    "Lendo histórico · Ctrl+End: resposta mais recente".into()
                } else {
                    status
                },
                Style::default().fg(TEAL),
            ),
            Line::styled(
                format!("PgUp/PgDn · rolagem do mouse · F1 ajuda · Ctrl+Q sai · {usage}"),
                Style::default().fg(Color::Gray),
            ),
        ];
        if !notice.is_empty() {
            footer.insert(
                1,
                Line::styled(display(notice), Style::default().fg(ORANGE)),
            );
        }
        f.render_widget(Paragraph::new(footer), chunks[5]);
    }
    fn render_panel(&mut self, f: &mut Frame, panel: Panel, view: &View, root: &Path, area: Rect) {
        if panel == Panel::Activities {
            let lines = self.activity_panel.lines(
                area.width.saturating_sub(2),
                area.height.saturating_sub(2),
                &mut self.panel_scroll,
            );
            f.render_widget(
                Paragraph::new(lines)
                    .wrap(Wrap { trim: false })
                    .scroll((self.panel_scroll, 0))
                    .block(block(
                        "Atividades · chamadas, comandos e arquivos · Esc volta",
                    )),
                area,
            );
            return;
        }
        if panel == Panel::Sessions || panel == Panel::History {
            let rows = if panel == Panel::Sessions {
                view.sessions
                    .values()
                    .map(|s| {
                        format!(
                            "{}{}",
                            display(&s.title),
                            if s.id == self.selected {
                                " · atual"
                            } else {
                                ""
                            }
                        )
                    })
                    .collect::<Vec<_>>()
            } else {
                self.history_matches()
                    .iter()
                    .map(|s| s.replace('\n', " ↵ "))
                    .collect()
            };
            self.panel_selection = self.panel_selection.min(rows.len().saturating_sub(1));
            let name = if panel == Panel::Sessions {
                "Conversas deste projeto · Enter retoma · Esc volta".to_owned()
            } else {
                format!(
                    "Histórico da sessão · buscar: {} · Enter edita",
                    display(&self.history_query)
                )
            };
            let items = if rows.is_empty() {
                vec![ListItem::new("Nenhum resultado nesta sessão.")]
            } else {
                rows.into_iter().map(ListItem::new).collect()
            };
            let mut state = ListState::default().with_selected(Some(self.panel_selection));
            f.render_stateful_widget(
                List::new(items)
                    .block(block(&name))
                    .highlight_symbol("› ")
                    .highlight_style(Style::default().fg(ORANGE).bold()),
                area,
                &mut state,
            );
            return;
        }
        if panel == Panel::Modes {
            let rows = modes::OPTIONS
                .iter()
                .map(|(label, description, mode)| {
                    ListItem::new(vec![
                        Line::styled(
                            *label,
                            Style::default().fg(if mode.is_some() {
                                Color::White
                            } else {
                                Color::DarkGray
                            }),
                        ),
                        Line::from(*description),
                    ])
                })
                .collect::<Vec<_>>();
            let mut state = ListState::default().with_selected(Some(self.panel_selection));
            f.render_stateful_widget(
                List::new(rows)
                    .block(block(
                        "Escolha o modo · ↑/↓ · Enter seleciona · Esc mantém o atual",
                    ))
                    .highlight_symbol("› ")
                    .highlight_style(Style::default().fg(ORANGE).bold()),
                area,
                &mut state,
            );
            return;
        }
        if panel == Panel::Workflow {
            let mut lines = if self.workflow["module"] == "qa" {
                vec![
                    title(if self.workflow["status"] == "planned" {
                        "Planejamento QA legado · não executa"
                    } else {
                        "QA · escopo revisado e evidências observadas"
                    }),
                    Line::from(
                        "Revise argv, inputs, cobertura e lacunas. Enter prepara /qa-run; outro Enter executa. /qa-status [ID] consulta. Esc volta ao editor.",
                    ),
                ]
            } else {
                vec![
                    title("Plano, execução e evidências"),
                    Line::from("PgUp/PgDn percorrem o escopo. Esc volta ao editor."),
                    Line::from(
                        "/run DIGEST confirma o escopo; /tasks ID diagnostica; /tasks resume ID retoma.",
                    ),
                    Line::from(
                        "Plano preparado: Enter leva a autorização ao editor; outro Enter executa.",
                    ),
                ]
            };
            if let Some(request) = self
                .workflow
                .get("candidate")
                .and_then(|c| c.get("request"))
            {
                lines.push(title(request["title"].as_str().unwrap_or("Escopo")));
                let bug = &request["proposal"]["bug"];
                for (label, value) in [
                    ("Esperado", &bug["expected"]),
                    ("Reprodução", &bug["reproduction"]),
                ] {
                    if let Some(text) = value.as_str() {
                        lines.push(Line::from(format!("{label}: {text}")));
                    }
                }
                if let Some(files) = bug["planned_files"].as_array() {
                    lines.push(Line::from(format!(
                        "Arquivos previstos: {}",
                        files
                            .iter()
                            .filter_map(serde_json::Value::as_str)
                            .collect::<Vec<_>>()
                            .join(", ")
                    )));
                }
                lines.push(Line::from(if self.workflow["module"] == "qa" {
                    "QA: comandos revisados podem escrever. Alteração de fonte bloqueia aceite, sem restauração. Sem chamada nativa ou sandbox somente leitura."
                } else {
                    "Permissão: escrita no projeto pelo cliente nativo. Sem commit ou publicação."
                }));
                if let Some(checks) = request["checks"].as_array() {
                    for check in checks {
                        lines.push(Line::from(format!(
                            "Verificação {} · cobertura {}: {}",
                            check["id"].as_str().unwrap_or(""),
                            check["coverage_id"].as_str().unwrap_or("critério Feature"),
                            check["argv"]
                        )));
                    }
                }
                if let Some(files) = request["files"].as_object() {
                    for (name, body) in files {
                        lines.push(Line::from(format!("Verificador externo congelado: {name}")));
                        lines.extend(
                            body.as_str()
                                .unwrap_or("")
                                .lines()
                                .map(|line| Line::from(line.to_owned())),
                        );
                    }
                }
                if let Some(digest) = self.workflow["scope_digest"].as_str() {
                    let command = if self.workflow["module"] == "qa" {
                        "qa-run"
                    } else {
                        "run"
                    };
                    lines.push(Line::from(format!("Após revisar: /{command} {digest}")));
                }
                lines.push(Line::from("Contrato completo e evidências:"));
            }
            lines.extend(
                display(&serde_json::to_string_pretty(&self.workflow).unwrap_or_default())
                    .lines()
                    .map(|s| Line::from(s.to_owned())),
            );
            for line in &mut lines {
                for span in &mut line.spans {
                    span.content = display(&span.content).into();
                }
            }
            f.render_widget(
                Paragraph::new(lines)
                    .wrap(Wrap { trim: false })
                    .scroll((self.panel_scroll, 0)),
                area,
            );
            return;
        }
        let lines = if panel == Panel::Help {
            let mut lines = vec![
                title("Ajuda do Forge"),
                Line::from(
                    "F3 ou /mode escolhe o modo. Feature planeja; a execução exige revisar e confirmar o plano.",
                ),
                Line::from("Esc fecha este painel. Nenhum comando é enviado ao modelo."),
                Line::default(),
                title("Conversa e edição"),
            ];
            for text in [
                "Enter envia · Ctrl+J / Alt+Enter insere nova linha",
                "↑/↓ recuperam pedidos quando o rascunho tem uma linha",
                "Ctrl+R busca pedidos · Shift+seleção copia no terminal",
                "Ctrl+A/E início/fim da linha · Ctrl+W apaga palavra",
                "Ctrl+U/K recorta antes/depois do cursor · Ctrl+Y recupera",
                "Ctrl+C limpa com recuperação por Ctrl+Y; Esc interrompe turno",
                "Mouse/PgUp/PgDn: histórico · Ctrl+Home/End: início/fim",
                "Ctrl+O expande atividades · Ctrl+Q sai",
                "F2 / /activities: ↑/↓ selecionam, Enter/Espaço alternam detalhes",
                "No painel: ←/→ recolhem/expandem cada chamada ou arquivo",
            ] {
                lines.push(Line::from(text));
            }
            lines.push(Line::default());
            lines.push(title("Comandos disponíveis"));
            lines.extend(
                COMMANDS
                    .iter()
                    .map(|c| Line::from(format!("/{:<12} {}", c.name, c.description))),
            );
            lines.push(Line::default());
            lines.push(Line::from(
                "Interromper não garante encerrar terminais nativos em segundo plano.",
            ));
            lines
        } else {
            let session = view.sessions.get(&self.selected);
            let total = session.map(|s| &s.usage["total"]);
            vec![
                title("Status da sessão"),
                Line::from(format!("Projeto: {}", display(&root.to_string_lossy()))),
                Line::from(format!(
                    "Conexão: {}",
                    if view.connected {
                        "conectado"
                    } else {
                        "desconectado"
                    }
                )),
                Line::from(format!(
                    "Conta nativa: {}",
                    if view.account["authenticated"] == true {
                        "autenticada"
                    } else {
                        "não verificada"
                    }
                )),
                Line::from(format!(
                    "Modelo: {}",
                    display(
                        session
                            .and_then(|s| s.effective["model"].as_str())
                            .unwrap_or("configuração nativa; ainda não observado")
                    )
                )),
                Line::from("Permissões: somente leitura; aprovação nativa sob demanda"),
                Line::from(format!(
                    "Sessão: {}",
                    session
                        .map(|s| display(&s.title))
                        .unwrap_or_else(|| "ainda não criada".into())
                )),
                Line::default(),
                title("Tokens observados"),
                Line::from(format!(
                    "Entrada: {}",
                    total
                        .map(|t| metric(&t["inputTokens"]))
                        .unwrap_or_else(|| "não observado".into())
                )),
                Line::from(format!(
                    "Cache incluído na entrada: {}",
                    total
                        .map(|t| metric(&t["cachedInputTokens"]))
                        .unwrap_or_else(|| "não observado".into())
                )),
                Line::from(format!(
                    "Saída: {}",
                    total
                        .map(|t| metric(&t["outputTokens"]))
                        .unwrap_or_else(|| "não observado".into())
                )),
                Line::from(format!(
                    "Total: {}",
                    total
                        .map(|t| metric(&t["totalTokens"]))
                        .unwrap_or_else(|| "não observado".into())
                )),
                Line::default(),
                Line::from("Ausência não significa zero; não é saldo da assinatura ou custo."),
                Line::from("Chat e permissões de ferramentas não aprovam gates Forge."),
                Line::from("Esc volta à conversa."),
            ]
        };
        // Informational panels start at the top; PageDown advances toward the end.
        let paragraph = Paragraph::new(lines).wrap(Wrap { trim: false });
        f.render_widget(
            paragraph
                .scroll((self.panel_scroll, 0))
                .block(block(if panel == Panel::Help {
                    "Ajuda · PgUp/PgDn"
                } else {
                    "Status · PgUp/PgDn"
                })),
            area,
        );
    }
}