forjajs 5.1.0 → 5.3.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 (113) hide show
  1. package/CHANGELOG.md +76 -0
  2. package/README.md +37 -4
  3. package/README.pt-BR.md +39 -4
  4. package/dist/apps/cli/src/index.d.ts +0 -1
  5. package/dist/apps/cli/src/index.js +43 -32
  6. package/dist/apps/dashboard/app/api/forja/[...path]/route.js +34 -1
  7. package/dist/apps/dashboard/app/api/forja/capabilities.d.ts +26 -0
  8. package/dist/apps/dashboard/app/api/forja/capabilities.js +39 -0
  9. package/dist/apps/dashboard/app/dashboard-client.jsx +607 -42
  10. package/dist/apps/server/src/forja-nest.module.d.ts +6 -0
  11. package/dist/apps/server/src/forja-nest.module.js +55 -0
  12. package/dist/apps/server/src/main.d.ts +21 -4
  13. package/dist/apps/server/src/main.js +79 -57
  14. package/dist/apps/server/src/task-planning-service.d.ts +29 -0
  15. package/dist/apps/server/src/task-planning-service.js +195 -0
  16. package/dist/apps/server/src/task-runtime-coordinator.d.ts +57 -0
  17. package/dist/apps/server/src/task-runtime-coordinator.js +229 -0
  18. package/dist/bin/forja.js +3 -2
  19. package/dist/lib/agent-evals.d.ts +138 -0
  20. package/dist/lib/agent-evals.js +349 -0
  21. package/dist/lib/cli-output.js +14 -2
  22. package/dist/lib/code-context.d.ts +33 -5
  23. package/dist/lib/code-context.js +70 -5
  24. package/dist/lib/context-builder.d.ts +49 -4
  25. package/dist/lib/context-builder.js +114 -47
  26. package/dist/lib/core/coverage-gate.d.ts +59 -0
  27. package/dist/lib/core/coverage-gate.js +58 -0
  28. package/dist/lib/core/doc-graph.d.ts +38 -0
  29. package/dist/lib/core/doc-graph.js +83 -0
  30. package/dist/lib/core/health.js +286 -5
  31. package/dist/lib/core/journey.js +26 -0
  32. package/dist/lib/core/registry.js +81 -6
  33. package/dist/lib/docs-reference.d.ts +35 -0
  34. package/dist/lib/docs-reference.js +57 -0
  35. package/dist/lib/project-wiring.js +6 -2
  36. package/dist/lib/session-memory.d.ts +38 -0
  37. package/dist/lib/session-memory.js +206 -0
  38. package/dist/lib/spec-trace.d.ts +46 -0
  39. package/dist/lib/spec-trace.js +184 -0
  40. package/dist/packages/adapter-nest/src/index.d.ts +2 -1
  41. package/dist/packages/adapter-nest/src/index.js +59 -1
  42. package/dist/packages/adapter-sqlite/src/index.d.ts +15 -1
  43. package/dist/packages/adapter-sqlite/src/index.js +61 -1
  44. package/dist/packages/context/src/index.d.ts +2 -0
  45. package/dist/packages/context/src/index.js +36 -15
  46. package/dist/packages/contracts/src/index.d.ts +64 -0
  47. package/dist/packages/core/src/index.d.ts +9 -1
  48. package/dist/packages/core/src/index.js +28 -3
  49. package/dist/packages/graph/src/index.js +14 -5
  50. package/dist/packages/mcp/src/index.d.ts +8 -0
  51. package/dist/packages/mcp/src/index.js +12 -1
  52. package/dist/packages/observability/src/index.d.ts +11 -0
  53. package/dist/packages/observability/src/index.js +3 -0
  54. package/dist/packages/orchestration/src/index.d.ts +15 -1
  55. package/dist/packages/orchestration/src/index.js +127 -21
  56. package/dist/packages/planner/src/index.d.ts +7 -1
  57. package/dist/packages/planner/src/index.js +67 -10
  58. package/dist/packages/planner/src/proposal-store.d.ts +30 -0
  59. package/dist/packages/planner/src/proposal-store.js +109 -0
  60. package/dist/packages/policy/src/index.d.ts +9 -16
  61. package/dist/packages/policy/src/index.js +114 -31
  62. package/dist/packages/runtime/src/index.d.ts +16 -2
  63. package/dist/packages/runtime/src/index.js +176 -61
  64. package/dist/scripts/build-smart-context.d.ts +2 -0
  65. package/dist/scripts/build-smart-context.js +12 -3
  66. package/dist/scripts/code-context.d.ts +3 -1
  67. package/dist/scripts/code-context.js +13 -3
  68. package/dist/scripts/coverage-gate.d.ts +2 -0
  69. package/dist/scripts/coverage-gate.js +101 -0
  70. package/dist/scripts/eval-agents.d.ts +11 -0
  71. package/dist/scripts/eval-agents.js +96 -0
  72. package/dist/scripts/gen-commands-doc.d.ts +2 -0
  73. package/dist/scripts/gen-commands-doc.js +18 -0
  74. package/dist/scripts/hook-session-memory.d.ts +9 -0
  75. package/dist/scripts/hook-session-memory.js +20 -0
  76. package/dist/scripts/hook-session-start.js +34 -0
  77. package/dist/scripts/spec-trace.d.ts +10 -0
  78. package/dist/scripts/spec-trace.js +73 -0
  79. package/dist/scripts/sync-universal-memory.js +69 -4
  80. package/dist/scripts/token-benchmark.d.ts +33 -1
  81. package/dist/scripts/token-benchmark.js +179 -5
  82. package/dist/scripts/token-economy.js +3 -1
  83. package/dist/scripts/tools-doctor.d.ts +16 -1
  84. package/dist/scripts/tools-doctor.js +58 -17
  85. package/docs/commands.md +155 -0
  86. package/docs/fluxo.md +11 -7
  87. package/docs/init-project.md +3 -1
  88. package/docs/llm-fit-loop.md +20 -0
  89. package/docs/manual-operacional-cli-sdd-gsd.md +3 -2
  90. package/docs/produto/factsheet-marketing.md +7 -5
  91. package/docs/produto/roteiro-demo.md +14 -5
  92. package/docs/quick-reference.md +3 -3
  93. package/docs/token-optimization.md +10 -6
  94. package/memory/90-decisions/0091-memoria-de-sessao-por-hooks.md +40 -0
  95. package/memory/90-decisions/0092-criterios-de-aceite-ligados-a-testes.md +37 -0
  96. package/memory/90-decisions/0093-avaliacoes-com-agentes-reais.md +40 -0
  97. package/package.json +4 -2
  98. package/specs/avaliacoes-de-agentes/spec.md +52 -0
  99. package/specs/criterios-ligados-a-testes/spec.md +42 -0
  100. package/specs/memoria-de-sessao/spec.md +48 -0
  101. package/specs/v6-agent-runtime-portable/spec.md +83 -0
  102. package/specs/v6-core-consolidation/spec.md +70 -0
  103. package/specs/v6-docs-drift/spec.md +85 -0
  104. package/specs/v6-quality-gates/spec.md +99 -0
  105. package/specs/v6-token-economy/spec.md +84 -0
  106. package/templates/evals/agents/adr.json +25 -0
  107. package/templates/evals/agents/memoria.json +32 -0
  108. package/templates/evals/agents/proxima-acao.json +29 -0
  109. package/templates/evals/agents/spec-nova.json +26 -0
  110. package/templates/evals/agents/teste-do-criterio.json +29 -0
  111. package/templates/project/AGENTS.md +7 -0
  112. package/templates/project/CLAUDE.md +3 -2
  113. package/templates/project/skills/testing/SKILL.md +1 -1
