micro-models-agent 0.41.2 → 0.42.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 (171) hide show
  1. package/bin/mma.mjs +41 -41
  2. package/dist/cli/commands.js +19 -9
  3. package/dist/cli/completer.js +37 -36
  4. package/dist/cli/index.js +2 -2
  5. package/dist/cli/main.js +23 -48
  6. package/dist/cli/repl-commands.js +12 -40
  7. package/dist/cli/repl.js +87 -217
  8. package/dist/cli/security-commands.js +7 -5
  9. package/dist/cli/setup.js +26 -8
  10. package/dist/config/config.js +5 -52
  11. package/dist/config/defaults.js +5 -29
  12. package/dist/config/experts.js +1 -1
  13. package/dist/config/index.js +3 -3
  14. package/dist/config/security.js +10 -3
  15. package/dist/core/agent-moe.js +10 -2
  16. package/dist/core/agent.js +82 -273
  17. package/dist/core/bootstrap.js +13 -80
  18. package/dist/core/index.js +2 -2
  19. package/dist/core/prompt-builder.js +2 -23
  20. package/dist/core/session-logger.js +4 -46
  21. package/dist/i18n/en.json +2 -75
  22. package/dist/i18n/ru.json +1 -74
  23. package/dist/index.js +1 -1
  24. package/dist/llm/image-utils.js +5 -4
  25. package/dist/llm/index.js +4 -4
  26. package/dist/llm/model-loader.js +6 -6
  27. package/dist/llm/openai-compat.js +34 -40
  28. package/dist/llm/orchestrator.js +29 -33
  29. package/dist/llm/response.js +9 -9
  30. package/dist/logger/app-logger.js +1 -1
  31. package/dist/logger/index.js +1 -1
  32. package/dist/main.js +299 -55
  33. package/dist/migration/backup.js +13 -13
  34. package/dist/migration/detect.js +11 -11
  35. package/dist/migration/index.js +2 -2
  36. package/dist/modules/browser/actions.js +4 -34
  37. package/dist/modules/browser/bridge-server.mjs +202 -202
  38. package/dist/modules/browser/cookie-store.js +6 -6
  39. package/dist/modules/browser/index.js +5 -7
  40. package/dist/modules/browser/module.js +7 -8
  41. package/dist/modules/browser/session.js +84 -87
  42. package/dist/modules/browser/snapshot.js +58 -92
  43. package/dist/modules/browser/types.js +1 -4
  44. package/dist/modules/certification/cli.js +4 -2
  45. package/dist/modules/certification/fact-checker.js +3 -1
  46. package/dist/modules/certification/loader.js +9 -3
  47. package/dist/modules/certification/runner.js +4 -1
  48. package/dist/modules/context/index.js +1 -1
  49. package/dist/modules/context/manager.js +86 -160
  50. package/dist/modules/execution/auditor.js +25 -177
  51. package/dist/modules/execution/module.js +544 -201
  52. package/dist/modules/execution/moe-executor.js +0 -25
  53. package/dist/modules/execution/plan-store.js +3 -1
  54. package/dist/modules/execution/plan-validator.js +10 -10
  55. package/dist/modules/execution/planner.js +1 -6
  56. package/dist/modules/execution/stuck-detector.js +10 -173
  57. package/dist/modules/execution/verifier.js +42 -86
  58. package/dist/modules/hallucination/confidence.js +1 -8
  59. package/dist/modules/hallucination/detector.js +5 -2
  60. package/dist/modules/hallucination/factual.js +64 -3
  61. package/dist/modules/hallucination/index.js +1 -1
  62. package/dist/modules/hallucination/js-identifiers.js +0 -190
  63. package/dist/modules/hallucination/llm-judge.js +3 -1
  64. package/dist/modules/indexer/cache.js +7 -9
  65. package/dist/modules/indexer/index.js +3 -3
  66. package/dist/modules/indexer/module.js +42 -95
  67. package/dist/modules/indexer/walker.js +17 -17
  68. package/dist/modules/lsp/client.js +31 -74
  69. package/dist/modules/lsp/config.js +33 -87
  70. package/dist/modules/lsp/index.js +3 -3
  71. package/dist/modules/lsp/module.js +21 -185
  72. package/dist/modules/mcp/module.js +6 -2
  73. package/dist/modules/memory/index.js +1 -1
  74. package/dist/modules/memory/module.js +23 -71
  75. package/dist/modules/memory/search.js +9 -11
  76. package/dist/modules/memory/store.js +13 -13
  77. package/dist/modules/pipelines/engine.js +10 -10
  78. package/dist/modules/pipelines/index.js +3 -3
  79. package/dist/modules/pipelines/parser.js +14 -17
  80. package/dist/modules/pipelines/template.js +1 -1
  81. package/dist/modules/plugins/builtin/lint-on-write.js +16 -21
  82. package/dist/modules/plugins/builtin/notify.js +2 -3
  83. package/dist/modules/plugins/index.js +1 -1
  84. package/dist/modules/plugins/loader.js +17 -59
  85. package/dist/modules/plugins/manager.js +17 -73
  86. package/dist/modules/processes/index.js +1 -1
  87. package/dist/modules/processes/registry.js +46 -135
  88. package/dist/modules/registry.js +2 -4
  89. package/dist/modules/security/audit-notifier.js +39 -39
  90. package/dist/modules/security/command-validator.js +8 -2
  91. package/dist/modules/security/data-sanitizer.js +9 -1
  92. package/dist/modules/security/encryption.js +56 -58
  93. package/dist/modules/security/network-validator.js +9 -1
  94. package/dist/modules/security/path-validator.js +3 -1
  95. package/dist/modules/security/security-policies.js +19 -3
  96. package/dist/modules/security/session-encryption.js +1 -1
  97. package/dist/modules/security/session-isolation.js +8 -8
  98. package/dist/modules/session/index.js +3 -3
  99. package/dist/modules/session/module.js +5 -5
  100. package/dist/modules/session/store.js +9 -3
  101. package/dist/modules/skills/module.js +2 -1
  102. package/dist/modules/updater/checker.js +6 -70
  103. package/dist/modules/updater/index.js +1 -2
  104. package/dist/modules/user-profile/compressor.js +2 -2
  105. package/dist/modules/user-profile/index.js +1 -1
  106. package/dist/modules/user-profile/profile.js +9 -9
  107. package/dist/tools/attach-image.js +1 -1
  108. package/dist/tools/bash.js +19 -178
  109. package/dist/tools/browser.js +29 -46
  110. package/dist/tools/executor.js +5 -4
  111. package/dist/tools/file-info.js +12 -13
  112. package/dist/tools/filter-tools.js +2 -9
  113. package/dist/tools/glob-tool.js +11 -11
  114. package/dist/tools/grep-tool.js +3 -1
  115. package/dist/tools/index.js +2 -13
  116. package/dist/tools/list-dir.js +17 -18
  117. package/dist/tools/load-skill.js +3 -1
  118. package/dist/tools/path-utils.js +4 -4
  119. package/dist/tools/pipeline-run.js +25 -25
  120. package/dist/tools/process-kill.js +11 -11
  121. package/dist/tools/process-list.js +22 -20
  122. package/dist/tools/process-log.js +18 -22
  123. package/dist/tools/question.js +3 -1
  124. package/dist/tools/read-file.js +2 -10
  125. package/dist/tools/recall.js +37 -44
  126. package/dist/tools/registry.js +4 -15
  127. package/dist/tools/remember.js +29 -29
  128. package/dist/tools/scope-check.js +9 -9
  129. package/dist/tools/subagent.js +9 -54
  130. package/dist/tools/user-input.js +1 -1
  131. package/dist/tools/web-browse.js +3 -3
  132. package/dist/tools/web-fetch.js +3 -3
  133. package/dist/tools/web-search.js +3 -3
  134. package/dist/tools/write-file.js +3 -1
  135. package/dist/ui/box.js +5 -1
  136. package/dist/ui/index.js +6 -6
  137. package/dist/ui/md-formatter.js +33 -33
  138. package/dist/ui/output.js +5 -5
  139. package/dist/ui/renderer.js +10 -15
  140. package/dist/ui/table.js +1 -1
  141. package/package.json +48 -48
  142. package/dist/cli/plugin-commands.js +0 -36
  143. package/dist/cli/run-result.js +0 -22
  144. package/dist/core/version.js +0 -24
  145. package/dist/modules/artifacts/store.js +0 -61
  146. package/dist/modules/browser/bridge-client.js +0 -199
  147. package/dist/modules/browser/bridge-path.js +0 -10
  148. package/dist/modules/browser/driver.js +0 -136
  149. package/dist/modules/context/chunk-query.js +0 -100
  150. package/dist/modules/context/fact-extractor.js +0 -162
  151. package/dist/modules/context/history.js +0 -15
  152. package/dist/modules/execution/audit-runners.js +0 -152
  153. package/dist/modules/execution/execution-plugin.js +0 -272
  154. package/dist/modules/execution/plan-tool.js +0 -508
  155. package/dist/modules/execution/windows-commands.js +0 -41
  156. package/dist/modules/indexer/project-profile.js +0 -183
  157. package/dist/modules/lsp/check-tool.js +0 -58
  158. package/dist/modules/lsp/command.js +0 -60
  159. package/dist/modules/lsp/probe.js +0 -76
  160. package/dist/modules/lsp/project-root.js +0 -32
  161. package/dist/modules/lsp/startup-check.js +0 -141
  162. package/dist/modules/processes/detect.js +0 -34
  163. package/dist/modules/skills/matcher.js +0 -27
  164. package/dist/modules/updater/module.js +0 -116
  165. package/dist/tools/chunk-query.js +0 -99
  166. package/dist/tools/download-file.js +0 -116
  167. package/dist/tools/enable-tools.js +0 -58
  168. package/dist/tools/hidden-tools-block.js +0 -37
  169. package/dist/ui/line-editor.js +0 -703
  170. package/dist/ui/line-math.js +0 -69
  171. package/dist/ui/plan-view.js +0 -103
