@cavelon/cli 0.1.5 → 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.
@@ -4,25 +4,29 @@ 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
12
  import { callStable } from "../invoke.js";
11
- import { harnessNotFoundError, lookupHarness } from "../harness-ref.js";
13
+ import { harnessNotFoundError, lookupHarness, SLUG } from "../harness-ref.js";
12
14
  import { defaultChangeLine, defaultCommands, named, readDefaultRoute, setDefaultRoute } from "../default-route.js";
13
15
  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";
16
+ import { deletePreview, digest, fileDigest, fileDigests, listPreviews, loadPreview, previewExpiry, readItemFiles, readPulledFiles, rememberAppliedFiles, savePreview, writePulledFiles, writeState, } from "../local-state.js";
15
17
  import { catalogEntry, checkPackage, KIT_CODES, packageVersionOf } from "../package-check.js";
16
18
  import { cliFix, similarCodes } from "../code-hints.js";
17
19
  import { KIT_ERROR_CODES } from "../kit-codes.js";
18
20
  import { pairOrderHint, pairOrderPointer } from "../pair-order.js";
19
- import { readPackage, writePackage } from "../package-files.js";
21
+ import { readPackage, tenantWideSections, writePackage } from "../package-files.js";
20
22
  import { blockerDetails, blockerLines, changeLines, fieldChanges, locateBlockers, notApplied, notAppliedLines } from "../preview-report.js";
21
23
  import { readPrincipal } from "../principal.js";
22
24
  import { CASE_STATUSES, caseStatus, TESTING_PAGE } from "../results.js";
25
+ import { KNOWLEDGE_OUTCOME_AREA, KNOWLEDGE_OUTCOME_PAGE, KNOWLEDGE_OUTCOMES, knowledgeOutcome } from "../trace-view.js";
23
26
  import { isUuid, requireInstance } from "../session.js";
24
27
  import { listedPages } from "./docs.js";
25
- import { readInventory, writeInventory } from "./inventory.js";
28
+ import { readInventory, readInventoryKinds, writeInventory } from "./inventory.js";
29
+ import { checkedBy, MODEL_UNKNOWN_CODE, missingInventory, REFERENCE_UNKNOWN_CODE } from "../package-references.js";
26
30
  import { cavelonCommand, shellWord } from "../shell.js";
27
31
  import { secretSetCommand, targetFlags, variableSetCommand } from "./values.js";
28
32
  const HARNESS_OPTION = { type: "string", value: "<harness>", description: "The solution (harness): its name, slug or id; default: env file, then cavelon.yaml." };
