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.
Files changed (160) hide show
  1. package/.claude/agents/release-auditor.md +19 -10
  2. package/AGENTS.md +1 -1
  3. package/CHANGELOG.md +80 -0
  4. package/DOC-MAP.md +9 -0
  5. package/README.md +85 -5
  6. package/README.pt-BR.md +34 -5
  7. package/dist/apps/dashboard/app/api/forja/[...path]/route.js +8 -1
  8. package/dist/apps/dashboard/app/api/forja/guard.d.ts +24 -0
  9. package/dist/apps/dashboard/app/api/forja/guard.js +63 -0
  10. package/dist/apps/server/src/forja-nest.module.js +9 -4
  11. package/dist/apps/server/src/main.js +10 -1
  12. package/dist/bin/forja.js +14 -2
  13. package/dist/lib/code-context.js +6 -0
  14. package/dist/lib/core/architecture-gate.d.ts +20 -0
  15. package/dist/lib/core/architecture-gate.js +60 -0
  16. package/dist/lib/core/doc-graph.js +6 -4
  17. package/dist/lib/core/drift-gate.d.ts +18 -0
  18. package/dist/lib/core/drift-gate.js +55 -0
  19. package/dist/lib/core/gates.d.ts +9 -2
  20. package/dist/lib/core/gates.js +13 -2
  21. package/dist/lib/core/health.js +15 -0
  22. package/dist/lib/core/incident-search.d.ts +19 -0
  23. package/dist/lib/core/incident-search.js +32 -0
  24. package/dist/lib/core/model-pricing.d.ts +31 -0
  25. package/dist/lib/core/model-pricing.js +74 -0
  26. package/dist/lib/core/registry.d.ts +248 -0
  27. package/dist/lib/core/registry.js +249 -0
  28. package/dist/lib/core/release.d.ts +247 -0
  29. package/dist/lib/core/release.js +5 -1
  30. package/dist/lib/core/risk-collect.d.ts +19 -0
  31. package/dist/lib/core/risk-collect.js +173 -0
  32. package/dist/lib/drift-sentinel.d.ts +59 -0
  33. package/dist/lib/drift-sentinel.js +126 -0
  34. package/dist/lib/generators/memory-generator.js +8 -6
  35. package/dist/lib/generators/nest-generator.js +24 -10
  36. package/dist/lib/project-upgrade.js +1 -1
  37. package/dist/lib/workspace.d.ts +7 -0
  38. package/dist/lib/workspace.js +34 -5
  39. package/dist/packages/adapter-git/src/index.d.ts +1 -1
  40. package/dist/packages/adapter-git/src/index.js +11 -6
  41. package/dist/packages/adapter-nest/src/index.d.ts +19 -0
  42. package/dist/packages/adapter-nest/src/index.js +26 -1
  43. package/dist/packages/adapter-sqlite/src/index.d.ts +27 -1
  44. package/dist/packages/adapter-sqlite/src/index.js +49 -0
  45. package/dist/packages/contracts/src/index.d.ts +33 -0
  46. package/dist/packages/contracts/src/index.js +13 -0
  47. package/dist/packages/core/src/index.d.ts +12 -0
  48. package/dist/packages/core/src/index.js +29 -0
  49. package/dist/packages/engineering/architecture/src/index.d.ts +76 -0
  50. package/dist/packages/engineering/architecture/src/index.js +131 -0
  51. package/dist/packages/engineering/evidence/src/index.d.ts +41 -0
  52. package/dist/packages/engineering/evidence/src/index.js +31 -0
  53. package/dist/packages/engineering/identity/src/index.d.ts +57 -0
  54. package/dist/packages/engineering/identity/src/index.js +88 -0
  55. package/dist/packages/engineering/monitoring/src/index.d.ts +37 -0
  56. package/dist/packages/engineering/monitoring/src/index.js +40 -0
  57. package/dist/packages/engineering/provenance/src/index.d.ts +25 -0
  58. package/dist/packages/engineering/provenance/src/index.js +21 -0
  59. package/dist/packages/engineering/risk/src/index.d.ts +89 -0
  60. package/dist/packages/engineering/risk/src/index.js +120 -0
  61. package/dist/packages/graph/src/index.d.ts +23 -1
  62. package/dist/packages/graph/src/index.js +88 -15
  63. package/dist/packages/llm/src/index.d.ts +43 -0
  64. package/dist/packages/llm/src/index.js +131 -0
  65. package/dist/packages/mcp/src/index.js +27 -8
  66. package/dist/packages/orchestration/src/index.d.ts +11 -1
  67. package/dist/packages/orchestration/src/index.js +34 -7
  68. package/dist/packages/policy/src/index.d.ts +40 -0
  69. package/dist/packages/policy/src/index.js +39 -4
  70. package/dist/packages/runtime/src/index.js +3 -0
  71. package/dist/packages/sandbox/src/index.d.ts +47 -0
  72. package/dist/packages/sandbox/src/index.js +59 -0
  73. package/dist/packages/validator/src/index.d.ts +8 -0
  74. package/dist/packages/validator/src/index.js +21 -6
  75. package/dist/scripts/adr.d.ts +17 -0
  76. package/dist/scripts/adr.js +152 -0
  77. package/dist/scripts/agent-harness.js +14 -4
  78. package/dist/scripts/agent.d.ts +27 -0
  79. package/dist/scripts/agent.js +249 -0
  80. package/dist/scripts/architecture.d.ts +16 -0
  81. package/dist/scripts/architecture.js +186 -0
  82. package/dist/scripts/cost-economy.d.ts +2 -0
  83. package/dist/scripts/cost-economy.js +79 -0
  84. package/dist/scripts/demo-autonomy.js +15 -8
  85. package/dist/scripts/demo-workspace.d.ts +6 -0
  86. package/dist/scripts/demo-workspace.js +101 -0
  87. package/dist/scripts/drift-check.d.ts +17 -0
  88. package/dist/scripts/drift-check.js +63 -0
  89. package/dist/scripts/engineer.d.ts +20 -0
  90. package/dist/scripts/engineer.js +208 -0
  91. package/dist/scripts/evidence.d.ts +12 -0
  92. package/dist/scripts/evidence.js +55 -0
  93. package/dist/scripts/gates.d.ts +6 -2
  94. package/dist/scripts/gates.js +14 -4
  95. package/dist/scripts/incident.d.ts +19 -0
  96. package/dist/scripts/incident.js +103 -0
  97. package/dist/scripts/llm-fit.js +160 -0
  98. package/dist/scripts/provenance.d.ts +14 -0
  99. package/dist/scripts/provenance.js +114 -0
  100. package/dist/scripts/risk.d.ts +15 -0
  101. package/dist/scripts/risk.js +81 -0
  102. package/dist/scripts/simulate.d.ts +20 -0
  103. package/dist/scripts/simulate.js +150 -0
  104. package/dist/scripts/sync-universal-memory.js +19 -6
  105. package/docs/architecture/FORJA-3-ENGINEERING-INTELLIGENCE-ARCHITECTURE.md +442 -0
  106. package/docs/llm-fit-loop.md +41 -0
  107. package/docs/modos-de-operacao.md +52 -0
  108. package/docs/produto/factsheet-marketing.md +151 -0
  109. package/docs/produto/roteiro-demo.md +47 -0
  110. package/memory/40-delivery/current-sprint.md +3 -6
  111. package/memory/90-decisions/0074-llm-fit-loop-cli-adapters.md +51 -0
  112. package/memory/90-decisions/0075-workspace-demo-isolado.md +43 -0
  113. package/memory/90-decisions/0076-modos-embedded-e-studio.md +43 -0
  114. package/memory/90-decisions/0077-cost-aware-autonomy-budget.md +95 -0
  115. package/memory/90-decisions/0078-forjajs-3-engineering-control-plane.md +116 -0
  116. package/memory/90-decisions/0079-autonomous-maintenance-readiness.md +102 -0
  117. package/package.json +9 -2
  118. package/specs/agent-identity-reputation/plan.md +133 -0
  119. package/specs/agent-identity-reputation/spec.md +125 -0
  120. package/specs/agent-identity-reputation/tasks.md +51 -0
  121. package/specs/agent-runtime-monitoring/plan.md +78 -0
  122. package/specs/agent-runtime-monitoring/spec.md +92 -0
  123. package/specs/agent-runtime-monitoring/tasks.md +39 -0
  124. package/specs/ai-code-provenance/plan.md +71 -0
  125. package/specs/ai-code-provenance/spec.md +97 -0
  126. package/specs/ai-code-provenance/tasks.md +39 -0
  127. package/specs/architecture-constitution/plan.md +110 -0
  128. package/specs/architecture-constitution/spec.md +114 -0
  129. package/specs/architecture-constitution/tasks.md +58 -0
  130. package/specs/change-risk-engine/plan.md +130 -0
  131. package/specs/change-risk-engine/spec.md +119 -0
  132. package/specs/change-risk-engine/tasks.md +72 -0
  133. package/specs/cost-aware-autonomy-budget/spec.md +102 -0
  134. package/specs/drift-sentinel/spec.md +117 -0
  135. package/specs/engineer-facade-extension/plan.md +71 -0
  136. package/specs/engineer-facade-extension/spec.md +98 -0
  137. package/specs/engineer-facade-extension/tasks.md +36 -0
  138. package/specs/engineering-evidence-ledger/plan.md +121 -0
  139. package/specs/engineering-evidence-ledger/spec.md +90 -0
  140. package/specs/engineering-evidence-ledger/tasks.md +54 -0
  141. package/specs/engineering-graph-extensions/plan.md +92 -0
  142. package/specs/engineering-graph-extensions/spec.md +101 -0
  143. package/specs/engineering-graph-extensions/tasks.md +60 -0
  144. package/specs/engineering-intelligence/spec.md +177 -0
  145. package/specs/learning-loop-incidents/plan.md +59 -0
  146. package/specs/learning-loop-incidents/spec.md +93 -0
  147. package/specs/learning-loop-incidents/tasks.md +36 -0
  148. package/specs/predictive-change-simulation/plan.md +109 -0
  149. package/specs/predictive-change-simulation/spec.md +107 -0
  150. package/specs/predictive-change-simulation/tasks.md +41 -0
  151. package/specs/release-auditor-health/plan.md +88 -0
  152. package/specs/release-auditor-health/spec.md +82 -0
  153. package/specs/release-auditor-health/tasks.md +72 -0
  154. package/specs/smart-agent-routing/plan.md +55 -0
  155. package/specs/smart-agent-routing/spec.md +85 -0
  156. package/specs/smart-agent-routing/tasks.md +26 -0
  157. package/dist/scripts/server-persistence-probe.d.ts +0 -1
  158. package/dist/scripts/server-persistence-probe.js +0 -52
  159. package/dist/scripts/server-persistence-probe.mjs +0 -52
  160. /package/dist/scripts/{server-persistence-probe.d.mts → llm-fit.d.ts} +0 -0
