@cavelon/cli 0.1.1 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,8 @@
1
1
  import { promises as fs } from "node:fs";
2
2
  import path from "node:path";
3
3
  import { LineCounter, parseDocument, stringify } from "yaml";
4
- import { readTextFile, writeFileAtomic } from "./fsutil.js";
4
+ import { CavelonError, ExitCode } from "./errors.js";
5
+ import { readTextFile, withoutBom, writeFileAtomic } from "./fsutil.js";
5
6
  export const DEFAULT_LAYOUT = { package: "package", items: {} };
6
7
  const PACKAGE_FILE = /\.(ya?ml|json)$/i;
7
8
  export function layoutFrom(raw) {
@@ -39,10 +40,16 @@ function rel(root, file) {
39
40
  async function listFiles(dir) {
40
41
  try {
41
42
  const entries = await fs.readdir(dir, { withFileTypes: true });
42
- return entries
43
- .filter((e) => e.isFile() && !e.name.startsWith(".") && PACKAGE_FILE.test(e.name))
44
- .map((e) => e.name)
45
- .sort((a, b) => a.localeCompare(b, "en"));
43
+ const names = [];
44
+ for (const e of entries) {
45
+ if (e.name.startsWith(".") || !PACKAGE_FILE.test(e.name))
46
+ continue;
47
+ if (e.isFile())
48
+ names.push(e.name);
49
+ else if (e.isSymbolicLink() && !(await fs.stat(path.join(dir, e.name)).then((st) => st.isDirectory(), () => false)))
50
+ names.push(e.name);
51
+ }
52
+ return names.sort((a, b) => a.localeCompare(b, "en"));
46
53
  }
47
54
  catch (error) {
48
55
  if (error.code === "ENOENT")
@@ -50,6 +57,31 @@ async function listFiles(dir) {
50
57
  throw error;
51
58
  }
52
59
  }
60
+ export async function contentPath(root, file) {
61
+ let real;
62
+ try {
63
+ real = await fs.realpath(file);
64
+ }
65
+ catch {
66
+ return file;
67
+ }
68
+ const relative = path.relative(await fs.realpath(root).catch(() => root), real);
69
+ return relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative) ? real : undefined;
70
+ }
71
+ async function readSource(root, file) {
72
+ const relative = rel(root, file);
73
+ const target = await contentPath(root, file);
74
+ const invalid = (message, hint) => ({
75
+ finding: { code: "package_file_invalid", severity: "error", file: relative, message, hint },
76
+ });
77
+ if (target === undefined) {
78
+ return invalid("It is a link to a file outside the solution folder.", "Move the file into the solution folder and link to it there, or copy it in.");
79
+ }
80
+ const text = await readTextFile(target);
81
+ if (text === undefined)
82
+ return invalid("It is a link to a file that does not exist.", "Point the link at an existing file, or remove it.");
83
+ return { text: withoutBom(text) };
84
+ }
53
85
  async function exists(dir) {
54
86
  try {
55
87
  return (await fs.stat(dir)).isDirectory();
@@ -107,7 +139,13 @@ export async function readPackage(root, layout) {
107
139
  });
108
140
  continue;
109
141
  }
110
- const parsed = parseFile(root, file, (await readTextFile(file)) ?? "");
142
+ const read = await readSource(root, file);
143
+ if ("finding" in read) {
144
+ sources[section] = { file: rel(root, file) };
145
+ findings.push(read.finding);
146
+ continue;
147
+ }
148
+ const parsed = parseFile(root, file, read.text);
111
149
  sources[section] = parsed.source;
112
150
  if (parsed.finding)
113
151
  findings.push(parsed.finding);
@@ -118,7 +156,11 @@ export async function readPackage(root, layout) {
118
156
  const itemDir = path.join(root, folder);
119
157
  if (!(await exists(itemDir)))
120
158
  continue;
121
- empty = false;
159
+ const names = await listFiles(itemDir);
160
+ if (names.length)
161
+ empty = false;
162
+ else if (section in sources)
163
+ continue;
122
164
  if (section in sources) {
123
165
  findings.push({
124
166
  code: "package_file_duplicate",
@@ -130,9 +172,15 @@ export async function readPackage(root, layout) {
130
172
  }
131
173
  const items = [];
132
174
  const itemSources = [];
133
- for (const name of await listFiles(itemDir)) {
175
+ for (const name of names) {
134
176
  const file = path.join(itemDir, name);
135
- const parsed = parseFile(root, file, (await readTextFile(file)) ?? "");
177
+ const read = await readSource(root, file);
178
+ if ("finding" in read) {
179
+ itemSources.push({ file: rel(root, file) });
180
+ findings.push(read.finding);
181
+ continue;
182
+ }
183
+ const parsed = parseFile(root, file, read.text);
136
184
  itemSources.push(parsed.source);
137
185
  if (parsed.finding)
138
186
  findings.push(parsed.finding);
@@ -197,16 +245,18 @@ export function canonical(value) {
197
245
  export function toYaml(value) {
198
246
  return stringify(value, { lineWidth: 0, aliasDuplicateObjects: false });
199
247
  }
200
- async function readValue(file) {
201
- const text = await readTextFile(file);
248
+ async function readValue(root, file) {
249
+ const target = await contentPath(root, file);
250
+ const text = target === undefined ? undefined : await readTextFile(target);
202
251
  if (text === undefined)
203
252
  return { ok: false };
204
253
  try {
205
- const value = /\.json$/i.test(file) ? JSON.parse(text) : parseDocument(text, { uniqueKeys: true }).toJS({ maxAliasCount: 1000 });
206
- return { text, value, ok: true };
254
+ const plain = withoutBom(text);
255
+ const value = /\.json$/i.test(file) ? JSON.parse(plain) : parseDocument(plain, { uniqueKeys: true }).toJS({ maxAliasCount: 1000 });
256
+ return { value, ok: true };
207
257
  }
208
258
  catch {
209
- return { text, ok: false };
259
+ return { ok: false };
210
260
  }
211
261
  }
212
262
  function itemFileName(item, index, taken) {
@@ -234,6 +284,7 @@ export async function writePackage(root, layout, pkg, schema, options = {}) {
234
284
  existing.set(name.replace(PACKAGE_FILE, ""), name);
235
285
  const plans = [];
236
286
  const same = [];
287
+ const removals = [];
237
288
  for (const [section, value] of Object.entries(pkg)) {
238
289
  if (section in layout.items && Array.isArray(value))
239
290
  continue;
@@ -243,7 +294,7 @@ export async function writePackage(root, layout, pkg, schema, options = {}) {
243
294
  }
244
295
  const current = existing.get(section);
245
296
  const file = path.join(dir, current ?? `${section}.yaml`);
246
- const old = await readValue(file);
297
+ const old = await readValue(root, file);
247
298
  if (old.ok && canonical(old.value) === canonical(value))
248
299
  same.push({ file, section });
249
300
  else
@@ -256,7 +307,7 @@ export async function writePackage(root, layout, pkg, schema, options = {}) {
256
307
  const itemDir = path.join(root, folder);
257
308
  const before = new Map();
258
309
  for (const name of await listFiles(itemDir)) {
259
- const old = await readValue(path.join(itemDir, name));
310
+ const old = await readValue(root, path.join(itemDir, name));
260
311
  if (old.ok)
261
312
  before.set(name, old.value);
262
313
  }
@@ -280,40 +331,54 @@ export async function writePackage(root, layout, pkg, schema, options = {}) {
280
331
  }
281
332
  plans.push({ file: path.join(itemDir, itemFileName(item, index, taken)), section, content: toYaml(item) });
282
333
  });
283
- for (const name of before.keys()) {
284
- if (!taken.has(name)) {
285
- if (!dryRun)
286
- await fs.rm(path.join(itemDir, name), { force: true });
287
- report.removed.push(rel(root, path.join(itemDir, name)));
288
- }
289
- }
334
+ for (const name of before.keys())
335
+ if (!taken.has(name))
336
+ removals.push(path.join(itemDir, name));
290
337
  if (!dryRun)
291
338
  await fs.mkdir(itemDir, { recursive: true });
292
339
  }
340
+ for (const [section, name] of existing) {
341
+ if (section in pkg)
342
+ continue;
343
+ const file = path.join(dir, name);
344
+ if (known.has(section))
345
+ removals.push(file);
346
+ else
347
+ report.kept.push(rel(root, file));
348
+ }
293
349
  const othersChanged = plans.some((p) => !required.has(p.section));
350
+ const writes = [];
351
+ const outside = [];
294
352
  for (const plan of plans) {
295
353
  if (required.has(plan.section) && !othersChanged && existing.has(plan.section)) {
296
354
  same.push({ file: plan.file, section: plan.section });
297
355
  continue;
298
356
  }
357
+ const target = await contentPath(root, plan.file);
358
+ if (target === undefined)
359
+ outside.push(rel(root, plan.file));
360
+ else
361
+ writes.push({ file: plan.file, target, content: plan.content });
362
+ }
363
+ if (outside.length) {
364
+ throw new CavelonError(ExitCode.conflict, {
365
+ code: "package_file_outside",
366
+ message: `${outside.join(", ")} ${outside.length === 1 ? "is a link" : "are links"} to a file outside the solution folder; nothing was written.`,
367
+ hint: "Move the file into the solution folder and link to it there, or replace the link with the file.",
368
+ details: { files: outside },
369
+ });
370
+ }
371
+ for (const write of writes) {
299
372
  if (!dryRun)
300
- await writeFileAtomic(plan.file, plan.content);
301
- report.written.push(rel(root, plan.file));
373
+ await writeFileAtomic(write.target, write.content);
374
+ report.written.push(rel(root, write.file));
302
375
  }
303
- report.unchanged.push(...same.map((s) => rel(root, s.file)));
304
- for (const [section, name] of existing) {
305
- if (section in pkg)
306
- continue;
307
- const file = path.join(dir, name);
308
- if (known.has(section)) {
309
- if (!dryRun)
310
- await fs.rm(file, { force: true });
311
- report.removed.push(rel(root, file));
312
- }
313
- else {
314
- report.kept.push(rel(root, file));
315
- }
376
+ for (const file of removals) {
377
+ if (!dryRun)
378
+ await fs.rm(file, { force: true });
379
+ report.removed.push(rel(root, file));
316
380
  }
381
+ report.unchanged.push(...same.map((s) => rel(root, s.file)));
317
382
  for (const list of Object.values(report))
318
383
  list.sort();
319
384
  return report;
package/dist/paths.js CHANGED
@@ -1,5 +1,9 @@
1
+ import { createHash } from "node:crypto";
2
+ import { promises as fs } from "node:fs";
1
3
  import os from "node:os";
2
4
  import path from "node:path";
5
+ import { CavelonError, ExitCode } from "./errors.js";
6
+ import { findProject } from "./project.js";
3
7
  function home(env) {
4
8
  return env.HOME || env.USERPROFILE || os.homedir();
5
9
  }
@@ -24,5 +28,50 @@ export function cacheDir(env) {
24
28
  export function instanceKey(url) {
25
29
  const parsed = new URL(url);
26
30
  const parts = [parsed.hostname, parsed.port, parsed.pathname.replace(/^\/+|\/+$/g, "")].filter(Boolean);
27
- return parts.join("_").replace(/[^A-Za-z0-9._-]+/g, "_");
31
+ const readable = parts.join("_").replace(/[^A-Za-z0-9._-]+/g, "_");
32
+ return `${readable}-${createHash("sha256").update(url).digest("hex").slice(0, 8)}`;
33
+ }
34
+ export async function confinedPath(ctx, raw, what) {
35
+ const resolved = path.resolve(ctx.io.cwd, raw);
36
+ if (ctx.mode !== "mcp")
37
+ return resolved;
38
+ const root = (await findProject(ctx.io.cwd))?.root ?? ctx.io.cwd;
39
+ const real = await realPath(resolved);
40
+ if (!within(await realPath(root), real)) {
41
+ throw new CavelonError(ExitCode.usage, {
42
+ code: "path_outside_solution",
43
+ message: `${what} ${raw} is outside the solution folder ${root}; over MCP a tool reads and writes only there.`,
44
+ hint: "Name a file inside the solution folder, or ask the person to run the command in their terminal.",
45
+ });
46
+ }
47
+ for (const dir of [configDir(ctx.io.env), cacheDir(ctx.io.env)]) {
48
+ if (within(await realPath(path.resolve(ctx.io.cwd, dir)), real, true)) {
49
+ throw new CavelonError(ExitCode.usage, {
50
+ code: "path_in_kit_directory",
51
+ message: `${what} ${raw} is in cavelon's own directory ${dir}, which holds its login and cache; no tool reads or writes there.`,
52
+ });
53
+ }
54
+ }
55
+ return resolved;
56
+ }
57
+ export async function realPath(file) {
58
+ const rest = [];
59
+ let current = file;
60
+ for (;;) {
61
+ try {
62
+ return path.join(await fs.realpath(current), ...rest.reverse());
63
+ }
64
+ catch (error) {
65
+ const parent = path.dirname(current);
66
+ if (error.code !== "ENOENT" || parent === current)
67
+ throw error;
68
+ rest.push(path.basename(current));
69
+ current = parent;
70
+ }
71
+ }
72
+ }
73
+ export function within(dir, file, fold = false) {
74
+ const norm = (p) => (fold && (process.platform === "win32" || process.platform === "darwin") ? p.toLowerCase() : p);
75
+ const rel = path.relative(norm(dir), norm(file));
76
+ return rel === "" || (rel !== ".." && !rel.startsWith(`..${path.sep}`) && !path.isAbsolute(rel));
28
77
  }
package/dist/project.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { promises as fs } from "node:fs";
1
2
  import path from "node:path";
2
3
  import { parse } from "yaml";
3
4
  import { readTextFile } from "./fsutil.js";
@@ -71,17 +72,36 @@ function refuseCredentials(file, map) {
71
72
  }
72
73
  }
73
74
  export const ENV_DIR = "env";
75
+ const ENV_NAME = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
74
76
  export function envFilePath(project, name) {
75
- if (!/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(name)) {
77
+ if (!ENV_NAME.test(name)) {
76
78
  throw usageError(`"${name}" is not an environment name.`, "Use letters, digits, dashes and underscores, as in --env test.");
77
79
  }
78
80
  return path.join(project.root, ENV_DIR, `${name}.yaml`);
79
81
  }
82
+ export async function envNames(project) {
83
+ let entries;
84
+ try {
85
+ entries = await fs.readdir(path.join(project.root, ENV_DIR));
86
+ }
87
+ catch {
88
+ return [];
89
+ }
90
+ return entries
91
+ .filter((entry) => entry.endsWith(".yaml"))
92
+ .map((entry) => entry.slice(0, -".yaml".length))
93
+ .filter((name) => ENV_NAME.test(name))
94
+ .sort();
95
+ }
80
96
  export async function readEnvFile(project, name) {
81
97
  const file = envFilePath(project, name);
82
98
  const text = await readTextFile(file);
83
- if (text === undefined)
84
- return { name, file, exists: false, runtimeBindings: {}, raw: {} };
99
+ if (text === undefined) {
100
+ const known = await envNames(project);
101
+ throw usageError(`No ${ENV_DIR}/${name}.yaml in this solution; nothing was sent.`, known.length
102
+ ? `Its env files: ${known.join(", ")}. Pass one of them to --env, or write ${ENV_DIR}/${name}.yaml first.`
103
+ : "`cavelon init` writes env/test.yaml and env/prod.yaml.");
104
+ }
85
105
  let raw;
86
106
  try {
87
107
  raw = parse(text) ?? {};
@@ -128,7 +148,6 @@ export async function readEnvFile(project, name) {
128
148
  return {
129
149
  name,
130
150
  file,
131
- exists: true,
132
151
  tenant: stringField(map.tenant, "id", "slug"),
133
152
  harness: stringField(map.harness, "slug", "id"),
134
153
  mode: mode,
package/dist/results.js CHANGED
@@ -4,11 +4,37 @@ import { callStable } from "./invoke.js";
4
4
  import { cavelonCommand } from "./shell.js";
5
5
  export const NOT_PASSED = new Set(["fail", "error"]);
6
6
  export function caseCounts(summary) {
7
- const count = (key) => {
8
- const value = Number(summary?.[key] ?? 0);
9
- return Number.isFinite(value) && value > 0 ? value : 0;
10
- };
11
- return { failed: count("failed"), errors: count("errors") };
7
+ return { failed: summaryCount(summary, "failed"), errors: summaryCount(summary, "errors") };
8
+ }
9
+ function summaryCount(summary, key) {
10
+ const value = Number(summary?.[key] ?? 0);
11
+ return Number.isFinite(value) && value > 0 ? value : 0;
12
+ }
13
+ const NOT_PASSED_COUNTS = ["failed", "errors", "technical_errors", "not_run", "cases_not_run", "missing_results", "unmeasurable_cases", "skipped"];
14
+ const WAITING_COUNTS = ["pending_review", "calibration_required"];
15
+ export function runVerdict(summary) {
16
+ const counts = {};
17
+ for (const key of [...NOT_PASSED_COUNTS, ...WAITING_COUNTS]) {
18
+ const value = summaryCount(summary, key);
19
+ if (value > 0)
20
+ counts[key] = value;
21
+ }
22
+ const said = summary?.comparable;
23
+ const comparable = typeof said === "boolean" ? said : summary && "pass_rate" in summary && summary.pass_rate == null ? false : null;
24
+ const reasons = Array.isArray(summary?.non_comparable_reasons) ? summary.non_comparable_reasons.map(String) : [];
25
+ let exitCode = 0;
26
+ if (NOT_PASSED_COUNTS.some((k) => k in counts))
27
+ exitCode = 1;
28
+ else if (WAITING_COUNTS.some((k) => k in counts))
29
+ exitCode = 5;
30
+ else if (comparable === false)
31
+ exitCode = 1;
32
+ return { counts, comparable, non_comparable_reasons: reasons, exit_code: exitCode };
33
+ }
34
+ export function countsText(counts) {
35
+ return Object.entries(counts)
36
+ .map(([key, value]) => `${value} ${key === "errors" ? "errored" : key.replaceAll("_", " ")}`)
37
+ .join(", ");
12
38
  }
13
39
  const MAX_CASES = 5;
14
40
  const REASON_CHARS = 500;
@@ -28,9 +54,10 @@ export async function resultFailure(ctx, op) {
28
54
  const id = op.result_ref.id;
29
55
  try {
30
56
  const run = await callStable(ctx, "GET", "/api/v1/test-runs/{run_id}", "test runs", { params: { run_id: [id] } });
31
- const { failed, errors } = caseCounts(run.summary);
32
- if (failed + errors === 0)
57
+ const verdict = runVerdict(run.summary);
58
+ if (verdict.exit_code === 0)
33
59
  return undefined;
60
+ const { failed, errors } = caseCounts(run.summary);
34
61
  const results = await callStable(ctx, "GET", "/api/v1/test-runs/{run_id}/results", "test results", { params: { run_id: [id] } });
35
62
  return {
36
63
  type: "test_run",
@@ -38,6 +65,10 @@ export async function resultFailure(ctx, op) {
38
65
  suite: run.suite_name ?? run.suite_id,
39
66
  failed_cases: failed,
40
67
  errored_cases: errors,
68
+ counts: verdict.counts,
69
+ comparable: verdict.comparable,
70
+ non_comparable_reasons: verdict.non_comparable_reasons,
71
+ exit_code: verdict.exit_code,
41
72
  cases: results.filter((r) => NOT_PASSED.has(r.status)).slice(0, MAX_CASES).map((r) => failedCase(r)),
42
73
  trace: cavelonCommand("trace", id),
43
74
  };
@@ -53,8 +84,15 @@ export function caseLabel(c) {
53
84
  return c.step === null ? c.case : `${c.case} (step ${c.step})`;
54
85
  }
55
86
  export function failureLines(failure) {
56
- const counts = [failure.failed_cases ? `${failure.failed_cases} failed` : "", failure.errored_cases ? `${failure.errored_cases} errored` : ""].filter(Boolean).join(", ");
57
- const lines = [` test run ${failure.id} (${failure.suite}) finished, but cases did not pass: ${counts}`];
87
+ const head = ` test run ${failure.id} (${failure.suite}) finished, but`;
88
+ const counts = countsText(failure.counts);
89
+ const lines = [
90
+ counts
91
+ ? `${head} ${failure.exit_code === 5 ? "answers wait for a person" : "cases did not pass"}: ${counts}`
92
+ : `${head} it measured nothing comparable and has no pass rate`,
93
+ ];
94
+ if (failure.comparable === false && failure.non_comparable_reasons.length)
95
+ lines.push(` Not comparable: ${failure.non_comparable_reasons.join(", ")}`);
58
96
  for (const c of failure.cases)
59
97
  lines.push(` ${caseLabel(c)} ${c.status}${c.reason ? ": " + c.reason : ""}`);
60
98
  const shown = failure.cases.length;
package/dist/session.js CHANGED
@@ -33,6 +33,16 @@ export function normalizeUrl(input, env = {}) {
33
33
  const pathname = url.pathname.replace(/\/+$/, "");
34
34
  return `${url.protocol}//${url.host.toLowerCase()}${pathname}`;
35
35
  }
36
+ function sameUrl(input, url, env) {
37
+ if (!input)
38
+ return false;
39
+ try {
40
+ return normalizeUrl(input, env) === url;
41
+ }
42
+ catch {
43
+ return false;
44
+ }
45
+ }
36
46
  export async function resolveSession(env, cwd, globals) {
37
47
  const project = await findProject(cwd);
38
48
  const config = await loadUserConfig(env);
@@ -45,11 +55,10 @@ export async function resolveSession(env, cwd, globals) {
45
55
  }
46
56
  let url;
47
57
  let urlSource;
48
- const envUrl = env.CAVELON_URL ? normalizeUrl(env.CAVELON_URL, env) : undefined;
49
58
  if (globals.instance)
50
59
  [url, urlSource] = [normalizeUrl(globals.instance, env), "option"];
51
- else if (envUrl)
52
- [url, urlSource] = [envUrl, "CAVELON_URL"];
60
+ else if (env.CAVELON_URL)
61
+ [url, urlSource] = [normalizeUrl(env.CAVELON_URL, env), "CAVELON_URL"];
53
62
  else if (project?.instance)
54
63
  [url, urlSource] = [normalizeUrl(project.instance, env), "cavelon.yaml"];
55
64
  else if (config.current_instance)
@@ -58,9 +67,9 @@ export async function resolveSession(env, cwd, globals) {
58
67
  const session = { url, urlSource, project, envFile, settings };
59
68
  if (!url)
60
69
  return session;
61
- if (env.CAVELON_TOKEN && !envUrl)
70
+ if (env.CAVELON_TOKEN && !env.CAVELON_URL)
62
71
  session.ignoredEnvToken = true;
63
- if (env.CAVELON_TOKEN && envUrl === url) {
72
+ if (env.CAVELON_TOKEN && sameUrl(env.CAVELON_URL, url, env)) {
64
73
  session.token = env.CAVELON_TOKEN.trim();
65
74
  session.tokenSource = "CAVELON_TOKEN";
66
75
  }
@@ -74,7 +83,7 @@ export async function resolveSession(env, cwd, globals) {
74
83
  }
75
84
  if (session.token)
76
85
  session.tokenKind = tokenKind(session.token);
77
- const projectMatches = project && (!project.instance || normalizeUrl(project.instance, env) === url);
86
+ const projectMatches = project && (!project.instance || sameUrl(project.instance, url, env));
78
87
  if (globals.tenant)
79
88
  [session.tenant, session.tenantSource] = [globals.tenant, "option"];
80
89
  else if (env.CAVELON_TENANT)
@@ -111,10 +120,13 @@ export function requireToken(session) {
111
120
  }
112
121
  return session.token;
113
122
  }
123
+ const MAX_SLUG_LOOKUPS = 25;
124
+ export const TENANT_REF_HINT = "Use the tenant's name or id instead: a member's token finds a tenant by its slug only where it may view the tenant's settings. `cavelon tenant list` shows the names and ids.";
114
125
  export async function lookupTenantId(client, ref) {
115
126
  if (isUuid(ref))
116
127
  return { id: ref };
117
128
  const wanted = ref.toLowerCase();
129
+ const memberships = new Map();
118
130
  if (client.target.token?.startsWith("cvpat_")) {
119
131
  const me = await client.get("/api/v1/auth/me", { sendTenant: false, allow: [403, 404] });
120
132
  if (me.status === 200 && me.data) {
@@ -122,6 +134,9 @@ export async function lookupTenantId(client, ref) {
122
134
  const hit = tenants.find((t) => t.tenant_name?.toLowerCase() === wanted || t.tenant_id === ref);
123
135
  if (hit)
124
136
  return { id: hit.tenant_id, name: hit.tenant_name };
137
+ for (const t of tenants)
138
+ if (isUuid(t.tenant_id))
139
+ memberships.set(t.tenant_id, t.tenant_name);
125
140
  }
126
141
  }
127
142
  const page = await client.get("/api/v1/tenants", {
@@ -134,6 +149,15 @@ export async function lookupTenantId(client, ref) {
134
149
  if (hit)
135
150
  return { id: hit.id, name: hit.name };
136
151
  }
152
+ for (const [id, name] of [...memberships].slice(0, MAX_SLUG_LOOKUPS)) {
153
+ const detail = await client.get(`/api/v1/tenants/${id}`, {
154
+ sendTenant: false,
155
+ headers: { "X-Tenant-Id": id },
156
+ allow: [400, 403, 404, 422],
157
+ });
158
+ if (detail.status === 200 && detail.data?.slug?.toLowerCase() === wanted)
159
+ return { id, name: detail.data.name ?? name };
160
+ }
137
161
  return undefined;
138
162
  }
139
163
  export async function resolveTenantId(env, session, client) {
@@ -153,7 +177,7 @@ export async function resolveTenantId(env, session, client) {
153
177
  throw new CavelonError(ExitCode.failure, {
154
178
  code: "tenant_not_found",
155
179
  message: `No tenant "${session.tenant}" that this token can see (from ${session.tenantSource}).`,
156
- hint: "Use the tenant's id instead; `cavelon tenant list` shows the ids.",
180
+ hint: TENANT_REF_HINT,
157
181
  });
158
182
  }
159
183
  const url = session.url;
@@ -51,7 +51,9 @@ for a public widget), **propose the change; the person decides.**
51
51
  without `confirm`). It changes nothing and shows the old and the new value,
52
52
  the operation it would send and the permissions it needs. Show that to the
53
53
  person with your reason (what fails or waits now), and wait for their answer.
54
- - Only after they agreed, run it again with `--confirm`. Never raise a limit on
54
+ - Only after they agreed, run the confirm command it printed (the `confirm`
55
+ field in `--json`) as it stands: it keeps the `--env` and `--tenant` of the
56
+ preview, so it changes the limit the preview showed. Never raise a limit on
55
57
  your own, never pick a value higher than the need you named, and never change
56
58
  one without telling them.
57
59
  - The same goes for the tenant's monthly inference budget
@@ -168,6 +170,14 @@ version; leave it as `pull` wrote it.
168
170
  (`cavelon docs get reference/builtin-tools` names it). Without one the agent
169
171
  answers from memory; `cavelon validate` warns
170
172
  (`knowledge_base_without_search_tool`).
173
+ - **Who approves goes on the Approval node, not into the memo.** When the
174
+ brief says who approves, or that nobody approves their own request, set the
175
+ node's `approvers` (tenant roles or access groups, directly or in `tiers`
176
+ chosen by a number at `by`, such as the amount) and `forbid_self_approval:
177
+ true`, where the package schema publishes them; the instance then refuses
178
+ anyone else. Read the approval node in the schema and the human-in-the-loop
179
+ docs for the shape. A test only shows the approval is reached; a person
180
+ decides once per branch.
171
181
 
172
182
  ## Variables and secrets the solution needs
173
183
 
@@ -198,8 +208,8 @@ schema has them: `cavelon validate` reports an unknown section):
198
208
  `variables_set` tool) when the value is not a credential and you know it;
199
209
  ask the person otherwise. `cavelon variables list` shows them.
200
210
  - **Secrets are set by a person, never by you.** Tell the person the exact
201
- command `apply` printed, `cavelon secrets set <name>` (with `--env <name>`
202
- when there is one), to run in their own terminal; it asks for the value
211
+ command `apply` printed, `cavelon secrets set <name>` (with the `--env` and
212
+ `--tenant` it printed), to run in their own terminal; it asks for the value
203
213
  without echoing it. Never ask for the value, never put it into a file,
204
214
  an argument or a message, and never put a credential into a variable.
205
215
  `cavelon secrets list` (the `secrets_list` tool) shows which are set,
@@ -62,7 +62,11 @@ cavelon wait <operation-id> --timeout 90s # exit 0 done, 1 failed, 5
62
62
  ```
63
63
 
64
64
  A loop started from `cavelon` runs **as the person whose token it is**, checked
65
- again on every iteration. Keep each `watch` or `wait` under your shell's time
65
+ again on every iteration. If `loop start` exits 8 (a timeout, a cut
66
+ connection), the run may have started: retry only with the
67
+ `--idempotency-key <key>` its error names, never without it, or a second run
68
+ starts and spends the budget again. `cavelon trace <operation-id>` reads the
69
+ run's traces. Keep each `watch` or `wait` under your shell's time
66
70
  limit and run it again to resume (exit 6 means still running). Over MCP, use the
67
71
  `loop_iterations` and `operation_status` tools; they never block.
68
72
 
@@ -23,7 +23,7 @@ use it when you parse the result.
23
23
  - **Secrets are set by a person.** When a preview or `cavelon secrets list`
24
24
  names a secret that is not set, tell the person the exact command to run in
25
25
  their terminal, `cavelon secrets set <name>` (as `apply` prints it, with its
26
- `--env`). Never ask for the value, never pipe or pass one yourself; there is
26
+ `--env` and `--tenant`). Never ask for the value, never pipe or pass one yourself; there is
27
27
  no MCP tool for it. Plain-text variables you may set with `cavelon variables
28
28
  set <name> <value>` when the value is not a credential.
29
29
  - **Read the limits before you plan a solution:** `cavelon limits` (the
@@ -48,7 +48,8 @@ use it when you parse the result.
48
48
  ## The loop
49
49
 
50
50
  1. **Pull** what is live: `cavelon pull`. It refuses when `package/` has
51
- uncommitted changes; commit first. `git diff` then shows what someone changed
51
+ uncommitted changes (outside git: files changed since the last pull);
52
+ commit or apply them first. `git diff` then shows what someone changed
52
53
  in the Admin.
53
54
  2. **Edit** the files in `package/` (one file per schema section) and `tests/`
54
55
  (one file per test suite). See the cavelon-authoring skill.
@@ -60,7 +61,7 @@ use it when you parse the result.
60
61
  secrets with the command that sets each, OAuth grants, runtime bindings,
61
62
  trigger identities), loop budgets, and what the instance ignores.
62
63
  5. **Confirm** exactly that preview: `cavelon apply --confirm <preview-id>`
63
- (with the same `--env`). Exit 4 means the target changed since the preview:
64
+ (the line `apply` printed, with the same `--env` and `--tenant`). Exit 4 means the target changed since the preview:
64
65
  preview again and confirm the new id. When the error lists `blockers`, the
65
66
  import's own check found them as it applied: fix what each names (the hint
66
67
  says how for a code the kit knows), then preview again.
@@ -37,6 +37,9 @@ the person would see: that the approval was reached, who approves, the facts
37
37
  and the recommendation in the instructions. The branches after the decision
38
38
  (approved, rejected, expired) are never reached by a test; a person checks them
39
39
  on a draft solution by deciding a real approval, and you never decide one.
40
+ Who may decide (`approvers`, `forbid_self_approval`) is enforced when a person
41
+ decides, not in a test: with tiers by amount, write one case per tier that
42
+ reaches the approval, and leave the refusals to the instance.
40
43
  `examples/expense-approval` in the dev-kit repository has such a suite.
41
44
 
42
45
  ## Running
@@ -52,7 +55,11 @@ each call under your shell's time limit). `test run --wait --timeout 5m` does
52
55
  both in one call where your client allows long commands; when its wait ends
53
56
  first, its last line is the command that resumes, with the same timeout. Exit 1 after a run
54
57
  means a case failed, even though the run itself finished; the output names the
55
- cases that did not pass and why, and `cavelon trace <run>` shows each one.
58
+ cases that did not pass and why, and `cavelon trace <run>` shows each one. Exit
59
+ 1 also means the run measured nothing comparable (steps not run, technical
60
+ errors, no pass rate): it is no evidence the solution works, so do not go on to
61
+ `activate`; find the cause and run again. Exit 5 means answers wait for a
62
+ person's verdict or a value a case needs: tell the person.
56
63
 
57
64
  ## Reading what happened
58
65
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cavelon/cli",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "description": "The cavelon binary: CLI and local MCP server for building Cavelon solutions with a coding agent.",
5
5
  "license": "Apache-2.0",
6
6
  "homepage": "https://github.com/goodguys-gmbh/cavelon-dev-kit",