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
@@ -0,0 +1,120 @@
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
+ /** Pesos default do §9 do doc de arquitetura — somam 1.0. Sempre sobrescrevíveis via `options.weights` (AC-1). */
11
+ export const DEFAULT_RISK_WEIGHTS = {
12
+ blast_radius: 0.20,
13
+ architecture_violations: 0.20,
14
+ security_sensitivity: 0.15,
15
+ historical_failure_rate: 0.15,
16
+ test_confidence: 0.10,
17
+ reversibility: 0.10,
18
+ deployment_complexity: 0.10,
19
+ };
20
+ /** Faixas sugeridas na visão original (0-25/26-50/51-75/76-100) — configuração default, nunca constante fixa (AC-6). */
21
+ export const DEFAULT_AUTONOMY_BAND_THRESHOLDS = {
22
+ autonomous: 25,
23
+ autonomousWithReview: 50,
24
+ supervised: 75,
25
+ };
26
+ const BLAST_RADIUS_CAP = 30;
27
+ const ARCHITECTURE_VIOLATION_CAP = 5;
28
+ const SENSITIVE_CATEGORY_VOCAB = ['secrets', 'database', 'deployment'];
29
+ function computeFactors(input, weights) {
30
+ const blastValue = Math.min(1, input.blastRadiusCount / BLAST_RADIUS_CAP);
31
+ const architectureValue = Math.min(1, input.architectureViolationCount / ARCHITECTURE_VIOLATION_CAP);
32
+ const sensitiveCount = SENSITIVE_CATEGORY_VOCAB.filter((category) => input.sensitiveCategoriesTouched.includes(category)).length;
33
+ const securityValue = sensitiveCount / SENSITIVE_CATEGORY_VOCAB.length;
34
+ const historicalHasData = input.historicalFailureRate !== undefined;
35
+ const historicalValue = input.historicalFailureRate ?? 0;
36
+ const testedHasData = input.testedPathsRatio !== undefined;
37
+ const testValue = testedHasData ? 1 - input.testedPathsRatio : 0.5;
38
+ const reversibilityValue = input.touchesSchemaOrMigration ? 1 : 0;
39
+ const deploymentValue = input.totalServiceCount === 0 ? 0 : Math.min(1, input.affectedServiceCount / input.totalServiceCount);
40
+ return [
41
+ {
42
+ name: 'blast_radius', weight: weights.blast_radius, value: blastValue, hasRealData: true,
43
+ evidenceIds: input.blastRadiusEvidenceIds,
44
+ rationale: `${input.blastRadiusCount} nó(s) alcançável(is) no Engineering Graph (cap ${BLAST_RADIUS_CAP})`,
45
+ },
46
+ {
47
+ name: 'architecture_violations', weight: weights.architecture_violations, value: architectureValue, hasRealData: true,
48
+ evidenceIds: input.architectureViolationEvidenceIds,
49
+ rationale: `${input.architectureViolationCount} violação(ões) de architecture:check no escopo afetado (cap ${ARCHITECTURE_VIOLATION_CAP})`,
50
+ },
51
+ {
52
+ name: 'security_sensitivity', weight: weights.security_sensitivity, value: securityValue, hasRealData: true,
53
+ evidenceIds: input.sensitiveCategoryEvidenceIds,
54
+ rationale: sensitiveCount === 0 ? 'nenhuma categoria sensível tocada' : `categorias tocadas: ${input.sensitiveCategoriesTouched.join(', ')}`,
55
+ },
56
+ {
57
+ name: 'historical_failure_rate', weight: weights.historical_failure_rate, value: historicalValue, hasRealData: historicalHasData,
58
+ evidenceIds: input.historicalEvidenceIds,
59
+ rationale: historicalHasData ? `taxa de falha observada: ${(historicalValue * 100).toFixed(0)}%` : 'sem Observation histórica para os arquivos afetados — cold start',
60
+ },
61
+ {
62
+ name: 'test_confidence', weight: weights.test_confidence, value: testValue, hasRealData: testedHasData,
63
+ evidenceIds: input.testEvidenceIds,
64
+ rationale: testedHasData ? `${(input.testedPathsRatio * 100).toFixed(0)}% dos arquivos afetados têm teste associado` : 'cobertura de teste não determinada',
65
+ },
66
+ {
67
+ name: 'reversibility', weight: weights.reversibility, value: reversibilityValue, hasRealData: true,
68
+ evidenceIds: input.reversibilityEvidenceIds,
69
+ rationale: input.touchesSchemaOrMigration ? 'toca migration/schema — baixa reversibilidade' : 'não toca migration/schema',
70
+ },
71
+ {
72
+ name: 'deployment_complexity', weight: weights.deployment_complexity, value: deploymentValue, hasRealData: true,
73
+ evidenceIds: input.deploymentEvidenceIds,
74
+ rationale: `${input.affectedServiceCount} de ${input.totalServiceCount} pacote(s)/app(s) afetado(s)`,
75
+ },
76
+ ];
77
+ }
78
+ function autonomyBandFor(score, thresholds) {
79
+ if (score <= thresholds.autonomous)
80
+ return 'autonomous';
81
+ if (score <= thresholds.autonomousWithReview)
82
+ return 'autonomous_with_review';
83
+ if (score <= thresholds.supervised)
84
+ return 'supervised';
85
+ return 'human_in_the_loop';
86
+ }
87
+ export function assessRisk(input, meta) {
88
+ const weights = { ...DEFAULT_RISK_WEIGHTS, ...meta.weights };
89
+ const thresholds = meta.thresholds ?? DEFAULT_AUTONOMY_BAND_THRESHOLDS;
90
+ const factors = computeFactors(input, weights);
91
+ const score = Math.round(100 * factors.reduce((sum, factor) => sum + factor.weight * factor.value, 0));
92
+ const confidence = Math.round((factors.filter((factor) => factor.hasRealData).length / factors.length) * 100) / 100;
93
+ return {
94
+ id: meta.id,
95
+ changeId: meta.changeId,
96
+ createdAt: meta.now,
97
+ score,
98
+ confidence,
99
+ autonomyBand: autonomyBandFor(score, thresholds),
100
+ factors,
101
+ };
102
+ }
103
+ export function explainAssessment(assessment) {
104
+ const lines = [
105
+ `${assessment.id} — mudança "${assessment.changeId}"`,
106
+ `score ${assessment.score}/100 → ${assessment.autonomyBand} (confidence ${(assessment.confidence * 100).toFixed(0)}%)`,
107
+ '',
108
+ ];
109
+ for (const factor of assessment.factors) {
110
+ const flag = factor.hasRealData ? '' : ' (sem dado real)';
111
+ lines.push(`${factor.name.padEnd(24)} peso ${factor.weight.toFixed(2)} valor ${factor.value.toFixed(2)}${flag}`);
112
+ lines.push(` ${factor.rationale}`);
113
+ }
114
+ return lines.join('\n');
115
+ }
116
+ export function createRiskEngine(config) {
117
+ return {
118
+ assess: (input, meta) => assessRisk(input, { ...meta, weights: config?.weights, thresholds: config?.thresholds }),
119
+ };
120
+ }
@@ -6,6 +6,7 @@ export interface GraphNodeSpec {
6
6
  readonly status: KnowledgeStatus;
7
7
  readonly validFrom?: ISO8601;
8
8
  readonly validTo?: ISO8601;
9
+ readonly documentStatus?: string;
9
10
  }
