tech-os 0.1.1 → 0.2.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 +21 -2
- package/dist/cli.js +23 -1
- package/dist/commands/doctor.d.ts +1 -0
- package/dist/commands/doctor.js +64 -0
- package/dist/commands/guide.js +7 -2
- package/dist/commands/init.d.ts +1 -1
- package/dist/commands/init.js +20 -73
- package/dist/commands/new.d.ts +1 -0
- package/dist/commands/new.js +43 -0
- package/dist/commands/run.js +37 -12
- package/dist/commands/update.d.ts +1 -0
- package/dist/commands/update.js +17 -0
- package/dist/core/installer.d.ts +14 -0
- package/dist/core/installer.js +98 -0
- package/dist/core/secret-guard.d.ts +10 -0
- package/dist/core/secret-guard.js +69 -0
- package/dist/tests/init-update.test.d.ts +1 -0
- package/dist/tests/init-update.test.js +35 -0
- package/dist/tests/secret-guard.test.d.ts +1 -0
- package/dist/tests/secret-guard.test.js +26 -0
- package/docs/tech-os-guia.html +13 -8
- package/docs/tech-os-guia.pdf +0 -0
- package/package.json +3 -2
- package/templates/profiles/_design.md +16 -0
- package/templates/rules/tech-os-core.md +4 -1
- package/templates/skills/tos-design/SKILL.md +28 -0
- package/templates/skills/tos-security/SKILL.md +30 -0
package/README.md
CHANGED
|
@@ -64,14 +64,30 @@ Inicializa o Tech OS no projeto atual. Pergunta quais ferramentas de IA você us
|
|
|
64
64
|
- `mvp`: pragmático, testes nos fluxos críticos.
|
|
65
65
|
- `producao`: rigor alto, baseline de segurança, meta de cobertura >= 80%.
|
|
66
66
|
- `estudo`: foco em clareza, aprendizado e explicação de trade-offs.
|
|
67
|
+
- `-d, --design` — Cria também `.tech-os/_design.md` para projetos com Frontend/UI.
|
|
67
68
|
|
|
68
69
|
**Exemplo:**
|
|
69
70
|
```bash
|
|
70
|
-
tech-os init --tools antigravity,cursor --profile producao
|
|
71
|
+
tech-os init --tools antigravity,cursor --profile producao --design
|
|
71
72
|
```
|
|
72
73
|
|
|
73
74
|
---
|
|
74
75
|
|
|
76
|
+
### `tech-os update`
|
|
77
|
+
Atualiza as skills (`tos-*`) e os blocos de regras (`AGENTS.md`, `CLAUDE.md`, `.cursor/rules/tech-os.mdc`) para a versão mais recente do Tech OS **sem sobrescrever** `.tech-os/00-manifesto.md`, `_dominio.md`, `_design.md` ou suas specs.
|
|
78
|
+
|
|
79
|
+
---
|
|
80
|
+
|
|
81
|
+
### `tech-os new <slug>`
|
|
82
|
+
Cria automaticamente a próxima pasta numerada da feature em `.tech-os/<NNN>-<slug>/` com um `01-discovery.md` inicial.
|
|
83
|
+
|
|
84
|
+
---
|
|
85
|
+
|
|
86
|
+
### `tech-os doctor`
|
|
87
|
+
Faz um diagnóstico de saúde do projeto: verifica se há Git inicializado, se o `.gitignore` protege `.env`, se `.tech-os/00-manifesto.md` existe, quais runners (`claude`, `codex`) estão no PATH e roda o **Secret Guard** nas alterações locais.
|
|
88
|
+
|
|
89
|
+
---
|
|
90
|
+
|
|
75
91
|
### `tech-os status`
|
|
76
92
|
Faz uma leitura da pasta `.tech-os/` e exibe um painel no terminal com:
|
|
77
93
|
- Status da fundação (`00-manifesto.md` e `_dominio.md`).
|
|
@@ -122,9 +138,11 @@ No chat do seu agente (Antigravity, Claude Code, Cursor), você aciona as skills
|
|
|
122
138
|
| **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
139
|
| **1** | **`tos-discovery`** | `01-discovery.md` | Entrevista você pergunta por pergunta para revelar **Unknown Knowns** e **Unknown Unknowns** antes de codar. |
|
|
124
140
|
| **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`**). |
|
|
141
|
+
| **2.5** | **`tos-design`** | `02-design.md` *(opcional)* | Define hierarquia visual, estados (`loading`, `empty`, `error`, `success`), responsividade e acessibilidade para UI. |
|
|
125
142
|
| **3** | **`tos-contratos`** | `03-contratos.md` *(opcional)* | Detalha rotas de API, schemas de dados, códigos de erro e regras de segurança. |
|
|
126
143
|
| **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-
|
|
144
|
+
| **5** | **`tos-security`** | *(auditoria)* | Audita segredos, validação de input, auth, PII em logs e dependências antes de fechar PR/feature. |
|
|
145
|
+
| **6** | **`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
146
|
|
|
129
147
|
---
|
|
130
148
|
|
|
@@ -139,6 +157,7 @@ seu-projeto/
|
|
|
139
157
|
└── .tech-os/
|
|
140
158
|
├── 00-manifesto.md # Lei do projeto (stack, segurança, DoD)
|
|
141
159
|
├── _dominio.md # Glossário de negócio
|
|
160
|
+
├── _design.md # Padrões visuais e de UI (opcional)
|
|
142
161
|
└── 001-minha-feature/
|
|
143
162
|
├── 01-discovery.md # Entendimento e decisões
|
|
144
163
|
├── 02-blueprint.md # PRD de engenharia e impacto
|
package/dist/cli.js
CHANGED
|
@@ -1,23 +1,39 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { Command } from 'commander';
|
|
3
3
|
import { runInit } from './commands/init.js';
|
|
4
|
+
import { runUpdate } from './commands/update.js';
|
|
4
5
|
import { runStatus } from './commands/status.js';
|
|
5
6
|
import { runLoop } from './commands/run.js';
|
|
7
|
+
import { runDoctor } from './commands/doctor.js';
|
|
8
|
+
import { runNewFeature } from './commands/new.js';
|
|
6
9
|
import { runGuide } from './commands/guide.js';
|
|
7
10
|
const program = new Command();
|
|
8
11
|
program
|
|
9
12
|
.name('tech-os')
|
|
10
13
|
.description('Tech OS — Spec-Driven Development, Context Engineering & Autonomous Loop')
|
|
11
|
-
.version('0.
|
|
14
|
+
.version('0.2.0');
|
|
12
15
|
program
|
|
13
16
|
.command('init')
|
|
14
17
|
.description('Inicializa o Tech OS no projeto atual (skills, regras e manifesto)')
|
|
15
18
|
.option('-y, --yes', 'Usa configurações padrão sem perguntas interativas')
|
|
16
19
|
.option('-t, --tools <tools>', 'Lista separada por vírgula: antigravity,claude,cursor,codex')
|
|
17
20
|
.option('-p, --profile <profile>', 'Perfil do manifesto: mvp | producao | estudo')
|
|
21
|
+
.option('-d, --design', 'Cria também o arquivo .tech-os/_design.md para projetos com UI')
|
|
18
22
|
.action(async (options) => {
|
|
19
23
|
await runInit(options);
|
|
20
24
|
});
|
|
25
|
+
program
|
|
26
|
+
.command('update')
|
|
27
|
+
.description('Atualiza skills e regras de contexto sem sobrescrever .tech-os/')
|
|
28
|
+
.action(async () => {
|
|
29
|
+
await runUpdate();
|
|
30
|
+
});
|
|
31
|
+
program
|
|
32
|
+
.command('new <slug>')
|
|
33
|
+
.description('Cria uma nova pasta numerada em .tech-os/<NNN>-<slug>/')
|
|
34
|
+
.action(async (slug) => {
|
|
35
|
+
await runNewFeature(slug);
|
|
36
|
+
});
|
|
21
37
|
program
|
|
22
38
|
.command('status')
|
|
23
39
|
.description('Mostra o status das features e fatias em .tech-os/')
|
|
@@ -41,6 +57,12 @@ program
|
|
|
41
57
|
commit: options.commit,
|
|
42
58
|
});
|
|
43
59
|
});
|
|
60
|
+
program
|
|
61
|
+
.command('doctor')
|
|
62
|
+
.description('Verifica saúde do ambiente (Git, .gitignore, runners e Secret Guard)')
|
|
63
|
+
.action(async () => {
|
|
64
|
+
await runDoctor();
|
|
65
|
+
});
|
|
44
66
|
program
|
|
45
67
|
.command('guide')
|
|
46
68
|
.description('Exibe um resumo didático da metodologia Tech OS no terminal')
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function runDoctor(cwd?: string): Promise<void>;
|
|
@@ -0,0 +1,64 @@
|
|
|
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 { detectInstalledTools, fileExists } from '../core/installer.js';
|
|
6
|
+
import { getTechOsDir } from '../core/paths.js';
|
|
7
|
+
import { scanWorkingTreeForSecrets } from '../core/secret-guard.js';
|
|
8
|
+
function checkCommandAvailable(cmd) {
|
|
9
|
+
const res = spawnSync(cmd, ['--version'], { stdio: 'ignore', shell: true });
|
|
10
|
+
return res.status === 0;
|
|
11
|
+
}
|
|
12
|
+
export async function runDoctor(cwd = process.cwd()) {
|
|
13
|
+
console.log(pc.bold(pc.cyan('\n🩺 Tech OS — Diagnóstico do Projeto\n')));
|
|
14
|
+
let warnings = 0;
|
|
15
|
+
// 1. Git repository
|
|
16
|
+
const hasGit = await fileExists(path.join(cwd, '.git'));
|
|
17
|
+
console.log(hasGit ? ` ${pc.green('✓')} Repositório Git inicializado` : ` ${pc.yellow('⚠')} Repositório Git não encontrado (commits automáticos do run não funcionarão)`);
|
|
18
|
+
if (!hasGit)
|
|
19
|
+
warnings++;
|
|
20
|
+
// 2. .gitignore protecting .env
|
|
21
|
+
const gitignorePath = path.join(cwd, '.gitignore');
|
|
22
|
+
let envIgnored = false;
|
|
23
|
+
if (await fileExists(gitignorePath)) {
|
|
24
|
+
const content = await fs.readFile(gitignorePath, 'utf-8');
|
|
25
|
+
envIgnored = /^\s*\.env/m.test(content);
|
|
26
|
+
}
|
|
27
|
+
console.log(envIgnored ? ` ${pc.green('✓')} .gitignore protege arquivos .env` : ` ${pc.yellow('⚠')} .env não está listado no .gitignore`);
|
|
28
|
+
if (!envIgnored)
|
|
29
|
+
warnings++;
|
|
30
|
+
// 3. .tech-os/ foundation
|
|
31
|
+
const techOsDir = getTechOsDir(cwd);
|
|
32
|
+
const hasManifesto = await fileExists(path.join(techOsDir, '00-manifesto.md'));
|
|
33
|
+
console.log(hasManifesto ? ` ${pc.green('✓')} .tech-os/00-manifesto.md presente` : ` ${pc.red('✗')} .tech-os/00-manifesto.md ausente (rode tech-os init)`);
|
|
34
|
+
if (!hasManifesto)
|
|
35
|
+
warnings++;
|
|
36
|
+
// 4. Tools detected
|
|
37
|
+
const tools = await detectInstalledTools(cwd);
|
|
38
|
+
console.log(tools.length > 0
|
|
39
|
+
? ` ${pc.green('✓')} Integrações detectadas: ${tools.join(', ')}`
|
|
40
|
+
: ` ${pc.yellow('⚠')} Nenhuma integração (Antigravity/Claude/Cursor/Codex) detectada`);
|
|
41
|
+
if (tools.length === 0)
|
|
42
|
+
warnings++;
|
|
43
|
+
// 5. Runners available in PATH
|
|
44
|
+
const hasClaude = checkCommandAvailable('claude');
|
|
45
|
+
const hasCodex = checkCommandAvailable('codex');
|
|
46
|
+
console.log(` ${pc.dim('•')} Runners no PATH: claude=${hasClaude ? pc.green('sim') : pc.dim('não')} · codex=${hasCodex ? pc.green('sim') : pc.dim('não')}`);
|
|
47
|
+
// 6. Secret Guard scan on working tree
|
|
48
|
+
if (hasGit) {
|
|
49
|
+
const secrets = await scanWorkingTreeForSecrets(cwd);
|
|
50
|
+
if (secrets.length === 0) {
|
|
51
|
+
console.log(` ${pc.green('✓')} Secret Guard: nenhum segredo exposto nas alterações locais`);
|
|
52
|
+
}
|
|
53
|
+
else {
|
|
54
|
+
warnings += secrets.length;
|
|
55
|
+
console.log(` ${pc.red('✗')} Secret Guard encontrou ${secrets.length} alerta(s):`);
|
|
56
|
+
for (const s of secrets) {
|
|
57
|
+
console.log(` ${pc.red('•')} ${s.file}: ${s.reason}`);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
console.log(warnings === 0
|
|
62
|
+
? pc.green('\nTudo saudável! Projeto pronto para usar o Tech OS.\n')
|
|
63
|
+
: pc.yellow(`\nDiagnóstico concluído com ${warnings} atenção(ões).\n`));
|
|
64
|
+
}
|
package/dist/commands/guide.js
CHANGED
|
@@ -15,16 +15,21 @@ export function runGuide() {
|
|
|
15
15
|
console.log(' • Known Unknowns: lacunas que você sabe que precisa descobrir.');
|
|
16
16
|
console.log(' • Unknown Knowns: regras óbvias do dia a dia que você esquece de dizer.');
|
|
17
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
|
|
18
|
+
console.log(pc.bold('4. O Fluxo das Skills (Spec-Driven Development)'));
|
|
19
19
|
console.log(` 0. ${pc.cyan('tos-manifesto')} → Cria a "lei" do projeto (00-manifesto.md + _dominio.md)`);
|
|
20
20
|
console.log(` 1. ${pc.cyan('tos-discovery')} → Entrevista para alinhar problema e incógnitas (01-discovery.md)`);
|
|
21
21
|
console.log(` 2. ${pc.cyan('tos-blueprint')} → PRD técnico + impacto local/estrutural (02-blueprint.md)`);
|
|
22
|
+
console.log(` * ${pc.cyan('tos-design')} → Especificação visual e estados de UI (02-design.md, opc.)`);
|
|
22
23
|
console.log(` 3. ${pc.cyan('tos-contratos')} → Contratos de API/schema/segurança (03-contratos.md, opc.)`);
|
|
23
24
|
console.log(` 4. ${pc.cyan('tos-planejar')} → Fatias executáveis [AUTO] e [HUMANO] (04-plano.md)`);
|
|
25
|
+
console.log(` * ${pc.cyan('tos-security')} → Auditoria de segurança antes de fechar PR/feature`);
|
|
24
26
|
console.log(` * ${pc.cyan('tos-sync')} → Atualiza a spec ANTES do código se algo mudar\n`);
|
|
25
27
|
console.log(pc.bold('5. Comandos da CLI'));
|
|
26
28
|
console.log(` ${pc.green('tech-os init')} Instala skills, regras e manifesto no projeto`);
|
|
29
|
+
console.log(` ${pc.green('tech-os update')} Atualiza skills/regras mantendo .tech-os/ intacto`);
|
|
30
|
+
console.log(` ${pc.green('tech-os new <slug>')} Cria nova pasta numerada .tech-os/00X-<slug>/`);
|
|
27
31
|
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 +
|
|
32
|
+
console.log(` ${pc.green('tech-os run <feature>')} Executa fatias [AUTO] em contexto limpo + Secret Guard`);
|
|
33
|
+
console.log(` ${pc.green('tech-os doctor')} Diagnostica Git, .gitignore, runners e segredos`);
|
|
29
34
|
console.log(` ${pc.green('tech-os guide')} Exibe este guia no terminal\n`);
|
|
30
35
|
}
|
package/dist/commands/init.d.ts
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
export type ToolTarget = 'antigravity' | 'claude' | 'cursor' | 'codex';
|
|
2
1
|
export type ManifestoProfile = 'mvp' | 'producao' | 'estudo';
|
|
3
2
|
export interface InitOptions {
|
|
4
3
|
yes?: boolean;
|
|
5
4
|
tools?: string;
|
|
6
5
|
profile?: ManifestoProfile;
|
|
6
|
+
design?: boolean;
|
|
7
7
|
}
|
|
8
8
|
export declare function runInit(options: InitOptions, cwd?: string): Promise<void>;
|
package/dist/commands/init.js
CHANGED
|
@@ -1,55 +1,9 @@
|
|
|
1
1
|
import fs from 'node:fs/promises';
|
|
2
2
|
import path from 'node:path';
|
|
3
|
-
import { checkbox, select } from '@inquirer/prompts';
|
|
3
|
+
import { checkbox, confirm, select } from '@inquirer/prompts';
|
|
4
4
|
import pc from 'picocolors';
|
|
5
|
+
import { fileExists, installToolsAndRules } from '../core/installer.js';
|
|
5
6
|
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
7
|
function parseToolsFlag(raw) {
|
|
54
8
|
if (!raw)
|
|
55
9
|
return null;
|
|
@@ -64,6 +18,7 @@ export async function runInit(options, cwd = process.cwd()) {
|
|
|
64
18
|
console.log(pc.bold(pc.cyan('\n⚡ Tech OS — Inicialização do Projeto\n')));
|
|
65
19
|
let tools = parseToolsFlag(options.tools) ?? [];
|
|
66
20
|
let profile = options.profile ?? 'mvp';
|
|
21
|
+
let includeDesign = Boolean(options.design);
|
|
67
22
|
if (options.yes) {
|
|
68
23
|
if (tools.length === 0)
|
|
69
24
|
tools = ['antigravity'];
|
|
@@ -92,42 +47,34 @@ export async function runInit(options, cwd = process.cwd()) {
|
|
|
92
47
|
default: 'mvp',
|
|
93
48
|
});
|
|
94
49
|
}
|
|
50
|
+
if (options.design === undefined) {
|
|
51
|
+
includeDesign = await confirm({
|
|
52
|
+
message: 'O projeto tem Frontend/UI e você quer criar .tech-os/_design.md?',
|
|
53
|
+
default: false,
|
|
54
|
+
});
|
|
55
|
+
}
|
|
95
56
|
}
|
|
96
|
-
const
|
|
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
|
-
}
|
|
57
|
+
const installedActions = await installToolsAndRules(tools, cwd);
|
|
118
58
|
// Create .tech-os/ foundation if missing
|
|
119
59
|
const techOsDir = getTechOsDir(cwd);
|
|
120
60
|
await fs.mkdir(techOsDir, { recursive: true });
|
|
121
61
|
const manifestoDest = path.join(techOsDir, '00-manifesto.md');
|
|
122
|
-
if (!(await
|
|
62
|
+
if (!(await fileExists(manifestoDest))) {
|
|
123
63
|
await fs.copyFile(getTemplatePath('profiles', `${profile}.md`), manifestoDest);
|
|
124
64
|
installedActions.push(`.tech-os/00-manifesto.md (perfil: ${profile})`);
|
|
125
65
|
}
|
|
126
66
|
const dominioDest = path.join(techOsDir, '_dominio.md');
|
|
127
|
-
if (!(await
|
|
67
|
+
if (!(await fileExists(dominioDest))) {
|
|
128
68
|
await fs.copyFile(getTemplatePath('profiles', '_dominio.md'), dominioDest);
|
|
129
69
|
installedActions.push('.tech-os/_dominio.md');
|
|
130
70
|
}
|
|
71
|
+
if (includeDesign) {
|
|
72
|
+
const designDest = path.join(techOsDir, '_design.md');
|
|
73
|
+
if (!(await fileExists(designDest))) {
|
|
74
|
+
await fs.copyFile(getTemplatePath('profiles', '_design.md'), designDest);
|
|
75
|
+
installedActions.push('.tech-os/_design.md');
|
|
76
|
+
}
|
|
77
|
+
}
|
|
131
78
|
console.log(pc.green('✓ Tech OS configurado com sucesso!\n'));
|
|
132
79
|
for (const item of installedActions) {
|
|
133
80
|
console.log(` ${pc.dim('•')} ${item}`);
|
|
@@ -135,5 +82,5 @@ export async function runInit(options, cwd = process.cwd()) {
|
|
|
135
82
|
console.log(pc.bold('\nPróximos passos:'));
|
|
136
83
|
console.log(` 1. Ajuste a stack em ${pc.cyan('.tech-os/00-manifesto.md')} (ou rode a skill ${pc.cyan('tos-manifesto')})`);
|
|
137
84
|
console.log(` 2. Na sua próxima feature, chame a skill ${pc.cyan('tos-discovery')} no seu agente`);
|
|
138
|
-
console.log(` 3.
|
|
85
|
+
console.log(` 3. Valide o ambiente com ${pc.cyan('tech-os doctor')} e acompanhe com ${pc.cyan('tech-os status')}\n`);
|
|
139
86
|
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function runNewFeature(rawSlug: string, cwd?: string): Promise<void>;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import pc from 'picocolors';
|
|
4
|
+
import { fileExists } from '../core/installer.js';
|
|
5
|
+
import { getTechOsDir } from '../core/paths.js';
|
|
6
|
+
function sanitizeSlug(raw) {
|
|
7
|
+
return raw
|
|
8
|
+
.trim()
|
|
9
|
+
.toLowerCase()
|
|
10
|
+
.replace(/[^a-z0-9-]+/g, '-')
|
|
11
|
+
.replace(/^-+|-+$/g, '');
|
|
12
|
+
}
|
|
13
|
+
export async function runNewFeature(rawSlug, cwd = process.cwd()) {
|
|
14
|
+
const slug = sanitizeSlug(rawSlug);
|
|
15
|
+
if (!slug) {
|
|
16
|
+
throw new Error('Informe um slug válido (ex: tech-os new auth-jwt).');
|
|
17
|
+
}
|
|
18
|
+
const techOsDir = getTechOsDir(cwd);
|
|
19
|
+
await fs.mkdir(techOsDir, { recursive: true });
|
|
20
|
+
const entries = await fs.readdir(techOsDir, { withFileTypes: true });
|
|
21
|
+
let maxNum = 0;
|
|
22
|
+
for (const entry of entries) {
|
|
23
|
+
if (!entry.isDirectory())
|
|
24
|
+
continue;
|
|
25
|
+
const match = entry.name.match(/^(\d+)-/);
|
|
26
|
+
if (match) {
|
|
27
|
+
const num = Number.parseInt(match[1], 10);
|
|
28
|
+
if (num > maxNum)
|
|
29
|
+
maxNum = num;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
const nextPrefix = String(maxNum + 1).padStart(3, '0');
|
|
33
|
+
const folderName = `${nextPrefix}-${slug}`;
|
|
34
|
+
const featureDir = path.join(techOsDir, folderName);
|
|
35
|
+
if (await fileExists(featureDir)) {
|
|
36
|
+
throw new Error(`A pasta .tech-os/${folderName} já existe.`);
|
|
37
|
+
}
|
|
38
|
+
await fs.mkdir(featureDir, { recursive: true });
|
|
39
|
+
const discoveryPath = path.join(featureDir, '01-discovery.md');
|
|
40
|
+
await fs.writeFile(discoveryPath, `# Discovery: ${folderName}\n\nslug: ${slug}\nescopo: feature\n\n## Problema\n_(descreva a dor ou necessidade)_\n\n## Solução Acordada\n_(preencher com a skill tos-discovery)_\n\n## Decisões e Premissas\n- \n\n## Fora de Escopo\n- \n`, 'utf-8');
|
|
41
|
+
console.log(pc.green(`\n✓ Feature criada: .tech-os/${folderName}/`));
|
|
42
|
+
console.log(` Próximo passo: chame a skill ${pc.cyan('tos-discovery')} no seu agente.\n`);
|
|
43
|
+
}
|
package/dist/commands/run.js
CHANGED
|
@@ -4,6 +4,7 @@ import { spawnSync } from 'node:child_process';
|
|
|
4
4
|
import pc from 'picocolors';
|
|
5
5
|
import { getTechOsDir } from '../core/paths.js';
|
|
6
6
|
import { findNextUnblockedSlice, readPlanFile, updateSliceStatus, } from '../core/plan-parser.js';
|
|
7
|
+
import { scanWorkingTreeForSecrets } from '../core/secret-guard.js';
|
|
7
8
|
async function readIfExists(filePath) {
|
|
8
9
|
try {
|
|
9
10
|
return await fs.readFile(filePath, 'utf-8');
|
|
@@ -29,18 +30,16 @@ function buildCleanPrompt(params) {
|
|
|
29
30
|
`- User Story: ${params.slice.us}`,
|
|
30
31
|
`- Feature: ${params.feature}`,
|
|
31
32
|
];
|
|
32
|
-
if (params.manifesto)
|
|
33
|
+
if (params.manifesto)
|
|
33
34
|
parts.push('', '## 00-manifesto.md', params.manifesto.trim());
|
|
34
|
-
|
|
35
|
-
if (params.dominio) {
|
|
35
|
+
if (params.dominio)
|
|
36
36
|
parts.push('', '## _dominio.md', params.dominio.trim());
|
|
37
|
-
|
|
38
|
-
|
|
37
|
+
if (params.design)
|
|
38
|
+
parts.push('', '## _design.md', params.design.trim());
|
|
39
|
+
if (params.blueprint)
|
|
39
40
|
parts.push('', '## 02-blueprint.md', params.blueprint.trim());
|
|
40
|
-
|
|
41
|
-
if (params.contratos) {
|
|
41
|
+
if (params.contratos)
|
|
42
42
|
parts.push('', '## 03-contratos.md', params.contratos.trim());
|
|
43
|
-
}
|
|
44
43
|
parts.push('', '## Instrução Final', `Implemente ${params.slice.id}, escreva/atualize os testes correspondentes e garanta que tudo passe.`);
|
|
45
44
|
return parts.join('\n');
|
|
46
45
|
}
|
|
@@ -79,6 +78,10 @@ function runShellCommand(command) {
|
|
|
79
78
|
});
|
|
80
79
|
return res.status === 0;
|
|
81
80
|
}
|
|
81
|
+
function printSummary(completedSlices, startTimeMs) {
|
|
82
|
+
const elapsedSec = ((Date.now() - startTimeMs) / 1000).toFixed(1);
|
|
83
|
+
console.log(pc.dim(` Resumo: ${completedSlices.length} fatia(s) concluída(s) [${completedSlices.join(', ') || '-'}] em ${elapsedSec}s\n`));
|
|
84
|
+
}
|
|
82
85
|
export async function runLoop(feature, maxIterationsArg, options, cwd = process.cwd()) {
|
|
83
86
|
const maxIterations = maxIterationsArg ? Number.parseInt(maxIterationsArg, 10) : 10;
|
|
84
87
|
if (Number.isNaN(maxIterations) || maxIterations <= 0) {
|
|
@@ -96,11 +99,14 @@ export async function runLoop(feature, maxIterationsArg, options, cwd = process.
|
|
|
96
99
|
}
|
|
97
100
|
const manifesto = await readIfExists(path.join(techOsDir, '00-manifesto.md'));
|
|
98
101
|
const dominio = await readIfExists(path.join(techOsDir, '_dominio.md'));
|
|
102
|
+
const design = await readIfExists(path.join(techOsDir, '_design.md'));
|
|
99
103
|
const blueprint = await readIfExists(path.join(featureDir, '02-blueprint.md'));
|
|
100
104
|
const contratos = await readIfExists(path.join(featureDir, '03-contratos.md'));
|
|
101
105
|
const testCmd = extractTestCommand(manifesto, options.testCmd);
|
|
102
106
|
const runner = options.runner ?? 'claude';
|
|
103
107
|
const shouldCommit = options.commit !== false;
|
|
108
|
+
const startTimeMs = Date.now();
|
|
109
|
+
const completedSlices = [];
|
|
104
110
|
console.log(pc.bold(pc.cyan(`\n🔁 Tech OS Runner — ${feature}\n`)));
|
|
105
111
|
console.log(` Runner: ${runner}${options.dryRun ? pc.yellow(' (dry-run)') : ''}`);
|
|
106
112
|
console.log(` DoD: ${testCmd ?? pc.dim('nenhum comando configurado')}\n`);
|
|
@@ -110,16 +116,18 @@ export async function runLoop(feature, maxIterationsArg, options, cwd = process.
|
|
|
110
116
|
if (!next) {
|
|
111
117
|
const allDone = slices.length > 0 && slices.every((s) => s.status === 'done');
|
|
112
118
|
if (allDone) {
|
|
113
|
-
console.log(pc.green('✓ Todas as fatias foram concluídas! <promise>COMPLETE</promise
|
|
119
|
+
console.log(pc.green('✓ Todas as fatias foram concluídas! <promise>COMPLETE</promise>'));
|
|
114
120
|
}
|
|
115
121
|
else {
|
|
116
|
-
console.log(pc.yellow('⚠ Nenhuma fatia desbloqueada encontrada. Verifique dependências em 04-plano.md
|
|
122
|
+
console.log(pc.yellow('⚠ Nenhuma fatia desbloqueada encontrada. Verifique dependências em 04-plano.md.'));
|
|
117
123
|
}
|
|
124
|
+
printSummary(completedSlices, startTimeMs);
|
|
118
125
|
return;
|
|
119
126
|
}
|
|
120
127
|
if (next.mode === 'HUMANO') {
|
|
121
128
|
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
|
|
129
|
+
console.log(pc.dim(` Conclua esta etapa manualmente, marque [x] em 04-plano.md e rode "tech-os run ${feature}" novamente.`));
|
|
130
|
+
printSummary(completedSlices, startTimeMs);
|
|
123
131
|
return;
|
|
124
132
|
}
|
|
125
133
|
console.log(pc.bold(`→ Iteração ${iteration}/${maxIterations}: [${next.id}] ${next.title}`));
|
|
@@ -128,6 +136,7 @@ export async function runLoop(feature, maxIterationsArg, options, cwd = process.
|
|
|
128
136
|
slice: next,
|
|
129
137
|
manifesto,
|
|
130
138
|
dominio,
|
|
139
|
+
design,
|
|
131
140
|
blueprint,
|
|
132
141
|
contratos,
|
|
133
142
|
});
|
|
@@ -142,6 +151,7 @@ export async function runLoop(feature, maxIterationsArg, options, cwd = process.
|
|
|
142
151
|
if (!agentOk) {
|
|
143
152
|
console.log(pc.red(`✗ Runner falhou na fatia ${next.id}. Marcando [~] e interrompendo.`));
|
|
144
153
|
process.exitCode = 1;
|
|
154
|
+
printSummary(completedSlices, startTimeMs);
|
|
145
155
|
return;
|
|
146
156
|
}
|
|
147
157
|
if (testCmd) {
|
|
@@ -150,10 +160,24 @@ export async function runLoop(feature, maxIterationsArg, options, cwd = process.
|
|
|
150
160
|
if (!testOk) {
|
|
151
161
|
console.log(pc.red(`✗ DoD falhou na fatia ${next.id}. Marcando [~] e interrompendo.`));
|
|
152
162
|
process.exitCode = 1;
|
|
163
|
+
printSummary(completedSlices, startTimeMs);
|
|
164
|
+
return;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
if (shouldCommit) {
|
|
168
|
+
const secrets = await scanWorkingTreeForSecrets(cwd);
|
|
169
|
+
if (secrets.length > 0) {
|
|
170
|
+
console.log(pc.red(`✗ Secret Guard bloqueou o commit da fatia ${next.id}:`));
|
|
171
|
+
for (const s of secrets) {
|
|
172
|
+
console.log(` ${pc.red('•')} ${s.file}: ${s.reason}`);
|
|
173
|
+
}
|
|
174
|
+
process.exitCode = 1;
|
|
175
|
+
printSummary(completedSlices, startTimeMs);
|
|
153
176
|
return;
|
|
154
177
|
}
|
|
155
178
|
}
|
|
156
179
|
await updateSliceStatus(planPath, next.id, 'done');
|
|
180
|
+
completedSlices.push(next.id);
|
|
157
181
|
console.log(pc.green(`✓ ${next.id} concluída!`));
|
|
158
182
|
if (shouldCommit) {
|
|
159
183
|
const commitMsg = `feat(${next.id}): ${next.title}`;
|
|
@@ -167,5 +191,6 @@ export async function runLoop(feature, maxIterationsArg, options, cwd = process.
|
|
|
167
191
|
}
|
|
168
192
|
console.log('');
|
|
169
193
|
}
|
|
170
|
-
console.log(pc.yellow(`⏹ Limite de ${maxIterations} iterações atingido
|
|
194
|
+
console.log(pc.yellow(`⏹ Limite de ${maxIterations} iterações atingido.`));
|
|
195
|
+
printSummary(completedSlices, startTimeMs);
|
|
171
196
|
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function runUpdate(cwd?: string): Promise<void>;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import pc from 'picocolors';
|
|
2
|
+
import { detectInstalledTools, installToolsAndRules } from '../core/installer.js';
|
|
3
|
+
export async function runUpdate(cwd = process.cwd()) {
|
|
4
|
+
console.log(pc.bold(pc.cyan('\n🔄 Tech OS — Atualizando Skills e Regras\n')));
|
|
5
|
+
const tools = await detectInstalledTools(cwd);
|
|
6
|
+
if (tools.length === 0) {
|
|
7
|
+
console.log(pc.yellow('Nenhuma instalação do Tech OS detectada neste projeto.'));
|
|
8
|
+
console.log(`Rode ${pc.cyan('tech-os init')} para inicializar.\n`);
|
|
9
|
+
return;
|
|
10
|
+
}
|
|
11
|
+
const updated = await installToolsAndRules(tools, cwd);
|
|
12
|
+
console.log(pc.green('✓ Skills e regras atualizadas sem alterar seu .tech-os/!\n'));
|
|
13
|
+
for (const item of updated) {
|
|
14
|
+
console.log(` ${pc.dim('•')} ${item}`);
|
|
15
|
+
}
|
|
16
|
+
console.log('');
|
|
17
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export type ToolTarget = 'antigravity' | 'claude' | 'cursor' | 'codex';
|
|
2
|
+
export declare function fileExists(targetPath: string): Promise<boolean>;
|
|
3
|
+
/**
|
|
4
|
+
* Inserts or replaces the Tech OS block inside a markdown rule file (AGENTS.md / CLAUDE.md).
|
|
5
|
+
*/
|
|
6
|
+
export declare function upsertMarkedSection(filePath: string, coreContent: string): Promise<void>;
|
|
7
|
+
/**
|
|
8
|
+
* Detects which AI tool integrations are already present in the workspace.
|
|
9
|
+
*/
|
|
10
|
+
export declare function detectInstalledTools(cwd: string): Promise<ToolTarget[]>;
|
|
11
|
+
/**
|
|
12
|
+
* Installs or updates skills and permanent rule files for the chosen AI tools.
|
|
13
|
+
*/
|
|
14
|
+
export declare function installToolsAndRules(tools: ToolTarget[], cwd: string): Promise<string[]>;
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { getTemplatePath } from './paths.js';
|
|
4
|
+
const START_MARKER = '<!-- tech-os:start -->';
|
|
5
|
+
const END_MARKER = '<!-- tech-os:end -->';
|
|
6
|
+
export async function fileExists(targetPath) {
|
|
7
|
+
try {
|
|
8
|
+
await fs.access(targetPath);
|
|
9
|
+
return true;
|
|
10
|
+
}
|
|
11
|
+
catch {
|
|
12
|
+
return false;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
async function copySkills(targetDir) {
|
|
16
|
+
const skillsSrc = getTemplatePath('skills');
|
|
17
|
+
const entries = await fs.readdir(skillsSrc, { withFileTypes: true });
|
|
18
|
+
let count = 0;
|
|
19
|
+
for (const entry of entries) {
|
|
20
|
+
if (!entry.isDirectory())
|
|
21
|
+
continue;
|
|
22
|
+
const srcSkill = path.join(skillsSrc, entry.name, 'SKILL.md');
|
|
23
|
+
const destDir = path.join(targetDir, entry.name);
|
|
24
|
+
await fs.mkdir(destDir, { recursive: true });
|
|
25
|
+
await fs.copyFile(srcSkill, path.join(destDir, 'SKILL.md'));
|
|
26
|
+
count++;
|
|
27
|
+
}
|
|
28
|
+
return count;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Inserts or replaces the Tech OS block inside a markdown rule file (AGENTS.md / CLAUDE.md).
|
|
32
|
+
*/
|
|
33
|
+
export async function upsertMarkedSection(filePath, coreContent) {
|
|
34
|
+
const block = `${START_MARKER}\n${coreContent.trim()}\n${END_MARKER}`;
|
|
35
|
+
if (!(await fileExists(filePath))) {
|
|
36
|
+
await fs.writeFile(filePath, `${block}\n`, 'utf-8');
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
const existing = await fs.readFile(filePath, 'utf-8');
|
|
40
|
+
const startIdx = existing.indexOf(START_MARKER);
|
|
41
|
+
const endIdx = existing.indexOf(END_MARKER);
|
|
42
|
+
if (startIdx !== -1 && endIdx !== -1 && endIdx > startIdx) {
|
|
43
|
+
const before = existing.slice(0, startIdx);
|
|
44
|
+
const after = existing.slice(endIdx + END_MARKER.length);
|
|
45
|
+
await fs.writeFile(filePath, `${before}${block}${after}`, 'utf-8');
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
const separator = existing.endsWith('\n') ? '\n' : '\n\n';
|
|
49
|
+
await fs.writeFile(filePath, `${existing}${separator}${block}\n`, 'utf-8');
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* Detects which AI tool integrations are already present in the workspace.
|
|
53
|
+
*/
|
|
54
|
+
export async function detectInstalledTools(cwd) {
|
|
55
|
+
const detected = [];
|
|
56
|
+
if (await fileExists(path.join(cwd, '.agents', 'skills'))) {
|
|
57
|
+
detected.push('antigravity');
|
|
58
|
+
}
|
|
59
|
+
else if (await fileExists(path.join(cwd, 'AGENTS.md'))) {
|
|
60
|
+
detected.push('codex');
|
|
61
|
+
}
|
|
62
|
+
if ((await fileExists(path.join(cwd, '.claude', 'skills'))) ||
|
|
63
|
+
(await fileExists(path.join(cwd, 'CLAUDE.md')))) {
|
|
64
|
+
detected.push('claude');
|
|
65
|
+
}
|
|
66
|
+
if (await fileExists(path.join(cwd, '.cursor', 'rules', 'tech-os.mdc'))) {
|
|
67
|
+
detected.push('cursor');
|
|
68
|
+
}
|
|
69
|
+
return detected;
|
|
70
|
+
}
|
|
71
|
+
/**
|
|
72
|
+
* Installs or updates skills and permanent rule files for the chosen AI tools.
|
|
73
|
+
*/
|
|
74
|
+
export async function installToolsAndRules(tools, cwd) {
|
|
75
|
+
const coreRules = await fs.readFile(getTemplatePath('rules', 'tech-os-core.md'), 'utf-8');
|
|
76
|
+
const actions = [];
|
|
77
|
+
if (tools.includes('antigravity') || tools.includes('codex')) {
|
|
78
|
+
await upsertMarkedSection(path.join(cwd, 'AGENTS.md'), coreRules);
|
|
79
|
+
actions.push('AGENTS.md');
|
|
80
|
+
}
|
|
81
|
+
if (tools.includes('antigravity')) {
|
|
82
|
+
const count = await copySkills(path.join(cwd, '.agents', 'skills'));
|
|
83
|
+
actions.push(`.agents/skills/ (${count} skills)`);
|
|
84
|
+
}
|
|
85
|
+
if (tools.includes('claude')) {
|
|
86
|
+
await upsertMarkedSection(path.join(cwd, 'CLAUDE.md'), coreRules);
|
|
87
|
+
const count = await copySkills(path.join(cwd, '.claude', 'skills'));
|
|
88
|
+
actions.push(`CLAUDE.md + .claude/skills/ (${count} skills)`);
|
|
89
|
+
}
|
|
90
|
+
if (tools.includes('cursor')) {
|
|
91
|
+
const cursorDir = path.join(cwd, '.cursor', 'rules');
|
|
92
|
+
await fs.mkdir(cursorDir, { recursive: true });
|
|
93
|
+
const cursorTemplate = await fs.readFile(getTemplatePath('rules', 'cursor-rule.mdc'), 'utf-8');
|
|
94
|
+
await fs.writeFile(path.join(cursorDir, 'tech-os.mdc'), cursorTemplate.replace('{{CORE_RULES}}', coreRules.trim()), 'utf-8');
|
|
95
|
+
actions.push('.cursor/rules/tech-os.mdc');
|
|
96
|
+
}
|
|
97
|
+
return actions;
|
|
98
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export interface SecretFinding {
|
|
2
|
+
file: string;
|
|
3
|
+
reason: string;
|
|
4
|
+
}
|
|
5
|
+
export declare function findSensitiveFileNames(files: string[]): SecretFinding[];
|
|
6
|
+
export declare function findSecretPatterns(file: string, content: string): SecretFinding[];
|
|
7
|
+
/**
|
|
8
|
+
* Scans modified/untracked git files in the workspace for sensitive filenames or inline secret patterns.
|
|
9
|
+
*/
|
|
10
|
+
export declare function scanWorkingTreeForSecrets(cwd?: string): Promise<SecretFinding[]>;
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { spawnSync } from 'node:child_process';
|
|
2
|
+
import fs from 'node:fs/promises';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
const SENSITIVE_FILE_PATTERNS = [
|
|
5
|
+
{ pattern: /(^|\/)\.env($|\.(?!example|sample|template))/i, reason: 'Arquivo .env não deve ser commitado' },
|
|
6
|
+
{ pattern: /\.(pem|key|p12|pfx)$/i, reason: 'Arquivo de chave privada detectado' },
|
|
7
|
+
{ pattern: /(^|\/)(id_rsa|id_ed25519)$/i, reason: 'Chave SSH privada detectada' },
|
|
8
|
+
{ pattern: /(^|\/)credentials\.json$/i, reason: 'Arquivo credentials.json detectado' },
|
|
9
|
+
];
|
|
10
|
+
const SECRET_CONTENT_PATTERNS = [
|
|
11
|
+
{ pattern: /-----BEGIN (?:RSA |EC |OPENSSH |DSA )?PRIVATE KEY-----/, reason: 'Chave privada inline detectada' },
|
|
12
|
+
{ pattern: /\bAKIA[0-9A-Z]{16}\b/, reason: 'Possível AWS Access Key ID (AKIA...)' },
|
|
13
|
+
{ pattern: /\bgh[po]_[A-Za-z0-9]{30,}\b/, reason: 'Possível token GitHub (ghp_/gho_)' },
|
|
14
|
+
{ pattern: /\bsk-[A-Za-z0-9_-]{20,}\b/, reason: 'Possível API key (sk-...)' },
|
|
15
|
+
{ pattern: /\bAIza[0-9A-Za-z_-]{35}\b/, reason: 'Possível Google API key (AIza...)' },
|
|
16
|
+
];
|
|
17
|
+
export function findSensitiveFileNames(files) {
|
|
18
|
+
const findings = [];
|
|
19
|
+
for (const file of files) {
|
|
20
|
+
const normalized = file.replace(/\\/g, '/');
|
|
21
|
+
for (const rule of SENSITIVE_FILE_PATTERNS) {
|
|
22
|
+
if (rule.pattern.test(normalized)) {
|
|
23
|
+
findings.push({ file: normalized, reason: rule.reason });
|
|
24
|
+
break;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
return findings;
|
|
29
|
+
}
|
|
30
|
+
export function findSecretPatterns(file, content) {
|
|
31
|
+
const findings = [];
|
|
32
|
+
for (const rule of SECRET_CONTENT_PATTERNS) {
|
|
33
|
+
if (rule.pattern.test(content)) {
|
|
34
|
+
findings.push({ file, reason: rule.reason });
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
return findings;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Scans modified/untracked git files in the workspace for sensitive filenames or inline secret patterns.
|
|
41
|
+
*/
|
|
42
|
+
export async function scanWorkingTreeForSecrets(cwd = process.cwd()) {
|
|
43
|
+
const res = spawnSync('git', ['status', '--porcelain'], { cwd, encoding: 'utf-8' });
|
|
44
|
+
if (res.status !== 0 || !res.stdout)
|
|
45
|
+
return [];
|
|
46
|
+
const changedFiles = res.stdout
|
|
47
|
+
.split(/\r?\n/)
|
|
48
|
+
.map((line) => line.slice(3).trim())
|
|
49
|
+
.filter(Boolean)
|
|
50
|
+
.map((entry) => {
|
|
51
|
+
const arrowIdx = entry.indexOf(' -> ');
|
|
52
|
+
return arrowIdx !== -1 ? entry.slice(arrowIdx + 4) : entry;
|
|
53
|
+
});
|
|
54
|
+
const findings = [...findSensitiveFileNames(changedFiles)];
|
|
55
|
+
for (const relPath of changedFiles) {
|
|
56
|
+
const fullPath = path.join(cwd, relPath);
|
|
57
|
+
try {
|
|
58
|
+
const stat = await fs.stat(fullPath);
|
|
59
|
+
if (!stat.isFile() || stat.size > 512 * 1024)
|
|
60
|
+
continue;
|
|
61
|
+
const content = await fs.readFile(fullPath, 'utf-8');
|
|
62
|
+
findings.push(...findSecretPatterns(relPath, content));
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
// Ignore deleted or unreadable files
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
return findings;
|
|
69
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { describe, it } from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import fs from 'node:fs/promises';
|
|
4
|
+
import os from 'node:os';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
import { runInit } from '../commands/init.js';
|
|
7
|
+
import { runUpdate } from '../commands/update.js';
|
|
8
|
+
describe('init & update', () => {
|
|
9
|
+
it('preserves existing AGENTS.md content and .tech-os/00-manifesto.md on update', async () => {
|
|
10
|
+
const tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'tech-os-test-'));
|
|
11
|
+
try {
|
|
12
|
+
await fs.writeFile(path.join(tmpDir, 'AGENTS.md'), '# Meu Projeto\n\nRegras próprias.\n', 'utf-8');
|
|
13
|
+
await runInit({ yes: true, tools: 'antigravity', profile: 'mvp', design: true }, tmpDir);
|
|
14
|
+
const agentsAfterInit = await fs.readFile(path.join(tmpDir, 'AGENTS.md'), 'utf-8');
|
|
15
|
+
assert.match(agentsAfterInit, /# Meu Projeto/);
|
|
16
|
+
assert.match(agentsAfterInit, /<!-- tech-os:start -->/);
|
|
17
|
+
// Customize manifesto to verify update does not overwrite it
|
|
18
|
+
const manifestoPath = path.join(tmpDir, '.tech-os', '00-manifesto.md');
|
|
19
|
+
await fs.writeFile(manifestoPath, '# Custom Manifesto\n', 'utf-8');
|
|
20
|
+
// Check _design.md was created
|
|
21
|
+
const designContent = await fs.readFile(path.join(tmpDir, '.tech-os', '_design.md'), 'utf-8');
|
|
22
|
+
assert.match(designContent, /Stack de UI/);
|
|
23
|
+
// Run update
|
|
24
|
+
await runUpdate(tmpDir);
|
|
25
|
+
const manifestoAfterUpdate = await fs.readFile(manifestoPath, 'utf-8');
|
|
26
|
+
assert.equal(manifestoAfterUpdate, '# Custom Manifesto\n');
|
|
27
|
+
// Check new v0.2.0 skills were copied
|
|
28
|
+
const secSkill = await fs.readFile(path.join(tmpDir, '.agents', 'skills', 'tos-security', 'SKILL.md'), 'utf-8');
|
|
29
|
+
assert.match(secSkill, /tos-security/);
|
|
30
|
+
}
|
|
31
|
+
finally {
|
|
32
|
+
await fs.rm(tmpDir, { recursive: true, force: true });
|
|
33
|
+
}
|
|
34
|
+
});
|
|
35
|
+
});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { describe, it } from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { findSecretPatterns, findSensitiveFileNames } from '../core/secret-guard.js';
|
|
4
|
+
describe('secret-guard', () => {
|
|
5
|
+
it('detects sensitive filenames like .env and .pem', () => {
|
|
6
|
+
const findings = findSensitiveFileNames([
|
|
7
|
+
'src/index.ts',
|
|
8
|
+
'.env',
|
|
9
|
+
'.env.production',
|
|
10
|
+
'.env.example',
|
|
11
|
+
'certs/server.pem',
|
|
12
|
+
]);
|
|
13
|
+
assert.equal(findings.length, 3);
|
|
14
|
+
assert.deepEqual(findings.map((f) => f.file), ['.env', '.env.production', 'certs/server.pem']);
|
|
15
|
+
});
|
|
16
|
+
it('detects common inline API keys and private keys', () => {
|
|
17
|
+
const awsDummy = 'AKIA' + '1234567890ABCDEF';
|
|
18
|
+
const ghDummy = 'ghp_' + '1234567890abcdefghijklmnopqrstuvwxyz';
|
|
19
|
+
const findings = findSecretPatterns('src/config.ts', `const key = "${awsDummy}";\nconst gh = "${ghDummy}";`);
|
|
20
|
+
assert.equal(findings.length, 2);
|
|
21
|
+
});
|
|
22
|
+
it('returns empty for clean code', () => {
|
|
23
|
+
const findings = findSecretPatterns('src/app.ts', 'export const PORT = process.env.PORT ?? 3000;');
|
|
24
|
+
assert.equal(findings.length, 0);
|
|
25
|
+
});
|
|
26
|
+
});
|
package/docs/tech-os-guia.html
CHANGED
|
@@ -269,7 +269,7 @@
|
|
|
269
269
|
</div>
|
|
270
270
|
</div>
|
|
271
271
|
<div class="footer">
|
|
272
|
-
<span>Tech OS · v0.
|
|
272
|
+
<span>Tech OS · v0.2.0 · github.com/rlucio01/tech-os</span>
|
|
273
273
|
<span>Página 1 / 8</span>
|
|
274
274
|
</div>
|
|
275
275
|
</section>
|
|
@@ -400,8 +400,8 @@
|
|
|
400
400
|
</div>
|
|
401
401
|
|
|
402
402
|
<div class="card" style="border-left: 4px solid var(--amber);">
|
|
403
|
-
<h3>
|
|
404
|
-
<p>
|
|
403
|
+
<h3>Skills Transversais: <code>tos-design</code> · <code>tos-security</code> · <code>tos-sync</code></h3>
|
|
404
|
+
<p><strong>UI:</strong> <code>tos-design</code> define estados e layout antes do código · <strong>Segurança:</strong> <code>tos-security</code> audita antes do PR · <strong>Anti-Drift:</strong> <code>tos-sync</code> atualiza a spec se o requisito mudar.</p>
|
|
405
405
|
</div>
|
|
406
406
|
|
|
407
407
|
<div class="footer">
|
|
@@ -553,16 +553,21 @@
|
|
|
553
553
|
<tr>
|
|
554
554
|
<td><code>tech-os init</code></td>
|
|
555
555
|
<td>Instala skills, regras e cria <code>.tech-os/</code> no projeto</td>
|
|
556
|
-
<td><code>--tools
|
|
556
|
+
<td><code>--tools</code> · <code>--profile mvp|producao|estudo</code> · <code>--design</code> · <code>-y</code></td>
|
|
557
557
|
</tr>
|
|
558
558
|
<tr>
|
|
559
|
-
<td><code>tech-os
|
|
560
|
-
<td>
|
|
561
|
-
<td>
|
|
559
|
+
<td><code>tech-os update</code> / <code>new</code></td>
|
|
560
|
+
<td>Atualiza skills sem tocar em <code>.tech-os/</code> · cria <code>00X-slug</code></td>
|
|
561
|
+
<td><code>tech-os update</code> · <code>tech-os new <slug></code></td>
|
|
562
|
+
</tr>
|
|
563
|
+
<tr>
|
|
564
|
+
<td><code>tech-os status</code> / <code>doctor</code></td>
|
|
565
|
+
<td>Progresso das features · diagnóstico Git, <code>.env</code> e Secret Guard</td>
|
|
566
|
+
<td>Verifica saúde e segredos locais automaticamente</td>
|
|
562
567
|
</tr>
|
|
563
568
|
<tr>
|
|
564
569
|
<td><code>tech-os run <feature></code></td>
|
|
565
|
-
<td>Executa fatias <code>[AUTO]</code> em contexto limpo +
|
|
570
|
+
<td>Executa fatias <code>[AUTO]</code> em contexto limpo + Secret Guard + commit</td>
|
|
566
571
|
<td><code>--dry-run</code> · <code>--runner claude|codex|custom</code> · <code>--test-cmd</code> · <code>--no-commit</code></td>
|
|
567
572
|
</tr>
|
|
568
573
|
<tr>
|
package/docs/tech-os-guia.pdf
CHANGED
|
Binary file
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "tech-os",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Spec-Driven Development, Context Engineering & Autonomous Loop framework for AI-assisted coding.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -17,7 +17,8 @@
|
|
|
17
17
|
"build": "tsc",
|
|
18
18
|
"dev": "tsc --watch",
|
|
19
19
|
"typecheck": "tsc --noEmit",
|
|
20
|
-
"test": "node --test dist/tests/*.test.js"
|
|
20
|
+
"test": "node --test dist/tests/*.test.js",
|
|
21
|
+
"docs:pdf": "chrome --headless --disable-gpu --no-pdf-header-footer --print-to-pdf=docs/tech-os-guia.pdf docs/tech-os-guia.html"
|
|
21
22
|
},
|
|
22
23
|
"keywords": [
|
|
23
24
|
"ai",
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
# _design.md — Padrões Visuais do Projeto
|
|
2
|
+
|
|
3
|
+
> Arquivo opcional para projetos com Frontend/UI. Lido pela skill `tos-design`.
|
|
4
|
+
|
|
5
|
+
## Stack de UI
|
|
6
|
+
- **Framework / Styling:** _(ex: React + Tailwind CSS + shadcn/ui)_
|
|
7
|
+
- **Ícones:** _(ex: Lucide)_
|
|
8
|
+
|
|
9
|
+
## Identidade Visual
|
|
10
|
+
- **Tema:** _(ex: Dark / Light / Sistema)_
|
|
11
|
+
- **Cor Primária:** _(ex: #38bdf8)_
|
|
12
|
+
- **Tipografia:** _(ex: Inter / JetBrains Mono)_
|
|
13
|
+
|
|
14
|
+
## Regras de UX
|
|
15
|
+
- Toda tela assíncrona deve tratar: `loading`, `empty`, `error` e `success`.
|
|
16
|
+
- Reutilizar componentes existentes antes de criar novos.
|
|
@@ -6,6 +6,7 @@ Este projeto utiliza o **Tech OS** (Spec-Driven Development + Context Engineerin
|
|
|
6
6
|
Sempre que iniciar uma tarefa, consulte (se existirem):
|
|
7
7
|
- `.tech-os/00-manifesto.md` — regras, stack, segurança e DoD do projeto
|
|
8
8
|
- `.tech-os/_dominio.md` — vocabulário e regras de negócio
|
|
9
|
+
- `.tech-os/_design.md` — padrões visuais e de UI (se houver frontend)
|
|
9
10
|
|
|
10
11
|
## Princípios Inegociáveis
|
|
11
12
|
1. **IA sugere; engenheiro decide.** Nunca tome decisões arquiteturais silenciosas.
|
|
@@ -23,6 +24,8 @@ Antes de implementar qualquer mudança:
|
|
|
23
24
|
- `tos-manifesto` — cria `00-manifesto.md` e `_dominio.md` (1x por projeto)
|
|
24
25
|
- `tos-discovery` — entrevista para mapear incógnitas (`01-discovery.md`)
|
|
25
26
|
- `tos-blueprint` — PRD técnico e impacto (`02-blueprint.md`)
|
|
26
|
-
- `tos-
|
|
27
|
+
- `tos-design` — especificação visual e estados de UI (`02-design.md`, opcional)
|
|
28
|
+
- `tos-contratos` — contratos de API/schema/segurança (`03-contratos.md`, opcional)
|
|
27
29
|
- `tos-planejar` — plano fatiado `[AUTO]` / `[HUMANO]` (`04-plano.md`)
|
|
30
|
+
- `tos-security` — auditoria de segurança antes de fechar PR/feature
|
|
28
31
|
- `tos-sync` — atualiza a spec antes do código quando um requisito muda
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: tos-design
|
|
3
|
+
description: Especifica a arquitetura visual, hierarquia, estados de interface (loading, empty, error, success), responsividade e acessibilidade antes de codar telas ou componentes de UI.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# `tos-design` — Especificação Visual e de UX (Opcional)
|
|
7
|
+
|
|
8
|
+
Você está executando a skill **`tos-design`** do **Tech OS**.
|
|
9
|
+
Use esta skill para features com interface (Web, Mobile, Desktop) para evitar UI genérica, inconsistente ou inacessível.
|
|
10
|
+
|
|
11
|
+
## Pré-requisito
|
|
12
|
+
- Leia `.tech-os/_design.md` (se existir) e `.tech-os/<NNN>-<slug>/02-blueprint.md`.
|
|
13
|
+
- Se `.tech-os/_design.md` ainda não existir e o projeto tiver frontend, sugira criar um com paleta, tipografia e stack de UI.
|
|
14
|
+
|
|
15
|
+
## O que definir antes de codar a UI
|
|
16
|
+
1. **Objetivo da Tela / Fluxo**: qual é a ação principal do usuário?
|
|
17
|
+
2. **Hierarquia Visual e Layout**: estrutura (grid, cards, sidebar, modal) reaproveitando componentes já existentes no projeto.
|
|
18
|
+
3. **Os 4 Estados Obrigatórios**:
|
|
19
|
+
- **Loading**: skeleton ou spinner sem quebrar o layout.
|
|
20
|
+
- **Empty**: mensagem clara + CTA quando não houver dados.
|
|
21
|
+
- **Error**: feedback humano e ação de retry.
|
|
22
|
+
- **Success**: estado populado e feedback de ações (toast/inline).
|
|
23
|
+
4. **Responsividade e Acessibilidade**:
|
|
24
|
+
- Comportamento mobile vs desktop.
|
|
25
|
+
- Contraste adequado, labels em inputs, navegação por teclado (`Tab` / `Enter` / `Esc`).
|
|
26
|
+
|
|
27
|
+
## Saída
|
|
28
|
+
- Registre a especificação de UI em `.tech-os/<NNN>-<slug>/02-design.md` (enxuto, objetivo) e siga para `tos-planejar`.
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: tos-security
|
|
3
|
+
description: Audita a feature ou o diff atual contra o baseline de segurança (segredos, validação de entrada, auth, PII em logs e dependências) antes de finalizar ou abrir PR.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# `tos-security` — Auditoria de Segurança
|
|
7
|
+
|
|
8
|
+
Você está executando a skill **`tos-security`** do **Tech OS**.
|
|
9
|
+
Seu objetivo é garantir que nenhuma vulnerabilidade óbvia ou vazamento de dados passe para produção.
|
|
10
|
+
|
|
11
|
+
## Quando usar
|
|
12
|
+
- Antes de concluir uma feature classificada como **`estrutural`**.
|
|
13
|
+
- Antes de abrir um Pull Request ou após implementar fluxos de autenticação, upload, pagamentos ou dados sensíveis.
|
|
14
|
+
|
|
15
|
+
## Checklist de Auditoria
|
|
16
|
+
1. **Segredos e Credenciais**:
|
|
17
|
+
- Verifique se há tokens, senhas, chaves de API ou `.env` hardcoded no código, testes ou fixtures.
|
|
18
|
+
2. **Validação de Entrada**:
|
|
19
|
+
- Todo input externo (body, query, params, webhooks, CLI args) está validado por schema/tipo antes de ser processado?
|
|
20
|
+
3. **Autenticação e Autorização**:
|
|
21
|
+
- Novas rotas/ações exigem autenticação por padrão? Há risco de IDOR (usuário A acessando recurso do usuário B)?
|
|
22
|
+
4. **Logs e Dados Sensíveis (PII)**:
|
|
23
|
+
- Senhas, tokens, CPFs, e-mails ou payloads completos estão sendo logados? Se sim, remova ou mascare.
|
|
24
|
+
5. **Dependências e Superfície de Ataque**:
|
|
25
|
+
- Verifique se há `eval`, `exec` com input não sanitizado, SQL concatenado ou dependências suspeitas.
|
|
26
|
+
|
|
27
|
+
## Saída
|
|
28
|
+
- Liste **apenas** os achados reais com arquivo e linha, classificados por severidade (`CRÍTICO`, `ALTO`, `MÉDIO`).
|
|
29
|
+
- Se houver item `CRÍTICO` ou `ALTO`, proponha a correção cirúrgica e aguarde confirmação antes de editar.
|
|
30
|
+
- Se estiver tudo limpo, registre: *"Auditoria `tos-security` aprovada sem pendências críticas."*
|