@indigoai-us/hq-cli 5.345.215 → 5.345.217

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. package/CHANGELOG.md +141 -0
  2. package/README.md +45 -0
  3. package/assets/scaffold/core/scripts/lib/epochrealtime.sh +30 -0
  4. package/assets/scaffold/core/scripts/lib/work-mesh-enqueue.sh +12 -5
  5. package/dist/command-catalog.generated.d.ts +59 -4
  6. package/dist/command-catalog.generated.js +74 -4
  7. package/dist/command-help.js +3 -1
  8. package/dist/command-registration-plan.d.ts +6 -0
  9. package/dist/command-registration-plan.js +1 -0
  10. package/dist/commands/auth.d.ts +1 -1
  11. package/dist/commands/auth.js +11 -52
  12. package/dist/commands/bot.js +11 -4
  13. package/dist/commands/cloud-demote.d.ts +19 -4
  14. package/dist/commands/cloud-demote.js +85 -12
  15. package/dist/commands/cloud-provision.d.ts +5 -1
  16. package/dist/commands/cloud-provision.js +6 -2
  17. package/dist/commands/cloud.d.ts +36 -0
  18. package/dist/commands/cloud.js +109 -26
  19. package/dist/commands/core.js +1 -0
  20. package/dist/commands/daemon.js +4 -1
  21. package/dist/commands/dm.js +7 -0
  22. package/dist/commands/doctor-usage.d.ts +8 -0
  23. package/dist/commands/doctor-usage.js +20 -0
  24. package/dist/commands/doctor.js +7 -1
  25. package/dist/commands/env.d.ts +18 -0
  26. package/dist/commands/env.js +82 -0
  27. package/dist/commands/install-global.js +2 -2
  28. package/dist/commands/lanes.js +100 -24
  29. package/dist/commands/logout.d.ts +7 -0
  30. package/dist/commands/logout.js +41 -34
  31. package/dist/commands/sources.d.ts +8 -2
  32. package/dist/commands/sources.js +65 -9
  33. package/dist/commands/whoami.js +26 -1
  34. package/dist/data/command-states.json +15 -0
  35. package/dist/index.js +52 -4
  36. package/dist/lazy-commands.js +2 -1
  37. package/dist/lib/anywhere-person-setting.d.ts +2 -0
  38. package/dist/lib/anywhere-person-setting.js +6 -3
  39. package/dist/lib/billing/usage-card.d.ts +25 -4
  40. package/dist/lib/billing/usage-card.js +76 -9
  41. package/dist/lib/billing/usage-cost.d.ts +3 -3
  42. package/dist/lib/billing/usage-cost.js +35 -13
  43. package/dist/lib/billing/usage-only.js +4 -2
  44. package/dist/lib/billing/usage-rate-card.d.ts +2 -2
  45. package/dist/lib/billing/usage-rate-card.js +3 -0
  46. package/dist/lib/bot/fleet-cron.js +93 -6
  47. package/dist/lib/bot/inflight.d.ts +9 -0
  48. package/dist/lib/bot/inflight.js +10 -0
  49. package/dist/lib/bot/jobs/hot-signal-sync.js +12 -1
  50. package/dist/lib/bot/runtime/grok-acp.d.ts +1 -0
  51. package/dist/lib/bot/runtime/grok-acp.js +26 -11
  52. package/dist/lib/bot/runtime/grok.js +1 -1
  53. package/dist/lib/daemon/flag-monitor.d.ts +8 -0
  54. package/dist/lib/daemon/flag-monitor.js +17 -6
  55. package/dist/lib/daemon/flag.d.ts +65 -1
  56. package/dist/lib/daemon/flag.js +190 -40
  57. package/dist/lib/daemon/ops/policy.js +62 -5
  58. package/dist/lib/daemon/paths.d.ts +72 -2
  59. package/dist/lib/daemon/paths.js +154 -3
  60. package/dist/lib/daemon/run.js +25 -20
  61. package/dist/lib/daemon/selfcheck.d.ts +22 -0
  62. package/dist/lib/daemon/selfcheck.js +40 -1
  63. package/dist/lib/daemon/server.d.ts +3 -1
  64. package/dist/lib/daemon/server.js +7 -22
  65. package/dist/lib/daemon/state-file-switch.d.ts +57 -0
  66. package/dist/lib/daemon/state-file-switch.js +88 -0
  67. package/dist/lib/daemon/state-file.d.ts +198 -0
  68. package/dist/lib/daemon/state-file.js +419 -0
  69. package/dist/lib/daemon/timed-flag-monitors.d.ts +47 -0
  70. package/dist/lib/daemon/timed-flag-monitors.js +75 -0
  71. package/dist/lib/doctor/checks/host-core.d.ts +50 -0
  72. package/dist/lib/doctor/checks/host-core.js +269 -0
  73. package/dist/lib/doctor/checks/replay-recorder.d.ts +39 -0
  74. package/dist/lib/doctor/checks/replay-recorder.js +261 -0
  75. package/dist/lib/doctor/registry.js +4 -0
  76. package/dist/lib/environment/profile.d.ts +239 -0
  77. package/dist/lib/environment/profile.js +251 -0
  78. package/dist/lib/hook-engine/reconcile.js +39 -13
  79. package/dist/lib/hook-engine/registration.d.ts +9 -0
  80. package/dist/lib/hook-engine/registration.js +19 -0
  81. package/dist/lib/hot-channels/adapters/slack.d.ts +21 -5
  82. package/dist/lib/hot-channels/adapters/slack.js +64 -21
  83. package/dist/lib/hot-channels/alert.d.ts +2 -0
  84. package/dist/lib/hot-channels/alert.js +8 -1
  85. package/dist/lib/hot-channels/contract.d.ts +12 -0
  86. package/dist/lib/hot-channels/contract.js +7 -0
  87. package/dist/lib/hot-channels/loop.js +1 -0
  88. package/dist/lib/hot-channels/run.d.ts +6 -0
  89. package/dist/lib/hot-channels/run.js +4 -0
  90. package/dist/lib/hot-channels/signals-pass.d.ts +64 -1
  91. package/dist/lib/hot-channels/signals-pass.js +21 -49
  92. package/dist/lib/install/claude-targets.d.ts +12 -1
  93. package/dist/lib/install/claude-targets.js +57 -5
  94. package/dist/lib/install/codex-targets.d.ts +2 -2
  95. package/dist/lib/install/codex-targets.js +36 -6
  96. package/dist/lib/install/hook-target.d.ts +3 -0
  97. package/dist/lib/install/hook-target.js +11 -0
  98. package/dist/lib/lanes/canonical-host.d.ts +35 -0
  99. package/dist/lib/lanes/canonical-host.js +65 -0
  100. package/dist/lib/lanes/host-capacity.d.ts +30 -0
  101. package/dist/lib/lanes/host-capacity.js +29 -3
  102. package/dist/lib/mesh/live/daemon/run.d.ts +2 -0
  103. package/dist/lib/mesh/live/daemon/run.js +5 -2
  104. package/dist/lib/mesh/live/flush.d.ts +5 -1
  105. package/dist/lib/mesh/live/flush.js +12 -6
  106. package/dist/lib/mesh/live/reporting-privacy.d.ts +32 -0
  107. package/dist/lib/mesh/live/reporting-privacy.js +56 -1
  108. package/dist/lib/mesh/live/spool.d.ts +7 -0
  109. package/dist/lib/mesh/live/spool.js +25 -0
  110. package/dist/lib/person-setting-cache.d.ts +38 -0
  111. package/dist/lib/person-setting-cache.js +98 -0
  112. package/dist/lib/safe-store.d.ts +245 -0
  113. package/dist/lib/safe-store.js +777 -0
  114. package/dist/lib/signals/engine.d.ts +29 -2
  115. package/dist/lib/signals/engine.js +103 -4
  116. package/dist/lib/signals/reply.js +73 -18
  117. package/dist/lib/signals/steps/adapters.js +7 -2
  118. package/dist/lib/signals/steps/extract.d.ts +13 -0
  119. package/dist/lib/signals/steps/extract.js +84 -4
  120. package/dist/main.js +46 -3
  121. package/dist/schemas/hq-environment-profile.v1.schema.json +438 -0
  122. package/dist/utils/auth-expiry.d.ts +8 -0
  123. package/dist/utils/auth-expiry.js +53 -0
  124. package/dist/utils/cli-telemetry.d.ts +21 -0
  125. package/dist/utils/cli-telemetry.js +34 -0
  126. package/dist/utils/command-usage.d.ts +275 -0
  127. package/dist/utils/command-usage.js +797 -0
  128. package/dist/utils/hook-trust.d.ts +7 -0
  129. package/dist/utils/hook-trust.js +31 -4
  130. package/dist/utils/host-registration.d.ts +126 -0
  131. package/dist/utils/host-registration.js +378 -0
  132. package/dist/utils/resident-package-preload.js +2 -0
  133. package/package.json +10 -8
  134. package/scripts/bench-core.mjs +1096 -0
  135. package/scripts/check-function-manifest.mjs +702 -0
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * Subcommands:
5
5
  * hq auth login — open the Cognito Hosted UI in the browser and cache tokens
