@payconductor/houndsman 0.5.0 → 0.6.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 (153) hide show
  1. package/README.md +24 -4
  2. package/assets/grammars/tree-sitter-javascript.wasm +0 -0
  3. package/assets/grammars/tree-sitter-tsx.wasm +0 -0
  4. package/assets/grammars/tree-sitter-typescript.wasm +0 -0
  5. package/assets/grammars/web-tree-sitter.wasm +0 -0
  6. package/package.json +11 -3
  7. package/src/cli/commands/command.ts +5 -0
  8. package/src/cli/commands/doctor-command.ts +116 -24
  9. package/src/cli/commands/hunt-command.ts +25 -0
  10. package/src/cli/help.ts +17 -1
  11. package/src/cli/index.ts +10 -6
  12. package/src/core/ai/ai-client.ts +221 -0
  13. package/src/core/ai/ai-sdk-model-provider.ts +101 -0
  14. package/src/core/ai/errors.ts +36 -0
  15. package/src/core/ai/features/brief-enricher.ts +62 -0
  16. package/src/core/ai/features/classifier.ts +50 -0
  17. package/src/core/ai/features/context-summarizer.ts +31 -0
  18. package/src/core/ai/features/pre-analyzer.ts +51 -0
  19. package/src/core/ai/features/verifier.ts +45 -0
  20. package/src/core/ai/index.ts +56 -0
  21. package/src/core/ai/model-factory.ts +137 -0
  22. package/src/core/ai/prompts/base.ts +36 -0
  23. package/src/core/ai/prompts/brief.ts +87 -0
  24. package/src/core/ai/prompts/classification.ts +36 -0
  25. package/src/core/ai/prompts/context.ts +29 -0
  26. package/src/core/ai/prompts/pre-analysis.ts +49 -0
  27. package/src/core/ai/prompts/verify.ts +40 -0
  28. package/src/core/ai/schemas.ts +110 -0
  29. package/src/core/ai/types.ts +76 -0
  30. package/src/core/ai/usage-budget.ts +75 -0
  31. package/src/core/ai/usage-recorder.ts +79 -0
  32. package/src/core/assets.ts +16 -0
  33. package/src/core/ast/diff.ts +220 -0
  34. package/src/core/ast/impact.ts +127 -0
  35. package/src/core/ast/parser.ts +167 -0
  36. package/src/core/ast/service.ts +233 -0
  37. package/src/core/ast/symbols.ts +294 -0
  38. package/src/core/ast/types.ts +125 -0
  39. package/src/core/brief.ts +138 -0
  40. package/src/core/commands/findings.ts +59 -1
  41. package/src/core/commands/review.ts +2 -0
  42. package/src/core/commands/scaffold.ts +159 -10
  43. package/src/core/commands/update.ts +5 -3
  44. package/src/core/config.ts +85 -0
  45. package/src/core/defaults.ts +27 -0
  46. package/src/core/domain/watchdog.ts +43 -5
  47. package/src/core/engine/houndsman-engine.ts +16 -1
  48. package/src/core/engine/review-scope.ts +52 -6
  49. package/src/core/engine/review-session.ts +27 -2
  50. package/src/core/env.ts +101 -0
  51. package/src/core/file-classifier.ts +25 -4
  52. package/src/core/jev/jev-client.ts +8 -7
  53. package/src/core/jev/jev-verify.ts +2 -1
  54. package/src/core/logging/index.ts +17 -0
  55. package/src/core/logging/logger.ts +187 -0
  56. package/src/core/orchestrator.ts +357 -9
  57. package/src/core/project-config.ts +123 -1
  58. package/src/core/registry-check.ts +148 -6
  59. package/src/core/renderers/manifest-writer.ts +33 -0
  60. package/src/core/rule-text.ts +97 -0
  61. package/src/core/services/file-classifier.ts +10 -3
  62. package/src/core/services/verifier.ts +14 -3
  63. package/src/core/storage/paths.ts +6 -5
  64. package/src/core/storage/types.ts +6 -0
  65. package/src/core/storage/work-area.ts +12 -0
  66. package/src/core/types.ts +37 -1
  67. package/src/core/verify.ts +17 -5
  68. package/src/harness/README.md +15 -0
  69. package/src/harness/agent/agent-context.ts +33 -0
  70. package/src/harness/agent/agent-errors.ts +30 -0
  71. package/src/harness/agent/agent-factory.ts +45 -0
  72. package/src/harness/agent/agent-reporter.ts +34 -0
  73. package/src/harness/agent/agent-result.ts +16 -0
  74. package/src/harness/agent/agent-runner.ts +32 -0
  75. package/src/harness/agent/agent-scheduler.ts +37 -0
  76. package/src/harness/agent/review-agent.ts +391 -0
  77. package/src/harness/config/harness-config.ts +84 -0
  78. package/src/harness/hunt/hunt-harness.ts +83 -0
  79. package/src/harness/hunt/hunt-options.ts +75 -0
  80. package/src/harness/hunt/hunt-result.ts +17 -0
  81. package/src/harness/hunt/hunt-session.ts +372 -0
  82. package/src/harness/hunt/review-planner.ts +98 -0
  83. package/src/harness/index.ts +36 -0
  84. package/src/harness/investigation/agent-state.ts +134 -0
  85. package/src/harness/investigation/evidence-verifier.ts +129 -0
  86. package/src/harness/investigation/evidence.ts +110 -0
  87. package/src/harness/investigation/finding-critic.ts +96 -0
  88. package/src/harness/investigation/investigation-planner.ts +118 -0
  89. package/src/harness/investigation/investigation-task.ts +10 -0
  90. package/src/harness/investigation/review-journal.ts +87 -0
  91. package/src/harness/investigation/rule-analyzer.ts +178 -0
  92. package/src/harness/investigation/rule-signals.ts +110 -0
  93. package/src/harness/prompts/agent-schemas.ts +57 -0
  94. package/src/harness/prompts/reviewer-prompt-builder.ts +101 -0
  95. package/src/harness/prompts/states/conclude-prompt.ts +16 -0
  96. package/src/harness/prompts/states/investigate-prompt.ts +37 -0
  97. package/src/harness/prompts/states/orient-prompt.ts +15 -0
  98. package/src/harness/prompts/states/verify-prompt.ts +22 -0
  99. package/src/harness/tools/agent-tool.ts +102 -0
  100. package/src/harness/tools/builtin/changed-symbols-tool.ts +48 -0
  101. package/src/harness/tools/builtin/doc-context-tool.ts +74 -0
  102. package/src/harness/tools/builtin/file-outline-tool.ts +66 -0
  103. package/src/harness/tools/builtin/find-references-tool.ts +66 -0
  104. package/src/harness/tools/builtin/find-symbol-tool.ts +91 -0
  105. package/src/harness/tools/builtin/helpers.ts +115 -0
  106. package/src/harness/tools/builtin/impact-tool.ts +48 -0
  107. package/src/harness/tools/builtin/imports-exports-tool.ts +53 -0
  108. package/src/harness/tools/builtin/index.ts +59 -0
  109. package/src/harness/tools/builtin/list-files-tool.ts +85 -0
  110. package/src/harness/tools/builtin/pr-context-tool.ts +41 -0
  111. package/src/harness/tools/builtin/read-file-range-tool.ts +73 -0
  112. package/src/harness/tools/builtin/rule-signals-tool.ts +36 -0
  113. package/src/harness/tools/builtin/search-code-tool.ts +65 -0
  114. package/src/harness/tools/builtin/symbol-context-tool.ts +106 -0
  115. package/src/harness/tools/builtin/tests-for-symbol-tool.ts +61 -0
  116. package/src/harness/tools/path-guard.ts +90 -0
  117. package/src/harness/tools/result-limiter.ts +49 -0
  118. package/src/harness/tools/secret-redactor.ts +54 -0
  119. package/src/harness/tools/tool-cache.ts +50 -0
  120. package/src/harness/tools/tool-call-budget.ts +60 -0
  121. package/src/harness/tools/tool-context.ts +5 -0
  122. package/src/harness/tools/tool-middleware.ts +105 -0
  123. package/src/harness/tools/tool-policy.ts +51 -0
  124. package/src/harness/tools/tool-registry.ts +112 -0
  125. package/src/harness/tools/tool-result.ts +15 -0
  126. package/src/harness/tools/toolbox.ts +36 -0
  127. package/src/harness/validation/finding-validator.ts +119 -0
  128. package/src/index.ts +46 -0
  129. package/src/server/client/utils/constants.ts +27 -5
  130. package/src/server/client/utils/types.ts +6 -0
  131. package/src/server/index.ts +3 -2
  132. package/src/skill/OUTPUT-FORMAT.md +12 -0
  133. package/src/skill/SETUP.md +6 -2
  134. package/src/skill/hunt.md +14 -2
  135. package/src/skill/verify.md +1 -1
  136. package/src/tests/__snapshots__/baseline.test.ts.snap +96 -14
  137. package/src/tests/ai-core.test.ts +120 -0
  138. package/src/tests/ai-features.test.ts +183 -0
  139. package/src/tests/ast.test.ts +335 -0
  140. package/src/tests/env.test.ts +69 -0
  141. package/src/tests/fallback.test.ts +172 -0
  142. package/src/tests/fixtures/fake-agent-tools.ts +69 -0
  143. package/src/tests/fixtures/fake-investigation.ts +64 -0
  144. package/src/tests/fixtures/fake-model-provider.ts +48 -0
  145. package/src/tests/harness-agent.test.ts +122 -0
  146. package/src/tests/harness-investigation.test.ts +206 -0
  147. package/src/tests/harness-tools.test.ts +148 -0
  148. package/src/tests/hunt-command.test.ts +212 -0
  149. package/src/tests/logger.test.ts +83 -0
  150. package/src/tests/review-scope.test.ts +11 -11
  151. package/src/tests/rule-analyzer.test.ts +61 -0
  152. package/src/tests/tool-contracts.test.ts +82 -0
  153. package/src/tests/verify.test.ts +1 -1
