@payconductor/houndsman 0.13.0 → 0.16.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 (116) hide show
  1. package/README.md +6 -1
  2. package/package.json +1 -1
  3. package/src/cli/commands/compare-command.ts +112 -0
  4. package/src/cli/commands/context-command.ts +1 -0
  5. package/src/cli/commands/findings-command.ts +11 -1
  6. package/src/cli/commands/golden-command.ts +92 -0
  7. package/src/cli/commands/hunt-command.ts +105 -4
  8. package/src/cli/commands/review-command.ts +38 -0
  9. package/src/cli/commands/status-command.ts +3 -2
  10. package/src/cli/help.ts +6 -1
  11. package/src/cli/index.ts +5 -1
  12. package/src/cli/progress.ts +7 -2
  13. package/src/core/ai/ai-client.ts +38 -2
  14. package/src/core/ai/features/brief-enricher.ts +1 -1
  15. package/src/core/ai/features/business-analyzer.ts +61 -0
  16. package/src/core/ai/features/business-summarizer.ts +44 -0
  17. package/src/core/ai/index.ts +8 -0
  18. package/src/core/ai/prompts/brief.ts +33 -7
  19. package/src/core/ai/prompts/business.ts +76 -0
  20. package/src/core/ai/provider-capabilities.ts +12 -0
  21. package/src/core/ai/schemas.ts +70 -2
  22. package/src/core/ai/usage-recorder.ts +53 -1
  23. package/src/core/brief.ts +278 -16
  24. package/src/core/builtins.ts +108 -0
  25. package/src/core/business-summary.ts +583 -0
  26. package/src/core/commands/compare.ts +266 -0
  27. package/src/core/commands/context.ts +6 -2
  28. package/src/core/commands/findings.ts +38 -30
  29. package/src/core/commands/golden.ts +176 -0
  30. package/src/core/commands/review.ts +6 -0
  31. package/src/core/commands/scaffold.ts +29 -0
  32. package/src/core/commands/status.ts +9 -4
  33. package/src/core/compare.ts +310 -0
  34. package/src/core/concurrency.ts +30 -0
  35. package/src/core/config.ts +41 -3
  36. package/src/core/defaults.ts +50 -4
  37. package/src/core/domain/budget.ts +62 -4
  38. package/src/core/domain/classification.ts +12 -2
  39. package/src/core/engine/carryover.ts +4 -0
  40. package/src/core/engine/finalize-pipeline.ts +371 -0
  41. package/src/core/engine/prepare-pipeline.ts +1294 -0
  42. package/src/core/engine/review-context.ts +51 -0
  43. package/src/core/engine/review-options.ts +47 -0
  44. package/src/core/engine/review-scope.ts +14 -1
  45. package/src/core/engine/review-session.ts +11 -13
  46. package/src/core/engine/run-artifacts.ts +196 -0
  47. package/src/core/engine/run-format.ts +4 -0
  48. package/src/core/findings-state.ts +22 -2
  49. package/src/core/github-review.ts +5 -2
  50. package/src/core/golden.ts +346 -0
  51. package/src/core/hunt/hunt-runner.ts +621 -34
  52. package/src/core/hunt/index.ts +40 -1
  53. package/src/core/hunt/maki-intent-prompt.ts +50 -0
  54. package/src/core/hunt/maki-prompt.ts +298 -5
  55. package/src/core/hunt/maki-runner.ts +93 -16
  56. package/src/core/hunt/pool.ts +4 -26
  57. package/src/core/hunt/review-checks.ts +460 -0
  58. package/src/core/logging/index.ts +6 -1
  59. package/src/core/logging/progress.ts +85 -1
  60. package/src/core/orchestrator.ts +33 -1289
  61. package/src/core/paths.ts +6 -3
  62. package/src/core/pr-context.ts +2 -4
  63. package/src/core/prepare-report.ts +61 -0
  64. package/src/core/project-config.ts +18 -1
  65. package/src/core/propagation.ts +127 -0
  66. package/src/core/registry-check.ts +90 -27
  67. package/src/core/renderers/manifest-writer.ts +13 -0
  68. package/src/core/renderers/resume-renderer.ts +151 -11
  69. package/src/core/report-builder.ts +116 -278
  70. package/src/core/severity.ts +245 -0
  71. package/src/core/storage/file/file-storage.ts +7 -3
  72. package/src/core/storage/sqlite/mappers.ts +10 -0
  73. package/src/core/storage/sqlite/schema.ts +104 -23
  74. package/src/core/storage/sqlite/sqlite-storage.ts +22 -9
  75. package/src/core/storage/types.ts +17 -4
  76. package/src/core/storage/work-area.ts +59 -1
  77. package/src/core/types.ts +31 -0
  78. package/src/core/watchdog-registry.ts +21 -3
  79. package/src/index.ts +51 -4
  80. package/src/server/client/ArtifactsPanel.tsx +4 -2
  81. package/src/server/client/FindingCard.tsx +21 -1
  82. package/src/server/client/RunsSection.tsx +5 -0
  83. package/src/server/client/utils/constants.ts +21 -11
  84. package/src/server/client/utils/markdown.ts +1 -1
  85. package/src/server/client/utils/types.ts +14 -2
  86. package/src/server/run-repository.ts +35 -14
  87. package/src/server/styles.css +2 -0
  88. package/src/skill/OUTPUT-FORMAT.md +55 -10
  89. package/src/skill/README.md +19 -14
  90. package/src/skill/SETUP.md +1 -0
  91. package/src/skill/SKILL.md +13 -4
  92. package/src/skill/example-resume.md +43 -0
  93. package/src/skill/hunt.md +205 -58
  94. package/src/skill/train.md +3 -0
  95. package/src/tests/__snapshots__/baseline.test.ts.snap +208 -184
  96. package/src/tests/ai-core.test.ts +46 -0
  97. package/src/tests/ai-features.test.ts +95 -4
  98. package/src/tests/baseline.test.ts +29 -121
  99. package/src/tests/brief-scope.test.ts +250 -0
  100. package/src/tests/business-summary.test.ts +258 -0
  101. package/src/tests/compare.test.ts +256 -0
  102. package/src/tests/findings-state.test.ts +82 -0
  103. package/src/tests/fixtures/fake-model-provider.ts +2 -1
  104. package/src/tests/golden.test.ts +195 -0
  105. package/src/tests/hunt-maki.test.ts +710 -2
  106. package/src/tests/markdown.test.ts +3 -3
  107. package/src/tests/progress.test.ts +29 -1
  108. package/src/tests/propagation.test.ts +119 -0
  109. package/src/tests/review-resume.test.ts +60 -1
  110. package/src/tests/review-scope.test.ts +38 -29
  111. package/src/tests/review-scripts.test.ts +125 -218
  112. package/src/tests/server.test.ts +7 -4
  113. package/src/tests/severity.test.ts +235 -0
  114. package/src/tests/storage.test.ts +194 -9
  115. package/src/core/renderers/report-renderer.ts +0 -66
  116. package/src/skill/example-review.md +0 -66
