@indigoai-us/hq-cli 5.345.223 → 5.345.225

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 (96) hide show
  1. package/CHANGELOG.md +66 -0
  2. package/assets/bot-workers/setup/context/quick-reference.md +2 -2
  3. package/assets/mesh-daemon/README.md +11 -12
  4. package/dist/command-catalog.generated.d.ts +78 -4
  5. package/dist/command-catalog.generated.js +94 -4
  6. package/dist/commands/cloud-provision.d.ts +4 -1
  7. package/dist/commands/cloud-provision.js +7 -3
  8. package/dist/commands/cloud-retire.js +1 -1
  9. package/dist/commands/core-delegate-w1b.js +3 -1
  10. package/dist/commands/core-delegate.d.ts +5 -0
  11. package/dist/commands/core-dm-bind-native.d.ts +5 -1
  12. package/dist/commands/core-dm-bind-native.js +4 -0
  13. package/dist/commands/core-job-notify-native.d.ts +5 -1
  14. package/dist/commands/core-job-notify-native.js +8 -2
  15. package/dist/commands/core-jobs-native.d.ts +27 -1
  16. package/dist/commands/core-jobs-native.js +49 -28
  17. package/dist/commands/core-pipeline-conductor-native.js +7 -7
  18. package/dist/commands/core-pipeline-driver-native.js +5 -5
  19. package/dist/commands/core-refresh-vault-access-native.d.ts +5 -0
  20. package/dist/commands/core-refresh-vault-access-native.js +3 -1
  21. package/dist/commands/core-work-mesh-bind-trusted-native.js +1 -1
  22. package/dist/commands/daemon.d.ts +2 -0
  23. package/dist/commands/daemon.js +67 -1
  24. package/dist/commands/lanes-hold.d.ts +2 -27
  25. package/dist/commands/lanes-hold.js +3 -75
  26. package/dist/commands/lanes-loop.js +1 -1
  27. package/dist/commands/lanes-session-start.js +2 -2
  28. package/dist/commands/mesh.d.ts +12 -0
  29. package/dist/commands/mesh.js +13 -4
  30. package/dist/commands/monitor.js +1 -1
  31. package/dist/commands/packs.js +1 -1
  32. package/dist/commands/whoami.d.ts +10 -17
  33. package/dist/commands/whoami.js +7 -79
  34. package/dist/data/command-states.json +13 -0
  35. package/dist/index.js +1 -1
  36. package/dist/lib/daemon/catalog.d.ts +8 -5
  37. package/dist/lib/daemon/catalog.js +13 -7
  38. package/dist/lib/daemon/config.d.ts +5 -0
  39. package/dist/lib/daemon/config.js +6 -0
  40. package/dist/lib/daemon/lanes-monitor-state.d.ts +55 -0
  41. package/dist/lib/daemon/lanes-monitor-state.js +129 -0
  42. package/dist/lib/daemon/lanes-reconcile-loader.d.ts +7 -0
  43. package/dist/lib/daemon/lanes-reconcile-loader.js +13 -0
  44. package/dist/lib/daemon/merge-sections.d.ts +165 -0
  45. package/dist/lib/daemon/merge-sections.js +556 -0
  46. package/dist/lib/daemon/ops/policy.d.ts +1 -1
  47. package/dist/lib/daemon/ops/policy.js +1 -1
  48. package/dist/lib/daemon/protocol.d.ts +1 -1
  49. package/dist/lib/daemon/protocol.js +0 -6
  50. package/dist/lib/daemon/run.js +73 -1
  51. package/dist/lib/daemon/selfcheck.js +2 -2
  52. package/dist/lib/daemon/server.d.ts +2 -4
  53. package/dist/lib/daemon/server.js +5 -48
  54. package/dist/lib/daemon/state-file.d.ts +74 -4
  55. package/dist/lib/daemon/state-file.js +159 -19
  56. package/dist/lib/daemon/supervisor.d.ts +1 -1
  57. package/dist/lib/daemon/updater.d.ts +2 -6
  58. package/dist/lib/daemon/updater.js +4 -11
  59. package/dist/lib/daemon/whoami-cache.d.ts +96 -0
  60. package/dist/lib/daemon/whoami-cache.js +244 -0
  61. package/dist/lib/hook-engine/coverage.d.ts +2 -0
  62. package/dist/lib/hook-engine/coverage.js +71 -0
  63. package/dist/lib/hook-engine/native-precompact-compatibility.json +449 -0
  64. package/dist/lib/hook-engine/reconcile.js +14 -8
  65. package/dist/lib/install/hook-target.d.ts +13 -3
  66. package/dist/lib/install/hook-target.js +14 -11
  67. package/dist/lib/lanes/envelope-repair-dispatch.js +1 -1
  68. package/dist/lib/lanes/monitor.d.ts +2 -0
  69. package/dist/lib/lanes/monitor.js +2 -1
  70. package/dist/lib/lanes/registry-flag.d.ts +6 -0
  71. package/dist/lib/lanes/registry-flag.js +3 -2
  72. package/dist/lib/lanes/repo-merge-hold.d.ts +39 -0
  73. package/dist/lib/lanes/repo-merge-hold.js +90 -0
  74. package/dist/lib/lanes/watcher-main.js +3 -3
  75. package/dist/lib/mesh/live/daemon/doctor.js +1 -1
  76. package/dist/lib/mesh/live/daemon/install.js +2 -2
  77. package/dist/lib/windows/install-followup.js +1 -1
  78. package/dist/utils/client-health-contract.d.ts +1 -0
  79. package/dist/utils/client-health-contract.js +5 -0
  80. package/dist/utils/client-health.d.ts +2 -0
  81. package/dist/utils/client-health.js +40 -0
  82. package/dist/utils/cognito-session.d.ts +2 -14
  83. package/dist/utils/cognito-session.js +2 -40
  84. package/dist/utils/daemon-cli-version.d.ts +13 -0
  85. package/dist/utils/daemon-cli-version.js +47 -0
  86. package/dist/utils/duplicate-command-usage.js +1 -1
  87. package/dist/utils/machine-token-cache.d.ts +21 -0
  88. package/dist/utils/machine-token-cache.js +49 -0
  89. package/dist/utils/resident-package-preload.js +4 -0
  90. package/dist/utils/whoami-identity.d.ts +54 -0
  91. package/dist/utils/whoami-identity.js +108 -0
  92. package/package.json +7 -7
  93. package/dist/lib/daemon/ops/memory.d.ts +0 -18
  94. package/dist/lib/daemon/ops/memory.js +0 -65
  95. package/dist/lib/daemon/ops/mesh.d.ts +0 -38
  96. package/dist/lib/daemon/ops/mesh.js +0 -70
