@cavelon/cli 0.1.3 → 0.1.5

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 (43) hide show
  1. package/README.md +43 -17
  2. package/dist/agent-env.js +24 -0
  3. package/dist/choose.js +8 -4
  4. package/dist/code-hints.js +74 -0
  5. package/dist/commands/api.js +174 -33
  6. package/dist/commands/async.js +26 -5
  7. package/dist/commands/docs.js +183 -37
  8. package/dist/commands/fmt.js +117 -0
  9. package/dist/commands/index.js +6 -1
  10. package/dist/commands/init.js +28 -6
  11. package/dist/commands/inventory.js +27 -5
  12. package/dist/commands/models.js +7 -1
  13. package/dist/commands/schema.js +193 -0
  14. package/dist/commands/session.js +69 -13
  15. package/dist/commands/solution.js +275 -36
  16. package/dist/commands/tenants.js +125 -15
  17. package/dist/commands/work.js +245 -24
  18. package/dist/contracts.js +3 -0
  19. package/dist/default-route.js +21 -0
  20. package/dist/errors.js +4 -0
  21. package/dist/git.js +14 -5
  22. package/dist/http.js +27 -4
  23. package/dist/invoke.js +8 -4
  24. package/dist/kit-codes.js +85 -0
  25. package/dist/limits.js +12 -1
  26. package/dist/local-state.js +9 -2
  27. package/dist/main.js +16 -3
  28. package/dist/mcp.js +19 -8
  29. package/dist/openapi.js +91 -21
  30. package/dist/operations.js +4 -3
  31. package/dist/package-check.js +193 -4
  32. package/dist/package-files.js +21 -10
  33. package/dist/package-format.js +149 -0
  34. package/dist/package-references.js +231 -0
  35. package/dist/paths.js +4 -3
  36. package/dist/preview-report.js +152 -0
  37. package/dist/results.js +65 -5
  38. package/dist/skills/cavelon-authoring/SKILL.md +67 -8
  39. package/dist/skills/cavelon-long-running/SKILL.md +3 -1
  40. package/dist/skills/cavelon-loop/SKILL.md +75 -13
  41. package/dist/skills/cavelon-testing/SKILL.md +85 -4
  42. package/dist/tenant-choice.js +12 -5
  43. package/package.json +3 -3
@@ -6,6 +6,7 @@ import { failureLines, resultFailure } from "../results.js";
6
6
  import { readEvents } from "../sse.js";
7
7
  export const DEFAULT_WAIT = "90s";
8
8
  const MCP_TIMEOUT_MS = 0;