@@ -0,0 +1,96 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * eval:agents — avaliações com agentes reais em projeto descartável (SPEC-054, ADR-0093).
4
+ *
5
+ * forja eval:agents --agent claude|codex [--case a,b] [--model m] [--budget-usd n]
6
+ * [--timeout s] [--keep] [--list] [--json]
7
+ *
8
+ * Custa: cada caso é uma sessão real do agente. Exit 0 = todos passaram, 2 = algum falhou,
9
+ * 1 = agente ausente, caso inexistente ou argumento inválido.
10
+ */
11
+ import fs from 'node:fs';
12
+ import path from 'node:path';
13
+ import { emitError, emitOk, emitRejected } from '../lib/cli-output.js';
14
+ import { ADAPTERS, appendHistory, compareRuns, loadCases, previousRun, runSuite } from '../lib/agent-evals.js';
15
+ import { asset, pkgRoot, script } from '../lib/paths.js';
16
+ import { getWorkspaceContextDir, getWorkspaceInfo } from '../lib/workspace.js';
17
+ const argv = process.argv.slice(2);
18
+ const json = argv.includes('--json');
19
+ const flag = (name) => { const i = argv.indexOf(name); return i >= 0 ? argv[i + 1] : undefined; };
20
+ const die = (msg, code = 'INVALID_ARGS') => {
21
+ if (json)
22
+ emitError(msg, { code });
23
+ console.error(msg);
24
+ process.exit(1);
25
+ };
26
+ const all = loadCases(asset('templates', 'evals', 'agents'));
27
+ if (argv.includes('--list')) {
28
+ if (json)
29
+ emitOk({ cases: all.map((c) => ({ id: c.id, title: c.title, checks: c.checks.length })) });
30
+ for (const c of all)
31
+ console.log(`${c.id.padEnd(20)} ${c.title} (${c.checks.length} checks)`);
32
+ process.exit(0);
33
+ }
34
+ // Sem padrão de propósito: rodar custa dinheiro, então o agente é sempre uma escolha explícita.
35
+ const agentName = flag('--agent') ?? die(`escolha o agente: --agent ${Object.keys(ADAPTERS).join('|')} (cada caso é uma sessão real e paga)`, 'MISSING_ARG');
36
+ const make = ADAPTERS[agentName];
37
+ if (!make)
38
+ die(`agente desconhecido: ${agentName} (suportados: ${Object.keys(ADAPTERS).join(', ')})`);
39
+ const adapter = make();
40
+ if (!adapter.version())
41
+ die(`${agentName} não está instalado ou não responde a --version`, 'AGENT_MISSING');
42
+ const wanted = flag('--case')?.split(',').map((s) => s.trim()).filter(Boolean);
43
+ const unknown = (wanted ?? []).filter((id) => !all.some((c) => c.id === id));
44
+ if (unknown.length)
45
+ die(`caso desconhecido: ${unknown.join(', ')} (veja forja eval:agents --list)`, 'NOT_FOUND');
46
+ const cases = wanted ? all.filter((c) => wanted.includes(c.id)) : all;
47
+ const budgetUsd = Number(flag('--budget-usd') ?? 1);
48
+ const timeoutS = Number(flag('--timeout') ?? 300);
49
+ if (!(budgetUsd > 0) || !(timeoutS > 0))
50
+ die('--budget-usd e --timeout precisam ser positivos');
51
+ const model = flag('--model');
52
+ const version = JSON.parse(fs.readFileSync(path.join(pkgRoot, 'package.json'), 'utf8')).version;
53
+ if (!json) {
54
+ console.log(`Avaliando ${agentName}${model ? ` (${model})` : ''} em ${cases.length} caso(s) — cada caso é uma sessão real do agente.`);
55
+ if (agentName === 'claude')
56
+ console.log(`Teto por caso: US$ ${budgetUsd.toFixed(2)} · timeout ${timeoutS} s\n`);
57
+ else
58
+ console.log(`Timeout por caso: ${timeoutS} s (o Codex não tem teto de custo por flag)\n`);
59
+ }
60
+ const line = (r) => {
61
+ const cost = r.costUsd != null ? ` · US$ ${r.costUsd.toFixed(3)}` : '';
62
+ console.log(`${r.pass ? '✓' : '✗'} ${r.id.padEnd(20)} ${(r.durationMs / 1000).toFixed(0)} s · ${r.commands} comando(s)${cost}`);
63
+ for (const k of r.checks)
64
+ if (!k.ok || !r.pass)
65
+ console.log(` ${k.ok ? '✓' : '✗'} ${k.desc} — ${k.detail}`);
66
+ if (r.error)
67
+ console.log(` ✗ agente: ${r.error}`);
68
+ if (!r.pass && r.answer)
69
+ console.log(` resposta: ${r.answer.replace(/\s+/g, ' ').slice(0, 200)}`);
70
+ };
71
+ const result = runSuite(cases, adapter, version, {
72
+ forjaBin: script('bin/forja'), model, budgetUsd, timeoutMs: timeoutS * 1000, keep: argv.includes('--keep'),
73
+ onCase: json ? undefined : (_c, r) => line(r),
74
+ });
75
+ const ws = getWorkspaceInfo();
76
+ const historyFile = ws.exists ? path.join(getWorkspaceContextDir(), 'agent-evals.jsonl') : null;
77
+ const prev = historyFile ? previousRun(historyFile, result.agent, result.model) : null;
78
+ const diff = compareRuns(prev, result);
79
+ if (historyFile)
80
+ appendHistory(historyFile, result);
81
+ if (json) {
82
+ const payload = { ...result, regressed: diff.regressed, fixed: diff.fixed, history: historyFile };
83
+ if (result.passed < result.cases.length)
84
+ emitRejected(payload);
85
+ emitOk(payload);
86
+ }
87
+ console.log(`\n${result.passed}/${result.cases.length} caso(s) passaram${result.costUsd != null ? ` · custo total US$ ${result.costUsd.toFixed(3)}` : ''}`);
88
+ if (prev) {
89
+ console.log(`Comparado com ${prev.ts.slice(0, 16).replace('T', ' ')} (Forja ${prev.forjaVersion}): ${prev.passed}/${prev.cases.length}`);
90
+ if (diff.regressed.length)
91
+ console.log(` ✗ passaram a falhar: ${diff.regressed.join(', ')}`);
92
+ if (diff.fixed.length)
93
+ console.log(` ✓ passaram a passar: ${diff.fixed.join(', ')}`);
94
+ }
95
+ console.log(historyFile ? `Histórico: ${historyFile}` : 'Sem workspace: o resultado não foi guardado (forja workspace:init).');
96
+ process.exit(result.passed === result.cases.length ? 0 : 2);
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,18 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * docs:gen — regenera docs/commands.md a partir do registry (SPEC-055).
4
+ *
5
+ * A referência completa de comandos é derivada, nunca escrita à mão: o registry é a fonte única e o
6
+ * check `commands-ref` do doctor compara o arquivo com o que este script produz. Rodar é idempotente.
7
+ */
8
+ import fs from 'node:fs';
9
+ import path from 'node:path';
10
+ import { fileURLToPath } from 'node:url';
11
+ import { COMMANDS } from '../lib/core/registry.js';
12
+ import { renderCommandsDoc, skillsCount } from '../lib/docs-reference.js';
13
+ const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
14
+ const TARGET = path.join(ROOT, 'docs/commands.md');
15
+ const skills = skillsCount(fs, path.join(ROOT, 'templates', 'project', 'skills'));
16
+ const doc = renderCommandsDoc(COMMANDS, skills);
17
+ fs.writeFileSync(TARGET, doc);
18
+ console.log(`docs/commands.md gerado: ${Object.keys(COMMANDS).length} comandos em ${new Set(Object.values(COMMANDS).map((c) => c.domain)).size} domínios, ${skills} skills.`);
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Hook Stop / PreCompact — grava o checkpoint da sessão em memory/60-runs/sessions/ (SPEC-052, ADR-0091).
4
+ *
5
+ * stdin: `{ session_id, transcript_path, cwd, hook_event_name }` (Claude Code). Nunca derruba a
6
+ * sessão: qualquer falha sai com 0 e sem saída. Não escreve em stdout — no Stop, um JSON com
7
+ * `decision` bloquearia o fim do turno.
8
+ */
9
+ export {};
@@ -0,0 +1,20 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Hook Stop / PreCompact — grava o checkpoint da sessão em memory/60-runs/sessions/ (SPEC-052, ADR-0091).
4
+ *
5
+ * stdin: `{ session_id, transcript_path, cwd, hook_event_name }` (Claude Code). Nunca derruba a
6
+ * sessão: qualquer falha sai com 0 e sem saída. Não escreve em stdout — no Stop, um JSON com
7
+ * `decision` bloquearia o fim do turno.
8
+ */
9
+ import fs from 'node:fs';
10
+ import path from 'node:path';
11
+ import { writeCheckpoint } from '../lib/session-memory.js';
12
+ try {
13
+ const input = process.stdin.isTTY ? {} : JSON.parse(fs.readFileSync(0, 'utf8') || '{}');
14
+ const root = path.resolve(process.env.CLAUDE_PROJECT_DIR || input.cwd || process.cwd());
15
+ if (typeof input.session_id === 'string' && typeof input.transcript_path === 'string' && fs.existsSync(input.transcript_path)) {
16
+ writeCheckpoint(root, input.transcript_path, input.session_id, String(input.hook_event_name || 'Stop'));
17
+ }
18
+ }
19
+ catch { /* ADR-0091: o hook nunca derruba a sessão */ }
20
+ process.exit(0);
@@ -22,6 +22,7 @@ import { listSpecs } from '../lib/specs-index.js';
22
22
  import { openHandoffs } from '../lib/handoffs-index.js';
