@cavelon/cli 0.0.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/README.md +697 -3
  2. package/dist/LICENSE +201 -0
  3. package/dist/agents.js +91 -0
  4. package/dist/branches.js +61 -0
  5. package/dist/capacity.js +162 -0
  6. package/dist/cli.js +4 -0
  7. package/dist/command.js +62 -0
  8. package/dist/commands/api.js +243 -0
  9. package/dist/commands/async.js +207 -0
  10. package/dist/commands/docs.js +158 -0
  11. package/dist/commands/index.js +112 -0
  12. package/dist/commands/init.js +452 -0
  13. package/dist/commands/inventory.js +56 -0
  14. package/dist/commands/limits-set.js +624 -0
  15. package/dist/commands/limits.js +156 -0
  16. package/dist/commands/loops.js +792 -0
  17. package/dist/commands/models.js +197 -0
  18. package/dist/commands/sandboxes.js +667 -0
  19. package/dist/commands/session.js +476 -0
  20. package/dist/commands/solution.js +760 -0
  21. package/dist/commands/tenants.js +266 -0
  22. package/dist/commands/values.js +383 -0
  23. package/dist/commands/work.js +744 -0
  24. package/dist/context.js +56 -0
  25. package/dist/contracts.js +189 -0
  26. package/dist/credentials.js +134 -0
  27. package/dist/errors.js +64 -0
  28. package/dist/features.js +37 -0
  29. package/dist/format.js +36 -0
  30. package/dist/fsutil.js +40 -0
  31. package/dist/git.js +41 -0
  32. package/dist/http.js +286 -0
  33. package/dist/invoke.js +161 -0
  34. package/dist/io.js +49 -0
  35. package/dist/limits.js +299 -0
  36. package/dist/local-state.js +60 -0
  37. package/dist/main.js +227 -0
  38. package/dist/markers.js +113 -0
  39. package/dist/mcp.js +130 -0
  40. package/dist/openapi.js +223 -0
  41. package/dist/operations.js +107 -0
  42. package/dist/package-check.js +342 -0
  43. package/dist/package-files.js +329 -0
  44. package/dist/pair-order.js +39 -0
  45. package/dist/paths.js +28 -0
  46. package/dist/principal.js +33 -0
  47. package/dist/project.js +138 -0
  48. package/dist/prompt.js +34 -0
  49. package/dist/results.js +66 -0
  50. package/dist/session.js +166 -0
  51. package/dist/shell.js +41 -0
  52. package/dist/skills/cavelon-authoring/SKILL.md +214 -0
  53. package/dist/skills/cavelon-long-running/SKILL.md +181 -0
  54. package/dist/skills/cavelon-loop/SKILL.md +158 -0
  55. package/dist/skills/cavelon-testing/SKILL.md +90 -0
  56. package/dist/sse.js +44 -0
  57. package/dist/tar.js +172 -0
  58. package/dist/user-config.js +36 -0
  59. package/dist/version.js +17 -0
  60. package/dist/zip.js +132 -0
  61. package/package.json +40 -4