@@ -6,9 +6,25 @@
6
6
  * O contrato do consumidor (`houndsman.config.ts`) não muda.
7
7
  */
8
8
 
9
- import type { HoundsmanConfig, HoundsmanStorage } from "./config";
9
+ import type {
10
+ AiProviderKind,
11
+ HoundsmanAi,
12
+ HoundsmanAiFeatures,
13
+ HoundsmanAst,
14
+ HoundsmanConfig,
15
+ HoundsmanStorage,
16
+ } from "./config";
10
17
  import {
18
+ DEFAULT_AI_CONCURRENCY,
19
+ DEFAULT_AI_MAX_CALLS_PER_REVIEW,
20
+ DEFAULT_AI_MAX_OUTPUT_TOKENS,
21
+ DEFAULT_AI_MAX_STEPS,
22
+ DEFAULT_AI_MODEL,
23
+ DEFAULT_AI_PROVIDER,
24
+ DEFAULT_AI_TIMEOUT_MS,
11
25
  DEFAULT_ALWAYS_INCLUDE_DOCS,
26
+ DEFAULT_AST_MAX_FILE_BYTES,
27
+ DEFAULT_AST_MAX_IMPACT_FILES,
12
28
  DEFAULT_JEV_CONCURRENCY,
13
29
  DEFAULT_MAX_FILES_PER_BRIEF,
14
30
  } from "./defaults";
