@payconductor/houndsman 0.5.0 → 0.7.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 (175) 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/commands/server-command.ts +7 -1
  11. package/src/cli/help.ts +18 -2
  12. package/src/cli/index.ts +10 -6
  13. package/src/core/ai/ai-client.ts +221 -0
  14. package/src/core/ai/ai-sdk-model-provider.ts +101 -0
  15. package/src/core/ai/errors.ts +36 -0
  16. package/src/core/ai/features/brief-enricher.ts +62 -0
  17. package/src/core/ai/features/classifier.ts +50 -0
  18. package/src/core/ai/features/context-summarizer.ts +31 -0
  19. package/src/core/ai/features/pre-analyzer.ts +51 -0
  20. package/src/core/ai/features/verifier.ts +45 -0
  21. package/src/core/ai/index.ts +56 -0
  22. package/src/core/ai/model-factory.ts +137 -0
  23. package/src/core/ai/prompts/base.ts +36 -0
  24. package/src/core/ai/prompts/brief.ts +87 -0
  25. package/src/core/ai/prompts/classification.ts +36 -0
  26. package/src/core/ai/prompts/context.ts +29 -0
  27. package/src/core/ai/prompts/pre-analysis.ts +49 -0
  28. package/src/core/ai/prompts/verify.ts +40 -0
  29. package/src/core/ai/schemas.ts +110 -0
  30. package/src/core/ai/types.ts +76 -0
  31. package/src/core/ai/usage-budget.ts +75 -0
  32. package/src/core/ai/usage-recorder.ts +79 -0
  33. package/src/core/assets.ts +16 -0
  34. package/src/core/ast/diff.ts +220 -0
  35. package/src/core/ast/impact.ts +127 -0
  36. package/src/core/ast/parser.ts +167 -0
  37. package/src/core/ast/service.ts +233 -0
  38. package/src/core/ast/symbols.ts +294 -0
  39. package/src/core/ast/types.ts +125 -0
  40. package/src/core/brief.ts +138 -0
  41. package/src/core/commands/findings.ts +65 -2
  42. package/src/core/commands/review.ts +2 -0
  43. package/src/core/commands/scaffold.ts +159 -10
  44. package/src/core/commands/update.ts +5 -3
  45. package/src/core/config.ts +85 -0
  46. package/src/core/defaults.ts +27 -0
  47. package/src/core/domain/watchdog.ts +43 -5
  48. package/src/core/engine/houndsman-engine.ts +16 -1
  49. package/src/core/engine/review-scope.ts +52 -6
  50. package/src/core/engine/review-session.ts +27 -2
  51. package/src/core/env.ts +101 -0
  52. package/src/core/file-classifier.ts +25 -4
  53. package/src/core/git-runner.ts +25 -13
  54. package/src/core/github-review.ts +10 -7
  55. package/src/core/jev/jev-client.ts +8 -7
  56. package/src/core/jev/jev-verify.ts +2 -1
  57. package/src/core/logging/index.ts +17 -0
  58. package/src/core/logging/logger.ts +187 -0
  59. package/src/core/orchestrator.ts +357 -9
  60. package/src/core/project-config.ts +123 -1
  61. package/src/core/registry-check.ts +148 -6
  62. package/src/core/renderers/manifest-writer.ts +33 -0
  63. package/src/core/rule-text.ts +97 -0
  64. package/src/core/services/file-classifier.ts +10 -3
  65. package/src/core/services/gh-client.ts +38 -22
  66. package/src/core/services/verifier.ts +14 -3
  67. package/src/core/storage/paths.ts +6 -5
  68. package/src/core/storage/types.ts +6 -0
  69. package/src/core/storage/work-area.ts +12 -0
  70. package/src/core/types.ts +37 -1
  71. package/src/core/verify.ts +17 -5
  72. package/src/harness/README.md +15 -0
  73. package/src/harness/agent/agent-context.ts +33 -0
  74. package/src/harness/agent/agent-errors.ts +30 -0
  75. package/src/harness/agent/agent-factory.ts +45 -0
  76. package/src/harness/agent/agent-reporter.ts +34 -0
  77. package/src/harness/agent/agent-result.ts +16 -0
  78. package/src/harness/agent/agent-runner.ts +32 -0
  79. package/src/harness/agent/agent-scheduler.ts +37 -0
  80. package/src/harness/agent/review-agent.ts +391 -0
  81. package/src/harness/config/harness-config.ts +84 -0
  82. package/src/harness/hunt/hunt-harness.ts +83 -0
  83. package/src/harness/hunt/hunt-options.ts +75 -0
  84. package/src/harness/hunt/hunt-result.ts +17 -0
  85. package/src/harness/hunt/hunt-session.ts +372 -0
  86. package/src/harness/hunt/review-planner.ts +98 -0
  87. package/src/harness/index.ts +36 -0
  88. package/src/harness/investigation/agent-state.ts +134 -0
  89. package/src/harness/investigation/evidence-verifier.ts +129 -0
  90. package/src/harness/investigation/evidence.ts +110 -0
  91. package/src/harness/investigation/finding-critic.ts +96 -0
  92. package/src/harness/investigation/investigation-planner.ts +118 -0
  93. package/src/harness/investigation/investigation-task.ts +10 -0
  94. package/src/harness/investigation/review-journal.ts +87 -0
  95. package/src/harness/investigation/rule-analyzer.ts +178 -0
  96. package/src/harness/investigation/rule-signals.ts +110 -0
  97. package/src/harness/prompts/agent-schemas.ts +57 -0
  98. package/src/harness/prompts/reviewer-prompt-builder.ts +101 -0
  99. package/src/harness/prompts/states/conclude-prompt.ts +16 -0
  100. package/src/harness/prompts/states/investigate-prompt.ts +37 -0
  101. package/src/harness/prompts/states/orient-prompt.ts +15 -0
  102. package/src/harness/prompts/states/verify-prompt.ts +22 -0
  103. package/src/harness/tools/agent-tool.ts +102 -0
  104. package/src/harness/tools/builtin/changed-symbols-tool.ts +48 -0
  105. package/src/harness/tools/builtin/doc-context-tool.ts +74 -0
  106. package/src/harness/tools/builtin/file-outline-tool.ts +66 -0
  107. package/src/harness/tools/builtin/find-references-tool.ts +66 -0
  108. package/src/harness/tools/builtin/find-symbol-tool.ts +91 -0
  109. package/src/harness/tools/builtin/helpers.ts +115 -0
  110. package/src/harness/tools/builtin/impact-tool.ts +48 -0
  111. package/src/harness/tools/builtin/imports-exports-tool.ts +53 -0
  112. package/src/harness/tools/builtin/index.ts +59 -0
  113. package/src/harness/tools/builtin/list-files-tool.ts +85 -0
  114. package/src/harness/tools/builtin/pr-context-tool.ts +41 -0
  115. package/src/harness/tools/builtin/read-file-range-tool.ts +73 -0
  116. package/src/harness/tools/builtin/rule-signals-tool.ts +36 -0
  117. package/src/harness/tools/builtin/search-code-tool.ts +65 -0
  118. package/src/harness/tools/builtin/symbol-context-tool.ts +106 -0
  119. package/src/harness/tools/builtin/tests-for-symbol-tool.ts +61 -0
  120. package/src/harness/tools/path-guard.ts +90 -0
  121. package/src/harness/tools/result-limiter.ts +49 -0
  122. package/src/harness/tools/secret-redactor.ts +54 -0
  123. package/src/harness/tools/tool-cache.ts +50 -0
  124. package/src/harness/tools/tool-call-budget.ts +60 -0
  125. package/src/harness/tools/tool-context.ts +5 -0
  126. package/src/harness/tools/tool-middleware.ts +105 -0
  127. package/src/harness/tools/tool-policy.ts +51 -0
  128. package/src/harness/tools/tool-registry.ts +112 -0
  129. package/src/harness/tools/tool-result.ts +15 -0
  130. package/src/harness/tools/toolbox.ts +36 -0
  131. package/src/harness/validation/finding-validator.ts +119 -0
  132. package/src/index.ts +46 -0
  133. package/src/server/client/App.tsx +38 -12
  134. package/src/server/client/CommentsPanel.tsx +255 -0
  135. package/src/server/client/FindingCard.tsx +12 -4
  136. package/src/server/client/FindingsList.tsx +4 -1
  137. package/src/server/client/Sidebar.tsx +397 -0
  138. package/src/server/client/SubmitModal.tsx +61 -5
  139. package/src/server/client/icons.tsx +19 -0
  140. package/src/server/client/index.tsx +1 -1
  141. package/src/server/client/utils/constants.ts +29 -5
  142. package/src/server/client/utils/format.ts +47 -2
  143. package/src/server/client/utils/types.ts +88 -0
  144. package/src/server/editor.ts +129 -0
  145. package/src/server/index.ts +115 -5
  146. package/src/server/pr-comments.ts +256 -0
  147. package/src/server/pr-inbox.ts +202 -0
  148. package/src/server/run-repository.ts +33 -1
  149. package/src/skill/OUTPUT-FORMAT.md +12 -0
  150. package/src/skill/SETUP.md +6 -2
  151. package/src/skill/hunt.md +14 -2
  152. package/src/skill/verify.md +1 -1
  153. package/src/tests/__snapshots__/baseline.test.ts.snap +96 -14
  154. package/src/tests/ai-core.test.ts +120 -0
  155. package/src/tests/ai-features.test.ts +183 -0
  156. package/src/tests/ast.test.ts +335 -0
  157. package/src/tests/cli.test.ts +33 -0
  158. package/src/tests/env.test.ts +69 -0
  159. package/src/tests/fallback.test.ts +172 -0
  160. package/src/tests/fixtures/fake-agent-tools.ts +69 -0
  161. package/src/tests/fixtures/fake-investigation.ts +64 -0
  162. package/src/tests/fixtures/fake-model-provider.ts +48 -0
  163. package/src/tests/github-review.test.ts +9 -0
  164. package/src/tests/harness-agent.test.ts +122 -0
  165. package/src/tests/harness-investigation.test.ts +206 -0
  166. package/src/tests/harness-tools.test.ts +148 -0
  167. package/src/tests/hunt-command.test.ts +212 -0
  168. package/src/tests/logger.test.ts +83 -0
  169. package/src/tests/review-scope.test.ts +11 -11
  170. package/src/tests/rule-analyzer.test.ts +61 -0
  171. package/src/tests/server-editor.test.ts +100 -0
  172. package/src/tests/server.test.ts +295 -2
  173. package/src/tests/tool-contracts.test.ts +82 -0
  174. package/src/tests/verify.test.ts +1 -1
  175. package/src/server/client/RunList.tsx +0 -75
