up-cc 0.5.2 → 0.7.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.
@@ -18,13 +18,18 @@ Voce NAO cria planos. Voce AVALIA planos contra criterios objetivos.
18
18
  Voce e **critico por design**. Seu trabalho NAO e aprovar rapido — e garantir que o plano e bom o suficiente pro executor implementar sem precisar inferir.
19
19
 
20
20
  **CRITICO: Leitura Inicial Obrigatoria**
21
- 1. `$HOME/.claude/up/references/governance-rules.md`
22
- 2. `$HOME/.claude/up/references/engineering-principles.md`
23
- 3. `$HOME/.claude/up/references/rework-limits.md`
24
- 4. `.plano/REQUIREMENTS.md`
25
- 5. `.plano/SYSTEM-DESIGN.md`
26
- 6. `.plano/CHECKLIST.md`
27
- 7. O(s) PLAN.md em analise (passados no prompt)
21
+
22
+ Versoes COMPRIMIDAS de governance/engineering/rework sao injetadas no proprio prompt do workflow (~700 tokens vs 7700). NAO carregue os arquivos full por padrao.
23
+
24
+ Leitura obrigatoria do disco:
25
+ 1. O(s) PLAN.md em analise (passados no prompt)
26
+ 2. `.plano/CHECKLIST.md` (estado dos planos)
27
+ 3. Apenas a SECAO relevante de REQUIREMENTS/SYSTEM-DESIGN — use `.plano/fases/{N}/REQUIREMENTS-SLICE.md` se existir, senao Read seletivo
28
+
29
+ Leitura sob demanda (so se decisao precisa de detalhe):
30
+ - `references/engineering-principles.md` — exemplos completos
31
+ - `references/governance-rules.md` — hierarquia detalhada
32
+ - `references/rework-limits.md` — fluxos por ciclo
28
33
  </role>
29
34
 
30
35
  <criteria>
@@ -13,10 +13,15 @@ Supervisiona: `up-product-analyst`, `up-pesquisador-projeto`, `up-pesquisador-me
13
13
  Garante que pesquisas sao rigorosas e relevantes pro briefing.
14
14
 
15
15
  **CRITICO: Leitura Inicial Obrigatoria**
16
- 1. `$HOME/.claude/up/references/governance-rules.md`
17
- 2. `.plano/BRIEFING.md`
18
- 3. `.plano/OWNER.md`
19
- 4. Outputs do agente em avaliacao
16
+
17
+ Governance rules vem injetado no prompt do workflow em forma comprimida (~250 tokens vs 1.9k). NAO carregue o arquivo full por padrao.
18
+
19
+ Leitura obrigatoria do disco:
20
+ 1. `.plano/BRIEFING.md`
21
+ 2. `.plano/OWNER.md`
22
+ 3. Outputs do agente em avaliacao
23
+
24
+ Leitura sob demanda: `references/governance-rules.md` se precisar de hierarquia detalhada.
20
25
  </role>
21
26
 
22
27
  <criteria>
@@ -13,12 +13,17 @@ Supervisiona: `up-visual-critic`, `up-exhaustive-tester`, `up-api-tester`, `up-q
13
13
  Seu trabalho: consolidar os relatorios dos detectores, validar severidade das issues, e aprovar ou pedir re-deteccao.
14
14
 
15
15
  **CRITICO: Leitura Inicial Obrigatoria**
16
- 1. `$HOME/.claude/up/references/governance-rules.md`
17
- 2. VISUAL-REPORT.md
18
- 3. EXHAUSTIVE-REPORT.md
19
- 4. API-REPORT.md
20
- 5. QA-REPORT.md (se rodou)
21
- 6. `.plano/DESIGN-TOKENS.md`
16
+
17
+ Governance rules vem injetado no prompt do workflow em forma comprimida. NAO carregue o arquivo full por padrao.
18
+
19
+ Leitura obrigatoria do disco:
20
+ 1. VISUAL-REPORT.md
21
+ 2. EXHAUSTIVE-REPORT.md
22
+ 3. API-REPORT.md
23
+ 4. QA-REPORT.md (se rodou)
24
+ 5. `.plano/DESIGN-TOKENS.md`
25
+
26
+ Leitura sob demanda: `references/governance-rules.md` se precisar de detalhe.
22
27
  </role>