@@ -32,6 +48,26 @@ export class ProjectConfig<TId extends string = string> {
32
48
  return this.raw.storage ?? {};
33
49
  }
34
50
 
51
+ /** Config do AST (objeto vazio quando ausente). */
52
+ get ast(): HoundsmanAst {
53
+ return this.raw.ast ?? {};
54
+ }
55
+
56
+ /** AST habilitado (default: ligado; falhas de grammar são fail-open). */
57
+ get astEnabled(): boolean {
58
+ return this.ast.enabled !== false;
59
+ }
60
+
61
+ get astMaxFileBytes(): number {
62
+ const value = this.ast.maxFileBytes;
63
+ return value !== undefined && value > 0 ? value : DEFAULT_AST_MAX_FILE_BYTES;
64
+ }
65
+
66
+ get astMaxImpactFiles(): number {
67
+ const value = this.ast.maxImpactFiles;
68
+ return value !== undefined && value >= 0 ? value : DEFAULT_AST_MAX_IMPACT_FILES;
69
+ }
70
+
35
71
  get maxFilesPerBrief(): number {
36
72
  const value = this.raw.budgets?.maxFilesPerBrief;
37
73
  return value !== undefined && value > 0 ? value : DEFAULT_MAX_FILES_PER_BRIEF;
@@ -53,4 +89,90 @@ export class ProjectConfig<TId extends string = string> {
53
89
  get docMappings(): readonly (readonly [RegExp, readonly string[]])[] {
54
90
  return this.raw.docMappings;
55
91
  }
92
+
93
+ /** Config de IA (objeto vazio quando ausente). */
94
+ get ai(): HoundsmanAi {
95
+ return this.raw.ai ?? {};
96
+ }
97
+
98
+ /** IA habilitada (default: ligada; sem chave é fail-open). */
99
+ get aiEnabled(): boolean {
100
+ return this.ai.enabled !== false;
101
+ }
102
+
103
+ get aiProvider(): AiProviderKind {
104
+ return this.ai.provider ?? DEFAULT_AI_PROVIDER;
105
+ }
106
+
107
+ get aiModel(): string {
108
+ const value = this.ai.model?.trim();
109
+ return value && value.length > 0 ? value : DEFAULT_AI_MODEL;
110
+ }
111
+
112
+ get aiConcurrency(): number {
113
+ return positive(this.ai.concurrency, DEFAULT_AI_CONCURRENCY);
114
+ }
115
+
116
+ get aiMaxSteps(): number {
117
+ return positive(this.ai.maxSteps, DEFAULT_AI_MAX_STEPS);
118
+ }
119
+
120
+ get aiMaxOutputTokens(): number {
121
+ return positive(this.ai.maxOutputTokens, DEFAULT_AI_MAX_OUTPUT_TOKENS);
122
+ }
123
+
124
+ get aiTemperature(): number {
125
+ const value = this.ai.temperature;
126
+ return typeof value === "number" && Number.isFinite(value) ? value : 0;
127
+ }
128
+
129
+ get aiTimeoutMs(): number {
130
+ return positive(this.ai.timeoutMs, DEFAULT_AI_TIMEOUT_MS);
131
+ }
132
+
133
+ get aiMaxCallsPerReview(): number {
134
+ return positive(this.ai.maxCallsPerReview, DEFAULT_AI_MAX_CALLS_PER_REVIEW);
135
+ }
136
+
137
+ /** Teto de tokens por review (0/ausente = sem teto). */
138
+ get aiMaxTokensPerReview(): number | undefined {
139
+ const value = this.ai.maxTokensPerReview;
140
+ return value !== undefined && value > 0 ? value : undefined;
141
+ }
142
+
143
+ /** Features resolvidas com defaults (`context`/`brief` ligadas). */
144
+ get aiFeatures(): Required<HoundsmanAiFeatures> {
145
+ const features = this.ai.features ?? {};
146
+ return {
147
+ context: features.context !== false,
148
+ brief: features.brief !== false,
149
+ classification: features.classification === true,
150
+ preAnalysis: features.preAnalysis === true,
151
+ verify: features.verify === true,
152
+ };
153
+ }
154
+
155
+ /** Modelo efetivo de um watchdog (override por watchdog ou global). */
156
+ aiModelFor(watchdogId: string): string {
157
+ const override = this.ai.watchdogs?.[watchdogId]?.model?.trim();
158
+ return override && override.length > 0 ? override : this.aiModel;
159
+ }
160
+
161
+ /** Passos efetivos de um watchdog (override por watchdog ou global). */
162
+ aiMaxStepsFor(watchdogId: string): number {
163
+ return positive(this.ai.watchdogs?.[watchdogId]?.maxSteps, this.aiMaxSteps);
164
+ }
165
+
166
+ /** Tokens de saída efetivos de um watchdog. */
167
+ aiMaxOutputTokensFor(watchdogId: string): number {
168
+ return positive(
169
+ this.ai.watchdogs?.[watchdogId]?.maxOutputTokens,
170
+ this.aiMaxOutputTokens,
171
+ );
172
+ }
173
+ }
174
+
175
+ /** Inteiro positivo ou o default. */
176
+ function positive(value: number | undefined, fallback: number): number {
177
+ return value !== undefined && Number.isFinite(value) && value > 0 ? value : fallback;
56
178
  }
@@ -6,8 +6,10 @@
6
6
  */
7
7
 
8
8
  import type { HoundsmanConfig } from "./config";
9
+ import { env } from "./env";
9
10
  import { JevQuestionFactory } from "./jev";
10
11
  import { renderReport, sanitizeBranch } from "./report-builder";
12
+ import { hasExplicitPolarity } from "./rule-text";
11
13
  import type { WatchdogMeta } from "./types";
12
14
 
13
15
  /** `id` da definição bate com a chave; `description` não vazio. */
@@ -27,17 +29,56 @@ function checkDefinitions(config: HoundsmanConfig, problems: string[]): void {
27
29
  }
28
30
  }
