@indigoai-us/hq-cli 5.345.218 → 5.345.220

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 +130 -0
  2. package/dist/command-catalog.generated.d.ts +94 -1
  3. package/dist/command-catalog.generated.js +114 -1
  4. package/dist/commands/agents.d.ts +22 -0
  5. package/dist/commands/agents.js +92 -1
  6. package/dist/commands/bot.d.ts +48 -0
  7. package/dist/commands/bot.js +108 -8
  8. package/dist/commands/cloud.d.ts +16 -0
  9. package/dist/commands/cloud.js +112 -102
  10. package/dist/commands/core-checkpoint-native.d.ts +13 -0
  11. package/dist/commands/core-checkpoint-native.js +167 -52
  12. package/dist/commands/core-hook-registration-plan.d.ts +8 -0
  13. package/dist/commands/core-hook-registration-plan.js +22 -0
  14. package/dist/commands/core.js +9 -0
  15. package/dist/commands/daemon.js +21 -2
  16. package/dist/commands/doctor.js +4 -0
  17. package/dist/commands/integrations.js +84 -3
  18. package/dist/commands/lanes-shared.d.ts +2 -0
  19. package/dist/commands/lanes-watch.js +28 -1
  20. package/dist/commands/lanes.d.ts +2 -0
  21. package/dist/commands/lanes.js +99 -9
  22. package/dist/commands/packs.js +23 -0
  23. package/dist/commands/pkg-update.d.ts +6 -0
  24. package/dist/commands/pkg-update.js +15 -7
  25. package/dist/commands/reindex.js +6 -0
  26. package/dist/commands/run.js +55 -45
  27. package/dist/commands/sources.js +3 -2
  28. package/dist/index.js +8 -0
  29. package/dist/lib/anywhere-person-setting.d.ts +2 -2
  30. package/dist/lib/anywhere-person-setting.js +2 -2
  31. package/dist/lib/bot/fleet-cron.js +5 -2
  32. package/dist/lib/bot/inflight.d.ts +9 -0
  33. package/dist/lib/bot/jobs/hot-signal-sync.d.ts +51 -0
  34. package/dist/lib/bot/jobs/hot-signal-sync.js +90 -9
  35. package/dist/lib/bot/run.d.ts +29 -5
  36. package/dist/lib/bot/run.js +203 -1
  37. package/dist/lib/bot/signals-try-now.d.ts +76 -0
  38. package/dist/lib/bot/signals-try-now.js +111 -0
  39. package/dist/lib/capacity/collectors/claude-oauth.d.ts +22 -3
  40. package/dist/lib/capacity/collectors/claude-oauth.js +78 -22
  41. package/dist/lib/capacity/scheduler.d.ts +8 -0
  42. package/dist/lib/capacity/scheduler.js +5 -2
  43. package/dist/lib/daemon/anywhere-listener.d.ts +33 -1
  44. package/dist/lib/daemon/anywhere-listener.js +86 -4
  45. package/dist/lib/daemon/machine-check-owner.d.ts +21 -0
  46. package/dist/lib/daemon/machine-check-owner.js +95 -0
  47. package/dist/lib/daemon/machine-check-registration.d.ts +4 -0
  48. package/dist/lib/daemon/machine-check-registration.js +64 -0
  49. package/dist/lib/daemon/machine-checks.d.ts +144 -0
  50. package/dist/lib/daemon/machine-checks.js +412 -0
  51. package/dist/lib/daemon/run.js +35 -4
  52. package/dist/lib/daemon/runtime-notifications.d.ts +7 -0
  53. package/dist/lib/daemon/runtime-notifications.js +50 -0
  54. package/dist/lib/daemon/server.d.ts +2 -0
  55. package/dist/lib/daemon/server.js +6 -0
  56. package/dist/lib/daemon/state-file.d.ts +12 -1
  57. package/dist/lib/daemon/state-file.js +23 -1
  58. package/dist/lib/doctor/checks/fleet-hook-core.d.ts +12 -0
  59. package/dist/lib/doctor/checks/fleet-hook-core.js +127 -0
  60. package/dist/lib/doctor/checks/host-core.js +3 -1
  61. package/dist/lib/doctor/checks/machine-checks.d.ts +16 -0
  62. package/dist/lib/doctor/checks/machine-checks.js +103 -0
  63. package/dist/lib/doctor/registry.js +4 -0
  64. package/dist/lib/doctor/types.d.ts +4 -0
  65. package/dist/lib/hook-engine/canary-gate.d.ts +64 -0
  66. package/dist/lib/hook-engine/canary-gate.js +147 -0
  67. package/dist/lib/hook-engine/coverage.d.ts +3 -1
  68. package/dist/lib/hook-engine/coverage.js +8 -2
  69. package/dist/lib/hook-engine/fleet-registration.d.ts +42 -0
  70. package/dist/lib/hook-engine/fleet-registration.js +168 -0
  71. package/dist/lib/hook-engine/reconcile.js +3 -2
  72. package/dist/lib/hook-engine/registration-identity.d.ts +33 -0
  73. package/dist/lib/hook-engine/registration-identity.js +97 -0
  74. package/dist/lib/hook-engine/registration.d.ts +1 -30
  75. package/dist/lib/hook-engine/registration.js +1 -88
  76. package/dist/lib/hook-engine/resolve.d.ts +2 -0
  77. package/dist/lib/hook-engine/resolve.js +7 -3
  78. package/dist/lib/hot-channels/alert.d.ts +10 -1
  79. package/dist/lib/hot-channels/alert.js +34 -7
  80. package/dist/lib/hot-channels/signals-claude-login.d.ts +53 -0
  81. package/dist/lib/hot-channels/signals-claude-login.js +96 -0
  82. package/dist/lib/hot-channels/signals-pass.d.ts +17 -0
  83. package/dist/lib/hot-channels/signals-pass.js +31 -3
  84. package/dist/lib/lanes/canonical-host.d.ts +8 -1
  85. package/dist/lib/lanes/canonical-host.js +9 -3
  86. package/dist/lib/lanes/machine-identity.d.ts +15 -0
  87. package/dist/lib/lanes/machine-identity.js +26 -0
  88. package/dist/lib/lanes/spawn.js +17 -3
  89. package/dist/lib/search-index/index.js +11 -1
  90. package/dist/lib/signals/engine.d.ts +1 -0
  91. package/dist/lib/signals/engine.js +7 -0
  92. package/dist/lib/signals/reply.d.ts +48 -0
  93. package/dist/lib/signals/reply.js +72 -11
  94. package/dist/lib/signals/steps/adapters.js +6 -0
  95. package/dist/lib/signals/steps/extract.d.ts +50 -3
  96. package/dist/lib/signals/steps/extract.js +100 -17
  97. package/dist/lib/signals/steps/types.d.ts +19 -0
  98. package/dist/lib/sync-core/engine-home.d.ts +6 -1
  99. package/dist/lib/sync-core/engine-home.js +13 -3
  100. package/dist/lib/sync-core/reconcile.js +1 -1
  101. package/dist/lib/sync-core/release-compare.d.ts +7 -0
  102. package/dist/lib/sync-core/release-compare.js +16 -0
  103. package/dist/lib/sync-core/release.d.ts +2 -1
  104. package/dist/lib/sync-core/release.js +2 -10
  105. package/dist/run/schema-env-overrides.d.ts +24 -0
  106. package/dist/run/schema-env-overrides.js +72 -0
  107. package/dist/utils/core-next-flag.d.ts +4 -0
  108. package/dist/utils/core-next-flag.js +22 -0
  109. package/dist/utils/core-next-kill.d.ts +16 -0
  110. package/dist/utils/core-next-kill.js +35 -0
  111. package/dist/utils/host-registration.d.ts +33 -23
  112. package/dist/utils/host-registration.js +90 -66
  113. package/package.json +14 -10
  114. package/scripts/check-function-manifest.mjs +5 -4
  115. package/dist/commands/__fixtures__/access-vault.d.ts +0 -95
  116. package/dist/commands/__fixtures__/access-vault.js +0 -166
  117. package/dist/commands/__fixtures__/make-tar.d.ts +0 -38
  118. package/dist/commands/__fixtures__/make-tar.js +0 -102
  119. package/dist/commands/secrets-public-types.test-d.d.ts +0 -2
  120. package/dist/commands/secrets-public-types.test-d.js +0 -18
  121. package/dist/lib/decisions/fixtures/us001.d.ts +0 -137
  122. package/dist/lib/decisions/fixtures/us001.js +0 -21
  123. package/dist/lib/doctor/__testing__/fake-hq-tree.d.ts +0 -226
  124. package/dist/lib/doctor/__testing__/fake-hq-tree.js +0 -408
  125. package/dist/lib/doctor/__testing__/run-doctor.d.ts +0 -8
  126. package/dist/lib/doctor/__testing__/run-doctor.js +0 -69
  127. package/dist/lib/fingerprint/fixtures.d.ts +0 -19
  128. package/dist/lib/fingerprint/fixtures.js +0 -61
  129. package/dist/lib/hot-channels/adapters/__fixtures__/dummy.d.ts +0 -33
  130. package/dist/lib/hot-channels/adapters/__fixtures__/dummy.js +0 -53
  131. package/dist/lib/hot-channels/adapters/__fixtures__/meeting-providers.d.ts +0 -38
  132. package/dist/lib/hot-channels/adapters/__fixtures__/meeting-providers.js +0 -64
  133. package/dist/lib/mesh/live/daemon/mqtt-events.test-d.d.ts +0 -2
  134. package/dist/lib/mesh/live/daemon/mqtt-events.test-d.js +0 -10
  135. package/dist/lib/test-utils/isolated-flag-company-context.d.ts +0 -3
  136. package/dist/lib/test-utils/isolated-flag-company-context.js +0 -18
  137. package/scripts/hook-engine-manifest.mjs +0 -22
  138. package/scripts/mesh-daemon-if-stale.mjs +0 -20
