micro-models-agent 0.44.0 → 0.45.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 (188) hide show
  1. package/README.md +312 -312
  2. package/bin/mma.mjs +41 -41
  3. package/dist/main.js +241 -56
  4. package/dist/skills/builtin/git.md +36 -36
  5. package/dist/skills/builtin/typescript.md +35 -35
  6. package/package.json +1 -1
  7. package/dist/cli/commands.js +0 -333
  8. package/dist/cli/completer.js +0 -168
  9. package/dist/cli/index.js +0 -2
  10. package/dist/cli/main.js +0 -140
  11. package/dist/cli/repl-commands.js +0 -633
  12. package/dist/cli/repl.js +0 -486
  13. package/dist/cli/security-commands.js +0 -166
  14. package/dist/cli/setup.js +0 -249
  15. package/dist/config/config.js +0 -202
  16. package/dist/config/defaults.js +0 -100
  17. package/dist/config/experts.js +0 -15
  18. package/dist/config/index.js +0 -3
  19. package/dist/config/security.js +0 -200
  20. package/dist/config/types.js +0 -1
  21. package/dist/core/agent-moe.js +0 -110
  22. package/dist/core/agent.js +0 -695
  23. package/dist/core/bootstrap.js +0 -337
  24. package/dist/core/index.js +0 -2
  25. package/dist/core/prompt-builder.js +0 -55
  26. package/dist/core/session-logger.js +0 -155
  27. package/dist/core/types.js +0 -1
  28. package/dist/core/workspace.js +0 -76
  29. package/dist/i18n/en.json +0 -525
  30. package/dist/i18n/index.js +0 -46
  31. package/dist/i18n/ru.json +0 -525
  32. package/dist/index.js +0 -22
  33. package/dist/llm/image-utils.js +0 -144
  34. package/dist/llm/index.js +0 -4
  35. package/dist/llm/model-loader.js +0 -78
  36. package/dist/llm/openai-compat.js +0 -353
  37. package/dist/llm/orchestrator.js +0 -194
  38. package/dist/llm/provider.js +0 -10
  39. package/dist/llm/response.js +0 -39
  40. package/dist/llm/token-counter.js +0 -39
  41. package/dist/llm/types.js +0 -1
  42. package/dist/logger/app-logger.js +0 -143
  43. package/dist/logger/file-log.js +0 -151
  44. package/dist/logger/index.js +0 -1
  45. package/dist/migration/backup.js +0 -45
  46. package/dist/migration/detect.js +0 -50
  47. package/dist/migration/index.js +0 -2
  48. package/dist/modules/browser/actions.js +0 -46
  49. package/dist/modules/browser/cookie-store.js +0 -24
  50. package/dist/modules/browser/index.js +0 -5
  51. package/dist/modules/browser/module.js +0 -28
  52. package/dist/modules/browser/session.js +0 -335
  53. package/dist/modules/browser/snapshot.js +0 -114
  54. package/dist/modules/browser/types.js +0 -9
  55. package/dist/modules/certification/cli.js +0 -176
  56. package/dist/modules/certification/fact-checker.js +0 -84
  57. package/dist/modules/certification/loader.js +0 -111
  58. package/dist/modules/certification/manifest.js +0 -50
  59. package/dist/modules/certification/runner.js +0 -162
  60. package/dist/modules/certification/scenarios.js +0 -124
  61. package/dist/modules/certification/types.js +0 -1
  62. package/dist/modules/context/index.js +0 -1
  63. package/dist/modules/context/manager.js +0 -349
  64. package/dist/modules/execution/auditor.js +0 -66
  65. package/dist/modules/execution/index.js +0 -8
  66. package/dist/modules/execution/module.js +0 -779
  67. package/dist/modules/execution/moe-executor.js +0 -266
  68. package/dist/modules/execution/plan-coverage.js +0 -68
  69. package/dist/modules/execution/plan-persister.js +0 -46
  70. package/dist/modules/execution/plan-store.js +0 -159
  71. package/dist/modules/execution/plan-validator.js +0 -153
  72. package/dist/modules/execution/planner.js +0 -85
  73. package/dist/modules/execution/stuck-detector.js +0 -347
  74. package/dist/modules/execution/tracker.js +0 -67
  75. package/dist/modules/execution/types.js +0 -1
  76. package/dist/modules/execution/verifier.js +0 -178
  77. package/dist/modules/hallucination/confidence.js +0 -59
  78. package/dist/modules/hallucination/consistency.js +0 -26
  79. package/dist/modules/hallucination/detector.js +0 -46
  80. package/dist/modules/hallucination/factual.js +0 -190
  81. package/dist/modules/hallucination/index.js +0 -5
  82. package/dist/modules/hallucination/js-identifiers.js +0 -72
  83. package/dist/modules/hallucination/llm-judge.js +0 -103
  84. package/dist/modules/index.js +0 -5
  85. package/dist/modules/indexer/cache.js +0 -38
  86. package/dist/modules/indexer/index.js +0 -3
  87. package/dist/modules/indexer/module.js +0 -192
  88. package/dist/modules/indexer/walker.js +0 -101
  89. package/dist/modules/lsp/client.js +0 -235
  90. package/dist/modules/lsp/config.js +0 -81
  91. package/dist/modules/lsp/index.js +0 -3
  92. package/dist/modules/lsp/module.js +0 -68
  93. package/dist/modules/lsp/types.js +0 -1
  94. package/dist/modules/mcp/client.js +0 -399
  95. package/dist/modules/mcp/index.js +0 -3
  96. package/dist/modules/mcp/module.js +0 -146
  97. package/dist/modules/mcp/registry.js +0 -15
  98. package/dist/modules/memory/index.js +0 -1
  99. package/dist/modules/memory/module.js +0 -48
  100. package/dist/modules/memory/search.js +0 -40
  101. package/dist/modules/memory/store.js +0 -69
  102. package/dist/modules/pipelines/engine.js +0 -60
  103. package/dist/modules/pipelines/index.js +0 -3
  104. package/dist/modules/pipelines/parser.js +0 -53
  105. package/dist/modules/pipelines/template.js +0 -14
  106. package/dist/modules/plugins/builtin/lint-on-write.js +0 -226
  107. package/dist/modules/plugins/builtin/notify.js +0 -8
  108. package/dist/modules/plugins/index.js +0 -1
  109. package/dist/modules/plugins/loader.js +0 -28
  110. package/dist/modules/plugins/manager.js +0 -161
  111. package/dist/modules/plugins/types.js +0 -1
  112. package/dist/modules/processes/index.js +0 -2
  113. package/dist/modules/processes/registry.js +0 -238
  114. package/dist/modules/processes/runner.js +0 -23
  115. package/dist/modules/registry.js +0 -45
  116. package/dist/modules/security/audit-log.js +0 -136
  117. package/dist/modules/security/audit-notifier.js +0 -292
  118. package/dist/modules/security/command-validator.js +0 -211
  119. package/dist/modules/security/content-scanner.js +0 -53
  120. package/dist/modules/security/data-sanitizer.js +0 -97
  121. package/dist/modules/security/encryption.js +0 -240
  122. package/dist/modules/security/index.js +0 -14
  123. package/dist/modules/security/network-validator.js +0 -79
  124. package/dist/modules/security/path-validator.js +0 -209
  125. package/dist/modules/security/rate-limiter.js +0 -119
  126. package/dist/modules/security/security-policies.js +0 -547
  127. package/dist/modules/security/session-encryption.js +0 -210
  128. package/dist/modules/security/session-isolation.js +0 -95
  129. package/dist/modules/session/index.js +0 -3
  130. package/dist/modules/session/manager.js +0 -172
  131. package/dist/modules/session/module.js +0 -24
  132. package/dist/modules/session/store.js +0 -228
  133. package/dist/modules/session/types.js +0 -1
  134. package/dist/modules/skills/index.js +0 -2
  135. package/dist/modules/skills/loader.js +0 -72
  136. package/dist/modules/skills/module.js +0 -130
  137. package/dist/modules/types.js +0 -1
  138. package/dist/modules/updater/checker.js +0 -32
  139. package/dist/modules/updater/index.js +0 -1
  140. package/dist/modules/user-profile/compressor.js +0 -16
  141. package/dist/modules/user-profile/index.js +0 -1
  142. package/dist/modules/user-profile/profile.js +0 -68
  143. package/dist/tools/approve.js +0 -32
  144. package/dist/tools/attach-image.js +0 -89
  145. package/dist/tools/bash.js +0 -337
  146. package/dist/tools/browser.js +0 -97
  147. package/dist/tools/create-dir.js +0 -55
  148. package/dist/tools/delete-file.js +0 -62
  149. package/dist/tools/edit-file.js +0 -79
  150. package/dist/tools/executor.js +0 -145
  151. package/dist/tools/file-info.js +0 -45
  152. package/dist/tools/filter-tools.js +0 -10
  153. package/dist/tools/glob-tool.js +0 -26
  154. package/dist/tools/grep-tool.js +0 -86
  155. package/dist/tools/index.js +0 -67
  156. package/dist/tools/list-dir.js +0 -47
  157. package/dist/tools/load-skill.js +0 -44
  158. package/dist/tools/mcp-call.js +0 -68
  159. package/dist/tools/move-file.js +0 -85
  160. package/dist/tools/path-utils.js +0 -51
  161. package/dist/tools/pipeline-run.js +0 -144
  162. package/dist/tools/preview.js +0 -2
  163. package/dist/tools/process-kill.js +0 -29
  164. package/dist/tools/process-list.js +0 -38
  165. package/dist/tools/process-log.js +0 -41
  166. package/dist/tools/question.js +0 -142
  167. package/dist/tools/read-file.js +0 -83
  168. package/dist/tools/recall.js +0 -110
  169. package/dist/tools/registry.js +0 -36
  170. package/dist/tools/remember.js +0 -67
  171. package/dist/tools/scope-check.js +0 -30
  172. package/dist/tools/search-history.js +0 -84
  173. package/dist/tools/subagent.js +0 -151
  174. package/dist/tools/types.js +0 -1
  175. package/dist/tools/user-input.js +0 -123
  176. package/dist/tools/web-browse.js +0 -86
  177. package/dist/tools/web-fetch.js +0 -98
  178. package/dist/tools/web-search.js +0 -78
  179. package/dist/tools/write-file.js +0 -83
  180. package/dist/ui/box.js +0 -81
  181. package/dist/ui/colors.js +0 -4
  182. package/dist/ui/diff.js +0 -178
  183. package/dist/ui/index.js +0 -6
  184. package/dist/ui/md-formatter.js +0 -212
  185. package/dist/ui/output.js +0 -13
  186. package/dist/ui/renderer.js +0 -204
  187. package/dist/ui/spinner.js +0 -70
  188. package/dist/ui/table.js +0 -144