29
31
 
30
- /** Todo watchdog precisa declarar ao menos um arquivo em `classify`. */
32
+ /** Todo watchdog precisa declarar ao menos um arquivo em `classify` (fallback isento). */
31
33
  function checkClassification(config: HoundsmanConfig, problems: string[]): void {
32
34
  for (const id of config.watchdogIds) {
33
35
  const def = config.watchdogs[id];
34
36
  if (!def) continue;
37
+ if (def.fallback) continue;
35
38
  if (!def.classify || def.classify.length === 0) {
36
39
  problems.push(`Watchdog '${id}' não declara nenhum padrão em 'classify'`);
37
40
  }
38
41
  }
39
42
  }
40
43
 
44
+ /** Fallback: no máximo um; `classify` é ignorado; precisa de regras. */
45
+ function checkFallbacks(config: HoundsmanConfig, warnings: string[]): void {
46
+ const fallbacks = config.watchdogIds.filter(
47
+ (id) => config.watchdogs[id]?.fallback === true,
48
+ );
49
+ if (fallbacks.length > 1) {
50
+ warnings.push(
51
+ `Mais de um watchdog fallback (${fallbacks.join(", ")}); o primeiro declarado vence.`,
52
+ );
53
+ }
54
+ for (const id of fallbacks) {
55
+ const def = config.watchdogs[id];
56
+ if (!def) continue;
57
+ if (def.classify && def.classify.length > 0) {
58
+ warnings.push(`watchdogs['${id}'] é fallback — 'classify' é ignorado.`);
59
+ }
60
+ if (def.rules.length === 0) {
61
+ warnings.push(`Watchdog fallback '${id}' não declara nenhuma regra.`);
62
+ }
63
+ }
64
+ }
65
+
66
+ /** Findings emergentes exigem ao menos uma regra de lógica/domínio como piso. */
67
+ function checkEmergent(config: HoundsmanConfig, warnings: string[]): void {
68
+ for (const id of config.watchdogIds) {
69
+ const def = config.watchdogs[id];
70
+ if (!def?.allowEmergentFindings) continue;
71
+ const hasGeneric = def.rules.some((rule) =>
72
+ /l[oó]gica|dom[ií]nio/i.test(rule.text),
73
+ );
74
+ if (!hasGeneric) {
75
+ warnings.push(
76
+ `watchdogs['${id}'].allowEmergentFindings sem regra de lógica/domínio — o piso fica implícito.`,
77
+ );
78
+ }
79
+ }
80
+ }
81
+
41
82
  /** Smoke test dos helpers críticos de renderização. */