@@ -11,6 +11,7 @@ import * as path from "node:path";
11
11
  import { createHash, randomUUID } from "node:crypto";
12
12
  import { execFileSync, spawn } from "node:child_process";
13
13
  import { homedir } from "node:os";
14
+ import { isDeepStrictEqual } from "node:util";
14
15
  import { toHqStateWriteError } from "../utils/hq-state-write-error.js";
15
16
  import { checkpointStampWriteErrorFor, isCheckpointStampWriteError, } from "../utils/checkpoint-stamp-write-error.js";
16
17
  import { isExecutableOnPath } from "../utils/resolve-executable.js";
@@ -585,19 +586,24 @@ function writeCheckpointStampAtomically(targetPath, contents, fsImpl, waitForRet
585
586
  }
586
587
  }
587
588
  }
589
+ /**
590
+ * Filename-safe form of a session ID, shared by every per-session state file
591
+ * (checkpoint-cli-last-*, checkpoint-auto-sibling-*, checkpoint-auto-thread-*).
592
+ */
593
+ function sessionKey(sessionId) {
594
+ return sessionId ? sessionId.replace(/[^A-Za-z0-9._-]/g, "_") || "unknown" : "unknown";
595
+ }
588
596
  export function writeStamps(liveRoot, sessionId, options = {}) {
589
597
  const fsImpl = options.fs ?? fs;
590
598
  const platform = options.platform ?? process.platform;
591
599
  const waitForRetry = options.waitForRetry ?? waitForCheckpointWriteRetry;
592
600
  const stateDir = path.join(liveRoot, "workspace", "orchestrator", "hook-state");
593
601
  writeHqState(stateDir, "create the checkpoint state directory", () => fsImpl.mkdirSync(stateDir, { recursive: true }));
594
- const sessionKey = sessionId
595
- ? sessionId.replace(/[^A-Za-z0-9._-]/g, "_") || "unknown"
596
- : "unknown";
602
+ const key = sessionKey(sessionId);
597
603
  const timestamp = Math.floor(Date.now() / 1000).toString();
598
604
  const stampPaths = [
599
605
  path.join(stateDir, "checkpoint-cli-last"),
600
- path.join(stateDir, `checkpoint-cli-last-${sessionKey}`),
606
+ path.join(stateDir, `checkpoint-cli-last-${key}`),
601
607
  ];
602
608
  for (const stampPath of stampPaths) {
603
609
  writeHqState(stampPath, "write its checkpoint state file", () => platform === "win32"
@@ -606,9 +612,67 @@ export function writeStamps(liveRoot, sessionId, options = {}) {
606
612
  }
607
613
  return stampPaths;
608
614
  }
615
+ function autoThreadPointerPath(liveRoot, sessionId) {
616
+ return path.join(liveRoot, "workspace", "orchestrator", "hook-state", `checkpoint-auto-thread-${sessionKey(sessionId)}`);
617
+ }
618
+ /**
619
+ * The session's existing automatic checkpoint thread, if any. The Stop gate
620
+ * fires `--trigger stop-gate-auto` after every replied turn, and each run used
621
+ * to write a new `T-*-auto-*.json` (about 3,500 files and a 700 KB threads
622
+ * index in one install, feedback_b4d615f1). A per-session pointer stamp names
623
+ * the thread file; it is trusted only when the file still parses and carries
624
+ * the same session_id and the stop-gate-auto trigger. Only that trigger reuses
625
+ * a thread: explicit checkpoints always write their own. Without a session ID
626
+ * there is nothing to match on, so a new thread is written.
627
+ */
628
+ function findAutoThread(liveRoot, trigger, sessionId) {
629
+ if (trigger !== AUTO_TRIGGER || !sessionId)
630
+ return null;
631
+ try {
632
+ const name = fs.readFileSync(autoThreadPointerPath(liveRoot, sessionId), "utf8").trim();
633
+ if (!name || name !== path.basename(name) || !name.endsWith(".json"))
634
+ return null;
635
+ const threadPath = path.join(liveRoot, "workspace", "threads", name);
636
+ const thread = JSON.parse(fs.readFileSync(threadPath, "utf8"));
637
+ if (thread.session_id !== sessionId || thread.metadata?.trigger !== AUTO_TRIGGER)
638
+ return null;
639
+ return { threadPath, thread };
640
+ }
641
+ catch {
642
+ return null;
643
+ }
644
+ }
645
+ /**
646
+ * Test seam: runs after the auto thread was found and before the existence
647
+ * re-check, so a test can delete or rename the thread in that window.
648
+ */
649
+ export const checkpointTestSeams = {};
650
+ /**
651
+ * Write through a temp file in the same directory, then rename (atomic). On any
652
+ * failure the temp file is removed and the error is rethrown. `fsImpl` is a
653
+ * test seam.
654
+ */
655
+ export function writeFileAtomic(target, contents, fsImpl = fs) {
656
+ const tmp = `${target}.${process.pid}.${randomUUID()}.tmp`;
657
+ try {
658
+ fsImpl.writeFileSync(tmp, contents);
659
+ fsImpl.renameSync(tmp, target);
660
+ }
661
+ catch (error) {
662
+ try {
663
+ fsImpl.unlinkSync(tmp);
664
+ }
665
+ catch {
666
+ // nothing to clean up
667
+ }
668
+ throw error;
669
+ }
670
+ }
671
+ function mergeUnique(a, b) {
672
+ return [...new Set([...(a ?? []), ...b])];
673
+ }
609
674
  function autoSiblingStampPath(liveRoot, sessionId) {
610
- const sessionKey = sessionId.replace(/[^A-Za-z0-9._-]/g, "_") || "unknown";
611
- return path.join(liveRoot, "workspace", "orchestrator", "hook-state", `checkpoint-auto-sibling-${sessionKey}`);
675
+ return path.join(liveRoot, "workspace", "orchestrator", "hook-state", `checkpoint-auto-sibling-${sessionKey(sessionId)}`);
612
676
  }
613
677
  /**
614
678
  * True when an automatic checkpoint for this session already started (or
@@ -1555,54 +1619,105 @@ async function runCheckpoint(options, command, group, preResolvedHqRoot) {
1555
1619
  ? "none"
1556
1620
  : await resolveBackend(requestedBackend, liveRoot, input.company, { dryRun: options.dryRun });
1557
1621
  const now = new Date();
1558
- const threadId = `T-${formatTimestamp(now)}-auto-${summarySlug(input.summary)}`;
1559
- const threadPath = path.join(liveRoot, "workspace", "threads", `${threadId}.json`);
1560
- const relativeThreadPath = path.relative(liveRoot, threadPath);
1561
- const git = gitStateFor(process.cwd(), liveRoot, input.initialCommit, input.commits);
1562
- const stampPaths = [
1563
- path.join(liveRoot, "workspace", "orchestrator", "hook-state", "checkpoint-cli-last"),
1564
- path.join(liveRoot, "workspace", "orchestrator", "hook-state", `checkpoint-cli-last-${input.sessionId ? input.sessionId.replace(/[^A-Za-z0-9._-]/g, "_") || "unknown" : "unknown"}`),
1565
- ];
1566
- if (options.dryRun) {
1567
- printDryRun({
1568
- live_root: liveRoot,
1569
- idle: false,
1570
- thread: relativeThreadPath,
1571
- checkpoint: {
1572
- git,
1573
- insights: input.insights,
1574
- worker: input.worker,
1622
+ let existingAuto = findAutoThread(liveRoot, input.trigger, input.sessionId);
1623
+ let threadId = existingAuto?.thread.thread_id ?? `T-${formatTimestamp(now)}-auto-${summarySlug(input.summary)}`;
1624
+ let threadPath = existingAuto?.threadPath ?? path.join(liveRoot, "workspace", "threads", `${threadId}.json`);
1625
+ let relativeThreadPath = path.relative(liveRoot, threadPath);
1626
+ {
1627
+ const git = gitStateFor(process.cwd(), liveRoot, input.initialCommit, input.commits);
1628
+ const stampPaths = [
1629
+ path.join(liveRoot, "workspace", "orchestrator", "hook-state", "checkpoint-cli-last"),
1630
+ path.join(liveRoot, "workspace", "orchestrator", "hook-state", `checkpoint-cli-last-${sessionKey(input.sessionId)}`),
1631
+ ];
1632
+ if (options.dryRun) {
1633
+ printDryRun({
1634
+ live_root: liveRoot,
1635
+ idle: false,
1636
+ thread: relativeThreadPath,
1637
+ checkpoint: {
1638
+ git,
1639
+ insights: input.insights,
1640
+ worker: input.worker,
1641
+ },
1642
+ stamps: stampPaths.map((stampPath) => path.relative(liveRoot, stampPath)),
1643
+ sibling: siblingOptOut || autoDebounced ? null : { backend },
1644
+ });
1645
+ return;
1646
+ }
1647
+ if (existingAuto) {
1648
+ checkpointTestSeams.beforeAutoThreadWrite?.();
1649
+ // The maintenance sibling may have renamed or archived the thread since
1650
+ // it was found. Do not resurrect the old name: start a new thread.
1651
+ if (!fs.existsSync(existingAuto.threadPath)) {
1652
+ existingAuto = null;
1653
+ threadId = `T-${formatTimestamp(now)}-auto-${summarySlug(input.summary)}`;
1654
+ threadPath = path.join(liveRoot, "workspace", "threads", `${threadId}.json`);
1655
+ relativeThreadPath = path.relative(liveRoot, threadPath);
1656
+ }
1657
+ }
1658
+ const prior = existingAuto?.thread;
1659
+ // Merge policy when reusing a thread: files_touched, learnings, insights,
1660
+ // decisions and tags are unioned. next_steps, conversation_summary and the
1661
+ // git fields are REPLACED by this run's values. Keys the maintenance
1662
+ // sibling added (top-level or inside git, such as git.knowledge_repos)
1663
+ // survive because the update is spread over the prior thread.
1664
+ // Title rule: metadata.title is set from this run's summary only when the
1665
+ // prior thread has no title, or its title still equals the one
1666
+ // auto-generated from the prior summary; a title the sibling improved is
1667
+ // kept.
1668
+ // Concurrency: same-session runs are not serialised (no lockfile). Writes
1669
+ // are atomic (temp file plus rename), so a reader never sees a partial
1670
+ // file. The existence re-check above narrows resurrecting a renamed-away
1671
+ // thread to a very small window between the check and the rename. Two runs
1672
+ // of the same session at the same instant can lose one union merge, and on
1673
+ // the session's first turn they can fork a second thread (the last pointer
1674
+ // write wins).
1675
+ const priorTitle = prior?.metadata?.title;
1676
+ const keepTitle = typeof priorTitle === "string" &&
1677
+ priorTitle !== "" &&
1678
+ priorTitle !== titleFor(prior?.conversation_summary ?? "");
1679
+ const thread = {
1680
+ ...prior,
1681
+ thread_id: threadId,
1682
+ version: 1,
1683
+ type: "auto-checkpoint",
1684
+ created_at: prior?.created_at ?? now.toISOString(),
1685
+ updated_at: now.toISOString(),
1686
+ workspace_root: liveRoot,
1687
+ cwd: process.cwd(),
1688
+ git: { ...prior?.git, ...git },
1689
+ conversation_summary: input.summary,
1690
+ files_touched: mergeUnique(prior?.files_touched, input.files),
1691
+ next_steps: input.nextSteps,
1692
+ learnings: mergeUnique(prior?.learnings, input.learnings),
1693
+ insights: mergeUnique(prior?.insights, input.insights),
1694
+ decisions: mergeUnique(prior?.decisions, input.decisions),
1695
+ worker: input.worker ?? prior?.worker,
1696
+ session_id: input.sessionId ?? null,
1697
+ metadata: {
1698
+ ...prior?.metadata,
1699
+ title: keepTitle ? priorTitle : titleFor(input.summary),
1700
+ tags: mergeUnique(prior?.metadata?.tags, ["auto-checkpoint", ...input.tags]),
1701
+ trigger: input.trigger,
1575
1702
  },
1576
- stamps: stampPaths.map((stampPath) => path.relative(liveRoot, stampPath)),
1577
- sibling: siblingOptOut || autoDebounced ? null : { backend },
1578
- });
1579
- return;
1703
+ };
1704
+ // Nothing changed since the last update: leave the file (and its mtime)
1705
+ // alone rather than rewrite it with a new updated_at. Deep-equal, so key
1706
+ // order does not matter; the JSON round trip drops undefined values.
1707
+ const unchanged = prior !== undefined &&
1708
+ isDeepStrictEqual({ ...prior, updated_at: "" }, { ...JSON.parse(JSON.stringify(thread)), updated_at: "" });
1709
+ if (!unchanged) {
1710
+ writeHqState(path.dirname(threadPath), "create the checkpoint thread directory", () => fs.mkdirSync(path.dirname(threadPath), { recursive: true }));
1711
+ writeHqState(threadPath, "write the checkpoint thread file", () => writeFileAtomic(threadPath, `${JSON.stringify(thread, null, 2)}\n`));
1712
+ }
1713
+ if (!existingAuto && input.trigger === AUTO_TRIGGER && input.sessionId) {
1714
+ const pointerPath = autoThreadPointerPath(liveRoot, input.sessionId);
1715
+ writeHqState(pointerPath, "record the session's auto checkpoint thread", () => {
1716
+ fs.mkdirSync(path.dirname(pointerPath), { recursive: true });
1717
+ writeFileAtomic(pointerPath, path.basename(threadPath));
1718
+ });
1719
+ }
1580
1720
  }
1581
- const thread = {
1582
- thread_id: threadId,
1583
- version: 1,
1584
- type: "auto-checkpoint",
1585
- created_at: now.toISOString(),
1586
- updated_at: now.toISOString(),
1587
- workspace_root: liveRoot,
1588
- cwd: process.cwd(),
1589
- git,
1590
- conversation_summary: input.summary,
1591
- files_touched: input.files,
1592
- next_steps: input.nextSteps,
1593
- learnings: input.learnings,
1594
- insights: input.insights,
1595
- decisions: input.decisions,
1596
- worker: input.worker,
1597
- session_id: input.sessionId ?? null,
1598
- metadata: {
1599
- title: titleFor(input.summary),
1600
- tags: ["auto-checkpoint", ...input.tags],
1601
- trigger: input.trigger,
1602
- },
1603
- };
1604
- writeHqState(path.dirname(threadPath), "create the checkpoint thread directory", () => fs.mkdirSync(path.dirname(threadPath), { recursive: true }));
1605
- writeHqState(threadPath, "write the checkpoint thread file", () => fs.writeFileSync(threadPath, `${JSON.stringify(thread, null, 2)}\n`));
1606
1721
  writeStamps(liveRoot, input.sessionId);
1607
1722
  printResult(`checkpoint: ${relativeThreadPath}`);
1608
1723
  // finally: the thread is already written at this point, so the agent must
@@ -0,0 +1,8 @@
1
+ import type { Command } from 'commander';
2
+ import { type FleetPlanOptions } from '../lib/hook-engine/fleet-registration.js';
3
+ export declare function registerCoreHookRegistrationPlan(core: Command, runtime?: {
4
+ readInput?: () => string;
5
+ writeOutput?: (value: string) => void;
6
+ planOptions?: FleetPlanOptions;
7
+ }): void;
8
+ //# sourceMappingURL=core-hook-registration-plan.d.ts.map
@@ -0,0 +1,22 @@
1
+ import * as fs from 'node:fs';
2
+ import * as os from 'node:os';
3
+ import { fleetRegistrationPlan, isFleetHost } from '../lib/hook-engine/fleet-registration.js';
4
+ import { describeCoreCommand } from './core-command-catalog.js';
5
+ export function registerCoreHookRegistrationPlan(core, runtime = {}) {
6
+ const command = core.command('hook-registration-plan')
7
+ .description('Print the offline fleet hook registration plan without changing the installation')
8
+ .requiredOption('--host <host>', 'Registration host')
9
+ .option('--json', 'Print JSON')
10
+ .action((options, command) => {
11
+ const host = options.host;
12
+ if (!isFleetHost(host))
13
+ throw new Error('Only fleet-local and agents-v2 registration are supported');
14
+ const root = command.optsWithGlobals().hqRoot;
15
+ if (!root)
16
+ throw new Error('--hq-root is required');
17
+ const fallbacks = JSON.parse((runtime.readInput ?? (() => fs.readFileSync(0, 'utf8')))());
18
+ (runtime.writeOutput ?? console.log)(JSON.stringify(fleetRegistrationPlan(root, fallbacks, { ...(runtime.planOptions ?? { home: process.env.HOME ?? os.homedir() }), host })));
19
+ });
20
+ describeCoreCommand(command, { execution: 'native', root: 'live' });
21
+ }
22
+ //# sourceMappingURL=core-hook-registration-plan.js.map
@@ -29,6 +29,7 @@
29
29
  * `ScaffoldRoot`.
30
30
  */
31
31
  import { Option } from "commander";
32
+ import { registerCoreHookRegistrationPlan } from "./core-hook-registration-plan.js";
32
33
  import { registerCoreCheckpointCommand } from "./core-checkpoint.js";
33
34
  import { runHookEnginePath } from '../hook-engine-path.js';
34
35
  import { registerCoreDelegateCommand } from "./core-delegate.js";
@@ -442,7 +443,15 @@ export function registerCoreCommands(program) {
442
443
  .addOption(new Option("--hq-root <path>", "HQ installation to operate on (live-root commands)").hideHelp());
443
444
  // This group primarily hosts manifest-driven bundled assets, but it also
444
445
  // hosts native TypeScript plumbing when a scaffold contract needs it.
446
+ const machineCheckOwnerCommand = core.command("machine-check-owner")
447
+ .description("Report the offline owner of the twelve scheduled machine checks")
448
+ .action(async () => {
449
+ const { machineCheckOwner } = await import("../lib/daemon/machine-check-owner.js");
450
+ process.stdout.write(`${JSON.stringify(machineCheckOwner())}\n`);
451
+ });
452
+ describeCoreCommand(machineCheckOwnerCommand, { execution: "native", root: "cwd" });
445
453
  registerCoreCheckpointCommand(core);
454
+ registerCoreHookRegistrationPlan(core);
446
455
  const hookEnginePath = core.command('hook-engine-path')
447
456
  .description('Print the offline, version-pinned native hook engine path')
448
457
  .option('--repair', 'Repair the pinned copy after closing running hook processes')
@@ -1703,9 +1703,28 @@ export function registerDaemonCommand(program, over = {}) {
1703
1703
  }));
1704
1704
  sync
1705
1705
  .command("status")
1706
- .description("Show sync ownership, heartbeat, last pass and log path")
1706
+ .description("Show sync ownership, heartbeat, last pass and log path (--local: the local sync journal summary)")
1707
1707
  .option("--json", "Print machine-readable JSON")
1708
- .action(wrap((d, opts) => runDaemonSyncStatus(d, opts)));
1708
+ .option("--local", "Show the local sync journal summary (what `hq sync status` prints) instead of the daemon's state")
1709
+ .option("--hq-root <path>", "With --local: local HQ tree root")
1710
+ .option("--company <slug>", "With --local: show only this company's journal (company slug)")
1711
+ .option("--all", "With --local: list every local-only file instead of the first 20 per company")
1712
+ .action(async (opts) => {
1713
+ if (opts.local) {
1714
+ // Same function, output and exit status as `hq sync status`.
1715
+ const { runSyncJournalStatus } = await import("./cloud.js");
1716
+ runSyncJournalStatus({ hqRoot: opts.hqRoot, company: opts.company, all: opts.all, json: opts.json });
1717
+ return;
1718
+ }
1719
+ await wrap((d, o) => {
1720
+ const localOnly = ["hqRoot", "company", "all"].find((key) => o[key] !== undefined);
1721
+ if (localOnly) {
1722
+ const flag = { hqRoot: "--hq-root", company: "--company", all: "--all" }[localOnly];
1723
+ throw new DaemonCommandError(`${flag} needs --local (it selects the local sync journal summary).`);
1724
+ }
1725
+ return runDaemonSyncStatus(d, { json: o.json });
1726
+ })(opts);
1727
+ });
1709
1728
  sync
1710
1729
  .command("now")
1711
1730
  .description("Start a fresh sync pass immediately")
@@ -134,7 +134,11 @@ export async function runDoctor(options = {}) {
134
134
  liveRuntimes: options.liveRuntimes === true,
135
135
  company: options.company,
136
136
  integrations: options.integrations !== false,
137
+ verbose: options.verbose === true,
138
+ runMachineChecks: requested?.includes("machine-checks") === true,
137
139
  };
140
+ if (context.runMachineChecks)
141
+ writeErr("hq doctor: machine checks run repair actions on this machine.\n");
138
142
  const families = await registry.run(context);
139
143
  if (!requested)
140
144
  await addHostCoreFamily(families, registry, context);
@@ -297,6 +297,44 @@ export async function waitForApprovalTerminal(token, companyUid, queueId, option
297
297
  }
298
298
  return null;
299
299
  }