@@ -1,266 +0,0 @@
1
- import { getExpertConfig } from "../../config/experts";
2
- import { filterToolsByTags } from "../../tools/filter-tools";
3
- import { StuckDetector } from "./stuck-detector";
4
- import { t } from "../../i18n/index";
5
- const TRANSIENT_ERROR_PATTERNS = [
6
- "timeout",
7
- "Timeout",
8
- "TIMEOUT",
9
- "5xx",
10
- "500",
11
- "502",
12
- "503",
13
- "network",
14
- "Network",
15
- "ECONNREFUSED",
16
- "ECONNRESET",
17
- "fetch failed",
18
- "abort",
19
- "Abort",
20
- ];
21
- function isTransientError(error) {
22
- return TRANSIENT_ERROR_PATTERNS.some((p) => error.includes(p));
23
- }
24
- function sleep(ms) {
25
- return new Promise((r) => setTimeout(r, ms));
26
- }
27
- export function topologicalSort(subtasks) {
28
- const sorted = [];
29
- const remaining = new Set(subtasks.map((s) => s.id));
30
- const subtaskMap = new Map(subtasks.map((s) => [s.id, s]));
31
- while (remaining.size > 0) {
32
- const ready = [];
33
- for (const id of remaining) {
34
- const sub = subtaskMap.get(id);
35
- const depsSatisfied = (sub.depends_on || []).every((d) => !remaining.has(d));
36
- if (depsSatisfied) {
37
- ready.push(sub);
38
- }
39
- }
40
- if (ready.length === 0) {
41
- break;
42
- }
43
- sorted.push(ready);
44
- for (const r of ready) {
45
- remaining.delete(r.id);
46
- }
47
- }
48
- return sorted;
49
- }
50
- async function executeSubtask(subtask, deps, _sharedContext) {
51
- const startTime = Date.now();
52
- const expertConfig = getExpertConfig(deps.config, subtask.expert_tag);
53
- if (!expertConfig) {
54
- return {
55
- subtaskId: subtask.id,
56
- success: false,
57
- summary: `Unknown expert_tag: ${subtask.expert_tag}`,
58
- result: "",
59
- error: `No expert config found for tag "${subtask.expert_tag}"`,
60
- durationMs: Date.now() - startTime,
61
- };
62
- }
63
- const subagentTool = deps.toolRegistry.get("subagent");
64
- if (!subagentTool) {
65
- return {
66
- subtaskId: subtask.id,
67
- success: false,
68
- summary: "Subagent tool not registered",
69
- result: "",
70
- error: "Subagent tool not found in registry",
71
- durationMs: Date.now() - startTime,
72
- };
73
- }
74
- const allTools = deps.toolRegistry.getAll();
75
- const filteredTools = filterToolsByTags(allTools, expertConfig.tool_tags);
76
- if (filteredTools.length === 0) {
77
- return {
78
- subtaskId: subtask.id,
79
- success: false,
80
- summary: `No tools available for expert "${subtask.expert_tag}" (tags: ${expertConfig.tool_tags.join(", ")})`,
81
- result: "",
82
- error: "No matching tools",
83
- durationMs: Date.now() - startTime,
84
- };
85
- }
86
- const maxAttempts = expertConfig.max_attempts || 3;
87
- let lastError = "";
88
- let lastResult = null;
89
- const stuckDetector = new StuckDetector(maxAttempts * 2, maxAttempts);
90
- for (let attempt = 1; attempt <= maxAttempts; attempt++) {
91
- stuckDetector.recordIteration(1);
92
- try {
93
- const allowedFiles = subtask.allowed_files || [];
94
- const readOnlyFiles = subtask.read_only_files || [];
95
- const scopePrompt = allowedFiles.length > 0 || readOnlyFiles.length > 0
96
- ? `\n\nAllowed files to write: ${allowedFiles.join(", ") || "(none)"}\nRead-only files: ${readOnlyFiles.join(", ") || "(none)"}`
97
- : "";
98
- const taskPrompt = `${subtask.description}\n\nExpected output: ${subtask.expected_output}\nSuccess criteria:\n${(subtask.success_criteria || []).map((c) => `- ${c}`).join("\n")}${scopePrompt}`;
99
- const subagentArgs = {
100
- task: taskPrompt,
101
- allowed_files: allowedFiles,
102
- read_only_files: readOnlyFiles,
103
- tool_tags: expertConfig.tool_tags,
104
- };
105
- const result = await subagentTool.handler({
106
- config: deps.config,
107
- baseDir: deps.baseDir,
108
- logger: deps.logger,
109
- llmProvider: deps.llmProvider,
110
- toolExecutor: deps.toolExecutor,
111
- }, subagentArgs);
112
- if (result.success) {
113
- return {
114
- subtaskId: subtask.id,
115
- success: true,
116
- summary: `Completed: ${subtask.id}`,
117
- result: result.output,
118
- durationMs: Date.now() - startTime,
119
- };
120
- }
121
- lastError = result.output;
122
- lastResult = result;
123
- stuckDetector.recordToolError("subagent", result.output);
124
- // Inject actionable hints into the next retry's prompt
125
- if (attempt < maxAttempts) {
126
- const hints = stuckDetector.getActionableHints();
127
- const recovery = stuckDetector.getRecoveryMessage();
128
- if (hints.length > 0) {
129
- deps.logger.debug(`Hint for subtask "${subtask.id}" retry: ${hints.join("; ")}`);
130
- }
131
- if (recovery) {
132
- deps.logger.debug(`Recovery for subtask "${subtask.id}": ${recovery}`);
133
- }
134
- }
135
- if (isTransientError(lastError) && attempt < maxAttempts) {
136
- const delay = Math.min(1000 * Math.pow(2, attempt - 1), 8000);
137
- deps.logger.debug(`Retrying subtask "${subtask.id}" (attempt ${attempt}/${maxAttempts}) after ${delay}ms: transient error`);
138
- await sleep(delay);
139
- continue;
140
- }
141
- // Non-transient failure — build detailed error with hints
142
- const hints = stuckDetector.getActionableHints();
143
- let errorDetail = result.output;
144
- if (hints.length > 0) {
145
- errorDetail += `\n\n${t("exec.hints", { hints: hints.map((h) => `- ${h}`).join("\n") })}`;
146
- }
147
- if (lastError) {
148
- errorDetail +=
149
- "\n\nIf relevant skills are available, consider loading one with load_skill for expert guidance.";
150
- }
151
- return {
152
- subtaskId: subtask.id,
153
- success: false,
154
- summary: `Failed: ${subtask.id}`,
155
- result: result.output,
156
- error: errorDetail,
157
- durationMs: Date.now() - startTime,
158
- };
159
- }
160
- catch (e) {
161
- lastError = e.message;
162
- stuckDetector.recordToolError("subagent", e.message);
163
- if (isTransientError(lastError) && attempt < maxAttempts) {
164
- const delay = Math.min(1000 * Math.pow(2, attempt - 1), 8000);
165
- deps.logger.debug(`Retrying subtask "${subtask.id}" (attempt ${attempt}/${maxAttempts}) after ${delay}ms: ${lastError}`);
166
- await sleep(delay);
167
- continue;
168
- }
169
- const hints = stuckDetector.getActionableHints();
170
- let errorDetail = e.message;
171
- if (hints.length > 0) {
172
- errorDetail += `\n\n${t("exec.hints", { hints: hints.map((h) => `- ${h}`).join("\n") })}`;
173
- }
174
- if (lastError) {
175
- errorDetail +=
176
- "\n\nIf relevant skills are available, consider loading one with load_skill for expert guidance.";
177
- }
178
- return {
179
- subtaskId: subtask.id,
180
- success: false,
181
- summary: `Error: ${subtask.id}`,
182
- result: "",
183
- error: errorDetail,
184
- durationMs: Date.now() - startTime,
185
- };
186
- }
187
- }
188
- // Exhausted retries — build detailed failure
189
- const stuckReason = stuckDetector.getStuckReason();
190
- let finalError = lastError;
191
- if (stuckReason) {
192
- finalError += `\n${stuckReason}`;
193
- }
194
- return {
195
- subtaskId: subtask.id,
196
- success: false,
197
- summary: `Failed after ${maxAttempts} attempts: ${subtask.id}`,
198
- result: "",
199
- error: finalError,
200
- durationMs: Date.now() - startTime,
201
- };
202
- }
203
- export class MoEExecutor {
204
- deps;
205
- constructor(deps) {
206
- this.deps = deps;
207
- }
208
- async executePlan(plan) {
209
- const results = [];
210
- const errors = [];
211
- const warnings = [];
212
- const waves = topologicalSort(plan.subtasks);
213
- if (waves.length === 0) {
214
- return {
215
- success: false,
216
- results: [],
217
- errors: ["Failed to topologically sort subtasks (possible cycle)"],
218
- warnings: [],
219
- };
220
- }
221
- // Verify all subtasks are included — catch silent drops from unresolved dependencies
222
- const sortedCount = waves.flat().length;
223
- if (sortedCount < plan.subtasks.length) {
224
- const missing = plan.subtasks
225
- .filter((s) => !waves.flat().some((w) => w.id === s.id))
226
- .map((s) => s.id);
227
- return {
228
- success: false,
229
- results: [],
230
- errors: [
231
- `Missing subtasks after topological sort: ${missing.join(", ")} (dangling or invalid depends_on)`,
232
- ],
233
- warnings: [],
234
- };
235
- }
236
- for (let waveIdx = 0; waveIdx < waves.length; waveIdx++) {
237
- const wave = waves[waveIdx];
238
- const wavePromises = wave.map((subtask) => executeSubtask(subtask, this.deps, plan.shared_context)
239
- .then((result) => {
240
- results.push(result);
241
- return result;
242
- })
243
- .catch((e) => {
244
- const errResult = {
245
- subtaskId: subtask.id,
246
- success: false,
247
- summary: `Unhandled error: ${subtask.id}`,
248
- result: "",
249
- error: e.message,
250
- durationMs: 0,
251
- };
252
- results.push(errResult);
253
- return errResult;
254
- }));
255
- await Promise.all(wavePromises);
256
- }
257
- const failed = results.filter((r) => !r.success);
258
- if (failed.length > 0) {
259
- errors.push(...failed.map((f) => `[${f.subtaskId}] ${f.error || f.summary}`));
260
- }
261
- return { success: failed.length === 0, results, errors, warnings };
262
- }
263
- getChainMaxAttempts() {
264
- return 3;
265
- }
266
- }
@@ -1,68 +0,0 @@
1
- const FILE_PATH_RE = /\b[\w./\\-]+\.[a-z]+\b/gi;
2
- const IGNORED_EXT = new Set([
3
- "tsx",
4
- "jsx",
5
- "json5",
6
- "mdx",
7
- "yml",
8
- "yaml",
9
- "toml",
10
- "lock",
11
- "svg",
12
- "png",
13
- "jpg",
14
- "jpeg",
15
- "gif",
16
- "webp",
17
- "ico",
18
- "css",
19
- "scss",
20
- "less",
21
- "html",
22
- ]);
23
- /**
24
- * Extract file paths (with extensions) mentioned in a task statement.
25
- * Used to check whether a generated plan covers every file the task requires.
26
- */
27
- export function extractFilePaths(text) {
28
- if (!text)
29
- return [];
30
- const seen = new Set();
31
- const result = [];
32
- for (const m of text.matchAll(FILE_PATH_RE)) {
33
- let p = m[0];
34
- // Trim trailing punctuation that regex greedily keeps (e.g. "test.ts.")
35
- p = p.replace(/[.,;:)\]>]+$/g, "");
36
- const ext = p.split(".").pop()?.toLowerCase() ?? "";
37
- if (!p || IGNORED_EXT.has(ext))
38
- continue;
39
- const key = p.toLowerCase();
40
- if (seen.has(key))
41
- continue;
42
- seen.add(key);
43
- result.push(p);
44
- }
45
- return result;
46
- }
47
- function basename(p) {
48
- const parts = p.split(/[/\\]/);
49
- return parts[parts.length - 1] ?? p;
50
- }
51
- /**
52
- * Compare the file requirements in the task statement against the plan's step
53
- * descriptions. A requirement is "covered" when its path (or its basename)
54
- * appears in at least one step. Returns the missing paths.
55
- */
56
- export function checkPlanCoverage(taskText, stepDescriptions) {
57
- const taskPaths = extractFilePaths(taskText);
58
- if (taskPaths.length === 0)
59
- return { missing: [] };
60
- const stepText = stepDescriptions.map((s) => s.toLowerCase()).join("\n");
61
- const missing = taskPaths.filter((p) => {
62
- const lower = p.toLowerCase();
63
- const base = basename(lower);
64
- // A step mentioning either the full relative path or its basename counts.
65
- return !stepText.includes(lower) && !stepText.includes(base);
66
- });
67
- return { missing };
68
- }
@@ -1,46 +0,0 @@
1
- import { readFileSync, writeFileSync, mkdirSync, existsSync } from "fs";
2
- import { join } from "path";
3
- export class PlanPersister {
4
- filePath;
5
- constructor(baseDir) {
6
- const mmaDir = join(baseDir, ".mma");
7
- if (!existsSync(mmaDir)) {
8
- mkdirSync(mmaDir, { recursive: true });
9
- }
10
- this.filePath = join(mmaDir, "plan.json");
11
- }
12
- save(plan) {
13
- const file = {
14
- id: plan.id,
15
- title: plan.title,
16
- steps: plan.steps,
17
- createdAt: plan.createdAt,
18
- updatedAt: new Date().toISOString(),
19
- baseDir: plan.baseDir,
20
- };
21
- writeFileSync(this.filePath, JSON.stringify(file, null, 2), "utf-8");
22
- }
23
- load() {
24
- if (!existsSync(this.filePath))
25
- return null;
26
- try {
27
- const raw = readFileSync(this.filePath, "utf-8");
28
- const file = JSON.parse(raw);
29
- return {
30
- id: file.id || "plan_legacy",
31
- title: file.title,
32
- steps: file.steps,
33
- createdAt: file.createdAt,
34
- baseDir: file.baseDir || process.cwd(),
35
- };
36
- }
37
- catch {
38
- return null;
39
- }
40
- }
41
- clear() {
42
- if (existsSync(this.filePath)) {
43
- writeFileSync(this.filePath, "", "utf-8");
44
- }
45
- }
46
- }
@@ -1,159 +0,0 @@
1
- import { readFileSync, writeFileSync, mkdirSync, existsSync, readdirSync, rmSync } from "fs";
2
- import { join } from "path";
3
- const LEGACY_FILE = "plan.json";
4
- function readPlanFile(path, fallbackBaseDir) {
5
- try {
6
- const raw = readFileSync(path, "utf-8");
7
- if (!raw.trim())
8
- return null;
9
- const parsed = JSON.parse(raw);
10
- if (!parsed || !Array.isArray(parsed.steps))
11
- return null;
12
- return {
13
- id: parsed.id || "plan_legacy",
14
- title: parsed.title || "Legacy plan",
15
- steps: parsed.steps,
16
- createdAt: parsed.createdAt || new Date().toISOString(),
17
- baseDir: parsed.baseDir || fallbackBaseDir,
18
- name: parsed.name,
19
- };
20
- }
21
- catch {
22
- return null;
23
- }
24
- }
25
- function writePlanFile(path, plan) {
26
- writeFileSync(path, JSON.stringify(plan, null, 2), "utf-8");
27
- }
28
- function listDir(dir, baseDir) {
29
- if (!existsSync(dir))
30
- return [];
31
- const files = readdirSync(dir).filter((f) => f.endsWith(".json"));
32
- return files
33
- .map((f) => readPlanFile(join(dir, f), baseDir))
34
- .filter((p) => p !== null);
35
- }
36
- function toMeta(plan, status) {
37
- return {
38
- id: plan.id,
39
- name: plan.name,
40
- title: plan.title,
41
- status,
42
- createdAt: plan.createdAt,
43
- stepCount: plan.steps.length,
44
- doneCount: plan.steps.filter((s) => s.status === "done" || s.status === "skipped").length,
45
- };
46
- }
47
- export class PlanStore {
48
- baseDir;
49
- plansDir;
50
- draftsDir;
51
- archiveDir;
52
- legacyPath;
53
- constructor(baseDir) {
54
- const mmaDir = join(baseDir, ".mma");
55
- if (!existsSync(mmaDir))
56
- mkdirSync(mmaDir, { recursive: true });
57
- this.baseDir = baseDir;
58
- this.plansDir = join(mmaDir, "plans");
59
- this.draftsDir = join(this.plansDir, "drafts");
60
- this.archiveDir = join(this.plansDir, "archive");
61
- this.legacyPath = join(mmaDir, LEGACY_FILE);
62
- for (const dir of [this.plansDir, this.draftsDir, this.archiveDir]) {
63
- if (!existsSync(dir))
64
- mkdirSync(dir, { recursive: true });
65
- }
66
- }
67
- activePath() {
68
- return join(this.plansDir, "active.json");
69
- }
70
- // ---- Active plan ----
71
- saveActive(plan) {
72
- writePlanFile(this.activePath(), plan);
73
- }
74
- loadActive() {
75
- const activePath = this.activePath();
76
- if (existsSync(activePath)) {
77
- const plan = readPlanFile(activePath, this.baseDir);
78
- if (plan)
79
- return plan;
80
- }
81
- // Legacy migration: read .mma/plan.json and move to active
82
- if (existsSync(this.legacyPath)) {
83
- const legacy = readPlanFile(this.legacyPath, this.baseDir);
84
- if (legacy) {
85
- this.saveActive(legacy);
86
- try {
87
- rmSync(this.legacyPath, { force: true });
88
- }
89
- catch { }
90
- return legacy;
91
- }
92
- }
93
- return null;
94
- }
95
- clearActive() {
96
- const p = this.activePath();
97
- if (existsSync(p))
98
- rmSync(p, { force: true });
99
- }
100
- // ---- Drafts (saved plans) ----
101
- saveDraft(plan) {
102
- writePlanFile(join(this.draftsDir, `${plan.id}.json`), plan);
103
- }
104
- loadDraft(id) {
105
- const p = join(this.draftsDir, `${id}.json`);
106
- return existsSync(p) ? readPlanFile(p, this.baseDir) : null;
107
- }
108
- removeDraft(id) {
109
- const p = join(this.draftsDir, `${id}.json`);
110
- if (existsSync(p))
111
- rmSync(p, { force: true });
112
- }
113
- listDrafts() {
114
- return listDir(this.draftsDir, this.baseDir);
115
- }
116
- // ---- Archive ----
117
- archivePlan(plan) {
118
- writePlanFile(join(this.archiveDir, `${plan.id}.json`), plan);
119
- // Remove from drafts if present
120
- this.removeDraft(plan.id);
121
- // If archived plan was active, clear active
122
- const active = this.loadActive();
123
- if (active && active.id === plan.id) {
124
- this.clearActive();
125
- }
126
- }
127
- listArchived() {
128
- return listDir(this.archiveDir, this.baseDir);
129
- }
130
- removeArchived(id) {
131
- const p = join(this.archiveDir, `${id}.json`);
132
- if (existsSync(p))
133
- rmSync(p, { force: true });
134
- }
135
- // ---- Cross-status queries ----
136
- listAll() {
137
- const metas = [];
138
- const active = this.loadActive();
139
- if (active)
140
- metas.push(toMeta(active, "active"));
141
- for (const p of this.listDrafts())
142
- metas.push(toMeta(p, "draft"));
143
- for (const p of this.listArchived())
144
- metas.push(toMeta(p, "archived"));
145
- return metas;
146
- }
147
- find(id) {
148
- const active = this.loadActive();
149
- if (active && active.id === id)
150
- return { plan: active, status: "active" };
151
- const draft = this.loadDraft(id);
152
- if (draft)
153
- return { plan: draft, status: "draft" };
154
- const archived = this.listArchived().find((p) => p.id === id);
155
- if (archived)
156
- return { plan: archived, status: "archived" };
157
- return null;
158
- }
159
- }
@@ -1,153 +0,0 @@
1
- export function validatePlan(plan, config) {
2
- const errors = [];
3
- const warnings = [];
4
- const autoFixes = [];
5
- if (!plan.subtasks || plan.subtasks.length === 0) {
6
- return { valid: false, errors: ['Plan has no subtasks'], warnings: [], autoFixes: [] };
7
- }
8
- errors.push(...expertTagsExist(plan.subtasks, config));
9
- errors.push(...hasCycle(plan.subtasks));
10
- const overlapErrors = hasAllowedFilesOverlap(plan.subtasks);
11
- errors.push(...overlapErrors);
12
- const readOverlaps = deleteReadOverlap(plan.subtasks);
13
- for (const overlap of readOverlaps) {
14
- if (overlap.canAutoFix) {
15
- autoFixes.push({ subtaskId: overlap.subtaskId, fix: `Add depends_on: ${overlap.dependsOn}` });
16
- }
17
- else if (overlap.error) {
18
- errors.push(overlap.error);
19
- }
20
- }
21
- return {
22
- valid: errors.length === 0,
23
- errors,
24
- warnings,
25
- autoFixes,
26
- };
27
- }
28
- export function expertTagsExist(subtasks, config) {
29
- const errors = [];
30
- const knownExperts = new Set(Object.keys(config.experts || {}));
31
- for (const subtask of subtasks) {
32
- if (!knownExperts.has(subtask.expert_tag)) {
33
- errors.push(`Subtask "${subtask.id}" references unknown expert_tag "${subtask.expert_tag}". Known experts: ${Array.from(knownExperts).join(', ')}`);
34
- }
35
- }
36
- return errors;
37
- }
38
- export function hasCycle(subtasks) {
39
- const edges = new Map();
40
- for (const s of subtasks) {
41
- edges.set(s.id, s.depends_on || []);
42
- }
43
- const visited = new Set();
44
- const inStack = new Set();
45
- function dfs(node) {
46
- if (inStack.has(node))
47
- return true;
48
- if (visited.has(node))
49
- return false;
50
- visited.add(node);
51
- inStack.add(node);
52
- const deps = edges.get(node) || [];
53
- for (const dep of deps) {
54
- if (edges.has(dep) && dfs(dep))
55
- return true;
56
- }
57
- inStack.delete(node);
58
- return false;
59
- }
60
- const errors = [];
61
- for (const s of subtasks) {
62
- visited.clear();
63
- inStack.clear();
64
- if (dfs(s.id)) {
65
- errors.push(`Cycle detected involving subtask "${s.id}"`);
66
- break;
67
- }
68
- }
69
- return errors;
70
- }
71
- export function hasAllowedFilesOverlap(subtasks) {
72
- const errors = [];
73
- const writeFiles = new Map();
74
- for (const s of subtasks) {
75
- for (const f of s.allowed_files || []) {
76
- if (!writeFiles.has(f)) {
77
- writeFiles.set(f, []);
78
- }
79
- writeFiles.get(f).push(s.id);
80
- }
81
- }
82
- for (const [file, writers] of writeFiles) {
83
- if (writers.length > 1) {
84
- const noDep = writers.filter(w => {
85
- const sub = subtasks.find(s => s.id === w);
86
- return sub && !sub.depends_on?.some(d => writers.includes(d));
87
- });
88
- if (noDep.length > 1) {
89
- errors.push(`Write-write overlap on "${file}" between subtasks: ${writers.join(', ')} without dependency chain`);
90
- }
91
- }
92
- }
93
- return errors;
94
- }
95
- export function deleteReadOverlap(subtasks) {
96
- const results = [];
97
- for (let i = 0; i < subtasks.length; i++) {
98
- for (let j = 0; j < subtasks.length; j++) {
99
- if (i === j)
100
- continue;
101
- const writer = subtasks[i];
102
- const reader = subtasks[j];
103
- if (!writer.allowed_files || !reader.read_only_files)
104
- continue;
105
- const readFiles = new Set(reader.read_only_files);
106
- const writeFiles = writer.allowed_files;
107
- const overlapping = writeFiles.filter(f => {
108
- for (const rf of readFiles) {
109
- if (f.startsWith(rf) || rf.startsWith(f))
110
- return true;
111
- }
112
- return false;
113
- });
114
- if (overlapping.length > 0 && !reader.depends_on?.includes(writer.id)) {
115
- const canAutoFix = !reader.depends_on || reader.depends_on.length === 0;
116
- if (canAutoFix) {
117
- results.push({
118
- subtaskId: reader.id,
119
- dependsOn: writer.id,
120
- canAutoFix: true,
121
- });
122
- }
123
- else {
124
- results.push({
125
- subtaskId: reader.id,
126
- dependsOn: writer.id,
127
- canAutoFix: false,
128
- error: `Read-after-write overlap between "${writer.id}" (writer) and "${reader.id}" (reader) on "${overlapping.join(', ')}" — add depends_on: [${writer.id}]`,
129
- });
130
- }
131
- }
132
- }
133
- }
134
- return results;
135
- }
136
- export function applyAutoFixes(plan, autoFixes) {
137
- const fixed = { ...plan, subtasks: plan.subtasks.map(s => ({ ...s })) };
138
- for (const fix of autoFixes) {
139
- const sub = fixed.subtasks.find(s => s.id === fix.subtaskId);
140
- if (!sub)
141
- continue;
142
- const dependsOnMatch = fix.fix.match(/depends_on:\s*(\S+)/);
143
- if (dependsOnMatch) {
144
- const dep = dependsOnMatch[1];
145
- if (!sub.depends_on)
146
- sub.depends_on = [];
147
- if (!sub.depends_on.includes(dep)) {
148
- sub.depends_on.push(dep);
149
- }
150
- }
151
- }
152
- return fixed;
153
- }