6
- * hq auth logout — clear the cached HQ session
6
+ * hq auth logout — second name for `hq logout` (same sign-out)
7
7
  * hq auth refresh — ensure a valid cached Cognito session (non-interactive)
8
8
  * hq auth status — show whether a valid session is cached + expiry
9
9
  * hq auth machine-session --output <path> — write machine tokens to a private file
@@ -17,13 +17,14 @@
17
17
  * by the deploy + sync skills.
18
18
  */
19
19
  import { loginWithBrowserPreference } from "../utils/login-browser.js";
20
+ import { formatAuthExpiry } from "../utils/auth-expiry.js";
20
21
  import { releaseCurrentPackageUseLease, releasePackageUseLeaseAfterResidentPreload } from "../utils/package-use-lease.js";
21
22
  import { preloadResidentPackageModules, reportResidentPackagePreloadFailure } from "../utils/resident-package-preload.js";
22
23
  import * as fs from "node:fs";
23
24
  import { open, realpath } from "node:fs/promises";
24
25
  import path from "node:path";
25
26
  import chalk from "chalk";
26
- import { clearCachedTokens, loadCachedTokens, isExpiring, loadMachineCreds, isExternalMachineCreds, CognitoAuthError, } from "@indigoai-us/hq-cloud";
27
+ import { loadCachedTokens, isExpiring, loadMachineCreds, isExternalMachineCreds, CognitoAuthError, } from "@indigoai-us/hq-cloud";
27
28
  import { authenticateMachineSession, MachineLoginError } from "../lib/daemon/machine-login.js";