23
23
  import { getWorkspaceRoot, isInsideFrameworkRepo, currentProjectName } from '../lib/workspace.js';
24
24
  import { pkgRoot } from '../lib/paths.js';
25
+ import { findCheckpoint, latestCheckpoint, summarizeCheckpoint } from '../lib/session-memory.js';
25
26
  const __filename = fileURLToPath(import.meta.url);
26
27
  const __dirname = path.dirname(__filename);
27
28
  const frameworkRoot = pkgRoot;
@@ -31,6 +32,37 @@ const root = isInsideFrameworkRepo(cwd)
31
32
  : (fs.existsSync(path.join(cwd, 'specs')) || fs.existsSync(path.join(cwd, 'package.json')))
32
33
  ? cwd
33
34
  : getWorkspaceRoot();
35
+ /** stdin do Claude Code: `{ session_id, source: startup|resume|clear|compact }`. Ausente → {}. */
36
+ function hookInput() {
37
+ if (process.stdin.isTTY)
38
+ return {}; // rodado à mão no terminal: não espera stdin
39
+ try {
40
+ return JSON.parse(fs.readFileSync(0, 'utf8') || '{}');
41
+ }
42
+ catch {
43
+ return {};
44
+ }
45
+ }
46
+ const CHECKPOINT_CAP = 3000;
47
+ /** SPEC-052: depois de compactar, o checkpoint da própria sessão; senão, onde a última parou. */
48
+ function sessionMemory(input) {
49
+ try {
50
+ if (input.source === 'compact' && input.session_id) {
51
+ const file = findCheckpoint(root, input.session_id);
52
+ if (!file)
53
+ return [];
54
+ const text = fs.readFileSync(file, 'utf8').replace(/<!--[\s\S]*?-->\n?/g, '').trim();
55
+ return ['', `Checkpoint desta sessão antes da compactação (${path.relative(root, file)}):`, text.slice(0, CHECKPOINT_CAP)];
56
+ }
57
+ if (input.source === 'clear')
58
+ return [];
59
+ const last = latestCheckpoint(root, input.session_id);
60
+ return last ? ['', `Última sessão: ${summarizeCheckpoint(last)} (${path.relative(root, last)})`] : [];
61
+ }
62
+ catch {
63
+ return [];
64
+ }
65
+ }
34
66
  /**
35
67
  * Nunca lança e nunca trava a sessão: o hook reporta, o `tools:doctor` é que é gate. Se a própria
36
68
  * lib de health não carregar, seguimos com o resto do briefing em vez de abortar (ADR-0021).
@@ -44,6 +76,7 @@ async function coreHealth() {
44
76
  }
45
77
  }
46
78
  (async function main() {
79
+ const input = hookInput();
47
80
  const specs = listSpecs(root);
48
81
  const health = await coreHealth();
49
82
  const problemas = health.filter((c) => c.status === 'fail' || c.status === 'warn');
@@ -79,6 +112,7 @@ async function coreHealth() {
79
112
  for (const h of handoffs)
80
113
  lines.push(` - #${h.id} ${h.from} → ${h.to} (${h.intent}) ${h.slug || ''}`);
81
114
  }
115
+ lines.push(...sessionMemory(input));
82
116
  lines.push('\nFluxo SDD: `forja spec:new|spec:plan|spec:tasks|spec:check <slug>` · próximo passo: `forja next`');
83
117
  lines.push('Handoff: `forja hermes:handoff \'<json ADR-0005>\'`');
84
118
  lines.push('</framework-status>');
@@ -0,0 +1,10 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * spec:trace — critérios de aceite × testes que os citam (SPEC-053, ADR-0092).
4
+ *
5
+ * forja spec:trace [slug] [--strict] [--json]
6
+ *
7
+ * Sem `--strict` só informa (exit 0). Com `--strict`, spec approved/implementing/done com critério
8
+ * sem teste ou citação órfã → exit 2 (`rejected`, ADR-0082).
9
+ */
10
+ export {};
@@ -0,0 +1,73 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * spec:trace — critérios de aceite × testes que os citam (SPEC-053, ADR-0092).
4
+ *
5
+ * forja spec:trace [slug] [--strict] [--json]
6
+ *
7
+ * Sem `--strict` só informa (exit 0). Com `--strict`, spec approved/implementing/done com critério
8
+ * sem teste ou citação órfã → exit 2 (`rejected`, ADR-0082).
9
+ */
10
+ import path from 'node:path';
11
+ import { emitError, emitOk, emitRejected } from '../lib/cli-output.js';
12
+ import { GATED_STATUSES, strictFailures, traceSpecs } from '../lib/spec-trace.js';
13
+ const args = process.argv.slice(2);
14
+ const json = args.includes('--json');
15
+ const strict = args.includes('--strict');
16
+ const slug = args.find((a) => !a.startsWith('--'));
17
+ const root = path.resolve(process.cwd());
18
+ const report = traceSpecs(root);
19
+ let specs = report.specs;
20
+ if (slug) {
21
+ specs = specs.filter((s) => s.slug === slug || s.specId === slug.toUpperCase());
22
+ if (!specs.length) {
23
+ if (json)
24
+ emitError(`spec não encontrada: ${slug}`, { code: 'NOT_FOUND' });
25
+ console.error(`spec não encontrada: ${slug} (veja specs/)`);
26
+ process.exit(1);
27
+ }
28
+ }
29
+ const withCriteria = specs.filter((s) => s.criteria.length);
30
+ const failures = strict ? strictFailures(withCriteria) : [];
31
+ const total = withCriteria.reduce((n, s) => n + s.criteria.length, 0);
32
+ const covered = withCriteria.reduce((n, s) => n + s.criteria.length - s.uncovered.length, 0);
33
+ const ambiguous = slug ? [] : report.ambiguous;
34
+ if (json) {
35
+ const payload = {
36
+ totals: { specs: withCriteria.length, criteria: total, covered, testFiles: report.testFiles },
37
+ specs: withCriteria,
38
+ ambiguous,
39
+ ...(strict ? { failing: failures.map((s) => s.slug) } : {}),
40
+ };
41
+ if (failures.length)
42
+ emitRejected(payload);
43
+ emitOk(payload);
44
+ }
45
+ const where = (r) => `${r.file}:${r.line}`;
46
+ function print(s) {
47
+ const n = s.criteria.length - s.uncovered.length;
48
+ const mark = n === s.criteria.length && !s.orphans.length ? '✓' : GATED(s) ? '✗' : '·';
49
+ console.log(`${mark} ${s.specId ?? '—'} ${s.slug} [${s.status}] — ${n}/${s.criteria.length} critérios com teste`);
50
+ for (const c of s.criteria) {
51
+ if (c.tests.length)
52
+ console.log(` ✓ ${c.id} ${c.tests.slice(0, 3).map(where).join(', ')}${c.tests.length > 3 ? ` (+${c.tests.length - 3})` : ''}`);
53
+ else
54
+ console.log(` ✗ ${c.id} sem teste — ${c.text.slice(0, 80)}`);
55
+ }
56
+ for (const o of s.orphans)
57
+ console.log(` ⚠ ${o.ac} não existe na spec, mas ${where(o.ref)} o cita`);
58
+ }
59
+ function GATED(s) { return GATED_STATUSES.has(s.status); }
60
+ if (!withCriteria.length) {
61
+ console.log(slug ? `${slug}: a spec não tem critérios AC-N.` : 'Nenhuma spec com critérios AC-N em specs/.');
62
+ process.exit(0);
63
+ }
64
+ for (const s of withCriteria)
65
+ print(s);
66
+ console.log(`\n${covered}/${total} critérios com teste em ${withCriteria.length} spec(s) · ${report.testFiles} arquivo(s) de teste lidos`);
67
+ if (ambiguous.length)
68
+ console.log(`${ambiguous.length} citação(ões) AC-N sem spec identificável (motivo em --json): qualifique com SPEC-NNN AC-N.`);
69
+ console.log('Para ligar um teste: cite `SPEC-NNN AC-N` no nome ou num comentário do teste.');
70
+ if (strict && failures.length) {
71
+ console.log(`\n✗ --strict: ${failures.length} spec(s) com "pronto" prometido e lacuna de rastreio: ${failures.map((s) => s.slug).join(', ')}`);
72
+ process.exit(2);
73
+ }
@@ -48,6 +48,15 @@ CREATE VIRTUAL TABLE IF NOT EXISTS search_idx USING fts5(
48
48
  content,
49
49
  tokenize='porter'
50
50
  );
