@cavelon/cli 0.2.6 → 0.2.8

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.
package/dist/access.js CHANGED
@@ -4,6 +4,10 @@ import { cavelonCommand } from "./printed.js";
4
4
  export const ACTIVATE_PERMISSION = "harnesses.activate";
5
5
  const SETTINGS_VALUES = ["settings.secrets.manage", "settings.manage"];
6
6
  export const OPERATION_PERMISSIONS = {
7
+ "GET /api/v1/harnesses/{harness_id}/publication": ["harnesses.view"],
8
+ "POST /api/v1/harnesses/{harness_id}/publish": ["harnesses.manage", "harnesses.activate"],
9
+ "POST /api/v1/harnesses/{harness_id}/rollback": ["harnesses.manage", "harnesses.activate"],
10
+ "POST /api/v1/harnesses/{harness_id}/discard-draft": ["harnesses.manage"],
7
11
  "POST /api/v1/agent-graph/import": ["agents.edit"],
8
12
  "POST /api/v1/harnesses": ["harnesses.manage"],
9
13
  "POST /api/v1/harnesses/{harness_id}/activate": ["harnesses.manage", ACTIVATE_PERMISSION],
@@ -119,11 +119,17 @@ function byPathWords(op) {
119
119
  const words = op.path.toLowerCase().split("/").filter((word) => word && !word.startsWith("{"));
120
120
  return FOR_A_PERSON.find((rule) => words.some((word) => rule.match(word)));
121
121
  }
122
+ function privacyRelease(op) {
123
+ return op.personOnly?.marked === true && op.method === "POST" &&
124
+ (op.path === "/api/v1/knowledge-bases/{kb_id}/documents/{doc_id}/release" || op.path === "/api/v1/admin/uploads/{file_id}/release");
125
+ }
122
126
  export function keptForPerson(op, all) {
123
127
  if (all.some((o) => o.personOnly)) {
124
128
  if (!op.personOnly?.marked)
125
129
  return undefined;
126
- const hint = byPathWords(op)?.hint ?? `A person runs it: in Cavelon, or in their own terminal with \`cavelon api ${op.alias}\`.`;
130
+ const hint = privacyRelease(op)
131
+ ? "A person with knowledge_bases.manage_documents reviews and releases the document in the Admin. API keys and personal access tokens cannot release it, including from a person's terminal."
132
+ : byPathWords(op)?.hint ?? `A person runs it: in Cavelon, or in their own terminal with \`cavelon api ${op.alias}\`.`;
127
133
  return { source: "instance", ...(op.personOnly.reason ? { reason: op.personOnly.reason } : {}), hint };
128
134
  }
129
135
  if (op.readOnly)
@@ -212,7 +218,8 @@ export const api = {
212
218
  "sends a file outside the solution folder. Secret body fields (x-cavelon-secret) are refused in every mode, including\n" +
213
219
  "a person's terminal; enter passwords, keys and keytabs in the Admin. On an\n" +
214
220
  "instance that marks no operation, one that changes a secret, creates or revokes a credential or decides an\n" +
215
- "approval is refused. A person's own terminal sends at once.\n" +
221
+ "approval is refused. A person's own terminal sends ordinary requests at once. Releasing held documents needs\n" +
222
+ "a dashboard person; no kit credential sends either release operation, including with YOLO.\n" +
216
223
  "In a solution folder, the persona operations (get_bot_persona, upsert_bot_persona, …) get the folder's solution as\n" +
217
224
  "harness_id when none is passed, since without it they reach the tenant's default route.",
218
225
  readOnly: false,
@@ -264,6 +271,13 @@ export const api = {
264
271
  }
265
272
  const rawOutput = stringOption(input, "output");
266
273
  const output = rawOutput ? await confinedPath(ctx, rawOutput, "The output file", confine) : undefined;
274
+ if (privacyRelease(op)) {
275
+ throw new CavelonError(ExitCode.needsAction, {
276
+ code: "operation_for_a_person",
277
+ message: `${op.alias} requires a dashboard person; cavelon holds a token and does not send this request.`,
278
+ hint: keptForPerson(op, operations(doc)).hint,
279
+ });
280
+ }
267
281
  if (driven) {
268
282
  const kept = keptForPerson(op, operations(doc));
269
283
  if (kept) {
@@ -0,0 +1,115 @@
1
+ import { promises as fs } from "node:fs";
2
+ import { drivenByAgent } from "../agent-env.js";
3
+ import { intOption, positional, stringOption } from "../command.js";
4
+ import { CavelonError, ExitCode, usageError } from "../errors.js";
5
+ import { table } from "../format.js";
6
+ import { callOperation, callStable, workflowOperation } from "../invoke.js";
7
+ import { confinedPath } from "../paths.js";
8
+ import { resolveKbId } from "./work.js";
9
+ const DOCUMENTS = "/api/v1/knowledge-bases/{kb_id}/documents";
10
+ const FILES = `${DOCUMENTS}/{doc_id}/files`;
11
+ const REVIEW = "A person with knowledge_bases.manage_documents reviews and releases it in the Admin. Tokens and API keys cannot release it; YOLO does not change this.";
12
+ const kbOption = { type: "string", value: "<name-or-id>", description: "The knowledge base's name or id." };
13
+ async function kbOf(ctx, input) {
14
+ const ref = stringOption(input, "kb");
15
+ if (!ref)
16
+ throw usageError("Which knowledge base?", "Pass --kb <name-or-id>.");
17
+ return (await resolveKbId(ctx, ref)).id;
18
+ }
19
+ async function filesOf(ctx, kb, document) {
20
+ return callStable(ctx, "GET", FILES, "a document's conversion files", { params: { kb_id: [kb], doc_id: [document] } });
21
+ }
22
+ export const kbDocuments = {
23
+ name: "kb documents",
24
+ summary: "List documents and their status, including those held for privacy review.",
25
+ readOnly: true,
26
+ idempotent: true,
27
+ mcpTool: "kb_documents",
28
+ operations: [`GET ${DOCUMENTS}`],
29
+ options: { kb: kbOption, limit: { type: "string", value: "<n>", description: "Show at most n documents (default 50, at most 200)." } },
30
+ examples: ["cavelon kb documents --kb Records --json"],
31
+ async run(ctx, input) {
32
+ const kb = await kbOf(ctx, input);
33
+ const limit = intOption(input, "limit", { min: 1, max: 200, fallback: 50 });
34
+ const documents = await callStable(ctx, "GET", DOCUMENTS, "a knowledge base's documents", { params: { kb_id: [kb] } });
35
+ const items = documents.slice(0, limit).map(d => ({ ...d, needs_person: d.status === "held" }));
36
+ if (documents.length > limit)
37
+ ctx.warn(`Showing ${limit} of ${documents.length} documents. cavelon api list_documents --limit 0 --output <file> saves the full list; pass kb_id too.`);
38
+ return {
39
+ data: { kb_id: kb, items, total: documents.length },
40
+ text: (table(items, ["filename", "status", "needs_person", "id"]) || "No documents.") + (items.some(d => d.needs_person) ? `\n\nheld: not indexed or readable. ${REVIEW}` : ""),
41
+ };
42
+ },
43
+ };
44
+ export const kbFiles = {
45
+ name: "kb files",
46
+ summary: "List a document's conversion file ids, access flags and privacy summary.",
47
+ description: "The list contains metadata only. Restricted reports and privacy vaults remain dashboard-only; a held document cannot be read or downloaded.",
48
+ readOnly: true,
49
+ idempotent: true,
50
+ mcpTool: "kb_files",
51
+ operations: [`GET ${FILES}`],
52
+ positionals: [{ name: "document", description: "Document id.", required: true }],
53
+ options: { kb: kbOption },
54
+ examples: ["cavelon kb files <document-id> --kb Records --json"],
55
+ async run(ctx, input) {
56
+ const data = await filesOf(ctx, await kbOf(ctx, input), positional(input, "document"));
57
+ return {
58
+ data,
59
+ text: [`Document ${data.document_id}: ${data.status}`, table(data.files, ["kind", "filename", "size_bytes", "agent_readable", "restricted", "id"]) || "No conversion files.", ...(data.privacy ? [`Privacy summary: ${JSON.stringify(data.privacy)}`] : []), ...(data.status === "held" ? [REVIEW] : [])].join("\n\n"),
60
+ };
61
+ },
62
+ };
63
+ export const kbDownload = {
64
+ name: "kb download",
65
+ summary: "Save a document or one of its readable conversion files without overwriting a local file.",
66
+ description: "Without --file, the instance serves the redacted PDF where privacy_document is on. --file takes an id from kb files, never a filename or URL. Reports and vaults require a dashboard person. Output from an agent stays inside the solution folder.",
67
+ readOnly: true,
68
+ mcpTool: "kb_download",
69
+ operations: [`GET ${FILES}`, `GET ${FILES}/{file_id}`, `GET ${DOCUMENTS}/{doc_id}/download`],
70
+ positionals: [{ name: "document", description: "Document id.", required: true }],
71
+ options: { kb: kbOption, file: { type: "string", value: "<file-id>", description: "Id of an agent-readable conversion file from kb files." }, output: { type: "string", value: "<path>", description: "New local file to write; required." } },
72
+ examples: ["cavelon kb download <document-id> --kb Records --output record.pdf", "cavelon kb download <document-id> --kb Records --file <file-id> --output tables.xlsx"],
73
+ async run(ctx, input) {
74
+ const raw = stringOption(input, "output");
75
+ if (!raw)
76
+ throw usageError("Where should the file be saved?", "Pass --output <path> for a new file.");
77
+ const output = await confinedPath(ctx, raw, "The output file", drivenByAgent(ctx) !== undefined);
78
+ const kb = await kbOf(ctx, input);
79
+ const document = positional(input, "document");
80
+ const listing = await filesOf(ctx, kb, document);
81
+ if (listing.status === "held")
82
+ throw new CavelonError(ExitCode.needsAction, { code: "held_for_privacy_review", message: "This document is held for privacy review and cannot be read or downloaded.", hint: REVIEW });
83
+ const id = stringOption(input, "file");
84
+ const file = id ? listing.files.find(f => f.id === id) : undefined;
85
+ if (id && !file)
86
+ throw usageError("That file id is not listed for this document.", "Choose an id from kb files.");
87
+ if (file && (file.restricted || file.agent_readable !== true || file.kind === "privacy_vault" || file.kind === "conversion_report"))
88
+ throw new CavelonError(ExitCode.needsAction, { code: "document_file_for_a_person", message: "This file is not available to agents or tokens.", hint: "A person with knowledge_bases.manage_documents opens the restricted file in the Admin. The privacy vault and conversion report are never agent-readable." });
89
+ const route = file ? `${FILES}/{file_id}` : `${DOCUMENTS}/{doc_id}/download`;
90
+ const { doc, op } = await workflowOperation(ctx, "GET", route, "downloading a document file");
91
+ let handle;
92
+ try {
93
+ handle = await fs.open(output, "wx", 0o600);
94
+ }
95
+ catch (error) {
96
+ if (error.code === "EEXIST")
97
+ throw usageError(`The output file ${raw} already exists.`, "Choose a new output path.");
98
+ throw error;
99
+ }
100
+ let bytes;
101
+ try {
102
+ const response = await callOperation(ctx, await ctx.client(), doc, op, { params: { kb_id: [kb], doc_id: [document], ...(file ? { file_id: [file.id] } : {}) } });
103
+ const body = response.bytes ?? Buffer.from(typeof response.data === "string" ? response.data : response.data == null ? "" : JSON.stringify(response.data));
104
+ await handle.writeFile(body);
105
+ bytes = body.length;
106
+ }
107
+ catch (error) {
108
+ await handle.close();
109
+ await fs.unlink(output);
110
+ throw error;
111
+ }
112
+ await handle.close();
113
+ return { data: { document_id: document, file_id: file?.id ?? null, kind: file?.kind ?? null, written: raw, bytes }, text: `Wrote ${bytes} bytes to ${raw}.` };
114
+ },
115
+ };
@@ -12,8 +12,10 @@ import { limitsSet } from "./limits-set.js";
12
12
  import { modelsList, modelsSetLimit } from "./models.js";
13
13
  import { activate, apply, explain, pull, validate } from "./solution.js";
14
14
  import { schema } from "./schema.js";
15
+ import { publication, publish, discardDraft, rollback } from "./publication.js";
15
16
  import { harnessClone, harnessDefault, harnessList, harnessNew, tenantCreate, tenantList } from "./tenants.js";
16
17
  import { kbUpload, testRun, trace } from "./work.js";
18
+ import { kbDocuments, kbFiles, kbDownload } from "./documents.js";
17
19
  import { dbConnections, dbInstance, dbQueries, dbRuns, dbTest, dbTestRun } from "./db.js";
18
20
  import { dbConnectionCa, dbConnectionCreate, dbConnectionDelete, dbConnectionUpdate, dbLoginScript, dbSchema } from "./db-connections.js";
19
21
  import { dbQueryDelete, dbQueryEnable, dbQueryDisable, dbQueryRename } from "./db-query-management.js";
@@ -79,6 +81,10 @@ export const COMMANDS = [
79
81
  tenantList,
80
82
  harnessList,
81
83
  harnessDefault,
84
+ publication,
85
+ publish,
86
+ discardDraft,
87
+ rollback,
82
88
  harnessNew,
83
89
  harnessClone,
84
90
  activate,
@@ -106,6 +112,9 @@ export const COMMANDS = [
106
112
  wait,
107
113
  watch,
108
114
  kbUpload,
115
+ kbDocuments,
116
+ kbFiles,
117
+ kbDownload,
109
118
  testRun,
110
119
  trace,
111
120
  dbInstance,
@@ -0,0 +1,169 @@
1
+ import { accessFor, operationAccess, whoInstead } from "../access.js";
2
+ import { positional, stringOption } from "../command.js";
3
+ import { confirmation, confirmTokenRequired, PERSON_CONFIRMS_HELP } from "../confirm-token.js";
4
+ import { CavelonError, ExitCode, usageError } from "../errors.js";
5
+ import { clip, keyValues, table } from "../format.js";
6
+ import { harnessNotFoundError, lookupHarness } from "../harness-ref.js";
7
+ import { callOperation, workflowOperation } from "../invoke.js";
8
+ import { cavelonCommand } from "../printed.js";
9
+ const BASE = "/api/v1/harnesses/{harness_id}";
10
+ const READ = `${BASE}/publication`;
11
+ const harnessOption = { type: "string", value: "<harness>", description: "Solution name, slug or id; default: selected environment or cavelon.yaml." };
12
+ const envOption = { type: "string", value: "<name>", description: "Use env/<name>.yaml's tenant and solution." };
13
+ const confirmOption = { type: "boolean", mcpToken: true, description: "After review, ask the person to confirm exactly this change." };
14
+ async function target(ctx, input) {
15
+ const session = await ctx.session();
16
+ const ref = stringOption(input, "harness") ?? positional(input, "solution") ?? session.envFile?.harness ?? session.project?.harness;
17
+ if (!ref)
18
+ throw usageError("Which solution?", "Pass --harness <name-or-id>, or select one in cavelon.yaml or the environment.");
19
+ const { harness, candidates } = await lookupHarness(ctx, ref);
20
+ if (!harness)
21
+ throw harnessNotFoundError(ref, candidates);
22
+ return harness;
23
+ }
24
+ async function operation(ctx, route, method = "GET") {
25
+ const result = await workflowOperation(ctx, method, route, "solution publication");
26
+ if (!result.doc)
27
+ throw new CavelonError(ExitCode.failure, { code: "operation_unavailable", message: "This instance does not publish a solution-publication contract." });
28
+ return result;
29
+ }
30
+ async function read(ctx, id, snapshot) {
31
+ const { doc, op } = await operation(ctx, READ);
32
+ const result = await callOperation(ctx, await ctx.client(), doc, op, { params: { harness_id: [id], ...(snapshot ? { snapshot_id: [snapshot] } : {}) } });
33
+ const p = result.data;
34
+ if (!p || !Number.isSafeInteger(p.published_version) || p.published_version < 0 || !Number.isSafeInteger(p.draft_revision) || p.draft_revision < 0 || typeof p.has_draft !== "boolean" || !Array.isArray(p.changes) || !Array.isArray(p.readiness?.blockers) || !Number.isSafeInteger(p.waiting_runs_affected) || p.waiting_runs_affected < 0 || !Array.isArray(p.review_run_ids) || p.review_run_ids.some(id => typeof id !== "string") || !Array.isArray(p.waiting_runs) || !Array.isArray(p.published_snapshots) || typeof p.can_rollback !== "boolean") {
35
+ throw new CavelonError(ExitCode.failure, { code: "publication_state_unknown", message: "The instance did not describe a complete publication state; nothing was changed.", hint: "Read the solution's publication state in the Admin or update the instance." });
36
+ }
37
+ return p;
38
+ }
39
+ function stateText(p) {
40
+ return keyValues([
41
+ ["published", `v${p.published_version}`],
42
+ ["draft", p.has_draft ? `${p.draft_change_count} unpublished changes (revision ${p.draft_revision})` : "none"],
43
+ ["readiness blockers", p.readiness.blockers.length],
44
+ ["waiting runs affected", p.waiting_runs_affected],
45
+ ]) + (p.waiting_runs.length ? `\n\nWaiting runs:\n${table(p.waiting_runs.slice(0, 20), ["id", "node_name"])}` : "") + (p.readiness.blockers.length ? `\n\nBlockers:\n${p.readiness.blockers.slice(0, 20).map(b => clip(JSON.stringify(b), 500)).join("\n")}` : "") + (p.changes.length ? `\n\n${table(p.changes.slice(0, 50), ["entity", "name", "action", "id"])}` : "") + (p.changes.length > 50 ? `\n${p.changes.length - 50} more changes; --json includes all.` : "");
46
+ }
47
+ export const publication = {
48
+ name: "harness publication",
49
+ summary: "Read published version, pending draft, readiness, waiting runs and rollback snapshots.",
50
+ readOnly: true, idempotent: true, mcpTool: "harness_publication", operations: [`GET ${READ}`],
51
+ positionals: [{ name: "solution", description: "Solution name, slug or id; default: environment or cavelon.yaml." }],
52
+ options: { env: envOption },
53
+ async run(ctx, input) {
54
+ const harness = await target(ctx, input);
55
+ const p = await read(ctx, harness.id);
56
+ return { data: { harness, ...p }, text: `${harness.name} (${harness.slug})\n${stateText(p)}` };
57
+ },
58
+ };
59
+ const ACTIONS = {
60
+ publish: { words: ["publish"], tool: "solution_publish", summary: "Review and publish a solution's draft through its readiness gate." },
61
+ "discard-draft": { words: ["harness", "discard-draft"], tool: "harness_discard_draft", summary: "Review and discard a solution's unpublished draft." },
62
+ rollback: { words: ["harness", "rollback"], tool: "harness_rollback", summary: "Review and restore a pinned published version as a new publication." },
63
+ };
64
+ function earlierSnapshot(p, requested, harness) {
65
+ const snapshots = p.published_snapshots.filter(s => typeof s.id === "string" && s.id.length > 0 && Number.isSafeInteger(s.version) && s.version < p.published_version).sort((a, b) => b.version - a.version);
66
+ const snapshot = requested ? snapshots.find(s => s.id === requested) : snapshots[0];
67
+ if (!p.can_rollback || !snapshot)
68
+ throw usageError("No earlier pinned published snapshot matches this rollback.", `Choose a snapshot id from ${cavelonCommand("harness", "publication", harness.slug, "--json")}.`);
69
+ return snapshot;
70
+ }
71
+ function mutationBody(action, p, snapshot) {
72
+ const body = { expected_version: p.published_version, expected_draft_revision: p.draft_revision };
73
+ if (snapshot)
74
+ body.snapshot_id = snapshot.id;
75
+ if (action !== "discard-draft") {
76
+ body.confirm_affected_runs = p.waiting_runs_affected > 0;
77
+ body.expected_waiting_run_ids = [...p.review_run_ids].sort((a, b) => a.localeCompare(b));
78
+ }
79
+ return body;
80
+ }
81
+ function commandWords(action, input, harness, snapshot) {
82
+ const words = [...ACTIONS[action].words, "--harness", harness.slug];
83
+ const env = stringOption(input, "env");
84
+ if (env)
85
+ words.push("--env", env);
86
+ if (snapshot)
87
+ words.push("--snapshot", snapshot.id);
88
+ words.push("--confirm");
89
+ return words;
90
+ }
91
+ function consequenceOf(action, harness, p, snapshot) {
92
+ if (action === "publish")
93
+ return `Publish ${harness.name}'s reviewed draft to live traffic.`;
94
+ if (action === "discard-draft")
95
+ return `Discard ${harness.name}'s unpublished edits; the published graph stays in service.`;
96
+ let message = `Restore published v${snapshot.version} for ${harness.name} as a new live publication.`;
97
+ if (p.has_draft)
98
+ message += " Unpublished edits will be saved in a pinned recovery snapshot and the working draft cleared.";
99
+ return message;
100
+ }
101
+ async function checkMutationAccess(ctx, action) {
102
+ const access = await accessFor(await ctx.client());
103
+ if (action !== "discard-draft" && access?.principal.token?.may_activate === false) {
104
+ throw new CavelonError(ExitCode.unauthorized, { code: "token_activation_refused", message: "This personal access token does not allow activation, publication or rollback.", hint: "A person performs it in the Admin or creates an appropriately scoped token with May activate." });
105
+ }
106
+ const permission = operationAccess(access, `POST ${BASE}/${action}`);
107
+ if (permission.allowed === false)
108
+ throw new CavelonError(ExitCode.unauthorized, { code: "permission_missing", message: "This credential cannot perform the publication change; nothing was changed.", hint: whoInstead(access, permission) });
109
+ }
110
+ function previewResult(harness, p, gate, consequence, words, snapshot) {
111
+ const confirm = gate.confirm(cavelonCommand(...words));
112
+ return {
113
+ data: { changed: false, harness, publication: p, ...(snapshot ? { rollback_snapshot: snapshot } : {}), confirm, ...gate.fields },
114
+ text: [consequence, stateText(p), gate.where, ...(gate.mismatch ? [gate.mismatch] : []), `Show this to a person; with their yes: ${confirm}`].join("\n"),
115
+ ...(gate.exitCode ? { exitCode: gate.exitCode } : {}),
116
+ };
117
+ }
118
+ async function runChange(ctx, input, action) {
119
+ const tool = ACTIONS[action].tool;
120
+ if (ctx.mode === "mcp" && input.options.confirm === true)
121
+ throw confirmTokenRequired(tool);
122
+ const harness = await target(ctx, input);
123
+ let p = await read(ctx, harness.id);
124
+ if (action !== "rollback" && !p.has_draft)
125
+ return { data: { changed: false, harness, publication: p }, text: "No unpublished draft; nothing was changed." };
126
+ if (action === "publish" && p.readiness.blockers.length)
127
+ return { data: { changed: false, harness, publication: p, blockers: p.readiness.blockers }, text: `${stateText(p)}\n\nPublication is blocked. Fix the instance's readiness/Graph Check findings and review again.`, exitCode: ExitCode.validation };
128
+ let snapshot;
129
+ if (action === "rollback") {
130
+ snapshot = earlierSnapshot(p, stringOption(input, "snapshot"), harness);
131
+ p = await read(ctx, harness.id, snapshot.id);
132
+ }
133
+ const { doc, op } = await operation(ctx, `${BASE}/${action}`, "POST");
134
+ await checkMutationAccess(ctx, action);
135
+ const body = mutationBody(action, p, snapshot);
136
+ const words = commandWords(action, input, harness, snapshot);
137
+ const consequence = consequenceOf(action, harness, p, snapshot);
138
+ const changes = [...p.changes].sort((a, b) => (a.entity + ":" + a.id).localeCompare(b.entity + ":" + b.id));
139
+ const waiting = [...p.waiting_runs].sort((a, b) => a.id.localeCompare(b.id));
140
+ const gate = await confirmation(ctx, input, tool, { harness: harness.id, body, changes, waiting_runs: waiting, has_draft: p.has_draft }, { person: { what: `${consequence}\n${stateText(p)}`, words } });
141
+ if (!gate.confirmed)
142
+ return previewResult(harness, p, gate, consequence, words, snapshot);
143
+ const result = await callOperation(ctx, await ctx.client(), doc, op, { params: { harness_id: [harness.id] }, body });
144
+ const data = result.data;
145
+ const warnings = Array.isArray(data.warnings) ? data.warnings.map(w => clip(String(w), 500)) : [];
146
+ return { data: { changed: true, harness, result: data }, text: [`${action} completed for ${harness.name}.`, ...warnings].join("\n") };
147
+ }
148
+ function changeCommand(action) {
149
+ const config = ACTIONS[action];
150
+ return {
151
+ name: config.words.join(" "), summary: config.summary,
152
+ description: "Previews first. Publishing and rollback change live traffic; discarding removes unpublished work. Each needs a person's fresh confirmation, including in YOLO mode. No force option is offered.\n" + PERSON_CONFIRMS_HELP,
153
+ readOnly: false, destructive: action === "discard-draft", mcpTool: config.tool,
154
+ operations: [`GET ${READ}`, `POST ${BASE}/${action}`],
155
+ options: { harness: harnessOption, env: envOption, confirm: confirmOption, ...(action === "rollback" ? { snapshot: { type: "string", value: "<id>", description: "Pinned published snapshot id; default: the previous published version." } } : {}) },
156
+ run: (ctx, input) => runChange(ctx, input, action),
157
+ };
158
+ }
159
+ export const publish = changeCommand("publish");
160
+ export const discardDraft = changeCommand("discard-draft");
161
+ export const rollback = changeCommand("rollback");
162
+ export function publicationNotice(value) {
163
+ const p = value;
164
+ if (p?.target === "draft")
165
+ return `Unpublished draft; live traffic stays on published v${typeof p.published_version === "number" ? p.published_version : "?"}. Review ${cavelonCommand("publish")} before putting these edits live. Tenant-wide resources retain their existing behavior.`;
166
+ if (p?.target === "published")
167
+ return "Editable solution configuration; activation/publication follows the instance's lifecycle.";
168
+ return undefined;
169
+ }
@@ -36,6 +36,7 @@ import { checkedBy, MODEL_UNKNOWN_CODE, missingInventory, REFERENCE_UNKNOWN_CODE
36
36
  import { cavelonCommand, personCommand, printedCommand, spoken } from "../printed.js";
37
37
  import { secretStep, variableSetCommand } from "./values.js";
38
38
  import { maySetSecrets, SECRET_SETTER, SECRET_SETTER_IN_ADMIN, secretsInAdminOnly, VARIABLE_SETTER } from "../secret-access.js";
39
+ import { publicationNotice } from "./publication.js";
39
40
  import { ACTIVATOR, accessFor, accessOf, mayActivate, operationAccess, principalOf } from "../access.js";
40
41
  const HARNESS_OPTION = { type: "string", value: "<harness>", description: "The solution (harness): its name, slug or id; default: env file, then cavelon.yaml." };
41
42
  const ENV_OPTION = { type: "string", value: "<name>", description: "Use env/<name>.yaml: its tenant, solution and runtime bindings." };
@@ -540,6 +541,9 @@ function changesNothing(p) {
540
541
  }
541
542
  export function previewText(p, context = {}) {
542
543
  const lines = [["ready", p.ready ? "yes" : "no"]];
544
+ const publication = publicationNotice(p.publication);
545
+ if (publication)
546
+ lines.push(["publication", publication]);
543
547
  const s = p.summary ?? {};
544
548
  for (const [label, map] of [["creates", s.creates], ["updates", s.updates], ["deletes", s.deletes]]) {
545
549
  const text = counts(map);
@@ -822,6 +826,7 @@ async function confirmPreview(ctx, project, previewId, allowStale, automatic = f
822
826
  const text = keyValues([
823
827
  ["applied", `preview ${stored.preview_id}${stored.harness ? ` to ${stored.harness.slug}` : ""}${stored.env ? ` (env ${stored.env})` : ""}`],
824
828
  ["acted on", targetText(acting)],
829
+ ["publication", publicationNotice(result.publication)],
825
830
  ["tenant-wide", sharedText],
826
831
  ["created", counts(summary?.creates) || undefined],
827
832
  ["updated", counts(summary?.updates) || undefined],
@@ -930,13 +935,20 @@ function packageHarnessName(pkg, slug) {
930
935
  return name ? name.slice(0, 255) : undefined;
931
936
  }
932
937
  const QUERY_IMPORT_REASON = "creates or changes database queries, whose SQL can read or change rows in the tenant's database";
938
+ function graphDraftTarget(preview, harness) {
939
+ const p = preview.publication;
940
+ return Boolean(harness && p?.target === "draft" && p.harness_id === harness.id &&
941
+ Number.isSafeInteger(p.published_version) && p.published_version >= 0 &&
942
+ Number.isSafeInteger(p.draft_revision) && p.draft_revision >= 0 &&
943
+ Array.isArray(preview.impact?.active_harnesses));
944
+ }
933
945
  function personReason(preview, harness, mode, env, shared = [], sharedReaches = []) {
934
946
  if (shared.length) {
935
947
  const reaching = sharedReaches.length ? `, reaching the active solution${sharedReaches.length === 1 ? "" : "s"} ${list(sharedReaches, 5)}` : "";
936
948
  return `changes what the whole tenant shares (${list(shared, 5)})${reaching}`;
937
949
  }
938
950
  const active = (preview.impact?.active_harnesses ?? []).map((h) => h.harness_slug ?? h.name).filter((n) => Boolean(n));
939
- if (harness?.status === "active" && !active.includes(harness.slug))
951
+ if (harness?.status === "active" && !graphDraftTarget(preview, harness) && !active.includes(harness.slug))
940
952
  active.unshift(harness.slug);
941
953
  if (active.length)
942
954
  return `reaches the active solution${active.length === 1 ? "" : "s"} ${list(active, 5)}`;
@@ -954,6 +966,7 @@ export const apply = {
954
966
  name: "apply",
955
967
  summary: "Preview the package files against the instance and print a preview id; --confirm <id> imports exactly that preview.",
956
968
  description: "Without --confirm, shows a preview. With --yolo, an eligible routine draft is previewed and imported in one call.\n" +
969
+ "An active solution qualifies only where the instance explicitly reports an isolated graph draft; publish stays a separate person-reviewed step.\n" +
957
970
  "The preview shows what changes, which active solutions it reaches, what the target\n" +
958
971
  "still needs (secrets and variables with the command that sets each, grants, runtime bindings, trigger identities), loop\n" +
959
972
  "budgets and ignored sections, and is stored in .cavelon/. A preview never creates the solution: one the env file names\n" +
@@ -1184,7 +1197,7 @@ export const apply = {
1184
1197
  }
1185
1198
  const queryEffectsKnown = !queryTools(disk.package).length ||
1186
1199
  Array.isArray(preview.database_queries?.would_write);
1187
- if (preview.preview_id && !reason && !refusal && harness?.status === "draft" &&
1200
+ if (preview.preview_id && !reason && !refusal && (harness?.status === "draft" || graphDraftTarget(preview, harness)) &&
1188
1201
  scope === "agent_graph" && queryEffectsKnown && preview.summary && Array.isArray(preview.impact?.active_harnesses) &&
1189
1202
  await yoloAllows(ctx, harness)) {
1190
1203
  const applied = await confirmPreview(ctx, project, preview.preview_id, false, true);
@@ -231,6 +231,11 @@ export const tenantList = {
231
231
  };
232
232
  },
233
233
  };
234
+ function draftMark(value) {
235
+ if (value === undefined)
236
+ return "?";
237
+ return value ? "yes" : "";
238
+ }
234
239
  export const harnessList = {
235
240
  name: "harness list",
236
241
  summary: "List the tenant's solutions (harnesses), marking the default route.",
@@ -255,11 +260,14 @@ export const harnessList = {
255
260
  slug: h.slug,
256
261
  name: h.name,
257
262
  status: h.status,
263
+ ...(typeof h.published_version === "number" ? { published_version: h.published_version } : {}),
264
+ ...(typeof h.has_draft === "boolean" ? { has_draft: h.has_draft } : {}),
265
+ ...(typeof h.draft_revision === "number" ? { draft_revision: h.draft_revision } : {}),
258
266
  is_default: marksDefault ? h.is_default === true : null,
259
267
  ...(h.readiness ? { ready_to_activate: h.readiness.ready_to_activate ?? null } : {}),
260
268
  })), limit, stringOption(input, "cursor"));
261
- const rows = page.items.map((h) => ({ ...h, default: h.is_default ? "yes" : "" }));
262
- const columns = ["slug", "name", "status", ...(marksDefault ? ["default"] : []), ...(boolOption(input, "readiness") ? ["ready_to_activate"] : []), "id"];
269
+ const rows = page.items.map((h) => ({ ...h, default: h.is_default ? "yes" : "", draft: draftMark(h.has_draft) }));
270
+ const columns = ["slug", "name", "status", ...(marksDefault ? ["default"] : []), ...(harnesses.some(h => typeof h.published_version === "number" || typeof h.has_draft === "boolean") ? ["published_version", "draft"] : []), ...(boolOption(input, "readiness") ? ["ready_to_activate"] : []), "id"];
263
271
  return {
264
272
  data: page,
265
273
  text: (table(rows, columns) || `No solutions yet. Create one: ${cavelonCommand("harness", "new", fill("slug"))}`) + moreHint(page.next_cursor, cavelonCommand("harness", "list")),
@@ -8,7 +8,7 @@ import { CavelonError, ExitCode, usageError } from "../errors.js";
8
8
  import { confirmation } from "../confirm-token.js";
9
9
  import { confinedPath } from "../paths.js";
10
10
  import { clip, keyValues, moreHint, table } from "../format.js";
11
- import { callStable, workflowOperation } from "../invoke.js";
11
+ import { callOperation, callStable, workflowOperation } from "../invoke.js";
12
12
  import { deref } from "../openapi.js";
13
13
  import { bindsNow, changedBy, limitError, limitsOrWarn, readLimits } from "../limits.js";
14
14
  import { getOperation } from "../operations.js";
@@ -180,7 +180,7 @@ async function deactivate(ctx, kbId, matches) {
180
180
  return error;
181
181
  }
182
182
  }
183
- async function resolveKbId(ctx, ref) {
183
+ export async function resolveKbId(ctx, ref) {
184
184
  if (isUuid(ref))
185
185
  return { id: ref };
186
186
  const page = await callStable(ctx, "GET", "/api/v1/knowledge-bases", "knowledge bases", {
@@ -585,6 +585,12 @@ export const kbUpload = {
585
585
  ];
586
586
  };
587
587
  const uploadedText = (where) => created ? `Uploaded ${fileCount(created)}${where}.` : `Nothing new uploaded${where}: the content of ${deduplicated.length === 1 ? "the file is" : "every file is"} already active.`;
588
+ const held = () => documents.filter(d => d.status === "held");
589
+ const privacyReview = () => held().length ? {
590
+ held_documents: held().map(d => d.id),
591
+ needs_person: "A person reviews and releases the held documents in the Admin; tokens cannot release them.",
592
+ } : {};
593
+ const heldLines = () => held().map(d => `${d.filename}: held for privacy review; not indexed or readable. A person reviews it in the Admin. The old documents stay active.`);
588
594
  if (operationIds.length < fresh.length)
589
595
  ctx.warn("The instance returned no operation id for some documents; it may be older than the operations API.");
590
596
  if (failure) {
@@ -604,20 +610,27 @@ export const kbUpload = {
604
610
  }
605
611
  if (boolOption(input, "wait") && ctx.mode === "cli" && operationIds.length) {
606
612
  const waited = await waitAndReport(ctx, operationIds, timeoutMs(ctx, stringOption(input, "timeout")));
607
- const refused = waited.exitCode === ExitCode.ok ? await deactivate(ctx, kb.id, matches) : undefined;
608
- if (waited.exitCode !== ExitCode.ok)
613
+ await refreshStatuses(ctx, kb.id, documents);
614
+ const ready = waited.exitCode === ExitCode.ok && !held().length;
615
+ const refused = ready ? await deactivate(ctx, kb.id, matches) : undefined;
616
+ if (!ready)
609
617
  for (const m of matches)
610
618
  if (m.outcome === undefined)
611
619
  m.outcome = "stays_active";
612
620
  if (refused)
613
621
  ctx.warn(`The old documents stay active: ${refused.message}`);
614
- await refreshStatuses(ctx, kb.id, documents);
615
622
  return {
616
- data: { ...summary(), ...waited.data },
617
- text: [uploadedText(""), ...matchLines(), waited.text].join("\n"),
618
- exitCode: refused && waited.exitCode === ExitCode.ok ? refused.exitCode : waited.exitCode,
623
+ data: { ...summary(), ...waited.data, ...privacyReview() },
624
+ text: [uploadedText(""), ...matchLines(), waited.text, ...heldLines()].join("\n"),
625
+ exitCode: waited.exitCode !== ExitCode.ok ? waited.exitCode : refused?.exitCode ?? (held().length ? ExitCode.needsAction : ExitCode.ok),
619
626
  };
620
627
  }
628
+ if (held().length) {
629
+ for (const m of matches)
630
+ if (m.outcome === undefined)
631
+ m.outcome = "stays_active";
632
+ return { data: { ...summary(), ...privacyReview() }, text: [uploadedText(` to ${kb.name ?? kb.id}`), ...matchLines(), ...heldLines()].join("\n"), exitCode: ExitCode.needsAction };
633
+ }
621
634
  const refused = await deactivate(ctx, kb.id, matches);
622
635
  if (refused)
623
636
  ctx.warn(`The old documents stay active: ${refused.message}`);
@@ -973,11 +986,50 @@ async function testRunView(ctx, id, results, options) {
973
986
  (await capacityFooter(ctx, items.map((r) => r.error))),
974
987
  };
975
988
  }
989
+ const TRACE_EXPORT = "/api/v1/conversations/{conversation_id}/traces/{trace_id}/export";
990
+ async function exportTrace(ctx, conversation, traceId, raw) {
991
+ const output = await confinedPath(ctx, raw, "The trace export", true);
992
+ const { doc, op } = await workflowOperation(ctx, "GET", TRACE_EXPORT, "conversation trace exports");
993
+ if (!doc)
994
+ throw new CavelonError(ExitCode.failure, { code: "operation_unavailable", message: "The instance does not publish an OpenAPI contract for conversation trace exports." });
995
+ let handle;
996
+ try {
997
+ handle = await fs.open(output, "wx", 0o600);
998
+ }
999
+ catch (error) {
1000
+ if (error.code === "EEXIST")
1001
+ throw usageError(`The output file ${raw} already exists.`, "Choose a new output path.");
1002
+ throw error;
1003
+ }
1004
+ let body;
1005
+ let manifest;
1006
+ try {
1007
+ const response = await callOperation(ctx, await ctx.client(), doc, op, { params: { conversation_id: [conversation], trace_id: [traceId] }, preserveBytes: true });
1008
+ const data = response.data;
1009
+ if (!data || typeof data !== "object" || !data.trace || typeof data.trace !== "object" || Array.isArray(data.trace) || !data.manifest || typeof data.manifest !== "object" || Array.isArray(data.manifest) || !response.bytes) {
1010
+ throw new CavelonError(ExitCode.failure, { code: "invalid_trace_export", message: "The instance did not return a JSON trace and manifest; no export was kept." });
1011
+ }
1012
+ body = response.bytes;
1013
+ manifest = data.manifest;
1014
+ await handle.writeFile(body);
1015
+ }
1016
+ catch (error) {
1017
+ await handle.close();
1018
+ await fs.unlink(output);
1019
+ throw error;
1020
+ }
1021
+ await handle.close();
1022
+ return {
1023
+ data: { conversation_id: conversation, trace_id: traceId, written: raw, bytes: body.length, file_sha256: createHash("sha256").update(body).digest("hex"), manifest, signature_verified: false },
1024
+ text: `Wrote ${body.length} original bytes to ${raw}. The instance's manifest is preserved; its signature has not been verified locally.`,
1025
+ };
1026
+ }
976
1027
  export const trace = {
977
1028
  name: "trace",
978
1029
  summary: "Summarise the traces of a run, with a command for each span's detail.",
979
1030
  description: "<run> is a trigger run id, a test run id, a conversation id or an operation id (op_…).\n" +
980
- "Without --trace: one line per trace (or per test result). With --trace: its spans. With --span: one span in full.",
1031
+ "Without --trace: one line per trace (or per test result). With --trace: its spans. With --span: one span in full.\n" +
1032
+ "With --kind conversation --trace <id> --export <file>: save the instance's original JSON export and integrity manifest inside the solution. Needs conversations.view and conversations.export. Signatures remain unverified locally.",
981
1033
  readOnly: true,
982
1034
  idempotent: true,
983
1035
  mcpTool: "trace",
@@ -987,6 +1039,7 @@ export const trace = {
987
1039
  trace: { type: "string", value: "<trace_id>", description: "Show this trace's spans." },
988
1040
  span: { type: "string", value: "<span_id>", description: "Show one span's input, output and error (needs --trace)." },
989
1041
  full: { type: "boolean", description: "Do not shorten span input and output." },
1042
+ export: { type: "string", value: "<file>", description: "Save the original trace export to a new file inside the solution (needs --kind conversation and --trace; excludes --span and --full)." },
990
1043
  limit: LIMIT_OPTION,
991
1044
  cursor: CURSOR_OPTION,
992
1045
  },
@@ -998,6 +1051,14 @@ export const trace = {
998
1051
  throw usageError("--kind must be trigger, test or conversation.");
999
1052
  const limit = intOption(input, "limit", { min: 1, max: 500, fallback: 20 });
1000
1053
  const cursor = stringOption(input, "cursor");
1054
+ const output = stringOption(input, "export");
1055
+ if (output !== undefined) {
1056
+ const traceId = stringOption(input, "trace");
1057
+ if (!output || kind !== "conversation" || !traceId || id.startsWith("op_") || stringOption(input, "span") || boolOption(input, "full") || cursor) {
1058
+ throw usageError("--export needs a conversation id, --kind conversation and --trace <trace_id>; it cannot be combined with --span, --full or --cursor.");
1059
+ }
1060
+ return exportTrace(ctx, id, traceId, output);
1061
+ }
1001
1062
  if (id.startsWith("op_")) {
1002
1063
  const op = await getOperation(await ctx.client(), id);
1003
1064
  const ref = op.result_ref;
package/dist/invoke.js CHANGED
@@ -98,7 +98,8 @@ export async function callOperation(ctx, client, doc, op, args) {
98
98
  const response = await client.fetchRaw(op.method, target, { query, headers: { ...headers, ...confirmed }, json, form, sendTenant: args.sendTenant, signal });
99
99
  const contentType = response.headers.get("content-type") ?? "";
100
100
  const bytes = await bodyBytes(response, client.resolve(target), signal);
101
- const isText = /json|text|xml|yaml|markdown|event-stream/.test(contentType) || bytes.length === 0;
101
+ const mediaType = contentType.split(";", 1)[0].trim().toLowerCase();
102
+ const isText = mediaType.startsWith("text/") || /^application\/(?:[\w.+-]+\+)?(?:json|xml|yaml|x-yaml|markdown|event-stream)$/.test(mediaType) || bytes.length === 0;
102
103
  const text = isText ? new TextDecoder().decode(bytes) : "";
103
104
  let data = text;
104
105
  if (contentType.includes("json") && text) {
@@ -123,7 +124,10 @@ export async function callOperation(ctx, client, doc, op, args) {
123
124
  });
124
125
  throw confirmationRefused(error, Boolean(confirmed) || args.confirmation === false);
125
126
  }
126
- return { status: response.status, contentType, data: isText ? (text ? data : null) : undefined, bytes: isText ? undefined : bytes };
127
+ let responseData;
128
+ if (isText)
129
+ responseData = text ? data : null;
130
+ return { status: response.status, contentType, data: responseData, bytes: !isText || args.preserveBytes ? bytes : undefined };
127
131
  }
128
132
  export async function workflowOperation(ctx, method, pathTemplate, what) {
129
133
  const doc = await openapiOrWarn(ctx);