23
28
 
24
29
  <criteria>
@@ -13,12 +13,17 @@ Supervisiona: `up-verificador`, `up-blind-validator`.
13
13
  Seu trabalho NAO e verificar o codigo — e verificar se a VERIFICACAO foi feita corretamente.
14
14
 
15
15
  **CRITICO: Leitura Inicial Obrigatoria**
16
- 1. `$HOME/.claude/up/references/governance-rules.md`
17
- 2. VERIFICATION.md (output do verificador)
18
- 3. BLIND-VALIDATION.md (se rodou)
19
- 4. E2E-RESULTS.md (se rodou)
20
- 5. DCRV reports (se rodaram)
21
- 6. REQUIREMENTS.md (para cross-check)
16
+
17
+ Governance rules vem injetado no prompt do workflow em forma comprimida. NAO carregue o arquivo full por padrao.
18
+
19
+ Leitura obrigatoria do disco:
20
+ 1. VERIFICATION.md (output do verificador)
21
+ 2. BLIND-VALIDATION.md (se rodou)
22
+ 3. E2E-RESULTS.md (se rodou)
23
+ 4. DCRV reports (se rodaram)
24
+ 5. REQUIREMENTS.md — preferir slice da fase: `.plano/fases/{N}/REQUIREMENTS-SLICE.md` se existir
25
+
26
+ Leitura sob demanda: `references/governance-rules.md` se precisar de detalhe.
22
27
  </role>
23
28
 
24
29
  <criteria>