9
+ export const MCP_MAX_WAIT_MS = 50_000;
9
10
  export const TIMEOUT_OPTION = {
10
11
  type: "string",
11
12
  value: "<duration>",
@@ -20,10 +21,22 @@ function intervalMs(ctx) {
20
21
  const fromEnv = Number(ctx.io.env.CAVELON_POLL_INTERVAL_MS);
21
22
  return Number.isFinite(fromEnv) && fromEnv > 0 ? fromEnv : 1000;
22
23
  }
24
+ function waitTimeoutMs(ctx, raw) {
25
+ if (ctx.mode !== "mcp")
26
+ return parseDuration(raw ?? DEFAULT_WAIT);
27
+ if (raw === undefined || raw === "")
28
+ return 0;
29
+ const asked = parseDuration(raw);
30
+ if (asked > MCP_MAX_WAIT_MS) {
31
+ ctx.warn(`operation_status waits at most ${MCP_MAX_WAIT_MS / 1000} s, not ${raw}; call it again to keep waiting.`);
32
+ return MCP_MAX_WAIT_MS;
33
+ }
34
+ return asked;
35
+ }
23
36
  export async function waitAndReport(ctx, ids, timeout) {
24
37
  const client = await ctx.client();
25
38
  const progress = !ctx.json && ctx.io.stderr.isTTY && ctx.mode === "cli";
26
- const { operations, timedOut } = await waitFor(ctx, client, ids, {
39
+ const { operations, timedOut, waitedMs } = await waitFor(ctx, client, ids, {
27
40
  timeoutMs: timeout,
28
41
  intervalMs: intervalMs(ctx),
29
42
  onChange: progress ? (op) => ctx.io.stderr.write(`${ctx.style.dim(describe(op).split("\n")[0])}\n`) : undefined,
@@ -39,6 +52,8 @@ export async function waitAndReport(ctx, ids, timeout) {
39
52
  operations,
40
53
  settled: pending.length === 0,
41
54
  timed_out: timedOut,
55
+ timeout_ms: timeout,
56
+ waited_ms: waitedMs,
42
57
  ...(pending.length ? { resume: `cavelon wait ${pending.join(" ")}` } : {}),
43
58
  ...(waits.length ? { capacity_waits: waits } : {}),
44
59
  ...(refusals.length ? { capacity_refusals: refusals } : {}),
@@ -59,19 +74,25 @@ export const wait = {
59
74
  name: "wait",
60
75
  summary: "Wait until operations finish, need a person, or the timeout passes.",
61
76
  description: "Exit 0 when all succeeded, 1 when one failed or was cancelled, 5 when one needs a person,\n" +
62
- "6 when the timeout passed first. A test run that finished with failed cases counts as failed, and its cases are named.\n" +
63
- "The state is printed in every case, and a second `wait` resumes.",
77
+ "6 when one still runs at the end (timed_out says whether it waited the whole timeout; --timeout 0 reads the state once).\n" +
78
+ "A test run that finished with failed cases counts as failed, and its cases are named.\n" +
79
+ "The state is printed in every case with waited_ms, and a second `wait` resumes. As the MCP tool operation_status it\n" +
80
+ `returns the state at once unless given a timeout, and waits at most ${MCP_MAX_WAIT_MS / 1000} s.`,
64
81
  readOnly: true,
65
82
  idempotent: true,
66
83
  mcpTool: "operation_status",
67
84
  positionals: [{ name: "operation", description: "Operation ids (op_…).", required: true, variadic: true }],
68
85
  options: {
69
- timeout: TIMEOUT_OPTION,
86
+ timeout: {
87
+ ...TIMEOUT_OPTION,
88
+ description: `Stop waiting after this long (90s, 5m; default ${DEFAULT_WAIT}). The work goes on; run wait again to resume. ` +
89
+ `As an MCP tool: none by default (returns at once), at most ${MCP_MAX_WAIT_MS / 1000}s.`,
90
+ },
70
91
  },
71
92
  examples: ["cavelon wait op_test_run_0f…", "cavelon wait op_a op_b --timeout 5m --json"],
72
93
  async run(ctx, input) {
73
94
  const ids = input.positionals.operation.filter(Boolean);
74
- return waitAndReport(ctx, [...new Set(ids)], timeoutMs(ctx, stringOption(input, "timeout")));
95
+ return waitAndReport(ctx, [...new Set(ids)], waitTimeoutMs(ctx, stringOption(input, "timeout")));
75
96
  },
76
97
  };
77
98
  export const watch = {
@@ -50,7 +50,7 @@ async function loadIndex(ctx) {
50
50
  else {
51
51
  text = await fetchIndex(client);
52
52
  }
53
- return { client, entries: parseIndex(text, client.url) };
53
+ return { client, entries: parseIndex(text, client.url), text };
54
54
  }
55
55
  export async function listedPages(ctx, pages) {
56
56
  try {
@@ -61,44 +61,180 @@ export async function listedPages(ctx, pages) {
61
61
  return [];
62
62
  }
63
63
  }
64
- function terms(query) {
65
- return query
64
+ const STOP_WORDS = new Set(("a an and are as at be by can could do does for from get got have how i in into is it its me my of on or our should so " +
65
+ "that the their them then there these this those to use using was we what when where which who why will with would you your " +
66
+ "aber alle als am an auch auf aus bei bin bis da damit dann das dass dem den der des die dies diese diesem diesen dieser " +
67
+ "doch du ein eine einem einen einer eines er es für geht gibt hat habe haben ich ihr im in ist ja kann kannst können man " +
68
+ "mein meine meinem meinen meiner mich mir mit muss müssen nach nicht noch nur ob oder sich sie sind so soll um und uns " +
69
+ "unser unsere vom von vor war was welche welcher welches wenn wer werden wie wird wo zu zum zur").split(" "));
70
+ const CONCEPT_TERMS = {
71
+ bot: "solution",
72
+ bots: "solution",
73
+ chatbot: "solution",
74
+ wissensbasis: "knowledge base",
75
+ wissensbasen: "knowledge base",
76
+ wissensdatenbank: "knowledge base",
77
+ wissensdatenbanken: "knowledge base",
78
+ dokument: "document",
79
+ dokumente: "document",
80
+ dokumenten: "document",
81
+ datei: "file",
82
+ dateien: "file",
83
+ hochladen: "upload",
84
+ lade: "upload",
85
+ laden: "upload",
86
+ hoch: "upload",
87
+ teste: "test",
88
+ testen: "test",
89
+ testet: "test",
90
+ tests: "test",
91
+ testfall: "test case",
92
+ testfälle: "test case",
93
+ agent: "agent",
94
+ agenten: "agent",
95
+ standard: "default",
96
+ standardmodell: "default model",
97
+ standardantwort: "default answer",
98
+ antwort: "answer",
99
+ antworten: "answer",
100
+ nutzer: "user",
101
+ benutzer: "user",
102
+ standardmäßig: "default",
103
+ voreinstellung: "default",
104
+ modell: "model",
105
+ modelle: "model",
106
+ sprachmodell: "model",
107
+ werkzeug: "tool",
108
+ werkzeuge: "tool",
109
+ fähigkeit: "skill",
110
+ fähigkeiten: "skill",
111
+ lösung: "solution",
112
+ lösungen: "solution",
113
+ auslöser: "trigger",
114
+ geheimnis: "secret",
115
+ geheimnisse: "secret",
116
+ variablen: "variable",
117
+ grenze: "limit",
118
+ grenzen: "limit",
119
+ gedächtnis: "memory",
120
+ erinnerung: "memory",
121
+ übergabe: "handoff",
122
+ übergaben: "handoff",
123
+ freigabe: "approval",
124
+ genehmigung: "approval",
125
+ kanal: "channel",
126
+ kanäle: "channel",
127
+ ablaufverfolgung: "trace",
128
+ protokoll: "trace",
129
+ aktivieren: "activate",
130
+ veröffentlichen: "activate",
131
+ bereitstellen: "deploy",
132
+ anmelden: "login",
133
+ mandant: "tenant",
134
+ mandanten: "tenant",
135
+ persona: "persona",
136
+ leitplanken: "guardrail",
137
+ schleife: "loop",
138
+ kosten: "cost",
139
+ kapazität: "capacity",
140
+ };
141
+ function stem(word) {
142
+ if (word.length > 5 && word.endsWith("ing"))
143
+ return word.slice(0, -3);
144
+ if (word.length > 3 && word.endsWith("s") && !word.endsWith("ss"))
145
+ return word.slice(0, -1);
146
+ return word;
147
+ }
148
+ function words(text) {
149
+ return text
66
150
  .toLowerCase()
67
- .split(/[^\p{L}\p{N}_]+/u)
68
- .filter((t) => t.length > 1);
151
+ .split(/[^\p{L}\p{N}]+/u)
152
+ .filter(Boolean);
153
+ }
154
+ export function queryTerms(query) {
155
+ const terms = [];
156
+ const phrases = [];
157
+ const raw = words(query).filter((w) => !STOP_WORDS.has(w));
158
+ for (const word of raw) {
159
+ const english = CONCEPT_TERMS[word];
160
+ const parts = english ? english.split(" ") : [word];
161
+ if (parts.length > 1)
162
+ phrases.push(parts.map(stem));
163
+ for (const part of parts)
164
+ if (part.length > 1 || /\p{N}/u.test(part))
165
+ terms.push(stem(part));
166
+ }
167
+ for (let i = 0; i + 1 < terms.length; i++)
168
+ phrases.push([terms[i], terms[i + 1]]);
169
+ return { terms: [...new Set(terms)], phrases };
69
170
  }
171
+ function fieldWords(text) {
172
+ return words(text).map(stem);
173
+ }
174
+ function hasPhrase(field, phrase) {
175
+ for (let i = 0; i + phrase.length <= field.length; i++) {
176
+ if (phrase.every((w, j) => field[i + j] === w))
177
+ return true;
178
+ }
179
+ return false;
180
+ }
181
+ const MIN_EVIDENCE = 2;
182
+ const MIN_SHARE_OF_BEST = 0.35;
70
183
  export function searchIndex(entries, query) {
71
- const words = terms(query);
72
- const phrase = query.trim().toLowerCase();
73
- return entries
74
- .map((entry) => {
75
- const title = entry.title.toLowerCase();
76
- const description = entry.description.toLowerCase();
77
- const page = entry.page.toLowerCase();
78
- const section = entry.section.toLowerCase();
184
+ const { terms, phrases } = queryTerms(query);
185
+ if (!terms.length)
186
+ return [];
187
+ const fields = entries.map((entry) => ({
188
+ entry,
189
+ title: fieldWords(entry.title),
190
+ page: fieldWords(entry.page),
191
+ description: fieldWords(entry.description),
192
+ section: fieldWords(entry.section),
193
+ }));
194
+ const weight = new Map();
195
+ for (const term of terms) {
196
+ const pages = fields.filter((f) => f.title.includes(term) || f.page.includes(term) || f.description.includes(term)).length;
197
+ weight.set(term, Math.log(1 + entries.length / (1 + pages)));
198
+ }
199
+ const scored = fields
200
+ .map(({ entry, title, page, description, section }) => {
201
+ let evidence = 0;
79
202
  let score = 0;
80
- if (phrase && title.includes(phrase))
81
- score += 10;
82
- if (phrase && description.includes(phrase))
83
- score += 4;
84
- for (const word of words) {
85
- if (title.includes(word))
86
- score += 3;
87
- if (page.includes(word))
88
- score += 2;
89
- if (description.includes(word))
90
- score += 1;
91
- if (section.includes(word))
92
- score += 1;
203
+ for (const term of terms) {
204
+ const hits = (title.includes(term) ? 3 : 0) + (page.includes(term) ? 2 : 0) + (description.includes(term) ? 1 : 0) + (section.includes(term) ? 1 : 0);
205
+ evidence += hits;
206
+ score += hits * weight.get(term);
207
+ }
208
+ for (const phrase of phrases) {
209
+ const w = Math.max(...phrase.map((t) => weight.get(t) ?? 1));
210
+ if (hasPhrase(title, phrase))
211
+ score += 3 * w;
212
+ else if (hasPhrase(description, phrase))
213
+ score += w;
93
214
  }
94
- return { ...entry, score };
215
+ const titleWords = title.filter((w) => !STOP_WORDS.has(w));
216
+ const named = titleWords.filter((w) => terms.includes(w));
217
+ if (titleWords.length && named.length / titleWords.length >= 0.5)
218
+ score += (3 * named.length * Math.max(...named.map((t) => weight.get(t)))) / titleWords.length;
219
+ if (score > 0 && section.includes("concept"))
220
+ score *= 1.15;
221
+ return { ...entry, score: Math.round(score * 100) / 100, evidence };
95
222
  })
96
- .filter((e) => e.score > 0)
97
- .sort((a, b) => b.score - a.score || a.title.localeCompare(b.title));
223
+ .filter((e) => e.evidence >= MIN_EVIDENCE);
224
+ const best = Math.max(0, ...scored.map((e) => e.score));
225
+ return scored
226
+ .filter((e) => e.score >= best * MIN_SHARE_OF_BEST)
227
+ .sort((a, b) => b.score - a.score || a.title.localeCompare(b.title))
228
+ .map(({ evidence: _evidence, ...e }) => e);
98
229
  }
230
+ const INDEX_REF = "index";
99
231
  export const docsSearch = {
100
232
  name: "docs search",
101
233
  summary: "Search this instance's docs (titles and summaries).",
234
+ description: "Ranks the pages of the instance's docs index by the words of the question in their titles, addresses and\n" +
235
+ "summaries, rare words counting more than common ones. Stop words (English and German) are ignored, words match\n" +
236
+ "whole (\"test\" finds \"testing\", not \"latest\"), and German words for the core concepts are looked up in English\n" +
237
+ "(Wissensbasis: knowledge base). Only pages that match well are listed.",
102
238
  readOnly: true,
103
239
  idempotent: true,
104
240
  mcpTool: "docs_search",
@@ -109,12 +245,14 @@ export const docsSearch = {
109
245
  const limit = intOption(input, "limit", { min: 1, max: 100, fallback: 10 });
110
246
  const { entries } = await loadIndex(ctx);
111
247
  const hits = searchIndex(entries, query);
248
+ const { terms } = queryTerms(query);
112
249
  const items = hits.slice(0, limit).map(({ page, title, description, section }) => ({ page, title, section, description }));
250
+ const none = `No page matches "${query}"${terms.length ? ` (looked for: ${terms.join(", ")})` : " (it has only stop words)"}. ` +
251
+ `The docs are in English: try English words for the concept (knowledge base, test, trigger, default), ` +
252
+ `or read the list of all ${entries.length} pages with: ${cavelonCommand("docs", "get", INDEX_REF)}`;
113
253
  return {
114
- data: { query, items, total: hits.length },
115
- text: items.length
116
- ? `${table(items, ["page", "title", "description"], 70)}\n\nRead one: cavelon docs get <page>`
117
- : `No page matches "${query}". The index has ${entries.length} pages.`,
254
+ data: { query, terms, items, total: hits.length, ...(items.length ? {} : { hint: none }) },
255
+ text: items.length ? `${table(items, ["page", "title", "description"], 70)}\n\nRead one: cavelon docs get <page>` : none,
118
256
  };
119
257
  },
120
258
  };
@@ -124,18 +262,28 @@ export const docsGet = {
124
262
  readOnly: true,
125
263
  idempotent: true,
126
264
  mcpTool: "docs_get",
127
- positionals: [{ name: "page", description: "section/slug from `docs search`, a title, or the page URL.", required: true }],
265
+ positionals: [{ name: "page", description: "section/slug from `docs search`, a title, the page URL, or `index` for the list of all pages.", required: true }],
128
266
  options: {
129
267
  "max-chars": { type: "string", value: "<n>", description: "Print at most n characters (default 40000)." },
130
268
  cursor: { type: "string", value: "<offset>", description: "Continue a long page where the previous output stopped." },
131
269
  },
132
270
  async run(ctx, input) {
133
271
  const ref = positional(input, "page");
134
- const { client, entries } = await loadIndex(ctx);
272
+ const { client, entries, text: index } = await loadIndex(ctx);
135
273
  const wanted = ref.replace(/\.md$/, "").replace(/^\/+/, "");
136
274
  const entry = entries.find((e) => e.page === wanted || e.url === ref) ??
137
275
  entries.find((e) => e.title.toLowerCase() === ref.toLowerCase()) ??
138
276
  entries.find((e) => e.page.endsWith(`/${wanted}`));
277
+ const max = intOption(input, "max-chars", { min: 100, fallback: 40_000 });
278
+ const offset = intOption(input, "cursor", { min: 0, fallback: 0 });
279
+ if (!entry && (wanted === INDEX_REF || wanted === "llms.txt")) {
280
+ const chunk = index.slice(offset, offset + max);
281
+ const next = offset + max < index.length ? String(offset + max) : null;
282
+ return {
283
+ data: { page: INDEX_REF, title: "Docs index", url: `${client.url}/llms.txt`, markdown: chunk, next_cursor: next, length: index.length },
284
+ text: chunk + (next ? `\n\n… index continues: ${cavelonCommand("docs", "get", INDEX_REF, "--cursor", next)}` : ""),
285
+ };
286
+ }
139
287
  if (!entry) {
140
288
  const near = searchIndex(entries, ref.replace(/[/-]/g, " ")).slice(0, 5).map((e) => e.page);
141
289
  throw new CavelonError(ExitCode.failure, {
@@ -146,8 +294,6 @@ export const docsGet = {
146
294
  }
147
295
  const response = await client.get(entry.url, { accept: "text/markdown, text/plain" });
148
296
  const markdown = response.text;
149
- const max = intOption(input, "max-chars", { min: 100, fallback: 40_000 });
150
- const offset = intOption(input, "cursor", { min: 0, fallback: 0 });
151
297
  const chunk = markdown.slice(offset, offset + max);
152
298
  const next = offset + max < markdown.length ? String(offset + max) : null;
153
299
  return {
@@ -0,0 +1,117 @@
1
+ import path from "node:path";
2
+ import { boolOption } from "../command.js";
3
+ import { CavelonError, ExitCode } from "../errors.js";
4
+ import { readTextFile, writeFileAtomic } from "../fsutil.js";
5
+ import { fileDigest, fileDigests, readPulledFiles, rememberAppliedFiles } from "../local-state.js";
6
+ import { packageVersionOf } from "../package-check.js";
7
+ import { canonical, contentPath, readPackage } from "../package-files.js";
8
+ import { exportForm, sectionContent, toYaml } from "../package-format.js";
9
+ import { requireInstance } from "../session.js";
10
+ import { requireSolution, schemaFor } from "./solution.js";
11
+ export const fmt = {
12
+ name: "fmt",
13
+ summary: "Bring the package files into the export's form (field order and defaults from the package schema), offline.",
14
+ description: "A file whose value the export would spell differently is rewritten: each field in the schema's order, and each field it\n" +
15
+ "leaves out set to the schema's default, as the export writes it (the instance applies the same defaults, so nothing\n" +
16
+ "changes in what apply sends but the spelling). Lists become block lists; the persona file shows every field, the unset\n" +
17
+ "ones as comments. Comments in a rewritten file are not kept, as pull does not keep them. A file already in that form\n" +
18
+ "keeps its bytes, and so do the files of sections the schema does not know. Run it after writing package files by hand\n" +
19
+ "and before `apply`, so the next `pull` shows only what changed on the instance. --check writes nothing and exits 3 when a\n" +
20
+ "file would change. Uses the cached package schema (as validate does); --offline never contacts the instance.",
21
+ readOnly: false,
22
+ idempotent: true,
23
+ mcpTool: "fmt",
24
+ mcpEffect: "Changes nothing on the instance. Rewrites package files in the solution folder (not with check).",
25
+ options: {
26
+ check: { type: "boolean", description: "Write nothing; exit 3 when a file would change." },
27
+ offline: { type: "boolean", description: "Never contact the instance, even when no schema is cached." },
28
+ },
29
+ examples: ["cavelon fmt", "cavelon fmt --check"],
30
+ async run(ctx, input) {
31
+ const session = await ctx.session();
32
+ const project = requireSolution(session);
33
+ requireInstance(session);
34
+ const check = boolOption(input, "check");
35
+ const disk = await readPackage(project.root, project.layout);
36
+ const invalid = disk.findings.filter((f) => f.severity === "error");
37
+ if (invalid.length) {
38
+ throw new CavelonError(ExitCode.validation, {
39
+ code: "package_file_invalid",
40
+ message: `${invalid.length} package file${invalid.length === 1 ? "" : "s"} cannot be read: ${invalid.map((f) => `${f.file}${f.line ? `:${f.line}` : ""}`).join(", ")}.`,
41
+ hint: "Fix them first (`cavelon validate` names each); fmt changes nothing until then.",
42
+ });
43
+ }
44
+ const version = packageVersionOf(disk.package) ?? project.packageVersion;
45
+ const { schema } = await schemaFor(ctx, version, boolOption(input, "offline"));
46
+ if (!schema) {
47
+ throw new CavelonError(ExitCode.failure, {
48
+ code: "package_schema_unavailable",
49
+ message: `No package schema${version ? ` for format ${version}` : ""} is cached for this instance, and it was not read.`,
50
+ hint: "Run `cavelon fmt` (or `cavelon validate`) once without --offline while the instance is reachable.",
51
+ });
52
+ }
53
+ const changes = [];
54
+ let unchanged = 0;
55
+ for (const [section, source] of Object.entries(disk.sources)) {
56
+ const node = schema.properties?.[section];
57
+ if (!node)
58
+ continue;
59
+ if (Array.isArray(source)) {
60
+ const items = Array.isArray(disk.package[section]) ? disk.package[section] : [];
61
+ source.forEach((s, i) => {
62
+ const item = items[i];
63
+ const formed = exportForm(schema, node, [item])[0];
64
+ if (canonical(item) === canonical(formed))
65
+ unchanged++;
66
+ else
67
+ changes.push({ file: s.file, content: toYaml(formed) });
68
+ });
69
+ continue;
70
+ }
71
+ const value = disk.package[section];
72
+ const formed = exportForm(schema, node, value);
73
+ if (canonical(value ?? null) === canonical(formed ?? null))
74
+ unchanged++;
75
+ else
76
+ changes.push({ file: source.file, content: sectionContent(section, formed, schema, /\.json$/i.test(source.file)) });
77
+ }
78
+ const written = [];
79
+ if (!check && changes.length) {
80
+ const known = await readPulledFiles(project.root);
81
+ const wasKnown = [];
82
+ for (const change of changes) {
83
+ const file = path.join(project.root, change.file);
84
+ const target = await contentPath(project.root, file);
85
+ if (target === undefined)
86
+ continue;
87
+ if ((await readTextFile(target)) === change.content)
88
+ continue;
89
+ if (known[change.file] !== undefined && known[change.file] === (await fileDigest(file)))
90
+ wasKnown.push(change.file);
91
+ await writeFileAtomic(target, change.content);
92
+ written.push(change.file);
93
+ }
94
+ if (wasKnown.length)
95
+ await rememberAppliedFiles(project.root, await fileDigests(project.root, wasKnown));
96
+ }
97
+ const files = changes.map((c) => c.file).sort((a, b) => a.localeCompare(b, "en"));
98
+ const data = { check, changed: files, written: written.sort((a, b) => a.localeCompare(b, "en")), unchanged };
99
+ if (check) {
100
+ return {
101
+ data,
102
+ text: files.length
103
+ ? [...files.map((f) => `would format ${f}`), `${files.length} file${files.length === 1 ? "" : "s"} not in the export's form; run \`cavelon fmt\`.`].join("\n")
104
+ : `All ${unchanged} package files are in the export's form.`,
105
+ exitCode: files.length ? ExitCode.validation : ExitCode.ok,
106
+ };
107
+ }
108
+ return {
109
+ data,
110
+ text: [
111
+ ...written.map((f) => `formatted ${f}`),
112
+ `${written.length} file${written.length === 1 ? "" : "s"} formatted, ${unchanged} already in the export's form.`,
113
+ ...(written.length ? ["Check it: cavelon validate; then git diff shows only the spelling."] : []),
114
+ ].join("\n"),
115
+ };
116
+ },
117
+ };
@@ -4,12 +4,14 @@ import { wait, watch } from "./async.js";
4
4
  import { docsGet, docsSearch } from "./docs.js";
5
5
  import { login, logout, status, use, whoami } from "./session.js";
6
6
  import { init } from "./init.js";
7
+ import { fmt } from "./fmt.js";
7
8
  import { setup } from "./setup.js";
8
9
  import { limits } from "./limits.js";
9
10
  import { limitsSet } from "./limits-set.js";
10
11
  import { modelsList, modelsSetLimit } from "./models.js";
11
12
  import { activate, apply, explain, pull, validate } from "./solution.js";
12
- import { harnessClone, harnessList, harnessNew, tenantCreate, tenantList } from "./tenants.js";
13
+ import { schema } from "./schema.js";
14
+ import { harnessClone, harnessDefault, harnessList, harnessNew, tenantCreate, tenantList } from "./tenants.js";
13
15
  import { kbUpload, testRun, trace } from "./work.js";
14
16
  import { secretsDelete, secretsList, secretsSet, variablesDelete, variablesGet, variablesList, variablesSet } from "./values.js";
15
17
  import { loopCancel, loopIterations, loopPause, loopResume, loopStart, loopWatch, triggerIdentity } from "./loops.js";
@@ -67,12 +69,15 @@ export const COMMANDS = [
67
69
  tenantCreate,
68
70
  tenantList,
69
71
  harnessList,
72
+ harnessDefault,
70
73
  harnessNew,
71
74
  harnessClone,
72
75
  activate,
73
76
  init,
74
77
  pull,
75
78
  validate,
79
+ fmt,
80
+ schema,
76
81
  apply,
77
82
  explain,
78
83
  variablesList,
@@ -7,10 +7,11 @@ import { CavelonError, ExitCode, usageError } from "../errors.js";
7
7
  import { confinedPath, realPath, within } from "../paths.js";
8
8
  import { readTextFile, withoutBom, writeFileAtomic } from "../fsutil.js";
9
9
  import { git } from "../git.js";
10
- import { ensureStateDir, STATE_DIR } from "../local-state.js";
10
+ import { ensureStateDir, fileDigests, rememberAppliedFiles, STATE_DIR } from "../local-state.js";
11
11
  import { isGenerated, upsertBlock, upsertJsonEntry } from "../markers.js";
12
12
  import { packageVersionOf } from "../package-check.js";
13
- import { defaultLayoutFor, safeSectionName, schemaSections, toYaml, writePackage } from "../package-files.js";
13
+ import { PERSONA_SECTION, personaYaml, sectionFields } from "../package-format.js";
14
+ import { defaultLayoutFor, placeholdersOnly, safeSectionName, schemaSections, toYaml, writePackage } from "../package-files.js";
14
15
  import { readPrincipal, readTenantless } from "../principal.js";
15
16
  import { ENV_DIR, parseProject, PROJECT_FILE } from "../project.js";
16
17
  import { canAsk, readLine } from "../prompt.js";
@@ -76,6 +77,17 @@ async function ownFile(root, relative, content) {
76
77
  await writeFileAtomic(file, content);
77
78
  return { file: relative, action: "created" };
78
79
  }
80
+ async function personaPlaceholders(ctx, project) {
81
+ const { schema } = await schemaFor(ctx, project.packageVersion, false).catch(() => ({ schema: null }));
82
+ const fields = sectionFields(schema, PERSONA_SECTION);
83
+ if (!fields)
84
+ return undefined;
85
+ const relative = `${project.layout.package}/${PERSONA_SECTION}.yaml`;
86
+ const action = await ownFile(project.root, relative, personaYaml(null, fields));
87
+ if (action.action === "created")
88
+ await rememberAppliedFiles(project.root, await fileDigests(project.root, [relative]));
89
+ return action;
90
+ }
79
91
  async function generatedFile(root, relative, content) {
80
92
  const file = path.join(root, relative);
81
93
  const existing = await readTextFile(file);
@@ -129,7 +141,7 @@ async function writeMcp(root, target, onlyExisting) {
129
141
  if (target.format === "toml")
130
142
  return applyBlock(root, file, upsertBlock(existing, target.block, "hash", { onlyExisting }));
131
143
  if (onlyExisting) {
132
- let present = false;
144
+ let present;
133
145
  try {
134
146
  present = Boolean(existing && JSON.parse(existing)[target.keys[0]]?.[target.keys[1]]);
135
147
  }
@@ -263,7 +275,7 @@ async function initTenant(ctx, session) {
263
275
  const choice = await chooseTenant(ctx, client, reach);
264
276
  if (choice.kind === "none")
265
277
  throw noTenantError(client.url, false);
266
- if (choice.kind === "open") {
278
+ if (choice.kind !== "chosen") {
267
279
  throw tenantOpenError(client.url, reach, "A solution belongs to one tenant. ", {
268
280
  line: (ref) => cavelonCommand("init", "--tenant", ref),
269
281
  template: "cavelon init --tenant <name or slug>",
@@ -351,12 +363,17 @@ function envYaml(name, harness) {
351
363
  ].join("\n");
352
364
  }
353
365
  async function hasPackageFiles(root, dir) {
366
+ let names;
354
367
  try {
355
- return (await fs.readdir(path.join(root, dir))).some((n) => /\.(ya?ml|json)$/i.test(n));
368
+ names = (await fs.readdir(path.join(root, dir))).filter((n) => /\.(ya?ml|json)$/i.test(n));
356
369
  }
357
370
  catch {
358
371
  return false;
359
372
  }
373
+ for (const name of names)
374
+ if (!(await placeholdersOnly(root, `${dir}/${name}`)))
375
+ return true;
376
+ return false;
360
377
  }
361
378
  const MAX_PACKAGE_FILE_BYTES = 50 * 1024 * 1024;
362
379
  function importFileError(from, reason, hint) {
@@ -408,7 +425,7 @@ async function importPackage(ctx, project, from, pkg, force) {
408
425
  const planned = await writePackage(project.root, project.layout, pkg, schema, { dryRun: true });
409
426
  const overwritten = [];
410
427
  for (const file of planned.written) {
411
- if ((await readTextFile(path.join(project.root, file))) !== undefined)
428
+ if ((await readTextFile(path.join(project.root, file))) !== undefined && !(await placeholdersOnly(project.root, file)))
412
429
  overwritten.push(file);
413
430
  }
414
431
  const conflicts = [...overwritten, ...planned.removed].sort((a, b) => a.localeCompare(b, "en"));
@@ -555,6 +572,9 @@ async function runInit(ctx, input) {
555
572
  }
556
573
  else
557
574
  next.unshift("Bring an existing solution into package/: cavelon pull --harness <name or slug> (or write package files, then cavelon validate)");
575
+ const persona = await personaPlaceholders(ctx, project);
576
+ if (persona)
577
+ actions.push(persona);
558
578
  }
559
579
  return { root, actions, next, imported: result, harness: chosenHarness };
560
580
  }
@@ -569,6 +589,8 @@ export const init = {
569
589
  "file that holds something else unless --force, and names the sections the instance's schema does not know.",
570
590
  readOnly: false,
571
591
  destructive: true,
592
+ mcpEffect: "Changes nothing on the instance (as a tool it never creates a solution). Writes files in the solution folder; never overwrites a " +
593
+ "file it did not create, and changes only the blocks between its markers in AGENTS.md, CLAUDE.md and .gitignore.",
572
594
  idempotent: true,
573
595
  mcpTool: "init",
574
596
  options: {