@@ -50,7 +50,7 @@ export class SprintEngine {
50
50
  if (sprint.taskIds.includes(taskId))
51
51
  return sprint;
52
52
  const updated = this.updated(sprint, { taskIds: [...sprint.taskIds, taskId] });
53
- await this.store.saveSprint(updated);
53
+ await this.saveSprintGuarded(sprint, updated);
54
54
  await this.record('sprint', updated.id, [taskId], updated.evidenceIds);
55
55
  return updated;
56
56
  }
@@ -65,7 +65,7 @@ export class SprintEngine {
65
65
  if (result.status !== 'accepted')
66
66
  throw new OrchestrationError(`Sprint validation did not accept completion: ${result.status}`);
67
67
  const updated = this.updated(sprint, { status: 'completed', evidenceIds: this.unique([...sprint.evidenceIds, ...this.evidenceFrom(result)]) });
68
- await this.store.saveSprint(updated);
68
+ await this.saveSprintGuarded(sprint, updated);
69
69
  await this.record('sprint', updated.id, updated.taskIds, updated.evidenceIds);
70
70
  return updated;
71
71
  }
@@ -74,10 +74,22 @@ export class SprintEngine {
74
74
  if (!allowed.includes(sprint.status))
75
75
  throw new OrchestrationError(`Invalid sprint transition from ${sprint.status} to ${status}`);
76
76
  const updated = this.updated(sprint, { status });
77
- await this.store.saveSprint(updated);
77
+ await this.saveSprintGuarded(sprint, updated);
78
78
  await this.record('sprint', updated.id, updated.taskIds, updated.evidenceIds);
79
79
  return updated;
80
80
  }
