@cavelon/cli 0.2.0 → 0.2.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.
@@ -0,0 +1,43 @@
1
+ function object(value) {
2
+ return value !== null && typeof value === "object" && !Array.isArray(value);
3
+ }
4
+ function fields(body, allowed) {
5
+ return object(body) && Object.keys(body).every(key => allowed.includes(key));
6
+ }
7
+ function optionalText(body, keys) {
8
+ return keys.every(key => body[key] === undefined || body[key] === null || typeof body[key] === "string");
9
+ }
10
+ export function apiApproval(op, args) {
11
+ if (op.confirmation || op.personOnly?.marked)
12
+ return "person";
13
+ if (op.readOnly)
14
+ return "read";
15
+ if (op.method !== "POST" || args.files?.length || args.bytes || Object.keys(args.headers ?? {}).length)
16
+ return "person";
17
+ const params = Object.keys(args.params ?? {});
18
+ const onlyParams = (...names) => params.every(key => names.includes(key));
19
+ const uuidParam = (name) => {
20
+ const values = args.params?.[name];
21
+ return values?.length === 1 && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(values[0]);
22
+ };
23
+ const body = args.body;
24
+ if (op.path === "/api/v1/harnesses" && onlyParams("Idempotency-Key") &&
25
+ fields(body, ["slug", "name", "description"]) && typeof body.slug === "string" && typeof body.name === "string" &&
26
+ optionalText(body, ["description"]))
27
+ return "routine";
28
+ if (op.path === "/api/v1/harnesses/{harness_id}/clone" && onlyParams("harness_id", "Idempotency-Key") && uuidParam("harness_id") &&
29
+ fields(body, ["slug", "name", "description", "element_slug_suffix", "include_tests", "include_triggers"]) &&
30
+ optionalText(body, ["slug", "name", "description", "element_slug_suffix"]) &&
31
+ ["include_tests", "include_triggers"].every(key => body[key] === undefined || typeof body[key] === "boolean"))
32
+ return "routine";
33
+ if (op.path === "/api/v1/agent-graph/import/preview" && onlyParams() &&
34
+ fields(body, ["package", "mode", "harness_id", "runtime_bindings", "include_tenant_wide"]) && object(body.package) &&
35
+ (body.mode === undefined || body.mode === "overwrite" || body.mode === "replace") && optionalText(body, ["harness_id"]) &&
36
+ (body.runtime_bindings === undefined || object(body.runtime_bindings) && Object.values(body.runtime_bindings).every(value => typeof value === "string")) &&
37
+ (body.include_tenant_wide === undefined || typeof body.include_tenant_wide === "boolean"))
38
+ return "read";
39
+ if (op.path === "/api/v1/database-connectors/connections/{connection_id}/schema" && onlyParams("connection_id") && uuidParam("connection_id") &&
40
+ (body === undefined || body === null || fields(body, ["schema"]) && optionalText(body, ["schema"])))
41
+ return "read";
42
+ return "person";
43
+ }
@@ -0,0 +1,45 @@
1
+ import { createHash } from "node:crypto";
2
+ import { realpath } from "node:fs/promises";
3
+ import { actingTarget } from "./acting.js";
4
+ import { canonical } from "./package-files.js";
5
+ import { lookupHarness } from "./harness-ref.js";
6
+ export async function yoloScope(ctx) {
7
+ const session = await ctx.session();
8
+ const target = await actingTarget(ctx);
9
+ if (!session.token || target.mode !== "tenant" || !target.tenant?.id)
10
+ return undefined;
11
+ const selected = session.envFile?.harness ?? session.project?.harness;
12
+ const harness = selected ? (await lookupHarness(ctx, selected)).harness : undefined;
13
+ if (selected && !harness)
14
+ return undefined;
15
+ return canonical({
16
+ instance: target.instance,
17
+ tenant: target.tenant.id,
18
+ credential: createHash("sha256").update(session.token).digest("hex"),
19
+ root: await realpath(session.project?.root ?? ctx.io.cwd),
20
+ harness: selected ?? null,
21
+ harness_id: harness?.id ?? null,
22
+ environment: ctx.globals.solutionEnv ?? null,
23
+ bindings: session.envFile?.runtimeBindings ?? {},
24
+ mode: session.envFile?.mode ?? null,
25
+ });
26
+ }
27
+ export async function yoloAllows(ctx, harness) {
28
+ if (!ctx.globals.yolo)
29
+ return false;
30
+ const original = await ctx.globals.yoloScope;
31
+ const current = await yoloScope(ctx);
32
+ if (!original || current !== original) {
33
+ ctx.warn("YOLO does not cover this target, credential or solution folder; using the standard confirmation policy. Restart with the intended target to enable it there.");
34
+ return false;
35
+ }
36
+ if (harness) {
37
+ const session = await ctx.session();
38
+ const selected = session.envFile?.harness ?? session.project?.harness;
39
+ if (!selected || (await lookupHarness(ctx, selected)).harness?.id !== harness.id) {
40
+ ctx.warn("YOLO covers only the solution selected at startup; using the standard confirmation policy for this solution.");
41
+ return false;
42
+ }
43
+ }
44
+ return true;
45
+ }
package/dist/command.js CHANGED
@@ -37,6 +37,7 @@ export function ownsTenant(spec) {
37
37
  }
