@cavelon/cli 0.1.5 → 0.1.7

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 (42) hide show
  1. package/README.md +56 -18
  2. package/dist/command.js +10 -0
  3. package/dist/commands/api.js +40 -36
  4. package/dist/commands/chat.js +183 -0
  5. package/dist/commands/docs.js +77 -9
  6. package/dist/commands/fmt.js +61 -6
  7. package/dist/commands/index.js +3 -0
  8. package/dist/commands/init.js +61 -26
  9. package/dist/commands/inventory.js +21 -0
  10. package/dist/commands/limits-set.js +10 -6
  11. package/dist/commands/loops.js +22 -11
  12. package/dist/commands/models.js +11 -7
  13. package/dist/commands/sandboxes.js +11 -5
  14. package/dist/commands/schema.js +230 -48
  15. package/dist/commands/session.js +100 -14
  16. package/dist/commands/setup.js +22 -6
  17. package/dist/commands/solution.js +493 -86
  18. package/dist/commands/tenants.js +43 -10
  19. package/dist/commands/values.js +20 -11
  20. package/dist/commands/work.js +167 -33
  21. package/dist/confirm-token.js +72 -0
  22. package/dist/format.js +4 -4
  23. package/dist/harness-ref.js +17 -4
  24. package/dist/http.js +6 -0
  25. package/dist/kit-codes.js +11 -1
  26. package/dist/local-state.js +46 -10
  27. package/dist/main.js +38 -6
  28. package/dist/mcp.js +65 -14
  29. package/dist/openapi.js +30 -0
  30. package/dist/package-check.js +206 -18
  31. package/dist/package-files.js +98 -40
  32. package/dist/package-format.js +81 -8
  33. package/dist/package-references.js +77 -10
  34. package/dist/results.js +21 -1
  35. package/dist/session.js +9 -0
  36. package/dist/skills/cavelon-authoring/SKILL.md +54 -21
  37. package/dist/skills/cavelon-long-running/SKILL.md +13 -9
  38. package/dist/skills/cavelon-loop/SKILL.md +124 -28
  39. package/dist/skills/cavelon-testing/SKILL.md +69 -16
  40. package/dist/tenant-choice.js +19 -0
  41. package/dist/trace-view.js +172 -0
  42. package/package.json +1 -1
