@indigoai-us/hq-cli 5.345.220 → 5.345.221

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 (138) hide show
  1. package/CHANGELOG.md +118 -0
  2. package/dist/command-catalog.generated.d.ts +144 -2
  3. package/dist/command-catalog.generated.js +175 -2
  4. package/dist/commands/auth.js +4 -1
  5. package/dist/commands/bot-runtime.d.ts +18 -5
  6. package/dist/commands/bot-runtime.js +29 -12
  7. package/dist/commands/bot.d.ts +39 -2
  8. package/dist/commands/bot.js +140 -11
  9. package/dist/commands/core-stop-autosave.d.ts +21 -0
  10. package/dist/commands/core-stop-autosave.js +300 -0
  11. package/dist/commands/core.js +2 -0
  12. package/dist/commands/daemon.d.ts +5 -0
  13. package/dist/commands/daemon.js +31 -7
  14. package/dist/commands/doctor-usage.d.ts +5 -0
  15. package/dist/commands/doctor-usage.js +25 -0
  16. package/dist/commands/env.d.ts +49 -4
  17. package/dist/commands/env.js +355 -5
  18. package/dist/commands/lanes-shared.d.ts +3 -0
  19. package/dist/commands/lanes.d.ts +3 -0
  20. package/dist/commands/lanes.js +87 -3
  21. package/dist/commands/sources.js +3 -3
  22. package/dist/commands/sync-core.d.ts +1 -0
  23. package/dist/commands/sync-core.js +77 -3
  24. package/dist/commands/whoami.js +96 -80
  25. package/dist/lib/bot/config.d.ts +17 -0
  26. package/dist/lib/bot/config.js +13 -0
  27. package/dist/lib/bot/fleet-cron.js +24 -2
  28. package/dist/lib/bot/fleet-local.d.ts +30 -2
  29. package/dist/lib/bot/fleet-local.js +60 -1
  30. package/dist/lib/bot/grok-login-scope.d.ts +36 -0
  31. package/dist/lib/bot/grok-login-scope.js +93 -0
  32. package/dist/lib/bot/legacy-provider-login.d.ts +32 -9
  33. package/dist/lib/bot/legacy-provider-login.js +28 -22
  34. package/dist/lib/bot/runtime-sign-in-check.js +6 -1
  35. package/dist/lib/bot/runtime-sign-in.d.ts +2 -0
  36. package/dist/lib/core-utils/sentry-report.js +2 -0
  37. package/dist/lib/daemon/machine-checks.d.ts +22 -1
  38. package/dist/lib/daemon/machine-checks.js +54 -12
  39. package/dist/lib/daemon/run.js +66 -8
  40. package/dist/lib/daemon/stop-autosave-lock.d.ts +19 -0
  41. package/dist/lib/daemon/stop-autosave-lock.js +166 -0
  42. package/dist/lib/daemon/stop-autosave.d.ts +28 -0
  43. package/dist/lib/daemon/stop-autosave.js +111 -0
  44. package/dist/lib/daemon/stop-diagnostics.d.ts +11 -0
  45. package/dist/lib/daemon/stop-diagnostics.js +136 -0
  46. package/dist/lib/daemon/stop-job-executor.d.ts +19 -0
  47. package/dist/lib/daemon/stop-job-executor.js +126 -0
  48. package/dist/lib/daemon/stop-jobs.d.ts +93 -0
  49. package/dist/lib/daemon/stop-jobs.js +599 -0
  50. package/dist/lib/doctor/checks/fleet-hook-core.js +1 -1
  51. package/dist/lib/doctor/checks/host-core.js +1 -1
  52. package/dist/lib/environment/access-probes.d.ts +234 -0
  53. package/dist/lib/environment/access-probes.js +918 -0
  54. package/dist/lib/environment/profile.d.ts +15 -2
  55. package/dist/lib/environment/profile.js +55 -20
  56. package/dist/lib/environment/rfc3339.d.ts +8 -0
  57. package/dist/lib/environment/rfc3339.js +26 -0
  58. package/dist/lib/environment/work-requirements.d.ts +169 -0
  59. package/dist/lib/environment/work-requirements.js +389 -0
  60. package/dist/lib/hook-engine/coverage.d.ts +137 -7
  61. package/dist/lib/hook-engine/coverage.js +1424 -4
  62. package/dist/lib/hook-engine/fleet-registration.js +2 -2
  63. package/dist/lib/hook-engine/git-stop-config.json +513 -0
  64. package/dist/lib/hook-engine/native-stop-compatibility.json +311 -0
  65. package/dist/lib/hook-engine/reconcile.js +2 -2
  66. package/dist/lib/hot-channels/alert.d.ts +2 -2
  67. package/dist/lib/hot-channels/alert.js +8 -5
  68. package/dist/lib/hot-channels/signals-pass.d.ts +126 -17
  69. package/dist/lib/hot-channels/signals-pass.js +296 -17
  70. package/dist/lib/hot-channels/signals-runtime.d.ts +30 -0
  71. package/dist/lib/hot-channels/signals-runtime.js +82 -0
  72. package/dist/lib/install/hook-target.js +1 -1
  73. package/dist/lib/lanes/host-capacity.d.ts +26 -2
  74. package/dist/lib/lanes/host-capacity.js +17 -2
  75. package/dist/lib/lanes/host-compute.d.ts +90 -0
  76. package/dist/lib/lanes/host-compute.js +185 -0
  77. package/dist/lib/lanes/index.d.ts +2 -0
  78. package/dist/lib/lanes/index.js +1 -0
  79. package/dist/lib/lanes/reconcile.js +22 -1
  80. package/dist/lib/lanes/resource-usage.d.ts +155 -0
  81. package/dist/lib/lanes/resource-usage.js +589 -0
  82. package/dist/lib/lanes/run-size.d.ts +46 -0
  83. package/dist/lib/lanes/run-size.js +197 -0
  84. package/dist/lib/lanes/store.js +27 -0
  85. package/dist/lib/lanes/throttle.d.ts +36 -1
  86. package/dist/lib/lanes/throttle.js +47 -10
  87. package/dist/lib/lanes/types.d.ts +40 -0
  88. package/dist/lib/lanes/types.js +2 -2
  89. package/dist/lib/lanes/watcher.js +13 -4
  90. package/dist/lib/lanes/worker-process.d.ts +25 -2
  91. package/dist/lib/lanes/worker-process.js +71 -19
  92. package/dist/lib/placement/match.d.ts +192 -0
  93. package/dist/lib/placement/match.js +667 -0
  94. package/dist/lib/safe-store.d.ts +14 -0
  95. package/dist/lib/safe-store.js +77 -4
  96. package/dist/lib/search-index/index.d.ts +88 -4
  97. package/dist/lib/search-index/index.js +288 -24
  98. package/dist/lib/search-index/max-doc-bytes.d.ts +17 -6
  99. package/dist/lib/search-index/max-doc-bytes.js +48 -23
  100. package/dist/lib/signals/codex-lockdown.d.ts +79 -0
  101. package/dist/lib/signals/codex-lockdown.js +271 -0
  102. package/dist/lib/signals/codex-login.d.ts +37 -0
  103. package/dist/lib/signals/codex-login.js +83 -0
  104. package/dist/lib/signals/engine.d.ts +27 -0
  105. package/dist/lib/signals/engine.js +70 -0
  106. package/dist/lib/signals/reply.js +22 -1
  107. package/dist/lib/signals/run-record.js +6 -1
  108. package/dist/lib/signals/settings.d.ts +5 -0
  109. package/dist/lib/signals/settings.js +2 -0
  110. package/dist/lib/signals/steps/extract.d.ts +85 -9
  111. package/dist/lib/signals/steps/extract.js +317 -68
  112. package/dist/lib/signals/steps/types.d.ts +2 -0
  113. package/dist/lib/sync-core/engine-home.d.ts +35 -1
  114. package/dist/lib/sync-core/engine-home.js +119 -16
  115. package/dist/lib/sync-core/rollout-state.d.ts +2 -1
  116. package/dist/lib/sync-core/rollout-state.js +5 -2
  117. package/dist/lib/sync-core/vault-uid.d.ts +2 -0
  118. package/dist/lib/sync-core/vault-uid.js +4 -0
  119. package/dist/schemas/hq-work-requirements.v1.schema.json +145 -0
  120. package/dist/utils/auth-session-check.d.ts +16 -0
  121. package/dist/utils/auth-session-check.js +16 -0
  122. package/dist/utils/client-health-contract.d.ts +6 -0
  123. package/dist/utils/client-health-contract.js +13 -0
  124. package/dist/utils/client-health.d.ts +7 -0
  125. package/dist/utils/client-health.js +22 -1
  126. package/dist/utils/command-usage.d.ts +40 -0
  127. package/dist/utils/command-usage.js +61 -0
  128. package/dist/utils/duplicate-command-usage.d.ts +72 -0
  129. package/dist/utils/duplicate-command-usage.js +125 -0
  130. package/dist/utils/host-registration.js +2 -1
  131. package/dist/utils/resident-package-preload.js +4 -0
  132. package/dist/utils/sentry-fingerprint.js +9 -0
  133. package/dist/utils/windows-bash.d.ts +2 -0
  134. package/dist/utils/windows-bash.js +2 -1
  135. package/package.json +9 -8
  136. package/scripts/bench-core-compare.mjs +313 -0
  137. package/scripts/bench-core.mjs +399 -12
  138. package/scripts/check-function-manifest.mjs +116 -3