@@ -112,6 +116,7 @@ async function limitsFor(ctx, offline) {
112
116
  async function acceptedVersions(ctx, offline) {
113
117
  return (await capabilitiesFor(ctx, offline))?.contracts?.package_versions?.accepted;
114
118
  }
119
+ const BLOCKING_WARNINGS = new Set([REFERENCE_UNKNOWN_CODE, MODEL_UNKNOWN_CODE]);
115
120
  function findingLine(f) {
116
121
  const where = f.file ? `${f.file}${f.line ? `:${f.line}` : ""}` : "";
117
122
  const at = f.path ? ` ${f.path}` : "";
@@ -142,8 +147,8 @@ async function unknownStates(root, files, known) {
142
147
  }
143
148
  return out;
144
149
  }
145
- async function editedSincePull(project, pkg, schema) {
146
- const planned = await writePackage(project.root, project.layout, pkg, schema, { dryRun: true });
150
+ async function editedSincePull(project, pkg, schema, options) {
151
+ const planned = await writePackage(project.root, project.layout, pkg, schema, { ...options, dryRun: true, placed: undefined });
147
152
  const pulled = await readPulledFiles(project.root);
148
153
  const edited = [];
149
154
  for (const file of [...planned.written, ...planned.removed]) {
@@ -157,8 +162,11 @@ export const pull = {
157
162
  name: "pull",
158
163
  summary: "Write the instance's package into package/ (split along the schema's sections) and the inventory into .cavelon/.",
159
164
  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" +
165
+ "A file whose content did not change keeps its bytes, so `git diff` shows what changed on the instance; a field the export\n" +
166
+ "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" +
167
+ "pulled into or applied from, whatever its name. Files of sections the schema does not know are kept byte for byte.\n" +
168
+ "A solution's export leaves the tenant-wide sections (the tenant's settings, its model list) out of the folder, unless\n" +
169
+ "--tenant-wide. Refuses when package files have uncommitted changes, unless --force;\n" +
162
170
  "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
171
  "or apply left it (digests in .cavelon/) counts as unchanged, committed or not.",
164
172
  readOnly: false,
@@ -170,8 +178,12 @@ export const pull = {
170
178
  options: {
171
179
  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
180
  force: { type: "boolean", description: "Overwrite package files that have uncommitted changes since the last pull or apply." },
181
+ "tenant-wide": {
182
+ type: "boolean",
183
+ description: "With a solution, also write the tenant-wide sections its export carries (tenant_settings, model_registry): apply then sends them for the whole tenant.",
184
+ },
173
185
  },
174
- examples: ["cavelon pull --harness support", "cavelon pull && git diff -- package tests"],
186
+ examples: ["cavelon pull --harness support", "cavelon pull && git status --short -- package tests"],
175
187
  async run(ctx, input) {
176
188
  const session = await ctx.session();
177
189
  const project = requireSolution(session);
@@ -200,14 +212,17 @@ export const pull = {
200
212
  const { schema } = await schemaFor(ctx, version, false);
201
213
  if (!schema)
202
214
  ctx.warn("The instance does not publish its package schema; every top-level key became a file of its own.");
215
+ const skip = harness && !boolOption(input, "tenant-wide") ? tenantWideSections(schema) : new Set();
216
+ const placed = {};
217
+ const options = { skip, itemFiles: await readItemFiles(project.root), placed };
203
218
  if (dirty === undefined) {
204
- const edited = await editedSincePull(project, exported, schema);
219
+ const edited = await editedSincePull(project, exported, schema, options);
205
220
  if (edited.length) {
206
221
  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
222
  }
208
223
  }
209
- const report = await writePackage(project.root, project.layout, exported, schema);
210
- await writePulledFiles(project.root, [...report.written, ...report.unchanged]);
224
+ const report = await writePackage(project.root, project.layout, exported, schema, options);
225
+ await writePulledFiles(project.root, [...report.written, ...report.unchanged], placed);
211
226
  if (harness && !project.harness)
212
227
  await setProjectKey(project, "harness", harness.slug);
213
228
  if (version && project.packageVersion !== version)
@@ -228,6 +243,12 @@ export const pull = {
228
243
  ctx.warn(`Kept ${file}: its section is not in this instance's package schema.`);
229
244
  for (const section of report.refused)
230
245
  ctx.warn(`Did not write section ${JSON.stringify(section)}: its name is not a plain file name.`);
246
+ const tenantFiles = report.tenant_wide.flatMap((section) => [".yaml", ".yml", ".json"].map((ext) => `${project.layout.package}/${section}${ext}`));
247
+ for (const file of tenantFiles) {
248
+ if ((await readTextFile(path.join(project.root, file))) === undefined)
249
+ continue;
250
+ ctx.warn(`Kept ${file} as it is: it holds a tenant-wide section, which pull leaves out of a solution's folder. apply sends it for the whole tenant; remove the file unless you mean that.`);
251
+ }
231
252
  const rewritten = report.written.length + report.removed.length;
232
253
  const lines = [
233
254
  `Pulled ${harness ? `solution ${harness.name} (${harness.slug})` : "the tenant's full configuration"} into ${project.layout.package}/` +
@@ -236,12 +257,36 @@ export const pull = {
236
257
  ...report.written.map((f) => `written ${f}`),
237
258
  ...report.removed.map((f) => `removed ${f}`),
238
259
  `${report.unchanged.length} file${report.unchanged.length === 1 ? "" : "s"} unchanged.`,
260
+ ...(report.tenant_wide.length
261
+ ? [`Left out the tenant-wide section${report.tenant_wide.length === 1 ? "" : "s"} ${report.tenant_wide.join(", ")} (--tenant-wide writes them).`]
262
+ : []),
239
263
  `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.",
264
+ !rewritten
265
+ ? "Nothing changed on the instance since the last pull."
266
+ : dirty === undefined
267
+ ? "See what changed: the files listed above (this folder is not in a git repository)."
268
+ : `See what changed: git status --short -- ${layoutDirs.join(" ")} (new files), then git diff -- ${layoutDirs.join(" ")}`,
241
269
  ];
242
270
  return { data: { ...record, inventory }, text: lines.join("\n") };
243
271
  },
244
272
  };
273
+ async function inventoryFor(ctx, project, disk, offline) {
274
+ let inventory = await readInventory(project.root);
275
+ const missing = missingInventory(disk, inventory);
276
+ let failed = missing;
277
+ if (missing.length && !offline) {
278
+ failed = await readInventoryKinds(ctx, project.root, missing, ctx.io.now());
279
+ inventory = await readInventory(project.root);
280
+ }
281
+ const skipped = failed.map((kind) => ({
282
+ check: checkedBy(kind),
283
+ kind,
284
+ reason: offline
285
+ ? `--offline, and no list of the tenant's ${kind.replace("_", " ")} is cached; \`cavelon ${kind === "models" ? "models list" : "pull"}\` reads it`
286
+ : `the tenant's ${kind.replace("_", " ")} could not be read`,
287
+ }));
288
+ return { inventory, skipped };
289
+ }
245
290
  async function validatePackage(ctx, project, offline) {
246
291
  const disk = await readPackage(project.root, project.layout);
247
292
  const version = packageVersionOf(disk.package) ?? project.packageVersion;
@@ -255,14 +300,16 @@ async function validatePackage(ctx, project, offline) {
255
300
  : "The instance does not publish its package schema (/api/v1/meta/package-schema).",
256
301
  });
257
302
  }
303
+ const { inventory, skipped } = await inventoryFor(ctx, project, disk, offline);
258
304
  const findings = checkPackage(disk, {
259
305
  schema,
260
306
  catalog: await catalogFor(ctx, offline),
261
307
  accepted: await acceptedVersions(ctx, offline),
262
308
  limits: await limitsFor(ctx, offline),
263
- inventory: await readInventory(project.root),
309
+ inventory,
310
+ solution: project.harness,
264
311
  });
265
- return { disk, findings, schemaVersion: schema["x-package-version"] ?? version ?? null, used };
312
+ return { disk, findings, schemaVersion: schema["x-package-version"] ?? version ?? null, used, skipped };
266
313
  }
267
314
  function schemaUsedLine(used, ttlSeconds) {
268
315
  const from = used.source === "instance" ? "read from the instance now" : `cached at ${used.fetched_at ?? "an unknown time"}`;
@@ -285,10 +332,16 @@ export const validate = {
285
332
  "sent with it; --verbose says which copy was used.\n" +
286
333
  "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
334
  "tenant runs fan-outs and Map loops in sequence, from the limits the instance last published.\n" +
335
+ "References to skills, tools, knowledge bases, solutions and models outside the package are checked against the tenant's\n" +
336
+ "lists in .cavelon/inventory.json (pull, models list); a list no command has read yet is read now, unless --offline, and a\n" +
337
+ "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" +
338
+ "on the instance before the import; the import preview blocks it otherwise, so validate does not say \"Valid\" then, and\n" +
339
+ "--strict fails on every warning (exit 3).\n" +
288
340
  "Each finding carries a code: `cavelon explain <code>` says more. The import preview checks everything again on the server.\n\n" +
289
341
  "With --json, `warnings` is always a list of `{code, message}` objects: the warning findings (at most --limit), then the\n" +
290
342
  "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.",
343
+ "`error_count` the errors (`errors` is the same number); `findings` has each finding's file, line and hint; `blocking_count`\n" +
344
+ "counts the warnings the import preview blocks on.",
292
345
  readOnly: true,
293
346
  idempotent: true,
294
347
  mcpTool: "validate",
@@ -296,15 +349,19 @@ export const validate = {
296
349
  offline: { type: "boolean", description: "Never contact the instance, even when nothing is cached." },
297
350
  limit: { type: "string", value: "<n>", description: "Print at most n findings (default 50)." },
298
351
  verbose: { type: "boolean", description: "Also say which copy of the package schema was used: cached or read now, when, and its hash." },
352
+ 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
353
  },
300
354
  async run(ctx, input) {
301
355
  const session = await ctx.session();
302
356
  const project = requireSolution(session);
303
357
  requireInstance(session);
304
358
  const limit = intOption(input, "limit", { min: 1, max: 1000, fallback: 50 });
305
- const { disk, findings, schemaVersion, used } = await validatePackage(ctx, project, boolOption(input, "offline"));
359
+ const strict = boolOption(input, "strict");
360
+ const { disk, findings, schemaVersion, used, skipped } = await validatePackage(ctx, project, boolOption(input, "offline"));
306
361
  const errors = findings.filter((f) => f.severity === "error");
307
362
  const warnings = findings.filter((f) => f.severity === "warning");
363
+ const blocking = warnings.filter((f) => BLOCKING_WARNINGS.has(f.code));
364
+ const failed = errors.length > 0 || (strict && warnings.length > 0);
308
365
  if (disk.empty)
309
366
  ctx.warn(`No package files in ${project.layout.package}/ yet; \`cavelon pull\` brings an existing solution.`);
310
367
  const contracts = await ctx.contracts();
@@ -314,26 +371,37 @@ export const validate = {
314
371
  ...ctx.warnings.map((message) => ({ code: null, message })),
315
372
  ];
316
373
  const data = {
317
- valid: errors.length === 0,
374
+ valid: !failed,
375
+ strict,
318
376
  schema_version: schemaVersion,
319
377
  schema: used,
320
378
  sections: Object.keys(disk.package).length,
321
379
  error_count: errors.length,
322
380
  warning_count: warnings.length + ctx.warnings.length,
381
+ blocking_count: blocking.length,
323
382
  errors: errors.length,
324
383
  warnings: listed,
325
384
  findings: shown,
326
385
  more: Math.max(0, findings.length - shown.length),
386
+ skipped,
327
387
  };
388
+ const counts = `${errors.length} error${errors.length === 1 ? "" : "s"}, ${warnings.length} warning${warnings.length === 1 ? "" : "s"}`;
389
+ const verdict = errors.length
390
+ ? `${counts}. \`cavelon explain <code>\` says more.`
391
+ : strict && warnings.length
392
+ ? `${counts}; --strict fails on warnings. \`cavelon explain <code>\` says more.`
393
+ : blocking.length
394
+ ? `No errors against package schema ${schemaVersion ?? "?"} (${data.sections} sections), but ${blocking.length === 1 ? "one reference" : `${blocking.length} references`} ` +
395
+ `the import preview will block unless ${blocking.length === 1 ? "it exists" : "they exist"} on the instance by then (${counts}; --strict fails on warnings).`
396
+ : `Valid against package schema ${schemaVersion ?? "?"} (${data.sections} sections${warnings.length ? `, ${warnings.length} warning${warnings.length === 1 ? "" : "s"}` : ""}).`;
328
397
  const text = [
329
398
  ...(boolOption(input, "verbose") ? [schemaUsedLine(used, (v) => contracts.ttlSeconds(v))] : []),
330
399
  ...shown.map(findingLine),
331
400
  ...(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"}` : ""}).`,
401
+ ...skipped.map((s) => `Not checked: ${s.check} (${s.reason}).`),
402
+ verdict,
335
403
  ].join("\n");
336
- return { data, text, exitCode: errors.length ? ExitCode.validation : ExitCode.ok };
404
+ return { data, text, exitCode: failed ? ExitCode.validation : ExitCode.ok };
337
405
  },
338
406
  };
339
407
  function valueNeeds(list) {
@@ -448,16 +516,89 @@ function previewIdOption(input) {
448
516
  throw usageError("--confirm needs the preview id that `cavelon apply` printed.");
449
517
  return id?.trim();
450
518
  }
451
- async function confirmPreview(ctx, project, previewId) {
519
+ function previewUnknown(previewId) {
520
+ return new CavelonError(ExitCode.usage, {
521
+ code: "preview_unknown",
522
+ message: `No open preview ${previewId} in this solution.`,
523
+ hint: "Run `cavelon apply` (with the same --env or --harness) for a new preview and confirm its id; `cavelon status` lists the open ones.",
524
+ });
525
+ }
526
+ async function discardPreviews(ctx, project, which) {
527
+ const open = await listPreviews(project.root, ctx.io.now());
528
+ const chosen = which === "all" ? open : open.filter((p) => p.preview_id === which);
529
+ if (which !== "all" && chosen.length === 0)
530
+ throw previewUnknown(which);
531
+ for (const p of chosen)
532
+ await deletePreview(project.root, p.preview_id);
533
+ const ids = chosen.map((p) => p.preview_id);
534
+ return {
535
+ data: { discarded: ids, count: ids.length },
536
+ text: ids.length ? `Discarded ${ids.length === 1 ? "preview" : `${ids.length} previews`}: ${ids.join(", ")}. Nothing changed on the instance.` : "No open previews to discard.",
537
+ };
538
+ }
539
+ async function filesChangedSince(project, stored, disk) {
540
+ if (!stored.file_digests)
541
+ return [];
542
+ const previewed = stored.file_digests;
543
+ const now = await fileDigests(project.root, sourceFiles(disk));
544
+ const files = new Set([...Object.keys(previewed), ...Object.keys(now)]);
545
+ return [...files].filter((file) => previewed[file] !== now[file]).sort((a, b) => a.localeCompare(b, "en"));
546
+ }
547
+ async function rememberImported(ctx, project, stored, disk, changed) {
548
+ if (!stored.file_digests)
549
+ return;
550
+ const now = await fileDigests(project.root, sourceFiles(disk));
551
+ const known = {};
552
+ for (const [file, value] of Object.entries(stored.file_digests))
553
+ if (now[file] === value)
554
+ known[file] = value;
555
+ if (!changed.length)
556
+ return rememberAppliedFiles(project.root, known);
557
+ const holds = await instanceHolds(ctx, project, stored).catch((error) => {
558
+ 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.`);
559
+ return undefined;
560
+ });
561
+ const unknown = [];
562
+ for (const file of changed) {
563
+ if (holds?.has(file) && now[file])
564
+ known[file] = now[file];
565
+ else
566
+ unknown.push(file);
567
+ }
568
+ await rememberAppliedFiles(project.root, known, unknown);
569
+ }
570
+ async function instanceHolds(ctx, project, stored) {
571
+ const harnessId = stored.request.harness_id;
572
+ const scope = harnessId ? "agent_graph" : stored.request.package.manifest?.scope;
573
+ if (scope !== "agent_graph" && scope !== "full_config")
574
+ return undefined;
575
+ if (scope === "agent_graph" && !harnessId)
576
+ return undefined;
577
+ const exported = await callStable(ctx, "GET", "/api/v1/agent-graph/export", "exporting packages", {
578
+ query: { scope, harness_id: harnessId },
579
+ timeoutMs: 120_000,
580
+ });
581
+ if (!exported || typeof exported !== "object" || Array.isArray(exported))
582
+ return undefined;
583
+ const { schema } = await schemaFor(ctx, packageVersionOf(exported), false);
584
+ const planned = await writePackage(project.root, project.layout, exported, schema, { dryRun: true });
585
+ return new Set(planned.unchanged);
586
+ }
587
+ async function confirmPreview(ctx, project, previewId, allowStale) {
452
588
  const stored = await loadPreview(project.root, previewId);
453
- 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.",
589
+ if (!stored)
590
+ throw previewUnknown(previewId);
591
+ const session = await ctx.session();
592
+ const expiry = previewExpiry(stored.created_at, ctx.io.now());
593
+ if (expiry.expired) {
594
+ await deletePreview(project.root, stored.preview_id);
595
+ throw new CavelonError(ExitCode.conflict, {
596
+ code: "preview_expired",
597
+ message: `Preview ${previewId} was made at ${stored.created_at} and expired${expiry.expires_at ? ` at ${expiry.expires_at}` : ""}; nothing was imported.`,
598
+ hint: `Run \`${previewAgain(stored, session)}\` again, show the new preview, and confirm its id.`,
599
+ details: { preview_id: stored.preview_id, created_at: stored.created_at, expires_at: expiry.expires_at },
458
600
  });
459
601
  }
460
- const session = await ctx.session();
461
602
  if (requireInstance(session) !== stored.instance) {
462
603
  throw new CavelonError(ExitCode.conflict, {
463
604
  code: "preview_other_instance",
@@ -476,18 +617,28 @@ async function confirmPreview(ctx, project, previewId) {
476
617
  if (stored.tenant_id && session.tokenKind !== "api_key")
477
618
  client.target.tenantId = stored.tenant_id;
478
619
  const disk = await readPackage(project.root, project.layout);
620
+ const changed = await filesChangedSince(project, stored, disk);
479
621
  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.");
622
+ if (!allowStale) {
623
+ throw new CavelonError(ExitCode.conflict, {
624
+ code: "preview_files_changed",
625
+ message: `The package files changed since preview ${previewId}${changed.length ? ` (${list(changed, 5)})` : ""}; nothing was imported.`,
626
+ hint: `Run \`${previewAgain(stored, session)}\` for a preview of the files as they are now, show it, and confirm its id. ` +
627
+ `To import what preview ${previewId} showed instead, add --allow-stale to the confirm.`,
628
+ details: { preview_id: stored.preview_id, files: changed },
629
+ });
630
+ }
631
+ ctx.warn(`The package files changed since this preview${changed.length ? ` (${list(changed, 5)})` : ""}; importing what the preview showed (--allow-stale). ` +
632
+ "The files keep their changes, which the instance does not hold; run `cavelon apply` to preview them.");
481
633
  }
482
634
  try {
483
635
  const result = await callStable(ctx, "POST", "/api/v1/agent-graph/import", "importing packages", {
484
636
  body: { ...stored.request, preview_id: stored.preview_id },
485
637
  timeoutMs: 300_000,
486
638
  });
487
- for (const other of await listPreviews(project.root))
639
+ for (const other of await listPreviews(project.root, ctx.io.now()))
488
640
  await deletePreview(project.root, other.preview_id);
489
- if (stored.file_digests)
490
- await rememberAppliedFiles(project.root, stored.file_digests);
641
+ await rememberImported(ctx, project, stored, disk, changed);
491
642
  const summary = (result.summary ?? {});
492
643
  const flags = targetFlags(session, stored.env ?? session.envFile?.name);
493
644
  const still = setCommands(stored.preview, flags);
@@ -567,17 +718,21 @@ async function applyTarget(ctx, session, input, pkg) {
567
718
  return undefined;
568
719
  const { harness: found, candidates } = await lookupHarness(ctx, ref);
569
720
  if (found)
570
- return { ...found, created: false };
571
- if (!source?.startsWith("env/") || isUuid(ref))
721
+ return found;
722
+ if (!source || source === "option" || isUuid(ref) || !SLUG.test(ref))
572
723
  throw harnessNotFoundError(ref, candidates, source);
573
724
  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 };
725
+ const create = cavelonCommand("harness", "new", ref, ...(name !== ref ? ["--name", name] : []));
726
+ throw new CavelonError(ExitCode.failure, {
727
+ code: "solution_not_found",
728
+ message: `Solution ${ref}, which ${source} names, is not on the instance yet; apply previews into an existing solution and creates none.`,
729
+ hint: `Create it as a draft: ${create}, then run \`${cavelonCommand("apply")}${targetFlags(session)}\` again.`,
730
+ details: { slug: ref, name, create },
731
+ });
577
732
  }
578
733
  function packageHarnessName(pkg, slug) {
579
734
  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);
735
+ const entry = entries.find((h) => h.slug === slug);
581
736
  const name = typeof entry?.name === "string" ? entry.name.trim() : "";
582
737
  return name ? name.slice(0, 255) : undefined;
583
738
  }
@@ -600,10 +755,14 @@ export const apply = {
600
755
  summary: "Preview the package files against the instance and print a preview id; --confirm <id> imports exactly that preview.",
601
756
  description: "Without --confirm nothing is imported: the preview shows what changes, which active solutions it reaches, what the target\n" +
602
757
  "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.",
758
+ "budgets and ignored sections, and is stored in .cavelon/. A preview never creates the solution: one the env file names\n" +
759
+ "that is not on the instance yet gets the `cavelon harness new` command that creates it as a draft. A person sets the\n" +
760
+ "secrets (`cavelon secrets set <name>`), never the agent.\n" +
761
+ "Show a preview that reaches an active solution or env/prod to a person before confirming. A stale preview exits 4 and\n" +
762
+ "imports nothing: one whose target changed on the instance since, one whose package files changed since (what they\n" +
763
+ "hold, not their formatting; --allow-stale imports what the preview showed anyway), and one older than a day. So does\n" +
764
+ "an import its own check refuses when it applies, naming each blocker. --discard <id|all> forgets stored previews;\n" +
765
+ "`cavelon status` lists them with when each expires.",
607
766
  readOnly: false,
608
767
  destructive: true,
609
768
  mcpTool: "apply",
@@ -611,16 +770,32 @@ export const apply = {
611
770
  env: ENV_OPTION,
612
771
  harness: HARNESS_OPTION,
613
772
  confirm: { type: "string", value: "<preview-id>", description: "Import exactly this stored preview." },
773
+ "allow-stale": {
774
+ type: "boolean",
775
+ description: "With --confirm: import what the preview showed although the package files changed since it.",
776
+ },
777
+ discard: { type: "string", value: "<preview-id|all>", description: "Forget this stored preview, or all of them; changes nothing on the instance." },
614
778
  mode: { type: "string", value: "<mode>", description: "overwrite (default) or replace (deletes what the package does not hold)." },
615
779
  },
616
- examples: ["cavelon apply --env test", "cavelon apply --confirm <preview-id>", "cavelon apply --env prod --json"],
780
+ examples: ["cavelon apply --env test", "cavelon apply --confirm <preview-id>", "cavelon apply --env prod --json", "cavelon apply --discard all"],
617
781
  async run(ctx, input) {
618
782
  const session = await ctx.session();
619
783
  const project = requireSolution(session);
620
784
  const url = requireInstance(session);
621
785
  const confirm = previewIdOption(input);
786
+ const discard = stringOption(input, "discard")?.trim();
787
+ const allowStale = boolOption(input, "allow-stale");
788
+ if (discard !== undefined && confirm)
789
+ throw usageError("Pass --confirm or --discard, not both.");
790
+ if (allowStale && !confirm)
791
+ throw usageError("--allow-stale only applies to --confirm <preview-id>.");
792
+ if (discard !== undefined) {
793
+ if (!discard)
794
+ throw usageError("--discard needs a preview id, or all.", "`cavelon status` lists the open previews.");
795
+ return discardPreviews(ctx, project, discard);
796
+ }
622
797
  if (confirm)
623
- return confirmPreview(ctx, project, confirm);
798
+ return confirmPreview(ctx, project, confirm, allowStale);
624
799
  const envFile = session.envFile;
625
800
  if (envFile?.tenant && session.tenantSource !== `env/${envFile.name}.yaml`) {
626
801
  ctx.warn(`${session.tenantSource} names tenant "${session.tenant}" and takes precedence over ${envFile.name}.yaml's "${envFile.tenant}".`);
@@ -653,7 +828,7 @@ export const apply = {
653
828
  body: request,
654
829
  timeoutMs: 120_000,
655
830
  });
656
- const target = harness ? { id: harness.id, slug: harness.slug, created: harness.created } : null;
831
+ const target = harness ? { id: harness.id, slug: harness.slug } : null;
657
832
  const data = { previewed: true, ...preview, env: envFile?.name ?? null, harness: target };
658
833
  const flags = targetFlags(session);
659
834
  const commands = setCommands(preview, flags);
@@ -696,6 +871,9 @@ export const apply = {
696
871
  preview,
697
872
  };
698
873
  await savePreview(project.root, stored);
874
+ for (const old of await listPreviews(project.root, ctx.io.now()))
875
+ if (old.expired)
876
+ await deletePreview(project.root, old.preview_id);
699
877
  }
700
878
  const reason = personReason(preview, harness, mode, envFile?.name);
701
879
  data.show_to_person = Boolean(reason);
@@ -755,6 +933,32 @@ async function caseStatusAnswer(ctx, status) {
755
933
  ]),
756
934
  };
757
935
  }
936
+ async function knowledgeOutcomeAnswer(ctx, outcome) {
937
+ const instance = (await ctx.session().catch(() => undefined))?.url;
938
+ const page = `/docs/${KNOWLEDGE_OUTCOME_PAGE}`;
939
+ const data = {
940
+ code: outcome.value,
941
+ kind: "knowledge_outcome",
942
+ message: outcome.message,
943
+ hint: outcome.hint,
944
+ ...(outcome.recorded_as ? { recorded_as: outcome.recorded_as } : {}),
945
+ docs: instance ? `${instance}${page}` : page,
946
+ read: [{ page: KNOWLEDGE_OUTCOME_PAGE, command: cavelonCommand("docs", "get", KNOWLEDGE_OUTCOME_PAGE) }],
947
+ };
948
+ return {
949
+ data,
950
+ text: keyValues([
951
+ ["code", outcome.value],
952
+ ["kind", OUTCOME_KIND],
953
+ ["meaning", outcome.message],
954
+ ["next", outcome.hint],
955
+ ["recorded as", outcome.recorded_as],
956
+ ["docs", data.docs],
957
+ ["read", data.read[0].command],
958
+ ]),
959
+ };
960
+ }
961
+ const OUTCOME_KIND = "knowledge outcome (what a knowledge search found, as its retrieval span's knowledge_outcome says)";
758
962
  export const explain = {
759
963
  name: "explain",
760
964
  summary: "Look a code up in the instance's error catalog: what it means and how to fix it.",
@@ -762,7 +966,9 @@ export const explain = {
762
966
  "findings, and errors the CLI raises itself, such as operation_not_found or uncommitted_changes) are known too. Uses the\n" +
763
967
  "cached catalog first. Where the instance's fix names an API route, the command that does the same is added. An unknown\n" +
764
968
  "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(", ")}.`,
969
+ `Also explains the test-case statuses that are neither pass nor fail: ${CASE_STATUSES.map((s) => s.status).join(", ")};\n` +
970
+ `and the values of a retrieval span's knowledge_outcome (${KNOWLEDGE_OUTCOMES.map((o) => o.value).join(", ")}), from the\n` +
971
+ "instance's catalog (area knowledge_outcome) where it lists them.",
766
972
  readOnly: true,
767
973
  idempotent: true,
768
974
  mcpTool: "explain",
@@ -770,10 +976,17 @@ export const explain = {
770
976
  async run(ctx, input) {
771
977
  const code = positional(input, "code").trim();
772
978
  const status = caseStatus(code);
773
- let catalog = status ? await catalogFor(ctx, false).catch(() => null) : await catalogFor(ctx, false);
979
+ const outcome = knowledgeOutcome(code);
980
+ let catalog = status || outcome ? await catalogFor(ctx, false).catch(() => null) : await catalogFor(ctx, false);
774
981
  let entry = catalogEntry(catalog, code) ?? looseEntry(catalog, code);
982
+ if (!entry && outcome && catalog) {
983
+ catalog = await (await ctx.contracts()).errorCatalog({ refresh: true }).catch(() => catalog);
984
+ entry = catalogEntry(catalog, outcome.value);
985
+ }
775
986
  if (!entry && status)
776
987
  return caseStatusAnswer(ctx, status);
988
+ if (!entry && outcome)
989
+ return knowledgeOutcomeAnswer(ctx, outcome);
777
990
  if (!entry || entry.kind === "kit" || entry.kind === "cli") {
778
991
  catalog = await (await ctx.contracts()).errorCatalog({ refresh: true }).catch(() => catalog);
779
992
  entry = catalogEntry(catalog, code) ?? looseEntry(catalog, code) ?? entry;
@@ -792,6 +1005,7 @@ export const explain = {
792
1005
  ...KIT_CODES,
793
1006
  ...KIT_ERROR_CODES,
794
1007
  ...CASE_STATUSES.map((s) => ({ code: s.status })),
1008
+ ...KNOWLEDGE_OUTCOMES.map((o) => ({ code: o.value })),
795
1009
  ].map((e) => e.code);
796
1010
  const similar = similarCodes(code, all);
797
1011
  throw new CavelonError(ExitCode.failure, {
@@ -815,7 +1029,7 @@ export const explain = {
815
1029
  const pages = capacity === MODEL_ENDPOINT_BUSY ? [CAPACITY_TUTORIAL_PAGE, CAPACITY_CONCEPT_PAGE] : [CAPACITY_CONCEPT_PAGE, CAPACITY_TUTORIAL_PAGE];
816
1030
  const read = capacity ? (await listedPages(ctx, pages)).map((page) => ({ page, command: cavelonCommand("docs", "get", page) })) : [];
817
1031
  const cli = entry.kind === "cli" ? undefined : cliFix(entry);
818
- const data = { ...entry, docs, ...(cli ? { cli_fix: cli } : {}), ...(kitHint ? { kit_hint: kitHint } : {}), ...(read.length ? { read } : {}) };
1032
+ const data = { ...entry, ...(entry.area === KNOWLEDGE_OUTCOME_AREA ? { kind: "knowledge_outcome" } : {}), docs, ...(cli ? { cli_fix: cli } : {}), ...(kitHint ? { kit_hint: kitHint } : {}), ...(read.length ? { read } : {}) };
819
1033
  return {
820
1034
  data,
821
1035
  text: keyValues([
@@ -828,7 +1042,9 @@ export const explain = {
828
1042
  ? "cavelon validate code"
829
1043
  : entry.kind === "cli"
830
1044
  ? "cavelon error code (raised by the CLI, not the instance)"
831
- : `API error code${entry.area ? ` (${entry.area})` : ""}`,
1045
+ : entry.area === KNOWLEDGE_OUTCOME_AREA
1046
+ ? OUTCOME_KIND
1047
+ : `API error code${entry.area ? ` (${entry.area})` : ""}`,
832
1048
  ],
833
1049
  ["meaning", entry.message],
834
1050
  ["fix", entry.hint ?? undefined],
@@ -853,6 +1069,14 @@ export async function solutionState(ctx, ref) {
853
1069
  if (!harness)
854
1070
  return { harness: null, unavailable: `This tenant has no solution "${ref}".` };
855
1071
  const state = { harness: { id: harness.id, slug: harness.slug, name: harness.name, status: harness.status } };
1072
+ try {
1073
+ const route = await readDefaultRoute(ctx);
1074
+ const current = route.current ? { id: route.current.id, slug: route.current.slug, name: route.current.name } : null;
1075
+ state.default_route = { is_default: route.known ? route.current?.id === harness.id : null, current };
1076
+ }
1077
+ catch (error) {
1078
+ ctx.warn(`Could not read the tenant's default route: ${error instanceof Error ? error.message : String(error)}`);
1079
+ }
856
1080
  try {
857
1081
  const readiness = await callStable(ctx, "GET", "/api/v1/harnesses/{harness_id}/readiness", "reading readiness", {
858
1082
  params: { harness_id: [harness.id] },
@@ -882,12 +1106,18 @@ export async function solutionState(ctx, ref) {
882
1106
  export function solutionStateLines(state) {
883
1107
  if (!state.harness)
884
1108
  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;
1109
+ const active = state.harness.status === "active";
1110
+ const ready = active
1111
+ ? undefined
1112
+ : state.ready_to_activate === true
1113
+ ? "ready to activate"
1114
+ : state.ready_to_activate === false
1115
+ ? `not ready to activate${state.blockers?.length ? ` (${list(state.blockers, 3)})` : ""}`
1116
+ : undefined;
890
1117
  const lines = [["state", [state.harness.status, ready].filter(Boolean).join(", ")]];
1118
+ const route = state.default_route;
1119
+ if (route)
1120
+ lines.push(["default route", defaultRouteText(state.harness, route)]);
891
1121
  const run = state.latest_test_run;
892
1122
  if (run === null)
893
1123
  lines.push(["last test run", "none yet (`cavelon test run`)"]);
@@ -901,6 +1131,15 @@ export function solutionStateLines(state) {
901
1131
  lines.push(["state error", state.unavailable]);
902
1132
  return lines;
903
1133
  }
1134
+ function defaultRouteText(harness, route) {
1135
+ if (route.is_default === null)
1136
+ return "unknown (this instance does not say which solution is the default)";
1137
+ if (route.is_default)
1138
+ return "yes: the tenant's chat and widget answer with it where a conversation names no solution";
1139
+ const now = route.current ? named(route.current) : "no solution";
1140
+ const how = harness.status === "active" ? cavelonCommand("harness", "default", harness.slug) : cavelonCommand("activate", "--harness", harness.slug, "--make-default");
1141
+ return `no: ${now} answers the tenant's chat and widget; preview a change with ${how}`;
1142
+ }
904
1143
  function checkLine(c) {
905
1144
  return clip([c.label ?? c.key, c.message ?? c.detail].filter(Boolean).join(": "), 300);
906
1145
  }
@@ -937,7 +1176,8 @@ async function defaultRouteAfterActivation(ctx, harness, input) {
937
1176
  if (route.current?.id === harness.id)
938
1177
  return { data: { default_route: { is_default: true, current } }, lines: [`${named(harness)} is the tenant's default route.`] };
939
1178
  const commands = defaultCommands(harness.slug);
940
- if (make && boolOption(input, "confirm")) {
1179
+ const gate = make ? await confirmation(ctx, input, "activate", { harness: harness.id, from: current?.id ?? null }) : undefined;
1180
+ if (gate?.confirmed) {
941
1181
  try {
942
1182
  await setDefaultRoute(ctx, harness.id);
943
1183
  }
@@ -958,12 +1198,18 @@ async function defaultRouteAfterActivation(ctx, harness, input) {
958
1198
  }
959
1199
  if (!route.known && !make)
960
1200
  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
- ];
1201
+ if (gate) {
1202
+ const confirm = cavelonCommand("activate", "--harness", harness.slug, "--make-default", "--confirm");
1203
+ return {
1204
+ data: { default_route: { is_default: false, known: route.known, current, preview: commands.preview, confirm: gate.confirm(confirm), ...gate.fields } },
1205
+ lines: [defaultChangeLine(harness, route), ...(gate.mismatch ? [gate.mismatch] : []), `Show this to a person; with their yes: ${gate.confirm(confirm)}`],
1206
+ ...(gate.exitCode ? { exitCode: gate.exitCode } : {}),
1207
+ };
1208
+ }
1209
+ const lines = [
1210
+ `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.`,
1211
+ `Ask the person whether ${named(harness)} should answer there; that changes live traffic. Preview: ${commands.preview}`,
1212
+ ];
967
1213
  return { data: { default_route: { is_default: false, known: route.known, current, preview: commands.preview, confirm: commands.confirm } }, lines };
968
1214
  }
969
1215
  export const activate = {
@@ -982,7 +1228,7 @@ export const activate = {
982
1228
  harness: HARNESS_OPTION,
983
1229
  env: ENV_OPTION,
984
1230
  "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)." },
1231
+ confirm: { type: "boolean", mcpToken: true, description: "With --make-default: change the default route (after a person saw the preview)." },
986
1232
  },
987
1233
  examples: ["cavelon activate", "cavelon activate --make-default", "cavelon activate --make-default --confirm"],
988
1234
  async run(ctx, input) {
@@ -990,9 +1236,15 @@ export const activate = {
990
1236
  const { ref, source } = harnessRef(session, input);
991
1237
  if (!ref)
992
1238
  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")) {
1239
+ if (confirmGiven(input) && !boolOption(input, "make-default")) {
994
1240
  throw usageError("--confirm only applies to --make-default.", "Activation itself needs no confirmation; the default route does.");
995
1241
  }
1242
+ if (ctx.mode === "mcp" && input.options.confirm === true)
1243
+ throw confirmTokenRequired("activate");
1244
+ const driven = drivenByAgent(ctx);
1245
+ if (driven?.by === "agent" && input.options.confirm === true) {
1246
+ throw shellTokenRequired(cavelonCommand("activate", "--harness", ref, "--make-default"), driven.variable);
1247
+ }
996
1248
  const client = await ctx.client();
997
1249
  const principal = await readPrincipal(client);
998
1250
  if (principal?.kind === "personal_access_token" && principal.token && !principal.token.may_activate) {
@@ -1008,7 +1260,7 @@ export const activate = {
1008
1260
  return {
1009
1261
  data: { activated: false, already_active: true, harness, ...route.data },
1010
1262
  text: [`${harness.name} (${harness.slug}) is already active.`, ...route.lines].join("\n"),
1011
- ...(route.failed ? { exitCode: ExitCode.failure } : {}),
1263
+ ...(route.failed ? { exitCode: ExitCode.failure } : route.exitCode ? { exitCode: route.exitCode } : {}),
1012
1264
  };
1013
1265
  }
1014
1266
  const readiness = await callStable(ctx, "GET", "/api/v1/harnesses/{harness_id}/readiness", "reading readiness", {
@@ -1039,7 +1291,7 @@ export const activate = {
1039
1291
  return {
1040
1292
  data: { activated: true, harness: activated, checks, warnings, readiness, ...route.data },
1041
1293
  text: [`Activated ${activated.name} (${activated.slug}); status ${activated.status}.`, ...readinessText(checks, warnings), ...route.lines].join("\n"),
1042
- ...(route.failed ? { exitCode: ExitCode.failure } : {}),
1294
+ ...(route.failed ? { exitCode: ExitCode.failure } : route.exitCode ? { exitCode: route.exitCode } : {}),
1043
1295
  };
1044
1296
  },
1045
1297
  };