@cavelon/cli 0.1.6 → 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.
@@ -269,6 +269,22 @@ export const logout = {
269
269
  return { data: { logged_out: results }, text: text || "No stored logins." };
270
270
  },
271
271
  };
272
+ function tenantSourceText(session) {
273
+ switch (session.tenantSource) {
274
+ case undefined:
275
+ return undefined;
276
+ case "option":
277
+ return "--tenant";
278
+ case "CAVELON_TENANT":
279
+ return "the CAVELON_TENANT variable";
280
+ case "use":
281
+ return session.project
282
+ ? "`cavelon use` (this folder's cavelon.yaml names no tenant for this instance)"
283
+ : "`cavelon use`, for every folder without a cavelon.yaml (--tenant chooses another for one command)";
284
+ default:
285
+ return session.tenantSource;
286
+ }
287
+ }
272
288
  function credentialSource(session) {
273
289
  if (session.tokenSource === "CAVELON_TOKEN")
274
290
  return "CAVELON_TOKEN";
@@ -400,7 +416,7 @@ export const whoami = {
400
416
  ["instance", `${session.url} (${session.urlSource})`],
401
417
  ["acting as", owner],
402
418
  ["tenant", contextTenant ? tenantTitle({ id: contextTenant, name: tenantName, slug: tenantSlug }) : nowhere ? "none chosen (`cavelon use` chooses one)" : "none (Platform mode)"],
403
- ["tenant from", session.tenant ? session.tenantSource : nowhere ? undefined : "the token's default"],
419
+ ["tenant from", session.tenant ? tenantSourceText(session) : nowhere ? undefined : "the token's default"],
404
420
  ["role", data.role ?? undefined],
405
421
  ["credential", `${session.tokenKind === "api_key" ? "tenant API key" : session.tokenKind === "personal_access_token" ? "personal access token" : "token"}${tokenName} from ${credentialSource(session)}`],
406
422
  ["expires", expires],
@@ -626,7 +642,7 @@ export const status = {
626
642
  }
627
643
  const shownTenant = data.tenant;
628
644
  const tenantText = session.tenant
629
- ? `${shownTenant?.id && (shownTenant.name || shownTenant.slug) ? tenantTitle({ id: shownTenant.id, name: shownTenant.name, slug: shownTenant.slug }) : session.tenant} (${session.tenantSource})`
645
+ ? `${shownTenant?.id && (shownTenant.name || shownTenant.slug) ? tenantTitle({ id: shownTenant.id, name: shownTenant.name, slug: shownTenant.slug }) : session.tenant}, from ${tenantSourceText(session)}`
630
646
  : session.tokenKind === "api_key"
631
647
  ? "the API key's tenant"
632
648
  : "not chosen (`cavelon use` lists your tenants to choose from)";
@@ -670,7 +686,9 @@ export const status = {
670
686
  if (waiting.length)
671
687
  data.capacity_waits = waiting;
672
688
  const ops = data.operations;
673
- const others = ops.other_solutions ? ` (${ops.other_solutions} of other solutions not shown; \`cavelon api list_operations_route\` lists all)` : "";
689
+ const others = ops.other_solutions
690
+ ? ` (${ops.other_solutions} operation${ops.other_solutions === 1 ? "" : "s"} of other solutions not shown; \`cavelon api list_operations_route\` lists all)`
691
+ : "";
674
692
  const heading = ops.scope === "solution" ? `Running operations of ${ops.harness} and the tenant's shared work${others}` : "Running operations in the tenant";
675
693
  text += operations.length
676
694
  ? `\n\n${heading}:\n${operations
@@ -9,11 +9,12 @@ import { confirmation, confirmGiven, confirmTokenRequired, shellTokenRequired }
9
9
  import { clip, keyValues } from "../format.js";
10
10
  import { readTextFile, writeFileAtomic } from "../fsutil.js";
11
11
  import { uncommitted } from "../git.js";
12
- import { callStable } from "../invoke.js";
12
+ import { callStable, workflowOperation } from "../invoke.js";
13
+ import { deref, jsonBodySchema } from "../openapi.js";
13
14
  import { harnessNotFoundError, lookupHarness, SLUG } from "../harness-ref.js";
14
15
  import { defaultChangeLine, defaultCommands, named, readDefaultRoute, setDefaultRoute } from "../default-route.js";
15
16
  import { ceilingHint, LIMIT_ABOVE_CEILING, parseLimits, readLimits } from "../limits.js";
16
- import { deletePreview, digest, fileDigest, fileDigests, listPreviews, loadPreview, previewExpiry, readItemFiles, 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";
17
18
  import { catalogEntry, checkPackage, KIT_CODES, packageVersionOf } from "../package-check.js";
18
19
  import { cliFix, similarCodes } from "../code-hints.js";
19
20
  import { KIT_ERROR_CODES } from "../kit-codes.js";
@@ -23,7 +24,7 @@ import { blockerDetails, blockerLines, changeLines, fieldChanges, locateBlockers
23
24
  import { readPrincipal } from "../principal.js";
24
25
  import { CASE_STATUSES, caseStatus, TESTING_PAGE } from "../results.js";
25
26
  import { KNOWLEDGE_OUTCOME_AREA, KNOWLEDGE_OUTCOME_PAGE, KNOWLEDGE_OUTCOMES, knowledgeOutcome } from "../trace-view.js";
26
- import { isUuid, requireInstance } from "../session.js";
27
+ import { contextFlags, isUuid, requireInstance } from "../session.js";
27
28
  import { listedPages } from "./docs.js";
28
29
  import { readInventory, readInventoryKinds, writeInventory } from "./inventory.js";
29
30
  import { checkedBy, MODEL_UNKNOWN_CODE, missingInventory, REFERENCE_UNKNOWN_CODE } from "../package-references.js";
@@ -31,12 +32,15 @@ import { cavelonCommand, shellWord } from "../shell.js";
31
32
  import { secretSetCommand, targetFlags, variableSetCommand } from "./values.js";
32
33
  const HARNESS_OPTION = { type: "string", value: "<harness>", description: "The solution (harness): its name, slug or id; default: env file, then cavelon.yaml." };
33
34
  const ENV_OPTION = { type: "string", value: "<name>", description: "Use env/<name>.yaml: its tenant, solution and runtime bindings." };
34
- export function requireSolution(session) {
35
+ export function requireSolution(session, harness) {
35
36
  if (!session.project) {
37
+ const flags = contextFlags(session);
36
38
  throw new CavelonError(ExitCode.usage, {
37
39
  code: "no_solution",
38
40
  message: "This folder is not a Cavelon solution (no cavelon.yaml here or above).",
39
- 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.`,
40
44
  });
41
45
  }