@@ -67,7 +67,9 @@ export { OUTPOST_DIR, OUTPOST_ID_PATH, readOutpostIdentity } from "../lib/lanes/
67
67
  import { buildOutpostCapacityCommand, buildOutpostIdentityBackfillCommand, buildOutpostLaneCommand, buildOutpostQuestionListCommand, buildOutpostPickupCommand, createOutpostsClient, dispatchErrorMessage, dispatchOutpostPickup, buildOutpostLaneListCommand, buildOutpostLegacyLaneUlidListCommand, REMOTE_LANE_READ_ENV, outpostRejectedEffortOption, parseOutpostPickupPayload, PICKUP_WAIT_MS, stageOutpostPayload, } from "../lib/lanes/outpost-dispatch.js";
68
68
  import { outpostHireSummaryCacheKey, OUTPOST_HIRE_SUMMARY_CACHE_TTL_MS, readOutpostHireSummaryCache, readOutpostHireSummaryCacheIncludingStale, writeOutpostHireSummaryCache, } from "../lib/lanes/outpost-hire-cache.js";
69
69
  import { buildHostCapacitySnapshot, chooseHostForLane, hostCapacitySnapshotToWire, parseHostCapacitySnapshot, } from "../lib/lanes/host-capacity.js";
70
+ import { readHostCompute } from "../lib/lanes/host-compute.js";
70
71
  import { resolveCanonicalHost } from "../lib/lanes/canonical-host.js";
72
+ import { parseLaneRunSize, runSizeMediansByRepo } from "../lib/lanes/run-size.js";
71
73
  import { readInstanceIdFromDisk } from "../lib/lanes/machine-identity.js";
72
74
  import { BALANCE_MOVABLE_STATES, selectClaudeAccount, } from "../lib/lanes/claude-balance.js";
73
75
  import { parseUserYaml } from "../utils/user-yaml-error.js";
@@ -84,11 +86,12 @@ import { applyLoopDisposition, loopDispositionSnapshot } from "../lib/lanes/loop
84
86
  import { listLaneReviews } from "../lib/lanes/reviews.js";
85
87
  import { effectiveAccountHome } from "../lib/lanes/account-home.js";
86
88
  import { remoteControlSelectionConfig, remoteControlSessionHome } from "../lib/lanes/remote-control-lane.js";
