predators-protocol 1.0.0 → 1.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.
Files changed (65) hide show
  1. package/bin/predators-cli.js +825 -777
  2. package/bundle/.claude/commands/encarnar.md +22 -0
  3. package/bundle/CLAUDE.md +43 -11
  4. package/bundle/docs/CANON/AUDIT-FIRM-READINESS-CHECKLIST.md +6 -6
  5. package/bundle/docs/CANON/BRAND-CANON.json +45 -0
  6. package/bundle/docs/CANON/SELF-HEALING-LOG-CANON.json +583 -353
  7. package/bundle/docs/ENCARNACAO.md +12 -1
  8. package/bundle/docs/SYNAPSE.md +23 -11
  9. package/bundle/predators/apex/aguia-real/constitution.md +347 -347
  10. package/bundle/predators/apex/aguia-real/predator.json +1 -1
  11. package/bundle/predators/apex/leao/constitution.md +283 -283
  12. package/bundle/predators/apex/leao/predator.json +1 -1
  13. package/bundle/predators/apex/orca/constitution.md +279 -279
  14. package/bundle/predators/apex/orca/predator.json +1 -1
  15. package/bundle/predators/apex/tigre-siberiano/constitution.md +276 -276
  16. package/bundle/predators/apex/tigre-siberiano/predator.json +1 -1
  17. package/bundle/predators/designer/pavao/constitution.md +37 -0
  18. package/bundle/predators/hunter/crocodilo/constitution.md +293 -293
  19. package/bundle/predators/hunter/crocodilo/predator.json +1 -1
  20. package/bundle/predators/hunter/escorpiao/constitution.md +327 -327
  21. package/bundle/predators/hunter/escorpiao/predator.json +1 -1
  22. package/bundle/predators/hunter/hiena/constitution.md +343 -343
  23. package/bundle/predators/hunter/hiena/predator.json +1 -1
  24. package/bundle/predators/hunter/tubarao-branco/constitution.md +527 -527
  25. package/bundle/predators/hunter/tubarao-branco/predator.json +1 -1
  26. package/bundle/predators/intel/guepardo/constitution.md +201 -201
  27. package/bundle/predators/intel/guepardo/predator.json +1 -1
  28. package/bundle/predators/intel/jiboia/constitution.md +243 -243
  29. package/bundle/predators/intel/jiboia/predator.json +1 -1
  30. package/bundle/predators/intel/lobo-solitario/constitution.md +275 -275
  31. package/bundle/predators/intel/lobo-solitario/predator.json +1 -1
  32. package/bundle/predators/intel/morcego/constitution.md +217 -217
  33. package/bundle/predators/intel/morcego/predator.json +1 -1
  34. package/bundle/predators/intel/pirarucu/constitution.md +309 -309
  35. package/bundle/predators/intel/pirarucu/predator.json +1 -1
  36. package/bundle/predators/intel/polvo-mimico/constitution.md +220 -220
  37. package/bundle/predators/intel/polvo-mimico/predator.json +1 -1
  38. package/bundle/predators/intel/tarantula/constitution.md +222 -222
  39. package/bundle/predators/intel/tarantula/predator.json +1 -1
  40. package/bundle/predators/meta/aranha-d-agua/constitution.md +264 -264
  41. package/bundle/predators/meta/aranha-d-agua/predator.json +1 -1
  42. package/bundle/predators/meta/camaleao-real/constitution.md +245 -245
  43. package/bundle/predators/meta/camaleao-real/predator.json +1 -1
  44. package/bundle/predators/meta/coruja-real/constitution.md +255 -255
  45. package/bundle/predators/meta/coruja-real/predator.json +1 -1
  46. package/bundle/predators/meta/dragao-ancestral/constitution.md +297 -297
  47. package/bundle/predators/meta/dragao-ancestral/predator.json +1 -1
  48. package/bundle/predators/meta/fenix/constitution.md +286 -286
  49. package/bundle/predators/meta/fenix/predator.json +1 -1
  50. package/bundle/predators/meta/lince-das-neves/constitution.md +252 -252
  51. package/bundle/predators/meta/lince-das-neves/predator.json +1 -1
  52. package/bundle/predators/web3/caranguejo-ferradura/constitution.md +245 -245
  53. package/bundle/predators/web3/caranguejo-ferradura/predator.json +1 -1
  54. package/bundle/predators/web3/medusa/constitution.md +236 -236
  55. package/bundle/predators/web3/medusa/predator.json +1 -1
  56. package/bundle/predators/web3/orca-alfa/constitution.md +227 -227
  57. package/bundle/predators/web3/orca-alfa/predator.json +1 -1
  58. package/bundle/predators/web3/polvo-gigante/constitution.md +240 -240
  59. package/bundle/predators/web3/polvo-gigante/predator.json +1 -1
  60. package/bundle/predators/web3/raia-eletrica/constitution.md +236 -236
  61. package/bundle/predators/web3/raia-eletrica/predator.json +1 -1
  62. package/bundle/predators/web3/tubarao-martelo/constitution.md +236 -236
  63. package/bundle/predators/web3/tubarao-martelo/predator.json +1 -1
  64. package/lib/access-token-client.js +2 -0
  65. package/package.json +1 -1