42
46
  return session.project;
@@ -54,7 +58,7 @@ function harnessRef(session, input) {
54
58
  async function findHarness(ctx, ref, source) {
55
59
  const { harness, candidates } = await lookupHarness(ctx, ref);
56
60
  if (!harness)
57
- throw harnessNotFoundError(ref, candidates, source);
61
+ throw harnessNotFoundError(ref, candidates, source, undefined, contextFlags(await ctx.session()));
58
62
  return harness;
59
63
  }
60
64
  async function cachedFirst(ctx, what, cached, offline, fetch) {
@@ -158,6 +162,25 @@ async function editedSincePull(project, pkg, schema, options) {
158
162
  }
159
163
  return edited.sort((a, b) => a.localeCompare(b, "en"));
160
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
+ }
161
184
  export const pull = {
162
185
  name: "pull",
163
186
  summary: "Write the instance's package into package/ (split along the schema's sections) and the inventory into .cavelon/.",
@@ -165,8 +188,8 @@ export const pull = {
165
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" +
166
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" +
167
190
  "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" +
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" +
170
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" +
171
194
  "or apply left it (digests in .cavelon/) counts as unchanged, committed or not.",
172
195
  readOnly: false,
@@ -180,13 +203,13 @@ export const pull = {
180
203
  force: { type: "boolean", description: "Overwrite package files that have uncommitted changes since the last pull or apply." },
181
204
  "tenant-wide": {
182
205
  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.",
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.",
184
207
  },
185
208
  },
186
209
  examples: ["cavelon pull --harness support", "cavelon pull && git status --short -- package tests"],
187
210
  async run(ctx, input) {
188
211
  const session = await ctx.session();
189
- const project = requireSolution(session);
212
+ const project = requireSolution(session, stringOption(input, "harness"));
190
213
  const url = requireInstance(session);
191
214
  const layoutDirs = [project.layout.package, ...Object.values(project.layout.items)];
192
215
  const force = boolOption(input, "force");
@@ -201,8 +224,12 @@ export const pull = {
201
224
  harness = await findHarness(ctx, ref);
202
225
  }
203
226
  const scope = harness ? "agent_graph" : "full_config";
204
- const exported = await callStable(ctx, "GET", "/api/v1/agent-graph/export", "exporting packages", {
205
- 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 } : {}) },
206
233
  timeoutMs: 120_000,
207
234
  });
208
235
  if (!exported || typeof exported !== "object" || Array.isArray(exported)) {
@@ -212,7 +239,8 @@ export const pull = {
212
239
  const { schema } = await schemaFor(ctx, version, false);
213
240
  if (!schema)
214
241
  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();
242
+ const shared = tenantWideSections(schema);
243
+ const skip = harness && !tenantWide ? shared : new Set();
216
244
  const placed = {};
217
245
  const options = { skip, itemFiles: await readItemFiles(project.root), placed };
218
246
  if (dirty === undefined) {
@@ -239,16 +267,15 @@ export const pull = {
239
267
  files: report,
240
268
  };
241
269
  await writeState(project.root, "pull.json", JSON.stringify(record, null, 2));
242
- for (const file of report.kept)
243
- 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
+ }
244
276
  for (const section of report.refused)
245
277
  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
- }
278
+ const pulledShared = harness && tenantWide ? Object.keys(exported).filter((section) => shared.has(section)) : undefined;
252
279
  const rewritten = report.written.length + report.removed.length;
253
280
  const lines = [
254
281
  `Pulled ${harness ? `solution ${harness.name} (${harness.slug})` : "the tenant's full configuration"} into ${project.layout.package}/` +
@@ -260,6 +287,13 @@ export const pull = {
260
287
  ...(report.tenant_wide.length
261
288
  ? [`Left out the tenant-wide section${report.tenant_wide.length === 1 ? "" : "s"} ${report.tenant_wide.join(", ")} (--tenant-wide writes them).`]
262
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
+ : []),
263
297
  `Inventory: ${inventory.file} (${inventory.counts.map((c) => `${c.count} ${c.label}`).join(", ")})`,
264
298
  !rewritten
265
299
  ? "Nothing changed on the instance since the last pull."
@@ -267,7 +301,7 @@ export const pull = {
267
301
  ? "See what changed: the files listed above (this folder is not in a git repository)."
268
302
  : `See what changed: git status --short -- ${layoutDirs.join(" ")} (new files), then git diff -- ${layoutDirs.join(" ")}`,
269
303
  ];
270
- return { data: { ...record, inventory }, text: lines.join("\n") };
304
+ return { data: { ...record, inventory, ...(pulledShared ? { tenant_wide_pulled: pulledShared } : {}) }, text: lines.join("\n") };
271
305
  },
272
306
  };
273
307
  async function inventoryFor(ctx, project, disk, offline) {
@@ -309,7 +343,7 @@ async function validatePackage(ctx, project, offline) {
309
343
  inventory,
310
344
  solution: project.harness,
311
345
  });
312
- return { disk, findings, schemaVersion: schema["x-package-version"] ?? version ?? null, used, skipped };
346
+ return { disk, findings, schema, schemaVersion: schema["x-package-version"] ?? version ?? null, used, skipped };
313
347
  }
314
348
  function schemaUsedLine(used, ttlSeconds) {
315
349
  const from = used.source === "instance" ? "read from the instance now" : `cached at ${used.fetched_at ?? "an unknown time"}`;
@@ -452,6 +486,12 @@ function needsLines(needs, flags) {
452
486
  lines.push(["needs identities", triggers.map((t) => `\n - ${t}`).join("")]);
453
487
  return lines;
454
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
+ }
455
495
  export function previewText(p, flags = "", context = {}) {
456
496
  const lines = [["ready", p.ready ? "yes" : "no"]];
457
497
  const s = p.summary ?? {};
@@ -523,13 +563,56 @@ function previewUnknown(previewId) {
523
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.",
524
564
  });
525
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
+ }
526
609
  async function discardPreviews(ctx, project, which) {
527
610
  const open = await listPreviews(project.root, ctx.io.now());
528
611
  const chosen = which === "all" ? open : open.filter((p) => p.preview_id === which);
529
612
  if (which !== "all" && chosen.length === 0)
530
613
  throw previewUnknown(which);
531
- for (const p of chosen)
532
- await deletePreview(project.root, p.preview_id);
614
+ const at = ctx.io.now().toISOString();
615
+ await retirePreviews(project.root, chosen.map((p) => ({ preview_id: p.preview_id, reason: "discarded", at })));
533
616
  const ids = chosen.map((p) => p.preview_id);
534
617
  return {
535
618
  data: { discarded: ids, count: ids.length },
@@ -574,8 +657,9 @@ async function instanceHolds(ctx, project, stored) {
574
657
  return undefined;
575
658
  if (scope === "agent_graph" && !harnessId)
576
659
  return undefined;
577
- const exported = await callStable(ctx, "GET", "/api/v1/agent-graph/export", "exporting packages", {
578
- query: { scope, harness_id: harnessId },
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 } : {}) },
579
663
  timeoutMs: 120_000,
580
664
  });
581
665
  if (!exported || typeof exported !== "object" || Array.isArray(exported))
@@ -586,12 +670,16 @@ async function instanceHolds(ctx, project, stored) {
586
670
  }
587
671
  async function confirmPreview(ctx, project, previewId, allowStale) {
588
672
  const stored = await loadPreview(project.root, previewId);
589
- if (!stored)
590
- throw previewUnknown(previewId);
591
673
  const session = await ctx.session();
674
+ if (!stored) {
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 }]);
592
680
  const expiry = previewExpiry(stored.created_at, ctx.io.now());
