@cavelon/cli 0.1.6 → 0.1.8

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,21 +9,22 @@ 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";
20
21
  import { pairOrderHint, pairOrderPointer } from "../pair-order.js";
21
22
  import { readPackage, tenantWideSections, writePackage } from "../package-files.js";
22
- import { blockerDetails, blockerLines, changeLines, fieldChanges, locateBlockers, notApplied, notAppliedLines } from "../preview-report.js";
23
+ import { blockerDetails, blockerLines, changeLines, fieldChanges, locateBlockers, notApplied, notAppliedLines, tenantWideReport } from "../preview-report.js";
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
+ "--include-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,
@@ -178,15 +201,16 @@ export const pull = {
178
201
  options: {
179
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." },
180
203
  force: { type: "boolean", description: "Overwrite package files that have uncommitted changes since the last pull or apply." },
181
- "tenant-wide": {
204
+ "include-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
+ formerly: "tenant-wide",
207
+ 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 --include-tenant-wide` sends them back, for the whole tenant.",
184
208
  },
185
209
  },
186
- examples: ["cavelon pull --harness support", "cavelon pull && git status --short -- package tests"],
210
+ examples: ["cavelon pull --harness support", "cavelon pull --include-tenant-wide", "cavelon pull && git status --short -- package tests"],
187
211
  async run(ctx, input) {
188
212
  const session = await ctx.session();
189
- const project = requireSolution(session);
213
+ const project = requireSolution(session, stringOption(input, "harness"));
190
214
  const url = requireInstance(session);
191
215
  const layoutDirs = [project.layout.package, ...Object.values(project.layout.items)];
192
216
  const force = boolOption(input, "force");
@@ -201,8 +225,12 @@ export const pull = {
201
225
  harness = await findHarness(ctx, ref);
202
226
  }
203
227
  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 },
228
+ const tenantWide = boolOption(input, "include-tenant-wide");
229
+ if (tenantWide && !harness)
230
+ ctx.warn("--include-tenant-wide applies to a solution's pull; the tenant's full configuration carries the tenant-wide sections anyway.");
231
+ const askTenantWide = Boolean(harness) && tenantWide && (await takesTenantWide(ctx, "export"));
232
+ const exported = await callStable(ctx, "GET", EXPORT_ROUTE, "exporting packages", {
233
+ query: { scope, harness_id: harness?.id, ...(askTenantWide ? { [INCLUDE_TENANT_WIDE]: true } : {}) },
206
234
  timeoutMs: 120_000,
207
235
  });
208
236
  if (!exported || typeof exported !== "object" || Array.isArray(exported)) {
@@ -212,7 +240,8 @@ export const pull = {
212
240
  const { schema } = await schemaFor(ctx, version, false);
213
241
  if (!schema)
214
242
  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();
243
+ const shared = tenantWideSections(schema);
244
+ const skip = harness && !tenantWide ? shared : new Set();
216
245
  const placed = {};
217
246
  const options = { skip, itemFiles: await readItemFiles(project.root), placed };
218
247
  if (dirty === undefined) {
@@ -239,16 +268,15 @@ export const pull = {
239
268
  files: report,
240
269
  };
241
270
  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.`);
271
+ for (const file of report.kept) {
272
+ const section = path.posix.basename(file).replace(/\.(ya?ml|json)$/i, "");
273
+ ctx.warn(report.tenant_wide.includes(section)
274
+ ? `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 --include-tenant-wide\` sends it for the whole tenant; remove the file unless you mean that.`
275
+ : `Kept ${file}: its section is not in this instance's package schema.`);
276
+ }
244
277
  for (const section of report.refused)
245
278
  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
- }
279
+ const pulledShared = harness && tenantWide ? Object.keys(exported).filter((section) => shared.has(section)) : undefined;
252
280
  const rewritten = report.written.length + report.removed.length;
253
281
  const lines = [
254
282
  `Pulled ${harness ? `solution ${harness.name} (${harness.slug})` : "the tenant's full configuration"} into ${project.layout.package}/` +
@@ -258,7 +286,14 @@ export const pull = {
258
286
  ...report.removed.map((f) => `removed ${f}`),
259
287
  `${report.unchanged.length} file${report.unchanged.length === 1 ? "" : "s"} unchanged.`,
260
288
  ...(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).`]
289
+ ? [`Left out the tenant-wide section${report.tenant_wide.length === 1 ? "" : "s"} ${report.tenant_wide.join(", ")} (--include-tenant-wide writes them).`]
290
+ : []),
291
+ ...(pulledShared
292
+ ? [
293
+ pulledShared.length
294
+ ? `Tenant-wide: ${pulledShared.join(", ")} (shared by every solution of the tenant; only \`apply --include-tenant-wide\` sends them back).`
295
+ : `The export carries no tenant-wide sections${askTenantWide ? "" : " (this instance's export does not take include_tenant_wide)"}, so --include-tenant-wide wrote none.`,
296
+ ]
262
297
  : []),
263
298
  `Inventory: ${inventory.file} (${inventory.counts.map((c) => `${c.count} ${c.label}`).join(", ")})`,
264
299
  !rewritten
@@ -267,7 +302,7 @@ export const pull = {
267
302
  ? "See what changed: the files listed above (this folder is not in a git repository)."
268
303
  : `See what changed: git status --short -- ${layoutDirs.join(" ")} (new files), then git diff -- ${layoutDirs.join(" ")}`,
269
304
  ];
270
- return { data: { ...record, inventory }, text: lines.join("\n") };
305
+ return { data: { ...record, inventory, ...(pulledShared ? { tenant_wide_pulled: pulledShared } : {}) }, text: lines.join("\n") };
271
306
  },
272
307
  };
