maestrokit 0.0.0-stage → 0.1.0-beta.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/LICENSE +21 -0
- package/README.md +107 -2
- package/THIRD_PARTY.md +13 -0
- package/agents/tester/mk-tester.md +20 -0
- package/agents/tester/skills/mk-test/SKILL.md +32 -0
- package/commands/mk-feat-notest.md +23 -0
- package/commands/mk-feat.md +57 -0
- package/dist/cli.js +47 -0
- package/dist/main.js +2549 -0
- package/package.json +77 -4
- package/shared/mk-clarify/SKILL.md +43 -0
- package/shared/mk-implement/SKILL.md +31 -0
- package/shared/mk-knowledge/SKILL.md +46 -0
- package/shared/mk-plan/SKILL.md +53 -0
- package/shared/mk-plan/references/structure-expo.md +21 -0
- package/shared/mk-plan/references/structure-flutter.md +22 -0
- package/shared/mk-plan/references/structure-rn-bare.md +22 -0
- package/shared/mk-rules/SKILL.md +20 -0
- package/tech/frameworks/flutter/flutter-core/SKILL.md +61 -0
- package/tech/frameworks/flutter/flutter-testing/SKILL.md +45 -0
- package/tech/frameworks/flutter/stack.yaml +40 -0
- package/tech/frameworks/react-native/expo/eas/SKILL.md +27 -0
- package/tech/frameworks/react-native/expo/expo-core/SKILL.md +33 -0
- package/tech/frameworks/react-native/expo/expo-upgrade/SKILL.md +27 -0
- package/tech/frameworks/react-native/rn-core/SKILL.md +60 -0
- package/tech/frameworks/react-native/rn-core/references/performance.md +32 -0
- package/tech/frameworks/react-native/rn-core/references/platform-security-a11y.md +21 -0
- package/tech/frameworks/react-native/rn-testing/SKILL.md +44 -0
- package/tech/frameworks/react-native/rn-testing/references/examples.md +49 -0
- package/tech/frameworks/react-native/stack.yaml +57 -0
- package/tech/languages/dart/dart-core/SKILL.md +49 -0
- package/tech/languages/dart/stack.yaml +34 -0
- package/tech/languages/typescript/ts-core/SKILL.md +35 -0
- package/tech/languages/typescript/ts-core/references/patterns.md +40 -0
package/dist/main.js
ADDED
|
@@ -0,0 +1,2549 @@
|
|
|
1
|
+
// src/main.ts
|
|
2
|
+
import { Command, CommanderError } from "commander";
|
|
3
|
+
|
|
4
|
+
// src/commands/init.ts
|
|
5
|
+
import { copyFile, cp, mkdir as mkdir2, readFile as readFile5, rm as rm2, rmdir as rmdir2, writeFile } from "fs/promises";
|
|
6
|
+
import path8 from "path";
|
|
7
|
+
import { stringify } from "yaml";
|
|
8
|
+
|
|
9
|
+
// src/core/claude-settings.ts
|
|
10
|
+
import { readFile } from "fs/promises";
|
|
11
|
+
import path from "path";
|
|
12
|
+
var SETTINGS_PATH = ".claude/settings.local.json";
|
|
13
|
+
var rule = (prefix) => `Bash(${prefix}:*)`;
|
|
14
|
+
var ALWAYS_ALLOW = ["npx maestrokit", "git status", "git diff", "git log", "git show", "git ls-files"].map(rule);
|
|
15
|
+
function allowRules(stack) {
|
|
16
|
+
const prefixes = stack === null ? [] : [...stack.profile.allow_commands, ...stack.profile.variants[stack.variant]?.allow_commands ?? []];
|
|
17
|
+
return [.../* @__PURE__ */ new Set([...ALWAYS_ALLOW, ...prefixes.map(rule)])];
|
|
18
|
+
}
|
|
19
|
+
var isMapping = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
20
|
+
async function planSettings(projectDir, rules) {
|
|
21
|
+
const abs3 = path.join(projectDir, ...SETTINGS_PATH.split("/"));
|
|
22
|
+
let before = null;
|
|
23
|
+
try {
|
|
24
|
+
before = await readFile(abs3, "utf8");
|
|
25
|
+
} catch (error) {
|
|
26
|
+
if (error.code !== "ENOENT") {
|
|
27
|
+
return { kind: "skip", path: SETTINGS_PATH, warning: `${SETTINGS_PATH} is not valid \u2014 no command rules added` };
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
if (before === null) {
|
|
31
|
+
const text = `${JSON.stringify({ permissions: { allow: [...rules] } }, null, 2)}
|
|
32
|
+
`;
|
|
33
|
+
return { kind: "write", path: SETTINGS_PATH, before: null, text, added: [...rules] };
|
|
34
|
+
}
|
|
35
|
+
const warning = `${SETTINGS_PATH} is not valid \u2014 no command rules added`;
|
|
36
|
+
let data;
|
|
37
|
+
try {
|
|
38
|
+
data = JSON.parse(before.replace(/^\uFEFF/, ""));
|
|
39
|
+
} catch {
|
|
40
|
+
return { kind: "skip", path: SETTINGS_PATH, warning };
|
|
41
|
+
}
|
|
42
|
+
if (!isMapping(data)) return { kind: "skip", path: SETTINGS_PATH, warning };
|
|
43
|
+
const permissions = data.permissions ?? {};
|
|
44
|
+
if (!isMapping(permissions)) return { kind: "skip", path: SETTINGS_PATH, warning };
|
|
45
|
+
const allow = permissions.allow ?? [];
|
|
46
|
+
if (!Array.isArray(allow)) return { kind: "skip", path: SETTINGS_PATH, warning };
|
|
47
|
+
const current = allow;
|
|
48
|
+
const added = rules.filter((r) => !current.includes(r));
|
|
49
|
+
if (added.length === 0) return { kind: "none", path: SETTINGS_PATH };
|
|
50
|
+
const merged = { ...data, permissions: { ...permissions, allow: [...current, ...added] } };
|
|
51
|
+
return { kind: "write", path: SETTINGS_PATH, before, text: `${JSON.stringify(merged, null, 2)}
|
|
52
|
+
`, added };
|
|
53
|
+
}
|
|
54
|
+
async function planSettingsRemoval(projectDir, settings) {
|
|
55
|
+
if (settings == null) return { kind: "none" };
|
|
56
|
+
let text;
|
|
57
|
+
try {
|
|
58
|
+
text = await readFile(path.join(projectDir, ...settings.path.split("/")), "utf8");
|
|
59
|
+
} catch {
|
|
60
|
+
return { kind: "none" };
|
|
61
|
+
}
|
|
62
|
+
let data;
|
|
63
|
+
try {
|
|
64
|
+
data = JSON.parse(text.replace(/^\uFEFF/, ""));
|
|
65
|
+
} catch {
|
|
66
|
+
return { kind: "none" };
|
|
67
|
+
}
|
|
68
|
+
if (!isMapping(data) || !isMapping(data.permissions) || !Array.isArray(data.permissions.allow)) return { kind: "none" };
|
|
69
|
+
const allow = data.permissions.allow;
|
|
70
|
+
const kept = allow.filter((r) => !(typeof r === "string" && settings.added.includes(r)));
|
|
71
|
+
const permissions = { ...data.permissions, allow: kept };
|
|
72
|
+
const next = { ...data, permissions };
|
|
73
|
+
const onlyEmpty = Object.keys(next).length === 1 && Object.keys(permissions).length === 1 && kept.length === 0;
|
|
74
|
+
if (settings.created && onlyEmpty) return { kind: "delete" };
|
|
75
|
+
return { kind: "write", text: `${JSON.stringify(next, null, 2)}
|
|
76
|
+
` };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// src/core/errors.ts
|
|
80
|
+
var MaestroError = class extends Error {
|
|
81
|
+
code;
|
|
82
|
+
exitCode = 1;
|
|
83
|
+
hint;
|
|
84
|
+
/** Project-relative POSIX paths (collisions, leftovers; directories end in `/`), or an absolute path outside the project (the git exclude file). */
|
|
85
|
+
paths;
|
|
86
|
+
constructor(code, message, options = {}) {
|
|
87
|
+
super(message, "cause" in options ? { cause: options.cause } : void 0);
|
|
88
|
+
this.name = "MaestroError";
|
|
89
|
+
this.code = code;
|
|
90
|
+
this.hint = options.hint;
|
|
91
|
+
this.paths = options.paths ?? [];
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
// src/core/git-exclude.ts
|
|
96
|
+
var EXCLUDE_BEGIN = "# >>> maestrokit (managed by maestrokit init; do not edit)";
|
|
97
|
+
var EXCLUDE_END = "# <<< maestrokit";
|
|
98
|
+
var isBegin = (line) => line.startsWith("# >>> maestrokit");
|
|
99
|
+
var isEnd = (line) => line.startsWith("# <<< maestrokit");
|
|
100
|
+
function upsertExcludeBlock(text, entries) {
|
|
101
|
+
const eol = text.includes("\r\n") ? "\r\n" : "\n";
|
|
102
|
+
const block = [EXCLUDE_BEGIN, ...entries, EXCLUDE_END];
|
|
103
|
+
const lines = text === "" ? [] : text.split(/\r?\n/);
|
|
104
|
+
if (lines.length > 0 && lines.at(-1) === "") lines.pop();
|
|
105
|
+
const start = lines.findIndex(isBegin);
|
|
106
|
+
const end = start < 0 ? -1 : lines.findIndex((line, i) => i > start && isEnd(line));
|
|
107
|
+
const out = start >= 0 && end >= 0 ? [...lines.slice(0, start), ...block, ...lines.slice(end + 1)] : [...lines, ...block];
|
|
108
|
+
return `${out.join(eol)}${eol}`;
|
|
109
|
+
}
|
|
110
|
+
function escapeGitPattern(path23) {
|
|
111
|
+
return path23.replace(/[\\*?[]/g, (c) => `\\${c}`).replace(/ (?=\/|$)/g, "\\ ");
|
|
112
|
+
}
|
|
113
|
+
function removeExcludeBlock(text) {
|
|
114
|
+
const eol = text.includes("\r\n") ? "\r\n" : "\n";
|
|
115
|
+
const lines = text === "" ? [] : text.split(/\r?\n/);
|
|
116
|
+
const start = lines.findIndex(isBegin);
|
|
117
|
+
const end = start < 0 ? -1 : lines.findIndex((line, i) => i > start && isEnd(line));
|
|
118
|
+
if (start < 0 || end < 0) return text;
|
|
119
|
+
const after = lines[end + 1] === "" && end + 1 < lines.length - 1 ? end + 2 : end + 1;
|
|
120
|
+
const out = [...lines.slice(0, start), ...lines.slice(after)];
|
|
121
|
+
if (out.length > 0 && out.at(-1) === "") out.pop();
|
|
122
|
+
return out.length === 0 ? "" : `${out.join(eol)}${eol}`;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// src/core/hash.ts
|
|
126
|
+
import { createHash } from "crypto";
|
|
127
|
+
import { readFile as readFile2 } from "fs/promises";
|
|
128
|
+
async function sha256File(file) {
|
|
129
|
+
return createHash("sha256").update(await readFile2(file)).digest("hex");
|
|
130
|
+
}
|
|
131
|
+
async function gitBlobSha(file) {
|
|
132
|
+
const bytes = await readFile2(file);
|
|
133
|
+
return createHash("sha1").update(`blob ${bytes.length}\0`).update(bytes).digest("hex");
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// src/core/install-set.ts
|
|
137
|
+
import { lstat, readdir } from "fs/promises";
|
|
138
|
+
import path6 from "path";
|
|
139
|
+
|
|
140
|
+
// src/core/catalog.ts
|
|
141
|
+
import path2 from "path";
|
|
142
|
+
import { glob } from "tinyglobby";
|
|
143
|
+
var PROCESS_SKILLS = ["agents/*/skills/*/SKILL.md", "shared/*/SKILL.md"];
|
|
144
|
+
var STACK_SKILLS = ["tech/languages/*/*/SKILL.md", "tech/frameworks/*/*/SKILL.md", "tech/frameworks/*/*/*/SKILL.md"];
|
|
145
|
+
async function find(root, patterns) {
|
|
146
|
+
return (await glob([...patterns], { cwd: root, onlyFiles: true, dot: false })).sort();
|
|
147
|
+
}
|
|
148
|
+
var toItem = (root) => (rel) => ({ source: path2.join(root, ...rel.split("/")), rel });
|
|
149
|
+
function toSkill(root, skillMd) {
|
|
150
|
+
const rel = path2.posix.dirname(skillMd);
|
|
151
|
+
return { name: path2.posix.basename(rel), dir: path2.join(root, ...rel.split("/")), rel };
|
|
152
|
+
}
|
|
153
|
+
async function loadCatalog(contentRoot) {
|
|
154
|
+
const commands = (await find(contentRoot, ["commands/mk-*.md"])).map(toItem(contentRoot));
|
|
155
|
+
const agents = (await find(contentRoot, ["agents/*/mk-*.md"])).map(toItem(contentRoot));
|
|
156
|
+
const processSkills = (await find(contentRoot, PROCESS_SKILLS)).map((f) => toSkill(contentRoot, f));
|
|
157
|
+
const stackSkills = (await find(contentRoot, STACK_SKILLS)).map((f) => toSkill(contentRoot, f));
|
|
158
|
+
const skillsByName = /* @__PURE__ */ new Map();
|
|
159
|
+
for (const skill of [...processSkills, ...stackSkills]) {
|
|
160
|
+
const other = skillsByName.get(skill.name);
|
|
161
|
+
if (other !== void 0) {
|
|
162
|
+
throw new MaestroError("PACKAGE_CONTENT_INVALID", `Two skills are named "${skill.name}"`, {
|
|
163
|
+
paths: [`${other.rel}/`, `${skill.rel}/`]
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
skillsByName.set(skill.name, skill);
|
|
167
|
+
}
|
|
168
|
+
return { commands, agents, processSkills, skillsByName };
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// src/core/project.ts
|
|
172
|
+
import { readFile as readFile3 } from "fs/promises";
|
|
173
|
+
import path3 from "path";
|
|
174
|
+
import { execa } from "execa";
|
|
175
|
+
import { parse } from "yaml";
|
|
176
|
+
|
|
177
|
+
// src/core/schemas/manifest.ts
|
|
178
|
+
import { z } from "zod";
|
|
179
|
+
var ProjectManifestSchema = z.looseObject({
|
|
180
|
+
dependencies: z.record(z.string(), z.string()).optional(),
|
|
181
|
+
devDependencies: z.record(z.string(), z.string()).optional()
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
// src/core/schemas/pubspec.ts
|
|
185
|
+
import { z as z2 } from "zod";
|
|
186
|
+
var PubspecSchema = z2.looseObject({
|
|
187
|
+
name: z2.unknown().optional(),
|
|
188
|
+
// a list or string is valid YAML but no Flutter app → dropped, read as pure Dart (step 5 F1)
|
|
189
|
+
dependencies: z2.record(z2.string(), z2.unknown()).nullable().optional().catch(void 0),
|
|
190
|
+
flutter: z2.unknown().optional()
|
|
191
|
+
});
|
|
192
|
+
|
|
193
|
+
// src/core/project.ts
|
|
194
|
+
async function readManifest(dir) {
|
|
195
|
+
let text;
|
|
196
|
+
try {
|
|
197
|
+
text = await readFile3(path3.join(dir, "package.json"), "utf8");
|
|
198
|
+
} catch (error) {
|
|
199
|
+
if (error.code === "ENOENT") return null;
|
|
200
|
+
throw error;
|
|
201
|
+
}
|
|
202
|
+
const invalid = (cause) => new MaestroError("INVALID_MANIFEST", "package.json is not valid JSON", {
|
|
203
|
+
hint: "Fix package.json, then run maestrokit init again.",
|
|
204
|
+
cause
|
|
205
|
+
});
|
|
206
|
+
let data;
|
|
207
|
+
try {
|
|
208
|
+
data = JSON.parse(text.replace(/^\uFEFF/, ""));
|
|
209
|
+
} catch (error) {
|
|
210
|
+
throw invalid(error);
|
|
211
|
+
}
|
|
212
|
+
const parsed = ProjectManifestSchema.safeParse(data);
|
|
213
|
+
if (!parsed.success) throw invalid(parsed.error);
|
|
214
|
+
return parsed.data;
|
|
215
|
+
}
|
|
216
|
+
async function readGit(dir) {
|
|
217
|
+
const result = await execa("git", ["rev-parse", "--show-prefix", "--git-path", "info/exclude"], {
|
|
218
|
+
cwd: dir,
|
|
219
|
+
reject: false
|
|
220
|
+
});
|
|
221
|
+
if (result.failed || result.exitCode !== 0) return null;
|
|
222
|
+
const [prefix = "", gitPath = ""] = result.stdout.split(/\r?\n/);
|
|
223
|
+
if (gitPath.trim() === "") return null;
|
|
224
|
+
return { excludePath: path3.resolve(dir, gitPath.trim()), prefix: prefix.trim() };
|
|
225
|
+
}
|
|
226
|
+
async function readProject(dir) {
|
|
227
|
+
const manifest = await readManifest(dir);
|
|
228
|
+
const git = await readGit(dir);
|
|
229
|
+
return { manifest, git };
|
|
230
|
+
}
|
|
231
|
+
async function readPubspec(dir) {
|
|
232
|
+
let text;
|
|
233
|
+
try {
|
|
234
|
+
text = await readFile3(path3.join(dir, "pubspec.yaml"), "utf8");
|
|
235
|
+
} catch (error) {
|
|
236
|
+
if (error.code === "ENOENT") return null;
|
|
237
|
+
throw error;
|
|
238
|
+
}
|
|
239
|
+
const invalid = (cause) => new MaestroError("INVALID_MANIFEST", "pubspec.yaml is not valid YAML", {
|
|
240
|
+
hint: "Fix pubspec.yaml, then run maestrokit init again.",
|
|
241
|
+
cause
|
|
242
|
+
});
|
|
243
|
+
let data;
|
|
244
|
+
try {
|
|
245
|
+
data = parse(text.replace(/^\uFEFF/, ""));
|
|
246
|
+
} catch (error) {
|
|
247
|
+
throw invalid(error);
|
|
248
|
+
}
|
|
249
|
+
if (data === null || data === void 0) return {};
|
|
250
|
+
if (typeof data !== "object" || Array.isArray(data)) throw invalid();
|
|
251
|
+
const parsed = PubspecSchema.safeParse(data);
|
|
252
|
+
if (!parsed.success) throw invalid(parsed.error);
|
|
253
|
+
return parsed.data;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
// src/core/select.ts
|
|
257
|
+
import path4 from "path";
|
|
258
|
+
function stackSkillNames(stack) {
|
|
259
|
+
const variant = stack.profile.variants[stack.variant];
|
|
260
|
+
return [...stack.profile.core_skills, ...variant?.extra_core_skills ?? [], ...variant?.task_skills ?? []];
|
|
261
|
+
}
|
|
262
|
+
function selectInstall(catalog, stack) {
|
|
263
|
+
const items = [
|
|
264
|
+
...catalog.commands.map((c) => ({ source: c.source, target: `.claude/commands/${path4.posix.basename(c.rel)}`, kind: "command" })),
|
|
265
|
+
...catalog.agents.map((a) => ({ source: a.source, target: `.claude/agents/${path4.posix.basename(a.rel)}`, kind: "agent" }))
|
|
266
|
+
];
|
|
267
|
+
const skills = new Set(catalog.processSkills.map((s) => s.name));
|
|
268
|
+
if (stack !== null) {
|
|
269
|
+
for (const name of stackSkillNames(stack)) {
|
|
270
|
+
if (!catalog.skillsByName.has(name)) {
|
|
271
|
+
throw new MaestroError("PACKAGE_CONTENT_INVALID", `Stack ${stack.id} names a missing skill "${name}"`);
|
|
272
|
+
}
|
|
273
|
+
skills.add(name);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
for (const name of skills) {
|
|
277
|
+
const skill = catalog.skillsByName.get(name);
|
|
278
|
+
if (skill !== void 0) items.push({ source: skill.dir, target: `.claude/skills/${name}`, kind: "skill" });
|
|
279
|
+
}
|
|
280
|
+
return items.sort((a, b) => a.target < b.target ? -1 : a.target > b.target ? 1 : 0);
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
// src/core/stack.ts
|
|
284
|
+
import { readFile as readFile4 } from "fs/promises";
|
|
285
|
+
import path5 from "path";
|
|
286
|
+
import { glob as glob2 } from "tinyglobby";
|
|
287
|
+
import { parse as parse2 } from "yaml";
|
|
288
|
+
|
|
289
|
+
// src/core/schemas/stack.ts
|
|
290
|
+
import { z as z3 } from "zod";
|
|
291
|
+
var StackProfileSchema = z3.looseObject({
|
|
292
|
+
id: z3.string(),
|
|
293
|
+
detect: z3.union([
|
|
294
|
+
z3.object({ manifest: z3.literal("package.json"), dependency: z3.string() }),
|
|
295
|
+
z3.object({ manifest: z3.literal("pubspec.yaml"), sdk: z3.enum(["flutter", "dart"]) })
|
|
296
|
+
]),
|
|
297
|
+
// Key order is the YAML order, which is the "first match wins" order of variant detection.
|
|
298
|
+
variants: z3.record(
|
|
299
|
+
z3.string(),
|
|
300
|
+
z3.looseObject({
|
|
301
|
+
detect: z3.union([
|
|
302
|
+
z3.object({ dependency: z3.string() }),
|
|
303
|
+
z3.object({ flutter_plugin: z3.literal(true) }),
|
|
304
|
+
z3.object({ otherwise: z3.literal(true) })
|
|
305
|
+
]),
|
|
306
|
+
extra_core_skills: z3.array(z3.string()).default([]),
|
|
307
|
+
task_skills: z3.array(z3.string()).default([]),
|
|
308
|
+
allow_commands: z3.array(z3.string()).default([])
|
|
309
|
+
})
|
|
310
|
+
),
|
|
311
|
+
core_skills: z3.array(z3.string()),
|
|
312
|
+
/** command prefixes init allows in `.claude/settings.local.json` (spec init-allowlist BR2) */
|
|
313
|
+
allow_commands: z3.array(z3.string()).default([]),
|
|
314
|
+
library_ecosystem: z3.enum(["npm", "pub"])
|
|
315
|
+
});
|
|
316
|
+
|
|
317
|
+
// src/core/stack.ts
|
|
318
|
+
var sources = /* @__PURE__ */ new WeakMap();
|
|
319
|
+
function profileSource(profile) {
|
|
320
|
+
return sources.get(profile);
|
|
321
|
+
}
|
|
322
|
+
async function loadStackProfiles(contentRoot) {
|
|
323
|
+
const files = [
|
|
324
|
+
...(await glob2("tech/frameworks/*/stack.yaml", { cwd: contentRoot })).sort(),
|
|
325
|
+
...(await glob2("tech/languages/*/stack.yaml", { cwd: contentRoot })).sort()
|
|
326
|
+
];
|
|
327
|
+
const profiles = [];
|
|
328
|
+
for (const file of files) {
|
|
329
|
+
const parsed = StackProfileSchema.safeParse(parse2(await readFile4(path5.join(contentRoot, file), "utf8")));
|
|
330
|
+
if (!parsed.success) {
|
|
331
|
+
throw new MaestroError("PACKAGE_CONTENT_INVALID", `Invalid stack profile ${file}`, { cause: parsed.error });
|
|
332
|
+
}
|
|
333
|
+
sources.set(parsed.data, path5.join(contentRoot, file));
|
|
334
|
+
profiles.push(parsed.data);
|
|
335
|
+
}
|
|
336
|
+
return profiles;
|
|
337
|
+
}
|
|
338
|
+
var isMapping2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
339
|
+
function pubspecKind(p) {
|
|
340
|
+
const flutterDep = isMapping2(p.dependencies) ? p.dependencies.flutter : void 0;
|
|
341
|
+
if (!isMapping2(flutterDep) || flutterDep.sdk !== "flutter") return "dart";
|
|
342
|
+
return isMapping2(p.flutter) && isMapping2(p.flutter.plugin) ? "plugin" : "app";
|
|
343
|
+
}
|
|
344
|
+
function firstVariant(profile, has, plugin = false) {
|
|
345
|
+
for (const [variant, spec] of Object.entries(profile.variants)) {
|
|
346
|
+
const d = spec.detect;
|
|
347
|
+
const hit = "otherwise" in d ? true : "flutter_plugin" in d ? plugin : has(d.dependency);
|
|
348
|
+
if (hit) return { id: profile.id, variant, profile };
|
|
349
|
+
}
|
|
350
|
+
return null;
|
|
351
|
+
}
|
|
352
|
+
function detectStack(manifest, profiles, pubspec = null) {
|
|
353
|
+
if (manifest !== null) {
|
|
354
|
+
const deps = { ...manifest.dependencies, ...manifest.devDependencies };
|
|
355
|
+
const has = (name) => Object.hasOwn(deps, name);
|
|
356
|
+
for (const profile of profiles) {
|
|
357
|
+
if (profile.detect.manifest !== "package.json" || !has(profile.detect.dependency)) continue;
|
|
358
|
+
const found = firstVariant(profile, has);
|
|
359
|
+
if (found !== null) return found;
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
if (pubspec !== null) {
|
|
363
|
+
const kind = pubspecKind(pubspec);
|
|
364
|
+
const sdk = kind === "dart" ? "dart" : "flutter";
|
|
365
|
+
for (const profile of profiles) {
|
|
366
|
+
if (profile.detect.manifest !== "pubspec.yaml" || profile.detect.sdk !== sdk) continue;
|
|
367
|
+
const found = firstVariant(profile, () => false, kind === "plugin");
|
|
368
|
+
if (found !== null) return found;
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
return null;
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
// src/core/install-set.ts
|
|
375
|
+
var MAESTROKIT_DIR = ".maestrokit";
|
|
376
|
+
var RECORD_PATH = `${MAESTROKIT_DIR}/install.json`;
|
|
377
|
+
var CONFIG_PATH = `${MAESTROKIT_DIR}/config.yml`;
|
|
378
|
+
var STACK_PATH = `${MAESTROKIT_DIR}/stack.yaml`;
|
|
379
|
+
var NO_GIT_WARNING = "not a git repository \u2014 files are not hidden from git";
|
|
380
|
+
var plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
|
|
381
|
+
var abs = (root, rel) => path6.join(root, ...rel.split("/"));
|
|
382
|
+
async function exists(p) {
|
|
383
|
+
try {
|
|
384
|
+
await lstat(p);
|
|
385
|
+
return true;
|
|
386
|
+
} catch {
|
|
387
|
+
return false;
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
async function filesUnder(dir) {
|
|
391
|
+
const entries = await readdir(dir, { recursive: true, withFileTypes: true });
|
|
392
|
+
return entries.filter((e) => e.isFile()).map((e) => path6.relative(dir, path6.join(e.parentPath, e.name)).split(path6.sep).join("/")).sort();
|
|
393
|
+
}
|
|
394
|
+
var byPath = (a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0;
|
|
395
|
+
function noStackWarning(manifest) {
|
|
396
|
+
const tail = "installed without stack skills";
|
|
397
|
+
if (manifest !== null) return `no React Native or Expo project found in package.json \u2014 ${tail}`;
|
|
398
|
+
return `no package.json or pubspec.yaml here \u2014 ${tail}`;
|
|
399
|
+
}
|
|
400
|
+
function basicSupportWarning(stack) {
|
|
401
|
+
if (stack.id === "flutter" && stack.variant === "plugin") return "Flutter plugins have basic support only (dart-core, flutter-testing)";
|
|
402
|
+
if (stack.id === "dart") return "pure Dart packages have basic support only (dart-core)";
|
|
403
|
+
return null;
|
|
404
|
+
}
|
|
405
|
+
var STACK_NAMES = { "react-native": "React Native", flutter: "Flutter", dart: "Dart" };
|
|
406
|
+
function stackLabel(stack) {
|
|
407
|
+
if (stack === null) return "none";
|
|
408
|
+
const name = STACK_NAMES[stack.id] ?? stack.id;
|
|
409
|
+
return `${name} (${stack.variant})`;
|
|
410
|
+
}
|
|
411
|
+
async function computeInstallSet(dir, contentRoot) {
|
|
412
|
+
const project = await readProject(dir);
|
|
413
|
+
const pubspec = await readPubspec(dir);
|
|
414
|
+
const stack = detectStack(project.manifest, await loadStackProfiles(contentRoot), pubspec);
|
|
415
|
+
const items = selectInstall(await loadCatalog(contentRoot), stack);
|
|
416
|
+
const warnings = [];
|
|
417
|
+
if (stack === null) {
|
|
418
|
+
warnings.push(noStackWarning(project.manifest));
|
|
419
|
+
} else {
|
|
420
|
+
const basic = basicSupportWarning(stack);
|
|
421
|
+
if (basic !== null) warnings.push(basic);
|
|
422
|
+
}
|
|
423
|
+
const files = [];
|
|
424
|
+
for (const item of items) {
|
|
425
|
+
if (item.kind === "skill") {
|
|
426
|
+
for (const rel of await filesUnder(item.source)) {
|
|
427
|
+
const source = abs(item.source, rel);
|
|
428
|
+
files.push({ path: `${item.target}/${rel}`, source, sha256: await sha256File(source) });
|
|
429
|
+
}
|
|
430
|
+
} else {
|
|
431
|
+
files.push({ path: item.target, source: item.source, sha256: await sha256File(item.source) });
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
const stackSource = stack === null ? void 0 : profileSource(stack.profile);
|
|
435
|
+
if (stackSource !== void 0) files.push({ path: STACK_PATH, source: stackSource, sha256: await sha256File(stackSource) });
|
|
436
|
+
files.sort(byPath);
|
|
437
|
+
return { project, stack, warnings, items, files, stackSource, allow: allowRules(stack) };
|
|
438
|
+
}
|
|
439
|
+
function excludeEntries(project, items, settingsPath) {
|
|
440
|
+
if (project.git === null) return null;
|
|
441
|
+
const prefix = `/${escapeGitPattern(project.git.prefix)}`;
|
|
442
|
+
return [
|
|
443
|
+
`${prefix}${MAESTROKIT_DIR}/`,
|
|
444
|
+
`${prefix}${escapeGitPattern(settingsPath)}`,
|
|
445
|
+
...items.map((i) => `${prefix}${i.target}${i.kind === "skill" ? "/" : ""}`)
|
|
446
|
+
];
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
// src/core/schemas/config.ts
|
|
450
|
+
import { z as z4 } from "zod";
|
|
451
|
+
var ConfigSchema = z4.strictObject({
|
|
452
|
+
keepSpecs: z4.number().int().min(0),
|
|
453
|
+
language: z4.union([z4.literal("auto"), z4.string().min(2)])
|
|
454
|
+
});
|
|
455
|
+
var DEFAULT_CONFIG = { keepSpecs: 0, language: "auto" };
|
|
456
|
+
|
|
457
|
+
// src/core/transaction.ts
|
|
458
|
+
import { mkdir, mkdtemp, rename, rm, rmdir } from "fs/promises";
|
|
459
|
+
import path7 from "path";
|
|
460
|
+
var STAGING_PREFIX = ".maestrokit-staging-";
|
|
461
|
+
var abs2 = (root, rel) => path7.join(root, ...rel.split("/"));
|
|
462
|
+
var REMOVE = { recursive: true, force: true, maxRetries: 5, retryDelay: 100 };
|
|
463
|
+
function rolledBack(error, signal, leftovers, restoreFailed) {
|
|
464
|
+
const hints = [];
|
|
465
|
+
if (leftovers.length > 0) hints.push("Some files could not be removed; delete them, then run maestrokit init again.");
|
|
466
|
+
if (restoreFailed !== null) hints.push(`The git exclude file could not be restored; restore it by hand: ${restoreFailed}`);
|
|
467
|
+
const clean = hints.length === 0;
|
|
468
|
+
if (error instanceof MaestroError && clean) return error;
|
|
469
|
+
const base = error instanceof MaestroError ? error : signal.aborted ? interrupted() : null;
|
|
470
|
+
const paths = [...base?.paths ?? [], ...leftovers, ...restoreFailed === null ? [] : [restoreFailed]];
|
|
471
|
+
return new MaestroError(base?.code ?? "WRITE_FAILED", base?.message ?? `Could not install: ${error.message}`, {
|
|
472
|
+
hint: clean ? "Nothing was changed. Fix the problem, then run maestrokit init again." : hints.join(" "),
|
|
473
|
+
paths,
|
|
474
|
+
cause: error
|
|
475
|
+
});
|
|
476
|
+
}
|
|
477
|
+
function interrupted() {
|
|
478
|
+
return new MaestroError("INTERRUPTED", "Interrupted \u2014 nothing was installed");
|
|
479
|
+
}
|
|
480
|
+
async function ensureParents(projectDir, target) {
|
|
481
|
+
const created = [];
|
|
482
|
+
const parts = target.split("/").slice(0, -1);
|
|
483
|
+
for (let i = 1; i <= parts.length; i += 1) {
|
|
484
|
+
const dir = abs2(projectDir, parts.slice(0, i).join("/"));
|
|
485
|
+
try {
|
|
486
|
+
await mkdir(dir);
|
|
487
|
+
created.push(dir);
|
|
488
|
+
} catch (error) {
|
|
489
|
+
if (error.code !== "EEXIST") throw error;
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
return created;
|
|
493
|
+
}
|
|
494
|
+
async function runTransaction(projectDir, items, signal, steps = {}) {
|
|
495
|
+
if (signal.aborted) throw interrupted();
|
|
496
|
+
const staging = await mkdtemp(path7.join(projectDir, STAGING_PREFIX));
|
|
497
|
+
const placed = [];
|
|
498
|
+
const createdDirs = [];
|
|
499
|
+
let afterPlaceStarted = false;
|
|
500
|
+
try {
|
|
501
|
+
for (const item of items) {
|
|
502
|
+
if (signal.aborted) throw interrupted();
|
|
503
|
+
const dest = abs2(staging, item.target);
|
|
504
|
+
await mkdir(path7.dirname(dest), { recursive: true });
|
|
505
|
+
await item.write(dest);
|
|
506
|
+
}
|
|
507
|
+
for (const item of items) {
|
|
508
|
+
if (signal.aborted) throw interrupted();
|
|
509
|
+
createdDirs.push(...await ensureParents(projectDir, item.target));
|
|
510
|
+
const dest = abs2(projectDir, item.target);
|
|
511
|
+
await rename(abs2(staging, item.target), dest);
|
|
512
|
+
placed.push(dest);
|
|
513
|
+
}
|
|
514
|
+
if (signal.aborted) throw interrupted();
|
|
515
|
+
afterPlaceStarted = true;
|
|
516
|
+
await steps.afterPlace?.();
|
|
517
|
+
} catch (error) {
|
|
518
|
+
const leftovers = [];
|
|
519
|
+
const rel = (p) => path7.relative(projectDir, p).split(path7.sep).join("/");
|
|
520
|
+
for (const dest of placed.reverse()) {
|
|
521
|
+
await rm(dest, REMOVE).catch(() => leftovers.push(rel(dest)));
|
|
522
|
+
}
|
|
523
|
+
for (const dir of createdDirs.reverse()) await rmdir(dir).catch(() => void 0);
|
|
524
|
+
let restoreFailed = null;
|
|
525
|
+
if (afterPlaceStarted && steps.onRollback !== void 0) {
|
|
526
|
+
await steps.onRollback().catch(() => {
|
|
527
|
+
restoreFailed = steps.rollbackTarget ?? "git exclude file";
|
|
528
|
+
});
|
|
529
|
+
}
|
|
530
|
+
await rm(staging, REMOVE).catch(() => leftovers.push(`${rel(staging)}/`));
|
|
531
|
+
throw rolledBack(error, signal, leftovers, restoreFailed);
|
|
532
|
+
}
|
|
533
|
+
await rm(staging, REMOVE).catch(() => void 0);
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
// src/lib/output.ts
|
|
537
|
+
var symbols = { success: "\u2714", warning: "\u26A0", error: "\u2716" };
|
|
538
|
+
function isInteractive(io) {
|
|
539
|
+
return io.stdin.isTTY === true && io.stdout.isTTY === true;
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
// src/commands/init.ts
|
|
543
|
+
var DONE_LINE = "Done. Type `/mk-feat <description>` to start.";
|
|
544
|
+
async function runInit(o) {
|
|
545
|
+
const dir = o.cwd;
|
|
546
|
+
const now = o.now ?? (() => /* @__PURE__ */ new Date());
|
|
547
|
+
if (await exists(abs(dir, MAESTROKIT_DIR))) {
|
|
548
|
+
throw new MaestroError("ALREADY_INSTALLED", "maestrokit is already installed here", {
|
|
549
|
+
hint: "Nothing was changed."
|
|
550
|
+
});
|
|
551
|
+
}
|
|
552
|
+
if (o.signal.aborted) throw new MaestroError("INTERRUPTED", "Interrupted \u2014 nothing was installed");
|
|
553
|
+
const set = await computeInstallSet(dir, o.contentRoot ?? o.pkg.root);
|
|
554
|
+
const { project, stack, items, stackSource } = set;
|
|
555
|
+
const collisions = [];
|
|
556
|
+
for (const item of items) {
|
|
557
|
+
if (await exists(abs(dir, item.target))) collisions.push(item.kind === "skill" ? `${item.target}/` : item.target);
|
|
558
|
+
}
|
|
559
|
+
if (collisions.length > 0) {
|
|
560
|
+
throw new MaestroError("PATH_COLLISION", "These files already exist:", {
|
|
561
|
+
paths: collisions,
|
|
562
|
+
hint: "Move or rename them, then run maestrokit init again. Nothing was changed."
|
|
563
|
+
});
|
|
564
|
+
}
|
|
565
|
+
const warnings = [...set.warnings];
|
|
566
|
+
if (project.git === null) warnings.push(NO_GIT_WARNING);
|
|
567
|
+
const settingsPlan = await planSettings(dir, set.allow);
|
|
568
|
+
if (settingsPlan.kind === "skip") warnings.push(settingsPlan.warning);
|
|
569
|
+
const settingsAbs = abs(dir, settingsPlan.path);
|
|
570
|
+
const configText = stringify(DEFAULT_CONFIG);
|
|
571
|
+
const excludeEntries2 = excludeEntries(project, items, settingsPlan.path);
|
|
572
|
+
const files = set.files.map((f) => ({ path: f.path, sha256: f.sha256 }));
|
|
573
|
+
const record = {
|
|
574
|
+
recordVersion: 1,
|
|
575
|
+
packageVersion: o.pkg.version,
|
|
576
|
+
installedAt: now().toISOString(),
|
|
577
|
+
stack: stack === null ? null : { id: stack.id, variant: stack.variant },
|
|
578
|
+
files,
|
|
579
|
+
excludeEntries: excludeEntries2,
|
|
580
|
+
settings: settingsPlan.kind === "skip" ? null : {
|
|
581
|
+
path: settingsPlan.path,
|
|
582
|
+
created: settingsPlan.kind === "write" && settingsPlan.before === null,
|
|
583
|
+
added: settingsPlan.kind === "write" ? settingsPlan.added : []
|
|
584
|
+
}
|
|
585
|
+
};
|
|
586
|
+
const configRel = `${MAESTROKIT_DIR}/config.yml`;
|
|
587
|
+
const staged = [
|
|
588
|
+
...items.map((item) => ({
|
|
589
|
+
target: item.target,
|
|
590
|
+
write: (dest) => item.kind === "skill" ? cp(item.source, dest, { recursive: true }) : copyFile(item.source, dest)
|
|
591
|
+
})),
|
|
592
|
+
{
|
|
593
|
+
// Placed last: its presence means "installed" (P4).
|
|
594
|
+
target: MAESTROKIT_DIR,
|
|
595
|
+
write: async (dest) => {
|
|
596
|
+
await mkdir2(dest, { recursive: true });
|
|
597
|
+
await writeFile(path8.join(dest, "config.yml"), configText);
|
|
598
|
+
if (stackSource !== void 0) await copyFile(stackSource, path8.join(dest, "stack.yaml"));
|
|
599
|
+
const withConfig = { ...record, files: [...record.files] };
|
|
600
|
+
withConfig.files.push({ path: configRel, sha256: await sha256File(path8.join(dest, "config.yml")) });
|
|
601
|
+
withConfig.files.sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
|
|
602
|
+
await writeFile(path8.join(dest, "install.json"), `${JSON.stringify(withConfig, null, 2)}
|
|
603
|
+
`);
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
];
|
|
607
|
+
let excludeBefore = null;
|
|
608
|
+
let createdExcludeDir;
|
|
609
|
+
let excludeTouched = false;
|
|
610
|
+
const git = project.git;
|
|
611
|
+
let settingsTouched = false;
|
|
612
|
+
const claudeDirExisted = await exists(abs(dir, ".claude"));
|
|
613
|
+
const writeExclude = async () => {
|
|
614
|
+
if (git === null || excludeEntries2 === null) return;
|
|
615
|
+
try {
|
|
616
|
+
excludeBefore = await readFile5(git.excludePath, "utf8");
|
|
617
|
+
} catch (error) {
|
|
618
|
+
if (error.code !== "ENOENT") throw error;
|
|
619
|
+
}
|
|
620
|
+
createdExcludeDir = await mkdir2(path8.dirname(git.excludePath), { recursive: true });
|
|
621
|
+
excludeTouched = true;
|
|
622
|
+
await writeFile(git.excludePath, upsertExcludeBlock(excludeBefore ?? "", excludeEntries2));
|
|
623
|
+
};
|
|
624
|
+
const restoreExclude = async () => {
|
|
625
|
+
if (git === null) return;
|
|
626
|
+
if (!excludeTouched) return;
|
|
627
|
+
if (excludeBefore !== null) {
|
|
628
|
+
await writeFile(git.excludePath, excludeBefore);
|
|
629
|
+
return;
|
|
630
|
+
}
|
|
631
|
+
await rm2(git.excludePath, { force: true });
|
|
632
|
+
if (createdExcludeDir === void 0) return;
|
|
633
|
+
for (let dir2 = path8.dirname(git.excludePath); ; dir2 = path8.dirname(dir2)) {
|
|
634
|
+
await rmdir2(dir2).catch(() => void 0);
|
|
635
|
+
if (dir2 === createdExcludeDir || path8.dirname(dir2) === dir2) break;
|
|
636
|
+
}
|
|
637
|
+
};
|
|
638
|
+
await runTransaction(dir, staged, o.signal, {
|
|
639
|
+
afterPlace: async () => {
|
|
640
|
+
await writeExclude();
|
|
641
|
+
if (settingsPlan.kind !== "write") return;
|
|
642
|
+
settingsTouched = true;
|
|
643
|
+
await mkdir2(path8.dirname(settingsAbs), { recursive: true });
|
|
644
|
+
await writeFile(settingsAbs, settingsPlan.text);
|
|
645
|
+
},
|
|
646
|
+
onRollback: async () => {
|
|
647
|
+
if (settingsTouched && settingsPlan.kind === "write") {
|
|
648
|
+
if (settingsPlan.before === null) {
|
|
649
|
+
await rm2(settingsAbs, { force: true });
|
|
650
|
+
if (!claudeDirExisted) await rmdir2(path8.dirname(settingsAbs)).catch(() => void 0);
|
|
651
|
+
} else await writeFile(settingsAbs, settingsPlan.before);
|
|
652
|
+
}
|
|
653
|
+
await restoreExclude();
|
|
654
|
+
},
|
|
655
|
+
...git === null ? {} : { rollbackTarget: git.excludePath }
|
|
656
|
+
});
|
|
657
|
+
const counts = {
|
|
658
|
+
commands: items.filter((i) => i.kind === "command").length,
|
|
659
|
+
agents: items.filter((i) => i.kind === "agent").length,
|
|
660
|
+
skills: items.filter((i) => i.kind === "skill").length
|
|
661
|
+
};
|
|
662
|
+
for (const w of warnings) o.io.stderr.write(`${symbols.warning} ${w}
|
|
663
|
+
`);
|
|
664
|
+
o.io.stdout.write(
|
|
665
|
+
[
|
|
666
|
+
`${symbols.success} maestrokit ${o.pkg.version} installed`,
|
|
667
|
+
` Stack: ${stackLabel(stack)}`,
|
|
668
|
+
` ${plural(counts.commands, "command")} \xB7 ${plural(counts.agents, "agent")} \xB7 ${plural(counts.skills, "skill")}`,
|
|
669
|
+
...settingsPlan.kind === "write" ? [` ${plural(settingsPlan.added.length, "command rule")} added to ${settingsPlan.path}`] : [],
|
|
670
|
+
DONE_LINE,
|
|
671
|
+
""
|
|
672
|
+
].join("\n")
|
|
673
|
+
);
|
|
674
|
+
return { stack: record.stack, counts, warnings, excludePath: git?.excludePath ?? null };
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
// src/commands/uninstall.ts
|
|
678
|
+
import { readFile as readFile7, writeFile as writeFile3 } from "fs/promises";
|
|
679
|
+
import path10 from "path";
|
|
680
|
+
import { confirm, isCancel } from "@clack/prompts";
|
|
681
|
+
|
|
682
|
+
// src/core/file-changes.ts
|
|
683
|
+
import { copyFile as copyFile2, lstat as lstat2, mkdir as mkdir3, rename as rename2, rm as rm3, rmdir as rmdir3, writeFile as writeFile2 } from "fs/promises";
|
|
684
|
+
import path9 from "path";
|
|
685
|
+
async function present(p) {
|
|
686
|
+
try {
|
|
687
|
+
await lstat2(p);
|
|
688
|
+
return true;
|
|
689
|
+
} catch {
|
|
690
|
+
return false;
|
|
691
|
+
}
|
|
692
|
+
}
|
|
693
|
+
var FileChanges = class {
|
|
694
|
+
constructor(projectDir) {
|
|
695
|
+
this.projectDir = projectDir;
|
|
696
|
+
this.backupDir = path9.join(projectDir, `.maestrokit-backup-${String(process.pid)}`);
|
|
697
|
+
}
|
|
698
|
+
projectDir;
|
|
699
|
+
backupDir;
|
|
700
|
+
undo = [];
|
|
701
|
+
backups = 0;
|
|
702
|
+
abs(rel) {
|
|
703
|
+
return path9.join(this.projectDir, ...rel.split("/"));
|
|
704
|
+
}
|
|
705
|
+
/** Creates the missing parent folders of `target`, remembering them for rollback. */
|
|
706
|
+
async parents(target) {
|
|
707
|
+
const missing = [];
|
|
708
|
+
for (let dir = path9.dirname(target); dir !== this.projectDir && !await present(dir); dir = path9.dirname(dir)) {
|
|
709
|
+
missing.push(dir);
|
|
710
|
+
if (path9.dirname(dir) === dir) break;
|
|
711
|
+
}
|
|
712
|
+
await mkdir3(path9.dirname(target), { recursive: true });
|
|
713
|
+
for (const dir of missing.reverse()) this.undo.push({ kind: "rmdir", target: dir });
|
|
714
|
+
}
|
|
715
|
+
/** Moves an existing path into the backup folder and records how to put it back. */
|
|
716
|
+
async stash(target) {
|
|
717
|
+
if (!await present(target)) return;
|
|
718
|
+
this.backups += 1;
|
|
719
|
+
const backup = path9.join(this.backupDir, String(this.backups));
|
|
720
|
+
await mkdir3(this.backupDir, { recursive: true });
|
|
721
|
+
await rename2(target, backup);
|
|
722
|
+
this.undo.push({ kind: "restore", target, backup });
|
|
723
|
+
}
|
|
724
|
+
async put(rel, write) {
|
|
725
|
+
const target = this.abs(rel);
|
|
726
|
+
await this.stash(target);
|
|
727
|
+
await this.parents(target);
|
|
728
|
+
this.undo.push({ kind: "remove", target });
|
|
729
|
+
await write(target);
|
|
730
|
+
}
|
|
731
|
+
/** Copies `source` to `rel`; the old file, if any, is kept for rollback. */
|
|
732
|
+
async write(rel, source) {
|
|
733
|
+
await this.put(rel, (target) => copyFile2(source, target));
|
|
734
|
+
}
|
|
735
|
+
/** Writes `text` to `rel`; the old file, if any, is kept for rollback. */
|
|
736
|
+
async writeText(rel, text) {
|
|
737
|
+
await this.put(rel, (target) => writeFile2(target, text));
|
|
738
|
+
}
|
|
739
|
+
/** Removes a file (moved to the backup, restored on rollback). */
|
|
740
|
+
async remove(rel) {
|
|
741
|
+
await this.stash(this.abs(rel));
|
|
742
|
+
}
|
|
743
|
+
/** Removes a whole folder with everything in it (moved to the backup, restored on rollback). */
|
|
744
|
+
async removeDir(rel) {
|
|
745
|
+
await this.stash(this.abs(rel));
|
|
746
|
+
}
|
|
747
|
+
/** Removes a folder only when it is empty; a folder that still holds files is left alone. */
|
|
748
|
+
async removeDirIfEmpty(rel) {
|
|
749
|
+
const target = this.abs(rel);
|
|
750
|
+
try {
|
|
751
|
+
await rmdir3(target);
|
|
752
|
+
} catch {
|
|
753
|
+
return false;
|
|
754
|
+
}
|
|
755
|
+
this.undo.push({ kind: "mkdir", target });
|
|
756
|
+
return true;
|
|
757
|
+
}
|
|
758
|
+
/** Keeps the changes: the backup folder is deleted. */
|
|
759
|
+
async commit() {
|
|
760
|
+
await rm3(this.backupDir, { recursive: true, force: true });
|
|
761
|
+
this.undo.length = 0;
|
|
762
|
+
}
|
|
763
|
+
/** Undoes every change, newest first; returns the paths it could not restore. */
|
|
764
|
+
async rollback() {
|
|
765
|
+
const failed = [];
|
|
766
|
+
for (const step of this.undo.reverse()) {
|
|
767
|
+
try {
|
|
768
|
+
if (step.kind === "remove") await rm3(step.target, { recursive: true, force: true });
|
|
769
|
+
else if (step.kind === "rmdir") await rmdir3(step.target).catch(() => void 0);
|
|
770
|
+
else if (step.kind === "mkdir") await mkdir3(step.target, { recursive: true });
|
|
771
|
+
else {
|
|
772
|
+
await mkdir3(path9.dirname(step.target), { recursive: true });
|
|
773
|
+
await rename2(step.backup, step.target);
|
|
774
|
+
}
|
|
775
|
+
} catch {
|
|
776
|
+
failed.push(step.target);
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
this.undo.length = 0;
|
|
780
|
+
if (failed.length === 0) await rm3(this.backupDir, { recursive: true, force: true });
|
|
781
|
+
return failed;
|
|
782
|
+
}
|
|
783
|
+
};
|
|
784
|
+
|
|
785
|
+
// src/core/install-record.ts
|
|
786
|
+
import { readFile as readFile6 } from "fs/promises";
|
|
787
|
+
|
|
788
|
+
// src/core/schemas/record.ts
|
|
789
|
+
import { z as z5 } from "zod";
|
|
790
|
+
var InstallRecordSchema = z5.strictObject({
|
|
791
|
+
recordVersion: z5.literal(1),
|
|
792
|
+
packageVersion: z5.string(),
|
|
793
|
+
installedAt: z5.iso.datetime(),
|
|
794
|
+
stack: z5.strictObject({ id: z5.string(), variant: z5.string() }).nullable(),
|
|
795
|
+
/** Every installed file except install.json, project-relative POSIX, sorted. */
|
|
796
|
+
files: z5.array(z5.strictObject({ path: z5.string(), sha256: z5.string().regex(/^[0-9a-f]{64}$/) })),
|
|
797
|
+
/** The lines inside the exclude block; null without git. */
|
|
798
|
+
excludeEntries: z5.array(z5.string()).nullable(),
|
|
799
|
+
/** Command rules init added to `.claude/settings.local.json`; null when the file was invalid (spec init-allowlist BR5). */
|
|
800
|
+
settings: z5.strictObject({ path: z5.string(), created: z5.boolean(), added: z5.array(z5.string()) }).nullable().optional()
|
|
801
|
+
});
|
|
802
|
+
|
|
803
|
+
// src/core/install-record.ts
|
|
804
|
+
async function readInstallRecord(dir) {
|
|
805
|
+
const notInstalled = (cause) => new MaestroError("NOT_INSTALLED", `maestrokit is not installed here (no ${RECORD_PATH})`, {
|
|
806
|
+
hint: "Run maestrokit init first.",
|
|
807
|
+
...cause === void 0 ? {} : { cause }
|
|
808
|
+
});
|
|
809
|
+
let text;
|
|
810
|
+
try {
|
|
811
|
+
text = await readFile6(abs(dir, RECORD_PATH), "utf8");
|
|
812
|
+
} catch (error) {
|
|
813
|
+
throw notInstalled(error);
|
|
814
|
+
}
|
|
815
|
+
let data;
|
|
816
|
+
try {
|
|
817
|
+
data = JSON.parse(text);
|
|
818
|
+
} catch (error) {
|
|
819
|
+
throw notInstalled(error);
|
|
820
|
+
}
|
|
821
|
+
const parsed = InstallRecordSchema.safeParse(data);
|
|
822
|
+
if (!parsed.success) throw notInstalled(parsed.error);
|
|
823
|
+
return parsed.data;
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
// src/commands/uninstall.ts
|
|
827
|
+
var CONFIRM_QUESTION = "Remove maestrokit and .maestrokit/ (knowledge tree, specs)?";
|
|
828
|
+
function folders(rel) {
|
|
829
|
+
const out = [];
|
|
830
|
+
for (let dir = path10.posix.dirname(rel); dir !== "." && dir !== ""; dir = path10.posix.dirname(dir)) out.push(dir);
|
|
831
|
+
return out;
|
|
832
|
+
}
|
|
833
|
+
async function confirmed(o) {
|
|
834
|
+
if (o.yes) return;
|
|
835
|
+
if (!isInteractive(o.io)) {
|
|
836
|
+
throw new MaestroError("CONFIRMATION_REQUIRED", "Refusing to remove without confirmation", {
|
|
837
|
+
hint: "Run maestrokit uninstall --yes in scripts."
|
|
838
|
+
});
|
|
839
|
+
}
|
|
840
|
+
const answer = await confirm({ message: CONFIRM_QUESTION, initialValue: false });
|
|
841
|
+
if (isCancel(answer) || !answer) {
|
|
842
|
+
throw new MaestroError("CONFIRMATION_REQUIRED", "Nothing was removed.");
|
|
843
|
+
}
|
|
844
|
+
}
|
|
845
|
+
async function runUninstall(o) {
|
|
846
|
+
const dir = o.cwd;
|
|
847
|
+
const record = await readInstallRecord(dir);
|
|
848
|
+
await confirmed(o);
|
|
849
|
+
if (o.signal.aborted) throw new MaestroError("INTERRUPTED", "Interrupted \u2014 nothing was removed");
|
|
850
|
+
const outside = record.files.filter((f) => !f.path.startsWith(`${MAESTROKIT_DIR}/`));
|
|
851
|
+
const modified = [];
|
|
852
|
+
const present3 = [];
|
|
853
|
+
for (const f of outside) {
|
|
854
|
+
let sha;
|
|
855
|
+
try {
|
|
856
|
+
sha = await sha256File(abs(dir, f.path));
|
|
857
|
+
} catch {
|
|
858
|
+
continue;
|
|
859
|
+
}
|
|
860
|
+
present3.push(f.path);
|
|
861
|
+
if (sha !== f.sha256) modified.push(f.path);
|
|
862
|
+
}
|
|
863
|
+
const settingsPlan = await planSettingsRemoval(dir, record.settings);
|
|
864
|
+
const rulesRemoved = settingsPlan.kind === "none" ? 0 : record.settings?.added.length ?? 0;
|
|
865
|
+
const project = await readProject(dir);
|
|
866
|
+
const git = project.git;
|
|
867
|
+
const changes = new FileChanges(dir);
|
|
868
|
+
let excludeBefore;
|
|
869
|
+
const check = () => {
|
|
870
|
+
if (o.signal.aborted) throw new MaestroError("INTERRUPTED", "Interrupted \u2014 nothing was removed");
|
|
871
|
+
};
|
|
872
|
+
try {
|
|
873
|
+
for (const rel of present3) {
|
|
874
|
+
check();
|
|
875
|
+
await changes.remove(rel);
|
|
876
|
+
}
|
|
877
|
+
if (settingsPlan.kind === "write") await changes.writeText(record.settings?.path ?? "", settingsPlan.text);
|
|
878
|
+
if (settingsPlan.kind === "delete" && record.settings) await changes.remove(record.settings.path);
|
|
879
|
+
const touched = [...present3, ...settingsPlan.kind === "delete" && record.settings ? [record.settings.path] : []];
|
|
880
|
+
const emptied = [...new Set(touched.flatMap(folders))].sort((a, b) => b.length - a.length);
|
|
881
|
+
for (const folder of emptied) {
|
|
882
|
+
if (folder === ".claude" || folder.startsWith(".claude/")) await changes.removeDirIfEmpty(folder);
|
|
883
|
+
}
|
|
884
|
+
check();
|
|
885
|
+
await changes.removeDir(MAESTROKIT_DIR);
|
|
886
|
+
if (git !== null) {
|
|
887
|
+
excludeBefore = await readFile7(git.excludePath, "utf8").catch(() => null);
|
|
888
|
+
if (excludeBefore !== null) await writeFile3(git.excludePath, removeExcludeBlock(excludeBefore));
|
|
889
|
+
}
|
|
890
|
+
check();
|
|
891
|
+
await changes.commit();
|
|
892
|
+
} catch (error) {
|
|
893
|
+
const failed = await changes.rollback();
|
|
894
|
+
if (git !== null && typeof excludeBefore === "string") {
|
|
895
|
+
const text = excludeBefore;
|
|
896
|
+
await writeFile3(git.excludePath, text).catch(() => failed.push(git.excludePath));
|
|
897
|
+
}
|
|
898
|
+
if (error instanceof MaestroError && error.code === "INTERRUPTED" && failed.length === 0) throw error;
|
|
899
|
+
throw new MaestroError("WRITE_FAILED", "Uninstall failed \u2014 the previous files were restored", {
|
|
900
|
+
paths: failed,
|
|
901
|
+
...failed.length > 0 ? { hint: "These could not be restored; fix them by hand." } : {},
|
|
902
|
+
cause: error
|
|
903
|
+
});
|
|
904
|
+
}
|
|
905
|
+
const excludeRemoved = typeof excludeBefore === "string" && removeExcludeBlock(excludeBefore) !== excludeBefore;
|
|
906
|
+
const parts = [plural(present3.length, "file"), `${MAESTROKIT_DIR}/`, ...excludeRemoved ? ["exclude block"] : [], plural(rulesRemoved, "command rule")];
|
|
907
|
+
const lines = [`${symbols.success} maestrokit removed`, ` ${parts.join(" \xB7 ")}`, ...modified.map((p) => ` removed although you changed it: ${p}`)];
|
|
908
|
+
o.io.stdout.write(`${lines.join("\n")}
|
|
909
|
+
`);
|
|
910
|
+
return { files: present3.length, modified, rulesRemoved, excludeRemoved };
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
// src/commands/update.ts
|
|
914
|
+
import { mkdir as mkdir4, readFile as readFile8, rm as rm4, writeFile as writeFile4 } from "fs/promises";
|
|
915
|
+
import path11 from "path";
|
|
916
|
+
var byPath2 = (a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0;
|
|
917
|
+
async function diskSha(dir, rel) {
|
|
918
|
+
try {
|
|
919
|
+
return await sha256File(abs(dir, rel));
|
|
920
|
+
} catch {
|
|
921
|
+
return null;
|
|
922
|
+
}
|
|
923
|
+
}
|
|
924
|
+
function folders2(rel) {
|
|
925
|
+
const out = [];
|
|
926
|
+
for (let dir = path11.posix.dirname(rel); dir !== "." && dir !== ""; dir = path11.posix.dirname(dir)) out.push(dir);
|
|
927
|
+
return out;
|
|
928
|
+
}
|
|
929
|
+
async function runUpdate(o) {
|
|
930
|
+
const dir = o.cwd;
|
|
931
|
+
const now = o.now ?? (() => /* @__PURE__ */ new Date());
|
|
932
|
+
const record = await readInstallRecord(dir);
|
|
933
|
+
if (o.signal.aborted) throw new MaestroError("INTERRUPTED", "Interrupted \u2014 nothing was changed");
|
|
934
|
+
const set = await computeInstallSet(dir, o.contentRoot ?? o.pkg.root);
|
|
935
|
+
const recorded = new Map(record.files.map((f) => [f.path, f]));
|
|
936
|
+
const target = new Map(set.files.map((f) => [f.path, f]));
|
|
937
|
+
const updated = [];
|
|
938
|
+
const added = [];
|
|
939
|
+
const removed = [];
|
|
940
|
+
const kept = [];
|
|
941
|
+
const conflicts = [];
|
|
942
|
+
const nextFiles = [];
|
|
943
|
+
for (const file of set.files) {
|
|
944
|
+
const old = recorded.get(file.path);
|
|
945
|
+
const onDisk = await diskSha(dir, file.path);
|
|
946
|
+
if (old !== void 0) {
|
|
947
|
+
const userChanged = onDisk !== null && onDisk !== old.sha256;
|
|
948
|
+
if (userChanged && !o.force) {
|
|
949
|
+
kept.push(file.path);
|
|
950
|
+
nextFiles.push(old);
|
|
951
|
+
continue;
|
|
952
|
+
}
|
|
953
|
+
if (onDisk !== file.sha256) (onDisk === null ? added : updated).push(file);
|
|
954
|
+
nextFiles.push({ path: file.path, sha256: file.sha256 });
|
|
955
|
+
continue;
|
|
956
|
+
}
|
|
957
|
+
if (onDisk !== null && onDisk !== file.sha256 && !o.force) {
|
|
958
|
+
conflicts.push(file.path);
|
|
959
|
+
continue;
|
|
960
|
+
}
|
|
961
|
+
if (onDisk !== file.sha256) added.push(file);
|
|
962
|
+
nextFiles.push({ path: file.path, sha256: file.sha256 });
|
|
963
|
+
}
|
|
964
|
+
for (const old of record.files) {
|
|
965
|
+
if (target.has(old.path) || old.path === CONFIG_PATH) continue;
|
|
966
|
+
const onDisk = await diskSha(dir, old.path);
|
|
967
|
+
if (onDisk === null) continue;
|
|
968
|
+
if (onDisk !== old.sha256 && !o.force) {
|
|
969
|
+
kept.push(old.path);
|
|
970
|
+
nextFiles.push(old);
|
|
971
|
+
continue;
|
|
972
|
+
}
|
|
973
|
+
removed.push(old.path);
|
|
974
|
+
}
|
|
975
|
+
const config = recorded.get(CONFIG_PATH);
|
|
976
|
+
if (config !== void 0) nextFiles.push(config);
|
|
977
|
+
nextFiles.sort(byPath2);
|
|
978
|
+
kept.sort();
|
|
979
|
+
const settingsPlan = await planSettings(dir, set.allow);
|
|
980
|
+
const excludeEntries2 = excludeEntries(set.project, set.items, settingsPlan.path);
|
|
981
|
+
const sameStack = JSON.stringify(record.stack) === JSON.stringify(set.stack === null ? null : { id: set.stack.id, variant: set.stack.variant });
|
|
982
|
+
const sameExclude = JSON.stringify(record.excludeEntries) === JSON.stringify(excludeEntries2);
|
|
983
|
+
const nothingToDo = record.packageVersion === o.pkg.version && sameStack && sameExclude && updated.length === 0 && added.length === 0 && removed.length === 0 && settingsPlan.kind !== "write";
|
|
984
|
+
const summary = {
|
|
985
|
+
from: record.packageVersion,
|
|
986
|
+
to: o.pkg.version,
|
|
987
|
+
stack: set.stack === null ? null : { id: set.stack.id, variant: set.stack.variant },
|
|
988
|
+
updated: updated.map((f) => f.path),
|
|
989
|
+
added: added.map((f) => f.path),
|
|
990
|
+
removed,
|
|
991
|
+
kept,
|
|
992
|
+
conflicts
|
|
993
|
+
};
|
|
994
|
+
if (nothingToDo) {
|
|
995
|
+
o.io.stdout.write(`Already up to date (maestrokit ${o.pkg.version}).
|
|
996
|
+
`);
|
|
997
|
+
return { ...summary, upToDate: true };
|
|
998
|
+
}
|
|
999
|
+
const previous2 = record.settings ?? null;
|
|
1000
|
+
const settings = settingsPlan.kind === "skip" ? previous2 ?? null : {
|
|
1001
|
+
path: settingsPlan.path,
|
|
1002
|
+
created: previous2?.created ?? (settingsPlan.kind === "write" && settingsPlan.before === null),
|
|
1003
|
+
added: [.../* @__PURE__ */ new Set([...previous2?.added ?? [], ...settingsPlan.kind === "write" ? settingsPlan.added : []])]
|
|
1004
|
+
};
|
|
1005
|
+
const nextRecord = {
|
|
1006
|
+
recordVersion: 1,
|
|
1007
|
+
packageVersion: o.pkg.version,
|
|
1008
|
+
installedAt: now().toISOString(),
|
|
1009
|
+
stack: summary.stack,
|
|
1010
|
+
files: nextFiles,
|
|
1011
|
+
excludeEntries: excludeEntries2,
|
|
1012
|
+
settings
|
|
1013
|
+
};
|
|
1014
|
+
const changes = new FileChanges(dir);
|
|
1015
|
+
const git = set.project.git;
|
|
1016
|
+
let excludeBefore;
|
|
1017
|
+
const check = () => {
|
|
1018
|
+
if (o.signal.aborted) throw new MaestroError("INTERRUPTED", "Interrupted \u2014 nothing was changed");
|
|
1019
|
+
};
|
|
1020
|
+
try {
|
|
1021
|
+
for (const file of [...updated, ...added]) {
|
|
1022
|
+
check();
|
|
1023
|
+
await changes.write(file.path, file.source);
|
|
1024
|
+
}
|
|
1025
|
+
for (const rel of removed) {
|
|
1026
|
+
check();
|
|
1027
|
+
await changes.remove(rel);
|
|
1028
|
+
}
|
|
1029
|
+
const emptied = [...new Set(removed.flatMap(folders2))].sort((a, b) => b.length - a.length);
|
|
1030
|
+
for (const folder of emptied) {
|
|
1031
|
+
if (folder.startsWith(".claude/") || folder.startsWith(".maestrokit/")) await changes.removeDirIfEmpty(folder);
|
|
1032
|
+
}
|
|
1033
|
+
if (settingsPlan.kind === "write") await changes.writeText(settingsPlan.path, settingsPlan.text);
|
|
1034
|
+
check();
|
|
1035
|
+
if (git !== null && excludeEntries2 !== null) {
|
|
1036
|
+
excludeBefore = await readFile8(git.excludePath, "utf8").catch(() => null);
|
|
1037
|
+
await mkdir4(path11.dirname(git.excludePath), { recursive: true });
|
|
1038
|
+
await writeFile4(git.excludePath, upsertExcludeBlock(excludeBefore ?? "", excludeEntries2));
|
|
1039
|
+
}
|
|
1040
|
+
await changes.writeText(RECORD_PATH, `${JSON.stringify(nextRecord, null, 2)}
|
|
1041
|
+
`);
|
|
1042
|
+
check();
|
|
1043
|
+
await changes.commit();
|
|
1044
|
+
} catch (error) {
|
|
1045
|
+
const failed = await changes.rollback();
|
|
1046
|
+
if (git !== null && excludeBefore !== void 0) {
|
|
1047
|
+
const undo = excludeBefore === null ? rm4(git.excludePath, { force: true }) : writeFile4(git.excludePath, excludeBefore);
|
|
1048
|
+
await undo.catch(() => failed.push(git.excludePath));
|
|
1049
|
+
}
|
|
1050
|
+
if (error instanceof MaestroError && error.code === "INTERRUPTED" && failed.length === 0) throw error;
|
|
1051
|
+
throw new MaestroError("WRITE_FAILED", "Update failed \u2014 the previous files were restored", {
|
|
1052
|
+
paths: failed,
|
|
1053
|
+
...failed.length > 0 ? { hint: "These could not be restored; fix them by hand." } : {},
|
|
1054
|
+
cause: error
|
|
1055
|
+
});
|
|
1056
|
+
}
|
|
1057
|
+
const lines = [
|
|
1058
|
+
`${symbols.success} maestrokit ${summary.from} \u2192 ${summary.to} updated`,
|
|
1059
|
+
` Stack: ${stackLabel(summary.stack)}`,
|
|
1060
|
+
` ${String(updated.length)} updated \xB7 ${String(added.length)} added \xB7 ${String(removed.length)} removed`,
|
|
1061
|
+
...kept.map((p) => ` kept (you changed it): ${p}`),
|
|
1062
|
+
...conflicts.map((p) => ` kept (not installed by maestrokit): ${p}`)
|
|
1063
|
+
];
|
|
1064
|
+
if (kept.length > 0 || conflicts.length > 0) lines.push("Run maestrokit update --force to replace them.");
|
|
1065
|
+
for (const w of set.warnings) o.io.stderr.write(`${symbols.warning} ${w}
|
|
1066
|
+
`);
|
|
1067
|
+
if (settingsPlan.kind === "skip") o.io.stderr.write(`${symbols.warning} ${settingsPlan.warning}
|
|
1068
|
+
`);
|
|
1069
|
+
o.io.stdout.write(`${lines.join("\n")}
|
|
1070
|
+
`);
|
|
1071
|
+
return { ...summary, upToDate: false };
|
|
1072
|
+
}
|
|
1073
|
+
|
|
1074
|
+
// src/core/structure.ts
|
|
1075
|
+
import { readFile as readFile9 } from "fs/promises";
|
|
1076
|
+
import path12 from "path";
|
|
1077
|
+
import { execa as execa2 } from "execa";
|
|
1078
|
+
|
|
1079
|
+
// src/core/knowledge-dir.ts
|
|
1080
|
+
var DEFAULT_KNOWLEDGE_DIR = ".maestrokit/knowledge";
|
|
1081
|
+
|
|
1082
|
+
// src/core/structure.ts
|
|
1083
|
+
function structureRules(markdown) {
|
|
1084
|
+
const rules = [];
|
|
1085
|
+
for (const line of markdown.split(/\r?\n/)) {
|
|
1086
|
+
if (!line.startsWith("|")) continue;
|
|
1087
|
+
const cell = line.split("|")[2] ?? "";
|
|
1088
|
+
for (const m of cell.matchAll(/`([^`]+)`/g)) {
|
|
1089
|
+
const value = (m[1] ?? "").trim();
|
|
1090
|
+
if (!value.includes("/") || value.includes(" ")) continue;
|
|
1091
|
+
const deep = value.endsWith("/");
|
|
1092
|
+
const dir = deep ? value.replace(/\/$/, "") : value.slice(0, value.lastIndexOf("/"));
|
|
1093
|
+
if (dir !== "") rules.push({ segments: dir.split("/"), deep });
|
|
1094
|
+
}
|
|
1095
|
+
}
|
|
1096
|
+
return rules;
|
|
1097
|
+
}
|
|
1098
|
+
function seg(pattern, part) {
|
|
1099
|
+
if (!pattern.includes("<")) return pattern === part;
|
|
1100
|
+
const re = pattern.split(/<[^>]+>/).map((t) => t.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("[^/]+");
|
|
1101
|
+
return new RegExp(`^${re}$`).test(part);
|
|
1102
|
+
}
|
|
1103
|
+
function fits(file, rules) {
|
|
1104
|
+
const dirParts = file.split("/").slice(0, -1);
|
|
1105
|
+
return rules.some((r) => {
|
|
1106
|
+
if (r.deep ? r.segments.length > dirParts.length : r.segments.length !== dirParts.length) return false;
|
|
1107
|
+
return r.segments.every((p, i) => seg(p, dirParts[i] ?? ""));
|
|
1108
|
+
});
|
|
1109
|
+
}
|
|
1110
|
+
var isTest = (file) => /(^|\/)__tests__\//.test(file) || /\.test\.[^/]+$/.test(file);
|
|
1111
|
+
async function newFiles(cwd) {
|
|
1112
|
+
const untracked = await execa2("git", ["ls-files", "--others", "--exclude-standard"], { cwd, reject: false });
|
|
1113
|
+
const added = await execa2("git", ["diff", "--cached", "--name-only", "--diff-filter=A", "--relative"], { cwd, reject: false });
|
|
1114
|
+
const lines = (r) => r.exitCode === 0 ? String(r.stdout).split(/\r?\n/).filter(Boolean) : [];
|
|
1115
|
+
return [.../* @__PURE__ */ new Set([...lines(untracked), ...lines(added)])].sort();
|
|
1116
|
+
}
|
|
1117
|
+
async function checkStructure(o) {
|
|
1118
|
+
let markdown;
|
|
1119
|
+
try {
|
|
1120
|
+
markdown = await readFile9(path12.resolve(o.cwd, o.knowledgeDir ?? DEFAULT_KNOWLEDGE_DIR, "structure.md"), "utf8");
|
|
1121
|
+
} catch {
|
|
1122
|
+
return { found: false, checked: [], misses: [] };
|
|
1123
|
+
}
|
|
1124
|
+
const rules = structureRules(markdown);
|
|
1125
|
+
const candidates = o.files ?? await newFiles(o.cwd);
|
|
1126
|
+
const checked = candidates.map((f) => f.split(path12.sep).join("/").replace(/^\.\//, "")).filter((f) => f.includes("/") && !isTest(f) && !f.startsWith("."));
|
|
1127
|
+
return { found: true, checked, misses: checked.filter((f) => !fits(f, rules)) };
|
|
1128
|
+
}
|
|
1129
|
+
|
|
1130
|
+
// src/commands/check-structure.ts
|
|
1131
|
+
async function checkStructureCommand(o) {
|
|
1132
|
+
const r = await checkStructure({
|
|
1133
|
+
cwd: o.cwd,
|
|
1134
|
+
...o.knowledge === void 0 ? {} : { knowledgeDir: o.knowledge },
|
|
1135
|
+
...o.files.length === 0 ? {} : { files: o.files }
|
|
1136
|
+
});
|
|
1137
|
+
if (o.json) {
|
|
1138
|
+
o.io.stdout.write(`${JSON.stringify(r)}
|
|
1139
|
+
`);
|
|
1140
|
+
return 0;
|
|
1141
|
+
}
|
|
1142
|
+
if (!r.found) {
|
|
1143
|
+
o.io.stdout.write("no structure.md yet\n");
|
|
1144
|
+
return 0;
|
|
1145
|
+
}
|
|
1146
|
+
if (r.misses.length === 0) {
|
|
1147
|
+
o.io.stdout.write(`structure ok (${String(r.checked.length)} new files checked)
|
|
1148
|
+
`);
|
|
1149
|
+
return 0;
|
|
1150
|
+
}
|
|
1151
|
+
o.io.stdout.write(`${r.misses.map((f) => `\u2716 ${f} \u2014 no structure row fits`).join("\n")}
|
|
1152
|
+
`);
|
|
1153
|
+
return 0;
|
|
1154
|
+
}
|
|
1155
|
+
|
|
1156
|
+
// src/core/code-map.ts
|
|
1157
|
+
import { readFile as readFile11 } from "fs/promises";
|
|
1158
|
+
|
|
1159
|
+
// src/core/atomic-write.ts
|
|
1160
|
+
import { mkdir as mkdir5, rename as rename3, rm as rm5, writeFile as writeFile5 } from "fs/promises";
|
|
1161
|
+
import path13 from "path";
|
|
1162
|
+
async function writeFileAtomic(target, text) {
|
|
1163
|
+
const temp = `${target}.${String(process.pid)}.tmp`;
|
|
1164
|
+
try {
|
|
1165
|
+
await mkdir5(path13.dirname(target), { recursive: true });
|
|
1166
|
+
await writeFile5(temp, text);
|
|
1167
|
+
await rename3(temp, target);
|
|
1168
|
+
} catch (error) {
|
|
1169
|
+
await rm5(temp, { force: true }).catch(() => void 0);
|
|
1170
|
+
throw error;
|
|
1171
|
+
}
|
|
1172
|
+
}
|
|
1173
|
+
|
|
1174
|
+
// src/core/code-map.ts
|
|
1175
|
+
import path16 from "path";
|
|
1176
|
+
import { glob as glob3 } from "tinyglobby";
|
|
1177
|
+
import { parse as parse4 } from "yaml";
|
|
1178
|
+
|
|
1179
|
+
// src/core/code/reader.ts
|
|
1180
|
+
import { access, readFile as readFile10 } from "fs/promises";
|
|
1181
|
+
import { createRequire } from "module";
|
|
1182
|
+
import path14 from "path";
|
|
1183
|
+
import { parse as parse3 } from "yaml";
|
|
1184
|
+
|
|
1185
|
+
// src/core/code/dart-reader.ts
|
|
1186
|
+
var DART_GLOBS = ["lib/**/*.dart", "test/**/*.dart"];
|
|
1187
|
+
var IDENT = "[A-Za-z_$][\\w$]*";
|
|
1188
|
+
var KEYWORDS = /* @__PURE__ */ new Set(["final", "const", "var", "late", "external", "static", "covariant", "required", "Function", "get", "set"]);
|
|
1189
|
+
var isIdentChar = (ch) => ch !== void 0 && /[\w$]/.test(ch);
|
|
1190
|
+
function blankDart(text) {
|
|
1191
|
+
let code = "";
|
|
1192
|
+
let bare = "";
|
|
1193
|
+
const stack = [];
|
|
1194
|
+
const blank = (s) => s.replace(/[^\n]/g, " ");
|
|
1195
|
+
const emit = (s, inString) => {
|
|
1196
|
+
code += s;
|
|
1197
|
+
bare += inString ? blank(s) : s;
|
|
1198
|
+
};
|
|
1199
|
+
let i = 0;
|
|
1200
|
+
while (i < text.length) {
|
|
1201
|
+
const ch = text[i];
|
|
1202
|
+
const top = stack.at(-1);
|
|
1203
|
+
if (top?.kind === "string") {
|
|
1204
|
+
if (!top.raw && ch === "\\") {
|
|
1205
|
+
emit(text.slice(i, i + 2), true);
|
|
1206
|
+
i += 2;
|
|
1207
|
+
continue;
|
|
1208
|
+
}
|
|
1209
|
+
const close = top.triple ? top.quote.repeat(3) : top.quote;
|
|
1210
|
+
if (text.startsWith(close, i)) {
|
|
1211
|
+
stack.pop();
|
|
1212
|
+
emit(close, stack.length > 0);
|
|
1213
|
+
i += close.length;
|
|
1214
|
+
continue;
|
|
1215
|
+
}
|
|
1216
|
+
if (!top.raw && text.startsWith("${", i)) {
|
|
1217
|
+
stack.push({ kind: "interp", depth: 1 });
|
|
1218
|
+
emit("${", true);
|
|
1219
|
+
i += 2;
|
|
1220
|
+
continue;
|
|
1221
|
+
}
|
|
1222
|
+
if (!top.triple && ch === "\n") {
|
|
1223
|
+
stack.pop();
|
|
1224
|
+
emit(ch, stack.length > 0);
|
|
1225
|
+
i += 1;
|
|
1226
|
+
continue;
|
|
1227
|
+
}
|
|
1228
|
+
emit(ch, true);
|
|
1229
|
+
i += 1;
|
|
1230
|
+
continue;
|
|
1231
|
+
}
|
|
1232
|
+
const inString = stack.length > 0;
|
|
1233
|
+
if (text.startsWith("//", i)) {
|
|
1234
|
+
const end = text.indexOf("\n", i);
|
|
1235
|
+
const stop = end === -1 ? text.length : end;
|
|
1236
|
+
code += blank(text.slice(i, stop));
|
|
1237
|
+
bare += blank(text.slice(i, stop));
|
|
1238
|
+
i = stop;
|
|
1239
|
+
continue;
|
|
1240
|
+
}
|
|
1241
|
+
if (text.startsWith("/*", i)) {
|
|
1242
|
+
let depth = 0;
|
|
1243
|
+
let j = i;
|
|
1244
|
+
while (j < text.length) {
|
|
1245
|
+
if (text.startsWith("/*", j)) {
|
|
1246
|
+
depth += 1;
|
|
1247
|
+
j += 2;
|
|
1248
|
+
} else if (text.startsWith("*/", j)) {
|
|
1249
|
+
depth -= 1;
|
|
1250
|
+
j += 2;
|
|
1251
|
+
if (depth === 0) break;
|
|
1252
|
+
} else j += 1;
|
|
1253
|
+
}
|
|
1254
|
+
code += blank(text.slice(i, j));
|
|
1255
|
+
bare += blank(text.slice(i, j));
|
|
1256
|
+
i = j;
|
|
1257
|
+
continue;
|
|
1258
|
+
}
|
|
1259
|
+
const raw = ch === "r" && (text[i + 1] === "'" || text[i + 1] === '"') && !isIdentChar(text[i - 1]);
|
|
1260
|
+
const q = raw ? text[i + 1] : ch;
|
|
1261
|
+
if (q === "'" || q === '"') {
|
|
1262
|
+
if (raw) {
|
|
1263
|
+
emit("r", inString);
|
|
1264
|
+
i += 1;
|
|
1265
|
+
}
|
|
1266
|
+
const triple = text.startsWith(q.repeat(3), i);
|
|
1267
|
+
emit(triple ? q.repeat(3) : q, inString);
|
|
1268
|
+
i += triple ? 3 : 1;
|
|
1269
|
+
stack.push({ kind: "string", quote: q, triple, raw });
|
|
1270
|
+
continue;
|
|
1271
|
+
}
|
|
1272
|
+
if (top?.kind === "interp") {
|
|
1273
|
+
if (ch === "{") top.depth += 1;
|
|
1274
|
+
if (ch === "}") {
|
|
1275
|
+
top.depth -= 1;
|
|
1276
|
+
if (top.depth === 0) {
|
|
1277
|
+
stack.pop();
|
|
1278
|
+
emit(ch, true);
|
|
1279
|
+
i += 1;
|
|
1280
|
+
continue;
|
|
1281
|
+
}
|
|
1282
|
+
}
|
|
1283
|
+
}
|
|
1284
|
+
emit(ch, inString);
|
|
1285
|
+
i += 1;
|
|
1286
|
+
}
|
|
1287
|
+
return { code, bare };
|
|
1288
|
+
}
|
|
1289
|
+
function names(list) {
|
|
1290
|
+
return (list ?? "").split(",").map((n) => n.trim()).filter((n) => new RegExp(`^${IDENT}$`).test(n));
|
|
1291
|
+
}
|
|
1292
|
+
function shown(tail) {
|
|
1293
|
+
const out = [];
|
|
1294
|
+
for (const m of tail.matchAll(/\bshow\s+([\w$\s,]+?)(?=\s+(?:show|hide)\b|\s*$)/g)) out.push(...names(m[1]));
|
|
1295
|
+
return out;
|
|
1296
|
+
}
|
|
1297
|
+
var DIRECTIVE = /^[ \t]*(import|export|part)\s+(?!of\b)(['"])([^'"\n]*)\2([^;]*);/gm;
|
|
1298
|
+
function directives(code, bare) {
|
|
1299
|
+
const exports = [];
|
|
1300
|
+
const imports = [];
|
|
1301
|
+
for (const m of code.matchAll(DIRECTIVE)) {
|
|
1302
|
+
const lead = m[0].indexOf(m[1]) + m[1].length;
|
|
1303
|
+
if (bare.slice(m.index, m.index + lead) !== code.slice(m.index, m.index + lead)) continue;
|
|
1304
|
+
const [, keyword, , uri = "", rest = ""] = m;
|
|
1305
|
+
const tail = rest.replace(/\bif\s*\([^)]*\)\s*(['"])[^'"]*\1/g, " ");
|
|
1306
|
+
const show = shown(tail);
|
|
1307
|
+
if (keyword === "export") {
|
|
1308
|
+
for (const name of show.length > 0 ? show : ["*"]) exports.push({ name, kind: "reexport", from: uri });
|
|
1309
|
+
}
|
|
1310
|
+
imports.push({ specifier: uri, names: keyword === "part" || show.length === 0 ? ["*"] : show, resolved: null });
|
|
1311
|
+
}
|
|
1312
|
+
return { exports, imports };
|
|
1313
|
+
}
|
|
1314
|
+
var OPENERS = /* @__PURE__ */ new Set(["(", "["]);
|
|
1315
|
+
var CLOSERS = /* @__PURE__ */ new Set([")", "]"]);
|
|
1316
|
+
function splitTop(head) {
|
|
1317
|
+
const parts = [];
|
|
1318
|
+
let depth = 0;
|
|
1319
|
+
let current = "";
|
|
1320
|
+
for (const ch of head) {
|
|
1321
|
+
if ("([{<".includes(ch)) depth += 1;
|
|
1322
|
+
else if (")]}>".includes(ch)) depth = Math.max(0, depth - 1);
|
|
1323
|
+
if (ch === "," && depth === 0) {
|
|
1324
|
+
parts.push(current);
|
|
1325
|
+
current = "";
|
|
1326
|
+
} else current += ch;
|
|
1327
|
+
}
|
|
1328
|
+
parts.push(current);
|
|
1329
|
+
return parts;
|
|
1330
|
+
}
|
|
1331
|
+
function assignIndex(head) {
|
|
1332
|
+
let depth = 0;
|
|
1333
|
+
for (let i = 0; i < head.length; i++) {
|
|
1334
|
+
const ch = head[i];
|
|
1335
|
+
if (OPENERS.has(ch) || ch === "{") depth += 1;
|
|
1336
|
+
else if (CLOSERS.has(ch) || ch === "}") depth = Math.max(0, depth - 1);
|
|
1337
|
+
else if (ch === "=" && depth === 0 && head[i + 1] !== "=" && head[i + 1] !== ">" && !"=<>!".includes(head[i - 1] ?? "")) return i;
|
|
1338
|
+
}
|
|
1339
|
+
return -1;
|
|
1340
|
+
}
|
|
1341
|
+
function stripAnnotations(head) {
|
|
1342
|
+
let out = "";
|
|
1343
|
+
let i = 0;
|
|
1344
|
+
while (i < head.length) {
|
|
1345
|
+
const m = head[i] === "@" ? new RegExp(`^@${IDENT}(?:\\.${IDENT})*`).exec(head.slice(i)) : null;
|
|
1346
|
+
if (m === null) {
|
|
1347
|
+
out += head[i];
|
|
1348
|
+
i += 1;
|
|
1349
|
+
continue;
|
|
1350
|
+
}
|
|
1351
|
+
let j = i + m[0].length;
|
|
1352
|
+
for (const [open, close] of [["<", ">"], ["(", ")"]]) {
|
|
1353
|
+
let k = j;
|
|
1354
|
+
while (head[k] === " " || head[k] === "\n" || head[k] === " ") k += 1;
|
|
1355
|
+
if (head[k] !== open) continue;
|
|
1356
|
+
let depth = 0;
|
|
1357
|
+
for (; k < head.length; k++) {
|
|
1358
|
+
if (head[k] === open) depth += 1;
|
|
1359
|
+
else if (head[k] === close && --depth === 0) break;
|
|
1360
|
+
}
|
|
1361
|
+
j = k + 1;
|
|
1362
|
+
}
|
|
1363
|
+
out += " ";
|
|
1364
|
+
i = j;
|
|
1365
|
+
}
|
|
1366
|
+
return out;
|
|
1367
|
+
}
|
|
1368
|
+
var lastIdent = (s) => new RegExp(`(${IDENT})\\s*$`).exec(s)?.[1];
|
|
1369
|
+
function classify(rawHead) {
|
|
1370
|
+
const head = stripAnnotations(rawHead).replace(/\s+/g, " ").trim().replace(/^external\s+/, "");
|
|
1371
|
+
if (head === "" || /^(import|export|part|library)\b/.test(head)) return [];
|
|
1372
|
+
const type = (name) => name === void 0 ? [] : [{ name, kind: "type" }];
|
|
1373
|
+
let m = new RegExp(`^(?:(?:abstract|sealed|base|final|interface|mixin)\\s+)*class\\s+(${IDENT})`).exec(head);
|
|
1374
|
+
if (m) return type(m[1]);
|
|
1375
|
+
m = new RegExp(`^(?:base\\s+)?mixin\\s+(${IDENT})`).exec(head);
|
|
1376
|
+
if (m) return type(m[1]);
|
|
1377
|
+
m = new RegExp(`^enum\\s+(${IDENT})`).exec(head);
|
|
1378
|
+
if (m) return type(m[1]);
|
|
1379
|
+
m = new RegExp(`^extension\\s+type\\s+(?:const\\s+)?(${IDENT})`).exec(head);
|
|
1380
|
+
if (m) return type(m[1]);
|
|
1381
|
+
if (/^extension\b/.test(head)) {
|
|
1382
|
+
m = new RegExp(`^extension\\s+(${IDENT})\\s*(?:<[^{]*?>)?\\s+on\\b`).exec(head);
|
|
1383
|
+
return m ? type(m[1]) : [];
|
|
1384
|
+
}
|
|
1385
|
+
if (/^typedef\b/.test(head)) {
|
|
1386
|
+
const eq2 = head.indexOf("=");
|
|
1387
|
+
if (eq2 >= 0) return type(new RegExp(`^typedef\\s+(${IDENT})`).exec(head)?.[1]);
|
|
1388
|
+
const paren2 = head.indexOf("(");
|
|
1389
|
+
return type(lastIdent((paren2 >= 0 ? head.slice(0, paren2) : head).replace(/<[^<>]*>\s*$/, "")));
|
|
1390
|
+
}
|
|
1391
|
+
m = new RegExp(`(?:^|\\s)(?:get|set)\\s+(${IDENT})\\b`).exec(head);
|
|
1392
|
+
if (m && m[1] !== void 0 && !KEYWORDS.has(m[1])) return [{ name: m[1], kind: "value" }];
|
|
1393
|
+
const paren = head.indexOf("(");
|
|
1394
|
+
const eq = assignIndex(head);
|
|
1395
|
+
if (paren >= 0 && (eq < 0 || paren < eq)) {
|
|
1396
|
+
const name = lastIdent(head.slice(0, paren).replace(/<[^<>]*(?:<[^<>]*>[^<>]*)*>\s*$/, ""));
|
|
1397
|
+
if (name !== void 0 && name !== "Function") return [{ name, kind: "value" }];
|
|
1398
|
+
}
|
|
1399
|
+
const out = [];
|
|
1400
|
+
for (const part of splitTop(head)) {
|
|
1401
|
+
const at = assignIndex(part);
|
|
1402
|
+
const name = lastIdent(at >= 0 ? part.slice(0, at) : part);
|
|
1403
|
+
if (name !== void 0 && !KEYWORDS.has(name)) out.push({ name, kind: "value" });
|
|
1404
|
+
}
|
|
1405
|
+
return out;
|
|
1406
|
+
}
|
|
1407
|
+
function declarations(bare) {
|
|
1408
|
+
const found = [];
|
|
1409
|
+
let head = "";
|
|
1410
|
+
let nest = 0;
|
|
1411
|
+
let body = 0;
|
|
1412
|
+
for (const ch of bare) {
|
|
1413
|
+
if (body > 0) {
|
|
1414
|
+
if (ch === "{") body += 1;
|
|
1415
|
+
else if (ch === "}") body -= 1;
|
|
1416
|
+
continue;
|
|
1417
|
+
}
|
|
1418
|
+
if (nest > 0) {
|
|
1419
|
+
if (OPENERS.has(ch) || ch === "{") nest += 1;
|
|
1420
|
+
else if (CLOSERS.has(ch) || ch === "}") nest -= 1;
|
|
1421
|
+
head += ch;
|
|
1422
|
+
continue;
|
|
1423
|
+
}
|
|
1424
|
+
if (OPENERS.has(ch)) {
|
|
1425
|
+
nest += 1;
|
|
1426
|
+
head += ch;
|
|
1427
|
+
} else if (ch === "{") {
|
|
1428
|
+
found.push(...classify(head));
|
|
1429
|
+
head = "";
|
|
1430
|
+
body = 1;
|
|
1431
|
+
} else if (ch === ";") {
|
|
1432
|
+
found.push(...classify(head));
|
|
1433
|
+
head = "";
|
|
1434
|
+
} else if (ch === "}") {
|
|
1435
|
+
head = "";
|
|
1436
|
+
} else head += ch;
|
|
1437
|
+
}
|
|
1438
|
+
found.push(...classify(head));
|
|
1439
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1440
|
+
return found.filter((e) => {
|
|
1441
|
+
if (e.name.startsWith("_") || seen.has(e.name)) return false;
|
|
1442
|
+
seen.add(e.name);
|
|
1443
|
+
return true;
|
|
1444
|
+
});
|
|
1445
|
+
}
|
|
1446
|
+
function createDartReader() {
|
|
1447
|
+
return {
|
|
1448
|
+
id: "dart-regex",
|
|
1449
|
+
extensions: [".dart"],
|
|
1450
|
+
defaultGlobs: DART_GLOBS,
|
|
1451
|
+
read(_file, text) {
|
|
1452
|
+
const { code, bare } = blankDart(text.replace(/^\uFEFF/, ""));
|
|
1453
|
+
const facts = directives(code, bare);
|
|
1454
|
+
return { exports: [...facts.exports, ...declarations(bare)], imports: facts.imports };
|
|
1455
|
+
}
|
|
1456
|
+
};
|
|
1457
|
+
}
|
|
1458
|
+
|
|
1459
|
+
// src/core/code/regex-reader.ts
|
|
1460
|
+
function stripComments(text) {
|
|
1461
|
+
return text.replace(/("(?:\\.|[^"\\\n])*"|'(?:\\.|[^'\\\n])*'|`(?:\\.|[^`\\])*`)|\/\*[\s\S]*?\*\/|\/\/[^\n]*/g, (m, str) => {
|
|
1462
|
+
if (str === void 0) return " ";
|
|
1463
|
+
return str.startsWith("`") ? `\`${str.slice(1, -1).replace(/[^\n]/g, " ")}\`` : str;
|
|
1464
|
+
});
|
|
1465
|
+
}
|
|
1466
|
+
var OPEN = /* @__PURE__ */ new Set(["(", "[", "{"]);
|
|
1467
|
+
var CLOSE = /* @__PURE__ */ new Set([")", "]", "}"]);
|
|
1468
|
+
function declaredNames(text, start) {
|
|
1469
|
+
const parts = [];
|
|
1470
|
+
let current = "";
|
|
1471
|
+
let depth = 0;
|
|
1472
|
+
let quote = null;
|
|
1473
|
+
for (let i = start; i < text.length; i++) {
|
|
1474
|
+
const ch = text[i];
|
|
1475
|
+
if (quote !== null) {
|
|
1476
|
+
current += ch;
|
|
1477
|
+
if (ch === "\\") current += text[++i] ?? "";
|
|
1478
|
+
else if (ch === quote) quote = null;
|
|
1479
|
+
continue;
|
|
1480
|
+
}
|
|
1481
|
+
if (ch === '"' || ch === "'" || ch === "`") quote = ch;
|
|
1482
|
+
else if (OPEN.has(ch)) depth++;
|
|
1483
|
+
else if (CLOSE.has(ch)) depth = Math.max(0, depth - 1);
|
|
1484
|
+
else if (depth === 0 && ch === ";") break;
|
|
1485
|
+
else if (depth === 0 && ch === ",") {
|
|
1486
|
+
parts.push(current);
|
|
1487
|
+
current = "";
|
|
1488
|
+
continue;
|
|
1489
|
+
} else if (depth === 0 && ch === "\n") {
|
|
1490
|
+
const t = current.trim();
|
|
1491
|
+
if (t !== "" && !t.endsWith("=")) break;
|
|
1492
|
+
}
|
|
1493
|
+
current += ch;
|
|
1494
|
+
}
|
|
1495
|
+
parts.push(current);
|
|
1496
|
+
const names2 = [];
|
|
1497
|
+
for (const part of parts) {
|
|
1498
|
+
const m = new RegExp(`^\\s*(${IDENT2})\\s*(?::|=|$)`).exec(part);
|
|
1499
|
+
if (m?.[1] !== void 0) names2.push(m[1]);
|
|
1500
|
+
}
|
|
1501
|
+
return names2;
|
|
1502
|
+
}
|
|
1503
|
+
var IDENT2 = "[A-Za-z_$][\\w$]*";
|
|
1504
|
+
var SPEC = `['"]([^'"]+)['"]`;
|
|
1505
|
+
function namedList(list) {
|
|
1506
|
+
return list.split(",").map((part) => part.trim()).filter((part) => part !== "").map((part) => {
|
|
1507
|
+
const type = /^type\s+/.test(part);
|
|
1508
|
+
const clean = part.replace(/^type\s+/, "");
|
|
1509
|
+
const [a = "", b] = clean.split(/\s+as\s+/);
|
|
1510
|
+
return { local: a.trim(), exported: (b ?? a).trim(), type };
|
|
1511
|
+
});
|
|
1512
|
+
}
|
|
1513
|
+
function createRegexReader() {
|
|
1514
|
+
return {
|
|
1515
|
+
id: "regex",
|
|
1516
|
+
extensions: JS_EXTENSIONS,
|
|
1517
|
+
read(_file, raw) {
|
|
1518
|
+
const text = stripComments(raw);
|
|
1519
|
+
const exports = [];
|
|
1520
|
+
const imports = [];
|
|
1521
|
+
for (const m of text.matchAll(new RegExp(`^\\s*import\\s+(?:type\\s+)?([^'"]*?)\\s*from\\s*${SPEC}`, "gm"))) {
|
|
1522
|
+
const clause = m[1] ?? "";
|
|
1523
|
+
const names2 = [];
|
|
1524
|
+
const def = new RegExp(`^(${IDENT2})\\s*(?:,|$)`).exec(clause.trim());
|
|
1525
|
+
if (def && def[1] !== "type") names2.push("default");
|
|
1526
|
+
if (/\*\s*as\s+/.test(clause)) names2.push("*");
|
|
1527
|
+
const braces = /\{([^}]*)\}/.exec(clause);
|
|
1528
|
+
if (braces) for (const n of namedList(braces[1] ?? "")) names2.push(n.local);
|
|
1529
|
+
imports.push({ specifier: m[2] ?? "", names: names2, resolved: null });
|
|
1530
|
+
}
|
|
1531
|
+
for (const m of text.matchAll(new RegExp(`^\\s*import\\s*${SPEC}`, "gm"))) {
|
|
1532
|
+
imports.push({ specifier: m[1] ?? "", names: [], resolved: null });
|
|
1533
|
+
}
|
|
1534
|
+
for (const m of text.matchAll(new RegExp(`^\\s*export\\s+(?:type\\s+)?\\*\\s*(?:as\\s+(${IDENT2})\\s*)?from\\s*${SPEC}`, "gm"))) {
|
|
1535
|
+
const from = m[2] ?? "";
|
|
1536
|
+
exports.push({ name: m[1] ?? "*", kind: "reexport", from });
|
|
1537
|
+
imports.push({ specifier: from, names: ["*"], resolved: null });
|
|
1538
|
+
}
|
|
1539
|
+
for (const m of text.matchAll(new RegExp(`^\\s*export\\s+(type\\s+)?\\{([^}]*)\\}\\s*(?:from\\s*${SPEC})?`, "gm"))) {
|
|
1540
|
+
const list = namedList(m[2] ?? "");
|
|
1541
|
+
const from = m[3];
|
|
1542
|
+
if (from !== void 0) {
|
|
1543
|
+
for (const n of list) exports.push({ name: n.exported, kind: "reexport", from });
|
|
1544
|
+
imports.push({ specifier: from, names: list.map((n) => n.local), resolved: null });
|
|
1545
|
+
} else {
|
|
1546
|
+
for (const n of list) {
|
|
1547
|
+
exports.push({ name: n.exported, kind: n.exported === "default" ? "default" : m[1] || n.type ? "type" : "value" });
|
|
1548
|
+
}
|
|
1549
|
+
}
|
|
1550
|
+
}
|
|
1551
|
+
for (const _ of text.matchAll(/^\s*export\s+default\b/gm)) exports.push({ name: "default", kind: "default" });
|
|
1552
|
+
for (const m of text.matchAll(new RegExp(`^\\s*export\\s+(?:declare\\s+)?(?:async\\s+)?(?:function\\*?|class|enum|const\\s+enum|abstract\\s+class)\\s+(${IDENT2})`, "gm"))) {
|
|
1553
|
+
exports.push({ name: m[1] ?? "", kind: "value" });
|
|
1554
|
+
}
|
|
1555
|
+
for (const m of text.matchAll(/^\s*export\s+(?:declare\s+)?(?:const|let|var)\s+(?!enum\b)/gm)) {
|
|
1556
|
+
for (const name of declaredNames(text, (m.index ?? 0) + m[0].length)) exports.push({ name, kind: "value" });
|
|
1557
|
+
}
|
|
1558
|
+
for (const m of text.matchAll(new RegExp(`^\\s*export\\s+(?:declare\\s+)?(?:type|interface)\\s+(${IDENT2})`, "gm"))) {
|
|
1559
|
+
exports.push({ name: m[1] ?? "", kind: "type" });
|
|
1560
|
+
}
|
|
1561
|
+
return { exports, imports };
|
|
1562
|
+
}
|
|
1563
|
+
};
|
|
1564
|
+
}
|
|
1565
|
+
|
|
1566
|
+
// src/core/code/typescript-reader.ts
|
|
1567
|
+
function scriptKind(ts, file) {
|
|
1568
|
+
if (file.endsWith(".tsx")) return ts.ScriptKind.TSX;
|
|
1569
|
+
if (file.endsWith(".jsx")) return ts.ScriptKind.JSX;
|
|
1570
|
+
if (file.endsWith(".js")) return ts.ScriptKind.JS;
|
|
1571
|
+
return ts.ScriptKind.TS;
|
|
1572
|
+
}
|
|
1573
|
+
function hasModifier(ts, node, kind) {
|
|
1574
|
+
const mods = (ts.canHaveModifiers(node) ? ts.getModifiers(node) : void 0) ?? [];
|
|
1575
|
+
return mods.some((m) => m.kind === kind);
|
|
1576
|
+
}
|
|
1577
|
+
function createTypescriptReader(ts) {
|
|
1578
|
+
return {
|
|
1579
|
+
id: "typescript",
|
|
1580
|
+
extensions: JS_EXTENSIONS,
|
|
1581
|
+
read(file, text) {
|
|
1582
|
+
const sf = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, false, scriptKind(ts, file));
|
|
1583
|
+
const exports = [];
|
|
1584
|
+
const imports = [];
|
|
1585
|
+
for (const st of sf.statements) {
|
|
1586
|
+
if (ts.isImportDeclaration(st) && ts.isStringLiteral(st.moduleSpecifier)) {
|
|
1587
|
+
const names2 = [];
|
|
1588
|
+
const clause = st.importClause;
|
|
1589
|
+
if (clause?.name) names2.push("default");
|
|
1590
|
+
const nb = clause?.namedBindings;
|
|
1591
|
+
if (nb && ts.isNamespaceImport(nb)) names2.push("*");
|
|
1592
|
+
if (nb && ts.isNamedImports(nb)) for (const el of nb.elements) names2.push((el.propertyName ?? el.name).text);
|
|
1593
|
+
imports.push({ specifier: st.moduleSpecifier.text, names: names2, resolved: null });
|
|
1594
|
+
continue;
|
|
1595
|
+
}
|
|
1596
|
+
if (ts.isExportDeclaration(st)) {
|
|
1597
|
+
const from = st.moduleSpecifier && ts.isStringLiteral(st.moduleSpecifier) ? st.moduleSpecifier.text : void 0;
|
|
1598
|
+
const clause = st.exportClause;
|
|
1599
|
+
if (from !== void 0) {
|
|
1600
|
+
const names2 = [];
|
|
1601
|
+
if (clause === void 0 || ts.isNamespaceExport(clause)) {
|
|
1602
|
+
exports.push({ name: clause ? clause.name.text : "*", kind: "reexport", from });
|
|
1603
|
+
names2.push("*");
|
|
1604
|
+
} else {
|
|
1605
|
+
for (const el of clause.elements) {
|
|
1606
|
+
exports.push({ name: el.name.text, kind: "reexport", from });
|
|
1607
|
+
names2.push((el.propertyName ?? el.name).text);
|
|
1608
|
+
}
|
|
1609
|
+
}
|
|
1610
|
+
imports.push({ specifier: from, names: names2, resolved: null });
|
|
1611
|
+
} else if (clause && ts.isNamedExports(clause)) {
|
|
1612
|
+
for (const el of clause.elements) {
|
|
1613
|
+
const name = el.name.text;
|
|
1614
|
+
exports.push({ name, kind: name === "default" ? "default" : st.isTypeOnly || el.isTypeOnly ? "type" : "value" });
|
|
1615
|
+
}
|
|
1616
|
+
}
|
|
1617
|
+
continue;
|
|
1618
|
+
}
|
|
1619
|
+
if (ts.isExportAssignment(st)) {
|
|
1620
|
+
if (!st.isExportEquals) exports.push({ name: "default", kind: "default" });
|
|
1621
|
+
continue;
|
|
1622
|
+
}
|
|
1623
|
+
if (!hasModifier(ts, st, ts.SyntaxKind.ExportKeyword)) continue;
|
|
1624
|
+
if (hasModifier(ts, st, ts.SyntaxKind.DefaultKeyword)) {
|
|
1625
|
+
exports.push({ name: "default", kind: "default" });
|
|
1626
|
+
} else if (ts.isVariableStatement(st)) {
|
|
1627
|
+
for (const d of st.declarationList.declarations) if (ts.isIdentifier(d.name)) exports.push({ name: d.name.text, kind: "value" });
|
|
1628
|
+
} else if (ts.isInterfaceDeclaration(st) || ts.isTypeAliasDeclaration(st)) {
|
|
1629
|
+
exports.push({ name: st.name.text, kind: "type" });
|
|
1630
|
+
} else if ((ts.isFunctionDeclaration(st) || ts.isClassDeclaration(st) || ts.isEnumDeclaration(st)) && st.name) {
|
|
1631
|
+
exports.push({ name: st.name.text, kind: "value" });
|
|
1632
|
+
}
|
|
1633
|
+
}
|
|
1634
|
+
return { exports, imports };
|
|
1635
|
+
}
|
|
1636
|
+
};
|
|
1637
|
+
}
|
|
1638
|
+
|
|
1639
|
+
// src/core/code/reader.ts
|
|
1640
|
+
var JS_EXTENSIONS = [".ts", ".tsx", ".js", ".jsx"];
|
|
1641
|
+
async function findProjectTypescript(projectDir) {
|
|
1642
|
+
for (let dir = path14.resolve(projectDir); ; dir = path14.dirname(dir)) {
|
|
1643
|
+
const candidate = path14.join(dir, "node_modules", "typescript", "package.json");
|
|
1644
|
+
try {
|
|
1645
|
+
await access(candidate);
|
|
1646
|
+
return candidate;
|
|
1647
|
+
} catch {
|
|
1648
|
+
}
|
|
1649
|
+
if (path14.dirname(dir) === dir) return null;
|
|
1650
|
+
}
|
|
1651
|
+
}
|
|
1652
|
+
var present2 = (p) => access(p).then(() => true, () => false);
|
|
1653
|
+
async function isDartProject(projectDir) {
|
|
1654
|
+
let stackText = null;
|
|
1655
|
+
try {
|
|
1656
|
+
stackText = await readFile10(path14.join(projectDir, ".maestrokit", "stack.yaml"), "utf8");
|
|
1657
|
+
} catch {
|
|
1658
|
+
}
|
|
1659
|
+
if (stackText !== null) {
|
|
1660
|
+
try {
|
|
1661
|
+
return parse3(stackText)?.language === "dart";
|
|
1662
|
+
} catch {
|
|
1663
|
+
return false;
|
|
1664
|
+
}
|
|
1665
|
+
}
|
|
1666
|
+
return await present2(path14.join(projectDir, "pubspec.yaml")) && !await present2(path14.join(projectDir, "package.json"));
|
|
1667
|
+
}
|
|
1668
|
+
async function loadReader(projectDir) {
|
|
1669
|
+
if (await isDartProject(projectDir)) return createDartReader();
|
|
1670
|
+
const pkg = await findProjectTypescript(projectDir);
|
|
1671
|
+
if (pkg !== null) {
|
|
1672
|
+
try {
|
|
1673
|
+
const ts = createRequire(pkg)("typescript");
|
|
1674
|
+
if (typeof ts.createSourceFile === "function") return createTypescriptReader(ts);
|
|
1675
|
+
} catch {
|
|
1676
|
+
}
|
|
1677
|
+
}
|
|
1678
|
+
return createRegexReader();
|
|
1679
|
+
}
|
|
1680
|
+
|
|
1681
|
+
// src/core/code/resolve.ts
|
|
1682
|
+
import { statSync } from "fs";
|
|
1683
|
+
import path15 from "path";
|
|
1684
|
+
var EXTENSIONS = [".ts", ".tsx", ".js", ".jsx"];
|
|
1685
|
+
var JS_TO_TS = { ".js": [".ts", ".tsx"], ".jsx": [".tsx"], ".mjs": [".mts"], ".cjs": [".cts"] };
|
|
1686
|
+
function orderedPaths(paths) {
|
|
1687
|
+
const rank = (pattern) => pattern.includes("*") ? pattern.indexOf("*") : Number.MAX_SAFE_INTEGER;
|
|
1688
|
+
return Object.entries(paths).sort(([a], [b]) => rank(b) - rank(a));
|
|
1689
|
+
}
|
|
1690
|
+
function isFile(abs3) {
|
|
1691
|
+
try {
|
|
1692
|
+
return statSync(abs3).isFile();
|
|
1693
|
+
} catch {
|
|
1694
|
+
return false;
|
|
1695
|
+
}
|
|
1696
|
+
}
|
|
1697
|
+
function probe(projectDir, rel) {
|
|
1698
|
+
const norm = path15.posix.normalize(rel);
|
|
1699
|
+
if (norm.startsWith("../") || norm === "..") return null;
|
|
1700
|
+
const abs3 = path15.join(projectDir, ...norm.split("/"));
|
|
1701
|
+
if (isFile(abs3)) return norm;
|
|
1702
|
+
for (const ext2 of EXTENSIONS) if (isFile(abs3 + ext2)) return norm + ext2;
|
|
1703
|
+
for (const ext2 of EXTENSIONS) if (isFile(path15.join(abs3, `index${ext2}`))) return `${norm}/index${ext2}`;
|
|
1704
|
+
const ext = path15.posix.extname(norm);
|
|
1705
|
+
for (const swap of JS_TO_TS[ext] ?? []) {
|
|
1706
|
+
const ts = norm.slice(0, -ext.length) + swap;
|
|
1707
|
+
if (isFile(path15.join(projectDir, ...ts.split("/")))) return ts;
|
|
1708
|
+
}
|
|
1709
|
+
return null;
|
|
1710
|
+
}
|
|
1711
|
+
function resolveDart(fromFile, uri, ctx) {
|
|
1712
|
+
if (uri.startsWith("dart:")) return null;
|
|
1713
|
+
if (uri.startsWith("package:")) {
|
|
1714
|
+
const name = ctx.dartPackage;
|
|
1715
|
+
const prefix = `package:${name ?? ""}/`;
|
|
1716
|
+
if (name == null || name === "" || !uri.startsWith(prefix)) return null;
|
|
1717
|
+
return exactFile(ctx.projectDir, `lib/${uri.slice(prefix.length)}`);
|
|
1718
|
+
}
|
|
1719
|
+
if (/^[a-z][a-z0-9+.-]*:/i.test(uri)) return null;
|
|
1720
|
+
return exactFile(ctx.projectDir, path15.posix.join(path15.posix.dirname(fromFile), uri));
|
|
1721
|
+
}
|
|
1722
|
+
function exactFile(projectDir, rel) {
|
|
1723
|
+
const norm = path15.posix.normalize(rel);
|
|
1724
|
+
if (norm.startsWith("../") || norm === ".." || path15.posix.isAbsolute(norm)) return null;
|
|
1725
|
+
return isFile(path15.join(projectDir, ...norm.split("/"))) ? norm : null;
|
|
1726
|
+
}
|
|
1727
|
+
function resolveImport(fromFile, specifier, ctx) {
|
|
1728
|
+
if (fromFile.endsWith(".dart")) return resolveDart(fromFile, specifier, ctx);
|
|
1729
|
+
if (specifier.startsWith("./") || specifier.startsWith("../")) {
|
|
1730
|
+
return probe(ctx.projectDir, path15.posix.join(path15.posix.dirname(fromFile), specifier));
|
|
1731
|
+
}
|
|
1732
|
+
for (const [pattern, targets] of orderedPaths(ctx.paths)) {
|
|
1733
|
+
const star = pattern.indexOf("*");
|
|
1734
|
+
let rest = null;
|
|
1735
|
+
if (star < 0) {
|
|
1736
|
+
if (specifier === pattern) rest = "";
|
|
1737
|
+
} else {
|
|
1738
|
+
const head = pattern.slice(0, star);
|
|
1739
|
+
const tail = pattern.slice(star + 1);
|
|
1740
|
+
if (specifier.startsWith(head) && specifier.endsWith(tail) && specifier.length >= head.length + tail.length) {
|
|
1741
|
+
rest = specifier.slice(head.length, specifier.length - tail.length);
|
|
1742
|
+
}
|
|
1743
|
+
}
|
|
1744
|
+
if (rest === null) continue;
|
|
1745
|
+
for (const target of targets) {
|
|
1746
|
+
const mapped = target.includes("*") ? target.replace("*", rest) : target;
|
|
1747
|
+
const found = probe(ctx.projectDir, path15.posix.join(ctx.baseUrl.split(path15.sep).join("/"), mapped));
|
|
1748
|
+
if (found !== null) return found;
|
|
1749
|
+
}
|
|
1750
|
+
}
|
|
1751
|
+
return null;
|
|
1752
|
+
}
|
|
1753
|
+
|
|
1754
|
+
// src/core/code-map.ts
|
|
1755
|
+
var SHA_LENGTH = 12;
|
|
1756
|
+
var DEFAULT_GLOBS = ["**/*.{ts,tsx,js,jsx}"];
|
|
1757
|
+
var IGNORE = ["**/node_modules/**", "ios/**", "android/**", "dist/**", "build/**"];
|
|
1758
|
+
async function sourceGlobs(cwd, fallback) {
|
|
1759
|
+
try {
|
|
1760
|
+
const data = parse4(await readFile11(path16.join(cwd, ".maestrokit", "stack.yaml"), "utf8"));
|
|
1761
|
+
const globs = data?.source_globs;
|
|
1762
|
+
if (Array.isArray(globs) && globs.every((g) => typeof g === "string") && globs.length > 0) return globs;
|
|
1763
|
+
} catch {
|
|
1764
|
+
}
|
|
1765
|
+
return [...fallback];
|
|
1766
|
+
}
|
|
1767
|
+
async function dartPackageName(cwd) {
|
|
1768
|
+
try {
|
|
1769
|
+
const name = (await readPubspec(cwd))?.name;
|
|
1770
|
+
return typeof name === "string" && name !== "" ? name : null;
|
|
1771
|
+
} catch {
|
|
1772
|
+
return null;
|
|
1773
|
+
}
|
|
1774
|
+
}
|
|
1775
|
+
async function tsconfigPaths(cwd) {
|
|
1776
|
+
let text;
|
|
1777
|
+
try {
|
|
1778
|
+
text = await readFile11(path16.join(cwd, "tsconfig.json"), "utf8");
|
|
1779
|
+
} catch {
|
|
1780
|
+
return { paths: {}, baseUrl: "." };
|
|
1781
|
+
}
|
|
1782
|
+
try {
|
|
1783
|
+
const clean = text.replace(/("(?:\\.|[^"\\])*")|\/\*[\s\S]*?\*\/|\/\/[^\n]*/g, (m, s) => s ?? "").replace(/,(\s*[}\]])/g, "$1");
|
|
1784
|
+
const data = JSON.parse(clean);
|
|
1785
|
+
return { paths: data.compilerOptions?.paths ?? {}, baseUrl: data.compilerOptions?.baseUrl ?? "." };
|
|
1786
|
+
} catch {
|
|
1787
|
+
return { paths: {}, baseUrl: ".", warning: "tsconfig.json is not valid JSON \u2014 import aliases are ignored" };
|
|
1788
|
+
}
|
|
1789
|
+
}
|
|
1790
|
+
function mapPath(cwd, knowledgeDir) {
|
|
1791
|
+
return path16.resolve(cwd, knowledgeDir ?? DEFAULT_KNOWLEDGE_DIR, "map", "files.json");
|
|
1792
|
+
}
|
|
1793
|
+
async function previous(file) {
|
|
1794
|
+
try {
|
|
1795
|
+
const data = JSON.parse(await readFile11(file, "utf8"));
|
|
1796
|
+
return data.version === 1 && Array.isArray(data.files) ? data : null;
|
|
1797
|
+
} catch {
|
|
1798
|
+
return null;
|
|
1799
|
+
}
|
|
1800
|
+
}
|
|
1801
|
+
async function buildMap(o) {
|
|
1802
|
+
const reader = await loadReader(o.cwd);
|
|
1803
|
+
const files = (await glob3(await sourceGlobs(o.cwd, reader.defaultGlobs ?? DEFAULT_GLOBS), { cwd: o.cwd, ignore: IGNORE, onlyFiles: true, dot: false })).filter((f) => reader.extensions.includes(path16.posix.extname(f))).sort();
|
|
1804
|
+
const out = mapPath(o.cwd, o.knowledgeDir);
|
|
1805
|
+
const old = await previous(out);
|
|
1806
|
+
const oldByPath = new Map((old?.reader === reader.id ? old.files : []).map((f) => [f.path, f]));
|
|
1807
|
+
const tsconfig = await tsconfigPaths(o.cwd);
|
|
1808
|
+
const dart = reader.extensions.includes(".dart");
|
|
1809
|
+
const ctx = {
|
|
1810
|
+
projectDir: o.cwd,
|
|
1811
|
+
paths: tsconfig.paths,
|
|
1812
|
+
baseUrl: tsconfig.baseUrl,
|
|
1813
|
+
...dart ? { dartPackage: await dartPackageName(o.cwd) } : {}
|
|
1814
|
+
};
|
|
1815
|
+
let reRead = 0;
|
|
1816
|
+
const entries = [];
|
|
1817
|
+
for (const file of files) {
|
|
1818
|
+
const abs3 = path16.join(o.cwd, ...file.split("/"));
|
|
1819
|
+
const sha = (await gitBlobSha(abs3)).slice(0, SHA_LENGTH);
|
|
1820
|
+
let facts = oldByPath.get(file);
|
|
1821
|
+
if (facts?.sha !== sha) {
|
|
1822
|
+
facts = { path: file, sha, ...reader.read(file, await readFile11(abs3, "utf8")) };
|
|
1823
|
+
reRead += 1;
|
|
1824
|
+
}
|
|
1825
|
+
entries.push({
|
|
1826
|
+
path: file,
|
|
1827
|
+
sha,
|
|
1828
|
+
exports: facts.exports,
|
|
1829
|
+
imports: facts.imports.map((i) => ({ specifier: i.specifier, names: i.names, resolved: resolveImport(file, i.specifier, ctx) }))
|
|
1830
|
+
});
|
|
1831
|
+
}
|
|
1832
|
+
const map = { version: 1, reader: reader.id, files: entries };
|
|
1833
|
+
const text = `${JSON.stringify(map, null, 2)}
|
|
1834
|
+
`;
|
|
1835
|
+
const before = await readFile11(out, "utf8").catch(() => null);
|
|
1836
|
+
if (before !== text) {
|
|
1837
|
+
await writeFileAtomic(out, text);
|
|
1838
|
+
}
|
|
1839
|
+
return { map, reRead, warnings: tsconfig.warning === void 0 ? [] : [tsconfig.warning] };
|
|
1840
|
+
}
|
|
1841
|
+
function findName(map, name) {
|
|
1842
|
+
const definitions = map.files.flatMap(
|
|
1843
|
+
(f) => f.exports.filter((e) => e.name === name && e.kind !== "reexport").map((e) => ({ file: f.path, kind: e.kind }))
|
|
1844
|
+
);
|
|
1845
|
+
const defFiles = new Set(definitions.map((d) => d.file));
|
|
1846
|
+
const byPath3 = new Map(map.files.map((f) => [f.path, f]));
|
|
1847
|
+
const barrels = /* @__PURE__ */ new Set();
|
|
1848
|
+
for (const f of map.files) {
|
|
1849
|
+
for (const e of f.exports) {
|
|
1850
|
+
if (e.kind !== "reexport" || e.name !== name && e.name !== "*") continue;
|
|
1851
|
+
const target = f.imports.find((i) => i.specifier === e.from)?.resolved;
|
|
1852
|
+
if (target != null && defFiles.has(target)) barrels.add(f.path);
|
|
1853
|
+
}
|
|
1854
|
+
}
|
|
1855
|
+
const importers = /* @__PURE__ */ new Set();
|
|
1856
|
+
for (const f of map.files) {
|
|
1857
|
+
if (barrels.has(f.path)) continue;
|
|
1858
|
+
for (const i of f.imports) {
|
|
1859
|
+
if (i.resolved === null) continue;
|
|
1860
|
+
if (!(defFiles.has(i.resolved) || barrels.has(i.resolved))) continue;
|
|
1861
|
+
if (i.names.includes(name) || i.names.includes("*") && byPath3.has(i.resolved)) importers.add(f.path);
|
|
1862
|
+
}
|
|
1863
|
+
}
|
|
1864
|
+
return { definitions, importers: [...importers].sort() };
|
|
1865
|
+
}
|
|
1866
|
+
|
|
1867
|
+
// src/commands/map.ts
|
|
1868
|
+
async function mapCommand(o) {
|
|
1869
|
+
const r = await buildMap({ cwd: o.cwd, ...o.knowledge === void 0 ? {} : { knowledgeDir: o.knowledge } });
|
|
1870
|
+
for (const w of r.warnings) o.io.stderr.write(`${symbols.warning} ${w}
|
|
1871
|
+
`);
|
|
1872
|
+
if (o.json) {
|
|
1873
|
+
o.io.stdout.write(`${JSON.stringify({ files: r.map.files.length, reRead: r.reRead, reader: r.map.reader })}
|
|
1874
|
+
`);
|
|
1875
|
+
} else {
|
|
1876
|
+
o.io.stdout.write(`map: ${String(r.map.files.length)} files, ${String(r.reRead)} re-read (${r.map.reader} reader) \u2192 ${mapPath(o.cwd, o.knowledge)}
|
|
1877
|
+
`);
|
|
1878
|
+
}
|
|
1879
|
+
return 0;
|
|
1880
|
+
}
|
|
1881
|
+
|
|
1882
|
+
// src/core/knowledge.ts
|
|
1883
|
+
import { readdir as readdir2, readFile as readFile12 } from "fs/promises";
|
|
1884
|
+
import path17 from "path";
|
|
1885
|
+
var ROW = /^\|\s*`([^`]+)`\s*\|\s*([0-9a-f]{7,40})\s*\|/i;
|
|
1886
|
+
function parseSources(markdown) {
|
|
1887
|
+
const rows = [];
|
|
1888
|
+
let inSources = false;
|
|
1889
|
+
for (const line of markdown.split(/\r?\n/)) {
|
|
1890
|
+
if (/^#{1,6}\s/.test(line)) {
|
|
1891
|
+
inSources = /^##\s+Sources\s*$/.test(line);
|
|
1892
|
+
continue;
|
|
1893
|
+
}
|
|
1894
|
+
if (!inSources) continue;
|
|
1895
|
+
const m = ROW.exec(line);
|
|
1896
|
+
if (m?.[1] !== void 0 && m[2] !== void 0) rows.push({ file: m[1], sha: m[2].toLowerCase() });
|
|
1897
|
+
}
|
|
1898
|
+
return rows;
|
|
1899
|
+
}
|
|
1900
|
+
async function shaOrNull(file) {
|
|
1901
|
+
try {
|
|
1902
|
+
return await gitBlobSha(file);
|
|
1903
|
+
} catch {
|
|
1904
|
+
return null;
|
|
1905
|
+
}
|
|
1906
|
+
}
|
|
1907
|
+
async function filesIn(dir) {
|
|
1908
|
+
try {
|
|
1909
|
+
return (await readdir2(dir, { withFileTypes: true })).filter((e) => e.isFile()).map((e) => e.name);
|
|
1910
|
+
} catch {
|
|
1911
|
+
return [];
|
|
1912
|
+
}
|
|
1913
|
+
}
|
|
1914
|
+
async function runStale(o) {
|
|
1915
|
+
const modulesDir = path17.resolve(o.cwd, o.knowledgeDir ?? DEFAULT_KNOWLEDGE_DIR, "modules");
|
|
1916
|
+
let noteFiles;
|
|
1917
|
+
try {
|
|
1918
|
+
noteFiles = (await readdir2(modulesDir)).filter((f) => f.endsWith(".md")).sort();
|
|
1919
|
+
} catch {
|
|
1920
|
+
return { notes: 0, modules: [], fresh: true, found: false };
|
|
1921
|
+
}
|
|
1922
|
+
const notes = await Promise.all(
|
|
1923
|
+
noteFiles.map(async (f) => ({
|
|
1924
|
+
module: f.slice(0, -3),
|
|
1925
|
+
rows: parseSources(await readFile12(path17.join(modulesDir, f), "utf8"))
|
|
1926
|
+
}))
|
|
1927
|
+
);
|
|
1928
|
+
const listed = new Set(notes.flatMap((n) => n.rows.map((r) => path17.posix.normalize(r.file))));
|
|
1929
|
+
const results = [];
|
|
1930
|
+
const reportedNew = /* @__PURE__ */ new Set();
|
|
1931
|
+
for (const note of notes) {
|
|
1932
|
+
const changed = [];
|
|
1933
|
+
const missing = [];
|
|
1934
|
+
const folders3 = /* @__PURE__ */ new Set();
|
|
1935
|
+
const rows = [];
|
|
1936
|
+
for (const row of note.rows) {
|
|
1937
|
+
const rel = path17.posix.normalize(row.file);
|
|
1938
|
+
rows.push(rel);
|
|
1939
|
+
folders3.add(path17.posix.dirname(rel));
|
|
1940
|
+
const sha = await shaOrNull(path17.join(o.cwd, ...rel.split("/")));
|
|
1941
|
+
if (sha === null) missing.push(rel);
|
|
1942
|
+
else if (!sha.startsWith(row.sha)) changed.push(rel);
|
|
1943
|
+
}
|
|
1944
|
+
const added = [];
|
|
1945
|
+
for (const folder of [...folders3].sort()) {
|
|
1946
|
+
for (const name of (await filesIn(path17.join(o.cwd, ...folder.split("/")))).sort()) {
|
|
1947
|
+
const rel = folder === "." ? name : `${folder}/${name}`;
|
|
1948
|
+
if (!listed.has(rel) && !reportedNew.has(rel)) {
|
|
1949
|
+
reportedNew.add(rel);
|
|
1950
|
+
added.push(rel);
|
|
1951
|
+
}
|
|
1952
|
+
}
|
|
1953
|
+
}
|
|
1954
|
+
results.push({ module: note.module, changed, missing, new: added, rows });
|
|
1955
|
+
}
|
|
1956
|
+
const changedAll = new Set(results.flatMap((r) => r.changed));
|
|
1957
|
+
const importsOf = /* @__PURE__ */ new Map();
|
|
1958
|
+
if (changedAll.size > 0) {
|
|
1959
|
+
const { map } = await buildMap({ cwd: o.cwd, ...o.knowledgeDir === void 0 ? {} : { knowledgeDir: o.knowledgeDir } });
|
|
1960
|
+
for (const f of map.files) importsOf.set(f.path, f.imports.flatMap((i) => i.resolved === null ? [] : [i.resolved]));
|
|
1961
|
+
}
|
|
1962
|
+
const modules = results.map((r) => ({
|
|
1963
|
+
module: r.module,
|
|
1964
|
+
changed: r.changed,
|
|
1965
|
+
missing: r.missing,
|
|
1966
|
+
new: r.new,
|
|
1967
|
+
depChanged: r.rows.filter((f) => !changedAll.has(f) && (importsOf.get(f) ?? []).some((d) => changedAll.has(d)))
|
|
1968
|
+
}));
|
|
1969
|
+
const fresh = modules.every((m) => m.changed.length + m.missing.length + m.new.length + m.depChanged.length === 0);
|
|
1970
|
+
return { notes: notes.length, modules, fresh, found: true };
|
|
1971
|
+
}
|
|
1972
|
+
|
|
1973
|
+
// src/commands/stale.ts
|
|
1974
|
+
async function staleCommand(o) {
|
|
1975
|
+
const report = await runStale({ cwd: o.cwd, ...o.knowledge === void 0 ? {} : { knowledgeDir: o.knowledge } });
|
|
1976
|
+
if (o.json) {
|
|
1977
|
+
const { found: _found, ...data } = report;
|
|
1978
|
+
o.io.stdout.write(`${JSON.stringify(data)}
|
|
1979
|
+
`);
|
|
1980
|
+
return 0;
|
|
1981
|
+
}
|
|
1982
|
+
if (!report.found) {
|
|
1983
|
+
o.io.stdout.write("no knowledge tree yet\n");
|
|
1984
|
+
return 0;
|
|
1985
|
+
}
|
|
1986
|
+
if (report.fresh) {
|
|
1987
|
+
o.io.stdout.write(`knowledge is up to date (${String(report.notes)} notes)
|
|
1988
|
+
`);
|
|
1989
|
+
return 0;
|
|
1990
|
+
}
|
|
1991
|
+
const lines = [];
|
|
1992
|
+
for (const m of report.modules) {
|
|
1993
|
+
const parts = [
|
|
1994
|
+
...m.changed.map((f) => `CHANGED ${f}`),
|
|
1995
|
+
...m.missing.map((f) => `MISSING ${f}`),
|
|
1996
|
+
...m.new.map((f) => `NEW ${f}`),
|
|
1997
|
+
...m.depChanged.map((f) => `DEP-CHANGED ${f}`)
|
|
1998
|
+
];
|
|
1999
|
+
if (parts.length > 0) lines.push(`${m.module}: ${parts.join(" \xB7 ")}`);
|
|
2000
|
+
}
|
|
2001
|
+
o.io.stdout.write(`${lines.join("\n")}
|
|
2002
|
+
`);
|
|
2003
|
+
return 0;
|
|
2004
|
+
}
|
|
2005
|
+
|
|
2006
|
+
// src/commands/where.ts
|
|
2007
|
+
async function whereCommand(o) {
|
|
2008
|
+
const { map, warnings } = await buildMap({ cwd: o.cwd, ...o.knowledge === void 0 ? {} : { knowledgeDir: o.knowledge } });
|
|
2009
|
+
for (const w of warnings) o.io.stderr.write(`${symbols.warning} ${w}
|
|
2010
|
+
`);
|
|
2011
|
+
const r = findName(map, o.name);
|
|
2012
|
+
if (o.json) {
|
|
2013
|
+
o.io.stdout.write(`${JSON.stringify({ name: o.name, ...r })}
|
|
2014
|
+
`);
|
|
2015
|
+
return 0;
|
|
2016
|
+
}
|
|
2017
|
+
if (r.definitions.length === 0) {
|
|
2018
|
+
o.io.stdout.write(`no export named ${o.name}
|
|
2019
|
+
`);
|
|
2020
|
+
return 0;
|
|
2021
|
+
}
|
|
2022
|
+
const lines = [
|
|
2023
|
+
...r.definitions.map((d) => `defined: ${d.file} (${d.kind})`),
|
|
2024
|
+
...r.importers.length === 0 ? ["imported by: none"] : r.importers.map((f) => `imported by: ${f}`)
|
|
2025
|
+
];
|
|
2026
|
+
o.io.stdout.write(`${lines.join("\n")}
|
|
2027
|
+
`);
|
|
2028
|
+
return 0;
|
|
2029
|
+
}
|
|
2030
|
+
|
|
2031
|
+
// src/core/verify-baseline.ts
|
|
2032
|
+
import { readFile as readFile13 } from "fs/promises";
|
|
2033
|
+
import path19 from "path";
|
|
2034
|
+
|
|
2035
|
+
// src/core/schemas/verify-baseline.ts
|
|
2036
|
+
import { z as z6 } from "zod";
|
|
2037
|
+
var BaselineStepSchema = z6.strictObject({
|
|
2038
|
+
failed: z6.boolean(),
|
|
2039
|
+
/** false when the step failed but its output matched no known format (BR6) */
|
|
2040
|
+
parsed: z6.boolean(),
|
|
2041
|
+
/** `failureKey` of every failure; repeated keys mean repeated failures (BR3) */
|
|
2042
|
+
keys: z6.array(z6.string()),
|
|
2043
|
+
/** exit code of the step when saved; absent in files from before spec mvp-cleanup (BR8) */
|
|
2044
|
+
exitCode: z6.number().int().nullable().optional()
|
|
2045
|
+
});
|
|
2046
|
+
var BaselineSchema = z6.strictObject({
|
|
2047
|
+
version: z6.literal(1),
|
|
2048
|
+
steps: z6.strictObject({
|
|
2049
|
+
typecheck: BaselineStepSchema.optional(),
|
|
2050
|
+
lint: BaselineStepSchema.optional(),
|
|
2051
|
+
test: BaselineStepSchema.optional()
|
|
2052
|
+
})
|
|
2053
|
+
});
|
|
2054
|
+
|
|
2055
|
+
// src/core/verify-parse.ts
|
|
2056
|
+
import path18 from "path";
|
|
2057
|
+
var MAX_LINE = 160;
|
|
2058
|
+
var ANSI = new RegExp(`${String.fromCharCode(27)}\\[[0-9;]*[A-Za-z]`, "g");
|
|
2059
|
+
var TSC_PAREN = /^(.+?)\((\d+),\d+\): error (TS\d+): (.*)$/;
|
|
2060
|
+
var TSC_PRETTY = /^(.+?):(\d+):\d+ - error (TS\d+): (.*)$/;
|
|
2061
|
+
var ESLINT_ERROR = /^\s+(\d+):\d+\s+error\s+(.+?)\s{2,}(\S+)\s*$/;
|
|
2062
|
+
var JEST_FAIL = /^\s*FAIL\s+(\S.*?)\s*$/;
|
|
2063
|
+
var JEST_TEST = /^\s*● (.+?)\s*$/;
|
|
2064
|
+
var VITEST_SUITE_FAIL = /^\s*FAIL\s+(?:\|[^|]*\|\s+)?(\S+)\s+\[\s*\S+\s*\]\s*$/;
|
|
2065
|
+
var VITEST_FAIL = /^\s*FAIL\s+(?:\|[^|]*\|\s+)?(\S+?)\s+>\s+(.+?)\s*$/;
|
|
2066
|
+
var NO_TESTS = /^(No tests found, exiting with code|No test files found, exiting with code|Test directory "test" not found\.|Test directory "test" does not appear to contain any test files\.|No tests were found\.|No test files were passed and the default "test\/" directory doesn't exist\.)/;
|
|
2067
|
+
var FLUTTER_NO_TESTS = /^(?:\d+:\d+ \+\d+(?: ~\d+)?(?: -\d+)?: )?No tests ran\.$/;
|
|
2068
|
+
var DART_ANALYZE = /^\s*(error|warning|info)\s+-\s+(\S+?):(\d+):\d+\s+-\s+(.+?)\s+-\s+([a-z0-9_]+)\s*$/;
|
|
2069
|
+
var FLUTTER_ANALYZE = /^\s*(error|warning|info)\s+(?:•|-)\s+(.+?)\s+(?:•|-)\s+(\S+?):(\d+):\d+\s+(?:•|-)\s+([a-z0-9_]+)\s*$/;
|
|
2070
|
+
var FLUTTER_SUMMARY_LINE = /^\s+(.+?\.dart): (.+?)\s*$/;
|
|
2071
|
+
var FLUTTER_TEST_FAIL = /^\d+:\d+ \+\d+(?: ~\d+)? -\d+: (?:loading )?(.+?\.dart)(?:: (.+?))? \[E\]\s*$/;
|
|
2072
|
+
function relative(file, cwd) {
|
|
2073
|
+
const trimmed = file.trim();
|
|
2074
|
+
const rel = path18.isAbsolute(trimmed) ? path18.relative(cwd, trimmed) : trimmed;
|
|
2075
|
+
return rel.replace(/\\/g, "/");
|
|
2076
|
+
}
|
|
2077
|
+
function parseOutput(output, cwd) {
|
|
2078
|
+
const lines = output.replace(ANSI, "").split(/\r?\n/);
|
|
2079
|
+
const failures = [];
|
|
2080
|
+
let noTests = false;
|
|
2081
|
+
let eslintFile = null;
|
|
2082
|
+
let jestFile = null;
|
|
2083
|
+
let jestSummary = false;
|
|
2084
|
+
const flutterProgress = [];
|
|
2085
|
+
let flutterSummary = null;
|
|
2086
|
+
let inFlutterSummary = false;
|
|
2087
|
+
for (const line of lines) {
|
|
2088
|
+
if (line.trim() === "Failing tests:") {
|
|
2089
|
+
flutterSummary = [];
|
|
2090
|
+
inFlutterSummary = true;
|
|
2091
|
+
continue;
|
|
2092
|
+
}
|
|
2093
|
+
if (inFlutterSummary) {
|
|
2094
|
+
const s = FLUTTER_SUMMARY_LINE.exec(line);
|
|
2095
|
+
if (s) {
|
|
2096
|
+
const name = s[2];
|
|
2097
|
+
const load = name === `loading ${s[1]}`;
|
|
2098
|
+
flutterSummary?.push({ file: relative(s[1], cwd), line: null, code: "test", message: load ? "test file failed to run" : name });
|
|
2099
|
+
continue;
|
|
2100
|
+
}
|
|
2101
|
+
inFlutterSummary = false;
|
|
2102
|
+
}
|
|
2103
|
+
if (NO_TESTS.test(line.trim()) || FLUTTER_NO_TESTS.test(line.trim())) {
|
|
2104
|
+
noTests = true;
|
|
2105
|
+
continue;
|
|
2106
|
+
}
|
|
2107
|
+
let f = DART_ANALYZE.exec(line);
|
|
2108
|
+
if (f) {
|
|
2109
|
+
failures.push({ file: relative(f[2], cwd), line: Number(f[3]), code: f[5], message: f[4].trim() });
|
|
2110
|
+
continue;
|
|
2111
|
+
}
|
|
2112
|
+
f = FLUTTER_ANALYZE.exec(line);
|
|
2113
|
+
if (f) {
|
|
2114
|
+
failures.push({ file: relative(f[3], cwd), line: Number(f[4]), code: f[5], message: f[2].trim() });
|
|
2115
|
+
continue;
|
|
2116
|
+
}
|
|
2117
|
+
f = FLUTTER_TEST_FAIL.exec(line);
|
|
2118
|
+
if (f) {
|
|
2119
|
+
flutterProgress.push({ file: relative(f[1], cwd), line: null, code: "test", message: f[2]?.trim() ?? "test file failed to run" });
|
|
2120
|
+
continue;
|
|
2121
|
+
}
|
|
2122
|
+
let m = TSC_PAREN.exec(line) ?? TSC_PRETTY.exec(line);
|
|
2123
|
+
if (m) {
|
|
2124
|
+
failures.push({ file: relative(m[1], cwd), line: Number(m[2]), code: m[3], message: m[4].trim() });
|
|
2125
|
+
continue;
|
|
2126
|
+
}
|
|
2127
|
+
m = VITEST_SUITE_FAIL.exec(line);
|
|
2128
|
+
if (m) {
|
|
2129
|
+
failures.push({ file: relative(m[1], cwd), line: null, code: "test", message: "test file failed to run" });
|
|
2130
|
+
continue;
|
|
2131
|
+
}
|
|
2132
|
+
m = VITEST_FAIL.exec(line);
|
|
2133
|
+
if (m) {
|
|
2134
|
+
failures.push({ file: relative(m[1], cwd), line: null, code: "test", message: m[2].split(/\s+>\s+/).join(" \u203A ") });
|
|
2135
|
+
continue;
|
|
2136
|
+
}
|
|
2137
|
+
if (line.trim() === "Summary of all failing tests") {
|
|
2138
|
+
jestSummary = true;
|
|
2139
|
+
continue;
|
|
2140
|
+
}
|
|
2141
|
+
m = JEST_FAIL.exec(line);
|
|
2142
|
+
if (m) {
|
|
2143
|
+
jestFile = relative(m[1], cwd);
|
|
2144
|
+
continue;
|
|
2145
|
+
}
|
|
2146
|
+
m = JEST_TEST.exec(line);
|
|
2147
|
+
if (m) {
|
|
2148
|
+
if (!jestSummary && jestFile !== null && m[1] !== "Console") {
|
|
2149
|
+
failures.push({ file: jestFile, line: null, code: "test", message: m[1] });
|
|
2150
|
+
}
|
|
2151
|
+
continue;
|
|
2152
|
+
}
|
|
2153
|
+
m = ESLINT_ERROR.exec(line);
|
|
2154
|
+
if (m) {
|
|
2155
|
+
if (eslintFile !== null) failures.push({ file: eslintFile, line: Number(m[1]), code: m[3], message: m[2].trim() });
|
|
2156
|
+
continue;
|
|
2157
|
+
}
|
|
2158
|
+
if (line.trim() === "" || /^\s/.test(line)) continue;
|
|
2159
|
+
eslintFile = /^[>✖]/.test(line) ? null : relative(line, cwd);
|
|
2160
|
+
}
|
|
2161
|
+
failures.push(...flutterSummary !== null && flutterSummary.length > 0 ? flutterSummary : flutterProgress);
|
|
2162
|
+
return { failures, noTests };
|
|
2163
|
+
}
|
|
2164
|
+
function failureKey(step, f) {
|
|
2165
|
+
return `${step}|${f.file}|${f.code}|${f.message}`;
|
|
2166
|
+
}
|
|
2167
|
+
function formatFailure(f, max = MAX_LINE) {
|
|
2168
|
+
const text = `${f.file}${f.line === null ? "" : `(${String(f.line)})`}: ${f.code} \u2014 ${f.message}`;
|
|
2169
|
+
return text.length <= max ? text : `${text.slice(0, max - 1)}\u2026`;
|
|
2170
|
+
}
|
|
2171
|
+
|
|
2172
|
+
// src/core/verify-baseline.ts
|
|
2173
|
+
var BASELINE_FILE = ".maestrokit/verify-baseline.json";
|
|
2174
|
+
var WARNING = "Baseline unreadable \u2014 ignored. Run maestrokit verify --save-baseline.";
|
|
2175
|
+
var fullPath = (cwd) => path19.join(cwd, ...BASELINE_FILE.split("/"));
|
|
2176
|
+
async function readBaseline(cwd) {
|
|
2177
|
+
let text;
|
|
2178
|
+
try {
|
|
2179
|
+
text = await readFile13(fullPath(cwd), "utf8");
|
|
2180
|
+
} catch (error) {
|
|
2181
|
+
if (error.code === "ENOENT") return { baseline: null, warning: null };
|
|
2182
|
+
return { baseline: null, warning: WARNING };
|
|
2183
|
+
}
|
|
2184
|
+
try {
|
|
2185
|
+
const parsed = BaselineSchema.safeParse(JSON.parse(text));
|
|
2186
|
+
return parsed.success ? { baseline: parsed.data, warning: null } : { baseline: null, warning: WARNING };
|
|
2187
|
+
} catch {
|
|
2188
|
+
return { baseline: null, warning: WARNING };
|
|
2189
|
+
}
|
|
2190
|
+
}
|
|
2191
|
+
async function writeBaseline(cwd, report) {
|
|
2192
|
+
const steps = {};
|
|
2193
|
+
let count = 0;
|
|
2194
|
+
for (const s of report.steps) {
|
|
2195
|
+
const keys = s.failures.map((f) => failureKey(s.name, f));
|
|
2196
|
+
count += keys.length;
|
|
2197
|
+
steps[s.name] = { failed: s.status === "fail", parsed: s.parsed, keys, exitCode: s.exitCode };
|
|
2198
|
+
}
|
|
2199
|
+
const baseline = { version: 1, steps };
|
|
2200
|
+
try {
|
|
2201
|
+
await writeFileAtomic(fullPath(cwd), `${JSON.stringify(baseline, null, 2)}
|
|
2202
|
+
`);
|
|
2203
|
+
} catch (error) {
|
|
2204
|
+
throw new MaestroError("WRITE_FAILED", `Could not write ${BASELINE_FILE}: ${error.message}`, { cause: error });
|
|
2205
|
+
}
|
|
2206
|
+
return count;
|
|
2207
|
+
}
|
|
2208
|
+
function newFailures(step, failures, base) {
|
|
2209
|
+
const left = /* @__PURE__ */ new Map();
|
|
2210
|
+
for (const k of base?.keys ?? []) left.set(k, (left.get(k) ?? 0) + 1);
|
|
2211
|
+
const fresh = [];
|
|
2212
|
+
let preExisting = 0;
|
|
2213
|
+
for (const f of failures) {
|
|
2214
|
+
const k = failureKey(step, f);
|
|
2215
|
+
const n = left.get(k) ?? 0;
|
|
2216
|
+
if (n > 0) {
|
|
2217
|
+
left.set(k, n - 1);
|
|
2218
|
+
preExisting++;
|
|
2219
|
+
} else {
|
|
2220
|
+
fresh.push(f);
|
|
2221
|
+
}
|
|
2222
|
+
}
|
|
2223
|
+
return { fresh, preExisting };
|
|
2224
|
+
}
|
|
2225
|
+
|
|
2226
|
+
// src/core/verify.ts
|
|
2227
|
+
import { access as access2, readFile as readFile14 } from "fs/promises";
|
|
2228
|
+
import path21 from "path";
|
|
2229
|
+
import { execa as execa3 } from "execa";
|
|
2230
|
+
import { parse as parse5 } from "yaml";
|
|
2231
|
+
|
|
2232
|
+
// src/core/package-manager.ts
|
|
2233
|
+
import { lstat as lstat3 } from "fs/promises";
|
|
2234
|
+
import path20 from "path";
|
|
2235
|
+
var LOCKFILES = [
|
|
2236
|
+
["pnpm-lock.yaml", "pnpm"],
|
|
2237
|
+
["yarn.lock", "yarn"],
|
|
2238
|
+
["bun.lockb", "bun"]
|
|
2239
|
+
];
|
|
2240
|
+
async function detectPackageManager(dir) {
|
|
2241
|
+
for (const [file, manager] of LOCKFILES) {
|
|
2242
|
+
try {
|
|
2243
|
+
await lstat3(path20.join(dir, file));
|
|
2244
|
+
return manager;
|
|
2245
|
+
} catch {
|
|
2246
|
+
}
|
|
2247
|
+
}
|
|
2248
|
+
return "npm";
|
|
2249
|
+
}
|
|
2250
|
+
|
|
2251
|
+
// src/core/verify.ts
|
|
2252
|
+
var STEPS = ["typecheck", "lint", "test"];
|
|
2253
|
+
var FALLBACK = { typecheck: "typecheck", lint: "lint", test: "test_all" };
|
|
2254
|
+
var TAIL_LINES = 15;
|
|
2255
|
+
async function stackCommands(cwd) {
|
|
2256
|
+
try {
|
|
2257
|
+
const data = parse5(await readFile14(path21.join(cwd, ".maestrokit", "stack.yaml"), "utf8"));
|
|
2258
|
+
const commands = data?.commands;
|
|
2259
|
+
return typeof commands === "object" && commands !== null ? commands : {};
|
|
2260
|
+
} catch {
|
|
2261
|
+
return {};
|
|
2262
|
+
}
|
|
2263
|
+
}
|
|
2264
|
+
var ESLINT_COMMAND = /\b(eslint|expo\s+lint)\b/;
|
|
2265
|
+
var ESLINT_CONFIGS = [
|
|
2266
|
+
"eslint.config.js",
|
|
2267
|
+
"eslint.config.mjs",
|
|
2268
|
+
"eslint.config.cjs",
|
|
2269
|
+
"eslint.config.ts",
|
|
2270
|
+
"eslint.config.mts",
|
|
2271
|
+
"eslint.config.cts",
|
|
2272
|
+
".eslintrc",
|
|
2273
|
+
".eslintrc.js",
|
|
2274
|
+
".eslintrc.cjs",
|
|
2275
|
+
".eslintrc.json",
|
|
2276
|
+
".eslintrc.yaml",
|
|
2277
|
+
".eslintrc.yml"
|
|
2278
|
+
];
|
|
2279
|
+
function runsEslint(command, script) {
|
|
2280
|
+
return ESLINT_COMMAND.test(command) || typeof script === "string" && ESLINT_COMMAND.test(script);
|
|
2281
|
+
}
|
|
2282
|
+
async function hasEslintConfig(cwd, manifest) {
|
|
2283
|
+
if (typeof manifest === "object" && manifest !== null && "eslintConfig" in manifest) return true;
|
|
2284
|
+
for (const name of ESLINT_CONFIGS) {
|
|
2285
|
+
try {
|
|
2286
|
+
await access2(path21.join(cwd, name));
|
|
2287
|
+
return true;
|
|
2288
|
+
} catch {
|
|
2289
|
+
}
|
|
2290
|
+
}
|
|
2291
|
+
return false;
|
|
2292
|
+
}
|
|
2293
|
+
function tailOf(output) {
|
|
2294
|
+
return output.split(/\r?\n/).filter((line) => line.trim() !== "").slice(-TAIL_LINES);
|
|
2295
|
+
}
|
|
2296
|
+
async function runVerify(o) {
|
|
2297
|
+
let project;
|
|
2298
|
+
try {
|
|
2299
|
+
project = await readProject(o.cwd);
|
|
2300
|
+
} catch (error) {
|
|
2301
|
+
if (error instanceof MaestroError && error.code === "INVALID_MANIFEST") {
|
|
2302
|
+
throw new MaestroError("INVALID_MANIFEST", error.message, { hint: "Fix package.json, then run maestrokit verify again.", cause: error });
|
|
2303
|
+
}
|
|
2304
|
+
throw error;
|
|
2305
|
+
}
|
|
2306
|
+
const scripts = project.manifest?.scripts ?? {};
|
|
2307
|
+
const manager = await detectPackageManager(o.cwd);
|
|
2308
|
+
const fallbacks = await stackCommands(o.cwd);
|
|
2309
|
+
const { baseline, warning } = o.useBaseline === false ? { baseline: null, warning: null } : await readBaseline(o.cwd);
|
|
2310
|
+
const steps = [];
|
|
2311
|
+
for (const name of STEPS) {
|
|
2312
|
+
if (o.signal.aborted) break;
|
|
2313
|
+
let command = null;
|
|
2314
|
+
if (typeof scripts[name] === "string") {
|
|
2315
|
+
command = `${manager} run ${name}`;
|
|
2316
|
+
} else {
|
|
2317
|
+
const fb = fallbacks[FALLBACK[name]];
|
|
2318
|
+
if (typeof fb === "string" && !fb.includes("{files}")) command = fb;
|
|
2319
|
+
}
|
|
2320
|
+
if (command !== null && name === "lint" && runsEslint(command, scripts.lint) && !await hasEslintConfig(o.cwd, project.manifest)) {
|
|
2321
|
+
steps.push({ name, command: null, status: "skipped", exitCode: null, tail: [], failures: [], preExisting: 0, parsed: true, note: "no ESLint config" });
|
|
2322
|
+
continue;
|
|
2323
|
+
}
|
|
2324
|
+
const coveredBy = fallbacks[`${name}_covered_by`];
|
|
2325
|
+
if (command === null && typeof coveredBy === "string") {
|
|
2326
|
+
const note = `covered by ${coveredBy}`;
|
|
2327
|
+
steps.push({ name, command: null, status: "skipped", exitCode: null, tail: [], failures: [], preExisting: 0, parsed: true, note });
|
|
2328
|
+
continue;
|
|
2329
|
+
}
|
|
2330
|
+
if (command === null) {
|
|
2331
|
+
steps.push({ name, command: null, status: "skipped", exitCode: null, tail: [], failures: [], preExisting: 0, parsed: true });
|
|
2332
|
+
continue;
|
|
2333
|
+
}
|
|
2334
|
+
const result = await execa3(command, {
|
|
2335
|
+
cwd: o.cwd,
|
|
2336
|
+
shell: true,
|
|
2337
|
+
all: true,
|
|
2338
|
+
reject: false,
|
|
2339
|
+
cancelSignal: o.signal,
|
|
2340
|
+
env: { CI: "true" }
|
|
2341
|
+
});
|
|
2342
|
+
if (o.signal.aborted) break;
|
|
2343
|
+
const exitCode = result.exitCode ?? 1;
|
|
2344
|
+
const base = { name, command, exitCode };
|
|
2345
|
+
if (exitCode === 0 && !result.failed) {
|
|
2346
|
+
steps.push({ ...base, status: "pass", tail: [], failures: [], preExisting: 0, parsed: true });
|
|
2347
|
+
continue;
|
|
2348
|
+
}
|
|
2349
|
+
const output = String(result.all ?? "");
|
|
2350
|
+
const tail = tailOf(output);
|
|
2351
|
+
const parsedOutput = parseOutput(output, o.cwd);
|
|
2352
|
+
const before = baseline?.steps[name];
|
|
2353
|
+
if (parsedOutput.failures.length > 0) {
|
|
2354
|
+
const { fresh, preExisting } = newFailures(name, parsedOutput.failures, before);
|
|
2355
|
+
const exitChanged = typeof before?.exitCode === "number" && before.exitCode !== exitCode;
|
|
2356
|
+
steps.push({ ...base, status: fresh.length > 0 || exitChanged ? "fail" : "pass", tail, failures: fresh, preExisting, parsed: true });
|
|
2357
|
+
} else if (parsedOutput.noTests) {
|
|
2358
|
+
steps.push({ ...base, status: "no-tests", tail: [], failures: [], preExisting: 0, parsed: true });
|
|
2359
|
+
} else if (before?.failed === true && !before.parsed) {
|
|
2360
|
+
steps.push({ ...base, status: "pass", tail, failures: [], preExisting: 1, parsed: false });
|
|
2361
|
+
} else {
|
|
2362
|
+
steps.push({ ...base, status: "fail", tail, failures: [], preExisting: 0, parsed: false });
|
|
2363
|
+
}
|
|
2364
|
+
}
|
|
2365
|
+
const interrupted2 = o.signal.aborted;
|
|
2366
|
+
return { steps, ok: !interrupted2 && steps.every((s) => s.status !== "fail"), interrupted: interrupted2, baseline: baseline !== null, warning };
|
|
2367
|
+
}
|
|
2368
|
+
|
|
2369
|
+
// src/commands/verify.ts
|
|
2370
|
+
var MAX_FAILURES = 10;
|
|
2371
|
+
var LINE_MAX = 160;
|
|
2372
|
+
function stepLines(s) {
|
|
2373
|
+
if (s.status === "skipped") {
|
|
2374
|
+
if (s.note === void 0) return [`\u2013 ${s.name} skipped`];
|
|
2375
|
+
return [s.note.startsWith("covered by") ? `\u2013 ${s.name} ${s.note}` : `\u2013 ${s.name} skipped (${s.note})`];
|
|
2376
|
+
}
|
|
2377
|
+
if (s.status === "no-tests") return [`\u2013 ${s.name} no tests`];
|
|
2378
|
+
if (s.status === "pass") return [s.preExisting > 0 ? `\u2714 ${s.name}: ${String(s.preExisting)} pre-existing (ignored)` : `\u2714 ${s.name}`];
|
|
2379
|
+
const head = `\u2716 ${s.name} (exit ${String(s.exitCode)})${s.preExisting > 0 ? `: ${String(s.preExisting)} pre-existing (ignored)` : ""}`;
|
|
2380
|
+
if (s.failures.length === 0) return [head, ...s.tail.map((l) => ` ${l}`)];
|
|
2381
|
+
const shown2 = s.failures.slice(0, MAX_FAILURES).map((f) => ` ${formatFailure(f, LINE_MAX - 2)}`);
|
|
2382
|
+
const more = s.failures.length - MAX_FAILURES;
|
|
2383
|
+
return [head, ...shown2, ...more > 0 ? [` \u2026 ${String(more)} more`] : []];
|
|
2384
|
+
}
|
|
2385
|
+
async function verifyCommand(o) {
|
|
2386
|
+
const save = o.saveBaseline === true;
|
|
2387
|
+
const report = await runVerify({ cwd: o.cwd, signal: o.signal, useBaseline: !save });
|
|
2388
|
+
if (report.warning !== null) o.io.stderr.write(`! ${report.warning}
|
|
2389
|
+
`);
|
|
2390
|
+
if (report.interrupted) {
|
|
2391
|
+
if (o.json) o.io.stdout.write(`${JSON.stringify(report)}
|
|
2392
|
+
`);
|
|
2393
|
+
return 130;
|
|
2394
|
+
}
|
|
2395
|
+
const saved = save ? await writeBaseline(o.cwd, report) : null;
|
|
2396
|
+
if (o.json) {
|
|
2397
|
+
o.io.stdout.write(`${JSON.stringify(report)}
|
|
2398
|
+
`);
|
|
2399
|
+
} else {
|
|
2400
|
+
const lines = report.steps.flatMap(stepLines);
|
|
2401
|
+
if (saved !== null) lines.push(`Baseline saved: ${String(saved)} failures (${BASELINE_FILE})`);
|
|
2402
|
+
o.io.stdout.write(`${lines.join("\n")}
|
|
2403
|
+
`);
|
|
2404
|
+
}
|
|
2405
|
+
if (save) return 0;
|
|
2406
|
+
return report.ok ? 0 : 1;
|
|
2407
|
+
}
|
|
2408
|
+
|
|
2409
|
+
// src/core/package.ts
|
|
2410
|
+
import { readFile as readFile15 } from "fs/promises";
|
|
2411
|
+
import path22 from "path";
|
|
2412
|
+
import { fileURLToPath } from "url";
|
|
2413
|
+
import { z as z7 } from "zod";
|
|
2414
|
+
var PACKAGE_NAME = "maestrokit";
|
|
2415
|
+
var OwnManifestSchema = z7.looseObject({
|
|
2416
|
+
name: z7.literal(PACKAGE_NAME),
|
|
2417
|
+
version: z7.string().min(1),
|
|
2418
|
+
bugs: z7.union([z7.string().min(1), z7.looseObject({ url: z7.string().min(1) })])
|
|
2419
|
+
});
|
|
2420
|
+
async function readJsonOrNull(file) {
|
|
2421
|
+
let text;
|
|
2422
|
+
try {
|
|
2423
|
+
text = await readFile15(file, "utf8");
|
|
2424
|
+
} catch {
|
|
2425
|
+
return null;
|
|
2426
|
+
}
|
|
2427
|
+
try {
|
|
2428
|
+
return JSON.parse(text.replace(/^\uFEFF/, ""));
|
|
2429
|
+
} catch {
|
|
2430
|
+
return null;
|
|
2431
|
+
}
|
|
2432
|
+
}
|
|
2433
|
+
function hasOurName(data) {
|
|
2434
|
+
return typeof data === "object" && data !== null && "name" in data && data.name === PACKAGE_NAME;
|
|
2435
|
+
}
|
|
2436
|
+
async function loadPackageInfo(fromUrl) {
|
|
2437
|
+
let dir = path22.dirname(fileURLToPath(fromUrl));
|
|
2438
|
+
for (; ; ) {
|
|
2439
|
+
const data = await readJsonOrNull(path22.join(dir, "package.json"));
|
|
2440
|
+
if (hasOurName(data)) {
|
|
2441
|
+
const parsed = OwnManifestSchema.safeParse(data);
|
|
2442
|
+
if (!parsed.success) {
|
|
2443
|
+
throw new MaestroError(
|
|
2444
|
+
"PACKAGE_CONTENT_INVALID",
|
|
2445
|
+
`The maestrokit package is damaged: ${path22.join(dir, "package.json")} is invalid (${parsed.error.issues.map((issue) => issue.path.join(".") || issue.message).join(", ")}). Reinstall it.`
|
|
2446
|
+
);
|
|
2447
|
+
}
|
|
2448
|
+
const { version, bugs } = parsed.data;
|
|
2449
|
+
return { root: dir, version, bugsUrl: typeof bugs === "string" ? bugs : bugs.url };
|
|
2450
|
+
}
|
|
2451
|
+
const parent = path22.dirname(dir);
|
|
2452
|
+
if (parent === dir) {
|
|
2453
|
+
throw new MaestroError(
|
|
2454
|
+
"PACKAGE_CONTENT_INVALID",
|
|
2455
|
+
"The maestrokit package is damaged: its package.json was not found. Reinstall it."
|
|
2456
|
+
);
|
|
2457
|
+
}
|
|
2458
|
+
dir = parent;
|
|
2459
|
+
}
|
|
2460
|
+
}
|
|
2461
|
+
|
|
2462
|
+
// src/main.ts
|
|
2463
|
+
var EXIT_OK = 0;
|
|
2464
|
+
var EXIT_FAILURE = 1;
|
|
2465
|
+
var EXIT_USAGE = 2;
|
|
2466
|
+
var EXIT_INTERRUPTED = 130;
|
|
2467
|
+
var SUCCESS_CODES = /* @__PURE__ */ new Set(["commander.helpDisplayed", "commander.version"]);
|
|
2468
|
+
function createProgram(io, packageInfo) {
|
|
2469
|
+
return new Command("maestrokit").description("Structured multi-agent workflow for AI coding agents").version(packageInfo.version, "-v, --version", "print the maestrokit version").helpOption("-h, --help", "show help").helpCommand(false).exitOverride().showHelpAfterError("See maestrokit --help").configureOutput({
|
|
2470
|
+
writeOut: (text) => io.stdout.write(text),
|
|
2471
|
+
writeErr: (text) => io.stderr.write(text)
|
|
2472
|
+
});
|
|
2473
|
+
}
|
|
2474
|
+
function reportError(error, io, bugsUrl) {
|
|
2475
|
+
if (error instanceof CommanderError) {
|
|
2476
|
+
return SUCCESS_CODES.has(error.code) ? EXIT_OK : EXIT_USAGE;
|
|
2477
|
+
}
|
|
2478
|
+
if (error instanceof MaestroError) {
|
|
2479
|
+
const lines = [`${symbols.error} ${error.message}`, ...error.paths.map((p) => ` ${p}`)];
|
|
2480
|
+
if (error.hint !== void 0) lines.push(` ${error.hint}`);
|
|
2481
|
+
io.stderr.write(`${lines.join("\n")}
|
|
2482
|
+
`);
|
|
2483
|
+
return error.exitCode;
|
|
2484
|
+
}
|
|
2485
|
+
const detail = error instanceof Error ? error.stack ?? String(error) : String(error);
|
|
2486
|
+
const where = bugsUrl === null ? "" : ` at ${bugsUrl}`;
|
|
2487
|
+
io.stderr.write(`${detail}
|
|
2488
|
+
|
|
2489
|
+
This is a bug in maestrokit. Please report it${where}.
|
|
2490
|
+
`);
|
|
2491
|
+
return EXIT_FAILURE;
|
|
2492
|
+
}
|
|
2493
|
+
async function main(argv, io, signal) {
|
|
2494
|
+
let bugsUrl = null;
|
|
2495
|
+
try {
|
|
2496
|
+
const packageInfo = await loadPackageInfo(import.meta.url);
|
|
2497
|
+
bugsUrl = packageInfo.bugsUrl;
|
|
2498
|
+
const program = createProgram(io, packageInfo);
|
|
2499
|
+
program.command("init").description("install maestrokit into the current folder").action(async () => {
|
|
2500
|
+
await runInit({ cwd: io.cwd, io, signal, pkg: packageInfo });
|
|
2501
|
+
});
|
|
2502
|
+
let exitCode = EXIT_OK;
|
|
2503
|
+
const interruptible = async (run) => {
|
|
2504
|
+
try {
|
|
2505
|
+
await run();
|
|
2506
|
+
return EXIT_OK;
|
|
2507
|
+
} catch (error) {
|
|
2508
|
+
if (error instanceof MaestroError && error.code === "INTERRUPTED") {
|
|
2509
|
+
reportError(error, io, bugsUrl);
|
|
2510
|
+
return EXIT_INTERRUPTED;
|
|
2511
|
+
}
|
|
2512
|
+
throw error;
|
|
2513
|
+
}
|
|
2514
|
+
};
|
|
2515
|
+
program.command("update").description("move an installed project to this version of maestrokit (files you changed are kept)").option("--force", "also replace files you changed and files maestrokit did not install").action(async (opts) => {
|
|
2516
|
+
exitCode = await interruptible(() => runUpdate({ cwd: io.cwd, io, signal, pkg: packageInfo, force: opts.force === true }));
|
|
2517
|
+
});
|
|
2518
|
+
program.command("uninstall").description("remove everything maestrokit installed, including .maestrokit/ (knowledge tree, specs)").option("--yes", "do not ask for confirmation (required when not in a terminal)").action(async (opts) => {
|
|
2519
|
+
exitCode = await interruptible(() => runUninstall({ cwd: io.cwd, io, signal, yes: opts.yes === true }));
|
|
2520
|
+
});
|
|
2521
|
+
program.command("verify").description("run the project's typecheck, lint and test scripts; print a compact result").option("--save-baseline", "record the current failures; later runs fail only on new ones").option("--json", "print one JSON object").action(async (opts) => {
|
|
2522
|
+
exitCode = await verifyCommand({ cwd: io.cwd, io, signal, json: opts.json === true, saveBaseline: opts.saveBaseline === true });
|
|
2523
|
+
});
|
|
2524
|
+
program.command("stale").description("list knowledge notes whose source files changed, went missing or have new neighbours").option("--knowledge <dir>", "knowledge folder", ".maestrokit/knowledge").option("--json", "print one JSON object").action(async (opts) => {
|
|
2525
|
+
exitCode = await staleCommand({ cwd: io.cwd, io, knowledge: opts.knowledge, json: opts.json === true });
|
|
2526
|
+
});
|
|
2527
|
+
program.command("map").description("refresh the code map (exports and imports of every source file)").option("--knowledge <dir>", "knowledge folder", ".maestrokit/knowledge").option("--json", "print one JSON object").action(async (opts) => {
|
|
2528
|
+
exitCode = await mapCommand({ cwd: io.cwd, io, knowledge: opts.knowledge, json: opts.json === true });
|
|
2529
|
+
});
|
|
2530
|
+
program.command("where").description("show where a name is exported and which files import it").argument("<name>", "exported name, e.g. useAuth").option("--knowledge <dir>", "knowledge folder", ".maestrokit/knowledge").option("--json", "print one JSON object").action(async (name, opts) => {
|
|
2531
|
+
exitCode = await whereCommand({ cwd: io.cwd, io, name, knowledge: opts.knowledge, json: opts.json === true });
|
|
2532
|
+
});
|
|
2533
|
+
program.command("check-structure").description("check that new files sit in a folder of structure.md").argument("[files...]", "files to check (default: new files in git)").option("--knowledge <dir>", "knowledge folder", ".maestrokit/knowledge").option("--json", "print one JSON object").action(async (files, opts) => {
|
|
2534
|
+
exitCode = await checkStructureCommand({ cwd: io.cwd, io, files, knowledge: opts.knowledge, json: opts.json === true });
|
|
2535
|
+
});
|
|
2536
|
+
if (argv.length === 0) {
|
|
2537
|
+
program.outputHelp({ error: true });
|
|
2538
|
+
return EXIT_USAGE;
|
|
2539
|
+
}
|
|
2540
|
+
await program.parseAsync(argv, { from: "user" });
|
|
2541
|
+
return exitCode;
|
|
2542
|
+
} catch (error) {
|
|
2543
|
+
return reportError(error, io, bugsUrl);
|
|
2544
|
+
}
|
|
2545
|
+
}
|
|
2546
|
+
export {
|
|
2547
|
+
main,
|
|
2548
|
+
reportError
|
|
2549
|
+
};
|