@@ -0,0 +1,212 @@
1
+ /**
2
+ * `hunt` — parser de flags, dry-run e fluxo completo com provider fake.
3
+ */
4
+
5
+ import { afterAll, describe, expect, test } from "bun:test";
6
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
7
+ import { tmpdir } from "node:os";
8
+ import { join } from "node:path";
9
+ import { defineHoundsmanConfig } from "../core/config";
10
+ import { HoundsmanEngine } from "../core/engine/houndsman-engine";
11
+ import { SilentLogger } from "../core/logging";
12
+ import { defineWatchdog } from "../core/types";
13
+ import { HuntHarness } from "../harness/hunt/hunt-harness";
14
+ import { parseHuntArgs } from "../harness/hunt/hunt-options";
15
+ import { FakeModelProvider } from "./fixtures/fake-model-provider";
16
+
17
+ const RULE = "Nunca usar `any`.";
18
+
19
+ const configBase = defineHoundsmanConfig({
20
+ projectName: "Hunt",
21
+ watchdogs: {
22
+ alpha: defineWatchdog({
23
+ id: "alpha",
24
+ name: "Alpha",
25
+ description: "Watchdog do hunt.",
26
+ scope: "src/alpha/**",
27
+ classify: [{ value: "^src/alpha/" }],
28
+ rules: [{ severity: "blocking", text: RULE }],
29
+ contextFiles: [],
30
+ }),
31
+ },
32
+ exclusions: [],
33
+ docMappings: [],
34
+ });
35
+
36
+ describe("parseHuntArgs", () => {
37
+ test("flags e defaults", () => {
38
+ const options = parseHuntArgs([
39
+ "--base",
40
+ "origin/main",
41
+ "--head",
42
+ "abc",
43
+ "--watchdog",
44
+ "alpha",
45
+ "--full",
46
+ "--no-ast",
47
+ "--resume",
48
+ "--allow-partial",
49
+ "--dry-run",
50
+ "--fail-on-blocking",
51
+ "--max-calls",
52
+ "7",
53
+ "--concurrency",
54
+ "3",
55
+ "--model",
56
+ "m",
57
+ ]);
58
+ expect(options.base).toBe("origin/main");
59
+ expect(options.head).toBe("abc");
60
+ expect(options.watchdog).toBe("alpha");
61
+ expect(options.full).toBe(true);
62
+ expect(options.noAst).toBe(true);
63
+ expect(options.noJev).toBe(true);
64
+ expect(options.resume).toBe(true);
65
+ expect(options.allowPartial).toBe(true);
66
+ expect(options.dryRun).toBe(true);
67
+ expect(options.failOnBlocking).toBe(true);
68
+ expect(options.maxCalls).toBe(7);
69
+ expect(options.concurrency).toBe(3);
70
+ expect(options.model).toBe("m");
71
+ });
72
+ });
73
+
74
+ // ---------------------------------------------------------------------------
75
+ // Repo git temporário
76
+ // ---------------------------------------------------------------------------
77
+
78
+ const cwd = mkdtempSync(join(tmpdir(), "houndsman-hunt-"));
79
+ const originalCwd = process.cwd();
80
+ const originalHome = process.env.HOUNDSMAN_HOME;
81
+ const originalKey = process.env.HOUNDSMAN_DEEP_SEEK_API_KEY;
82
+ let base = "";
83
+
84
+ function git(args: string[]): string {
85
+ const result = Bun.spawnSync(["git", ...args], {
86
+ cwd,
87
+ stdout: "pipe",
88
+ stderr: "pipe",
89
+ });
90
+ if (result.exitCode !== 0) {
91
+ throw new Error(`git ${args.join(" ")}: ${result.stderr.toString()}`);
92
+ }
93
+ return result.stdout.toString();
94
+ }
95
+
96
+ function setupRepo(): void {
97
+ git(["init", "-b", "main"]);
98
+ git(["config", "user.email", "hunt@example.test"]);
99
+ git(["config", "user.name", "Hunt"]);
100
+ git(["config", "commit.gpgsign", "false"]);
101
+ mkdirSync(join(cwd, "src", "alpha"), { recursive: true });
102
+ writeFileSync(join(cwd, "src/alpha/a.ts"), "export const a = 1;\n");
103
+ git(["add", "."]);
104
+ git(["commit", "-m", "initial"]);
105
+ base = git(["rev-parse", "HEAD"]).trim();
106
+ writeFileSync(join(cwd, "src/alpha/a.ts"), "export const a: any = 1;\n");
107
+ git(["add", "-A"]);
108
+ git(["commit", "-m", "change"]);
109
+ process.env.HOUNDSMAN_HOME = join(cwd, ".home");
110
+ process.chdir(cwd);
111
+ }
112
+
113
+ function engine(): HoundsmanEngine {
114
+ return new HoundsmanEngine({
115
+ ...configBase,
116
+ storage: { provider: "sqlite", path: join(cwd, "houndsman.db") },
117
+ });
118
+ }
119
+
120
+ setupRepo();
121
+ afterAll(() => {
122
+ process.chdir(originalCwd);
123
+ if (originalHome === undefined) delete process.env.HOUNDSMAN_HOME;
124
+ else process.env.HOUNDSMAN_HOME = originalHome;
125
+ if (originalKey === undefined) delete process.env.HOUNDSMAN_DEEP_SEEK_API_KEY;
126
+ else process.env.HOUNDSMAN_DEEP_SEEK_API_KEY = originalKey;
127
+ rmSync(cwd, { recursive: true, force: true });
128
+ });
129
+
130
+ describe("hunt", () => {
131
+ test("dry-run lista watchdogs sem chamar IA", async () => {
132
+ const instance = engine();
133
+ try {
134
+ const harness = await HuntHarness.from(
135
+ instance,
136
+ parseHuntArgs(["--base", base, "--head", "HEAD", "--dry-run"]),
137
+ new SilentLogger(),
138
+ );
139
+ const result = await harness.run();
140
+ expect(result.status).toBe("dry-run");
141
+ expect(result.messages.join("\n")).toContain("alpha");
142
+ } finally {
143
+ instance.close();
144
+ }
145
+ });
146
+
147
+ test("sem chave e sem --dry-run falha com mensagem clara", async () => {
148
+ delete process.env.HOUNDSMAN_DEEP_SEEK_API_KEY;
149
+ const instance = engine();
150
+ try {
151
+ await expect(
152
+ HuntHarness.from(
153
+ instance,
154
+ parseHuntArgs(["--base", base, "--head", "HEAD"]),
155
+ new SilentLogger(),
156
+ ),
157
+ ).rejects.toThrow(/hunt exige IA configurada/);
158
+ } finally {
159
+ instance.close();
160
+ }
161
+ });
162
+
163
+ test("provider fake investiga, grava findings e finaliza", async () => {
164
+ const provider = new FakeModelProvider(async (request, index) => {
165
+ if (index === 0) return { hypotheses: ["any"] };
166
+ if (index === 1) return { taskIds: ["rule-0"] };
167
+ const tool = request.tools?.read_file_range;
168
+ if (!tool) throw new Error("read_file_range ausente");
169
+ const parsed = JSON.parse(
170
+ await tool.execute({ path: "src/alpha/a.ts", startLine: 1, endLine: 1 }),
171
+ ) as { evidence?: { id: string }[] };
172
+ return {
173
+ findingDrafts: [
174
+ {
175
+ rule: RULE,
176
+ severity: "blocking",
177
+ file: "src/alpha/a.ts",
178
+ line: 1,
179
+ message: "any detectado",
180
+ action: "tipar",
181
+ evidenceIds: [parsed.evidence?.[0]?.id].filter(Boolean),
182
+ confidence: 0.9,
183
+ },
184
+ ],
185
+ coverage: [{ rule: RULE, status: "checked" }],
186
+ };
187
+ });
188
+ const instance = engine();
189
+ try {
190
+ const harness = await HuntHarness.from(
191
+ instance,
192
+ parseHuntArgs(["--base", base, "--head", "HEAD"]),
193
+ new SilentLogger(),
194
+ provider,
195
+ );
196
+ const result = await harness.run();
197
+ expect(result.status).toBe("completed");
198
+ expect(result.blockers).toBe(1);
199
+ const review = instance.storage.readArtifact(result.reviewId, "review.md");
200
+ expect(review?.content).toContain("any detectado");
201
+ const transcript = instance.storage.readArtifact(
202
+ result.reviewId,
203
+ "harness-transcript.json",
204
+ );
205
+ expect(transcript?.content).toContain("VERIFY");
206
+ const usage = instance.storage.readArtifact(result.reviewId, "ai-usage.json");
207
+ expect(usage?.content).toContain('"calls"');
208
+ } finally {
209
+ instance.close();
210
+ }
211
+ });
212
+ });
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Logger único: cor opcional, spinner em não-TTY e tabela.
3
+ */
4
+
5
+ import { describe, expect, test } from "bun:test";
6
+ import { Logger, SilentLogger } from "../core/logging";
7
+
8
+ function memoryStream(): { stream: NodeJS.WritableStream; text: () => string } {
9
+ let content = "";
10
+ const stream = {
11
+ write(chunk: string) {
12
+ content += chunk;
13
+ return true;
14
+ },
15
+ isTTY: false,
16
+ } as unknown as NodeJS.WritableStream;
17
+ return { stream, text: () => content };
18
+ }
19
+
20
+ describe("Logger", () => {
21
+ test("escreve texto puro quando color=false e sem TTY", () => {
22
+ const out = memoryStream();
23
+ const err = memoryStream();
24
+ const logger = new Logger({
25
+ stdout: out.stream,
26
+ stderr: err.stream,
27
+ color: false,
28
+ isTTY: false,
29
+ });
30
+ logger.info("info");
31
+ logger.success("ok");
32
+ logger.warn("aviso");
33
+ logger.error("falhou");
34
+ logger.step("passo");
35
+ const text = `${out.text()}${err.text()}`;
36
+ expect(text).toContain("info");
37
+ expect(text).toContain("ok");
38
+ expect(text).toContain("aviso");
39
+ expect(text).toContain("falhou");
40
+ expect(text).toContain("passo");
41
+ expect(text).not.toContain("\u001b[");
42
+ });
43
+
44
+ test("spinner é nulo em não-TTY", () => {
45
+ const out = memoryStream();
46
+ const logger = new Logger({ stdout: out.stream, isTTY: false });
47
+ expect(logger.spinner("x")).toBeNull();
48
+ });
49
+
50
+ test("quiet suprime info/sucesso mas não erro", () => {
51
+ const out = memoryStream();
52
+ const err = memoryStream();
53
+ const logger = new Logger({
54
+ stdout: out.stream,
55
+ stderr: err.stream,
56
+ quiet: true,
57
+ color: false,
58
+ });
59
+ logger.info("info");
60
+ logger.success("ok");
61
+ logger.error("erro");
62
+ expect(out.text()).toBe("");
63
+ expect(err.text()).toContain("erro");
64
+ });
65
+
66
+ test("tabela alinha colunas", () => {
67
+ const out = memoryStream();
68
+ const logger = new Logger({ stdout: out.stream, color: false });
69
+ logger.table([
70
+ ["id", "findings"],
71
+ ["alpha", "2"],
72
+ ]);
73
+ expect(out.text()).toContain("id");
74
+ expect(out.text()).toContain("alpha");
75
+ });
76
+
77
+ test("SilentLogger não escreve e executa withSpinner", async () => {
78
+ const logger = new SilentLogger();
79
+ logger.info("x");
80
+ const result = await logger.withSpinner("x", async () => 42);
81
+ expect(result).toBe(42);
82
+ });
83
+ });
@@ -111,12 +111,12 @@ function makeRepo(): Repo {
111
111
  // ---------------------------------------------------------------------------
112
112
 
113
113
  describe("ReviewScopeResolver", () => {
114
- test("mesmo commit revisado vira no-op (sem tocar no git)", () => {
114
+ test("mesmo commit revisado vira no-op (sem tocar no git)", async () => {
115
115
  const sha = "a".repeat(40);
116
- const scope = new ReviewScopeResolver(options(), fakeHoundsmanConfig).resolve(
117
- stateWith(sha),
118
- sha,
119
- );
116
+ const scope = await new ReviewScopeResolver(
117
+ options(),
118
+ fakeHoundsmanConfig,
119
+ ).resolve(stateWith(sha), sha);
120
120
 
121
121
  expect(scope.kind).toBe("noop");
122
122
  if (scope.kind !== "noop") throw new Error("esperava noop");
@@ -124,12 +124,12 @@ describe("ReviewScopeResolver", () => {
124
124
  expect(scope.headSha).toBe(sha);
125
125
  });
126
126
 
127
- test("`--full` re-revisa o mesmo commit", () => {
127
+ test("`--full` re-revisa o mesmo commit", async () => {
128
128
  const repo = makeRepo();
129
129
  const originalCwd = process.cwd();
130
130
  try {
131
131
  process.chdir(repo.cwd);
132
- const scope = new ReviewScopeResolver(
132
+ const scope = await new ReviewScopeResolver(
133
133
  options({ base: repo.base, full: true }),
134
134
  fakeHoundsmanConfig,
135
135
  ).resolve(stateWith(repo.head), repo.head);
@@ -144,7 +144,7 @@ describe("ReviewScopeResolver", () => {
144
144
  }
145
145
  });
146
146
 
147
- test("delta revisa só os arquivos alterados e carrega o resto", () => {
147
+ test("delta revisa só os arquivos alterados e carrega o resto", async () => {
148
148
  const repo = makeRepo();
149
149
  const originalCwd = process.cwd();
150
150
  try {
@@ -153,7 +153,7 @@ describe("ReviewScopeResolver", () => {
153
153
  abcdef1234: findingState({ file: "src/alpha/keep.ts" }),
154
154
  fedcba4321: findingState({ file: "src/alpha/a.ts" }),
155
155
  });
156
- const scope = new ReviewScopeResolver(
156
+ const scope = await new ReviewScopeResolver(
157
157
  options({ base: repo.base }),
158
158
  fakeHoundsmanConfig,
159
159
  ).resolve(previous, repo.head);
@@ -172,13 +172,13 @@ describe("ReviewScopeResolver", () => {
172
172
  }
173
173
  });
174
174
 
175
- test("histórico reescrito (HEAD sem ancestrais comuns) cai no completo", () => {
175
+ test("histórico reescrito (HEAD sem ancestrais comuns) cai no completo", async () => {
176
176
  const repo = makeRepo();
177
177
  const originalCwd = process.cwd();
178
178
  try {
179
179
  process.chdir(repo.cwd);
180
180
  // `repo.head` não é ancestral de `repo.base` → revisão completa.
181
- const scope = new ReviewScopeResolver(
181
+ const scope = await new ReviewScopeResolver(
182
182
  options({ base: repo.base }),
183
183
  fakeHoundsmanConfig,
184
184
  ).resolve(stateWith(repo.head), repo.base);
@@ -0,0 +1,61 @@
1
+ /**
2
+ * RuleAnalyzer — polaridade, categoria, sinais e hints.
3
+ */
4
+
5
+ import { describe, expect, test } from "bun:test";
6
+ import { RuleAnalyzer } from "../harness/investigation/rule-analyzer";
7
+
8
+ const analyzer = new RuleAnalyzer();
9
+
10
+ describe("RuleAnalyzer", () => {
11
+ test("detecta polaridade explícita", () => {
12
+ const [avoid, promote] = analyzer.analyze([
13
+ { severity: "blocking", text: "Evitar: chamar banco diretamente em rotas." },
14
+ { severity: "attention", text: "Promover: usar `logger` estruturado." },
15
+ ]);
16
+ expect(avoid?.intent).toBe("avoid");
17
+ expect(promote?.intent).toBe("promote");
18
+ });
19
+
20
+ test("classifica categoria por keywords", () => {
21
+ const [data, tests] = analyzer.analyze([
22
+ {
23
+ severity: "attention",
24
+ text: "Evitar: query direta no banco sem migration.",
25
+ },
26
+ { severity: "nit", text: "Promover: cobertura de teste no handler." },
27
+ ]);
28
+ expect(data?.category).toBe("data");
29
+ expect(tests?.category).toBe("tests");
30
+ });
31
+
32
+ test("extrai sinais de backticks e hints (confiança alta)", () => {
33
+ const [analysis] = analyzer.analyze([
34
+ {
35
+ severity: "blocking",
36
+ text: "Evitar: usar `db.query` fora do service.",
37
+ hints: {
38
+ symbols: ["OrderService"],
39
+ imports: ["db"],
40
+ checks: ["symbol_context"],
41
+ },
42
+ },
43
+ ]);
44
+ expect(analysis?.confidence).toBe("high");
45
+ expect(analysis?.signals.some((signal) => signal.value === "OrderService")).toBe(
46
+ true,
47
+ );
48
+ expect(analysis?.signals.some((signal) => signal.value === "db")).toBe(true);
49
+ expect(analysis?.checks.some((check) => check.tool === "symbol_context")).toBe(
50
+ true,
51
+ );
52
+ });
53
+
54
+ test("keywords ignoram stopwords", () => {
55
+ const [analysis] = analyzer.analyze([
56
+ { severity: "nit", text: "Nunca usar any em produção" },
57
+ ]);
58
+ expect(analysis?.keywords).not.toContain("nunca");
59
+ expect(analysis?.keywords).toContain("produção");
60
+ });
61
+ });
@@ -0,0 +1,100 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import {
3
+ editorFileLink,
4
+ jetbrainsFileLink,
5
+ vscodeFileLink,
6
+ } from "../server/client/utils/format";
7
+ import { detectEditor, resolveEditor } from "../server/editor";
8
+
9
+ describe("detecção de editor", () => {
10
+ test("VS Code pelo TERM_PROGRAM", () => {
11
+ expect(detectEditor({ TERM_PROGRAM: "vscode" }, "/work/app")).toMatchObject({
12
+ kind: "vscode",
13
+ project: "app",
14
+ });
15
+ });
16
+
17
+ test("VS Code pelas variáveis VSCODE_*", () => {
18
+ expect(detectEditor({ VSCODE_PID: "123" }, "/work/app")).toMatchObject({
19
+ kind: "vscode",
20
+ project: "app",
21
+ });
22
+ });
23
+
24
+ test("JetBrains pelo terminal e produto do bundle", () => {
25
+ expect(
26
+ detectEditor(
27
+ {
28
+ TERMINAL_EMULATOR: "JetBrains-JediTerm",
29
+ __CFBundleIdentifier: "com.jetbrains.pycharm",
30
+ },
31
+ "/work/app",
32
+ ),
33
+ ).toEqual({ kind: "jetbrains", project: "app", product: "pycharm" });
34
+ });
35
+
36
+ test("JetBrains por *_INITIAL_DIRECTORY", () => {
37
+ expect(
38
+ detectEditor({ WEBSTORM_INITIAL_DIRECTORY: "/work/app" }, "/work/app"),
39
+ ).toEqual({ kind: "jetbrains", project: "app", product: "webstorm" });
40
+ });
41
+
42
+ test("produto JetBrains ambíguo cai em idea", () => {
43
+ expect(
44
+ detectEditor({ TERMINAL_EMULATOR: "JetBrains-JediTerm" }, "/work/app"),
45
+ ).toEqual({ kind: "jetbrains", project: "app", product: "idea" });
46
+ });
47
+
48
+ test("sem pistas → none", () => {
49
+ expect(detectEditor({}, "/work/app")).toEqual({
50
+ kind: "none",
51
+ project: "app",
52
+ });
53
+ });
54
+
55
+ test("resolveEditor força vscode/jetbrains/none", () => {
56
+ expect(resolveEditor("vscode", {}, "/work/app")).toMatchObject({
57
+ kind: "vscode",
58
+ });
59
+ expect(resolveEditor("jetbrains", {}, "/work/app")).toMatchObject({
60
+ kind: "jetbrains",
61
+ product: "idea",
62
+ });
63
+ expect(
64
+ resolveEditor("none", { TERM_PROGRAM: "vscode" }, "/work/app"),
65
+ ).toMatchObject({ kind: "none" });
66
+ expect(resolveEditor("desconhecido", {}, "/work/app")).toMatchObject({
67
+ kind: "none",
68
+ });
69
+ });
70
+ });
71
+
72
+ describe("links de editor", () => {
73
+ test("VS Code normaliza o drive e mantém a linha", () => {
74
+ expect(vscodeFileLink("C:\\repo\\src\\a.ts", 12)).toBe(
75
+ "vscode://file/c:/repo/src/a.ts:12",
76
+ );
77
+ });
78
+
79
+ test("JetBrains monta navigate/reference", () => {
80
+ const link = jetbrainsFileLink("C:\\repo\\src\\a.ts", 12, "app", "webstorm");
81
+ expect(link).toContain(
82
+ "jetbrains://webstorm/navigate/reference?project=app&path=",
83
+ );
84
+ expect(link ? decodeURIComponent(link) : "").toContain("C:/repo/src/a.ts:12");
85
+ });
86
+
87
+ test("editorFileLink respeita o tipo detectado", () => {
88
+ expect(editorFileLink("/repo/a.ts", 3, { kind: "vscode", project: "app" })).toBe(
89
+ "vscode://file//repo/a.ts:3",
90
+ );
91
+ expect(
92
+ editorFileLink("/repo/a.ts", 3, {
93
+ kind: "jetbrains",
94
+ project: "app",
95
+ product: "goland",
96
+ }),
97
+ ).toContain("jetbrains://goland/");
98
+ expect(editorFileLink("/repo/a.ts", 3, { kind: "none" })).toBeNull();
99
+ });
100
+ });