@cavelon/cli 0.1.5 → 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.
Files changed (42) hide show
  1. package/README.md +56 -18
  2. package/dist/command.js +10 -0
  3. package/dist/commands/api.js +40 -36
  4. package/dist/commands/chat.js +183 -0
  5. package/dist/commands/docs.js +77 -9
  6. package/dist/commands/fmt.js +61 -6
  7. package/dist/commands/index.js +3 -0
  8. package/dist/commands/init.js +61 -26
  9. package/dist/commands/inventory.js +21 -0
  10. package/dist/commands/limits-set.js +10 -6
  11. package/dist/commands/loops.js +22 -11
  12. package/dist/commands/models.js +11 -7
  13. package/dist/commands/sandboxes.js +11 -5
  14. package/dist/commands/schema.js +230 -48
  15. package/dist/commands/session.js +100 -14
  16. package/dist/commands/setup.js +22 -6
  17. package/dist/commands/solution.js +493 -86
  18. package/dist/commands/tenants.js +43 -10
  19. package/dist/commands/values.js +20 -11
  20. package/dist/commands/work.js +167 -33
  21. package/dist/confirm-token.js +72 -0
  22. package/dist/format.js +4 -4
  23. package/dist/harness-ref.js +17 -4
  24. package/dist/http.js +6 -0
  25. package/dist/kit-codes.js +11 -1
  26. package/dist/local-state.js +46 -10
  27. package/dist/main.js +38 -6
  28. package/dist/mcp.js +65 -14
  29. package/dist/openapi.js +30 -0
  30. package/dist/package-check.js +206 -18
  31. package/dist/package-files.js +98 -40
  32. package/dist/package-format.js +81 -8
  33. package/dist/package-references.js +77 -10
  34. package/dist/results.js +21 -1
  35. package/dist/session.js +9 -0
  36. package/dist/skills/cavelon-authoring/SKILL.md +54 -21
  37. package/dist/skills/cavelon-long-running/SKILL.md +13 -9
  38. package/dist/skills/cavelon-loop/SKILL.md +124 -28
  39. package/dist/skills/cavelon-testing/SKILL.md +69 -16
  40. package/dist/tenant-choice.js +19 -0
  41. package/dist/trace-view.js +172 -0
  42. package/package.json +1 -1
@@ -1,27 +1,31 @@
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
- import { checkModels, checkReferences, checkUnknownFields, DUPLICATE_CODE, FIELD_UNKNOWN_CODE, MODEL_UNKNOWN_CODE, REFERENCE_MISSING_CODE, REFERENCE_UNKNOWN_CODE, SEARCH_TOOL_KEYS, } from "./package-references.js";
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";
7
7
  export const SCHEMA_CODE = "package_schema_invalid";
8
8
  const ENDPOINT_LIMIT_CODE = "model_endpoint_limit_without_base_url";
9
9
  const ENDPOINT_LIMIT_NOT_CARRIED = "model_endpoint_limit_not_in_package_schema";
10
10
  const REGISTRY_SECTION = "model_registry";
11
11
  const ENDPOINT_LIMIT_FIELD = "max_concurrent_requests";
12
12
  const PACKAGE_DOCS = "/docs/reference/api-endpoints";
13
+ const IMPORT_DOCS = "/docs/concepts/harnesses#import-export-and-backup";
13
14
  const BRANCH_WIDTH_CODE = "branch_width_capped";
14
15
  const BRANCHES_SEQUENTIAL_CODE = "branches_run_in_sequence";
15
16
  const BRANCH_DOCS = "/docs/concepts/capacity-and-concurrency#branch-concurrency";
16
17
  const KB_WITHOUT_SEARCH_CODE = "knowledge_base_without_search_tool";
17
18
  const SEARCH_DOCS = "/docs/reference/builtin-tools#binding-knowledge-bases-to-search_documents";
18
19
  const SEARCH_TOOL = "search_documents";
20
+ const LIST_TOOL = "list_documents";
19
21
  const PERSONA_MESSAGE_CODE = "persona_message_empty";
20
22
  const PERSONA_DOCS = "/docs/concepts/personas";