300
+ /**
301
+ * True when the gateway says the call ran but its result was not kept. An
302
+ * explicit `resultAvailable` is authoritative (true can pair with a null
303
+ * result: a call may legitimately return null). Only gateways that omit it
304
+ * fall back to `callAlreadyRan` with no result.
305
+ */
306
+ function resultNotKept(r) {
307
+ if (r.resultAvailable !== undefined)
308
+ return r.resultAvailable === false;
309
+ return r.callAlreadyRan === true && (r.result === null || r.result === undefined);
310
+ }
311
+ /** Detail suffix such as " (reason: x, 12 bytes)"; empty when the gateway sent neither. */
312
+ function resultOmittedDetail(r) {
313
+ const parts = [];
314
+ if (typeof r.resultOmittedReason === "string" && r.resultOmittedReason) {
315
+ parts.push(`reason: ${terminalSafeText(r.resultOmittedReason)}`);
316
+ }
317
+ if (typeof r.resultBytes === "number")
318
+ parts.push(`${r.resultBytes} bytes`);
319
+ return parts.length ? ` (${parts.join(", ")})` : "";
320
+ }
321
+ /** Plain-text notice for a finished call whose result was not kept. */
322
+ function resultNotKeptNotice(r) {
323
+ const message = typeof r.message === "string" && r.message.trim()
324
+ ? terminalSafeText(r.message)
325
+ : "The call ran and will not run again, but its result was not kept.";
326
+ return `${message}${resultOmittedDetail(r)}`;
327
+ }
328
+ /**
329
+ * Server note printed after a result that is present: the live-result shape
330
+ * (the row did not keep it, so this response is the only copy). Undefined
331
+ * when the gateway sent no message.
332
+ */
333
+ function resultPresentNote(r) {
334
+ if (typeof r.message !== "string" || !r.message.trim())
335
+ return undefined;
336
+ return `${terminalSafeText(r.message)}${resultOmittedDetail(r)}`;
337
+ }
300
338
  /**
301
339
  * Read the stored result of an approved call that already ran. The confirm
302
340
  * route answers an approve for a `resumed` row from the queue row
@@ -316,7 +354,19 @@ async function fetchStoredApprovalResult(token, companyUid, connectionId, queueI
316
354
  const body = (await res.json().catch(() => ({})));
317
355
  if (body.status !== "resumed" || body.alreadyResumed !== true)
318
356
  return undefined;
319
- return { result: body.result };
357
+ const stored = { result: body.result };
358
+ // Newer gateways say why a finished call has no result to show.
359
+ if (body.callAlreadyRan !== undefined)
360
+ stored.callAlreadyRan = body.callAlreadyRan;
361
+ if (body.resultAvailable !== undefined)
362
+ stored.resultAvailable = body.resultAvailable;
363
+ if (body.resultOmittedReason !== undefined)
364
+ stored.resultOmittedReason = body.resultOmittedReason;
365
+ if (body.resultBytes !== undefined)
366
+ stored.resultBytes = body.resultBytes;
367
+ if (body.message !== undefined)
368
+ stored.message = body.message;
369
+ return stored;
320
370
  }
321
371
  catch {
322
372
  return undefined;
@@ -644,7 +694,17 @@ export function registerIntegrationsCommand(program) {
644
694
  ? await fetchStoredApprovalResult(token, companyUid, connection.id, queueId)
645
695
  : undefined;
646
696
  if (opts.json) {
647
- printJson(stored && stored.result !== undefined ? { ...terminal, result: stored.result } : terminal);
697
+ printJson(stored
698
+ ? {
699
+ ...terminal,
700
+ ...(stored.result !== undefined ? { result: stored.result } : {}),
701
+ ...(stored.callAlreadyRan !== undefined ? { callAlreadyRan: stored.callAlreadyRan } : {}),
702
+ ...(stored.resultAvailable !== undefined ? { resultAvailable: stored.resultAvailable } : {}),
703
+ ...(stored.resultOmittedReason !== undefined ? { resultOmittedReason: stored.resultOmittedReason } : {}),
704
+ ...(stored.resultBytes !== undefined ? { resultBytes: stored.resultBytes } : {}),
705
+ ...(stored.message !== undefined ? { message: stored.message } : {}),
706
+ }
707
+ : terminal);
648
708
  }
649
709
  else if (approvalOutcomeFailed(terminal)) {
650
710
  const unknown = terminal.status === "write_unknown" || terminal.outcome === "unknown";
@@ -658,6 +718,16 @@ export function registerIntegrationsCommand(program) {
658
718
  console.log(chalk.green("Approved — the call completed."));
659
719
  if (stored && stored.result !== undefined && stored.result !== null) {
660
720
  printJson(unwrapGatewayResult(stored.result));
721
+ const note = resultPresentNote(stored);
722
+ if (note)
723
+ console.log(chalk.yellow(note));
724
+ }
725
+ else if (stored && resultNotKept(stored)) {
726
+ console.log(chalk.yellow(resultNotKeptNotice(stored)));
727
+ }
728
+ else if (stored && stored.resultAvailable === true) {
729
+ // The call legitimately returned null; same as the sync path.
730
+ printJson(stored.result ?? null);
661
731
  }
662
732
  else if (ran) {
663
733
  console.log(chalk.yellow(`The call's result could not be read back. Run \`hq integrations approve ${queueId} --provider ${bareProvider(connection.provider)}${opts.company ? ` --company ${opts.company}` : ""}\` again to fetch it; the call will not run twice.`));
@@ -705,8 +775,19 @@ export function registerIntegrationsCommand(program) {
705
775
  else {
706
776
  console.log(chalk.yellow(`Approval ended with status ${body.status ?? "unknown"}.`));
707
777
  }
708
- if (result !== undefined)
778
+ if (result !== undefined && result !== null) {
709
779
  printJson(result);
780
+ const note = resultPresentNote(body);
781
+ if (note)
782
+ console.log(chalk.yellow(note));
783
+ }
784
+ else if (resultNotKept(body)) {
785
+ console.log(chalk.yellow(resultNotKeptNotice(body)));
786
+ }
787
+ else if (result === null) {
788
+ // Older gateways, or a call that legitimately returned null.
789
+ printJson(result);
790
+ }
710
791
  });
711
792
  }
712
793
  registerConnectCommands(integrations);
@@ -309,6 +309,8 @@ export interface Ctx {
309
309
  /** Claude access-token expiry check for account status. Absent in tests that fake the probe. */
