tech-os 0.0.0-stage → 0.1.1
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 +152 -2
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +54 -0
- package/dist/commands/guide.d.ts +1 -0
- package/dist/commands/guide.js +30 -0
- package/dist/commands/init.d.ts +8 -0
- package/dist/commands/init.js +139 -0
- package/dist/commands/run.d.ts +9 -0
- package/dist/commands/run.js +171 -0
- package/dist/commands/status.d.ts +1 -0
- package/dist/commands/status.js +69 -0
- package/dist/core/paths.d.ts +13 -0
- package/dist/core/paths.js +23 -0
- package/dist/core/plan-parser.d.ts +28 -0
- package/dist/core/plan-parser.js +94 -0
- package/dist/tests/plan-parser.test.d.ts +1 -0
- package/dist/tests/plan-parser.test.js +42 -0
- package/docs/tech-os-guia.html +590 -0
- package/docs/tech-os-guia.pdf +0 -0
- package/package.json +50 -4
- package/templates/profiles/_dominio.md +9 -0
- package/templates/profiles/estudo.md +14 -0
- package/templates/profiles/mvp.md +21 -0
- package/templates/profiles/producao.md +23 -0
- package/templates/rules/cursor-rule.mdc +6 -0
- package/templates/rules/tech-os-core.md +28 -0
- package/templates/skills/tos-blueprint/SKILL.md +29 -0
- package/templates/skills/tos-contratos/SKILL.md +22 -0
- package/templates/skills/tos-discovery/SKILL.md +39 -0
- package/templates/skills/tos-manifesto/SKILL.md +34 -0
- package/templates/skills/tos-planejar/SKILL.md +38 -0
- package/templates/skills/tos-sync/SKILL.md +23 -0
package/README.md
CHANGED
|
@@ -1,3 +1,153 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Tech OS
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**Spec-Driven Development, Context Engineering & Autonomous Loop** para programar com IA com previsibilidade, código limpo e controle humano.
|
|
4
|
+
|
|
5
|
+
Compatível com **Antigravity**, **Claude Code**, **Cursor** e **Codex**.
|
|
6
|
+
|
|
7
|
+
> 📄 **Material para compartilhar:** Veja o guia visual completo em [docs/tech-os-guia.html](docs/tech-os-guia.html) ou baixe o PDF em [docs/tech-os-guia.pdf](docs/tech-os-guia.pdf).
|
|
8
|
+
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
## Por que o Tech OS existe?
|
|
12
|
+
|
|
13
|
+
Programar no modo *"vibe coding"* (pedir uma feature inteira e aceitar o código sem entender) funciona para protótipos rápidos, mas cobra um preço alto em projetos reais:
|
|
14
|
+
- Código heterogêneo, difícil de manter e cheio de abstrações desnecessárias.
|
|
15
|
+
- Modelos de IA perdem qualidade quando a janela de contexto ultrapassa ~50% (*dumb zone*).
|
|
16
|
+
- Mudanças silenciosas que quebram outras partes do sistema.
|
|
17
|
+
|
|
18
|
+
O **Tech OS** resolve isso combinando **4 pilares**:
|
|
19
|
+
1. **Contexto Persistente (`.tech-os/00-manifesto.md`)**: regras, stack, segurança e Definition of Done carregados em toda sessão.
|
|
20
|
+
2. **Spec-Driven Development (Skills `tos-*`)**: você pensa, investiga incógnitas e especifica *antes* de escrever código.
|
|
21
|
+
3. **Fatiamento (`[AUTO]` vs `[HUMANO]`)**: entregas quebradas em micro-tarefas testáveis.
|
|
22
|
+
4. **Execução em Contexto Limpo (`tech-os run`)**: cada fatia roda em uma sessão isolada da IA com apenas o contexto necessário + teste + commit atômico.
|
|
23
|
+
|
|
24
|
+
### Princípios Inegociáveis
|
|
25
|
+
- **IA sugere; engenheiro decide.** Decisões arquiteturais nunca são delegadas.
|
|
26
|
+
- **Pense antes de programar.** Exponha premissas e descubra incógnitas antes de codar.
|
|
27
|
+
- **Código mínimo que resolve o problema.** Combate ativo ao *overengineering*.
|
|
28
|
+
- **Mudanças cirúrgicas.** Altere apenas o que tem relação direta com o pedido.
|
|
29
|
+
- **Regra de Ouro:** *"Consigo explicar esta mudança sem abrir o chat?"* — se não, não faça commit.
|
|
30
|
+
|
|
31
|
+
---
|
|
32
|
+
|
|
33
|
+
## Instalação
|
|
34
|
+
|
|
35
|
+
Use direto via `npx` em qualquer projeto:
|
|
36
|
+
```bash
|
|
37
|
+
npx tech-os init
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Ou instale globalmente:
|
|
41
|
+
```bash
|
|
42
|
+
npm install -g tech-os
|
|
43
|
+
```
|
|
44
|
+
*(Disponibiliza os comandos `tech-os` e o atalho `tos`.)*
|
|
45
|
+
|
|
46
|
+
---
|
|
47
|
+
|
|
48
|
+
## Comandos da CLI
|
|
49
|
+
|
|
50
|
+
### `tech-os init`
|
|
51
|
+
Inicializa o Tech OS no projeto atual. Pergunta quais ferramentas de IA você usa e qual perfil de rigor deseja para o manifesto.
|
|
52
|
+
|
|
53
|
+
**O que ele cria:**
|
|
54
|
+
- **Antigravity**: `.agents/skills/tos-*/SKILL.md` + bloco no `AGENTS.md`
|
|
55
|
+
- **Claude Code**: `.claude/skills/tos-*/SKILL.md` + bloco no `CLAUDE.md`
|
|
56
|
+
- **Cursor**: `.cursor/rules/tech-os.mdc`
|
|
57
|
+
- **Codex / Outros**: `AGENTS.md`
|
|
58
|
+
- **Fundação do projeto**: `.tech-os/00-manifesto.md` e `.tech-os/_dominio.md`
|
|
59
|
+
|
|
60
|
+
**Flags disponíveis:**
|
|
61
|
+
- `-y, --yes` — Pula perguntas interativas e usa o padrão (`antigravity`, perfil `mvp`).
|
|
62
|
+
- `-t, --tools <lista>` — Ferramentas separadas por vírgula (`antigravity,claude,cursor,codex`).
|
|
63
|
+
- `-p, --profile <perfil>` — Perfil do manifesto:
|
|
64
|
+
- `mvp`: pragmático, testes nos fluxos críticos.
|
|
65
|
+
- `producao`: rigor alto, baseline de segurança, meta de cobertura >= 80%.
|
|
66
|
+
- `estudo`: foco em clareza, aprendizado e explicação de trade-offs.
|
|
67
|
+
|
|
68
|
+
**Exemplo:**
|
|
69
|
+
```bash
|
|
70
|
+
tech-os init --tools antigravity,cursor --profile producao
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
---
|
|
74
|
+
|
|
75
|
+
### `tech-os status`
|
|
76
|
+
Faz uma leitura da pasta `.tech-os/` e exibe um painel no terminal com:
|
|
77
|
+
- Status da fundação (`00-manifesto.md` e `_dominio.md`).
|
|
78
|
+
- Todas as features iniciadas e quais fases já foram concluídas (`discovery`, `blueprint`, `contratos`, `plano`).
|
|
79
|
+
- Quantas fatias foram concluídas (`X/Y`) e qual é a **próxima fatia desbloqueada** (`[AUTO]` ou `[HUMANO]`).
|
|
80
|
+
|
|
81
|
+
---
|
|
82
|
+
|
|
83
|
+
### `tech-os run <feature> [maxIterations]`
|
|
84
|
+
O orquestrador autônomo em **contexto limpo**. Ele lê `.tech-os/<feature>/04-plano.md` e executa uma fatia por iteração:
|
|
85
|
+
1. Seleciona a próxima fatia `[ ]` cujas dependências (`deps`) já estejam `[x]`.
|
|
86
|
+
2. Se a fatia for `[HUMANO]`, pausa e avisa o que precisa da sua validação antes de continuar.
|
|
87
|
+
3. Se for `[AUTO]`, monta um prompt enxuto contendo **apenas**: `00-manifesto.md`, `_dominio.md`, `02-blueprint.md`, `03-contratos.md` (se existir) e a fatia atual.
|
|
88
|
+
4. Chama o agente CLI configurado, roda o comando de verificação (DoD) e, se passar, marca `[x]` e faz `git commit -m "feat(<ID>): <descrição>"`.
|
|
89
|
+
|
|
90
|
+
**Flags disponíveis:**
|
|
91
|
+
- `-r, --runner <runner>` — CLI usada para executar a fatia: `claude` (padrão), `codex` ou `custom`.
|
|
92
|
+
- `--cmd <comando>` — Comando customizado quando `--runner custom` (recebe o prompt via `stdin`).
|
|
93
|
+
- `--test-cmd <comando>` — Sobrescreve o comando de verificação (DoD) definido no `00-manifesto.md`.
|
|
94
|
+
- `--dry-run` — Apenas imprime o prompt em contexto limpo no terminal sem executar o agente.
|
|
95
|
+
- `--no-commit` — Não cria commit git automático ao concluir a fatia.
|
|
96
|
+
|
|
97
|
+
**Exemplos:**
|
|
98
|
+
```bash
|
|
99
|
+
# Visualizar exatamente o prompt que seria enviado para a IA
|
|
100
|
+
tech-os run 001-auth-jwt --dry-run
|
|
101
|
+
|
|
102
|
+
# Rodar até 5 fatias usando Claude Code
|
|
103
|
+
tech-os run 001-auth-jwt 5
|
|
104
|
+
|
|
105
|
+
# Rodar usando um comando customizado e sem commit automático
|
|
106
|
+
tech-os run 001-auth-jwt --runner custom --cmd "meu-agente" --no-commit
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
---
|
|
110
|
+
|
|
111
|
+
### `tech-os guide`
|
|
112
|
+
Exibe no terminal um resumo didático da metodologia (por que usar, os 4 tipos de incógnitas, regra de ouro, fluxo das 6 skills e comandos). Ideal para apresentar o framework para amigos ou colegas.
|
|
113
|
+
|
|
114
|
+
---
|
|
115
|
+
|
|
116
|
+
## Fluxo das Skills (`tos-*`)
|
|
117
|
+
|
|
118
|
+
No chat do seu agente (Antigravity, Claude Code, Cursor), você aciona as skills conforme a etapa da feature:
|
|
119
|
+
|
|
120
|
+
| Ordem | Skill | Arquivo gerado | Objetivo |
|
|
121
|
+
| :--- | :--- | :--- | :--- |
|
|
122
|
+
| **0** | **`tos-manifesto`** | `.tech-os/00-manifesto.md`<br>`.tech-os/_dominio.md` | Define stack, segurança, DoD e vocabulário do projeto. Roda **1x por projeto**. |
|
|
123
|
+
| **1** | **`tos-discovery`** | `01-discovery.md` | Entrevista você pergunta por pergunta para revelar **Unknown Knowns** e **Unknown Unknowns** antes de codar. |
|
|
124
|
+
| **2** | **`tos-blueprint`** | `02-blueprint.md` | Formaliza o PRD técnico com User Stories, módulos afetados, testes e classificação de impacto (**`local`** vs **`estrutural`**). |
|
|
125
|
+
| **3** | **`tos-contratos`** | `03-contratos.md` *(opcional)* | Detalha rotas de API, schemas de dados, códigos de erro e regras de segurança. |
|
|
126
|
+
| **4** | **`tos-planejar`** | `04-plano.md` | Quebra a entrega em fatias executáveis (`F01`, `F02`...) com dependências e marcação `[AUTO]` ou `[HUMANO]`. |
|
|
127
|
+
| **5** | **`tos-sync`** | *(atualiza os `.md`)* | Atualiza a especificação **antes** do código quando um requisito muda no meio do caminho (evita *spec drift*). |
|
|
128
|
+
|
|
129
|
+
---
|
|
130
|
+
|
|
131
|
+
## Estrutura de Arquivos no Projeto
|
|
132
|
+
|
|
133
|
+
```text
|
|
134
|
+
seu-projeto/
|
|
135
|
+
├── AGENTS.md # Regras permanentes (Antigravity / Codex)
|
|
136
|
+
├── CLAUDE.md # Regras permanentes (Claude Code, opcional)
|
|
137
|
+
├── .agents/skills/tos-*/ # Skills instaladas para o Antigravity
|
|
138
|
+
├── .cursor/rules/tech-os.mdc # Regras instaladas para o Cursor (opcional)
|
|
139
|
+
└── .tech-os/
|
|
140
|
+
├── 00-manifesto.md # Lei do projeto (stack, segurança, DoD)
|
|
141
|
+
├── _dominio.md # Glossário de negócio
|
|
142
|
+
└── 001-minha-feature/
|
|
143
|
+
├── 01-discovery.md # Entendimento e decisões
|
|
144
|
+
├── 02-blueprint.md # PRD de engenharia e impacto
|
|
145
|
+
├── 03-contratos.md # Contratos técnicos (opcional)
|
|
146
|
+
└── 04-plano.md # Fatias [AUTO] e [HUMANO]
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
---
|
|
150
|
+
|
|
151
|
+
## Licença
|
|
152
|
+
|
|
153
|
+
MIT
|
package/dist/cli.d.ts
ADDED
package/dist/cli.js
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { Command } from 'commander';
|
|
3
|
+
import { runInit } from './commands/init.js';
|
|
4
|
+
import { runStatus } from './commands/status.js';
|
|
5
|
+
import { runLoop } from './commands/run.js';
|
|
6
|
+
import { runGuide } from './commands/guide.js';
|
|
7
|
+
const program = new Command();
|
|
8
|
+
program
|
|
9
|
+
.name('tech-os')
|
|
10
|
+
.description('Tech OS — Spec-Driven Development, Context Engineering & Autonomous Loop')
|
|
11
|
+
.version('0.1.0');
|
|
12
|
+
program
|
|
13
|
+
.command('init')
|
|
14
|
+
.description('Inicializa o Tech OS no projeto atual (skills, regras e manifesto)')
|
|
15
|
+
.option('-y, --yes', 'Usa configurações padrão sem perguntas interativas')
|
|
16
|
+
.option('-t, --tools <tools>', 'Lista separada por vírgula: antigravity,claude,cursor,codex')
|
|
17
|
+
.option('-p, --profile <profile>', 'Perfil do manifesto: mvp | producao | estudo')
|
|
18
|
+
.action(async (options) => {
|
|
19
|
+
await runInit(options);
|
|
20
|
+
});
|
|
21
|
+
program
|
|
22
|
+
.command('status')
|
|
23
|
+
.description('Mostra o status das features e fatias em .tech-os/')
|
|
24
|
+
.action(async () => {
|
|
25
|
+
await runStatus();
|
|
26
|
+
});
|
|
27
|
+
program
|
|
28
|
+
.command('run <feature> [maxIterations]')
|
|
29
|
+
.description('Executa o loop autônomo em contexto limpo para uma feature (ex: 001-auth)')
|
|
30
|
+
.option('-r, --runner <runner>', 'Runner CLI: claude | codex | custom', 'claude')
|
|
31
|
+
.option('--cmd <command>', 'Comando customizado quando --runner custom')
|
|
32
|
+
.option('--test-cmd <command>', 'Sobrescreve o comando de verificação (DoD)')
|
|
33
|
+
.option('--dry-run', 'Mostra o prompt em contexto limpo sem executar o agente')
|
|
34
|
+
.option('--no-commit', 'Não cria commit git automático após cada fatia')
|
|
35
|
+
.action(async (feature, maxIterations, options) => {
|
|
36
|
+
await runLoop(feature, maxIterations, {
|
|
37
|
+
runner: options.runner,
|
|
38
|
+
cmd: options.cmd,
|
|
39
|
+
testCmd: options.testCmd,
|
|
40
|
+
dryRun: Boolean(options.dryRun),
|
|
41
|
+
commit: options.commit,
|
|
42
|
+
});
|
|
43
|
+
});
|
|
44
|
+
program
|
|
45
|
+
.command('guide')
|
|
46
|
+
.description('Exibe um resumo didático da metodologia Tech OS no terminal')
|
|
47
|
+
.action(() => {
|
|
48
|
+
runGuide();
|
|
49
|
+
});
|
|
50
|
+
program.parseAsync(process.argv).catch((err) => {
|
|
51
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
52
|
+
console.error(`Erro: ${message}`);
|
|
53
|
+
process.exit(1);
|
|
54
|
+
});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function runGuide(): void;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import pc from 'picocolors';
|
|
2
|
+
export function runGuide() {
|
|
3
|
+
console.log(pc.bold(pc.cyan('\n📘 Tech OS — Guia Completo da Metodologia\n')));
|
|
4
|
+
console.log(pc.bold('1. O Problema que o Tech OS Resolve'));
|
|
5
|
+
console.log(' • Vibe coding funciona para protótipos, mas gera código difícil de manter.');
|
|
6
|
+
console.log(' • Modelos perdem eficiência quando o contexto passa de ~50% (dumb zone).');
|
|
7
|
+
console.log(' • Sem spec, não há rastreabilidade nem segurança arquitetural.\n');
|
|
8
|
+
console.log(pc.bold('2. Princípios & Regra de Ouro'));
|
|
9
|
+
console.log(' • IA sugere; engenheiro decide.');
|
|
10
|
+
console.log(' • Código mínimo que resolve o problema (sem overengineering).');
|
|
11
|
+
console.log(' • Mudanças cirúrgicas: altere apenas o necessário para a tarefa.');
|
|
12
|
+
console.log(` • ${pc.yellow('Regra de Ouro: "Consigo explicar esta mudança sem abrir o chat?"')}\n`);
|
|
13
|
+
console.log(pc.bold('3. Os 4 Tipos de Incógnitas (mapeados no tos-discovery)'));
|
|
14
|
+
console.log(' • Known Knowns: o que você já sabe e colocou no pedido.');
|
|
15
|
+
console.log(' • Known Unknowns: lacunas que você sabe que precisa descobrir.');
|
|
16
|
+
console.log(' • Unknown Knowns: regras óbvias do dia a dia que você esquece de dizer.');
|
|
17
|
+
console.log(` • ${pc.red('Unknown Unknowns:')} cenários de borda que nem você sabia que existiam.\n`);
|
|
18
|
+
console.log(pc.bold('4. O Fluxo das 6 Skills (Spec-Driven Development)'));
|
|
19
|
+
console.log(` 0. ${pc.cyan('tos-manifesto')} → Cria a "lei" do projeto (00-manifesto.md + _dominio.md)`);
|
|
20
|
+
console.log(` 1. ${pc.cyan('tos-discovery')} → Entrevista para alinhar problema e incógnitas (01-discovery.md)`);
|
|
21
|
+
console.log(` 2. ${pc.cyan('tos-blueprint')} → PRD técnico + impacto local/estrutural (02-blueprint.md)`);
|
|
22
|
+
console.log(` 3. ${pc.cyan('tos-contratos')} → Contratos de API/schema/segurança (03-contratos.md, opc.)`);
|
|
23
|
+
console.log(` 4. ${pc.cyan('tos-planejar')} → Fatias executáveis [AUTO] e [HUMANO] (04-plano.md)`);
|
|
24
|
+
console.log(` * ${pc.cyan('tos-sync')} → Atualiza a spec ANTES do código se algo mudar\n`);
|
|
25
|
+
console.log(pc.bold('5. Comandos da CLI'));
|
|
26
|
+
console.log(` ${pc.green('tech-os init')} Instala skills, regras e manifesto no projeto`);
|
|
27
|
+
console.log(` ${pc.green('tech-os status')} Mostra progresso das features e próxima fatia`);
|
|
28
|
+
console.log(` ${pc.green('tech-os run <feature>')} Executa fatias [AUTO] em contexto limpo + commit`);
|
|
29
|
+
console.log(` ${pc.green('tech-os guide')} Exibe este guia no terminal\n`);
|
|
30
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export type ToolTarget = 'antigravity' | 'claude' | 'cursor' | 'codex';
|
|
2
|
+
export type ManifestoProfile = 'mvp' | 'producao' | 'estudo';
|
|
3
|
+
export interface InitOptions {
|
|
4
|
+
yes?: boolean;
|
|
5
|
+
tools?: string;
|
|
6
|
+
profile?: ManifestoProfile;
|
|
7
|
+
}
|
|
8
|
+
export declare function runInit(options: InitOptions, cwd?: string): Promise<void>;
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { checkbox, select } from '@inquirer/prompts';
|
|
4
|
+
import pc from 'picocolors';
|
|
5
|
+
import { getTechOsDir, getTemplatePath } from '../core/paths.js';
|
|
6
|
+
const START_MARKER = '<!-- tech-os:start -->';
|
|
7
|
+
const END_MARKER = '<!-- tech-os:end -->';
|
|
8
|
+
async function exists(targetPath) {
|
|
9
|
+
try {
|
|
10
|
+
await fs.access(targetPath);
|
|
11
|
+
return true;
|
|
12
|
+
}
|
|
13
|
+
catch {
|
|
14
|
+
return false;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
async function copySkills(targetDir) {
|
|
18
|
+
const skillsSrc = getTemplatePath('skills');
|
|
19
|
+
const entries = await fs.readdir(skillsSrc, { withFileTypes: true });
|
|
20
|
+
let count = 0;
|
|
21
|
+
for (const entry of entries) {
|
|
22
|
+
if (!entry.isDirectory())
|
|
23
|
+
continue;
|
|
24
|
+
const srcSkill = path.join(skillsSrc, entry.name, 'SKILL.md');
|
|
25
|
+
const destDir = path.join(targetDir, entry.name);
|
|
26
|
+
await fs.mkdir(destDir, { recursive: true });
|
|
27
|
+
await fs.copyFile(srcSkill, path.join(destDir, 'SKILL.md'));
|
|
28
|
+
count++;
|
|
29
|
+
}
|
|
30
|
+
return count;
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Inserts or replaces the Tech OS block inside a markdown rule file (AGENTS.md / CLAUDE.md).
|
|
34
|
+
*/
|
|
35
|
+
async function upsertMarkedSection(filePath, coreContent) {
|
|
36
|
+
const block = `${START_MARKER}\n${coreContent.trim()}\n${END_MARKER}`;
|
|
37
|
+
if (!(await exists(filePath))) {
|
|
38
|
+
await fs.writeFile(filePath, `${block}\n`, 'utf-8');
|
|
39
|
+
return;
|
|
40
|
+
}
|
|
41
|
+
const existing = await fs.readFile(filePath, 'utf-8');
|
|
42
|
+
const startIdx = existing.indexOf(START_MARKER);
|
|
43
|
+
const endIdx = existing.indexOf(END_MARKER);
|
|
44
|
+
if (startIdx !== -1 && endIdx !== -1 && endIdx > startIdx) {
|
|
45
|
+
const before = existing.slice(0, startIdx);
|
|
46
|
+
const after = existing.slice(endIdx + END_MARKER.length);
|
|
47
|
+
await fs.writeFile(filePath, `${before}${block}${after}`, 'utf-8');
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
const separator = existing.endsWith('\n') ? '\n' : '\n\n';
|
|
51
|
+
await fs.writeFile(filePath, `${existing}${separator}${block}\n`, 'utf-8');
|
|
52
|
+
}
|
|
53
|
+
function parseToolsFlag(raw) {
|
|
54
|
+
if (!raw)
|
|
55
|
+
return null;
|
|
56
|
+
const valid = new Set(['antigravity', 'claude', 'cursor', 'codex']);
|
|
57
|
+
const parsed = raw
|
|
58
|
+
.split(',')
|
|
59
|
+
.map((t) => t.trim().toLowerCase())
|
|
60
|
+
.filter((t) => valid.has(t));
|
|
61
|
+
return parsed.length > 0 ? parsed : null;
|
|
62
|
+
}
|
|
63
|
+
export async function runInit(options, cwd = process.cwd()) {
|
|
64
|
+
console.log(pc.bold(pc.cyan('\n⚡ Tech OS — Inicialização do Projeto\n')));
|
|
65
|
+
let tools = parseToolsFlag(options.tools) ?? [];
|
|
66
|
+
let profile = options.profile ?? 'mvp';
|
|
67
|
+
if (options.yes) {
|
|
68
|
+
if (tools.length === 0)
|
|
69
|
+
tools = ['antigravity'];
|
|
70
|
+
}
|
|
71
|
+
else {
|
|
72
|
+
if (tools.length === 0) {
|
|
73
|
+
tools = await checkbox({
|
|
74
|
+
message: 'Quais ferramentas de IA você (ou seu time) usa neste projeto?',
|
|
75
|
+
choices: [
|
|
76
|
+
{ name: 'Antigravity (.agents/skills + AGENTS.md)', value: 'antigravity', checked: true },
|
|
77
|
+
{ name: 'Claude Code (.claude/skills + CLAUDE.md)', value: 'claude' },
|
|
78
|
+
{ name: 'Cursor (.cursor/rules/tech-os.mdc)', value: 'cursor' },
|
|
79
|
+
{ name: 'Codex / Outros (AGENTS.md)', value: 'codex' },
|
|
80
|
+
],
|
|
81
|
+
required: true,
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
if (!options.profile) {
|
|
85
|
+
profile = await select({
|
|
86
|
+
message: 'Qual perfil de rigor para o .tech-os/00-manifesto.md?',
|
|
87
|
+
choices: [
|
|
88
|
+
{ name: 'MVP Rápido — pragmático, testes nos fluxos críticos', value: 'mvp' },
|
|
89
|
+
{ name: 'Produção — rigor alto, baseline de segurança, testes >= 80%', value: 'producao' },
|
|
90
|
+
{ name: 'Estudo & Protótipo — foco em clareza e aprendizado', value: 'estudo' },
|
|
91
|
+
],
|
|
92
|
+
default: 'mvp',
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
const coreRules = await fs.readFile(getTemplatePath('rules', 'tech-os-core.md'), 'utf-8');
|
|
97
|
+
const installedActions = [];
|
|
98
|
+
if (tools.includes('antigravity') || tools.includes('codex')) {
|
|
99
|
+
await upsertMarkedSection(path.join(cwd, 'AGENTS.md'), coreRules);
|
|
100
|
+
installedActions.push('AGENTS.md');
|
|
101
|
+
}
|
|
102
|
+
if (tools.includes('antigravity')) {
|
|
103
|
+
const count = await copySkills(path.join(cwd, '.agents', 'skills'));
|
|
104
|
+
installedActions.push(`.agents/skills/ (${count} skills)`);
|
|
105
|
+
}
|
|
106
|
+
if (tools.includes('claude')) {
|
|
107
|
+
await upsertMarkedSection(path.join(cwd, 'CLAUDE.md'), coreRules);
|
|
108
|
+
const count = await copySkills(path.join(cwd, '.claude', 'skills'));
|
|
109
|
+
installedActions.push(`CLAUDE.md + .claude/skills/ (${count} skills)`);
|
|
110
|
+
}
|
|
111
|
+
if (tools.includes('cursor')) {
|
|
112
|
+
const cursorDir = path.join(cwd, '.cursor', 'rules');
|
|
113
|
+
await fs.mkdir(cursorDir, { recursive: true });
|
|
114
|
+
const cursorTemplate = await fs.readFile(getTemplatePath('rules', 'cursor-rule.mdc'), 'utf-8');
|
|
115
|
+
await fs.writeFile(path.join(cursorDir, 'tech-os.mdc'), cursorTemplate.replace('{{CORE_RULES}}', coreRules.trim()), 'utf-8');
|
|
116
|
+
installedActions.push('.cursor/rules/tech-os.mdc');
|
|
117
|
+
}
|
|
118
|
+
// Create .tech-os/ foundation if missing
|
|
119
|
+
const techOsDir = getTechOsDir(cwd);
|
|
120
|
+
await fs.mkdir(techOsDir, { recursive: true });
|
|
121
|
+
const manifestoDest = path.join(techOsDir, '00-manifesto.md');
|
|
122
|
+
if (!(await exists(manifestoDest))) {
|
|
123
|
+
await fs.copyFile(getTemplatePath('profiles', `${profile}.md`), manifestoDest);
|
|
124
|
+
installedActions.push(`.tech-os/00-manifesto.md (perfil: ${profile})`);
|
|
125
|
+
}
|
|
126
|
+
const dominioDest = path.join(techOsDir, '_dominio.md');
|
|
127
|
+
if (!(await exists(dominioDest))) {
|
|
128
|
+
await fs.copyFile(getTemplatePath('profiles', '_dominio.md'), dominioDest);
|
|
129
|
+
installedActions.push('.tech-os/_dominio.md');
|
|
130
|
+
}
|
|
131
|
+
console.log(pc.green('✓ Tech OS configurado com sucesso!\n'));
|
|
132
|
+
for (const item of installedActions) {
|
|
133
|
+
console.log(` ${pc.dim('•')} ${item}`);
|
|
134
|
+
}
|
|
135
|
+
console.log(pc.bold('\nPróximos passos:'));
|
|
136
|
+
console.log(` 1. Ajuste a stack em ${pc.cyan('.tech-os/00-manifesto.md')} (ou rode a skill ${pc.cyan('tos-manifesto')})`);
|
|
137
|
+
console.log(` 2. Na sua próxima feature, chame a skill ${pc.cyan('tos-discovery')} no seu agente`);
|
|
138
|
+
console.log(` 3. Acompanhe o progresso com ${pc.cyan('tech-os status')}\n`);
|
|
139
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export type RunnerType = 'claude' | 'codex' | 'custom';
|
|
2
|
+
export interface RunOptions {
|
|
3
|
+
runner?: RunnerType;
|
|
4
|
+
cmd?: string;
|
|
5
|
+
testCmd?: string;
|
|
6
|
+
dryRun?: boolean;
|
|
7
|
+
commit?: boolean;
|
|
8
|
+
}
|
|
9
|
+
export declare function runLoop(feature: string, maxIterationsArg: string | undefined, options: RunOptions, cwd?: string): Promise<void>;
|
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { spawnSync } from 'node:child_process';
|
|
4
|
+
import pc from 'picocolors';
|
|
5
|
+
import { getTechOsDir } from '../core/paths.js';
|
|
6
|
+
import { findNextUnblockedSlice, readPlanFile, updateSliceStatus, } from '../core/plan-parser.js';
|
|
7
|
+
async function readIfExists(filePath) {
|
|
8
|
+
try {
|
|
9
|
+
return await fs.readFile(filePath, 'utf-8');
|
|
10
|
+
}
|
|
11
|
+
catch {
|
|
12
|
+
return '';
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
function extractTestCommand(manifesto, override) {
|
|
16
|
+
if (override)
|
|
17
|
+
return override;
|
|
18
|
+
const match = manifesto.match(/Comando de Verificação \(DoD\):\*\*\s*`([^`]+)`/i);
|
|
19
|
+
return match ? match[1].trim() : null;
|
|
20
|
+
}
|
|
21
|
+
function buildCleanPrompt(params) {
|
|
22
|
+
const parts = [
|
|
23
|
+
`Você está executando UMA única fatia do Tech OS em contexto limpo.`,
|
|
24
|
+
`NÃO amplie o escopo. Altere apenas o necessário para concluir a fatia abaixo.`,
|
|
25
|
+
``,
|
|
26
|
+
`## Fatia Atual`,
|
|
27
|
+
`- ID: ${params.slice.id}`,
|
|
28
|
+
`- Tarefa: ${params.slice.title}`,
|
|
29
|
+
`- User Story: ${params.slice.us}`,
|
|
30
|
+
`- Feature: ${params.feature}`,
|
|
31
|
+
];
|
|
32
|
+
if (params.manifesto) {
|
|
33
|
+
parts.push('', '## 00-manifesto.md', params.manifesto.trim());
|
|
34
|
+
}
|
|
35
|
+
if (params.dominio) {
|
|
36
|
+
parts.push('', '## _dominio.md', params.dominio.trim());
|
|
37
|
+
}
|
|
38
|
+
if (params.blueprint) {
|
|
39
|
+
parts.push('', '## 02-blueprint.md', params.blueprint.trim());
|
|
40
|
+
}
|
|
41
|
+
if (params.contratos) {
|
|
42
|
+
parts.push('', '## 03-contratos.md', params.contratos.trim());
|
|
43
|
+
}
|
|
44
|
+
parts.push('', '## Instrução Final', `Implemente ${params.slice.id}, escreva/atualize os testes correspondentes e garanta que tudo passe.`);
|
|
45
|
+
return parts.join('\n');
|
|
46
|
+
}
|
|
47
|
+
function invokeRunner(runner, prompt, customCmd) {
|
|
48
|
+
if (runner === 'custom') {
|
|
49
|
+
if (!customCmd) {
|
|
50
|
+
throw new Error('Runner "custom" exige --cmd "<comando>".');
|
|
51
|
+
}
|
|
52
|
+
const res = spawnSync(customCmd, {
|
|
53
|
+
input: prompt,
|
|
54
|
+
stdio: ['pipe', 'inherit', 'inherit'],
|
|
55
|
+
shell: true,
|
|
56
|
+
});
|
|
57
|
+
return res.status === 0;
|
|
58
|
+
}
|
|
59
|
+
if (runner === 'claude') {
|
|
60
|
+
const res = spawnSync('claude', ['-p', prompt], {
|
|
61
|
+
stdio: 'inherit',
|
|
62
|
+
shell: true,
|
|
63
|
+
});
|
|
64
|
+
return res.status === 0;
|
|
65
|
+
}
|
|
66
|
+
if (runner === 'codex') {
|
|
67
|
+
const res = spawnSync('codex', ['exec', prompt], {
|
|
68
|
+
stdio: 'inherit',
|
|
69
|
+
shell: true,
|
|
70
|
+
});
|
|
71
|
+
return res.status === 0;
|
|
72
|
+
}
|
|
73
|
+
return false;
|
|
74
|
+
}
|
|
75
|
+
function runShellCommand(command) {
|
|
76
|
+
const res = spawnSync(command, {
|
|
77
|
+
stdio: 'inherit',
|
|
78
|
+
shell: true,
|
|
79
|
+
});
|
|
80
|
+
return res.status === 0;
|
|
81
|
+
}
|
|
82
|
+
export async function runLoop(feature, maxIterationsArg, options, cwd = process.cwd()) {
|
|
83
|
+
const maxIterations = maxIterationsArg ? Number.parseInt(maxIterationsArg, 10) : 10;
|
|
84
|
+
if (Number.isNaN(maxIterations) || maxIterations <= 0) {
|
|
85
|
+
throw new Error('maxIterations deve ser um número inteiro positivo.');
|
|
86
|
+
}
|
|
87
|
+
const techOsDir = getTechOsDir(cwd);
|
|
88
|
+
const featureDir = path.join(techOsDir, feature);
|
|
89
|
+
const planPath = path.join(featureDir, '04-plano.md');
|
|
90
|
+
const planRaw = await readIfExists(planPath);
|
|
91
|
+
if (!planRaw) {
|
|
92
|
+
console.log(pc.red(`\n✗ Plano não encontrado em ${planPath}`));
|
|
93
|
+
console.log(`Gere o plano primeiro com a skill ${pc.cyan('tos-planejar')}.\n`);
|
|
94
|
+
process.exitCode = 1;
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
const manifesto = await readIfExists(path.join(techOsDir, '00-manifesto.md'));
|
|
98
|
+
const dominio = await readIfExists(path.join(techOsDir, '_dominio.md'));
|
|
99
|
+
const blueprint = await readIfExists(path.join(featureDir, '02-blueprint.md'));
|
|
100
|
+
const contratos = await readIfExists(path.join(featureDir, '03-contratos.md'));
|
|
101
|
+
const testCmd = extractTestCommand(manifesto, options.testCmd);
|
|
102
|
+
const runner = options.runner ?? 'claude';
|
|
103
|
+
const shouldCommit = options.commit !== false;
|
|
104
|
+
console.log(pc.bold(pc.cyan(`\n🔁 Tech OS Runner — ${feature}\n`)));
|
|
105
|
+
console.log(` Runner: ${runner}${options.dryRun ? pc.yellow(' (dry-run)') : ''}`);
|
|
106
|
+
console.log(` DoD: ${testCmd ?? pc.dim('nenhum comando configurado')}\n`);
|
|
107
|
+
for (let iteration = 1; iteration <= maxIterations; iteration++) {
|
|
108
|
+
const slices = await readPlanFile(planPath);
|
|
109
|
+
const next = findNextUnblockedSlice(slices);
|
|
110
|
+
if (!next) {
|
|
111
|
+
const allDone = slices.length > 0 && slices.every((s) => s.status === 'done');
|
|
112
|
+
if (allDone) {
|
|
113
|
+
console.log(pc.green('✓ Todas as fatias foram concluídas! <promise>COMPLETE</promise>\n'));
|
|
114
|
+
}
|
|
115
|
+
else {
|
|
116
|
+
console.log(pc.yellow('⚠ Nenhuma fatia desbloqueada encontrada. Verifique dependências em 04-plano.md.\n'));
|
|
117
|
+
}
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
if (next.mode === 'HUMANO') {
|
|
121
|
+
console.log(pc.yellow(`⏸ Pausado em ${next.id} [HUMANO]: ${next.title}`));
|
|
122
|
+
console.log(pc.dim(` Conclua esta etapa manualmente, marque [x] em 04-plano.md e rode "tech-os run ${feature}" novamente.\n`));
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
console.log(pc.bold(`→ Iteração ${iteration}/${maxIterations}: [${next.id}] ${next.title}`));
|
|
126
|
+
const prompt = buildCleanPrompt({
|
|
127
|
+
feature,
|
|
128
|
+
slice: next,
|
|
129
|
+
manifesto,
|
|
130
|
+
dominio,
|
|
131
|
+
blueprint,
|
|
132
|
+
contratos,
|
|
133
|
+
});
|
|
134
|
+
if (options.dryRun) {
|
|
135
|
+
console.log(pc.dim('\n--- PROMPT EM CONTEXTO LIMPO ---'));
|
|
136
|
+
console.log(prompt);
|
|
137
|
+
console.log(pc.dim('--- FIM DO DRY-RUN ---\n'));
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
await updateSliceStatus(planPath, next.id, 'in_progress');
|
|
141
|
+
const agentOk = invokeRunner(runner, prompt, options.cmd);
|
|
142
|
+
if (!agentOk) {
|
|
143
|
+
console.log(pc.red(`✗ Runner falhou na fatia ${next.id}. Marcando [~] e interrompendo.`));
|
|
144
|
+
process.exitCode = 1;
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
if (testCmd) {
|
|
148
|
+
console.log(pc.dim(` Rodando DoD: ${testCmd}`));
|
|
149
|
+
const testOk = runShellCommand(testCmd);
|
|
150
|
+
if (!testOk) {
|
|
151
|
+
console.log(pc.red(`✗ DoD falhou na fatia ${next.id}. Marcando [~] e interrompendo.`));
|
|
152
|
+
process.exitCode = 1;
|
|
153
|
+
return;
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
await updateSliceStatus(planPath, next.id, 'done');
|
|
157
|
+
console.log(pc.green(`✓ ${next.id} concluída!`));
|
|
158
|
+
if (shouldCommit) {
|
|
159
|
+
const commitMsg = `feat(${next.id}): ${next.title}`;
|
|
160
|
+
const committed = runShellCommand(`git add -A && git commit -m "${commitMsg.replace(/"/g, '\\"')}"`);
|
|
161
|
+
if (committed) {
|
|
162
|
+
console.log(pc.dim(` git commit: ${commitMsg}`));
|
|
163
|
+
}
|
|
164
|
+
else {
|
|
165
|
+
console.log(pc.yellow(' ⚠ Não foi possível criar commit git (sem alterações ou repo não inicializado).'));
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
console.log('');
|
|
169
|
+
}
|
|
170
|
+
console.log(pc.yellow(`⏹ Limite de ${maxIterations} iterações atingido.\n`));
|
|
171
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function runStatus(cwd?: string): Promise<void>;
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import pc from 'picocolors';
|
|
4
|
+
import { getTechOsDir } from '../core/paths.js';
|
|
5
|
+
import { findNextUnblockedSlice, readPlanFile } from '../core/plan-parser.js';
|
|
6
|
+
async function fileExists(targetPath) {
|
|
7
|
+
try {
|
|
8
|
+
await fs.access(targetPath);
|
|
9
|
+
return true;
|
|
10
|
+
}
|
|
11
|
+
catch {
|
|
12
|
+
return false;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
export async function runStatus(cwd = process.cwd()) {
|
|
16
|
+
const techOsDir = getTechOsDir(cwd);
|
|
17
|
+
if (!(await fileExists(techOsDir))) {
|
|
18
|
+
console.log(pc.yellow('\nPasta .tech-os/ não encontrada neste projeto.'));
|
|
19
|
+
console.log(`Rode ${pc.cyan('tech-os init')} para inicializar.\n`);
|
|
20
|
+
return;
|
|
21
|
+
}
|
|
22
|
+
const hasManifesto = await fileExists(path.join(techOsDir, '00-manifesto.md'));
|
|
23
|
+
const hasDominio = await fileExists(path.join(techOsDir, '_dominio.md'));
|
|
24
|
+
console.log(pc.bold(pc.cyan('\n📊 Tech OS — Status do Projeto\n')));
|
|
25
|
+
console.log(` Fundação: ${hasManifesto ? pc.green('✓ 00-manifesto.md') : pc.red('✗ 00-manifesto.md')} ${hasDominio ? pc.green('✓ _dominio.md') : pc.yellow('○ _dominio.md')}\n`);
|
|
26
|
+
const entries = await fs.readdir(techOsDir, { withFileTypes: true });
|
|
27
|
+
const featureDirs = entries
|
|
28
|
+
.filter((e) => e.isDirectory())
|
|
29
|
+
.map((e) => e.name)
|
|
30
|
+
.sort();
|
|
31
|
+
if (featureDirs.length === 0) {
|
|
32
|
+
console.log(pc.dim(' Nenhuma feature iniciada ainda. Use a skill tos-discovery para começar.\n'));
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
for (const dir of featureDirs) {
|
|
36
|
+
const featurePath = path.join(techOsDir, dir);
|
|
37
|
+
const stages = [
|
|
38
|
+
{ key: 'discovery', file: '01-discovery.md' },
|
|
39
|
+
{ key: 'blueprint', file: '02-blueprint.md' },
|
|
40
|
+
{ key: 'contratos', file: '03-contratos.md' },
|
|
41
|
+
{ key: 'plano', file: '04-plano.md' },
|
|
42
|
+
];
|
|
43
|
+
const badges = [];
|
|
44
|
+
for (const s of stages) {
|
|
45
|
+
const ok = await fileExists(path.join(featurePath, s.file));
|
|
46
|
+
badges.push(ok ? pc.green(`✓ ${s.key}`) : pc.dim(`· ${s.key}`));
|
|
47
|
+
}
|
|
48
|
+
console.log(` ${pc.bold(dir)}`);
|
|
49
|
+
console.log(` Fases: ${badges.join(' ')}`);
|
|
50
|
+
const planPath = path.join(featurePath, '04-plano.md');
|
|
51
|
+
if (await fileExists(planPath)) {
|
|
52
|
+
const slices = await readPlanFile(planPath);
|
|
53
|
+
const doneCount = slices.filter((s) => s.status === 'done').length;
|
|
54
|
+
const next = findNextUnblockedSlice(slices);
|
|
55
|
+
console.log(` Fatias: ${doneCount}/${slices.length} concluídas`);
|
|
56
|
+
if (slices.length > 0 && doneCount === slices.length) {
|
|
57
|
+
console.log(` Estado: ${pc.green('COMPLETE')}`);
|
|
58
|
+
}
|
|
59
|
+
else if (next) {
|
|
60
|
+
const modeTag = next.mode === 'HUMANO' ? pc.yellow('[HUMANO]') : pc.cyan('[AUTO]');
|
|
61
|
+
console.log(` Próxima: ${next.id} ${modeTag} ${next.title}`);
|
|
62
|
+
}
|
|
63
|
+
else if (slices.length > 0) {
|
|
64
|
+
console.log(` Estado: ${pc.yellow('Bloqueado em dependências')}`);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
console.log('');
|
|
68
|
+
}
|
|
69
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Resolves the root directory of the installed `tech-os` package
|
|
3
|
+
* (works both from `src/` during development and `dist/` when built).
|
|
4
|
+
*/
|
|
5
|
+
export declare function getPackageRoot(): string;
|
|
6
|
+
/**
|
|
7
|
+
* Resolves a path inside the package's `templates/` directory.
|
|
8
|
+
*/
|
|
9
|
+
export declare function getTemplatePath(...segments: string[]): string;
|
|
10
|
+
/**
|
|
11
|
+
* Resolves the `.tech-os` directory in the target project workspace.
|
|
12
|
+
*/
|
|
13
|
+
export declare function getTechOsDir(cwd?: string): string;
|