forjajs 2.0.3 → 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.claude/agents/release-auditor.md +19 -10
- package/AGENTS.md +1 -1
- package/CHANGELOG.md +80 -0
- package/DOC-MAP.md +9 -0
- package/README.md +85 -5
- package/README.pt-BR.md +34 -5
- package/dist/apps/dashboard/app/api/forja/[...path]/route.js +8 -1
- package/dist/apps/dashboard/app/api/forja/guard.d.ts +24 -0
- package/dist/apps/dashboard/app/api/forja/guard.js +63 -0
- package/dist/apps/server/src/forja-nest.module.js +9 -4
- package/dist/apps/server/src/main.js +10 -1
- package/dist/bin/forja.js +14 -2
- package/dist/lib/code-context.js +6 -0
- package/dist/lib/core/architecture-gate.d.ts +20 -0
- package/dist/lib/core/architecture-gate.js +60 -0
- package/dist/lib/core/doc-graph.js +6 -4
- package/dist/lib/core/drift-gate.d.ts +18 -0
- package/dist/lib/core/drift-gate.js +55 -0
- package/dist/lib/core/gates.d.ts +9 -2
- package/dist/lib/core/gates.js +13 -2
- package/dist/lib/core/health.js +15 -0
- package/dist/lib/core/incident-search.d.ts +19 -0
- package/dist/lib/core/incident-search.js +32 -0
- package/dist/lib/core/model-pricing.d.ts +31 -0
- package/dist/lib/core/model-pricing.js +74 -0
- package/dist/lib/core/registry.d.ts +248 -0
- package/dist/lib/core/registry.js +249 -0
- package/dist/lib/core/release.d.ts +247 -0
- package/dist/lib/core/release.js +5 -1
- package/dist/lib/core/risk-collect.d.ts +19 -0
- package/dist/lib/core/risk-collect.js +173 -0
- package/dist/lib/drift-sentinel.d.ts +59 -0
- package/dist/lib/drift-sentinel.js +126 -0
- package/dist/lib/generators/memory-generator.js +8 -6
- package/dist/lib/generators/nest-generator.js +24 -10
- package/dist/lib/project-upgrade.js +1 -1
- package/dist/lib/workspace.d.ts +7 -0
- package/dist/lib/workspace.js +34 -5
- package/dist/packages/adapter-git/src/index.d.ts +1 -1
- package/dist/packages/adapter-git/src/index.js +11 -6
- package/dist/packages/adapter-nest/src/index.d.ts +19 -0
- package/dist/packages/adapter-nest/src/index.js +26 -1
- package/dist/packages/adapter-sqlite/src/index.d.ts +27 -1
- package/dist/packages/adapter-sqlite/src/index.js +49 -0
- package/dist/packages/contracts/src/index.d.ts +33 -0
- package/dist/packages/contracts/src/index.js +13 -0
- package/dist/packages/core/src/index.d.ts +12 -0
- package/dist/packages/core/src/index.js +29 -0
- package/dist/packages/engineering/architecture/src/index.d.ts +76 -0
- package/dist/packages/engineering/architecture/src/index.js +131 -0
- package/dist/packages/engineering/evidence/src/index.d.ts +41 -0
- package/dist/packages/engineering/evidence/src/index.js +31 -0
- package/dist/packages/engineering/identity/src/index.d.ts +57 -0
- package/dist/packages/engineering/identity/src/index.js +88 -0
- package/dist/packages/engineering/monitoring/src/index.d.ts +37 -0
- package/dist/packages/engineering/monitoring/src/index.js +40 -0
- package/dist/packages/engineering/provenance/src/index.d.ts +25 -0
- package/dist/packages/engineering/provenance/src/index.js +21 -0
- package/dist/packages/engineering/risk/src/index.d.ts +89 -0
- package/dist/packages/engineering/risk/src/index.js +120 -0
- package/dist/packages/graph/src/index.d.ts +23 -1
- package/dist/packages/graph/src/index.js +88 -15
- package/dist/packages/llm/src/index.d.ts +43 -0
- package/dist/packages/llm/src/index.js +131 -0
- package/dist/packages/mcp/src/index.js +27 -8
- package/dist/packages/orchestration/src/index.d.ts +11 -1
- package/dist/packages/orchestration/src/index.js +34 -7
- package/dist/packages/policy/src/index.d.ts +40 -0
- package/dist/packages/policy/src/index.js +39 -4
- package/dist/packages/runtime/src/index.js +3 -0
- package/dist/packages/sandbox/src/index.d.ts +47 -0
- package/dist/packages/sandbox/src/index.js +59 -0
- package/dist/packages/validator/src/index.d.ts +8 -0
- package/dist/packages/validator/src/index.js +21 -6
- package/dist/scripts/adr.d.ts +17 -0
- package/dist/scripts/adr.js +152 -0
- package/dist/scripts/agent-harness.js +14 -4
- package/dist/scripts/agent.d.ts +27 -0
- package/dist/scripts/agent.js +249 -0
- package/dist/scripts/architecture.d.ts +16 -0
- package/dist/scripts/architecture.js +186 -0
- package/dist/scripts/cost-economy.d.ts +2 -0
- package/dist/scripts/cost-economy.js +79 -0
- package/dist/scripts/demo-autonomy.js +15 -8
- package/dist/scripts/demo-workspace.d.ts +6 -0
- package/dist/scripts/demo-workspace.js +101 -0
- package/dist/scripts/drift-check.d.ts +17 -0
- package/dist/scripts/drift-check.js +63 -0
- package/dist/scripts/engineer.d.ts +20 -0
- package/dist/scripts/engineer.js +208 -0
- package/dist/scripts/evidence.d.ts +12 -0
- package/dist/scripts/evidence.js +55 -0
- package/dist/scripts/gates.d.ts +6 -2
- package/dist/scripts/gates.js +14 -4
- package/dist/scripts/incident.d.ts +19 -0
- package/dist/scripts/incident.js +103 -0
- package/dist/scripts/llm-fit.js +160 -0
- package/dist/scripts/provenance.d.ts +14 -0
- package/dist/scripts/provenance.js +114 -0
- package/dist/scripts/risk.d.ts +15 -0
- package/dist/scripts/risk.js +81 -0
- package/dist/scripts/simulate.d.ts +20 -0
- package/dist/scripts/simulate.js +150 -0
- package/dist/scripts/sync-universal-memory.js +19 -6
- package/docs/architecture/FORJA-3-ENGINEERING-INTELLIGENCE-ARCHITECTURE.md +442 -0
- package/docs/llm-fit-loop.md +41 -0
- package/docs/modos-de-operacao.md +52 -0
- package/docs/produto/factsheet-marketing.md +151 -0
- package/docs/produto/roteiro-demo.md +47 -0
- package/memory/40-delivery/current-sprint.md +3 -6
- package/memory/90-decisions/0074-llm-fit-loop-cli-adapters.md +51 -0
- package/memory/90-decisions/0075-workspace-demo-isolado.md +43 -0
- package/memory/90-decisions/0076-modos-embedded-e-studio.md +43 -0
- package/memory/90-decisions/0077-cost-aware-autonomy-budget.md +95 -0
- package/memory/90-decisions/0078-forjajs-3-engineering-control-plane.md +116 -0
- package/memory/90-decisions/0079-autonomous-maintenance-readiness.md +102 -0
- package/package.json +9 -2
- package/specs/agent-identity-reputation/plan.md +133 -0
- package/specs/agent-identity-reputation/spec.md +125 -0
- package/specs/agent-identity-reputation/tasks.md +51 -0
- package/specs/agent-runtime-monitoring/plan.md +78 -0
- package/specs/agent-runtime-monitoring/spec.md +92 -0
- package/specs/agent-runtime-monitoring/tasks.md +39 -0
- package/specs/ai-code-provenance/plan.md +71 -0
- package/specs/ai-code-provenance/spec.md +97 -0
- package/specs/ai-code-provenance/tasks.md +39 -0
- package/specs/architecture-constitution/plan.md +110 -0
- package/specs/architecture-constitution/spec.md +114 -0
- package/specs/architecture-constitution/tasks.md +58 -0
- package/specs/change-risk-engine/plan.md +130 -0
- package/specs/change-risk-engine/spec.md +119 -0
- package/specs/change-risk-engine/tasks.md +72 -0
- package/specs/cost-aware-autonomy-budget/spec.md +102 -0
- package/specs/drift-sentinel/spec.md +117 -0
- package/specs/engineer-facade-extension/plan.md +71 -0
- package/specs/engineer-facade-extension/spec.md +98 -0
- package/specs/engineer-facade-extension/tasks.md +36 -0
- package/specs/engineering-evidence-ledger/plan.md +121 -0
- package/specs/engineering-evidence-ledger/spec.md +90 -0
- package/specs/engineering-evidence-ledger/tasks.md +54 -0
- package/specs/engineering-graph-extensions/plan.md +92 -0
- package/specs/engineering-graph-extensions/spec.md +101 -0
- package/specs/engineering-graph-extensions/tasks.md +60 -0
- package/specs/engineering-intelligence/spec.md +177 -0
- package/specs/learning-loop-incidents/plan.md +59 -0
- package/specs/learning-loop-incidents/spec.md +93 -0
- package/specs/learning-loop-incidents/tasks.md +36 -0
- package/specs/predictive-change-simulation/plan.md +109 -0
- package/specs/predictive-change-simulation/spec.md +107 -0
- package/specs/predictive-change-simulation/tasks.md +41 -0
- package/specs/release-auditor-health/plan.md +88 -0
- package/specs/release-auditor-health/spec.md +82 -0
- package/specs/release-auditor-health/tasks.md +72 -0
- package/specs/smart-agent-routing/plan.md +55 -0
- package/specs/smart-agent-routing/spec.md +85 -0
- package/specs/smart-agent-routing/tasks.md +26 -0
- package/dist/scripts/server-persistence-probe.d.ts +0 -1
- package/dist/scripts/server-persistence-probe.js +0 -52
- package/dist/scripts/server-persistence-probe.mjs +0 -52
- /package/dist/scripts/{server-persistence-probe.d.mts → llm-fit.d.ts} +0 -0
package/dist/lib/code-context.js
CHANGED
|
@@ -72,6 +72,12 @@ function moduleFiles(projectRoot, domain, env) {
|
|
|
72
72
|
* a exploração. Com `includeCode`, anexa o código da fatia — o que se lê ao *editar*.
|
|
73
73
|
*/
|
|
74
74
|
export function buildContextPack({ projectRoot, domain, includeCode = false }, env = defaultFsEnv) {
|
|
75
|
+
// Allowlist against the domains the project actually declares (memory/30-domains/*) — rejects early
|
|
76
|
+
// rather than sanitizing, since it's information this function already has and a traversal payload
|
|
77
|
+
// (e.g. "../../etc") can never literally equal one of those directory names.
|
|
78
|
+
if (!domainsOf(projectRoot, env).includes(domain)) {
|
|
79
|
+
return { domain, found: false, mapPath: null, map: null, mapTokens: 0, code: [], codeTokens: 0, totalTokens: 0 };
|
|
80
|
+
}
|
|
75
81
|
const mapPath = path.join(projectRoot, 'memory', '30-domains', domain, 'context.md');
|
|
76
82
|
let map = null;
|
|
77
83
|
try {
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* lib/core/architecture-gate.ts — ponte opt-in entre `architecture:check` (SPEC-033) e `check:all`
|
|
3
|
+
* (AC-7).
|
|
4
|
+
*
|
|
5
|
+
* Mesmo padrão de `lib/core/drift-gate.ts`: chama o comando real via subprocess em vez de
|
|
6
|
+
* reimportar os internals, e traduz o resultado num `Result` do runner de gates. `architecture:check`
|
|
7
|
+
* reindexa o workspace inteiro (mesmo custo de `drift:check`/`graph:sync`) — por isso opt-in
|
|
8
|
+
* (`--with-architecture`), não o comportamento padrão de `check:all`.
|
|
9
|
+
*
|
|
10
|
+
* `severity: 'critical'` on a violation (not `'warn'` like the drift-gate — the gate runner's own
|
|
11
|
+
* `Severity` type is only `'critical' | 'warn'`, a coarser vocabulary than `ArchitectureSeverity`):
|
|
12
|
+
* a violation only exists because a rule reached `active` — either the deterministic parser had
|
|
13
|
+
* confidence 1, or a human explicitly ran `architecture:approve`. Unlike drift (which signals
|
|
14
|
+
* something for review, no prior judgment of right/wrong), an `active` rule is by definition a
|
|
15
|
+
* decision someone already confirmed should be respected — violating it is a real failure, not an
|
|
16
|
+
* invitation to review, so (unlike drift) it's allowed to escalate `check:all`'s verdict to `fail`.
|
|
17
|
+
*/
|
|
18
|
+
import type { Result } from './checks.ts';
|
|
19
|
+
/** Roda `architecture:check` num subprocesso e traduz o resultado num `Result` de gate. */
|
|
20
|
+
export declare function runArchitectureGate(): Promise<Result[]>;
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* lib/core/architecture-gate.ts — ponte opt-in entre `architecture:check` (SPEC-033) e `check:all`
|
|
3
|
+
* (AC-7).
|
|
4
|
+
*
|
|
5
|
+
* Mesmo padrão de `lib/core/drift-gate.ts`: chama o comando real via subprocess em vez de
|
|
6
|
+
* reimportar os internals, e traduz o resultado num `Result` do runner de gates. `architecture:check`
|
|
7
|
+
* reindexa o workspace inteiro (mesmo custo de `drift:check`/`graph:sync`) — por isso opt-in
|
|
8
|
+
* (`--with-architecture`), não o comportamento padrão de `check:all`.
|
|
9
|
+
*
|
|
10
|
+
* `severity: 'critical'` on a violation (not `'warn'` like the drift-gate — the gate runner's own
|
|
11
|
+
* `Severity` type is only `'critical' | 'warn'`, a coarser vocabulary than `ArchitectureSeverity`):
|
|
12
|
+
* a violation only exists because a rule reached `active` — either the deterministic parser had
|
|
13
|
+
* confidence 1, or a human explicitly ran `architecture:approve`. Unlike drift (which signals
|
|
14
|
+
* something for review, no prior judgment of right/wrong), an `active` rule is by definition a
|
|
15
|
+
* decision someone already confirmed should be respected — violating it is a real failure, not an
|
|
16
|
+
* invitation to review, so (unlike drift) it's allowed to escalate `check:all`'s verdict to `fail`.
|
|
17
|
+
*/
|
|
18
|
+
import { spawnSync } from 'node:child_process';
|
|
19
|
+
import path from 'node:path';
|
|
20
|
+
import { fileURLToPath } from 'node:url';
|
|
21
|
+
import { resolveScript } from "./registry.js";
|
|
22
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
23
|
+
const repoRoot = path.resolve(path.dirname(__filename), '..', '..');
|
|
24
|
+
const ID = 'architecture-check';
|
|
25
|
+
const TITLE = 'architecture:check — o código respeita a Constitution compilada (SPEC-033, opt-in)';
|
|
26
|
+
/** Cada violação imprime sua própria linha de severidade (ver cmdCheck em scripts/architecture.ts)
|
|
27
|
+
* — contar essas linhas é mais direto que reanalisar o relatório inteiro aqui. */
|
|
28
|
+
function violationCountFrom(stdout) {
|
|
29
|
+
return stdout.split('\n').filter((line) => /^(INFO|LOW|MEDIUM|HIGH|CRITICAL)$/.test(line.trim())).length;
|
|
30
|
+
}
|
|
31
|
+
/** Roda `architecture:check` num subprocesso e traduz o resultado num `Result` de gate. */
|
|
32
|
+
export async function runArchitectureGate() {
|
|
33
|
+
const script = resolveScript(repoRoot, 'scripts/architecture.ts');
|
|
34
|
+
const result = spawnSync('node', [script, 'check'], { cwd: process.cwd(), encoding: 'utf8' });
|
|
35
|
+
const stdout = result.stdout ?? '';
|
|
36
|
+
if (result.error !== undefined || (result.status !== 0 && result.status !== 1)) {
|
|
37
|
+
return [{
|
|
38
|
+
id: ID,
|
|
39
|
+
title: TITLE,
|
|
40
|
+
severity: 'critical',
|
|
41
|
+
status: 'fail',
|
|
42
|
+
detail: `architecture:check não rodou: ${result.stderr || result.error?.message || `exit ${result.status}`}`,
|
|
43
|
+
fix: 'rode `forja architecture:check` diretamente para depurar; se nunca compilado, rode `forja architecture:compile` primeiro',
|
|
44
|
+
}];
|
|
45
|
+
}
|
|
46
|
+
if (stdout.includes('Nenhuma regra compilada')) {
|
|
47
|
+
return [{ id: ID, title: TITLE, severity: 'critical', status: 'warn', detail: 'nenhuma Constitution compilada ainda — rode `forja architecture:compile`', fix: '`forja architecture:compile`' }];
|
|
48
|
+
}
|
|
49
|
+
if (result.status === 1) {
|
|
50
|
+
return [{
|
|
51
|
+
id: ID,
|
|
52
|
+
title: TITLE,
|
|
53
|
+
severity: 'critical',
|
|
54
|
+
status: 'fail',
|
|
55
|
+
detail: `${violationCountFrom(stdout)} violação(ões) de arquitetura encontrada(s)`,
|
|
56
|
+
fix: '`forja architecture:check` para o relatório completo, com remediação sugerida por violação',
|
|
57
|
+
}];
|
|
58
|
+
}
|
|
59
|
+
return [{ id: ID, title: TITLE, severity: 'critical', status: 'ok', detail: 'código em conformidade com toda regra active da Constitution', fix: null }];
|
|
60
|
+
}
|
|
@@ -13,6 +13,8 @@
|
|
|
13
13
|
*/
|
|
14
14
|
import fs from 'node:fs';
|
|
15
15
|
import path from 'node:path';
|
|
16
|
+
import { fileURLToPath } from 'node:url';
|
|
17
|
+
function portablePath(value) { return value.replaceAll(path.sep, '/'); }
|
|
16
18
|
/**
|
|
17
19
|
* Superfícies de instrução. Escaneia o que orienta o agente **agora** — não o histórico.
|
|
18
20
|
*
|
|
@@ -81,7 +83,7 @@ export function docFiles(env) {
|
|
|
81
83
|
const seen = new Set();
|
|
82
84
|
for (const surface of DOC_SURFACES) {
|
|
83
85
|
for (const file of collectMarkdown(env, surface)) {
|
|
84
|
-
seen.add(path.relative(env.root, file));
|
|
86
|
+
seen.add(portablePath(path.relative(env.root, file)));
|
|
85
87
|
}
|
|
86
88
|
}
|
|
87
89
|
return [...seen];
|
|
@@ -131,7 +133,7 @@ export function scanLinks(env) {
|
|
|
131
133
|
file: rel,
|
|
132
134
|
line: i + 1,
|
|
133
135
|
target,
|
|
134
|
-
resolved: path.normalize(path.join(dir, target)),
|
|
136
|
+
resolved: portablePath(path.normalize(path.join(dir, target))),
|
|
135
137
|
});
|
|
136
138
|
}
|
|
137
139
|
});
|
|
@@ -183,7 +185,7 @@ export function scanAdrRefs(env) {
|
|
|
183
185
|
const seen = new Set();
|
|
184
186
|
for (const surface of ADR_REF_SURFACES) {
|
|
185
187
|
for (const file of collectMarkdown(env, surface)) {
|
|
186
|
-
const rel = path.relative(env.root, file);
|
|
188
|
+
const rel = portablePath(path.relative(env.root, file));
|
|
187
189
|
if (seen.has(rel))
|
|
188
190
|
continue;
|
|
189
191
|
seen.add(rel);
|
|
@@ -289,7 +291,7 @@ export function projectCommands(env) {
|
|
|
289
291
|
/** Ambiente padrão para uso fora do runner de checks (o CLI, testes de integração). */
|
|
290
292
|
export function defaultEnv(overrides = {}) {
|
|
291
293
|
return {
|
|
292
|
-
root: path.resolve(path.dirname(
|
|
294
|
+
root: path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..'),
|
|
293
295
|
fs,
|
|
294
296
|
...overrides,
|
|
295
297
|
};
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* lib/core/drift-gate.ts — ponte opt-in entre `drift:check` (SPEC-030) e `check:all` (AC-5).
|
|
3
|
+
*
|
|
4
|
+
* `drift:check` reindexa o workspace inteiro por extração determinística — o mesmo custo de rodar
|
|
5
|
+
* `graph:sync`/`code:index` uma vez a mais (ver NFR do spec). Rodar isso em **todo** `check:all`
|
|
6
|
+
* (e, por extensão, em todo commit/CI) seria caro demais para repos grandes sem medição prévia de
|
|
7
|
+
* custo — por isso AC-5 pede opt-in (`--with-drift`), nunca o comportamento padrão.
|
|
8
|
+
*
|
|
9
|
+
* Este módulo não reimplementa `drift:check`: chama o comando real via subprocess (mesmo padrão de
|
|
10
|
+
* `lib/core/release.ts`/`project-smoke.ts`, que também compõem gates via `execFileSync` em vez de
|
|
11
|
+
* importar os internals uns dos outros) e traduz a saída num `Result` do runner de gates
|
|
12
|
+
* (`lib/core/checks.ts`). `severity: 'warn'` é deliberado: drift é sinal para revisão humana/de
|
|
13
|
+
* agente, não uma falha que deve travar `check:all` (SPEC-030 §5 — o comando só sinaliza, nunca
|
|
14
|
+
* corrige ou bloqueia sozinho).
|
|
15
|
+
*/
|
|
16
|
+
import type { Result } from './checks.ts';
|
|
17
|
+
/** Roda `drift:check` num subprocesso e traduz o resultado num `Result` de gate. */
|
|
18
|
+
export declare function runDriftGate(): Promise<Result[]>;
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* lib/core/drift-gate.ts — ponte opt-in entre `drift:check` (SPEC-030) e `check:all` (AC-5).
|
|
3
|
+
*
|
|
4
|
+
* `drift:check` reindexa o workspace inteiro por extração determinística — o mesmo custo de rodar
|
|
5
|
+
* `graph:sync`/`code:index` uma vez a mais (ver NFR do spec). Rodar isso em **todo** `check:all`
|
|
6
|
+
* (e, por extensão, em todo commit/CI) seria caro demais para repos grandes sem medição prévia de
|
|
7
|
+
* custo — por isso AC-5 pede opt-in (`--with-drift`), nunca o comportamento padrão.
|
|
8
|
+
*
|
|
9
|
+
* Este módulo não reimplementa `drift:check`: chama o comando real via subprocess (mesmo padrão de
|
|
10
|
+
* `lib/core/release.ts`/`project-smoke.ts`, que também compõem gates via `execFileSync` em vez de
|
|
11
|
+
* importar os internals uns dos outros) e traduz a saída num `Result` do runner de gates
|
|
12
|
+
* (`lib/core/checks.ts`). `severity: 'warn'` é deliberado: drift é sinal para revisão humana/de
|
|
13
|
+
* agente, não uma falha que deve travar `check:all` (SPEC-030 §5 — o comando só sinaliza, nunca
|
|
14
|
+
* corrige ou bloqueia sozinho).
|
|
15
|
+
*/
|
|
16
|
+
import { spawnSync } from 'node:child_process';
|
|
17
|
+
import path from 'node:path';
|
|
18
|
+
import { fileURLToPath } from 'node:url';
|
|
19
|
+
import { resolveScript } from "./registry.js";
|
|
20
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
21
|
+
const repoRoot = path.resolve(path.dirname(__filename), '..', '..');
|
|
22
|
+
const ID = 'drift-check';
|
|
23
|
+
const TITLE = 'drift:check — o verified continua verdade (SPEC-030, opt-in)';
|
|
24
|
+
function driftCountFrom(stdout) {
|
|
25
|
+
return /(\d+) com drift detectado/.exec(stdout)?.[1] ?? '?';
|
|
26
|
+
}
|
|
27
|
+
/** Roda `drift:check` num subprocesso e traduz o resultado num `Result` de gate. */
|
|
28
|
+
export async function runDriftGate() {
|
|
29
|
+
const script = resolveScript(repoRoot, 'scripts/drift-check.ts');
|
|
30
|
+
const result = spawnSync('node', [script], { cwd: process.cwd(), encoding: 'utf8' });
|
|
31
|
+
const stdout = result.stdout ?? '';
|
|
32
|
+
// exit 0 = sem drift, exit 1 = drift detectado (ambos "o comando rodou"); qualquer outro código —
|
|
33
|
+
// ou erro ao spawnar — é falha de infraestrutura do gate em si, não um veredito sobre o grafo.
|
|
34
|
+
if (result.error !== undefined || (result.status !== 0 && result.status !== 1)) {
|
|
35
|
+
return [{
|
|
36
|
+
id: ID,
|
|
37
|
+
title: TITLE,
|
|
38
|
+
severity: 'warn',
|
|
39
|
+
status: 'fail',
|
|
40
|
+
detail: `drift:check não rodou: ${result.stderr || result.error?.message || `exit ${result.status}`}`,
|
|
41
|
+
fix: 'rode `forja drift:check` diretamente para depurar',
|
|
42
|
+
}];
|
|
43
|
+
}
|
|
44
|
+
if (result.status === 1) {
|
|
45
|
+
return [{
|
|
46
|
+
id: ID,
|
|
47
|
+
title: TITLE,
|
|
48
|
+
severity: 'warn',
|
|
49
|
+
status: 'warn',
|
|
50
|
+
detail: `${driftCountFrom(stdout)} documento(s) com relação(ões) verified que a extração atual não reproduz mais`,
|
|
51
|
+
fix: '`forja drift:check` para o relatório completo — corrigir o código ou a ADR/spec desatualizada é decisão humana/de agente',
|
|
52
|
+
}];
|
|
53
|
+
}
|
|
54
|
+
return [{ id: ID, title: TITLE, severity: 'warn', status: 'ok', detail: 'nenhuma relação verified ficou stale desde a última indexação', fix: null }];
|
|
55
|
+
}
|
package/dist/lib/core/gates.d.ts
CHANGED
|
@@ -20,15 +20,22 @@ export interface GatesDeps {
|
|
|
20
20
|
full: boolean;
|
|
21
21
|
}) => Promise<any[]>;
|
|
22
22
|
release?: () => Promise<any[]>;
|
|
23
|
+
drift?: () => Promise<any[]>;
|
|
24
|
+
architecture?: () => Promise<any[]>;
|
|
23
25
|
}
|
|
24
26
|
/**
|
|
25
27
|
* Roda os gates aplicáveis ao framework e devolve os resultados agrupados por gate.
|
|
26
28
|
*
|
|
27
29
|
* Tier barato (default): coerência (doctor) + projeto gerado (smoke barato). `--full` adiciona os
|
|
28
|
-
* caros: o tarball (release) e o build do gerado (smoke --full).
|
|
30
|
+
* caros: o tarball (release) e o build do gerado (smoke --full). `--with-drift` (SPEC-030 AC-5) é
|
|
31
|
+
* um terceiro eixo, independente de `full`: reindexa o workspace inteiro por extração
|
|
32
|
+
* determinística — não é caro na mesma escala do tarball, mas também não é grátis o bastante para
|
|
33
|
+
* rodar em todo commit sem medição, daí opt-in em vez de padrão.
|
|
29
34
|
*/
|
|
30
|
-
export declare function runGates({ full, deps }?: {
|
|
35
|
+
export declare function runGates({ full, withDrift, withArchitecture, deps }?: {
|
|
31
36
|
full?: boolean;
|
|
37
|
+
withDrift?: boolean;
|
|
38
|
+
withArchitecture?: boolean;
|
|
32
39
|
deps?: GatesDeps;
|
|
33
40
|
}): Promise<GateGroup[]>;
|
|
34
41
|
/** O pior status entre todos os gates — o veredito único. */
|
package/dist/lib/core/gates.js
CHANGED
|
@@ -11,21 +11,32 @@
|
|
|
11
11
|
import { runChecks as runHealthChecks, worstStatus } from "./health.js";
|
|
12
12
|
import { runProjectSmoke } from "./project-smoke.js";
|
|
13
13
|
import { runReleaseChecks } from "./release.js";
|
|
14
|
+
import { runDriftGate } from "./drift-gate.js";
|
|
15
|
+
import { runArchitectureGate } from "./architecture-gate.js";
|
|
14
16
|
/**
|
|
15
17
|
* Roda os gates aplicáveis ao framework e devolve os resultados agrupados por gate.
|
|
16
18
|
*
|
|
17
19
|
* Tier barato (default): coerência (doctor) + projeto gerado (smoke barato). `--full` adiciona os
|
|
18
|
-
* caros: o tarball (release) e o build do gerado (smoke --full).
|
|
20
|
+
* caros: o tarball (release) e o build do gerado (smoke --full). `--with-drift` (SPEC-030 AC-5) é
|
|
21
|
+
* um terceiro eixo, independente de `full`: reindexa o workspace inteiro por extração
|
|
22
|
+
* determinística — não é caro na mesma escala do tarball, mas também não é grátis o bastante para
|
|
23
|
+
* rodar em todo commit sem medição, daí opt-in em vez de padrão.
|
|
19
24
|
*/
|
|
20
|
-
export async function runGates({ full = false, deps = {} } = {}) {
|
|
25
|
+
export async function runGates({ full = false, withDrift = false, withArchitecture = false, deps = {} } = {}) {
|
|
21
26
|
const health = deps.health ?? (() => runHealthChecks());
|
|
22
27
|
const smoke = deps.smoke ?? ((o) => runProjectSmoke(o));
|
|
23
28
|
const release = deps.release ?? (() => runReleaseChecks({}));
|
|
29
|
+
const drift = deps.drift ?? (() => runDriftGate());
|
|
30
|
+
const architecture = deps.architecture ?? (() => runArchitectureGate());
|
|
24
31
|
const groups = [];
|
|
25
32
|
groups.push({ name: 'núcleo & coerência', results: await health() });
|
|
26
33
|
groups.push({ name: 'projeto gerado', results: await smoke({ full }) });
|
|
27
34
|
if (full)
|
|
28
35
|
groups.push({ name: 'tarball (instalação limpa)', results: await release() });
|
|
36
|
+
if (withDrift)
|
|
37
|
+
groups.push({ name: 'drift sentinel (opt-in, SPEC-030)', results: await drift() });
|
|
38
|
+
if (withArchitecture)
|
|
39
|
+
groups.push({ name: 'architecture constitution (opt-in, SPEC-033)', results: await architecture() });
|
|
29
40
|
return groups;
|
|
30
41
|
}
|
|
31
42
|
/** O pior status entre todos os gates — o veredito único. */
|
package/dist/lib/core/health.js
CHANGED
|
@@ -171,6 +171,21 @@ const memoryDb = {
|
|
|
171
171
|
fix: 'aguarde o processo concorrente liberar o lock e rode de novo',
|
|
172
172
|
};
|
|
173
173
|
}
|
|
174
|
+
// "no such table: memory_nodes" (achado real, SPEC-032/033): `getWorkspaceDbPath()` é
|
|
175
|
+
// compartilhado por dois mecanismos de schema independentes — `sync:universal` cria
|
|
176
|
+
// `memory_nodes` por conta própria, enquanto `drift:check`/`adr:*`/`architecture:*`/
|
|
177
|
+
// `agent:*`/`incident:*` usam `SqliteMigrationRunner` (schema do Engineering Graph), que
|
|
178
|
+
// nunca cria essa tabela. Um workspace onde só os comandos de grafo já rodaram tem um banco
|
|
179
|
+
// são, só sem essa tabela específica ainda — SQLITE_ERROR genérico, não corrupção. Mesmo
|
|
180
|
+
// `code` (`SQLITE_ERROR`) cobre outros erros de SQL também, então o texto da mensagem é o
|
|
181
|
+
// único sinal confiável aqui — `PRAGMA integrity_check` confirmaria são se alguém checasse.
|
|
182
|
+
if (asErrno(err).message?.includes('no such table: memory_nodes')) {
|
|
183
|
+
return {
|
|
184
|
+
status: 'warn',
|
|
185
|
+
detail: `banco existe mas ainda não foi sincronizado (tabela memory_nodes ausente) — comum se só drift:check/adr:*/architecture:*/agent:*/incident:* já rodaram neste workspace`,
|
|
186
|
+
fix: 'npm run sync:universal',
|
|
187
|
+
};
|
|
188
|
+
}
|
|
174
189
|
// Só o que sobra — SQLITE_CORRUPT, SQLITE_NOTADB, o resto — é integridade. Aí sim reindexar.
|
|
175
190
|
return {
|
|
176
191
|
status: 'fail',
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* lib/core/incident-search.ts — busca de incidentes por palavra-chave (SPEC-041, reaproveitada por
|
|
3
|
+
* SPEC-042).
|
|
4
|
+
*
|
|
5
|
+
* Extraído pra `lib/core` (mesmo padrão de `risk-collect.ts`) em vez de ficar em
|
|
6
|
+
* `scripts/incident.ts`: um script tem `main()` executado incondicionalmente ao ser importado — um
|
|
7
|
+
* `import` de `scripts/engineer.ts` pra `scripts/incident.ts` rodaria o `main()` de `incident.ts`
|
|
8
|
+
* como efeito colateral, processando o `argv` errado. Lógica compartilhada entre comandos sempre
|
|
9
|
+
* vive em `lib/core`/`packages/*`, nunca em outro `scripts/*.ts`.
|
|
10
|
+
*/
|
|
11
|
+
import type { GraphNode } from '../../packages/contracts/src/index.ts';
|
|
12
|
+
import type { SqliteGraphStore } from '../../packages/adapter-sqlite/src/index.ts';
|
|
13
|
+
export declare function incidentRecords(store: SqliteGraphStore): readonly GraphNode[];
|
|
14
|
+
export declare function titleOf(node: GraphNode): string;
|
|
15
|
+
export interface RankedIncident {
|
|
16
|
+
readonly record: GraphNode;
|
|
17
|
+
readonly relevance: number;
|
|
18
|
+
}
|
|
19
|
+
export declare function rankIncidentsByQuery(records: readonly GraphNode[], query: string): readonly RankedIncident[];
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* lib/core/incident-search.ts — busca de incidentes por palavra-chave (SPEC-041, reaproveitada por
|
|
3
|
+
* SPEC-042).
|
|
4
|
+
*
|
|
5
|
+
* Extraído pra `lib/core` (mesmo padrão de `risk-collect.ts`) em vez de ficar em
|
|
6
|
+
* `scripts/incident.ts`: um script tem `main()` executado incondicionalmente ao ser importado — um
|
|
7
|
+
* `import` de `scripts/engineer.ts` pra `scripts/incident.ts` rodaria o `main()` de `incident.ts`
|
|
8
|
+
* como efeito colateral, processando o `argv` errado. Lógica compartilhada entre comandos sempre
|
|
9
|
+
* vive em `lib/core`/`packages/*`, nunca em outro `scripts/*.ts`.
|
|
10
|
+
*/
|
|
11
|
+
export function incidentRecords(store) {
|
|
12
|
+
return store.listNodes().filter((node) => node.type === 'Incident').sort((left, right) => right.createdAt.localeCompare(left.createdAt));
|
|
13
|
+
}
|
|
14
|
+
export function titleOf(node) {
|
|
15
|
+
return node.label.split('\n')[0];
|
|
16
|
+
}
|
|
17
|
+
const STOPWORDS = new Set(['o', 'a', 'os', 'as', 'de', 'do', 'da', 'em', 'um', 'uma', 'e', 'que', 'para', 'com', 'não']);
|
|
18
|
+
function terms(text) {
|
|
19
|
+
return text.toLowerCase().split(/[^a-z0-9áéíóúâêôãõç]+/).filter((term) => term.length > 1 && !STOPWORDS.has(term));
|
|
20
|
+
}
|
|
21
|
+
export function rankIncidentsByQuery(records, query) {
|
|
22
|
+
const queryTerms = terms(query);
|
|
23
|
+
return records
|
|
24
|
+
.map((record) => {
|
|
25
|
+
const recordTerms = new Set(terms(record.label));
|
|
26
|
+
const matches = queryTerms.filter((term) => recordTerms.has(term)).length;
|
|
27
|
+
return { record, matches, relevance: queryTerms.length === 0 ? 0 : matches / queryTerms.length };
|
|
28
|
+
})
|
|
29
|
+
.filter((item) => item.matches > 0)
|
|
30
|
+
.map(({ record, relevance }) => ({ record, relevance }))
|
|
31
|
+
.sort((left, right) => right.relevance - left.relevance || left.record.id.localeCompare(right.record.id));
|
|
32
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
export declare const DEFAULT_PRICING_PATH: string;
|
|
2
|
+
/** Dias após os quais um preço não revisado é considerado velho (risco do SPEC-029: "asOf > 90 dias"). */
|
|
3
|
+
export declare const STALE_PRICE_MAX_AGE_DAYS = 90;
|
|
4
|
+
export interface ModelPrice {
|
|
5
|
+
readonly inputPer1kUsd: number;
|
|
6
|
+
readonly outputPer1kUsd: number;
|
|
7
|
+
/** Data (YYYY-MM-DD) em que este preço foi conferido pela última vez. */
|
|
8
|
+
readonly asOf: string;
|
|
9
|
+
}
|
|
10
|
+
export interface PricingTable {
|
|
11
|
+
readonly version: number;
|
|
12
|
+
readonly currency: 'USD';
|
|
13
|
+
/** Chave: `${provider}:${model}` — o mesmo formato já usado em `Observation.model` (ver LlmProfile). */
|
|
14
|
+
readonly prices: Readonly<Record<string, ModelPrice>>;
|
|
15
|
+
}
|
|
16
|
+
export declare class ModelPricingError extends Error {
|
|
17
|
+
constructor(message: string);
|
|
18
|
+
}
|
|
19
|
+
/** Lê e valida a tabela local. Sem rede — só filesystem (NFR local-first do SPEC-029). */
|
|
20
|
+
export declare function loadPricingTable(filePath?: string): PricingTable;
|
|
21
|
+
export declare function validatePricingTable(value: unknown, source?: string): PricingTable;
|
|
22
|
+
/** `undefined` quando o provider/modelo não está na tabela — nunca lança (AC-4: preço desconhecido não bloqueia). */
|
|
23
|
+
export declare function lookupPrice(table: PricingTable, model: string | undefined): ModelPrice | undefined;
|
|
24
|
+
/**
|
|
25
|
+
* Custo real estimado em USD para `model`, a partir de tokens de entrada/saída já capturados
|
|
26
|
+
* (ex.: `Observation.inputTokens`/`outputTokens`). `undefined` quando o preço é desconhecido —
|
|
27
|
+
* o chamador decide entre seguir sem custo computado (fail-open, AC-4) ou logar um aviso.
|
|
28
|
+
*/
|
|
29
|
+
export declare function computeCostUsd(table: PricingTable, model: string | undefined, inputTokens: number, outputTokens: number): number | undefined;
|
|
30
|
+
/** True quando `price.asOf` está mais velho que `maxAgeDays` em relação a `now` (mitigação de risco do SPEC-029). */
|
|
31
|
+
export declare function isPriceStale(price: ModelPrice, now?: Date, maxAgeDays?: number): boolean;
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* lib/core/model-pricing.ts — tabela de preço local, versionada (SPEC-029, AC-3).
|
|
3
|
+
*
|
|
4
|
+
* Local-first por design (NFR do spec): nenhuma chamada de rede. `lib/core/model-pricing.json` é
|
|
5
|
+
* mantido manualmente/por PR, não sincronizado com o billing real de nenhum provider — ver "Fora"
|
|
6
|
+
* do SPEC-029. Cada entrada carrega `asOf` porque preço de LLM muda com frequência (risco do spec);
|
|
7
|
+
* `pricingWarnings` abaixo é o que alimenta o aviso de "tabela desatualizada" em `forja llm:doctor`.
|
|
8
|
+
*
|
|
9
|
+
* Preço desconhecido nunca lança: `lookupPrice`/`computeCostUsd` devolvem `undefined` (AC-4). Quem
|
|
10
|
+
* chama decide o que fazer com isso — normalmente: seguir a execução e avisar, nunca bloquear.
|
|
11
|
+
*/
|
|
12
|
+
import fs from 'node:fs';
|
|
13
|
+
import path from 'node:path';
|
|
14
|
+
import { fileURLToPath } from 'node:url';
|
|
15
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
16
|
+
const __dirname = path.dirname(__filename);
|
|
17
|
+
export const DEFAULT_PRICING_PATH = path.join(__dirname, 'model-pricing.json');
|
|
18
|
+
/** Dias após os quais um preço não revisado é considerado velho (risco do SPEC-029: "asOf > 90 dias"). */
|
|
19
|
+
export const STALE_PRICE_MAX_AGE_DAYS = 90;
|
|
20
|
+
export class ModelPricingError extends Error {
|
|
21
|
+
constructor(message) { super(message); this.name = 'ModelPricingError'; }
|
|
22
|
+
}
|
|
23
|
+
/** Lê e valida a tabela local. Sem rede — só filesystem (NFR local-first do SPEC-029). */
|
|
24
|
+
export function loadPricingTable(filePath = DEFAULT_PRICING_PATH) {
|
|
25
|
+
let raw;
|
|
26
|
+
try {
|
|
27
|
+
raw = JSON.parse(fs.readFileSync(filePath, 'utf8'));
|
|
28
|
+
}
|
|
29
|
+
catch (error) {
|
|
30
|
+
throw new ModelPricingError(`Falha ao ler tabela de preço (${filePath}): ${error instanceof Error ? error.message : 'erro desconhecido'}`);
|
|
31
|
+
}
|
|
32
|
+
return validatePricingTable(raw, filePath);
|
|
33
|
+
}
|
|
34
|
+
export function validatePricingTable(value, source = '<inline>') {
|
|
35
|
+
if (!isRecord(value) || typeof value.version !== 'number' || value.currency !== 'USD' || !isRecord(value.prices)) {
|
|
36
|
+
throw new ModelPricingError(`Tabela de preço inválida (${source}): esperado { version, currency: 'USD', prices }`);
|
|
37
|
+
}
|
|
38
|
+
const prices = {};
|
|
39
|
+
for (const [model, entry] of Object.entries(value.prices))
|
|
40
|
+
prices[model] = validatePrice(model, entry, source);
|
|
41
|
+
return { version: value.version, currency: 'USD', prices };
|
|
42
|
+
}
|
|
43
|
+
function validatePrice(model, value, source) {
|
|
44
|
+
if (!isRecord(value) || typeof value.inputPer1kUsd !== 'number' || value.inputPer1kUsd < 0 || typeof value.outputPer1kUsd !== 'number' || value.outputPer1kUsd < 0 || typeof value.asOf !== 'string' || value.asOf.trim().length === 0) {
|
|
45
|
+
throw new ModelPricingError(`Preço inválido para "${model}" (${source}): esperado { inputPer1kUsd >= 0, outputPer1kUsd >= 0, asOf }`);
|
|
46
|
+
}
|
|
47
|
+
return { inputPer1kUsd: value.inputPer1kUsd, outputPer1kUsd: value.outputPer1kUsd, asOf: value.asOf };
|
|
48
|
+
}
|
|
49
|
+
/** `undefined` quando o provider/modelo não está na tabela — nunca lança (AC-4: preço desconhecido não bloqueia). */
|
|
50
|
+
export function lookupPrice(table, model) {
|
|
51
|
+
if (model === undefined)
|
|
52
|
+
return undefined;
|
|
53
|
+
return table.prices[model];
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Custo real estimado em USD para `model`, a partir de tokens de entrada/saída já capturados
|
|
57
|
+
* (ex.: `Observation.inputTokens`/`outputTokens`). `undefined` quando o preço é desconhecido —
|
|
58
|
+
* o chamador decide entre seguir sem custo computado (fail-open, AC-4) ou logar um aviso.
|
|
59
|
+
*/
|
|
60
|
+
export function computeCostUsd(table, model, inputTokens, outputTokens) {
|
|
61
|
+
const price = lookupPrice(table, model);
|
|
62
|
+
if (price === undefined)
|
|
63
|
+
return undefined;
|
|
64
|
+
return (inputTokens / 1000) * price.inputPer1kUsd + (outputTokens / 1000) * price.outputPer1kUsd;
|
|
65
|
+
}
|
|
66
|
+
/** True quando `price.asOf` está mais velho que `maxAgeDays` em relação a `now` (mitigação de risco do SPEC-029). */
|
|
67
|
+
export function isPriceStale(price, now = new Date(), maxAgeDays = STALE_PRICE_MAX_AGE_DAYS) {
|
|
68
|
+
const asOf = new Date(price.asOf);
|
|
69
|
+
if (Number.isNaN(asOf.getTime()))
|
|
70
|
+
return true;
|
|
71
|
+
const ageDays = (now.getTime() - asOf.getTime()) / (1000 * 60 * 60 * 24);
|
|
72
|
+
return ageDays > maxAgeDays;
|
|
73
|
+
}
|
|
74
|
+
function isRecord(value) { return typeof value === 'object' && value !== null; }
|