21
23
  const PERSONA_MESSAGES = [
22
24
  { switch: "greeting_enabled", text: "greeting_message", what: "greeting", when: "when a conversation starts" },
23
25
  { switch: "fallback_message_enabled", text: "fallback_message", what: "fallback message", when: "when the assistant has no answer" },
24
26
  ];
27
+ const SOLUTION_MISMATCH_CODE = "solution_slug_mismatch";
28
+ const TENANT_WIDE_CODE = "tenant_wide_section";
25
29
  const ASSERTION_UNCHECKED_CODE = "test_assertion_unchecked";
26
30
  const TESTING_DOCS = "/docs/concepts/regression-testing";
27
31
  export const KIT_CODES = [
@@ -77,8 +81,9 @@ export const KIT_CODES = [
77
81
  {
78
82
  code: KB_WITHOUT_SEARCH_CODE,
79
83
  area: "package",
80
- message: "An agent is given knowledge bases, but no search tool reaches it, so it cannot read them.",
81
- hint: `A knowledge base reaches an agent only through a search tool: add \`- tool_slug: ${SEARCH_TOOL}\` to the tool_assignments of the skill that names the knowledge base, or of the agent. \`cavelon docs get reference/builtin-tools\` shows the binding.`,
84
+ message: "An agent is given knowledge bases, but no tool that searches or lists them reaches it, so it cannot read them.",
85
+ hint: `A knowledge base reaches an agent only through a built-in document tool: add \`- tool_slug: ${SEARCH_TOOL}\` (or ${LIST_TOOL}, with read_document to read ` +
86
+ "what it lists) to the tool_assignments of the skill that names the knowledge base, or of the agent. `cavelon docs get reference/builtin-tools` shows the binding.",
82
87
  docs: SEARCH_DOCS,
83
88
  },
84
89
  {
@@ -102,20 +107,21 @@ export const KIT_CODES = [
102
107
  area: "package",
103
108
  message: "Two entries of one section have the same key (slug, or name for a knowledge base).",
104
109
  hint: "Rename or remove one of them: the import keeps only one entry per key.",
105
- docs: PACKAGE_DOCS,
110
+ docs: IMPORT_DOCS,
106
111
  },
107
112
  {
108
113
  code: REFERENCE_MISSING_CODE,
109
114
  area: "package",
110
- message: "An agent hands off to an agent that is not in the package.",
111
- hint: "Fix the to_agent_slug (the finding suggests the closest slug), or add the agent to package/agents.yaml.",
115
+ message: "An agent hands off to an agent that is not in the package, or a test step's assertion (answered_by, handoff_to) names one.",
116
+ hint: "Fix the to_agent_slug or the assertion's value (the finding suggests the closest slug), or add the agent to package/agents.yaml.",
112
117
  docs: PACKAGE_DOCS,
113
118
  },
114
119
  {
115
120
  code: REFERENCE_UNKNOWN_CODE,
116
121
  area: "package",
117
- message: "A skill, tool, knowledge base or solution is named that is neither in the package nor among what the tenant held at the last pull.",
118
- hint: "Fix the name (the finding suggests the closest one), or add the entry to the package. If it was created on the instance since, `cavelon pull` refreshes the list in .cavelon/inventory.json.",
122
+ message: "A skill, tool, knowledge base or solution is named (by an agent, a skill or a test step's assertion) that is neither in the package nor among what the tenant held at the last pull.",
123
+ hint: "Fix the name (the finding suggests the closest one), or add the entry to the package. The import preview blocks a reference it cannot resolve, " +
124
+ "so validate --strict fails on it. If it was created on the instance since, `cavelon pull` refreshes the list in .cavelon/inventory.json.",
119
125
  docs: PACKAGE_DOCS,
120
126
  },
121
127
  {
@@ -123,13 +129,30 @@ export const KIT_CODES = [
123
129
  area: "package",
124
130
  message: "A package file sets a field this instance's package schema does not have; the import ignores it.",
125
131
  hint: "Check the field name for a typo (the finding suggests the closest field); a field from a newer instance is ignored by this one.",
126
- docs: PACKAGE_DOCS,
132
+ docs: IMPORT_DOCS,
127
133
  },
128
134
  {
129
135
  code: MODEL_UNKNOWN_CODE,
130
136
  area: "package",
131
137
  message: "An agent's llm_model is not in the tenant's model list as the kit last read it.",
132
- hint: "Fix the model id (the finding suggests the closest one), or register the model. `cavelon models list` shows the tenant's models and refreshes the list validate checks against.",
138
+ hint: "Fix the model id (the finding suggests the closest one), or register the model: the import preview blocks a model the tenant does not have. " +
139
+ "`cavelon models list` shows the tenant's models and refreshes the list validate checks against.",
140
+ docs: PACKAGE_DOCS,
141
+ },
142
+ {
143
+ code: SOLUTION_MISMATCH_CODE,
144
+ area: "package",
145
+ message: "The package names another solution than cavelon.yaml: harnesses.yaml's slug, or an entry's harness_slug.",
146
+ hint: "After copying a solution under another name, change the slug in package/harnesses.yaml and every harness_slug to the one cavelon.yaml names " +
147
+ "(or set harness in cavelon.yaml to the package's); the import otherwise works on the solution the package names.",
148
+ docs: PACKAGE_DOCS,
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.",
133
156
  docs: PACKAGE_DOCS,
134
157
  },
135
158
  {
@@ -140,6 +163,9 @@ export const KIT_CODES = [
140
163
  docs: PACKAGE_DOCS,
141
164
  },
142
165
  ];
166
+ function findingEntry(catalog, code) {
167
+ return catalog?.rule_codes?.find((e) => e.code === code) ?? KIT_CODES.find((e) => e.code === code) ?? catalog?.api_error_codes?.find((e) => e.code === code);
168
+ }
143
169
  export function catalogEntry(catalog, code) {
144
170
  const rule = catalog?.rule_codes?.find((e) => e.code === code);
145
171
  if (rule)
@@ -252,15 +278,32 @@ export function checkPackage(disk, options) {
252
278
  const validate = compile(options.schema);
253
279
  if (!validate(disk.package)) {
254
280
  const seen = new Set();
255
- for (const error of closestBranchErrors(validate.errors ?? [])) {
281
+ const errors = validate.errors ?? [];
282
+ const misnamed = misnamedVariants(options.schema, disk.package).filter((m) => errors.some((e) => within(e.instancePath, m.pointer)));
283
+ for (const m of misnamed) {
284
+ findings.push({
285
+ code: SCHEMA_CODE,
286
+ severity: "error",
287
+ ...locate(disk, `${m.pointer}/${m.field}`),
288
+ message: `${m.field} "${m.value}" is none of the types this field takes (${m.allowed.join(", ")}).` + (m.suggestion ? ` Did you mean "${m.suggestion}"?` : ""),
289
+ ...(m.suggestion ? { suggestion: m.suggestion } : {}),
290
+ hint: schemaHint(disk.package, m.pointer),
291
+ });
292
+ }
293
+ const unreadable = new Set(disk.unreadable ?? []);
294
+ for (const error of closestBranchErrors(errors)) {
256
295
  if (error.keyword === "anyOf" || error.keyword === "oneOf")
257
296
  continue;
297
+ if (misnamed.some((m) => within(error.instancePath, m.pointer)))
298
+ continue;
299
+ if (error.keyword === "required" && error.instancePath === "" && unreadable.has(String(error.params.missingProperty)))
300
+ continue;
258
301
  const { pointer, message } = describe(error);
259
302
  const key = `${pointer} ${message}`;
260
303
  if (seen.has(key))
261
304
  continue;
262
305
  seen.add(key);
263
- findings.push({ code: SCHEMA_CODE, severity: "error", ...locate(disk, pointer), message });
306
+ findings.push({ code: SCHEMA_CODE, severity: "error", ...locate(disk, pointer), message, hint: schemaHint(disk.package, pointer) });
264
307
  }
265
308
  }
266
309
  findings.push(...checkEndpointLimits(disk, options.schema));
@@ -271,8 +314,10 @@ export function checkPackage(disk, options) {
271
314
  findings.push(...checkModels(disk, options.inventory));
272
315
  findings.push(...checkPersonaMessages(disk, options.schema));
273
316
  findings.push(...checkUncheckedAssertions(disk, options.schema));
317
+ findings.push(...checkSolutionSlug(disk, options.solution));
318
+ findings.push(...checkTenantWide(disk, options.schema, options.solution));
274
319
  for (const finding of findings) {
275
- const entry = catalogEntry(options.catalog, finding.code);
320
+ const entry = findingEntry(options.catalog, finding.code);
276
321
  if (!entry)
277
322
  continue;
278
323
  finding.hint ??= entry.hint ?? undefined;
@@ -394,9 +439,9 @@ const active = (e) => e.is_active !== false;
394
439
  const quoted = (names) => names.map((n) => `"${n}"`).join(", ");
395
440
  function checkKnowledgeSearch(disk) {
396
441
  const pkg = disk.package;
397
- const searchSlugs = new Set(SEARCH_TOOL_KEYS);
442
+ const searchSlugs = new Set(KNOWLEDGE_TOOL_KEYS);
398
443
  for (const tool of asList(pkg.tools)) {
399
- if (typeof tool.slug === "string" && typeof tool.builtin_key === "string" && SEARCH_TOOL_KEYS.has(tool.builtin_key))
444
+ if (typeof tool.slug === "string" && typeof tool.builtin_key === "string" && KNOWLEDGE_TOOL_KEYS.has(tool.builtin_key))
400
445
  searchSlugs.add(tool.slug);
401
446
  }
402
447
  const searches = (assignments) => asList(assignments).some((a) => active(a) && typeof a.tool_slug === "string" && searchSlugs.has(a.tool_slug));
@@ -449,8 +494,8 @@ function checkKnowledgeSearch(disk) {
449
494
  severity: "warning",
450
495
  ...locate(disk, first.pointer),
451
496
  message: `The agent${agentName} is given the knowledge base${names.length === 1 ? "" : "s"} ${quoted(names)}` +
452
- `${first.via ? ` through the skill "${first.via}"` : ""}, but no search tool reaches it, so it cannot search ${names.length === 1 ? "it" : "them"}: ` +
453
- `add ${SEARCH_TOOL} to the ${first.via ? "skill's" : "agent's"} tool_assignments.`,
497
+ `${first.via ? ` through the skill "${first.via}"` : ""}, but no tool that searches or lists ${names.length === 1 ? "it" : "them"} reaches the agent, ` +
498
+ `so it cannot read ${names.length === 1 ? "it" : "them"}: add ${SEARCH_TOOL} (or ${LIST_TOOL}) to the ${first.via ? "skill's" : "agent's"} tool_assignments.`,
454
499
  });
455
500
  });
456
501
  return findings;
@@ -529,3 +574,146 @@ function checkPersonaMessages(disk, schema) {
529
574
  }
530
575
  return findings;
531
576
  }
577
+ const within = (pointer, outer) => pointer === outer || pointer.startsWith(`${outer}/`);
578
+ export function schemaPathOf(pkg, pointer) {
579
+ const keys = pointer.split("/").slice(1).map((k) => k.replace(/~1/g, "/").replace(/~0/g, "~"));
580
+ let value = pkg;
581
+ const names = [];
582
+ for (const key of keys) {
583
+ const inner = Array.isArray(value) ? value[Number(key)] : asObject(value)?.[key];
584
+ if (inner === undefined || inner === null || typeof inner !== "object")
585
+ break;
586
+ if (!Array.isArray(value))
587
+ names.push(key);
588
+ value = inner;
589
+ }
590
+ return names.join(".");
591
+ }
592
+ function schemaHint(pkg, pointer) {
593
+ const at = schemaPathOf(pkg, pointer);
594
+ return at
595
+ ? `Fix the field the finding names; \`cavelon schema ${at}\` lists the fields there (type, required, allowed values) with a minimal entry.`
596
+ : "Fix the field the finding names; `cavelon schema` lists the sections, and `cavelon schema <section>` their fields.";
597
+ }
598
+ const propertiesIn = (node) => asObject(node.properties);
599
+ function listedValues(schema, node) {
600
+ const values = [];
601
+ for (const branch of branches(schema, node)) {
602
+ if ("const" in branch)
603
+ values.push(branch.const);
604
+ else if (Array.isArray(branch.enum))
605
+ values.push(...branch.enum);
606
+ else if (branch.type !== "null")
607
+ return undefined;
608
+ }
609
+ return values.length ? values : undefined;
610
+ }
611
+ function misnamedVariants(schema, pkg) {
612
+ const found = [];
613
+ const walk = (value, node, pointer, depth) => {
614
+ if (depth > 40)
615
+ return;
616
+ if (Array.isArray(value)) {
617
+ const items = branches(schema, node).map((b) => b.items).find((i) => i !== undefined);
618
+ if (items !== undefined)
619
+ value.forEach((item, i) => walk(item, items, `${pointer}/${i}`, depth + 1));
620
+ return;
621
+ }
622
+ const object = asObject(value);
623
+ if (!object)
624
+ return;
625
+ const shapes = branches(schema, node).filter((b) => propertiesIn(b));
626
+ if (shapes.length > 1) {
627
+ for (const [field, given] of Object.entries(object)) {
628
+ if (typeof given !== "string")
629
+ continue;
630
+ const defining = shapes.filter((shape) => propertiesIn(shape)[field] !== undefined);
631
+ if (defining.length < 2)
632
+ continue;
633
+ const lists = defining.map((shape) => listedValues(schema, propertiesIn(shape)[field]));
634
+ if (lists.some((l) => l === undefined))
635
+ continue;
636
+ const allowed = [...new Set(lists.flat().filter((v) => typeof v === "string"))];
637
+ if (allowed.includes(given)) {
638
+ const shape = defining.find((_, i) => lists[i].includes(given));
639
+ for (const [key, inner] of Object.entries(object)) {
640
+ const sub = propertiesIn(shape)[key];
641
+ if (sub !== undefined)
642
+ walk(inner, sub, `${pointer}/${key}`, depth + 1);
643
+ }
644
+ return;
645
+ }
646
+ found.push({ pointer, field, value: given, allowed: allowed.sort((a, b) => a.localeCompare(b, "en")), suggestion: closest(given, allowed) });
647
+ return;
648
+ }
649
+ }
650
+ const shape = shapes.length === 1 ? shapes[0] : undefined;
651
+ if (!shape)
652
+ return;
653
+ for (const [key, inner] of Object.entries(object)) {
654
+ const sub = propertiesIn(shape)[key];
655
+ if (sub !== undefined)
656
+ walk(inner, sub, `${pointer}/${key}`, depth + 1);
657
+ }
658
+ };
659
+ const sections = asObject(schema.properties) ?? {};
660
+ for (const [section, value] of Object.entries(pkg))
661
+ if (section in sections)
662
+ walk(value, sections[section], `/${section}`, 0);
663
+ return found;
664
+ }
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
+ }
684
+ function checkSolutionSlug(disk, solution) {
685
+ if (!solution || UUID.test(solution))
686
+ return [];
687
+ const pkg = disk.package;
688
+ const harnesses = asList(pkg.harnesses);
689
+ const own = harnesses.find((h) => h.slug === solution || h.name === solution);
690
+ const slug = typeof own?.slug === "string" ? own.slug : solution;
691
+ const findings = [];
692
+ if (harnesses.length && !own) {
693
+ const named = harnesses.map((h) => h.slug).filter((v) => typeof v === "string");
694
+ findings.push({
695
+ code: SOLUTION_MISMATCH_CODE,
696
+ severity: "warning",
697
+ ...locate(disk, "/harnesses/0/slug"),
698
+ message: `cavelon.yaml names the solution "${solution}", and the package's harnesses name ${quoted(named)}: ` +
699
+ `rename the slug (and every harness_slug) to "${solution}", or set harness in cavelon.yaml to the package's.`,
700
+ });
701
+ }
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"]) {
704
+ const entries = asList(pkg[section]);
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 }] : []));
707
+ if (!off.length)
708
+ continue;
709
+ const names = [...new Set(off.map((o) => o.name))];
710
+ findings.push({
711
+ code: SOLUTION_MISMATCH_CODE,
712
+ severity: "warning",
713
+ ...locate(disk, `/${section}/${off[0].i}/harness_slug`),
714
+ message: `${off.length} of the ${section} name${off.length === 1 ? "s" : ""} the solution ${quoted(names)} in harness_slug, and cavelon.yaml names "${slug}": ` +
715
+ `set harness_slug to "${slug}".`,
716
+ });
717
+ }
718
+ return findings;
719
+ }
@@ -1,10 +1,10 @@
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
- import { PERSONA_SECTION, sameSectionValue, sectionContent, sectionFields, toYaml, withoutNulls } from "./package-format.js";
7
- export { toYaml };
6
+ import { canonical, PERSONA_SECTION, sameEntry, sameSectionValue, sectionContent, sectionFields, toYaml } from "./package-format.js";
7
+ export { canonical, toYaml };
8
8
  export const DEFAULT_LAYOUT = { package: "package", items: {} };
