@cavelon/cli 0.2.11 → 0.2.12

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.
@@ -27,6 +27,8 @@ import { pairOrderHint, pairOrderPointer } from "../pair-order.js";
27
27
  import { readPackage, tenantWideSections, writePackage } from "../package-files.js";
28
28
  import { blockerDetails, blockerLines, changeLines, fieldChanges, locateBlockers, notApplied, notAppliedLines, tenantWideReport } from "../preview-report.js";
29
29
  import { readPrincipal } from "../principal.js";
30
+ import { hasManagedFields, packageToSend, packageToWrite } from "../managed-fields.js";
31
+ import { liveFields, previewLiveFields, ruleFields, rulesChange, rulesChangeLines, rulesWarning } from "../engagement.js";
30
32
  import { CASE_STATUSES, caseStatus, TESTING_PAGE } from "../results.js";
31
33
  import { KNOWLEDGE_OUTCOME_AREA, KNOWLEDGE_OUTCOME_PAGE, KNOWLEDGE_OUTCOMES, knowledgeOutcome } from "../trace-view.js";
32
34
  import { isUuid, requireInstance } from "../session.js";
@@ -182,6 +184,21 @@ async function takesTenantWide(ctx, where) {
182
184
  const properties = doc && schema ? deref(doc, schema)?.properties : undefined;
183
185
  return Boolean(properties?.[INCLUDE_TENANT_WIDE]);
184
186
  }