@@ -1,100 +0,0 @@
1
- export const DEFAULT_CHUNK_SYSTEM_PROMPT = 'Answer the query using ONLY the provided text. Be concise. If the text does not contain the answer, say "NO_EVIDENCE".';
2
- export const DEFAULT_SYNTHESIS_SYSTEM_PROMPT = "You are given a query and per-chunk answers over a large text. Produce the final answer to the query, combining evidence from the chunks. If no chunk had evidence, say so.";
3
- /** Split text into newline-aware chunks, each <= chunkChars chars. */
4
- export function splitTextIntoChunks(text, chunkChars) {
5
- if (chunkChars <= 0)
6
- throw new Error("chunkChars must be > 0");
7
- if (text.length <= chunkChars)
8
- return [text];
9
- const lines = text.split("\n");
10
- const chunks = [];
11
- let current = [];
12
- let size = 0;
13
- for (const line of lines) {
14
- if (current.length > 0 && size + line.length + 1 > chunkChars) {
15
- chunks.push(current.join("\n"));
16
- current = [];
17
- size = 0;
18
- }
19
- current.push(line);
20
- size += line.length + 1;
21
- }
22
- if (current.length > 0)
23
- chunks.push(current.join("\n"));
24
- return chunks;
25
- }
26
- async function chatText(provider, messages, maxTokens, reasoningEffort) {
27
- let out = "";
28
- for await (const chunk of provider.chat(messages, undefined, undefined, {
29
- maxTokens,
30
- reasoningEffort,
31
- })) {
32
- if (chunk.type === "text" && chunk.content)
33
- out += chunk.content;
34
- }
35
- return out;
36
- }
37
- /**
38
- * RLM-style llm_query: answer `query` over `text` by chunking and querying the
39
- * model per chunk with a fixed system prompt (KV-cache friendly), bounded
40
- * concurrency, and an optional synthesis pass.
41
- */
42
- export async function runChunkQuery(provider, text, query, opts = {}) {
43
- const chunkChars = opts.chunkChars ?? 12000;
44
- const maxParallel = Math.max(1, opts.maxParallel ?? 4);
45
- const maxChunkTokens = opts.maxChunkTokens ?? 1024;
46
- const maxSynthesisTokens = opts.maxSynthesisTokens ?? 2048;
47
- const reasoningEffort = opts.reasoningEffort ?? "none";
48
- const chunks = splitTextIntoChunks(text, chunkChars);
49
- const answers = new Array(chunks.length);
50
- const chunkSystem = opts.querySystemPrompt ?? DEFAULT_CHUNK_SYSTEM_PROMPT;
51
- const logger = opts.logger;
52
- if (chunks.length === 1) {
53
- logger?.debug(`runChunkQuery: single chunk (${text.length} chars), no chunking needed`);
54
- }
55
- else {
56
- logger?.debug(`runChunkQuery: ${chunks.length} chunks over ${text.length} chars (chunkChars=${chunkChars}, maxParallel=${maxParallel})`);
57
- }
58
- let cursor = 0;
59
- let inFlight = 0;
60
- let maxParallelObserved = 0;
61
- const workers = Array.from({ length: Math.min(maxParallel, chunks.length) }, async () => {
62
- while (cursor < chunks.length) {
63
- const idx = cursor++;
64
- inFlight++;
65
- maxParallelObserved = Math.max(maxParallelObserved, inFlight);
66
- try {
67
- answers[idx] = await chatText(provider, [
68
- { role: "system", content: chunkSystem },
69
- { role: "user", content: `Query: ${query}\n\nText:\n${chunks[idx]}` },
70
- ], maxChunkTokens, reasoningEffort);
71
- }
72
- finally {
73
- inFlight--;
74
- }
75
- }
76
- });
77
- await Promise.all(workers);
78
- let synthesis = "";
79
- if (opts.synthesize !== false && chunks.length > 0) {
80
- const joined = answers
81
- .map((a, i) => `--- Chunk ${i + 1}/${chunks.length} ---\n${a}`)
82
- .join("\n\n");
83
- logger?.debug(`runChunkQuery: synthesis pass over ${chunks.length} answers`);
84
- synthesis = await chatText(provider, [
85
- {
86
- role: "system",
87
- content: opts.synthesisSystemPrompt ?? DEFAULT_SYNTHESIS_SYSTEM_PROMPT,
88
- },
89
- { role: "user", content: `Query: ${query}\n\nChunk answers:\n${joined}` },
90
- ], maxSynthesisTokens, reasoningEffort);
91
- }
92
- logger?.debug(`runChunkQuery: done, ${chunks.length} chunks, max parallel observed ${maxParallelObserved}, synthesis ${synthesis.length} chars`);
93
- return {
94
- chunks: chunks.length,
95
- answers,
96
- synthesis,
97
- totalChars: text.length,
98
- maxParallelObserved,
99
- };
100
- }
@@ -1,162 +0,0 @@
1
- import { getMessageText } from "../../llm/provider";
2
- /**
3
- * Regex-based fact extraction from tool/assistant messages. Owns the file /
4
- * deleted / decision / error fact lists that survive compaction. Extracted
5
- * from ContextManager so the ~115-line regex logic has one home (rule #2).
6
- */
7
- export class FactExtractor {
8
- fileFacts = [];
9
- deletedFacts = [];
10
- decisionFacts = [];
11
- errorFacts = [];
12
- readFacts = [];
13
- static MAX_FACTS = 20;
14
- get errorCount() {
15
- return this.errorFacts.length;
16
- }
17
- /** Scan a batch of compacted turns and fold their facts into the lists. */
18
- extract(turns) {
19
- // Absolute Windows paths ("E:\proj\src\a.ts") need an optional drive prefix;
20
- // without it the colon breaks the match and the fact is silently dropped.
21
- const DRIVE = "(?:[a-zA-Z]:[\\\\/])?";
22
- const createdPatterns = [
23
- new RegExp(`(?:Created|Updated|Written|Moved|Replaced in) ${DRIVE}([\\w./\\\\-]+\\.[a-z]+)`, "gi"),
24
- new RegExp(`Файл (?:создан|обновлён|записан|перемещён):? ${DRIVE}([\\w./\\\\-]+\\.[a-z]+)`, "gi"),
25
- new RegExp(`file (?:created|updated|written|moved):? ${DRIVE}([\\w./\\\\-]+\\.[a-z]+)`, "gi"),
26
- ];
27
- const deletedPatterns = [
28
- new RegExp(`Deleted ${DRIVE}([\\w./\\\\-]+\\.[a-z]+)`, "gi"),
29
- new RegExp(`(?:Удалён|Файл удалён):? ${DRIVE}([\\w./\\\\-]+\\.[a-z]+)`, "gi"),
30
- ];
31
- // read_file output header — locale-independent prefix `── path (ext, …`
32
- // (en: "lines", ru: "строк"). The path is already prefixed with the same
33
- // box-drawing marker in both locales, so the pattern needs no localization.
34
- const readPatterns = [new RegExp(`── (${DRIVE}[\\w./\\\\-]+\\.[a-z]+) \\(`, "gi")];
35
- const newFiles = [];
36
- const newDeleted = [];
37
- const newDecisions = [];
38
- const newErrors = [];
39
- const newReads = [];
40
- // Track the LAST tool event per path so a delete followed by a re-create
41
- // (or vice versa) in the same window resolves to its final state instead of
42
- // being both filtered out of [Files:] and reported as [Deleted:].
43
- const lastEvent = new Map();
44
- for (const msg of turns) {
45
- const content = getMessageText(msg.content);
46
- // The system prompt is never a fact source — the memory module embeds
47
- // errors.md (with historical "Tool X failed Nx" entries from PAST days)
48
- // there, and extracting that text as current [Errors:] misleads the model
49
- // into thinking IT is failing (observed: ses_msvuao0h — a stale
50
- // "edit_file failed 3x" from 2026-08-15 landed in every compaction
51
- // summary as if it were the live session's failure).
52
- if (msg.role === "system")
53
- continue;
54
- // Never feed a previous <system-summary> block into new facts — that is
55
- // the source of recursive summary nesting (summary inside summary).
56
- if (msg.role === "user" &&
57
- (content.startsWith("<system-summary>") || content.includes("[Compressed:"))) {
58
- continue;
59
- }
60
- if (msg.role === "tool") {
61
- for (const pattern of createdPatterns) {
62
- for (const match of content.matchAll(pattern)) {
63
- newFiles.push(match[1]);
64
- lastEvent.set(match[1], "file");
65
- }
66
- }
67
- for (const pattern of deletedPatterns) {
68
- for (const match of content.matchAll(pattern)) {
69
- newDeleted.push(match[1]);
70
- lastEvent.set(match[1], "deleted");
71
- }
72
- }
73
- for (const pattern of readPatterns) {
74
- for (const match of content.matchAll(pattern)) {
75
- newReads.push(match[1]);
76
- }
77
- }
78
- if (content.includes("Plan:") && content.includes("[")) {
79
- const planLine = content.split("\n").find((line) => line.includes("Plan:"));
80
- if (planLine)
81
- newDecisions.push(planLine.trim());
82
- }
83
- }
84
- if (msg.role === "assistant") {
85
- if (content.includes("decided:") || content.includes("decision:")) {
86
- const line = content
87
- .split("\n")
88
- .find((l) => l.includes("decided:") || l.includes("decision:"));
89
- if (line)
90
- newDecisions.push(line.trim().slice(0, 200));
91
- }
92
- }
93
- if (msg.role === "tool" || msg.role === "assistant") {
94
- if (content.includes("Error:") ||
95
- content.includes("failed") ||
96
- content.includes("Ошибка:") ||
97
- content.includes("не удалось")) {
98
- const line = content
99
- .split("\n")
100
- .find((l) => l.includes("Error:") ||
101
- l.includes("failed") ||
102
- l.includes("Ошибка:") ||
103
- l.includes("не удалось"));
104
- if (line)
105
- newErrors.push(line.trim().slice(0, 250));
106
- }
107
- }
108
- }
109
- // Deduplicate and cap facts to prevent unbounded growth. Files that were
110
- // DELETED leave the "known files" list — a deleted file must not keep
111
- // being reported as existing (observed: deleted .js files listed in
112
- // every [Files: ...] block for the whole session). A path that is deleted
113
- // then RE-CREATED (delete_file A → write_file A) is un-deleted: the last
114
- // event in the window wins, so it returns to [Files:] and leaves [Deleted:].
115
- const dedup = (arr) => [...new Set(arr)];
116
- const finalFiles = dedup(newFiles.filter((p) => lastEvent.get(p) === "file"));
117
- const finalDeleted = dedup(newDeleted.filter((p) => lastEvent.get(p) === "deleted"));
118
- this.fileFacts = dedup([...this.fileFacts, ...finalFiles].filter((p) => !finalDeleted.includes(p))).slice(-FactExtractor.MAX_FACTS);
119
- this.deletedFacts = dedup([...this.deletedFacts, ...finalDeleted].filter((p) => !finalFiles.includes(p))).slice(-FactExtractor.MAX_FACTS);
120
- this.decisionFacts = dedup([...this.decisionFacts, ...newDecisions]).slice(-FactExtractor.MAX_FACTS);
121
- this.errorFacts = dedup([...this.errorFacts, ...newErrors]).slice(-FactExtractor.MAX_FACTS);
122
- this.readFacts = dedup([...this.readFacts, ...newReads]).slice(-FactExtractor.MAX_FACTS);
123
- }
124
- /** `[Files: a; b]` line for a compaction summary, or null. */
125
- filesLine() {
126
- const deletedSet = new Set(this.deletedFacts);
127
- const liveFiles = this.fileFacts.filter((p) => !deletedSet.has(p));
128
- if (liveFiles.length === 0)
129
- return null;
130
- return `[Files: ${liveFiles.slice(-15).join("; ")}]`;
131
- }
132
- /** `[Deleted: c]` line, or null. */
133
- deletedLine() {
134
- if (this.deletedFacts.length === 0)
135
- return null;
136
- return `[Deleted: ${this.deletedFacts.slice(-10).join("; ")}]`;
137
- }
138
- /** `[Decisions: d]` line, or null. */
139
- decisionsLine() {
140
- if (this.decisionFacts.length === 0)
141
- return null;
142
- return `[Decisions: ${this.decisionFacts.slice(-5).join("; ")}]`;
143
- }
144
- /** `[Errors: e]` line, or null. */
145
- errorsLine() {
146
- if (this.errorFacts.length === 0)
147
- return null;
148
- return `[Errors: ${this.errorFacts.slice(-3).join("; ")}]`;
149
- }
150
- /**
151
- * `[Read: p1; p2]` line — files already inspected via read_file. Lets the
152
- * model re-orient after compaction without rescanning the whole project: it
153
- * knows which files were already read and only re-reads what changed
154
- * (observed: post-compaction the model re-read the same files it had already
155
- * inspected, because "already read" never survived compaction).
156
- */
157
- readLine() {
158
- if (this.readFacts.length === 0)
159
- return null;
160
- return `[Read: ${this.readFacts.slice(-12).join("; ")}]`;
161
- }
162
- }
@@ -1,15 +0,0 @@
1
- import { appendFileSync, mkdirSync, existsSync } from 'fs';
2
- import { join } from 'path';
3
- export class SessionHistoryWriter {
4
- historyPath;
5
- constructor(sessionsDir, sessionId) {
6
- const sessionDir = join(sessionsDir, sessionId);
7
- if (!existsSync(sessionDir)) {
8
- mkdirSync(sessionDir, { recursive: true });
9
- }
10
- this.historyPath = join(sessionDir, 'history.jsonl');
11
- }
12
- append(msg) {
13
- appendFileSync(this.historyPath, JSON.stringify(msg) + '\n', 'utf-8');
14
- }
15
- }
@@ -1,152 +0,0 @@
1
- import { existsSync, readdirSync } from "fs";
2
- import { dirname, join, resolve } from "path";
3
- import { detectTestResults } from "../../tools/bash";
4
- import { processRegistry } from "../processes";
5
- /** Directories never searched for test files. */
6
- export const SKIP_DIRS = new Set([
7
- "node_modules",
8
- ".git",
9
- ".mma",
10
- "dist",
11
- "build",
12
- "coverage",
13
- ".next",
14
- ".nuxt",
15
- "vendor",
16
- ]);
17
- const TEST_EXT_RE = /\.(test|spec)\.[jt]sx?$/i;
18
- const TEST_STEP_RE = /\b(test(ing|s)?|тест(ы|ирование|ировать)?|провер\w*\s+тест|запустить\s+тест)\b|bun test|npm test|vitest|pytest|go test|jest|mocha/i;
19
- /** Recursive, depth-limited walk that stops early on the first test file. */
20
- export function findTestFile(dir, depth = 0) {
21
- if (depth > 5)
22
- return null;
23
- let entries;
24
- try {
25
- entries = readdirSync(dir, { withFileTypes: true });
26
- }
27
- catch {
28
- return null;
29
- }
30
- for (const e of entries) {
31
- const full = join(dir, e.name);
32
- if (e.isDirectory()) {
33
- if (SKIP_DIRS.has(e.name))
34
- continue;
35
- const found = findTestFile(full, depth + 1);
36
- if (found)
37
- return found;
38
- }
39
- else if (TEST_EXT_RE.test(e.name)) {
40
- return full;
41
- }
42
- }
43
- return null;
44
- }
45
- /** The plan's step descriptions mention running/checking tests. */
46
- export function hasTestStep(plan) {
47
- return plan.steps.some((s) => TEST_STEP_RE.test(s.description));
48
- }
49
- /** Extract failing test names from a runner's output (bun/vitest style). */
50
- function extractFailingNames(output, limit = 5) {
51
- const names = [];
52
- for (const m of output.matchAll(/\(fail\)\s*([^\n]+)/g)) {
53
- const name = m[1].trim();
54
- if (name && !names.includes(name))
55
- names.push(name);
56
- if (names.length >= limit)
57
- break;
58
- }
59
- return names;
60
- }
61
- export async function runTests(baseDir) {
62
- const entry = processRegistry.start("bun test", baseDir);
63
- const exited = await processRegistry.waitForExit(entry.id, 90_000);
64
- const output = entry.log.join("\n");
65
- processRegistry.remove(entry.id);
66
- if (!exited) {
67
- // Timed out — we cannot claim success or failure from an unfinished run.
68
- return {
69
- checked: true,
70
- passed: true, // don't block completion on an inconclusive run
71
- failed: 0,
72
- passedCount: 0,
73
- detail: "test run timed out after 90s — result unknown",
74
- command: "bun test",
75
- };
76
- }
77
- const run = detectTestResults(output);
78
- if (!run) {
79
- // No recognizable runner summary. A non-zero exit means the test run
80
- // (or its runner) failed — the audit must not pass on it; report a
81
- // single "at least one failed" since we cannot count them. Exit 0
82
- // with unrecognized output stays checked-but-inconclusive.
83
- return {
84
- checked: true,
85
- passed: entry.exitCode === 0,
86
- failed: entry.exitCode === 0 ? 0 : 1,
87
- passedCount: 0,
88
- detail: output.slice(0, 200).trim(),
89
- command: "bun test",
90
- };
91
- }
92
- const names = extractFailingNames(output);
93
- return {
94
- checked: true,
95
- passed: run.failed === 0,
96
- failed: run.failed,
97
- passedCount: run.passed,
98
- detail: names.length
99
- ? names.join("; ")
100
- : run.summary || `${run.failed} failed / ${run.passed} passed`,
101
- command: "bun test",
102
- };
103
- }
104
- /** First `error TS…` line in a tsc output, or null when none/inconclusive. */
105
- export function parseTypecheckErrors(output) {
106
- const line = output.split("\n").find((l) => /error TS\d+/.test(l));
107
- return line ? line.trim().slice(0, 300) : null;
108
- }
109
- /**
110
- * Locate the nearest project root that owns a tsconfig.json.
111
- *
112
- * The agent frequently creates the project in a nested subfolder of its
113
- * baseDir (e.g. `bicycle-shop/`), so the tsconfig lives at
114
- * `baseDir/bicycle-shop/` and the old `existsSync(baseDir/tsconfig.json)`
115
- * gate silently skipped the final typecheck — the audit passed even with
116
- * dozens of tsc errors (observed in both analyzed sessions). This walks each
117
- * candidate (baseDir plus the resolved step files) upward to the nearest
118
- * tsconfig.json, preferring the shallowest hit so the baseDir project wins
119
- * over a stray tsconfig further up. Returns null when no tsconfig exists in
120
- * any reachable subtree. `existingFiles` must contain resolved absolute paths
121
- * (relative tokens would resolve against the process cwd, not baseDir).
122
- */
123
- export function findTypecheckRoot(baseDir, existingFiles = []) {
124
- const candidates = [baseDir, ...existingFiles];
125
- let best = null;
126
- for (const start of candidates) {
127
- let dir = resolve(start);
128
- for (let depth = 0; depth <= 10; depth++) {
129
- if (existsSync(join(dir, "tsconfig.json"))) {
130
- if (!best || depth < best.depth)
131
- best = { depth, root: dir };
132
- break;
133
- }
134
- const parent = dirname(dir);
135
- if (parent === dir)
136
- break;
137
- dir = parent;
138
- }
139
- }
140
- return best?.root ?? null;
141
- }
142
- export async function runTypecheck(baseDir) {
143
- const entry = processRegistry.start("npx --no-install tsc --noEmit --skipLibCheck", baseDir);
144
- const exited = await processRegistry.waitForExit(entry.id, 90_000);
145
- const output = entry.log.join("\n");
146
- processRegistry.remove(entry.id);
147
- // A timeout, or output with no `error TS` lines (missing typescript / wrong
148
- // working dir) is inconclusive — never block completion on those.
149
- if (!exited)
150
- return null;
151
- return parseTypecheckErrors(output);
152
- }