@@ -4,35 +4,43 @@ import { CAPACITY_CONCEPT_PAGE, CAPACITY_TUTORIAL_PAGE, capacityCodeIn, capacity
4
4
  import { boolOption, intOption, positional, stringOption } from "../command.js";
5
5
  import { Contracts } from "../contracts.js";
6
6
  import { CavelonError, ExitCode, usageError } from "../errors.js";
7
+ import { drivenByAgent } from "../agent-env.js";
8
+ import { confirmation, confirmGiven, confirmTokenRequired, shellTokenRequired } from "../confirm-token.js";
7
9
  import { clip, keyValues } from "../format.js";
8
10
  import { readTextFile, writeFileAtomic } from "../fsutil.js";
9
11
  import { uncommitted } from "../git.js";
10
- import { callStable } from "../invoke.js";
11
- import { harnessNotFoundError, lookupHarness } from "../harness-ref.js";
12
+ import { callStable, workflowOperation } from "../invoke.js";
13
+ import { deref, jsonBodySchema } from "../openapi.js";
14
+ import { harnessNotFoundError, lookupHarness, SLUG } from "../harness-ref.js";
12
15
  import { defaultChangeLine, defaultCommands, named, readDefaultRoute, setDefaultRoute } from "../default-route.js";
13
16
  import { ceilingHint, LIMIT_ABOVE_CEILING, parseLimits, readLimits } from "../limits.js";
14
- import { deletePreview, digest, fileDigest, fileDigests, listPreviews, loadPreview, readPulledFiles, rememberAppliedFiles, savePreview, writePulledFiles, writeState, } from "../local-state.js";
17
+ import { digest, fileDigest, fileDigests, listPreviews, loadPreview, previewExpiry, readItemFiles, readPulledFiles, rememberAppliedFiles, retiredPreview, retirePreviews, savePreview, writePulledFiles, writeState, } from "../local-state.js";
15
18
  import { catalogEntry, checkPackage, KIT_CODES, packageVersionOf } from "../package-check.js";
16
19
  import { cliFix, similarCodes } from "../code-hints.js";
17
20
  import { KIT_ERROR_CODES } from "../kit-codes.js";
18
21
  import { pairOrderHint, pairOrderPointer } from "../pair-order.js";
19
- import { readPackage, writePackage } from "../package-files.js";
22
+ import { readPackage, tenantWideSections, writePackage } from "../package-files.js";
20
23
  import { blockerDetails, blockerLines, changeLines, fieldChanges, locateBlockers, notApplied, notAppliedLines } from "../preview-report.js";
21
24
  import { readPrincipal } from "../principal.js";
22
25
  import { CASE_STATUSES, caseStatus, TESTING_PAGE } from "../results.js";
23
- import { isUuid, requireInstance } from "../session.js";
26
+ import { KNOWLEDGE_OUTCOME_AREA, KNOWLEDGE_OUTCOME_PAGE, KNOWLEDGE_OUTCOMES, knowledgeOutcome } from "../trace-view.js";
27
+ import { contextFlags, isUuid, requireInstance } from "../session.js";
24
28
  import { listedPages } from "./docs.js";
25
- import { readInventory, writeInventory } from "./inventory.js";
29
+ import { readInventory, readInventoryKinds, writeInventory } from "./inventory.js";
30
+ import { checkedBy, MODEL_UNKNOWN_CODE, missingInventory, REFERENCE_UNKNOWN_CODE } from "../package-references.js";
26
31
  import { cavelonCommand, shellWord } from "../shell.js";
27
32
  import { secretSetCommand, targetFlags, variableSetCommand } from "./values.js";
28
33
  const HARNESS_OPTION = { type: "string", value: "<harness>", description: "The solution (harness): its name, slug or id; default: env file, then cavelon.yaml." };
29
34
  const ENV_OPTION = { type: "string", value: "<name>", description: "Use env/<name>.yaml: its tenant, solution and runtime bindings." };
30
- export function requireSolution(session) {
35
+ export function requireSolution(session, harness) {
31
36
  if (!session.project) {
37
+ const flags = contextFlags(session);
32
38
  throw new CavelonError(ExitCode.usage, {
33
39
  code: "no_solution",
34
40
  message: "This folder is not a Cavelon solution (no cavelon.yaml here or above).",
35
- hint: "Run `cavelon init`: it asks which solution, or a new one, on a terminal. `cavelon harness list` shows the solutions.",
41
+ hint: harness
42
+ ? `Make it the folder of that solution first: ${cavelonCommand("init", "--harness", harness)}${flags}, then run this command again.`
43
+ : `Run \`cavelon init${flags}\`: it asks which solution, or a new one, on a terminal. \`cavelon harness list${flags}\` shows the solutions.`,
36
44
  });
37
45
  }
38
46
  return session.project;
@@ -50,7 +58,7 @@ function harnessRef(session, input) {
50
58
  async function findHarness(ctx, ref, source) {
51
59
  const { harness, candidates } = await lookupHarness(ctx, ref);
52
60
  if (!harness)
53
- throw harnessNotFoundError(ref, candidates, source);
61
+ throw harnessNotFoundError(ref, candidates, source, undefined, contextFlags(await ctx.session()));
54
62
  return harness;
55
63
  }
56
64
  async function cachedFirst(ctx, what, cached, offline, fetch) {
@@ -112,6 +120,7 @@ async function limitsFor(ctx, offline) {
112
120
  async function acceptedVersions(ctx, offline) {
113
121
  return (await capabilitiesFor(ctx, offline))?.contracts?.package_versions?.accepted;
114
122
  }
123
+ const BLOCKING_WARNINGS = new Set([REFERENCE_UNKNOWN_CODE, MODEL_UNKNOWN_CODE]);
115
124
  function findingLine(f) {
116
125
  const where = f.file ? `${f.file}${f.line ? `:${f.line}` : ""}` : "";
117
126
  const at = f.path ? ` ${f.path}` : "";
@@ -142,8 +151,8 @@ async function unknownStates(root, files, known) {
142
151
  }
143
152
  return out;
144
153
  }
145
- async function editedSincePull(project, pkg, schema) {
146
- const planned = await writePackage(project.root, project.layout, pkg, schema, { dryRun: true });
154
+ async function editedSincePull(project, pkg, schema, options) {
155
+ const planned = await writePackage(project.root, project.layout, pkg, schema, { ...options, dryRun: true, placed: undefined });
147
156
  const pulled = await readPulledFiles(project.root);
148
157
  const edited = [];
149
158
  for (const file of [...planned.written, ...planned.removed]) {
@@ -153,12 +162,34 @@ async function editedSincePull(project, pkg, schema) {
153
162
  }
154
163
  return edited.sort((a, b) => a.localeCompare(b, "en"));
155
164
  }
165
+ const EXPORT_ROUTE = "/api/v1/agent-graph/export";
166
+ const PREVIEW_ROUTE = "/api/v1/agent-graph/import/preview";
167
+ const INCLUDE_TENANT_WIDE = "include_tenant_wide";
168
+ async function takesTenantWide(ctx, where) {
169
+ if (where === "export") {
170
+ const { doc, op } = await workflowOperation(ctx, "GET", EXPORT_ROUTE, "exporting packages");
171
+ return Boolean(doc) && op.parameters.some((p) => p.name === INCLUDE_TENANT_WIDE);
172
+ }
173
+ const { doc, op } = await workflowOperation(ctx, "POST", PREVIEW_ROUTE, "previewing imports");
174
+ const schema = jsonBodySchema(op);
175
+ const properties = doc && schema ? deref(doc, schema)?.properties : undefined;
176
+ return Boolean(properties?.[INCLUDE_TENANT_WIDE]);
177
+ }
178
+ function sectionFiles(disk, sections) {
179
+ return sections.flatMap((section) => {
180
+ const source = disk.sources[section];
181
+ return (Array.isArray(source) ? source : source ? [source] : []).map((s) => s.file);
182
+ });
183
+ }
156
184
  export const pull = {
157
185
  name: "pull",
158
186
  summary: "Write the instance's package into package/ (split along the schema's sections) and the inventory into .cavelon/.",
159
187
  description: "With a solution (--harness, or cavelon.yaml's harness), exports that solution; without one, the tenant's full configuration.\n" +
160
- "A file whose content did not change keeps its bytes, so `git diff` shows what changed on the instance. Files of sections\n" +
161
- "the schema does not know are kept byte for byte. Refuses when package files have uncommitted changes, unless --force;\n" +
188
+ "A file whose content did not change keeps its bytes, so `git diff` shows what changed on the instance; a field the export\n" +
189
+ "spells out that the file leaves out (an empty list, a default) is no change. A test suite goes back to the file it was\n" +
190
+ "pulled into or applied from, whatever its name. Files of sections the schema does not know are kept byte for byte.\n" +
191
+ "A solution's pull leaves the tenant-wide sections (the tenant's settings, its model list) out of the folder, unless\n" +
192
+ "--tenant-wide; it says when the export carries none. Refuses when package files have uncommitted changes, unless --force;\n" +
162
193
  "outside a git repository, when a file it would overwrite or remove changed since the last pull. A file as the last pull\n" +
163
194
  "or apply left it (digests in .cavelon/) counts as unchanged, committed or not.",
164
195
  readOnly: false,
@@ -170,11 +201,15 @@ export const pull = {
170
201
  options: {
171
202
  harness: { type: "string", value: "<harness>", description: "The solution to export, by name, slug or id; its slug is recorded in cavelon.yaml when it names none." },
172
203
  force: { type: "boolean", description: "Overwrite package files that have uncommitted changes since the last pull or apply." },
204
+ "tenant-wide": {
205
+ type: "boolean",
206
+ description: "With a solution, also write the tenant-wide sections (tenant_settings, model_registry, …): asked of the export where the instance takes include_tenant_wide. Only `apply --tenant-wide` sends them back, for the whole tenant.",
207
+ },
173
208
  },
174
- examples: ["cavelon pull --harness support", "cavelon pull && git diff -- package tests"],
209
+ examples: ["cavelon pull --harness support", "cavelon pull && git status --short -- package tests"],
175
210
  async run(ctx, input) {
176
211
  const session = await ctx.session();
177
- const project = requireSolution(session);
212
+ const project = requireSolution(session, stringOption(input, "harness"));
178
213
  const url = requireInstance(session);
179
214
  const layoutDirs = [project.layout.package, ...Object.values(project.layout.items)];
180
215
  const force = boolOption(input, "force");
@@ -189,8 +224,12 @@ export const pull = {
189
224
  harness = await findHarness(ctx, ref);
190
225
  }
191
226
  const scope = harness ? "agent_graph" : "full_config";
192
- const exported = await callStable(ctx, "GET", "/api/v1/agent-graph/export", "exporting packages", {
193
- query: { scope, harness_id: harness?.id },
227
+ const tenantWide = boolOption(input, "tenant-wide");
228
+ if (tenantWide && !harness)
229
+ ctx.warn("--tenant-wide applies to a solution's pull; the tenant's full configuration carries the tenant-wide sections anyway.");
230
+ const askTenantWide = Boolean(harness) && tenantWide && (await takesTenantWide(ctx, "export"));
231
+ const exported = await callStable(ctx, "GET", EXPORT_ROUTE, "exporting packages", {
232
+ query: { scope, harness_id: harness?.id, ...(askTenantWide ? { [INCLUDE_TENANT_WIDE]: true } : {}) },
194
233
  timeoutMs: 120_000,
195
234
  });
196
235
  if (!exported || typeof exported !== "object" || Array.isArray(exported)) {
@@ -200,14 +239,18 @@ export const pull = {
200
239
  const { schema } = await schemaFor(ctx, version, false);
201
240
  if (!schema)
202
241
  ctx.warn("The instance does not publish its package schema; every top-level key became a file of its own.");
242
+ const shared = tenantWideSections(schema);
243
+ const skip = harness && !tenantWide ? shared : new Set();
244
+ const placed = {};
245
+ const options = { skip, itemFiles: await readItemFiles(project.root), placed };
203
246
  if (dirty === undefined) {
204
- const edited = await editedSincePull(project, exported, schema);
247
+ const edited = await editedSincePull(project, exported, schema, options);
205
248
  if (edited.length) {
206
249
  throw uncommittedChanges(edited, "This folder is not in a git repository, and pull would overwrite or remove files that changed since the last pull");
207
250
  }
208
251
  }
209
- const report = await writePackage(project.root, project.layout, exported, schema);
210
- await writePulledFiles(project.root, [...report.written, ...report.unchanged]);
252
+ const report = await writePackage(project.root, project.layout, exported, schema, options);
253
+ await writePulledFiles(project.root, [...report.written, ...report.unchanged], placed);
211
254
  if (harness && !project.harness)
212
255
  await setProjectKey(project, "harness", harness.slug);
213
256
  if (version && project.packageVersion !== version)
@@ -224,10 +267,15 @@ export const pull = {
224
267
  files: report,
225
268
  };
226
269
  await writeState(project.root, "pull.json", JSON.stringify(record, null, 2));
227
- for (const file of report.kept)
228
- ctx.warn(`Kept ${file}: its section is not in this instance's package schema.`);
270
+ for (const file of report.kept) {
271
+ const section = path.posix.basename(file).replace(/\.(ya?ml|json)$/i, "");
272
+ ctx.warn(report.tenant_wide.includes(section)
273
+ ? `Kept ${file} as it is: it holds a tenant-wide section, which pull leaves out of a solution's folder. apply leaves it out too, and \`apply --tenant-wide\` sends it for the whole tenant; remove the file unless you mean that.`
274
+ : `Kept ${file}: its section is not in this instance's package schema.`);
275
+ }
229
276
  for (const section of report.refused)
230
277
  ctx.warn(`Did not write section ${JSON.stringify(section)}: its name is not a plain file name.`);
278
+ const pulledShared = harness && tenantWide ? Object.keys(exported).filter((section) => shared.has(section)) : undefined;
231
279
  const rewritten = report.written.length + report.removed.length;
232
280
  const lines = [
233
281
  `Pulled ${harness ? `solution ${harness.name} (${harness.slug})` : "the tenant's full configuration"} into ${project.layout.package}/` +
@@ -236,12 +284,43 @@ export const pull = {
236
284
  ...report.written.map((f) => `written ${f}`),
237
285
  ...report.removed.map((f) => `removed ${f}`),
238
286
  `${report.unchanged.length} file${report.unchanged.length === 1 ? "" : "s"} unchanged.`,
287
+ ...(report.tenant_wide.length
288
+ ? [`Left out the tenant-wide section${report.tenant_wide.length === 1 ? "" : "s"} ${report.tenant_wide.join(", ")} (--tenant-wide writes them).`]
289
+ : []),
290
+ ...(pulledShared
291
+ ? [
292
+ pulledShared.length
293
+ ? `Tenant-wide: ${pulledShared.join(", ")} (shared by every solution of the tenant; only \`apply --tenant-wide\` sends them back).`
294
+ : `The export carries no tenant-wide sections${askTenantWide ? "" : " (this instance's export does not take include_tenant_wide)"}, so --tenant-wide wrote none.`,
295
+ ]
296
+ : []),
239
297
  `Inventory: ${inventory.file} (${inventory.counts.map((c) => `${c.count} ${c.label}`).join(", ")})`,
240
- rewritten ? `See what changed: git diff -- ${layoutDirs.join(" ")}` : "Nothing changed on the instance since the last pull.",
298
+ !rewritten
299
+ ? "Nothing changed on the instance since the last pull."
300
+ : dirty === undefined
301
+ ? "See what changed: the files listed above (this folder is not in a git repository)."
302
+ : `See what changed: git status --short -- ${layoutDirs.join(" ")} (new files), then git diff -- ${layoutDirs.join(" ")}`,
241
303
  ];
242
- return { data: { ...record, inventory }, text: lines.join("\n") };
304
+ return { data: { ...record, inventory, ...(pulledShared ? { tenant_wide_pulled: pulledShared } : {}) }, text: lines.join("\n") };
243
305
  },
244
306
  };
307
+ async function inventoryFor(ctx, project, disk, offline) {
308
+ let inventory = await readInventory(project.root);
309
+ const missing = missingInventory(disk, inventory);
310
+ let failed = missing;
311
+ if (missing.length && !offline) {
312
+ failed = await readInventoryKinds(ctx, project.root, missing, ctx.io.now());
313
+ inventory = await readInventory(project.root);
314
+ }
315
+ const skipped = failed.map((kind) => ({
316
+ check: checkedBy(kind),
317
+ kind,
318
+ reason: offline
319
+ ? `--offline, and no list of the tenant's ${kind.replace("_", " ")} is cached; \`cavelon ${kind === "models" ? "models list" : "pull"}\` reads it`
320
+ : `the tenant's ${kind.replace("_", " ")} could not be read`,
321
+ }));
322
+ return { inventory, skipped };
323
+ }
245
324
  async function validatePackage(ctx, project, offline) {
246
325
  const disk = await readPackage(project.root, project.layout);
247
326
  const version = packageVersionOf(disk.package) ?? project.packageVersion;
@@ -255,14 +334,16 @@ async function validatePackage(ctx, project, offline) {
255
334
  : "The instance does not publish its package schema (/api/v1/meta/package-schema).",
256
335
  });
257
336
  }
337
+ const { inventory, skipped } = await inventoryFor(ctx, project, disk, offline);
258
338
  const findings = checkPackage(disk, {
259
339
  schema,
260
340
  catalog: await catalogFor(ctx, offline),
261
341
  accepted: await acceptedVersions(ctx, offline),
262
342
  limits: await limitsFor(ctx, offline),
263
- inventory: await readInventory(project.root),
343
+ inventory,
344
+ solution: project.harness,
264
345
  });
265
- return { disk, findings, schemaVersion: schema["x-package-version"] ?? version ?? null, used };
346
+ return { disk, findings, schema, schemaVersion: schema["x-package-version"] ?? version ?? null, used, skipped };
266
347
  }
267
348
  function schemaUsedLine(used, ttlSeconds) {
268
349
  const from = used.source === "instance" ? "read from the instance now" : `cached at ${used.fetched_at ?? "an unknown time"}`;
@@ -285,10 +366,16 @@ export const validate = {
285
366
  "sent with it; --verbose says which copy was used.\n" +
286
367
  "Warns (never fails) when a fan-out or Map loop's max_concurrency is above the instance's branch width, and when the\n" +
287
368
  "tenant runs fan-outs and Map loops in sequence, from the limits the instance last published.\n" +
369
+ "References to skills, tools, knowledge bases, solutions and models outside the package are checked against the tenant's\n" +
370
+ "lists in .cavelon/inventory.json (pull, models list); a list no command has read yet is read now, unless --offline, and a\n" +
371
+ "check that cannot be made is named (`skipped` in --json). A reference that is in neither is a warning, as it may be created\n" +
372
+ "on the instance before the import; the import preview blocks it otherwise, so validate does not say \"Valid\" then, and\n" +
373
+ "--strict fails on every warning (exit 3).\n" +
288
374
  "Each finding carries a code: `cavelon explain <code>` says more. The import preview checks everything again on the server.\n\n" +
289
375
  "With --json, `warnings` is always a list of `{code, message}` objects: the warning findings (at most --limit), then the\n" +
290
376
  "warnings about the run, such as a stale copy of the schema, with code null. `warning_count` counts them all and\n" +
291
- "`error_count` the errors (`errors` is the same number); `findings` has each finding's file, line and hint.",
377
+ "`error_count` the errors (`errors` is the same number); `findings` has each finding's file, line and hint; `blocking_count`\n" +
378
+ "counts the warnings the import preview blocks on.",
292
379
  readOnly: true,
293
380
  idempotent: true,
294
381
  mcpTool: "validate",
@@ -296,15 +383,19 @@ export const validate = {
296
383
  offline: { type: "boolean", description: "Never contact the instance, even when nothing is cached." },
297
384
  limit: { type: "string", value: "<n>", description: "Print at most n findings (default 50)." },
298
385
  verbose: { type: "boolean", description: "Also say which copy of the package schema was used: cached or read now, when, and its hash." },
386
+ strict: { type: "boolean", description: "Fail (exit 3) on warnings too, such as a reference the import preview will block unless it exists by then." },
299
387
  },
300
388
  async run(ctx, input) {
301
389
  const session = await ctx.session();
302
390
  const project = requireSolution(session);
303
391
  requireInstance(session);
304
392
  const limit = intOption(input, "limit", { min: 1, max: 1000, fallback: 50 });
305
- const { disk, findings, schemaVersion, used } = await validatePackage(ctx, project, boolOption(input, "offline"));
393
+ const strict = boolOption(input, "strict");
394
+ const { disk, findings, schemaVersion, used, skipped } = await validatePackage(ctx, project, boolOption(input, "offline"));
306
395
  const errors = findings.filter((f) => f.severity === "error");
307
396
  const warnings = findings.filter((f) => f.severity === "warning");
397
+ const blocking = warnings.filter((f) => BLOCKING_WARNINGS.has(f.code));
398
+ const failed = errors.length > 0 || (strict && warnings.length > 0);
308
399
  if (disk.empty)
309
400
  ctx.warn(`No package files in ${project.layout.package}/ yet; \`cavelon pull\` brings an existing solution.`);
310
401
  const contracts = await ctx.contracts();
@@ -314,26 +405,37 @@ export const validate = {
314
405
  ...ctx.warnings.map((message) => ({ code: null, message })),
315
406
  ];
316
407
  const data = {
317
- valid: errors.length === 0,
408
+ valid: !failed,
409
+ strict,
318
410
  schema_version: schemaVersion,
319
411
  schema: used,
320
412
  sections: Object.keys(disk.package).length,
321
413
  error_count: errors.length,
322
414
  warning_count: warnings.length + ctx.warnings.length,
415
+ blocking_count: blocking.length,
323
416
  errors: errors.length,
324
417
  warnings: listed,
325
418
  findings: shown,
326
419
  more: Math.max(0, findings.length - shown.length),
420
+ skipped,
327
421
  };
422
+ const counts = `${errors.length} error${errors.length === 1 ? "" : "s"}, ${warnings.length} warning${warnings.length === 1 ? "" : "s"}`;
423
+ const verdict = errors.length
424
+ ? `${counts}. \`cavelon explain <code>\` says more.`
425
+ : strict && warnings.length
426
+ ? `${counts}; --strict fails on warnings. \`cavelon explain <code>\` says more.`
427
+ : blocking.length
428
+ ? `No errors against package schema ${schemaVersion ?? "?"} (${data.sections} sections), but ${blocking.length === 1 ? "one reference" : `${blocking.length} references`} ` +
429
+ `the import preview will block unless ${blocking.length === 1 ? "it exists" : "they exist"} on the instance by then (${counts}; --strict fails on warnings).`
430
+ : `Valid against package schema ${schemaVersion ?? "?"} (${data.sections} sections${warnings.length ? `, ${warnings.length} warning${warnings.length === 1 ? "" : "s"}` : ""}).`;
328
431
  const text = [
329
432
  ...(boolOption(input, "verbose") ? [schemaUsedLine(used, (v) => contracts.ttlSeconds(v))] : []),
330
433
  ...shown.map(findingLine),
331
434
  ...(data.more ? [`… and ${data.more} more (--limit).`] : []),
332
- errors.length
333
- ? `${errors.length} error${errors.length === 1 ? "" : "s"}, ${warnings.length} warning${warnings.length === 1 ? "" : "s"}. \`cavelon explain <code>\` says more.`
334
- : `Valid against package schema ${schemaVersion ?? "?"} (${data.sections} sections${warnings.length ? `, ${warnings.length} warning${warnings.length === 1 ? "" : "s"}` : ""}).`,
435
+ ...skipped.map((s) => `Not checked: ${s.check} (${s.reason}).`),
436
+ verdict,
335
437
  ].join("\n");
336
- return { data, text, exitCode: errors.length ? ExitCode.validation : ExitCode.ok };
438
+ return { data, text, exitCode: failed ? ExitCode.validation : ExitCode.ok };
337
439
  },
338
440
  };
339
441
  function valueNeeds(list) {
@@ -384,6 +486,12 @@ function needsLines(needs, flags) {
384
486
  lines.push(["needs identities", triggers.map((t) => `\n - ${t}`).join("")]);
385
487
  return lines;
386
488
  }
489
+ function changesNothing(p) {
490
+ const s = p.summary;
491
+ if (!s || typeof s !== "object")
492
+ return false;
493
+ return !counts(s.creates) && !counts(s.updates) && !counts(s.deletes) && fieldChanges(p.changes).length === 0;
494
+ }
387
495
  export function previewText(p, flags = "", context = {}) {
388
496
  const lines = [["ready", p.ready ? "yes" : "no"]];
389
497
  const s = p.summary ?? {};
@@ -448,16 +556,137 @@ function previewIdOption(input) {
448
556
  throw usageError("--confirm needs the preview id that `cavelon apply` printed.");
449
557
  return id?.trim();
450
558
  }
451
- async function confirmPreview(ctx, project, previewId) {
559
+ function previewUnknown(previewId) {
560
+ return new CavelonError(ExitCode.usage, {
561
+ code: "preview_unknown",
562
+ message: `No open preview ${previewId} in this solution.`,
563
+ hint: "Run `cavelon apply` (with the same --env or --harness) for a new preview and confirm its id; `cavelon status` lists the open ones.",
564
+ });
565
+ }
566
+ const PREVIEW_STALE = "import_preview_stale";
567
+ function previewRetired(retired, again) {
568
+ const id = retired.preview_id;
569
+ const fresh = `Run \`${again}\` for a new preview, show it, and confirm its id.`;
570
+ const details = { preview_id: id, reason: retired.reason, at: retired.at, ...(retired.by ? { superseded_by: retired.by } : {}) };
571
+ switch (retired.reason) {
572
+ case "applied":
573
+ return new CavelonError(ExitCode.conflict, {
574
+ code: "preview_applied",
575
+ message: `Preview ${id} was imported already (${retired.at}); nothing was imported again.`,
576
+ hint: `To import the files as they are now: ${fresh}`,
577
+ details,
578
+ });
579
+ case "superseded":
580
+ return new CavelonError(ExitCode.conflict, {
581
+ code: "preview_superseded",
582
+ message: `Preview ${id} was superseded: preview ${retired.by ?? "another one"} was imported after it (${retired.at}), so what it showed is no longer what an import would do; nothing was imported.`,
583
+ hint: fresh,
584
+ details,
585
+ });
586
+ case "discarded":
587
+ return new CavelonError(ExitCode.conflict, {
588
+ code: "preview_discarded",
589
+ message: `Preview ${id} was discarded (${retired.at}); nothing was imported.`,
590
+ hint: fresh,
591
+ details,
592
+ });
593
+ case "expired":
594
+ return new CavelonError(ExitCode.conflict, {
595
+ code: "preview_expired",
596
+ message: `Preview ${id} expired and was removed (${retired.at}); nothing was imported.`,
597
+ hint: fresh,
598
+ details,
599
+ });
600
+ case "stale":
601
+ return new CavelonError(ExitCode.conflict, {
602
+ code: PREVIEW_STALE,
603
+ message: `Preview ${id} was refused earlier because its target changed since (${retired.at}); nothing was imported.`,
604
+ hint: fresh,
605
+ details,
606
+ });
607
+ }
608
+ }
609
+ async function discardPreviews(ctx, project, which) {
610
+ const open = await listPreviews(project.root, ctx.io.now());
611
+ const chosen = which === "all" ? open : open.filter((p) => p.preview_id === which);
612
+ if (which !== "all" && chosen.length === 0)
613
+ throw previewUnknown(which);
614
+ const at = ctx.io.now().toISOString();
615
+ await retirePreviews(project.root, chosen.map((p) => ({ preview_id: p.preview_id, reason: "discarded", at })));
616
+ const ids = chosen.map((p) => p.preview_id);
617
+ return {
618
+ data: { discarded: ids, count: ids.length },
619
+ text: ids.length ? `Discarded ${ids.length === 1 ? "preview" : `${ids.length} previews`}: ${ids.join(", ")}. Nothing changed on the instance.` : "No open previews to discard.",
620
+ };
621
+ }
622
+ async function filesChangedSince(project, stored, disk) {
623
+ if (!stored.file_digests)
624
+ return [];
625
+ const previewed = stored.file_digests;
626
+ const now = await fileDigests(project.root, sourceFiles(disk));
627
+ const files = new Set([...Object.keys(previewed), ...Object.keys(now)]);
628
+ return [...files].filter((file) => previewed[file] !== now[file]).sort((a, b) => a.localeCompare(b, "en"));
629
+ }
630
+ async function rememberImported(ctx, project, stored, disk, changed) {
631
+ if (!stored.file_digests)
632
+ return;
633
+ const now = await fileDigests(project.root, sourceFiles(disk));
634
+ const known = {};
635
+ for (const [file, value] of Object.entries(stored.file_digests))
636
+ if (now[file] === value)
637
+ known[file] = value;
638
+ if (!changed.length)
639
+ return rememberAppliedFiles(project.root, known);
640
+ const holds = await instanceHolds(ctx, project, stored).catch((error) => {
641
+ ctx.warn(`Could not read what the instance holds after the import (${error instanceof Error ? error.message : String(error)}); pull treats ${changed.join(", ")} as local changes.`);
642
+ return undefined;
643
+ });
644
+ const unknown = [];
645
+ for (const file of changed) {
646
+ if (holds?.has(file) && now[file])
647
+ known[file] = now[file];
648
+ else
649
+ unknown.push(file);
650
+ }
651
+ await rememberAppliedFiles(project.root, known, unknown);
652
+ }
653
+ async function instanceHolds(ctx, project, stored) {
654
+ const harnessId = stored.request.harness_id;
655
+ const scope = harnessId ? "agent_graph" : stored.request.package.manifest?.scope;
656
+ if (scope !== "agent_graph" && scope !== "full_config")
657
+ return undefined;
658
+ if (scope === "agent_graph" && !harnessId)
659
+ return undefined;
660
+ const shared = stored.request[INCLUDE_TENANT_WIDE] === true && scope === "agent_graph" && (await takesTenantWide(ctx, "export"));
661
+ const exported = await callStable(ctx, "GET", EXPORT_ROUTE, "exporting packages", {
662
+ query: { scope, harness_id: harnessId, ...(shared ? { [INCLUDE_TENANT_WIDE]: true } : {}) },
663
+ timeoutMs: 120_000,
664
+ });
665
+ if (!exported || typeof exported !== "object" || Array.isArray(exported))
666
+ return undefined;
667
+ const { schema } = await schemaFor(ctx, packageVersionOf(exported), false);
668
+ const planned = await writePackage(project.root, project.layout, exported, schema, { dryRun: true });
669
+ return new Set(planned.unchanged);
670
+ }
671
+ async function confirmPreview(ctx, project, previewId, allowStale) {
452
672
  const stored = await loadPreview(project.root, previewId);
673
+ const session = await ctx.session();
453
674
  if (!stored) {
454
- throw new CavelonError(ExitCode.usage, {
455
- code: "preview_unknown",
456
- message: `No open preview ${previewId} in this solution.`,
457
- hint: "Run `cavelon apply` (with the same --env or --harness) for a new preview and confirm its id; `cavelon status` lists the open ones.",
675
+ const retired = await retiredPreview(project.root, previewId);
676
+ throw retired ? previewRetired(retired, `${cavelonCommand("apply")}${targetFlags(session)}`) : previewUnknown(previewId);
677
+ }
678
+ const now = ctx.io.now().toISOString();
679
+ const retire = (reason) => retirePreviews(project.root, [{ preview_id: stored.preview_id, reason, at: now }]);
680
+ const expiry = previewExpiry(stored.created_at, ctx.io.now());
681
+ if (expiry.expired) {
682
+ await retire("expired");
683
+ throw new CavelonError(ExitCode.conflict, {
684
+ code: "preview_expired",
685
+ message: `Preview ${previewId} was made at ${stored.created_at} and expired${expiry.expires_at ? ` at ${expiry.expires_at}` : ""}; nothing was imported.`,
686
+ hint: `Run \`${previewAgain(stored, session)}\` again, show the new preview, and confirm its id.`,
687
+ details: { preview_id: stored.preview_id, created_at: stored.created_at, expires_at: expiry.expires_at },
458
688
  });
459
689
  }
460
- const session = await ctx.session();
461
690
  if (requireInstance(session) !== stored.instance) {
462
691
  throw new CavelonError(ExitCode.conflict, {
463
692
  code: "preview_other_instance",
@@ -476,18 +705,31 @@ async function confirmPreview(ctx, project, previewId) {
476
705
  if (stored.tenant_id && session.tokenKind !== "api_key")
477
706
  client.target.tenantId = stored.tenant_id;
478
707
  const disk = await readPackage(project.root, project.layout);
708
+ const changed = await filesChangedSince(project, stored, disk);
479
709
  if (digest(disk.package) !== stored.package_digest) {
480
- ctx.warn("The package files changed since this preview; importing what the preview showed. Run `cavelon apply` to preview the files as they are now.");
710
+ if (!allowStale) {
711
+ throw new CavelonError(ExitCode.conflict, {
712
+ code: "preview_files_changed",
713
+ message: `The package files changed since preview ${previewId}${changed.length ? ` (${list(changed, 5)})` : ""}; nothing was imported.`,
714
+ hint: `Run \`${previewAgain(stored, session)}\` for a preview of the files as they are now, show it, and confirm its id. ` +
715
+ `To import what preview ${previewId} showed instead, add --allow-stale to the confirm.`,
716
+ details: { preview_id: stored.preview_id, files: changed },
717
+ });
718
+ }
719
+ ctx.warn(`The package files changed since this preview${changed.length ? ` (${list(changed, 5)})` : ""}; importing what the preview showed (--allow-stale). ` +
720
+ "The files keep their changes, which the instance does not hold; run `cavelon apply` to preview them.");
481
721
  }
482
722
  try {
483
723
  const result = await callStable(ctx, "POST", "/api/v1/agent-graph/import", "importing packages", {
484
724
  body: { ...stored.request, preview_id: stored.preview_id },
485
725
  timeoutMs: 300_000,
486
726
  });
487
- for (const other of await listPreviews(project.root))
488
- await deletePreview(project.root, other.preview_id);
489
- if (stored.file_digests)
490
- await rememberAppliedFiles(project.root, stored.file_digests);
727
+ const others = (await listPreviews(project.root, ctx.io.now())).filter((p) => p.preview_id !== stored.preview_id);
728
+ await retirePreviews(project.root, [
729
+ { preview_id: stored.preview_id, reason: "applied", at: now },
730
+ ...others.map((p) => ({ preview_id: p.preview_id, reason: "superseded", at: now, by: stored.preview_id })),
731
+ ]);
732
+ await rememberImported(ctx, project, stored, disk, changed);
491
733
  const summary = (result.summary ?? {});
492
734
  const flags = targetFlags(session, stored.env ?? session.envFile?.name);
493
735
  const still = setCommands(stored.preview, flags);
@@ -507,19 +749,22 @@ async function confirmPreview(ctx, project, previewId) {
507
749
  }
508
750
  catch (error) {
509
751
  if (error instanceof CavelonError && error.code === REQUIREMENTS_CHANGED && (error.blockers?.length || error.blockerDetails?.length)) {
510
- await deletePreview(project.root, stored.preview_id);
752
+ await retire("stale");
511
753
  throw requirementsChanged(error, stored, session, await catalogFor(ctx, false), disk);
512
754
  }
513
755
  if (error instanceof CavelonError && error.blockerDetails?.length)
514
756
  throw withBlockersLocated(error, disk, stored, session);
515
757
  if (error instanceof CavelonError && (error.code === "import_preview_stale" || (error.status === 409 && /preview/i.test(error.message)))) {
516
- await deletePreview(project.root, stored.preview_id);
758
+ await retire("stale");
759
+ const said = error.details?.changed;
760
+ const changed = Array.isArray(said) ? said.filter((c) => typeof c === "string") : [];
517
761
  throw new CavelonError(ExitCode.conflict, {
518
762
  code: error.code === "conflict" ? "import_preview_stale" : error.code,
519
763
  status: 409,
520
- message: `The target changed since preview ${stored.preview_id}; nothing was imported.`,
764
+ message: `The target changed since preview ${stored.preview_id}${changed.length ? `: ${changed.join("; ")}` : ""}; nothing was imported.`,
521
765
  hint: `Run \`${previewAgain(stored, session)}\` again, show the new preview, and confirm its id.`,
522
766
  docs: error.docs,
767
+ ...(changed.length ? { details: { preview_id: stored.preview_id, changed } } : {}),
523
768
  });
524
769
  }
525
770
  throw error;
@@ -567,21 +812,25 @@ async function applyTarget(ctx, session, input, pkg) {
567
812
  return undefined;
568
813
  const { harness: found, candidates } = await lookupHarness(ctx, ref);
569
814
  if (found)
570
- return { ...found, created: false };
571
- if (!source?.startsWith("env/") || isUuid(ref))
572
- throw harnessNotFoundError(ref, candidates, source);
815
+ return found;
816
+ if (!source || source === "option" || isUuid(ref) || !SLUG.test(ref))
817
+ throw harnessNotFoundError(ref, candidates, source, undefined, contextFlags(session));
573
818
  const name = packageHarnessName(pkg, ref) ?? ref;
574
- const created = await callStable(ctx, "POST", "/api/v1/harnesses", "creating solutions", { body: { slug: ref, name } });
575
- ctx.warn(`Created the draft solution ${created.name} (${created.slug}) that ${source} names.`);
576
- return { ...created, created: true };
819
+ const create = `${cavelonCommand("harness", "new", ref, ...(name !== ref ? ["--name", name] : []))}${targetFlags(session, null)}`;
820
+ throw new CavelonError(ExitCode.failure, {
821
+ code: "solution_not_found",
822
+ message: `Solution ${ref}, which ${source} names, is not on the instance yet; apply previews into an existing solution and creates none.`,
823
+ hint: `Create it as a draft: ${create}, then run \`${cavelonCommand("apply")}${targetFlags(session)}\` again.`,
824
+ details: { slug: ref, name, create },
825
+ });
577
826
  }
578
827
  function packageHarnessName(pkg, slug) {
579
828
  const entries = (Array.isArray(pkg.harnesses) ? pkg.harnesses : []).filter((h) => Boolean(h) && typeof h === "object" && !Array.isArray(h));
580
- const entry = entries.find((h) => h.slug === slug) ?? (entries.length === 1 ? entries[0] : undefined);
829
+ const entry = entries.find((h) => h.slug === slug);
581
830
  const name = typeof entry?.name === "string" ? entry.name.trim() : "";
582
831
  return name ? name.slice(0, 255) : undefined;
583
832
  }
584
- function personReason(preview, harness, mode, env) {
833
+ function personReason(preview, harness, mode, env, shared = []) {
585
834
  const active = (preview.impact?.active_harnesses ?? []).map((h) => h.harness_slug ?? h.name).filter((n) => Boolean(n));
586
835
  if (harness?.status === "active" && !active.includes(harness.slug))
587
836
  active.unshift(harness.slug);
@@ -589,6 +838,8 @@ function personReason(preview, harness, mode, env) {
589
838
  return `reaches the active solution${active.length === 1 ? "" : "s"} ${list(active, 5)}`;
590
839
  if (preview.impact?.active_harnesses?.length)
591
840
  return "reaches an active solution";
841
+ if (shared.length)
842
+ return `changes what the whole tenant shares (${list(shared, 5)})`;
592
843
  if (counts(preview.summary?.deletes) || mode === "replace")
593
844
  return "deletes";
594
845
  if (env === "prod")
@@ -600,10 +851,17 @@ export const apply = {
600
851
  summary: "Preview the package files against the instance and print a preview id; --confirm <id> imports exactly that preview.",
601
852
  description: "Without --confirm nothing is imported: the preview shows what changes, which active solutions it reaches, what the target\n" +
602
853
  "still needs (secrets and variables with the command that sets each, grants, runtime bindings, trigger identities), loop\n" +
603
- "budgets and ignored sections, and is stored in .cavelon/. When the env file names a solution that does not exist yet,\n" +
604
- "apply creates it as a draft first. A person sets the secrets (`cavelon secrets set <name>`), never the agent.\n" +
605
- "Show a preview that reaches an active solution or env/prod to a person before confirming. A stale preview exits 4;\n" +
606
- "so does an import its own check refuses when it applies, naming each blocker.",
854
+ "budgets and ignored sections, and is stored in .cavelon/. A preview never creates the solution: one the env file names\n" +
855
+ "that is not on the instance yet gets the `cavelon harness new` command that creates it as a draft. A person sets the\n" +
856
+ "secrets (`cavelon secrets set <name>`), never the agent.\n" +
857
+ "Show a preview that reaches an active solution or env/prod to a person before confirming. A stale preview exits 4 and\n" +
858
+ "imports nothing: one whose target changed on the instance since, one whose package files changed since (what they\n" +
859
+ "hold, not their formatting; --allow-stale imports what the preview showed anyway), and one older than a day. So does\n" +
860
+ "an import its own check refuses when it applies, naming each blocker. --discard <id|all> forgets stored previews;\n" +
861
+ "`cavelon status` lists them with when each expires.\n" +
862
+ "A solution's import leaves the package's tenant-wide sections (tenant_settings, model_registry, …) out; --tenant-wide\n" +
863
+ "imports them, for every solution of the tenant. An instance that does not publish include_tenant_wide imports them with\n" +
864
+ "every solution's package, and apply says so.",
607
865
  readOnly: false,
608
866
  destructive: true,
609
867
  mcpTool: "apply",
@@ -611,16 +869,42 @@ export const apply = {
611
869
  env: ENV_OPTION,
612
870
  harness: HARNESS_OPTION,
613
871
  confirm: { type: "string", value: "<preview-id>", description: "Import exactly this stored preview." },
872
+ "allow-stale": {
873
+ type: "boolean",
874
+ description: "With --confirm: import what the preview showed although the package files changed since it.",
875
+ },
876
+ discard: { type: "string", value: "<preview-id|all>", description: "Forget this stored preview, or all of them; changes nothing on the instance." },
614
877
  mode: { type: "string", value: "<mode>", description: "overwrite (default) or replace (deletes what the package does not hold)." },
878
+ "tenant-wide": {
879
+ type: "boolean",
880
+ description: "With a solution, also import the package's tenant-wide sections (tenant_settings, model_registry, …): they change for every solution of the tenant, so a person sees the preview first.",
881
+ },
615
882
  },
616
- examples: ["cavelon apply --env test", "cavelon apply --confirm <preview-id>", "cavelon apply --env prod --json"],
883
+ examples: [
884
+ "cavelon apply --env test",
885
+ "cavelon apply --confirm <preview-id>",
886
+ "cavelon apply --env test --tenant-wide",
887
+ "cavelon apply --env prod --json",
888
+ "cavelon apply --discard all",
889
+ ],
617
890
  async run(ctx, input) {
618
891
  const session = await ctx.session();
619
- const project = requireSolution(session);
892
+ const project = requireSolution(session, stringOption(input, "harness"));
620
893
  const url = requireInstance(session);
621
894
  const confirm = previewIdOption(input);
895
+ const discard = stringOption(input, "discard")?.trim();
896
+ const allowStale = boolOption(input, "allow-stale");
897
+ if (discard !== undefined && confirm)
898
+ throw usageError("Pass --confirm or --discard, not both.");
899
+ if (allowStale && !confirm)
900
+ throw usageError("--allow-stale only applies to --confirm <preview-id>.");
901
+ if (discard !== undefined) {
902
+ if (!discard)
903
+ throw usageError("--discard needs a preview id, or all.", "`cavelon status` lists the open previews.");
904
+ return discardPreviews(ctx, project, discard);
905
+ }
622
906
  if (confirm)
623
- return confirmPreview(ctx, project, confirm);
907
+ return confirmPreview(ctx, project, confirm, allowStale);
624
908
  const envFile = session.envFile;
625
909
  if (envFile?.tenant && session.tenantSource !== `env/${envFile.name}.yaml`) {
626
910
  ctx.warn(`${session.tenantSource} names tenant "${session.tenant}" and takes precedence over ${envFile.name}.yaml's "${envFile.tenant}".`);
@@ -628,7 +912,7 @@ export const apply = {
628
912
  const mode = (stringOption(input, "mode") ?? envFile?.mode ?? "overwrite");
629
913
  if (mode !== "overwrite" && mode !== "replace")
630
914
  throw usageError(`--mode must be overwrite or replace, got "${mode}".`);
631
- const { disk, findings } = await validatePackage(ctx, project, false);
915
+ const { disk, findings, schema } = await validatePackage(ctx, project, false);
632
916
  if (disk.empty)
633
917
  throw usageError(`No package files in ${project.layout.package}/.`, "Run `cavelon pull --harness <name or slug>` first (`cavelon harness list` shows them), or write the package files.");
634
918
  const errors = findings.filter((f) => f.severity === "error");
@@ -648,13 +932,37 @@ export const apply = {
648
932
  request.harness_id = harness.id;
649
933
  if (envFile && Object.keys(envFile.runtimeBindings).length)
650
934
  request.runtime_bindings = envFile.runtimeBindings;
935
+ const tenantWide = boolOption(input, "tenant-wide");
936
+ const solutionImport = Boolean(harness) && scope !== "full_config";
937
+ if (tenantWide && !solutionImport)
938
+ ctx.warn("--tenant-wide applies to a solution's import; this one goes to the whole tenant anyway.");
939
+ const shared = solutionImport ? [...tenantWideSections(schema)].filter((section) => section in disk.package) : [];
940
+ const takes = solutionImport && (tenantWide || shared.length > 0) && (await takesTenantWide(ctx, "import"));
941
+ if (tenantWide && takes)
942
+ request[INCLUDE_TENANT_WIDE] = true;
943
+ const sharedImported = tenantWide || !takes ? shared : [];
944
+ const sharedLeftOut = tenantWide || !takes ? [] : shared;
945
+ if (tenantWide && solutionImport && !shared.length)
946
+ ctx.warn("--tenant-wide: the package holds no tenant-wide section, so this import changes nothing the whole tenant shares.");
947
+ if (sharedImported.length) {
948
+ const files = sectionFiles(disk, sharedImported).join(", ");
949
+ ctx.warn(`${files} ${sharedImported.length === 1 ? "holds a section" : "hold sections"} the whole tenant shares: this import changes ${sharedImported.join(", ")} for every solution of the tenant` +
950
+ (takes ? "." : " (this instance does not publish include_tenant_wide and imports them with every solution's package); remove the file unless that is meant."));
951
+ }
651
952
  const client = await ctx.client();
652
953
  const preview = await callStable(ctx, "POST", "/api/v1/agent-graph/import/preview", "previewing imports", {
653
954
  body: request,
654
955
  timeoutMs: 120_000,
655
956
  });
656
- const target = harness ? { id: harness.id, slug: harness.slug, created: harness.created } : null;
957
+ const target = harness ? { id: harness.id, slug: harness.slug } : null;
657
958
  const data = { previewed: true, ...preview, env: envFile?.name ?? null, harness: target };
959
+ if (shared.length || tenantWide)
960
+ data.tenant_wide = { sections: shared, imported: sharedImported, left_out: sharedLeftOut };
961
+ const sharedLine = sharedImported.length
962
+ ? `tenant-wide: ${sharedImported.join(", ")} change for every solution of the tenant`
963
+ : sharedLeftOut.length
964
+ ? `tenant-wide: ${sharedLeftOut.join(", ")} left out (\`cavelon apply --tenant-wide\` imports them, for every solution of the tenant)`
965
+ : undefined;
658
966
  const flags = targetFlags(session);
659
967
  const commands = setCommands(preview, flags);
660
968
  if (commands.secrets.length || commands.variables.length)
@@ -668,17 +976,38 @@ export const apply = {
668
976
  ]);
669
977
  if (pair)
670
978
  data.hint = pair.hint;
979
+ const blockedShared = sharedLeftOut.filter((section) => blockerDetails(preview.blocker_details).some((b) => b.path === section || b.path?.startsWith(`${section}.`) || b.path?.startsWith(`${section}[`)));
980
+ const sharedHint = blockedShared.length
981
+ ? `A blocker is in ${sectionFiles(disk, blockedShared).join(", ")}, which this import leaves out (tenant-wide); the instance checks it anyway: remove the file, or fix it.`
982
+ : undefined;
983
+ if (sharedHint)
984
+ data.tenant_wide_hint = sharedHint;
671
985
  return {
672
986
  data,
673
987
  text: [
674
988
  previewText(preview, flags, context),
989
+ ...(sharedLine ? [sharedLine] : []),
675
990
  "",
676
991
  ...(pair ? [`hint: ${pair.hint}`] : []),
992
+ ...(sharedHint ? [`hint: ${sharedHint}`] : []),
677
993
  "The preview has blockers; fix them and run `cavelon apply` again.",
678
994
  ].join("\n"),
679
995
  exitCode: ExitCode.validation,
680
996
  };
681
997
  }
998
+ if (changesNothing(preview)) {
999
+ data.nothing_to_import = true;
1000
+ delete data.preview_id;
1001
+ return {
1002
+ data,
1003
+ text: [
1004
+ `Preview of ${project.layout.package}/ for ${harness ? `solution ${harness.slug}${harness.status ? ` (${harness.status})` : ""}` : "the tenant"}${envFile ? ` [env ${envFile.name}]` : ""}:`,
1005
+ previewText(preview, flags, context),
1006
+ "",
1007
+ "Nothing to import: the instance already holds what the package files say. No preview was stored.",
1008
+ ].join("\n"),
1009
+ };
1010
+ }
682
1011
  if (!preview.preview_id) {
683
1012
  ctx.warn("This instance's preview returns no preview id, so `apply --confirm` cannot import exactly it; update the instance.");
684
1013
  }
@@ -696,13 +1025,17 @@ export const apply = {
696
1025
  preview,
697
1026
  };
698
1027
  await savePreview(project.root, stored);
1028
+ const at = ctx.io.now().toISOString();
1029
+ const expired = (await listPreviews(project.root, ctx.io.now())).filter((old) => old.expired);
1030
+ await retirePreviews(project.root, expired.map((old) => ({ preview_id: old.preview_id, reason: "expired", at })));
699
1031
  }
700
- const reason = personReason(preview, harness, mode, envFile?.name);
1032
+ const reason = personReason(preview, harness, mode, envFile?.name, sharedImported);
701
1033
  data.show_to_person = Boolean(reason);
702
1034
  const confirmLine = preview.preview_id ? `${cavelonCommand("apply", "--confirm", preview.preview_id)}${flags}` : undefined;
703
1035
  const text = [
704
1036
  `Preview of ${project.layout.package}/ for ${harness ? `solution ${harness.slug}${harness.status ? ` (${harness.status})` : ""}` : "the tenant"}${envFile ? ` [env ${envFile.name}]` : ""}:`,
705
1037
  previewText(preview, flags, context),
1038
+ ...(sharedLine ? [sharedLine] : []),
706
1039
  "",
707
1040
  ...(preview.preview_id ? [`preview id: ${preview.preview_id}`] : []),
708
1041
  ...(reason ? [`This ${reason}: show this preview to a person before confirming.`] : []),
@@ -755,6 +1088,32 @@ async function caseStatusAnswer(ctx, status) {
755
1088
  ]),
756
1089
  };
757
1090
  }
1091
+ async function knowledgeOutcomeAnswer(ctx, outcome) {
1092
+ const instance = (await ctx.session().catch(() => undefined))?.url;
1093
+ const page = `/docs/${KNOWLEDGE_OUTCOME_PAGE}`;
1094
+ const data = {
1095
+ code: outcome.value,
1096
+ kind: "knowledge_outcome",
1097
+ message: outcome.message,
1098
+ hint: outcome.hint,
1099
+ ...(outcome.recorded_as ? { recorded_as: outcome.recorded_as } : {}),
1100
+ docs: instance ? `${instance}${page}` : page,
1101
+ read: [{ page: KNOWLEDGE_OUTCOME_PAGE, command: cavelonCommand("docs", "get", KNOWLEDGE_OUTCOME_PAGE) }],
1102
+ };
1103
+ return {
1104
+ data,
1105
+ text: keyValues([
1106
+ ["code", outcome.value],
1107
+ ["kind", OUTCOME_KIND],
1108
+ ["meaning", outcome.message],
1109
+ ["next", outcome.hint],
1110
+ ["recorded as", outcome.recorded_as],
1111
+ ["docs", data.docs],
1112
+ ["read", data.read[0].command],
1113
+ ]),
1114
+ };
1115
+ }
1116
+ const OUTCOME_KIND = "knowledge outcome (what a knowledge search found, as its retrieval span's knowledge_outcome says)";
758
1117
  export const explain = {
759
1118
  name: "explain",
760
1119
  summary: "Look a code up in the instance's error catalog: what it means and how to fix it.",
@@ -762,7 +1121,9 @@ export const explain = {
762
1121
  "findings, and errors the CLI raises itself, such as operation_not_found or uncommitted_changes) are known too. Uses the\n" +
763
1122
  "cached catalog first. Where the instance's fix names an API route, the command that does the same is added. An unknown\n" +
764
1123
  "code gets the closest known ones (a typo away, the same start).\n" +
765
- `Also explains the test-case statuses that are neither pass nor fail: ${CASE_STATUSES.map((s) => s.status).join(", ")}.`,
1124
+ `Also explains the test-case statuses that are neither pass nor fail: ${CASE_STATUSES.map((s) => s.status).join(", ")};\n` +
1125
+ `and the values of a retrieval span's knowledge_outcome (${KNOWLEDGE_OUTCOMES.map((o) => o.value).join(", ")}), from the\n` +
1126
+ "instance's catalog (area knowledge_outcome) where it lists them.",
766
1127
  readOnly: true,
767
1128
  idempotent: true,
768
1129
  mcpTool: "explain",
@@ -770,10 +1131,17 @@ export const explain = {
770
1131
  async run(ctx, input) {
771
1132
  const code = positional(input, "code").trim();
772
1133
  const status = caseStatus(code);
773
- let catalog = status ? await catalogFor(ctx, false).catch(() => null) : await catalogFor(ctx, false);
1134
+ const outcome = knowledgeOutcome(code);
1135
+ let catalog = status || outcome ? await catalogFor(ctx, false).catch(() => null) : await catalogFor(ctx, false);
774
1136
  let entry = catalogEntry(catalog, code) ?? looseEntry(catalog, code);
1137
+ if (!entry && outcome && catalog) {
1138
+ catalog = await (await ctx.contracts()).errorCatalog({ refresh: true }).catch(() => catalog);
1139
+ entry = catalogEntry(catalog, outcome.value);
1140
+ }
775
1141
  if (!entry && status)
776
1142
  return caseStatusAnswer(ctx, status);
1143
+ if (!entry && outcome)
1144
+ return knowledgeOutcomeAnswer(ctx, outcome);
777
1145
  if (!entry || entry.kind === "kit" || entry.kind === "cli") {
778
1146
  catalog = await (await ctx.contracts()).errorCatalog({ refresh: true }).catch(() => catalog);
779
1147
  entry = catalogEntry(catalog, code) ?? looseEntry(catalog, code) ?? entry;
@@ -792,6 +1160,7 @@ export const explain = {
792
1160
  ...KIT_CODES,
793
1161
  ...KIT_ERROR_CODES,
794
1162
  ...CASE_STATUSES.map((s) => ({ code: s.status })),
1163
+ ...KNOWLEDGE_OUTCOMES.map((o) => ({ code: o.value })),
795
1164
  ].map((e) => e.code);
796
1165
  const similar = similarCodes(code, all);
797
1166
  throw new CavelonError(ExitCode.failure, {
@@ -815,7 +1184,7 @@ export const explain = {
815
1184
  const pages = capacity === MODEL_ENDPOINT_BUSY ? [CAPACITY_TUTORIAL_PAGE, CAPACITY_CONCEPT_PAGE] : [CAPACITY_CONCEPT_PAGE, CAPACITY_TUTORIAL_PAGE];
816
1185
  const read = capacity ? (await listedPages(ctx, pages)).map((page) => ({ page, command: cavelonCommand("docs", "get", page) })) : [];
817
1186
  const cli = entry.kind === "cli" ? undefined : cliFix(entry);
818
- const data = { ...entry, docs, ...(cli ? { cli_fix: cli } : {}), ...(kitHint ? { kit_hint: kitHint } : {}), ...(read.length ? { read } : {}) };
1187
+ const data = { ...entry, ...(entry.area === KNOWLEDGE_OUTCOME_AREA ? { kind: "knowledge_outcome" } : {}), docs, ...(cli ? { cli_fix: cli } : {}), ...(kitHint ? { kit_hint: kitHint } : {}), ...(read.length ? { read } : {}) };
819
1188
  return {
820
1189
  data,
821
1190
  text: keyValues([
@@ -828,7 +1197,9 @@ export const explain = {
828
1197
  ? "cavelon validate code"
829
1198
  : entry.kind === "cli"
830
1199
  ? "cavelon error code (raised by the CLI, not the instance)"
831
- : `API error code${entry.area ? ` (${entry.area})` : ""}`,
1200
+ : entry.area === KNOWLEDGE_OUTCOME_AREA
1201
+ ? OUTCOME_KIND
1202
+ : `API error code${entry.area ? ` (${entry.area})` : ""}`,
832
1203
  ],
833
1204
  ["meaning", entry.message],
834
1205
  ["fix", entry.hint ?? undefined],
@@ -853,6 +1224,14 @@ export async function solutionState(ctx, ref) {
853
1224
  if (!harness)
854
1225
  return { harness: null, unavailable: `This tenant has no solution "${ref}".` };
855
1226
  const state = { harness: { id: harness.id, slug: harness.slug, name: harness.name, status: harness.status } };
1227
+ try {
1228
+ const route = await readDefaultRoute(ctx);
1229
+ const current = route.current ? { id: route.current.id, slug: route.current.slug, name: route.current.name } : null;
1230
+ state.default_route = { is_default: route.known ? route.current?.id === harness.id : null, current };
1231
+ }
1232
+ catch (error) {
1233
+ ctx.warn(`Could not read the tenant's default route: ${error instanceof Error ? error.message : String(error)}`);
1234
+ }
856
1235
  try {
857
1236
  const readiness = await callStable(ctx, "GET", "/api/v1/harnesses/{harness_id}/readiness", "reading readiness", {
858
1237
  params: { harness_id: [harness.id] },
@@ -882,12 +1261,18 @@ export async function solutionState(ctx, ref) {
882
1261
  export function solutionStateLines(state) {
883
1262
  if (!state.harness)
884
1263
  return [["state", `not readable: ${state.unavailable ?? "unknown"}`]];
885
- const ready = state.ready_to_activate === true
886
- ? "ready to activate"
887
- : state.ready_to_activate === false
888
- ? `not ready to activate${state.blockers?.length ? ` (${list(state.blockers, 3)})` : ""}`
889
- : undefined;
1264
+ const active = state.harness.status === "active";
1265
+ const ready = active
1266
+ ? undefined
1267
+ : state.ready_to_activate === true
1268
+ ? "ready to activate"
1269
+ : state.ready_to_activate === false
1270
+ ? `not ready to activate${state.blockers?.length ? ` (${list(state.blockers, 3)})` : ""}`
1271
+ : undefined;
890
1272
  const lines = [["state", [state.harness.status, ready].filter(Boolean).join(", ")]];
1273
+ const route = state.default_route;
1274
+ if (route)
1275
+ lines.push(["default route", defaultRouteText(state.harness, route)]);
891
1276
  const run = state.latest_test_run;
892
1277
  if (run === null)
893
1278
  lines.push(["last test run", "none yet (`cavelon test run`)"]);
@@ -901,6 +1286,15 @@ export function solutionStateLines(state) {
901
1286
  lines.push(["state error", state.unavailable]);
902
1287
  return lines;
903
1288
  }
1289
+ function defaultRouteText(harness, route) {
1290
+ if (route.is_default === null)
1291
+ return "unknown (this instance does not say which solution is the default)";
1292
+ if (route.is_default)
1293
+ return "yes: the tenant's chat and widget answer with it where a conversation names no solution";
1294
+ const now = route.current ? named(route.current) : "no solution";
1295
+ const how = harness.status === "active" ? cavelonCommand("harness", "default", harness.slug) : cavelonCommand("activate", "--harness", harness.slug, "--make-default");
1296
+ return `no: ${now} answers the tenant's chat and widget; preview a change with ${how}`;
1297
+ }
904
1298
  function checkLine(c) {
905
1299
  return clip([c.label ?? c.key, c.message ?? c.detail].filter(Boolean).join(": "), 300);
906
1300
  }
@@ -937,7 +1331,8 @@ async function defaultRouteAfterActivation(ctx, harness, input) {
937
1331
  if (route.current?.id === harness.id)
938
1332
  return { data: { default_route: { is_default: true, current } }, lines: [`${named(harness)} is the tenant's default route.`] };
939
1333
  const commands = defaultCommands(harness.slug);
940
- if (make && boolOption(input, "confirm")) {
1334
+ const gate = make ? await confirmation(ctx, input, "activate", { harness: harness.id, from: current?.id ?? null }) : undefined;
1335
+ if (gate?.confirmed) {
941
1336
  try {
942
1337
  await setDefaultRoute(ctx, harness.id);
943
1338
  }
@@ -958,12 +1353,18 @@ async function defaultRouteAfterActivation(ctx, harness, input) {
958
1353
  }
959
1354
  if (!route.known && !make)
960
1355
  return { data: { default_route: { is_default: null, known: false } }, lines: [] };
961
- const lines = make
962
- ? [defaultChangeLine(harness, route), `Show this to a person; with their yes: ${cavelonCommand("activate", "--harness", harness.slug, "--make-default", "--confirm")}`]
963
- : [
964
- `Not the default route: ${current ? `the tenant's chat and widget answer with ${named(current)}` : "the tenant has none"} where a conversation names no solution.`,
965
- `Ask the person whether ${named(harness)} should answer there; that changes live traffic. Preview: ${commands.preview}`,
966
- ];
1356
+ if (gate) {
1357
+ const confirm = cavelonCommand("activate", "--harness", harness.slug, "--make-default", "--confirm");
1358
+ return {
1359
+ data: { default_route: { is_default: false, known: route.known, current, preview: commands.preview, confirm: gate.confirm(confirm), ...gate.fields } },
1360
+ lines: [defaultChangeLine(harness, route), ...(gate.mismatch ? [gate.mismatch] : []), `Show this to a person; with their yes: ${gate.confirm(confirm)}`],
1361
+ ...(gate.exitCode ? { exitCode: gate.exitCode } : {}),
1362
+ };
1363
+ }
1364
+ const lines = [
1365
+ `Not the default route: ${current ? `the tenant's chat and widget answer with ${named(current)}` : "the tenant has none"} where a conversation names no solution.`,
1366
+ `Ask the person whether ${named(harness)} should answer there; that changes live traffic. Preview: ${commands.preview}`,
1367
+ ];
967
1368
  return { data: { default_route: { is_default: false, known: route.known, current, preview: commands.preview, confirm: commands.confirm } }, lines };
968
1369
  }
969
1370
  export const activate = {
@@ -982,17 +1383,23 @@ export const activate = {
982
1383
  harness: HARNESS_OPTION,
983
1384
  env: ENV_OPTION,
984
1385
  "make-default": { type: "boolean", description: "Also make it the tenant's default route: previews the change; with --confirm, makes it." },
985
- confirm: { type: "boolean", description: "With --make-default: change the default route (after a person saw the preview)." },
1386
+ confirm: { type: "boolean", mcpToken: true, description: "With --make-default: change the default route (after a person saw the preview)." },
986
1387
  },
987
- examples: ["cavelon activate", "cavelon activate --make-default", "cavelon activate --make-default --confirm"],
1388
+ examples: ["cavelon activate", "cavelon activate --make-default", "cavelon activate --make-default --confirm", "cavelon activate --make-default --confirm <token>"],
988
1389
  async run(ctx, input) {
989
1390
  const session = await ctx.session();
990
1391
  const { ref, source } = harnessRef(session, input);
991
1392
  if (!ref)
992
1393
  throw usageError("Which solution?", "Pass --harness <name or slug> (`cavelon harness list` shows them), or set harness in cavelon.yaml or the env file.");
993
- if (boolOption(input, "confirm") && !boolOption(input, "make-default")) {
1394
+ if (confirmGiven(input) && !boolOption(input, "make-default")) {
994
1395
  throw usageError("--confirm only applies to --make-default.", "Activation itself needs no confirmation; the default route does.");
995
1396
  }
1397
+ if (ctx.mode === "mcp" && input.options.confirm === true)
1398
+ throw confirmTokenRequired("activate");
1399
+ const driven = drivenByAgent(ctx);
1400
+ if (driven?.by === "agent" && input.options.confirm === true) {
1401
+ throw shellTokenRequired(cavelonCommand("activate", "--harness", ref, "--make-default"), driven.variable);
1402
+ }
996
1403
  const client = await ctx.client();
997
1404
  const principal = await readPrincipal(client);
998
1405
  if (principal?.kind === "personal_access_token" && principal.token && !principal.token.may_activate) {
@@ -1008,7 +1415,7 @@ export const activate = {
1008
1415
  return {
1009
1416
  data: { activated: false, already_active: true, harness, ...route.data },
1010
1417
  text: [`${harness.name} (${harness.slug}) is already active.`, ...route.lines].join("\n"),
1011
- ...(route.failed ? { exitCode: ExitCode.failure } : {}),
1418
+ ...(route.failed ? { exitCode: ExitCode.failure } : route.exitCode ? { exitCode: route.exitCode } : {}),
1012
1419
  };
1013
1420
  }
1014
1421
  const readiness = await callStable(ctx, "GET", "/api/v1/harnesses/{harness_id}/readiness", "reading readiness", {
@@ -1039,7 +1446,7 @@ export const activate = {
1039
1446
  return {
1040
1447
  data: { activated: true, harness: activated, checks, warnings, readiness, ...route.data },
1041
1448
  text: [`Activated ${activated.name} (${activated.slug}); status ${activated.status}.`, ...readinessText(checks, warnings), ...route.lines].join("\n"),
1042
- ...(route.failed ? { exitCode: ExitCode.failure } : {}),
1449
+ ...(route.failed ? { exitCode: ExitCode.failure } : route.exitCode ? { exitCode: route.exitCode } : {}),
1043
1450
  };
1044
1451
  },
1045
1452
  };