@cavelon/cli 0.1.4 → 0.1.6

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 (50) hide show
  1. package/README.md +58 -22
  2. package/dist/choose.js +8 -4
  3. package/dist/code-hints.js +74 -0
  4. package/dist/commands/api.js +83 -44
  5. package/dist/commands/async.js +26 -5
  6. package/dist/commands/chat.js +177 -0
  7. package/dist/commands/docs.js +240 -37
  8. package/dist/commands/fmt.js +120 -0
  9. package/dist/commands/index.js +9 -1
  10. package/dist/commands/init.js +64 -30
  11. package/dist/commands/inventory.js +48 -5
  12. package/dist/commands/limits-set.js +9 -6
  13. package/dist/commands/loops.js +15 -9
  14. package/dist/commands/models.js +16 -7
  15. package/dist/commands/sandboxes.js +8 -4
  16. package/dist/commands/schema.js +361 -0
  17. package/dist/commands/session.js +148 -24
  18. package/dist/commands/setup.js +22 -6
  19. package/dist/commands/solution.js +537 -76
  20. package/dist/commands/tenants.js +156 -15
  21. package/dist/commands/values.js +18 -9
  22. package/dist/commands/work.js +343 -35
  23. package/dist/confirm-token.js +72 -0
  24. package/dist/contracts.js +3 -0
  25. package/dist/default-route.js +21 -0
  26. package/dist/errors.js +4 -0
  27. package/dist/git.js +14 -5
  28. package/dist/harness-ref.js +14 -1
  29. package/dist/http.js +27 -4
  30. package/dist/invoke.js +8 -4
  31. package/dist/kit-codes.js +91 -0
  32. package/dist/limits.js +12 -1
  33. package/dist/local-state.js +32 -7
  34. package/dist/main.js +52 -4
  35. package/dist/mcp.js +72 -15
  36. package/dist/openapi.js +77 -21
  37. package/dist/operations.js +4 -3
  38. package/dist/package-check.js +361 -12
  39. package/dist/package-files.js +92 -45
  40. package/dist/package-format.js +222 -0
  41. package/dist/package-references.js +298 -0
  42. package/dist/preview-report.js +152 -0
  43. package/dist/results.js +21 -1
  44. package/dist/skills/cavelon-authoring/SKILL.md +98 -13
  45. package/dist/skills/cavelon-long-running/SKILL.md +3 -1
  46. package/dist/skills/cavelon-loop/SKILL.md +129 -21
  47. package/dist/skills/cavelon-testing/SKILL.md +130 -10
  48. package/dist/tenant-choice.js +31 -5
  49. package/dist/trace-view.js +172 -0
  50. package/package.json +1 -1