81
+ /**
82
+ * Read-modify-write without this is a lost-update race: two concurrent callers can both read
83
+ * the same `sprint`, compute different `updated` values, and the second `saveSprint` silently
84
+ * clobbers the first. Re-checking `updatedAt` immediately before writing narrows that window to
85
+ * the store's own read/write latency instead of this method's full async body.
86
+ */
87
+ async saveSprintGuarded(before, after) {
88
+ const current = await this.store.getSprint(before.id);
89
+ if (current === undefined || current.updatedAt !== before.updatedAt)
90
+ throw new OrchestrationError(`Sprint was modified concurrently: ${before.id}`);
91
+ await this.store.saveSprint(after);
92
+ }
81
93
  async requireSprint(id) { const value = await this.store.getSprint(id); if (!value)
82
94
  throw new OrchestrationError(`Sprint not found: ${id}`); return value; }
83
95
  async record(kind, id, relatedIds, evidenceIds) { if (this.graph)
@@ -126,11 +138,11 @@ export class TaskEngine {
126
138
  if (task.status !== 'todo' && task.status !== 'blocked')
127
139
  throw new OrchestrationError(`Invalid task start from ${task.status}`);
128
140
  const updated = this.updated(task, { status: 'in_progress' });
129
- await this.store.saveTask(updated);
141
+ await this.saveTaskGuarded(task, updated);
130
142
  return updated;
131
143
  }
132
144
  async block(id) { const task = await this.require(id); if (task.status !== 'in_progress')
133
- throw new OrchestrationError('Only an in-progress task can be blocked'); const updated = this.updated(task, { status: 'blocked' }); await this.store.saveTask(updated); return updated; }
145
+ throw new OrchestrationError('Only an in-progress task can be blocked'); const updated = this.updated(task, { status: 'blocked' }); await this.saveTaskGuarded(task, updated); return updated; }
134
146
  async complete(id, validator) {
135
147
  const task = await this.require(id);
136
148
  if (task.status !== 'in_progress')
@@ -140,11 +152,18 @@ export class TaskEngine {
140
152
  throw new OrchestrationError(`Task validation did not accept completion: ${result.status}`);
141
153
  const evidenceIds = this.unique([...task.evidenceIds, ...result.checks.flatMap((check) => check.evidenceIds)]);
142
154
  const updated = this.updated(task, { status: 'done', evidenceIds });
143
- await this.store.saveTask(updated);
155
+ await this.saveTaskGuarded(task, updated);
144
156
  if (this.graph)
145
157
  await this.graph.record({ kind: 'task', id: updated.id, relatedIds: [updated.sprintId, ...updated.dependencyIds], evidenceIds });
146
158
  return updated;
147
159
  }
160
+ /** See SprintEngine.saveSprintGuarded — same lost-update race, same narrowing mitigation. */
161
+ async saveTaskGuarded(before, after) {
162
+ const current = await this.store.getTask(before.id);
163
+ if (current === undefined || current.updatedAt !== before.updatedAt)
164
+ throw new OrchestrationError(`Task was modified concurrently: ${before.id}`);
165
+ await this.store.saveTask(after);
166
+ }
148
167
  async require(id) { const value = await this.store.getTask(id); if (!value)
149
168
  throw new OrchestrationError(`Task not found: ${id}`); return value; }
150
169
  updated(value, changes) { return { ...value, ...changes, updatedAt: new Date().toISOString() }; }
@@ -156,7 +175,8 @@ export class HandoffEngine {
156
175
  graph;
157
176
  maxItems;
158
177
  maxItemLength;
159
- constructor(store, graph, maxItems = 20, maxItemLength = 500) { this.store = store; this.graph = graph; this.maxItems = maxItems; this.maxItemLength = maxItemLength; }
178
+ maxHandoffsPerCorrelation;
179
+ constructor(store, graph, maxItems = 20, maxItemLength = 500, maxHandoffsPerCorrelation = 200) { this.store = store; this.graph = graph; this.maxItems = maxItems; this.maxItemLength = maxItemLength; this.maxHandoffsPerCorrelation = maxHandoffsPerCorrelation; }
160
180
  async create(input) {
161
181
  for (const [name, value] of Object.entries({ from: input.from, to: input.to, intent: input.intent, objective: input.objective, nextAgent: input.nextAgent }))
162
182
  if (value.trim().length === 0)
@@ -166,6 +186,13 @@ export class HandoffEngine {
166
186
  if (input.evidenceIds.length === 0)
167
187
  throw new OrchestrationError('Handoff requires evidence references');
168
188
  const fields = { schemaVersion: CONTRACT_VERSION, createdAt: new Date().toISOString(), updatedAt: new Date().toISOString(), correlationId: input.correlationId ?? `handoff:${input.intent}` };
189
+ // Nothing else bounds how many handoffs a single run can chain through (A→B→A→B→… has no
190
+ // structural cycle marker to detect), so this is the circuit breaker: past this count for one
191
+ // correlationId, something is looping without a human/gate in the loop, and it should fail
192
+ // loudly rather than accumulate audit records forever.
193
+ const priorForRun = (await this.store.listHandoffs()).filter((handoff) => handoff.correlationId === fields.correlationId).length;
194
+ if (priorForRun >= this.maxHandoffsPerCorrelation)
195
+ throw new OrchestrationError(`Handoff chain exceeded ${this.maxHandoffsPerCorrelation} handoffs for correlationId ${fields.correlationId} — likely an unbounded loop`);
169
196
  const value = { ...fields, id: randomUUID(), from: input.from.trim(), to: input.to.trim(), intent: input.intent.trim(), objective: input.objective.trim(), completedWork: this.compact(input.completedWork), decisions: this.compact(input.decisions), constraints: this.compact(input.constraints), pending: this.compact(input.pending), evidenceIds: [...new Set(input.evidenceIds)], acceptance: this.compact(input.acceptance), blockers: this.compact(input.blockers), nextAgent: input.nextAgent.trim() };
170
197
  await this.store.saveHandoff(value);
171
198
  if (this.graph)
@@ -9,12 +9,32 @@ export interface PolicyScope {
9
9
  readonly risks?: readonly RiskLevel[];
10
10
  readonly categories?: readonly PolicyCategory[];
11
11
  readonly pathPrefixes?: readonly string[];
12
+ /**
13
+ * Faixa opcional de `ChangeRiskAssessment.score` (0-100, SPEC-034) que a regra se aplica a.
14
+ * `PolicyRequest.riskScore` é um `number` puro, não o assessment inteiro — este pacote nunca
15
+ * importa `@forja/engineering-risk` (AC-5); quem calcula o score chama `RiskEngine.assess()`
16
+ * antes de montar o `PolicyRequest`.
17
+ */
18
+ readonly riskScoreRange?: readonly [number, number];
19
+ /**
20
+ * Faixa opcional de `AnomalyAssessment.score` (0-100, SPEC-040) que a regra se aplica a. Mesmo
21
+ * padrão exato de `riskScoreRange`: `PolicyRequest.anomalyScore` é um `number` puro, não o
22
+ * assessment inteiro — este pacote nunca importa `@forja/engineering-monitoring`; quem calcula o
23
+ * score chama `detectAnomaly()` antes de montar o `PolicyRequest`.
24
+ */
25
+ readonly anomalyScoreRange?: readonly [number, number];
12
26
  }
13
27
  export interface PolicyLimits {
14
28
  readonly maxTokens?: number;
15
29
  readonly maxFiles?: number;
16
30
  readonly maxDurationMs?: number;
17
31
  readonly maxRetries?: number;
32
+ /**
33
+ * Real dollar ceiling per execution (SPEC-029). Enforced the same way as maxFiles/maxTokens, in
34
+ * `CapabilityRegistry.checkLimits` — see that method for why this is a `checkLimits` concern and
35
+ * not part of rule matching. Optional so every existing rule keeps working unchanged.
36
+ */
37
+ readonly maxCostUsd?: number;
18
38
  }
19
39
  export interface PolicyRule {
20
40
  readonly id: string;
@@ -34,6 +54,14 @@ export interface ApprovalDetails {
34
54
  export interface PolicyRequest {
35
55
  readonly definition: CapabilityDefinition;
36
56
  readonly agent: AgentIdentity;
57
+ /**
58
+ * Identifies the run/action this decision belongs to. Required for approvals to actually
59
+ * resolve: without a stable key, every retry of the same step looks like a brand-new request
60
+ * and `authorize()` can never see that a human already approved it. Callers that omit this
61
+ * fall back to `agent.id`, which only works correctly for an agent with a single in-flight
62
+ * approval at a time.
63
+ */
64
+ readonly correlationId?: string;
37
65
  readonly projectId?: string;
38
66
  readonly environment: string;
39
67
  readonly categories: readonly string[];
@@ -41,6 +69,10 @@ export interface PolicyRequest {
41
69
  readonly budget?: TokenBudget;
42
70
  readonly now: ISO8601;
43
71
  readonly approval?: ApprovalDetails;
72
+ /** Score 0-100 de um `ChangeRiskAssessment` já calculado (SPEC-034) — ver `PolicyScope.riskScoreRange`. */
73
+ readonly riskScore?: number;
74
+ /** Score 0-100 de um `AnomalyAssessment` já calculado (SPEC-040) — ver `PolicyScope.anomalyScoreRange`. */
75
+ readonly anomalyScore?: number;
44
76
  }
45
77
  export interface ApprovalDecision {
46
78
  readonly decision: 'approved' | 'rejected';
@@ -66,6 +98,8 @@ export declare class ApprovalLedger {
66
98
  list(): readonly ApprovalRequest[];
67
99
  decide(id: EntityId, decision: ApprovalDecision): ApprovalRequest;
68
100
  expire(now: ISO8601): readonly ApprovalRequest[];
101
+ /** Most recent approval request recorded for this correlationId, if any. */
102
+ findByCorrelationId(correlationId: string): ApprovalRequest | undefined;
69
103
  get(id: EntityId): ApprovalRequest;
70
104
  }
71
105
  export declare class PolicyEngine {
@@ -79,6 +113,12 @@ export declare class PolicyEngine {
79
113
  });
80
114
  authorize(request: PolicyRequest): PolicyDecision;
81
115
  get approvals(): ApprovalLedger;
116
+ /**
117
+ * Resolves approval state for `request` instead of unconditionally demanding a fresh one.
118
+ * Keyed by `request.correlationId` (falling back to the agent id) so that resuming/retrying
119
+ * the same run recognizes a decision a human already made, rather than re-issuing an
120
+ * unresolvable `REQUIRE_APPROVAL` on every attempt — see ADR/finding on approval resume.
121
+ */
82
122
  private withApproval;
83
123
  private matches;
84
124
  private validateRules;
@@ -1,5 +1,5 @@
1
1
  import { randomUUID } from 'node:crypto';
2
- import { CONTRACT_VERSION, } from "../../contracts/src/index.js";
2
+ import { CONTRACT_VERSION, isPathWithinRoot, } from "../../contracts/src/index.js";
3
3
  export class PolicyError extends Error {
4
4
  constructor(message) {
5
5
  super(message);
@@ -61,6 +61,11 @@ export class ApprovalLedger {
61
61
  }
62
62
  return expired;
63
63
  }
64
+ /** Most recent approval request recorded for this correlationId, if any. */
65
+ findByCorrelationId(correlationId) {
66
+ const matches = this.list().filter((request) => request.correlationId === correlationId);
67
+ return matches.at(-1);
68
+ }
64
69
  get(id) {
65
70
  const request = this.requests.get(id);
66
71
  if (request === undefined && this.store !== undefined) {
@@ -90,7 +95,10 @@ export class PolicyEngine {
90
95
  const decision = match === undefined
91
96
  ? { effect: 'DENY', reason: 'No matching policy rule', policyId: 'default-deny' }
92
97
  : { effect: match.effect, reason: match.reason, policyId: match.id, ...(match.limits === undefined ? {} : { limits: this.asNumericLimits(match.limits) }) };
93
- if (this.approvalRequiredRisks.includes(request.definition.risk) && decision.effect === 'ALLOW') {
98
+ // ALLOW_WITH_LIMITS still grants execution — a critical-risk capability must not skip
99
+ // approval just because a rule chose to bound it with limits instead of an unconditional ALLOW.
100
+ const isGranting = decision.effect === 'ALLOW' || decision.effect === 'ALLOW_WITH_LIMITS';
101
+ if (this.approvalRequiredRisks.includes(request.definition.risk) && isGranting) {
94
102
  return this.withApproval(request, decision, 'Risk requires explicit approval');
95
103
  }
96
104
  if (decision.effect === 'REQUIRE_APPROVAL')
@@ -100,10 +108,33 @@ export class PolicyEngine {
100
108
  get approvals() {
101
109
  return this.approvalLedger;
102
110
  }
111
+ /**
112
+ * Resolves approval state for `request` instead of unconditionally demanding a fresh one.
113
+ * Keyed by `request.correlationId` (falling back to the agent id) so that resuming/retrying
114
+ * the same run recognizes a decision a human already made, rather than re-issuing an
115
+ * unresolvable `REQUIRE_APPROVAL` on every attempt — see ADR/finding on approval resume.
116
+ */
103
117
  withApproval(request, decision, reason) {
118
+ const correlationId = request.correlationId ?? request.agent.id;
119
+ const existing = this.approvalLedger.findByCorrelationId(correlationId);
120
+ if (existing !== undefined) {
121
+ if (existing.decision === 'approved') {
122
+ // `decision.effect` may already be ALLOW/ALLOW_WITH_LIMITS (gated only by the risk-level
123
+ // approval requirement) — keep it as-is. But when the *rule itself* is REQUIRE_APPROVAL,
124
+ // that's a gate, not a final verdict: once approved, it must resolve to a grant, or every
125
+ // retry would see the same rule match and stay stuck at REQUIRE_APPROVAL forever.
126
+ const effect = decision.effect === 'ALLOW' || decision.effect === 'ALLOW_WITH_LIMITS' ? decision.effect : decision.limits === undefined ? 'ALLOW' : 'ALLOW_WITH_LIMITS';
127
+ return { ...decision, effect, reason: 'Approval granted', approvalRequestId: existing.id };
128
+ }
129
+ if (existing.decision === 'rejected')
130
+ return { ...decision, effect: 'DENY', reason: `Approval rejected: ${existing.id}`, approvalRequestId: existing.id };
131
+ if (existing.decision === undefined)
132
+ return { ...decision, effect: 'REQUIRE_APPROVAL', reason, approvalRequestId: existing.id };
133
+ // existing.decision === 'expired': falls through to issue a fresh request below.
134
+ }
104
135
  if (request.approval === undefined)
105
136
  return { ...decision, effect: 'REQUIRE_APPROVAL', reason };
106
- const approval = this.approvalLedger.create({ ...request.approval, correlationId: request.agent.id }, request.now);
137
+ const approval = this.approvalLedger.create({ ...request.approval, correlationId }, request.now);
107
138
  return { ...decision, effect: 'REQUIRE_APPROVAL', reason, approvalRequestId: approval.id };
108
139
  }
109
140
  matches(scope, request) {
@@ -121,7 +152,11 @@ export class PolicyEngine {
121
152
  return false;
122
153
  if (scope.categories !== undefined && !scope.categories.some((category) => request.categories.includes(category)))
123
154
  return false;
124
- if (scope.pathPrefixes !== undefined && !request.files.every((file) => scope.pathPrefixes?.some((prefix) => file.startsWith(prefix))))
155
+ if (scope.pathPrefixes !== undefined && !request.files.every((file) => scope.pathPrefixes?.some((prefix) => isPathWithinRoot(prefix, file))))
156
+ return false;
157
+ if (scope.riskScoreRange !== undefined && (request.riskScore === undefined || request.riskScore < scope.riskScoreRange[0] || request.riskScore > scope.riskScoreRange[1]))
158
+ return false;
159
+ if (scope.anomalyScoreRange !== undefined && (request.anomalyScore === undefined || request.anomalyScore < scope.anomalyScoreRange[0] || request.anomalyScore > scope.anomalyScoreRange[1]))
125
160
  return false;
126
161
  return true;
127
162
  }
@@ -123,6 +123,9 @@ export class RuntimeEngine {
123
123
  input: { capabilityId: step.capabilityId, payload: step.payload },
124
124
  agent: run.agent,
125
125
  policy: this.policies.get(runId) ?? (() => { throw new RuntimeError('Runtime policy is missing'); })(),
126
+ // Stable across retries/resume of the same run — without it every attempt looks like a
127
+ // brand-new approval request and a human's decision can never be recognized on retry.
128
+ correlationId: runId,
126
129
  projectId: step.projectId,
127
130
  environment: step.environment,
128
131
  categories: step.categories,
@@ -64,3 +64,50 @@ export declare class SandboxEngine {
64
64
  private checksum;
65
65
  private audit;
66
66
  }
67
+ export interface SandboxedCapabilityOptions<T> {
68
+ readonly sandbox: SandboxEngine;
69
+ readonly runId: RunId;
70
+ /** Directory the isolated worktree/copy is created at — never the live project root. */
71
+ readonly root: string;
72
+ readonly backend?: SandboxSession['backend'];
73
+ readonly correlationId?: string;
74
+ /**
75
+ * Does the actual work: write files under `session.root` (never outside it), and run whatever
76
+ * verification the capability needs via `sandbox.execute(session.id, ...)` on the same instance
77
+ * passed in `options.sandbox`. Its return value is threaded through untouched as `workResult`.
78
+ */
79
+ readonly work: (session: SandboxSession) => T | Promise<T>;
80
+ }
81
+ export type SandboxedCapabilityOutcome = 'promoted' | 'rejected' | 'failed';
82
+ export interface SandboxedCapabilityResult<T> {
83
+ readonly session: SandboxSession;
84
+ readonly outcome: SandboxedCapabilityOutcome;
85
+ readonly workResult?: T;
86
+ readonly validation?: SandboxValidation;
87
+ readonly diff?: SandboxDiff;
88
+ readonly error?: unknown;
89
+ }
90
+ /**
91
+ * The create→prepare→work→validate→diff→promote(-or-reject/rollback)→destroy lifecycle, as a
92
+ * single call instead of hand-rolled per call site. Extracted from `scripts/demo-autonomy.ts`,
93
+ * which proved the pattern for one capability (`fixture.code.write`) — this is that same pattern
94
+ * made reusable, so a future capability that edits real project files has a paved, tested path to
95
+ * real isolation instead of either reinventing this state machine or (as every capability
96
+ * registered in `apps/cli/src/index.ts` does today) skipping isolation entirely because none of
97
+ * them currently write to project source — see docs/security/2026-08-31 audit for why that's
98
+ * currently fine and when it stops being fine: the moment a capability's handler starts writing
99
+ * to arbitrary project files, it needs to go through this, not straight `fs`/`spawnSync` on the
100
+ * live tree.
101
+ *
102
+ * Always destroys the session before returning, on every outcome — a caller never has to remember
103
+ * cleanup. Never throws for a rejected/failed *validation* (that's a normal outcome, reported via
104
+ * the return value); only rethrows if `options.work` itself throws, after best-effort cleanup.
105
+ *
106
+ * `options.work` must call `sandbox.execute(session.id, ...)` (on the same `sandbox` passed in
107
+ * `options.sandbox`) at least once before returning: `SandboxEngine.validate()` requires the
108
+ * session to already be in the `'validating'` state, and only `execute()` puts it there — this
109
+ * mirrors `demo-autonomy.ts`'s own capability handler, which always runs its verification command
110
+ * (`npm test` in the worktree) before considering the edit done. Writing files without ever
111
+ * calling `execute()` is a caller error, not something this helper can validate away.
112
+ */
113
+ export declare function runSandboxedCapability<T>(options: SandboxedCapabilityOptions<T>): Promise<SandboxedCapabilityResult<T>>;
@@ -116,3 +116,62 @@ export class SandboxEngine {
116
116
  checksum(value) { return createHash('sha256').update(JSON.stringify({ files: [...value.files].sort(), additions: value.additions, deletions: value.deletions, evidenceIds: [...value.evidenceIds].sort() })).digest('hex'); }
117
117
  audit(correlationId, value) { const now = new Date().toISOString(); return { ...value, schemaVersion: CONTRACT_VERSION, createdAt: now, updatedAt: now, correlationId }; }
118
118
  }
119
+ /**
120
+ * The create→prepare→work→validate→diff→promote(-or-reject/rollback)→destroy lifecycle, as a
121
+ * single call instead of hand-rolled per call site. Extracted from `scripts/demo-autonomy.ts`,
122
+ * which proved the pattern for one capability (`fixture.code.write`) — this is that same pattern
123
+ * made reusable, so a future capability that edits real project files has a paved, tested path to
124
+ * real isolation instead of either reinventing this state machine or (as every capability
125
+ * registered in `apps/cli/src/index.ts` does today) skipping isolation entirely because none of
126
+ * them currently write to project source — see docs/security/2026-08-31 audit for why that's
127
+ * currently fine and when it stops being fine: the moment a capability's handler starts writing
128
+ * to arbitrary project files, it needs to go through this, not straight `fs`/`spawnSync` on the
129
+ * live tree.
130
+ *
131
+ * Always destroys the session before returning, on every outcome — a caller never has to remember
132
+ * cleanup. Never throws for a rejected/failed *validation* (that's a normal outcome, reported via
133
+ * the return value); only rethrows if `options.work` itself throws, after best-effort cleanup.
134
+ *
135
+ * `options.work` must call `sandbox.execute(session.id, ...)` (on the same `sandbox` passed in
136
+ * `options.sandbox`) at least once before returning: `SandboxEngine.validate()` requires the
137
+ * session to already be in the `'validating'` state, and only `execute()` puts it there — this
138
+ * mirrors `demo-autonomy.ts`'s own capability handler, which always runs its verification command
139
+ * (`npm test` in the worktree) before considering the edit done. Writing files without ever
140
+ * calling `execute()` is a caller error, not something this helper can validate away.
141
+ */
142
+ export async function runSandboxedCapability(options) {
143
+ const { sandbox } = options;
144
+ const session = await sandbox.create({ runId: options.runId, root: options.root, backend: options.backend, correlationId: options.correlationId });
145
+ try {
146
+ await sandbox.prepare(session.id);
147
+ const workResult = await options.work(session);
148
+ const validation = await sandbox.validate(session.id);
149
+ if (validation.status !== 'accepted') {
150
+ // `validate()` already moved the session to 'rejected' when validation.status is itself
151
+ // 'rejected'; for 'blocked'/'inconclusive' it stays 'validating', so reject() is still a
152
+ // valid transition. Try it either way and ignore the "already rejected" case.
153
+ try {
154
+ await sandbox.reject(session.id);
155
+ }
156
+ catch { /* already in a terminal reject state */ }
157
+ const destroyed = await sandbox.destroy(session.id);
158
+ return { session: destroyed, outcome: 'rejected', workResult, validation };
159
+ }
160
+ const diff = await sandbox.diff(session.id);
161
+ await sandbox.promote(session.id, diff);
162
+ const destroyed = await sandbox.destroy(session.id);
163
+ return { session: destroyed, outcome: 'promoted', workResult, validation, diff };
164
+ }
165
+ catch (error) {
166
+ try {
167
+ await sandbox.reject(session.id);
168
+ }
169
+ catch { /* already in a terminal reject state */ }
170
+ let destroyed = session;
171
+ try {
172
+ destroyed = await sandbox.destroy(session.id);
173
+ }
174
+ catch { /* best-effort — nothing more we can do */ }
175
+ return { session: destroyed, outcome: 'failed', error };
176
+ }
177
+ }
@@ -31,6 +31,14 @@ export declare class ValidatorError extends Error {
31
31
  constructor(message: string);
32
32
  }
33
33
  export declare class DeterministicValidator {
34
+ /**
35
+ * A `passed: true` claim with no evidenceIds is unsubstantiated: this validator has no way to
36
+ * confirm the check actually ran (it never executes build/test/lint/typecheck itself — it only
37
+ * aggregates what the caller reports), so an evidence-free "passed" is treated as not passed
38
+ * rather than taken on faith. The internally-computed `scope` check is exempt: it's derived
39
+ * here from `changedFiles`/`plan`, not asserted by the caller, so it needs no evidence pointer.
40
+ */
41
+ private substantiated;
34
42
  validate(request: ValidationRequest): EvaluationResult;
35
43
  private summary;
36
44
  }
@@ -6,16 +6,31 @@ export class ValidatorError extends Error {
6
6
  }
7
7
  }
8
8
  export class DeterministicValidator {
9
+ /**
10
+ * A `passed: true` claim with no evidenceIds is unsubstantiated: this validator has no way to
11
+ * confirm the check actually ran (it never executes build/test/lint/typecheck itself — it only
12
+ * aggregates what the caller reports), so an evidence-free "passed" is treated as not passed
13
+ * rather than taken on faith. The internally-computed `scope` check is exempt: it's derived
14
+ * here from `changedFiles`/`plan`, not asserted by the caller, so it needs no evidence pointer.
15
+ */
16
+ substantiated(item) {
17
+ return item.passed && item.evidenceIds.length > 0;
18
+ }
9
19
  validate(request) {
10
20
  const required = request.requiredChecks ?? ['build', 'tests', 'lint', 'typecheck'];
11
- const checks = [...request.checks];
21
+ const scopeCheckName = 'scope';
12
22
  const allowedFiles = request.plan.steps.flatMap((step) => step.allowedFiles);
13
23
  const outOfScope = request.changedFiles.filter((file) => !allowedFiles.some((allowed) => allowed === file || allowed === '*' || (allowed.endsWith('/') && file.startsWith(allowed))));
14
- checks.push({ name: 'scope', passed: outOfScope.length === 0, evidenceIds: [], detail: outOfScope.length === 0 ? 'All changed files are within plan scope' : `Out of scope: ${outOfScope.join(', ')}` });
24
+ const scopeCheck = { name: scopeCheckName, passed: outOfScope.length === 0, evidenceIds: [], detail: outOfScope.length === 0 ? 'All changed files are within plan scope' : `Out of scope: ${outOfScope.join(', ')}` };
25
+ const checks = [...request.checks, scopeCheck];
26
+ // A validation that reports zero checks and zero acceptance results proves nothing, no matter
27
+ // how empty `requiredChecks` is set — without this, an empty `checks`/`acceptance`/
28
+ // `requiredChecks` trio sails straight through every other condition below as "accepted".
29
+ const noWorkReported = request.checks.length === 0 && request.acceptance.length === 0;
15
30
  const missingChecks = required.filter((name) => !request.checks.some((check) => check.name === name));
16
- const failedChecks = checks.filter((check) => !check.passed);
31
+ const failedChecks = checks.filter((check) => check.name === scopeCheckName ? !check.passed : !this.substantiated(check));
17
32
  const missingAcceptance = request.plan.steps.flatMap((step) => step.acceptanceCriteria).filter((criterion) => !request.acceptance.some((result) => result.criterion === criterion));
18
- const failedAcceptance = request.acceptance.filter((result) => !result.passed);
33
+ const failedAcceptance = request.acceptance.filter((result) => !this.substantiated(result));
19
34
  const contradictions = request.contradictions ?? [];
20
35
  const securityFindings = request.securityFindings ?? [];
21
36
  const severeSecurity = securityFindings.filter((finding) => finding.severity === 'high' || finding.severity === 'critical');
@@ -30,7 +45,7 @@ export class DeterministicValidator {
30
45
  status = 'blocked';
31
46
  else if (outOfScope.length > 0 || failedChecks.length > 0 || failedAcceptance.length > 0 || contradictions.length > 0 || severeSecurity.length > 0)
32
47
  status = 'rejected';
33
- else if (missingChecks.length > 0 || missingAcceptance.length > 0)
48
+ else if (missingChecks.length > 0 || missingAcceptance.length > 0 || noWorkReported)
34
49
  status = 'inconclusive';
35
50
  const now = new Date().toISOString();
36
51
  return {
@@ -40,7 +55,7 @@ export class DeterministicValidator {
40
55
  correlationId: request.correlationId ?? request.plan.id,
41
56
  status,
42
57
  checks: [
43
- ...checks.map(({ name, passed, evidenceIds }) => ({ name, passed, evidenceIds })),
58
+ ...checks.map(({ name, passed, evidenceIds }) => ({ name, passed: name === scopeCheckName ? passed : this.substantiated({ passed, evidenceIds }), evidenceIds })),
44
59
  { name: 'acceptance', passed: failedAcceptance.length === 0 && missingAcceptance.length === 0, evidenceIds: request.acceptance.flatMap((result) => result.evidenceIds) },
45
60
  { name: 'contradictions', passed: contradictions.length === 0, evidenceIds: contradictions.flatMap((item) => item.evidenceIds) },
46
61
  { name: 'security', passed: severeSecurity.length === 0, evidenceIds: severeSecurity.flatMap((item) => item.evidenceIds) },
@@ -0,0 +1,17 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * adr:list / adr:show / adr:impact / adr:graph (SPEC-032)
4
+ *
5
+ * forja adr:list lista ADRs com status
6
+ * forja adr:show <id> mostra uma ADR: status, arquivo, constraints (se houver)
7
+ * forja adr:impact <id> componentes/documentos alcançáveis a partir da ADR
8
+ * forja adr:graph [<id>] subgrafo (JSON) de nós ADR/SPEC + vizinhança direta
9
+ *
10
+ * Reindexa o workspace pelo mesmo mecanismo de `graph:sync`/`drift:check` (checksum de fonte +
11
+ * extração determinística) antes de consultar — mesma escolha de `drift:check`, para não exigir
12
+ * que o operador lembre de rodar `code:sync` antes. `<id>` aceita `0020` ou `ADR-0020`
13
+ * indiferentemente.
14
+ *
15
+ * Só leitura: nenhum destes comandos escreve em arquivo de projeto (SPEC-032 §5).
16
+ */
17
+ export {};
@@ -0,0 +1,152 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * adr:list / adr:show / adr:impact / adr:graph (SPEC-032)
4
+ *
5
+ * forja adr:list lista ADRs com status
6
+ * forja adr:show <id> mostra uma ADR: status, arquivo, constraints (se houver)
7
+ * forja adr:impact <id> componentes/documentos alcançáveis a partir da ADR
8
+ * forja adr:graph [<id>] subgrafo (JSON) de nós ADR/SPEC + vizinhança direta
9
+ *
10
+ * Reindexa o workspace pelo mesmo mecanismo de `graph:sync`/`drift:check` (checksum de fonte +
11
+ * extração determinística) antes de consultar — mesma escolha de `drift:check`, para não exigir
12
+ * que o operador lembre de rodar `code:sync` antes. `<id>` aceita `0020` ou `ADR-0020`
13
+ * indiferentemente.
14
+ *
15
+ * Só leitura: nenhum destes comandos escreve em arquivo de projeto (SPEC-032 §5).
16
+ */
17
+ import fs from 'node:fs';
18
+ import path from 'node:path';
19
+ import Database from 'better-sqlite3';
20
+ import { GitGraphDocumentSource, SpawnCommandRunner } from "../packages/adapter-git/src/index.js";
21
+ import { GraphIndexer, GraphLoop } from "../packages/graph/src/index.js";
22
+ import { SqliteGraphStore, SqliteMigrationRunner } from "../packages/adapter-sqlite/src/index.js";
23
+ import { getWorkspaceDbDir, getWorkspaceDbPath } from "../lib/workspace.js";
24
+ function normalizeAdrId(raw) {
25
+ const digits = /(\d{4})/.exec(raw)?.[1];
26
+ return digits === undefined ? raw : `ADR-${digits}`;
27
+ }
28
+ function adrFile(id) {
29
+ const digits = /(\d{4})/.exec(id)?.[1];
30
+ if (digits === undefined)
31
+ return undefined;
32
+ const dir = path.join(process.env.FORJA_GRAPH_ROOT ?? process.cwd(), 'memory', '90-decisions');
33
+ if (!fs.existsSync(dir))
34
+ return undefined;
35
+ const match = fs.readdirSync(dir).find((name) => name.startsWith(`${digits}-`));
36
+ return match === undefined ? undefined : path.join(dir, match);
37
+ }
38
+ function constraintsOf(file) {
39
+ const content = fs.readFileSync(file, 'utf8');
40
+ const section = /## Constraints\n([\s\S]*?)(?:\n## |\n?$)/.exec(content)?.[1];
41
+ if (section === undefined)
42
+ return [];
43
+ return section.split('\n').map((line) => line.trim()).filter((line) => line.startsWith('- '));
44
+ }
45
+ async function withGraph(fn) {
46
+ fs.mkdirSync(getWorkspaceDbDir(), { recursive: true });
47
+ const database = new Database(process.env.FORJA_RUNTIME_DB ?? getWorkspaceDbPath());
48
+ new SqliteMigrationRunner(database).apply();
49
+ const store = new SqliteGraphStore(database);
50
+ const graph = new GraphLoop(store);
51
+ const source = new GitGraphDocumentSource(process.env.FORJA_GRAPH_ROOT ?? process.cwd(), new SpawnCommandRunner());
52
+ await new GraphIndexer(graph).sync(source);
53
+ try {
54
+ return await fn(graph, store);
55
+ }
56
+ finally {
57
+ database.close();
58
+ }
59
+ }
60
+ async function cmdList() {
61
+ await withGraph((graph) => {
62
+ const adrs = [...graph.query({ type: 'ADR' })].sort((left, right) => left.label.localeCompare(right.label));
63
+ if (adrs.length === 0) {
64
+ console.log('Nenhuma ADR encontrada no grafo.');
65
+ return;
66
+ }
67
+ console.log(`${adrs.length} ADR(s):\n`);
68
+ for (const node of adrs)
69
+ console.log(`${node.label}\t${node.documentStatus ?? '(status desconhecido)'}`);
70
+ });
71
+ }
72
+ async function cmdShow([rawId]) {
73
+ if (!rawId) {
74
+ console.error('Uso: forja adr:show <id>');
75
+ process.exit(1);
76
+ }
77
+ const id = normalizeAdrId(rawId);
78
+ await withGraph((graph) => {
79
+ const node = graph.query({ type: 'ADR' }).find((item) => item.label === id);
80
+ if (node === undefined) {
81
+ console.error(`ADR não encontrada no grafo: ${id}`);
82
+ process.exit(1);
83
+ return;
84
+ }
85
+ const file = adrFile(id);
86
+ console.log(`${node.label} — ${node.documentStatus ?? '(status desconhecido)'}`);
87
+ console.log(`arquivo: ${file ?? '(não encontrado em memory/90-decisions)'}`);
88
+ if (file !== undefined) {
89
+ const constraints = constraintsOf(file);
90
+ if (constraints.length > 0) {
91
+ console.log('\nConstraints:');
92
+ for (const line of constraints)
93
+ console.log(` ${line}`);
94
+ }
95
+ }
96
+ });
97
+ }
98
+ async function cmdImpact([rawId, depthArg]) {
99
+ if (!rawId) {
100
+ console.error('Uso: forja adr:impact <id> [profundidade]');
101
+ process.exit(1);
102
+ }
103
+ const id = normalizeAdrId(rawId);
104
+ const depth = Number.parseInt(depthArg ?? '', 10) || 2;
105
+ await withGraph((graph) => {
106
+ const node = graph.query({ type: 'ADR' }).find((item) => item.label === id);
107
+ if (node === undefined) {
108
+ console.error(`ADR não encontrada no grafo: ${id}`);
109
+ process.exit(1);
110
+ return;
111
+ }
112
+ const impact = graph.impact(node.id, depth, 'incoming'); // incoming: quem DEPENDS_ON/DERIVED_FROM/governed_by aponta PARA a ADR
113
+ console.log(`Impacto de ${id} (profundidade ${depth}):\n`);
114
+ console.log(`${impact.nodes.length - 1} nó(s) alcançável(is), ${impact.edges.length} aresta(s):\n`);
115
+ for (const n of impact.nodes)
116
+ if (n.id !== node.id)
117
+ console.log(` ${n.type}\t${n.label}`);
118
+ });
119
+ }
120
+ async function cmdGraph([rawId]) {
121
+ await withGraph((graph) => {
122
+ if (rawId) {
123
+ const id = normalizeAdrId(rawId);
124
+ const node = [...graph.query({ type: 'ADR' }), ...graph.query({ type: 'SPEC' })].find((item) => item.label === id);
125
+ if (node === undefined) {
126
+ console.error(`Não encontrado no grafo: ${id}`);
127
+ process.exit(1);
128
+ return;
129
+ }
130
+ console.log(JSON.stringify(graph.impact(node.id, 1, 'both'), null, 2));
131
+ return;
132
+ }
133
+ const nodes = [...graph.query({ type: 'ADR' }), ...graph.query({ type: 'SPEC' })];
134
+ console.log(JSON.stringify({ nodes }, null, 2));
135
+ });
136
+ }
137
+ async function main() {
138
+ const [subcommand, ...rest] = process.argv.slice(2);
139
+ switch (subcommand) {
140
+ case 'list': return cmdList();
141
+ case 'show': return cmdShow(rest);
142
+ case 'impact': return cmdImpact(rest);
143
+ case 'graph': return cmdGraph(rest);
144
+ default:
145
+ console.error('Uso: forja adr:<list|show|impact|graph> [args]');
146
+ process.exit(1);
147
+ }
148
+ }
149
+ main().catch((error) => {
150
+ console.error(`\nadr: falhou: ${error instanceof Error ? error.message : String(error)}`);
151
+ process.exit(1);
152
+ });