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
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Architecture Constitution (SPEC-033) — turns an ADR's `## Constraints` section into rules that
|
|
3
|
+
* can be checked against real code, instead of a decision that only a human remembers to reread.
|
|
4
|
+
*
|
|
5
|
+
* Pure domain: no `fs`, no network, no dependency on `GraphLoop`/SQLite. `scripts/architecture.ts`
|
|
6
|
+
* is the adapter that reads ADR files and resolves `DependencyEdge[]` from the real Engineering
|
|
7
|
+
* Graph — this module only parses strings and compares lists, so it's fully unit-testable and
|
|
8
|
+
* reusable from a future MCP tool or the dashboard without dragging in I/O.
|
|
9
|
+
*
|
|
10
|
+
* LLM never decides a rule is `active` (ADR-0078, security principles). The recognized-phrase
|
|
11
|
+
* vocabulary here is small and fixed on purpose: anything outside it produces a `proposed` rule
|
|
12
|
+
* with `confidence < 1`, never `active` — a wrong guess here is a false positive that erodes trust
|
|
13
|
+
* in every future run of `architecture:check`, so silence (staying `proposed`) is the safe default,
|
|
14
|
+
* not a failure.
|
|
15
|
+
*/
|
|
16
|
+
export type ArchitectureConstraintKind = 'forbid_import' | 'require_dependency' | 'forbid_dependency';
|
|
17
|
+
export interface ArchitectureConstraint {
|
|
18
|
+
readonly kind: ArchitectureConstraintKind;
|
|
19
|
+
readonly target: string;
|
|
20
|
+
}
|
|
21
|
+
export type ArchitectureRuleStatus = 'active' | 'proposed';
|
|
22
|
+
export type ArchitectureSeverity = 'info' | 'low' | 'medium' | 'high' | 'critical';
|
|
23
|
+
export interface ArchitectureRule {
|
|
24
|
+
readonly id: string;
|
|
25
|
+
readonly source: string;
|
|
26
|
+
readonly status: ArchitectureRuleStatus;
|
|
27
|
+
readonly scope: {
|
|
28
|
+
readonly paths: readonly string[];
|
|
29
|
+
};
|
|
30
|
+
readonly constraint: ArchitectureConstraint;
|
|
31
|
+
readonly severity: ArchitectureSeverity;
|
|
32
|
+
readonly rationale: string;
|
|
33
|
+
readonly confidence: number;
|
|
34
|
+
}
|
|
35
|
+
/** A real (or hypothesized) import/dependency edge the graph already extracted — file path to a
|
|
36
|
+
* target label (an import specifier, a relative path, or an npm package name). */
|
|
37
|
+
export interface DependencyEdge {
|
|
38
|
+
readonly fromPath: string;
|
|
39
|
+
readonly targetLabel: string;
|
|
40
|
+
}
|
|
41
|
+
export interface ArchitectureViolation {
|
|
42
|
+
readonly ruleId: string;
|
|
43
|
+
readonly severity: ArchitectureSeverity;
|
|
44
|
+
readonly file: string;
|
|
45
|
+
readonly target: string;
|
|
46
|
+
readonly source: string;
|
|
47
|
+
readonly remediation: string;
|
|
48
|
+
}
|
|
49
|
+
export interface ArchitectureCheckReport {
|
|
50
|
+
readonly compliant: number;
|
|
51
|
+
readonly violations: readonly ArchitectureViolation[];
|
|
52
|
+
}
|
|
53
|
+
export interface ParsedConstraintLine {
|
|
54
|
+
readonly constraint: ArchitectureConstraint;
|
|
55
|
+
readonly scopeRaw: string;
|
|
56
|
+
readonly confidence: number;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Parses one bullet from an ADR's `## Constraints` section. Returns `undefined` only when the
|
|
60
|
+
* line isn't a bullet at all; an unrecognized bullet still returns a result, just with
|
|
61
|
+
* `confidence` low enough that `compileConstitution` keeps it `proposed`.
|
|
62
|
+
*/
|
|
63
|
+
export declare function parseConstraintLine(rawLine: string): ParsedConstraintLine | undefined;
|
|
64
|
+
export interface AdrDocument {
|
|
65
|
+
readonly source: string;
|
|
66
|
+
readonly content: string;
|
|
67
|
+
}
|
|
68
|
+
/** Extracts every `## Constraints` section's bullets from a set of ADR documents and compiles
|
|
69
|
+
* them into rules. Deterministic — no LLM, no I/O (the caller reads the files). */
|
|
70
|
+
export declare function compileConstitution(adrs: readonly AdrDocument[]): readonly ArchitectureRule[];
|
|
71
|
+
/**
|
|
72
|
+
* Checks only `active` rules (a `proposed` rule isn't enforced — that's the whole point of the
|
|
73
|
+
* status) against the real dependency edges the caller resolved from the graph.
|
|
74
|
+
*/
|
|
75
|
+
export declare function checkConstitution(rules: readonly ArchitectureRule[], edges: readonly DependencyEdge[]): ArchitectureCheckReport;
|
|
76
|
+
export declare function explainRule(rules: readonly ArchitectureRule[], ruleId: string): ArchitectureRule | undefined;
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Architecture Constitution (SPEC-033) — turns an ADR's `## Constraints` section into rules that
|
|
3
|
+
* can be checked against real code, instead of a decision that only a human remembers to reread.
|
|
4
|
+
*
|
|
5
|
+
* Pure domain: no `fs`, no network, no dependency on `GraphLoop`/SQLite. `scripts/architecture.ts`
|
|
6
|
+
* is the adapter that reads ADR files and resolves `DependencyEdge[]` from the real Engineering
|
|
7
|
+
* Graph — this module only parses strings and compares lists, so it's fully unit-testable and
|
|
8
|
+
* reusable from a future MCP tool or the dashboard without dragging in I/O.
|
|
9
|
+
*
|
|
10
|
+
* LLM never decides a rule is `active` (ADR-0078, security principles). The recognized-phrase
|
|
11
|
+
* vocabulary here is small and fixed on purpose: anything outside it produces a `proposed` rule
|
|
12
|
+
* with `confidence < 1`, never `active` — a wrong guess here is a false positive that erodes trust
|
|
13
|
+
* in every future run of `architecture:check`, so silence (staying `proposed`) is the safe default,
|
|
14
|
+
* not a failure.
|
|
15
|
+
*/
|
|
16
|
+
/** A recognized scope/target must look like a path or package specifier, not an arbitrary noun
|
|
17
|
+
* phrase — this is most of what keeps false positives out (D2, plan.md). */
|
|
18
|
+
function looksLikePathOrPackage(value) {
|
|
19
|
+
return /[\w-]+(\/[\w.-]+)+|^@?[a-z0-9][\w.-]*$/i.test(value) && value.length > 0;
|
|
20
|
+
}
|
|
21
|
+
const PATTERNS = [
|
|
22
|
+
{ kind: 'forbid_import', regex: /^([\w./-]+?)\s+n[ãa]o\s+(?:pode\s+)?depend(?:e|er)\s+de\s+([\w./-]+?)\s*\.?$/i },
|
|
23
|
+
{ kind: 'forbid_import', regex: /^([\w./-]+?)\s+n[ãa]o\s+import(?:a|am)\s+([\w./-]+?)\s*(?:diretamente)?\s*\.?$/i },
|
|
24
|
+
{ kind: 'forbid_dependency', regex: /^([\w./-]+?)\s+n[ãa]o\s+acess(?:a|am)\s+([\w./-]+?)\s*(?:diretamente)?\s*\.?$/i },
|
|
25
|
+
{ kind: 'require_dependency', regex: /^([\w./-]+?)\s+usa(?:m)?\s+([\w./-]+?)\s*\.?$/i },
|
|
26
|
+
];
|
|
27
|
+
/**
|
|
28
|
+
* Parses one bullet from an ADR's `## Constraints` section. Returns `undefined` only when the
|
|
29
|
+
* line isn't a bullet at all; an unrecognized bullet still returns a result, just with
|
|
30
|
+
* `confidence` low enough that `compileConstitution` keeps it `proposed`.
|
|
31
|
+
*/
|
|
32
|
+
export function parseConstraintLine(rawLine) {
|
|
33
|
+
const line = rawLine.trim().replace(/^-\s*/, '');
|
|
34
|
+
if (line.length === 0)
|
|
35
|
+
return undefined;
|
|
36
|
+
for (const { kind, regex } of PATTERNS) {
|
|
37
|
+
const match = regex.exec(line);
|
|
38
|
+
if (match?.[1] === undefined || match[2] === undefined)
|
|
39
|
+
continue;
|
|
40
|
+
const scopeRaw = match[1].trim();
|
|
41
|
+
const target = match[2].trim();
|
|
42
|
+
const confidence = looksLikePathOrPackage(scopeRaw) && looksLikePathOrPackage(target) ? 1 : 0.3;
|
|
43
|
+
return { constraint: { kind, target }, scopeRaw, confidence };
|
|
44
|
+
}
|
|
45
|
+
// No fixed pattern matched at all — still worth surfacing as a low-confidence proposal (an
|
|
46
|
+
// operator can see it in `architecture:status` and either rephrase it or approve it manually),
|
|
47
|
+
// rather than silently dropping the ADR author's intent.
|
|
48
|
+
return { constraint: { kind: 'forbid_dependency', target: line }, scopeRaw: '(não reconhecido)', confidence: 0.1 };
|
|
49
|
+
}
|
|
50
|
+
function toPathPattern(scopeRaw) {
|
|
51
|
+
return scopeRaw.endsWith('/') || scopeRaw.endsWith('*') ? scopeRaw : `${scopeRaw}/**`;
|
|
52
|
+
}
|
|
53
|
+
function severityFor(confidence) {
|
|
54
|
+
return confidence >= 1 ? 'high' : confidence >= 0.5 ? 'medium' : 'info';
|
|
55
|
+
}
|
|
56
|
+
function slug(source, index, constraint) {
|
|
57
|
+
const base = source.replace(/^.*\//, '').replace(/\.md$/, '');
|
|
58
|
+
return `${base}-${constraint.kind}-${index}`;
|
|
59
|
+
}
|
|
60
|
+
/** Extracts every `## Constraints` section's bullets from a set of ADR documents and compiles
|
|
61
|
+
* them into rules. Deterministic — no LLM, no I/O (the caller reads the files). */
|
|
62
|
+
export function compileConstitution(adrs) {
|
|
63
|
+
const rules = [];
|
|
64
|
+
for (const adr of adrs) {
|
|
65
|
+
const section = /## Constraints\n([\s\S]*?)(?:\n## |\n?$)/.exec(adr.content)?.[1];
|
|
66
|
+
if (section === undefined)
|
|
67
|
+
continue;
|
|
68
|
+
const bullets = section.split('\n').map((line) => line.trim()).filter((line) => line.startsWith('- '));
|
|
69
|
+
bullets.forEach((bullet, index) => {
|
|
70
|
+
const parsed = parseConstraintLine(bullet);
|
|
71
|
+
if (parsed === undefined)
|
|
72
|
+
return;
|
|
73
|
+
rules.push({
|
|
74
|
+
id: slug(adr.source, index, parsed.constraint),
|
|
75
|
+
source: adr.source,
|
|
76
|
+
status: parsed.confidence >= 1 ? 'active' : 'proposed',
|
|
77
|
+
scope: { paths: [toPathPattern(parsed.scopeRaw)] },
|
|
78
|
+
constraint: parsed.constraint,
|
|
79
|
+
severity: severityFor(parsed.confidence),
|
|
80
|
+
rationale: bullet.replace(/^-\s*/, ''),
|
|
81
|
+
confidence: parsed.confidence,
|
|
82
|
+
});
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
return rules;
|
|
86
|
+
}
|
|
87
|
+
function matchesScope(file, paths) {
|
|
88
|
+
return paths.some((pattern) => {
|
|
89
|
+
const prefix = pattern.replace(/\*+$/, '');
|
|
90
|
+
return file === prefix.replace(/\/$/, '') || file.startsWith(prefix);
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
function matchesTarget(targetLabel, ruleTarget) {
|
|
94
|
+
return targetLabel === ruleTarget || targetLabel.includes(ruleTarget);
|
|
95
|
+
}
|
|
96
|
+
const REMEDIATION = {
|
|
97
|
+
forbid_import: (rule) => `Remova a dependência de "${rule.constraint.target}" em ${rule.scope.paths[0]} — introduza um adapter/porta em vez de importar diretamente (ver ${rule.source}).`,
|
|
98
|
+
forbid_dependency: (rule) => `Remova o acesso a "${rule.constraint.target}" em ${rule.scope.paths[0]} — a ADR de origem (${rule.source}) exige uma camada intermediária.`,
|
|
99
|
+
require_dependency: (rule) => `${rule.scope.paths[0]} deveria depender de "${rule.constraint.target}" segundo ${rule.source}, mas nenhuma aresta correspondente foi encontrada.`,
|
|
100
|
+
};
|
|
101
|
+
/**
|
|
102
|
+
* Checks only `active` rules (a `proposed` rule isn't enforced — that's the whole point of the
|
|
103
|
+
* status) against the real dependency edges the caller resolved from the graph.
|
|
104
|
+
*/
|
|
105
|
+
export function checkConstitution(rules, edges) {
|
|
106
|
+
const violations = [];
|
|
107
|
+
let compliant = 0;
|
|
108
|
+
for (const rule of rules) {
|
|
109
|
+
if (rule.status !== 'active')
|
|
110
|
+
continue;
|
|
111
|
+
if (rule.constraint.kind === 'require_dependency') {
|
|
112
|
+
const satisfied = edges.some((edge) => matchesScope(edge.fromPath, rule.scope.paths) && matchesTarget(edge.targetLabel, rule.constraint.target));
|
|
113
|
+
if (satisfied)
|
|
114
|
+
compliant += 1;
|
|
115
|
+
else
|
|
116
|
+
violations.push({ ruleId: rule.id, severity: rule.severity, file: rule.scope.paths[0] ?? '', target: rule.constraint.target, source: rule.source, remediation: REMEDIATION.require_dependency(rule) });
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
const offending = edges.filter((edge) => matchesScope(edge.fromPath, rule.scope.paths) && matchesTarget(edge.targetLabel, rule.constraint.target));
|
|
120
|
+
if (offending.length === 0) {
|
|
121
|
+
compliant += 1;
|
|
122
|
+
continue;
|
|
123
|
+
}
|
|
124
|
+
for (const edge of offending)
|
|
125
|
+
violations.push({ ruleId: rule.id, severity: rule.severity, file: edge.fromPath, target: rule.constraint.target, source: rule.source, remediation: REMEDIATION[rule.constraint.kind](rule) });
|
|
126
|
+
}
|
|
127
|
+
return { compliant, violations };
|
|
128
|
+
}
|
|
129
|
+
export function explainRule(rules, ruleId) {
|
|
130
|
+
return rules.find((rule) => rule.id === ruleId);
|
|
131
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @forja/engineering-evidence — Engineering Evidence Ledger (SPEC-035).
|
|
3
|
+
*
|
|
4
|
+
* Não é uma fonte de dado nova: `buildEvidenceLedger` é um mapeamento puro sobre um `RuntimeRun`
|
|
5
|
+
* + `AuditRecord`/`ApprovalRequest` já persistidos (packages/contracts, packages/adapter-sqlite)
|
|
6
|
+
* e, opcionalmente, um `ArchitectureCheckReport` (SPEC-033) / `ChangeRiskAssessment` (SPEC-034) já
|
|
7
|
+
* calculados em outro lugar. Nada aqui busca dado sozinho (isso é `scripts/evidence.ts`) e nada
|
|
8
|
+
* aqui inventa um campo que não veio no input — reflete só o que os componentes já disseram (D3
|
|
9
|
+
* do plan, mesmo princípio de AC-3 em `forja engineer`).
|
|
10
|
+
*/
|
|
11
|
+
import type { AgentIdentity, ApprovalRequest, AuditRecord, EvaluationResult, RuntimeRun } from '../../../contracts/src/index.ts';
|
|
12
|
+
import type { ArchitectureCheckReport } from '../../architecture/src/index.ts';
|
|
13
|
+
import type { ChangeRiskAssessment } from '../../risk/src/index.ts';
|
|
14
|
+
export interface EvidenceLedgerInput {
|
|
15
|
+
readonly run: RuntimeRun;
|
|
16
|
+
readonly auditRecords: readonly AuditRecord[];
|
|
17
|
+
readonly approvals: readonly ApprovalRequest[];
|
|
18
|
+
readonly architectureCheck?: ArchitectureCheckReport;
|
|
19
|
+
readonly riskAssessment?: ChangeRiskAssessment;
|
|
20
|
+
readonly commit?: string;
|
|
21
|
+
}
|
|
22
|
+
export interface EvidenceLedgerRunSummary {
|
|
23
|
+
readonly runId: string;
|
|
24
|
+
readonly state: string;
|
|
25
|
+
readonly startedAt: string;
|
|
26
|
+
readonly updatedAt: string;
|
|
27
|
+
readonly steps: number;
|
|
28
|
+
readonly changedFiles: readonly string[];
|
|
29
|
+
}
|
|
30
|
+
export interface EvidenceLedgerRecord {
|
|
31
|
+
readonly run: EvidenceLedgerRunSummary;
|
|
32
|
+
readonly intent: string;
|
|
33
|
+
readonly agent: AgentIdentity;
|
|
34
|
+
readonly architectureCheck?: ArchitectureCheckReport;
|
|
35
|
+
readonly risk?: ChangeRiskAssessment;
|
|
36
|
+
readonly tests?: EvaluationResult;
|
|
37
|
+
readonly auditRecords: readonly AuditRecord[];
|
|
38
|
+
readonly approvals: readonly ApprovalRequest[];
|
|
39
|
+
readonly commit?: string;
|
|
40
|
+
}
|
|
41
|
+
export declare function buildEvidenceLedger(input: EvidenceLedgerInput): EvidenceLedgerRecord;
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @forja/engineering-evidence — Engineering Evidence Ledger (SPEC-035).
|
|
3
|
+
*
|
|
4
|
+
* Não é uma fonte de dado nova: `buildEvidenceLedger` é um mapeamento puro sobre um `RuntimeRun`
|
|
5
|
+
* + `AuditRecord`/`ApprovalRequest` já persistidos (packages/contracts, packages/adapter-sqlite)
|
|
6
|
+
* e, opcionalmente, um `ArchitectureCheckReport` (SPEC-033) / `ChangeRiskAssessment` (SPEC-034) já
|
|
7
|
+
* calculados em outro lugar. Nada aqui busca dado sozinho (isso é `scripts/evidence.ts`) e nada
|
|
8
|
+
* aqui inventa um campo que não veio no input — reflete só o que os componentes já disseram (D3
|
|
9
|
+
* do plan, mesmo princípio de AC-3 em `forja engineer`).
|
|
10
|
+
*/
|
|
11
|
+
export function buildEvidenceLedger(input) {
|
|
12
|
+
const { run } = input;
|
|
13
|
+
return {
|
|
14
|
+
run: {
|
|
15
|
+
runId: run.runId,
|
|
16
|
+
state: run.state,
|
|
17
|
+
startedAt: run.createdAt,
|
|
18
|
+
updatedAt: run.updatedAt,
|
|
19
|
+
steps: run.steps,
|
|
20
|
+
changedFiles: run.changedFiles,
|
|
21
|
+
},
|
|
22
|
+
intent: run.objective,
|
|
23
|
+
agent: run.agent,
|
|
24
|
+
...(input.architectureCheck === undefined ? {} : { architectureCheck: input.architectureCheck }),
|
|
25
|
+
...(input.riskAssessment === undefined ? {} : { risk: input.riskAssessment }),
|
|
26
|
+
...(run.validation === undefined ? {} : { tests: run.validation }),
|
|
27
|
+
auditRecords: input.auditRecords,
|
|
28
|
+
approvals: input.approvals,
|
|
29
|
+
...(input.commit === undefined ? {} : { commit: input.commit }),
|
|
30
|
+
};
|
|
31
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @forja/engineering-identity — Agent Reputation (SPEC-036) + Smart Agent Routing (SPEC-037).
|
|
3
|
+
*
|
|
4
|
+
* Domínio puro: `computeReputationScore` recebe um `EvaluationReport` já produzido por
|
|
5
|
+
* `packages/evals.EvaluationEngine` (reaproveitado, não reimplementado — nenhuma métrica nova
|
|
6
|
+
* calculada aqui) e devolve um `AgentReputationScore`. `recommendAgent` classifica
|
|
7
|
+
* `AgentProfile2[]` (já registrados/pontuados) por adequação a um papel/domínio — não confundir
|
|
8
|
+
* com `packages/llm.recommendProfile` (routing de provider/model de LLM, problema adjacente, não
|
|
9
|
+
* o mesmo; ver nota no topo de `specs/smart-agent-routing/spec.md`). Nenhum `fs`/rede/SQLite — a
|
|
10
|
+
* persistência (`SqliteAgentProfileStore`) e a coleta de `Observation`s vivem em `scripts/agent.ts`.
|
|
11
|
+
*/
|
|
12
|
+
import type { AgentProfile2, EvaluationReport } from '../../../contracts/src/index.ts';
|
|
13
|
+
export type AutonomyLevel = 'autonomous' | 'autonomous_with_review' | 'supervised' | 'human_in_the_loop';
|
|
14
|
+
export interface AgentReputationScore {
|
|
15
|
+
readonly agentId: string;
|
|
16
|
+
readonly domain?: string;
|
|
17
|
+
/** 0-5. */
|
|
18
|
+
readonly trustLevel: number;
|
|
19
|
+
readonly autonomyLevel: AutonomyLevel;
|
|
20
|
+
/** 0-1 — proporcional ao tamanho da amostra, nunca escondida (AC-2). */
|
|
21
|
+
readonly confidence: number;
|
|
22
|
+
readonly sampleSize: number;
|
|
23
|
+
readonly metrics: Readonly<Record<string, number>>;
|
|
24
|
+
readonly evidenceIds: readonly string[];
|
|
25
|
+
}
|
|
26
|
+
export interface ReputationThresholds {
|
|
27
|
+
/** Abaixo disso, `autonomyLevel` é sempre `human_in_the_loop` — fail-closed em cold start (AC-3). */
|
|
28
|
+
readonly minSampleSize: number;
|
|
29
|
+
/** `trustLevel` mínimo (escala 0-5) para cada banda, do mais alto para o mais baixo. */
|
|
30
|
+
readonly autonomous: number;
|
|
31
|
+
readonly autonomousWithReview: number;
|
|
32
|
+
readonly supervised: number;
|
|
33
|
+
}
|
|
34
|
+
/** Sugeridos na visão original — configuração default, nunca constante fixa (mesmo princípio de RiskEngine/SPEC-034). */
|
|
35
|
+
export declare const DEFAULT_REPUTATION_THRESHOLDS: ReputationThresholds;
|
|
36
|
+
export declare function computeReputationScore(report: EvaluationReport, meta: {
|
|
37
|
+
readonly agentId: string;
|
|
38
|
+
readonly domain?: string;
|
|
39
|
+
readonly thresholds?: ReputationThresholds;
|
|
40
|
+
}): AgentReputationScore;
|
|
41
|
+
export interface AgentRecommendation {
|
|
42
|
+
readonly agentId: string;
|
|
43
|
+
readonly score: number;
|
|
44
|
+
readonly reasons: readonly string[];
|
|
45
|
+
}
|
|
46
|
+
export interface AgentRecommendationCriteria {
|
|
47
|
+
readonly role: string;
|
|
48
|
+
readonly domain?: string;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* `score` = (role casado ? 100 : 0) + (domain casado em `architectureDomains` ? 50 : 0) +
|
|
52
|
+
* (`trustLevel` ?? 0) · 10 (0-50) — mesma proporção de pesos de `packages/llm.recommendProfile`
|
|
53
|
+
* (D1 do plan), nunca "número mágico". Um agente sem `trustLevel` ainda **não é excluído** do
|
|
54
|
+
* ranking (AC-2) — o termo de reputação entra como 0 e o motivo declara isso explicitamente, nunca
|
|
55
|
+
* finge um trust level que não existe.
|
|
56
|
+
*/
|
|
57
|
+
export declare function recommendAgent(profiles: readonly AgentProfile2[], criteria: AgentRecommendationCriteria): readonly AgentRecommendation[];
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @forja/engineering-identity — Agent Reputation (SPEC-036) + Smart Agent Routing (SPEC-037).
|
|
3
|
+
*
|
|
4
|
+
* Domínio puro: `computeReputationScore` recebe um `EvaluationReport` já produzido por
|
|
5
|
+
* `packages/evals.EvaluationEngine` (reaproveitado, não reimplementado — nenhuma métrica nova
|
|
6
|
+
* calculada aqui) e devolve um `AgentReputationScore`. `recommendAgent` classifica
|
|
7
|
+
* `AgentProfile2[]` (já registrados/pontuados) por adequação a um papel/domínio — não confundir
|
|
8
|
+
* com `packages/llm.recommendProfile` (routing de provider/model de LLM, problema adjacente, não
|
|
9
|
+
* o mesmo; ver nota no topo de `specs/smart-agent-routing/spec.md`). Nenhum `fs`/rede/SQLite — a
|
|
10
|
+
* persistência (`SqliteAgentProfileStore`) e a coleta de `Observation`s vivem em `scripts/agent.ts`.
|
|
11
|
+
*/
|
|
12
|
+
/** Sugeridos na visão original — configuração default, nunca constante fixa (mesmo princípio de RiskEngine/SPEC-034). */
|
|
13
|
+
export const DEFAULT_REPUTATION_THRESHOLDS = {
|
|
14
|
+
minSampleSize: 5,
|
|
15
|
+
autonomous: 4,
|
|
16
|
+
autonomousWithReview: 3,
|
|
17
|
+
supervised: 1,
|
|
18
|
+
};
|
|
19
|
+
/**
|
|
20
|
+
* `trustLevel` = 0.5·successRate + 0.2·(1-reworkRate) + 0.2·(1-rollbackRate) +
|
|
21
|
+
* 0.1·(1-assertionsWithoutEvidenceRate), escalado 0-5. Pesos documentados aqui e no plan
|
|
22
|
+
* (D1) — nunca "número mágico" (mesmo princípio de RiskEngine).
|
|
23
|
+
*
|
|
24
|
+
* `sampleSize === 0` é tratado à parte, ANTES da fórmula: `EvaluationEngine.rate()` devolve `0`
|
|
25
|
+
* (não `undefined`) para toda métrica quando não há `Observation` nenhuma — a fórmula acima leria
|
|
26
|
+
* esses zeros de "sem dado" como reworkRate/rollbackRate/assertionsWithoutEvidenceRate = 0 (bom
|
|
27
|
+
* sinal!) e produziria um trustLevel médio (~3/5) sem nenhuma evidência real por trás. Isso
|
|
28
|
+
* contradiz AC-2 ("nunca escondida"): 0 observações é 0 de confiança, não neutro.
|
|
29
|
+
*/
|
|
30
|
+
function trustLevelFrom(metrics, sampleSize) {
|
|
31
|
+
if (sampleSize === 0)
|
|
32
|
+
return 0;
|
|
33
|
+
const successRate = metrics.successRate ?? 0;
|
|
34
|
+
const reworkRate = metrics.reworkRate ?? 0;
|
|
35
|
+
const rollbackRate = metrics.rollbackRate ?? 0;
|
|
36
|
+
const assertionsWithoutEvidenceRate = metrics.assertionsWithoutEvidenceRate ?? 0;
|
|
37
|
+
const raw = 0.5 * successRate + 0.2 * (1 - reworkRate) + 0.2 * (1 - rollbackRate) + 0.1 * (1 - assertionsWithoutEvidenceRate);
|
|
38
|
+
return Math.min(5, Math.max(0, Math.round(raw * 5)));
|
|
39
|
+
}
|
|
40
|
+
function autonomyLevelFor(trustLevel, sampleSize, thresholds) {
|
|
41
|
+
if (sampleSize < thresholds.minSampleSize)
|
|
42
|
+
return 'human_in_the_loop';
|
|
43
|
+
if (trustLevel >= thresholds.autonomous)
|
|
44
|
+
return 'autonomous';
|
|
45
|
+
if (trustLevel >= thresholds.autonomousWithReview)
|
|
46
|
+
return 'autonomous_with_review';
|
|
47
|
+
if (trustLevel >= thresholds.supervised)
|
|
48
|
+
return 'supervised';
|
|
49
|
+
return 'human_in_the_loop';
|
|
50
|
+
}
|
|
51
|
+
export function computeReputationScore(report, meta) {
|
|
52
|
+
const thresholds = meta.thresholds ?? DEFAULT_REPUTATION_THRESHOLDS;
|
|
53
|
+
const sampleSize = report.metrics.observationCount ?? report.observationIds.length;
|
|
54
|
+
const trustLevel = trustLevelFrom(report.metrics, sampleSize);
|
|
55
|
+
return {
|
|
56
|
+
agentId: meta.agentId,
|
|
57
|
+
...(meta.domain === undefined ? {} : { domain: meta.domain }),
|
|
58
|
+
trustLevel,
|
|
59
|
+
autonomyLevel: autonomyLevelFor(trustLevel, sampleSize, thresholds),
|
|
60
|
+
confidence: Math.min(1, sampleSize / thresholds.minSampleSize),
|
|
61
|
+
sampleSize,
|
|
62
|
+
metrics: report.metrics,
|
|
63
|
+
evidenceIds: report.observationIds,
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* `score` = (role casado ? 100 : 0) + (domain casado em `architectureDomains` ? 50 : 0) +
|
|
68
|
+
* (`trustLevel` ?? 0) · 10 (0-50) — mesma proporção de pesos de `packages/llm.recommendProfile`
|
|
69
|
+
* (D1 do plan), nunca "número mágico". Um agente sem `trustLevel` ainda **não é excluído** do
|
|
70
|
+
* ranking (AC-2) — o termo de reputação entra como 0 e o motivo declara isso explicitamente, nunca
|
|
71
|
+
* finge um trust level que não existe.
|
|
72
|
+
*/
|
|
73
|
+
export function recommendAgent(profiles, criteria) {
|
|
74
|
+
return profiles
|
|
75
|
+
.map((profile) => {
|
|
76
|
+
const roleMatch = profile.role === criteria.role;
|
|
77
|
+
const domainMatch = criteria.domain !== undefined && profile.architectureDomains.includes(criteria.domain);
|
|
78
|
+
const trustLevel = profile.trustLevel;
|
|
79
|
+
const score = (roleMatch ? 100 : 0) + (domainMatch ? 50 : 0) + (trustLevel ?? 0) * 10;
|
|
80
|
+
const reasons = [
|
|
81
|
+
...(roleMatch ? [`role:${criteria.role}`] : []),
|
|
82
|
+
...(domainMatch ? [`domain:${criteria.domain}`] : []),
|
|
83
|
+
...(trustLevel === undefined ? ['sem pontuação ainda — rode agent:score'] : [`trustLevel ${trustLevel}/5 (${profile.autonomyLevel})`]),
|
|
84
|
+
];
|
|
85
|
+
return { agentId: profile.id, score, reasons };
|
|
86
|
+
})
|
|
87
|
+
.sort((left, right) => right.score - left.score || left.agentId.localeCompare(right.agentId));
|
|
88
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @forja/engineering-monitoring — Agent Runtime Monitoring / Behavior Anomaly Engine (SPEC-040).
|
|
3
|
+
*
|
|
4
|
+
* Domínio puro: `detectAnomaly` compara dois `EvaluationReport` (linha de base + recente, ambos já
|
|
5
|
+
* produzidos por `packages/evals.EvaluationEngine` — nenhuma métrica reimplementada aqui) e devolve
|
|
6
|
+
* um `AnomalyAssessment`. Nenhum `fs`/rede/SQLite — a coleta de `Observation`s por janela de tempo
|
|
7
|
+
* vive em `scripts/agent.ts`.
|
|
8
|
+
*
|
|
9
|
+
* "Dentro de Policy, não paralelo" (gap analysis original): o cálculo mora aqui, separado; a
|
|
10
|
+
* *decisão* continua sendo do `PolicyEngine`/humano — `packages/policy` ganha um campo `number`
|
|
11
|
+
* opcional (`anomalyScore`) pra consultar isto, exatamente como `riskScore` já faz pra risco
|
|
12
|
+
* (SPEC-034 D3). `detectAnomaly` nunca decide nada sozinho.
|
|
13
|
+
*/
|
|
14
|
+
import type { EvaluationReport } from '../../../contracts/src/index.ts';
|
|
15
|
+
export interface AnomalySignal {
|
|
16
|
+
readonly metric: string;
|
|
17
|
+
readonly baseline: number;
|
|
18
|
+
readonly recent: number;
|
|
19
|
+
readonly delta: number;
|
|
20
|
+
}
|
|
21
|
+
export interface AnomalyAssessment {
|
|
22
|
+
readonly agentId: string;
|
|
23
|
+
/** 0-100. */
|
|
24
|
+
readonly score: number;
|
|
25
|
+
/** 0-1 — proporcional ao menor dos dois tamanhos de amostra, nunca escondida (AC-2). */
|
|
26
|
+
readonly confidence: number;
|
|
27
|
+
readonly signals: readonly AnomalySignal[];
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* `score` = 0.5·max(0, -ΔsuccessRate) + 0.25·max(0, ΔreworkRate) + 0.25·max(0, ΔrollbackRate),
|
|
31
|
+
* escalado 0-100 — mesmo vocabulário de métricas de `computeReputationScore` (D1 do plan, SPEC-036),
|
|
32
|
+
* só o sinal muda (aqui é desvio de linha de base, não nível absoluto). Só a direção "ruim" de cada
|
|
33
|
+
* métrica conta — sucesso subindo ou retrabalho/rollback caindo nunca aumentam o score.
|
|
34
|
+
*/
|
|
35
|
+
export declare function detectAnomaly(agentId: string, baseline: EvaluationReport, recent: EvaluationReport, options?: {
|
|
36
|
+
readonly minSampleSize?: number;
|
|
37
|
+
}): AnomalyAssessment;
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @forja/engineering-monitoring — Agent Runtime Monitoring / Behavior Anomaly Engine (SPEC-040).
|
|
3
|
+
*
|
|
4
|
+
* Domínio puro: `detectAnomaly` compara dois `EvaluationReport` (linha de base + recente, ambos já
|
|
5
|
+
* produzidos por `packages/evals.EvaluationEngine` — nenhuma métrica reimplementada aqui) e devolve
|
|
6
|
+
* um `AnomalyAssessment`. Nenhum `fs`/rede/SQLite — a coleta de `Observation`s por janela de tempo
|
|
7
|
+
* vive em `scripts/agent.ts`.
|
|
8
|
+
*
|
|
9
|
+
* "Dentro de Policy, não paralelo" (gap analysis original): o cálculo mora aqui, separado; a
|
|
10
|
+
* *decisão* continua sendo do `PolicyEngine`/humano — `packages/policy` ganha um campo `number`
|
|
11
|
+
* opcional (`anomalyScore`) pra consultar isto, exatamente como `riskScore` já faz pra risco
|
|
12
|
+
* (SPEC-034 D3). `detectAnomaly` nunca decide nada sozinho.
|
|
13
|
+
*/
|
|
14
|
+
const DEFAULT_MIN_SAMPLE_SIZE = 5;
|
|
15
|
+
function signal(metric, baseline, recent) {
|
|
16
|
+
const baselineValue = baseline[metric] ?? 0;
|
|
17
|
+
const recentValue = recent[metric] ?? 0;
|
|
18
|
+
return { metric, baseline: baselineValue, recent: recentValue, delta: recentValue - baselineValue };
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* `score` = 0.5·max(0, -ΔsuccessRate) + 0.25·max(0, ΔreworkRate) + 0.25·max(0, ΔrollbackRate),
|
|
22
|
+
* escalado 0-100 — mesmo vocabulário de métricas de `computeReputationScore` (D1 do plan, SPEC-036),
|
|
23
|
+
* só o sinal muda (aqui é desvio de linha de base, não nível absoluto). Só a direção "ruim" de cada
|
|
24
|
+
* métrica conta — sucesso subindo ou retrabalho/rollback caindo nunca aumentam o score.
|
|
25
|
+
*/
|
|
26
|
+
export function detectAnomaly(agentId, baseline, recent, options) {
|
|
27
|
+
const minSampleSize = options?.minSampleSize ?? DEFAULT_MIN_SAMPLE_SIZE;
|
|
28
|
+
const signals = [
|
|
29
|
+
signal('successRate', baseline.metrics, recent.metrics),
|
|
30
|
+
signal('reworkRate', baseline.metrics, recent.metrics),
|
|
31
|
+
signal('rollbackRate', baseline.metrics, recent.metrics),
|
|
32
|
+
];
|
|
33
|
+
const [successSignal, reworkSignal, rollbackSignal] = signals;
|
|
34
|
+
const raw = 0.5 * Math.max(0, -successSignal.delta) + 0.25 * Math.max(0, reworkSignal.delta) + 0.25 * Math.max(0, rollbackSignal.delta);
|
|
35
|
+
const score = Math.min(100, Math.max(0, Math.round(raw * 100)));
|
|
36
|
+
const baselineSampleSize = baseline.metrics.observationCount ?? baseline.observationIds.length;
|
|
37
|
+
const recentSampleSize = recent.metrics.observationCount ?? recent.observationIds.length;
|
|
38
|
+
const confidence = Math.min(1, Math.min(baselineSampleSize, recentSampleSize) / minSampleSize);
|
|
39
|
+
return { agentId, score, confidence, signals };
|
|
40
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @forja/engineering-provenance — AI Code Provenance (SPEC-039).
|
|
3
|
+
*
|
|
4
|
+
* Domínio puro: `extractProvenance` mapeia um `RuntimeRun` já persistido (`packages/contracts`,
|
|
5
|
+
* `changedFiles`+`agent` já existentes) para `ProvenanceRecord[]` — um por arquivo. Nenhum `fs`/
|
|
6
|
+
* rede/SQLite aqui; a persistência (`SqliteProvenanceStore`) e a leitura do `RuntimeRun` vivem em
|
|
7
|
+
* `scripts/provenance.ts`.
|
|
8
|
+
*
|
|
9
|
+
* Granularidade é **arquivo**, não linha (AC-2, `ProvenanceRecord.lines` sempre `undefined` nesta
|
|
10
|
+
* spec) — nenhuma fonte de dado real deste repositório rastreia hunks de linha por run hoje, e
|
|
11
|
+
* fingir essa granularidade seria inventar precisão que os dados não sustentam.
|
|
12
|
+
*/
|
|
13
|
+
import type { RuntimeRun } from '../../../contracts/src/index.ts';
|
|
14
|
+
export interface ProvenanceRecord {
|
|
15
|
+
readonly file: string;
|
|
16
|
+
readonly runId: string;
|
|
17
|
+
readonly agentId: string;
|
|
18
|
+
readonly agentName: string;
|
|
19
|
+
/** Sempre `undefined` — `AgentIdentity` (o tipo de `RuntimeRun.agent`) não carrega um campo de modelo de LLM hoje. Presente no tipo para não quebrar quando uma fonte real desse dado existir. */
|
|
20
|
+
readonly model?: string;
|
|
21
|
+
/** Sempre `undefined` nesta spec — ver nota no topo do arquivo. Presente no tipo pela mesma razão de `model`. */
|
|
22
|
+
readonly lines?: readonly [number, number][];
|
|
23
|
+
readonly recordedAt: string;
|
|
24
|
+
}
|
|
25
|
+
export declare function extractProvenance(run: RuntimeRun): readonly ProvenanceRecord[];
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @forja/engineering-provenance — AI Code Provenance (SPEC-039).
|
|
3
|
+
*
|
|
4
|
+
* Domínio puro: `extractProvenance` mapeia um `RuntimeRun` já persistido (`packages/contracts`,
|
|
5
|
+
* `changedFiles`+`agent` já existentes) para `ProvenanceRecord[]` — um por arquivo. Nenhum `fs`/
|
|
6
|
+
* rede/SQLite aqui; a persistência (`SqliteProvenanceStore`) e a leitura do `RuntimeRun` vivem em
|
|
7
|
+
* `scripts/provenance.ts`.
|
|
8
|
+
*
|
|
9
|
+
* Granularidade é **arquivo**, não linha (AC-2, `ProvenanceRecord.lines` sempre `undefined` nesta
|
|
10
|
+
* spec) — nenhuma fonte de dado real deste repositório rastreia hunks de linha por run hoje, e
|
|
11
|
+
* fingir essa granularidade seria inventar precisão que os dados não sustentam.
|
|
12
|
+
*/
|
|
13
|
+
export function extractProvenance(run) {
|
|
14
|
+
return run.changedFiles.map((file) => ({
|
|
15
|
+
file,
|
|
16
|
+
runId: run.runId,
|
|
17
|
+
agentId: run.agent.id,
|
|
18
|
+
agentName: run.agent.name,
|
|
19
|
+
recordedAt: run.updatedAt,
|
|
20
|
+
}));
|
|
21
|
+
}
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @forja/engineering-risk — Change Risk Engine (SPEC-034).
|
|
3
|
+
*
|
|
4
|
+
* Domínio puro: nenhum `fs`/rede/SQLite aqui. `assessRisk` recebe métricas já coletadas por um
|
|
5
|
+
* adapter (`scripts/risk.ts`) e aplica a fórmula documentada em
|
|
6
|
+
* `docs/architecture/FORJA-3-ENGINEERING-INTELLIGENCE-ARCHITECTURE.md` §9: 7 fatores nomeados,
|
|
7
|
+
* pesos configuráveis (nunca constante escondida), cada fator carregando os `evidenceIds` que o
|
|
8
|
+
* adapter coletou — o engine nunca inventa evidência, só soma o que recebeu (AC-2).
|
|
9
|
+
*/
|
|
10
|
+
export type RiskFactorName = 'blast_radius' | 'architecture_violations' | 'security_sensitivity' | 'historical_failure_rate' | 'test_confidence' | 'reversibility' | 'deployment_complexity';
|
|
11
|
+
export type RiskWeights = Readonly<Record<RiskFactorName, number>>;
|
|
12
|
+
/** Pesos default do §9 do doc de arquitetura — somam 1.0. Sempre sobrescrevíveis via `options.weights` (AC-1). */
|
|
13
|
+
export declare const DEFAULT_RISK_WEIGHTS: RiskWeights;
|
|
14
|
+
export interface AutonomyBandThresholds {
|
|
15
|
+
/** Score máximo (inclusive) ainda considerado 'autonomous'. */
|
|
16
|
+
readonly autonomous: number;
|
|
17
|
+
/** Score máximo (inclusive) ainda 'autonomous_with_review'. */
|
|
18
|
+
readonly autonomousWithReview: number;
|
|
19
|
+
/** Score máximo (inclusive) ainda 'supervised'; acima disso, 'human_in_the_loop'. */
|
|
20
|
+
readonly supervised: number;
|
|
21
|
+
}
|
|
22
|
+
/** Faixas sugeridas na visão original (0-25/26-50/51-75/76-100) — configuração default, nunca constante fixa (AC-6). */
|
|
23
|
+
export declare const DEFAULT_AUTONOMY_BAND_THRESHOLDS: AutonomyBandThresholds;
|
|
24
|
+
export type AutonomyBand = 'autonomous' | 'autonomous_with_review' | 'supervised' | 'human_in_the_loop';
|
|
25
|
+
/**
|
|
26
|
+
* Métricas cruas já coletadas pelo adapter (grafo, `architecture:check`, `Observation` histórica,
|
|
27
|
+
* heurísticas de path). Cada campo tem seu par de evidência — nada entra no score sem rastro de
|
|
28
|
+
* onde veio (AC-2). Campos `?:` (histórico, teste) podem ser `undefined` — cold start é esperado,
|
|
29
|
+
* não erro (AC-3, D4 do plan).
|
|
30
|
+
*/
|
|
31
|
+
export interface RiskInput {
|
|
32
|
+
readonly blastRadiusCount: number;
|
|
33
|
+
readonly blastRadiusEvidenceIds: readonly string[];
|
|
34
|
+
readonly architectureViolationCount: number;
|
|
35
|
+
readonly architectureViolationEvidenceIds: readonly string[];
|
|
36
|
+
readonly sensitiveCategoriesTouched: readonly string[];
|
|
37
|
+
readonly sensitiveCategoryEvidenceIds: readonly string[];
|
|
38
|
+
readonly historicalFailureRate?: number;
|
|
39
|
+
readonly historicalEvidenceIds: readonly string[];
|
|
40
|
+
readonly testedPathsRatio?: number;
|
|
41
|
+
readonly testEvidenceIds: readonly string[];
|
|
42
|
+
readonly touchesSchemaOrMigration: boolean;
|
|
43
|
+
readonly reversibilityEvidenceIds: readonly string[];
|
|
44
|
+
readonly affectedServiceCount: number;
|
|
45
|
+
readonly totalServiceCount: number;
|
|
46
|
+
readonly deploymentEvidenceIds: readonly string[];
|
|
47
|
+
}
|
|
48
|
+
export interface RiskFactorResult {
|
|
49
|
+
readonly name: RiskFactorName;
|
|
50
|
+
readonly weight: number;
|
|
51
|
+
/** Normalizado 0-1. */
|
|
52
|
+
readonly value: number;
|
|
53
|
+
/** `false` = cold start / dado indisponível; o fator ainda participa do score (com valor neutro), mas `confidence` cai. */
|
|
54
|
+
readonly hasRealData: boolean;
|
|
55
|
+
readonly evidenceIds: readonly string[];
|
|
56
|
+
readonly rationale: string;
|
|
57
|
+
}
|
|
58
|
+
export interface ChangeRiskAssessment {
|
|
59
|
+
readonly id: string;
|
|
60
|
+
readonly changeId: string;
|
|
61
|
+
readonly createdAt: string;
|
|
62
|
+
/** 0-100. */
|
|
63
|
+
readonly score: number;
|
|
64
|
+
/** 0-1, fração de fatores com `hasRealData: true`. */
|
|
65
|
+
readonly confidence: number;
|
|
66
|
+
readonly autonomyBand: AutonomyBand;
|
|
67
|
+
readonly factors: readonly RiskFactorResult[];
|
|
68
|
+
}
|
|
69
|
+
export interface RiskAssessMeta {
|
|
70
|
+
readonly id: string;
|
|
71
|
+
readonly changeId: string;
|
|
72
|
+
readonly now: string;
|
|
73
|
+
readonly weights?: Partial<RiskWeights>;
|
|
74
|
+
readonly thresholds?: AutonomyBandThresholds;
|
|
75
|
+
}
|
|
76
|
+
export declare function assessRisk(input: RiskInput, meta: RiskAssessMeta): ChangeRiskAssessment;
|
|
77
|
+
export declare function explainAssessment(assessment: ChangeRiskAssessment): string;
|
|
78
|
+
/** Interface pequena e opcional para quem quiser injetar o engine (ex.: montar `PolicyRequest.riskScore` antes de `authorize()`) sem acoplar ao módulo inteiro. */
|
|
79
|
+
export interface RiskEngine {
|
|
80
|
+
assess(input: RiskInput, meta: {
|
|
81
|
+
readonly id: string;
|
|
82
|
+
readonly changeId: string;
|
|
83
|
+
readonly now: string;
|
|
84
|
+
}): ChangeRiskAssessment;
|
|
85
|
+
}
|
|
86
|
+
export declare function createRiskEngine(config?: {
|
|
87
|
+
readonly weights?: Partial<RiskWeights>;
|
|
88
|
+
readonly thresholds?: AutonomyBandThresholds;
|
|
89
|
+
}): RiskEngine;
|