@@ -0,0 +1,177 @@
1
+ import { parseDuration, positional, stringOption } from "../command.js";
2
+ import { confirmation, confirmTokenRequired } from "../confirm-token.js";
3
+ import { named, readDefaultRoute } from "../default-route.js";
4
+ import { CavelonError, ExitCode, usageError } from "../errors.js";
5
+ import { clip } from "../format.js";
6
+ import { harnessNotFoundError, lookupHarness } from "../harness-ref.js";
7
+ import { callStable, workflowOperation } from "../invoke.js";
8
+ import { cavelonCommand } from "../shell.js";
9
+ import { MCP_MAX_WAIT_MS } from "./async.js";
10
+ function harnessRef(session, input) {
11
+ const option = stringOption(input, "harness");
12
+ if (option)
13
+ return { ref: option, source: "option" };
14
+ if (session.envFile?.harness)
15
+ return { ref: session.envFile.harness, source: `env/${session.envFile.name}.yaml` };
16
+ if (session.project?.harness)
17
+ return { ref: session.project.harness, source: "cavelon.yaml" };
18
+ return {};
19
+ }
20
+ async function findHarness(ctx, ref, source, command) {
21
+ const { harness, candidates } = await lookupHarness(ctx, ref);
22
+ if (!harness)
23
+ throw harnessNotFoundError(ref, candidates, source === "option" ? undefined : source, command);
24
+ return harness;
25
+ }
26
+ const HARNESS_OPTION = {
27
+ type: "string",
28
+ value: "<harness>",
29
+ description: "The solution (harness): its name, slug or id; default: env file, then cavelon.yaml.",
30
+ };
31
+ const ENV_OPTION = { type: "string", value: "<name>", description: "Use env/<name>.yaml: its tenant and solution." };
32
+ const DEFAULT_CHAT_TIMEOUT = "2m";
33
+ function chatError(error, harness) {
34
+ if (!(error instanceof CavelonError) || error.status !== 409)
35
+ return error;
36
+ const hint = !harness
37
+ ? "Nothing answers on the tenant's default route yet: name a solution with --harness, or make an active one the default (`cavelon harness default <solution>`)."
38
+ : harness.status !== "active"
39
+ ? `${named(harness)} is ${harness.status}: a draft answers only a person's token (as a Playground run), never a tenant API key. Use a personal access token, or activate it first (\`cavelon activate --harness ${harness.slug}\`).`
40
+ : "A session belongs to the solution it started with: leave out --session to start a new one.";
41
+ return new CavelonError(error.exitCode, { code: error.code, status: error.status, message: error.message, hint, docs: error.docs, details: error.details });
42
+ }
43
+ export const chat = {
44
+ name: "chat",
45
+ summary: "Send one message to a solution and print its answer, with the session to continue and the conversation to trace.",
46
+ description: "The tenant's chat and widget answer only with the default route; this names the solution, so an active solution that is\n" +
47
+ "not the default, or a draft, can be tried before it answers anyone. A draft answers a person's token as a Playground run\n" +
48
+ "(counted as testing), never a tenant API key. Without --harness: the env file's or cavelon.yaml's solution, else the\n" +
49
+ "tenant's default route. Each call is one turn; --session continues a conversation. Not streamed: waits for the whole\n" +
50
+ `answer, at most --timeout (default ${DEFAULT_CHAT_TIMEOUT}; ${MCP_MAX_WAIT_MS / 1000} s as an MCP tool).`,
51
+ readOnly: false,
52
+ mcpEffect: "Starts or continues a conversation with the solution and runs its agents (model usage, its tools' actions); changes no configuration.",
53
+ mcpTool: "chat",
54
+ positionals: [{ name: "message", description: "What the user says.", required: true }],
55
+ options: {
56
+ harness: HARNESS_OPTION,
57
+ env: ENV_OPTION,
58
+ session: { type: "string", value: "<session_id>", description: "Continue this conversation (the session_id a previous chat printed)." },
59
+ timeout: { type: "string", value: "<duration>", description: `Wait at most this long for the answer (90s, 5m; default ${DEFAULT_CHAT_TIMEOUT}).` },
60
+ },
61
+ examples: ['cavelon chat "When are you open?" --harness support-faq', 'cavelon chat "And on Saturdays?" --session <session_id>', 'cavelon chat "Hello" --json'],
62
+ async run(ctx, input) {
63
+ const message = positional(input, "message");
64
+ if (!message.trim())
65
+ throw usageError("The message is empty.");
66
+ const raw = stringOption(input, "timeout");
67
+ const timeout = Math.min(parseDuration(raw ?? DEFAULT_CHAT_TIMEOUT), ctx.mode === "mcp" ? MCP_MAX_WAIT_MS : Number.MAX_SAFE_INTEGER);
68
+ const session = await ctx.session();
69
+ const { ref, source } = harnessRef(session, input);
70
+ const harness = ref ? await findHarness(ctx, ref, source, (slug) => cavelonCommand("chat", "<message>", "--harness", slug)) : undefined;
71
+ const body = { message, stream: false };
72
+ if (harness)
73
+ body.harness_id = harness.id;
74
+ const sessionId = stringOption(input, "session");
75
+ if (sessionId)
76
+ body.session_id = sessionId;
77
+ let answer;
78
+ try {
79
+ answer = await callStable(ctx, "POST", "/api/v1/chat", "chatting with a solution", { body, timeoutMs: timeout });
80
+ }
81
+ catch (error) {
82
+ throw chatError(error, harness);
83
+ }
84
+ const target = harness ? { id: harness.id, slug: harness.slug, name: harness.name, status: harness.status } : null;
85
+ if (answer.retrieval_warning)
86
+ ctx.warn(answer.retrieval_warning);
87
+ const next = {
88
+ continue: cavelonCommand("chat", "<message>", "--session", answer.session_id),
89
+ trace: cavelonCommand("trace", answer.conversation_id, "--kind", "conversation"),
90
+ };
91
+ const who = harness ? named(harness) : "The default route";
92
+ const directives = answer.ui_directives?.length ? `\n(${answer.ui_directives.length} UI directive${answer.ui_directives.length === 1 ? "" : "s"}, such as a form; --json shows them)` : "";
93
+ const limit = answer.limit_error ? `\nlimit: ${clip(JSON.stringify(answer.limit_error), 300)}` : "";
94
+ return {
95
+ data: { harness: target, ...answer, next },
96
+ text: [
97
+ `${who} answered:`,
98
+ `${answer.response || "(no text)"}${directives}${limit}`,
99
+ "",
100
+ `session: ${answer.session_id} continue with: ${next.continue}`,
101
+ `conversation_id: ${answer.conversation_id} its traces: ${next.trace}`,
102
+ ].join("\n"),
103
+ };
104
+ },
105
+ };
106
+ export const deactivate = {
107
+ name: "deactivate",
108
+ summary: "Take an active solution out of service; previews first, --confirm deactivates.",
109
+ description: "An active solution answers live traffic: the conversations, channels and API keys that name it. Deactivating stops that\n" +
110
+ "until it is activated again (`cavelon activate`, through its readiness gate). Without --confirm nothing changes: the\n" +
111
+ "preview says what would stop. Show it to a person and confirm only with their yes. The tenant's default route is refused\n" +
112
+ "before anything is sent: make another solution the default first (`cavelon harness default <solution>`). An instance\n" +
113
+ "that publishes no deactivate route is said so; a person deactivates in the Admin there.",
114
+ readOnly: false,
115
+ destructive: true,
116
+ idempotent: true,
117
+ mcpTool: "deactivate",
118
+ options: {
119
+ harness: HARNESS_OPTION,
120
+ env: ENV_OPTION,
121
+ confirm: { type: "boolean", mcpToken: true, description: "Deactivate it (after a person saw the preview)." },
122
+ },
123
+ examples: ["cavelon deactivate --harness support-faq", "cavelon deactivate --harness support-faq --confirm"],
124
+ async run(ctx, input) {
125
+ const session = await ctx.session();
126
+ const { ref, source } = harnessRef(session, input);
127
+ if (!ref)
128
+ throw usageError("Which solution?", "Pass --harness <name or slug> (`cavelon harness list` shows them), or set harness in cavelon.yaml or the env file.");
129
+ if (ctx.mode === "mcp" && input.options.confirm === true)
130
+ throw confirmTokenRequired("deactivate");
131
+ await workflowOperation(ctx, "POST", "/api/v1/harnesses/{harness_id}/deactivate", "deactivating solutions").catch((error) => {
132
+ if (error instanceof CavelonError && error.code === "operation_unavailable") {
133
+ throw new CavelonError(ExitCode.failure, {
134
+ code: "operation_unavailable",
135
+ message: "This instance publishes no route to deactivate a solution; nothing was changed.",
136
+ hint: "A person deactivates it in the Admin; the instance may be older than the route (`cavelon status` shows its version).",
137
+ });
138
+ }
139
+ throw error;
140
+ });
141
+ const harness = await findHarness(ctx, ref, source, (slug) => cavelonCommand("deactivate", "--harness", slug));
142
+ const target = { id: harness.id, slug: harness.slug, name: harness.name, status: harness.status };
143
+ if (harness.status !== "active") {
144
+ return { data: { changed: false, harness: target }, text: `${named(harness)} is ${harness.status}, not active; nothing to deactivate.` };
145
+ }
146
+ const route = await readDefaultRoute(ctx).catch(() => undefined);
147
+ if (route?.current?.id === harness.id) {
148
+ throw new CavelonError(ExitCode.needsAction, {
149
+ code: "default_route_deactivate",
150
+ message: `${named(harness)} is the tenant's default route: the tenant's chat and widget answer with it. Nothing was changed.`,
151
+ hint: "Ask the person which solution should answer there instead, make it the default (`cavelon harness default <solution>`, previews first), then deactivate this one.",
152
+ details: { harness: target },
153
+ });
154
+ }
155
+ const confirmCommand = cavelonCommand("deactivate", "--harness", harness.slug, "--confirm");
156
+ const gate = await confirmation(ctx, input, "deactivate", { harness: harness.id, status: harness.status });
157
+ if (!gate.confirmed) {
158
+ const known = route?.known ? "" : " (this instance does not say which solution is the default route)";
159
+ return {
160
+ data: { changed: false, harness: target, would: "deactivate", confirm: gate.confirm(confirmCommand), ...gate.fields },
161
+ text: [
162
+ `Deactivating ${named(harness)} takes it out of live traffic: the conversations, channels and API keys that name it are no longer answered by it until it is activated again${known}.`,
163
+ ...(gate.mismatch ? [gate.mismatch] : []),
164
+ `Show this to a person; with their yes: ${gate.confirm(confirmCommand)}`,
165
+ ].join("\n"),
166
+ ...(gate.exitCode ? { exitCode: gate.exitCode } : {}),
167
+ };
168
+ }
169
+ const updated = await callStable(ctx, "POST", "/api/v1/harnesses/{harness_id}/deactivate", "deactivating solutions", {
170
+ params: { harness_id: [harness.id] },
171
+ });
172
+ return {
173
+ data: { changed: true, harness: { ...target, status: updated?.status ?? target.status } },
174
+ text: `Deactivated ${named(harness)}; status ${updated?.status ?? "unknown"}. \`cavelon activate --harness ${harness.slug}\` puts it back through its readiness gate.`,
175
+ };
176
+ },
177
+ };
@@ -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,237 @@ 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
+ begrüßung: "greeting",
141
+ begrüssung: "greeting",
142
+ begrüßungen: "greeting",
143
+ begrüßungsnachricht: "greeting",
144
+ begrüßungstext: "greeting",
145
+ willkommensnachricht: "greeting",
146
+ webseite: "website",
147
+ homepage: "website",
148
+ einbinden: "embed",
149
+ binde: "embed",
150
+ einbetten: "embed",
151
+ bette: "embed",
152
+ speichern: "store",
153
+ speichere: "store",
154
+ hinterlegen: "store",
155
+ hinterlege: "store",
156
+ schlüssel: "key",
157
+ passwort: "password",
158
+ zugangsdaten: "credential",
159
+ falsch: "wrong",
160
+ falsche: "wrong",
161
+ falschen: "wrong",
162
+ geantwortet: "answer",
163
+ antwortet: "answer",
164
+ fehler: "error",
165
+ ändern: "change",
166
+ ändere: "change",
167
+ };
168
+ const RELATED_TERMS = {
169
+ greet: ["persona"],
170
+ greeting: ["persona"],
171
+ welcome: ["greeting", "persona"],
172
+ website: ["widget", "embed"],
173
+ site: ["widget", "embed"],
174
+ embed: ["widget"],
175
+ key: ["secret", "credential"],
176
+ password: ["secret", "credential"],
177
+ credential: ["secret"],
178
+ wrong: ["debug", "trace"],
179
+ incorrect: ["debug", "trace"],
180
+ error: ["debug", "trace"],
181
+ debug: ["trace", "playground"],
182
+ };
183
+ const GENERIC_TERMS = new Set(["agent", "cavelon"]);
184
+ const GENERIC_WEIGHT = 0.3;
185
+ const IN_CONTEXT = [
186
+ { all: ["key"], any: ["tool", "webhook", "integration", "mcp"], add: ["secret"], damp: ["api", "key"] },
187
+ ];
188
+ function stem(word) {
189
+ if (word.length > 5 && word.endsWith("ing")) {
190
+ const base = word.slice(0, -3);
191
+ return base.length > 3 && base[base.length - 1] === base[base.length - 2] && !/[aeiouls]/.test(base[base.length - 1]) ? base.slice(0, -1) : base;
192
+ }
193
+ if (word.length > 3 && word.endsWith("s") && !word.endsWith("ss"))
194
+ return word.slice(0, -1);
195
+ return word;
196
+ }
197
+ function words(text) {
198
+ return text
66
199
  .toLowerCase()
67
- .split(/[^\p{L}\p{N}_]+/u)
68
- .filter((t) => t.length > 1);
200
+ .split(/[^\p{L}\p{N}]+/u)
201
+ .filter(Boolean);
202
+ }
203
+ export function queryTerms(query) {
204
+ const terms = [];
205
+ const phrases = [];
206
+ const raw = words(query).filter((w) => !STOP_WORDS.has(w));
207
+ for (const word of raw) {
208
+ const english = CONCEPT_TERMS[word];
209
+ const parts = english ? english.split(" ") : [word];
210
+ if (parts.length > 1)
211
+ phrases.push(parts.map(stem));
212
+ for (const part of parts)
213
+ if (part.length > 1 || /\p{N}/u.test(part))
214
+ terms.push(stem(part));
215
+ }
216
+ for (let i = 0; i + 1 < terms.length; i++)
217
+ phrases.push([terms[i], terms[i + 1]]);
218
+ const related = terms.flatMap((t) => RELATED_TERMS[t] ?? []).map(stem);
219
+ const damped = [];
220
+ for (const rule of IN_CONTEXT) {
221
+ if (!rule.all.every((t) => terms.includes(t)) || !rule.any.some((t) => terms.includes(t)))
222
+ continue;
223
+ related.push(...rule.add.map(stem));
224
+ damped.push(...rule.damp);
225
+ }
226
+ return { terms: [...new Set([...terms, ...related])], phrases, damped };
69
227
  }