@@ -1,3 +1,5 @@
1
+ /** Native TypeScript ports for the Wave 4a scheduled-jobs scaffold tools. */
2
+ import { daemonWhoamiOutput } from "../lib/daemon/whoami-cache.js";
1
3
  import * as fs from "node:fs";
2
4
  import * as path from "node:path";
3
5
  import { spawnSync } from "node:child_process";
@@ -426,11 +428,11 @@ function isExecutable(file) {
426
428
  return false;
427
429
  }
428
430
  }
429
- function findExecutable(command, searchPath) {
431
+ function findExecutable(command, searchPath, delimiter = path.delimiter) {
430
432
  if (path.isAbsolute(command) || command.includes(path.sep)) {
431
433
  return isExecutable(command) ? command : undefined;
432
434
  }
433
- for (const directory of searchPath.split(path.delimiter)) {
435
+ for (const directory of searchPath.split(delimiter)) {
434
436
  if (!directory)
435
437
  continue;
436
438
  const candidate = path.join(directory, command);
@@ -490,12 +492,16 @@ function resolveBoxOwners(options) {
490
492
  add(process.env.HQ_JOB_OWNER_UID);
491
493
  add(process.env.OUTPOST_USER_ID);
492
494
  const searchPath = process.env.PATH ?? "";
493
- if (findExecutable("hq", searchPath)) {
495
+ const cachedWho = (options.daemonWhoami ?? daemonWhoamiOutput)(true);
496
+ if (cachedWho !== null || findExecutable("hq", searchPath)) {
494
497
  const run = options.commandRunner ?? commandResult;
495
- let result = run("hq", ["whoami", "--json"]);
496
- if (result.status !== 0)
497
- result = run("hq", ["whoami"]);
498
- const who = result.stdout;
498
+ let who = cachedWho;
499
+ if (who === null) {
500
+ let result = run("hq", ["whoami", "--json"]);
501
+ if (result.status !== 0)
502
+ result = run("hq", ["whoami"]);
503
+ who = result.stdout;
504
+ }
499
505
  if (who) {
500
506
  let parsed;
501
507
  try {
@@ -741,35 +747,51 @@ function cronToOnCalendar(fields) {
741
747
  time = `${hourValue}:${minuteValue}:00`;
742
748
  return dowValue ? `${dowValue} ${date} ${time}` : `${date} ${time}`;
743
749
  }
744
- function normalizeServicePath(value) {
750
+ const HOST_PATH_RULES = { delimiter: path.delimiter, isAbsolute: path.isAbsolute };
751
+ function normalizeServicePath(value, rules) {
745
752
  const entries = [];
746
- for (const entry of value.split(":")) {
747
- if (entry.startsWith("/") && !entries.includes(entry))
753
+ for (const entry of value.split(rules.delimiter)) {
754
+ if (rules.isAbsolute(entry) && !entries.includes(entry))
748
755
  entries.push(entry);
749
756
  }
750
- return entries.join(":");
757
+ return entries.join(rules.delimiter);
751
758
  }
752
- function servicePathValue() {
753
- let servicePath = normalizeServicePath(process.env.PATH || "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin");
754
- const hq = findExecutable("hq", servicePath);
755
- if (hq) {
756
- let binDirectory = "";
757
- try {
758
- binDirectory = fs.realpathSync(path.dirname(hq));
759
- }
760
- catch { /* `pwd -P` failed in the shell equivalent. */ }
761
- if (binDirectory && !servicePath.split(":").includes(binDirectory))
762
- servicePath = [binDirectory, servicePath].filter(Boolean).join(":");
759
+ const DEFAULT_SERVICE_DIRECTORIES = ["/usr/local/sbin", "/usr/local/bin", "/usr/sbin", "/usr/bin", "/sbin", "/bin"];
760
+ /**
761
+ * One `hq` lookup for the service PATH and the unit's ExecStart. ExecStart
762
+ * uses the PATH entry as found (`hq`), not its realpath: mise and Volta
763
+ * install `hq` as a symlink to one multi-call shim that dispatches on argv[0],
764
+ * so exec'ing the symlink target would run the shim as itself instead of as
765
+ * `hq`. `servicePath` is the absolute, de-duplicated entries of `pathValue`,
766
+ * with the real directory of that `hq` in front when it is not already listed.
767
+ */
768
+ export function resolveServicePath(pathValue, rules = HOST_PATH_RULES) {
769
+ const searchPath = normalizeServicePath(pathValue || DEFAULT_SERVICE_DIRECTORIES.join(rules.delimiter), rules);
770
+ const hq = findExecutable("hq", searchPath, rules.delimiter);
771
+ if (!hq)
772
+ return { servicePath: searchPath, hq };
773
+ let binDirectory = "";
774
+ try {
775
+ binDirectory = fs.realpathSync(path.dirname(hq));
763
776
  }
764
- return servicePath;
777
+ catch { /* `pwd -P` failed in the shell equivalent. */ }
778
+ if (binDirectory && !searchPath.split(rules.delimiter).includes(binDirectory)) {
779
+ return { servicePath: [binDirectory, searchPath].filter(Boolean).join(rules.delimiter), hq };
780
+ }
781
+ return { servicePath: searchPath, hq };
782
+ }
783
+ function serviceRunner(root, id, hq) {
784
+ const executable = hq ?? "/usr/bin/env hq";
785
+ return `${executable} core job run --hq-root ${root} --job-id ${id}`;
765
786
  }
766
787
  function systemdQuote(value) {
767
788
  return `"${value.replace(/%/g, "%%").replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t")}"`;
768
789
  }
769
790
  function serviceUnit(root, id) {
770
- const pathValue = systemdQuote(`PATH=${servicePathValue()}`);
771
- const runner = path.resolve(root, "core/scripts/hq-job-run.sh");
772
- return `# Generated by outpost-jobs-reconcile.sh — disposable derived state. Do not edit.\n[Unit]\nDescription=HQ Outpost scheduled job: ${id}\nDocumentation=file://${root}/core/knowledge/public/hq-core/outpost-jobs-spec.md\nAfter=network-online.target\nWants=network-online.target\n\n[Service]\nType=oneshot\nEnvironment=HQ_ROOT=${root}\nEnvironment=${pathValue}\nEnvironment=HQ_SYNC_UNATTENDED=1\nExecStart=${runner} --hq-root ${root} --job-id ${id}\nNice=10\n\n[Install]\nWantedBy=default.target\n`;
791
+ const { servicePath, hq } = resolveServicePath(process.env.PATH);
792
+ const pathValue = systemdQuote(`PATH=${servicePath}`);
793
+ const runner = serviceRunner(root, id, hq);
794
+ return `# Generated by outpost-jobs-reconcile.sh — disposable derived state. Do not edit.\n[Unit]\nDescription=HQ Outpost scheduled job: ${id}\nDocumentation=file://${root}/core/knowledge/public/hq-core/outpost-jobs-spec.md\nAfter=network-online.target\nWants=network-online.target\n\n[Service]\nType=oneshot\nEnvironment=HQ_ROOT=${root}\nEnvironment=${pathValue}\nEnvironment=HQ_SYNC_UNATTENDED=1\nExecStart=${runner}\nNice=10\n\n[Install]\nWantedBy=default.target\n`;
773
795
  }
774
796
  function timerUnit(id, onCalendar, randomize, root) {
775
797
  return `# Generated by outpost-jobs-reconcile.sh — disposable derived state. Do not edit.\n[Unit]\nDescription=HQ Outpost scheduled job timer: ${id}\nDocumentation=file://${root}/core/knowledge/public/hq-core/outpost-jobs-spec.md\n\n[Timer]\nOnCalendar=${onCalendar}\nPersistent=true\nRandomizedDelaySec=${randomize}\nUnit=hq-job-${id}.service\n\n[Install]\nWantedBy=timers.target\n`;
@@ -882,8 +904,7 @@ export async function runReconcile(argv, rootArg, options = {}) {
882
904
  }
883
905
  if (!root)
884
906
  root = resolveLiveRoot();
885
- const servicePath = servicePathValue();
886
- const hq = findExecutable("hq", servicePath) || "hq";
907
+ const hq = findExecutable("hq", resolveServicePath(process.env.PATH).servicePath) || "hq";
887
908
  const home = process.env.HOME ?? "";
888
909
  const unitDir = process.env.HQ_JOB_UNIT_DIR || path.join(home, ".config", "systemd", "user");
889
910
  const cacheDir = process.env.HQ_JOB_STATUS_CACHE_DIR || path.join(home, ".hq", "jobs", "status-cache");
@@ -1682,7 +1682,7 @@ function do_route(p, sid) {
1682
1682
  if (lane) {
1683
1683
  let rows;
1684
1684
  try {
1685
- const listed = JSON.parse(run(E.PC_HQ, ["lanes", "list", "--json"], { timeout: 30000 }).stdout || "{}");
1685
+ const listed = JSON.parse(run(E.PC_HQ, ["runners", "list", "--json"], { timeout: 30000 }).stdout || "{}");
1686
1686
  rows = Array.isArray(listed) ? listed : get(listed, "lanes", null);
1687
1687
  }
1688
1688
  catch (e) {
@@ -1707,7 +1707,7 @@ function do_route(p, sid) {
1707
1707
  const laneBrief = pjoin(laneBriefDir, ph.worker + ".md");
1708
1708
  writeText(laneBrief, "# Pipeline loop lane: " + project + " / " + ph.worker + "\n\n" +
1709
1709
  "Pipeline phases arrive as queued envelopes. Follow each envelope; this standing brief has no task of its own.\n");
1710
- const createArgs = ["lanes", "create", "--loop", "--company", company, "--project", project,
1710
+ const createArgs = ["runners", "create", "--loop", "--company", company, "--project", project,
1711
1711
  "--story", sid, "--worker", ph.worker, "--brief-file", abspath(laneBrief), "--senior", "session:" + session, "--json"];
1712
1712
  const table = get(or(jload(sp("run.json"), {}), {}), "table", "");
1713
1713
  if (T(table) && exists(table)) {
@@ -1752,7 +1752,7 @@ function do_route(p, sid) {
1752
1752
  envData.id = baseEnvelopeId + (suffixes[ph.phase] ? ".r" + suffixes[ph.phase] : "");
1753
1753
  envData.result_path = abspath(sp("handoffs", sid + "-" + ph.phase + ".json"));
1754
1754
  jsave(ep, envData);
1755
- let r = run(E.PC_HQ, ["lanes", "enqueue", lane, "--envelope", abspath(ep)], { timeout: 30000 });
1755
+ let r = run(E.PC_HQ, ["runners", "enqueue", lane, "--envelope", abspath(ep)], { timeout: 30000 });
1756
1756
  let ans;
1757
1757
  try {
1758
1758
  ans = JSON.parse(r.stdout);
@@ -1770,7 +1770,7 @@ function do_route(p, sid) {
1770
1770
  envData.id = baseEnvelopeId + ".r" + n;
1771
1771
  jsave(sfile(sid), st);
1772
1772
  jsave(ep, envData);
1773
- r = run(E.PC_HQ, ["lanes", "enqueue", lane, "--envelope", abspath(ep)], { timeout: 30000 });
1773
+ r = run(E.PC_HQ, ["runners", "enqueue", lane, "--envelope", abspath(ep)], { timeout: 30000 });
1774
1774
  try {
1775
1775
  ans = JSON.parse(r.stdout);
1776
1776
  }
@@ -2621,7 +2621,7 @@ function lane_runs() {
2621
2621
  function withdraw(lane, sid, ph) {
2622
2622
  if (!T(lane))
2623
2623
  return false;
2624
- const r = run(E.PC_HQ, ["lanes", "interrupt", lane, "--story", sid, "--phase", ph, "--json"], { timeout: 30000 });
2624
+ const r = run(E.PC_HQ, ["runners", "interrupt", lane, "--story", sid, "--phase", ph, "--json"], { timeout: 30000 });
2625
2625
  let ans;
2626
2626
  try {
2627
2627
  ans = JSON.parse(r.stdout);
@@ -2701,10 +2701,10 @@ function do_stop() {
2701
2701
  do_interrupt("stop: " + (note() || "parent stop command"));
2702
2702
  const lanes = Array.from(lane_runs().values());
2703
2703
  for (const lane of lanes)
2704
- run(E.PC_HQ, ["lanes", "stop", lane], { timeout: 30000 });
2704
+ run(E.PC_HQ, ["runners", "stop", lane], { timeout: 30000 });
2705
2705
  let listed = null;
2706
2706
  try {
2707
- const parsed = JSON.parse(run(E.PC_HQ, ["lanes", "list", "--json"], { timeout: 30000 }).stdout || "{}");
2707
+ const parsed = JSON.parse(run(E.PC_HQ, ["runners", "list", "--json"], { timeout: 30000 }).stdout || "{}");
2708
2708
  listed = Array.isArray(parsed) ? parsed : get(parsed, "lanes", null);
2709
2709
  }
2710
2710
  catch (e) {
@@ -54,7 +54,7 @@ export function scanDriverState(stateDir, maxFails, hqBin, run = spawnSync, queu
54
54
  lanes = new Map();
55
55
  try {
56
56
  const owned = load(path.join(S, 'lanes.json')) || {};
57
- const r = run(HQ, ['lanes', 'list', '--json'], { encoding: 'utf8', timeout: 30000 });
57
+ const r = run(HQ, ['runners', 'list', '--json'], { encoding: 'utf8', timeout: 30000 });
58
58
  if (!r.error) {
59
59
  const text = String(r.stdout || ''), starts = [text.indexOf('['), text.indexOf('{')].filter((n) => n >= 0);
60
60
  const parsed = JSON.parse(starts.length ? text.slice(Math.min(...starts)) : text);
@@ -314,7 +314,7 @@ export function checkDriverStall(stateDir, stallWindow, hqBin, run = spawnSync)
314
314
  let rows = [];
315
315
  try {
316
316
  const owned = load(path.join(S, 'lanes.json')) || {};
317
- const r = run(HQ, ['lanes', 'list', '--json'], { encoding: 'utf8', timeout: 30000 });
317
+ const r = run(HQ, ['runners', 'list', '--json'], { encoding: 'utf8', timeout: 30000 });
318
318
  const text = String(r.stdout || ''), starts = [text.indexOf('['), text.indexOf('{')].filter((n) => n >= 0);
319
319
  const parsed = JSON.parse(starts.length ? text.slice(Math.min(...starts)) : text);
320
320
  const listed = Array.isArray(parsed) ? parsed : (isObj(parsed) && Array.isArray(parsed.lanes) ? parsed.lanes : []);
@@ -629,7 +629,7 @@ function driverTimestamp() {
629
629
  return new Date().toISOString().replace(/\.\d{3}Z$/, "Z");
630
630
  }
631
631
  function laneRowsFromHq(hq) {
632
- const result = driverRun(hq, ["lanes", "list", "--json"]);
632
+ const result = driverRun(hq, ["runners", "list", "--json"]);
633
633
  if (result.code !== 0)
634
634
  throw new Error(`hq lanes list --json exited ${result.code}: ${result.stderr.trim()}`);
635
635
  return extractLaneRows(result.stdout);
@@ -649,7 +649,7 @@ export async function stopDriverLanes(state, hq, logFile, options = {}) {
649
649
  const owned = readJson(laneFile) || {};
650
650
  const laneIds = Object.values(owned).filter((lane) => typeof lane === "string" && lane.length > 0);
651
651
  for (const lane of laneIds)
652
- (options.stop ?? ((id) => { driverRun(hq, ["lanes", "stop", id]); }))(lane);
652
+ (options.stop ?? ((id) => { driverRun(hq, ["runners", "stop", id]); }))(lane);
653
653
  const deadline = Date.now() + (options.timeoutMs ?? 60_000);
654
654
  while (Date.now() < deadline) {
655
655
  let rows;
@@ -861,7 +861,7 @@ export async function runPipelineDriverNative(args, hqRoot = "") {
861
861
  const worker = c;
862
862
  const { lane, company } = stalledLaneContext(state, worker);
863
863
  const listed = lane && company
864
- ? driverRun(hq, ["lanes", "questions", "list", "--company", company, "--json"])
864
+ ? driverRun(hq, ["runners", "questions", "list", "--company", company, "--json"])
865
865
  : { code: 1, stdout: "", stderr: "" };
866
866
  let question = "";
867
867
  if (listed.code === 0) {
@@ -10,6 +10,11 @@ export type HqResult = {
10
10
  timedOut?: boolean;
11
11
  };
12
12
  export type RefreshVaultAccessDependencies = {
13
+ /**
14
+ * The daemon's cached `hq whoami` output (json or plain), or null to run
15
+ * `hq whoami` (hq-core-rust US-036). Default: src/lib/daemon/whoami-cache.ts.
16
+ */
17
+ daemonWhoami?: (json: boolean) => string | null;
13
18
  cwd: string;
14
19
  env: NodeJS.ProcessEnv;
15
20
  now: () => Date;
@@ -1,4 +1,5 @@
1
1
  /** Native local manifest refresh for core/scripts/refresh-vault-access.sh. */
2
+ import { daemonWhoamiOutput } from "../lib/daemon/whoami-cache.js";
2
3
  import { spawnSync } from "node:child_process";
3
4
  import { randomBytes } from "node:crypto";
4
5
  import * as fs from "node:fs";
@@ -305,7 +306,8 @@ function resolveEmail(deps, runHq) {
305
306
  const override = deps.env.HQ_VAULT_ACCESS_EMAIL ?? "";
306
307
  if (override)
307
308
  return { email: override, stderr: "", signedOut: false };
308
- const result = runHq(["whoami"], deps.cwd);
309
+ const cached = (deps.daemonWhoami ?? ((asJson) => daemonWhoamiOutput(asJson, deps.env)))(false);
310
+ const result = cached !== null ? { stdout: cached } : runHq(["whoami"], deps.cwd);
309
311
  const email = getEmail(result.stdout);
310
312
  // An API key reaches the vault without a person session, so only a
311
313
  // key-less caller whose whoami reports no session is treated as signed out.
@@ -288,7 +288,7 @@ export function runWorkMeshBindTrusted(args, deps) {
288
288
  if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
289
289
  const daemon = parsed;
290
290
  if (daemon.ok === true && daemon.running === false && typeof daemon.message === "string" && daemon.message.includes("installed (")) {
291
- stderr += "Work Mesh daemon is installed but not loaded; start it with: hq mesh daemon install\n";
291
+ stderr += "Work Mesh daemon is installed but not loaded; start it with: hq daemon install\n";
292
292
  }
293
293
  }
294
294
  }
@@ -8,7 +8,9 @@
8
8
  * hq daemon status [--json] includes whether the service manager runs it
9
9
  * hq daemon logs [unit] [--follow] [--lines N]
10
10
  * hq daemon restart [unit] | trigger <unit>
11
+ * hq daemon doctor Work Mesh health (spool, held, dead-letter, MQTT)
11
12
  * hq daemon enable|disable <service...> per-machine overrides
13
+ * hq daemon pause|resume sync-core stop the new sync engine until resumed
12
14
  * hq daemon migrate list the older units it would take over (read-only)
13
15
  * hq daemon uninstall [--purge]
14
16
  *
@@ -8,7 +8,9 @@
8
8
  * hq daemon status [--json] includes whether the service manager runs it
9
9
  * hq daemon logs [unit] [--follow] [--lines N]
10
10
  * hq daemon restart [unit] | trigger <unit>
11
+ * hq daemon doctor Work Mesh health (spool, held, dead-letter, MQTT)
11
12
  * hq daemon enable|disable <service...> per-machine overrides
13
+ * hq daemon pause|resume sync-core stop the new sync engine until resumed
12
14
  * hq daemon migrate list the older units it would take over (read-only)
13
15
  * hq daemon uninstall [--purge]
14
16
  *
@@ -552,6 +554,7 @@ async function runStatus(d, opts) {
552
554
  warnings: statusWarnings(service, paths),
553
555
  machineType: state?.machineType ?? config.machineType ?? null,
554
556
  units: state?.units ?? [],
557
+ syncCorePause: config.syncCorePause ?? null,
555
558
  }, null, 2));
556
559
  return;
557
560
  }
@@ -559,6 +562,9 @@ async function runStatus(d, opts) {
559
562
  ? `Service manager: running as the HQ desktop app's child (${service.detail}).`
560
563
  : `Service manager: ${describeSupervision(service)}.`;
561
564
  const warnings = statusWarnings(service, paths).map((w) => `Warning: ${w}`);
565
+ if (config.syncCorePause) {
566
+ d.out(`sync-core paused at ${config.syncCorePause.at} by ${config.syncCorePause.by}; resume with \`hq daemon resume sync-core\`.`);
567
+ }
562
568
  if (!pid || !state) {
563
569
  const { detected } = host;
564
570
  d.out(`hq daemon is not running. Machine type: ${detected.type} (${detected.detail}).`);
@@ -974,6 +980,40 @@ async function runToggle(d, action, services) {
974
980
  d.out(line);
975
981
  d.out("A running daemon picks this up within 15 seconds.");
976
982
  }
983
+ async function runSyncCorePause(d, paused, service, opts) {
984
+ if (service !== "sync-core") {
985
+ throw new DaemonCommandError(`hq daemon ${paused ? "pause" : "resume"} works on sync-core only. Use hq daemon enable/disable for ${service}.`);
986
+ }
987
+ const host = currentHost(d);
988
+ const config = readDaemonConfig(host.paths.configPath);
989
+ const before = config.syncCorePause;
990
+ // A second pause keeps the first time and requester.
991
+ const next = paused ? (before ?? { at: new Date().toISOString(), by: `local uid ${d.uid}` }) : undefined;
992
+ if (next !== before) {
993
+ const updated = { ...config };
994
+ if (next)
995
+ updated.syncCorePause = next;
996
+ else
997
+ delete updated.syncCorePause;
998
+ writeDaemonConfig(host.paths.configPath, updated);
999
+ }
1000
+ const daemonRunning = queueDaemonSyncControl(d, { action: "reconcile" });
1001
+ const disabled = config.disable.includes("sync-core");
1002
+ const result = { service: "sync-core", paused, syncCorePause: next ?? null, persisted: true, daemonRunning, disabled };
1003
+ if (opts.json) {
1004
+ d.out(JSON.stringify(result, null, 2));
1005
+ return;
1006
+ }
1007
+ d.out(paused
1008
+ ? `sync-core paused at ${next.at} by ${next.by}. It stays stopped, including across daemon restarts, until \`hq daemon resume sync-core\`.`
1009
+ : before
1010
+ ? "sync-core resumed."
1011
+ : "sync-core was not paused.");
1012
+ if (!daemonRunning)
1013
+ d.out("The daemon is not running; this applies when it starts.");
1014
+ if (!paused && disabled)
1015
+ d.out("sync-core is still disabled on this machine; `hq daemon enable sync-core` turns it back on.");
1016
+ }
977
1017
  async function runPinHqCloud(d, version, opts) {
978
1018
  if (opts.clear === Boolean(version)) {
979
1019
  throw new DaemonCommandError("Pass one exact semver version, or use --clear.");
@@ -1678,7 +1718,7 @@ export function registerDaemonCommand(program, over = {}) {
1678
1718
  }));
1679
1719
  daemon
1680
1720
  .command("call <op>")
1681
- .description("Send one request to hqd (policy.check, journal.append, memory.get, memory.put, mesh.presence, mcp.call, …) and print the result as JSON")
1721
+ .description("Send one request to hqd (policy.check, journal.append, mcp.call, …) and print the result as JSON")
1682
1722
  .option("--json <args>", "Request args as a JSON object", "{}")
1683
1723
  .option("--timeout <ms>", "Give up after this many milliseconds")
1684
1724
  .action(wrap(async (d, op, opts) => {
@@ -1706,6 +1746,14 @@ export function registerDaemonCommand(program, over = {}) {
1706
1746
  .description("Show the machine type and each service's state")
1707
1747
  .option("--json", "Print machine-readable JSON")
1708
1748
  .action(wrap((d, opts) => runStatus(d, opts)));
1749
+ daemon
1750
+ .command("doctor")
1751
+ .description("Report Work Mesh health: running, MQTT, spool, held, dead-letter, outbox and flush (replaces the separate mesh daemon doctor)")
1752
+ .option("--json", "Print machine-readable JSON")
1753
+ .action(async (opts) => {
1754
+ const { runMeshDaemonDoctor } = await import("./mesh.js");
1755
+ await runMeshDaemonDoctor(opts);
1756
+ });
1709
1757
  const sync = daemon
1710
1758
  .command("sync")
1711
1759
  .description("Inspect and control the daemon's company sync runner");
@@ -1823,6 +1871,16 @@ export function registerDaemonCommand(program, over = {}) {
1823
1871
  .command("disable <services...>")
1824
1872
  .description("Turn default services off for this machine")
1825
1873
  .action(wrap((d, services) => runToggle(d, "disable", services)));
1874
+ daemon
1875
+ .command("pause <service>")
1876
+ .description("Stop sync-core and keep it stopped (watchdog and daemon restarts included) until resumed")
1877
+ .option("--json", "Print machine-readable JSON")
1878
+ .action(wrap((d, service, opts) => runSyncCorePause(d, true, service, opts)));
1879
+ daemon
1880
+ .command("resume <service>")
1881
+ .description("Start a paused sync-core again")
1882
+ .option("--json", "Print machine-readable JSON")
1883
+ .action(wrap((d, service, opts) => runSyncCorePause(d, false, service, opts)));
1826
1884
  daemon
1827
1885
  .command("pin-hq-cloud [version]")
1828
1886
  .description("Pin hq-cloud to an exact version, or clear the pin")
@@ -1849,6 +1907,14 @@ export function registerDaemonCommand(program, over = {}) {
1849
1907
  const service = daemon
1850
1908
  .command("service", { hidden: true })
1851
1909
  .description("Entry points the daemon runs for services that have no command of their own");
1910
+ service
1911
+ .command("mesh")
1912
+ .description("Work Mesh Live: spool drain, MQTT presence and the live Board cache (the daemon's mesh service)")
1913
+ .option("--hq-root <path>", "HQ folder the service works against")
1914
+ .action(async (opts) => {
1915
+ const { runMeshDaemonService } = await import("./mesh.js");
1916
+ await runMeshDaemonService(opts);
1917
+ });
1852
1918
  service
1853
1919
  .command("self-update")
1854
1920
  .description("Update the hq CLI, Claude, Codex and Grok, then restart the daemon onto a new CLI")
@@ -1,31 +1,7 @@
1
1
  import type { Command } from "commander";
2
2
  import type { LaneCompanyRef } from "../lib/lanes/types.js";
3
- export declare const LANES_REPO_MERGE_HOLD_FLAG = "lanes.repo-merge-hold";
4
- export declare const LANES_REVIEW_BEFORE_MERGE_FLAG = "lanes.review-before-merge";
5
- export declare const REPO_MERGE_HOLDS_REL: string;
6
- declare const HOLD_SCHEMA_VERSION = "hq-lanes-repo-merge-hold.v1";
7
- interface HoldHistoryEntry {
8
- set_at: string;
9
- until: string;
10
- reason: string;
11
- set_by_lane: string | null;
12
- set_by_session: string | null;
13
- released_at?: string;
14
- released_reason?: string;
15
- }
16
- export interface RepoMergeHold {
17
- schema_version: typeof HOLD_SCHEMA_VERSION;
18
- repo: string;
19
- company: LaneCompanyRef;
20
- reason: string;
21
- set_at: string;
22
- until: string;
23
- set_by_lane: string | null;
24
- set_by_session: string | null;
25
- released_at?: string;
26
- released_reason?: string;
27
- history: HoldHistoryEntry[];
28
- }
3
+ import { LANES_REPO_MERGE_HOLD_FLAG, LANES_REVIEW_BEFORE_MERGE_FLAG, REPO_MERGE_HOLDS_REL, type RepoMergeHold } from "../lib/lanes/repo-merge-hold.js";
4
+ export { LANES_REPO_MERGE_HOLD_FLAG, LANES_REVIEW_BEFORE_MERGE_FLAG, REPO_MERGE_HOLDS_REL, type RepoMergeHold };
29
5
  export interface LaneRepoMergeHoldDeps {
30
6
  hqRoot: () => string;
31
7
  resolveCompany: (company?: string) => Promise<LaneCompanyRef>;
@@ -38,5 +14,4 @@ type WrapHandler = <Args extends unknown[]>(action: (...args: Args) => Promise<v
38
14
  /** Serialize the read-modify-write cycle so concurrent set/release calls cannot overwrite each other. */
39
15
  export declare function withRepoMergeHoldRecordLock<T>(recordPath: string, action: () => T | Promise<T>): Promise<T>;
40
16
  export declare function registerLaneRepoMergeHoldCommand(lanes: Command, deps: LaneRepoMergeHoldDeps, wrap: WrapHandler): void;
41
- export {};
42
17
  //# sourceMappingURL=lanes-hold.d.ts.map
@@ -9,20 +9,13 @@ import { readLanesFlagLocalOverride, readLanesRegistryFlag } from "../lib/lanes/
9
9
  import { sessionIdFromEnv } from "../lib/mesh/live/session-identity.js";
10
10
  import { readLaneReview } from "../lib/lanes/reviews.js";
11
11
  import { resolveLaneCompany } from "../lib/lanes/lane-company.js";
12
- export const LANES_REPO_MERGE_HOLD_FLAG = "lanes.repo-merge-hold";
13
- export const LANES_REVIEW_BEFORE_MERGE_FLAG = "lanes.review-before-merge";
14
- export const REPO_MERGE_HOLDS_REL = path.join("workspace", "lanes", "holds");
15
- const HOLD_SCHEMA_VERSION = "hq-lanes-repo-merge-hold.v1";
16
- const HISTORY_CAP = 50;
12
+ import { HOLD_HISTORY_CAP, HOLD_SCHEMA_VERSION, LANES_REPO_MERGE_HOLD_FLAG, LANES_REVIEW_BEFORE_MERGE_FLAG, REPO_MERGE_HOLDS_REL, holdFilePath, parseHold, } from "../lib/lanes/repo-merge-hold.js";
13
+ export { LANES_REPO_MERGE_HOLD_FLAG, LANES_REVIEW_BEFORE_MERGE_FLAG, REPO_MERGE_HOLDS_REL };
17
14
  const HOLD_LOCK_WAIT_MS = 5_000;
18
15
  const HOLD_LOCK_STALE_MS = 5 * 60_000;
19
16
  function fail(error, message, details = {}) {
20
17
  throw new LanesError(error, message, details);
21
18
  }
22
- function holdFilePath(hqRoot, repo) {
23
- const [owner, repository] = canonicalRepo(repo).split("/");
24
- return path.join(hqRoot, REPO_MERGE_HOLDS_REL, `${owner}__${repository}.json`);
25
- }
26
19
  function nonEmptyText(field, raw) {
27
20
  const value = raw.trim();
28
21
  if (!value)
@@ -66,71 +59,6 @@ function parseUntil(raw, now) {
66
59
  }
67
60
  return new Date(timestamp).toISOString();
68
61
  }
69
- function isObject(value) {
70
- return value !== null && typeof value === "object" && !Array.isArray(value);
71
- }
72
- function isCanonicalTimestamp(value) {
73
- if (typeof value !== "string")
74
- return false;
75
- const timestamp = Date.parse(value);
76
- return Number.isFinite(timestamp) && new Date(timestamp).toISOString() === value;
77
- }
78
- function parseHold(raw, file) {
79
- if (!isObject(raw))
80
- return fail("repo_hold_invalid", "Merge hold record must be an object", { path: file });
81
- const company = raw.company;
82
- const history = raw.history;
83
- if (raw.schema_version !== HOLD_SCHEMA_VERSION || typeof raw.repo !== "string" ||
84
- !isObject(company) || typeof company.slug !== "string" || !company.slug.trim() ||
85
- typeof company.uid !== "string" || !company.uid.trim() ||
86
- typeof raw.reason !== "string" || !raw.reason.trim() ||
87
- !isCanonicalTimestamp(raw.set_at) || !isCanonicalTimestamp(raw.until) ||
88
- !(raw.set_by_lane === null || typeof raw.set_by_lane === "string") ||
89
- !(raw.set_by_session === null || typeof raw.set_by_session === "string") ||
90
- !Array.isArray(history) || history.length > HISTORY_CAP ||
91
- (raw.released_at !== undefined && !isCanonicalTimestamp(raw.released_at)) ||
92
- (raw.released_reason !== undefined && typeof raw.released_reason !== "string")) {
93
- return fail("repo_hold_invalid", "Merge hold record has invalid fields", { path: file });
94
- }
95
- let repo;
96
- try {
97
- repo = canonicalRepo(raw.repo);
98
- }
99
- catch {
100
- return fail("repo_hold_invalid", "Merge hold record has an invalid repository", { path: file });
101
- }
102
- if (repo !== raw.repo)
103
- return fail("repo_hold_invalid", "Merge hold repository is not canonical", { path: file });
104
- if ((raw.released_at === undefined) !== (raw.released_reason === undefined)) {
105
- return fail("repo_hold_invalid", "Released merge hold must include both release fields", { path: file });
106
- }
107
- if (raw.released_at !== undefined && (!raw.released_reason || !raw.released_reason.trim())) {
108
- return fail("repo_hold_invalid", "Released merge hold is missing its reason", { path: file });
109
- }
110
- assertNoSecretText("hold.reason", raw.reason);
111
- if (typeof raw.released_reason === "string")
112
- assertNoSecretText("hold.released_reason", raw.released_reason);
113
- for (const entry of history) {
114
- if (!isObject(entry) || !isCanonicalTimestamp(entry.set_at) || !isCanonicalTimestamp(entry.until) ||
115
- typeof entry.reason !== "string" || !entry.reason.trim() ||
116
- !(entry.set_by_lane === null || typeof entry.set_by_lane === "string") ||
117
- !(entry.set_by_session === null || typeof entry.set_by_session === "string") ||
118
- (entry.released_at !== undefined && !isCanonicalTimestamp(entry.released_at)) ||
119
- (entry.released_reason !== undefined && typeof entry.released_reason !== "string")) {
120
- return fail("repo_hold_invalid", "Merge hold history has invalid entries", { path: file });
121
- }
122
- if ((entry.released_at === undefined) !== (entry.released_reason === undefined)) {
123
- return fail("repo_hold_invalid", "Merge hold history release fields are incomplete", { path: file });
124
- }
125
- if (entry.released_reason !== undefined && !entry.released_reason.trim()) {
126
- return fail("repo_hold_invalid", "Merge hold history release reason is empty", { path: file });
127
- }
128
- assertNoSecretText("hold.history.reason", entry.reason);
129
- if (typeof entry.released_reason === "string")
130
- assertNoSecretText("hold.history.released_reason", entry.released_reason);
131
- }
132
- return raw;
133
- }
134
62
  function readHold(hqRoot, repo) {
135
63
  const file = holdFilePath(hqRoot, repo);
136
64
  let contents;
@@ -474,7 +402,7 @@ export function registerLaneRepoMergeHoldCommand(lanes, deps, wrap) {
474
402
  until,
475
403
  set_by_lane: env.HQ_LANE_ID?.trim() || null,
476
404
  set_by_session: sessionIdFromEnv(env) ?? null,
477
- history: [...(previous?.history ?? []), ...(previous ? [historyEntry(previous)] : [])].slice(-HISTORY_CAP),
405
+ history: [...(previous?.history ?? []), ...(previous ? [historyEntry(previous)] : [])].slice(-HOLD_HISTORY_CAP),
478
406
  };
479
407
  writeHold(hqRoot, next);
480
408
  return next;
@@ -122,7 +122,7 @@ export function startLaneLoopControllerWithAdmissionLockHeld(ctx, laneId, initia
122
122
  const entry = process.argv[1];
123
123
  if (!entry)
124
124
  throw new LanesError("loop_controller_entry_missing", "Cannot resolve the hq CLI entry point for the loop controller", { lane_id: laneId });
125
- const args = [entry, "lanes", "_loop-worker", laneId];
125
+ const args = [entry, "runners", "_loop-worker", laneId];
126
126
  const env = { ...ctx.env, HQ_LANE_LOOP_CONTROLLER: "1", ...(initialAdmission ? { HQ_LANE_LOOP_INITIAL: "1" } : {}) };
127
127
  const child = ctx.spawnProcess
128
128
  ? ctx.spawnProcess(liveNodeBinary(), args, { cwd: ctx.hqRoot(), detached: true, windowsHide: true, stdio: ["ignore", 1, 2], env })
@@ -489,7 +489,7 @@ export function startSessionStartOrphanSweep(root, env = process.env, spawnDetac
489
489
  "const start=()=>{let lease;try{lease=JSON.parse(fs.readFileSync(lock,'utf8'))}catch{}if(lease?.owner_token!==token){if(Date.now()<Number(lease?.started_at||0)+1000)return setTimeout(start,10);process.exit(0)}",
490
490
  "try{fs.writeFileSync(lock,JSON.stringify({...lease,pid:process.pid}))}catch{}",
491
491
  "const tmp=report+'.tmp';let output;try{output=fs.createWriteStream(tmp,{flags:'wx',mode:0o600})}catch{cleanup();process.exit(0)}",
492
- "const child=cp.spawn(process.execPath,[cli,'lanes','_reap','--json','--legacy'],{stdio:['ignore','pipe','ignore'],env:{...process.env,HQ_ROOT:root,HQ_NO_UPDATE_CHECK:'1'}});",
492
+ "const child=cp.spawn(process.execPath,[cli,'runners','_reap','--json','--legacy'],{stdio:['ignore','pipe','ignore'],env:{...process.env,HQ_ROOT:root,HQ_NO_UPDATE_CHECK:'1'}});",
493
493
  "child.stdout.pipe(output);child.on('error',()=>{output.destroy();try{fs.rmSync(tmp,{force:true})}catch{}cleanup()});",
494
494
  "child.on('exit',(code)=>output.end(()=>{try{if(code===0)fs.renameSync(tmp,report);else fs.rmSync(tmp,{force:true})}catch{}cleanup()}));};start();",
495
495
  ].join("");
@@ -554,7 +554,7 @@ export function startSessionStartFlagRefresh(env, spawnDetached = spawn, now = D
554
554
  catch {
555
555
  return false;
556
556
  }
557
- const child = spawnDetached(process.execPath, [cli, "lanes", "session-start", "--refresh-flags"], {
557
+ const child = spawnDetached(process.execPath, [cli, "runners", "session-start", "--refresh-flags"], {
558
558
  detached: true,
559
559
  stdio: "ignore",
560
560
  env: { ...env, HQ_NO_UPDATE_CHECK: "1" },
@@ -64,6 +64,14 @@ export declare function runContextCorrect(opts: {
64
64
  export declare function registerMeshCommand(program: Command, deps?: {
65
65
  defaultCompanyPrompt?: DefaultCompanyPromptDeps;
66
66
  }): void;
67
+ /**
68
+ * The resident Work Mesh loop. `hq daemon` runs it as its `mesh` service
69
+ * (`hq daemon service mesh`); `hq mesh daemon run`, which older standalone
70
+ * units still start, is retiring and runs the same loop.
71
+ */
72
+ export declare function runMeshDaemonService(opts?: {
73
+ hqRoot?: string;
74
+ }): Promise<void>;
67
75
  export declare function runDaemonStatus(opts: {
68
76
  json?: boolean;
69
77
  }, deps?: {
@@ -73,5 +81,9 @@ export declare function runDaemonStatus(opts: {
73
81
  run?: RunCommand;
74
82
  uid?: number;
75
83
  }): Promise<void>;
84
+ /** Work Mesh health report: `hq daemon doctor` (and the retiring `hq mesh daemon doctor`). */
85
+ export declare function runMeshDaemonDoctor(opts: {
86
+ json?: boolean;
87
+ }): Promise<void>;
76
88
  export {};
77
89
  //# sourceMappingURL=mesh.d.ts.map