9
9
  const PACKAGE_FILE = /\.(ya?ml|json)$/i;
10
10
  export function layoutFrom(raw) {
@@ -36,6 +36,15 @@ export function defaultLayoutFor(schema) {
36
36
  export function schemaSections(schema) {
37
37
  return Object.keys(schema?.properties ?? {});
38
38
  }
39
+ const SCOPE_KEY = "x-cavelon-scope";
40
+ const TENANT_WIDE_UNMARKED = ["tenant_settings", "model_registry"];
41
+ export function tenantWideSections(schema) {
42
+ const properties = (schema?.properties ?? {});
43
+ const marked = Object.entries(properties).filter(([, node]) => node && typeof node[SCOPE_KEY] === "string");
44
+ if (marked.length)
45
+ return new Set(marked.filter(([, node]) => node[SCOPE_KEY] === "tenant").map(([section]) => section));
46
+ return new Set(TENANT_WIDE_UNMARKED.filter((section) => section in properties));
47
+ }
39
48
  function rel(root, file) {
40
49
  return path.relative(root, file).split(path.sep).join("/");
41
50
  }
@@ -92,6 +101,27 @@ async function exists(dir) {
92
101
  return false;
93
102
  }
94
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
+ }
95
125
  function parseFile(root, file, text) {
96
126
  const relative = rel(root, file);
97
127
  if (/\.json$/i.test(file)) {
@@ -115,7 +145,7 @@ function parseFile(root, file, text) {
115
145
  code: "package_file_invalid",
116
146
  severity: "error",
117
147
  file: relative,
118
- line: first.linePos?.[0]?.line,
148
+ line: errorLine(text, first, lines),
119
149
  message: `Not valid YAML: ${first.message.split("\n")[0]}`,
120
150
  },
121
151
  };
@@ -126,6 +156,7 @@ export async function readPackage(root, layout) {
126
156
  const pkg = {};
127
157
  const sources = {};
128
158
  const findings = [];
159
+ const unreadable = new Set();
129
160
  const dir = path.join(root, layout.package);
130
161
  let empty = true;
131
162
  for (const name of await listFiles(dir)) {
@@ -144,6 +175,7 @@ export async function readPackage(root, layout) {
144
175
  if ("finding" in read) {
145
176
  sources[section] = { file: rel(root, file) };
146
177
  findings.push(read.finding);
178
+ unreadable.add(section);
147
179
  empty = false;
148
180
  continue;
149
181
  }
@@ -152,8 +184,10 @@ export async function readPackage(root, layout) {
152
184
  if (!parsed.finding && section === PERSONA_SECTION && (parsed.value === null || parsed.value === undefined))
153
185
  continue;
154
186
  empty = false;
155
- if (parsed.finding)
187
+ if (parsed.finding) {
156
188
  findings.push(parsed.finding);
189
+ unreadable.add(section);
190
+ }
157
191
  else
158
192
  pkg[section] = parsed.value;
159
193
  }
@@ -181,21 +215,23 @@ export async function readPackage(root, layout) {
181
215
  const file = path.join(itemDir, name);
182
216
  const read = await readSource(root, file);
183
217
  if ("finding" in read) {
184
- itemSources.push({ file: rel(root, file) });
185
218
  findings.push(read.finding);
219
+ unreadable.add(section);
186
220
  continue;
187
221
  }
188
222
  const parsed = parseFile(root, file, read.text);
189
- itemSources.push(parsed.source);
190
- if (parsed.finding)
223
+ if (parsed.finding) {
191
224
  findings.push(parsed.finding);
192
- else
193
- items.push(parsed.value);
225
+ unreadable.add(section);
226
+ continue;
227
+ }
228
+ itemSources.push(parsed.source);
229
+ items.push(parsed.value);
194
230
  }
195
231
  sources[section] = itemSources;
196
232
  pkg[section] = items;
197
233
  }
198
- return { package: pkg, sources, findings, empty };
234
+ return { package: pkg, sources, findings, empty, unreadable: [...unreadable] };
199
235
  }
200
236
  export function locate(disk, pointer) {
201
237
  const keys = pointer
@@ -239,14 +275,6 @@ function lineOf(source, keys) {
239
275
  export function safeSectionName(section) {
240
276
  return /^[A-Za-z0-9][A-Za-z0-9_.-]{0,99}$/.test(section) && !section.includes("..");
241
277
  }
242
- export function canonical(value) {
243
- return JSON.stringify(value, (_key, v) => {
244
- if (v && typeof v === "object" && !Array.isArray(v)) {
245
- return Object.fromEntries(Object.entries(v).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
246
- }
247
- return v;
248
- });
249
- }
250
278
  async function readValue(root, file) {
251
279
  const target = await contentPath(root, file);
252
280
  const text = target === undefined ? undefined : await readTextFile(target);
@@ -267,9 +295,12 @@ export async function placeholdersOnly(root, relative) {
267
295
  const old = await readValue(root, path.join(root, relative));
268
296
  return old.ok && (old.value === null || old.value === undefined);
269
297
  }
270
- function itemFileName(item, index, taken) {
298
+ export function entryLabel(item) {
271
299
  const record = item && typeof item === "object" && !Array.isArray(item) ? item : {};
272
- const label = [record.slug, record.name, record.key].find((v) => typeof v === "string" && v.trim() !== "");
300
+ return [record.slug, record.name, record.key].find((v) => typeof v === "string" && v.trim() !== "");
301
+ }
302
+ function itemFileName(item, index, taken) {
303
+ const label = entryLabel(item);
273
304
  const base = trimDashesAndDots((label ?? `item-${index + 1}`)
274
305
  .toLowerCase()
275
306
  .normalize("NFKD")
@@ -283,7 +314,8 @@ function itemFileName(item, index, taken) {
283
314
  }
284
315
  export async function writePackage(root, layout, pkg, schema, options = {}) {
285
316
  const dryRun = options.dryRun === true;
286
- const report = { written: [], unchanged: [], removed: [], kept: [], refused: [] };
317
+ const skip = options.skip ?? new Set();
318
+ const report = { written: [], unchanged: [], removed: [], kept: [], refused: [], tenant_wide: [] };
287
319
  const known = new Set(schemaSections(schema));
288
320
  const required = new Set(schema?.required ?? []);
289
321
  const dir = path.join(root, layout.package);
@@ -297,6 +329,10 @@ export async function writePackage(root, layout, pkg, schema, options = {}) {
297
329
  if (!(PERSONA_SECTION in pkg) && sectionFields(schema, PERSONA_SECTION))
298
330
  sections.push([PERSONA_SECTION, null]);
299
331
  for (const [section, value] of sections) {
332
+ if (skip.has(section)) {
333
+ report.tenant_wide.push(section);
334
+ continue;
335
+ }
300
336
  if (section in layout.items && Array.isArray(value))
301
337
  continue;
302
338
  if (!safeSectionName(section)) {
@@ -306,42 +342,58 @@ export async function writePackage(root, layout, pkg, schema, options = {}) {
306
342
  const current = existing.get(section);
307
343
  const file = path.join(dir, current ?? `${section}.yaml`);
308
344
  const old = await readValue(root, file);
309
- if (old.ok && sameSectionValue(section, old.value, value, canonical))
345
+ if (old.ok && sameSectionValue(section, old.value, value, schema))
310
346
  same.push({ file, section });
311
347
  else
312
348
  plans.push({ file, section, content: sectionContent(section, value, schema, /\.json$/i.test(file)) });
313
349
  }
314
350
  for (const [section, folder] of Object.entries(layout.items)) {
315
351
  const value = pkg[section];
316
- if (!Array.isArray(value))
352
+ if (!Array.isArray(value) || skip.has(section))
317
353
  continue;
318
354
  const itemDir = path.join(root, folder);
355
+ const names = await listFiles(itemDir);
319
356
  const before = new Map();
320
- for (const name of await listFiles(itemDir)) {
357
+ for (const name of names) {
321
358
  const old = await readValue(root, path.join(itemDir, name));
322
359
  if (old.ok)
323
360
  before.set(name, old.value);
324
361
  }
325
362
  const taken = new Set();
326
- const unclaimed = new Map(before);
327
- const placed = value.map((item) => {
328
- for (const [name, old] of unclaimed) {
329
- if (canonical(withoutNulls(old)) === canonical(withoutNulls(item))) {
330
- unclaimed.delete(name);
331
- taken.add(name);
332
- return name;
333
- }
334
- }
335
- return undefined;
363
+ const claim = (name) => {
364
+ taken.add(name);
365
+ return name;
366
+ };
367
+ const holding = value.map((item) => {
368
+ const name = [...before].find(([name, old]) => !taken.has(name) && sameEntry(section, old, item, schema))?.[0];
369
+ return name && claim(name);
336
370
  });
371
+ const recorded = options.itemFiles?.[section] ?? {};
372
+ const home = value.map((item, index) => {
373
+ if (holding[index])
374
+ return holding[index];
375
+ const label = entryLabel(item);
376
+ if (label === undefined)
377
+ return undefined;
378
+ const byName = [...before].find(([name, old]) => !taken.has(name) && entryLabel(old) === label)?.[0];
379
+ if (byName)
380
+ return claim(byName);
381
+ const last = recorded[label];
382
+ return last && !taken.has(last) && names.includes(last) && !before.has(last) ? claim(last) : undefined;
383
+ });
384
+ const placedHere = {};
337
385
  value.forEach((item, index) => {
338
- const name = placed[index];
339
- if (name) {
386
+ const name = home[index] ?? itemFileName(item, index, taken);
387
+ const label = entryLabel(item);
388
+ if (label !== undefined)
389
+ placedHere[label] = name;
390
+ if (holding[index])
340
391
  same.push({ file: path.join(itemDir, name), section });
341
- return;
342
- }
343
- plans.push({ file: path.join(itemDir, itemFileName(item, index, taken)), section, content: toYaml(item) });
392
+ else
393
+ plans.push({ file: path.join(itemDir, name), section, content: toYaml(item) });
344
394
  });
395
+ if (options.placed)
396
+ options.placed[section] = placedHere;
345
397
  for (const name of before.keys())
346
398
  if (!taken.has(name))
347
399
  removals.push(path.join(itemDir, name));
@@ -349,6 +401,12 @@ export async function writePackage(root, layout, pkg, schema, options = {}) {
349
401
  await fs.mkdir(itemDir, { recursive: true });
350
402
  }
351
403
  for (const [section, name] of existing) {
404
+ if (skip.has(section)) {
405
+ if (!report.tenant_wide.includes(section))
406
+ report.tenant_wide.push(section);
407
+ report.kept.push(rel(root, path.join(dir, name)));
408
+ continue;
409
+ }
352
410
  if (section in pkg || section === PERSONA_SECTION)
353
411
  continue;
354
412
  const file = path.join(dir, name);