@@ -1,777 +1,825 @@
1
- #!/usr/bin/env node
2
- // packages/predators-protocol/bin/predators-cli.js
3
- // NPX CLI canon Predators Protocol · 11 comandos fase BETA cumulativa
4
- // Lei #11 honest UPFRONT · Lei #14 PERFEITO OU FIX-GERAL · Lei #13 Pureza canon
5
-
6
- "use strict";
7
-
8
- const fs = require("fs");
9
- const path = require("path");
10
- const { spawnSync } = require("child_process");
11
-
12
- const CLI_VERSION_CANON = "predators-cli-canon-1.0.0-STABLE-14-leis-14-canon-docs-brain-100pct-2026-05-28";
13
-
14
- const PACKAGE_ROOT = path.resolve(__dirname, "..");
15
- const BUNDLE_DIR = path.join(PACKAGE_ROOT, "bundle");
16
- const LIB_DIR = path.join(PACKAGE_ROOT, "lib");
17
-
18
- // UX layer (additive · Lei #4 byte-canon preserve · 11 comandos existentes inalterados)
19
- let uxLib = null;
20
- function loadUxLib() {
21
- if (uxLib) return uxLib;
22
- try {
23
- uxLib = {
24
- splash: require(path.join(LIB_DIR, "splash.js")),
25
- config: require(path.join(LIB_DIR, "config.js")),
26
- audio: require(path.join(LIB_DIR, "audio.js")),
27
- colors: require(path.join(LIB_DIR, "colors.js")),
28
- asciiArt: require(path.join(LIB_DIR, "ascii-art.js")),
29
- spinners: require(path.join(LIB_DIR, "spinners.js")),
30
- };
31
- return uxLib;
32
- } catch (err) {
33
- return null;
34
- }
35
- }
36
-
37
- function bundlePath(relPath) {
38
- return path.join(BUNDLE_DIR, relPath);
39
- }
40
-
41
- function detectPythonCanon() {
42
- // Priority: PREDATORS_PYTHON env override → repo .venv (if in dev) → python3 → python
43
- const candidates = [];
44
-
45
- if (process.env.PREDATORS_PYTHON && fs.existsSync(process.env.PREDATORS_PYTHON)) {
46
- candidates.push(process.env.PREDATORS_PYTHON);
47
- }
48
-
49
- // Dev mode: if invoked from within Predators repo (next to .venv)
50
- const devVenvWin = path.resolve(PACKAGE_ROOT, "..", "..", ".venv", "Scripts", "python.exe");
51
- const devVenvUnix = path.resolve(PACKAGE_ROOT, "..", "..", ".venv", "bin", "python");
52
- if (fs.existsSync(devVenvWin)) candidates.push(devVenvWin);
53
- if (fs.existsSync(devVenvUnix)) candidates.push(devVenvUnix);
54
-
55
- // System python
56
- for (const cmd of ["python3", "python"]) {
57
- const probe = spawnSync(cmd, ["--version"], { encoding: "utf8" });
58
- if (probe.status === 0) {
59
- candidates.push(cmd);
60
- break;
61
- }
62
- }
63
-
64
- return candidates.length > 0 ? candidates[0] : null;
65
- }
66
-
67
- function printHelpCanon() {
68
- console.error(`
69
- predators-cli · canon Predators NPX CLI 1.0.0 STABLE (canon 100% · 14 leis ratificadas)
70
-
71
- USO:
72
- npx predators-protocol <comando>
73
-
74
- COMANDOS canon vigentes (17 comandos):
75
-
76
- -- fase 1 (introspecção · 4 comandos) --
77
- version Exibe versão canon
78
- status Estado atual canon · bundle integrity check
79
- list-predators Lista 64 predadores frota canon vigente
80
- list-workflows Lista 4 workflows canon (caca-sistematica · pacto-cyber-squad · pipeline-fenix · saneamento-brownfield)
81
-
82
- -- fase BETA (state machines · 5 comandos) --
83
- workflow-states Lista 6 WorkflowStateCanon (PENDING/SCHEDULED/RUNNING/COMPLETED/FAILED/PAUSED)
84
- story-states Lista 5 StoryStateCanon (DRAFT/REFINEMENT/READY/IN_PROGRESS/DONE)
85
- layers-list Lista 7 ContextLayerCanon L0-L6 (Lei do Sangue → user input)
86
- benchmark-info Mostra benchmark scipy protocol canon (N=180 p<0.05)
87
- metrics-list Lista 4 golden signals canon M1 APM (latency + traffic + errors + saturation)
88
-
89
- -- fase UX (additive · Lei #4 byte-canon preserve · 5 comandos) --
90
- init Polimórfico · sem arg = splash cinematográfico · com <name> = scaffolda projeto novo + sync
91
- Flags: --force (sempre cinemático · ignora cache) · --minimal (1-linha)
92
- config Preferências user (theme · audio · splash · telemetry)
93
- show Renderiza ASCII art predator card OR The Eye logo
94
- sync Sincroniza canon files (predators/ + docs/ + .claude/ + CLAUDE.md) do bundle NPX para CWD
95
- tour Cinematic walkthrough · 5 atos canon (camadas · leis · diretrizes · comandos · próximos passos)
96
-
97
- -- fase R2 (onboarding · 2026-05-26 · Polvo · 1 comando novo) --
98
- install Alias semântico para 'sync --force' · UX onboarding clearer
99
-
100
- -- fase TOKEN-COLABORADOR (2026-05-27 · Borboleta + Jaguar · 2 comandos novos) --
101
- unlock <TOKEN> Ativa acesso colaborador via token (canon access-token-client)
102
- gen-token Apex T7 gera token via CLI (PREDATORS_OWNER_KEY_BACKEND env)
103
- Usage: gen-token --name "Nome" [--email x] [--list]
104
-
105
- -- fase BRAIN (2026-05-28 · 1.0.0 STABLE · 1 comando novo) --
106
- brain-status Snapshot canon estrutura cerebral · 11 daemons + 6 flags + Elefante (READ-only)
107
- Runtime real exige Python + clonar repo + brain-on.cmd · ver caminho em docs
108
-
109
- help Exibe esta mensagem
110
-
111
- Lei #11 honest UPFRONT 1.0.0 STABLE cumulativa:
112
- · Bundle 162 files · 64 predadores + 14 LEI canon-docs + AUDIT-FIRM + SH-CATALOG + 7 skills · ZERO infra leak
113
- · sync command requer CWD contendo predators/ OU --force flag · pattern canon partner-bundle
114
- · NPX = portal READ canon · scaffold projeto novo + token unlock. Encarnação real exige Claude Code CLI + repo + chave LLM
115
- · brain-status = snapshot canon (não-live) · runtime real exige Python 3.11+ + brain-on.cmd · ver QUICKSTART-SOCIO.md
116
- `);
117
- }
118
-
119
- function printVersionCanon() {
120
- console.log(CLI_VERSION_CANON);
121
- }
122
-
123
- function printStatusCanon() {
124
- const synapseMd = bundlePath("docs/SYNAPSE.md");
125
- const encarnacaoMd = bundlePath("docs/ENCARNACAO.md");
126
- const claudeMd = bundlePath("CLAUDE.md");
127
- const predatorsDir = bundlePath("predators");
128
- const skillsDir = bundlePath(".claude/commands");
129
- let predatorCount = 0;
130
- if (fs.existsSync(predatorsDir)) {
131
- const walk = (dir) => {
132
- for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
133
- const p = path.join(dir, e.name);
134
- if (e.isDirectory()) walk(p);
135
- else if (e.name === "predator.json") predatorCount++;
136
- }
137
- };
138
- walk(predatorsDir);
139
- }
140
- console.log("canon Predators status:");
141
- console.log(` CLI version: ${CLI_VERSION_CANON}`);
142
- console.log(` bundle root: ${BUNDLE_DIR}`);
143
- console.log(` CLAUDE.md: ${fs.existsSync(claudeMd) ? "PRESENT" : "MISSING"}`);
144
- console.log(` SYNAPSE.md: ${fs.existsSync(synapseMd) ? "PRESENT" : "MISSING"}`);
145
- console.log(` ENCARNACAO.md: ${fs.existsSync(encarnacaoMd) ? "PRESENT" : "MISSING"}`);
146
- console.log(` predators canon: ${predatorCount}/63 byte-presente`);
147
- console.log(` .claude/commands/: ${fs.existsSync(skillsDir) ? "PRESENT" : "MISSING"}`);
148
- console.log(` Lei #14 canon: PERFEITO OU FIX-GERAL ratificada constitucional`);
149
- console.log(` Lei #1 reign: bundle slim · ZERO infra leak audit (0.3.0-beta.0)`);
150
- console.log(` Diretrizes 4 (2026-05-24): Lei do Tom · Autonomia Sequencial · PASSO 0 EVERY · Separação canon-doc/comunicação`);
151
- }
152
-
153
- function listPredatorsCanon() {
154
- console.log("64 predadores frota canon vigente pós-F4 Baleia-cantora:");
155
- console.log(" apex: 4 (Águia + Leão + Orca + Tigre-siberiano)");
156
- console.log(" hunter: 5 (Tubarão-branco JUIZ FINAL Art. 14 + Escorpião + Hiena + Crocodilo + Piranha)");
157
- console.log(" builder: 9 (Jaguar + Tatu-bola + Coruja + Pirarucu + Lince + Polvo + 3)");
158
- console.log(" designer: 8 (Borboleta-azul + Tucano-toco + Baleia-cantora + 5)");
159
- console.log(" copy: 6 (Serpente-coral + 5)");
160
- console.log(" intel: 8 (Lobo-solitário + Tarântula + Jiboia + 5)");
161
- console.log(" governance: 6");
162
- console.log(" growth: 6");
163
- console.log(" web3: 6 (Medusa + 5)");
164
- console.log(" meta: 6 (Dragão-ancestral + Elefante + Fênix + Camaleão + Serpente + 1)");
165
- }
166
-
167
- function listWorkflowsCanon() {
168
- console.log("4 workflows canon Predators (Lei #13 Pureza):");
169
- console.log(" - caca-sistematica");
170
- console.log(" - pacto-cyber-squad");
171
- console.log(" - pipeline-fenix");
172
- console.log(" - saneamento-brownfield");
173
- }
174
-
175
- function listWorkflowStatesCanon() {
176
- console.log("6 WorkflowStateCanon canon Predators (D2 ETAPA 2 state machine):");
177
- console.log(" PENDING · workflow definição cravada · zero execução");
178
- console.log(" SCHEDULED · próxima execução planejada · cron canon");
179
- console.log(" RUNNING · steps em execução runtime");
180
- console.log(" COMPLETED · todos steps OK · success path");
181
- console.log(" FAILED · step falhou · rollback canon");
182
- console.log(" PAUSED · humano interrompeu · retomar manual");
183
- console.log("");
184
- console.log("7 transições válidas canon (Lei #4 reign state machine):");
185
- console.log(" PENDING → SCHEDULED · SCHEDULED RUNNING · RUNNING → COMPLETED");
186
- console.log(" RUNNING → FAILED · RUNNING → PAUSED · PAUSED RUNNING · FAILED → PENDING");
187
- }
188
-
189
- function listStoryStatesCanon() {
190
- console.log("5 StoryStateCanon canon Predators (D3 ETAPA 3 state machine):");
191
- console.log(" DRAFT · criação inicial · briefing parcial");
192
- console.log(" REFINEMENT · briefing completo · Águia preside refinamento");
193
- console.log(" READY · predator owner identificado · scope clear");
194
- console.log(" IN_PROGRESS · predator encarnado executando");
195
- console.log(" DONE · 5 garantias entregues · audit Tubarão PASS");
196
- console.log("");
197
- console.log("7 transições válidas canon:");
198
- console.log(" DRAFT → REFINEMENT → READY → IN_PROGRESS DONE (caminho canônico)");
199
- console.log(" REFINEMENT/READY/IN_PROGRESS DRAFT (rejeição com feedback)");
200
- }
201
-
202
- function listLayersCanon() {
203
- console.log("7 ContextLayerCanon L0-L6 canon Predators (D5 ETAPA 1 runtime middleware):");
204
- console.log(" L0 LEI_DO_SANGUE_ART_1 · CRITICAL_imutavel priority 1000");
205
- console.log(" L1 LEI_4_SYNAPSE_5_GARANTIAS · CRITICAL_reign priority 900");
206
- console.log(" L2 5_IMUTAVEIS_BYTE_PRESERVED · CRITICAL_byte_preserved priority 800");
207
- console.log(" L3 14_LEIS_CANON_VIGENTES · ALTA_vigente priority 600");
208
- console.log(" L4 PREDATOR_ENCARNADO_CONSTITUTION · ALTA_encarnacao priority 500");
209
- console.log(" L5 TASK_ESPECIFICA_CONTEXTO · MEDIA_task priority 300");
210
- console.log(" L6 USER_PROMPT_INPUT · INFO_user_input priority 100");
211
- console.log("");
212
- console.log("L0+L1+L2 CRITICAL mandatory · Lei #14 BINARY FIX-GERAL trigger se ausentes");
213
- }
214
-
215
- function showBenchmarkInfoCanon() {
216
- console.log("Benchmark canon Predators · scipy.stats N=180 p<0.05 protocol:");
217
- console.log("");
218
- console.log(" dimensions canon (6):");
219
- console.log(" D5_context_layers_L0_L6");
220
- console.log(" D2_workflows_engine");
221
- console.log(" D3_stories_lifecycle");
222
- console.log(" D4_multi_project_filesystem");
223
- console.log(" D1_mcp_consuming");
224
- console.log(" D6_dispatcher_integration");
225
- console.log("");
226
- console.log(" parâmetros estatísticos canon:");
227
- console.log(" sample size per dimension: 30");
228
- console.log(" total samples N: 180");
229
- console.log(" p-value threshold: < 0.05");
230
- console.log(" confidence interval: 95%");
231
- console.log("");
232
- console.log(" ttest_ind canon próprio Lei #13 Pureza (sem scipy hard-dep)");
233
- console.log("");
234
- console.log("Lei #11 honest UPFRONT: execução real depende provisioning Apex T7");
235
- }
236
-
237
- function listGoldenSignalsCanon() {
238
- console.log("4 Golden Signals canon M1 APM Predators (B2 ONDA PRIORIDADES):");
239
- console.log(" latency_milliseconds · CanonMetricHistogram (p50/p95/p99 via percentile_canon)");
240
- console.log(" traffic_total · CanonMetricCounter");
241
- console.log(" errors_total · CanonMetricCounter");
242
- console.log(" saturation_active · CanonMetricGauge");
243
- console.log("");
244
- console.log("5 dimensões instrumentadas canon:");
245
- console.log(" D1_mcp_consuming · D2_workflows_engine · D3_stories_lifecycle · D4_multi_project_filesystem · D5_context_layers_middleware");
246
- console.log("");
247
- console.log("Lei #13 Pureza: metrics canon próprio · duck-type prometheus_client (sem hard-dep externa)");
248
- }
249
-
250
- // ──────────────────────────────────────────────────────────────────────
251
- // UX layer commands (additive · Lei #4 byte-canon preserve)
252
- // ──────────────────────────────────────────────────────────────────────
253
-
254
- async function runInitCommand() {
255
- const args = process.argv.slice(3);
256
- const positionalArgs = args.filter(a => !a.startsWith("-"));
257
- const projectName = positionalArgs[0] || null;
258
-
259
- // Polymorphic init (R2 onda · 2026-05-26 · Polvo Builder)
260
- // - no positional arg → splash UX (backward compat byte-preserved)
261
- // - positional arg project scaffolding (mkdir + sync inside)
262
- if (projectName) {
263
- return runInitProjectMode(projectName, args);
264
- }
265
-
266
- const ux = loadUxLib();
267
- if (!ux) {
268
- console.error("UX layer não-disponível neste pacote.");
269
- process.exit(1);
270
- }
271
- const forceFlag = args.includes("--force") || args.includes("-f");
272
- const minimalFlag = args.includes("--minimal") || args.includes("-m");
273
- await ux.splash.runInitSplash({ force: forceFlag, minimal: minimalFlag });
274
- }
275
-
276
- function runInitProjectMode(projectName, args) {
277
- const cwd = process.cwd();
278
- const targetDir = path.resolve(cwd, projectName);
279
- const force = args.includes("--force") || args.includes("-f");
280
-
281
- if (fs.existsSync(targetDir)) {
282
- const contents = fs.readdirSync(targetDir);
283
- if (contents.length > 0 && !force) {
284
- console.error(`init · diretório ${projectName} já existe e não está vazio.`);
285
- console.error(" · Use diretório vazio · OU passe --force para sobrescrever (cuidado)");
286
- process.exit(1);
287
- }
288
- } else {
289
- fs.mkdirSync(targetDir, { recursive: true });
290
- }
291
-
292
- console.log("Predators Protocol · init project canon (R2 onda 2026-05-26 · Polvo)");
293
- console.log(` projeto: ${projectName}`);
294
- console.log(` path: ${targetDir}`);
295
- console.log("");
296
-
297
- process.chdir(targetDir);
298
- if (!process.argv.includes("--force")) {
299
- process.argv.push("--force");
300
- }
301
- runSyncCommand();
302
-
303
- console.log("");
304
- console.log("Próximos passos:");
305
- console.log(` cd ${projectName}`);
306
- console.log(" npx predators-protocol tour # tour cinematográfico");
307
- console.log(" npx predators-protocol show eye # logo canon");
308
- }
309
-
310
- function runInstallCommand() {
311
- // Alias semântico canon para `sync --force` (UX onboarding clearer)
312
- // R2 onda · 2026-05-26 · Polvo · LMAS parity sem violar Lei #13 (canon próprio)
313
- console.log("install · alias canon para `sync --force` · instala canon files no CWD");
314
- console.log("");
315
- if (!process.argv.includes("--force")) {
316
- process.argv.push("--force");
317
- }
318
- runSyncCommand();
319
- }
320
-
321
- function runConfigCommand() {
322
- const ux = loadUxLib();
323
- if (!ux) {
324
- console.error("UX layer não-disponível neste pacote.");
325
- process.exit(1);
326
- }
327
- const subcommand = process.argv[3] || "show";
328
- const arg = process.argv[4];
329
-
330
- if (subcommand === "show" || subcommand === "status") {
331
- const cfg = ux.config.readConfig();
332
- console.log("Predators Protocol · user config");
333
- console.log(` path: ${ux.config.getConfigPath()}`);
334
- console.log(` theme: ${cfg.theme}`);
335
- console.log(` splash.enabled: ${cfg.splash.enabled}`);
336
- console.log(` audio.enabled: ${cfg.audio.enabled}`);
337
- console.log(` firstConnectionAt: ${cfg.firstConnectionAt || "(never)"}`);
338
- console.log(` lastConnectionAt: ${cfg.lastConnectionAt || "(never)"}`);
339
- return;
340
- }
341
- if (subcommand === "theme") {
342
- if (!arg) {
343
- console.log(`Current theme: ${ux.config.getTheme()}`);
344
- console.log("Available: default, dark, light, monochrome");
345
- return;
346
- }
347
- const result = ux.config.setTheme(arg);
348
- if (result) {
349
- console.log(`Theme set: ${arg}`);
350
- } else {
351
- console.error(`Invalid theme: ${arg} · available: default, dark, light, monochrome`);
352
- process.exit(1);
353
- }
354
- return;
355
- }
356
- if (subcommand === "audio") {
357
- if (arg === "--enable" || arg === "on") {
358
- ux.config.setAudioEnabled(true);
359
- console.log("Audio: enabled · .mp3 byte pendentes produção externa (Suno/ElevenLabs/Stable Audio · canon spec docs/PRDs/ONDA-BALEIA-CANTORA-FASE-2-SIGNATURES-2026-05-24/)");
360
- return;
361
- }
362
- if (arg === "--disable" || arg === "off") {
363
- ux.config.setAudioEnabled(false);
364
- console.log("Audio: disabled");
365
- return;
366
- }
367
- if (arg === "--status" || !arg) {
368
- const status = ux.audio.getStatusReport();
369
- console.log("Audio status canon:");
370
- console.log(` enabled: ${status.enabled}`);
371
- console.log(` platform: ${status.platform} (WSL: ${status.is_wsl})`);
372
- console.log(` player_available: ${status.player_available} (${status.player_cmd || "none"})`);
373
- console.log(` ${status.canon_note}`);
374
- console.log(" signatures Baleia-cantora F4 Fase 2:");
375
- for (const s of status.sounds) {
376
- console.log(` · ${s.name} - ${s.description} (file: ${s.file_present ? "PRESENT" : "PENDENTE"})`);
377
- }
378
- return;
379
- }
380
- }
381
- if (subcommand === "telemetry") {
382
- if (arg === "--enable" || arg === "on") {
383
- ux.config.setTelemetryEnabled(true);
384
- const status = ux.config.getTelemetryStatus();
385
- console.log("Telemetry: enabled");
386
- console.log(` anonymous_id: ${status.anonymous_id} (gerado runtime · zero PII)`);
387
- console.log(` endpoint: ${status.endpoint || "local-only (future network endpoint TBD Apex T7)"}`);
388
- console.log(" Lei #1 reign: zero PII · zero IP capture · zero hostname · só sync events anônimos");
389
- return;
390
- }
391
- if (arg === "--disable" || arg === "off") {
392
- ux.config.setTelemetryEnabled(false);
393
- console.log("Telemetry: disabled · zero coleta");
394
- return;
395
- }
396
- if (arg === "--status" || !arg) {
397
- const status = ux.config.getTelemetryStatus();
398
- console.log("Telemetry status canon:");
399
- console.log(` enabled: ${status.enabled}`);
400
- console.log(` anonymous_id: ${status.anonymous_id || "(não gerado · opt-in pendente)"}`);
401
- console.log(` sync_count: ${status.sync_count}`);
402
- console.log(` last_sync_at: ${status.last_sync_at || "(nunca)"}`);
403
- console.log(` endpoint: ${status.endpoint || "local-only (null)"}`);
404
- console.log(` ${status.canon_note}`);
405
- return;
406
- }
407
- }
408
- console.error(`Config subcommand desconhecido: ${subcommand}`);
409
- console.error("Available: show · theme [default|dark|light|monochrome] · audio [--enable|--disable|--status] · telemetry [--enable|--disable|--status]");
410
- process.exit(1);
411
- }
412
-
413
- function runShowCommand() {
414
- const ux = loadUxLib();
415
- if (!ux) {
416
- console.error("UX layer não-disponível neste pacote.");
417
- process.exit(1);
418
- }
419
- const target = process.argv[3] || "eye";
420
- const theme = ux.config.getTheme();
421
-
422
- if (target === "eye" || target === "logo") {
423
- console.log(ux.asciiArt.renderEye(theme));
424
- return;
425
- }
426
- if (target === "banner") {
427
- console.log(ux.asciiArt.renderHeroBanner(theme));
428
- return;
429
- }
430
- if (target === "list") {
431
- console.log("Predator cards canon vigentes:");
432
- for (const id of ux.asciiArt.listPredatorsWithCards()) {
433
- console.log(` · ${id}`);
434
- }
435
- return;
436
- }
437
- const card = ux.asciiArt.renderPredatorCard(target, theme);
438
- if (!card) {
439
- console.error(`Predator card não-disponível: ${target}`);
440
- console.error("Disponíveis: " + ux.asciiArt.listPredatorsWithCards().join(", "));
441
- console.error("Outros targets: eye | logo | banner | list");
442
- process.exit(1);
443
- }
444
- console.log(card);
445
- }
446
-
447
- // ──────────────────────────────────────────────────────────────────────
448
- // sync command · canon files refresh CWD from bundle (0.3.0-beta.0)
449
- // ──────────────────────────────────────────────────────────────────────
450
-
451
- function copyDirRecursive(src, dst) {
452
- if (!fs.existsSync(src)) return { copied: 0, skipped: 0 };
453
- fs.mkdirSync(dst, { recursive: true });
454
- let copied = 0;
455
- let skipped = 0;
456
- for (const e of fs.readdirSync(src, { withFileTypes: true })) {
457
- const s = path.join(src, e.name);
458
- const d = path.join(dst, e.name);
459
- if (e.isDirectory()) {
460
- const r = copyDirRecursive(s, d);
461
- copied += r.copied;
462
- skipped += r.skipped;
463
- } else {
464
- fs.copyFileSync(s, d);
465
- copied++;
466
- }
467
- }
468
- return { copied, skipped };
469
- }
470
-
471
- function backupExistingPath(target) {
472
- if (!fs.existsSync(target)) return null;
473
- const ts = new Date().toISOString().replace(/[:.]/g, "-");
474
- const backup = `${target}.backup-${ts}`;
475
- fs.renameSync(target, backup);
476
- return backup;
477
- }
478
-
479
- function runSyncCommand() {
480
- const args = process.argv.slice(3);
481
- const dryRun = args.includes("--dry-run");
482
- const force = args.includes("--force") || args.includes("-f");
483
- const cwd = process.cwd();
484
-
485
- // Refuse to overwrite a non-Predators directory unless --force passed.
486
- const looksLikePredatorsCwd =
487
- fs.existsSync(path.join(cwd, "predators")) ||
488
- fs.existsSync(path.join(cwd, "CLAUDE.md")) ||
489
- fs.existsSync(path.join(cwd, ".claude")) ||
490
- fs.existsSync(path.join(cwd, "QUICKSTART-SOCIO.md"));
491
-
492
- if (!looksLikePredatorsCwd && !force) {
493
- console.error("sync · CWD não parece ser pasta Predators (sem predators/ · CLAUDE.md · .claude/).");
494
- console.error(` CWD: ${cwd}`);
495
- console.error(" · Para sync inicial em pasta vazia · use: npx predators-protocol sync --force");
496
- console.error(" · Para sync em pasta Predators existente · CWD precisa conter CLAUDE.md ou predators/");
497
- process.exit(1);
498
- }
499
-
500
- const SYNC_TARGETS = [
501
- { rel: "predators", type: "dir" },
502
- { rel: "docs", type: "dir" },
503
- { rel: ".claude/commands", type: "dir" },
504
- { rel: "CLAUDE.md", type: "file" },
505
- { rel: "QUICKSTART-SOCIO.md", type: "file" },
506
- ];
507
-
508
- console.log("Predators Protocol · sync canon files do bundle NPX para CWD");
509
- console.log(` bundle: ${BUNDLE_DIR}`);
510
- console.log(` target: ${cwd}`);
511
- if (dryRun) console.log(" mode: DRY-RUN (zero writes)");
512
- console.log("");
513
-
514
- let totalCopied = 0;
515
- for (const { rel, type } of SYNC_TARGETS) {
516
- const src = path.join(BUNDLE_DIR, rel);
517
- const dst = path.join(cwd, rel);
518
-
519
- if (!fs.existsSync(src)) {
520
- console.log(` skip: ${rel} (não-presente no bundle)`);
521
- continue;
522
- }
523
-
524
- if (dryRun) {
525
- console.log(` preview: ${rel} (${type}) · would sync from bundle`);
526
- continue;
527
- }
528
-
529
- const backup = backupExistingPath(dst);
530
- if (backup) {
531
- console.log(` backup: ${path.basename(backup)}`);
532
- }
533
-
534
- if (type === "dir") {
535
- const r = copyDirRecursive(src, dst);
536
- console.log(` sync: ${rel}/ (${r.copied} files)`);
537
- totalCopied += r.copied;
538
- } else {
539
- fs.mkdirSync(path.dirname(dst), { recursive: true });
540
- fs.copyFileSync(src, dst);
541
- console.log(` sync: ${rel}`);
542
- totalCopied++;
543
- }
544
- }
545
-
546
- if (dryRun) {
547
- console.log("\nDRY-RUN complete · use sem --dry-run para aplicar.");
548
- } else {
549
- // Record sync event canon (local always · network telemetry if opt-in + endpoint configured)
550
- const ux = loadUxLib();
551
- if (ux && ux.config && ux.config.recordSyncEvent) {
552
- try { ux.config.recordSyncEvent(); } catch (e) { /* graceful · sync continua */ }
553
- }
554
- console.log(`\nsync complete · ${totalCopied} files canon writados · backups com sufixo .backup-<timestamp>`);
555
- console.log("Lei #1 reign: bundle slim · ZERO infra leak (1.0.0 STABLE)");
556
- }
557
- }
558
-
559
- // ──────────────────────────────────────────────────────────────────────
560
- // tour command · cinematic walkthrough canon vigente (1.0.0 STABLE)
561
- // ──────────────────────────────────────────────────────────────────────
562
-
563
- function sleep(ms) {
564
- return new Promise(resolve => setTimeout(resolve, ms));
565
- }
566
-
567
- async function runTourCommand() {
568
- const ux = loadUxLib();
569
- if (!ux) {
570
- console.error("UX layer não-disponível neste pacote.");
571
- process.exit(1);
572
- }
573
- const args = process.argv.slice(3);
574
- const fast = args.includes("--fast");
575
- const beat = fast ? 200 : 800;
576
-
577
- const theme = ux.config.getTheme();
578
- console.log("");
579
- console.log(ux.asciiArt.renderEye(theme));
580
- await sleep(beat);
581
-
582
- console.log("");
583
- console.log("PREDADORES PROTOCOL · tour canon vigente (1.0.0 STABLE)");
584
- console.log("64 predadores · 10 camadas · 14 leis · 5 garantias Synapse");
585
- await sleep(beat);
586
-
587
- console.log("");
588
- console.log("─── 1/5 · 10 camadas trofic ───");
589
- await sleep(beat / 2);
590
- const layers = [
591
- ["apex", "4 predators", "T5", "Águia + Leão + Orca + Tigre"],
592
- ["hunter", "5 predators", "T4-T5", "Tubarão JUIZ + Cyber Squad"],
593
- ["builder", "9 predators", "T3", "Polvo + Tatu + Jaguar + 6"],
594
- ["designer", "8 predators", "T3-T4", "Borboleta + Tucano + Baleia-cantora F4"],
595
- ["copy", "6 predators", "T3", "Serpente-coral + 5"],
596
- ["intel", "8 predators", "T3", "Lobo-solitário + Tarântula + 6"],
597
- ["governance", "6 predators", "T3", "Tigre + Gorila + Lince + 3"],
598
- ["growth", "6 predators", "T2-T3", "Leão push + Formiga + 4"],
599
- ["web3", "6 predators", "T3", "Medusa veto + 5"],
600
- ["meta", "6 predators", "T1-T2", "Dragão + Fênix + Elefante + 3"],
601
- ];
602
- for (const [layer, count, trophic, examples] of layers) {
603
- console.log(` · ${layer.padEnd(11)} ${count.padEnd(12)} ${trophic.padEnd(6)} ${examples}`);
604
- await sleep(beat / 4);
605
- }
606
-
607
- console.log("");
608
- console.log("─── 2/5 · 14 leis canon vigentes ───");
609
- await sleep(beat / 2);
610
- const laws = [
611
- "Lei #1 Lei do Sangue (ABSOLUTO · Tubarão Art. 1 imutável)",
612
- "Lei #2 Lei dos Predadores (Fênix Protocol exclusive)",
613
- "Lei #3 Lei da Melhoria Disciplinada",
614
- "Lei #4 Lei da Synapse (5 garantias canon)",
615
- "Lei #5 Canon dos 3 Vetos (Sangue · Operacional · Constitucional)",
616
- "Lei #6 Lei dos Predadores Reais (zero demo)",
617
- "Lei #7 Lei da Matilha Paralela",
618
- "Lei #8 Verificação Empírica (ABSOLUTO)",
619
- "Lei #9 Análise antes de Execução",
620
- "Lei #10 Skill canon estrito",
621
- "Lei #11 NUNCA MINTA JAMAIS (ABSOLUTO)",
622
- "Lei #12 O melhor dos melhores",
623
- "Lei #13 Pureza Predators (ABSOLUTO)",
624
- "Lei #14 PERFEITO OU FIX-GERAL (BINARY)",
625
- ];
626
- for (const law of laws) {
627
- console.log(` · ${law}`);
628
- await sleep(beat / 5);
629
- }
630
-
631
- console.log("");
632
- console.log("─── 3/5 · 4 Diretrizes Comunicação ───");
633
- await sleep(beat / 2);
634
- console.log(" 1. Lei do Tom Conversacional (Apex T7 direct)");
635
- console.log(" 2. Autonomia Sequencial (Lei #9)");
636
- console.log(" 3. PASSO 0 EVERY ONDA (Lei #8 baseline)");
637
- console.log(" 4. Separação canon-doc vs comunicação direta");
638
- await sleep(beat);
639
-
640
- console.log("");
641
- console.log("─── 4/5 · 13 comandos NPX vigentes ───");
642
- await sleep(beat / 2);
643
- console.log(" introspecção: version · status · list-predators · list-workflows");
644
- console.log(" state machines: workflow-states · story-states · layers-list · benchmark-info · metrics-list");
645
- console.log(" experiência UX: init · config · show · sync · tour");
646
- await sleep(beat);
647
-
648
- console.log("");
649
- console.log("─── 5/5 · Comando canon para sócios ───");
650
- await sleep(beat / 2);
651
- console.log("");
652
- console.log(" mkdir predators-protocol && cd predators-protocol");
653
- console.log(" npx predators-protocol@beta sync --force");
654
- console.log("");
655
- console.log(" → 143 files canon na pasta (64 predadores + docs + skills + CLAUDE.md)");
656
- console.log(" abre no VS Code · ativa extensão Claude Code");
657
- console.log(" /encarnar tubarao-branco (ou qualquer dos 64 IDs)");
658
- await sleep(beat);
659
-
660
- console.log("");
661
- console.log("─── fim do tour ───");
662
- console.log("");
663
- console.log("Próximos passos sugeridos:");
664
- console.log(" · npx predators-protocol@beta sync --force (instala canon na pasta atual)");
665
- console.log(" · npx predators-protocol@beta show eye (logo cinematográfico)");
666
- console.log(" · npx predators-protocol@beta show list (lista predator cards disponíveis)");
667
- console.log(" · npx predators-protocol@beta help (todos os 13 comandos)");
668
- console.log("");
669
- console.log("🦈🐋 Predators Protocol · proprietário · Alex Gonzaga (Tubarão-Apex) · 2026-05-24");
670
- }
671
-
672
- // ──────────────────────────────────────────────────────────────────────
673
-
674
- const command = process.argv[2] || "help";
675
-
676
- // Lei #1 [a-m] gates · access-token middleware canon 2026-05-27
677
- // Sócios bypass via PREDATORS_OWNER_KEY env var · colaboradores via `unlock <TOKEN>`
678
- const { runUnlock, requireValidAccess } = require("../lib/access-token-client.js");
679
- // Lei #1 [ok1-ok4] gates · gen-token CLI canon 2026-05-27
680
- const { runGenToken } = require("../lib/gen-token-client.js");
681
-
682
- async function runUnlockCommand() {
683
- const token = process.argv[3];
684
- await runUnlock(token);
685
- }
686
-
687
- async function runGenTokenCommand() {
688
- await runGenToken();
689
- }
690
-
691
- // brain-status command · 1.0.0 STABLE · ONDA-NPX-100-RELEASE
692
- // Snapshot canon estrutura cerebral · READ-only · runtime real exige Python
693
- async function runBrainStatusCommand() {
694
- const snapshotPath = bundlePath("docs/CANON/BRAIN-STATUS-SNAPSHOT.json");
695
- if (!fs.existsSync(snapshotPath)) {
696
- console.error("brain-status snapshot ausente no bundle · re-sync canon necessário");
697
- process.exit(1);
698
- }
699
- let snapshot;
700
- try {
701
- snapshot = JSON.parse(fs.readFileSync(snapshotPath, "utf-8"));
702
- } catch (err) {
703
- console.error(`brain-status snapshot JSON inválido: ${err.message}`);
704
- process.exit(1);
705
- }
706
- console.log("");
707
- console.log("PREDADORES PROTOCOL · ESTRUTURA CEREBRAL · snapshot canon");
708
- console.log("==========================================================");
709
- console.log(`Snapshot cravado: ${snapshot.snapshot_at}`);
710
- console.log(`Commit master: ${snapshot.commit_hash_short}`);
711
- console.log(`Status agregado: ${snapshot.status_aggregate}`);
712
- console.log("");
713
- console.log("11 daemons cerebrais (runtime real · não-snapshot):");
714
- for (const d of snapshot.daemons) {
715
- console.log(` · ${d.name.padEnd(22)} ${d.role}`);
716
- }
717
- console.log("");
718
- console.log("6 feature flags Híbrida (default canon vigente):");
719
- for (const f of snapshot.feature_flags) {
720
- const mark = f.default === "true" ? "LIVE" : "OPT-IN";
721
- console.log(` · ${f.name.padEnd(28)} default=${f.default.padEnd(5)} ${mark}`);
722
- }
723
- console.log("");
724
- console.log("Elefante · memória institucional Art. 6 imutável:");
725
- console.log(` · pointers cumulative: ${snapshot.elefante.memory_pointers_count}`);
726
- console.log(` · trace neural files: ${snapshot.elefante.trace_neural_files_count}`);
727
- console.log(` · consolidation cycles: ${snapshot.elefante.consolidation_cycles_cumulative}`);
728
- console.log("");
729
- console.log("Honest UPFRONT (Lei #11):");
730
- console.log(" · brain-status é READ-only snapshot · cravado no commit acima");
731
- console.log(" · runtime real exige: clone repo + Python 3.11+ + brain-on.cmd");
732
- console.log(" · 11 daemons LIVE só rodam em clone do repositório · não-NPX");
733
- console.log(" · ver bundle/QUICKSTART-SOCIO.md para caminho completo");
734
- }
735
-
736
- const commandsCanon = {
737
- version: printVersionCanon,
738
- status: printStatusCanon,
739
- "list-predators": listPredatorsCanon,
740
- "list-workflows": listWorkflowsCanon,
741
- "workflow-states": listWorkflowStatesCanon,
742
- "story-states": listStoryStatesCanon,
743
- "layers-list": listLayersCanon,
744
- "benchmark-info": showBenchmarkInfoCanon,
745
- "metrics-list": listGoldenSignalsCanon,
746
- init: runInitCommand,
747
- config: runConfigCommand,
748
- show: runShowCommand,
749
- sync: runSyncCommand,
750
- install: runInstallCommand,
751
- tour: runTourCommand,
752
- unlock: runUnlockCommand,
753
- "gen-token": runGenTokenCommand,
754
- "brain-status": runBrainStatusCommand,
755
- help: printHelpCanon,
756
- "--help": printHelpCanon,
757
- "-h": printHelpCanon,
758
- };
759
-
760
- const handler = commandsCanon[command];
761
- if (!handler) {
762
- console.error(`Comando canon NÃO vigente: ${command}`);
763
- printHelpCanon();
764
- process.exit(1);
765
- }
766
-
767
- // Lei #1 middleware · valida acesso ANTES de executar comando sensível
768
- // (PUBLIC_COMMANDS · owner bypass · cache local 5min · phone-home revalidação)
769
- (async () => {
770
- try {
771
- await requireValidAccess(command);
772
- await handler();
773
- } catch (err) {
774
- console.error(`Falha runtime canon: ${err && err.message ? err.message : err}`);
775
- process.exit(1);
776
- }
777
- })();
1
+ #!/usr/bin/env node
2
+ // packages/predators-protocol/bin/predators-cli.js
3
+ // NPX CLI canon Predators Protocol · 11 comandos fase BETA cumulativa
4
+ // Lei #11 honest UPFRONT · Lei #14 PERFEITO OU FIX-GERAL · Lei #13 Pureza canon
5
+
6
+ "use strict";
7
+
8
+ const fs = require("fs");
9
+ const path = require("path");
10
+ const { spawnSync } = require("child_process");
11
+
12
+ const CLI_VERSION_CANON = "predators-cli-canon-1.0.0-STABLE-14-leis-14-canon-docs-brain-100pct-2026-05-28";
13
+
14
+ const PACKAGE_ROOT = path.resolve(__dirname, "..");
15
+ const BUNDLE_DIR = path.join(PACKAGE_ROOT, "bundle");
16
+ const LIB_DIR = path.join(PACKAGE_ROOT, "lib");
17
+
18
+ // UX layer (additive · Lei #4 byte-canon preserve · 11 comandos existentes inalterados)
19
+ let uxLib = null;
20
+ function loadUxLib() {
21
+ if (uxLib) return uxLib;
22
+ try {
23
+ uxLib = {
24
+ splash: require(path.join(LIB_DIR, "splash.js")),
25
+ config: require(path.join(LIB_DIR, "config.js")),
26
+ audio: require(path.join(LIB_DIR, "audio.js")),
27
+ colors: require(path.join(LIB_DIR, "colors.js")),
28
+ asciiArt: require(path.join(LIB_DIR, "ascii-art.js")),
29
+ spinners: require(path.join(LIB_DIR, "spinners.js")),
30
+ };
31
+ return uxLib;
32
+ } catch (err) {
33
+ return null;
34
+ }
35
+ }
36
+
37
+ function bundlePath(relPath) {
38
+ return path.join(BUNDLE_DIR, relPath);
39
+ }
40
+
41
+ function detectPythonCanon() {
42
+ // Priority: PREDATORS_PYTHON env override → repo .venv (if in dev) → python3 → python
43
+ const candidates = [];
44
+
45
+ if (process.env.PREDATORS_PYTHON && fs.existsSync(process.env.PREDATORS_PYTHON)) {
46
+ candidates.push(process.env.PREDATORS_PYTHON);
47
+ }
48
+
49
+ // Dev mode: if invoked from within Predators repo (next to .venv)
50
+ const devVenvWin = path.resolve(PACKAGE_ROOT, "..", "..", ".venv", "Scripts", "python.exe");
51
+ const devVenvUnix = path.resolve(PACKAGE_ROOT, "..", "..", ".venv", "bin", "python");
52
+ if (fs.existsSync(devVenvWin)) candidates.push(devVenvWin);
53
+ if (fs.existsSync(devVenvUnix)) candidates.push(devVenvUnix);
54
+
55
+ // System python
56
+ for (const cmd of ["python3", "python"]) {
57
+ const probe = spawnSync(cmd, ["--version"], { encoding: "utf8" });
58
+ if (probe.status === 0) {
59
+ candidates.push(cmd);
60
+ break;
61
+ }
62
+ }
63
+
64
+ return candidates.length > 0 ? candidates[0] : null;
65
+ }
66
+
67
+ function printHelpCanon() {
68
+ console.error(`
69
+ predators-cli · canon Predators NPX CLI 1.0.0 STABLE (canon 100% · 14 leis ratificadas)
70
+
71
+ USO:
72
+ npx predators-protocol <comando>
73
+
74
+ COMANDOS canon vigentes (17 comandos):
75
+
76
+ -- fase 1 (introspecção · 4 comandos) --
77
+ version Exibe versão canon
78
+ status Estado atual canon · bundle integrity check
79
+ list-predators Lista 64 predadores frota canon vigente
80
+ list-workflows Lista 4 workflows canon (caca-sistematica · pacto-cyber-squad · pipeline-fenix · saneamento-brownfield)
81
+
82
+ -- fase BETA (state machines · 5 comandos) --
83
+ workflow-states Lista 6 WorkflowStateCanon (PENDING/SCHEDULED/RUNNING/COMPLETED/FAILED/PAUSED)
84
+ story-states Lista 5 StoryStateCanon (DRAFT/REFINEMENT/READY/IN_PROGRESS/DONE)
85
+ layers-list Lista 7 ContextLayerCanon L0-L6 (Lei do Sangue → user input)
86
+ benchmark-info Mostra benchmark scipy protocol canon (N=180 p<0.05)
87
+ metrics-list Lista 4 golden signals canon M1 APM (latency + traffic + errors + saturation)
88
+
89
+ -- fase UX (additive · Lei #4 byte-canon preserve · 5 comandos) --
90
+ init Polimórfico · sem arg = splash cinematográfico · com <name> = scaffolda projeto novo + sync
91
+ Flags: --force (sempre cinemático · ignora cache) · --minimal (1-linha)
92
+ config Preferências user (theme · audio · splash · telemetry)
93
+ show Renderiza ASCII art predator card OR The Eye logo
94
+ sync Sincroniza canon files (predators/ + docs/ + .claude/ + CLAUDE.md) do bundle NPX para CWD
95
+ tour Cinematic walkthrough · 5 atos canon (camadas · leis · diretrizes · comandos · próximos passos)
96
+
97
+ -- fase R2 (onboarding · 2026-05-26 · Polvo · 1 comando novo) --
98
+ install Alias semântico para 'sync --force' · UX onboarding clearer
99
+
100
+ -- fase TOKEN-COLABORADOR (2026-05-27 · Borboleta + Jaguar · 2 comandos novos) --
101
+ unlock <TOKEN> Ativa acesso colaborador via token (canon access-token-client)
102
+ gen-token Apex T7 gera token via CLI (PREDATORS_OWNER_KEY_BACKEND env)
103
+ Usage: gen-token --name "Nome" [--email x] [--list]
104
+
105
+ -- fase BRAIN (2026-05-28 · 1.0.0 STABLE · 1 comando novo) --
106
+ brain-status Snapshot canon estrutura cerebral · 11 daemons + 6 flags + Elefante (READ-only)
107
+ Runtime real exige Python + clonar repo + brain-on.cmd · ver caminho em docs
108
+
109
+ -- fase BRAND (2026-05-29 · BrandBook v2 OBSIDIANA · 1 comando novo) --
110
+ brand-status Snapshot canon paleta v2 + tipografia + cadeia de ratificacao (READ-only)
111
+ 13 hex byte-canon · Archivo/Inter/JetBrains Mono · Pavao Art. 4 v2 + Dragao Art. 3
112
+
113
+ help Exibe esta mensagem
114
+
115
+ Lei #11 honest UPFRONT 1.0.0 STABLE cumulativa:
116
+ · Bundle 163 files · 64 predadores + 14 LEI canon-docs + AUDIT-FIRM + SH-CATALOG + BRAND-CANON + 7 skills · ZERO infra leak
117
+ · sync command requer CWD contendo predators/ OU --force flag · pattern canon partner-bundle
118
+ · NPX = portal READ canon · scaffold projeto novo + token unlock. Encarnação real exige Claude Code CLI + repo + chave LLM
119
+ · brain-status = snapshot canon (não-live) · runtime real exige Python 3.11+ + brain-on.cmd · ver QUICKSTART-SOCIO.md
120
+ `);
121
+ }
122
+
123
+ function printVersionCanon() {
124
+ console.log(CLI_VERSION_CANON);
125
+ }
126
+
127
+ function printStatusCanon() {
128
+ const synapseMd = bundlePath("docs/SYNAPSE.md");
129
+ const encarnacaoMd = bundlePath("docs/ENCARNACAO.md");
130
+ const claudeMd = bundlePath("CLAUDE.md");
131
+ const predatorsDir = bundlePath("predators");
132
+ const skillsDir = bundlePath(".claude/commands");
133
+ let predatorCount = 0;
134
+ if (fs.existsSync(predatorsDir)) {
135
+ const walk = (dir) => {
136
+ for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
137
+ const p = path.join(dir, e.name);
138
+ if (e.isDirectory()) walk(p);
139
+ else if (e.name === "predator.json") predatorCount++;
140
+ }
141
+ };
142
+ walk(predatorsDir);
143
+ }
144
+ console.log("canon Predators status:");
145
+ console.log(` CLI version: ${CLI_VERSION_CANON}`);
146
+ console.log(` bundle root: ${BUNDLE_DIR}`);
147
+ console.log(` CLAUDE.md: ${fs.existsSync(claudeMd) ? "PRESENT" : "MISSING"}`);
148
+ console.log(` SYNAPSE.md: ${fs.existsSync(synapseMd) ? "PRESENT" : "MISSING"}`);
149
+ console.log(` ENCARNACAO.md: ${fs.existsSync(encarnacaoMd) ? "PRESENT" : "MISSING"}`);
150
+ console.log(` predators canon: ${predatorCount}/63 byte-presente`);
151
+ console.log(` .claude/commands/: ${fs.existsSync(skillsDir) ? "PRESENT" : "MISSING"}`);
152
+ console.log(` Lei #14 canon: PERFEITO OU FIX-GERAL ratificada constitucional`);
153
+ console.log(` Lei #1 reign: bundle slim · ZERO infra leak audit (0.3.0-beta.0)`);
154
+ console.log(` Diretrizes 4 (2026-05-24): Lei do Tom · Autonomia Sequencial · PASSO 0 EVERY · Separação canon-doc/comunicação`);
155
+ }
156
+
157
+ function listPredatorsCanon() {
158
+ console.log("64 predadores frota canon vigente pós-F4 Baleia-cantora:");
159
+ console.log(" apex: 4 (Águia + Leão + Orca + Tigre-siberiano)");
160
+ console.log(" hunter: 5 (Tubarão-branco JUIZ FINAL Art. 14 + Escorpião + Hiena + Crocodilo + Piranha)");
161
+ console.log(" builder: 9 (Jaguar + Tatu-bola + Coruja + Pirarucu + Lince + Polvo + 3)");
162
+ console.log(" designer: 8 (Borboleta-azul + Tucano-toco + Baleia-cantora + 5)");
163
+ console.log(" copy: 6 (Serpente-coral + 5)");
164
+ console.log(" intel: 8 (Lobo-solitário + Tarântula + Jiboia + 5)");
165
+ console.log(" governance: 6");
166
+ console.log(" growth: 6");
167
+ console.log(" web3: 6 (Medusa + 5)");
168
+ console.log(" meta: 6 (Dragão-ancestral + Elefante + Fênix + Camaleão + Serpente + 1)");
169
+ }
170
+
171
+ function listWorkflowsCanon() {
172
+ console.log("4 workflows canon Predators (Lei #13 Pureza):");
173
+ console.log(" - caca-sistematica");
174
+ console.log(" - pacto-cyber-squad");
175
+ console.log(" - pipeline-fenix");
176
+ console.log(" - saneamento-brownfield");
177
+ }
178
+
179
+ function listWorkflowStatesCanon() {
180
+ console.log("6 WorkflowStateCanon canon Predators (D2 ETAPA 2 state machine):");
181
+ console.log(" PENDING · workflow definição cravada · zero execução");
182
+ console.log(" SCHEDULED · próxima execução planejada · cron canon");
183
+ console.log(" RUNNING · steps em execução runtime");
184
+ console.log(" COMPLETED · todos steps OK · success path");
185
+ console.log(" FAILED · step falhou · rollback canon");
186
+ console.log(" PAUSED · humano interrompeu · retomar manual");
187
+ console.log("");
188
+ console.log("7 transições válidas canon (Lei #4 reign state machine):");
189
+ console.log(" PENDING → SCHEDULED · SCHEDULED → RUNNING · RUNNING → COMPLETED");
190
+ console.log(" RUNNING FAILED · RUNNING PAUSED · PAUSED → RUNNING · FAILED → PENDING");
191
+ }
192
+
193
+ function listStoryStatesCanon() {
194
+ console.log("5 StoryStateCanon canon Predators (D3 ETAPA 3 state machine):");
195
+ console.log(" DRAFT · criação inicial · briefing parcial");
196
+ console.log(" REFINEMENT · briefing completo · Águia preside refinamento");
197
+ console.log(" READY · predator owner identificado · scope clear");
198
+ console.log(" IN_PROGRESS · predator encarnado executando");
199
+ console.log(" DONE · 5 garantias entregues · audit Tubarão PASS");
200
+ console.log("");
201
+ console.log("7 transições válidas canon:");
202
+ console.log(" DRAFT → REFINEMENT → READY → IN_PROGRESS → DONE (caminho canônico)");
203
+ console.log(" REFINEMENT/READY/IN_PROGRESS DRAFT (rejeição com feedback)");
204
+ }
205
+
206
+ function listLayersCanon() {
207
+ console.log("7 ContextLayerCanon L0-L6 canon Predators (D5 ETAPA 1 runtime middleware):");
208
+ console.log(" L0 LEI_DO_SANGUE_ART_1 · CRITICAL_imutavel priority 1000");
209
+ console.log(" L1 LEI_4_SYNAPSE_5_GARANTIAS · CRITICAL_reign priority 900");
210
+ console.log(" L2 5_IMUTAVEIS_BYTE_PRESERVED · CRITICAL_byte_preserved priority 800");
211
+ console.log(" L3 14_LEIS_CANON_VIGENTES · ALTA_vigente priority 600");
212
+ console.log(" L4 PREDATOR_ENCARNADO_CONSTITUTION · ALTA_encarnacao priority 500");
213
+ console.log(" L5 TASK_ESPECIFICA_CONTEXTO · MEDIA_task priority 300");
214
+ console.log(" L6 USER_PROMPT_INPUT · INFO_user_input priority 100");
215
+ console.log("");
216
+ console.log("L0+L1+L2 CRITICAL mandatory · Lei #14 BINARY FIX-GERAL trigger se ausentes");
217
+ }
218
+
219
+ function showBenchmarkInfoCanon() {
220
+ console.log("Benchmark canon Predators · scipy.stats N=180 p<0.05 protocol:");
221
+ console.log("");
222
+ console.log(" dimensions canon (6):");
223
+ console.log(" D5_context_layers_L0_L6");
224
+ console.log(" D2_workflows_engine");
225
+ console.log(" D3_stories_lifecycle");
226
+ console.log(" D4_multi_project_filesystem");
227
+ console.log(" D1_mcp_consuming");
228
+ console.log(" D6_dispatcher_integration");
229
+ console.log("");
230
+ console.log(" parâmetros estatísticos canon:");
231
+ console.log(" sample size per dimension: 30");
232
+ console.log(" total samples N: 180");
233
+ console.log(" p-value threshold: < 0.05");
234
+ console.log(" confidence interval: 95%");
235
+ console.log("");
236
+ console.log(" ttest_ind canon próprio Lei #13 Pureza (sem scipy hard-dep)");
237
+ console.log("");
238
+ console.log("Lei #11 honest UPFRONT: execução real depende provisioning Apex T7");
239
+ }
240
+
241
+ function listGoldenSignalsCanon() {
242
+ console.log("4 Golden Signals canon M1 APM Predators (B2 ONDA PRIORIDADES):");
243
+ console.log(" latency_milliseconds · CanonMetricHistogram (p50/p95/p99 via percentile_canon)");
244
+ console.log(" traffic_total · CanonMetricCounter");
245
+ console.log(" errors_total · CanonMetricCounter");
246
+ console.log(" saturation_active · CanonMetricGauge");
247
+ console.log("");
248
+ console.log("5 dimensões instrumentadas canon:");
249
+ console.log(" D1_mcp_consuming · D2_workflows_engine · D3_stories_lifecycle · D4_multi_project_filesystem · D5_context_layers_middleware");
250
+ console.log("");
251
+ console.log("Lei #13 Pureza: metrics canon próprio · duck-type prometheus_client (sem hard-dep externa)");
252
+ }
253
+
254
+ // ──────────────────────────────────────────────────────────────────────
255
+ // UX layer commands (additive · Lei #4 byte-canon preserve)
256
+ // ──────────────────────────────────────────────────────────────────────
257
+
258
+ async function runInitCommand() {
259
+ const args = process.argv.slice(3);
260
+ const positionalArgs = args.filter(a => !a.startsWith("-"));
261
+ const projectName = positionalArgs[0] || null;
262
+
263
+ // Polymorphic init (R2 onda · 2026-05-26 · Polvo Builder)
264
+ // - no positional arg → splash UX (backward compat byte-preserved)
265
+ // - positional arg → project scaffolding (mkdir + sync inside)
266
+ if (projectName) {
267
+ return runInitProjectMode(projectName, args);
268
+ }
269
+
270
+ const ux = loadUxLib();
271
+ if (!ux) {
272
+ console.error("UX layer não-disponível neste pacote.");
273
+ process.exit(1);
274
+ }
275
+ const forceFlag = args.includes("--force") || args.includes("-f");
276
+ const minimalFlag = args.includes("--minimal") || args.includes("-m");
277
+ await ux.splash.runInitSplash({ force: forceFlag, minimal: minimalFlag });
278
+ }
279
+
280
+ function runInitProjectMode(projectName, args) {
281
+ const cwd = process.cwd();
282
+ const targetDir = path.resolve(cwd, projectName);
283
+ const force = args.includes("--force") || args.includes("-f");
284
+
285
+ if (fs.existsSync(targetDir)) {
286
+ const contents = fs.readdirSync(targetDir);
287
+ if (contents.length > 0 && !force) {
288
+ console.error(`init · diretório ${projectName} existe e não está vazio.`);
289
+ console.error(" · Use diretório vazio · OU passe --force para sobrescrever (cuidado)");
290
+ process.exit(1);
291
+ }
292
+ } else {
293
+ fs.mkdirSync(targetDir, { recursive: true });
294
+ }
295
+
296
+ console.log("Predators Protocol · init project canon (R2 onda 2026-05-26 · Polvo)");
297
+ console.log(` projeto: ${projectName}`);
298
+ console.log(` path: ${targetDir}`);
299
+ console.log("");
300
+
301
+ process.chdir(targetDir);
302
+ if (!process.argv.includes("--force")) {
303
+ process.argv.push("--force");
304
+ }
305
+ runSyncCommand();
306
+
307
+ console.log("");
308
+ console.log("Próximos passos:");
309
+ console.log(` cd ${projectName}`);
310
+ console.log(" npx predators-protocol tour # tour cinematográfico");
311
+ console.log(" npx predators-protocol show eye # logo canon");
312
+ }
313
+
314
+ function runInstallCommand() {
315
+ // Alias semântico canon para `sync --force` (UX onboarding clearer)
316
+ // R2 onda · 2026-05-26 · Polvo · LMAS parity sem violar Lei #13 (canon próprio)
317
+ console.log("install · alias canon para `sync --force` · instala canon files no CWD");
318
+ console.log("");
319
+ if (!process.argv.includes("--force")) {
320
+ process.argv.push("--force");
321
+ }
322
+ runSyncCommand();
323
+ }
324
+
325
+ function runConfigCommand() {
326
+ const ux = loadUxLib();
327
+ if (!ux) {
328
+ console.error("UX layer não-disponível neste pacote.");
329
+ process.exit(1);
330
+ }
331
+ const subcommand = process.argv[3] || "show";
332
+ const arg = process.argv[4];
333
+
334
+ if (subcommand === "show" || subcommand === "status") {
335
+ const cfg = ux.config.readConfig();
336
+ console.log("Predators Protocol · user config");
337
+ console.log(` path: ${ux.config.getConfigPath()}`);
338
+ console.log(` theme: ${cfg.theme}`);
339
+ console.log(` splash.enabled: ${cfg.splash.enabled}`);
340
+ console.log(` audio.enabled: ${cfg.audio.enabled}`);
341
+ console.log(` firstConnectionAt: ${cfg.firstConnectionAt || "(never)"}`);
342
+ console.log(` lastConnectionAt: ${cfg.lastConnectionAt || "(never)"}`);
343
+ return;
344
+ }
345
+ if (subcommand === "theme") {
346
+ if (!arg) {
347
+ console.log(`Current theme: ${ux.config.getTheme()}`);
348
+ console.log("Available: default, dark, light, monochrome");
349
+ return;
350
+ }
351
+ const result = ux.config.setTheme(arg);
352
+ if (result) {
353
+ console.log(`Theme set: ${arg}`);
354
+ } else {
355
+ console.error(`Invalid theme: ${arg} · available: default, dark, light, monochrome`);
356
+ process.exit(1);
357
+ }
358
+ return;
359
+ }
360
+ if (subcommand === "audio") {
361
+ if (arg === "--enable" || arg === "on") {
362
+ ux.config.setAudioEnabled(true);
363
+ console.log("Audio: enabled · .mp3 byte pendentes produção externa (Suno/ElevenLabs/Stable Audio · canon spec docs/PRDs/ONDA-BALEIA-CANTORA-FASE-2-SIGNATURES-2026-05-24/)");
364
+ return;
365
+ }
366
+ if (arg === "--disable" || arg === "off") {
367
+ ux.config.setAudioEnabled(false);
368
+ console.log("Audio: disabled");
369
+ return;
370
+ }
371
+ if (arg === "--status" || !arg) {
372
+ const status = ux.audio.getStatusReport();
373
+ console.log("Audio status canon:");
374
+ console.log(` enabled: ${status.enabled}`);
375
+ console.log(` platform: ${status.platform} (WSL: ${status.is_wsl})`);
376
+ console.log(` player_available: ${status.player_available} (${status.player_cmd || "none"})`);
377
+ console.log(` ${status.canon_note}`);
378
+ console.log(" signatures Baleia-cantora F4 Fase 2:");
379
+ for (const s of status.sounds) {
380
+ console.log(` · ${s.name} - ${s.description} (file: ${s.file_present ? "PRESENT" : "PENDENTE"})`);
381
+ }
382
+ return;
383
+ }
384
+ }
385
+ if (subcommand === "telemetry") {
386
+ if (arg === "--enable" || arg === "on") {
387
+ ux.config.setTelemetryEnabled(true);
388
+ const status = ux.config.getTelemetryStatus();
389
+ console.log("Telemetry: enabled");
390
+ console.log(` anonymous_id: ${status.anonymous_id} (gerado runtime · zero PII)`);
391
+ console.log(` endpoint: ${status.endpoint || "local-only (future network endpoint TBD Apex T7)"}`);
392
+ console.log(" Lei #1 reign: zero PII · zero IP capture · zero hostname · só sync events anônimos");
393
+ return;
394
+ }
395
+ if (arg === "--disable" || arg === "off") {
396
+ ux.config.setTelemetryEnabled(false);
397
+ console.log("Telemetry: disabled · zero coleta");
398
+ return;
399
+ }
400
+ if (arg === "--status" || !arg) {
401
+ const status = ux.config.getTelemetryStatus();
402
+ console.log("Telemetry status canon:");
403
+ console.log(` enabled: ${status.enabled}`);
404
+ console.log(` anonymous_id: ${status.anonymous_id || "(não gerado · opt-in pendente)"}`);
405
+ console.log(` sync_count: ${status.sync_count}`);
406
+ console.log(` last_sync_at: ${status.last_sync_at || "(nunca)"}`);
407
+ console.log(` endpoint: ${status.endpoint || "local-only (null)"}`);
408
+ console.log(` ${status.canon_note}`);
409
+ return;
410
+ }
411
+ }
412
+ console.error(`Config subcommand desconhecido: ${subcommand}`);
413
+ console.error("Available: show · theme [default|dark|light|monochrome] · audio [--enable|--disable|--status] · telemetry [--enable|--disable|--status]");
414
+ process.exit(1);
415
+ }
416
+
417
+ function runShowCommand() {
418
+ const ux = loadUxLib();
419
+ if (!ux) {
420
+ console.error("UX layer não-disponível neste pacote.");
421
+ process.exit(1);
422
+ }
423
+ const target = process.argv[3] || "eye";
424
+ const theme = ux.config.getTheme();
425
+
426
+ if (target === "eye" || target === "logo") {
427
+ console.log(ux.asciiArt.renderEye(theme));
428
+ return;
429
+ }
430
+ if (target === "banner") {
431
+ console.log(ux.asciiArt.renderHeroBanner(theme));
432
+ return;
433
+ }
434
+ if (target === "list") {
435
+ console.log("Predator cards canon vigentes:");
436
+ for (const id of ux.asciiArt.listPredatorsWithCards()) {
437
+ console.log(` · ${id}`);
438
+ }
439
+ return;
440
+ }
441
+ const card = ux.asciiArt.renderPredatorCard(target, theme);
442
+ if (!card) {
443
+ console.error(`Predator card não-disponível: ${target}`);
444
+ console.error("Disponíveis: " + ux.asciiArt.listPredatorsWithCards().join(", "));
445
+ console.error("Outros targets: eye | logo | banner | list");
446
+ process.exit(1);
447
+ }
448
+ console.log(card);
449
+ }
450
+
451
+ // ──────────────────────────────────────────────────────────────────────
452
+ // sync command · canon files refresh CWD from bundle (0.3.0-beta.0)
453
+ // ──────────────────────────────────────────────────────────────────────
454
+
455
+ function copyDirRecursive(src, dst) {
456
+ if (!fs.existsSync(src)) return { copied: 0, skipped: 0 };
457
+ fs.mkdirSync(dst, { recursive: true });
458
+ let copied = 0;
459
+ let skipped = 0;
460
+ for (const e of fs.readdirSync(src, { withFileTypes: true })) {
461
+ const s = path.join(src, e.name);
462
+ const d = path.join(dst, e.name);
463
+ if (e.isDirectory()) {
464
+ const r = copyDirRecursive(s, d);
465
+ copied += r.copied;
466
+ skipped += r.skipped;
467
+ } else {
468
+ fs.copyFileSync(s, d);
469
+ copied++;
470
+ }
471
+ }
472
+ return { copied, skipped };
473
+ }
474
+
475
+ function backupExistingPath(target) {
476
+ if (!fs.existsSync(target)) return null;
477
+ const ts = new Date().toISOString().replace(/[:.]/g, "-");
478
+ const backup = `${target}.backup-${ts}`;
479
+ fs.renameSync(target, backup);
480
+ return backup;
481
+ }
482
+
483
+ function runSyncCommand() {
484
+ const args = process.argv.slice(3);
485
+ const dryRun = args.includes("--dry-run");
486
+ const force = args.includes("--force") || args.includes("-f");
487
+ const cwd = process.cwd();
488
+
489
+ // Refuse to overwrite a non-Predators directory unless --force passed.
490
+ const looksLikePredatorsCwd =
491
+ fs.existsSync(path.join(cwd, "predators")) ||
492
+ fs.existsSync(path.join(cwd, "CLAUDE.md")) ||
493
+ fs.existsSync(path.join(cwd, ".claude")) ||
494
+ fs.existsSync(path.join(cwd, "QUICKSTART-SOCIO.md"));
495
+
496
+ if (!looksLikePredatorsCwd && !force) {
497
+ console.error("sync · CWD não parece ser pasta Predators (sem predators/ · CLAUDE.md · .claude/).");
498
+ console.error(` CWD: ${cwd}`);
499
+ console.error(" · Para sync inicial em pasta vazia · use: npx predators-protocol sync --force");
500
+ console.error(" · Para sync em pasta Predators existente · CWD precisa conter CLAUDE.md ou predators/");
501
+ process.exit(1);
502
+ }
503
+
504
+ const SYNC_TARGETS = [
505
+ { rel: "predators", type: "dir" },
506
+ { rel: "docs", type: "dir" },
507
+ { rel: ".claude/commands", type: "dir" },
508
+ { rel: "CLAUDE.md", type: "file" },
509
+ { rel: "QUICKSTART-SOCIO.md", type: "file" },
510
+ ];
511
+
512
+ console.log("Predators Protocol · sync canon files do bundle NPX para CWD");
513
+ console.log(` bundle: ${BUNDLE_DIR}`);
514
+ console.log(` target: ${cwd}`);
515
+ if (dryRun) console.log(" mode: DRY-RUN (zero writes)");
516
+ console.log("");
517
+
518
+ let totalCopied = 0;
519
+ for (const { rel, type } of SYNC_TARGETS) {
520
+ const src = path.join(BUNDLE_DIR, rel);
521
+ const dst = path.join(cwd, rel);
522
+
523
+ if (!fs.existsSync(src)) {
524
+ console.log(` skip: ${rel} (não-presente no bundle)`);
525
+ continue;
526
+ }
527
+
528
+ if (dryRun) {
529
+ console.log(` preview: ${rel} (${type}) · would sync from bundle`);
530
+ continue;
531
+ }
532
+
533
+ const backup = backupExistingPath(dst);
534
+ if (backup) {
535
+ console.log(` backup: ${path.basename(backup)}`);
536
+ }
537
+
538
+ if (type === "dir") {
539
+ const r = copyDirRecursive(src, dst);
540
+ console.log(` sync: ${rel}/ (${r.copied} files)`);
541
+ totalCopied += r.copied;
542
+ } else {
543
+ fs.mkdirSync(path.dirname(dst), { recursive: true });
544
+ fs.copyFileSync(src, dst);
545
+ console.log(` sync: ${rel}`);
546
+ totalCopied++;
547
+ }
548
+ }
549
+
550
+ if (dryRun) {
551
+ console.log("\nDRY-RUN complete · use sem --dry-run para aplicar.");
552
+ } else {
553
+ // Record sync event canon (local always · network telemetry if opt-in + endpoint configured)
554
+ const ux = loadUxLib();
555
+ if (ux && ux.config && ux.config.recordSyncEvent) {
556
+ try { ux.config.recordSyncEvent(); } catch (e) { /* graceful · sync continua */ }
557
+ }
558
+ console.log(`\nsync complete · ${totalCopied} files canon writados · backups com sufixo .backup-<timestamp>`);
559
+ console.log("Lei #1 reign: bundle slim · ZERO infra leak (1.0.0 STABLE)");
560
+ }
561
+ }
562
+
563
+ // ──────────────────────────────────────────────────────────────────────
564
+ // tour command · cinematic walkthrough canon vigente (1.0.0 STABLE)
565
+ // ──────────────────────────────────────────────────────────────────────
566
+
567
+ function sleep(ms) {
568
+ return new Promise(resolve => setTimeout(resolve, ms));
569
+ }
570
+
571
+ async function runTourCommand() {
572
+ const ux = loadUxLib();
573
+ if (!ux) {
574
+ console.error("UX layer não-disponível neste pacote.");
575
+ process.exit(1);
576
+ }
577
+ const args = process.argv.slice(3);
578
+ const fast = args.includes("--fast");
579
+ const beat = fast ? 200 : 800;
580
+
581
+ const theme = ux.config.getTheme();
582
+ console.log("");
583
+ console.log(ux.asciiArt.renderEye(theme));
584
+ await sleep(beat);
585
+
586
+ console.log("");
587
+ console.log("PREDADORES PROTOCOL · tour canon vigente (1.0.0 STABLE)");
588
+ console.log("64 predadores · 10 camadas · 14 leis · 5 garantias Synapse");
589
+ await sleep(beat);
590
+
591
+ console.log("");
592
+ console.log("─── 1/5 · 10 camadas trofic ───");
593
+ await sleep(beat / 2);
594
+ const layers = [
595
+ ["apex", "4 predators", "T5", "Águia + Leão + Orca + Tigre"],
596
+ ["hunter", "5 predators", "T4-T5", "Tubarão JUIZ + Cyber Squad"],
597
+ ["builder", "9 predators", "T3", "Polvo + Tatu + Jaguar + 6"],
598
+ ["designer", "8 predators", "T3-T4", "Borboleta + Tucano + Baleia-cantora F4"],
599
+ ["copy", "6 predators", "T3", "Serpente-coral + 5"],
600
+ ["intel", "8 predators", "T3", "Lobo-solitário + Tarântula + 6"],
601
+ ["governance", "6 predators", "T3", "Tigre + Gorila + Lince + 3"],
602
+ ["growth", "6 predators", "T2-T3", "Leão push + Formiga + 4"],
603
+ ["web3", "6 predators", "T3", "Medusa veto + 5"],
604
+ ["meta", "6 predators", "T1-T2", "Dragão + Fênix + Elefante + 3"],
605
+ ];
606
+ for (const [layer, count, trophic, examples] of layers) {
607
+ console.log(` · ${layer.padEnd(11)} ${count.padEnd(12)} ${trophic.padEnd(6)} ${examples}`);
608
+ await sleep(beat / 4);
609
+ }
610
+
611
+ console.log("");
612
+ console.log("─── 2/5 · 14 leis canon vigentes ───");
613
+ await sleep(beat / 2);
614
+ const laws = [
615
+ "Lei #1 Lei do Sangue (ABSOLUTO · Tubarão Art. 1 imutável)",
616
+ "Lei #2 Lei dos Predadores (Fênix Protocol exclusive)",
617
+ "Lei #3 Lei da Melhoria Disciplinada",
618
+ "Lei #4 Lei da Synapse (5 garantias canon)",
619
+ "Lei #5 Canon dos 3 Vetos (Sangue · Operacional · Constitucional)",
620
+ "Lei #6 Lei dos Predadores Reais (zero demo)",
621
+ "Lei #7 Lei da Matilha Paralela",
622
+ "Lei #8 Verificação Empírica (ABSOLUTO)",
623
+ "Lei #9 Análise antes de Execução",
624
+ "Lei #10 Skill canon estrito",
625
+ "Lei #11 NUNCA MINTA JAMAIS (ABSOLUTO)",
626
+ "Lei #12 O melhor dos melhores",
627
+ "Lei #13 Pureza Predators (ABSOLUTO)",
628
+ "Lei #14 PERFEITO OU FIX-GERAL (BINARY)",
629
+ ];
630
+ for (const law of laws) {
631
+ console.log(` · ${law}`);
632
+ await sleep(beat / 5);
633
+ }
634
+
635
+ console.log("");
636
+ console.log("─── 3/5 · 4 Diretrizes Comunicação ───");
637
+ await sleep(beat / 2);
638
+ console.log(" 1. Lei do Tom Conversacional (Apex T7 direct)");
639
+ console.log(" 2. Autonomia Sequencial (Lei #9)");
640
+ console.log(" 3. PASSO 0 EVERY ONDA (Lei #8 baseline)");
641
+ console.log(" 4. Separação canon-doc vs comunicação direta");
642
+ await sleep(beat);
643
+
644
+ console.log("");
645
+ console.log("─── 4/5 · 13 comandos NPX vigentes ───");
646
+ await sleep(beat / 2);
647
+ console.log(" introspecção: version · status · list-predators · list-workflows");
648
+ console.log(" state machines: workflow-states · story-states · layers-list · benchmark-info · metrics-list");
649
+ console.log(" experiência UX: init · config · show · sync · tour");
650
+ await sleep(beat);
651
+
652
+ console.log("");
653
+ console.log("─── 5/5 · Comando canon para sócios ───");
654
+ await sleep(beat / 2);
655
+ console.log("");
656
+ console.log(" mkdir predators-protocol && cd predators-protocol");
657
+ console.log(" npx predators-protocol@beta sync --force");
658
+ console.log("");
659
+ console.log(" → 143 files canon na pasta (64 predadores + docs + skills + CLAUDE.md)");
660
+ console.log(" → abre no VS Code · ativa extensão Claude Code");
661
+ console.log(" /encarnar tubarao-branco (ou qualquer dos 64 IDs)");
662
+ await sleep(beat);
663
+
664
+ console.log("");
665
+ console.log("─── fim do tour ───");
666
+ console.log("");
667
+ console.log("Próximos passos sugeridos:");
668
+ console.log(" · npx predators-protocol@beta sync --force (instala canon na pasta atual)");
669
+ console.log(" · npx predators-protocol@beta show eye (logo cinematográfico)");
670
+ console.log(" · npx predators-protocol@beta show list (lista predator cards disponíveis)");
671
+ console.log(" · npx predators-protocol@beta help (todos os 13 comandos)");
672
+ console.log("");
673
+ console.log("🦈🐋 Predators Protocol · proprietário · Alex Gonzaga (Tubarão-Apex) · 2026-05-24");
674
+ }
675
+
676
+ // ──────────────────────────────────────────────────────────────────────
677
+
678
+ const command = process.argv[2] || "help";
679
+
680
+ // Lei #1 [a-m] gates · access-token middleware canon 2026-05-27
681
+ // Sócios bypass via PREDATORS_OWNER_KEY env var · colaboradores via `unlock <TOKEN>`
682
+ const { runUnlock, requireValidAccess } = require("../lib/access-token-client.js");
683
+ // Lei #1 [ok1-ok4] gates · gen-token CLI canon 2026-05-27
684
+ const { runGenToken } = require("../lib/gen-token-client.js");
685
+
686
+ async function runUnlockCommand() {
687
+ const token = process.argv[3];
688
+ await runUnlock(token);
689
+ }
690
+
691
+ async function runGenTokenCommand() {
692
+ await runGenToken();
693
+ }
694
+
695
+ // brain-status command · 1.0.0 STABLE · ONDA-NPX-100-RELEASE
696
+ // Snapshot canon estrutura cerebral · READ-only · runtime real exige Python
697
+ async function runBrainStatusCommand() {
698
+ const snapshotPath = bundlePath("docs/CANON/BRAIN-STATUS-SNAPSHOT.json");
699
+ if (!fs.existsSync(snapshotPath)) {
700
+ console.error("brain-status snapshot ausente no bundle · re-sync canon necessário");
701
+ process.exit(1);
702
+ }
703
+ let snapshot;
704
+ try {
705
+ snapshot = JSON.parse(fs.readFileSync(snapshotPath, "utf-8"));
706
+ } catch (err) {
707
+ console.error(`brain-status snapshot JSON inválido: ${err.message}`);
708
+ process.exit(1);
709
+ }
710
+ console.log("");
711
+ console.log("PREDADORES PROTOCOL · ESTRUTURA CEREBRAL · snapshot canon");
712
+ console.log("==========================================================");
713
+ console.log(`Snapshot cravado: ${snapshot.snapshot_at}`);
714
+ console.log(`Commit master: ${snapshot.commit_hash_short}`);
715
+ console.log(`Status agregado: ${snapshot.status_aggregate}`);
716
+ console.log("");
717
+ console.log("11 daemons cerebrais (runtime real · não-snapshot):");
718
+ for (const d of snapshot.daemons) {
719
+ console.log(` · ${d.name.padEnd(22)} ${d.role}`);
720
+ }
721
+ console.log("");
722
+ console.log("6 feature flags Híbrida (default canon vigente):");
723
+ for (const f of snapshot.feature_flags) {
724
+ const mark = f.default === "true" ? "LIVE" : "OPT-IN";
725
+ console.log(` · ${f.name.padEnd(28)} default=${f.default.padEnd(5)} ${mark}`);
726
+ }
727
+ console.log("");
728
+ console.log("Elefante · memória institucional Art. 6 imutável:");
729
+ console.log(` · pointers cumulative: ${snapshot.elefante.memory_pointers_count}`);
730
+ console.log(` · trace neural files: ${snapshot.elefante.trace_neural_files_count}`);
731
+ console.log(` · consolidation cycles: ${snapshot.elefante.consolidation_cycles_cumulative}`);
732
+ console.log("");
733
+ console.log("Honest UPFRONT (Lei #11):");
734
+ console.log(" · brain-status é READ-only snapshot · cravado no commit acima");
735
+ console.log(" · runtime real exige: clone repo + Python 3.11+ + brain-on.cmd");
736
+ console.log(" · 11 daemons LIVE só rodam em clone do repositório · não-NPX");
737
+ console.log(" · ver bundle/QUICKSTART-SOCIO.md para caminho completo");
738
+ }
739
+
740
+ // brand-status command · BrandBook v2 OBSIDIANA · ONDA-BRANDBOOK-CANON-V2 Frente F
741
+ // Snapshot canon paleta + tipografia + cadeia de ratificacao · READ-only
742
+ async function runBrandStatusCommand() {
743
+ const snapshotPath = bundlePath("docs/CANON/BRAND-CANON.json");
744
+ if (!fs.existsSync(snapshotPath)) {
745
+ console.error("brand-status snapshot ausente no bundle · re-sync canon necessário");
746
+ process.exit(1);
747
+ }
748
+ let brand;
749
+ try {
750
+ brand = JSON.parse(fs.readFileSync(snapshotPath, "utf-8"));
751
+ } catch (err) {
752
+ console.error(`brand-status snapshot JSON inválido: ${err.message}`);
753
+ process.exit(1);
754
+ }
755
+ console.log("");
756
+ console.log("PREDADORES PROTOCOL · BRAND CANON · snapshot");
757
+ console.log("============================================");
758
+ console.log(`BrandBook: ${brand.brandbook_version}`);
759
+ console.log(`Snapshot cravado: ${brand.snapshot_at}`);
760
+ console.log(`Onda: ${brand.ratificacao.onda}`);
761
+ console.log(`Canon-doc: ${brand.ratificacao.canon_doc}`);
762
+ console.log(`Substitui: ${brand.ratificacao.substitui}`);
763
+ console.log("");
764
+ console.log(`Paleta · ${brand.paleta.familias} familias canon (WCAG base ${brand.paleta.wcag_base}):`);
765
+ for (const t of brand.paleta.tokens) {
766
+ const wcag = t.wcag ? ` [${t.wcag}]` : "";
767
+ console.log(` · ${t.token.padEnd(16)} ${t.hex.padEnd(9)} ${t.papel}${wcag}`);
768
+ }
769
+ console.log("");
770
+ console.log("Tipografia canon:");
771
+ console.log(` · display ${brand.tipografia.display.familia.padEnd(14)} ${brand.tipografia.display.papel} (${brand.tipografia.display.pesos})`);
772
+ console.log(` · body ${brand.tipografia.body.familia.padEnd(14)} ${brand.tipografia.body.papel}`);
773
+ console.log(` · mono ${brand.tipografia.mono.familia.padEnd(14)} ${brand.tipografia.mono.papel}`);
774
+ console.log("");
775
+ console.log(`Runtime source-of-truth: ${brand.runtime_source_of_truth}`);
776
+ console.log("");
777
+ console.log("Honest UPFRONT (Lei #11):");
778
+ for (const h of brand.honest_upfront) {
779
+ console.log(` · ${h}`);
780
+ }
781
+ }
782
+
783
+ const commandsCanon = {
784
+ version: printVersionCanon,
785
+ status: printStatusCanon,
786
+ "list-predators": listPredatorsCanon,
787
+ "list-workflows": listWorkflowsCanon,
788
+ "workflow-states": listWorkflowStatesCanon,
789
+ "story-states": listStoryStatesCanon,
790
+ "layers-list": listLayersCanon,
791
+ "benchmark-info": showBenchmarkInfoCanon,
792
+ "metrics-list": listGoldenSignalsCanon,
793
+ init: runInitCommand,
794
+ config: runConfigCommand,
795
+ show: runShowCommand,
796
+ sync: runSyncCommand,
797
+ install: runInstallCommand,
798
+ tour: runTourCommand,
799
+ unlock: runUnlockCommand,
800
+ "gen-token": runGenTokenCommand,
801
+ "brain-status": runBrainStatusCommand,
802
+ "brand-status": runBrandStatusCommand,
803
+ help: printHelpCanon,
804
+ "--help": printHelpCanon,
805
+ "-h": printHelpCanon,
806
+ };
807
+
808
+ const handler = commandsCanon[command];
809
+ if (!handler) {
810
+ console.error(`Comando canon NÃO vigente: ${command}`);
811
+ printHelpCanon();
812
+ process.exit(1);
813
+ }
814
+
815
+ // Lei #1 middleware · valida acesso ANTES de executar comando sensível
816
+ // (PUBLIC_COMMANDS · owner bypass · cache local 5min · phone-home revalidação)
817
+ (async () => {
818
+ try {
819
+ await requireValidAccess(command);
820
+ await handler();
821
+ } catch (err) {
822
+ console.error(`Falha runtime canon: ${err && err.message ? err.message : err}`);
823
+ process.exit(1);
824
+ }
825
+ })();