@@ -27,7 +27,7 @@ export class AiBriefEnricher {
27
27
  instructions: briefInstructions(),
28
28
  prompt: briefPrompt(input),
29
29
  outputSchema: BriefPlanSchema,
30
- maxOutputTokens: 700,
30
+ maxOutputTokens: 1_400,
31
31
  },
32
32
  this.client.projectConfig.aiModelFor(input.watchdogId),
33
33
  );
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Hipóteses de lógica/domínio via IA (`AiBusinessAnalyzer`).
3
+ *
4
+ * Produz **candidatos** para o revisor `general` confirmar ou refutar — nunca
5
+ * achados. Serve para dar cobertura a PRs maiores que o orçamento do brief.
6
+ */
7
+
8
+ import { GENERAL_WATCHDOG_ID } from "../../builtins";
9
+ import type { BusinessInput, BusinessSummary } from "../../business-summary";
10
+ import { buildBusinessPromptPayload } from "../../business-summary";
11
+ import type { JevCandidate } from "../../jev";
12
+ import type { AiClient } from "../ai-client";
13
+ import {
14
+ businessAnalysisInstructions,
15
+ businessAnalysisPrompt,
16
+ } from "../prompts/business";
17
+ import { BusinessHypothesesSchema, type BusinessHypothesis } from "../schemas";
18
+
19
+ /** Confiança mínima para a hipótese virar candidato. */
20
+ const MIN_CONFIDENCE = 0.5;
21
+
22
+ /** Gera hipóteses de fluxo para o watchdog `general`. */
23
+ export class AiBusinessAnalyzer {
24
+ constructor(private readonly client: AiClient) {}
25
+
26
+ /** `true` quando a feature está ligada e há IA disponível. */
27
+ get enabled(): boolean {
28
+ return this.client.available && this.client.features.business;
29
+ }
30
+
31
+ /** Candidatos validados contra os arquivos do escopo. */
32
+ async analyze(input: {
33
+ business: BusinessSummary;
34
+ payload: BusinessInput;
35
+ }): Promise<JevCandidate[]> {
36
+ if (!this.enabled) return [];
37
+ const files = new Set(Object.keys(input.payload.classification.files));
38
+ const result = await this.client.generateObject<{
39
+ hypotheses: BusinessHypothesis[];
40
+ }>("business-analysis", {
41
+ instructions: businessAnalysisInstructions(),
42
+ prompt: businessAnalysisPrompt(
43
+ input.business,
44
+ buildBusinessPromptPayload(input.payload),
45
+ ),
46
+ outputSchema: BusinessHypothesesSchema,
47
+ maxOutputTokens: 1_600,
48
+ });
49
+ if (!result.ok) return [];
50
+ return result.output.hypotheses
51
+ .filter((item) => files.has(item.file) && item.confidence >= MIN_CONFIDENCE)
52
+ .map((item, index) => ({
53
+ watchdogId: GENERAL_WATCHDOG_ID,
54
+ rule: `${item.kind === "domain" ? "Domínio" : "Lógica"}: ${item.statement}`,
55
+ severity: "attention" as const,
56
+ file: item.file,
57
+ confidence: item.confidence,
58
+ questionKey: `business-${index}`,
59
+ }));
60
+ }
61
+ }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Modelo de intenção via IA (`AiBusinessSummarizer`).
3
+ *
4
+ * Fail-open: sem IA/chave/feature a feature fica desligada e o prepare mantém o
5
+ * modelo determinístico. A saída é validada por schema — nada de texto solto.
6
+ */
7
+
8
+ import {
9
+ type BusinessInput,
10
+ type BusinessSummary,
11
+ buildBusinessPromptPayload,
12
+ parseBusinessSummary,
13
+ } from "../../business-summary";
14
+ import type { AiClient } from "../ai-client";
15
+ import { businessInstructions, businessPrompt } from "../prompts/business";
16
+ import { type BusinessSummaryPlan, BusinessSummarySchema } from "../schemas";
17
+
18
+ /** Reconstrói a intenção da PR a partir do diff. */
19
+ export class AiBusinessSummarizer {
20
+ constructor(private readonly client: AiClient) {}
21
+
22
+ /** `true` quando a feature está ligada e há IA disponível. */
23
+ get enabled(): boolean {
24
+ return this.client.available && this.client.features.business;
25
+ }
26
+
27
+ /** Falha-aberto: sem IA ou saída inválida → `null`. */
28
+ async summarize(input: BusinessInput): Promise<BusinessSummary | null> {
29
+ if (!this.enabled) return null;
30
+ const result = await this.client.generateObject<BusinessSummaryPlan>("business", {
31
+ instructions: businessInstructions(),
32
+ prompt: businessPrompt(buildBusinessPromptPayload(input)),
33
+ outputSchema: BusinessSummarySchema,
34
+ // Schema permite 12 fluxos/12 contratos: 1.400 truncava com thinking ligado.
35
+ maxOutputTokens: 2_000,
36
+ });
37
+ if (!result.ok) return null;
38
+ return parseBusinessSummary(
39
+ { ...result.output, source: "ai", headSha: input.headSha },
40
+ "ai",
41
+ input.headSha,
42
+ );
43
+ }
44
+ }
@@ -23,6 +23,8 @@ export {
23
23
  errorMessage,
24
24
  } from "./errors";
