micro-models-agent 0.57.0 → 0.57.2

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 (233) hide show
  1. package/CHANGELOG.md +518 -476
  2. package/README.md +358 -358
  3. package/dist/certification/certifications.json +493 -493
  4. package/dist/cli/commands.js +447 -0
  5. package/dist/cli/completer.js +167 -0
  6. package/dist/cli/index.js +2 -0
  7. package/dist/cli/main.js +153 -0
  8. package/dist/cli/plugin-commands.js +36 -0
  9. package/dist/cli/repl-commands.js +761 -0
  10. package/dist/cli/repl.js +702 -0
  11. package/dist/cli/run-result.js +33 -0
  12. package/dist/cli/security-commands.js +164 -0
  13. package/dist/cli/setup.js +237 -0
  14. package/dist/config/config.js +276 -0
  15. package/dist/config/defaults.js +141 -0
  16. package/dist/config/domains.js +179 -0
  17. package/dist/config/experts.js +15 -0
  18. package/dist/config/index.js +4 -0
  19. package/dist/config/security.js +213 -0
  20. package/dist/config/types.js +1 -0
  21. package/dist/core/agent-moe.js +102 -0
  22. package/dist/core/agent.js +1018 -0
  23. package/dist/core/bootstrap.js +481 -0
  24. package/dist/core/crash-handler.js +51 -0
  25. package/dist/core/environment.js +199 -0
  26. package/dist/core/index.js +2 -0
  27. package/dist/core/prompt-builder.js +76 -0
  28. package/dist/core/session-logger.js +251 -0
  29. package/dist/core/types.js +1 -0
  30. package/dist/core/version.js +26 -0
  31. package/dist/core/workspace.js +76 -0
  32. package/dist/i18n/en.json +679 -0
  33. package/dist/i18n/index.js +46 -0
  34. package/dist/i18n/ru.json +679 -0
  35. package/dist/index.js +22 -0
  36. package/dist/llm/image-utils.js +143 -0
  37. package/dist/llm/index.js +4 -0
  38. package/dist/llm/model-loader.js +78 -0
  39. package/dist/llm/openai-compat.js +497 -0
  40. package/dist/llm/orchestrator.js +200 -0
  41. package/dist/llm/provider.js +10 -0
  42. package/dist/llm/response.js +39 -0
  43. package/dist/llm/token-counter.js +39 -0
  44. package/dist/llm/types.js +1 -0
  45. package/dist/logger/app-logger.js +189 -0
  46. package/dist/logger/file-log.js +151 -0
  47. package/dist/logger/index.js +1 -0
  48. package/dist/main.js +2351 -1640
  49. package/dist/migration/backup.js +45 -0
  50. package/dist/migration/detect.js +50 -0
  51. package/dist/migration/index.js +2 -0
  52. package/dist/modules/artifacts/store.js +61 -0
  53. package/dist/modules/browser/actions.js +76 -0
  54. package/dist/modules/browser/bridge-client.js +199 -0
  55. package/dist/modules/browser/bridge-path.js +10 -0
  56. package/dist/modules/browser/bridge-server.mjs +219 -219
  57. package/dist/modules/browser/cookie-store.js +24 -0
  58. package/dist/modules/browser/driver.js +136 -0
  59. package/dist/modules/browser/index.js +7 -0
  60. package/dist/modules/browser/module.js +29 -0
  61. package/dist/modules/browser/session.js +342 -0
  62. package/dist/modules/browser/snapshot.js +148 -0
  63. package/dist/modules/browser/types.js +12 -0
  64. package/dist/modules/certification/cli.js +213 -0
  65. package/dist/modules/certification/fact-checker.js +82 -0
  66. package/dist/modules/certification/loader.js +106 -0
  67. package/dist/modules/certification/manifest.js +58 -0
  68. package/dist/modules/certification/runner.js +245 -0
  69. package/dist/modules/certification/scenarios.js +407 -0
  70. package/dist/modules/certification/types.js +1 -0
  71. package/dist/modules/context/chunk-query.js +100 -0
  72. package/dist/modules/context/fact-extractor.js +168 -0
  73. package/dist/modules/context/history.js +15 -0
  74. package/dist/modules/context/index.js +1 -0
  75. package/dist/modules/context/manager.js +440 -0
  76. package/dist/modules/execution/audit-runners.js +206 -0
  77. package/dist/modules/execution/auditor.js +218 -0
  78. package/dist/modules/execution/execution-plugin.js +431 -0
  79. package/dist/modules/execution/index.js +8 -0
  80. package/dist/modules/execution/module.js +625 -0
  81. package/dist/modules/execution/moe-executor.js +304 -0
  82. package/dist/modules/execution/plan-coverage.js +68 -0
  83. package/dist/modules/execution/plan-persister.js +46 -0
  84. package/dist/modules/execution/plan-store.js +196 -0
  85. package/dist/modules/execution/plan-tool.js +677 -0
  86. package/dist/modules/execution/plan-validator.js +153 -0
  87. package/dist/modules/execution/planner.js +94 -0
  88. package/dist/modules/execution/stuck-detector.js +746 -0
  89. package/dist/modules/execution/tracker.js +69 -0
  90. package/dist/modules/execution/types.js +1 -0
  91. package/dist/modules/execution/verifier.js +235 -0
  92. package/dist/modules/execution/windows-commands.js +41 -0
  93. package/dist/modules/hallucination/confidence.js +66 -0
  94. package/dist/modules/hallucination/consistency.js +26 -0
  95. package/dist/modules/hallucination/detector.js +47 -0
  96. package/dist/modules/hallucination/factual.js +169 -0
  97. package/dist/modules/hallucination/index.js +5 -0
  98. package/dist/modules/hallucination/js-identifiers.js +262 -0
  99. package/dist/modules/hallucination/llm-judge.js +101 -0
  100. package/dist/modules/index.js +5 -0
  101. package/dist/modules/indexer/cache.js +40 -0
  102. package/dist/modules/indexer/index.js +3 -0
  103. package/dist/modules/indexer/module.js +246 -0
  104. package/dist/modules/indexer/project-profile.js +183 -0
  105. package/dist/modules/indexer/walker.js +101 -0
  106. package/dist/modules/lsp/check-tool.js +58 -0
  107. package/dist/modules/lsp/client.js +389 -0
  108. package/dist/modules/lsp/command.js +60 -0
  109. package/dist/modules/lsp/config.js +135 -0
  110. package/dist/modules/lsp/index.js +3 -0
  111. package/dist/modules/lsp/module.js +260 -0
  112. package/dist/modules/lsp/probe.js +86 -0
  113. package/dist/modules/lsp/project-root.js +32 -0
  114. package/dist/modules/lsp/startup-check.js +144 -0
  115. package/dist/modules/lsp/types.js +1 -0
  116. package/dist/modules/mcp/client.js +399 -0
  117. package/dist/modules/mcp/index.js +3 -0
  118. package/dist/modules/mcp/module.js +142 -0
  119. package/dist/modules/mcp/registry.js +15 -0
  120. package/dist/modules/memory/index.js +1 -0
  121. package/dist/modules/memory/module.js +96 -0
  122. package/dist/modules/memory/search.js +42 -0
  123. package/dist/modules/memory/store.js +69 -0
  124. package/dist/modules/pipelines/engine.js +60 -0
  125. package/dist/modules/pipelines/index.js +3 -0
  126. package/dist/modules/pipelines/parser.js +56 -0
  127. package/dist/modules/pipelines/template.js +14 -0
  128. package/dist/modules/plugins/builtin/lint-on-write.js +334 -0
  129. package/dist/modules/plugins/builtin/notify.js +9 -0
  130. package/dist/modules/plugins/index.js +1 -0
  131. package/dist/modules/plugins/loader.js +70 -0
  132. package/dist/modules/plugins/manager.js +261 -0
  133. package/dist/modules/plugins/types.js +1 -0
  134. package/dist/modules/pricing/index.js +61 -0
  135. package/dist/modules/pricing/prices.js +129 -0
  136. package/dist/modules/processes/detect.js +34 -0
  137. package/dist/modules/processes/index.js +2 -0
  138. package/dist/modules/processes/registry.js +327 -0
  139. package/dist/modules/processes/runner.js +23 -0
  140. package/dist/modules/providers/create.js +22 -0
  141. package/dist/modules/providers/fallback.js +79 -0
  142. package/dist/modules/providers/health.js +46 -0
  143. package/dist/modules/providers/index.js +5 -0
  144. package/dist/modules/providers/manager.js +161 -0
  145. package/dist/modules/providers/presets.js +128 -0
  146. package/dist/modules/providers/registry.js +22 -0
  147. package/dist/modules/providers/types.js +1 -0
  148. package/dist/modules/registry.js +48 -0
  149. package/dist/modules/security/audit-log.js +136 -0
  150. package/dist/modules/security/audit-notifier.js +292 -0
  151. package/dist/modules/security/command-validator.js +219 -0
  152. package/dist/modules/security/content-scanner.js +53 -0
  153. package/dist/modules/security/data-sanitizer.js +89 -0
  154. package/dist/modules/security/encryption.js +242 -0
  155. package/dist/modules/security/index.js +14 -0
  156. package/dist/modules/security/network-validator.js +88 -0
  157. package/dist/modules/security/path-validator.js +203 -0
  158. package/dist/modules/security/rate-limiter.js +119 -0
  159. package/dist/modules/security/security-policies.js +531 -0
  160. package/dist/modules/security/session-encryption.js +210 -0
  161. package/dist/modules/security/session-isolation.js +95 -0
  162. package/dist/modules/session/index.js +3 -0
  163. package/dist/modules/session/manager.js +172 -0
  164. package/dist/modules/session/module.js +24 -0
  165. package/dist/modules/session/store.js +222 -0
  166. package/dist/modules/session/types.js +1 -0
  167. package/dist/modules/skills/index.js +2 -0
  168. package/dist/modules/skills/loader.js +72 -0
  169. package/dist/modules/skills/matcher.js +27 -0
  170. package/dist/modules/skills/module.js +129 -0
  171. package/dist/modules/types.js +1 -0
  172. package/dist/modules/updater/checker.js +96 -0
  173. package/dist/modules/updater/index.js +2 -0
  174. package/dist/modules/updater/module.js +116 -0
  175. package/dist/modules/user-profile/compressor.js +16 -0
  176. package/dist/modules/user-profile/index.js +1 -0
  177. package/dist/modules/user-profile/profile.js +68 -0
  178. package/dist/skills/builtin/git.md +36 -36
  179. package/dist/skills/builtin/typescript.md +35 -35
  180. package/dist/tools/approve.js +33 -0
  181. package/dist/tools/attach-image.js +101 -0
  182. package/dist/tools/bash.js +519 -0
  183. package/dist/tools/browser.js +115 -0
  184. package/dist/tools/chunk-query.js +100 -0
  185. package/dist/tools/create-dir.js +56 -0
  186. package/dist/tools/delete-file.js +63 -0
  187. package/dist/tools/download-file.js +117 -0
  188. package/dist/tools/edit-file.js +80 -0
  189. package/dist/tools/enable-tools.js +59 -0
  190. package/dist/tools/executor.js +154 -0
  191. package/dist/tools/file-info.js +47 -0
  192. package/dist/tools/filter-tools.js +17 -0
  193. package/dist/tools/glob-tool.js +27 -0
  194. package/dist/tools/grep-tool.js +125 -0
  195. package/dist/tools/hidden-tools-block.js +37 -0
  196. package/dist/tools/index.js +78 -0
  197. package/dist/tools/list-dir.js +49 -0
  198. package/dist/tools/load-skill.js +43 -0
  199. package/dist/tools/mcp-call.js +69 -0
  200. package/dist/tools/move-file.js +86 -0
  201. package/dist/tools/path-utils.js +101 -0
  202. package/dist/tools/pipeline-run.js +145 -0
  203. package/dist/tools/preview.js +2 -0
  204. package/dist/tools/process-kill.js +40 -0
  205. package/dist/tools/process-list.js +37 -0
  206. package/dist/tools/process-log.js +54 -0
  207. package/dist/tools/question.js +141 -0
  208. package/dist/tools/read-file.js +179 -0
  209. package/dist/tools/recall.js +118 -0
  210. package/dist/tools/registry.js +47 -0
  211. package/dist/tools/remember.js +68 -0
  212. package/dist/tools/scope-check.js +32 -0
  213. package/dist/tools/search-history.js +85 -0
  214. package/dist/tools/subagent.js +196 -0
  215. package/dist/tools/types.js +1 -0
  216. package/dist/tools/user-input.js +123 -0
  217. package/dist/tools/web-browse.js +87 -0
  218. package/dist/tools/web-fetch.js +119 -0
  219. package/dist/tools/web-search.js +105 -0
  220. package/dist/tools/write-file.js +82 -0
  221. package/dist/ui/box.js +77 -0
  222. package/dist/ui/colors.js +4 -0
  223. package/dist/ui/diff.js +178 -0
  224. package/dist/ui/index.js +6 -0
  225. package/dist/ui/line-editor.js +822 -0
  226. package/dist/ui/line-math.js +73 -0
  227. package/dist/ui/md-formatter.js +212 -0
  228. package/dist/ui/output.js +13 -0
  229. package/dist/ui/plan-view.js +103 -0
  230. package/dist/ui/renderer.js +259 -0
  231. package/dist/ui/spinner.js +70 -0
  232. package/dist/ui/table.js +144 -0
  233. package/package.json +51 -51