310
310
  readClaudeCredential?: ClaudeCredentialReader;
311
311
  resolveMachineIdentity: () => MachineIdentity;
312
+ /** This machine's EC2 instance id from a local file, or null. No network call. */
313
+ readInstanceIdFromDisk: () => string | null;
312
314
  runCompaction?: RunCompactionFn;
313
315
  locateTranscript?: (home: string, sessionId: string) => string | null;
314
316
  monitorEvidence: MonitorEvidenceReader;
@@ -1,5 +1,7 @@
1
1
  import { accountStatus, coveredLaneIds, expiredLaneIds, loadLanesConfig, MAX_WATCHED_LANES, MONITOR_ENGINES, MONITOR_MAX_TIMEOUT_MS, MONITOR_UNCOVERED_EXIT_CODE, monitorReminderText, runLaneWatch, } from "../lib/lanes/index.js";
2
+ import { resolveAdmissionHost } from "../lib/lanes/admission-host.js";
2
3
  import { LEAD_LANE_KEEP_ALIVE_FLAG } from "../lib/lanes/keep-alive.js";
4
+ import { localHostIdsReferToSameMachine } from "../lib/lanes/local-host-identity.js";
3
5
  import { resolveLaneCompany } from "../lib/lanes/lane-company.js";
4
6
  import { readLanesRegistryFlag } from "../lib/lanes/registry-flag.js";
