@cavelon/cli 0.1.1 → 0.1.3

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 (52) hide show
  1. package/README.md +50 -20
  2. package/dist/agents.js +43 -19
  3. package/dist/choose.js +112 -0
  4. package/dist/command.js +1 -1
  5. package/dist/commands/api.js +76 -6
  6. package/dist/commands/index.js +2 -0
  7. package/dist/commands/init.js +196 -29
  8. package/dist/commands/limits-set.js +17 -8
  9. package/dist/commands/limits.js +2 -2
  10. package/dist/commands/loops.js +12 -6
  11. package/dist/commands/sandboxes.js +27 -20
  12. package/dist/commands/session.js +179 -45
  13. package/dist/commands/setup.js +426 -0
  14. package/dist/commands/solution.js +137 -91
  15. package/dist/commands/tenants.js +33 -22
  16. package/dist/commands/values.js +8 -5
  17. package/dist/commands/work.js +33 -16
  18. package/dist/context.js +5 -1
  19. package/dist/contracts.js +83 -38
  20. package/dist/embedded.js +7 -0
  21. package/dist/features.js +15 -0
  22. package/dist/fsutil.js +3 -0
  23. package/dist/git.js +14 -9
  24. package/dist/harness-ref.js +54 -0
  25. package/dist/http.js +44 -18
  26. package/dist/install.js +94 -0
  27. package/dist/invoke.js +17 -13
  28. package/dist/limits.js +9 -1
  29. package/dist/local-state.js +18 -0
  30. package/dist/main.js +31 -2
  31. package/dist/markers.js +53 -0
  32. package/dist/mcp.js +9 -2
  33. package/dist/openapi.js +10 -0
  34. package/dist/operations.js +1 -1
  35. package/dist/package-check.js +1 -1
  36. package/dist/package-files.js +103 -38
  37. package/dist/paths.js +53 -4
  38. package/dist/principal.js +43 -0
  39. package/dist/project.js +23 -4
  40. package/dist/prompt.js +55 -11
  41. package/dist/results.js +47 -9
  42. package/dist/run-program.js +92 -0
  43. package/dist/session.js +100 -19
  44. package/dist/setup-agents.js +544 -0
  45. package/dist/skills/cavelon-authoring/SKILL.md +13 -3
  46. package/dist/skills/cavelon-long-running/SKILL.md +5 -1
  47. package/dist/skills/cavelon-loop/SKILL.md +15 -9
  48. package/dist/skills/cavelon-testing/SKILL.md +9 -2
  49. package/dist/tenant-choice.js +93 -0
  50. package/dist/update-check.js +118 -0
  51. package/dist/version.js +2 -1
  52. package/package.json +5 -2
@@ -8,8 +8,9 @@ import { clip, keyValues } from "../format.js";
8
8
  import { readTextFile, writeFileAtomic } from "../fsutil.js";
9
9
  import { uncommitted } from "../git.js";
10
10
  import { callStable } from "../invoke.js";
11
+ import { harnessNotFoundError, lookupHarness } from "../harness-ref.js";
11
12
  import { ceilingHint, LIMIT_ABOVE_CEILING, parseLimits, readLimits } from "../limits.js";
12
- import { deletePreview, digest, listPreviews, loadPreview, savePreview, writeState, } from "../local-state.js";
13
+ import { deletePreview, digest, fileDigest, listPreviews, loadPreview, readPulledFiles, savePreview, writePulledFiles, writeState, } from "../local-state.js";
13
14
  import { catalogEntry, checkPackage, KIT_CODES, packageVersionOf } from "../package-check.js";
14
15
  import { pairOrderHint, pairOrderPointer } from "../pair-order.js";
15
16
  import { readPackage, writePackage } from "../package-files.js";
@@ -19,14 +20,14 @@ import { listedPages } from "./docs.js";
19
20
  import { writeInventory } from "./inventory.js";
20
21
  import { cavelonCommand, shellWord } from "../shell.js";
21
22
  import { secretSetCommand, targetFlags, variableSetCommand } from "./values.js";
22
- const HARNESS_OPTION = { type: "string", value: "<slug>", description: "The solution (harness); default: env file, then cavelon.yaml." };
23
+ const HARNESS_OPTION = { type: "string", value: "<harness>", description: "The solution (harness): its name, slug or id; default: env file, then cavelon.yaml." };
23
24
  const ENV_OPTION = { type: "string", value: "<name>", description: "Use env/<name>.yaml: its tenant, solution and runtime bindings." };