28
29
  import { DEFAULT_COGNITO, refreshCachedSession, resolveCognitoTokenSource, ensureMachineSessionTokens, personTokenCacheFile, machineTokenCacheFile, loadMachineCachedTokens, } from "../utils/cognito-session.js";
29
30
  // Static (node builtins only): a lazy import here would need a resident
@@ -49,44 +50,6 @@ function decodeIdTokenClaims(idToken) {
49
50
  return undefined;
50
51
  }
51
52
  }
52
- function formatAuthExpiry(expiresAt, now = Date.now()) {
53
- const expiresAtMs = typeof expiresAt === "number" ? expiresAt : Date.parse(expiresAt);
54
- const expiresAtDate = new Date(expiresAtMs);
55
- if (!Number.isFinite(expiresAtMs) || Number.isNaN(expiresAtDate.getTime())) {
56
- return String(expiresAt);
57
- }
58
- const remainingMs = expiresAtMs - now;
59
- const absoluteMs = Math.abs(remainingMs);
60
- let unit;
61
- let unitMs;
62
- if (absoluteMs >= 365 * 24 * 60 * 60 * 1_000) {
63
- unit = "year";
64
- unitMs = 365 * 24 * 60 * 60 * 1_000;
65
- }
66
- else if (absoluteMs >= 30 * 24 * 60 * 60 * 1_000) {
67
- unit = "month";
68
- unitMs = 30 * 24 * 60 * 60 * 1_000;
69
- }
70
- else if (absoluteMs >= 24 * 60 * 60 * 1_000) {
71
- unit = "day";
72
- unitMs = 24 * 60 * 60 * 1_000;
73
- }
74
- else if (absoluteMs >= 60 * 60 * 1_000) {
75
- unit = "hour";
76
- unitMs = 60 * 60 * 1_000;
77
- }
78
- else if (absoluteMs >= 60 * 1_000) {
79
- unit = "minute";
80
- unitMs = 60 * 1_000;
81
- }
82
- else {
83
- unit = "second";
84
- unitMs = 1_000;
85
- }
86
- const relative = new Intl.RelativeTimeFormat("en", { numeric: "always" })
87
- .format(Math.round(remainingMs / unitMs), unit);
88
- return expiresAtDate.toISOString() + " (" + relative + ")";
89
- }
90
53
  function peekIdToken(idToken) {
91
54
  const claims = decodeIdTokenClaims(idToken);
92
55
  return {
@@ -311,7 +274,7 @@ export function registerAuthCommands(program) {
311
274
  const existing = loadCachedTokens();
312
275
  if (existing && !isExpiring(existing, 120)) {
313
276
  const who = peekIdToken(existing.idToken).email ?? "cached session";
314
- console.log(chalk.green(`Already signed in (${who}). Run \`hq auth logout\` to switch accounts.`));
277
+ console.log(chalk.green(`Already signed in (${who}). Run \`hq logout\` to switch accounts.`));
315
278
  return;
316
279
  }
317
280
  try {
@@ -360,17 +323,13 @@ export function registerAuthCommands(program) {
360
323
  });
361
324
  authCmd
362
325
  .command("logout")
363
- .description("Clear the cached HQ Cognito session")
326
+ .description("Same as `hq logout`: end the session on the server and clear cached tokens")
364
327
  .action(async () => {
365
- const { clearMcpOAuthCaches } = await import("../lib/daemon/mcp-oauth.js");
366
- clearMcpOAuthCaches();
367
- const existing = loadCachedTokens();
368
- if (!existing) {
369
- console.log(chalk.yellow("No cached HQ session"));
370
- return;
371
- }
372
- clearCachedTokens();
373
- console.log(chalk.green("Signed out — removed ~/.hq/cognito-tokens.json"));
328
+ // Second name for `hq logout`. It signs out exactly as `hq logout` does,
329
+ // so the refresh token is revoked on the server on this path too. It is
330
+ // not marked retiring yet: the shipped /hq-logout skill still runs it.
331
+ const { runLogout } = await import("./logout.js");
332
+ await runLogout();
374
333
  });
375
334
  authCmd
376
335
  .command("keychain")
@@ -463,7 +422,7 @@ export function registerAuthCommands(program) {
463
422
  console.log(chalk.dim(`token source: ${tokenSource}`));
464
423
  return;
465
424
  }
466
- console.log(chalk.yellow("No cached HQ session — run `hq auth login`"));
425
+ console.log(chalk.yellow("No cached HQ session — run `hq login`"));
467
426
  console.log(chalk.dim(`token source: ${tokenSource}`));
468
427
  process.exit(1);
469
428
  }
@@ -4,6 +4,8 @@ import { legacyProviderLoginProbe } from "../lib/bot/legacy-provider-login.js";
4
4
  import { randomUUID } from "node:crypto";
5
5
  import { CLI_VERSION } from "../cli-version.js";
6
6
  import { runSignals } from "../lib/signals/engine.js";
7
+ // The main bot's runtime, the same one the signals engine's extract step uses.
8
+ import { defaultResolveBotRuntime } from "../lib/signals/steps/extract.js";
7
9
  import { BOT_SIGNALS_ENGINE_JOB_FLAG, signalsEngineForJob } from "../lib/bot/signals-engine-flag.js";
8
10
  import { resolveProcessFlagGate } from "../lib/flag-registry.js";
9
11
  import { currentHotSignalSyncCompany, readActiveCompanySlug, registerHotSignalSyncOnStart, runHotSignalSyncJob } from "../lib/bot/jobs/hot-signal-sync.js";
@@ -12,7 +14,7 @@ import { machineTimeZone } from "../lib/bot/job-run.js";
12
14
  import { runCompanyHotChannelSync } from "./sources.js";
13
15
  import { OwnerContextCache, lookupOwnerContext } from "../lib/bot/owner-context.js";
14
16
  import { hasActivePromotion } from "../lib/bot/promotion-receipt.js";
15
- import { readInflightTurns } from "../lib/bot/inflight.js";
17
+ import { botBusyState, readInflightTurns } from "../lib/bot/inflight.js";
16
18
  import { hasPromotionHold, promotionHoldSummary } from "../lib/bot/promotion-hold.js";
17
19
  /**
18
20
  * `hq bot` — personal local bots (local-bots US-003/US-004/US-005).
@@ -585,6 +587,11 @@ function rowFor(name, opts = {}) {
585
587
  });
586
588
  // Turns this bot has taken and not finished: what "thinking" means.
587
589
  const inflightTurns = readInflightTurns(dir);
590
+ // A gateway that is still starting can carry a dead predecessor's
591
+ // active_agents; the runtime counts turns only once it is running.
592
+ const gatewayState = fleet ? readFleetLocalGatewayState(config.agentUid) : null;
593
+ const gatewayTurns = gatewayState && (gatewayState.gatewayState === "running" || gatewayState.gatewayState === "draining") ? gatewayState.activeAgents : 0;
594
+ const { busy, busySince } = botBusyState(processAlive, inflightTurns, gatewayTurns);
588
595
  let daemonInstalled = false;
589
596
  let daemonLoaded = false;
590
597
  let daemonNodeMissing = null;
@@ -620,8 +627,8 @@ function rowFor(name, opts = {}) {
620
627
  lastHeartbeatOk: status?.lastHeartbeatOk ?? null,
621
628
  lastInboxPollAt: status?.lastInboxPollAt ?? null,
622
629
  lastInboxPollOk: status?.lastInboxPollOk ?? null,
623
- busy: processAlive && inflightTurns.length > 0,
624
- busySince: processAlive ? (inflightTurns[0]?.startedAt ?? null) : null,
630
+ busy,
631
+ busySince,
625
632
  runtimeSignIn: status?.runtimeSignIn ?? null,
626
633
  runtimeSignInCheck: status?.runtimeSignInCheck ?? null,
627
634
  runtimeSignedIn: config.fleetAuthPending === true ? false : runtimeSignedIn(status, processAlive),
@@ -2105,7 +2112,7 @@ async function runBotResident(nameArg) {
2105
2112
  ...(signals ? { signals } : {}),
2106
2113
  sync: (syncInput) => runCompanyHotChannelSync({ hqRoot: config.hqRoot, ...syncInput }),
2107
2114
  // A new pass per run: the login preflight and the 20-document cap are per run.
2108
- signalsPass: createClaudeSignalsPass({ hqRoot: config.hqRoot, company: input.company }),
2115
+ signalsPass: createClaudeSignalsPass({ hqRoot: config.hqRoot, company: input.company, botRuntime: defaultResolveBotRuntime }),
2109
2116
  }));
2110
2117
  // Prefer the Executive bot for daily hot-channel sync. Other personal bots
2111
2118
  // keep their company covered until the Executive has a replacement job.
@@ -17,10 +17,19 @@
17
17
  * 3. Strip `cloud_uid` + `bucket_name` from `companies/manifest.yaml`'s
18
18
  * `companies.<slug>` entry. The slug entry + other fields stay.
19
19
  *
20
- * Safety check (default on): `findCompanyBySlug` MUST return an entity with
21
- * `deleted: true`. A live entity, or no entity at all, refuses with code 2.
22
- * `--force` skips the network call (AppBar passes it because Path A just
23
- * checked).
20
+ * Safety check (default on): `findCompanyBySlug` returning an entity with
21
+ * `deleted: true` passes; a live entity refuses with code 2. hq-pro hides a
22
+ * retired company from by-slug, so on a miss demote reads `companyUid` and
23
+ * `companySlug` from the company's own `.hq/config.json`. It refuses if
24
+ * either is missing or the slug differs, then calls `getCompanyByUid`:
25
+ * - 200 with `deleted: true` and matching slug/uid passes; live refuses;
26
+ * - 404 passes, because hq-pro answers 404 for a retired company. The
27
+ * result's `cloud_check` names the 404 and says demote proceeded because
28
+ * the company is retired or gone;
29
+ * - any other error (403, 5xx, network) refuses.
30
+ * Every refusal names `--force`, which skips the network calls (AppBar
31
+ * passes it because Path A just checked). Nothing in the cloud is deleted
32
+ * or detached by demote.
24
33
  *
25
34
  * Exit codes (mirrors cloud-provision):
26
35
  * 0 — success or idempotent no-op.
@@ -45,6 +54,12 @@ export interface DemoteResult {
45
54
  * a non-deleted entity throws code 2 before reaching the result.)
46
55
  */
47
56
  cloud_was_deleted: boolean | null;
57
+ /**
58
+ * Set only when demote proceeded on a 404 from GET /entity/{uid} for the
59
+ * locally recorded uid (hq-pro returns 404 for a retired company). Says
60
+ * what was checked and why demote went ahead.
61
+ */
62
+ cloud_check?: string;
48
63
  }
49
64
  export interface DemoteCompanyOptions {
50
65
  slug: string;
@@ -17,10 +17,19 @@
17
17
  * 3. Strip `cloud_uid` + `bucket_name` from `companies/manifest.yaml`'s
18
18
  * `companies.<slug>` entry. The slug entry + other fields stay.
19
19
  *
20
- * Safety check (default on): `findCompanyBySlug` MUST return an entity with
21
- * `deleted: true`. A live entity, or no entity at all, refuses with code 2.
22
- * `--force` skips the network call (AppBar passes it because Path A just
23
- * checked).
20
+ * Safety check (default on): `findCompanyBySlug` returning an entity with
21
+ * `deleted: true` passes; a live entity refuses with code 2. hq-pro hides a
22
+ * retired company from by-slug, so on a miss demote reads `companyUid` and
23
+ * `companySlug` from the company's own `.hq/config.json`. It refuses if
24
+ * either is missing or the slug differs, then calls `getCompanyByUid`:
25
+ * - 200 with `deleted: true` and matching slug/uid passes; live refuses;
26
+ * - 404 passes, because hq-pro answers 404 for a retired company. The
27
+ * result's `cloud_check` names the 404 and says demote proceeded because
28
+ * the company is retired or gone;
29
+ * - any other error (403, 5xx, network) refuses.
30
+ * Every refusal names `--force`, which skips the network calls (AppBar
31
+ * passes it because Path A just checked). Nothing in the cloud is deleted
32
+ * or detached by demote.
24
33
  *
25
34
  * Exit codes (mirrors cloud-provision):
26
35
  * 0 — success or idempotent no-op.
@@ -32,6 +41,7 @@ import * as path from "node:path";
32
41
  import * as yaml from "js-yaml";
33
42
  import { parseUserYaml } from "../utils/user-yaml-error.js";
34
43
  import chalk from "chalk";
44
+ import { readLocalCompanyUid } from "./cloud-retire.js";
35
45
  import { ProvisionError, companyConfigPath, companyDirPath, createDefaultVaultClient, manifestPath, validateManifestAndDir, validateSlug, } from "./cloud-provision.js";
36
46
  import { DEFAULT_HQ_ROOT, DEFAULT_VAULT_API_URL, ensureCognitoToken, } from "../utils/cognito-session.js";
37
47
  // ── Helpers ──────────────────────────────────────────────────────────────────
@@ -106,6 +116,7 @@ export async function demoteCompany(options) {
106
116
  // be a silent no-op (all helpers return false but we'd still report ok=true).
107
117
  validateManifestAndDir(options.hqRoot, options.slug);
108
118
  let cloudWasDeleted = null;
119
+ let cloudCheck;
109
120
  if (!options.force) {
110
121
  const accessToken = options.resolveAccessToken
111
122
  ? await options.resolveAccessToken()
@@ -117,17 +128,55 @@ export async function demoteCompany(options) {
117
128
  entity = await client.findCompanyBySlug(options.slug);
118
129
  }
119
130
  catch (err) {
120
- if (err instanceof ProvisionError)
121
- throw err;
122
- throw new ProvisionError(1, `Vault GET by-slug failed: ${err instanceof Error ? err.message : String(err)}`);
131
+ throw refusal(options.slug, err, "the by-slug lookup failed");
123
132
  }
124
133
  if (!entity) {
125
- throw new ProvisionError(2, `Refusing to demote '${options.slug}': no cloud entity found. Pass --force to demote anyway.`);
134
+ // The by-slug route filters out soft-tombstoned entities, so a miss
135
+ // right after `hq cloud retire company` is the expected shape of a
136
+ // retired company. Fall back to the uid recorded locally in
137
+ // `.hq/config.json` (the same fallback retire uses) and read the
138
+ // entity by uid instead.
139
+ const localUid = readLocalCompanyUid(options.hqRoot, options.slug);
140
+ if (!localUid) {
141
+ throw new ProvisionError(2, `Refusing to demote '${options.slug}': no cloud entity found by slug and no local cloud uid in the company's .hq/config.json. Pass --force to demote anyway.`);
142
+ }
143
+ // A copied or stale config can carry another company's uid. The 404
144
+ // rule below trusts the uid only when the same file names this slug.
145
+ const localSlug = readLocalCompanySlug(options.hqRoot, options.slug);
146
+ if (localSlug !== options.slug) {
147
+ throw new ProvisionError(2, `Refusing to demote '${options.slug}': its .hq/config.json records companySlug '${localSlug ?? "(missing)"}', not '${options.slug}'. Nothing was changed. Fix the config, or pass --force to demote anyway.`);
148
+ }
149
+ let byUid;
150
+ try {
151
+ byUid = await client.getCompanyByUid(localUid);
152
+ }
153
+ catch (err) {
154
+ if (!(err instanceof ProvisionError && err.httpStatus === 404)) {
155
+ throw refusal(options.slug, err, `GET /entity/${localUid} failed`);
156
+ }
157
+ // hq-pro answers GET /entity/{uid} with 404 for a tombstoned
158
+ // (retired) company and has no caller-readable tombstone route. The
159
+ // uid and slug both come from this company's own .hq/config.json and
160
+ // the by-slug lookup also missed, so treat the 404 as retired or
161
+ // gone. Demote only touches local files; nothing in the cloud is
162
+ // deleted or detached. Any other error (403, 5xx, network) refuses.
163
+ cloudCheck = `No cloud entity found by slug, and GET /entity/${localUid} (the uid in this company's .hq/config.json) returned 404. Demote proceeded because the company is retired or gone.`;
164
+ }
165
+ if (byUid) {
166
+ // Retire is a soft delete: the entity row keeps its slug and uid.
167
+ // Require both to match before treating it as this slug's entity.
168
+ if (byUid.slug !== options.slug || byUid.uid !== localUid) {
169
+ throw new ProvisionError(2, `Refusing to demote '${options.slug}': the cloud uid in its .hq/config.json (${localUid}) belongs to a different company (slug '${byUid.slug}'). Nothing was changed. Fix the config, or pass --force to demote anyway.`);
170
+ }
171
+ entity = byUid;
172
+ }
126
173
  }
127
- // `deleted` is added by hq-pro and isn't in the static VaultEntity type.
128
- const deleted = entity.deleted === true;
129
- if (!deleted) {
130
- throw new ProvisionError(2, `Refusing to demote '${options.slug}': cloud entity is not deleted (uid=${entity.uid}). Pass --force to demote anyway.`);
174
+ if (entity) {
175
+ // `deleted` is added by hq-pro and isn't in the static VaultEntity type.
176
+ const deleted = entity.deleted === true;
177
+ if (!deleted) {
178
+ throw new ProvisionError(2, `Refusing to demote '${options.slug}': cloud entity is not deleted (uid=${entity.uid}). Pass --force to demote anyway.`);
179
+ }
131
180
  }
132
181
  cloudWasDeleted = true;
133
182
  }
@@ -146,8 +195,29 @@ export async function demoteCompany(options) {
146
195
  yaml_flipped: yamlFlipped,
147
196
  manifest_stripped: manifestStripped,
148
197
  cloud_was_deleted: cloudWasDeleted,
198
+ ...(cloudCheck ? { cloud_check: cloudCheck } : {}),
149
199
  };
150
200
  }
201
+ /** Wrap a failed safety-check call into a refusal that keeps the --force hint. */
202
+ function refusal(slug, err, what) {
203
+ const detail = err instanceof Error ? err.message : String(err);
204
+ return new ProvisionError(err instanceof ProvisionError ? err.code : 1, `Refusing to demote '${slug}': ${what} (${detail}). Nothing was changed. Pass --force to demote anyway.`);
205
+ }
206
+ /** `companySlug` from `companies/<slug>/.hq/config.json`, or null. */
207
+ function readLocalCompanySlug(hqRoot, slug) {
208
+ const cPath = companyConfigPath(hqRoot, slug);
209
+ if (!fs.existsSync(cPath))
210
+ return null;
211
+ try {
212
+ const parsed = JSON.parse(fs.readFileSync(cPath, "utf-8"));
213
+ return typeof parsed.companySlug === "string" && parsed.companySlug.length > 0
214
+ ? parsed.companySlug
215
+ : null;
216
+ }
217
+ catch {
218
+ return null;
219
+ }
220
+ }
151
221
  // ── Commander wiring ─────────────────────────────────────────────────────────
152
222
  /**
153
223
  * Register `demote company <slug>` under the `cloud` command group. Wired in
@@ -176,6 +246,9 @@ export function registerCloudDemoteCommands(program) {
176
246
  vaultApiUrl: options.vaultApiUrl,
177
247
  force: options.force,
178
248
  });
249
+ if (result.cloud_check) {
250
+ process.stderr.write(chalk.yellow(`[hq cloud demote] ${result.cloud_check}\n`));
251
+ }
179
252
  process.stdout.write(JSON.stringify(result) + "\n");
180
253
  process.exit(0);
181
254
  }
@@ -163,7 +163,11 @@ export interface VaultClient {
163
163
  export declare class ProvisionError extends Error {
164
164
  readonly code: 1 | 2 | 3;
165
165
  readonly partial?: Partial<ProvisionResult> | undefined;
166
- constructor(code: 1 | 2 | 3, message: string, partial?: Partial<ProvisionResult> | undefined);
166
+ /** HTTP status of the failed vault response, when there was one. */
167
+ readonly httpStatus?: number | undefined;
168
+ constructor(code: 1 | 2 | 3, message: string, partial?: Partial<ProvisionResult> | undefined,
169
+ /** HTTP status of the failed vault response, when there was one. */
170
+ httpStatus?: number | undefined);
167
171
  }
168
172
  /**
169
173
  * Validate a company slug per the contract: alphanumeric / dot / dash / underscore,
@@ -57,10 +57,14 @@ function hasLocalSharedStarterPath(hqRoot, slug) {
57
57
  export class ProvisionError extends Error {
58
58
  code;
59
59
  partial;
60
- constructor(code, message, partial) {
60
+ httpStatus;
61
+ constructor(code, message, partial,
62
+ /** HTTP status of the failed vault response, when there was one. */
63
+ httpStatus) {
61
64
  super(message);
62
65
  this.code = code;
63
66
  this.partial = partial;
67
+ this.httpStatus = httpStatus;
64
68
  this.name = "ProvisionError";
65
69
  }
66
70
  }