51
+
52
+ -- Uma linha por execução de sync. Existe porque um sync incremental que pula tudo não escreve byte
53
+ -- nenhum no banco, e o doctor compara o mtime do banco com o de memory/ (check memory-fresh): sem
54
+ -- ela, o índice em dia pareceria velho. De quebra carrega os contadores da execução.
55
+ CREATE TABLE IF NOT EXISTS sync_meta (
56
+ name TEXT PRIMARY KEY,
57
+ value TEXT NOT NULL,
58
+ updated_at TEXT NOT NULL
59
+ );
51
60
  `;
52
61
  function log(msg, level = 'info') {
53
62
  const prefix = { info: 'INFO', success: 'OK', warn: 'WARN', error: 'ERROR' }[level] || 'INFO';
@@ -95,6 +104,8 @@ const upsertProject = db.prepare('INSERT INTO projects (name, path, created_at)
95
104
  // um documento sob o node_id de outro (ADR-0021).
96
105
  const upsertNode = db.prepare('INSERT INTO memory_nodes (project_id, path, kind, title, content, content_hash, updated_at) VALUES (?, ?, ?, ?, ?, ?, ?) ON CONFLICT(path) DO UPDATE SET project_id=excluded.project_id, kind=excluded.kind, title=excluded.title, content=excluded.content, content_hash=excluded.content_hash, updated_at=excluded.updated_at RETURNING id');
97
106
  const getProjectId = db.prepare('SELECT id FROM projects WHERE name = ?');
107
+ const getStoredNode = db.prepare('SELECT content_hash, project_id FROM memory_nodes WHERE path = ?');
108
+ const upsertSyncMeta = db.prepare('INSERT INTO sync_meta (name, value, updated_at) VALUES (?, ?, ?) ON CONFLICT(name) DO UPDATE SET value=excluded.value, updated_at=excluded.updated_at');
98
109
  const deleteFts = db.prepare('DELETE FROM search_idx WHERE node_id = ?');
99
110
  const insertFts = db.prepare('INSERT INTO search_idx (node_id, title, content) VALUES (?, ?, ?)');
100
111
  const purgeFtsOrphans = db.prepare('DELETE FROM search_idx WHERE node_id NOT IN (SELECT id FROM memory_nodes)');
@@ -230,22 +241,70 @@ function syncAssetCatalog() {
230
241
  }
231
242
  log(`Asset catalog sincronizado: ${assets.length}`, 'info');
232
243
  }
244
+ /** Contadores da execução: o log diz quanto do sync foi trabalho de verdade e quanto foi pulado. */
245
+ const tally = { indexados: 0, pulados: 0, falhas: 0 };
246
+ /**
247
+ * `abs` está mesmo dentro de `base`? `startsWith('..')` não basta: em Windows, `path.relative()` entre
248
+ * unidades diferentes devolve o caminho **absoluto** de `abs` — que não começa por `..` e seria lido
249
+ * como "está dentro".
250
+ */
251
+ function inside(base, abs) {
252
+ const rel = path.relative(base, abs);
253
+ return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel);
254
+ }
255
+ const realCache = new Map();
256
+ function realOf(p) {
257
+ let v = realCache.get(p);
258
+ if (v === undefined) {
259
+ try {
260
+ v = fs.realpathSync(p);
261
+ }
262
+ catch {
263
+ v = p;
264
+ }
265
+ realCache.set(p, v);
266
+ }
267
+ return v;
268
+ }
269
+ /**
270
+ * Caminho do nó: relativo à raiz cujo conteúdo ele é, na mesma forma em qualquer máquina. Dois
271
+ * atalhos unix-cêntricos gravavam o mesmo arquivo com duas identidades no Windows — `relative()`
272
+ * entre unidade diferente devolve caminho absoluto, e `os.tmpdir()` chega como nome 8.3
273
+ * (`RUNNER~1`) enquanto o walk devolve a forma longa, o que faz o `relative()` subir a árvore toda e
274
+ * cair na raiz errada. Se a forma direta não contém o arquivo, tenta a canônica dos dois lados.
275
+ */
276
+ function nodePathOf(abs) {
277
+ for (const base of [contentRoot, operationRoot]) {
278
+ if (inside(base, abs))
279
+ return path.relative(base, abs);
280
+ if (inside(realOf(base), realOf(abs)))
281
+ return path.relative(realOf(base), realOf(abs));
282
+ }
283
+ return path.relative(contentRoot, abs);
284
+ }
233
285
  function syncFiles(files, projectId = null) {
234
286
  for (const abs of files) {
235
- let rel = path.relative(contentRoot, abs);
236
- if (rel.startsWith('..')) {
237
- rel = path.relative(operationRoot, abs);
238
- }
287
+ const rel = nodePathOf(abs);
239
288
  const raw = fs.readFileSync(abs, 'utf8');
240
289
  const hash = crypto.createHash('sha256').update(raw).digest('hex');
290
+ // O `content_hash` sempre foi gravado e nunca foi comparado: todo sync re-upsertava e re-indexava
291
+ // os 289 nós do pacote. Pular o inalterado é seguro — a linha e o trecho FTS continuam lá — e o
292
+ // project_id entra na comparação porque o mesmo path pode mudar de dono (global ↔ projeto).
293
+ const stored = getStoredNode.get(rel);
294
+ if (stored && stored.content_hash === hash && stored.project_id === projectId) {
295
+ tally.pulados++;
296
+ continue;
297
+ }
241
298
  const titleMatch = raw.match(/^#\s+(.+)$/m);
242
299
  const title = titleMatch ? titleMatch[1].trim() : path.basename(rel, '.md');
243
300
  try {
244
301
  const { id: nodeId } = upsertNode.get(projectId, rel, getKind(rel), title, raw, hash, now);
245
302
  deleteFts.run(nodeId);
246
303
  insertFts.run(nodeId, title, raw);
304
+ tally.indexados++;
247
305
  }
248
306
  catch (e) {
307
+ tally.falhas++;
249
308
  log(`Erro sincronizando ${rel}: ${e.message}`, 'error');
250
309
  }
251
310
  }
@@ -309,5 +368,11 @@ if (mode === 'studio' && fs.existsSync(workspaceProjectsMemoryDir)) {
309
368
  const orphans = purgeFtsOrphans.run().changes;
310
369
  if (orphans)
311
370
  log(`Índice FTS: ${orphans} linhas órfãs removidas`, 'info');
371
+ // Marca a execução mesmo quando tudo foi pulado — ver o comentário de `sync_meta` no schema.
372
+ upsertSyncMeta.run('last_sync', JSON.stringify({ at: now, ...tally }), now);
373
+ log(`Nós: ${tally.indexados} indexados · ${tally.pulados} inalterados (pulados) · ${tally.falhas} falhas`, 'info');
374
+ // O banco abre em WAL: sem checkpoint, uma escrita pequena fica no -wal e o mtime do .db não muda —
375
+ // o arquivo principal passa a mentir sobre a idade do índice (e vale menos sozinho, sem o -wal).
376
+ db.pragma('wal_checkpoint(TRUNCATE)');
312
377
  db.close();
313
378
  log('Sincronização Universal Concluída!', 'success');
@@ -13,8 +13,40 @@
13
13
  * Estimar tokens (1KB ≈ 250 tokens, aproximação)
14
14
  */
15
15
  declare function estimateTokens(content: any): number;
16
+ /**
17
+ * Formatar bytes em legível
18
+ */
19
+ declare function formatBytes(bytes: any): string;
20
+ declare function walkMarkdown(dir: any, out?: string[]): string[];
21
+ /**
22
+ * O projeto de referência sai do banco, não de um nome chutado. O benchmark media
23
+ * 'benchmark-project', que não existe em lugar nenhum: domain e task voltavam só com os nós globais e
24
+ * o relatório anunciava ~99% de "economia" por não ter injetado quase nada (achado da SPEC-057 —
25
+ * medição que não mede é pior que medição nenhuma, porque decide no escuro com ar de número).
26
+ */
27
+ declare function referenceProject(dbPath: string): {
28
+ name: string;
29
+ nodes: number;
30
+ } | null;
31
+ /** Nós injetados no pacote. Comparado com o do modo global, diz se o projeto contribuiu com algo. */
32
+ declare function nodesIn(pack: string): number;
33
+ /**
34
+ * Termo do modo task: um que existe no projeto (o primeiro domínio indexado, senão o primeiro slug de
35
+ * spec). O termo chutado em inglês que estava aqui antes — 'architecture implementation' — não casa
36
+ * com memória em pt-BR, e o modo task media um pacote sem nenhum nó do projeto.
37
+ */
38
+ declare function taskKeyword(dbPath: string, project: string): string;
39
+ interface RefRow {
40
+ keyword: string;
41
+ nodes: number;
42
+ trecho: number;
43
+ integral: number;
44
+ corte: number;
45
+ }
46
+ declare function referenceScenario(): RefRow[];
47
+ declare function referenceScenarioReport(rows: RefRow[] | null): void;
16
48
  /**
17
49
  * Executar benchmark
18
50
  */
19
51
  declare function benchmark(): Promise<void>;
20
- export { benchmark, estimateTokens };
52
+ export { benchmark, estimateTokens, formatBytes, walkMarkdown, nodesIn, referenceProject, referenceScenario, referenceScenarioReport, taskKeyword, };