25
25
  export { AiBriefEnricher } from "./features/brief-enricher";
26
+ export { AiBusinessAnalyzer } from "./features/business-analyzer";
27
+ export { AiBusinessSummarizer } from "./features/business-summarizer";
26
28
  export { AiClassifier } from "./features/classifier";
27
29
  export { AiContextSummarizer } from "./features/context-summarizer";
28
30
  export { AiPreAnalyzer } from "./features/pre-analyzer";
@@ -33,8 +35,14 @@ export {
33
35
  type AiCandidate,
34
36
  type AiClassification,
35
37
  type AiVerdict,
38
+ type BriefCheck,
39
+ BriefCheckSchema,
36
40
  type BriefPlan,
37
41
  BriefPlanSchema,
42
+ BusinessHypothesesSchema,
43
+ type BusinessHypothesis,
44
+ type BusinessSummaryPlan,
45
+ BusinessSummarySchema,
38
46
  CandidateSchema,
39
47
  ClassificationSchema,
40
48
  type ContextSummaryPlan,
@@ -6,6 +6,8 @@
6
6
  */
7
7
 
8
8
  import type { AstFileBrief } from "../../ast/types";
9
+ import { type BusinessSummary, renderBusinessLines } from "../../business-summary";
10
+ import type { ChangedScope } from "../../changed-scope";
9
11
  import type { ChurnMap, Rule, WatchdogRenderContext } from "../../types";
10
12
  import { buildSystem } from "./base";
11
13
 
@@ -21,6 +23,12 @@ export type BriefPromptInput = {
21
23
  context?: WatchdogRenderContext | null;
22
24
  ast?: readonly AstFileBrief[];
23
25
  docs?: readonly string[];
26
+ /** Modelo de intenção da PR (contrato esperado). */
27
+ business?: BusinessSummary | null;
28
+ /** Trechos alterados — a única fonte real para verificar lógica. */
29
+ snippets?: readonly { file: string; snippet: string }[];
30
+ /** Faixas revisáveis por arquivo. */
31
+ changedScope?: ChangedScope;
24
32
  };
25
33
 
26
34
  /** Instruções de sistema do enriquecimento. */
@@ -29,11 +37,13 @@ export function briefInstructions(): string {
29
37
  "Você é um revisor sênior que prepara um plano de leitura para um watchdog (revisor) especializado.",
30
38
  [
31
39
  "As regras fornecidas são o PISO da revisão, não o teto.",
32
- "Além delas, procure riscos de consistência lógica: nome/contrato vs comportamento (ex.: `fazA` que faz `fazB`), fluxos incompletos, estados inválidos, off-by-one e bordas.",
33
- "Procure também riscos do domínio de negócio: transições de estado, idempotência, arredondamento, timezone, autorização e invariantes implícitas.",
34
- "Sugira foco de leitura (até 5), perguntas de verificação (até 3), riscos (até 3), verificações de lógica (até 3) e de domínio (até 3).",
40
+ "Derive cada verificação dos trechos alterados fornecidos — não apenas do nome do arquivo.",
41
+ "Toda verificação cita arquivo e, quando possível, símbolo; sem âncora, não sugira.",
42
+ "Além das regras, procure riscos de consistência lógica: nome/contrato vs comportamento (ex.: `fazA` que faz `fazB`), fluxos incompletos, estados inválidos, off-by-one e bordas.",
43
+ "Procure também riscos do domínio de negócio: transições de estado, idempotência, arredondamento, timezone, autorização, paridade de capacidade e invariantes implícitas.",
44
+ "Sugira foco de leitura (até 5), perguntas (até 3), riscos (até 3), verificações de lógica (até 4) e de domínio (até 4).",
35
45
  "Sugira verificações, nunca afirme violação; não crie regra nova nem invente arquivo, linha ou achado.",
36
- "Se uma suspeita não couber em nenhuma regra, coloque-a em `logic`/`domain` como pergunta de verificação.",
46
+ "Se uma suspeita não couber em nenhuma regra, coloque-a em `logic`/`domain` como verificação ancorada.",
37
47
  "Não repita o texto literal das regras; o brief já as contém.",
38
48
  ],
39
49
  );
@@ -62,6 +72,15 @@ export function briefPrompt(input: BriefPromptInput): string {
62
72
  lines.push(`Motivação: ${input.context.motivation}`);
63
73
  for (const item of input.context.changeSummary ?? []) lines.push(`- ${item}`);
64
74
  }
75
+ if (input.business) {
76
+ const business = renderBusinessLines(input.business, {
77
+ flows: 8,
78
+ invariants: 8,
79
+ contracts: 8,
80
+ states: 4,
81
+ });
82
+ if (business.length > 0) lines.push("", "## Modelo de intenção", ...business);
83
+ }
65
84
  if (input.ast && input.ast.length > 0) {
66
85
  lines.push("", "## Estrutura (AST)");
67
86
  for (const entry of input.ast) {
@@ -71,15 +90,22 @@ export function briefPrompt(input: BriefPromptInput): string {
71
90
  );
72
91
  }
73
92
  }
93
+ if (input.snippets && input.snippets.length > 0) {
94
+ lines.push("", "## Trechos alterados (diff)");
95
+ for (const item of input.snippets.slice(0, 12)) {
96
+ lines.push(`### ${item.file}`, "```diff", item.snippet.trimEnd(), "```");
97
+ }
98
+ }
74
99
  if (input.docs && input.docs.length > 0) {
75
100
  lines.push("", "## Docs disponíveis", ...input.docs.map((doc) => `- ${doc}`));
76
101
  }
77
102
  lines.push(
78
103
  "",
79
104
  "## Revisão além das regras",
80
- "As regras são o piso. Aponte verificações de consistência lógica e de domínio",
81
- "que mereçam inspeção mesmo sem regra explícita (nome vs comportamento, estados,",
82
- "transições, idempotência, bordas). Sugira verificações; não afirme violações.",
105
+ "As regras são o piso. Aponte verificações de lógica e domínio ancoradas nos",
106
+ "trechos alterados (nome vs comportamento, estados, transições, idempotência,",
107
+ "paridade de capacidade, credencial, bordas). Sugira verificações; não afirme",
108
+ "violações.",
83
109
  "",
84
110
  "Produza o plano de revisão em JSON (focus, questions, risks, logic, domain).",
85
111
  );
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Prompt do modelo de intenção (`AiBusinessSummarizer`) e das hipóteses
3
+ * (`AiBusinessAnalyzer`).
4
+ *
5
+ * Os dois derivam **do diff**, nunca da prosa da PR. O primeiro descreve o
6
+ * contrato esperado; o segundo aponta suspeitas para o revisor `general`
7
+ * confirmar ou refutar (nunca viram achado sozinhas).
8
+ */
9
+
10
+ import { buildSystem, clip, OUTPUT_LANGUAGE_RULE } from "./base";
11
+
12
+ /** Instruções do resumo de negócio. */
13
+ export function businessInstructions(): string {
14
+ return buildSystem(
15
+ "Você reconstrói a intenção de uma Pull Request a partir do diff real.",
16
+ [
17
+ OUTPUT_LANGUAGE_RULE,
18
+ "Descreva o comportamento que a PR promete entregar, não a estrutura do código.",
19
+ "Derive do diff fornecido: fluxos, invariantes, contratos e estados.",
20
+ "Paridade de capacidade é prioridade: se um lado declara feature/método/evento, verifique se o outro lado o honra.",
21
+ "Fluxos de ciclo de vida contam: criação, renovação, cancelamento, retry, webhook e erro.",
22
+ "Registre o que não estiver claro em `openQuestions`; não invente.",
23
+ "NÃO produza achados, severidade, arquivo:linha ou recomendação de correção.",
24
+ "Seja específico e curto: nomes de fluxo/contrato citam símbolos e arquivos reais.",
25
+ ],
26
+ );
27
+ }
28
+
29
+ /** Prompt do usuário com o payload compactado. */
30
+ export function businessPrompt(payload: unknown): string {
31
+ return [
32
+ "Reconstrua a intenção da PR abaixo.",
33
+ "",
34
+ "```json",
35
+ clip(JSON.stringify(payload), 24_000),
36
+ "```",
37
+ "",
38
+ "Produza o modelo de intenção em JSON.",
39
+ ].join("\n");
40
+ }
41
+
42
+ /** Instruções das hipóteses de lógica/domínio. */
43
+ export function businessAnalysisInstructions(): string {
44
+ return buildSystem(
45
+ "Você aponta suspeitas de gap de lógica/domínio para um revisor confirmar.",
46
+ [
47
+ OUTPUT_LANGUAGE_RULE,
48
+ "Use o modelo de intenção e os trechos alterados fornecidos.",
49
+ "Cada hipótese precisa citar um arquivo do escopo e uma afirmação concreta.",
50
+ "Prefira gaps de fluxo: caminho incompleto, capacidade declarada e não honrada, credencial/contexto divergente, estado sem tratamento, identificador trocado.",
51
+ "Confiança calibrada (0–1); abaixo de 0.5 não vale reportar.",
52
+ '`kind: "domain"` para invariantes/fluxo de negócio; `kind: "logic"` para nome/contrato vs comportamento.',
53
+ "NÃO invente arquivos e NÃO produza severidade — isto não é um achado.",
54
+ "No máximo 12 hipóteses.",
55
+ ],
56
+ );
57
+ }
58
+
59
+ /** Prompt do usuário com intenção + trechos alterados. */
60
+ export function businessAnalysisPrompt(business: unknown, payload: unknown): string {
61
+ return [
62
+ "## Modelo de intenção",
63
+ "",
64
+ "```json",
65
+ clip(JSON.stringify(business), 8_000),
66
+ "```",
67
+ "",
68
+ "## Diff compactado",
69
+ "",
70
+ "```json",
71
+ clip(JSON.stringify(payload), 16_000),
72
+ "```",
73
+ "",
74
+ "Produza as hipóteses em JSON.",
75
+ ].join("\n");
76
+ }
@@ -43,3 +43,15 @@ export function temperatureApplies(
43
43
  if (provider !== "deepseek") return true;
44
44
  return !deepSeekThinkingEnabled(modelId, providerOptions);
45
45
  }
46
+
47
+ /**
48
+ * Opções para tarefas estruturadas curtas (resumo, plano, classificação).
49
+ *
50
+ * O thinking do DeepSeek V4 consome o teto de saída e dominava a latência: a
51
+ * resposta JSON truncava (`finishReason: "length"`) e a feature caía no
52
+ * fallback sem produzir nada. Desligar o raciocínio nessas chamadas mantém o
53
+ * schema e corta a latência. Providers não-DeepSeek ignoram a chave.
54
+ */
55
+ export const LEAN_PROVIDER_OPTIONS: AiProviderOptions = {
56
+ deepseek: { thinking: { type: "disabled" } },
57
+ };
@@ -43,18 +43,86 @@ export const TechnicalSummarySchema = z.object({
43
43
  });
44
44
  export type TechnicalSummaryPlan = z.infer<typeof TechnicalSummarySchema>;
45
45
 
46
+ /** Verificação sugerida — sempre ancorada em arquivo/símbolo quando possível. */
47
+ export const BriefCheckSchema = z.object({
48
+ statement: z.string().min(1).max(240),
49
+ file: z.string().max(200).optional(),
50
+ symbol: z.string().max(120).optional(),
51
+ /** Invariante que a verificação protege (`domain`). */
52
+ invariant: z.string().max(200).optional(),
53
+ });
54
+ export type BriefCheck = z.infer<typeof BriefCheckSchema>;
55
+
46
56
  /** Plano de revisão sugerido por IA para um brief. */
47
57
  export const BriefPlanSchema = z.object({
48
58
  focus: z.array(z.string()).max(5).default([]),
49
59
  questions: z.array(z.string()).max(3).default([]),
50
60
  risks: z.array(z.string()).max(3).default([]),
51
61
  /** Verificações de consistência lógica (fora das regras explícitas). */
52
- logic: z.array(z.string()).max(3).default([]),
62
+ logic: z.array(BriefCheckSchema).max(4).default([]),
53
63
  /** Riscos do domínio de negócio (fora das regras explícitas). */
54
- domain: z.array(z.string()).max(3).default([]),
64
+ domain: z.array(BriefCheckSchema).max(4).default([]),
55
65
  });
56
66
  export type BriefPlan = z.infer<typeof BriefPlanSchema>;
57
67
 
68
+ /** Modelo de intenção da PR (`business-summary.json`). */
69
+ export const BusinessSummarySchema = z.object({
70
+ intent: z.string().max(800).optional(),
71
+ flows: z
72
+ .array(
73
+ z.object({
74
+ name: z.string().min(1).max(120),
75
+ trigger: z.string().max(240).optional(),
76
+ expected: z.string().max(400).optional(),
77
+ files: z.array(z.string().max(200)).max(20).optional(),
78
+ }),
79
+ )
80
+ .max(12)
81
+ .default([]),
82
+ invariants: z.array(z.string().max(300)).max(12).default([]),
83
+ contracts: z
84
+ .array(
85
+ z.object({
86
+ name: z.string().min(1).max(120),
87
+ sides: z.array(z.string().max(160)).max(8).optional(),
88
+ expectation: z.string().max(400).optional(),
89
+ }),
90
+ )
91
+ .max(12)
92
+ .default([]),
93
+ states: z
94
+ .array(
95
+ z.object({
96
+ name: z.string().min(1).max(120),
97
+ transitions: z.array(z.string().max(200)).max(12).optional(),
98
+ }),
99
+ )
100
+ .max(8)
101
+ .default([]),
102
+ nonGoals: z.array(z.string().max(240)).max(8).optional(),
103
+ openQuestions: z.array(z.string().max(300)).max(8).optional(),
104
+ });
105
+ export type BusinessSummaryPlan = z.infer<typeof BusinessSummarySchema>;
106
+
107
+ /** Hipóteses de lógica/domínio (candidatos, nunca achados). */
108
+ export const BusinessHypothesesSchema = z.object({
109
+ hypotheses: z
110
+ .array(
111
+ z.object({
112
+ file: z.string().min(1),
113
+ kind: z.enum(["logic", "domain"]),
114
+ statement: z.string().min(1).max(300),
115
+ invariant: z.string().max(200).optional(),
116
+ confidence: z.number().min(0).max(1),
117
+ }),
118
+ )
119
+ .max(12)
120
+ .default([]),
121
+ });
122
+ export type BusinessHypothesis = z.infer<
123
+ typeof BusinessHypothesesSchema
124
+ >["hypotheses"][number];
125
+
58
126
  /** Classificação de arquivos não classificados. */
59
127
  export const ClassificationSchema = z.object({
60
128
  assignments: z
@@ -17,17 +17,36 @@ export type AiUsageEntry = {
17
17
  usage: AiUsage;
18
18
  };
19
19
 
20
+ /** Chamada que falhou (timeout, truncamento, schema) — não consome tokens. */
21
+ export type AiFailureEntry = {
22
+ feature: string;
23
+ model: string;
24
+ at: string;
25
+ durationMs: number;
26
+ finishReason?: string;
27
+ error: string;
28
+ };
29
+
30
+ /** Uso agregado + tentativas/falhas (vai para `prepare-report.json`). */
31
+ export type AiUsageSummary = AiUsage & {
32
+ attempts: number;
33
+ failures: AiFailureEntry[];
34
+ };
35
+
20
36
  /** Formato persistido em `ai-usage.json`. */
21
37
  export type AiUsageFile = {
22
38
  provider: string;
23
39
  model: string;
24
40
  total: AiUsage;
41
+ attempts: number;
25
42
  entries: AiUsageEntry[];
43
+ failures: AiFailureEntry[];
26
44
  };
27
45
 
28
46
  /** Acumulador de uso (em memória) com persistência opcional. */
29
47
  export class AiUsageRecorder {
30
48
  private readonly entries: AiUsageEntry[] = [];
49
+ private readonly failed: AiFailureEntry[] = [];
31
50
  private readonly provider: string;
32
51
  private readonly model: string;
33
52
 
@@ -41,7 +60,23 @@ export class AiUsageRecorder {
41
60
  this.entries.push({ feature, model, at: systemClock(), usage: { ...usage } });
42
61
  }
43
62
 
44
- /** Total agregado de todas as chamadas. */
63
+ /** Registra uma tentativa que falhou (fail-open: nunca derruba a revisão). */
64
+ recordFailure(
65
+ feature: string,
66
+ model: string,
67
+ detail: { durationMs: number; error: string; finishReason?: string },
68
+ ): void {
69
+ this.failed.push({
70
+ feature,
71
+ model,
72
+ at: systemClock(),
73
+ durationMs: detail.durationMs,
74
+ error: detail.error,
75
+ ...(detail.finishReason ? { finishReason: detail.finishReason } : {}),
76
+ });
77
+ }
78
+
79
+ /** Total agregado de todas as chamadas concluídas. */
45
80
  get total(): AiUsage {
46
81
  return this.entries.reduce(
47
82
  (acc, entry) => addUsage(acc, entry.usage),
@@ -49,13 +84,30 @@ export class AiUsageRecorder {
49
84
  );
50
85
  }
51
86
 
87
+ /** Tentativas (sucesso + falha) — a métrica honesta de custo/latência. */
88
+ get attempts(): number {
89
+ return this.entries.length + this.failed.length;
90
+ }
91
+
92
+ /** Falhas registradas, na ordem em que ocorreram. */
93
+ get failures(): readonly AiFailureEntry[] {
94
+ return this.failed;
95
+ }
96
+
97
+ /** Resumo para o `prepare-report.json`. */
98
+ get summary(): AiUsageSummary {
99
+ return { ...this.total, attempts: this.attempts, failures: [...this.failed] };
100
+ }
101
+
52
102
  /** Snapshot serializável. */
53
103
  toJSON(): AiUsageFile {
54
104
  return {
55
105
  provider: this.provider,
56
106
  model: this.model,
57
107
  total: this.total,
108
+ attempts: this.attempts,
58
109
  entries: [...this.entries],
110
+ failures: [...this.failed],
59
111
  };
60
112
  }
61
113