@@ -364,7 +368,7 @@ export function createDefaultVaultClient(apiUrl, accessToken) {
364
368
  return withVaultRequest(url, { method: "GET", headers }, async (res) => {
365
369
  if (!res.ok) {
366
370
  const body = await safeBody(res);
367
- throw new ProvisionError(1, `Vault GET /entity/${uid} failed: ${res.status} ${res.statusText} — ${body}`);
371
+ throw new ProvisionError(1, `Vault GET /entity/${uid} failed: ${res.status} ${res.statusText} — ${body}`, undefined, res.status);
368
372
  }
369
373
  const data = (await res.json());
370
374
  if (!data.entity) {
@@ -490,6 +490,10 @@ export interface ShareCallResult {
490
490
  filesUploaded: number;
491
491
  bytesUploaded: number;
492
492
  filesSkipped: number;
493
+ /** Per-kind skip counts from hq-cloud; absent on an older engine. */
494
+ filesSkippedDetail?: PushSkipDetail;
495
+ /** Non-up-to-date skip reasons this CLI tallied from the push's `reconciled` events. */
496
+ skipReasons?: PushSkipReasonCounts;
493
497
  filesDeleted: number;
494
498
  filesExcludedByScope: number;
495
499
  filesRefusedStale?: number;
@@ -773,5 +777,37 @@ export declare function printReadOnlyLocalOnly(hqRoot: string, journals: Readonl
773
777
  export declare function printServerOwnedLocalOnly(hqRoot: string, journals: ReadonlyArray<StatusJournal>, log?: (line: string) => void, opts?: {
774
778
  all?: boolean;
775
779
  }): number;
780
+ interface PushSkipDetail {
781
+ upToDate: number;
782
+ conflict: number;
783
+ brokenLink: number;
784
+ other: number;
785
+ }
786
+ export type PushSkipReasonCounts = Partial<Record<string, number>>;
787
+ /** Tallies push `reconciled` skip reasons (other than up to date) so every summary can name them. */
788
+ export declare function createPushSkipReasonTracker(): {
789
+ observe: (event: {
790
+ type: string;
791
+ direction?: unknown;
792
+ reason?: unknown;
793
+ }) => void;
794
+ counts: () => PushSkipReasonCounts | undefined;
795
+ };
796
+ /**
797
+ * The one summary every push print site uses. Up-to-date skips read "already
798
+ * up to date" and each other reason is named in words. Conflicts, broken
799
+ * links and reasons that need a look are grouped as "N skipped (...)" and
800
+ * set `warn` so callers can mark the line. Skips with no named reason are
801
+ * counted as a plain "N skipped" and never warn. The counts always add up
802
+ * to filesSkipped.
803
+ */
804
+ export declare function describePushSkips(result: {
805
+ filesSkipped: number;
806
+ filesSkippedDetail?: PushSkipDetail;
807
+ skipReasons?: PushSkipReasonCounts;
808
+ }): {
809
+ text: string;
810
+ warn: boolean;
811
+ };
776
812
  export {};
777
813
  //# sourceMappingURL=cloud.d.ts.map