@@ -0,0 +1,342 @@
1
+ import { Ajv2020 } from "ajv/dist/2020.js";
2
+ import { BRANCH_WIDTH_KEY, branchConcurrency, offText } from "./branches.js";
3
+ import { locate, schemaSections } from "./package-files.js";
4
+ export const SCHEMA_CODE = "package_schema_invalid";
5
+ const ENDPOINT_LIMIT_CODE = "model_endpoint_limit_without_base_url";
6
+ const ENDPOINT_LIMIT_NOT_CARRIED = "model_endpoint_limit_not_in_package_schema";
7
+ const REGISTRY_SECTION = "model_registry";
8
+ const ENDPOINT_LIMIT_FIELD = "max_concurrent_requests";
9
+ const PACKAGE_DOCS = "/docs/reference/api-endpoints";
10
+ const BRANCH_WIDTH_CODE = "branch_width_capped";
11
+ const BRANCHES_SEQUENTIAL_CODE = "branches_run_in_sequence";
12
+ const BRANCH_DOCS = "/docs/concepts/capacity-and-concurrency#branch-concurrency";
13
+ const KB_WITHOUT_SEARCH_CODE = "knowledge_base_without_search_tool";
14
+ const SEARCH_DOCS = "/docs/reference/builtin-tools#binding-knowledge-bases-to-search_documents";
15
+ const SEARCH_TOOL = "search_documents";
16
+ const SEARCH_TOOL_KEYS = new Set([SEARCH_TOOL, "search_knowledge_base", "search_kb"]);
17
+ export const KIT_CODES = [
18
+ {
19
+ code: SCHEMA_CODE,
20
+ area: "package",
21
+ message: "A package file does not match the instance's package schema.",
22
+ hint: "Fix the field the finding names (file, line and path); copy the shape of a similar entry from `cavelon pull`.",
23
+ docs: PACKAGE_DOCS,
24
+ },
25
+ {
26
+ code: "package_section_unknown",
27
+ area: "package",
28
+ message: "A file in package/ holds a section this instance's package schema does not have.",
29
+ hint: "Check the file name for a typo; a section from a newer instance is kept and sent, and this instance ignores it.",
30
+ docs: PACKAGE_DOCS,
31
+ },
32
+ {
33
+ code: "package_file_invalid",
34
+ area: "package",
35
+ message: "A package file is not valid YAML or JSON.",
36
+ hint: "Fix the syntax at the line the finding names.",
37
+ docs: PACKAGE_DOCS,
38
+ },
39
+ {
40
+ code: ENDPOINT_LIMIT_CODE,
41
+ area: "package",
42
+ message: "A Model Registry row sets max_concurrent_requests without a base_url.",
43
+ hint: "The limit belongs to a self-hosted endpoint: add the row's base_url, or remove max_concurrent_requests (empty means no limit).",
44
+ docs: PACKAGE_DOCS,
45
+ },
46
+ {
47
+ code: ENDPOINT_LIMIT_NOT_CARRIED,
48
+ area: "package",
49
+ message: "This instance's package format does not carry max_concurrent_requests on Model Registry rows.",
50
+ hint: "The import ignores it. Set it on the row in the Admin's model form, or with PATCH /api/v1/model-registry/{model_registry_id}.",
51
+ docs: PACKAGE_DOCS,
52
+ },
53
+ {
54
+ code: BRANCH_WIDTH_CODE,
55
+ area: "package",
56
+ message: "A fan-out or Map loop sets max_concurrency above the branch width this instance publishes; it runs at the width.",
57
+ hint: "Nothing fails: the node runs at most the published width at once. Lower max_concurrency to the width, or ask the operator to raise ORCHESTRATION_MAX_BRANCH_CONCURRENCY. `cavelon limits --key orchestration_max_branch_concurrency` shows it.",
58
+ docs: BRANCH_DOCS,
59
+ },
60
+ {
61
+ code: BRANCHES_SEQUENTIAL_CODE,
62
+ area: "package",
63
+ message: "This tenant runs fan-outs and Map loops in sequence: a switch for concurrent branches is off.",
64
+ hint: "The result is the same, only slower. `cavelon limits --key orchestration_parallel_branches` names the switch that is off and who turns it on.",
65
+ docs: BRANCH_DOCS,
66
+ },
67
+ {
68
+ code: KB_WITHOUT_SEARCH_CODE,
69
+ area: "package",
70
+ message: "An agent is given knowledge bases, but no search tool reaches it, so it cannot read them.",
71
+ hint: `A knowledge base reaches an agent only through a search tool: add \`- tool_slug: ${SEARCH_TOOL}\` to the tool_assignments of the skill that names the knowledge base, or of the agent. \`cavelon docs get reference/builtin-tools\` shows the binding.`,
72
+ docs: SEARCH_DOCS,
73
+ },
74
+ {
75
+ code: "package_file_duplicate",
76
+ area: "package",
77
+ message: "One section is in two files.",
78
+ hint: "Keep one of them: package/<section>.yaml, or the section's own folder from cavelon.yaml's layout.",
79
+ docs: PACKAGE_DOCS,
80
+ },
81
+ ];
82
+ export function catalogEntry(catalog, code) {
83
+ const rule = catalog?.rule_codes?.find((e) => e.code === code);
84
+ if (rule)
85
+ return { ...rule, kind: "rule" };
86
+ const api = catalog?.api_error_codes?.find((e) => e.code === code);
87
+ if (api)
88
+ return { ...api, kind: "api" };
89
+ const kit = KIT_CODES.find((e) => e.code === code);
90
+ return kit ? { ...kit, kind: "kit" } : undefined;
91
+ }
92
+ export function packageVersionOf(pkg) {
93
+ const manifest = pkg.manifest;
94
+ if (!manifest || typeof manifest !== "object")
95
+ return undefined;
96
+ const version = manifest.package_version;
97
+ return typeof version === "string" ? version : undefined;
98
+ }
99
+ function compile(schema) {
100
+ const { $id: _id, $schema: _schema, ...body } = schema;
101
+ const ajv = new Ajv2020({ strict: false, allErrors: true, validateSchema: false, validateFormats: false });
102
+ return ajv.compile(body);
103
+ }
104
+ function describe(error) {
105
+ const params = error.params;
106
+ if (error.keyword === "required") {
107
+ return { pointer: error.instancePath, message: `missing required field "${String(params.missingProperty)}"` };
108
+ }
109
+ if (error.keyword === "enum") {
110
+ return { pointer: error.instancePath, message: `must be one of ${params.allowedValues.map((v) => JSON.stringify(v)).join(", ")}` };
111
+ }
112
+ if (error.keyword === "const") {
113
+ return { pointer: error.instancePath, message: `must be ${JSON.stringify(params.allowedValue)}` };
114
+ }
115
+ return { pointer: error.instancePath, message: error.message ?? "is invalid" };
116
+ }
117
+ export function checkPackage(disk, options) {
118
+ const findings = [...disk.findings];
119
+ const known = new Set(schemaSections(options.schema));
120
+ for (const section of Object.keys(disk.package)) {
121
+ if (known.has(section))
122
+ continue;
123
+ const source = disk.sources[section];
124
+ findings.push({
125
+ code: "package_section_unknown",
126
+ severity: "warning",
127
+ file: Array.isArray(source) ? source[0]?.file : source?.file,
128
+ path: section,
129
+ message: `This instance's package schema has no section "${section}". apply sends it as it is, and the instance ignores it (the preview lists it under "ignored").`,
130
+ });
131
+ }
132
+ const version = packageVersionOf(disk.package);
133
+ if (version && options.accepted?.length && !options.accepted.includes(version)) {
134
+ const at = locate(disk, "/manifest/package_version");
135
+ findings.push({
136
+ code: "package_version_unsupported",
137
+ severity: "error",
138
+ ...at,
139
+ message: `The package is written in format ${version}; this instance accepts ${options.accepted.join(", ")}.`,
140
+ });
141
+ }
142
+ const validate = compile(options.schema);
143
+ if (!validate(disk.package)) {
144
+ const seen = new Set();
145
+ for (const error of validate.errors ?? []) {
146
+ if (error.keyword === "anyOf" || error.keyword === "oneOf")
147
+ continue;
148
+ const { pointer, message } = describe(error);
149
+ const key = `${pointer} ${message}`;
150
+ if (seen.has(key))
151
+ continue;
152
+ seen.add(key);
153
+ findings.push({ code: SCHEMA_CODE, severity: "error", ...locate(disk, pointer), message });
154
+ }
155
+ }
156
+ findings.push(...checkEndpointLimits(disk, options.schema));
157
+ findings.push(...checkBranchConcurrency(disk, options.limits));
158
+ findings.push(...checkKnowledgeSearch(disk));
159
+ for (const finding of findings) {
160
+ const entry = catalogEntry(options.catalog, finding.code);
161
+ if (!entry)
162
+ continue;
163
+ finding.hint ??= entry.hint ?? undefined;
164
+ finding.docs ??= entry.docs;
165
+ }
166
+ return findings;
167
+ }
168
+ function entryProperties(schema, section) {
169
+ let entry = schema.properties?.[section]?.items;
170
+ const ref = typeof entry?.$ref === "string" ? entry.$ref : undefined;
171
+ if (ref?.startsWith("#/$defs/"))
172
+ entry = schema.$defs?.[ref.slice("#/$defs/".length)];
173
+ const properties = entry?.properties;
174
+ return properties && typeof properties === "object" ? properties : undefined;
175
+ }
176
+ function checkEndpointLimits(disk, schema) {
177
+ const rows = disk.package[REGISTRY_SECTION];
178
+ if (!Array.isArray(rows))
179
+ return [];
180
+ const carried = Boolean(entryProperties(schema, REGISTRY_SECTION)?.[ENDPOINT_LIMIT_FIELD]);
181
+ const findings = [];
182
+ rows.forEach((row, index) => {
183
+ if (!row || typeof row !== "object")
184
+ return;
185
+ const entry = row;
186
+ const limit = entry[ENDPOINT_LIMIT_FIELD];
187
+ if (limit === undefined || limit === null)
188
+ return;
189
+ const at = locate(disk, `/${REGISTRY_SECTION}/${index}/${ENDPOINT_LIMIT_FIELD}`);
190
+ const name = typeof entry.model_id === "string" ? ` "${entry.model_id}"` : "";
191
+ if (!carried) {
192
+ findings.push({
193
+ code: ENDPOINT_LIMIT_NOT_CARRIED,
194
+ severity: "warning",
195
+ ...at,
196
+ message: `Model${name} sets ${ENDPOINT_LIMIT_FIELD}, which this instance's package format does not carry; the import ignores it.`,
197
+ });
198
+ }
199
+ else if (typeof entry.base_url !== "string" || !entry.base_url.trim()) {
200
+ findings.push({
201
+ code: ENDPOINT_LIMIT_CODE,
202
+ severity: "error",
203
+ ...at,
204
+ message: `Model${name} sets ${ENDPOINT_LIMIT_FIELD} without a base_url; the limit belongs to a self-hosted endpoint.`,
205
+ });
206
+ }
207
+ });
208
+ return findings;
209
+ }
210
+ const asObject = (v) => (v && typeof v === "object" && !Array.isArray(v) ? v : undefined);
211
+ function branchingConfigs(pkg) {
212
+ const found = [];
213
+ const runsBranches = (c) => typeof c.max_concurrency === "number" || c.mode === "map" || c.fanout === true || c.execution === "parallel";
214
+ const registry = asObject(pkg.registry_entities);
215
+ const nodes = Array.isArray(registry?.orchestration_nodes) ? registry.orchestration_nodes : [];
216
+ nodes.forEach((raw, i) => {
217
+ const node = asObject(raw);
218
+ const config = asObject(node?.config);
219
+ if (config && runsBranches(config))
220
+ found.push({ name: `node "${String(node.slug ?? i)}"`, pointer: `/registry_entities/orchestration_nodes/${i}/config`, config });
221
+ });
222
+ const edges = Array.isArray(registry?.graph_edges) ? registry.graph_edges : [];
223
+ edges.forEach((raw, i) => {
224
+ const edge = asObject(raw);
225
+ const config = asObject(edge?.config);
226
+ const end = (ref) => String(asObject(ref)?.slug ?? "?");
227
+ if (config && runsBranches(config))
228
+ found.push({ name: `edge ${end(edge.from_node_ref)} → ${end(edge.to_node_ref)}`, pointer: `/registry_entities/graph_edges/${i}/config`, config });
229
+ });
230
+ const agents = Array.isArray(pkg.agents) ? pkg.agents : [];
231
+ agents.forEach((raw, i) => {
232
+ const agent = asObject(raw);
233
+ const handoffs = Array.isArray(agent?.handoffs) ? agent.handoffs : [];
234
+ handoffs.forEach((h, j) => {
235
+ const handoff = asObject(h);
236
+ const config = asObject(handoff?.orchestration_config);
237
+ if (config && runsBranches(config)) {
238
+ found.push({ name: `edge ${String(agent.slug ?? i)} → ${String(handoff.to_agent_slug ?? "?")}`, pointer: `/agents/${i}/handoffs/${j}/orchestration_config`, config });
239
+ }
240
+ });
241
+ });
242
+ return found;
243
+ }
244
+ function checkBranchConcurrency(disk, limits) {
245
+ const branches = branchConcurrency(limits);
246
+ if (!branches)
247
+ return [];
248
+ const configs = branchingConfigs(disk.package);
249
+ const findings = [];
250
+ const width = branches.width;
251
+ if (width !== null) {
252
+ for (const c of configs) {
253
+ const requested = c.config.max_concurrency;
254
+ if (typeof requested !== "number" || requested <= width)
255
+ continue;
256
+ findings.push({
257
+ code: BRANCH_WIDTH_CODE,
258
+ severity: "warning",
259
+ ...locate(disk, `${c.pointer}/max_concurrency`),
260
+ message: `The ${c.name} sets max_concurrency ${requested}, above this instance's branch width of ${width} ` +
261
+ `(${branches.width_setting ?? BRANCH_WIDTH_KEY}): it runs at most ${width} branches at once.`,
262
+ });
263
+ }
264
+ }
265
+ if (branches.parallel === false && configs.length) {
266
+ const names = configs.slice(0, 3).map((c) => c.name).join(", ") + (configs.length > 3 ? `, and ${configs.length - 3} more` : "");
267
+ findings.push({
268
+ code: BRANCHES_SEQUENTIAL_CODE,
269
+ severity: "warning",
270
+ ...locate(disk, configs[0].pointer),
271
+ message: `This tenant runs fan-outs and Map loops in sequence, so the ${names} run${configs.length === 1 ? "s" : ""} one branch after another ` +
272
+ `(same result, slower): ${offText(branches)}.`,
273
+ });
274
+ }
275
+ return findings;
276
+ }
277
+ const asList = (v) => Array.isArray(v) ? v.map(asObject).filter((e) => e !== undefined) : [];
278
+ const active = (e) => e.is_active !== false;
279
+ const quoted = (names) => names.map((n) => `"${n}"`).join(", ");
280
+ function checkKnowledgeSearch(disk) {
281
+ const pkg = disk.package;
282
+ const searchSlugs = new Set(SEARCH_TOOL_KEYS);
283
+ for (const tool of asList(pkg.tools)) {
284
+ if (typeof tool.slug === "string" && typeof tool.builtin_key === "string" && SEARCH_TOOL_KEYS.has(tool.builtin_key))
285
+ searchSlugs.add(tool.slug);
286
+ }
287
+ const searches = (assignments) => asList(assignments).some((a) => active(a) && typeof a.tool_slug === "string" && searchSlugs.has(a.tool_slug));
288
+ const skills = asList(pkg.skills);
289
+ const skillIndex = new Map();
290
+ skills.forEach((skill, i) => {
291
+ if (typeof skill.slug === "string")
292
+ skillIndex.set(skill.slug, i);
293
+ });
294
+ const findings = [];
295
+ asList(pkg.agents).forEach((agent, i) => {
296
+ if (!active(agent))
297
+ return;
298
+ const named = [];
299
+ let reached = searches(agent.tool_assignments);
300
+ let unseen = false;
301
+ asList(agent.tool_assignments).forEach((assignment, j) => {
302
+ const names = asObject(assignment.config_overrides)?.knowledge_base_names;
303
+ const list = Array.isArray(names) ? names.filter((n) => typeof n === "string") : [];
304
+ if (active(assignment) && list.length)
305
+ named.push({ names: list, pointer: `/agents/${i}/tool_assignments/${j}/config_overrides/knowledge_base_names` });
306
+ });
307
+ for (const assignment of asList(agent.skill_assignments)) {
308
+ if (!active(assignment) || typeof assignment.skill_slug !== "string")
309
+ continue;
310
+ const k = skillIndex.get(assignment.skill_slug);
311
+ if (k === undefined) {
312
+ unseen = true;
313
+ continue;
314
+ }
315
+ const skill = skills[k];
316
+ if (!active(skill))
317
+ continue;
318
+ if (searches(skill.tool_assignments))
319
+ reached = true;
320
+ const names = asList(skill.knowledge_base_assignments)
321
+ .filter(active)
322
+ .map((a) => a.knowledge_base_name)
323
+ .filter((n) => typeof n === "string");
324
+ if (names.length)
325
+ named.push({ names, pointer: `/skills/${k}/knowledge_base_assignments`, via: assignment.skill_slug });
326
+ }
327
+ if (reached || unseen || !named.length)
328
+ return;
329
+ const names = [...new Set(named.flatMap((n) => n.names))];
330
+ const first = named[0];
331
+ const agentName = typeof agent.slug === "string" ? ` "${agent.slug}"` : "";
332
+ findings.push({
333
+ code: KB_WITHOUT_SEARCH_CODE,
334
+ severity: "warning",
335
+ ...locate(disk, first.pointer),
336
+ message: `The agent${agentName} is given the knowledge base${names.length === 1 ? "" : "s"} ${quoted(names)}` +
337
+ `${first.via ? ` through the skill "${first.via}"` : ""}, but no search tool reaches it, so it cannot search ${names.length === 1 ? "it" : "them"}: ` +
338
+ `add ${SEARCH_TOOL} to the ${first.via ? "skill's" : "agent's"} tool_assignments.`,
339
+ });
340
+ });
341
+ return findings;
342
+ }
@@ -0,0 +1,329 @@
1
+ import { promises as fs } from "node:fs";
2
+ import path from "node:path";
3
+ import { LineCounter, parseDocument, stringify } from "yaml";
4
+ import { readTextFile, writeFileAtomic } from "./fsutil.js";
5
+ export const DEFAULT_LAYOUT = { package: "package", items: {} };
6
+ const PACKAGE_FILE = /\.(ya?ml|json)$/i;
7
+ export function layoutFrom(raw) {
8
+ const value = raw.layout;
9
+ if (!value || typeof value !== "object" || Array.isArray(value))
10
+ return { ...DEFAULT_LAYOUT, items: {} };
11
+ const map = value;
12
+ const items = {};
13
+ if (map.items && typeof map.items === "object" && !Array.isArray(map.items)) {
14
+ for (const [section, folder] of Object.entries(map.items)) {
15
+ if (typeof folder === "string" && safeFolder(folder))
16
+ items[section] = folder;
17
+ }
18
+ }
19
+ const pkg = typeof map.package === "string" && safeFolder(map.package) ? map.package : DEFAULT_LAYOUT.package;
20
+ return { package: pkg, items };
21
+ }
22
+ function safeFolder(folder) {
23
+ const normalized = path.posix.normalize(folder.replace(/\\/g, "/"));
24
+ return normalized !== "." && !normalized.startsWith("..") && !path.isAbsolute(folder) && !normalized.startsWith("/");
25
+ }
26
+ export function defaultLayoutFor(schema) {
27
+ const items = {};
28
+ const suites = schema?.properties?.test_suites;
29
+ if (suites && suites.type === "array")
30
+ items.test_suites = "tests";
31
+ return { package: DEFAULT_LAYOUT.package, items };
32
+ }
33
+ export function schemaSections(schema) {
34
+ return Object.keys(schema?.properties ?? {});
35
+ }
36
+ function rel(root, file) {
37
+ return path.relative(root, file).split(path.sep).join("/");
38
+ }
39
+ async function listFiles(dir) {
40
+ try {
41
+ const entries = await fs.readdir(dir, { withFileTypes: true });
42
+ return entries
43
+ .filter((e) => e.isFile() && !e.name.startsWith(".") && PACKAGE_FILE.test(e.name))
44
+ .map((e) => e.name)
45
+ .sort((a, b) => a.localeCompare(b, "en"));
46
+ }
47
+ catch (error) {
48
+ if (error.code === "ENOENT")
49
+ return [];
50
+ throw error;
51
+ }
52
+ }
53
+ async function exists(dir) {
54
+ try {
55
+ return (await fs.stat(dir)).isDirectory();
56
+ }
57
+ catch {
58
+ return false;
59
+ }
60
+ }
61
+ function parseFile(root, file, text) {
62
+ const relative = rel(root, file);
63
+ if (/\.json$/i.test(file)) {
64
+ try {
65
+ return { value: JSON.parse(text), source: { file: relative } };
66
+ }
67
+ catch (error) {
68
+ return {
69
+ source: { file: relative },
70
+ finding: { code: "package_file_invalid", severity: "error", file: relative, message: `Not valid JSON: ${error.message}` },
71
+ };
72
+ }
73
+ }
74
+ const lines = new LineCounter();
75
+ const doc = parseDocument(text, { lineCounter: lines, uniqueKeys: true, prettyErrors: false });
76
+ if (doc.errors.length) {
77
+ const first = doc.errors[0];
78
+ return {
79
+ source: { file: relative },
80
+ finding: {
81
+ code: "package_file_invalid",
82
+ severity: "error",
83
+ file: relative,
84
+ line: first.linePos?.[0]?.line,
85
+ message: `Not valid YAML: ${first.message.split("\n")[0]}`,
86
+ },
87
+ };
88
+ }
89
+ return { value: doc.toJS({ maxAliasCount: 1000 }), source: { file: relative, doc, lines } };
90
+ }
91
+ export async function readPackage(root, layout) {
92
+ const pkg = {};
93
+ const sources = {};
94
+ const findings = [];
95
+ const dir = path.join(root, layout.package);
96
+ let empty = true;
97
+ for (const name of await listFiles(dir)) {
98
+ empty = false;
99
+ const section = name.replace(PACKAGE_FILE, "");
100
+ const file = path.join(dir, name);
101
+ if (section in sources) {
102
+ findings.push({
103
+ code: "package_file_duplicate",
104
+ severity: "error",
105
+ file: rel(root, file),
106
+ message: `Section "${section}" has two files; keep one of them.`,
107
+ });
108
+ continue;
109
+ }
110
+ const parsed = parseFile(root, file, (await readTextFile(file)) ?? "");
111
+ sources[section] = parsed.source;
112
+ if (parsed.finding)
113
+ findings.push(parsed.finding);
114
+ else
115
+ pkg[section] = parsed.value;
116
+ }
117
+ for (const [section, folder] of Object.entries(layout.items)) {
118
+ const itemDir = path.join(root, folder);
119
+ if (!(await exists(itemDir)))
120
+ continue;
121
+ empty = false;
122
+ if (section in sources) {
123
+ findings.push({
124
+ code: "package_file_duplicate",
125
+ severity: "error",
126
+ file: rel(root, itemDir),
127
+ message: `Section "${section}" is both in ${layout.package}/ and in ${folder}/; keep one of them.`,
128
+ });
129
+ continue;
130
+ }
131
+ const items = [];
132
+ const itemSources = [];
133
+ for (const name of await listFiles(itemDir)) {
134
+ const file = path.join(itemDir, name);
135
+ const parsed = parseFile(root, file, (await readTextFile(file)) ?? "");
136
+ itemSources.push(parsed.source);
137
+ if (parsed.finding)
138
+ findings.push(parsed.finding);
139
+ else
140
+ items.push(parsed.value);
141
+ }
142
+ sources[section] = itemSources;
143
+ pkg[section] = items;
144
+ }
145
+ return { package: pkg, sources, findings, empty };
146
+ }
147
+ export function locate(disk, pointer) {
148
+ const keys = pointer
149
+ .split("/")
150
+ .slice(1)
151
+ .map((k) => k.replace(/~1/g, "/").replace(/~0/g, "~"));
152
+ const section = keys[0];
153
+ const display = keys.slice(1).reduce((acc, key) => (/^\d+$/.test(key) ? `${acc}[${key}]` : `${acc}.${key}`), section ?? "");
154
+ if (section === undefined)
155
+ return { path: "(package)" };
156
+ const source = disk.sources[section];
157
+ if (!source)
158
+ return { path: display };
159
+ let target;
160
+ let inner;
161
+ if (Array.isArray(source)) {
162
+ const index = Number(keys[1]);
163
+ if (!Number.isInteger(index) || !source[index])
164
+ return { file: source[0]?.file, path: display };
165
+ target = source[index];
166
+ inner = keys.slice(2);
167
+ }
168
+ else {
169
+ target = source;
170
+ inner = keys.slice(1);
171
+ }
172
+ return { file: target.file, line: lineOf(target, inner), path: display };
173
+ }
174
+ function lineOf(source, keys) {
175
+ if (!source.doc || !source.lines)
176
+ return undefined;
177
+ for (let n = keys.length; n >= 0; n--) {
178
+ const path = keys.slice(0, n).map((k) => (/^\d+$/.test(k) ? Number(k) : k));
179
+ const node = n === 0 ? source.doc.contents : source.doc.getIn(path, true);
180
+ const range = node?.range;
181
+ if (range)
182
+ return source.lines.linePos(range[0]).line;
183
+ }
184
+ return undefined;
185
+ }
186
+ export function safeSectionName(section) {
187
+ return /^[A-Za-z0-9][A-Za-z0-9_.-]{0,99}$/.test(section) && !section.includes("..");
188
+ }
189
+ export function canonical(value) {
190
+ return JSON.stringify(value, (_key, v) => {
191
+ if (v && typeof v === "object" && !Array.isArray(v)) {
192
+ return Object.fromEntries(Object.entries(v).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
193
+ }
194
+ return v;
195
+ });
196
+ }
197
+ export function toYaml(value) {
198
+ return stringify(value, { lineWidth: 0, aliasDuplicateObjects: false });
199
+ }
200
+ async function readValue(file) {
201
+ const text = await readTextFile(file);
202
+ if (text === undefined)
203
+ return { ok: false };
204
+ try {
205
+ const value = /\.json$/i.test(file) ? JSON.parse(text) : parseDocument(text, { uniqueKeys: true }).toJS({ maxAliasCount: 1000 });
206
+ return { text, value, ok: true };
207
+ }
208
+ catch {
209
+ return { text, ok: false };
210
+ }
211
+ }
212
+ function itemFileName(item, index, taken) {
213
+ const record = item && typeof item === "object" && !Array.isArray(item) ? item : {};
214
+ const label = [record.slug, record.name, record.key].find((v) => typeof v === "string" && v.trim() !== "");
215
+ const base = trimDashesAndDots((label ?? `item-${index + 1}`)
216
+ .toLowerCase()
217
+ .normalize("NFKD")
218
+ .replace(/[^a-z0-9._-]+/g, "-")).slice(0, 80) || `item-${index + 1}`;
219
+ let name = `${base}.yaml`;
220
+ let n = 1;
221
+ while (taken.has(name))
222
+ name = `${base}-${++n}.yaml`;
223
+ taken.add(name);
224
+ return name;
225
+ }
226
+ export async function writePackage(root, layout, pkg, schema, options = {}) {
227
+ const dryRun = options.dryRun === true;
228
+ const report = { written: [], unchanged: [], removed: [], kept: [], refused: [] };
229
+ const known = new Set(schemaSections(schema));
230
+ const required = new Set(schema?.required ?? []);
231
+ const dir = path.join(root, layout.package);
232
+ const existing = new Map();
233
+ for (const name of await listFiles(dir))
234
+ existing.set(name.replace(PACKAGE_FILE, ""), name);
235
+ const plans = [];
236
+ const same = [];
237
+ for (const [section, value] of Object.entries(pkg)) {
238
+ if (section in layout.items && Array.isArray(value))
239
+ continue;
240
+ if (!safeSectionName(section)) {
241
+ report.refused.push(section);
242
+ continue;
243
+ }
244
+ const current = existing.get(section);
245
+ const file = path.join(dir, current ?? `${section}.yaml`);
246
+ const old = await readValue(file);
247
+ if (old.ok && canonical(old.value) === canonical(value))
248
+ same.push({ file, section });
249
+ else
250
+ plans.push({ file, section, content: /\.json$/i.test(file) ? JSON.stringify(value, null, 2) + "\n" : toYaml(value) });
251
+ }
252
+ for (const [section, folder] of Object.entries(layout.items)) {
253
+ const value = pkg[section];
254
+ if (!Array.isArray(value))
255
+ continue;
256
+ const itemDir = path.join(root, folder);
257
+ const before = new Map();
258
+ for (const name of await listFiles(itemDir)) {
259
+ const old = await readValue(path.join(itemDir, name));
260
+ if (old.ok)
261
+ before.set(name, old.value);
262
+ }
263
+ const taken = new Set();
264
+ const unclaimed = new Map(before);
265
+ const placed = value.map((item) => {
266
+ for (const [name, old] of unclaimed) {
267
+ if (canonical(old) === canonical(item)) {
268
+ unclaimed.delete(name);
269
+ taken.add(name);
270
+ return name;
271
+ }
272
+ }
273
+ return undefined;
274
+ });
275
+ value.forEach((item, index) => {
276
+ const name = placed[index];
277
+ if (name) {
278
+ same.push({ file: path.join(itemDir, name), section });
279
+ return;
280
+ }
281
+ plans.push({ file: path.join(itemDir, itemFileName(item, index, taken)), section, content: toYaml(item) });
282
+ });
283
+ for (const name of before.keys()) {
284
+ if (!taken.has(name)) {
285
+ if (!dryRun)
286
+ await fs.rm(path.join(itemDir, name), { force: true });
287
+ report.removed.push(rel(root, path.join(itemDir, name)));
288
+ }
289
+ }
290
+ if (!dryRun)
291
+ await fs.mkdir(itemDir, { recursive: true });
292
+ }
293
+ const othersChanged = plans.some((p) => !required.has(p.section));
294
+ for (const plan of plans) {
295
+ if (required.has(plan.section) && !othersChanged && existing.has(plan.section)) {
296
+ same.push({ file: plan.file, section: plan.section });
297
+ continue;
298
+ }
299
+ if (!dryRun)
300
+ await writeFileAtomic(plan.file, plan.content);
301
+ report.written.push(rel(root, plan.file));
302
+ }
303
+ report.unchanged.push(...same.map((s) => rel(root, s.file)));
304
+ for (const [section, name] of existing) {
305
+ if (section in pkg)
306
+ continue;
307
+ const file = path.join(dir, name);
308
+ if (known.has(section)) {
309
+ if (!dryRun)
310
+ await fs.rm(file, { force: true });
311
+ report.removed.push(rel(root, file));
312
+ }
313
+ else {
314
+ report.kept.push(rel(root, file));
315
+ }
316
+ }
317
+ for (const list of Object.values(report))
318
+ list.sort();
319
+ return report;
320
+ }
321
+ function trimDashesAndDots(text) {
322
+ let start = 0;
323
+ let end = text.length;
324
+ while (start < end && (text[start] === "-" || text[start] === "."))
325
+ start++;
326
+ while (end > start && (text[end - 1] === "-" || text[end - 1] === "."))
327
+ end--;
328
+ return text.slice(start, end);
329
+ }