42
83
  function checkRendering(config: HoundsmanConfig, problems: string[]): void {
43
84
  if (sanitizeBranch("feature/x") !== "feature-x") {
@@ -106,9 +147,6 @@ function checkJevSpecs(config: HoundsmanConfig, problems: string[]): number {
106
147
  return generated;
107
148
  }
108
149
 
109
- /** Prefixos de polaridade aceitos no texto da regra (§ Convenções de escrita). */
110
- const POLARITY_PREFIX = /^(promover|evitar|não|nao|nunca)\b/i;
111
-
112
150
  /**
113
151
  * Aviso **não bloqueante** para regra sem polaridade explícita: o texto deve
114
152
  * começar com `Promover:` (DEVE acontecer) ou `Evitar:`/`Não`/`Nunca` (NÃO DEVE).
@@ -119,7 +157,7 @@ function checkRulePolarity(config: HoundsmanConfig, warnings: string[]): void {
119
157
  if (!def) continue;
120
158
  def.rules.forEach((rule, index) => {
121
159
  const text = rule.text.trim();
122
- if (!text || POLARITY_PREFIX.test(text)) return;
160
+ if (!text || hasExplicitPolarity(text)) return;
123
161
  warnings.push(
124
162
  `Regra sem polaridade explícita em ${id} (rule-${index}): ${rule.text}`,
125
163
  );
@@ -169,7 +207,7 @@ function checkMetadataPrecision(config: HoundsmanConfig, warnings: string[]): vo
169
207
  const items = def[field];
170
208
  if (!items) continue;
171
209
  items.forEach((item, index) => {
172
- if (!POLARITY_PREFIX.test(item.trim())) return;
210
+ if (!hasExplicitPolarity(item)) return;
173
211
  warnings.push(
174
212
  `Texto de regra em ${id}.${field}[${index}] — a regra vive só em 'rules': ${item}`,
175
213
  );
@@ -192,6 +230,106 @@ function checkBudgets(config: HoundsmanConfig, warnings: string[]): void {
192
230
  }
193
231
  }
194
232
 
233
+ /** Valida a configuração do AST (a disponibilidade das grammars é checada no doctor). */
234
+ function checkAstConfig(
235
+ config: HoundsmanConfig,
236
+ problems: string[],
237
+ warnings: string[],
238
+ ): void {
239
+ const ast = config.ast;
240
+ if (!ast) return;
241
+
242
+ if (ast.maxFileBytes !== undefined && ast.maxFileBytes <= 0) {
243
+ warnings.push(
244
+ `ast.maxFileBytes = ${ast.maxFileBytes} — não-positivo; usando o default.`,
245
+ );
246
+ }
247
+ if (ast.maxImpactFiles !== undefined && ast.maxImpactFiles < 0) {
248
+ warnings.push(
249
+ `ast.maxImpactFiles = ${ast.maxImpactFiles} — negativo; impacto será desabilitado.`,
250
+ );
251
+ }
252
+ const valid = new Set(["typescript", "tsx", "javascript"]);
253
+ for (const [extension, language] of Object.entries(ast.languages ?? {})) {
254
+ if (!valid.has(language)) {
255
+ problems.push(
256
+ `ast.languages['${extension}'] = '${language}' (esperado typescript|tsx|javascript)`,
257
+ );
258
+ }
259
+ }
260
+ for (const [alias, target] of Object.entries(ast.aliases ?? {})) {
261
+ if (!alias.trim() || !target.trim()) {
262
+ warnings.push(`ast.aliases['${alias}'] vazio — alias ignorado.`);
263
+ }
264
+ }
265
+ }
266
+
267
+ /** Valida a configuração de IA (sem exigir chave — fail-open). */
268
+ function checkAiConfig(
269
+ config: HoundsmanConfig,
270
+ problems: string[],
271
+ warnings: string[],
272
+ ): void {
273
+ const ai = config.ai;
274
+ if (!ai) return;
275
+
276
+ const validProviders = new Set(["deepseek", "openai", "anthropic"]);
277
+ if (ai.provider !== undefined && !validProviders.has(ai.provider)) {
278
+ problems.push(
279
+ `ai.provider = '${ai.provider}' (esperado deepseek|openai|anthropic)`,
280
+ );
281
+ }
282
+ if (ai.enabled !== false && ai.model !== undefined && !ai.model.trim()) {
283
+ warnings.push("ai.model vazio — usando o default.");
284
+ }
285
+ for (const key of [
286
+ "concurrency",
287
+ "maxSteps",
288
+ "maxOutputTokens",
289
+ "timeoutMs",
290
+ ] as const) {
291
+ const value = ai[key];
292
+ if (value !== undefined && value <= 0) {
293
+ warnings.push(`ai.${key} = ${value} — não-positivo; usando o default.`);
294
+ }
295
+ }
296
+ if (ai.maxCallsPerReview !== undefined && ai.maxCallsPerReview <= 0) {
297
+ warnings.push(
298
+ `ai.maxCallsPerReview = ${ai.maxCallsPerReview} — não-positivo; usando o default.`,
299
+ );
300
+ }
301
+ if (ai.maxTokensPerReview !== undefined && ai.maxTokensPerReview < 0) {
302
+ warnings.push(
303
+ `ai.maxTokensPerReview = ${ai.maxTokensPerReview} — negativo; sem teto.`,
304
+ );
305
+ }
306
+ for (const [id, override] of Object.entries(ai.watchdogs ?? {})) {
307
+ if (!config.watchdogIds.includes(id)) {
308
+ warnings.push(`ai.watchdogs['${id}'] não corresponde a nenhum watchdog.`);
309
+ }
310
+ if (override.maxSteps !== undefined && override.maxSteps <= 0) {
311
+ warnings.push(
312
+ `ai.watchdogs['${id}'].maxSteps não-positivo — usando o default.`,
313
+ );
314
+ }
315
+ }
316
+
317
+ const provider = ai.provider ?? "deepseek";
318
+ if (validProviders.has(provider) && ai.enabled !== false) {
319
+ const credential =
320
+ provider === "deepseek"
321
+ ? env.deepSeekApiKey
322
+ : provider === "openai"
323
+ ? env.openAiApiKey
324
+ : env.anthropicApiKey;
325
+ if (!credential) {
326
+ warnings.push(
327
+ `ai.provider '${provider}' sem credencial — features de IA ficam fail-open.`,
328
+ );
329
+ }
330
+ }
331
+ }
332
+
195
333
  export function checkRegistry(config: HoundsmanConfig): {
196
334
  problems: string[];
197
335
  warnings: string[];
@@ -202,11 +340,15 @@ export function checkRegistry(config: HoundsmanConfig): {
202
340
 
203
341
  checkDefinitions(config, problems);
204
342
  checkClassification(config, problems);
343
+ checkFallbacks(config, warnings);
344
+ checkEmergent(config, warnings);
205
345
  checkRendering(config, problems);
206
346
  checkRulePolarity(config, warnings);
207
347
  checkRuleDuplication(config, warnings);
208
348
  checkMetadataPrecision(config, warnings);
209
349
  checkBudgets(config, warnings);
350
+ checkAstConfig(config, problems, warnings);
351
+ checkAiConfig(config, problems, warnings);
210
352
  const jevQuestions = checkJevSpecs(config, problems);
211
353
 
212
354
  return { problems, warnings, jevQuestions };
@@ -6,6 +6,7 @@
6
6
  * findings apontam para o staging da review.
7
7
  */
8
8
 
9
+ import type { AiUsage } from "../ai/types";
9
10
  import { Classification } from "../domain/classification";
10
11
  import type { ClassificationResult } from "../file-classifier";
11
12
  import type { JevCandidatesFile } from "../jev";
@@ -22,6 +23,27 @@ export type ManifestOptions = {
22
23
  head: string;
23
24
  };
24
25
 
26
+ /** Resumo do AST no manifesto. */
27
+ export type ManifestAst = {
28
+ enabled: boolean;
29
+ languages: string[];
30
+ files: number;
31
+ impact: {
32
+ affectedFiles: number;
33
+ importers: number;
34
+ exportedChanges: number;
35
+ };
36
+ };
37
+
38
+ /** Resumo da IA no manifesto (só quando a IA foi usada). */
39
+ export type ManifestAi = {
40
+ enabled: boolean;
41
+ provider: string;
42
+ model: string;
43
+ briefPlans: number;
44
+ usage: AiUsage;
45
+ };
46
+
25
47
  /** Classificação enriquecida gravada pelo prepare (modo + incremental). */
26
48
  export type ManifestClassification = ClassificationResult & {
27
49
  headSha?: string;
@@ -57,6 +79,8 @@ export class ManifestWriter {
57
79
  activeIds: string[],
58
80
  pending: string[],
59
81
  jev: JevCandidatesFile,
82
+ ast?: ManifestAst,
83
+ ai?: ManifestAi,
60
84
  ): void {
61
85
  const view = Classification.from(classification);
62
86
  const maxFilesPerBrief = this.project.maxFilesPerBrief;
@@ -65,9 +89,11 @@ export class ManifestWriter {
65
89
  const watchdogs = activeIds.map((id) => {
66
90
  const selection = view.budgetFor(id, maxFilesPerBrief);
67
91
  filesOverBudget += selection.overflow.length;
92
+ const domain = this.project.watchdogs.find(id);
68
93
  return {
69
94
  id,
70
95
  name: this.project.watchdogs.nameOf(id),
96
+ ...(domain?.definition.fallback ? { fallback: true } : {}),
71
97
  files: selection.selected,
72
98
  overflow: selection.overflow.length,
73
99
  brief: this.work.briefFile(id),
@@ -109,6 +135,13 @@ export class ManifestWriter {
109
135
  skipped: jev.skipped?.length ?? 0,
110
136
  }
111
137
  : { available: false, reason: jev.reason },
138
+ ast: ast ?? {
139
+ enabled: false,
140
+ languages: [],
141
+ files: 0,
142
+ impact: { affectedFiles: 0, importers: 0, exportedChanges: 0 },
143
+ },
144
+ ai,
112
145
  deleted: classification.deleted,
113
146
  unclassified: classification.unclassified,
114
147
  excludedCount: classification.excludedCount,
@@ -0,0 +1,97 @@
1
+ /**
2
+ * Texto de regra (biblioteca) — fonte única de polaridade e prefixos reservados.
3
+ *
4
+ * `RuleAnalyzer`, `registry-check` e o harness usam as mesmas listas: evita
5
+ * divergência entre “Promover/Evitar” no analyzer e as validações anti-drift.
6
+ * Também define o vocabulário de findings emergentes (lógica/domínio).
7
+ */
8
+
9
+ /** Intenção de uma regra. */
10
+ export type RuleIntent = "promote" | "avoid";
11
+
12
+ /** Palavras que abrem uma regra de “deve acontecer”. */
13
+ export const PROMOTE_PREFIXES = [
14
+ "promover",
15
+ "deve",
16
+ "dever",
17
+ "use",
18
+ "prefira",
19
+ "sempre",
20
+ ] as const;
21
+
22
+ /** Palavras que abrem uma regra de “não deve acontecer”. */
23
+ export const AVOID_PREFIXES = [
24
+ "evitar",
25
+ "não",
26
+ "nao",
27
+ "nunca",
28
+ "proibido",
29
+ "jamais",
30
+ ] as const;
31
+
32
+ /** Conjunto normalizado (usado para remover polaridade das keywords). */
33
+ export const POLARITY_WORDS: ReadonlySet<string> = new Set([
34
+ ...PROMOTE_PREFIXES,
35
+ ...AVOID_PREFIXES,
36
+ ]);
37
+
38
+ /** Escapa um literal para uso em regex. */
39
+ function escapeWord(word: string): string {
40
+ return word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
41
+ }
42
+
43
+ /** Regex ancorada derivada das listas (sem repetir as palavras). */
44
+ function patternFor(words: readonly string[]): RegExp {
45
+ return new RegExp(`^(${words.map(escapeWord).join("|")})\\b`);
46
+ }
47
+
48
+ const PROMOTE_PATTERN = patternFor(PROMOTE_PREFIXES);
49
+ const AVOID_PATTERN = patternFor(AVOID_PREFIXES);
50
+
51
+ /** Polaridade explícita; sem prefixo conhecido, assume `avoid`. */
52
+ export function polarityOf(text: string): RuleIntent {
53
+ const normalized = text.trim().toLowerCase();
54
+ if (PROMOTE_PATTERN.test(normalized)) return "promote";
55
+ if (AVOID_PATTERN.test(normalized)) return "avoid";
56
+ return "avoid";
57
+ }
58
+
59
+ /** `true` quando a regra declara polaridade explícita. */
60
+ export function hasExplicitPolarity(text: string): boolean {
61
+ const normalized = text.trim().toLowerCase();
62
+ return PROMOTE_PATTERN.test(normalized) || AVOID_PATTERN.test(normalized);
63
+ }
64
+
65
+ /** Prefixos reservados para findings emergentes (fora das regras explícitas). */
66
+ export const EMERGENT_PREFIXES = {
67
+ logic: "Lógica:",
68
+ domain: "Domínio:",
69
+ } as const;
70
+
71
+ /** Espécie de finding emergente. */
72
+ export type EmergentKind = keyof typeof EMERGENT_PREFIXES;
73
+
74
+ /** Espécie de um finding emergente (`null` quando não é emergente). */
75
+ export function emergentKind(rule: string): EmergentKind | null {
76
+ const normalized = rule.trim();
77
+ if (normalized.startsWith(EMERGENT_PREFIXES.logic)) return "logic";
78
+ if (normalized.startsWith(EMERGENT_PREFIXES.domain)) return "domain";
79
+ return null;
80
+ }
81
+
82
+ /** `true` quando a regra usa um prefixo emergente. */
83
+ export function isEmergentRule(rule: string): boolean {
84
+ return emergentKind(rule) !== null;
85
+ }
86
+
87
+ /** Texto que sobra após o prefixo (vazio é inválido). */
88
+ export function emergentText(rule: string): string {
89
+ const kind = emergentKind(rule);
90
+ if (!kind) return "";
91
+ return rule.trim().slice(EMERGENT_PREFIXES[kind].length).trim();
92
+ }
93
+
94
+ /** Monta o texto de um finding emergente. */
95
+ export function emergentRule(kind: EmergentKind, text: string): string {
96
+ return `${EMERGENT_PREFIXES[kind]} ${text.trim()}`;
97
+ }
@@ -5,6 +5,7 @@
5
5
  * pública e os testes; a classe devolve `Classification` (domínio).
6
6
  */
7
7
 
8
+ import type { AstFacts } from "../ast/types";
8
9
  import type { HoundsmanConfig } from "../config";
9
10
  import type { DiffSource } from "../diff-source";
10
11
  import { Classification } from "../domain/classification";
@@ -23,12 +24,18 @@ export class FileClassifier {
23
24
  classify(
24
25
  entries: ReturnType<typeof parseEntries>,
25
26
  churn: ChurnMap = {},
27
+ astFacts?: ReadonlyMap<string, AstFacts>,
26
28
  ): Classification {
27
- return new Classification(classifyEntries(entries, this.config, churn));
29
+ return new Classification(classifyEntries(entries, this.config, churn, astFacts));
28
30
  }
29
31
 
30
32
  /** Executa o diff e classifica os arquivos entre `base` e `head`. */
31
- classifyRange(base: string, head: string, diff?: DiffSource): Classification {
32
- return new Classification(classifyRange(base, head, this.config, diff));
33
+ classifyRange(
34
+ base: string,
35
+ head: string,
36
+ diff?: DiffSource,
37
+ astFacts?: ReadonlyMap<string, AstFacts>,
38
+ ): Classification {
39
+ return new Classification(classifyRange(base, head, this.config, diff, astFacts));
33
40
  }
34
41
  }
@@ -12,10 +12,11 @@ import type {
12
12
  FindingsStateFile,
13
13
  } from "../findings-state";
14
14
  import {
15
- applyJev,
15
+ applyConfidence,
16
16
  applyResolutions,
17
17
  selectVerifiable,
18
18
  summarizeVerify,
19
+ type VerifyBasis,
19
20
  type VerifyEntry,
20
21
  type VerifySummary,
21
22
  verifyLocal,
@@ -33,13 +34,23 @@ export class Verifier {
33
34
  return verifyLocal(findings, readFile);
34
35
  }
35
36
 
36
- /** Tier 1 — aplica a confirmação do Jev aos casos ambíguos. */
37
+ /** Tier 1 — aplica confirmações externas (Jev ou IA) aos casos ambíguos. */
38
+ applyConfidence(
39
+ entries: VerifyEntry[],
40
+ confidence: Map<string, number>,
41
+ threshold: number,
42
+ basis: VerifyBasis = "jev",
43
+ ): number {
44
+ return applyConfidence(entries, confidence, threshold, basis);
45
+ }
46
+
47
+ /** Compatibilidade: confirmação via Jev. */
37
48
  applyJev(
38
49
  entries: VerifyEntry[],
39
50
  confidence: Map<string, number>,
40
51
  threshold: number,
41
52
  ): number {
42
- return applyJev(entries, confidence, threshold);
53
+ return applyConfidence(entries, confidence, threshold, "jev");
43
54
  }
44
55
 
45
56
  /** Contagem por status. */
@@ -9,17 +9,18 @@
9
9
  import { homedir } from "node:os";
10
10
  import { join, resolve } from "node:path";
11
11
  import type { HoundsmanConfig } from "../config";
12
+ import { ENV_NAMES, env } from "../env";
12
13
 
13
- export const HOUNDSMAN_HOME_ENV = "HOUNDSMAN_HOME";
14
+ export const HOUNDSMAN_HOME_ENV = ENV_NAMES.home;
14
15
 
15
16
  /** Diretório-base global do houndsman. */
16
17
  export function houndsmanHome(): string {
17
- const override = process.env[HOUNDSMAN_HOME_ENV];
18
- if (override && override.trim().length > 0) return resolve(override);
18
+ const override = env.home;
19
+ if (override) return resolve(override);
19
20
 
20
21
  const home = homedir();
21
22
  if (process.platform === "win32") {
22
- const local = process.env.LOCALAPPDATA;
23
+ const local = env.localAppData;
23
24
  return join(
24
25
  local && local.length > 0 ? local : join(home, "AppData", "Local"),
25
26
  "houndsman",
@@ -28,7 +29,7 @@ export function houndsmanHome(): string {
28
29
  if (process.platform === "darwin") {
29
30
  return join(home, "Library", "Application Support", "houndsman");
30
31
  }
31
- const xdg = process.env.XDG_DATA_HOME;
32
+ const xdg = env.xdgDataHome;
32
33
  return join(xdg && xdg.length > 0 ? xdg : join(home, ".local", "share"), "houndsman");
33
34
  }
34
35
 
@@ -92,6 +92,12 @@ export type ArtifactKind =
92
92
  | "resume"
93
93
  | "domain-review"
94
94
  | "verify"
95
+ | "ast"
96
+ | "ast-impact"
97
+ | "ai"
98
+ | "ai-usage"
99
+ | "ai-brief"
100
+ | "harness-transcript"
95
101
  | "other";
96
102
 
97
103
  /** Artefato persistido de uma review. */
@@ -106,12 +106,24 @@ export class ReviewWorkArea {
106
106
  writeFileSync(this.briefFile(id), content);
107
107
  }
108
108
 
109
+ /** Grava o relatório JSON de um watchdog (staging dos subagentes). */
110
+ writeFinding(id: string, content: string): void {
111
+ mkdirSync(this.findingsDir, { recursive: true });
112
+ writeFileSync(this.findingFile(id), content);
113
+ }
114
+
109
115
  writeContext(context: unknown, brief: string): void {
110
116
  mkdirSync(this.root, { recursive: true });
111
117
  writeFileSync(this.contextPaths.context, `${JSON.stringify(context, null, 2)}\n`);
112
118
  writeFileSync(this.contextPaths.brief, `${brief}\n`);
113
119
  }
114
120
 
121
+ /** Grava o resumo do contexto (gerado pelo subagente ou pela IA). */
122
+ writeContextSummary(summary: unknown): void {
123
+ mkdirSync(this.root, { recursive: true });
124
+ writeFileSync(this.contextPaths.summary, `${JSON.stringify(summary, null, 2)}\n`);
125
+ }
126
+
115
127
  /** Finds brutos gravados pelos subagentes (um JSON por watchdog). */
116
128
  readFindings(activeIds: string[]): FindingsIngest {
117
129
  const reports: WatchdogReport[] = [];