228
+ function fieldWords(text) {
229
+ return words(text).map(stem);
230
+ }
231
+ function hasPhrase(field, phrase) {
232
+ for (let i = 0; i + phrase.length <= field.length; i++) {
233
+ if (phrase.every((w, j) => field[i + j] === w))
234
+ return true;
235
+ }
236
+ return false;
237
+ }
238
+ const MIN_EVIDENCE = 2;
239
+ const MIN_SHARE_OF_BEST = 0.35;
70
240
  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();
241
+ const { terms, phrases, damped } = queryTerms(query);
242
+ if (!terms.length)
243
+ return [];
244
+ const fields = entries.map((entry) => ({
245
+ entry,
246
+ title: fieldWords(entry.title),
247
+ page: fieldWords(entry.page),
248
+ description: fieldWords(entry.description),
249
+ section: fieldWords(entry.section),
250
+ }));
251
+ const weight = new Map();
252
+ for (const term of terms) {
253
+ const pages = fields.filter((f) => f.title.includes(term) || f.page.includes(term) || f.description.includes(term)).length;
254
+ weight.set(term, Math.log(1 + entries.length / (1 + pages)) * (GENERIC_TERMS.has(term) || damped.includes(term) ? GENERIC_WEIGHT : 1));
255
+ }
256
+ const scored = fields
257
+ .map(({ entry, title, page, description, section }) => {
258
+ let evidence = 0;
79
259
  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;
260
+ for (const term of terms) {
261
+ const hits = (title.includes(term) ? 3 : 0) + (page.includes(term) ? 2 : 0) + (description.includes(term) ? 1 : 0) + (section.includes(term) ? 1 : 0);
262
+ evidence += hits;
263
+ score += hits * weight.get(term);
93
264
  }
94
- return { ...entry, score };
265
+ for (const phrase of phrases) {
266
+ const w = Math.max(...phrase.map((t) => weight.get(t) ?? 1));
267
+ if (hasPhrase(title, phrase))
268
+ score += 3 * w;
269
+ else if (hasPhrase(description, phrase))
270
+ score += w;
271
+ }
272
+ const titleWords = title.filter((w) => !STOP_WORDS.has(w));
273
+ const named = titleWords.filter((w) => terms.includes(w));
274
+ if (titleWords.length && named.length / titleWords.length >= 0.5)
275
+ score += (3 * named.length * Math.max(...named.map((t) => weight.get(t)))) / titleWords.length;
276
+ if (score > 0 && section.includes("concept"))
277
+ score *= 1.15;
278
+ return { ...entry, score: Math.round(score * 100) / 100, evidence };
95
279
  })