5
7
  import { isLanesError, LanesError } from "../lib/lanes/errors.js";
@@ -44,6 +46,7 @@ export function createLaneWatchHandlers(deps) {
44
46
  async function runWatch(ctx, laneIds, opts) {
45
47
  const rawInterval = opts.intervalMs === undefined ? undefined : Number(opts.intervalMs);
46
48
  const hqRoot = ctx.hqRoot();
49
+ let localMatch;
47
50
  await runLaneWatch(hqRoot, laneIds, {
48
51
  intervalMs: rawInterval,
49
52
  sleep: ctx.sleep,
@@ -57,8 +60,32 @@ export function createLaneWatchHandlers(deps) {
57
60
  const config = loadLanesConfig(hqRoot);
58
61
  const currentHost = laneHostFromCtx(ctx);
59
62
  const currentHostname = ctx.hostname().trim();
63
+ // A local lane is on this machine under any id admission accepts for it:
64
+ // the stable id, the hostname, or an earlier hostname in lane-host.json.
65
+ // The identity file is read once per watch, not once per poll. If it
66
+ // cannot be read, the watch matches by hostname as it did before.
67
+ if (localMatch === undefined) {
68
+ try {
69
+ const admissionHost = resolveAdmissionHost({
70
+ hostname: ctx.hostname,
71
+ homedir: ctx.homedir,
72
+ readOutpostIdentity: () => ({ kind: "not_outpost" }),
73
+ });
74
+ localMatch = {
75
+ hostname: admissionHost.hostname,
76
+ ...(admissionHost.machineId !== undefined ? { machineId: admissionHost.machineId } : {}),
77
+ ...(admissionHost.aliases !== undefined ? { aliases: admissionHost.aliases } : {}),
78
+ };
79
+ }
80
+ catch (err) {
81
+ process.stderr.write(`lane watch: could not read the lane host identity, matching local lanes by hostname: ${err instanceof Error ? err.message : String(err)}\n`);
82
+ localMatch = { hostname: currentHostname };
83
+ }
84
+ }
85
+ const match = localMatch;
60
86
  const isCurrentHost = (host) => (host.kind === currentHost.kind && host.id === currentHost.id) ||
61
- (host.kind === "local" && host.id === currentHostname);
87
+ (host.kind === "local" && host.id === currentHostname) ||
88
+ (host.kind === "local" && localHostIdsReferToSameMachine(host.id, match));
62
89
  const remoteOutpostIds = [...new Set(lanes
63
90
  .filter((lane) => lane.host.kind === "outpost" && !isCurrentHost(lane.host))
64
91
  .map((lane) => lane.host.id))];
@@ -90,6 +90,8 @@ export interface LanesCommandDeps {
90
90
  */
91
91
  readClaudeCredential?: ClaudeCredentialReader;
92
92
  resolveMachineIdentity?: () => MachineIdentity;
93
+ /** Injected in tests; the default reads the board asset tag on Linux and makes no network call. */
94
+ readInstanceIdFromDisk?: () => string | null;
93
95
  stageOutpostPayload?: (outpostId: string, bytes: Uint8Array) => Promise<{
94
96
  getUrl: string;
95
97
  }>;