passcontrol 0.6.0 → 0.6.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.
package/README.md CHANGED
@@ -207,7 +207,7 @@ const pc = new PassControl({ gateway, passportId, passportSecret });
207
207
  const openai = new OpenAI(pc.clientOptions("openai")); // baseURL + auth wired; visas auto-refresh
208
208
  ```
209
209
 
210
- The compiled ESM SDK ships at `passcontrol/sdk` in npm version 0.6.0. Keep the Passport secret
210
+ The compiled ESM SDK ships at `passcontrol/sdk` with the current CLI release. Keep the Passport secret
211
211
  in a trusted agent runtime; never place it in a browser-exposed environment variable. See the
212
212
  [Cloud Passport SDK guide](https://github.com/Vertias3u/PassControl/blob/main/docs/integrations/passport-sdk.md).
213
213
 
@@ -11,6 +11,7 @@ import {
11
11
  CONFIG_FILE,
12
12
  OPENAI_SHAPE_PROVIDERS,
13
13
  PROVIDERS,
14
+ WORKSPACE_IMPORT_MAX_VERSION,
14
15
  assertConfigLoaded,
15
16
  config,
16
17
  configPathLabel,
@@ -25,6 +26,8 @@ import {
25
26
  redact,
26
27
  requireControlApiKey,
27
28
  requireControlGateway,
29
+ operatorEnv,
30
+ probeGatewayOrigin,
28
31
  requirePassportGateway,
29
32
  requirePassport,
30
33
  step,
@@ -46,6 +49,8 @@ import {
46
49
  isIntegration,
47
50
  supportsWrite,
48
51
  } from "../cli/presets.mjs";
52
+ import { importCompletionMessage, noAgentCreateMessage } from "../cli/workspace-import-report.mjs";
53
+ import { checkForUpdate } from "../cli/update-check.mjs";
49
54
  import { startSidecar } from "../cli/sidecar.mjs";
50
55
  import {
51
56
  checkIssuerPublishesKey,
@@ -53,6 +58,7 @@ import {
53
58
  instanceKidFromSeed,
54
59
  } from "../cli/instance-key.mjs";
55
60
  import { FAILURE_REASONS, verifyAgentToken, verifyReceipt } from "../cli/verify.mjs";
61
+ import { compareProtocolSets } from "../cli/protocols.mjs";
56
62
 
57
63
  const b64url = (bytes) =>
58
64
  Buffer.from(bytes).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
@@ -143,9 +149,11 @@ ${heading("Quick start")}
143
149
  ${heading("Operate")}
144
150
  ${cmd} status [--no-network] [--json]
145
151
  show active config and instance state
152
+ ${cmd} version [--json] CLI, gateway and database schema versions
146
153
  ${cmd} doctor [--deep] [--fix] diagnose setup and repair a stopped dashboard
147
154
  ${cmd} call "hi" mint a visa and make a governed model call
148
- ${cmd} sidecar [--port 8788] start the local agent bridge
155
+ ${cmd} sidecar [--port 8788] [--allow-connect host[,host]]
156
+ start the local agent bridge
149
157
 
150
158
  ${heading("Manage")}
151
159
  ${cmd} agent list [--json] list agents
@@ -161,6 +169,9 @@ ${heading("Manage")}
161
169
  ${cmd} logs [--limit 20] [--json]
162
170
  show governed call logs
163
171
  ${cmd} kill on|off toggle the tenant kill switch
172
+ ${cmd} export [--out FILE] save a workspace configuration snapshot
173
+ ${cmd} import <file> [--confirm IMPORT]
174
+ restore agents from a snapshot (never overwrites)
164
175
 
165
176
  ${heading("Integrate")}
166
177
  ${cmd} env [integration] print settings without writing anything
@@ -260,6 +271,10 @@ async function printCockpit({ noNetwork = false, json = false } = {}) {
260
271
  const dashboard = dashboardStatusLabel(gateway, noNetwork);
261
272
  const app = appRootLabel();
262
273
  const configFile = configPathLabel(config.sources);
274
+ // This is deliberately credential-gated. Status remains useful to an agent
275
+ // install with no Control key, but it must never probe a tenant endpoint
276
+ // anonymously or make that normal setup state look like a failure.
277
+ const systemHealth = noNetwork ? { state: "not-checked" } : await fetchSystemHealth();
263
278
 
264
279
  if (json) {
265
280
  console.log(JSON.stringify({
@@ -274,6 +289,7 @@ async function printCockpit({ noNetwork = false, json = false } = {}) {
274
289
  passport_configured: passportConfigured,
275
290
  control_api_key_configured: adminConfigured,
276
291
  },
292
+ system_health: systemHealthForJson(systemHealth),
277
293
  }, null, 2));
278
294
  return;
279
295
  }
@@ -287,6 +303,7 @@ async function printCockpit({ noNetwork = false, json = false } = {}) {
287
303
  console.log(formatLabel("Model", config.model));
288
304
  console.log(formatLabel("Passport", passportConfigured ? redact(config.passportId) : "missing"));
289
305
  console.log(formatLabel("Admin key", adminConfigured ? redact(config.apiKey, 6) : "missing"));
306
+ console.log(formatLabel("System health", systemHealthLabel(systemHealth)));
290
307
  console.log(`${formatLabel("Sidecar", `foreground command (\`${cliCommand("sidecar")}\`)`)}\n`);
291
308
  const next = [];
292
309
  if (config.sources.length === 0) {
@@ -310,6 +327,99 @@ async function printCockpit({ noNetwork = false, json = false } = {}) {
310
327
  }
311
328
  }
312
329
 
330
+ function safeHealthText(value, fallback = "unavailable") {
331
+ if (typeof value !== "string") return fallback;
332
+ // Keep a compromised/misconfigured server from writing terminal control
333
+ // sequences or an unbounded line into an operator's terminal.
334
+ const clean = value.replace(/[\x00-\x1f\x7f]/g, " ").trim().slice(0, 240);
335
+ return clean || fallback;
336
+ }
337
+
338
+ async function fetchSystemHealth() {
339
+ if (!config.apiKey) return { state: "skipped" };
340
+ try {
341
+ const health = await api("GET", "/system");
342
+ if (!health || typeof health !== "object") return { state: "unavailable", reason: "invalid response" };
343
+ return { state: "available", health };
344
+ } catch (error) {
345
+ const message = error instanceof Error ? error.message : "request failed";
346
+ return { state: message.startsWith("403 ") ? "restricted" : "unavailable", reason: message };
347
+ }
348
+ }
349
+
350
+ function healthCompatibility(health) {
351
+ return compareProtocolSets(health && typeof health === "object" ? health.protocols : undefined);
352
+ }
353
+
354
+ function shortBuildCommit(value) {
355
+ return typeof value === "string" && /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i.test(value)
356
+ ? value.slice(0, 12).toLowerCase()
357
+ : "unknown";
358
+ }
359
+
360
+ function systemBuildSummary(health) {
361
+ const build = health?.build && typeof health.build === "object" ? health.build : {};
362
+ const migrations = health?.migrations && typeof health.migrations === "object" ? health.migrations : {};
363
+ return {
364
+ version: safeHealthText(build.version, "unknown"),
365
+ channel: safeHealthText(build.channel, "unknown"),
366
+ commit: shortBuildCommit(build.commit),
367
+ migrationState: safeHealthText(migrations.state, "unknown"),
368
+ migrationHead: safeHealthText(migrations.expected_head, "unknown"),
369
+ appliedMigrationHead: migrations.applied_head == null
370
+ ? "not recorded"
371
+ : safeHealthText(migrations.applied_head, "unknown"),
372
+ };
373
+ }
374
+
375
+ function systemHealthLabel(result) {
376
+ if (result.state === "skipped") return "skipped (operator read key required)";
377
+ if (result.state === "not-checked") return "not checked (--no-network)";
378
+ if (result.state === "restricted") return "restricted (control key cannot read system health)";
379
+ if (result.state !== "available") return `unavailable (${safeHealthText(result.reason)})`;
380
+ const build = systemBuildSummary(result.health);
381
+ const observed = safeHealthText(result.health.generated_at, "unknown");
382
+ return `${safeHealthText(result.health.overall, "reported")} · observed ${observed} · v${build.version} ${build.channel} ${build.commit} · migrations ${build.migrationState} (${build.appliedMigrationHead} → ${build.migrationHead}) · protocols ${healthCompatibility(result.health).state}`;
383
+ }
384
+
385
+ function systemHealthForJson(result) {
386
+ if (result.state !== "available") return { state: result.state };
387
+ return {
388
+ state: "available",
389
+ overall: safeHealthText(result.health.overall, "reported"),
390
+ observed_at: safeHealthText(result.health.generated_at, "unknown"),
391
+ protocol_compatibility: healthCompatibility(result.health).state,
392
+ build: systemBuildSummary(result.health),
393
+ };
394
+ }
395
+
396
+ function printSystemHealthDiagnostic(result) {
397
+ if (result.state === "skipped") {
398
+ step("System health skipped: an operator read key is required.");
399
+ return;
400
+ }
401
+ if (result.state === "restricted") {
402
+ fail("System health diagnostic restricted (403): this key's owner is not an allowlisted MFA-enrolled system operator.");
403
+ return;
404
+ }
405
+ if (result.state !== "available") {
406
+ fail(`System health diagnostic failed: ${safeHealthText(result.reason)}`);
407
+ return;
408
+ }
409
+ const compatibility = healthCompatibility(result.health);
410
+ const build = systemBuildSummary(result.health);
411
+ const observed = safeHealthText(result.health.generated_at, "unknown");
412
+ ok(`System health ${safeHealthText(result.health.overall, "reported")} · observed ${observed} · v${build.version} ${build.channel} ${build.commit} · migrations ${build.migrationState} (${build.appliedMigrationHead} → ${build.migrationHead}) · protocol compatibility ${compatibility.state}`);
413
+ for (const check of Array.isArray(result.health.checks) ? result.health.checks : []) {
414
+ if (!check || typeof check !== "object") continue;
415
+ const label = safeHealthText(check.label, "System check");
416
+ const state = safeHealthText(check.state, "unknown");
417
+ const summary = safeHealthText(check.summary, "No summary provided.");
418
+ console.log(` ${label}: ${state} — ${summary}`);
419
+ if (typeof check.action === "string" && check.action.trim()) step(`Remediation: ${safeHealthText(check.action)}`);
420
+ }
421
+ }
422
+
313
423
  function appConfigDir(env = process.env) {
314
424
  const base = env.XDG_CONFIG_HOME || path.join(os.homedir(), ".config");
315
425
  return path.join(base, "passcontrol");
@@ -430,13 +540,26 @@ function checkDockerDaemon() {
430
540
  try {
431
541
  // Docker Desktop can leave its CLI socket present while the engine is
432
542
  // wedged. A diagnostic command must report that state, not hang every
433
- // onboarding/release check indefinitely.
434
- execFileSync("docker", ["info"], { stdio: "ignore", timeout: 2_000 });
543
+ // onboarding/release check indefinitely — hence a bound.
544
+ //
545
+ // The bound is generous because the failure it must not cause is worse than
546
+ // the one it prevents. At 2s this reported "not running" about a daemon that
547
+ // was merely COLD: it failed the public repo's local-smoke CI job on a runner
548
+ // where Docker was available throughout, and it would tell a first-time user
549
+ // on a slow laptop to go start something already running. A wedged engine
550
+ // still gets caught; it just takes fifteen seconds to say so.
551
+ execFileSync("docker", ["info"], { stdio: "ignore", timeout: 15_000 });
435
552
  return { ok: true, message: "Docker daemon: running." };
436
- } catch {
553
+ } catch (error) {
554
+ // A timeout and a stopped daemon need different things from the reader, so
555
+ // they must not share a sentence. `execFileSync` surfaces the timeout kill as
556
+ // ETIMEDOUT, or as the signal it used when the platform reports no code.
557
+ const timedOut = error?.code === "ETIMEDOUT" || error?.signal === "SIGTERM";
437
558
  return {
438
559
  ok: false,
439
- message: "Docker daemon: not running. Fix: start Docker Desktop and wait for the engine to become ready.",
560
+ message: timedOut
561
+ ? "Docker daemon: did not respond within 15s. The engine may still be starting — wait and re-run. If it persists, Docker is wedged: restart Docker Desktop."
562
+ : "Docker daemon: not running. Fix: start Docker Desktop and wait for the engine to become ready.",
440
563
  };
441
564
  }
442
565
  }
@@ -1312,22 +1435,34 @@ async function tryCommand() {
1312
1435
  step("Next: add a real provider key in the Control Tower and re-point your agent at the gateway (see the README).");
1313
1436
  }
1314
1437
 
1315
- async function api(method, pathPart, body) {
1438
+ async function api(method, pathPart, body, { timeoutMs } = {}) {
1316
1439
  // Destination first, key second — same order and same reason as the SDK's
1317
1440
  // ControlClient. `config.gateway` is whatever PASSCONTROL_GATEWAY said, and
1318
1441
  // this is the one place a long-lived fleet-wide `pc_` key goes on the wire, so
1319
1442
  // the URL is built from the validated origin rather than from that string.
1320
1443
  const origin = requireControlGateway(config);
1321
1444
  const apiKey = requireControlApiKey(config);
1322
- const res = await fetch(`${origin}/api/control/v1${pathPart}`, {
1323
- method,
1324
- headers: {
1325
- authorization: `Bearer ${apiKey}`,
1326
- ...(body ? { "content-type": "application/json" } : {}),
1327
- ...(method !== "GET" ? { "idempotency-key": crypto.randomUUID() } : {}),
1328
- },
1329
- body: body ? JSON.stringify(body) : undefined,
1330
- });
1445
+ // Unbounded by default, deliberately: a fleet mutation must not be abandoned
1446
+ // halfway because a caller guessed a duration. `timeoutMs` is opt-in, for the
1447
+ // one kind of caller that is a REPORT — where a gateway that never answers is
1448
+ // itself the finding, and hanging turns a diagnostic into a hang.
1449
+ const controller = timeoutMs ? new AbortController() : null;
1450
+ const timer = controller ? setTimeout(() => controller.abort(), timeoutMs) : null;
1451
+ let res;
1452
+ try {
1453
+ res = await fetch(`${origin}/api/control/v1${pathPart}`, {
1454
+ method,
1455
+ headers: {
1456
+ authorization: `Bearer ${apiKey}`,
1457
+ ...(body ? { "content-type": "application/json" } : {}),
1458
+ ...(method !== "GET" ? { "idempotency-key": crypto.randomUUID() } : {}),
1459
+ },
1460
+ body: body ? JSON.stringify(body) : undefined,
1461
+ ...(controller ? { signal: controller.signal } : {}),
1462
+ });
1463
+ } finally {
1464
+ if (timer) clearTimeout(timer);
1465
+ }
1331
1466
  const text = await res.text();
1332
1467
  let json = {};
1333
1468
  try {
@@ -1339,7 +1474,7 @@ async function api(method, pathPart, body) {
1339
1474
  const e = json.error ?? {};
1340
1475
  throw new Error(`${res.status} ${e.code ?? ""} ${e.message ?? ""} (req ${e.request_id ?? "?"})`);
1341
1476
  }
1342
- return json.data;
1477
+ return Object.prototype.hasOwnProperty.call(json, "data") ? json.data : json;
1343
1478
  }
1344
1479
 
1345
1480
  function controlPath(pathPart, params = {}) {
@@ -1549,6 +1684,21 @@ async function sidecarCommand(rest, opts) {
1549
1684
  passportSecret,
1550
1685
  port: sidecarPort(opts),
1551
1686
  host: String(opts.host ?? process.env.SIDECAR_HOST ?? "127.0.0.1"),
1687
+ // Named on the command line, never inferred. A sidecar reachable off-host
1688
+ // mints visas for whoever connects, so widening the bind is a decision the
1689
+ // operator states rather than one a config value makes quietly.
1690
+ allowNonLoopback: Boolean(opts.allowNonLoopback),
1691
+ // Hosts the agent may CONNECT-tunnel to, beyond the gateway itself. Provider
1692
+ // hosts are never eligible — see cli/proxy-policy.mjs.
1693
+ //
1694
+ // `operatorEnv`, not `process.env`, for the same reason `allowNonLoopback`
1695
+ // above takes no environment fallback at all: this is an egress control. A
1696
+ // `.passcontrol` that travels with a cloned repository was able to add tunnel
1697
+ // destinations to a sidecar started with no flags, and say nothing about it.
1698
+ allowConnectHosts: String(opts.allowConnect ?? operatorEnv("SIDECAR_ALLOW_CONNECT") ?? "")
1699
+ .split(",")
1700
+ .map((entry) => entry.trim())
1701
+ .filter(Boolean),
1552
1702
  refreshSkewSeconds: Number(opts.refreshSkewSeconds ?? process.env.REFRESH_SKEW_SECONDS ?? 30),
1553
1703
  });
1554
1704
 
@@ -1781,6 +1931,133 @@ async function configureCommand(rest, opts = {}) {
1781
1931
  ok(`wrote ${target}`);
1782
1932
  }
1783
1933
 
1934
+ // ── Which build is which ─────────────────────────────────────────────────────
1935
+ //
1936
+ // Version drift between the CLI, the gateway and the database is the support
1937
+ // question that hides behind every other support question, and until now the
1938
+ // CLI could only answer a third of it. `passcontrol version` printed its own
1939
+ // number and stopped.
1940
+ //
1941
+ // The three rows come from three different places on purpose, and each degrades
1942
+ // on its own:
1943
+ //
1944
+ // CLI — the installed package. Always available.
1945
+ // Server — GET /api/version on the configured gateway. Unauthenticated,
1946
+ // because the release version is already on the site footer.
1947
+ // Schema — the migration block of /api/control/v1/system, which is behind
1948
+ // the operator gate. How far behind a database is doubles as a
1949
+ // list of the fixes it does not have, so it stays authenticated;
1950
+ // on a self-host the operator is the person running this, and on
1951
+ // Cloud a tenant correctly cannot read the instance's lag.
1952
+
1953
+ /** The gateway's own build, or null. Never throws: this is a report, not a gate. */
1954
+ async function serverVersion() {
1955
+ // Same origin rule as every other outbound path in this file, even though no
1956
+ // credential travels here — see probeGatewayOrigin.
1957
+ const origin = probeGatewayOrigin();
1958
+ if (!origin) return { version: null, detail: "the configured gateway is not a bare origin" };
1959
+ try {
1960
+ const res = await fetchWithTimeout(`${origin}/api/version`);
1961
+ // A gateway that predates this endpoint is a real PassControl gateway, and
1962
+ // saying "unreachable" about one that answered would send an operator to
1963
+ // debug their network instead of deploying.
1964
+ if (res.status === 404) return { version: null, detail: "running a build older than /api/version" };
1965
+ if (!res.ok) return { version: null, detail: `the gateway answered ${res.status}` };
1966
+ const body = await res.json();
1967
+ const version = typeof body?.version === "string" ? body.version : null;
1968
+ return { version, detail: version ? null : "the gateway did not report a version" };
1969
+ } catch {
1970
+ return { version: null, detail: "unreachable" };
1971
+ }
1972
+ }
1973
+
1974
+ /**
1975
+ * The migration block, or why it could not be read.
1976
+ *
1977
+ * Every branch is a distinct, actionable answer. "not checked" is not the same
1978
+ * as "forbidden", and neither is the same as a gateway that is simply down —
1979
+ * collapsing them is how an operator ends up debugging the wrong thing.
1980
+ */
1981
+ async function schemaState() {
1982
+ if (!config.apiKey) return { state: "unchecked", detail: "no control API key configured" };
1983
+ try {
1984
+ // Bounded: `doctor` exists to explain an unavailable gateway, so this line
1985
+ // must never be the reason the report does not print.
1986
+ const snapshot = await api("GET", "/system", undefined, { timeoutMs: 2500 });
1987
+ const migrations = snapshot?.data?.migrations ?? snapshot?.migrations ?? null;
1988
+ if (!migrations) return { state: "unchecked", detail: "the gateway returned no migration block" };
1989
+ return { state: migrations.state ?? "unknown", migrations };
1990
+ } catch (error) {
1991
+ const message = String(error?.message ?? error);
1992
+ if (/system_forbidden|system_not_configured|system_totp_required|system_allowlist_invalid/.test(message)) {
1993
+ return { state: "unchecked", detail: "this control key is not an operator of that instance" };
1994
+ }
1995
+ // A bare "fetch failed" reads as a bug in the CLI rather than as a gateway
1996
+ // that is not running, which is what it almost always means.
1997
+ if (/fetch failed|ECONNREFUSED|ENOTFOUND|aborted/i.test(message)) {
1998
+ return { state: "unchecked", detail: "the gateway is unreachable" };
1999
+ }
2000
+ // Never echo the upstream error body into this report: it is remote text,
2001
+ // and "401 invalid_api_key no (req ?)" tells an operator less than the
2002
+ // sentence it is standing in for.
2003
+ if (/invalid_api_key|\b401\b/.test(message)) {
2004
+ return { state: "unchecked", detail: "the control API key was rejected" };
2005
+ }
2006
+ if (/\b404\b/.test(message)) {
2007
+ return { state: "unchecked", detail: "this gateway is too old to report its schema" };
2008
+ }
2009
+ return { state: "unchecked", detail: "the gateway did not answer the system check" };
2010
+ }
2011
+ }
2012
+
2013
+ const SCHEMA_WORD = {
2014
+ current: "compatible",
2015
+ behind: "the database is missing migrations this build expects",
2016
+ ahead: "the database is newer than this build — was the app rolled back?",
2017
+ incompatible: "the applied migrations do not match this build",
2018
+ unknown: "could not be determined",
2019
+ };
2020
+
2021
+ async function versionCommand({ json = false } = {}) {
2022
+ const [server, schema] = await Promise.all([serverVersion(), schemaState()]);
2023
+ const migrations = schema.migrations ?? null;
2024
+ const serverLabel =
2025
+ server.version === null
2026
+ ? `not reported (${server.detail})`
2027
+ : `${server.version}${server.version === CLI_VERSION ? " ✓" : " ✗ different build from this CLI"}`;
2028
+
2029
+ if (json) {
2030
+ console.log(JSON.stringify({
2031
+ cli: CLI_VERSION,
2032
+ server: server.version,
2033
+ server_detail: server.detail,
2034
+ server_matches_cli: server.version === null ? null : server.version === CLI_VERSION,
2035
+ schema: migrations
2036
+ ? {
2037
+ state: schema.state,
2038
+ applied_head: migrations.applied_head ?? null,
2039
+ expected_head: migrations.expected_head ?? null,
2040
+ missing_count: migrations.missing_count ?? 0,
2041
+ extra_count: migrations.extra_count ?? 0,
2042
+ }
2043
+ : { state: schema.state, detail: schema.detail ?? null },
2044
+ }, null, 2));
2045
+ return;
2046
+ }
2047
+
2048
+ console.log(`${heading("PassControl")}\n`);
2049
+ console.log(formatLabel("CLI", CLI_VERSION, 18));
2050
+ console.log(formatLabel("Server", serverLabel, 18));
2051
+ if (migrations) {
2052
+ console.log(formatLabel("Database schema", migrations.applied_head ?? "none recorded", 18));
2053
+ console.log(formatLabel("Expected schema", migrations.expected_head ?? "unknown", 18));
2054
+ console.log(formatLabel("Status", `${schema.state} — ${SCHEMA_WORD[schema.state] ?? "see the dashboard"}`, 18));
2055
+ if (migrations.action) step(migrations.action);
2056
+ } else {
2057
+ console.log(formatLabel("Database schema", `not checked (${schema.detail})`, 18));
2058
+ }
2059
+ }
2060
+
1784
2061
  async function doctorCommand(opts = {}) {
1785
2062
  const gateway = await gatewayStatus(false);
1786
2063
  console.log(`${heading("PassControl doctor")}\n`);
@@ -1790,6 +2067,16 @@ async function doctorCommand(opts = {}) {
1790
2067
  );
1791
2068
  (config.apiKey ? ok : step)(`Control API key ${config.apiKey ? "configured" : "missing (needed only for agent/kill commands)"}`);
1792
2069
  step(`Config source: ${configPathLabel(config.sources)}`);
2070
+ // The check that answers "why did this work yesterday". A database behind the
2071
+ // build it serves is not visible from any other line in this report.
2072
+ const schema = await schemaState();
2073
+ if (schema.migrations) {
2074
+ (schema.state === "current" ? ok : fail)(
2075
+ `Database migrations ${schema.state} — ${SCHEMA_WORD[schema.state] ?? "see the dashboard"}`
2076
+ );
2077
+ } else {
2078
+ step(`Database migrations not checked (${schema.detail})`);
2079
+ }
1793
2080
 
1794
2081
  if (opts.fix) {
1795
2082
  console.log("");
@@ -1818,6 +2105,9 @@ async function doctorCommand(opts = {}) {
1818
2105
 
1819
2106
  console.log("");
1820
2107
  step("Deep checks");
2108
+ // One authenticated request for this command. Its failure is a failed
2109
+ // diagnostic, not a CLI crash: remaining local checks are still useful.
2110
+ printSystemHealthDiagnostic(await fetchSystemHealth());
1821
2111
  await runLocalPrerequisiteChecks({ report: true });
1822
2112
  if (config.passportId && config.passportSecret) {
1823
2113
  try {
@@ -1970,17 +2260,154 @@ async function openDashboard(opts = {}) {
1970
2260
  ok(`opening ${url}`);
1971
2261
  }
1972
2262
 
2263
+ // ── Workspace snapshots ─────────────────────────────────────────────────────
2264
+ // A recovery snapshot is CONFIGURATION, not a backup: it carries agents, their
2265
+ // scopes, budgets, policies and failover order, and deliberately carries no
2266
+ // secret value at all. What it cannot restore is stated in the file itself,
2267
+ // under `exclusions`, because this is the artifact someone opens at the worst
2268
+ // possible moment.
2269
+
2270
+ // lib/control/body.ts caps every control-plane request at 64 KiB, and it is not
2271
+ // raised for one route. Checking here means a large fleet is told what to do
2272
+ // instead of being handed a bare 413 by the server.
2273
+ const IMPORT_BODY_LIMIT = 64 * 1024;
2274
+
2275
+ // Wide enough for "Skipped (already exist)", the longest label below. formatLabel
2276
+ // pads to the width and does not truncate, so a short width silently glues the
2277
+ // value onto the colon.
2278
+ const REPORT_LABEL_WIDTH = 26;
2279
+
2280
+ // A passport public key is unique across the whole instance, not per workspace,
2281
+ // because the gateway identifies an agent BY that key. So importing a file into
2282
+ // a second workspace on the SAME instance refuses every agent still held by the
2283
+ // first — which is correct, and is not what a restore looks like. A restore
2284
+ // goes into a fresh instance, where the passports are free.
2285
+ const IMPORT_REASONS = {
2286
+ passport_registered_elsewhere:
2287
+ "its passport is already registered on this instance. Nothing was created for it. " +
2288
+ "Passports are unique per instance, so this file restores into a FRESH deployment, " +
2289
+ "not alongside the workspace it came from.",
2290
+ policy_malformed: "its policy could not be parsed, and creating it without one would leave it unrestricted.",
2291
+ policy_shadow_malformed: "its shadow policy could not be parsed.",
2292
+ unknown_status: "it records a status this version does not recognise.",
2293
+ };
2294
+
2295
+ async function exportCommand(opts = {}) {
2296
+ const snapshot = await api("GET", "/workspace/export");
2297
+ const body = JSON.stringify(snapshot, null, 2);
2298
+ const target = typeof opts.out === "string" ? opts.out : null;
2299
+ if (!target) {
2300
+ console.log(body);
2301
+ return;
2302
+ }
2303
+ fs.writeFileSync(target, `${body}\n`, { mode: 0o600 });
2304
+ ok(`Wrote ${snapshot.workspace.agents.length} agents to ${target}`);
2305
+ console.log(`\n${heading("Not in this file")}`);
2306
+ for (const line of snapshot.exclusions) console.log(` • ${line}`);
2307
+ }
2308
+
2309
+ async function importCommand(rest = [], opts = {}) {
2310
+ const file = rest[0];
2311
+ if (!file) throw new Error(`Usage: ${cliPrefix()} import <file> [--confirm IMPORT]`);
2312
+
2313
+ let snapshot;
2314
+ try {
2315
+ snapshot = JSON.parse(fs.readFileSync(file, "utf8"));
2316
+ } catch (error) {
2317
+ throw new Error(`Could not read ${file} as JSON: ${error.message}`);
2318
+ }
2319
+ if (snapshot?.format !== "passcontrol-export") {
2320
+ throw new Error(`${file} is not a PassControl workspace export.`);
2321
+ }
2322
+ // A file from a LATER schema may describe fields this CLI would silently drop.
2323
+ // Refusing is the honest move: a partial restore that reports success is the
2324
+ // failure this whole feature exists to prevent.
2325
+ if (Number(snapshot.version) > WORKSPACE_IMPORT_MAX_VERSION) {
2326
+ throw new Error(
2327
+ `${file} uses export format v${snapshot.version}; this CLI understands up to ` +
2328
+ `v${WORKSPACE_IMPORT_MAX_VERSION}. Upgrade PassControl and try again.`
2329
+ );
2330
+ }
2331
+
2332
+ // Only what the import writes goes on the wire. Provider mappings, break-glass
2333
+ // grants, the exclusions prose and the display settings stay on disk — they
2334
+ // are not importable, so sending them would spend the size budget on bytes the
2335
+ // server ignores.
2336
+ const agents = snapshot.workspace?.agents ?? [];
2337
+ const payload = { agents, ownership: snapshot.workspace?.ownership ?? null };
2338
+ const size = Buffer.byteLength(JSON.stringify(payload));
2339
+ if (size > IMPORT_BODY_LIMIT) {
2340
+ throw new Error(
2341
+ `This snapshot holds ${agents.length} agents (${Math.ceil(size / 1024)} KiB) and the import ` +
2342
+ `API accepts ${IMPORT_BODY_LIMIT / 1024} KiB per request. Split the "agents" array across ` +
2343
+ `several files and import them one at a time — importing is additive, so the parts combine.`
2344
+ );
2345
+ }
2346
+
2347
+ const preview = await api("POST", "/workspace/import?dry_run=true", payload);
2348
+ printImportReport(preview, { preview: true });
2349
+
2350
+ if (preview.agents.create === 0) {
2351
+ ok(noAgentCreateMessage(preview.agents));
2352
+ return;
2353
+ }
2354
+ if (opts.confirm !== "IMPORT") {
2355
+ console.log(
2356
+ `\nNothing has been written. Re-run with \`--confirm IMPORT\` to create the ` +
2357
+ `${preview.agents.create} agent(s) above.`
2358
+ );
2359
+ return;
2360
+ }
2361
+
2362
+ const result = await api("POST", "/workspace/import", payload);
2363
+ printImportReport(result, { preview: false });
2364
+ ok(importCompletionMessage(result));
2365
+ }
2366
+
2367
+ function printImportReport(report, { preview }) {
2368
+ console.log(`\n${heading(preview ? "Dry run — nothing written yet" : "Imported")}`);
2369
+ const created = preview ? report.agents.create : report.agents.created.length;
2370
+ console.log(formatLabel(preview ? "Will create" : "Created", String(created), REPORT_LABEL_WIDTH));
2371
+ if (report.agents.skipped.length > 0) {
2372
+ console.log(formatLabel("Skipped (already exist)", report.agents.skipped.join(", "), REPORT_LABEL_WIDTH));
2373
+ }
2374
+ for (const entry of report.agents.rejected) {
2375
+ console.log(formatLabel("Refused", `${entry.name} — ${IMPORT_REASONS[entry.reason] ?? entry.reason}`, REPORT_LABEL_WIDTH));
2376
+ }
2377
+ console.log(formatLabel("Ownership", report.ownership, REPORT_LABEL_WIDTH));
2378
+ console.log(`\n${heading("Not restored")}`);
2379
+ for (const line of report.not_restored) console.log(` • ${line}`);
2380
+ // Said once, plainly: an existing agent is never touched, so a re-run is safe.
2381
+ console.log(`\nAn agent already in the workspace is left exactly as it is — import never overwrites.`);
2382
+ }
2383
+
1973
2384
  async function main() {
1974
2385
  const { opts, rest } = parseArgv(process.argv.slice(2));
1975
2386
  const [command, ...commandRest] = rest;
1976
2387
 
2388
+ // Started here and awaited at the very end, so the registry lookup overlaps
2389
+ // the command instead of being tacked onto the exit. On anything that touches
2390
+ // the network — which is most of this CLI — it costs nothing measurable, and
2391
+ // it can never turn a registry outage into a slow `passcontrol call`.
2392
+ // .catch() rather than try/catch: an unhandled rejection from a background
2393
+ // nicety must not take down a command that already did its job.
2394
+ const updateNotice = checkForUpdate({
2395
+ current: CLI_VERSION,
2396
+ json: Boolean(opts.json),
2397
+ }).catch(() => null);
2398
+ const announceUpdate = async () => {
2399
+ const notice = await updateNotice;
2400
+ if (notice) console.log(`\n${notice}`);
2401
+ };
2402
+
1977
2403
  if (opts.help || command === "help") {
1978
2404
  const target = command === "help" ? commandRest[0] : command;
1979
2405
  console.log(target === "agent" || target === "fleet" ? agentUsage() : usage());
1980
2406
  return;
1981
2407
  }
1982
2408
  if (opts.version || command === "version") {
1983
- console.log(`passcontrol ${CLI_VERSION}`);
2409
+ await versionCommand({ json: Boolean(opts.json) });
2410
+ await announceUpdate();
1984
2411
  return;
1985
2412
  }
1986
2413
 
@@ -2050,6 +2477,12 @@ async function main() {
2050
2477
  case "kill":
2051
2478
  await killCommand(commandRest);
2052
2479
  break;
2480
+ case "export":
2481
+ await exportCommand(opts);
2482
+ break;
2483
+ case "import":
2484
+ await importCommand(commandRest, opts);
2485
+ break;
2053
2486
  case "open":
2054
2487
  await openDashboard(opts);
2055
2488
  break;
@@ -2062,6 +2495,8 @@ async function main() {
2062
2495
  default:
2063
2496
  throw new Error(`Unknown command "${command}". Run \`passcontrol help\`.`);
2064
2497
  }
2498
+ // Only on success. A notice printed under a failure buries the error.
2499
+ await announceUpdate();
2065
2500
  }
2066
2501
 
2067
2502
  main().catch((error) => {