38
38
  export const GLOBAL_OPTIONS = {
39
39
  json: { type: "boolean", description: "Print one JSON document instead of text." },
40
+ yolo: { type: "boolean", cliOnly: true, description: "Automatically apply eligible routine changes in this process's selected target; critical changes still need a person." },
40
41
  instance: { type: "string", value: "<url>", description: "The instance URL (overrides CAVELON_URL and cavelon.yaml)." },
41
42
  tenant: { type: "string", value: "<tenant>", description: "Tenant slug, name or id (overrides CAVELON_TENANT and cavelon.yaml)." },
42
43
  help: { type: "boolean", short: "h", description: "Show help for the command." },
@@ -13,6 +13,8 @@ import { CONFIRM_TOKEN, confirmInTerminal, confirmThroughClient, confirmToken, c
13
13
  import { actingTarget, targetLine } from "../acting.js";
14
14
  import { accessFor, operationAccess } from "../access.js";
15
15
  import { cavelonCommand, fill, personCommand } from "../printed.js";
16
+ import { apiApproval } from "../api-approval-policy.js";
17
+ import { yoloAllows } from "../automation-policy.js";
16
18
  export const JSON_BODY_DEPRECATED = "`--json <body>` as the request body is deprecated and will be removed in a later release; pass the body with --body. " +
17
19
  "--json alone prints JSON, as on every command.";
18
20
  export function splitJsonBody(args, warn) {
@@ -202,9 +204,10 @@ export const api = {
202
204
  "As an MCP tool, or run by a coding agent (" +
203
205
  AGENT_VARIABLES.filter((v) => v.variable !== "CAVELON_AGENT").map((v) => (v.value ? `${v.variable}=${v.value}` : v.variable)).join(", ") +
204
206
  "\nor CAVELON_AGENT=1 is set), an operation that changes something returns what it would send and a confirm token,\n" +
205
- "and sends it only with that token and the person's yes: as an MCP tool, confirm: \"<token>\", after which the client\n" +
206
- "asks the person; from an agent's shell, the person sends it from their own terminal. A changed request needs a new\n" +
207
- "preview; confirm: true is refused.\n" +
207
+ "and sends it with that token. Known draft creation and cloning need no personal approval; explicit --yolo also\n" +
208
+ "skips their token round trip within its bound scope. Known import previews and database catalog reads send at once.\n" +
209
+ "Other changes still need the person's yes: the MCP client asks them, or they send it from their own terminal.\n" +
210
+ "A changed request needs a new preview; confirm: true is refused. Instance confirmation requirements always win.\n" +
208
211
  "Run by an agent, one the instance marks for a person only (x-cavelon-person-only) is refused, as is a body that\n" +
209
212
  "sets a field the instance marks as a secret value (x-cavelon-secret) and a file outside the solution folder. On an\n" +
210
213
  "instance that marks no operation, one that changes a secret, creates or revokes a credential or decides an\n" +
@@ -227,8 +230,8 @@ export const api = {
227
230
  type: "string",
228
231
  value: "<token>",
229
232
  mcpToken: true,
230
- description: "Send an operation that changes something: run by a coding agent or as an MCP tool, the token its preview returned. " +
231
- "Without it, nothing is sent. A person's terminal sends at once.",
233
+ description: "Send a previewed operation: run by a coding agent or as an MCP tool, the token its preview returned. " +
234
+ "Known routine changes need no person; other changes require personal approval. A person's terminal sends at once.",
232
235
  },
233
236
  limit: { type: "string", value: "<n>", description: "Show at most n items of a list response (default 50, 0 for all)." },
234
237
  },
@@ -283,7 +286,7 @@ export const api = {
283
286
  ...(rawBody !== undefined ? ["--body", rawBody] : []),
284
287
  ...listOption(input, "file").flatMap((f) => ["--file", f]),
285
288
  ];
286
- const preview = await previewUnlessConfirmed(ctx, input, doc, op, args, driven, personCommand(...words));
289
+ const preview = await previewUnlessConfirmed(ctx, input, doc, op, args, driven, words);
287
290
  if (preview)
288
291
  return preview;
289
292
  }
@@ -308,29 +311,40 @@ export const api = {
308
311
  return { data, text };
309
312
  },
310
313
  };
311
- async function previewUnlessConfirmed(ctx, input, doc, op, args, driven, command) {
314
+ async function previewUnlessConfirmed(ctx, input, doc, op, args, driven, words) {
312
315
  const given = input.options.confirm;
313
316
  if (given === true)
314
317
  throw confirmTokenRequired("api");
315
318
  const request = previewRequest(doc, op, args);
319
+ const policy = apiApproval(op, args);
320
+ const needsPerson = policy === "person";
321
+ const harness = op.path === "/api/v1/harnesses/{harness_id}/clone" ? { id: args.params?.harness_id?.at(-1) ?? "" } : undefined;
322
+ if ((given === undefined || given === false) &&
323
+ (policy === "read" || policy === "routine" && await yoloAllows(ctx, harness)))
324
+ return undefined;
316
325
  const files = (args.files ?? []).map((f) => ({ field: f.field, file: path.relative(ctx.io.cwd, f.path) || f.path }));
317
326
  const session = await ctx.session();
318
327
  const token = confirmToken({ url: session.url, tenant: session.tenant }, "api", { request, files });
319
328
  const route = personRoute(ctx, driven);
329
+ const command = personCommand(...words);
320
330
  if (typeof given === "string" && given === token) {
321
- await personApproves(ctx, driven, { tool: "api", what: `Send ${request.method} ${request.path} (${op.alias}).`, command });
331
+ if (needsPerson)
332
+ await personApproves(ctx, driven, { tool: "api", what: `Send ${request.method} ${request.path} (${op.alias}).`, command });
322
333
  return undefined;
323
334
  }
324
335
  const stale = typeof given === "string" && given !== "";
325
336
  const bare = given === "" && driven.by === "agent";
326
- const confirm = route === "client" ? confirmThroughClient("api", token) : confirmInTerminal(command);
337
+ const confirm = needsPerson
338
+ ? route === "client" ? confirmThroughClient("api", token) : confirmInTerminal(command)
339
+ : driven.by === "mcp" ? `Call api again with the same arguments and confirm: "${token}". No personal approval is needed for this routine operation.`
340
+ : personCommand(...words, "--confirm", token);
327
341
  const target = await actingTarget(ctx);
328
342
  const shown = { operation: op.alias, ...request, ...(files.length ? { files } : {}), target, sent: false };
329
343
  const lines = [`Would send ${request.method} ${request.path}. Nothing was sent.`, targetLine(target)];
330
344
  if (stale)
331
345
  lines.push("The confirm token is not this request's: the request changed since its preview, or the token is another one's.");
332
- if (bare && driven.by === "agent")
333
- lines.push("A coding agent cannot send it: the person sends it from their own terminal.");
346
+ if (bare)
347
+ lines.push(needsPerson ? "A coding agent cannot send it: the person sends it from their own terminal." : "Pass this request's confirm token; a bare --confirm sends nothing.");
334
348
  if (op.confirmation) {
335
349
  lines.push(`The instance requires a confirmation bound to this request (x-cavelon-confirmation)${op.confirmationWhen ? `: ${op.confirmationWhen}` : ""}`, "cavelon asks the person; the instance does not verify their answer.");
336
350
  }
@@ -346,9 +360,9 @@ async function previewUnlessConfirmed(ctx, input, doc, op, args, driven, command
346
360
  return {
347
361
  data: {
348
362
  ...shown,
349
- ...(route === "client" ? { confirm_token: token } : {}),
363
+ ...(!needsPerson || route === "client" ? { confirm_token: token } : {}),
350
364
  confirm,
351
- needs_person: route,
365
+ ...(needsPerson ? { needs_person: route } : {}),
352
366
  ...(op.confirmation ? { instance_confirmation: op.confirmationWhen ?? true } : {}),
353
367
  ...(stale ? { token_mismatch: true } : {}),
354
368
  ...(bare ? { token_required: true } : {}),
@@ -44,10 +44,13 @@ const mcp = {
44
44
  description: "Started by the agent's plugin (`cavelon mcp`); it does not return until the agent disconnects.",
45
45
  readOnly: false,
46
46
  mcpTool: false,
47
+ options: { env: { type: "string", value: "<name>", description: "Start with env/<name>.yaml's tenant, solution and runtime bindings; --yolo stays bound to this environment." } },
47
48
  async run(ctx) {
49
+ if (ctx.globals.solutionEnv)
50
+ await ctx.session();
48
51
  const { createMcpServer } = await import("../mcp.js");
49
52
  const { StdioServerTransport } = await import("@modelcontextprotocol/sdk/server/stdio.js");
50
- const server = createMcpServer(ctx.io, COMMANDS);
53
+ const server = createMcpServer(ctx.io, COMMANDS, {}, ctx.globals);
51
54
  const transport = new StdioServerTransport();
52
55
  const closed = new Promise((resolve) => {
53
56
  server.onclose = () => resolve();
@@ -9,10 +9,11 @@ import { serverCommand } from "../setup-agents.js";
9
9
  import { encodeMcpEntry, isCurrentMcpEntry, isKitMcpEntry } from "../mcp-entry.js";
10
10
  import { upsertJsoncEntry } from "../jsonc-config.js";
11
11
  import { CavelonError, ExitCode, usageError } from "../errors.js";
12
- import { confinedPath, realPath, within } from "../paths.js";
12
+ import { privateDirs, confinedPath, realPath, within } from "../paths.js";
13
+ import { solutionPath, solutionPaths } from "../file-boundary.js";
13
14
  import { readTextFile, withoutBom, writeFileAtomic } from "../fsutil.js";
14
15
  import { git } from "../git.js";
15
- import { ensureStateDir, fileDigests, rememberAppliedFiles, STATE_DIR } from "../local-state.js";
16
+ import { checkStatePaths, ensureStateDir, fileDigests, rememberAppliedFiles, STATE_DIR } from "../local-state.js";
16
17
  import { isGenerated, upsertBlock, upsertJsonEntry } from "../markers.js";
17
18
  import { packageVersionOf } from "../package-check.js";
18
19
  import { MANIFEST_SECTION, PERSONA_SECTION, personaYaml, requiredFields, sectionFields } from "../package-format.js";
@@ -46,17 +47,9 @@ const GITIGNORE_BLOCK = ["# Local cavelon state (inventory, previews); never com
46
47
  function rel(root, file) {
47
48
  return path.relative(root, file).split(path.sep).join("/");
48
49
  }
49
- async function realFile(file) {
50
- try {
51
- return await fs.realpath(file);
52
- }
53
- catch {
54
- return file;
55
- }
56
- }
57
- async function applyBlock(root, file, result, mode) {
50
+ async function applyBlock(root, file, result, mode, boundary = root) {
58
51
  if (result.content !== undefined && result.outcome !== "unchanged" && result.outcome !== "skipped") {
59
- const target = await realFile(file);
52
+ const target = await solutionPath(boundary, file);
60
53
  const current = await fs.stat(target).then((st) => st.mode & 0o777, () => undefined);
61
54
  await writeFileAtomic(target, result.content, current ?? mode);
62
55
  }
@@ -64,19 +57,20 @@ async function applyBlock(root, file, result, mode) {
64
57
  }
65
58
  async function block(root, relative, body, style, options = {}) {
66
59
  const file = path.join(root, relative);
67
- return applyBlock(root, file, upsertBlock(await readTextFile(file), body, style, options));
60
+ const target = await solutionPath(root, file);
61
+ return applyBlock(root, file, upsertBlock(await readTextFile(target), body, style, options));
68
62
  }
69
63
  async function claudeImport(root, onlyExisting) {
70
- const claude = path.join(root, "CLAUDE.md");
64
+ const claude = await solutionPath(root, path.join(root, "CLAUDE.md"));
71
65
  if ((await readTextFile(claude)) === undefined)
72
66
  return undefined;
73
- if ((await realFile(claude)) === (await realFile(path.join(root, "AGENTS.md")))) {
67
+ if ((await realPath(claude)) === (await realPath(path.join(root, "AGENTS.md")))) {
74
68
  return { file: "CLAUDE.md", action: "unchanged", reason: "it is AGENTS.md" };
75
69
  }
76
70
  return block(root, "CLAUDE.md", "@AGENTS.md", "html", { onlyExisting });
77
71
  }
78
72
  async function ownFile(root, relative, content) {
79
- const file = path.join(root, relative);
73
+ const file = await solutionPath(root, path.join(root, relative));
80
74
  if ((await readTextFile(file)) !== undefined)
81
75
  return { file: relative, action: "unchanged" };
82
76
  await writeFileAtomic(file, content);
@@ -153,7 +147,7 @@ async function manifestFile(ctx, session, project, chosen) {
153
147
  return action;
154
148
  }
155
149
  async function generatedFile(root, relative, content) {
156
- const file = path.join(root, relative);
150
+ const file = await solutionPath(root, path.join(root, relative));
157
151
  const existing = await readTextFile(file);
158
152
  if (existing === undefined) {
159
153
  await writeFileAtomic(file, content);
@@ -167,7 +161,7 @@ async function generatedFile(root, relative, content) {
167
161
  return { file: relative, action: "updated" };
168
162
  }
169
163
  async function folder(root, relative) {
170
- const dir = path.join(root, relative);
164
+ const dir = await solutionPath(root, path.join(root, relative));
171
165
  try {
172
166
  await fs.stat(dir);
173
167
  return [];
@@ -222,7 +216,7 @@ async function writeMcp(root, target, onlyExisting, env) {
222
216
  return { file: rel(root, plan.directory), action: exists ? "updated" : "created" };
223
217
  }
224
218
  const file = path.join(root, target.file);
225
- const existing = await readTextFile(file);
219
+ const existing = await readTextFile(await solutionPath(root, file));
226
220
  if (existing !== undefined && holdsOtherForm(existing, target))
227
221
  return { file: target.file, action: "unchanged" };
228
222
  if (target.format === "toml")
@@ -308,12 +302,14 @@ async function installHook(root, onlyExisting) {
308
302
  reason: `core.hooksPath points to ${path.dirname(file)}, outside this repository, where other repositories' hooks may be; add the block yourself if you want it there`,
309
303
  };
310
304
  }
305
+ const boundary = own[inside.indexOf(true)];
306
+ await solutionPath(boundary, file);
311
307
  const body = HOOK_LINES(prefix).join("\n");
312
308
  const existing = await readTextFile(file);
313
309
  let result = upsertBlock(existing, body, "hash", { onlyExisting, afterShebang: true });
314
310
  if (result.outcome === "created")
315
311
  result = { ...result, content: `#!/bin/sh\n${result.content}` };
316
- const action = await applyBlock(root, file, result, 0o700);
312
+ const action = await applyBlock(root, file, result, 0o700, boundary);
317
313
  if (action.action !== "skipped" && action.action !== "unchanged") {
318
314
  const mode = (await fs.stat(file)).mode & 0o777;
319
315
  if (!(mode & 0o100))
@@ -566,6 +562,17 @@ async function importPackage(ctx, project, from, pkg, force) {
566
562
  ctx.warn(`Did not write section ${JSON.stringify(section)}: its name is not a plain file name.`);
567
563
  return { from, files, ignored, package_version: version ?? null };
568
564
  }
565
+ async function checkInitPaths(ctx, root, agents, update) {
566
+ const project = (await ctx.session()).project;
567
+ const layouts = project?.root === root ? [project.layout.package, ...Object.values(project.layout.items)] : ["package", "tests"];
568
+ const roots = update ? KNOWN_SKILL_ROOTS : agents.length ? skillRootsFor(agents) : [];
569
+ const skills = roots.length ? await bundledSkills() : [];
570
+ const files = [PROJECT_FILE, ...layouts, "tests", "seeds", "env/test.yaml", "env/prod.yaml", STATE_DIR, "AGENTS.md", "CLAUDE.md", ".gitignore",
571
+ ...roots, ...roots.flatMap(dir => skills.flatMap(skill => skill.files.map(file => `${dir}/${skill.name}/${file.path}`))),
572
+ ...(update ? AGENTS : agents).flatMap(agent => agent.mcp && agent.mcp.format !== "native" ? [agent.mcp.file] : [])];
573
+ await solutionPaths(root, files, privateDirs(ctx.io.env));
574
+ await checkStatePaths(root);
575
+ }
569
576
  async function runInit(ctx, input) {
570
577
  const update = boolOption(input, "update");
571
578
  const from = stringOption(input, "from");
@@ -583,6 +590,7 @@ async function runInit(ctx, input) {
583
590
  if (boolOption(input, "new") && (update || (!stringOption(input, "harness") && !from))) {
584
591
  throw usageError("--new needs the new solution's name: --harness <name>.", `\`${cavelonCommand("init", "--harness", fill("name"), "--new")}\` creates it as a draft, even when an existing solution has a similar name.`);
585
592
  }
593
+ await checkInitPaths(ctx, update ? session.project?.root ?? ctx.io.cwd : ctx.io.cwd, agents, update);
586
594
  const imported = from ? await readImportFile(ctx, from) : undefined;
587
595
  if (update) {
588
596
  if (!session.project)
@@ -656,7 +664,7 @@ async function runInit(ctx, input) {
656
664
  values.package_version = version;
657
665
  values.layout = defaultLayoutFor(schema);
658
666
  const note = tenant && (tenant.name || tenant.id !== tenant.ref) ? commentText([tenant.name, tenant.id !== tenant.ref ? tenant.id : undefined].filter(Boolean).join(", ")) : undefined;
659
- await writeFileAtomic(path.join(root, PROJECT_FILE), solutionYaml(values, note));
667
+ await writeFileAtomic(await solutionPath(root, path.join(root, PROJECT_FILE)), solutionYaml(values, note));
660
668
  actions.push({ file: PROJECT_FILE, action: "created" });
661
669
  }
662
670
  const project = parseProject(path.join(root, PROJECT_FILE), (await readTextFile(path.join(root, PROJECT_FILE))));
@@ -1,9 +1,8 @@
1
- import path from "node:path";
2
1
  import { CavelonError } from "../errors.js";
3
2
  import { table } from "../format.js";
4
3
  import { readJsonFile } from "../fsutil.js";
5
4
  import { callStable } from "../invoke.js";
6
- import { STATE_DIR, stateDir, writeState } from "../local-state.js";
5
+ import { STATE_DIR, statePath, writeState } from "../local-state.js";
7
6
  const LISTINGS = [
8
7
  { label: "solutions", path: "/api/v1/harnesses", kind: "solutions", field: "slug" },
9
8
  { label: "knowledge bases", path: "/api/v1/knowledge-bases", query: { page_size: 100 }, kind: "knowledge_bases", field: "name" },
@@ -15,7 +14,7 @@ const LISTINGS = [
15
14
  ];
16
15
  const INVENTORY_JSON = "inventory.json";
17
16
  export async function readInventory(root) {
18
- const inventory = await readJsonFile(path.join(stateDir(root), INVENTORY_JSON));
17
+ const inventory = await readJsonFile(await statePath(root, INVENTORY_JSON));
19
18
  return inventory && typeof inventory === "object" && inventory.names && typeof inventory.names === "object" ? inventory : undefined;
20
19
  }
21
20
  export async function refreshInventory(root, kind, names, now) {
@@ -1,4 +1,5 @@
1
1
  import { noteLines, runCapacityNote } from "../capacity.js";
2
+ import { yoloAllows } from "../automation-policy.js";
2
3
  import { boolOption, CURSOR_OPTION, intOption, LIMIT_OPTION, positional, stringOption, } from "../command.js";
3
4
  import { CavelonError, ExitCode, usageError } from "../errors.js";
4
5
  import { confirmation, confirmTokenRequired, PERSON_CONFIRMS_HELP } from "../confirm-token.js";
@@ -180,8 +181,8 @@ export const loopStart = {
180
181
  name: "loop start",
181
182
  summary: "Start a loop through its trigger, as you; previews first, --confirm starts it and returns the run and operation ids.",
182
183
  description: "Calls the trigger's run-now route. The run (and its loop) acts as the caller: with a personal access token, the person.\n" +
183
- "It runs on its own and spends the tenant's model budget, so without --confirm nothing starts: the preview names the\n" +
184
- "trigger, its solution and the payload. Show it to a person and confirm only with their yes. For a trigger of a draft\n" +
184
+ "It runs on its own and spends the tenant's model budget. The preview names the trigger, its solution and the payload.\n" +
185
+ "--yolo starts a draft's run at once only for the solution selected at startup; existing budget limits still apply. For a trigger of a draft\n" +
185
186
  "solution an agent confirms with the preview's token (--confirm <token>, or confirm over MCP); for any other,\n" +
186
187
  "a coding agent cannot confirm it: over MCP the client asks the person, and from an agent's shell the person runs the\n" +
187
188
  "confirm in their own terminal. Follow the run with `loop watch <run>`, or `wait <operation>`; `loop cancel <run>` stops it.",
@@ -194,7 +195,7 @@ export const loopStart = {
194
195
  wait: WAIT_OPTION,
195
196
  timeout: TIMEOUT_OPTION,
196
197
  "idempotency-key": UUID_KEY_OPTION,
197
- confirm: { type: "boolean", mcpToken: true, description: "Start the run (after a person saw the preview)." },
198
+ confirm: { type: "boolean", mcpToken: true, description: "Start the previewed run; a non-draft run also needs the person's approval." },
198
199
  },
199
200
  examples: [
200
201
  "cavelon loop start counter",
@@ -214,9 +215,10 @@ export const loopStart = {
214
215
  const solution = await triggerSolution(ctx, trigger);
215
216
  const given = stringOption(input, "idempotency-key");
216
217
  const words = ["loop", "start", trigger.slug, ...(raw !== undefined ? ["--input", raw] : []), ...(given ? ["--idempotency-key", given] : [])];
218
+ const automatic = input.options.confirm === undefined && solution?.status === "draft" && await yoloAllows(ctx, solution);
217
219
  const gate = await confirmation(ctx, input, "loop_start", { trigger: trigger.id, payload }, {
218
220
  ...(solution?.status === "draft"
219
- ? {}
221
+ ? { automatic }
220
222
  : { person: { what: `Start a run of the trigger ${trigger.slug}, which acts as the person and spends the tenant's model budget.`, words: [...words, "--confirm"] } }),
221
223
  });
222
224
  if (!gate.confirmed) {
@@ -241,7 +243,7 @@ export const loopStart = {
241
243
  : `Solution: ${solution.id} (not readable).`,
242
244
  `Payload: ${payloadText}`,
243
245
  gate.where, ...(gate.mismatch ? [gate.mismatch] : []),
244
- `Nothing was started. Show this to a person; with their yes: ${confirm}`,
246
+ solution?.status === "draft" ? `Nothing was started. Confirm the requested draft run with: ${confirm}` : `Nothing was started. The person approves this run with: ${confirm}`,
245
247
  ].join("\n"),
246
248
  ...(gate.exitCode ? { exitCode: gate.exitCode } : {}),
247
249
  };
@@ -256,7 +258,8 @@ export const loopStart = {
256
258
  });
257
259
  if (!trigger.is_active)
258
260
  ctx.warn(`Trigger "${trigger.slug}" is not active: its schedule and webhook start no runs, though this manual start did.`);
259
- const started = { trigger: { id: trigger.id, slug: trigger.slug }, ...runSummary(run), idempotency_key: key };
261
+ const started = { trigger: { id: trigger.id, slug: trigger.slug }, ...runSummary(run), idempotency_key: key,
262
+ ...(automatic ? { approval: { source: "yolo", reason: "selected draft run" } } : {}) };
260
263
  if (boolOption(input, "wait") && ctx.mode === "cli" && run.operation_id) {
261
264
  const waited = await waitAndReport(ctx, [run.operation_id], timeoutMs(ctx, stringOption(input, "timeout")));
262
265
  const text = `Started run ${run.id} of ${trigger.slug}.\n${waited.text}`;
@@ -18,6 +18,7 @@ import { ceilingHint, LIMIT_ABOVE_CEILING, parseLimits, readLimits } from "../li
18
18
  import { digest, fileDigest, fileDigests, listPreviews, loadPreview, previewExpiry, readItemFiles, readPulledFiles, rememberAppliedFiles, retiredPreview, retirePreviews, savePreview, writePulledFiles, writeState, } from "../local-state.js";
19
19
  import { catalogEntry, checkPackage, KIT_CODES, packageVersionOf } from "../package-check.js";
20
20
  import { applyQueryNotes, connectorOffer, importWritesQueries, NEEDS_SUPERADMIN_CODE, queryBlockedHint, queryChanges, queryTools, readQueryBaseline, rememberQueries, schemaKnowsWrites } from "../database-queries.js";
21
+ import { yoloAllows } from "../automation-policy.js";
21
22
  import { cliFix, similarCodes } from "../code-hints.js";
22
23
  import { KIT_ERROR_CODES } from "../kit-codes.js";
23
24
  import { confirmationPointer } from "../change-confirmation.js";
@@ -726,7 +727,7 @@ function importNeedsAPerson(access) {
726
727
  details: { credential: access?.kind ?? null, needs_a_person: true, reason: person },
727
728
  });
728
729
  }
729
- async function confirmPreview(ctx, project, previewId, allowStale) {
730
+ async function confirmPreview(ctx, project, previewId, allowStale, automatic = false) {
730
731
  const stored = await loadPreview(project.root, previewId);
731
732
  const session = await ctx.session();
732
733
  if (!stored) {
@@ -770,13 +771,6 @@ async function confirmPreview(ctx, project, previewId, allowStale) {
770
771
  const driven = drivenByAgent(ctx);
771
772
  const queries = importWritesQueries(stored.preview);
772
773
  const guarded = queries || stored.request[INCLUDE_TENANT_WIDE] === true || stored.request.package.manifest?.scope === "full_config";
773
- if (driven && (queries || stored.person_reason !== null)) {
774
- const into = stored.harness ? `solution ${stored.harness.slug}` : "the tenant";
775
- const reason = stored.person_reason ?? (queries ? QUERY_IMPORT_REASON : "was stored by an older cavelon, which did not record whether it needs a person");
776
- await personApproves(ctx, driven, { tool: "apply", what: `Import preview ${stored.preview_id} into ${into}: it ${reason}.`, command: personApplyCommand(stored), guarded });
777
- }
778
- else if (!driven)
779
- ctx.approved = { guarded };
780
774
  const acting = await actingTarget(ctx);
781
775
  const disk = await readPackage(project.root, project.layout);
782
776
  const changed = await filesChangedSince(project, stored, disk);
@@ -793,6 +787,13 @@ async function confirmPreview(ctx, project, previewId, allowStale) {
793
787
  ctx.warn(`The package files changed since this preview${changed.length ? ` (${list(changed, 5)})` : ""}; importing what the preview showed (--allow-stale). ` +
794
788
  `The files keep their changes, which the instance does not hold; run \`${cavelonCommand("apply")}\` to preview them.`);
795
789
  }
790
+ if (driven && (queries || stored.person_reason !== null)) {
791
+ const into = stored.harness ? `solution ${stored.harness.slug}` : "the tenant";
792
+ const reason = stored.person_reason ?? (queries ? QUERY_IMPORT_REASON : "was stored by an older cavelon, which did not record whether it needs a person");
793
+ await personApproves(ctx, driven, { tool: "apply", what: `Import preview ${stored.preview_id} into ${into}: it ${reason}.`, command: personApplyCommand(stored), guarded });
794
+ }
795
+ else if (!driven && !automatic)
796
+ ctx.approved = { guarded };
796
797
  try {
797
798
  const result = await callStable(ctx, "POST", "/api/v1/agent-graph/import", "importing packages", {
798
799
  body: { ...stored.request, preview_id: stored.preview_id },
@@ -951,7 +952,8 @@ function personReason(preview, harness, mode, env, shared = [], sharedReaches =
951
952
  export const apply = {
952
953
  name: "apply",
953
954
  summary: "Preview the package files against the instance and print a preview id; --confirm <id> imports exactly that preview.",
954
- description: "Without --confirm nothing is imported: the preview shows what changes, which active solutions it reaches, what the target\n" +
955
+ description: "Without --confirm, shows a preview. With --yolo, an eligible routine draft is previewed and imported in one call.\n" +
956
+ "The preview shows what changes, which active solutions it reaches, what the target\n" +
955
957
  "still needs (secrets and variables with the command that sets each, grants, runtime bindings, trigger identities), loop\n" +
956
958
  "budgets and ignored sections, and is stored in .cavelon/. A preview never creates the solution: one the env file names\n" +
957
959
  "that is not on the instance yet gets the `cavelon harness new` command that creates it as a draft. A person sets the\n" +
@@ -1179,6 +1181,18 @@ export const apply = {
1179
1181
  const expired = (await listPreviews(project.root, ctx.io.now())).filter((old) => old.expired);
1180
1182
  await retirePreviews(project.root, expired.map((old) => ({ preview_id: old.preview_id, reason: "expired", at })));
1181
1183
  }
1184
+ const queryEffectsKnown = !queryTools(disk.package).length ||
1185
+ Array.isArray(preview.database_queries?.would_write);
1186
+ if (preview.preview_id && !reason && !refusal && harness?.status === "draft" &&
1187
+ scope === "agent_graph" && queryEffectsKnown && preview.summary && Array.isArray(preview.impact?.active_harnesses) &&
1188
+ await yoloAllows(ctx, harness)) {
1189
+ const applied = await confirmPreview(ctx, project, preview.preview_id, false, true);
1190
+ return {
1191
+ ...applied,
1192
+ data: { ...applied.data, approval: { source: "yolo", reason: "routine draft import" } },
1193
+ text: `YOLO: validated and previewed the routine draft change.\n${applied.text}`,
1194
+ };
1195
+ }
1182
1196
  data.show_to_person = Boolean(reason || refusal);
1183
1197
  const driven = drivenByAgent(ctx);
1184
1198
  const route = !refusal && driven && reason && preview.preview_id ? personRoute(ctx, driven) : undefined;
@@ -39,6 +39,9 @@ async function gateOf(ctx, input, tool, change, options) {
39
39
  const given = input.options.confirm;
40
40
  const driven = drivenByAgent(ctx);
41
41
  const tokenGiven = typeof given === "string" && given !== "";
42
+ if (options.automatic && !options.person && given === undefined) {
43
+ return { confirmed: true, fields: {}, confirm: (command) => command };
44
+ }
42
45
  const approve = () => {
43
46
  if (!driven)
44
47
  ctx.approved = { guarded: Boolean(options.person) };
@@ -86,7 +89,7 @@ async function gateOf(ctx, input, tool, change, options) {
86
89
  confirmed: false,
87
90
  fields: { confirm_token: token, token_required: true },
88
91
  confirm,
89
- mismatch: `--confirm alone does not confirm when a coding agent runs cavelon. Nothing was changed: show the person this preview, and with their yes run the command below, which carries this change's token.`,
92
+ mismatch: `--confirm alone does not confirm when a coding agent runs cavelon. Nothing was changed: review this preview against the requested work, then run the command below, which carries this change's token.`,
90
93
  exitCode: ExitCode.needsAction,
91
94
  };
92
95
  }
@@ -134,7 +137,7 @@ export function needsPerson(command) {
134
137
  });
135
138
  }
136
139
  export function confirmThroughClient(tool, token) {
137
- return `Show the person this, then call ${tool} again with the same arguments and confirm: "${token}": the client then asks the person to approve exactly this change, and nothing changes without their yes.`;
140
+ return `Call ${tool} again with the same arguments and confirm: "${token}": the client asks the person to approve exactly this change. Do not ask for an additional chat confirmation; nothing changes without the dialog's yes.`;
138
141
  }
139
142
  export function confirmInTerminal(command) {
140
143
  return `${command} (the person runs it in their own terminal: a coding agent cannot confirm this change)`;
@@ -143,16 +146,16 @@ export function shellTokenRequired(command) {
143
146
  return new CavelonError(ExitCode.needsAction, {
144
147
  code: "confirm_token_required",
145
148
  message: "--confirm alone does not confirm when a coding agent runs cavelon; nothing was changed.",
146
- hint: `Run \`${command}\` without --confirm, show the person the preview, and with their yes run the command it prints, which carries the change's token.`,
149
+ hint: `Run \`${command}\` without --confirm and review the preview. Follow needs_person when present; otherwise confirm the requested work with the token it prints.`,
147
150
  });
148
151
  }
149
152
  export function confirmTokenRequired(tool) {
150
153
  return new CavelonError(ExitCode.usage, {
151
154
  code: "confirm_token_required",
152
155
  message: `${tool} confirms only with the confirm_token its preview returned, not with true; nothing was changed.`,
153
- hint: `Call ${tool} without confirm, show the person what it would do, then call it again with the same arguments and confirm set to its confirm_token.`,
156
+ hint: `Call ${tool} without confirm and review the preview. Follow needs_person when present; otherwise call it again for the requested work with confirm set to its confirm_token.`,
154
157
  });
155
158
  }
156
159
  export function confirmWith(tool, token) {
157
- return `Show the person this, then call ${tool} again with the same arguments and confirm: "${token}" to make exactly this change.`;
160
+ return `Review this preview against the requested work, then call ${tool} again with the same arguments and confirm: "${token}" to make exactly this change. No additional person approval is required.`;
158
161
  }
package/dist/context.js CHANGED
@@ -5,6 +5,12 @@ import { ApiClient } from "./http.js";
5
5
  import { colorEnabled, styleFor } from "./io.js";
6
6
  import { requireInstance, requireToken, resolveSession, resolveTenantId } from "./session.js";
7
7
  import { detectShell, useShell } from "./shell.js";
8
+ import { checkStatePaths } from "./local-state.js";
9
+ import { promises as fs } from "node:fs";
10
+ import { checkPrivatePaths, solutionPaths } from "./file-boundary.js";
11
+ import { privateDirs as kitPrivateDirs } from "./paths.js";
12
+ import path from "node:path";
13
+ import { yoloScope } from "./automation-policy.js";
8
14
  export function createContext(io, globals, mode = "cli") {
9
15
  const warnings = [];
10
16
  useShell(detectShell(io.env));
@@ -23,7 +29,26 @@ export function createContext(io, globals, mode = "cli") {
23
29
  warnings.push(message);
24
30
  },
25
31
  session() {
26
- sessionPromise ??= resolveSession(io.env, io.cwd, globals);
32
+ sessionPromise ??= (async () => {
33
+ const session = await resolveSession(io.env, io.cwd, globals);
34
+ const project = session.project;
35
+ if (project) {
36
+ const privateDirs = kitPrivateDirs(io.env);
37
+ const dirs = [project.layout.package, ...Object.values(project.layout.items), ".cavelon", "env"];
38
+ await solutionPaths(project.root, dirs, privateDirs);
39
+ await checkStatePaths(project.root);
40
+ for (const dir of [...dirs, ".cavelon/previews"]) {
41
+ const files = await fs.readdir(path.resolve(project.root, dir)).catch((error) => {
42
+ if (error.code === "ENOENT")
43
+ return [];
44
+ throw error;
45
+ });
46
+ await checkPrivatePaths(project.root, files.map(file => path.join(dir, file)), privateDirs);
47
+ }
48
+ await checkPrivatePaths(project.root, [project.file], privateDirs);
49
+ }
50
+ return session;
51
+ })();
27
52
  return sessionPromise;
28
53
  },
29
54
  async client(options = {}) {
@@ -52,6 +77,8 @@ export function createContext(io, globals, mode = "cli") {
52
77
  return contractsPromise;
53
78
  },
54
79
  };
80
+ if (globals.yolo && !globals.yoloScope)
81
+ globals.yoloScope = yoloScope(ctx).catch(() => undefined);
55
82
  return ctx;
56
83
  }
57
84
  export function withWarnings(data, warnings) {
@@ -1,6 +1,5 @@
1
- import path from "node:path";
2
1
  import { readJsonFile } from "./fsutil.js";
3
- import { stateDir, writeState } from "./local-state.js";
2
+ import { statePath, writeState } from "./local-state.js";
4
3
  import { locate } from "./package-files.js";
5
4
  import { canonical, settledForm } from "./package-format.js";
6
5
  export const QUERY_TOOL_TYPE = "database_query";
@@ -478,7 +477,7 @@ function baselineOf(schema, tool) {
478
477
  return out;
479
478
  }
480
479
  export async function readQueryBaseline(root) {
481
- const stored = await readJsonFile(path.join(stateDir(root), BASELINE_FILE));
480
+ const stored = await readJsonFile(await statePath(root, BASELINE_FILE));
482
481
  return stored && isObject(stored.tools) ? stored : undefined;
483
482
  }
484
483
  export async function rememberQueries(root, pkg, schema, by, now) {