micro-models-agent 0.39.0 → 0.40.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.
- package/bin/mma.mjs +41 -41
- package/dist/cli/commands.js +116 -3
- package/dist/cli/main.js +35 -8
- package/dist/cli/repl-commands.js +633 -0
- package/dist/cli/repl.js +110 -611
- package/dist/cli/setup.js +32 -12
- package/dist/config/config.js +46 -30
- package/dist/config/defaults.js +10 -1
- package/dist/config/security.js +15 -8
- package/dist/core/agent-moe.js +24 -12
- package/dist/core/agent.js +281 -47
- package/dist/core/bootstrap.js +52 -36
- package/dist/core/session-logger.js +35 -2
- package/dist/core/workspace.js +76 -0
- package/dist/i18n/en.json +79 -15
- package/dist/i18n/index.js +12 -9
- package/dist/i18n/ru.json +79 -15
- package/dist/index.js +13 -13
- package/dist/llm/openai-compat.js +39 -10
- package/dist/logger/app-logger.js +83 -16
- package/dist/logger/file-log.js +151 -0
- package/dist/main.js +537 -284
- package/dist/modules/browser/bridge-server.mjs +113 -105
- package/dist/modules/browser/session.js +108 -60
- package/dist/modules/certification/cli.js +176 -0
- package/dist/modules/certification/fact-checker.js +84 -0
- package/dist/modules/certification/loader.js +111 -0
- package/dist/modules/certification/manifest.js +50 -0
- package/dist/modules/certification/runner.js +162 -0
- package/dist/modules/certification/scenarios.js +124 -0
- package/dist/modules/certification/types.js +1 -0
- package/dist/modules/context/manager.js +119 -10
- package/dist/modules/execution/auditor.js +33 -39
- package/dist/modules/execution/index.js +8 -6
- package/dist/modules/execution/module.js +474 -32
- package/dist/modules/execution/moe-executor.js +97 -40
- package/dist/modules/execution/plan-coverage.js +68 -0
- package/dist/modules/execution/plan-persister.js +46 -0
- package/dist/modules/execution/plan-store.js +159 -0
- package/dist/modules/execution/planner.js +63 -13
- package/dist/modules/execution/stuck-detector.js +252 -39
- package/dist/modules/execution/tracker.js +21 -7
- package/dist/modules/execution/verifier.js +46 -17
- package/dist/modules/hallucination/confidence.js +7 -2
- package/dist/modules/hallucination/consistency.js +8 -42
- package/dist/modules/hallucination/detector.js +26 -21
- package/dist/modules/hallucination/factual.js +170 -150
- package/dist/modules/hallucination/index.js +5 -4
- package/dist/modules/hallucination/js-identifiers.js +72 -0
- package/dist/modules/hallucination/llm-judge.js +103 -0
- package/dist/modules/index.js +5 -5
- package/dist/modules/lsp/client.js +235 -0
- package/dist/modules/lsp/config.js +81 -0
- package/dist/modules/lsp/index.js +3 -0
- package/dist/modules/lsp/module.js +68 -0
- package/dist/modules/lsp/types.js +1 -0
- package/dist/modules/mcp/client.js +8 -2
- package/dist/modules/memory/store.js +4 -0
- package/dist/modules/plugins/builtin/lint-on-write.js +143 -38
- package/dist/modules/processes/index.js +1 -2
- package/dist/modules/processes/registry.js +125 -35
- package/dist/modules/processes/runner.js +9 -110
- package/dist/modules/security/audit-log.js +30 -10
- package/dist/modules/security/command-validator.js +42 -16
- package/dist/modules/security/content-scanner.js +9 -8
- package/dist/modules/security/network-validator.js +2 -2
- package/dist/modules/security/path-validator.js +64 -10
- package/dist/modules/security/security-policies.js +221 -67
- package/dist/modules/security/session-encryption.js +42 -25
- package/dist/modules/session/manager.js +15 -10
- package/dist/modules/session/store.js +62 -8
- package/dist/modules/skills/index.js +2 -3
- package/dist/modules/skills/module.js +10 -23
- package/dist/tools/bash.js +287 -90
- package/dist/tools/create-dir.js +0 -1
- package/dist/tools/delete-file.js +0 -1
- package/dist/tools/edit-file.js +10 -8
- package/dist/tools/executor.js +57 -7
- package/dist/tools/grep-tool.js +51 -29
- package/dist/tools/index.js +55 -40
- package/dist/tools/load-skill.js +14 -18
- package/dist/tools/move-file.js +3 -2
- package/dist/tools/pipeline-run.js +1 -1
- package/dist/tools/read-file.js +15 -5
- package/dist/tools/search-history.js +42 -22
- package/dist/tools/subagent.js +21 -12
- package/dist/tools/web-browse.js +54 -25
- package/dist/tools/web-fetch.js +60 -34
- package/dist/tools/web-search.js +39 -20
- package/dist/tools/write-file.js +13 -10
- package/dist/ui/diff.js +9 -16
- package/dist/ui/renderer.js +69 -6
- package/package.json +48 -45
- package/dist/modules/context/history.js +0 -15
- package/dist/modules/processes/detect.js +0 -34
- package/dist/modules/skills/matcher.js +0 -27
|
@@ -1,28 +1,38 @@
|
|
|
1
|
-
import { getExpertConfig } from
|
|
2
|
-
import { filterToolsByTags } from
|
|
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";
|
|
3
5
|
const TRANSIENT_ERROR_PATTERNS = [
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
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",
|
|
10
20
|
];
|
|
11
21
|
function isTransientError(error) {
|
|
12
|
-
return TRANSIENT_ERROR_PATTERNS.some(p => error.includes(p));
|
|
22
|
+
return TRANSIENT_ERROR_PATTERNS.some((p) => error.includes(p));
|
|
13
23
|
}
|
|
14
24
|
function sleep(ms) {
|
|
15
|
-
return new Promise(r => setTimeout(r, ms));
|
|
25
|
+
return new Promise((r) => setTimeout(r, ms));
|
|
16
26
|
}
|
|
17
27
|
export function topologicalSort(subtasks) {
|
|
18
28
|
const sorted = [];
|
|
19
|
-
const remaining = new Set(subtasks.map(s => s.id));
|
|
20
|
-
const subtaskMap = new Map(subtasks.map(s => [s.id, s]));
|
|
29
|
+
const remaining = new Set(subtasks.map((s) => s.id));
|
|
30
|
+
const subtaskMap = new Map(subtasks.map((s) => [s.id, s]));
|
|
21
31
|
while (remaining.size > 0) {
|
|
22
32
|
const ready = [];
|
|
23
33
|
for (const id of remaining) {
|
|
24
34
|
const sub = subtaskMap.get(id);
|
|
25
|
-
const depsSatisfied = (sub.depends_on || []).every(d => !remaining.has(d));
|
|
35
|
+
const depsSatisfied = (sub.depends_on || []).every((d) => !remaining.has(d));
|
|
26
36
|
if (depsSatisfied) {
|
|
27
37
|
ready.push(sub);
|
|
28
38
|
}
|
|
@@ -45,19 +55,19 @@ async function executeSubtask(subtask, deps, _sharedContext) {
|
|
|
45
55
|
subtaskId: subtask.id,
|
|
46
56
|
success: false,
|
|
47
57
|
summary: `Unknown expert_tag: ${subtask.expert_tag}`,
|
|
48
|
-
result:
|
|
58
|
+
result: "",
|
|
49
59
|
error: `No expert config found for tag "${subtask.expert_tag}"`,
|
|
50
60
|
durationMs: Date.now() - startTime,
|
|
51
61
|
};
|
|
52
62
|
}
|
|
53
|
-
const subagentTool = deps.toolRegistry.get(
|
|
63
|
+
const subagentTool = deps.toolRegistry.get("subagent");
|
|
54
64
|
if (!subagentTool) {
|
|
55
65
|
return {
|
|
56
66
|
subtaskId: subtask.id,
|
|
57
67
|
success: false,
|
|
58
|
-
summary:
|
|
59
|
-
result:
|
|
60
|
-
error:
|
|
68
|
+
summary: "Subagent tool not registered",
|
|
69
|
+
result: "",
|
|
70
|
+
error: "Subagent tool not found in registry",
|
|
61
71
|
durationMs: Date.now() - startTime,
|
|
62
72
|
};
|
|
63
73
|
}
|
|
@@ -67,23 +77,25 @@ async function executeSubtask(subtask, deps, _sharedContext) {
|
|
|
67
77
|
return {
|
|
68
78
|
subtaskId: subtask.id,
|
|
69
79
|
success: false,
|
|
70
|
-
summary: `No tools available for expert "${subtask.expert_tag}" (tags: ${expertConfig.tool_tags.join(
|
|
71
|
-
result:
|
|
72
|
-
error:
|
|
80
|
+
summary: `No tools available for expert "${subtask.expert_tag}" (tags: ${expertConfig.tool_tags.join(", ")})`,
|
|
81
|
+
result: "",
|
|
82
|
+
error: "No matching tools",
|
|
73
83
|
durationMs: Date.now() - startTime,
|
|
74
84
|
};
|
|
75
85
|
}
|
|
76
86
|
const maxAttempts = expertConfig.max_attempts || 3;
|
|
77
|
-
let lastError =
|
|
87
|
+
let lastError = "";
|
|
78
88
|
let lastResult = null;
|
|
89
|
+
const stuckDetector = new StuckDetector(maxAttempts * 2, maxAttempts);
|
|
79
90
|
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
|
91
|
+
stuckDetector.recordIteration(1);
|
|
80
92
|
try {
|
|
81
93
|
const allowedFiles = subtask.allowed_files || [];
|
|
82
94
|
const readOnlyFiles = subtask.read_only_files || [];
|
|
83
95
|
const scopePrompt = allowedFiles.length > 0 || readOnlyFiles.length > 0
|
|
84
|
-
? `\n\nAllowed files to write: ${allowedFiles.join(
|
|
85
|
-
:
|
|
86
|
-
const taskPrompt = `${subtask.description}\n\nExpected output: ${subtask.expected_output}\nSuccess criteria:\n${(subtask.success_criteria || []).map((c) => `- ${c}`).join(
|
|
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}`;
|
|
87
99
|
const subagentArgs = {
|
|
88
100
|
task: taskPrompt,
|
|
89
101
|
allowed_files: allowedFiles,
|
|
@@ -108,45 +120,83 @@ async function executeSubtask(subtask, deps, _sharedContext) {
|
|
|
108
120
|
}
|
|
109
121
|
lastError = result.output;
|
|
110
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
|
+
}
|
|
111
135
|
if (isTransientError(lastError) && attempt < maxAttempts) {
|
|
112
136
|
const delay = Math.min(1000 * Math.pow(2, attempt - 1), 8000);
|
|
113
137
|
deps.logger.debug(`Retrying subtask "${subtask.id}" (attempt ${attempt}/${maxAttempts}) after ${delay}ms: transient error`);
|
|
114
138
|
await sleep(delay);
|
|
115
139
|
continue;
|
|
116
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
|
+
}
|
|
117
151
|
return {
|
|
118
152
|
subtaskId: subtask.id,
|
|
119
153
|
success: false,
|
|
120
154
|
summary: `Failed: ${subtask.id}`,
|
|
121
155
|
result: result.output,
|
|
122
|
-
error:
|
|
156
|
+
error: errorDetail,
|
|
123
157
|
durationMs: Date.now() - startTime,
|
|
124
158
|
};
|
|
125
159
|
}
|
|
126
160
|
catch (e) {
|
|
127
161
|
lastError = e.message;
|
|
162
|
+
stuckDetector.recordToolError("subagent", e.message);
|
|
128
163
|
if (isTransientError(lastError) && attempt < maxAttempts) {
|
|
129
164
|
const delay = Math.min(1000 * Math.pow(2, attempt - 1), 8000);
|
|
130
165
|
deps.logger.debug(`Retrying subtask "${subtask.id}" (attempt ${attempt}/${maxAttempts}) after ${delay}ms: ${lastError}`);
|
|
131
166
|
await sleep(delay);
|
|
132
167
|
continue;
|
|
133
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
|
+
}
|
|
134
178
|
return {
|
|
135
179
|
subtaskId: subtask.id,
|
|
136
180
|
success: false,
|
|
137
181
|
summary: `Error: ${subtask.id}`,
|
|
138
|
-
result:
|
|
139
|
-
error:
|
|
182
|
+
result: "",
|
|
183
|
+
error: errorDetail,
|
|
140
184
|
durationMs: Date.now() - startTime,
|
|
141
185
|
};
|
|
142
186
|
}
|
|
143
187
|
}
|
|
188
|
+
// Exhausted retries — build detailed failure
|
|
189
|
+
const stuckReason = stuckDetector.getStuckReason();
|
|
190
|
+
let finalError = lastError;
|
|
191
|
+
if (stuckReason) {
|
|
192
|
+
finalError += `\n${stuckReason}`;
|
|
193
|
+
}
|
|
144
194
|
return {
|
|
145
195
|
subtaskId: subtask.id,
|
|
146
196
|
success: false,
|
|
147
197
|
summary: `Failed after ${maxAttempts} attempts: ${subtask.id}`,
|
|
148
|
-
result:
|
|
149
|
-
error:
|
|
198
|
+
result: "",
|
|
199
|
+
error: finalError,
|
|
150
200
|
durationMs: Date.now() - startTime,
|
|
151
201
|
};
|
|
152
202
|
}
|
|
@@ -161,34 +211,41 @@ export class MoEExecutor {
|
|
|
161
211
|
const warnings = [];
|
|
162
212
|
const waves = topologicalSort(plan.subtasks);
|
|
163
213
|
if (waves.length === 0) {
|
|
164
|
-
return {
|
|
214
|
+
return {
|
|
215
|
+
success: false,
|
|
216
|
+
results: [],
|
|
217
|
+
errors: ["Failed to topologically sort subtasks (possible cycle)"],
|
|
218
|
+
warnings: [],
|
|
219
|
+
};
|
|
165
220
|
}
|
|
166
221
|
// Verify all subtasks are included — catch silent drops from unresolved dependencies
|
|
167
222
|
const sortedCount = waves.flat().length;
|
|
168
223
|
if (sortedCount < plan.subtasks.length) {
|
|
169
224
|
const missing = plan.subtasks
|
|
170
|
-
.filter(s => !waves.flat().some(w => w.id === s.id))
|
|
171
|
-
.map(s => s.id);
|
|
225
|
+
.filter((s) => !waves.flat().some((w) => w.id === s.id))
|
|
226
|
+
.map((s) => s.id);
|
|
172
227
|
return {
|
|
173
228
|
success: false,
|
|
174
229
|
results: [],
|
|
175
|
-
errors: [
|
|
230
|
+
errors: [
|
|
231
|
+
`Missing subtasks after topological sort: ${missing.join(", ")} (dangling or invalid depends_on)`,
|
|
232
|
+
],
|
|
176
233
|
warnings: [],
|
|
177
234
|
};
|
|
178
235
|
}
|
|
179
236
|
for (let waveIdx = 0; waveIdx < waves.length; waveIdx++) {
|
|
180
237
|
const wave = waves[waveIdx];
|
|
181
|
-
const wavePromises = wave.map(subtask => executeSubtask(subtask, this.deps, plan.shared_context)
|
|
182
|
-
.then(result => {
|
|
238
|
+
const wavePromises = wave.map((subtask) => executeSubtask(subtask, this.deps, plan.shared_context)
|
|
239
|
+
.then((result) => {
|
|
183
240
|
results.push(result);
|
|
184
241
|
return result;
|
|
185
242
|
})
|
|
186
|
-
.catch(e => {
|
|
243
|
+
.catch((e) => {
|
|
187
244
|
const errResult = {
|
|
188
245
|
subtaskId: subtask.id,
|
|
189
246
|
success: false,
|
|
190
247
|
summary: `Unhandled error: ${subtask.id}`,
|
|
191
|
-
result:
|
|
248
|
+
result: "",
|
|
192
249
|
error: e.message,
|
|
193
250
|
durationMs: 0,
|
|
194
251
|
};
|
|
@@ -197,9 +254,9 @@ export class MoEExecutor {
|
|
|
197
254
|
}));
|
|
198
255
|
await Promise.all(wavePromises);
|
|
199
256
|
}
|
|
200
|
-
const failed = results.filter(r => !r.success);
|
|
257
|
+
const failed = results.filter((r) => !r.success);
|
|
201
258
|
if (failed.length > 0) {
|
|
202
|
-
errors.push(...failed.map(f => `[${f.subtaskId}] ${f.error || f.summary}`));
|
|
259
|
+
errors.push(...failed.map((f) => `[${f.subtaskId}] ${f.error || f.summary}`));
|
|
203
260
|
}
|
|
204
261
|
return { success: failed.length === 0, results, errors, warnings };
|
|
205
262
|
}
|
|
@@ -0,0 +1,68 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,159 @@
|
|
|
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,35 +1,85 @@
|
|
|
1
|
+
function generatePlanId() {
|
|
2
|
+
const chars = "abcdefghijklmnopqrstuvwxyz0123456789";
|
|
3
|
+
let id = "";
|
|
4
|
+
for (let i = 0; i < 6; i++) {
|
|
5
|
+
id += chars[Math.floor(Math.random() * chars.length)];
|
|
6
|
+
}
|
|
7
|
+
return `plan_${id}`;
|
|
8
|
+
}
|
|
1
9
|
export class PlanCreator {
|
|
2
10
|
static isMultiStep(task) {
|
|
3
11
|
const fileCount = (task.match(/\b[\w./-]+\.[a-z]+\b/gi) || []).length;
|
|
4
12
|
if (fileCount > 1)
|
|
5
13
|
return true;
|
|
6
|
-
const actionWords = [
|
|
14
|
+
const actionWords = [
|
|
15
|
+
"implement",
|
|
16
|
+
"create",
|
|
17
|
+
"add",
|
|
18
|
+
"build",
|
|
19
|
+
"setup",
|
|
20
|
+
"configure",
|
|
21
|
+
"write",
|
|
22
|
+
"make",
|
|
23
|
+
"develop",
|
|
24
|
+
];
|
|
7
25
|
const words = task.split(/\s+/);
|
|
8
|
-
const hasActionWord = actionWords.some(w => task.toLowerCase().includes(w));
|
|
26
|
+
const hasActionWord = actionWords.some((w) => task.toLowerCase().includes(w));
|
|
9
27
|
return hasActionWord && words.length > 8;
|
|
10
28
|
}
|
|
11
|
-
static createPlan(title, stepDescriptions) {
|
|
29
|
+
static createPlan(title, stepDescriptions, baseDir) {
|
|
30
|
+
const stepCount = stepDescriptions.length;
|
|
12
31
|
return {
|
|
13
|
-
|
|
32
|
+
id: generatePlanId(),
|
|
33
|
+
title: `[${stepCount}] ${title}`,
|
|
14
34
|
steps: stepDescriptions.map((desc, i) => ({
|
|
15
35
|
id: i + 1,
|
|
16
36
|
description: desc,
|
|
17
|
-
status:
|
|
37
|
+
status: "pending",
|
|
18
38
|
})),
|
|
19
39
|
createdAt: new Date().toISOString(),
|
|
40
|
+
baseDir,
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
static replan(plan, newSteps, title) {
|
|
44
|
+
const kept = plan.steps.filter((s) => s.status === "done" || s.status === "skipped");
|
|
45
|
+
const baseTitle = plan.title.replace(/^\[\d+[^]]*\]\s*/, "");
|
|
46
|
+
const newTitle = title || baseTitle;
|
|
47
|
+
const totalSteps = kept.length + newSteps.length;
|
|
48
|
+
const added = newSteps.map((desc, i) => ({
|
|
49
|
+
id: kept.length + i + 1,
|
|
50
|
+
description: desc,
|
|
51
|
+
status: "pending",
|
|
52
|
+
}));
|
|
53
|
+
return {
|
|
54
|
+
id: plan.id,
|
|
55
|
+
title: `[${totalSteps}] ${newTitle}`,
|
|
56
|
+
steps: [...kept, ...added],
|
|
57
|
+
createdAt: plan.createdAt,
|
|
58
|
+
baseDir: plan.baseDir,
|
|
59
|
+
name: plan.name,
|
|
20
60
|
};
|
|
21
61
|
}
|
|
22
62
|
static toPromptBlock(plan, currentStepIndex) {
|
|
23
|
-
const
|
|
63
|
+
const date = plan.createdAt.slice(0, 10);
|
|
64
|
+
const lines = [
|
|
65
|
+
`[${plan.id}] ${plan.title}`,
|
|
66
|
+
`Dir: ${plan.baseDir}`,
|
|
67
|
+
`Created: ${date} | Progress: ${plan.steps.filter((s) => s.status === "done").length}/${plan.steps.length} done, current: step ${currentStepIndex + 1}`,
|
|
68
|
+
``,
|
|
69
|
+
];
|
|
24
70
|
for (const step of plan.steps) {
|
|
25
|
-
const icon = step.status ===
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
71
|
+
const icon = step.status === "done"
|
|
72
|
+
? "[x]"
|
|
73
|
+
: step.status === "in_progress"
|
|
74
|
+
? "[*]"
|
|
75
|
+
: step.status === "failed"
|
|
76
|
+
? "[!]"
|
|
77
|
+
: step.status === "skipped"
|
|
78
|
+
? "[-]"
|
|
79
|
+
: "[ ]";
|
|
80
|
+
const note = step.note ? ` — ${step.note}` : "";
|
|
31
81
|
lines.push(`${icon} ${step.id}. ${step.description}${note}`);
|
|
32
82
|
}
|
|
33
|
-
return lines.join(
|
|
83
|
+
return lines.join("\n");
|
|
34
84
|
}
|
|
35
85
|
}
|