87
- import { AccountResolutionError, compareLaneQueueOrder, LANE_PROVIDERS, LANE_STATES, QUESTION_STATUSES, SENIOR_KINDS, accountStatus, appendCappedHistory, canonicalizeHome, createLane, decideAdmission, defaultLivenessDeps, defaultSystemdUserDir, defaultThrottleDeps, installReconcileTimer, providerPathEnv, probeDrainHookRegistration, isLanesError, isLaneVersionConflict, isTerminalLaneState, isFinishedResumableHireChild, childrenHoldingHireGrantCarve, laneHoldsHireGrantCarve, assignedChildHireGrants, hireGrantCapacityError, planHireGrantBackfill, terminalChildResumeHireGrantError, withHireGrantAdmission, laneStoryLedgerEnabled, syncLaneToProjectStoryLedger, removeLaneFromProjectStoryLedger, validateProjectStories, buildLaneStatusSnapshot, formatLaneStatusHuman, expandLocalLaneIdPrefix, listLaneIds, listQuestionIds, loadLanesConfig, laneRunsHere, MAX_LANE_DEPTH, MONITOR_ERROR_EXIT_CODE, readLiveMonitorEvidence, resolveMachineIdentity as lookupMachineIdentity, loadLivenessIndex, parseLaneProvider, isLaneProvider, parseLaneRecord, parseLaneState, parseQuestionRecord, parseSeniorKind, readAllLanes, readLane, sanitizeHostComponent, retryUpdateLane, syncLaneRecordFromOwner, readQuestion, resolveAccount, resolveLaneWorker, ignoredWorkerProfileFields, loadWorkerProfile, loadWorkerProfileWithRegistry, registryWorkerRecord, runReconcilePass, DEAD_HOST_MS, sessionLiveness, tryReadLane, uninstallReconcileTimer, updateLane, updateQuestion, dropboxDir, laneDeliveryMechanism, hasActiveAdmissionReservation, hasActivePendingResume, hasRecordedSessionId, hasEarlierEligibleQueuedLane, laneAdmissionCapReason, providerSupportsSessionResume, providerSessionPortable, isFailedQuotaKeepAliveLane, sessionNotPortableMessage, withLaneAdmissionLock, withAllLaneAdmissionLocks, readWorkerRunResult, resumeCommandRefusal, withLaneHireLocks, raiseLaneQuestion, sha256Text, } from "../lib/lanes/index.js";
89
+ import { AccountResolutionError, compareLaneQueueOrder, LANE_PROVIDERS, LANE_STATES, QUESTION_STATUSES, SENIOR_KINDS, accountStatus, appendCappedHistory, canonicalizeHome, createLane, mintLaneId, decideAdmission, defaultLivenessDeps, defaultSystemdUserDir, defaultThrottleDeps, installReconcileTimer, providerPathEnv, probeDrainHookRegistration, isLanesError, isLaneVersionConflict, isTerminalLaneState, isFinishedResumableHireChild, childrenHoldingHireGrantCarve, laneHoldsHireGrantCarve, assignedChildHireGrants, hireGrantCapacityError, planHireGrantBackfill, terminalChildResumeHireGrantError, withHireGrantAdmission, laneStoryLedgerEnabled, syncLaneToProjectStoryLedger, removeLaneFromProjectStoryLedger, validateProjectStories, buildLaneStatusSnapshot, formatLaneStatusHuman, expandLocalLaneIdPrefix, listLaneIds, listQuestionIds, loadLanesConfig, laneRunsHere, MAX_LANE_DEPTH, MONITOR_ERROR_EXIT_CODE, readLiveMonitorEvidence, resolveMachineIdentity as lookupMachineIdentity, loadLivenessIndex, parseLaneProvider, isLaneProvider, parseLaneRecord, parseLaneState, parseQuestionRecord, parseSeniorKind, readAllLanes, readLane, sanitizeHostComponent, retryUpdateLane, syncLaneRecordFromOwner, readQuestion, resolveAccount, resolveLaneWorker, ignoredWorkerProfileFields, loadWorkerProfile, loadWorkerProfileWithRegistry, registryWorkerRecord, runReconcilePass, DEAD_HOST_MS, sessionLiveness, tryReadLane, uninstallReconcileTimer, updateLane, updateQuestion, dropboxDir, laneDeliveryMechanism, hasActiveAdmissionReservation, hasActivePendingResume, hasRecordedSessionId, hasEarlierEligibleQueuedLane, laneAdmissionCapReason, providerSupportsSessionResume, providerSessionPortable, isFailedQuotaKeepAliveLane, sessionNotPortableMessage, withLaneAdmissionLock, withAllLaneAdmissionLocks, readWorkerRunResult, resumeCommandRefusal, withLaneHireLocks, raiseLaneQuestion, sha256Text, } from "../lib/lanes/index.js";
88
90
  import { admitQueuedNow } from "../lib/lanes/reconcile.js";
89
91
  import { laneStories, storyWarning, } from "../lib/lanes/stories.js";
90
92
  import { resolveLaneKeepAlive } from "../lib/lanes/profile.js";
91
93
  import { laneCompanyUidSource, resolveLaneCompany } from "../lib/lanes/lane-company.js";
94
+ import { deriveWorkRequirements, withRepairedCompany } from "../lib/environment/work-requirements.js";
92
95
  import { doneKeepAliveVerdict, hasPendingKeepAliveWork, keepAliveNextCheckAtMs, keepAliveExclusion, keepAliveSupersededBy, loadRetiredLaneEntries, matchesRetiredLaneEntry, LANE_SUPERSESSION_LINEAGE_AWARE_FLAG, loadRetiredLaneIds, } from "../lib/lanes/keep-alive.js";
93
96
  import { questionBodyAbsPath, resolveQuestionCompanyWithFallback, resolveProjectQuestionCompany, } from "../lib/lanes/questions.js";
94
97
  import { assertQuestionBodySecretSafe } from "../lib/lanes/questions.js";
@@ -422,6 +425,49 @@ function defaultSleep(ms) {
422
425
  function resolveCallerPath(callerCwd, filePath) {
423
426
  return path.resolve(callerCwd, filePath);
424
427
  }
428
+ /**
429
+ * hq-work-requirements.v1 for a lane created with no declaration (PS-002):
430
+ * the lane's company as resolveLaneCompany resolves it (company, mesh
431
+ * company, project company), else the caller's session lock, engines any,
432
+ * the repo the caller is in, on_no_fit conductor-harness.
433
+ *
434
+ * The derivation never breaks lane create: on any failure the lane is
435
+ * created without work_requirements and a warning is written to stderr.
436
+ */
437
+ function derivedLaneWorkRequirements(ctx, hqRoot, lane) {
438
+ try {
439
+ const resolved = resolveLaneCompany(hqRoot, lane);
440
+ const derive = ctx.deriveWorkRequirements ?? deriveWorkRequirements;
441
+ return {
442
+ work_requirements: derive({
443
+ hqRoot,
444
+ cwd: ctx.callerCwd(),
445
+ env: ctx.env,
446
+ origin: { kind: "lane", ref: lane.lane_id },
447
+ company: resolved.company?.slug ?? null,
448
+ }),
449
+ work_requirements_source: "derived",
450
+ };
451
+ }
452
+ catch (error) {
453
+ process.stderr.write(`${JSON.stringify({
454
+ event: "lanes.work_requirements.derive_failed",
455
+ lane_id: lane.lane_id,
456
+ error: error instanceof Error ? error.name : "UnknownError",
457
+ action: "lane created without work_requirements",
458
+ })}\n`);
459
+ return {};
460
+ }
461
+ }
462
+ /**
463
+ * The derived requirements after hq lanes repair-company sets the lane's
464
+ * company. A declared document is left as it is.
465
+ */
466
+ function repairedWorkRequirements(current, company) {
467
+ if (current.work_requirements_source !== "derived" || !current.work_requirements)
468
+ return {};
469
+ return { work_requirements: withRepairedCompany(current.work_requirements, company.slug) };
470
+ }
425
471
  function resolveDeps(deps = {}) {
426
472
  const env = deps.env ?? process.env;
427
473
  const cwd = deps.cwd ?? (() => process.cwd());
@@ -511,6 +557,7 @@ function resolveDeps(deps = {}) {
511
557
  lanePlacementEnabled: deps.lanePlacementEnabled ?? defaultLanePlacementEnabled,
512
558
  storyLedgerEnabled: deps.storyLedgerEnabled ?? laneStoryLedgerEnabled,
513
559
  focusGuardEnabled: deps.focusGuardEnabled,
560
+ deriveWorkRequirements: deps.deriveWorkRequirements,
514
561
  isSsmOwnerDispatch: deps.isSsmOwnerDispatch ?? (() => isSsmRunCommandProcess()),
515
562
  withGrantHireLocks: deps.withGrantHireLocks ?? withLaneHireLocks,
516
563
  withAdmissionLock: deps.withAdmissionLock ?? withLaneAdmissionLock,
@@ -1600,7 +1647,7 @@ async function readOutpostCapacityUncached(ctx, outpostId, waitMs = CAPACITY_PRO
1600
1647
  catch (err) {
1601
1648
  throw new LanesError("outpost_capacity_unavailable", `Outpost ${outpostId} returned invalid capacity JSON: ${dispatchErrorMessage(err)}`, { outpost_id: outpostId });
1602
1649
  }
1603
- const snapshot = parseHostCapacitySnapshot(raw);
1650
+ const snapshot = parseHostCapacitySnapshot(raw, ctx.now());
1604
1651
  if (snapshot.host.kind !== "outpost" || snapshot.host.id !== outpostId) {
1605
1652
  throw new LanesError("outpost_capacity_identity_mismatch", `Capacity response from Outpost ${outpostId} identified a different host`, { requested_outpost_id: outpostId, reported_host: snapshot.host });
1606
1653
  }
@@ -2000,6 +2047,7 @@ async function refreshRemoteLaneMirrors(ctx, hqRoot, records, parentLaneIds, opt
2000
2047
  const envelopeSummary = isTerminalLaneState(owner.state)
2001
2048
  ? owner.envelope_summary
2002
2049
  : undefined;
2050
+ const ownerRunSize = parseLaneRunSize(owner.run_size);
2003
2051
  const before = readLane(hqRoot, mirror.lane_id);
2004
2052
  if (before.host.kind !== "outpost" || before.host.id !== outpostId ||
2005
2053
  !originMatchesThisHost(before) ||
@@ -2031,7 +2079,10 @@ async function refreshRemoteLaneMirrors(ctx, hqRoot, records, parentLaneIds, opt
2031
2079
  before.story_complete !== owner.story_complete ||
2032
2080
  before.story_complete_reason !== owner.story_complete_reason ||
2033
2081
  before.story_status !== owner.story_status ||
2034
- before.terminal_reason !== owner.terminal_reason));
2082
+ before.terminal_reason !== owner.terminal_reason ||
2083
+ // A missing or malformed owner size never forces a rewrite: the
2084
+ // update below keeps the mirror's size in that case.
2085
+ (ownerRunSize !== undefined && JSON.stringify(before.run_size) !== JSON.stringify(ownerRunSize))));
2035
2086
  if (!needsUpdate) {
2036
2087
  result.updated.set(mirror.lane_id, before);
2037
2088
  continue;
@@ -2063,6 +2114,8 @@ async function refreshRemoteLaneMirrors(ctx, hqRoot, records, parentLaneIds, opt
2063
2114
  story_status: owner.story_status,
2064
2115
  terminal_reason: owner.terminal_reason,
2065
2116
  terminal_details: owner.terminal_details,
2117
+ // PS-011: the owner host measured the runs; the mirror keeps its size.
2118
+ ...(ownerRunSize !== undefined ? { run_size: ownerRunSize } : {}),
2066
2119
  } : {}),
2067
2120
  };
2068
2121
  });