@@ -0,0 +1,333 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * UP Instrumentation — measures token usage per UP agent
5
+ *
6
+ * Reads Claude Code session.jsonl + subagent jsonls and produces a token cost
7
+ * report grouped by agent. Used to identify the heaviest agents (so we know
8
+ * where to apply tiered context optimizations) and to give users visibility
9
+ * into the cost of a build.
10
+ *
11
+ * Usage:
12
+ * node up-instrument.cjs report # current project, current session
13
+ * node up-instrument.cjs report --all-sessions # current project, all sessions
14
+ * node up-instrument.cjs report --json # JSON output
15
+ * node up-instrument.cjs watch # write .plano/INSTRUMENTATION.md continuously
16
+ *
17
+ * Opt-in via /up:configurar (instrumentation.enabled = true).
18
+ * Default: off.
19
+ *
20
+ * NOTE: Only works with Claude Code runtime (reads ~/.claude/projects).
21
+ * OpenCode and Gemini CLI use different log formats — falls back gracefully.
22
+ */
23
+
24
+ const fs = require('fs');
25
+ const path = require('path');
26
+ const os = require('os');
27
+
28
+ const HOME = os.homedir();
29
+ const CLAUDE_PROJECTS = path.join(HOME, '.claude', 'projects');
30
+
31
+ // Convert /home/projects/up-cc → -home-projects-up-cc
32
+ function projectKey(cwd) {
33
+ return cwd.replace(/^\//, '').replace(/\//g, '-').replace(/^/, '-');
34
+ }
35
+
36
+ function listSessions(projectDir) {
37
+ if (!fs.existsSync(projectDir)) return [];
38
+ return fs
39
+ .readdirSync(projectDir, { withFileTypes: true })
40
+ .filter((d) => d.isDirectory())
41
+ .map((d) => path.join(projectDir, d.name));
42
+ }
43
+
44
+ function listJsonls(sessionDir) {
45
+ const files = [];
46
+ const walk = (dir) => {
47
+ if (!fs.existsSync(dir)) return;
48
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
49
+ const full = path.join(dir, entry.name);
50
+ if (entry.isDirectory()) walk(full);
51
+ else if (entry.name.endsWith('.jsonl')) files.push(full);
52
+ }
53
+ };
54
+ walk(sessionDir);
55
+ return files;
56
+ }
57
+
58
+ function parseJsonl(file) {
59
+ const events = [];
60
+ let raw;
61
+ try {
62
+ raw = fs.readFileSync(file, 'utf8');
63
+ } catch {
64
+ return events;
65
+ }
66
+ for (const line of raw.split('\n')) {
67
+ if (!line.trim()) continue;
68
+ try {
69
+ events.push(JSON.parse(line));
70
+ } catch {
71
+ // skip malformed
72
+ }
73
+ }
74
+ return events;
75
+ }
76
+
77
+ // Build canonical list of UP agent names from agents/ directory.
78
+ // This gives us ground truth and avoids false matches like "up-hover" or "up-load".
79
+ function loadUpAgentNames() {
80
+ const candidates = [
81
+ path.join(__dirname, '..', 'agents'),
82
+ path.join(__dirname, '..', 'up', 'agents'),
83
+ path.join(HOME, '.claude', 'up', 'agents'),
84
+ path.join(HOME, '.claude', 'agents'),
85
+ ];
86
+ const names = new Set();
87
+ for (const dir of candidates) {
88
+ if (!fs.existsSync(dir)) continue;
89
+ for (const f of fs.readdirSync(dir)) {
90
+ if (f.startsWith('up-') && f.endsWith('.md')) {
91
+ names.add(f.replace(/\.md$/, ''));
92
+ }
93
+ }
94
+ }
95
+ return names;
96
+ }
97
+
98
+ const KNOWN_UP_AGENTS = loadUpAgentNames();
99
+
100
+ // Extract agent name from a subagent jsonl path or first event.
101
+ // Subagent files live in <session>/subagents/agent-<id>.jsonl.
102
+ function detectAgentName(events, file) {
103
+ // Strategy 1: scan events for known UP agent names in content
104
+ for (const ev of events.slice(0, 5)) {
105
+ const c = ev?.message?.content;
106
+ let text = '';
107
+ if (typeof c === 'string') text = c;
108
+ else if (Array.isArray(c)) {
109
+ text = c
110
+ .map((item) => (typeof item === 'string' ? item : item?.text || ''))
111
+ .join(' ');
112
+ }
113
+ if (!text) continue;
114
+
115
+ // Match against canonical UP agent names
116
+ for (const name of KNOWN_UP_AGENTS) {
117
+ if (text.includes(name)) return name;
118
+ }
119
+
120
+ // Match "Voce e o {something}" pattern from UP role definitions
121
+ const roleMatch = text.match(/Voce e o ([A-Z][a-zA-Z ]+?)( UP|\.|,|\n)/);
122
+ if (roleMatch) {
123
+ const role = roleMatch[1].trim().toLowerCase().replace(/\s+/g, '-');
124
+ const candidate = `up-${role}`;
125
+ if (KNOWN_UP_AGENTS.has(candidate)) return candidate;
126
+ }
127
+ }
128
+
129
+ // Strategy 2: top-level fields
130
+ for (const ev of events.slice(0, 3)) {
131
+ if (ev?.subagent_type && ev.subagent_type.startsWith('up-')) {
132
+ return ev.subagent_type;
133
+ }
134
+ if (ev?.slug && ev.slug.startsWith('up-') && KNOWN_UP_AGENTS.has(ev.slug)) {
135
+ return ev.slug;
136
+ }
137
+ }
138
+
139
+ // Strategy 3: file id fallback (grouped under "non-up" so we don't pollute UP stats)
140
+ const m = file.match(/agent-([a-z0-9]+)\.jsonl$/);
141
+ return m ? `non-up-agent` : 'unknown';
142
+ }
143
+
144
+ function aggregateUsage(events) {
145
+ let input = 0;
146
+ let cacheCreation = 0;
147
+ let cacheRead = 0;
148
+ let output = 0;
149
+ let calls = 0;
150
+ for (const ev of events) {
151
+ const u = ev?.message?.usage || ev?.usage;
152
+ if (!u) continue;
153
+ input += u.input_tokens || 0;
154
+ cacheCreation += u.cache_creation_input_tokens || 0;
155
+ cacheRead += u.cache_read_input_tokens || 0;
156
+ output += u.output_tokens || 0;
157
+ calls += 1;
158
+ }
159
+ return { input, cacheCreation, cacheRead, output, calls };
160
+ }
161
+
162
+ // Opus 4.6 1M pricing (rough): input $15/M, output $75/M, cache write $18.75/M, cache read $1.50/M
163
+ function estimateCost(usage) {
164
+ const PRICE = {
165
+ input: 15 / 1_000_000,
166
+ cacheCreation: 18.75 / 1_000_000,
167
+ cacheRead: 1.5 / 1_000_000,
168
+ output: 75 / 1_000_000,
169
+ };
170
+ return (
171
+ usage.input * PRICE.input +
172
+ usage.cacheCreation * PRICE.cacheCreation +
173
+ usage.cacheRead * PRICE.cacheRead +
174
+ usage.output * PRICE.output
175
+ );
176
+ }
177
+
178
+ function formatNumber(n) {
179
+ if (n >= 1_000_000) return (n / 1_000_000).toFixed(2) + 'M';
180
+ if (n >= 1_000) return (n / 1_000).toFixed(1) + 'k';
181
+ return String(n);
182
+ }
183
+
184
+ function buildReport(opts = {}) {
185
+ const cwd = opts.cwd || process.cwd();
186
+ const projectDir = path.join(CLAUDE_PROJECTS, projectKey(cwd));
187
+ const sessions = listSessions(projectDir);
188
+ if (sessions.length === 0) {
189
+ return { error: 'no_sessions', message: `No Claude Code sessions found for ${cwd}. Are you running in Claude Code runtime?` };
190
+ }
191
+
192
+ const targetSessions = opts.allSessions ? sessions : [sessions[sessions.length - 1]];
193
+ const byAgent = new Map();
194
+ const filesScanned = [];
195
+
196
+ for (const sessionDir of targetSessions) {
197
+ const subagentDir = path.join(sessionDir, 'subagents');
198
+ const files = listJsonls(subagentDir);
199
+ for (const file of files) {
200
+ filesScanned.push(file);
201
+ const events = parseJsonl(file);
202
+ const name = detectAgentName(events, file);
203
+ const usage = aggregateUsage(events);
204
+ const prev = byAgent.get(name) || { input: 0, cacheCreation: 0, cacheRead: 0, output: 0, calls: 0, invocations: 0 };
205
+ prev.input += usage.input;
206
+ prev.cacheCreation += usage.cacheCreation;
207
+ prev.cacheRead += usage.cacheRead;
208
+ prev.output += usage.output;
209
+ prev.calls += usage.calls;
210
+ prev.invocations += 1;
211
+ byAgent.set(name, prev);
212
+ }
213
+ }
214
+
215
+ const rows = [];
216
+ let totalCost = 0;
217
+ let totalInput = 0;
218
+ let totalOutput = 0;
219
+ for (const [agent, u] of byAgent.entries()) {
220
+ const cost = estimateCost(u);
221
+ totalCost += cost;
222
+ totalInput += u.input + u.cacheCreation + u.cacheRead;
223
+ totalOutput += u.output;
224
+ rows.push({
225
+ agent,
226
+ invocations: u.invocations,
227
+ input: u.input + u.cacheCreation + u.cacheRead,
228
+ output: u.output,
229
+ cost,
230
+ avgPerInvoc: u.invocations > 0 ? (u.input + u.cacheCreation + u.cacheRead) / u.invocations : 0,
231
+ });
232
+ }
233
+ rows.sort((a, b) => b.cost - a.cost);
234
+
235
+ return {
236
+ cwd,
237
+ sessions: targetSessions.length,
238
+ files_scanned: filesScanned.length,
239
+ total_input_tokens: totalInput,
240
+ total_output_tokens: totalOutput,
241
+ total_cost_usd: totalCost,
242
+ agents: rows,
243
+ };
244
+ }
245
+
246
+ function renderMarkdown(report) {
247
+ if (report.error) return `# Instrumentation\n\n${report.message}\n`;
248
+ const lines = [];
249
+ lines.push('# Token Instrumentation');
250
+ lines.push('');
251
+ lines.push(`Project: \`${report.cwd}\``);
252
+ lines.push(`Sessions analyzed: ${report.sessions}`);
253
+ lines.push(`Subagent files scanned: ${report.files_scanned}`);
254
+ lines.push('');
255
+ lines.push('## Totals');
256
+ lines.push(`- Input tokens: **${formatNumber(report.total_input_tokens)}**`);
257
+ lines.push(`- Output tokens: **${formatNumber(report.total_output_tokens)}**`);
258
+ lines.push(`- Estimated cost (Opus 4.6 pricing): **$${report.total_cost_usd.toFixed(2)}**`);
259
+ lines.push('');
260
+ lines.push('## Top agents by cost');
261
+ lines.push('');
262
+ lines.push('| Agent | Invocations | Input | Avg/invoc | Output | Cost |');
263
+ lines.push('|---|---:|---:|---:|---:|---:|');
264
+ for (const row of report.agents.slice(0, 20)) {
265
+ lines.push(
266
+ `| ${row.agent} | ${row.invocations} | ${formatNumber(row.input)} | ${formatNumber(row.avgPerInvoc)} | ${formatNumber(row.output)} | $${row.cost.toFixed(2)} |`
267
+ );
268
+ }
269
+ lines.push('');
270
+ lines.push(`> Generated by \`up-instrument\` at ${new Date().toISOString()}`);
271
+ lines.push('> Pricing assumes Claude Opus 4.6 1M context. Real cost may vary.');
272
+ return lines.join('\n') + '\n';
273
+ }
274
+
275
+ function renderTable(report) {
276
+ if (report.error) return report.message;
277
+ const lines = [];
278
+ lines.push(`Project: ${report.cwd}`);
279
+ lines.push(`Sessions: ${report.sessions} Files: ${report.files_scanned}`);
280
+ lines.push(`Total: ${formatNumber(report.total_input_tokens)} in / ${formatNumber(report.total_output_tokens)} out / $${report.total_cost_usd.toFixed(2)}`);
281
+ lines.push('');
282
+ lines.push('Top agents:');
283
+ for (const row of report.agents.slice(0, 15)) {
284
+ const pad = (s, n) => String(s).padEnd(n);
285
+ lines.push(` ${pad(row.agent, 30)} ${pad(row.invocations + 'x', 6)} ${pad(formatNumber(row.input), 8)} avg ${pad(formatNumber(row.avgPerInvoc), 8)} $${row.cost.toFixed(2)}`);
286
+ }
287
+ return lines.join('\n');
288
+ }
289
+
290
+ // CLI
291
+ const args = process.argv.slice(2);
292
+ const cmd = args[0] || 'report';
293
+ const opts = {
294
+ allSessions: args.includes('--all-sessions'),
295
+ json: args.includes('--json'),
296
+ cwd: process.cwd(),
297
+ };
298
+
299
+ if (cmd === 'report') {
300
+ const report = buildReport(opts);
301
+ if (opts.json) {
302
+ console.log(JSON.stringify(report, null, 2));
303
+ } else {
304
+ console.log(renderTable(report));
305
+ }
306
+ } else if (cmd === 'write') {
307
+ const report = buildReport(opts);
308
+ const planoDir = path.join(opts.cwd, '.plano');
309
+ if (!fs.existsSync(planoDir)) {
310
+ console.error('No .plano directory found in current cwd. Run from a UP project root.');
311
+ process.exit(1);
312
+ }
313
+ const outFile = path.join(planoDir, 'INSTRUMENTATION.md');
314
+ fs.writeFileSync(outFile, renderMarkdown(report));
315
+ console.log(`Wrote ${outFile}`);
316
+ } else if (cmd === '--help' || cmd === 'help') {
317
+ console.log(`up-instrument — token usage measurement for UP agents
318
+
319
+ Commands:
320
+ report Print top agents by cost (default, current session)
321
+ report --all-sessions Same but across all sessions for current project
322
+ report --json JSON output
323
+ write Write .plano/INSTRUMENTATION.md (current session)
324
+ write --all-sessions Write report across all sessions
325
+
326
+ Notes:
327
+ - Only works with Claude Code (reads ~/.claude/projects/<key>/subagents/*.jsonl)
328
+ - OpenCode and Gemini CLI use different log formats and are not supported yet
329
+ - Pricing assumes Claude Opus 4.6 1M context — real cost may vary`);
330
+ } else {
331
+ console.error(`Unknown command: ${cmd}. Try 'help'.`);
332
+ process.exit(1);
333
+ }
@@ -0,0 +1,99 @@
1
+ ---
2
+ name: up:build
3
+ description: Executar projeto previamente planejado por /up:plan. Requer PLAN-READY.md. Pode rodar em runtime diferente do que planejou.
4
+ argument-hint: ""
5
+ allowed-tools:
6
+ - Read
7
+ - Write
8
+ - Edit
9
+ - Glob
10
+ - Grep
11
+ - Bash
12
+ - Task
13
+ - AskUserQuestion
14
+ - mcp__plugin_playwright_playwright__*
15
+ ---
16
+ <objective>
17
+ Executar projeto que foi previamente planejado.
18
+
19
+ Requer `.plano/PLAN-READY.md` no diretorio atual.
20
+
21
+ Conduz:
22
+ 1. Validacao light do plano (artefatos existem, planos OK)
23
+ 2. CEO local confirma execucao
24
+ 3. Build de todas as fases (com supervisao completa)
25
+ 4. Quality Gate global
26
+ 5. Delivery Audit
27
+ 6. CEO apresenta resultado
28
+
29
+ **Caso de uso principal:** executar projeto planejado em outro runtime.
30
+ Exemplo: planejou em Claude Code (`/up:plan "X"`), agora roda em OpenCode (`/up-build`).
31
+
32
+ **Re-plan local permitido (max 2):** se durante execucao o supervisor descobrir
33
+ que o plano esta inviavel, o planejador LOCAL refaz a fase. Nao volta pro runtime
34
+ que planejou originalmente.
35
+
36
+ Diferenca de /up:modo-builder:
37
+ - modo-builder: planeja + executa em sequencia
38
+ - build: SO executa, le PLAN-READY.md
39
+
40
+ Diferenca de /up:executar-fase:
41
+ - executar-fase: executa UMA fase
42
+ - build: executa o PROJETO INTEIRO ate delivery
43
+ </objective>
44
+
45
+ <execution_context>
46
+ @~/.claude/up/workflows/build.md
47
+ @~/.claude/up/workflows/governance.md
48
+ @~/.claude/up/workflows/dcrv.md
49
+ @~/.claude/up/workflows/builder-e2e.md
50
+ </execution_context>
51
+
52
+ <context>
53
+ $ARGUMENTS
54
+
55
+ Sem argumentos. O comando le tudo de `.plano/PLAN-READY.md`.
56
+ </context>
57
+
58
+ <process>
59
+ **GATE 1 — Owner Profile LOCAL:**
60
+ Verificar se `~/.claude/up/owner-profile.md` existe NESTE runtime.
61
+ Se nao: rodar `/up:onboard` primeiro.
62
+
63
+ **GATE 2 — PLAN-READY.md:**
64
+ ```bash
65
+ if [ ! -f .plano/PLAN-READY.md ]; then
66
+ echo "ERRO: Este projeto nao foi planejado."
67
+ echo "Use /up:plan primeiro pra planejar."
68
+ echo "Ou /up:modo-builder pra planejar e executar de uma vez."
69
+ exit 1
70
+ fi
71
+ ```
72
+
73
+ **GATE 3 — Validacao Light:**
74
+ Spot-check estrutura:
75
+ - Artefatos arquiteturais existem (PROJECT, ROADMAP, REQUIREMENTS, SYSTEM-DESIGN)?
76
+ - Todos planos listados em PLAN-READY.md existem no disco?
77
+ - Frontmatter dos planos e valido?
78
+
79
+ **Confiar no PLAN-READY.md.** NAO re-rodar planning-supervisor em tudo.
80
+
81
+ Se algo falta: alertar e oferecer planejamento local OU abortar.
82
+
83
+ **Sem model routing:** O runtime decide o modelo.
84
+
85
+ **Execute the build workflow from @~/.claude/up/workflows/build.md end-to-end.**
86
+
87
+ Estagios:
88
+ 1. Validacao light + CEO confirma
89
+ 2. Build (loop por fase com supervisao + DCRV + E2E + chief-engineer)
90
+ 3. Quality Gate global
91
+ 4. Delivery Audit
92
+ 5. Delivery (CEO apresenta)
93
+
94
+ **Re-plan local permitido (max 2 por projeto):**
95
+ Se execution-supervisor pedir REQUEST_REPLAN, o planejador LOCAL refaz a fase.
96
+ Registrar em `.plano/governance/replans.log`.
97
+
98
+ **A partir do CEO confirmar, ZERO interacao com usuario** (exceto alertas criticos).
99
+ </process>
@@ -0,0 +1,67 @@
1
+ ---
2
+ name: up:custos
3
+ description: Mostra estimativa de custo em tokens dos agentes UP usados no projeto atual (Claude Code only)
4
+ allowed-tools:
5
+ - Bash
6
+ - Read
7
+ ---
8
+
9
+ <objective>
10
+ Reportar custo estimado de tokens consumidos por agentes UP no projeto atual.
11
+ Usa `bin/up-instrument.cjs` para parsear `~/.claude/projects/<key>/subagents/*.jsonl`
12
+ e agregar uso por agente.
13
+ </objective>
14
+
15
+ <process>
16
+
17
+ ## 1. Detectar runtime
18
+
19
+ ```bash
20
+ if [ ! -d "$HOME/.claude/projects" ]; then
21
+ echo "Instrumentation requer Claude Code runtime."
22
+ echo "OpenCode e Gemini CLI usam formatos de log diferentes (nao suportado ainda)."
23
+ exit 0
24
+ fi
25
+ ```
26
+
27
+ ## 2. Rodar relatorio
28
+
29
+ ```bash
30
+ # Default: sessao mais recente
31
+ node "$HOME/.claude/up/bin/up-instrument.cjs" report
32
+
33
+ # Se quiser todas as sessoes do projeto:
34
+ # node "$HOME/.claude/up/bin/up-instrument.cjs" report --all-sessions
35
+
36
+ # Se quiser JSON:
37
+ # node "$HOME/.claude/up/bin/up-instrument.cjs" report --json
38
+ ```
39
+
40
+ ## 3. Salvar em .plano/INSTRUMENTATION.md (opcional)
41
+
42
+ Se a flag `--save` foi passada OU se .plano/ existe:
43
+
44
+ ```bash
45
+ if [ -d ".plano" ]; then
46
+ node "$HOME/.claude/up/bin/up-instrument.cjs" write
47
+ echo ""
48
+ echo "Relatorio salvo em .plano/INSTRUMENTATION.md"
49
+ fi
50
+ ```
51
+
52
+ ## 4. Apresentar interpretacao
53
+
54
+ Apos mostrar a tabela, comentar:
55
+
56
+ - **Top 3 agentes mais caros** — onde focar otimizacao
57
+ - **Total estimado** — em USD assumindo Opus 4.6 pricing
58
+ - **Comparacao com outras sessoes** se historico disponivel
59
+
60
+ </process>
61
+
62
+ <notes>
63
+ - Pricing assume Opus 4.6 1M context: input $15/M, output $75/M, cache write $18.75/M, cache read $1.50/M
64
+ - Custos reais podem variar conforme modelo selecionado no /model
65
+ - Apenas funciona em Claude Code — OpenCode e Gemini CLI nao expoe usage por subagent ainda
66
+ - Detecta agentes UP cruzando contra a lista canonica em `agents/up-*.md`
67
+ </notes>
@@ -0,0 +1,91 @@
1
+ ---
2
+ name: up:plan
3
+ description: Planejamento completo de projeto. Gera PLAN-READY.md pronto pra ser executado por /up:build (mesmo runtime ou outro)
4
+ argument-hint: "[descricao do projeto] [--execution-runtime=runtime] [--no-audit]"
5
+ allowed-tools:
6
+ - Read
7
+ - Write
8
+ - Edit
9
+ - Glob
10
+ - Grep
11
+ - Bash
12
+ - Task
13
+ - WebFetch
14
+ - WebSearch
15
+ - AskUserQuestion
16
+ - mcp__context7__*
17
+ ---
18
+ <objective>
19
+ Planejar projeto completo. NAO executa nada, so planeja.
20
+
21
+ Conduz:
22
+ 1. Intake (CEO entrevista o dono)
23
+ 2. Arquitetura completa (Product Analyst → System Designer → Arquiteto)
24
+ 3. Planejamento exaustivo de TODAS as fases (Sonnet-ready)
25
+ 4. Planning Audit (calcula confidence score)
26
+ 5. Gera PLAN-READY.md (arquivo-flag pra /up:build)
27
+
28
+ Resultado: projeto pronto pra execucao em qualquer runtime via `/up:build`.
29
+
30
+ **Caso de uso principal:** planejar em Claude Code (modelo capaz pra arquitetura)
31
+ e executar em OpenCode/Gemini (mais barato pra rodar volume).
32
+
33
+ Diferenca de /up:modo-builder:
34
+ - modo-builder: planeja + executa em sequencia, mesmo runtime
35
+ - plan: SO planeja, para apos PLAN-READY.md
36
+
37
+ Diferenca de /up:planejar-fase:
38
+ - planejar-fase: planeja UMA fase (em projeto ja inicializado)
39
+ - plan: planeja TODO o projeto do zero (incluindo intake e arquitetura)
40
+ </objective>
41
+
42
+ <execution_context>
43
+ @~/.claude/up/workflows/plan.md
44
+ @~/.claude/up/workflows/onboarding.md
45
+ @~/.claude/up/workflows/ceo-intake.md
46
+ @~/.claude/up/templates/plan-ready.md
47
+ @~/.claude/up/templates/audit-plan.md
48
+ </execution_context>
49
+
50
+ <context>
51
+ $ARGUMENTS
52
+
53
+ **Flags:**
54
+ - `--execution-runtime=<runtime>` — Informa qual runtime sera usado pra executar.
55
+ Valores: same | claude-code | opencode | gemini-cli | any
56
+ Default: same
57
+ - `--no-audit` — Pula Planning Audit (nao recomendado em producao)
58
+
59
+ O restante e o briefing em texto livre.
60
+
61
+ Se briefing vazio: CEO pergunta interativamente.
62
+
63
+ **Deteccao automatica de modo:**
64
+ - Codigo existente → BROWNFIELD
65
+ - Sem codigo → GREENFIELD
66
+ </context>
67
+
68
+ <process>
69
+ **GATE OBRIGATORIO — Owner Profile:**
70
+ Antes de qualquer coisa, verificar se `~/.claude/up/owner-profile.md` existe.
71
+ Se NAO existir: rodar `/up:onboard` primeiro (workflow onboarding.md).
72
+ Sem profile, o CEO nao pode conduzir intake.
73
+
74
+ **Sem model routing:** O runtime decide o modelo. NAO especificar `model=` em nenhum spawn.
75
+
76
+ **Sonnet-ready obrigatorio:** Todos planos devem ser gerados em nivel maximo de detalhe.
77
+
78
+ **Execute the plan workflow from @~/.claude/up/workflows/plan.md end-to-end.**
79
+
80
+ Estagios:
81
+ 1. Intake (CEO entrevista o dono) — interativo
82
+ 2. Arquitetura (greenfield: pesquisa + product/system/architect | brownfield: mapear + product/system/architect)
83
+ 3. Planejamento exaustivo (TODAS as fases, planning-supervisor revisa cada uma)
84
+ 4. Planning Audit (planning-auditor calcula confidence score)
85
+ 5. PLAN-READY.md gerado
86
+ 6. CEO apresenta resumo
87
+
88
+ **A partir do estagio 2, ZERO interacao com usuario.** Toda decisao e tomada autonomamente pelo CEO/chiefs/supervisores.
89
+
90
+ **NAO executar nada.** Para apos gerar PLAN-READY.md.
91
+ </process>