593
681
  if (expiry.expired) {
594
- await deletePreview(project.root, stored.preview_id);
682
+ await retire("expired");
595
683
  throw new CavelonError(ExitCode.conflict, {
596
684
  code: "preview_expired",
597
685
  message: `Preview ${previewId} was made at ${stored.created_at} and expired${expiry.expires_at ? ` at ${expiry.expires_at}` : ""}; nothing was imported.`,
@@ -636,8 +724,11 @@ async function confirmPreview(ctx, project, previewId, allowStale) {
636
724
  body: { ...stored.request, preview_id: stored.preview_id },
637
725
  timeoutMs: 300_000,
638
726
  });
639
- for (const other of await listPreviews(project.root, ctx.io.now()))
640
- await deletePreview(project.root, other.preview_id);
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
+ ]);
641
732
  await rememberImported(ctx, project, stored, disk, changed);
642
733
  const summary = (result.summary ?? {});
643
734
  const flags = targetFlags(session, stored.env ?? session.envFile?.name);
@@ -658,19 +749,22 @@ async function confirmPreview(ctx, project, previewId, allowStale) {
658
749
  }
659
750
  catch (error) {
660
751
  if (error instanceof CavelonError && error.code === REQUIREMENTS_CHANGED && (error.blockers?.length || error.blockerDetails?.length)) {
661
- await deletePreview(project.root, stored.preview_id);
752
+ await retire("stale");
662
753
  throw requirementsChanged(error, stored, session, await catalogFor(ctx, false), disk);
663
754
  }
664
755
  if (error instanceof CavelonError && error.blockerDetails?.length)
665
756
  throw withBlockersLocated(error, disk, stored, session);
666
757
  if (error instanceof CavelonError && (error.code === "import_preview_stale" || (error.status === 409 && /preview/i.test(error.message)))) {
667
- 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") : [];
668
761
  throw new CavelonError(ExitCode.conflict, {
669
762
  code: error.code === "conflict" ? "import_preview_stale" : error.code,
670
763
  status: 409,
671
- 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.`,
672
765
  hint: `Run \`${previewAgain(stored, session)}\` again, show the new preview, and confirm its id.`,
673
766
  docs: error.docs,
767
+ ...(changed.length ? { details: { preview_id: stored.preview_id, changed } } : {}),
674
768
  });
675
769
  }
676
770
  throw error;
@@ -720,9 +814,9 @@ async function applyTarget(ctx, session, input, pkg) {
720
814
  if (found)
721
815
  return found;
722
816
  if (!source || source === "option" || isUuid(ref) || !SLUG.test(ref))
723
- throw harnessNotFoundError(ref, candidates, source);
817
+ throw harnessNotFoundError(ref, candidates, source, undefined, contextFlags(session));
724
818
  const name = packageHarnessName(pkg, ref) ?? ref;
725
- const create = cavelonCommand("harness", "new", ref, ...(name !== ref ? ["--name", name] : []));
819
+ const create = `${cavelonCommand("harness", "new", ref, ...(name !== ref ? ["--name", name] : []))}${targetFlags(session, null)}`;
726
820
  throw new CavelonError(ExitCode.failure, {
727
821
  code: "solution_not_found",
728
822
  message: `Solution ${ref}, which ${source} names, is not on the instance yet; apply previews into an existing solution and creates none.`,
@@ -736,7 +830,7 @@ function packageHarnessName(pkg, slug) {
736
830
  const name = typeof entry?.name === "string" ? entry.name.trim() : "";
737
831
  return name ? name.slice(0, 255) : undefined;
738
832
  }
739
- function personReason(preview, harness, mode, env) {
833
+ function personReason(preview, harness, mode, env, shared = []) {
740
834
  const active = (preview.impact?.active_harnesses ?? []).map((h) => h.harness_slug ?? h.name).filter((n) => Boolean(n));
741
835
  if (harness?.status === "active" && !active.includes(harness.slug))
742
836
  active.unshift(harness.slug);
@@ -744,6 +838,8 @@ function personReason(preview, harness, mode, env) {
744
838
  return `reaches the active solution${active.length === 1 ? "" : "s"} ${list(active, 5)}`;
745
839
  if (preview.impact?.active_harnesses?.length)
746
840
  return "reaches an active solution";
841
+ if (shared.length)
842
+ return `changes what the whole tenant shares (${list(shared, 5)})`;
747
843
  if (counts(preview.summary?.deletes) || mode === "replace")
748
844
  return "deletes";
749
845
  if (env === "prod")
@@ -762,7 +858,10 @@ export const apply = {
762
858
  "imports nothing: one whose target changed on the instance since, one whose package files changed since (what they\n" +
763
859
  "hold, not their formatting; --allow-stale imports what the preview showed anyway), and one older than a day. So does\n" +
764
860
  "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.",
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.",
766
865
  readOnly: false,
767
866
  destructive: true,
768
867
  mcpTool: "apply",
@@ -776,11 +875,21 @@ export const apply = {
776
875
  },
777
876
  discard: { type: "string", value: "<preview-id|all>", description: "Forget this stored preview, or all of them; changes nothing on the instance." },
778
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
+ },
779
882
  },
780
- examples: ["cavelon apply --env test", "cavelon apply --confirm <preview-id>", "cavelon apply --env prod --json", "cavelon apply --discard all"],
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
+ ],
781
890
  async run(ctx, input) {
782
891
  const session = await ctx.session();
783
- const project = requireSolution(session);
892
+ const project = requireSolution(session, stringOption(input, "harness"));
784
893
  const url = requireInstance(session);
785
894
  const confirm = previewIdOption(input);
786
895
  const discard = stringOption(input, "discard")?.trim();
@@ -803,7 +912,7 @@ export const apply = {
803
912
  const mode = (stringOption(input, "mode") ?? envFile?.mode ?? "overwrite");
804
913
  if (mode !== "overwrite" && mode !== "replace")
805
914
  throw usageError(`--mode must be overwrite or replace, got "${mode}".`);
806
- const { disk, findings } = await validatePackage(ctx, project, false);
915
+ const { disk, findings, schema } = await validatePackage(ctx, project, false);
807
916
  if (disk.empty)
808
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.");
809
918
  const errors = findings.filter((f) => f.severity === "error");
@@ -823,6 +932,23 @@ export const apply = {
823
932
  request.harness_id = harness.id;
824
933
  if (envFile && Object.keys(envFile.runtimeBindings).length)
825
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
+ }
826
952
  const client = await ctx.client();
827
953
  const preview = await callStable(ctx, "POST", "/api/v1/agent-graph/import/preview", "previewing imports", {
828
954
  body: request,
@@ -830,6 +956,13 @@ export const apply = {
830
956
  });
831
957
  const target = harness ? { id: harness.id, slug: harness.slug } : null;
832
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;
833
966
  const flags = targetFlags(session);
834
967
  const commands = setCommands(preview, flags);
835
968
  if (commands.secrets.length || commands.variables.length)
@@ -843,17 +976,38 @@ export const apply = {
843
976
  ]);
844
977
  if (pair)
845
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;
846
985
  return {
847
986
  data,
848
987
  text: [
849
988
  previewText(preview, flags, context),
989
+ ...(sharedLine ? [sharedLine] : []),
850
990
  "",
851
991
  ...(pair ? [`hint: ${pair.hint}`] : []),
992
+ ...(sharedHint ? [`hint: ${sharedHint}`] : []),
852
993
  "The preview has blockers; fix them and run `cavelon apply` again.",
853
994
  ].join("\n"),
854
995
  exitCode: ExitCode.validation,
855
996
  };
856
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
+ }
857
1011
  if (!preview.preview_id) {
858
1012
  ctx.warn("This instance's preview returns no preview id, so `apply --confirm` cannot import exactly it; update the instance.");
859
1013
  }
@@ -871,16 +1025,17 @@ export const apply = {
871
1025
  preview,
872
1026
  };
873
1027
  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);
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 })));
877
1031
  }