@@ -4536,7 +4589,10 @@ async function runCreate(ctx, opts) {
4536
4589
  }
4537
4590
  const queuedReason = admission.action === "queue" ? admission.reason : undefined;
4538
4591
  const admissionReservedAt = admission.action === "start" ? ctx.now().toISOString() : undefined;
4592
+ // Minted here, as createLane would, so the derived requirements can name the lane.
4593
+ const laneId = mintLaneId();
4539
4594
  const laneInit = {
4595
+ lane_id: laneId,
4540
4596
  company,
4541
4597
  ...(opts.signalMetadata ? { signal: opts.signalMetadata, signal_link: opts.signalLink } : {}),
4542
4598
  ...(company === null && meshCompany
@@ -4632,6 +4688,12 @@ async function runCreate(ctx, opts) {
4632
4688
  ...(originHostSource !== undefined
4633
4689
  ? { origin_host_source: originHostSource }
4634
4690
  : {}),
4691
+ ...derivedLaneWorkRequirements(ctx, hqRoot, {
4692
+ lane_id: laneId,
4693
+ company,
4694
+ mesh_company: company === null && meshCompany ? meshCompany : undefined,
4695
+ project_id: project,
4696
+ }),
4635
4697
  attribution_history: [],
4636
4698
  };
4637
4699
  if (senior.kind === "lane" && senior.id) {
@@ -6410,6 +6472,7 @@ async function runList(ctx, opts) {
6410
6472
  ? (await loadHostCapacitySnapshots(ctx, hqRoot, undefined, allLanes)).entries
6411
6473
  .map((entry) => "schema_version" in entry ? hostCapacitySnapshotToWire(entry) : entry)
6412
6474
  : undefined;
6475
+ const runSizeByRepo = runSizeMediansByRepo(selectedLanes);
6413
6476
  const result = {
6414
6477
  ok: true,
6415
6478
  action: "list",
@@ -6418,6 +6481,8 @@ async function runList(ctx, opts) {
6418
6481
  ? { unverified_remote_lanes: [...remoteRefresh.unverifiedRemote.keys()] }
6419
6482
  : {}),
6420
6483
  ...(host_capacity !== undefined ? { host_capacity } : {}),
6484
+ // PS-011: per-repo medians over the listed lanes that carry a run_size.
6485
+ ...(runSizeByRepo.length > 0 ? { run_size_by_repo: runSizeByRepo } : {}),
6421
6486
  };
6422
6487
  if (opts.human)
6423
6488
  console.log(formatLaneListHuman(lanes));
@@ -6571,6 +6636,14 @@ async function runCapacity(ctx) {
6571
6636
  hostname,
6572
6637
  now,
6573
6638
  quotaState: loadQuotaState(hqRoot),
6639
+ // Read only, like the rest of this command: os.cpus, loadavg, the memory
6640
+ // gate's reading and statfs on the HQ root.
6641
+ compute: readHostCompute({
6642
+ deps: ctx.throttleDeps,
6643
+ diskPath: hqRoot,
6644
+ ...(ctx.statfs !== undefined ? { statfs: ctx.statfs } : {}),
6645
+ now,
6646
+ }),
6574
6647
  });
6575
6648
  printJson({
6576
6649
  ...hostCapacitySnapshotToWire(snapshot),
@@ -6837,6 +6910,8 @@ async function runShow(ctx, laneId, hasPendingQuestionForLane, resolveLaneTarget
6837
6910
  failed_resume_history: lane.failed_resume_history ?? [],
6838
6911
  pending_resume: lane.pending_resume ?? null,
6839
6912
  last_run_usage: lane.last_run_usage ?? null,
6913
+ // PS-011: work size and placement summed over the lane's measured runs.
6914
+ run_size: lane.run_size ?? null,
6840
6915
  model: lane.model ?? null,
6841
6916
  effort: lane.effort ?? null,
6842
6917
  effort_source: lane.effort_source ?? null,
@@ -8871,6 +8946,7 @@ async function repairCompanyOnOwner(ctx, laneId, opts, emitResult = true) {
8871
8946
  return {
8872
8947
  ...current,
8873
8948
  company,
8949
+ ...repairedWorkRequirements(current, company),
8874
8950
  company_history: appendCappedHistory(current.company_history ?? [], {
8875
8951
  from: null,
8876
8952
  to: company,
@@ -9543,7 +9619,9 @@ async function runCreateSubagent(ctx, opts) {
9543
9619
  }
9544
9620
  const taskBrief = fs.readFileSync(briefAbs, "utf8");
9545
9621
  const createdAt = ctx.now().toISOString();
9622
+ const laneId = mintLaneId();
9546
9623
  const lane = createLane(hqRoot, {
9624
+ lane_id: laneId,
9547
9625
  company,
9548
9626
  ...(opts.signalMetadata ? { signal: opts.signalMetadata, signal_link: opts.signalLink } : {}),
9549
9627
  ...(company === null && meshCompany ? { mesh_company: meshCompany } : {}),
@@ -9574,6 +9652,12 @@ async function runCreateSubagent(ctx, opts) {
9574
9652
  ...(cliEffort !== undefined ? { effort: cliEffort } : {}),
9575
9653
  effort_source: cliEffort !== undefined ? "cli" : "none",
9576
9654
  host: subagentLaneHost(ctx),
9655
+ ...derivedLaneWorkRequirements(ctx, hqRoot, {
9656
+ lane_id: laneId,
9657
+ company,
9658
+ mesh_company: company === null && meshCompany ? meshCompany : undefined,
9659
+ project_id: project,
9660
+ }),
9577
9661
  attribution_history: [],
9578
9662
  created_at: createdAt,
9579
9663
  updated_at: createdAt,
@@ -38,6 +38,7 @@ import { audienceKey } from "../lib/hot-channels/audience.js";
38
38
  import { appendRunLedgerEntry, ledgerDay, readRunLedger, RUN_TRIGGERS, summarizeRunLedger, } from "../lib/hot-channels/ledger.js";
39
39
  import { createClaudeSignalsPass, DEFAULT_MAX_SIGNAL_DOCS, readPendingSignals, SignalsPassError, } from "../lib/hot-channels/signals-pass.js";
40
40
  import { recordSignalsPassClaudeLogin } from "../lib/hot-channels/signals-claude-login.js";
41
+ import { executiveSignalsRuntimeOptions } from "../lib/hot-channels/signals-runtime.js";
41
42
  import { backlogRunResult, parseSince, queueSignalsRedo, selectSignalsRedo, SignalsRedoUsageError, } from "../lib/hot-channels/signals-redo.js";
42
43
  import { assertSafeSegment } from "../lib/hot-channels/landing.js";
43
44
  import { acquireSyncLock, SYNC_LOCK_BUSY_REASON } from "../lib/hot-channels/sync-lock.js";
@@ -49,7 +50,6 @@ import { S3Client } from "@aws-sdk/client-s3";
49
50
  import { resolveCanonicalPersonUid } from "./cloud.js";
50
51
  import { botsRoot as defaultBotsRoot } from "../lib/bot/paths.js";
51
52
  // The same main-bot runtime the signals engine's extract step uses.
52
- import { defaultResolveBotRuntime } from "../lib/signals/steps/extract.js";
53
53
  import { ensureHotSignalSyncJob } from "../lib/bot/jobs/hot-signal-sync.js";
54
54
  import { resolveExecutiveBot } from "../lib/bot/executive.js";
55
55
  import { companyOfHotSignalSyncJob, fleetCronOps } from "../lib/bot/fleet-cron.js";
@@ -608,7 +608,7 @@ export async function runSync(options, overrides = {}) {
608
608
  ...(overrides.registry ? { registry: overrides.registry } : {}),
609
609
  ...(overrides.now ? { now: overrides.now } : {}),
610
610
  ...(overrides.createSelections ? { createSelections: overrides.createSelections } : {}),
611
- signalsGenerated: overrides.signalsGenerated ?? createClaudeSignalsPass({ hqRoot: options.hqRoot, company, botRuntime: defaultResolveBotRuntime, onClaudeLogin: recordSignalsPassClaudeLogin }),
611
+ signalsGenerated: overrides.signalsGenerated ?? createClaudeSignalsPass({ hqRoot: options.hqRoot, company, ...executiveSignalsRuntimeOptions(), onClaudeLogin: recordSignalsPassClaudeLogin }),
612
612
  // The CLI has no owner-DM sender: the terminal is the primary alert here.
613
613
  signalsAlert: {
614
614
  sendOwnerDm: async (text) => {
@@ -724,7 +724,7 @@ export async function runSignalsRedo(options, overrides = {}) {
724
724
  });
725
725
  const pass = overrides.createPass
726
726
  ? overrides.createPass(maxDocs)
727
- : createClaudeSignalsPass({ hqRoot: options.hqRoot, company, maxDocs, botRuntime: defaultResolveBotRuntime, onClaudeLogin: recordSignalsPassClaudeLogin });
727
+ : createClaudeSignalsPass({ hqRoot: options.hqRoot, company, maxDocs, ...executiveSignalsRuntimeOptions(), onClaudeLogin: recordSignalsPassClaudeLogin });
728
728
  for (const channel of channels) {
729
729
  try {
730
730
  report.signalsWritten += await pass(backlogRunResult(channel), { beforeWrite: lock.assertHeld });
@@ -15,6 +15,7 @@ export interface SyncCoreCommandDeps {
15
15
  arch: string;
16
16
  out: (line: string) => void;
17
17
  err: (line: string) => void;
18
+ now?: () => Date;
18
19
  }
19
20
  export declare function runSyncCoreReconcile(opts: SyncCoreReconcileCommandOptions, d?: SyncCoreCommandDeps): Promise<SyncCoreReconcileResult>;
20
21
  export interface SyncCoreManifestCommandOptions {
@@ -2,6 +2,7 @@ import * as fs from "node:fs";
2
2
  import * as os from "node:os";
3
3
  import * as path from "node:path";
4
4
  import { ensureSyncCoreBinary, readSyncCorePin } from "../lib/sync-core/release.js";
5
+ import { readEngineStatus } from "../lib/sync-core/engine-home.js";
5
6
  import { readCompanyRolloutFlag } from "../lib/sync-core/flag.js";
6
7
  import { reconcileSyncCore } from "../lib/sync-core/reconcile.js";
7
8
  import { engineOwnedManifestScopes, manifestScopeArg } from "../lib/sync-core/manifest-scopes.js";
@@ -109,10 +110,81 @@ export async function runSyncCoreManifest(opts, d = defaultDeps()) {
109
110
  process.exitCode = 1;
110
111
  return results;
111
112
  }
113
+ function ago(at, now) {
114
+ const ms = now.getTime() - Date.parse(at);
115
+ if (!Number.isFinite(ms) || ms < 0)
116
+ return "";
117
+ const minutes = Math.floor(ms / 60_000);
118
+ if (minutes < 1)
119
+ return " (under a minute ago)";
120
+ if (minutes < 120)
121
+ return ` (${minutes} minute${minutes === 1 ? "" : "s"} ago)`;
122
+ const hours = Math.floor(minutes / 60);
123
+ if (hours < 48)
124
+ return ` (${hours} hours ago)`;
125
+ return ` (${Math.floor(hours / 24)} days ago)`;
126
+ }
127
+ function engineStatusLines(engine, full, now) {
128
+ if (!engine)
129
+ return [" no engine status yet (the engine has not written status.json)"];
130
+ const lines = [];
131
+ const live = engine.cycle;
132
+ if (live) {
133
+ const progress = live.phase === "planning"
134
+ ? ""
135
+ : `: ${live.uploadsDone} of ${live.uploadsTotal} uploads, ${live.downloadsDone} of ${live.downloadsTotal} downloads, ${live.failed} failed`;
136
+ lines.push(` cycle running since ${live.startedAt}${ago(live.startedAt, now)}, ${live.phase}${progress}`);
137
+ if (live.currentPath)
138
+ lines.push(` moving ${live.currentPath}`);
139
+ if (live.stale && live.updatedAt) {
140
+ lines.push(` no progress written since ${live.updatedAt}${ago(live.updatedAt, now)}; the engine may have stopped in the middle of this cycle`);
141
+ }
142
+ }
143
+ const c = engine.lastCycle;
144
+ if (c) {
145
+ const extras = [
146
+ ...(c.unsupported > 0 ? [`${c.unsupported} unsupported`] : []),
147
+ ...(c.skipped > 0 ? [`${c.skipped} skipped`] : []),
148
+ ...(c.transferFailures > 0 ? [`${c.transferFailures} failed transfer${c.transferFailures === 1 ? "" : "s"}`] : []),
149
+ ];
150
+ lines.push(` last cycle ${c.at}${ago(c.at, now)}${c.fullVault ? "" : ", one-file canary"}: ${c.planned} planned, ${c.completed} completed, ${c.pending} pending, ${c.held} held, ${c.notApplied} not applied${extras.length > 0 ? `, ${extras.join(", ")}` : ""}; ${c.success ? "everything planned was applied" : "work is left"}`);
151
+ if (c.listed > 0) {
152
+ lines.push(` listed work${c.truncated ? ` (first ${c.listed} items only)` : ""}: ${c.uploads} uploads, ${c.downloads} downloads, ${c.deletes} deletes, ${c.conflicts} conflict or merge copies, ${c.deferred} deferred`);
153
+ }
154
+ if (c.transfersQueued)
155
+ lines.push(` ${c.transfersQueued} transfer${c.transfersQueued === 1 ? "" : "s"} left for the next cycle`);
156
+ if (c.requestPauseUntil)
157
+ lines.push(` paused by the request limit until ${c.requestPauseUntil}`);
158
+ if (c.requestBreakerUntil)
159
+ lines.push(` slowed down by the request breaker until ${c.requestBreakerUntil}`);
160
+ if (c.transferWaitUntil)
161
+ lines.push(` waiting until ${c.transferWaitUntil} before sending again, after transfers failed in transit`);
162
+ if (c.snapshotWaitUntil)
163
+ lines.push(` waiting until ${c.snapshotWaitUntil} to read the vault again`);
164
+ }
165
+ else if (full && !live) {
166
+ lines.push(" no finished cycle yet");
167
+ }
168
+ const running = [
169
+ ...(engine.engineVersion ? [`hq-syncd ${engine.engineVersion}`] : []),
170
+ ...(engine.startedAt ? [`started ${engine.startedAt}`] : []),
171
+ ...(engine.requests24h !== undefined ? [`${engine.requests24h} requests in the last 24 hours`] : []),
172
+ ];
173
+ if (running.length > 0)
174
+ lines.push(` ${running.join(", ")}`);
175
+ return lines;
176
+ }
112
177
  export function runSyncCoreStatus(opts, d = defaultDeps()) {
113
178
  const state = readSyncCoreRolloutState(d.home);
114
179
  if (opts.json) {
115
- d.out(JSON.stringify(state, null, 2));
180
+ const jsonNow = (d.now ?? (() => new Date()))();
181
+ d.out(JSON.stringify(state && {
182
+ ...state,
183
+ vaults: state.vaults.map((vault) => {
184
+ const engine = readEngineStatus(vault.engineHome, vault.uid, jsonNow);
185
+ return engine ? { ...vault, engine } : vault;
186
+ }),
187
+ }, null, 2));
116
188
  return;
117
189
  }
118
190
  if (!state) {
@@ -120,16 +192,18 @@ export function runSyncCoreStatus(opts, d = defaultDeps()) {
120
192
  return;
121
193
  }
122
194
  const switches = readVaultSyncSwitches(d.home);
195
+ const now = (d.now ?? (() => new Date()))();
123
196
  d.out(`engine ${state.release} at ${state.binaryPath}, last read ${state.readAt}`);
124
197
  if (state.error)
125
198
  d.out(`warning: ${state.error}`);
126
199
  for (const vault of state.vaults) {
127
200
  const legacyOff = vault.kind === "personal" ? switches.personalOff : switches.offCompanies.has(vault.slug ?? "");
128
201
  d.out(` ${vault.uid} ${vault.kind}${vault.slug ? ` ${vault.slug}` : ""} ${vault.phase === "full" ? "full" : "read-only"} legacy sync ${legacyOff ? "off" : "still on"} home ${vault.engineHome}`);
202
+ for (const line of engineStatusLines(readEngineStatus(vault.engineHome, vault.uid, now), vault.phase === "full", now))
203
+ d.out(line);
129
204
  if (vault.firstCycle) {
130
205
  const c = vault.firstCycle;
131
- d.out(` first full cycle ${c.at}: ${c.planned} planned, ${c.completed} completed, ${c.pending} pending, ${c.held} held, ${c.notApplied} not applied`);
132
- d.out(` listed work${c.truncated ? ` (first ${c.listed} items only)` : ""}: ${c.uploads} uploads, ${c.downloads} downloads, ${c.deletes} deletes, ${c.conflicts} conflict or merge copies, ${c.deferred} deferred`);
206
+ d.out(` first full cycle ${c.at} (recorded at the switch): ${c.planned} planned, ${c.completed} completed, ${c.pending} pending, ${c.held} held, ${c.notApplied} not applied`);
133
207
  }
134
208
  }
135
209
  for (const skip of state.skipped ?? [])
@@ -11,6 +11,7 @@ import { queuePlanLimitInviteTeammateExposure } from "../utils/cli-telemetry.js"
11
11
  import { resolveCallerPersonUid } from "../utils/vault-api.js";
12
12
  import { printDeletedCompanyNotices } from "../utils/deleted-company-notice.js";
13
13
  import { authExpiryIso, formatAuthExpiry } from "../utils/auth-expiry.js";
14
+ import { authStatusExitCode } from "../utils/auth-session-check.js";
14
15
  export const CLI_LIMIT_INVITE_TEAMMATE_FLAG = "cli.limit-invite-teammate-v1";
15
16
  /**
16
17
  * Resolves the person represented by an ID token without pairing a delegated
@@ -169,6 +170,7 @@ export function registerWhoamiCommand(program) {
169
170
  .description('Show signed-in user and session expiry')
170
171
  .option('--json', 'Output identity metadata as JSON (never tokens)')
171
172
  .option('--company <slug>', 'Also report this company\'s billing and usage notice')
173
+ .option('--check', 'Exit 1 when there is no usable session, like `hq auth status`')
172
174
  .action(async (opts) => {
173
175
  try {
174
176
  // Effective source (same as auth status / ensureCognitoToken): env
@@ -176,87 +178,18 @@ export function registerWhoamiCommand(program) {
176
178
  // after a definitive person-refresh rejection marked the session rejected.
177
179
  const machine = resolveCognitoTokenSource() === "machine";
178
180
  const cached = loadCachedTokens();
179
- if (opts.json) {
180
- const machineCreds = machine ? loadMachineCreds() : null;
181
- const identityCache = machine ? loadMachineCachedTokens() : cached;
182
- const identity = identityCache ? peekIdToken(identityCache.idToken) : {};
183
- const displayedIdentity = resolveWhoamiIdentity(identity);
184
- const claims = identityCache ? decodeIdToken(identityCache.idToken) : {};
185
- // Modern credentials carry the canonical UID. Legacy caches may only
186
- // supply a UID when their subject is bound to the selected username.
187
- const boundLegacyAgent = machineCreds && identity.entityType === 'agent'
188
- && (claims['cognito:username'] === machineCreds.username
189
- || claims.username === machineCreds.username || claims.sub === machineCreds.username)
190
- ? identity.entityUid ?? null : null;
191
- const agentUid = machineCreds?.entityUid !== undefined
192
- ? (machineCreds.entityUid.startsWith('agt_') ? machineCreds.entityUid : null)
193
- : boundLegacyAgent;
194
- // planLimits is additive: absent-or-null means UNKNOWN.
195
- const planLimits = await readPlanLimits(opts.company);
196
- const authenticated = machine ? Boolean(machineCreds) : Boolean(cached && !isExpiring(cached, 0));
197
- const personUid = !machine && authenticated ? await readPersonUid(identity) : null;
198
- console.log(JSON.stringify({
199
- schemaVersion: 1,
200
- authenticated,
181
+ // `--check` keeps the `hq auth status` exit contract (US-041). Read
182
+ // from the same state auth status reads, before any lookup below
183
+ // could refresh the cache, and with the same shared predicate.
184
+ const checkExitCode = opts.check
185
+ ? authStatusExitCode({
201
186
  tokenSource: machine ? 'machine' : 'person',
202
- email: machine ? null : displayedIdentity.email ?? null,
203
- // Cognito subject of the person shown in `email` (null for machine
204
- // identities). Outpost jobs record owners by this id.
205
- sub: machine ? null : displayedIdentity.sub ?? null,
206
- // The human an Outpost session acts for, from the token's
207
- // delegated claims, for machine and person sources alike.
208
- delegatedEmail: identity.delegatedEmail !== undefined && identity.delegatedSub !== undefined
209
- ? identity.delegatedEmail : null,
210
- delegatedSub: identity.delegatedEmail !== undefined && identity.delegatedSub !== undefined
211
- ? identity.delegatedSub : null,
212
- personUid,
213
- agentUid,
214
- username: machineCreds?.username ?? null,
215
- // Additive (what `hq auth status` reported): when the cached
216
- // session expires, and whether it is inside the refresh window.
217
- // Both are null when no session is cached.
218
- sessionExpiresAt: identityCache ? authExpiryIso(identityCache.expiresAt) : null,
219
- sessionExpiring: identityCache ? isExpiring(identityCache) : null,
220
- planLimits,
221
- }, null, 2));
222
- return;
223
- }
224
- if (machine) {
225
- // Machine identities (company agents) mint sessions on demand from
226
- // long-lived creds — report the machine identity honestly even when
227
- // no session is cached yet.
228
- const username = loadMachineCreds()?.username ?? 'unknown';
229
- const entityUid = cached
230
- ? peekIdToken(cached.idToken).entityUid
231
- : undefined;
232
- console.log(`Machine identity ${username}${entityUid ? ` (agent ${entityUid})` : ''} — sessions mint automatically`);
233
- // Machine tokens live in the daemon state dir, never ~/.hq.
234
- const machineSession = loadMachineCachedTokens();
235
- if (machineSession)
236
- console.log(sessionStatusLine(machineSession));
237
- console.log(`token source: machine`);
238
- await printPlanBlock(opts.company);
239
- return;
240
- }
241
- if (!cached) {
242
- // No session, so no session status or token source to report.
243
- console.log("Not logged in. Run 'hq login' to authenticate.");
244
- return;
245
- }
246
- if (isExpiring(cached, 0)) {
247
- const who = resolveWhoamiIdentity(peekIdToken(cached.idToken)).email ?? 'unknown';
248
- console.log(chalk.yellow(`Session expired for ${who}. Run 'hq login' to re-authenticate.`));
249
- console.log(chalk.dim('token source: person'));
250
- return;
251
- }
252
- const { email, sub } = resolveWhoamiIdentity(peekIdToken(cached.idToken));
253
- console.log(`Logged in as ${email ?? 'unknown'}${sub ? ` (${sub})` : ''}`);
254
- console.log(sessionStatusLine(cached));
255
- console.log(chalk.dim('token source: person'));
256
- await printPlanBlock(opts.company);
257
- // Person sessions only: a deleted company is otherwise invisible here.
258
- // Bounded like the person-uid lookup, on stderr, and never a failure.
259
- await printDeletedCompanyNotices({ timeoutMs: PERSON_UID_LOOKUP_TIMEOUT_MS });
187
+ cached: machine ? loadMachineCachedTokens() : cached,
188
+ })
189
+ : 0;
190
+ await printWhoami(opts, machine, cached);
191
+ if (checkExitCode !== 0)
192
+ process.exit(checkExitCode);
260
193
  }
261
194
  catch (error) {
262
195
  console.error(chalk.red('Error:'), error instanceof Error ? error.message : 'Unknown error');
@@ -264,4 +197,87 @@ export function registerWhoamiCommand(program) {
264
197
  }
265
198
  });
266
199
  }
200
+ async function printWhoami(opts, machine, cached) {
201
+ if (opts.json) {
202
+ const machineCreds = machine ? loadMachineCreds() : null;
203
+ const identityCache = machine ? loadMachineCachedTokens() : cached;
204
+ const identity = identityCache ? peekIdToken(identityCache.idToken) : {};
205
+ const displayedIdentity = resolveWhoamiIdentity(identity);
206
+ const claims = identityCache ? decodeIdToken(identityCache.idToken) : {};
207
+ // Modern credentials carry the canonical UID. Legacy caches may only
208
+ // supply a UID when their subject is bound to the selected username.
209
+ const boundLegacyAgent = machineCreds && identity.entityType === 'agent'
210
+ && (claims['cognito:username'] === machineCreds.username
211
+ || claims.username === machineCreds.username || claims.sub === machineCreds.username)
212
+ ? identity.entityUid ?? null : null;
213
+ const agentUid = machineCreds?.entityUid !== undefined
214
+ ? (machineCreds.entityUid.startsWith('agt_') ? machineCreds.entityUid : null)
215
+ : boundLegacyAgent;
216
+ // planLimits is additive: absent-or-null means UNKNOWN.
217
+ const planLimits = await readPlanLimits(opts.company);
218
+ const authenticated = machine ? Boolean(machineCreds) : Boolean(cached && !isExpiring(cached, 0));
219
+ const personUid = !machine && authenticated ? await readPersonUid(identity) : null;
220
+ console.log(JSON.stringify({
221
+ schemaVersion: 1,
222
+ authenticated,
223
+ tokenSource: machine ? 'machine' : 'person',
224
+ email: machine ? null : displayedIdentity.email ?? null,
225
+ // Cognito subject of the person shown in `email` (null for machine
226
+ // identities). Outpost jobs record owners by this id.
227
+ sub: machine ? null : displayedIdentity.sub ?? null,
228
+ // The human an Outpost session acts for, from the token's
229
+ // delegated claims, for machine and person sources alike.
230
+ delegatedEmail: identity.delegatedEmail !== undefined && identity.delegatedSub !== undefined
231
+ ? identity.delegatedEmail : null,
232
+ delegatedSub: identity.delegatedEmail !== undefined && identity.delegatedSub !== undefined
233
+ ? identity.delegatedSub : null,
234
+ personUid,
235
+ agentUid,
236
+ username: machineCreds?.username ?? null,
237
+ // Additive (what `hq auth status` reported): when the cached
238
+ // session expires, and whether it is inside the refresh window.
239
+ // Both are null when no session is cached.
240
+ sessionExpiresAt: identityCache ? authExpiryIso(identityCache.expiresAt) : null,
241
+ sessionExpiring: identityCache ? isExpiring(identityCache) : null,
242
+ planLimits,
243
+ }, null, 2));
244
+ return;
245
+ }
246
+ if (machine) {
247
+ // Machine identities (company agents) mint sessions on demand from
248
+ // long-lived creds — report the machine identity honestly even when
249
+ // no session is cached yet.
250
+ const username = loadMachineCreds()?.username ?? 'unknown';
251
+ const entityUid = cached
252
+ ? peekIdToken(cached.idToken).entityUid
253
+ : undefined;
254
+ console.log(`Machine identity ${username}${entityUid ? ` (agent ${entityUid})` : ''} — sessions mint automatically`);
255
+ // Machine tokens live in the daemon state dir, never ~/.hq.
256
+ const machineSession = loadMachineCachedTokens();
257
+ if (machineSession)
258
+ console.log(sessionStatusLine(machineSession));
259
+ console.log(`token source: machine`);
260
+ await printPlanBlock(opts.company);
261
+ return;
262
+ }
263
+ if (!cached) {
264
+ // No session, so no session status or token source to report.
265
+ console.log("Not logged in. Run 'hq login' to authenticate.");
266
+ return;
267
+ }
268
+ if (isExpiring(cached, 0)) {
269
+ const who = resolveWhoamiIdentity(peekIdToken(cached.idToken)).email ?? 'unknown';
270
+ console.log(chalk.yellow(`Session expired for ${who}. Run 'hq login' to re-authenticate.`));
271
+ console.log(chalk.dim('token source: person'));
272
+ return;
273
+ }
274
+ const { email, sub } = resolveWhoamiIdentity(peekIdToken(cached.idToken));
275
+ console.log(`Logged in as ${email ?? 'unknown'}${sub ? ` (${sub})` : ''}`);
276
+ console.log(sessionStatusLine(cached));
277
+ console.log(chalk.dim('token source: person'));
278
+ await printPlanBlock(opts.company);
279
+ // Person sessions only: a deleted company is otherwise invisible here.
280
+ // Bounded like the person-uid lookup, on stderr, and never a failure.
281
+ await printDeletedCompanyNotices({ timeoutMs: PERSON_UID_LOOKUP_TIMEOUT_MS });
282
+ }
267
283
  //# sourceMappingURL=whoami.js.map
@@ -178,7 +178,24 @@ export interface BotConfig {
178
178
  * capacity account home. Names only, never a credential.
179
179
  */
180
180
  runtimeAuth?: BotRuntimeAuthMap;
181
+ /**
182
+ * Which model the local hot-channel signals pass uses (signals-pass.ts).
183
+ * Unset or "claude": Claude Code, as before. "bot": the bot's own runtime,
184
+ * which today takes effect for a Codex bot only (a Claude bot already runs
185
+ * on Claude; Grok is not supported). Per bot and local; set with
186
+ * `hq bot set <name> --signals-runtime bot|claude`.
187
+ */
188
+ signalsRuntime?: BotSignalsRuntimeSetting;
181
189
  }
190
+ /** The `signalsRuntime` values bot.json accepts. */
191
+ export declare const BOT_SIGNALS_RUNTIME_SETTINGS: readonly ["claude", "bot"];
192
+ export type BotSignalsRuntimeSetting = (typeof BOT_SIGNALS_RUNTIME_SETTINGS)[number];
193
+ /**
194
+ * The tool the hot-channel signals pass runs on for this bot: Codex only for
195
+ * a Codex bot that opted in with `signalsRuntime: "bot"`, Claude Code for
196
+ * every other bot (and for no bot at all).
197
+ */
198
+ export declare function signalsPassRuntime(config: Pick<BotConfig, "runtime" | "signalsRuntime"> | null | undefined): "claude" | "codex";
182
199
  export declare function readBotConfig(dir: string): BotConfig | null;
183
200
  export declare function writeBotConfig(dir: string, config: BotConfig): void;
184
201
  /** "local" when the memory folder is an absolute path outside the HQ tree. */
@@ -204,6 +204,19 @@ export function validateBotKickoff(text) {
204
204
  }
205
205
  return trimmed;
206
206
  }
207
+ /** The `signalsRuntime` values bot.json accepts. */
208
+ export const BOT_SIGNALS_RUNTIME_SETTINGS = ["claude", "bot"];
209
+ /**
210
+ * The tool the hot-channel signals pass runs on for this bot: Codex only for
211
+ * a Codex bot that opted in with `signalsRuntime: "bot"`, Claude Code for
212
+ * every other bot (and for no bot at all).
213
+ */
214
+ export function signalsPassRuntime(config) {
215
+ // Whether that bot's Codex login may be used (an HQ Fleet Runtime bot's may
216
+ // not) is decided in one place, signalsCodexLogin; `hq bot set` refuses the
217
+ // opt-in where it fails, and a pass that meets it reports codex-logged-out.
218
+ return config?.runtime === "codex" && config.signalsRuntime === "bot" ? "codex" : "claude";
219
+ }
207
220
  export function readBotConfig(dir) {
208
221
  const p = botConfigPath(dir);
209
222
  if (!fs.existsSync(p))