@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.
@@ -1,4 +1,5 @@
1
- import { promises as fs } from "node:fs";
1
+ import { createHash } from "node:crypto";
2
+ import { createReadStream, promises as fs } from "node:fs";
2
3
  import path from "node:path";
3
4
  import { boolOption, CURSOR_OPTION, intOption, LIMIT_OPTION, listOption, pageOf, positional, stringOption, } from "../command.js";
4
5
  import { capacityCodeIn, capacityHint, noteLines, runCapacityNote } from "../capacity.js";
@@ -62,6 +63,32 @@ async function existingDocuments(ctx, kbId) {
62
63
  return undefined;
63
64
  }
64
65
  }
66
+ async function sha256Of(file) {
67
+ const hash = createHash("sha256");
68
+ for await (const chunk of createReadStream(file))
69
+ hash.update(chunk);
70
+ return hash.digest("hex");
71
+ }
72
+ async function identicalFiles(files, cwd, existing) {
73
+ const hashed = existing.filter((d) => typeof d.file_sha256 === "string" && d.file_sha256 !== "");
74
+ if (existing.length && !hashed.length)
75
+ return undefined;
76
+ const byHash = new Map();
77
+ for (const d of [...hashed].sort((a, b) => (b.created_at ?? "").localeCompare(a.created_at ?? ""))) {
78
+ const key = d.file_sha256.toLowerCase();
79
+ if (!byHash.has(key))
80
+ byHash.set(key, d);
81
+ }
82
+ const out = [];
83
+ if (!byHash.size)
84
+ return out;
85
+ for (const file of files) {
86
+ const document = byHash.get(await sha256Of(file));
87
+ if (document)
88
+ out.push({ file: path.relative(cwd, file) || file, document_id: document.id, filename: document.filename });
89
+ }
90
+ return out;
91
+ }
65
92
  function nameMatches(files, cwd, existing, mode, support) {
66
93
  const matches = [];
67
94
  const mapped = new Set();
@@ -378,7 +405,9 @@ export const kbUpload = {
378
405
  "A file named like an active document of the knowledge base is listed, with what happens to that document. An\n" +
379
406
  "instance that replaces same-named documents on upload does so (--keep-both keeps both); elsewhere the old one stays\n" +
380
407
  "active. --replace replaces it: through the instance's own replacement where its upload offers one, else the kit\n" +
381
- "deactivates the old document after the upload (after the wait with --wait), and then only with --confirm.",
408
+ "deactivates the old document after the upload (after the wait with --wait), and then only with --confirm.\n" +
409
+ "--dry-run also names each file identical to an active document, which the upload would not create again, where the\n" +
410
+ "instance publishes its documents' file hashes.",
382
411
  readOnly: false,
383
412
  mcpTool: "kb_upload",
384
413
  positionals: [{ name: "dir", description: "Folder (or single file) to upload.", required: true }],
@@ -389,7 +418,7 @@ export const kbUpload = {
389
418
  replace: { type: "boolean", description: "Replace active documents with the same file name." },
390
419
  "keep-both": { type: "boolean", description: "Keep active documents with the same file name next to the new ones." },
391
420
  confirm: { type: "boolean", mcpToken: true, description: "With --replace, deactivate the old documents the instance does not replace itself; without it nothing is sent." },
392
- "dry-run": { type: "boolean", description: "List what would be uploaded and replaced, upload nothing." },
421
+ "dry-run": { type: "boolean", description: "List what would be uploaded, replaced and found identical; upload nothing." },
393
422
  wait: WAIT_OPTION,
394
423
  timeout: TIMEOUT_OPTION,
395
424
  },
@@ -431,17 +460,30 @@ export const kbUpload = {
431
460
  const matches = existing ? nameMatches(files, ctx.io.cwd, existing, mode, support) : [];
432
461
  const rel = files.map((f) => path.relative(ctx.io.cwd, f) || f);
433
462
  const planned = matches.map(({ outcome: _outcome, ...m }) => m);
434
- const hint = staysActiveHint(matches, mode);
435
463
  const deactivations = matches.filter((m) => m.plan === "deactivate");
436
464
  if (boolOption(input, "dry-run")) {
465
+ const identical = existing ? await identicalFiles(files, ctx.io.cwd, existing) : undefined;
466
+ const isIdentical = (m) => Boolean(identical?.some((i) => i.file === m.file && i.document_id === m.document_id));
467
+ const differing = matches.filter((m) => !isIdentical(m));
468
+ const dryHint = staysActiveHint(differing, mode);
469
+ const dryDeactivations = differing.filter((m) => m.plan === "deactivate");
437
470
  return {
438
- data: { kb: kbRef, files: rel, count: rel.length, dry_run: true, existing: planned },
471
+ data: {
472
+ kb: kbRef,
473
+ files: rel,
474
+ count: rel.length,
475
+ dry_run: true,
476
+ existing: planned.map((m, index) => (identical ? { ...m, identical: isIdentical(matches[index]) } : m)),
477
+ content_compared: identical !== undefined,
478
+ identical: identical ?? [],
479
+ },
439
480
  text: [
440
481
  `Would upload ${fileCount(rel.length)}:`,
441
482
  ...rel,
442
- ...matches.map(plannedLine),
443
- ...(hint ? [hint] : []),
444
- ...(deactivations.length ? [`The kit deactivates ${deactivations.length === 1 ? "that document" : "those documents"} only with --replace --confirm.`] : []),
483
+ ...(identical ?? []).map((i) => `${i.file}: identical to the active document ${shortId(i.document_id)}${i.filename === path.basename(i.file) ? "" : ` (${i.filename})`}; nothing new would be created (deduplicated)`),
484
+ ...differing.map(plannedLine),
485
+ ...(dryHint ? [dryHint] : []),
486
+ ...(dryDeactivations.length ? [`The kit deactivates ${dryDeactivations.length === 1 ? "that document" : "those documents"} only with --replace --confirm.`] : []),
445
487
  ].join("\n"),
446
488
  };
447
489
  }
@@ -504,11 +546,16 @@ export const kbUpload = {
504
546
  }
505
547
  }
506
548
  settleMatches(matches, documents, uploadedFiles);
507
- const operationIds = documents.map((d) => d.operation_id).filter((id) => Boolean(id));
508
549
  const before = new Set((existing ?? []).map((d) => d.id));
509
550
  const outcomes = new Map(documents.map((d) => [d, uploadOutcomeOf(d, before)]));
510
551
  const deduplicated = documents.filter((d) => outcomes.get(d) === "deduplicated");
511
- const created = documents.length - deduplicated.length;
552
+ const same = new Set(deduplicated.map((d) => d.id));
553
+ for (const m of matches)
554
+ if (same.has(m.document_id))
555
+ m.outcome = "identical";
556
+ const fresh = documents.filter((d) => !deduplicated.includes(d));
557
+ const operationIds = fresh.map((d) => d.operation_id).filter((id) => Boolean(id));
558
+ const created = fresh.length;
512
559
  const summary = () => ({
513
560
  kb: { id: kb.id, name: kb.name ?? null },
514
561
  documents: documents.map((d) => ({
@@ -526,12 +573,12 @@ export const kbUpload = {
526
573
  const note = staysActiveHint(matches, mode);
527
574
  return [
528
575
  ...deduplicated.map((d) => `${d.filename}: identical to the active document ${shortId(d.id)}; nothing new was created (deduplicated)`),
529
- ...matches.filter((m) => !deduplicated.some((d) => d.filename === m.filename)).map(outcomeLine),
576
+ ...matches.filter((m) => m.outcome !== "identical").map(outcomeLine),
530
577
  ...(note ? [note] : []),
531
578
  ];
532
579
  };
533
580
  const uploadedText = (where) => created ? `Uploaded ${fileCount(created)}${where}.` : `Nothing new uploaded${where}: the content of ${deduplicated.length === 1 ? "the file is" : "every file is"} already active.`;
534
- if (operationIds.length < documents.length)
581
+ if (operationIds.length < fresh.length)
535
582
  ctx.warn("The instance returned no operation id for some documents; it may be older than the operations API.");
536
583
  if (failure) {
537
584
  const refused = await deactivate(ctx, kb.id, matches);
package/dist/format.js CHANGED
@@ -1,13 +1,13 @@
1
1
  import { shellWord } from "./shell.js";
2
- export function table(rows, columns, maxWidth = 60) {
2
+ export function table(rows, columns, maxWidth = 60, whole = []) {
3
3
  if (rows.length === 0)
4
4
  return "";
5
- const cell = (value) => {
5
+ const cell = (value, column) => {
6
6
  const text = value === null || value === undefined ? "" : typeof value === "object" ? JSON.stringify(value) : String(value);
7
7
  const oneLine = text.replace(/\s+/g, " ");
8
- return oneLine.length > maxWidth ? `${oneLine.slice(0, maxWidth - 1)}…` : oneLine;
8
+ return oneLine.length > maxWidth && !whole.includes(column) ? `${oneLine.slice(0, maxWidth - 1)}…` : oneLine;
9
9
  };
10
- const cells = rows.map((row) => columns.map((c) => cell(row[c])));
10
+ const cells = rows.map((row) => columns.map((c) => cell(row[c], c)));
11
11
  const widths = columns.map((c, i) => Math.max(c.length, ...cells.map((r) => r[i].length)));
12
12
  const line = (values) => values
13
13
  .map((v, i) => (i === values.length - 1 ? v : v.padEnd(widths[i])))
@@ -1,7 +1,7 @@
1
1
  import { closest, displayName, exactMatch } from "./choose.js";
2
2
  import { CavelonError, ExitCode } from "./errors.js";
3
3
  import { callStable } from "./invoke.js";
4
- import { isUuid } from "./session.js";
4
+ import { contextFlags, isUuid } from "./session.js";
5
5
  import { shellWord } from "./shell.js";
6
6
  function notFound(error) {
7
7
  return error instanceof CavelonError && error.status === 404;
@@ -33,14 +33,14 @@ export async function lookupHarness(ctx, ref) {
33
33
  return { harness: hit, candidates: [] };
34
34
  return { candidates: closest(all, ref) };
35
35
  }
36
- export function harnessNotFoundError(ref, candidates, source, command) {
36
+ export function harnessNotFoundError(ref, candidates, source, command, flags = "") {
37
37
  const near = candidates.map(displayName).join(", ");
38
38
  const lines = candidates.map((h) => ` ${command ? command(h.slug) : `--harness ${shellWord(h.slug)}`}`).join("\n");
39
39
  return new CavelonError(ExitCode.failure, {
40
40
  code: "solution_not_found",
41
41
  message: `No solution "${ref}" in this tenant${source ? ` (from ${source})` : ""}.${near ? ` Closest: ${near}.` : ""}`,
42
42
  hint: (candidates.length ? `If you meant one of them:\n${lines}\n` : "") +
43
- "`cavelon harness list` shows this tenant's solutions with name, slug and id; `cavelon harness new <slug> --name <name>` creates one as a draft (`cavelon init --harness <name>` does too).",
43
+ `\`cavelon harness list${flags}\` shows this tenant's solutions with name, slug and id; \`cavelon harness new <slug> --name <name>${flags}\` creates one as a draft.`,
44
44
  details: candidates.length ? { candidates: candidates.map((h) => ({ id: h.id, slug: h.slug, name: h.name })) } : undefined,
45
45
  });
46
46
  }
@@ -49,7 +49,7 @@ export async function resolveHarnessId(ctx, ref) {
49
49
  return ref;
50
50
  const { harness, candidates } = await lookupHarness(ctx, ref);
51
51
  if (!harness)
52
- throw harnessNotFoundError(ref, candidates);
52
+ throw harnessNotFoundError(ref, candidates, undefined, undefined, contextFlags(await ctx.session()));
53
53
  return harness.id;
54
54
  }
55
55
  export function slugFromName(name) {
package/dist/http.js CHANGED
@@ -215,6 +215,7 @@ export function errorFromResponse(status, body, what, headers, sent = {}) {
215
215
  let details;
216
216
  let blockers;
217
217
  let structured;
218
+ let changed;
218
219
  const pick = (source) => {
219
220
  if (typeof source.code === "string")
220
221
  code = source.code;
@@ -232,6 +233,9 @@ export function errorFromResponse(status, body, what, headers, sent = {}) {
232
233
  const detailed = blockerDetails(source.blocker_details);
233
234
  if (detailed.length)
234
235
  structured = detailed;
236
+ const what = Array.isArray(source.changed) ? source.changed.filter((c) => typeof c === "string" && c.trim() !== "") : [];
237
+ if (what.length)
238
+ changed = what;
235
239
  };
236
240
  if (body && typeof body === "object" && !Array.isArray(body)) {
237
241
  const map = body;
@@ -276,6 +280,8 @@ export function errorFromResponse(status, body, what, headers, sent = {}) {
276
280
  hint = ceiling.hint;
277
281
  details = details && typeof details === "object" ? { ...details, ...ceiling.details } : ceiling.details;
278
282
  }
283
+ if (changed)
284
+ details = details && typeof details === "object" && !Array.isArray(details) ? { ...details, changed } : { changed };
279
285
  if (status === 400 && !hint && message && /select a tenant|tenant context|X-Tenant-Id/i.test(message)) {
280
286
  hint = "Choose a tenant with `cavelon use` (it lists your tenants), --tenant or CAVELON_TENANT.";
281
287
  }
package/dist/kit-codes.js CHANGED
@@ -34,7 +34,8 @@ export const KIT_ERROR_CODES = [
34
34
  { code: "operation_gone", area: "cli", message: "The operation no longer exists on the instance.", hint: "Start the work again; `cavelon status` lists the running operations." },
35
35
  { code: "stream_error", area: "cli", message: "The event stream of an operation broke off.", hint: "`cavelon wait <op_id>` polls instead." },
36
36
  { code: "no_solution", area: "cli", message: "This folder is not a Cavelon solution (no cavelon.yaml here or above).", hint: "Run `cavelon init`; `cavelon harness list` shows the tenant's solutions." },
37
- { code: "solution_not_found", area: "cli", message: "No solution by that name, slug or id in this tenant.", hint: "`cavelon harness list` shows them; `cavelon harness new <slug> --name <name>` creates one as a draft, which apply never does." },
37
+ { code: "solution_not_found", area: "cli", message: "No solution by that name, slug or id in this tenant.", hint: "`cavelon harness list` shows them; `cavelon harness new <slug> --name <name>` creates one as a draft, which apply never does; `cavelon init --harness <name> --new` creates it for a new folder, also beside a similar name." },
38
+ { code: "solution_exists", area: "cli", message: "`init --new` names a solution the tenant already has.", hint: "`cavelon init --harness <slug>` makes the folder that solution's; for a new one, give --new another name." },
38
39
  { code: "project_file_invalid", area: "cli", message: "cavelon.yaml is not a valid YAML mapping.", hint: "Fix the file at the place the message names." },
39
40
  { code: "project_file_has_secret", area: "cli", message: "cavelon.yaml holds a credential; solution files never do.", hint: "Remove it, revoke the token, and use `cavelon login` or CAVELON_TOKEN instead." },
40
41
  { code: "env_file_invalid", area: "cli", message: "An env/<name>.yaml file is invalid (not a mapping, a runtime binding that is not a resource id, or an unknown mode).", hint: "Fix the field the message names." },
@@ -53,10 +54,13 @@ export const KIT_ERROR_CODES = [
53
54
  { code: "preview_other_instance", area: "cli", message: "The preview was made on another instance.", hint: "Confirm it with the instance it was made on, or preview again here." },
54
55
  { code: "preview_other_tenant", area: "cli", message: "The preview was made for another tenant than this command acts in.", hint: "Run the confirm command the preview printed (it names --env and --tenant), or preview again here." },
55
56
  { code: "preview_files_changed", area: "cli", message: "The package files changed since the preview; nothing was imported.", hint: "Run `cavelon apply` for a preview of the files as they are now, show it, and confirm its id; --allow-stale with --confirm imports what the old preview showed." },
57
+ { code: "preview_superseded", area: "cli", message: "Another preview was imported after this one, so what it showed is no longer what an import would do; nothing was imported.", hint: "Run `cavelon apply` for a new preview, show it, and confirm its id." },
58
+ { code: "preview_applied", area: "cli", message: "The preview was imported already; nothing was imported again.", hint: "`cavelon apply` previews the files as they are now; confirm that preview's id." },
59
+ { code: "preview_discarded", area: "cli", message: "The preview was discarded (apply --discard); nothing was imported.", hint: "Run `cavelon apply` for a new preview, show it, and confirm its id." },
56
60
  { code: "preview_expired", area: "cli", message: "The preview is older than the kit keeps previews; nothing was imported.", hint: "Run `cavelon apply` for a new preview, show it, and confirm its id." },
57
61
  { code: "confirm_token_required", area: "cli", message: "Over MCP, or run by a coding agent in its shell, a changing command confirms only with the token its preview returned, never with true or a bare --confirm.", hint: "Call the tool (or run the command) without confirm, show the person the preview, then call it again with the same arguments and confirm set to its confirm_token (--confirm <token> in a shell)." },
58
62
  { code: "unknown_argument", area: "cli", message: "An MCP tool was called with an argument its schema does not list; nothing was done.", hint: "Call it again with the argument the error names (the tool's schema lists them all), spelled in snake_case." },
59
- { code: "solution_not_active", area: "cli", message: "Only an active solution can be the tenant's default route; this one is a draft (or archived), so nothing was changed.", hint: "Activate it through the readiness gate and preview the default route in one step: `cavelon activate --harness <slug> --make-default`." },
63
+ { code: "solution_not_active", area: "cli", message: "Only an active solution can be the tenant's default route; this one is not (a draft, or inactive after a deactivate), so nothing was changed.", hint: "Activate it through the readiness gate and preview the default route in one step: `cavelon activate --harness <slug> --make-default`." },
60
64
  { code: "default_route_deactivate", area: "cli", message: "The solution is the tenant's default route, so deactivate refused it; nothing was changed.", hint: "Ask the person which solution should answer in the tenant's chat and widget instead, make it the default (`cavelon harness default <solution>`), then deactivate." },
61
65
  { code: "default_route_unknown", area: "cli", message: "The instance does not say which solution is the tenant's default route (no is_default in its solution list).", hint: "The instance may be older than default routes; check the default in the Admin." },
62
66
  { code: "limit_not_found", area: "cli", message: "The instance lists no limit by that key.", hint: "`cavelon limits` lists the keys." },
@@ -75,6 +75,24 @@ export async function loadPreview(root, previewId) {
75
75
  export async function deletePreview(root, previewId) {
76
76
  await fs.rm(previewFile(root, previewId), { force: true });
77
77
  }
78
+ const RETIRED_PREVIEWS = "retired-previews.json";
79
+ const RETIRED_KEPT = 200;
80
+ async function readRetired(root) {
81
+ const stored = await readJsonFile(path.join(stateDir(root), RETIRED_PREVIEWS));
82
+ return Array.isArray(stored) ? stored.filter((r) => typeof r?.preview_id === "string") : [];
83
+ }
84
+ export async function retirePreviews(root, retired) {
85
+ if (!retired.length)
86
+ return;
87
+ for (const r of retired)
88
+ await deletePreview(root, r.preview_id);
89
+ const ids = new Set(retired.map((r) => r.preview_id));
90
+ const kept = (await readRetired(root)).filter((r) => !ids.has(r.preview_id));
91
+ await writeState(root, RETIRED_PREVIEWS, JSON.stringify([...kept, ...retired].slice(-RETIRED_KEPT), null, 2));
92
+ }
93
+ export async function retiredPreview(root, previewId) {
94
+ return (await readRetired(root)).find((r) => r.preview_id === previewId);
95
+ }
78
96
  export const PREVIEW_MAX_AGE_MS = 24 * 60 * 60 * 1000;
79
97
  export function previewExpiry(createdAt, now) {
80
98
  const created = Date.parse(createdAt);
package/dist/main.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { parseArgs } from "node:util";
2
- import { GLOBAL_OPTIONS } from "./command.js";
2
+ import { GLOBAL_OPTIONS, optionDescription, optionFlag } from "./command.js";
3
3
  import { createContext, withWarnings } from "./context.js";
4
4
  import { CONFIRM_TOKEN } from "./confirm-token.js";
5
5
  import { asCavelonError, ExitCode, usageError } from "./errors.js";
@@ -247,10 +247,7 @@ export function usageLine(spec) {
247
247
  return parts.join(" ");
248
248
  }
249
249
  function optionLines(options) {
250
- const rows = Object.entries(options).map(([name, o]) => {
251
- const flag = `${o.short ? `-${o.short}, ` : ""}--${name}${o.type === "string" ? ` ${o.value ?? "<value>"}` : ""}`;
252
- return [flag, o.description + (o.multiple ? " Repeatable." : "")];
253
- });
250
+ const rows = Object.entries(options).map(([name, o]) => [optionFlag(name, o), optionDescription(name, o)]);
254
251
  const width = Math.max(...rows.map(([f]) => f.length));
255
252
  return rows.map(([f, d]) => ` ${f.padEnd(width)} ${d}`);
256
253
  }
package/dist/mcp.js CHANGED
@@ -16,7 +16,9 @@ const INSTRUCTIONS = "Tools for one Cavelon instance, acting with the token a pe
16
16
  "confirm set to that token: show the person the preview first. The token confirms exactly the change the preview showed; " +
17
17
  "a different change needs a new preview, and confirm: true is refused. The default route " +
18
18
  "(harness_default, activate's make_default) decides which solution the tenant's chat and widget answer with: live traffic, " +
19
- "so ask the person, and confirm only with their yes; the same goes for deactivate, which takes a solution out of live traffic. " +
19
+ "so ask the person, and confirm only with their yes; the same goes for deactivate, which takes a solution out of live traffic " +
20
+ "(its status becomes inactive), and for apply with tenant_wide, which imports the tenant-wide sections (tenant_settings, " +
21
+ "model_registry, …) for every solution of the tenant. " +
20
22
  "chat sends one message to a solution and returns its answer: the way to try one that is not the default route. " +
21
23
  "kb_upload names files that match an active document of the knowledge base; with replace it replaces them, and where the " +
22
24
  "instance's upload cannot, it returns what it would deactivate and uploads nothing without its confirm_token. " +
@@ -1,6 +1,6 @@
1
1
  import { Ajv2020 } from "ajv/dist/2020.js";
2
2
  import { BRANCH_WIDTH_KEY, branchConcurrency, offText } from "./branches.js";
3
- import { locate, schemaSections } from "./package-files.js";
3
+ import { locate, schemaSections, tenantWideSections } from "./package-files.js";
4
4
  import { PERSONA_SECTION, sectionFields } from "./package-format.js";
5
5
  import { kitErrorEntry } from "./kit-codes.js";
6
6
  import { branches, checkModels, checkReferences, checkUnknownFields, closest, DUPLICATE_CODE, FIELD_UNKNOWN_CODE, MODEL_UNKNOWN_CODE, REFERENCE_MISSING_CODE, REFERENCE_UNKNOWN_CODE, KNOWLEDGE_TOOL_KEYS, } from "./package-references.js";
@@ -25,6 +25,7 @@ const PERSONA_MESSAGES = [
25
25
  { switch: "fallback_message_enabled", text: "fallback_message", what: "fallback message", when: "when the assistant has no answer" },
26
26
  ];
27
27
  const SOLUTION_MISMATCH_CODE = "solution_slug_mismatch";
28
+ const TENANT_WIDE_CODE = "tenant_wide_section";
28
29
  const ASSERTION_UNCHECKED_CODE = "test_assertion_unchecked";
29
30
  const TESTING_DOCS = "/docs/concepts/regression-testing";
30
31
  export const KIT_CODES = [
@@ -146,6 +147,14 @@ export const KIT_CODES = [
146
147
  "(or set harness in cavelon.yaml to the package's); the import otherwise works on the solution the package names.",
147
148
  docs: PACKAGE_DOCS,
148
149
  },
150
+ {
151
+ code: TENANT_WIDE_CODE,
152
+ area: "package",
153
+ message: "A solution's folder holds a section the whole tenant shares, such as tenant_settings or model_registry.",
154
+ hint: "`cavelon apply` leaves it out of the solution's import; `cavelon apply --tenant-wide` sends it, and then every solution of the tenant sees the change. " +
155
+ "Remove the file unless that is meant. An instance that does not publish include_tenant_wide imports it with every apply.",
156
+ docs: PACKAGE_DOCS,
157
+ },
149
158
  {
150
159
  code: "package_file_duplicate",
151
160
  area: "package",
@@ -306,6 +315,7 @@ export function checkPackage(disk, options) {
306
315
  findings.push(...checkPersonaMessages(disk, options.schema));
307
316
  findings.push(...checkUncheckedAssertions(disk, options.schema));
308
317
  findings.push(...checkSolutionSlug(disk, options.solution));
318
+ findings.push(...checkTenantWide(disk, options.schema, options.solution));
309
319
  for (const finding of findings) {
310
320
  const entry = findingEntry(options.catalog, finding.code);
311
321
  if (!entry)
@@ -653,6 +663,24 @@ function misnamedVariants(schema, pkg) {
653
663
  return found;
654
664
  }
655
665
  const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
666
+ function checkTenantWide(disk, schema, solution) {
667
+ if (!solution)
668
+ return [];
669
+ const shared = tenantWideSections(schema);
670
+ return Object.keys(disk.package)
671
+ .filter((section) => shared.has(section))
672
+ .map((section) => {
673
+ const source = disk.sources[section];
674
+ return {
675
+ code: TENANT_WIDE_CODE,
676
+ severity: "warning",
677
+ file: Array.isArray(source) ? source[0]?.file : source?.file,
678
+ path: section,
679
+ message: `${section} is shared by the whole tenant, not this solution's: apply leaves it out unless --tenant-wide, which changes it for every solution ` +
680
+ "(an instance that does not publish include_tenant_wide imports it with every apply). Remove the file unless that is meant.",
681
+ };
682
+ });
683
+ }
656
684
  function checkSolutionSlug(disk, solution) {
657
685
  if (!solution || UUID.test(solution))
658
686
  return [];
@@ -671,11 +699,11 @@ function checkSolutionSlug(disk, solution) {
671
699
  `rename the slug (and every harness_slug) to "${solution}", or set harness in cavelon.yaml to the package's.`,
672
700
  });
673
701
  }
674
- if (harnesses.length)
675
- return findings;
676
- for (const section of ["agents", "test_suites"]) {
702
+ const packaged = new Set(harnesses.map((h) => h.slug).filter((v) => typeof v === "string"));
703
+ for (const section of harnesses.length ? ["test_suites"] : ["agents", "test_suites"]) {
677
704
  const entries = asList(pkg[section]);
678
- const off = entries.flatMap((entry, i) => (typeof entry.harness_slug === "string" && entry.harness_slug !== slug ? [{ i, name: entry.harness_slug }] : []));
705
+ const fits = (name) => name === slug || packaged.has(name);
706
+ const off = entries.flatMap((entry, i) => (typeof entry.harness_slug === "string" && !fits(entry.harness_slug) ? [{ i, name: entry.harness_slug }] : []));
679
707
  if (!off.length)
680
708
  continue;
681
709
  const names = [...new Set(off.map((o) => o.name))];
@@ -1,6 +1,6 @@
1
1
  import { promises as fs } from "node:fs";
2
2
  import path from "node:path";
3
- import { LineCounter, parseDocument } from "yaml";
3
+ import { CST, LineCounter, Parser, parseDocument } from "yaml";
4
4
  import { CavelonError, ExitCode } from "./errors.js";
5
5
  import { readTextFile, withoutBom, writeFileAtomic } from "./fsutil.js";
6
6
  import { canonical, PERSONA_SECTION, sameEntry, sameSectionValue, sectionContent, sectionFields, toYaml } from "./package-format.js";
@@ -101,6 +101,27 @@ async function exists(dir) {
101
101
  return false;
102
102
  }
103
103
  }
104
+ function errorLine(text, error, lines) {
105
+ const at = error.linePos?.[0]?.line ?? (typeof error.pos?.[0] === "number" ? lines.linePos(error.pos[0]).line : undefined);
106
+ if (error.code !== "MISSING_CHAR" || typeof error.pos?.[0] === "undefined")
107
+ return at;
108
+ const pos = error.pos[0];
109
+ let start;
110
+ const quoted = (t) => {
111
+ if ((t?.type === "double-quoted-scalar" || t?.type === "single-quoted-scalar") && t.offset <= pos && t.offset + t.source.length >= pos)
112
+ start = t.offset;
113
+ };
114
+ for (const token of new Parser().parse(text)) {
115
+ if (token.type !== "document")
116
+ continue;
117
+ quoted(token.value);
118
+ CST.visit(token, (item) => {
119
+ quoted(item.key);
120
+ quoted(item.value);
121
+ });
122
+ }
123
+ return start === undefined ? at : lines.linePos(start).line;
124
+ }
104
125
  function parseFile(root, file, text) {
105
126
  const relative = rel(root, file);
106
127
  if (/\.json$/i.test(file)) {
@@ -124,7 +145,7 @@ function parseFile(root, file, text) {
124
145
  code: "package_file_invalid",
125
146
  severity: "error",
126
147
  file: relative,
127
- line: first.linePos?.[0]?.line ?? (typeof first.pos?.[0] === "number" ? lines.linePos(first.pos[0]).line : undefined),
148
+ line: errorLine(text, first, lines),
128
149
  message: `Not valid YAML: ${first.message.split("\n")[0]}`,
129
150
  },
130
151
  };
@@ -383,6 +404,7 @@ export async function writePackage(root, layout, pkg, schema, options = {}) {
383
404
  if (skip.has(section)) {
384
405
  if (!report.tenant_wide.includes(section))
385
406
  report.tenant_wide.push(section);
407
+ report.kept.push(rel(root, path.join(dir, name)));
386
408
  continue;
387
409
  }
388
410
  if (section in pkg || section === PERSONA_SECTION)
package/dist/session.js CHANGED
@@ -6,10 +6,19 @@ import { readTenantless } from "./principal.js";
6
6
  import { listsTenants, searchTenants, tenantMissError } from "./tenant-choice.js";
7
7
  import { findProject, readEnvFile } from "./project.js";
8
8
  import { loadUserConfig, tokenKind, updateInstance } from "./user-config.js";
9
+ import { shellWord } from "./shell.js";
9
10
  const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
10
11
  export function isUuid(value) {
11
12
  return UUID.test(value);
12
13
  }
14
+ export function contextFlags(session) {
15
+ let flags = "";
16
+ if (session.urlSource === "option" && session.url)
17
+ flags += ` --instance ${shellWord(session.url)}`;
18
+ if (session.tenantSource === "option" && session.tenant)
19
+ flags += ` --tenant ${shellWord(session.tenant)}`;
20
+ return flags;
21
+ }
13
22
  function isLocalHost(hostname) {
14
23
  return (hostname === "localhost" ||
15
24
  hostname.endsWith(".localhost") ||
@@ -108,13 +108,14 @@ endpoint.
108
108
  - On rows that already exist, `cavelon models list` shows each row's endpoint
109
109
  and `max_concurrent_requests` (never a key). `cavelon models set-limit
110
110
  <model_id> <n|none>` shows the old and the new value and changes nothing;
111
- with `--confirm` it changes the row. It refuses a row without a `base_url`.
111
+ the confirm command it prints changes the row (from your shell it carries the
112
+ preview's token, `--confirm <token>`). It refuses a row without a `base_url`.
112
113
  Where this instance's package format does not carry the field, `validate`
113
114
  warns that the import ignores it; set it this way instead.
114
115
 
115
116
  **Propose a limit; the person decides.** Say which value you would set and
116
117
  why (what the endpoint serves, which rows share it, what waits or fails now),
117
- then wait for the person's answer. Run `models set-limit --confirm` only after
118
+ then wait for the person's answer. Run the confirm command of `models set-limit` only after
118
119
  they agreed, and never raise or lower a limit without telling them. A limit
119
120
  `cavelon limits` names as the operator's (the run caps, the slot waits, the
120
121
  licence) is not yours or the tenant's to change: tell the person who changes
@@ -305,7 +306,10 @@ schema has them: `cavelon validate` reports an unknown section):
305
306
  instance's export gives them (field order, the schema's defaults filled in,
306
307
  test cases and steps numbered in their written order), so the first `pull`
307
308
  after `apply` shows only what changed on the instance; `cavelon fmt
308
- --check` changes nothing and exits 3 when a file would change.
309
+ --check` changes nothing and exits 3 when a file would change. fmt keeps
310
+ no comments (pull keeps none either) and names each file whose comments
311
+ it drops, as the example files' explanations: keep what the person needs
312
+ elsewhere before running it.
309
313
  2. `cavelon apply --env test` to see what the instance makes of it; the
310
314
  preview re-checks everything on the server, including rules that only the
311
315
  instance can check (graph rules, references between sections).
@@ -47,7 +47,9 @@ Do not work around it; use the other column.
47
47
  iteration, activate the parent (cavelon-loop skill, "A Masterloop parent and
48
48
  its iteration solution"). `activate` never forces.
49
49
  5. **Seed it.** Isolated container: `cavelon sandbox seed <sandbox> <folder>`
50
- shows what it would send; add `--confirm` to send it. The archive **replaces
50
+ shows what it would send and the confirm command that sends it: run that
51
+ one (from your shell it carries the preview's token, `--confirm <token>`;
52
+ a bare `--confirm` exits 5 and sends nothing). The archive **replaces
51
53
  the workspace**, so confirm only for a test Sandbox or after the person
52
54
  agreed. Customer VM: the files go onto the VM, then `cavelon sandbox refresh
53
55
  <sandbox>`.
@@ -79,14 +81,15 @@ seconds).
79
81
  `invalid_continuation`, …) resumes only with `--reason <the pause reason>`,
80
82
  exactly as the loop names it, once the person reviewed the cause; `--reason`
81
83
  is never free text. A pause that cannot be resumed is cancelled
82
- (`cavelon loop cancel <run> --confirm`) and started again after the fix; the
83
- watch prints both commands.
84
+ (`cavelon loop cancel <run>`, then the confirm command it prints) and started
85
+ again after the fix; the watch prints both commands.
84
86
  - An iteration reads **accepted** (with its outcome: continue, wait, done,
85
87
  blocked), **rejected**, or **failed** when its child failed. A run that ended
86
88
  without a loop names the stage that recorded an error.
87
89
  `cavelon trace <child_run_id>` reads one iteration's run.
88
- - **Stop** a run and its loops: `cavelon loop cancel <run>` shows what stops;
89
- `--confirm` stops it. Stop runs you started, not someone else's.
90
+ - **Stop** a run and its loops: `cavelon loop cancel <run>` shows what stops
91
+ and the confirm command (`--confirm <token>` from your shell) that stops it.
92
+ Stop runs you started, not someone else's.
90
93
  - A run that waits at an **Approval** node, or a loop paused by a guardrail,
91
94
  needs a person: `wait` prints the reason and the Admin link. An approval is
92
95
  decided by a person, or by an API key an owner granted the explicit scope
@@ -121,7 +124,8 @@ Two reasons end work for capacity; each has its code in `cavelon explain`:
121
124
  `model_endpoint_slot_wait_seconds`. Retry later, or, if the endpoint can serve
122
125
  more, propose raising the Model Registry row's `max_concurrent_requests`
123
126
  (`cavelon models list` shows it). The person decides; only then run
124
- `cavelon models set-limit <model_id> <n> --confirm`.
127
+ `cavelon models set-limit <model_id> <n>` and the confirm command it prints
128
+ (`--confirm <token>` from your shell).
125
129
 
126
130
  `cavelon limits` shows the caps, their source and origin, the slot waits, and
127
131
  branch concurrency (how many items of a Map loop run at once, and whether they
@@ -155,9 +159,9 @@ A scheduled or webhook run has no caller, so it acts as an **API key** bound to
155
159
  its trigger. `apply` never binds one; it lists unbound triggers in the preview.
156
160
 
157
161
  ```bash
158
- cavelon trigger identity <trigger> # who it runs as, what the key must reach
159
- cavelon trigger identity <trigger> <key-name> # shows the change
160
- cavelon trigger identity <trigger> <key-name> --confirm
162
+ cavelon trigger identity <trigger> # who it runs as, what the key must reach
163
+ cavelon trigger identity <trigger> <key-name> # shows the change and its confirm token
164
+ cavelon trigger identity <trigger> <key-name> --confirm <token> # from your shell; a person's terminal takes a bare --confirm
161
165
  ```
162
166
 
163
167
  Binding gives the trigger standing authority over its Sandboxes: show the person