24
25
  export function requireSolution(session) {
25
26
  if (!session.project) {
26
27
  throw new CavelonError(ExitCode.usage, {
27
28
  code: "no_solution",
28
29
  message: "This folder is not a Cavelon solution (no cavelon.yaml here or above).",
29
- hint: "Run `cavelon init` for a new solution, then `cavelon pull --harness <slug>` for an existing one.",
30
+ hint: "Run `cavelon init`: it asks which solution, or a new one, on a terminal. `cavelon harness list` shows the solutions.",
30
31
  });
31
32
  }
32
33
  return session.project;
@@ -41,64 +42,70 @@ function harnessRef(session, input) {
41
42
  return { ref: session.project.harness, source: "cavelon.yaml" };
42
43
  return {};
43
44
  }
44
- async function findHarness(ctx, ref) {
45
- if (isUuid(ref)) {
46
- try {
47
- return await callStable(ctx, "GET", "/api/v1/harnesses/{harness_id}", "reading solutions", { params: { harness_id: [ref] } });
48
- }
49
- catch (error) {
50
- if (error instanceof CavelonError && error.status === 404)
51
- return undefined;
52
- throw error;
53
- }
54
- }
45
+ async function findHarness(ctx, ref, source) {
46
+ const { harness, candidates } = await lookupHarness(ctx, ref);
47
+ if (!harness)
48
+ throw harnessNotFoundError(ref, candidates, source);
49
+ return harness;
50
+ }
51
+ async function cachedFirst(ctx, what, cached, offline, fetch) {
52
+ if (cached && (offline || !cached.stale))
53
+ return { value: cached.value, source: "cache" };
54
+ if (offline)
55
+ return { value: null, source: "none" };
55
56
  try {
56
- return await callStable(ctx, "GET", "/api/v1/harnesses/by-slug/{slug}", "finding solutions by slug", { params: { slug: [ref] } });
57
+ const value = await fetch();
58
+ if (value === null && cached)
59
+ return { value: cached.value, source: "cache" };
60
+ return { value, source: "instance" };
57
61
  }
58
62
  catch (error) {
59
- if (error instanceof CavelonError && error.status === 404)
60
- return undefined;
61
- throw error;
63
+ if (!cached)
64
+ throw error;
65
+ ctx.warn(`Could not read the ${what} again from the instance (${error instanceof Error ? error.message : String(error)}); ` +
66
+ `using the copy cached at ${cached.fetched_at ?? "an unknown time"} for development build ${cached.version}.`);
67
+ return { value: cached.value, source: "cache" };
62
68
  }
63
69
  }
64
- function harnessNotFound(ref, source) {
65
- return new CavelonError(ExitCode.failure, {
66
- code: "solution_not_found",
67
- message: `No solution "${ref}" in this tenant${source ? ` (from ${source})` : ""}.`,
68
- hint: "`cavelon harness list` shows them; `cavelon harness new <slug>` creates one, and an env file's harness is created by `apply`.",
69
- });
70
- }
71
70
  export async function schemaFor(ctx, version, offline) {
72
71
  const contracts = await ctx.contracts();
73
- const wanted = version ?? (await contracts.cachedOnly("capabilities.json"))?.value?.contracts?.package_versions?.current;
74
- if (wanted) {
75
- const cached = await contracts.cachedOnly(Contracts.packageSchemaFile(wanted));
76
- if (cached)
77
- return { schema: cached.value, source: "cache" };
78
- }
79
- if (offline)
80
- return { schema: null, source: "none" };
81
- return { schema: await contracts.packageSchema(wanted), source: "instance" };
72
+ let wanted = version ?? (await contracts.cachedOnly("capabilities.json"))?.value?.contracts?.package_versions?.current;
73
+ const cached = wanted ? await contracts.cachedOnly(Contracts.packageSchemaFile(wanted)) : undefined;
74
+ const { value: schema, source } = await cachedFirst(ctx, "package schema", cached, offline, async () => {
75
+ wanted ??= (await contracts.capabilities())?.contracts?.package_versions?.current;
76
+ return contracts.packageSchema(wanted);
77
+ });
78
+ const copy = source === "instance" && schema ? await contracts.cachedOnly(Contracts.packageSchemaFile(wanted ?? "current")) : source === "cache" ? cached : undefined;
79
+ return {
80
+ schema,
81
+ used: {
82
+ package_version: schema?.["x-package-version"] ?? wanted ?? null,
83
+ source: schema ? source : "none",
84
+ instance_version: copy?.version ?? null,
85
+ fetched_at: copy?.fetched_at ?? null,
86
+ etag: copy?.etag ?? null,
87
+ sha256: copy?.sha256 ?? null,
88
+ stale: copy?.stale ?? false,
89
+ },
90
+ };
82
91
  }
83
92
  export async function catalogFor(ctx, offline) {
84
93
  const contracts = await ctx.contracts();
85
94
  const cached = await contracts.cachedOnly("error-catalog.json");
86
- if (cached || offline)
87
- return cached?.value ?? null;
88
- return contracts.errorCatalog().catch(() => null);
95
+ return (await cachedFirst(ctx, "error catalog", cached, offline, () => contracts.errorCatalog()).catch(() => ({ value: null }))).value;
89
96
  }
90
- async function limitsFor(ctx, offline) {
97
+ async function capabilitiesFor(ctx, offline) {
91
98
  const contracts = await ctx.contracts();
92
99
  const cached = await contracts.cachedOnly("capabilities.json");
93
- if (cached || offline)
94
- return cached ? parseLimits(cached.value) : undefined;
95
- const live = await contracts.capabilities().catch(() => null);
96
- return live ? parseLimits(live) : undefined;
100
+ const read = () => contracts.capabilities();
101
+ return (await cachedFirst(ctx, "capabilities", cached, offline, read).catch(() => ({ value: null }))).value;
97
102
  }
98
- async function acceptedVersions(ctx) {
99
- const contracts = await ctx.contracts();
100
- const cached = await contracts.cachedOnly("capabilities.json");
101
- return cached?.value?.contracts?.package_versions?.accepted;
103
+ async function limitsFor(ctx, offline) {
104
+ const caps = await capabilitiesFor(ctx, offline);
105
+ return caps ? parseLimits(caps) : undefined;
106
+ }
107
+ async function acceptedVersions(ctx, offline) {
108
+ return (await capabilitiesFor(ctx, offline))?.contracts?.package_versions?.accepted;
102
109
  }
103
110
  function findingLine(f) {
104
111
  const where = f.file ? `${f.file}${f.line ? `:${f.line}` : ""}` : "";
@@ -113,19 +120,39 @@ export async function setProjectKey(project, key, value) {
113
120
  doc.set(key, value);
114
121
  await writeFileAtomic(project.file, doc.toString({ lineWidth: 0 }));
115
122
  }
123
+ function uncommittedChanges(files, what) {
124
+ return new CavelonError(ExitCode.conflict, {
125
+ code: "uncommitted_changes",
126
+ message: `${what}: ${files.slice(0, 5).join(", ")}${files.length > 5 ? ` and ${files.length - 5} more` : ""}.`,
127
+ hint: "Commit them first (then resolve the difference in git), apply them with `cavelon apply`, or pass --force to discard them.",
128
+ details: { files },
129
+ });
130
+ }
131
+ async function editedSincePull(project, pkg, schema) {
132
+ const planned = await writePackage(project.root, project.layout, pkg, schema, { dryRun: true });
133
+ const pulled = await readPulledFiles(project.root);
134
+ const edited = [];
135
+ for (const file of [...planned.written, ...planned.removed]) {
136
+ const current = await fileDigest(path.join(project.root, file));
137
+ if (current !== undefined && current !== pulled[file])
138
+ edited.push(file);
139
+ }
140
+ return edited.sort((a, b) => a.localeCompare(b, "en"));
141
+ }
116
142
  export const pull = {
117
143
  name: "pull",
118
144
  summary: "Write the instance's package into package/ (split along the schema's sections) and the inventory into .cavelon/.",
119
145
  description: "With a solution (--harness, or cavelon.yaml's harness), exports that solution; without one, the tenant's full configuration.\n" +
120
146
  "A file whose content did not change keeps its bytes, so `git diff` shows what changed on the instance. Files of sections\n" +
121
- "the schema does not know are kept byte for byte. Refuses when package files have uncommitted changes, unless --force.",
147
+ "the schema does not know are kept byte for byte. Refuses when package files have uncommitted changes, unless --force;\n" +
148
+ "outside a git repository, when a file it would overwrite or remove changed since the last pull.",
122
149
  readOnly: false,
123
150
  destructive: true,
124
151
  idempotent: true,
125
152
  mcpTool: "pull",
126
153
  options: {
127
- harness: { type: "string", value: "<slug>", description: "The solution to export; recorded in cavelon.yaml when it names none." },
128
- force: { type: "boolean", description: "Overwrite package files that have uncommitted changes." },
154
+ harness: { type: "string", value: "<harness>", description: "The solution to export, by name, slug or id; its slug is recorded in cavelon.yaml when it names none." },
155
+ force: { type: "boolean", description: "Overwrite package files that have uncommitted changes (outside git: changes since the last pull)." },
129
156
  },
130
157
  examples: ["cavelon pull --harness support", "cavelon pull && git diff -- package tests"],
131
158
  async run(ctx, input) {
@@ -133,23 +160,14 @@ export const pull = {
133
160
  const project = requireSolution(session);
134
161
  const url = requireInstance(session);
135
162
  const layoutDirs = [project.layout.package, ...Object.values(project.layout.items)];
136
- if (!boolOption(input, "force")) {
137
- const dirty = (await uncommitted(project.root, layoutDirs))?.filter((f) => /\.(ya?ml|json)"?$/i.test(f));
138
- if (dirty?.length) {
139
- throw new CavelonError(ExitCode.conflict, {
140
- code: "uncommitted_changes",
141
- message: `pull would overwrite uncommitted changes: ${dirty.slice(0, 5).join(", ")}${dirty.length > 5 ? ` and ${dirty.length - 5} more` : ""}.`,
142
- hint: "Commit them first (then resolve the difference in git), or pass --force to discard them.",
143
- details: { files: dirty },
144
- });
145
- }
146
- }
163
+ const force = boolOption(input, "force");
164
+ const dirty = force ? [] : (await uncommitted(project.root, layoutDirs))?.filter((f) => /\.(ya?ml|json)"?$/i.test(f));
165
+ if (dirty?.length)
166
+ throw uncommittedChanges(dirty, "pull would overwrite uncommitted changes");
147
167
  const { ref } = harnessRef(session, input);
148
168
  let harness;
149
169
  if (ref) {
150
170
  harness = await findHarness(ctx, ref);
151
- if (!harness)
152
- throw harnessNotFound(ref);
153
171
  }
154
172
  const scope = harness ? "agent_graph" : "full_config";
155
173
  const exported = await callStable(ctx, "GET", "/api/v1/agent-graph/export", "exporting packages", {
@@ -163,7 +181,14 @@ export const pull = {
163
181
  const { schema } = await schemaFor(ctx, version, false);
164
182
  if (!schema)
165
183
  ctx.warn("The instance does not publish its package schema; every top-level key became a file of its own.");
184
+ if (dirty === undefined) {
185
+ const edited = await editedSincePull(project, exported, schema);
186
+ if (edited.length) {
187
+ throw uncommittedChanges(edited, "This folder is not in a git repository, and pull would overwrite or remove files that changed since the last pull");
188
+ }
189
+ }
166
190
  const report = await writePackage(project.root, project.layout, exported, schema);
191
+ await writePulledFiles(project.root, [...report.written, ...report.unchanged]);
167
192
  if (harness && !project.harness)
168
193
  await setProjectKey(project, "harness", harness.slug);
169
194
  if (version && project.packageVersion !== version)
@@ -201,7 +226,7 @@ export const pull = {
201
226
  async function validatePackage(ctx, project, offline) {
202
227
  const disk = await readPackage(project.root, project.layout);
203
228
  const version = packageVersionOf(disk.package) ?? project.packageVersion;
204
- const { schema } = await schemaFor(ctx, version, offline);
229
+ const { schema, used } = await schemaFor(ctx, version, offline);
205
230
  if (!schema) {
206
231
  throw new CavelonError(ExitCode.failure, {
207
232
  code: "package_schema_unavailable",
@@ -214,46 +239,74 @@ async function validatePackage(ctx, project, offline) {
214
239
  const findings = checkPackage(disk, {
215
240
  schema,
216
241
  catalog: await catalogFor(ctx, offline),
217
- accepted: await acceptedVersions(ctx),
242
+ accepted: await acceptedVersions(ctx, offline),
218
243
  limits: await limitsFor(ctx, offline),
219
244
  });
220
- return { disk, findings, schemaVersion: schema["x-package-version"] ?? version ?? null };
245
+ return { disk, findings, schemaVersion: schema["x-package-version"] ?? version ?? null, used };
246
+ }
247
+ function schemaUsedLine(used, ttlSeconds) {
248
+ const from = used.source === "instance" ? "read from the instance now" : `cached at ${used.fetched_at ?? "an unknown time"}`;
249
+ const instance = used.instance_version ? `, instance ${used.instance_version}` : "";
250
+ const id = [used.sha256 ? `sha256 ${used.sha256}` : "", used.etag ? `ETag ${used.etag}` : ""].filter(Boolean).join(", ");
251
+ const kept = used.instance_version && Contracts.isDevelopment(used.instance_version)
252
+ ? used.etag
253
+ ? `; a development build: checked with its ETag after ${ttlSeconds(used.instance_version)} s`
254
+ : `; a development build: read again after ${ttlSeconds(used.instance_version)} s`
255
+ : "";
256
+ const stale = used.stale ? " (past its time-to-live; the instance was not read)" : "";
257
+ return `Schema: package format ${used.package_version ?? "?"}, ${from}${instance}${id ? ` (${id})` : ""}${kept}${stale}.`;
221
258
  }
222
259
  export const validate = {
223
260
  name: "validate",
224
261
  summary: "Check the package files against the instance's package schema, offline.",
225
- description: "Uses the schema and error catalog cached by init, pull or apply; fetches them only when none is cached (never with --offline).\n" +
262
+ description: "Uses the schema and error catalog cached by init, pull or apply; fetches them only when none is cached or a development\n" +
263
+ "build's copy is past its time-to-live, and never with --offline. A development build keeps one version while its schema\n" +
264
+ "changes, so its copy is read again after a minute (CAVELON_CONTRACT_TTL_SECONDS), or checked with the ETag the instance\n" +
265
+ "sent with it; --verbose says which copy was used.\n" +
226
266
  "Warns (never fails) when a fan-out or Map loop's max_concurrency is above the instance's branch width, and when the\n" +
227
267
  "tenant runs fan-outs and Map loops in sequence, from the limits the instance last published.\n" +
228
- "Each finding carries a code: `cavelon explain <code>` says more. The import preview checks everything again on the server.",
268
+ "Each finding carries a code: `cavelon explain <code>` says more. The import preview checks everything again on the server.\n\n" +
269
+ "With --json, `warnings` is always a list of `{code, message}` objects: the warning findings (at most --limit), then the\n" +
270
+ "warnings about the run, such as a stale copy of the schema, with code null. `warning_count` counts them all and\n" +
271
+ "`error_count` the errors (`errors` is the same number); `findings` has each finding's file, line and hint.",
229
272
  readOnly: true,
230
273
  idempotent: true,
231
274
  mcpTool: "validate",
232
275
  options: {
233
276
  offline: { type: "boolean", description: "Never contact the instance, even when nothing is cached." },
234
277
  limit: { type: "string", value: "<n>", description: "Print at most n findings (default 50)." },
278
+ verbose: { type: "boolean", description: "Also say which copy of the package schema was used: cached or read now, when, and its hash." },
235
279
  },
236
280
  async run(ctx, input) {
237
281
  const session = await ctx.session();
238
282
  const project = requireSolution(session);
239
283
  requireInstance(session);
240
284
  const limit = intOption(input, "limit", { min: 1, max: 1000, fallback: 50 });
241
- const { disk, findings, schemaVersion } = await validatePackage(ctx, project, boolOption(input, "offline"));
285
+ const { disk, findings, schemaVersion, used } = await validatePackage(ctx, project, boolOption(input, "offline"));
242
286
  const errors = findings.filter((f) => f.severity === "error");
243
287
  const warnings = findings.filter((f) => f.severity === "warning");
244
288
  if (disk.empty)
245
289
  ctx.warn(`No package files in ${project.layout.package}/ yet; \`cavelon pull\` brings an existing solution.`);
290
+ const contracts = await ctx.contracts();
246
291
  const shown = findings.slice(0, limit);
292
+ const listed = [
293
+ ...warnings.slice(0, limit).map((f) => ({ code: f.code, message: f.message })),
294
+ ...ctx.warnings.map((message) => ({ code: null, message })),
295
+ ];
247
296
  const data = {
248
297
  valid: errors.length === 0,
249
298
  schema_version: schemaVersion,
299
+ schema: used,
250
300
  sections: Object.keys(disk.package).length,
301
+ error_count: errors.length,
302
+ warning_count: warnings.length + ctx.warnings.length,
251
303
  errors: errors.length,
252
- warnings: warnings.length,
304
+ warnings: listed,
253
305
  findings: shown,
254
306
  more: Math.max(0, findings.length - shown.length),
255
307
  };
256
308
  const text = [
309
+ ...(boolOption(input, "verbose") ? [schemaUsedLine(used, (v) => contracts.ttlSeconds(v))] : []),
257
310
  ...shown.map(findingLine),
258
311
  ...(data.more ? [`… and ${data.more} more (--limit).`] : []),
259
312
  errors.length
@@ -372,7 +425,7 @@ async function confirmPreview(ctx, project, previewId) {
372
425
  throw new CavelonError(ExitCode.conflict, {
373
426
  code: "preview_other_tenant",
374
427
  message: `Preview ${previewId} was made for tenant ${stored.tenant_id}, but this command acts in ${client.target.tenantId}.`,
375
- hint: stored.env ? `Pass the same --env ${stored.env} as the preview.` : "Use the tenant of the preview, or preview again here.",
428
+ hint: "Run the confirm command the preview printed; it names the preview's --env and --tenant. Or preview again here.",
376
429
  });
377
430
  }
378
431
  if (stored.tenant_id && session.tokenKind !== "api_key")
@@ -389,7 +442,7 @@ async function confirmPreview(ctx, project, previewId) {
389
442
  for (const other of await listPreviews(project.root))
390
443
  await deletePreview(project.root, other.preview_id);
391
444
  const summary = (result.summary ?? {});
392
- const flags = stored.env ? ` --env ${shellWord(stored.env)}` : targetFlags(session);
445
+ const flags = targetFlags(session, stored.env ?? session.envFile?.name);
393
446
  const still = setCommands(stored.preview, flags);
394
447
  const text = keyValues([
395
448
  ["applied", `preview ${stored.preview_id}${stored.harness ? ` to ${stored.harness.slug}` : ""}${stored.env ? ` (env ${stored.env})` : ""}`],
@@ -408,7 +461,7 @@ async function confirmPreview(ctx, project, previewId) {
408
461
  catch (error) {
409
462
  if (error instanceof CavelonError && error.code === REQUIREMENTS_CHANGED && error.blockers?.length) {
410
463
  await deletePreview(project.root, stored.preview_id);
411
- throw requirementsChanged(error, stored, await catalogFor(ctx, false));
464
+ throw requirementsChanged(error, stored, session, await catalogFor(ctx, false));
412
465
  }
413
466
  if (error instanceof CavelonError && (error.code === "import_preview_stale" || (error.status === 409 && /preview/i.test(error.message)))) {
414
467
  await deletePreview(project.root, stored.preview_id);
@@ -416,7 +469,7 @@ async function confirmPreview(ctx, project, previewId) {
416
469
  code: error.code === "conflict" ? "import_preview_stale" : error.code,
417
470
  status: 409,
418
471
  message: `The target changed since preview ${stored.preview_id}; nothing was imported.`,
419
- hint: `Run \`${cavelonCommand("apply", ...previewTarget(stored))}\` again, show the new preview, and confirm its id.`,
472
+ hint: `Run \`${previewAgain(stored, session)}\` again, show the new preview, and confirm its id.`,
420
473
  docs: error.docs,
421
474
  });
422
475
  }
@@ -424,7 +477,7 @@ async function confirmPreview(ctx, project, previewId) {
424
477
  }
425
478
  }
426
479
  const REQUIREMENTS_CHANGED = "package_requirements_changed";
427
- function requirementsChanged(error, stored, catalog) {
480
+ function requirementsChanged(error, stored, session, catalog) {
428
481
  const blockers = error.blockers ?? [];
429
482
  const known = new Map();
430
483
  for (const blocker of blockers) {
@@ -436,25 +489,24 @@ function requirementsChanged(error, stored, catalog) {
436
489
  code: error.code,
437
490
  status: error.status,
438
491
  message: `The import's requirements changed since preview ${stored.preview_id}; nothing was imported; preview again.`,
439
- hint: [...known.values(), `Run \`${cavelonCommand("apply", ...previewTarget(stored))}\` again, show the new preview, and confirm its id.`].join(" "),
492
+ hint: [...known.values(), `Run \`${previewAgain(stored, session)}\` again, show the new preview, and confirm its id.`].join(" "),
440
493
  docs: error.docs,
441
494
  blockers,
442
495
  });
443
496
  }
444
- function previewTarget(stored) {
445
- if (stored.env)
446
- return ["--env", stored.env];
447
- return stored.harness ? ["--harness", stored.harness.slug] : [];
497
+ function previewAgain(stored, session) {
498
+ const harness = !stored.env && stored.harness ? ` --harness ${shellWord(stored.harness.slug)}` : "";
499
+ return `cavelon apply${harness}${targetFlags(session, stored.env)}`;
448
500
  }
449
501
  async function applyTarget(ctx, session, input, pkg) {
450
502
  const { ref, source } = harnessRef(session, input);
451
503
  if (!ref)
452
504
  return undefined;
453
- const found = await findHarness(ctx, ref);
505
+ const { harness: found, candidates } = await lookupHarness(ctx, ref);
454
506
  if (found)
455
507
  return { ...found, created: false };
456
508
  if (!source?.startsWith("env/") || isUuid(ref))
457
- throw harnessNotFound(ref, source);
509
+ throw harnessNotFoundError(ref, candidates, source);
458
510
  const name = packageHarnessName(pkg, ref) ?? ref;
459
511
  const created = await callStable(ctx, "POST", "/api/v1/harnesses", "creating solutions", { body: { slug: ref, name } });
460
512
  ctx.warn(`Created the draft solution ${created.name} (${created.slug}) that ${source} names.`);
@@ -502,9 +554,6 @@ export const apply = {
502
554
  if (confirm)
503
555
  return confirmPreview(ctx, project, confirm);
504
556
  const envFile = session.envFile;
505
- if (envFile && !envFile.exists) {
506
- throw usageError(`No ${path.relative(project.root, envFile.file).split(path.sep).join("/")}.`, "`cavelon init` writes env/test.yaml and env/prod.yaml.");
507
- }
508
557
  if (envFile?.tenant && session.tenantSource !== `env/${envFile.name}.yaml`) {
509
558
  ctx.warn(`${session.tenantSource} names tenant "${session.tenant}" and takes precedence over ${envFile.name}.yaml's "${envFile.tenant}".`);
510
559
  }
@@ -513,7 +562,7 @@ export const apply = {
513
562
  throw usageError(`--mode must be overwrite or replace, got "${mode}".`);
514
563
  const { disk, findings } = await validatePackage(ctx, project, false);
515
564
  if (disk.empty)
516
- throw usageError(`No package files in ${project.layout.package}/.`, "Run `cavelon pull --harness <slug>` first, or write the package files.");
565
+ throw usageError(`No package files in ${project.layout.package}/.`, "Run `cavelon pull --harness <name or slug>` first (`cavelon harness list` shows them), or write the package files.");
517
566
  const errors = findings.filter((f) => f.severity === "error");
518
567
  if (errors.length) {
519
568
  return {
@@ -576,8 +625,7 @@ export const apply = {
576
625
  }
577
626
  const reason = personReason(preview, harness, mode, envFile?.name);
578
627
  data.show_to_person = Boolean(reason);
579
- const envFlags = envFile ? ["--env", envFile.name] : [];
580
- const confirmLine = preview.preview_id ? cavelonCommand("apply", "--confirm", preview.preview_id, ...envFlags) : undefined;
628
+ const confirmLine = preview.preview_id ? `${cavelonCommand("apply", "--confirm", preview.preview_id)}${flags}` : undefined;
581
629
  const text = [
582
630
  `Preview of ${project.layout.package}/ for ${harness ? `solution ${harness.slug}${harness.status ? ` (${harness.status})` : ""}` : "the tenant"}${envFile ? ` [env ${envFile.name}]` : ""}:`,
583
631
  previewText(preview, flags),
@@ -712,7 +760,7 @@ export const activate = {
712
760
  const session = await ctx.session();
713
761
  const { ref, source } = harnessRef(session, input);
714
762
  if (!ref)
715
- throw usageError("Which solution?", "Pass --harness <slug>, or set harness in cavelon.yaml or the env file.");
763
+ throw usageError("Which solution?", "Pass --harness <name or slug> (`cavelon harness list` shows them), or set harness in cavelon.yaml or the env file.");
716
764
  const client = await ctx.client();
717
765
  const principal = await readPrincipal(client);
718
766
  if (principal?.kind === "personal_access_token" && principal.token && !principal.token.may_activate) {
@@ -722,9 +770,7 @@ export const activate = {
722
770
  hint: "A person activates the solution in the Admin, or creates a token with \"may activate\" on /account/access-tokens.",
723
771
  });
724
772
  }
725
- const harness = await findHarness(ctx, ref);
726
- if (!harness)
727
- throw harnessNotFound(ref, source);
773
+ const harness = await findHarness(ctx, ref, source);
728
774
  if (harness.status === "active") {
729
775
  return { data: { activated: false, already_active: true, harness }, text: `${harness.name} (${harness.slug}) is already active.` };
730
776
  }
@@ -3,7 +3,11 @@ import { CavelonError, ExitCode, usageError } from "../errors.js";
3
3
  import { keyValues, moreHint, table } from "../format.js";
4
4
  import { callStable } from "../invoke.js";
5
5
  import { formatQuota, limitError, limitsOrWarn, readQuotas } from "../limits.js";
6
- import { isUuid, requireInstance } from "../session.js";
6
+ import { containing } from "../choose.js";
7
+ import { readTenantless } from "../principal.js";
8
+ import { requireInstance } from "../session.js";
9
+ import { listsTenants, searchTenants } from "../tenant-choice.js";
10
+ import { resolveHarnessId } from "../harness-ref.js";
7
11
  import { cavelonCommand } from "../shell.js";
8
12
  import { rememberTenant } from "./session.js";
9
13
  function idempotency(key) {
@@ -56,7 +60,9 @@ export const tenantCreate = {
56
60
  };
57
61
  export const tenantList = {
58
62
  name: "tenant list",
59
- summary: "List the tenants this token can see.",
63
+ summary: "List the tenants this token can see, with name, slug and id.",
64
+ description: "A personal access token in Platform mode sees every tenant; any other sees the tenants it reaches. " +
65
+ "An operator's token that reaches every tenant lists the person's own and finds any other with --search.",
60
66
  readOnly: true,
61
67
  idempotent: true,
62
68
  mcpTool: "tenant_list",
@@ -72,16 +78,19 @@ export const tenantList = {
72
78
  }
73
79
  const limit = intOption(input, "limit", { min: 1, max: 200, fallback: 50 });
74
80
  const cursor = stringOption(input, "cursor");
81
+ const search = stringOption(input, "search");
75
82
  const offset = cursor === undefined ? 0 : Number(cursor);
76
83
  if (!Number.isInteger(offset) || offset < 0)
77
84
  throw usageError(`--cursor "${cursor}" is not a cursor from a previous page.`);
78
85
  const client = await ctx.client({ tenant: false });
79
86
  const listing = await client.get("/api/v1/tenants", {
80
- query: { limit, offset, search: stringOption(input, "search") },
87
+ query: { limit, offset, search },
81
88
  sendTenant: false,
82
89
  allow: [403],
83
90
  });
84
91
  let page;
92
+ let note = "";
93
+ const reach = listing.status === 200 ? undefined : await readTenantless(client);
85
94
  if (listing.status === 200) {
86
95
  const items = listing.data.items.map((t) => ({ id: t.id, slug: t.slug, name: t.name, status: t.status ?? null, plan: t.plan ?? null }));
87
96
  page = {
@@ -91,18 +100,28 @@ export const tenantList = {
91
100
  source: "platform",
92
101
  };
93
102
  }
103
+ else if (listsTenants(reach)) {
104
+ const found = search && reach.reachesAll ? await searchTenants(client, search) : search ? containing(reach.tenants, search) : reach.tenants;
105
+ const all = found.map((t) => ({ id: t.id, slug: t.slug, name: t.name, role: t.role, is_default: t.is_default }));
106
+ page = { ...pageOf(all, limit, cursor), source: "token", reaches_all_tenants: reach.reachesAll };
107
+ if (reach.reachesAll && !search) {
108
+ note = `\nThis token reaches every tenant on ${client.url}${all.length ? "; these are your own" : ""}. Find any other: cavelon tenant list --search <part of the name>`;
109
+ }
110
+ }
94
111
  else {
95
112
  const me = await client.get("/api/v1/auth/me", { sendTenant: false });
96
- const search = stringOption(input, "search")?.toLowerCase();
113
+ const wanted = search?.toLowerCase();
97
114
  const all = (me.data.memberships ?? [])
98
- .filter((m) => !search || m.tenant_name.toLowerCase().includes(search))
99
- .map((m) => ({ id: m.tenant_id, slug: null, name: m.tenant_name, role: m.role ?? null }));
115
+ .filter((m) => !wanted || m.tenant_name.toLowerCase().includes(wanted) || Boolean(m.tenant_slug?.toLowerCase().includes(wanted)))
116
+ .map((m) => ({ id: m.tenant_id, slug: m.tenant_slug ?? null, name: m.tenant_name, role: m.role ?? null }));
100
117
  page = { ...pageOf(all, limit, cursor), source: "memberships" };
101
118
  }
102
- const columns = page.source === "platform" ? ["slug", "name", "status", "id"] : ["name", "role", "id"];
119
+ const columns = page.source === "platform" ? ["name", "slug", "status", "id"] : ["name", "slug", "role", "id"];
120
+ const empty = search ? `No tenant's name or slug contains "${search}".` : note ? "" : "No tenants.";
121
+ const next = page.items.length ? `\nChoose one: cavelon use <slug> (or \`cavelon use\` to pick from a list)` : "";
103
122
  return {
104
123
  data: page,
105
- text: (table(page.items, columns) || "No tenants.") + moreHint(page.next_cursor, "cavelon tenant list"),
124
+ text: ((table(page.items, columns) || empty) + moreHint(page.next_cursor, "cavelon tenant list") + note + next).trimStart(),
106
125
  };
107
126
  },
108
127
  };
@@ -176,6 +195,10 @@ async function checkHarnessCapacity(ctx, slug) {
176
195
  }
177
196
  }
178
197
  }
198
+ export async function createHarness(ctx, body, idempotencyKey) {
199
+ await checkHarnessCapacity(ctx, body.slug);
200
+ return callStable(ctx, "POST", "/api/v1/harnesses", "creating solutions", { body, headers: idempotency(idempotencyKey) });
201
+ }
179
202
  export const harnessNew = {
180
203
  name: "harness new",
181
204
  summary: "Create an empty draft solution (harness).",
@@ -193,11 +216,7 @@ export const harnessNew = {
193
216
  const description = stringOption(input, "description");
194
217
  if (description)
195
218
  body.description = description;
196
- await checkHarnessCapacity(ctx, slug);
197
- const harness = await callStable(ctx, "POST", "/api/v1/harnesses", "creating solutions", {
198
- body,
199
- headers: idempotency(stringOption(input, "idempotency-key")),
200
- });
219
+ const harness = await createHarness(ctx, body, stringOption(input, "idempotency-key"));
201
220
  return {
202
221
  data: harness,
203
222
  text: keyValues([
@@ -208,20 +227,12 @@ export const harnessNew = {
208
227
  };
209
228
  },
210
229
  };
211
- export async function resolveHarnessId(ctx, ref) {
212
- if (isUuid(ref))
213
- return ref;
214
- const harness = await callStable(ctx, "GET", "/api/v1/harnesses/by-slug/{slug}", "finding solutions by slug", {
215
- params: { slug: [ref] },
216
- });
217
- return harness.id;
218
- }
219
230
  export const harnessClone = {
220
231
  name: "harness clone",
221
232
  summary: "Copy a solution into a new draft solution.",
222
233
  readOnly: false,
223
234
  mcpTool: "harness_clone",
224
- positionals: [{ name: "source", description: "Slug or id of the solution to copy.", required: true }],
235
+ positionals: [{ name: "source", description: "Name, slug or id of the solution to copy.", required: true }],
225
236
  options: {
226
237
  slug: { type: "string", value: "<slug>", description: "The copy's slug." },
227
238
  name: { type: "string", value: "<name>", description: "The copy's display name." },
@@ -12,12 +12,15 @@ export const ENV_OPTION = { type: "string", value: "<name>", description: "Act i
12
12
  const CONFIRM_OPTION = { type: "boolean", description: "Delete it; without this nothing is deleted." };
13
13
  const TOKEN_PREFIXES = ["cbp_", "cvpat_"];
14
14
  const LIST_VALUE_CHARS = 200;
15
- export function targetFlags(session) {
16
- if (session.envFile)
17
- return ` --env ${shellWord(session.envFile.name)}`;
15
+ export function targetFlags(session, env = session.envFile?.name) {
16
+ let flags = "";
17
+ if (session.urlSource === "option" && session.url)
18
+ flags += ` --instance ${shellWord(session.url)}`;
19
+ if (env)
20
+ flags += ` --env ${shellWord(env)}`;
18
21
  if (session.tenantSource === "option" && session.tenant)
19
- return ` --tenant ${shellWord(session.tenant)}`;
20
- return "";
22
+ flags += ` --tenant ${shellWord(session.tenant)}`;
23
+ return flags;
21
24
  }
22
25
  export function secretSetCommand(name, flags = "") {
23
26
  return `cavelon secrets set ${shellWord(name)}${flags}`;