96
- .filter((e) => e.score > 0)
97
- .sort((a, b) => b.score - a.score || a.title.localeCompare(b.title));
280
+ .filter((e) => e.evidence >= MIN_EVIDENCE);
281
+ const best = Math.max(0, ...scored.map((e) => e.score));
282
+ return scored
283
+ .filter((e) => e.score >= best * MIN_SHARE_OF_BEST)
284
+ .sort((a, b) => b.score - a.score || a.title.localeCompare(b.title))
285
+ .map(({ evidence: _evidence, ...e }) => e);
98
286
  }
287
+ const INDEX_REF = "index";
99
288
  export const docsSearch = {
100
289
  name: "docs search",
101
290
  summary: "Search this instance's docs (titles and summaries).",
291
+ description: "Ranks the pages of the instance's docs index by the words of the question in their titles, addresses and\n" +
292
+ "summaries, rare words counting more than common ones. Stop words (English and German) are ignored, words match\n" +
293
+ "whole (\"test\" finds \"testing\", not \"latest\"), and German words for the core concepts are looked up in English\n" +
294
+ "(Wissensbasis: knowledge base). Only pages that match well are listed.",
102
295
  readOnly: true,
103
296
  idempotent: true,
104
297
  mcpTool: "docs_search",
@@ -109,12 +302,14 @@ export const docsSearch = {
109
302
  const limit = intOption(input, "limit", { min: 1, max: 100, fallback: 10 });
110
303
  const { entries } = await loadIndex(ctx);
111
304
  const hits = searchIndex(entries, query);
305
+ const { terms } = queryTerms(query);
112
306
  const items = hits.slice(0, limit).map(({ page, title, description, section }) => ({ page, title, section, description }));
307
+ const none = `No page matches "${query}"${terms.length ? ` (looked for: ${terms.join(", ")})` : " (it has only stop words)"}. ` +
308
+ `The docs are in English: try English words for the concept (knowledge base, test, trigger, default), ` +
309
+ `or read the list of all ${entries.length} pages with: ${cavelonCommand("docs", "get", INDEX_REF)}`;
113
310
  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.`,
311
+ data: { query, terms, items, total: hits.length, ...(items.length ? {} : { hint: none }) },
312
+ text: items.length ? `${table(items, ["page", "title", "description"], 70)}\n\nRead one: cavelon docs get <page>` : none,
118
313
  };
119
314
  },
120
315
  };
@@ -124,18 +319,28 @@ export const docsGet = {
124
319
  readOnly: true,
125
320
  idempotent: true,
126
321
  mcpTool: "docs_get",
127
- positionals: [{ name: "page", description: "section/slug from `docs search`, a title, or the page URL.", required: true }],
322
+ 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
323
  options: {
129
324
  "max-chars": { type: "string", value: "<n>", description: "Print at most n characters (default 40000)." },
130
325
  cursor: { type: "string", value: "<offset>", description: "Continue a long page where the previous output stopped." },
131
326
  },
132
327
  async run(ctx, input) {
133
328
  const ref = positional(input, "page");
134
- const { client, entries } = await loadIndex(ctx);
329
+ const { client, entries, text: index } = await loadIndex(ctx);
135
330
  const wanted = ref.replace(/\.md$/, "").replace(/^\/+/, "");
136
331
  const entry = entries.find((e) => e.page === wanted || e.url === ref) ??
137
332
  entries.find((e) => e.title.toLowerCase() === ref.toLowerCase()) ??
138
333
  entries.find((e) => e.page.endsWith(`/${wanted}`));
334
+ const max = intOption(input, "max-chars", { min: 100, fallback: 40_000 });
335
+ const offset = intOption(input, "cursor", { min: 0, fallback: 0 });
336
+ if (!entry && (wanted === INDEX_REF || wanted === "llms.txt")) {
337
+ const chunk = index.slice(offset, offset + max);
338
+ const next = offset + max < index.length ? String(offset + max) : null;
339
+ return {
340
+ data: { page: INDEX_REF, title: "Docs index", url: `${client.url}/llms.txt`, markdown: chunk, next_cursor: next, length: index.length },
341
+ text: chunk + (next ? `\n\n… index continues: ${cavelonCommand("docs", "get", INDEX_REF, "--cursor", next)}` : ""),
342
+ };
343
+ }
139
344
  if (!entry) {
140
345
  const near = searchIndex(entries, ref.replace(/[/-]/g, " ")).slice(0, 5).map((e) => e.page);
141
346
  throw new CavelonError(ExitCode.failure, {
@@ -146,8 +351,6 @@ export const docsGet = {
146
351
  }
147
352
  const response = await client.get(entry.url, { accept: "text/markdown, text/plain" });
148
353
  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
354
  const chunk = markdown.slice(offset, offset + max);
152
355
  const next = offset + max < markdown.length ? String(offset + max) : null;
153
356
  return {
@@ -0,0 +1,120 @@
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 what the instance gives it, as the export writes it: the schema's default, an empty list or object for\n" +
16
+ "a list or object field without one. The instance applies the same values, so nothing changes in what apply sends but the\n" +
17
+ "spelling, with one exception: an entry of a list that leaves out an `..._order` field (sort_order, display_order,\n" +
18
+ "step_order) gets its position, so the instance keeps the written order instead of ordering entries that all carry the\n" +
19
+ "default its own way (test cases by name). Lists become block lists; the persona file shows every field, the unset\n" +
20
+ "ones as comments. Comments in a rewritten file are not kept, as pull does not keep them. A file already in that form\n" +
21
+ "keeps its bytes, and so do the files of sections the schema does not know. Run it after writing package files by hand\n" +
22
+ "and before `apply`, so the next `pull` shows only what changed on the instance. --check writes nothing and exits 3 when a\n" +
23
+ "file would change. Uses the cached package schema (as validate does); --offline never contacts the instance.",
24
+ readOnly: false,
25
+ idempotent: true,
26
+ mcpTool: "fmt",
27
+ mcpEffect: "Changes nothing on the instance. Rewrites package files in the solution folder (not with check).",
28
+ options: {
29
+ check: { type: "boolean", description: "Write nothing; exit 3 when a file would change." },
30
+ offline: { type: "boolean", description: "Never contact the instance, even when no schema is cached." },
31
+ },
32
+ examples: ["cavelon fmt", "cavelon fmt --check"],
33
+ async run(ctx, input) {
34
+ const session = await ctx.session();
35
+ const project = requireSolution(session);
36
+ requireInstance(session);
37
+ const check = boolOption(input, "check");
38
+ const disk = await readPackage(project.root, project.layout);
39
+ const invalid = disk.findings.filter((f) => f.severity === "error");
40
+ if (invalid.length) {
41
+ throw new CavelonError(ExitCode.validation, {
42
+ code: "package_file_invalid",
43
+ message: `${invalid.length} package file${invalid.length === 1 ? "" : "s"} cannot be read: ${invalid.map((f) => `${f.file}${f.line ? `:${f.line}` : ""}`).join(", ")}.`,
44
+ hint: "Fix them first (`cavelon validate` names each); fmt changes nothing until then.",
45
+ });
46
+ }
47
+ const version = packageVersionOf(disk.package) ?? project.packageVersion;
48
+ const { schema } = await schemaFor(ctx, version, boolOption(input, "offline"));
49
+ if (!schema) {
50
+ throw new CavelonError(ExitCode.failure, {
51
+ code: "package_schema_unavailable",
52
+ message: `No package schema${version ? ` for format ${version}` : ""} is cached for this instance, and it was not read.`,
53
+ hint: "Run `cavelon fmt` (or `cavelon validate`) once without --offline while the instance is reachable.",
54
+ });
55
+ }
56
+ const changes = [];
57
+ let unchanged = 0;
58
+ for (const [section, source] of Object.entries(disk.sources)) {
59
+ const node = schema.properties?.[section];
60
+ if (!node)
61
+ continue;
62
+ if (Array.isArray(source)) {
63
+ const items = Array.isArray(disk.package[section]) ? disk.package[section] : [];
64
+ source.forEach((s, i) => {
65
+ const item = items[i];
66
+ const formed = exportForm(schema, node, [item])[0];
67
+ if (canonical(item) === canonical(formed))
68
+ unchanged++;
69
+ else
70
+ changes.push({ file: s.file, content: toYaml(formed) });
71
+ });
72
+ continue;
73
+ }
74
+ const value = disk.package[section];
75
+ const formed = exportForm(schema, node, value);
76
+ if (canonical(value ?? null) === canonical(formed ?? null))
77
+ unchanged++;
78
+ else
79
+ changes.push({ file: source.file, content: sectionContent(section, formed, schema, /\.json$/i.test(source.file)) });
80
+ }
81
+ const written = [];
82
+ if (!check && changes.length) {
83
+ const known = await readPulledFiles(project.root);
84
+ const wasKnown = [];
85
+ for (const change of changes) {
86
+ const file = path.join(project.root, change.file);
87
+ const target = await contentPath(project.root, file);
88
+ if (target === undefined)
89
+ continue;
90
+ if ((await readTextFile(target)) === change.content)
91
+ continue;
92
+ if (known[change.file] !== undefined && known[change.file] === (await fileDigest(file)))
93
+ wasKnown.push(change.file);
94
+ await writeFileAtomic(target, change.content);
95
+ written.push(change.file);
96
+ }
97
+ if (wasKnown.length)
98
+ await rememberAppliedFiles(project.root, await fileDigests(project.root, wasKnown));
99
+ }
100
+ const files = changes.map((c) => c.file).sort((a, b) => a.localeCompare(b, "en"));
101
+ const data = { check, changed: files, written: written.sort((a, b) => a.localeCompare(b, "en")), unchanged };
102
+ if (check) {
103
+ return {
104
+ data,
105
+ text: files.length
106
+ ? [...files.map((f) => `would format ${f}`), `${files.length} file${files.length === 1 ? "" : "s"} not in the export's form; run \`cavelon fmt\`.`].join("\n")
107
+ : `All ${unchanged} package files are in the export's form.`,
108
+ exitCode: files.length ? ExitCode.validation : ExitCode.ok,
109
+ };
110
+ }
111
+ return {
112
+ data,
113
+ text: [
114
+ ...written.map((f) => `formatted ${f}`),
115
+ `${written.length} file${written.length === 1 ? "" : "s"} formatted, ${unchanged} already in the export's form.`,
116
+ ...(written.length ? ["Check it: cavelon validate; then git diff shows only the spelling."] : []),
117
+ ].join("\n"),
118
+ };
119
+ },
120
+ };