187
+ async function exportKindsQuery(ctx, managed) {
188
+ const lists = Object.entries(managed.kinds).filter(([pointer]) => /^\/persona\/[^/]+$/.test(pointer) && !managed.unmanaged.includes(pointer));
189
+ if (!lists.length)
190
+ return {};
191
+ const { doc, op } = await workflowOperation(ctx, "GET", EXPORT_ROUTE, "exporting packages");
192
+ if (!doc)
193
+ return {};
194
+ const query = {};
195
+ for (const [pointer, kinds] of lists) {
196
+ const name = `${pointer.slice("/persona/".length)}_kinds`;
197
+ if (op.parameters.some((p) => p.name === name))
198
+ query[name] = kinds;
199
+ }
200
+ return query;
201
+ }
185
202
  function sectionFiles(disk, sections) {
186
203
  return sections.flatMap((section) => {
187
204
  const source = disk.sources[section];
@@ -236,8 +253,9 @@ export const pull = {
236
253
  if (tenantWide && !harness)
237
254
  ctx.warn("--include-tenant-wide applies to a solution's pull; the tenant's full configuration carries the tenant-wide sections anyway.");
238
255
  const askTenantWide = Boolean(harness) && tenantWide && (await takesTenantWide(ctx, "export"));
256
+ const kindsQuery = await exportKindsQuery(ctx, project.managed);
239
257
  const exported = await callStable(ctx, "GET", EXPORT_ROUTE, "exporting packages", {
240
- query: { scope, harness_id: harness?.id, ...(askTenantWide ? { [INCLUDE_TENANT_WIDE]: true } : {}) },
258
+ query: { scope, harness_id: harness?.id, ...(askTenantWide ? { [INCLUDE_TENANT_WIDE]: true } : {}), ...kindsQuery },
241
259
  timeoutMs: 120_000,
242
260
  });
243
261
  if (!exported || typeof exported !== "object" || Array.isArray(exported)) {
@@ -251,13 +269,14 @@ export const pull = {
251
269
  const skip = harness && !tenantWide ? shared : new Set();
252
270
  const placed = {};
253
271
  const options = { skip, itemFiles: await readItemFiles(project.root), placed };
272
+ const folderPackage = packageToWrite(exported, project.managed, schema);
254
273
  if (dirty === undefined) {
255
- const edited = await editedSincePull(project, exported, schema, options);
274
+ const edited = await editedSincePull(project, folderPackage, schema, options);
256
275
  if (edited.length) {
257
276
  throw uncommittedChanges(edited, "This folder is not in a git repository, and pull would overwrite or remove files that changed since the last pull");
258
277
  }
259
278
  }
260
- const report = await writePackage(project.root, project.layout, exported, schema, options);
279
+ const report = await writePackage(project.root, project.layout, folderPackage, schema, options);
261
280
  await writePulledFiles(project.root, [...report.written, ...report.unchanged], placed);
262
281
  await rememberQueries(project.root, exported, schema, "pull", ctx.io.now());
263
282
  if (harness && !project.harness)
@@ -293,6 +312,7 @@ export const pull = {
293
312
  ...report.written.map((f) => `written ${f}`),
294
313
  ...report.removed.map((f) => `removed ${f}`),
295
314
  `${report.unchanged.length} file${report.unchanged.length === 1 ? "" : "s"} unchanged.`,
315
+ ...(hasManagedFields(project.managed) ? [managedPullLine(project.managed)] : []),
296
316
  ...(report.tenant_wide.length
297
317
  ? [`Left out the tenant-wide section${report.tenant_wide.length === 1 ? "" : "s"} ${report.tenant_wide.join(", ")} (--include-tenant-wide writes them).`]
298
318
  : []),
@@ -315,6 +335,13 @@ export const pull = {
315
335
  return { data: { ...record, inventory, ...(pulledShared ? { tenant_wide_pulled: pulledShared } : {}) }, text: lines.join("\n") };
316
336
  },
317
337
  };
338
+ function managedPullLine(managed) {
339
+ const parts = [
340
+ ...(managed.unmanaged.length ? [`${managed.unmanaged.join(", ")} (unmanaged)`] : []),
341
+ ...Object.entries(managed.kinds).map(([pointer, kinds]) => `${pointer} beyond ${kinds.join(", ")} (managed_kinds)`),
342
+ ];
343
+ return `Left to the Admin, as cavelon.yaml says: ${parts.join("; ")}.`;
344
+ }
318
345
  async function inventoryFor(ctx, project, disk, offline, schema) {
319
346
  let inventory = await readInventory(project.root);
320
347
  const missing = missingInventory(disk, inventory, schema);
@@ -364,6 +391,7 @@ export async function validatePackage(ctx, project, offline) {
364
391
  solution: project.harness,
365
392
  queryBaseline: await readQueryBaseline(project.root),
366
393
  queryConnections,
394
+ managed: project.managed,
367
395
  });
368
396
  return { disk, findings, schema, schemaVersion: schema["x-package-version"] ?? version ?? null, used, skipped };
369
397
  }
@@ -541,9 +569,11 @@ function changesNothing(p) {
541
569
  }
542
570
  export function previewText(p, context = {}) {
543
571
  const lines = [["ready", p.ready ? "yes" : "no"]];
544
- const publication = publicationNotice(p.publication);
572
+ const publication = publicationNotice(p.publication, context.live);
545
573
  if (publication)
546
574
  lines.push(["publication", publication]);
575
+ else if (context.live?.length)
576
+ lines.push(["live", liveText(context.live)]);
547
577
  const s = p.summary ?? {};
548
578
  for (const [label, map] of [["creates", s.creates], ["updates", s.updates], ["deletes", s.deletes]]) {
549
579
  const text = counts(map);
@@ -555,6 +585,8 @@ export function previewText(p, context = {}) {
555
585
  const changes = fieldChanges(p.changes);
556
586
  if (changes.length)
557
587
  lines.push(["field changes", changeLines(changes)]);
588
+ for (const rules of context.rules ?? [])
589
+ lines.push([rules.pointer.split("/").pop().replace(/_/g, " "), rulesChangeLines(rules)]);
558
590
  const details = blockerDetails(p.blocker_details, context.disk);
559
591
  if (details.length)
560
592
  lines.push(["blockers", blockerLines(details)]);
@@ -595,6 +627,47 @@ function previewReport(p, context) {
595
627
  const skipped = notApplied(p.ignored?.not_applied, context.disk?.package, context.harness, mayActivate(context.access));
596
628
  if (skipped.length)
597
629
  out.not_applied = skipped;
630
+ if (context.rules?.length)
631
+ out.engagement_rules = context.rules;
632
+ return out;
633
+ }
634
+ function liveText(live) {
635
+ return `${list(live, 10)} reach${live.length === 1 ? "es" : ""} visitors at once on an active solution, without a publication`;
636
+ }
637
+ async function currentPersona(ctx, harness) {
638
+ try {
639
+ const persona = await callStable(ctx, "GET", "/api/v1/bot-persona", "reading the persona", { query: { harness_id: harness?.id } });
640
+ return persona && typeof persona === "object" && !Array.isArray(persona) ? persona : undefined;
641
+ }
642
+ catch {
643
+ return undefined;
644
+ }
645
+ }
646
+ async function engagementChanges(ctx, sent, schema, harness) {
647
+ const persona = sent.persona && typeof sent.persona === "object" && !Array.isArray(sent.persona) ? sent.persona : undefined;
648
+ if (!persona)
649
+ return [];
650
+ const fields = ruleFields(schema).filter((f) => Array.isArray(persona[f.field]));
651
+ if (!fields.length)
652
+ return [];
653
+ const current = await currentPersona(ctx, harness);
654
+ return fields.map((f) => {
655
+ const kinds = persona[`${f.field}_kinds`];
656
+ const held = current?.[f.field];
657
+ return rulesChange(schema, f, current ? (Array.isArray(held) ? held : []) : undefined, persona[f.field], Array.isArray(kinds) ? kinds.filter((k) => typeof k === "string") : undefined);
658
+ });
659
+ }
660
+ function managedWarnings(sent) {
661
+ const out = [];
662
+ const unmanaged = sent.left_out.filter((pointer) => !sent.kinds.some((k) => k.pointer === pointer));
663
+ if (unmanaged.length)
664
+ out.push(`Left out ${unmanaged.join(", ")}: cavelon.yaml lists ${unmanaged.length === 1 ? "it" : "them"} as unmanaged, so the instance keeps its own value.`);
665
+ for (const k of sent.kinds) {
666
+ if (!k.sent)
667
+ out.push(`Left out ${k.pointer}: ${k.reason}; the solution keeps all of its entries. Remove it from managed_kinds in cavelon.yaml to send the whole list.`);
668
+ else if (k.other_kinds_left_out.length)
669
+ out.push(`Left out ${k.other_kinds_left_out.join(", ")} from ${k.pointer}: of kinds cavelon.yaml's managed_kinds does not list (${k.kinds.join(", ")}).`);
670
+ }
598
671
  return out;
599
672
  }
600
673
  function sourceFiles(disk) {
@@ -810,7 +883,9 @@ async function confirmPreview(ctx, project, previewId, allowStale, automatic = f
810
883
  ...others.map((p) => ({ preview_id: p.preview_id, reason: "superseded", at: now, by: stored.preview_id })),
811
884
  ]);
812
885
  await rememberImported(ctx, project, stored, disk, changed);
813
- await rememberQueries(project.root, stored.request.package, (await schemaFor(ctx, packageVersionOf(stored.request.package), false)).schema, "apply", ctx.io.now());
886
+ const importedSchema = (await schemaFor(ctx, packageVersionOf(stored.request.package), false)).schema;
887
+ await rememberQueries(project.root, stored.request.package, importedSchema, "apply", ctx.io.now());
888
+ const importedLive = previewLiveFields(stored.preview, liveFields(importedSchema).fields)?.pointers ?? [];
814
889
  const summary = (result.summary ?? {});
815
890
  const still = setCommands(stored.preview, stored.env ?? undefined, secretsInAdminOnly((await accessFor(client))?.principal) === true);
816
891
  const sharedSent = stored.request[INCLUDE_TENANT_WIDE] === true;
@@ -826,7 +901,7 @@ async function confirmPreview(ctx, project, previewId, allowStale, automatic = f
826
901
  const text = keyValues([
827
902
  ["applied", `preview ${stored.preview_id}${stored.harness ? ` to ${stored.harness.slug}` : ""}${stored.env ? ` (env ${stored.env})` : ""}`],
828
903
  ["acted on", targetText(acting)],
829
- ["publication", publicationNotice(result.publication)],
904
+ ["publication", publicationNotice(result.publication, importedLive)],
830
905
  ["tenant-wide", sharedText],
831
906
  ["created", counts(summary?.creates) || undefined],
832
907
  ["updated", counts(summary?.updates) || undefined],
@@ -942,7 +1017,7 @@ function graphDraftTarget(preview, harness) {
942
1017
  Number.isSafeInteger(p.draft_revision) && p.draft_revision >= 0 &&
943
1018
  Array.isArray(preview.impact?.active_harnesses));
944
1019
  }
945
- function personReason(preview, harness, mode, env, shared = [], sharedReaches = []) {
1020
+ function personReason(preview, harness, mode, env, shared = [], sharedReaches = [], live = []) {
946
1021
  if (shared.length) {
947
1022
  const reaching = sharedReaches.length ? `, reaching the active solution${sharedReaches.length === 1 ? "" : "s"} ${list(sharedReaches, 5)}` : "";
948
1023
  return `changes what the whole tenant shares (${list(shared, 5)})${reaching}`;
@@ -952,6 +1027,8 @@ function personReason(preview, harness, mode, env, shared = [], sharedReaches =
952
1027
  active.unshift(harness.slug);
953
1028
  if (active.length)
954
1029
  return `reaches the active solution${active.length === 1 ? "" : "s"} ${list(active, 5)}`;
1030
+ if (live.length && harness?.status === "active")
1031
+ return `changes ${list(live, 5)}, which visitors of the active solution ${harness.slug} see at once, without a publication`;
955
1032
  if (preview.impact?.active_harnesses?.length)
956
1033
  return "reaches an active solution";
957
1034
  if (counts(preview.summary?.deletes) || mode === "replace")
@@ -1051,7 +1128,10 @@ export const apply = {
1051
1128
  const scope = disk.package.manifest?.scope ?? "agent_graph";
1052
1129
  if (harness && scope === "full_config")
1053
1130
  ctx.warn("The package is a full configuration; the instance imports it tenant-wide, whatever the solution.");
1054
- const request = { package: disk.package, mode };
1131
+ const sent = packageToSend(disk.package, project.managed, schema);
1132
+ for (const warning of managedWarnings(sent))
1133
+ ctx.warn(warning);
1134
+ const request = { package: sent.package, mode };
1055
1135
  if (harness)
1056
1136
  request.harness_id = harness.id;
1057
1137
  if (envFile && Object.keys(envFile.runtimeBindings).length)
@@ -1078,6 +1158,20 @@ export const apply = {
1078
1158
  const target = harness ? { id: harness.id, slug: harness.slug } : null;
1079
1159
  const acting = await actingTarget(ctx);
1080
1160
  const data = { previewed: true, ...preview, env: envFile?.name ?? null, harness: target, target: acting };
1161
+ if (hasManagedFields(project.managed))
1162
+ data.managed = { left_out: sent.left_out, kinds: sent.kinds };
1163
+ const live = liveFields(schema);
1164
+ const reportedLive = previewLiveFields(preview, live.fields);
1165
+ const sentPersona = (sent.package.persona && typeof sent.package.persona === "object" ? sent.package.persona : {});
1166
+ const livePointers = reportedLive?.pointers ?? live.fields.filter((f) => f in sentPersona).map((f) => `/persona/${f}`);
1167
+ if (livePointers.length)
1168
+ data.live_fields = { pointers: livePointers, reported_by: reportedLive?.reported_by ?? "kit", marked_by_schema: live.marked };
1169
+ const rules = await engagementChanges(ctx, sent.package, schema, harness);
1170
+ for (const change of rules) {
1171
+ const warning = rulesWarning(change);
1172
+ if (warning)
1173
+ ctx.warn(warning);
1174
+ }
1081
1175
  if (queries.data) {
1082
1176
  const reported = preview.database_queries;
1083
1177
  data.database_queries = { ...queries.data, ...(reported && typeof reported === "object" && !Array.isArray(reported) ? reported : {}) };
@@ -1124,7 +1218,7 @@ export const apply = {
1124
1218
  const commands = setCommands(preview, undefined, secretsInAdminOnly(access?.principal) === true);
1125
1219
  if (commands.secrets.length || commands.variables.length)
1126
1220
  data.set_commands = commands;
1127
- const context = { disk, harness: harness?.slug, access };
1221
+ const context = { disk, harness: harness?.slug, access, live: livePointers, rules };
1128
1222
  Object.assign(data, previewReport(preview, context));
1129
1223
  if (!preview.ready) {
1130
1224
  const pair = pairOrderHint(await catalogFor(ctx, false), [
@@ -1175,7 +1269,7 @@ export const apply = {
1175
1269
  if (!preview.preview_id) {
1176
1270
  ctx.warn("This instance's preview returns no preview id, so `apply --confirm` cannot import exactly it; update the instance.");
1177
1271
  }
1178
- const reason = personReason(preview, harness, mode, envFile?.name, sharedImported, reaches);
1272
+ const reason = personReason(preview, harness, mode, envFile?.name, sharedImported, reaches, livePointers);
1179
1273
  if (preview.preview_id) {
1180
1274
  const stored = {
1181
1275
  preview_id: preview.preview_id,
@@ -645,6 +645,24 @@ export const kbUpload = {
645
645
  };
646
646
  },
647
647
  };
648
+ const ENGAGEMENT_TAG = "engagement";
649
+ const RULE_TAG_PREFIX = "rule:";
650
+ function votesNot(suite) {
651
+ if (typeof suite.counts_for_readiness === "boolean")
652
+ return !suite.counts_for_readiness;
653
+ const tags = Array.isArray(suite.tags) ? suite.tags : [];
654
+ return tags.includes(ENGAGEMENT_TAG) && tags.some((t) => typeof t === "string" && t.startsWith(RULE_TAG_PREFIX) && t.length > RULE_TAG_PREFIX.length);
655
+ }
656
+ function skippedView(suite) {
657
+ return { suite: suite.name, suite_id: suite.id, ...(suite.purpose ? { purpose: suite.purpose } : {}), reason: "not_in_readiness" };
658
+ }
659
+ function skippedText(skipped) {
660
+ if (!skipped.length)
661
+ return "";
662
+ const names = skipped.map((s) => `"${s.name}"`).join(", ");
663
+ return (`Skipped ${skipped.length === 1 ? "1 suite that does" : `${skipped.length} suites that do`} not vote in readiness (campaign question checks): ${names}. ` +
664
+ `Run one with: ${cavelonCommand("test", "run", "--suite", skipped[0].name)}`);
665
+ }
648
666
  function summaryText(summary) {
649
667
  const verdict = runVerdict(summary);
650
668
  const shown = ["passed", "failed", "errors"].filter((k) => k in summary).map((k) => k + " " + String(summary[k]));
@@ -664,7 +682,8 @@ function resumeCommand(pending, timeout) {
664
682
  export const testRun = {
665
683
  name: "test run",
666
684
  summary: "Start test-suite runs; returns operation ids.",
667
- description: "Without --suite, runs every suite of the solution (--harness, or cavelon.yaml's harness).\n" +
685
+ description: "Without --suite, runs every suite of the solution (--harness, or cavelon.yaml's harness), except suites that never\n" +
686
+ "vote in readiness, such as a campaign's question checks: they are listed as skipped, and --suite runs one.\n" +
668
687
  "With --wait, exits 1 when a case failed or a run measured nothing comparable (cases not run, technical errors),\n" +
669
688
  "5 when answers wait for a manual verdict or a value a case needs.\n" +
670
689
  "--as-chat-user chooses a Chat User reader for these runs only, for knowledge and identity-bound database queries;\n" +
@@ -695,6 +714,7 @@ export const testRun = {
695
714
  });
696
715
  const wanted = listOption(input, "suite");
697
716
  let chosen;
717
+ let skipped = [];
698
718
  if (wanted.length) {
699
719
  chosen = wanted.map((ref) => {
700
720
  const hit = suites.find((s) => s.id === ref) ?? suites.filter((s) => s.name.toLowerCase() === ref.toLowerCase());
@@ -711,11 +731,14 @@ export const testRun = {
711
731
  });
712
732
  }
713
733
  else {
714
- chosen = suites.filter((s) => !s.archived_at);
734
+ const current = suites.filter((s) => !s.archived_at);
735
+ skipped = current.filter(votesNot);
736
+ chosen = current.filter((s) => !votesNot(s));
715
737
  if (chosen.length === 0) {
716
738
  throw new CavelonError(ExitCode.failure, {
717
739
  code: "no_suites",
718
- message: harnessRef ? `${harnessRef} has no test suites.` : "This tenant has no test suites.",
740
+ message: (harnessRef ? `${harnessRef} has no test suites` : "This tenant has no test suites") +
741
+ (skipped.length ? ` that vote in readiness. ${skippedText(skipped)}` : "."),
719
742
  });
720
743
  }
721
744
  }
@@ -758,14 +781,20 @@ export const testRun = {
758
781
  waited.body,
759
782
  "",
760
783
  ...results.map((r) => `${r.suite}: ${r.status} ${summaryText(r.summary)}`),
784
+ ...(skipped.length ? ["", skippedText(skipped)] : []),
761
785
  ...(resume ? ["", `${waited.why} after the timeout; the runs go on. Resume: ${resume}`] : []),
762
786
  ].join("\n");
763
- return { data: { runs: results, failed_cases: failedCases, ...waited.data, ...reader, ...(resume ? { resume } : {}) }, text: reader ? `Reading as Chat User ${reader.reader_chat_user_id} for these runs only.\n${text}` : text, exitCode };
787
+ return {
788
+ data: { runs: results, failed_cases: failedCases, ...waited.data, ...reader, ...(skipped.length ? { skipped: skipped.map(skippedView) } : {}), ...(resume ? { resume } : {}) },
789
+ text: reader ? `Reading as Chat User ${reader.reader_chat_user_id} for these runs only.\n${text}` : text,
790
+ exitCode,
791
+ };
764
792
  }
765
793
  return {
766
- data: { runs: started, operation_ids: operationIds, ...reader },
794
+ data: { runs: started, operation_ids: operationIds, ...reader, ...(skipped.length ? { skipped: skipped.map(skippedView) } : {}) },
767
795
  text: (reader ? `Reading as Chat User ${reader.reader_chat_user_id} for these runs only.\n` : "") +
768
796
  table(started, ["suite", "run_id", "status", "operation_id"]) +
797
+ (skipped.length ? `\n\n${skippedText(skipped)}` : "") +
769
798
  (operationIds.length ? `\n\nWait with: ${cavelonCommand("wait", ...operationIds)}` : ""),
770
799
  };
771
800
  },
@@ -0,0 +1,117 @@
1
+ import { kindedList } from "./managed-fields.js";
2
+ import { canonical, PERSONA_SECTION, sectionFields, settledForm } from "./package-format.js";
3
+ export const LIVE_MARK = "x-cavelon-live";
4
+ const DOCUMENTED_LIVE = ["engagement_rules", "greeting_message", "greeting_enabled", "teaser_messages", "teaser_display_count"];
5
+ const RULES_FIELD = "engagement_rules";
6
+ const asObject = (v) => (v && typeof v === "object" && !Array.isArray(v) ? v : undefined);
7
+ export function liveFields(schema) {
8
+ const fields = sectionFields(schema, PERSONA_SECTION) ?? {};
9
+ const marked = Object.entries(fields).filter(([, node]) => node[LIVE_MARK] === true).map(([name]) => name);
10
+ if (marked.length)
11
+ return { fields: marked, marked: true };
12
+ const known = Object.keys(fields);
13
+ return { fields: DOCUMENTED_LIVE.filter((name) => !known.length || known.includes(name)), marked: false };
14
+ }
15
+ export function previewLiveFields(preview, live) {
16
+ const reported = asObject(preview.publication)?.live_fields;
17
+ if (Array.isArray(reported))
18
+ return { pointers: reported.filter((p) => typeof p === "string"), reported_by: "instance" };
19
+ if (!Array.isArray(preview.changes))
20
+ return undefined;
21
+ const pointers = new Set();
22
+ for (const entry of preview.changes) {
23
+ const change = asObject(entry);
24
+ if (change?.section !== PERSONA_SECTION)
25
+ continue;
26
+ const fields = Array.isArray(change.fields) ? change.fields : asObject(change.diff) ? Object.keys(change.diff) : [];
27
+ for (const field of fields) {
28
+ const name = typeof field === "string" ? field : asObject(field)?.field;
29
+ if (typeof name === "string" && live.includes(name))
30
+ pointers.add(`/${PERSONA_SECTION}/${name}`);
31
+ }
32
+ if (change.action === "create")
33
+ for (const name of live)
34
+ pointers.add(`/${PERSONA_SECTION}/${name}`);
35
+ }
36
+ return { pointers: [...pointers], reported_by: "kit" };
37
+ }
38
+ export function ruleFields(schema) {
39
+ const fields = sectionFields(schema, PERSONA_SECTION) ?? {};
40
+ const kinded = schema
41
+ ? Object.keys(fields).flatMap((field) => {
42
+ const shape = kindedList(schema, `/${PERSONA_SECTION}/${field}`);
43
+ return shape?.discriminator ? [{ field, discriminator: shape.discriminator }] : [];
44
+ })
45
+ : [];
46
+ if (kinded.length)
47
+ return kinded;
48
+ return RULES_FIELD in fields || !schema ? [{ field: RULES_FIELD, discriminator: "kind" }] : [];
49
+ }
50
+ function ref(entry, discriminator) {
51
+ const rule = asObject(entry) ?? {};
52
+ const text = (v) => (typeof v === "string" ? v : "");
53
+ return { id: text(rule.id) || "?", kind: text(rule[discriminator]) || "?", name: text(rule.name) };
54
+ }
55
+ export function rulesChange(schema, field, current, sent, kinds) {
56
+ const listNode = sectionFields(schema, PERSONA_SECTION)?.[field.field];
57
+ const same = (a, b) => schema && listNode ? canonical(settledForm(schema, listNode, [a])) === canonical(settledForm(schema, listNode, [b])) : canonical(a) === canonical(b);
58
+ const inScope = (entry) => !kinds || kinds.includes(ref(entry, field.discriminator).kind);
59
+ const before = (current ?? []).filter(inScope);
60
+ const byId = new Map(before.map((entry) => [ref(entry, field.discriminator).id, entry]));
61
+ const sentIds = new Set(sent.map((entry) => ref(entry, field.discriminator).id));
62
+ const change = {
63
+ pointer: `/${PERSONA_SECTION}/${field.field}`,
64
+ kinds: kinds ?? null,
65
+ current_known: current !== undefined,
66
+ added: [],
67
+ removed: [],
68
+ changed: [],
69
+ unchanged: 0,
70
+ kept: (current ?? []).length - before.length,
71
+ };
72
+ for (const entry of sent) {
73
+ const old = byId.get(ref(entry, field.discriminator).id);
74
+ if (old === undefined)
75
+ change.added.push(ref(entry, field.discriminator));
76
+ else if (same(old, entry))
77
+ change.unchanged++;
78
+ else
79
+ change.changed.push(ref(entry, field.discriminator));
80
+ }
81
+ for (const entry of before)
82
+ if (!sentIds.has(ref(entry, field.discriminator).id))
83
+ change.removed.push(ref(entry, field.discriminator));
84
+ return change;
85
+ }
86
+ const shownRule = (r) => `${r.kind} ${r.id}${r.name ? ` "${r.name}"` : ""}`;
87
+ export function rulesChangeLines(change, max = 10) {
88
+ const lines = [];
89
+ const add = (sign, rules) => {
90
+ for (const r of rules.slice(0, max))
91
+ lines.push(`\n ${sign} ${shownRule(r)}`);
92
+ if (rules.length > max)
93
+ lines.push(`\n … ${rules.length - max} more (--json)`);
94
+ };
95
+ add("+", change.added);
96
+ add("-", change.removed);
97
+ add("~", change.changed);
98
+ const rest = [
99
+ ...(change.unchanged ? [`${change.unchanged} unchanged`] : []),
100
+ ...(change.kinds ? [`only ${change.kinds.join(", ")} replaced${change.kept ? `; ${change.kept} rule${change.kept === 1 ? "" : "s"} of other kinds kept` : ""}`] : []),
101
+ ...(change.current_known ? [] : ["the solution's current rules could not be read, so every rule sent is listed as added"]),
102
+ ];
103
+ if (!lines.length && !rest.length)
104
+ return " none";
105
+ return lines.join("") + (rest.length ? `\n (${rest.join("; ")})` : "");
106
+ }
107
+ export function rulesWarning(change) {
108
+ const replaced = change.kinds ? [] : change.changed;
109
+ if (!change.removed.length && !replaced.length)
110
+ return undefined;
111
+ const parts = [
112
+ ...(change.removed.length ? [`removes ${change.removed.length} (${change.removed.slice(0, 5).map(shownRule).join(", ")}${change.removed.length > 5 ? ", …" : ""})`] : []),
113
+ ...(replaced.length ? [`replaces ${replaced.length} (${replaced.slice(0, 5).map(shownRule).join(", ")}${replaced.length > 5 ? ", …" : ""})`] : []),
114
+ ];
115
+ return (`This import ${parts.join(" and ")} of the solution's engagement rules (${change.pointer}): a campaign edited in the Admin since the last pull is lost. ` +
116
+ "Pull first to keep it, or name the kinds this folder manages in cavelon.yaml (managed_kinds) so the others stay as they are.");
117
+ }
package/dist/kit-codes.js CHANGED
@@ -24,6 +24,8 @@ export const KIT_ERROR_CODES = [
24
24
  { code: "foreign_url", area: "cli", message: "cavelon refused to send the token to a URL outside the instance.", hint: "Check the instance URL; the token goes only to the instance it was stored for." },
25
25
  { code: "network_error", area: "cli", message: "The instance could not be reached.", hint: "Check the instance URL and the network (VPN, proxy, allowlist)." },
26
26
  { code: "request_timeout", area: "cli", message: "The instance did not answer in time.", hint: "Retry; CAVELON_HTTP_TIMEOUT_MS raises the limit per request." },
27
+ { code: "chat_uploads_off", area: "cli", message: "The tenant does not take files in a chat: its document uploads, or their conversation scope, are off.", hint: "Someone who manages the tenant's uploads turns on document uploads and their Chat/Run Context scope in the Admin (Settings › Documents); or leave out --file." },
28
+ { code: "chat_turn_timeout", area: "cli", message: "A chat turn was not answered within the wait; the turn goes on on the instance, which stores its answer.", hint: "Do not send the message again: it would run twice. Read the conversation with `cavelon api get_conversation --param conversation_id=<conversation_id>` (the error names it, or the session to find it by in `cavelon api list_conversations`), then continue with `cavelon chat <message> --session <session_id>`; a longer --timeout waits longer." },
27
29
  { code: "unexpected_redirect", area: "cli", message: "The instance redirected a request elsewhere.", hint: "Check the instance URL (https, host, path)." },
28
30
  { code: "internal_error", area: "cli", message: "cavelon failed in an unexpected way.", hint: "Run the command again; if it repeats, report it with the command and its output." },
29
31
  { code: "operation_unavailable", area: "cli", message: "This instance does not offer what the command needs (the route or a field is not in its OpenAPI).", hint: "The instance may be older than the feature; `cavelon status` shows its version." },