@@ -0,0 +1,625 @@
1
+ import { t } from "../../i18n/index";
2
+ import { PlanTracker } from "./tracker";
3
+ import { StepVerifier } from "./verifier";
4
+ import { StuckDetector, isSearchableError, buildSearchQuery } from "./stuck-detector";
5
+ import { Auditor, findExistingFile } from "./auditor";
6
+ import { PlanStore } from "./plan-store";
7
+ import { getMessageText } from "../../llm/provider";
8
+ import { extractFileLikeTokens, stripUrls } from "../hallucination/js-identifiers";
9
+ import { existsSync, readFileSync } from "fs";
10
+ import { resolve } from "path";
11
+ import { performWebSearch } from "../../tools/web-search";
12
+ import { getSessionSecurityConfig } from "../security/session-isolation";
13
+ import { createPlanToolDefinitions } from "./plan-tool";
14
+ import { createExecutionPlugin, STUCK_RECOVERY_COOLDOWN, STUCK_WARN_REPEAT_EVERY, } from "./execution-plugin";
15
+ /**
16
+ * Minimum interval between automatic error searches. The spec asked for a
17
+ * STUCK_RECOVERY_COOLDOWN-iteration cap, but onAfterTool has no iteration
18
+ * counter (executor context), so the same anti-spam protection is
19
+ * time-based. Injectable via the constructor for tests (0 disables it).
20
+ */
21
+ const ERROR_SEARCH_MIN_INTERVAL_MS = 30000;
22
+ export class ExecutionModule {
23
+ name = "execution";
24
+ tracker = null;
25
+ verifier;
26
+ stuckDetector;
27
+ auditor;
28
+ store;
29
+ baseDir;
30
+ // Skip the first audit after restoring a plan from disk — gives the user
31
+ // one chance to change the subject before the audit gate locks in.
32
+ _auditSkipsRemaining = 0;
33
+ /**
34
+ * The last plan that was COMPLETED and auto-archived. `plan update` on the
35
+ * final step clears the tracker, which used to make runFinalAudit() return
36
+ * null and silently skip the final audit (tests + tsc + file checks) for a
37
+ * finished task. Keep the completed plan so the audit gate still runs.
38
+ */
39
+ completedPlan = null;
40
+ /**
41
+ * Deferred <system-summary> messages. Injected by onBeforeTool/onAfterTool
42
+ * but flushed in onBeforeThink, so they never land between an assistant
43
+ * tool_call message and its tool results (which breaks message pairing and
44
+ * buries the warnings the model should react to).
45
+ */
46
+ pendingMessages = [];
47
+ // Per-command failure counters for forbidden Windows commands (grep/sed/ls/
48
+ // find/… invoked through the bash tool). A hard stop after the second
49
+ // failure is evidence-based (actual command failures), not task
50
+ // classification (rule #10).
51
+ forbiddenBashFailures = new Map();
52
+ searchRunner;
53
+ webSearchThreshold;
54
+ searchesThisSession = 0;
55
+ retryWebSearchSignatures = new Set();
56
+ lastErrorSearchAt = 0;
57
+ errorSearchCooldownMs;
58
+ hallucinationDetector = null;
59
+ /**
60
+ * The execution-plugin's mutable state. Owned HERE and passed BY REFERENCE
61
+ * to the plugin factory — the plugin writes deps.state.* directly, so the
62
+ * assignments are visible on the module without any write-back.
63
+ */
64
+ state = {
65
+ lastRecoveryIteration: -STUCK_RECOVERY_COOLDOWN,
66
+ consecutivePlanWarnings: 0,
67
+ lastStepId: -1,
68
+ stuckNotified: false,
69
+ lastStuckWarnKey: "",
70
+ lastStuckWarnIter: -STUCK_WARN_REPEAT_EVERY,
71
+ depsGateHints: new Map(),
72
+ mutationsWithoutPlan: 0,
73
+ planNudgeSent: false,
74
+ typecheckFailures: new Map(),
75
+ };
76
+ /**
77
+ * Read/write accessor for the tracker, shared with the plan-tool and
78
+ * execution-plugin factories. The `plan` tool's abort action clears it
79
+ * (current = null) — the setter keeps this.tracker in sync. Object-literal
80
+ * getters bind `this` to the literal, so the instance is captured in a
81
+ * closure instead.
82
+ */
83
+ trackerRef = (() => {
84
+ const self = this;
85
+ return {
86
+ get current() {
87
+ return self.tracker;
88
+ },
89
+ set current(v) {
90
+ self.tracker = v;
91
+ },
92
+ };
93
+ })();
94
+ constructor(baseDir, stuckThreshold = 6, webSearchThreshold = 5, searchRunner = performWebSearch, errorSearchCooldownMs = ERROR_SEARCH_MIN_INTERVAL_MS) {
95
+ this.baseDir = baseDir;
96
+ this.verifier = new StepVerifier(baseDir);
97
+ this.stuckDetector = new StuckDetector(stuckThreshold, 3, webSearchThreshold);
98
+ this.auditor = new Auditor(baseDir);
99
+ this.store = new PlanStore(baseDir);
100
+ this.webSearchThreshold = webSearchThreshold;
101
+ this.searchRunner = searchRunner;
102
+ this.errorSearchCooldownMs = errorSearchCooldownMs;
103
+ }
104
+ setPlan(plan) {
105
+ this.tracker = new PlanTracker(plan);
106
+ // Advance the pointer past any done/skipped steps of a restored/replanned
107
+ // plan so display ("current: step N") and the off-track alignment match
108
+ // reality instead of always pointing at step 1.
109
+ this.tracker.syncCurrentStep();
110
+ this.store.saveActive(plan);
111
+ this.completedPlan = null; // a new plan supersedes the completed one
112
+ this._auditSkipsRemaining = 0; // plan explicitly created — arm the audit gate
113
+ }
114
+ /** Wire the hallucination detector so the plan tool can check whether
115
+ * a file was tracked as deleted (auto-switch kind gate). */
116
+ setHallucinationDetector(detector) {
117
+ this.hallucinationDetector = detector;
118
+ }
119
+ /** Remember the last completed plan so the final audit can still verify it
120
+ * after the tracker was cleared by the auto-archive. */
121
+ recordCompleted(plan) {
122
+ this.completedPlan = plan;
123
+ }
124
+ /** Forget the completed plan (abort/delete/purge — nothing left to audit). */
125
+ clearCompleted() {
126
+ this.completedPlan = null;
127
+ }
128
+ restorePlan() {
129
+ const plan = this.store.loadActive();
130
+ if (!plan)
131
+ return false;
132
+ const restored = new PlanTracker(plan);
133
+ // A plan that was already complete when saved must not come back as the
134
+ // active plan — archive it so it cannot re-anchor the agent (restored
135
+ // completed plans caused the "continue step 4" loop on restart).
136
+ if (restored.isComplete()) {
137
+ this.store.archivePlan(plan);
138
+ this.tracker = null;
139
+ return false;
140
+ }
141
+ this.tracker = restored;
142
+ // Advance to the first non-done step
143
+ this.tracker.syncCurrentStep();
144
+ this._auditSkipsRemaining = 1; // restored plan — one free pass
145
+ return true;
146
+ }
147
+ getTracker() {
148
+ return this.tracker;
149
+ }
150
+ /** The currently tracked plan (single source of truth for UI consumers).
151
+ * Null in a fresh session — a disk-resident plan is restored only when
152
+ * resuming a session with history, so the REPL must never see stale plans. */
153
+ getActivePlan() {
154
+ return this.tracker?.getPlan() ?? null;
155
+ }
156
+ getStore() {
157
+ return this.store;
158
+ }
159
+ getStuckDetector() {
160
+ return this.stuckDetector;
161
+ }
162
+ /**
163
+ * Automatic web search for a repeatedly failing error (>= errorWebSearch.threshold
164
+ * identical signatures). Fires the search fire-and-forget (never blocks the tool
165
+ * result) and queues the results as a <system-summary> in pendingMessages.
166
+ *
167
+ * Gates: webSearch master switch + errorWebSearch switch → repeated signature
168
+ * → not-searched (or retried) → session cap → meaningful error text →
169
+ * cooldown. One search per signature; empty results trigger a single retry
170
+ * (unmarkErrorSearched once), then the signature stays searched.
171
+ */
172
+ maybeSearchError(ctx, call) {
173
+ if (ctx.config?.webSearch?.enabled === false)
174
+ return;
175
+ const cfg = ctx.config?.errorWebSearch;
176
+ if (!cfg?.enabled)
177
+ return;
178
+ const sig = this.stuckDetector.getRepeatedErrorSignature();
179
+ if (!sig)
180
+ return;
181
+ if (this.stuckDetector.hasErrorSearched(sig) && !this.retryWebSearchSignatures.has(sig))
182
+ return;
183
+ if (this.searchesThisSession >= (cfg.maxSearchesPerSession ?? 3))
184
+ return;
185
+ const lastError = this.stuckDetector.getLastErrorOutput();
186
+ if (!isSearchableError(lastError)) {
187
+ ctx.logger?.debug(t("exec.error_search_no_query"));
188
+ return;
189
+ }
190
+ const now = Date.now();
191
+ if (now - this.lastErrorSearchAt < this.errorSearchCooldownMs)
192
+ return;
193
+ const stepDesc = this.tracker?.getCurrentStep()?.description ?? "";
194
+ const query = buildSearchQuery(stepDesc, this.stuckDetector.getLastBashCommand(), lastError, call.name, cfg.maxQueryChars ?? 200);
195
+ const count = this.stuckDetector.getErrorSignatureCount(sig);
196
+ this.stuckDetector.markErrorSearched(sig);
197
+ this.searchesThisSession++;
198
+ this.lastErrorSearchAt = now;
199
+ const networkConfig = getSessionSecurityConfig(ctx.config, ctx.sessionContext).network;
200
+ this.searchRunner(query, cfg.maxResults ?? 5, networkConfig, cfg.requestTimeoutMs ?? 10000)
201
+ .then((res) => {
202
+ if (!res.success || res.results.length === 0) {
203
+ if (!this.retryWebSearchSignatures.has(sig)) {
204
+ this.retryWebSearchSignatures.add(sig);
205
+ this.stuckDetector.unmarkErrorSearched(sig);
206
+ }
207
+ ctx.logger?.warn(t("exec.error_search_failed", { query }));
208
+ ctx.sessionLog?.plan("web-search", `empty/failed: ${query}`);
209
+ return;
210
+ }
211
+ const resultsText = res.results
212
+ .map((r, i) => `${i + 1}. ${r.title} \u2014 ${r.url}\n ${r.snippet}`)
213
+ .join("\n");
214
+ this.pendingMessages.push({
215
+ role: "user",
216
+ content: `<system-summary>${t("exec.error_search_results", {
217
+ sig,
218
+ count: String(count),
219
+ query,
220
+ results: resultsText,
221
+ })}</system-summary>`,
222
+ });
223
+ })
224
+ .catch((e) => ctx.logger?.warn(`error web search: ${e.message}`));
225
+ }
226
+ /**
227
+ * Final audit before the agent may declare the task done. Returns null when
228
+ * no plan is active; otherwise checks plan completion + artifact existence.
229
+ */
230
+ async runFinalAudit() {
231
+ // No active tracker: audit the last completed plan instead of bailing.
232
+ // A plan finished via `plan update` auto-archives and clears the tracker;
233
+ // without this the final audit (tests + tsc + file checks) was silently
234
+ // skipped and the model could declare success on broken artifacts.
235
+ if (!this.tracker) {
236
+ if (!this.completedPlan)
237
+ return null;
238
+ const plan = this.completedPlan;
239
+ const audit = await this.auditor.audit(plan);
240
+ const pendingSteps = plan.steps.flatMap((s) => s.status !== "done" && s.status !== "skipped" ? [`${s.id}. ${s.description}`] : []);
241
+ const done = plan.steps.filter((s) => s.status === "done").length;
242
+ return {
243
+ passed: audit.passed && pendingSteps.length === 0,
244
+ done,
245
+ total: plan.steps.length,
246
+ pendingSteps,
247
+ missingFiles: audit.missingFiles,
248
+ summary: audit.summary,
249
+ };
250
+ }
251
+ if (this._auditSkipsRemaining > 0) {
252
+ this._auditSkipsRemaining--;
253
+ return null;
254
+ }
255
+ const plan = this.tracker.getPlan();
256
+ const audit = await this.auditor.audit(plan);
257
+ const pendingSteps = plan.steps.flatMap((s) => s.status !== "done" && s.status !== "skipped" ? [`${s.id}. ${s.description}`] : []);
258
+ const done = plan.steps.filter((s) => s.status === "done").length;
259
+ const passed = audit.passed && pendingSteps.length === 0;
260
+ return {
261
+ passed,
262
+ done,
263
+ total: plan.steps.length,
264
+ pendingSteps,
265
+ missingFiles: audit.missingFiles,
266
+ summary: audit.summary,
267
+ };
268
+ }
269
+ getSystemPromptBlock() {
270
+ if (!this.tracker || this.tracker.isComplete())
271
+ return null;
272
+ return {
273
+ content: this.tracker.toPromptBlock(),
274
+ priority: "critical",
275
+ essential: true,
276
+ estimatedTokens: 200,
277
+ };
278
+ }
279
+ /**
280
+ * Short "current plan" line for the compaction summary. Null when no plan
281
+ * is active. For 9B models the explicit instruction "continue it, do NOT
282
+ * create a new plan" matters — after compaction the plan block is visible
283
+ * but the model re-creates the plan anyway (observed: ses_msvuao0h).
284
+ *
285
+ * When the plan is complete, the summary says the plan is done and the
286
+ * model may create a new plan — NOT "continue step 4, do NOT create a
287
+ * new plan" which anchored the ses_msxjbnm4 loop.
288
+ */
289
+ getPlanSummary() {
290
+ if (!this.tracker)
291
+ return null;
292
+ const plan = this.tracker.getPlan();
293
+ const done = plan.steps.filter((s) => s.status === "done").length;
294
+ const total = plan.steps.length;
295
+ if (this.tracker.isComplete()) {
296
+ return `[${plan.id}] "${plan.title}" ${done}/${total} done — plan complete. You may create a new plan for new work (plan create), or reply with your final answer.`;
297
+ }
298
+ const current = this.tracker.getCurrentStepIndex() + 1;
299
+ return `[${plan.id}] "${plan.title}" ${done}/${total} done, current: step ${current} — continue it (plan show / re-plan), do NOT create a new plan`;
300
+ }
301
+ getToolDefinitions() {
302
+ return createPlanToolDefinitions({
303
+ store: this.store,
304
+ verifier: this.verifier,
305
+ trackerRef: this.trackerRef,
306
+ preserveActive: () => this.preserveActive(),
307
+ setPlan: (p) => this.setPlan(p),
308
+ recordCompleted: (p) => this.recordCompleted(p),
309
+ clearCompleted: () => this.clearCompleted(),
310
+ hasStepDeliverables: (s) => this.hasStepDeliverables(s),
311
+ missingStepDeliverables: (s) => this.missingStepDeliverables(s),
312
+ stillExistingDeliverables: (s) => this.stillExistingDeliverables(s),
313
+ parseKinds: (a, st) => this.parseKinds(a, st),
314
+ getTaskText: (c) => this.getTaskText(c),
315
+ typecheckFailures: this.state.typecheckFailures,
316
+ baseDir: this.baseDir,
317
+ wasFileDeleted: this.hallucinationDetector
318
+ ? (path) => this.hallucinationDetector.getConsistencyCheck().getDeletedFiles().includes(path)
319
+ : undefined,
320
+ });
321
+ }
322
+ getPlugin() {
323
+ return createExecutionPlugin({
324
+ stuckDetector: this.stuckDetector,
325
+ trackerRef: this.trackerRef,
326
+ pendingMessages: this.pendingMessages,
327
+ forbiddenBashFailures: this.forbiddenBashFailures,
328
+ state: this.state,
329
+ store: this.store,
330
+ checkPlanAlignment: (call) => this.checkPlanAlignment(call),
331
+ advancePlanIfStepComplete: (cm, sl) => this.advancePlanIfStepComplete(cm, sl),
332
+ maybeSearchError: (ctx, call) => this.maybeSearchError(ctx, call),
333
+ });
334
+ }
335
+ preserveActive() {
336
+ if (!this.tracker)
337
+ return;
338
+ const plan = this.tracker.getPlan();
339
+ if (plan.steps.every((s) => s.status === "done" || s.status === "skipped")) {
340
+ this.store.archivePlan(plan);
341
+ }
342
+ else {
343
+ this.store.saveDraft(plan);
344
+ }
345
+ }
346
+ checkPlanAlignment(call) {
347
+ if (!this.tracker)
348
+ return null;
349
+ const step = this.tracker.getCurrentStep();
350
+ if (!step)
351
+ return null;
352
+ const allowedAlways = [
353
+ "plan",
354
+ "todo",
355
+ "verify",
356
+ "list_dir",
357
+ "read_file",
358
+ "glob",
359
+ "grep",
360
+ "file_info",
361
+ "load_skill",
362
+ ];
363
+ if (allowedAlways.includes(call.name))
364
+ return null;
365
+ const stepPaths = extractFileLikeTokens(stripUrls(step.description)).map((p) => p.toLowerCase());
366
+ if (stepPaths.length === 0)
367
+ return null;
368
+ // Only path-ish arguments are inspected. JSON-stringifying the whole args
369
+ // blob made write_file/edit_file `content` feed its code tokens into the
370
+ // off-path check (e.g. `import "./styles.css"` inside the file body) and
371
+ // raised phantom alignment warnings for on-track writes.
372
+ const argStr = this.pathArgStrings(call.arguments).join(" ");
373
+ const callPaths = extractFileLikeTokens(stripUrls(argStr)).map((p) => p.toLowerCase());
374
+ if (callPaths.length === 0)
375
+ return null;
376
+ // Files that already belong to COMPLETED (done/skipped) steps are
377
+ // legitimate rewrite targets — the agent iterates on them while fixing
378
+ // LSP/type errors. Blocking those would stop normal bug-fixing.
379
+ const plan = this.tracker.getPlan();
380
+ const finishedPaths = new Set();
381
+ for (const s of plan.steps) {
382
+ if (s.status === "done" || s.status === "skipped") {
383
+ extractFileLikeTokens(stripUrls(s.description))
384
+ .map((p) => p.toLowerCase())
385
+ .forEach((p) => finishedPaths.add(p));
386
+ }
387
+ }
388
+ const offPath = callPaths.some((p) => {
389
+ if (finishedPaths.has(p) || [...finishedPaths].some((s) => s.includes(p))) {
390
+ return false;
391
+ }
392
+ return !stepPaths.some((s) => p.includes(s) || s.includes(p));
393
+ });
394
+ if (!offPath)
395
+ return null;
396
+ return t("exec.plan_warning", {
397
+ step: String(step.id),
398
+ description: step.description,
399
+ tool: call.name,
400
+ });
401
+ }
402
+ /** String values of the path-like arguments of a tool call. Limits the
403
+ * off-path alignment check to arguments that actually name files (path,
404
+ * file, dir, src, dst, source, target, input, output, destination, glob,
405
+ * workdir, cwd, command, pattern) and never scans payload content. */
406
+ pathArgStrings(args) {
407
+ if (!args)
408
+ return [];
409
+ const out = [];
410
+ for (const [key, value] of Object.entries(args)) {
411
+ if (!/path|file|dir|src|dst|source|target|input|output|destination|glob|workdir|cwd|command|pattern|query/i.test(key)) {
412
+ continue;
413
+ }
414
+ if (typeof value === "string")
415
+ out.push(value);
416
+ else if (Array.isArray(value)) {
417
+ for (const v of value)
418
+ if (typeof v === "string")
419
+ out.push(v);
420
+ }
421
+ }
422
+ return out;
423
+ }
424
+ advancePlanIfStepComplete(contextManager, sessionLog) {
425
+ const step = this.tracker?.getCurrentStep();
426
+ if (!step)
427
+ return;
428
+ const stepText = step.description.toLowerCase();
429
+ // Shared file-token filter (allow-list of real extensions, extension-only
430
+ // segments rejected). A step like "Удалить .js, оставить .tsx/.ts" must
431
+ // NOT produce the phantom token "tsx/.ts" — that never exists, making
432
+ // allGone trivially true and auto-advancing a delete step while the real
433
+ // files to delete still exist (the raw regex path did exactly that).
434
+ const stepPaths = extractFileLikeTokens(stripUrls(step.description)) || [];
435
+ // Step gate: verify dependencies when mentioned — check BEFORE file paths.
436
+ // Requires an actual package-manager verb (rule #10 — no bare keyword
437
+ // matching: "init" alone or "setup project" must NOT trigger the lockfile
438
+ // hint, only concrete dependency-install commands do).
439
+ const isDepsStep = /(?:npm|bun|yarn|pnpm|pip|pip3|pipenv|poetry|composer|deno|go|gem|cargo)\s+(?:install|add|init|i|get)\b|bun\s+(?:add|install)|npm\s+(?:i|install|add)|(?:install|установ\w*)\s+(?:dependencies|зависимост\w*|пакет\w*|packages?)/i.test(stepText);
440
+ if (isDepsStep) {
441
+ const lockFiles = [
442
+ "package-lock.json",
443
+ "bun.lockb",
444
+ "yarn.lock",
445
+ "pnpm-lock.yaml",
446
+ "node_modules",
447
+ "go.sum",
448
+ "Cargo.lock",
449
+ "Pipfile.lock",
450
+ "poetry.lock",
451
+ "requirements.txt",
452
+ ];
453
+ const hasLockFile = lockFiles.some((f) => existsSync(resolve(this.baseDir, f)));
454
+ if (!hasLockFile) {
455
+ if (contextManager) {
456
+ const hints = this.state.depsGateHints.get(step.id) || 0;
457
+ this.state.depsGateHints.set(step.id, hints + 1);
458
+ const force = hints >= 1;
459
+ const content = force
460
+ ? t("exec.step_gate_deps_force", { step: String(step.id) })
461
+ : t("exec.step_gate_deps", {
462
+ step: String(step.id),
463
+ description: step.description,
464
+ });
465
+ contextManager.addMessage({
466
+ role: "user",
467
+ content: `<system-summary>${content}</system-summary>`,
468
+ });
469
+ }
470
+ return;
471
+ }
472
+ }
473
+ if (stepPaths.length === 0)
474
+ return;
475
+ // Resolve tokens with the SAME subtree walk the deliverable gate and the
476
+ // auditor use (findExistingFile), so a nested file
477
+ // ("bicycle-shop/src/bicycles.ts" for token "src/bicycles.ts") counts as
478
+ // present. The old exact existsSync(resolve()) never matched nested
479
+ // projects, so auto-advance stayed silent even after the model wrote the
480
+ // real file.
481
+ const resolved = stepPaths.map((p) => findExistingFile(this.baseDir, p));
482
+ const allExist = resolved.every((r) => r !== null);
483
+ const allGone = resolved.every((r) => r === null);
484
+ const satisfied = step.kind === "delete" ? allGone && !allExist : allExist;
485
+ if (!satisfied)
486
+ return;
487
+ // Step gate: verify files have content (not empty)
488
+ if (step.kind !== "delete") {
489
+ const emptyFiles = [];
490
+ for (const r of resolved) {
491
+ if (!r)
492
+ continue;
493
+ try {
494
+ const content = readFileSync(r, "utf-8");
495
+ if (content.trim().length < 10) {
496
+ emptyFiles.push(r);
497
+ }
498
+ }
499
+ catch {
500
+ // If we can't read it, rely on the existence result
501
+ }
502
+ }
503
+ if (emptyFiles.length > 0 && contextManager) {
504
+ contextManager.addMessage({
505
+ role: "user",
506
+ content: `<system-summary>${t("exec.step_gate_empty", { step: String(step.id), files: emptyFiles.join(", ") })}</system-summary>`,
507
+ });
508
+ return;
509
+ }
510
+ }
511
+ // All checks passed — advance
512
+ this.tracker?.updateStepStatus(step.id, "done");
513
+ const hadNext = this.tracker?.advance() ?? false;
514
+ if (this.tracker) {
515
+ this.store.saveActive(this.tracker.getPlan());
516
+ sessionLog?.plan("auto-advance", `Step ${step.id} auto-completed | ${this.tracker.getProgressString()} | current: step ${this.tracker.getCurrentStepIndex() + 1}`);
517
+ }
518
+ if (contextManager) {
519
+ const nextStep = hadNext ? this.tracker?.getCurrentStep() : null;
520
+ const nextMsg = nextStep
521
+ ? t("exec.step_gate_ok", {
522
+ step: String(step.id),
523
+ nextStep: String(nextStep.id),
524
+ nextDesc: nextStep.description,
525
+ })
526
+ : t("exec.step_gate_last", { step: String(step.id) });
527
+ contextManager.addMessage({
528
+ role: "user",
529
+ content: `<system-summary>${nextMsg}</system-summary>`,
530
+ });
531
+ }
532
+ // Auto-archive a plan that just became complete (all steps done/skipped).
533
+ // Keeps a finished plan from staying active forever and anchoring the agent
534
+ // to a completed task ("continue step 4, do NOT create a new plan" — the
535
+ // ses_msxjbnm4 loop). The per-step deliverable gate already verified files.
536
+ if (this.tracker?.isComplete()) {
537
+ const completed = this.tracker.getPlan();
538
+ this.store.archivePlan(completed);
539
+ this.recordCompleted(completed); // final audit still verifies it
540
+ this.tracker = null;
541
+ sessionLog?.plan("auto-archive", `Plan ${completed.id} complete — archived`);
542
+ }
543
+ }
544
+ /**
545
+ * File tokens named in a step description that do not resolve to a real
546
+ * file. Uses the same shared token extractor (allow-list of real file
547
+ * extensions, URLs stripped) and the auditor's subtree resolver, so
548
+ * "bicycles.ts" finds "bicycle-shop/src/data/bicycles.ts" and a hostname in
549
+ * the description is never reported as a missing deliverable. Steps with no
550
+ * file tokens (pure commands, verification runs) cannot be verified.
551
+ */
552
+ missingStepDeliverables(step) {
553
+ const tokens = extractFileLikeTokens(stripUrls(step.description));
554
+ if (tokens.length === 0)
555
+ return [];
556
+ return tokens.filter((p) => !findExistingFile(this.baseDir, p));
557
+ }
558
+ /**
559
+ * File tokens named in a step description that still resolve to a real
560
+ * file. The inverse of missingStepDeliverables — used by the gate for
561
+ * delete-kind steps ("done" means the files are gone).
562
+ */
563
+ stillExistingDeliverables(step) {
564
+ const tokens = extractFileLikeTokens(stripUrls(step.description));
565
+ if (tokens.length === 0)
566
+ return [];
567
+ return tokens.filter((p) => findExistingFile(this.baseDir, p));
568
+ }
569
+ /** Whether a step description names at least one real file token. Steps
570
+ * with no file tokens (pure commands, verification runs) cannot be
571
+ * auto-verified — the done-gate is vacuous for them. */
572
+ hasStepDeliverables(step) {
573
+ return extractFileLikeTokens(stripUrls(step.description)).length > 0;
574
+ }
575
+ /**
576
+ * Validate the optional per-step `kinds` argument for plan create and
577
+ * update-with-steps. Returns length-aligned kinds or an i18n error string.
578
+ * Absent kinds → null (caller falls back to all-create semantics). Used by
579
+ * BOTH branches so a rebuild via update can never silently drop kinds.
580
+ */
581
+ parseKinds(args, steps) {
582
+ if (args.kinds === undefined)
583
+ return { kinds: null, error: null };
584
+ if (!Array.isArray(args.kinds)) {
585
+ return { kinds: null, error: t("plan.kinds_not_array") };
586
+ }
587
+ const kindsRaw = args.kinds.map(String);
588
+ if (kindsRaw.length !== steps.length) {
589
+ return { kinds: null, error: t("plan.kinds_mismatch") };
590
+ }
591
+ const invalid = kindsRaw.filter((k) => k !== "create" && k !== "delete");
592
+ if (invalid.length > 0) {
593
+ return {
594
+ kinds: null,
595
+ error: t("plan.kinds_invalid", {
596
+ kinds: invalid.join(", "),
597
+ }),
598
+ };
599
+ }
600
+ return { kinds: kindsRaw, error: null };
601
+ }
602
+ /**
603
+ * Extract the original task statement from the first user message in the
604
+ * conversation history. Used to validate plan coverage against requirements.
605
+ */
606
+ getTaskText(ctx) {
607
+ const manager = ctx?.contextManager;
608
+ if (!manager)
609
+ return "";
610
+ const history = manager.getActiveHistory();
611
+ // The first user message may be an injected <system-summary> (compaction
612
+ // block) — it is NOT the task. Coverage must compare the plan against the
613
+ // model's real instruction (observed: a compaction summary's stale file
614
+ // list produced a bogus "plan is missing files" warning).
615
+ const firstUser = history.find((m) => {
616
+ if (m.role !== "user")
617
+ return false;
618
+ const text = getMessageText(m.content);
619
+ return !text.startsWith("<system-summary>") && !text.includes("[Compressed:");
620
+ });
621
+ if (!firstUser)
622
+ return "";
623
+ return getMessageText(firstUser.content).trim();
624
+ }
625
+ }