878
- const reason = personReason(preview, harness, mode, envFile?.name);
1032
+ const reason = personReason(preview, harness, mode, envFile?.name, sharedImported);
879
1033
  data.show_to_person = Boolean(reason);
880
1034
  const confirmLine = preview.preview_id ? `${cavelonCommand("apply", "--confirm", preview.preview_id)}${flags}` : undefined;
881
1035
  const text = [
882
1036
  `Preview of ${project.layout.package}/ for ${harness ? `solution ${harness.slug}${harness.status ? ` (${harness.status})` : ""}` : "the tenant"}${envFile ? ` [env ${envFile.name}]` : ""}:`,
883
1037
  previewText(preview, flags, context),
1038
+ ...(sharedLine ? [sharedLine] : []),
884
1039
  "",
885
1040
  ...(preview.preview_id ? [`preview id: ${preview.preview_id}`] : []),
886
1041
  ...(reason ? [`This ${reason}: show this preview to a person before confirming.`] : []),
@@ -1230,7 +1385,7 @@ export const activate = {
1230
1385
  "make-default": { type: "boolean", description: "Also make it the tenant's default route: previews the change; with --confirm, makes it." },
1231
1386
  confirm: { type: "boolean", mcpToken: true, description: "With --make-default: change the default route (after a person saw the preview)." },
1232
1387
  },
1233
- 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>"],
1234
1389
  async run(ctx, input) {
1235
1390
  const session = await ctx.session();
1236
1391
  const { ref, source } = harnessRef(session, input);
@@ -6,7 +6,7 @@ import { callStable } from "../invoke.js";
6
6
  import { formatQuota, limitError, limitsOrWarn, readQuotas } from "../limits.js";
7
7
  import { containing } from "../choose.js";
8
8
  import { readPrincipal, readTenantless } from "../principal.js";
9
- import { requireInstance } from "../session.js";
9
+ import { contextFlags, requireInstance } from "../session.js";
10
10
  import { listsTenants, searchTenants } from "../tenant-choice.js";
11
11
  import { harnessNotFoundError, lookupHarness, resolveHarnessId } from "../harness-ref.js";
12
12
  import { defaultChangeLine, defaultCommands, named, readDefaultRoute, setDefaultRoute } from "../default-route.js";
@@ -244,7 +244,7 @@ export const harnessDefault = {
244
244
  options: {
245
245
  confirm: { type: "boolean", mcpToken: true, description: "Change the default route (after a person saw the preview)." },
246
246
  },
247
- examples: ["cavelon harness default support", "cavelon harness default support --confirm"],
247
+ examples: ["cavelon harness default support", "cavelon harness default support --confirm", "cavelon harness default support --confirm <token>"],
248
248
  async run(ctx, input) {
249
249
  const session = await ctx.session();
250
250
  const ref = positional(input, "solution") ?? session.envFile?.harness ?? session.project?.harness;
@@ -253,8 +253,10 @@ export const harnessDefault = {
253
253
  if (ctx.mode === "mcp" && input.options.confirm === true)
254
254
  throw confirmTokenRequired("harness_default");
255
255
  const { harness, candidates } = await lookupHarness(ctx, ref);
256
- if (!harness)
257
- throw harnessNotFoundError(ref, candidates, undefined, (slug) => cavelonCommand("harness", "default", slug));
256
+ if (!harness) {
257
+ const flags = contextFlags(session);
258
+ throw harnessNotFoundError(ref, candidates, undefined, (slug) => cavelonCommand("harness", "default", slug) + flags, flags);
259
+ }
258
260
  const route = await readDefaultRoute(ctx);
259
261
  const target = { id: harness.id, slug: harness.slug, name: harness.name, status: harness.status };
260
262
  const current = route.current ? { id: route.current.id, slug: route.current.slug, name: route.current.name } : null;
@@ -13,7 +13,7 @@ export const ENV_OPTION = { type: "string", value: "<name>", description: "Act i
13
13
  const CONFIRM_OPTION = {
14
14
  type: "boolean",
15
15
  mcpToken: true,
16
- description: "Delete it; without this nothing is deleted. Run by a coding agent: the token its preview printed.",
16
+ description: "Delete it; without this nothing is deleted.",
17
17
  };
18
18
  const TOKEN_PREFIXES = ["cbp_", "cvpat_"];
19
19
  const LIST_VALUE_CHARS = 200;
@@ -169,7 +169,7 @@ export const variablesDelete = {
169
169
  mcpTool: false,
170
170
  positionals: [{ name: "name", description: "The variable's name.", required: true }],
171
171
  options: { confirm: CONFIRM_OPTION, env: ENV_OPTION },
172
- examples: ["cavelon variables delete old_url", "cavelon variables delete old_url --confirm"],
172
+ examples: ["cavelon variables delete old_url", "cavelon variables delete old_url --confirm", "cavelon variables delete old_url --confirm <token>"],
173
173
  async run(ctx, input) {
174
174
  const name = positional(input, "name");
175
175
  const flags = targetFlags(await ctx.session());
@@ -361,7 +361,7 @@ export const secretsDelete = {
361
361
  mcpTool: false,
362
362
  positionals: [{ name: "name", description: "The secret's name.", required: true }],
363
363
  options: { confirm: CONFIRM_OPTION, env: ENV_OPTION },
364
- examples: ["cavelon secrets delete old_token", "cavelon secrets delete old_token --confirm"],
364
+ examples: ["cavelon secrets delete old_token", "cavelon secrets delete old_token --confirm", "cavelon secrets delete old_token --confirm <token>"],
365
365
  async run(ctx, input) {
366
366
  const name = positional(input, "name");
367
367
  await requirePerson(ctx, "delete", name);