273
308
  async function inventoryFor(ctx, project, disk, offline) {
@@ -309,7 +344,7 @@ async function validatePackage(ctx, project, offline) {
309
344
  inventory,
310
345
  solution: project.harness,
311
346
  });
312
- return { disk, findings, schemaVersion: schema["x-package-version"] ?? version ?? null, used, skipped };
347
+ return { disk, findings, schema, schemaVersion: schema["x-package-version"] ?? version ?? null, used, skipped };
313
348
  }
314
349
  function schemaUsedLine(used, ttlSeconds) {
315
350
  const from = used.source === "instance" ? "read from the instance now" : `cached at ${used.fetched_at ?? "an unknown time"}`;
@@ -452,6 +487,12 @@ function needsLines(needs, flags) {
452
487
  lines.push(["needs identities", triggers.map((t) => `\n - ${t}`).join("")]);
453
488
  return lines;
454
489
  }
490
+ function changesNothing(p) {
491
+ const s = p.summary;
492
+ if (!s || typeof s !== "object")
493
+ return false;
494
+ return !counts(s.creates) && !counts(s.updates) && !counts(s.deletes) && fieldChanges(p.changes).length === 0;
495
+ }
455
496
  export function previewText(p, flags = "", context = {}) {
456
497
  const lines = [["ready", p.ready ? "yes" : "no"]];
457
498
  const s = p.summary ?? {};
@@ -523,13 +564,56 @@ function previewUnknown(previewId) {
523
564
  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
565
  });
525
566
  }