10
11
  export interface GraphEdgeSpec {
11
12
  readonly id?: EntityId;
@@ -61,10 +62,22 @@ export interface GraphStore {
61
62
  saveEvidence(item: Evidence): void;
62
63
  getSourceChecksum(sourceKey: string): string | undefined;
63
64
  saveSourceChecksum(sourceKey: string, checksum: string): void;
65
+ /**
66
+ * Opcional (achado real, GraphIndexer.sync contra ~1000 documentos): sem isto, cada
67
+ * `saveNode`/`saveEdge`/`saveEvidence` é um `INSERT` commitado individualmente — dezenas de
68
+ * milhares de fsyncs num repositório real. Um `GraphStore` que grava em algo transacional (ex.
69
+ * `SqliteGraphStore`) implementa isto pra agrupar; `InMemoryGraphStore` não precisa — sem custo
70
+ * de I/O, não há nada a agrupar, e `GraphLoop.transaction` cai pra "só chame `fn()`" quando
71
+ * ausente.
72
+ */
73
+ transaction?<T>(fn: () => T): T;
64
74
  }
65
75
  export declare class GraphError extends Error {
66
76
  constructor(message: string);
67
77
  }
78
+ export interface GraphLoopOptions {
79
+ readonly trustedEvidenceSources?: readonly string[];
80
+ }
68
81
  export declare class InMemoryGraphStore implements GraphStore {
69
82
  readonly nodes: Map<EntityId, GraphNode>;
70
83
  readonly edges: Map<string, GraphEdge>;
@@ -83,7 +96,9 @@ export declare class InMemoryGraphStore implements GraphStore {
83
96
  }
84
97
  export declare class GraphLoop {
85
98
  private readonly store;
86
- constructor(store?: GraphStore);
99
+ private readonly trustedEvidenceSources;
100
+ constructor(store?: GraphStore, options?: GraphLoopOptions);
101
+ private isTrustedSource;
87
102
  addEvidence(item: Evidence): void;
88
103
  upsertNode(spec: GraphNodeSpec): GraphNode;
89
104
  upsertEdge(spec: GraphEdgeSpec): GraphEdge;
@@ -92,6 +107,13 @@ export declare class GraphLoop {
92
107
  readonly edges: number;
93
108
  readonly skipped: boolean;
94
109
  };
110
+ /**
111
+ * Agrupa `fn` numa transação do `store`, se ele suportar uma (`GraphStore.transaction`,
112
+ * opcional). `GraphIndexer.sync` usa isto pra envolver o loop inteiro de `apply()` — uma
113
+ * transação pra todos os documentos, não uma implícita por `INSERT`. Sem suporte do store
114
+ * (ex. `InMemoryGraphStore`), só roda `fn()` normalmente.
115
+ */
116
+ transaction<T>(fn: () => T): T;
95
117
  query(query?: GraphQuery): readonly GraphNode[];
96
118
  path(from: EntityId, to: EntityId, maxDepth?: number, at?: ISO8601): GraphPath | undefined;
97
119
  impact(origin: EntityId, depth?: number, direction?: 'outgoing' | 'incoming' | 'both', at?: ISO8601): GraphImpact;
@@ -6,6 +6,16 @@ export class GraphError extends Error {
6
6
  this.name = 'GraphError';
7
7
  }
8
8
  }
9
+ /**
10
+ * Evidence sources allowed to claim `status: 'verified'` directly. Without this, any caller —
11
+ * including an LLM/agent whose output feeds `addEvidence`/`upsertEdge` — could write
12
+ * `status: 'verified'` on a bare assertion and GraphLoop would store it as indistinguishable
13
+ * from a fact derived by the deterministic extractor or a real sandboxed execution. Anything
14
+ * outside this allowlist is clamped to `'inferred'` (see `addEvidence`/`upsertEdge`) instead of
15
+ * being rejected, so the graph stays usable for genuinely uncertain input — it just can't be
16
+ * mislabeled as verified.
17
+ */
18
+ const DEFAULT_TRUSTED_EVIDENCE_SOURCES = ['deterministic-extractor', 'sandbox', 'forja.graph', 'forja.cli'];
9
19
  export class InMemoryGraphStore {
10
20
  nodes = new Map();
11
21
  edges = new Map();
@@ -24,17 +34,28 @@ export class InMemoryGraphStore {
24
34
  }
25
35
  export class GraphLoop {
26
36
  store;
27
- constructor(store = new InMemoryGraphStore()) {
37
+ trustedEvidenceSources;
38
+ constructor(store = new InMemoryGraphStore(), options = {}) {
28
39
  this.store = store;
40
+ this.trustedEvidenceSources = options.trustedEvidenceSources ?? DEFAULT_TRUSTED_EVIDENCE_SOURCES;
41
+ }
42
+ isTrustedSource(source) {
43
+ return this.trustedEvidenceSources.some((prefix) => source === prefix || source.startsWith(`${prefix}.`));
29
44
  }
30
45
  addEvidence(item) {
31
- this.store.saveEvidence(item);
46
+ const stored = item.status === 'verified' && !this.isTrustedSource(item.source) ? { ...item, status: 'inferred' } : item;
47
+ this.store.saveEvidence(stored);
32
48
  }
33
49
  upsertNode(spec) {
34
50
  if (spec.id.trim().length === 0 || spec.type.trim().length === 0 || spec.label.trim().length === 0)
35
51
  throw new GraphError('Graph node id, type and label are required');
36
52
  const current = this.store.getNode(spec.id);
37
- const node = { ...this.auditFields(current?.correlationId ?? `node:${spec.id}`), ...spec };
53
+ // `documentStatus` specifically survives an update that doesn't mention it: a document that
54
+ // only references this node in passing (e.g. "see ADR-0020") doesn't know that ADR's real
55
+ // status, and re-indexing it after the ADR's own file shouldn't erase what the ADR's own file
56
+ // already established — see extractDeterministicRelations' "Self-status" comment.
57
+ const documentStatus = spec.documentStatus ?? current?.documentStatus;
58
+ const node = { ...this.auditFields(current?.correlationId ?? `node:${spec.id}`), ...spec, ...(documentStatus === undefined ? {} : { documentStatus }) };
38
59
  this.store.saveNode(node);
39
60
  return node;
40
61
  }
@@ -43,14 +64,21 @@ export class GraphLoop {
43
64
  throw new GraphError('Graph edge endpoints must exist');
44
65
  if (spec.evidenceIds.length === 0)
45
66
  throw new GraphError('Graph edge requires at least one evidence id');
46
- for (const id of spec.evidenceIds)
47
- if (this.store.getEvidence(id) === undefined)
67
+ const referencedEvidence = [];
68
+ for (const id of spec.evidenceIds) {
69
+ const item = this.store.getEvidence(id);
70
+ if (item === undefined)
48
71
  throw new GraphError(`Graph edge evidence not found: ${id}`);
72
+ referencedEvidence.push(item);
73
+ }
49
74
  if (!Number.isFinite(spec.confidence) || spec.confidence < 0 || spec.confidence > 1)
50
75
  throw new GraphError('Graph edge confidence must be between 0 and 1');
76
+ // An edge can't be more verified than the evidence it rests on — otherwise 'verified' becomes
77
+ // a label the edge asserts about itself, exactly the self-declared-truth gap this guards.
78
+ const status = spec.status === 'verified' && !referencedEvidence.every((item) => item.status === 'verified') ? 'inferred' : spec.status;
51
79
  const key = this.edgeKey(spec);
52
80
  const current = this.store.getEdge(key);
53
- const edge = { ...this.auditFields(current?.correlationId ?? `edge:${key}`), ...spec, id: current?.id ?? spec.id ?? randomUUID() };
81
+ const edge = { ...this.auditFields(current?.correlationId ?? `edge:${key}`), ...spec, status, id: current?.id ?? spec.id ?? randomUUID() };
54
82
  this.store.saveEdge(key, edge);
55
83
  return edge;
56
84
  }
@@ -66,6 +94,15 @@ export class GraphLoop {
66
94
  this.store.saveSourceChecksum(mutation.sourceKey, mutation.sourceChecksum);
67
95
  return { nodes: mutation.nodes.length, edges: mutation.edges.length, skipped: false };
68
96
  }
97
+ /**
98
+ * Agrupa `fn` numa transação do `store`, se ele suportar uma (`GraphStore.transaction`,
99
+ * opcional). `GraphIndexer.sync` usa isto pra envolver o loop inteiro de `apply()` — uma
100
+ * transação pra todos os documentos, não uma implícita por `INSERT`. Sem suporte do store
101
+ * (ex. `InMemoryGraphStore`), só roda `fn()` normalmente.
102
+ */
103
+ transaction(fn) {
104
+ return this.store.transaction ? this.store.transaction(fn) : fn();
105
+ }
69
106
  query(query = {}) {
70
107
  return [...this.store.listNodes()]
71
108
  .filter((node) => query.type === undefined || node.type === query.type)
@@ -193,16 +230,21 @@ export class GraphIndexer {
193
230
  let skipped = 0;
194
231
  let nodes = 0;
195
232
  let edges = 0;
196
- for (const document of documents) {
197
- const result = this.graph.apply(extractDeterministicRelations(document));
198
- if (result.skipped)
199
- skipped += 1;
200
- else {
201
- indexed += 1;
202
- nodes += result.nodes;
203
- edges += result.edges;
233
+ // `GraphLoop.transaction` (achado real de performance): sem isto, cada apply() de cada
234
+ // documento fazia seus INSERTs num commit implícito próprio — dezenas de milhares de fsyncs
235
+ // pra um repositório de ~1000 arquivos. Uma transação pro sync inteiro, não uma por linha.
236
+ this.graph.transaction(() => {
237
+ for (const document of documents) {
238
+ const result = this.graph.apply(extractDeterministicRelations(document));
239
+ if (result.skipped)
240
+ skipped += 1;
241
+ else {
242
+ indexed += 1;
243
+ nodes += result.nodes;
244
+ edges += result.edges;
245
+ }
204
246
  }
205
- }
247
+ });
206
248
  return { documents: documents.length, indexed, skipped, nodes, edges, durationMs: Date.now() - started, files: documents.map((document) => document.locator) };
207
249
  }
208
250
  }
@@ -238,6 +280,9 @@ export function extractDeterministicRelations(document) {
238
280
  const adrMatches = line.match(/\bADR-\d{4}\b/g) ?? [];
239
281
  for (const adr of adrMatches)
240
282
  addRelation(adr, 'DERIVED_FROM', index + 1, 'ADR');
283
+ const specMatches = line.match(/\bSPEC-\d{3,4}\b/g) ?? [];
284
+ for (const spec of specMatches)
285
+ addRelation(spec, 'DERIVED_FROM', index + 1, 'SPEC');
241
286
  const taskMatch = line.match(/^\s*-\s*\[[ xX]\]\s+(.+)$/);
242
287
  if (taskMatch?.[1] !== undefined)
243
288
  addRelation(taskMatch[1], 'CONTAINS', index + 1, 'Task');
@@ -254,6 +299,34 @@ export function extractDeterministicRelations(document) {
254
299
  addRelation(name, 'CALLS', index + 1, 'Symbol');
255
300
  }
256
301
  });
302
+ // Self-status: when `document` IS an ADR or a spec.md (not just mentioning one in passing),
303
+ // attach the document's own `- **Status**: <value>` line to the ADR/SPEC node it represents —
304
+ // via the `nodes` map, not a direct `upsertNode` call, since this function stays pure/stateless
305
+ // (packages/graph SPEC-032 §5). A later `apply()` of some OTHER document that only references
306
+ // this same ADR/SPEC in passing won't know its status and won't include `documentStatus` in its
307
+ // own spec — `GraphLoop.upsertNode` preserves the previous value in that case rather than wiping
308
+ // it, so processing order across the corpus can't flip a real status back to unknown.
309
+ const adrSelfMatch = /^memory\/90-decisions\/(\d{4})-/.exec(document.locator);
310
+ const specSelfMatch = /^specs\/[^/]+\/spec\.md$/.test(document.locator);
311
+ if (adrSelfMatch || specSelfMatch) {
312
+ const statusMatch = /^-\s*\*\*Status\*\*:\s*(\S[^\n]*?)\s*$/m.exec(document.content);
313
+ const documentStatus = statusMatch?.[1];
314
+ if (documentStatus !== undefined) {
315
+ const label = adrSelfMatch ? `ADR-${adrSelfMatch[1]}` : /^-\s*\*\*ID\*\*:\s*(SPEC-\d{3,4})\s*$/m.exec(document.content)?.[1];
316
+ const type = adrSelfMatch ? 'ADR' : 'SPEC';
317
+ if (label !== undefined) {
318
+ // `addRelation` keys a node by `${relationType}:${label}` (e.g. `DERIVED_FROM:ADR-0041`),
319
+ // not `${nodeType}:${label}` — an existing quirk of this function, not something to change
320
+ // here. Reuse whatever id the self-reference already produced (present whenever the
321
+ // document's own text repeats its own ADR/SPEC id, which it always does per the template)
322
+ // instead of guessing that scheme, so this stays correct even if the keying convention
323
+ // changes later.
324
+ const existingEntry = [...nodes.entries()].find(([, node]) => node.type === type && node.label === label);
325
+ const targetId = existingEntry?.[0] ?? stableId(`DERIVED_FROM:${label}`);
326
+ nodes.set(targetId, { id: targetId, type, label, status: 'verified', documentStatus, ...(existingEntry?.[1].validFrom !== undefined ? { validFrom: existingEntry[1].validFrom } : {}) });
327
+ }
328
+ }
329
+ }
257
330
  if (document.locator.endsWith('package.json')) {
258
331
  try {
259
332
  const manifest = JSON.parse(document.content);
@@ -0,0 +1,43 @@
1
+ export declare const LLM_PROFILE_VERSION = 1;
2
+ export interface LlmProfile {
3
+ readonly provider: string;
4
+ readonly model: string;
5
+ readonly command: string;
6
+ readonly commandArgs?: readonly string[];
7
+ readonly roles: readonly string[];
8
+ readonly taskTypes: readonly string[];
9
+ readonly privacy: 'local' | 'external';
10
+ readonly enabled: boolean;
11
+ }
12
+ export interface LlmProfiles {
13
+ readonly version: typeof LLM_PROFILE_VERSION;
14
+ readonly profiles: Readonly<Record<string, LlmProfile>>;
15
+ }
16
+ export interface LlmExecution {
17
+ readonly executable: string;
18
+ readonly args: readonly string[];
19
+ }
20
+ export interface LlmExecutionResult {
21
+ readonly exitCode: number;
22
+ readonly stdout: string;
23
+ readonly stderr: string;
24
+ readonly durationMs: number;
25
+ readonly errorCode?: string;
26
+ }
27
+ export declare const DEFAULT_LLM_PROFILES: LlmProfiles;
28
+ export declare class LlmProfileError extends Error {
29
+ constructor(message: string);
30
+ }
31
+ export declare function validateProfiles(value: unknown): LlmProfiles;
32
+ export declare function buildLlmExecution(profile: LlmProfile, prompt: string): LlmExecution;
33
+ export declare function runLlm(execution: LlmExecution, cwd: string, timeoutMs?: number): Promise<LlmExecutionResult>;
34
+ export declare function recommendProfile(profiles: LlmProfiles, observations: readonly {
35
+ readonly model?: string;
36
+ readonly outcome: string;
37
+ readonly durationMs: number;
38
+ readonly cost?: number;
39
+ }[], role: string, taskType: string, privacy?: LlmProfile['privacy']): readonly {
40
+ readonly name: string;
41
+ readonly score: number;
42
+ readonly reasons: readonly string[];
43
+ }[];
@@ -0,0 +1,131 @@
1
+ import { spawn } from 'node:child_process';
2
+ export const LLM_PROFILE_VERSION = 1;
3
+ export const DEFAULT_LLM_PROFILES = {
4
+ version: LLM_PROFILE_VERSION,
5
+ profiles: {
6
+ codex: { provider: 'codex', model: 'default', command: 'codex', roles: ['orchestrator', 'worker'], taskTypes: ['orchestration', 'implementation', 'review'], privacy: 'external', enabled: true },
7
+ claude: { provider: 'claude', model: 'default', command: 'claude', roles: ['sdd-architect', 'product'], taskTypes: ['architecture', 'specification', 'analysis'], privacy: 'external', enabled: true },
8
+ gemini: { provider: 'gemini-cli', model: 'default', command: 'gemini', roles: ['context-engineer', 'marketing'], taskTypes: ['research', 'context', 'writing'], privacy: 'external', enabled: true },
9
+ ollama: { provider: 'ollama', model: 'llama3.3', command: 'ollama', roles: [], taskTypes: ['offline', 'sensitive'], privacy: 'local', enabled: false },
10
+ },
11
+ };
12
+ export class LlmProfileError extends Error {
13
+ constructor(message) { super(message); this.name = 'LlmProfileError'; }
14
+ }
15
+ export function validateProfiles(value) {
16
+ if (!isRecord(value) || value.version !== LLM_PROFILE_VERSION || !isRecord(value.profiles))
17
+ throw new LlmProfileError(`profiles must use version ${LLM_PROFILE_VERSION}`);
18
+ const profiles = {};
19
+ for (const [name, profile] of Object.entries(value.profiles))
20
+ profiles[name] = validateProfile(name, profile);
21
+ return { version: LLM_PROFILE_VERSION, profiles };
22
+ }
23
+ export function buildLlmExecution(profile, prompt) {
24
+ if (!profile.enabled)
25
+ throw new LlmProfileError('profile is disabled');
26
+ if (prompt.trim().length === 0)
27
+ throw new LlmProfileError('prompt is required');
28
+ const base = [...(profile.commandArgs ?? [])];
29
+ if (profile.provider === 'codex')
30
+ return { executable: profile.command, args: ['exec', ...base, ...(profile.model === 'default' ? [] : ['--model', profile.model]), '--sandbox', 'read-only', '--ask-for-approval', 'never', prompt] };
31
+ if (profile.provider === 'claude')
32
+ return { executable: profile.command, args: [...base, ...(profile.model === 'default' ? [] : ['--model', profile.model]), '-p', prompt] };
33
+ if (profile.provider === 'gemini-cli')
34
+ return { executable: profile.command, args: [...base, ...(profile.model === 'default' ? [] : ['-m', profile.model]), '-p', prompt] };
35
+ if (profile.provider === 'ollama')
36
+ return { executable: profile.command, args: [...base, 'run', profile.model, prompt] };
37
+ if (profile.provider === 'copilot')
38
+ return { executable: profile.command, args: [...base, 'copilot', 'suggest', '-t', 'shell', prompt] };
39
+ return { executable: profile.command, args: [...base, prompt] };
40
+ }
41
+ /** Grace period after SIGTERM before a timed-out LLM subprocess (and anything it spawned) gets SIGKILLed. */
42
+ const SIGTERM_GRACE_MS = 3_000;
43
+ export async function runLlm(execution, cwd, timeoutMs = 120_000) {
44
+ const started = Date.now();
45
+ return new Promise((resolve) => {
46
+ let stdout = '';
47
+ let stderr = '';
48
+ let settled = false;
49
+ const finish = (result) => {
50
+ if (settled)
51
+ return;
52
+ settled = true;
53
+ resolve({ ...result, durationMs: Date.now() - started });
54
+ };
55
+ // detached so the child leads its own process group: a negative pid targets the whole group,
56
+ // reaching grandchildren the CLI tool itself spawned (not just the immediate child).
57
+ const child = spawn(execution.executable, execution.args, { cwd, shell: false, stdio: ['ignore', 'pipe', 'pipe'], detached: true });
58
+ child.stdout.setEncoding('utf8');
59
+ child.stderr.setEncoding('utf8');
60
+ child.stdout.on('data', (chunk) => { stdout += chunk; });
61
+ child.stderr.on('data', (chunk) => { stderr += chunk; });
62
+ const killGroup = (signal) => {
63
+ if (child.pid === undefined)
64
+ return;
65
+ try {
66
+ process.kill(-child.pid, signal);
67
+ }
68
+ catch {
69
+ // no process group (platform didn't support detached, or it's already gone) — fall back to the child alone
70
+ try {
71
+ child.kill(signal);
72
+ }
73
+ catch { /* already dead */ }
74
+ }
75
+ };
76
+ let killTimer;
77
+ const timer = setTimeout(() => {
78
+ killGroup('SIGTERM');
79
+ killTimer = setTimeout(() => killGroup('SIGKILL'), SIGTERM_GRACE_MS);
80
+ finish({ exitCode: 124, stdout, stderr, errorCode: 'TIMEOUT' });
81
+ }, timeoutMs);
82
+ child.on('error', (error) => { clearTimeout(timer); clearTimeout(killTimer); finish({ exitCode: 127, stdout, stderr: `${stderr}${error.message}`, errorCode: 'SPAWN_FAILED' }); });
83
+ child.on('close', (code) => { clearTimeout(timer); clearTimeout(killTimer); finish({ exitCode: code ?? 1, stdout, stderr, ...(code === 0 ? {} : { errorCode: 'COMMAND_FAILED' }) }); });
84
+ });
85
+ }
86
+ export function recommendProfile(profiles, observations, role, taskType, privacy) {
87
+ return Object.entries(profiles.profiles)
88
+ .filter(([, profile]) => profile.enabled && (privacy === undefined || profile.privacy === privacy))
89
+ .map(([name, profile]) => {
90
+ const model = `${profile.provider}:${profile.model}`;
91
+ const samples = observations.filter((value) => value.model === model);
92
+ const succeeded = samples.filter((value) => value.outcome === 'succeeded').length;
93
+ const successRate = samples.length === 0 ? 0 : succeeded / samples.length;
94
+ const score = (profile.roles.includes(role) ? 100 : 0) + (profile.taskTypes.includes(taskType) ? 50 : 0) + Math.round(successRate * 25) + Math.min(samples.length, 10);
95
+ const reasons = [
96
+ ...(profile.roles.includes(role) ? [`role:${role}`] : []),
97
+ ...(profile.taskTypes.includes(taskType) ? [`task:${taskType}`] : []),
98
+ ...(samples.length > 0 ? [`${succeeded}/${samples.length} successful runs`] : ['no local evidence yet']),
99
+ ];
100
+ return { name, score, reasons };
101
+ })
102
+ .sort((a, b) => b.score - a.score || a.name.localeCompare(b.name));
103
+ }
104
+ function validateProfile(name, value) {
105
+ if (!/^[a-z0-9][a-z0-9_-]*$/.test(name) || !isRecord(value))
106
+ throw new LlmProfileError(`invalid profile: ${name}`);
107
+ const provider = string(value.provider, 'provider');
108
+ const model = string(value.model, 'model');
109
+ const command = string(value.command, 'command');
110
+ if (/\s/.test(command))
111
+ throw new LlmProfileError(`profile ${name}: command must be one executable; use commandArgs for arguments`);
112
+ const privacy = value.privacy;
113
+ if (privacy !== 'local' && privacy !== 'external')
114
+ throw new LlmProfileError(`profile ${name}: privacy must be local or external`);
115
+ if (typeof value.enabled !== 'boolean')
116
+ throw new LlmProfileError(`profile ${name}: enabled must be boolean`);
117
+ return { provider, model, command, commandArgs: strings(value.commandArgs, 'commandArgs'), roles: strings(value.roles, 'roles'), taskTypes: strings(value.taskTypes, 'taskTypes'), privacy, enabled: value.enabled };
118
+ }
119
+ function strings(value, field) {
120
+ if (value === undefined)
121
+ return [];
122
+ if (!Array.isArray(value) || !value.every((entry) => typeof entry === 'string' && entry.trim().length > 0))
123
+ throw new LlmProfileError(`${field} must be an array of non-empty strings`);
124
+ return [...new Set(value.map((entry) => entry.trim()))];
125
+ }
126
+ function string(value, field) {
127
+ if (typeof value !== 'string' || value.trim().length === 0)
128
+ throw new LlmProfileError(`${field} is required`);
129
+ return value.trim();
130
+ }
131
+ function isRecord(value) { return typeof value === 'object' && value !== null; }
@@ -83,15 +83,34 @@ export class McpServer {
83
83
  case 'forja_capabilities_list': return this.dependencies.registry.list({ agent: this.dependencies.agent, policy: this.dependencies.policy });
84
84
  case 'forja_capability_describe': return this.dependencies.registry.describe(this.string(input, 'capabilityId'), { agent: this.dependencies.agent, policy: this.dependencies.policy });
85
85
  case 'forja_capability_execute': return this.executeCapability(input);
86
- case 'forja_context_build': return this.requireContext().build(this.contextRequest(input));
87
- case 'forja_memory_query': return this.requireMemory().query(this.string(input, 'objective'));
88
- case 'forja_graph_query': return this.requireGraph().query(this.graphQuery(input));
89
- case 'forja_code_impact': return this.requireGraph().impact(this.entity(input, 'origin'), this.number(input, 'depth', 2), this.direction(input));
90
- case 'forja_task_next': return this.requireTasks().next(this.entity(input, 'sprintId'));
86
+ // read-only queries: low-risk read gate — same authorize() surface as forja_handoff_create, scoped down
87
+ case 'forja_context_build':
88
+ this.authorize('forja_context_build', 'read', 'low', []);
89
+ return this.requireContext().build(this.contextRequest(input));
90
+ case 'forja_memory_query':
91
+ this.authorize('forja_memory_query', 'read', 'low', []);
92
+ return this.requireMemory().query(this.string(input, 'objective'));
93
+ case 'forja_graph_query':
94
+ this.authorize('forja_graph_query', 'read', 'low', []);
95
+ return this.requireGraph().query(this.graphQuery(input));
96
+ case 'forja_code_impact':
97
+ this.authorize('forja_code_impact', 'read', 'low', []);
98
+ return this.requireGraph().impact(this.entity(input, 'origin'), this.number(input, 'depth', 2), this.direction(input));
99
+ case 'forja_task_next':
100
+ this.authorize('forja_task_next', 'read', 'low', []);
101
+ return this.requireTasks().next(this.entity(input, 'sprintId'));
91
102
  case 'forja_handoff_create': return this.createHandoff(input);
92
- case 'forja_spec_check': return this.requireSpecChecker().check(input);
93
- case 'forja_test_run': return this.requireTestRunner().run(input);
94
- case 'forja_execution_validate': return this.requireExecutionValidator().validate(input);
103
+ // spec_check/test_run/execution_validate call adapters directly (not through CapabilityRegistry.execute,
104
+ // which has its own policy gate), so this authorize() is their only checkpoint at the MCP surface.
105
+ case 'forja_spec_check':
106
+ this.authorize('forja_spec_check', 'validate', 'low', []);
107
+ return this.requireSpecChecker().check(input);
108
+ case 'forja_test_run':
109
+ this.authorize('forja_test_run', 'execute', 'medium', []);
110
+ return this.requireTestRunner().run(input);
111
+ case 'forja_execution_validate':
112
+ this.authorize('forja_execution_validate', 'validate', 'low', []);
113
+ return this.requireExecutionValidator().validate(input);
95
114
  default:
96
115
  if (name.startsWith('forja_capability_'))
97
116
  return this.executeDynamicCapability(name, input);
@@ -84,6 +84,13 @@ export declare class SprintEngine {
84
84
  attachTask(sprintId: EntityId, taskId: EntityId): Promise<Sprint>;
85
85
  complete(id: EntityId, validator: CompletionValidator): Promise<Sprint>;
86
86
  private transition;
87
+ /**
88
+ * Read-modify-write without this is a lost-update race: two concurrent callers can both read
89
+ * the same `sprint`, compute different `updated` values, and the second `saveSprint` silently
90
+ * clobbers the first. Re-checking `updatedAt` immediately before writing narrows that window to
91
+ * the store's own read/write latency instead of this method's full async body.
92
+ */
93
+ private saveSprintGuarded;
87
94
  private requireSprint;
88
95
  private record;
89
96
  private updated;
@@ -106,6 +113,8 @@ export declare class TaskEngine {
106
113
  start(id: EntityId): Promise<Task>;
107
114
  block(id: EntityId): Promise<Task>;
108
115
  complete(id: EntityId, validator: CompletionValidator): Promise<Task>;
116
+ /** See SprintEngine.saveSprintGuarded — same lost-update race, same narrowing mitigation. */
117
+ private saveTaskGuarded;
109
118
  private require;
110
119
  private updated;
111
120
  private clean;
@@ -116,7 +125,8 @@ export declare class HandoffEngine {
116
125
  private readonly graph?;
117
126
  private readonly maxItems;
118
127
  private readonly maxItemLength;
119
- constructor(store: OrchestrationStore, graph?: GraphRecorder, maxItems?: number, maxItemLength?: number);
128
+ private readonly maxHandoffsPerCorrelation;
129
+ constructor(store: OrchestrationStore, graph?: GraphRecorder, maxItems?: number, maxItemLength?: number, maxHandoffsPerCorrelation?: number);
120
130
  create(input: CreateHandoffInput): Promise<Handoff>;
121
131
  private compact;
122
132
  }