567
+ const PREVIEW_STALE = "import_preview_stale";
568
+ function previewRetired(retired, again) {
569
+ const id = retired.preview_id;
570
+ const fresh = `Run \`${again}\` for a new preview, show it, and confirm its id.`;
571
+ const details = { preview_id: id, reason: retired.reason, at: retired.at, ...(retired.by ? { superseded_by: retired.by } : {}) };
572
+ switch (retired.reason) {
573
+ case "applied":
574
+ return new CavelonError(ExitCode.conflict, {
575
+ code: "preview_applied",
576
+ message: `Preview ${id} was imported already (${retired.at}); nothing was imported again.`,
577
+ hint: `To import the files as they are now: ${fresh}`,
578
+ details,
579
+ });
580
+ case "superseded":
581
+ return new CavelonError(ExitCode.conflict, {
582
+ code: "preview_superseded",
583
+ 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.`,
584
+ hint: fresh,
585
+ details,
586
+ });
587
+ case "discarded":
588
+ return new CavelonError(ExitCode.conflict, {
589
+ code: "preview_discarded",
590
+ message: `Preview ${id} was discarded (${retired.at}); nothing was imported.`,
591
+ hint: fresh,
592
+ details,
593
+ });
594
+ case "expired":
595
+ return new CavelonError(ExitCode.conflict, {
596
+ code: "preview_expired",
597
+ message: `Preview ${id} expired and was removed (${retired.at}); nothing was imported.`,
598
+ hint: fresh,
599
+ details,
600
+ });
601
+ case "stale":
602
+ return new CavelonError(ExitCode.conflict, {
603
+ code: PREVIEW_STALE,
604
+ message: `Preview ${id} was refused earlier because its target changed since (${retired.at}); nothing was imported.`,
605
+ hint: fresh,
606
+ details,
607
+ });
608
+ }
609
+ }
526
610
  async function discardPreviews(ctx, project, which) {
527
611
  const open = await listPreviews(project.root, ctx.io.now());
528
612
  const chosen = which === "all" ? open : open.filter((p) => p.preview_id === which);
529
613
  if (which !== "all" && chosen.length === 0)
530
614
  throw previewUnknown(which);
531
- for (const p of chosen)
532
- await deletePreview(project.root, p.preview_id);
615
+ const at = ctx.io.now().toISOString();
616
+ await retirePreviews(project.root, chosen.map((p) => ({ preview_id: p.preview_id, reason: "discarded", at })));
533
617
  const ids = chosen.map((p) => p.preview_id);
534
618
  return {
535
619
  data: { discarded: ids, count: ids.length },
@@ -574,8 +658,9 @@ async function instanceHolds(ctx, project, stored) {
574
658
  return undefined;
575
659
  if (scope === "agent_graph" && !harnessId)
576
660
  return undefined;
577
- const exported = await callStable(ctx, "GET", "/api/v1/agent-graph/export", "exporting packages", {
578
- query: { scope, harness_id: harnessId },
661
+ const shared = stored.request[INCLUDE_TENANT_WIDE] === true && scope === "agent_graph" && (await takesTenantWide(ctx, "export"));
662
+ const exported = await callStable(ctx, "GET", EXPORT_ROUTE, "exporting packages", {
663
+ query: { scope, harness_id: harnessId, ...(shared ? { [INCLUDE_TENANT_WIDE]: true } : {}) },
579
664
  timeoutMs: 120_000,
580
665
  });
581
666
  if (!exported || typeof exported !== "object" || Array.isArray(exported))
@@ -586,12 +671,16 @@ async function instanceHolds(ctx, project, stored) {
586
671
  }
587
672
  async function confirmPreview(ctx, project, previewId, allowStale) {
588
673
  const stored = await loadPreview(project.root, previewId);
589
- if (!stored)
590
- throw previewUnknown(previewId);
591
674
  const session = await ctx.session();
675
+ if (!stored) {
676
+ const retired = await retiredPreview(project.root, previewId);
677
+ throw retired ? previewRetired(retired, `${cavelonCommand("apply")}${targetFlags(session)}`) : previewUnknown(previewId);
678
+ }
679
+ const now = ctx.io.now().toISOString();
680
+ const retire = (reason) => retirePreviews(project.root, [{ preview_id: stored.preview_id, reason, at: now }]);
592
681
  const expiry = previewExpiry(stored.created_at, ctx.io.now());
593
682
  if (expiry.expired) {
594
- await deletePreview(project.root, stored.preview_id);
683
+ await retire("expired");
595
684
  throw new CavelonError(ExitCode.conflict, {
596
685
  code: "preview_expired",
597
686
  message: `Preview ${previewId} was made at ${stored.created_at} and expired${expiry.expires_at ? ` at ${expiry.expires_at}` : ""}; nothing was imported.`,
@@ -636,14 +725,25 @@ async function confirmPreview(ctx, project, previewId, allowStale) {
636
725
  body: { ...stored.request, preview_id: stored.preview_id },
637
726
  timeoutMs: 300_000,
638
727
  });
639
- for (const other of await listPreviews(project.root, ctx.io.now()))
640
- await deletePreview(project.root, other.preview_id);
728
+ const others = (await listPreviews(project.root, ctx.io.now())).filter((p) => p.preview_id !== stored.preview_id);
729
+ await retirePreviews(project.root, [
730
+ { preview_id: stored.preview_id, reason: "applied", at: now },
731
+ ...others.map((p) => ({ preview_id: p.preview_id, reason: "superseded", at: now, by: stored.preview_id })),
732
+ ]);
641
733
  await rememberImported(ctx, project, stored, disk, changed);
642
734
  const summary = (result.summary ?? {});
643
735
  const flags = targetFlags(session, stored.env ?? session.envFile?.name);
644
736
  const still = setCommands(stored.preview, flags);
737
+ const sharedSent = stored.request[INCLUDE_TENANT_WIDE] === true;
738
+ const sharedReport = sharedSent ? tenantWideReport(stored.preview.tenant_wide) : undefined;
739
+ const sharedReaches = sharedReport?.reaches_active_solutions ?? [];
740
+ const sharedText = sharedSent
741
+ ? `${sharedReport?.sections.length ? sharedReport.sections.join(", ") : "the package's tenant-wide sections"}, for every solution of the tenant` +
742
+ (sharedReaches.length ? ` (active: ${list(sharedReaches, 10)})` : "")
743
+ : undefined;
645
744
  const text = keyValues([
646
745
  ["applied", `preview ${stored.preview_id}${stored.harness ? ` to ${stored.harness.slug}` : ""}${stored.env ? ` (env ${stored.env})` : ""}`],
746
+ ["tenant-wide", sharedText],
647
747
  ["created", counts(summary?.creates) || undefined],
648
748
  ["updated", counts(summary?.updates) || undefined],
649
749
  ["deleted", counts(summary?.deletes) || undefined],
@@ -652,25 +752,30 @@ async function confirmPreview(ctx, project, previewId, allowStale) {
652
752
  ["set variables", still.variables.length ? indented(still.variables) : undefined],
653
753
  ]);
654
754
  const data = { applied: true, preview_id: stored.preview_id, env: stored.env, harness: stored.harness, result };
755
+ if (sharedSent)
756
+ data.tenant_wide = { applied: true, sections: sharedReport?.sections ?? null, reaches_active_solutions: sharedReaches };
655
757
  if (still.secrets.length || still.variables.length)
656
758
  data.set_commands = still;
657
759
  return { data, text };
658
760
  }
659
761
  catch (error) {
660
762
  if (error instanceof CavelonError && error.code === REQUIREMENTS_CHANGED && (error.blockers?.length || error.blockerDetails?.length)) {
661
- await deletePreview(project.root, stored.preview_id);
763
+ await retire("stale");
662
764
  throw requirementsChanged(error, stored, session, await catalogFor(ctx, false), disk);
663
765
  }
664
766
  if (error instanceof CavelonError && error.blockerDetails?.length)
665
767
  throw withBlockersLocated(error, disk, stored, session);
666
768
  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);
769
+ await retire("stale");
770
+ const said = error.details?.changed;
771
+ const changed = Array.isArray(said) ? said.filter((c) => typeof c === "string") : [];
668
772
  throw new CavelonError(ExitCode.conflict, {
669
773
  code: error.code === "conflict" ? "import_preview_stale" : error.code,
670
774
  status: 409,
671
- message: `The target changed since preview ${stored.preview_id}; nothing was imported.`,
775
+ message: `The target changed since preview ${stored.preview_id}${changed.length ? `: ${changed.join("; ")}` : ""}; nothing was imported.`,
672
776
  hint: `Run \`${previewAgain(stored, session)}\` again, show the new preview, and confirm its id.`,
673
777
  docs: error.docs,
778
+ ...(changed.length ? { details: { preview_id: stored.preview_id, changed } } : {}),
674
779
  });
675
780
  }
676
781
  throw error;
@@ -720,9 +825,9 @@ async function applyTarget(ctx, session, input, pkg) {
720
825
  if (found)
721
826
  return found;
722
827
  if (!source || source === "option" || isUuid(ref) || !SLUG.test(ref))
723
- throw harnessNotFoundError(ref, candidates, source);
828
+ throw harnessNotFoundError(ref, candidates, source, undefined, contextFlags(session));
724
829
  const name = packageHarnessName(pkg, ref) ?? ref;
725
- const create = cavelonCommand("harness", "new", ref, ...(name !== ref ? ["--name", name] : []));
830
+ const create = `${cavelonCommand("harness", "new", ref, ...(name !== ref ? ["--name", name] : []))}${targetFlags(session, null)}`;
726
831
  throw new CavelonError(ExitCode.failure, {
727
832
  code: "solution_not_found",
728
833
  message: `Solution ${ref}, which ${source} names, is not on the instance yet; apply previews into an existing solution and creates none.`,
@@ -736,7 +841,11 @@ function packageHarnessName(pkg, slug) {
736
841
  const name = typeof entry?.name === "string" ? entry.name.trim() : "";
737
842
  return name ? name.slice(0, 255) : undefined;
738
843
  }
739
- function personReason(preview, harness, mode, env) {
844
+ function personReason(preview, harness, mode, env, shared = [], sharedReaches = []) {
845
+ if (shared.length) {
846
+ const reaching = sharedReaches.length ? `, reaching the active solution${sharedReaches.length === 1 ? "" : "s"} ${list(sharedReaches, 5)}` : "";
847
+ return `changes what the whole tenant shares (${list(shared, 5)})${reaching}`;
848
+ }
740
849
  const active = (preview.impact?.active_harnesses ?? []).map((h) => h.harness_slug ?? h.name).filter((n) => Boolean(n));
741
850
  if (harness?.status === "active" && !active.includes(harness.slug))
742
851
  active.unshift(harness.slug);
@@ -762,7 +871,10 @@ export const apply = {
762
871
  "imports nothing: one whose target changed on the instance since, one whose package files changed since (what they\n" +
763
872
  "hold, not their formatting; --allow-stale imports what the preview showed anyway), and one older than a day. So does\n" +
764
873
  "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.",
874
+ "`cavelon status` lists them with when each expires.\n" +
875
+ "A solution's import leaves the package's tenant-wide sections (tenant_settings, model_registry, …) out; --include-tenant-wide\n" +
876
+ "imports them, for every solution of the tenant. An instance that does not publish include_tenant_wide imports them with\n" +
877
+ "every solution's package, and apply says so.",
766
878
  readOnly: false,
767
879
  destructive: true,
768
880
  mcpTool: "apply",
@@ -776,11 +888,22 @@ export const apply = {
776
888
  },
777
889
  discard: { type: "string", value: "<preview-id|all>", description: "Forget this stored preview, or all of them; changes nothing on the instance." },
778
890
  mode: { type: "string", value: "<mode>", description: "overwrite (default) or replace (deletes what the package does not hold)." },
891
+ "include-tenant-wide": {
892
+ type: "boolean",
893
+ formerly: "tenant-wide",
894
+ 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.",
895
+ },
779
896
  },
780
- examples: ["cavelon apply --env test", "cavelon apply --confirm <preview-id>", "cavelon apply --env prod --json", "cavelon apply --discard all"],
897
+ examples: [
898
+ "cavelon apply --env test",
899
+ "cavelon apply --confirm <preview-id>",
900
+ "cavelon apply --env test --include-tenant-wide",
901
+ "cavelon apply --env prod --json",
902
+ "cavelon apply --discard all",
903
+ ],
781
904
  async run(ctx, input) {
782
905
  const session = await ctx.session();
783
- const project = requireSolution(session);
906
+ const project = requireSolution(session, stringOption(input, "harness"));
784
907
  const url = requireInstance(session);
785
908
  const confirm = previewIdOption(input);
786
909
  const discard = stringOption(input, "discard")?.trim();
@@ -803,7 +926,7 @@ export const apply = {
803
926
  const mode = (stringOption(input, "mode") ?? envFile?.mode ?? "overwrite");
804
927
  if (mode !== "overwrite" && mode !== "replace")
805
928
  throw usageError(`--mode must be overwrite or replace, got "${mode}".`);
806
- const { disk, findings } = await validatePackage(ctx, project, false);
929
+ const { disk, findings, schema } = await validatePackage(ctx, project, false);
807
930
  if (disk.empty)
808
931
  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
932
  const errors = findings.filter((f) => f.severity === "error");
@@ -823,6 +946,16 @@ export const apply = {
823
946
  request.harness_id = harness.id;
824
947
  if (envFile && Object.keys(envFile.runtimeBindings).length)
825
948
  request.runtime_bindings = envFile.runtimeBindings;
949
+ const tenantWide = boolOption(input, "include-tenant-wide");
950
+ const solutionImport = Boolean(harness) && scope !== "full_config";
951
+ if (tenantWide && !solutionImport)
952
+ ctx.warn("--include-tenant-wide applies to a solution's import; this one goes to the whole tenant anyway.");
953
+ const shared = solutionImport ? [...tenantWideSections(schema)].filter((section) => section in disk.package) : [];
954
+ const takes = solutionImport && (tenantWide || shared.length > 0) && (await takesTenantWide(ctx, "import"));
955
+ if (tenantWide && takes)
956
+ request[INCLUDE_TENANT_WIDE] = true;
957
+ if (tenantWide && solutionImport && !shared.length)
958
+ ctx.warn("--include-tenant-wide: the package holds no tenant-wide section, so this import changes nothing the whole tenant shares.");
826
959
  const client = await ctx.client();
827
960
  const preview = await callStable(ctx, "POST", "/api/v1/agent-graph/import/preview", "previewing imports", {
828
961
  body: request,
@@ -830,6 +963,33 @@ export const apply = {
830
963
  });
831
964
  const target = harness ? { id: harness.id, slug: harness.slug } : null;
832
965
  const data = { previewed: true, ...preview, env: envFile?.name ?? null, harness: target };
966
+ const reported = solutionImport ? tenantWideReport(preview.tenant_wide) : undefined;
967
+ const sections = reported?.sections ?? shared;
968
+ const applied = reported ? reported.applied : tenantWide || !takes;
969
+ const sharedImported = applied ? sections : [];
970
+ const sharedLeftOut = applied ? [] : sections;
971
+ const reaches = reported?.reaches_active_solutions ?? [];
972
+ if (sharedImported.length) {
973
+ const files = sectionFiles(disk, sharedImported).join(", ") || sharedImported.join(", ");
974
+ 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` +
975
+ (takes ? "." : " (this instance does not publish include_tenant_wide and imports them with every solution's package); remove the file unless that is meant."));
976
+ }
977
+ if (sections.length || tenantWide) {
978
+ data.tenant_wide = {
979
+ sections,
980
+ applied,
981
+ imported: sharedImported,
982
+ left_out: sharedLeftOut,
983
+ reaches_active_solutions: reaches,
984
+ reported_by: reported ? "instance" : "kit",
985
+ };
986
+ }
987
+ const reachText = reaches.length ? `the active solution${reaches.length === 1 ? "" : "s"} ${list(reaches, 10)}` : "";
988
+ const sharedLine = sharedImported.length
989
+ ? `tenant-wide: ${sharedImported.join(", ")} change for every solution of the tenant${reachText ? `, reaching ${reachText}` : ""}`
990
+ : sharedLeftOut.length
991
+ ? `tenant-wide: ${sharedLeftOut.join(", ")} left out (\`cavelon apply --include-tenant-wide\` imports them, for every solution of the tenant${reachText ? `; they would reach ${reachText}` : ""})`
992
+ : undefined;
833
993
  const flags = targetFlags(session);
834
994
  const commands = setCommands(preview, flags);
835
995
  if (commands.secrets.length || commands.variables.length)
@@ -843,17 +1003,38 @@ export const apply = {
843
1003
  ]);
844
1004
  if (pair)
845
1005
  data.hint = pair.hint;
1006
+ const blockedShared = sharedLeftOut.filter((section) => blockerDetails(preview.blocker_details).some((b) => b.path === section || b.path?.startsWith(`${section}.`) || b.path?.startsWith(`${section}[`)));
1007
+ const sharedHint = blockedShared.length
1008
+ ? `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.`
1009
+ : undefined;
1010
+ if (sharedHint)
1011
+ data.tenant_wide_hint = sharedHint;
846
1012
  return {
847
1013
  data,
848
1014
  text: [
849
1015
  previewText(preview, flags, context),
1016
+ ...(sharedLine ? [sharedLine] : []),
850
1017
  "",
851
1018
  ...(pair ? [`hint: ${pair.hint}`] : []),
1019
+ ...(sharedHint ? [`hint: ${sharedHint}`] : []),
852
1020
  "The preview has blockers; fix them and run `cavelon apply` again.",
853
1021
  ].join("\n"),
854
1022
  exitCode: ExitCode.validation,
855
1023
  };
856
1024
  }
1025
+ if (changesNothing(preview)) {
1026
+ data.nothing_to_import = true;
1027
+ delete data.preview_id;
1028
+ return {
1029
+ data,
1030
+ text: [
1031
+ `Preview of ${project.layout.package}/ for ${harness ? `solution ${harness.slug}${harness.status ? ` (${harness.status})` : ""}` : "the tenant"}${envFile ? ` [env ${envFile.name}]` : ""}:`,
1032
+ previewText(preview, flags, context),
1033
+ "",
1034
+ "Nothing to import: the instance already holds what the package files say. No preview was stored.",
1035
+ ].join("\n"),
1036
+ };
1037
+ }
857
1038
  if (!preview.preview_id) {
858
1039
  ctx.warn("This instance's preview returns no preview id, so `apply --confirm` cannot import exactly it; update the instance.");
859
1040
  }
@@ -871,16 +1052,17 @@ export const apply = {
871
1052
  preview,
872
1053
  };
873
1054
  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);
1055
+ const at = ctx.io.now().toISOString();
1056
+ const expired = (await listPreviews(project.root, ctx.io.now())).filter((old) => old.expired);
1057
+ await retirePreviews(project.root, expired.map((old) => ({ preview_id: old.preview_id, reason: "expired", at })));
877
1058
  }
878
- const reason = personReason(preview, harness, mode, envFile?.name);
1059
+ const reason = personReason(preview, harness, mode, envFile?.name, sharedImported, reaches);
879
1060
  data.show_to_person = Boolean(reason);
880
1061
  const confirmLine = preview.preview_id ? `${cavelonCommand("apply", "--confirm", preview.preview_id)}${flags}` : undefined;
881
1062
  const text = [
882
1063
  `Preview of ${project.layout.package}/ for ${harness ? `solution ${harness.slug}${harness.status ? ` (${harness.status})` : ""}` : "the tenant"}${envFile ? ` [env ${envFile.name}]` : ""}:`,
883
1064
  previewText(preview, flags, context),
1065
+ ...(sharedLine ? [sharedLine] : []),
884
1066
  "",
885
1067
  ...(preview.preview_id ? [`preview id: ${preview.preview_id}`] : []),
886
1068
  ...(reason ? [`This ${reason}: show this preview to a person before confirming.`] : []),
@@ -1230,7 +1412,7 @@ export const activate = {
1230
1412
  "make-default": { type: "boolean", description: "Also make it the tenant's default route: previews the change; with --confirm, makes it." },
1231
1413
  confirm: { type: "boolean", mcpToken: true, description: "With --make-default: change the default route (after a person saw the preview)." },
1232
1414
  },
1233
- examples: ["cavelon activate", "cavelon activate --make-default", "cavelon activate --make-default --confirm"],
1415
+ examples: ["cavelon activate", "cavelon activate --make-default", "cavelon activate --make-default --confirm", "cavelon activate --make-default --confirm <token>"],
1234
1416
  async run(ctx, input) {
1235
1417
  const session = await ctx.session();
1236
1418
  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;