@indigoai-us/hq-cli 5.345.231 → 5.345.232

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 (91) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/README.md +3 -2
  3. package/assets/lanes-reconcile/hq-lanes-reconcile.service +1 -1
  4. package/assets/scaffold/core/scripts/pipeline-conductor.sh +14 -14
  5. package/assets/scaffold/core/scripts/pipeline-driver.sh +7 -7
  6. package/assets/scaffold/core/scripts/session-project.sh +19 -4
  7. package/dist/command-catalog.generated.d.ts +213 -177
  8. package/dist/command-catalog.generated.js +263 -212
  9. package/dist/command-registration-plan.d.ts +6 -24
  10. package/dist/command-registration-plan.js +4 -8
  11. package/dist/commands/auth.js +3 -2
  12. package/dist/commands/core-pipeline-conductor-command.js +1 -1
  13. package/dist/commands/core-pipeline-conductor-native.js +5 -5
  14. package/dist/commands/core-pipeline-driver-native.js +5 -5
  15. package/dist/commands/daemon.js +7 -36
  16. package/dist/commands/deploy-access.js +6 -13
  17. package/dist/commands/deploy-comments.js +5 -13
  18. package/dist/commands/deploy-domains.js +6 -13
  19. package/dist/commands/deploy-list.js +25 -11
  20. package/dist/commands/deploy-mutations.d.ts +3 -0
  21. package/dist/commands/deploy-mutations.js +147 -0
  22. package/dist/commands/link.js +29 -0
  23. package/dist/commands/mesh.js +3 -1
  24. package/dist/commands/report.js +8 -9
  25. package/dist/data/command-states.json +10 -7
  26. package/dist/lib/bot/fleet-bots-update-pass.d.ts +8 -0
  27. package/dist/lib/bot/fleet-bots-update-pass.js +40 -0
  28. package/dist/lib/bot/fleet-bots-update-task.d.ts +12 -0
  29. package/dist/lib/bot/fleet-bots-update-task.js +52 -0
  30. package/dist/lib/bot/fleet-bots-update-worker-v1.d.ts +2 -0
  31. package/dist/lib/bot/fleet-bots-update-worker-v1.js +5 -0
  32. package/dist/lib/daemon/catalog.d.ts +8 -5
  33. package/dist/lib/daemon/catalog.js +15 -8
  34. package/dist/lib/daemon/lock.js +33 -37
  35. package/dist/lib/daemon/ops/skill-command.d.ts +99 -0
  36. package/dist/lib/daemon/ops/skill-command.js +260 -0
  37. package/dist/lib/daemon/protocol.d.ts +1 -1
  38. package/dist/lib/daemon/protocol.js +1 -0
  39. package/dist/lib/daemon/run.js +10 -18
  40. package/dist/lib/daemon/server.js +7 -0
  41. package/dist/lib/daemon/supervisor.d.ts +5 -0
  42. package/dist/lib/daemon/supervisor.js +17 -2
  43. package/dist/lib/db/app-ref.js +10 -15
  44. package/dist/lib/deploy-apps.d.ts +29 -0
  45. package/dist/lib/deploy-apps.js +37 -0
  46. package/dist/lib/doctor/checks/search-index.d.ts +16 -0
  47. package/dist/lib/doctor/checks/search-index.js +61 -0
  48. package/dist/lib/doctor/checks/stranded-lanes.js +1 -1
  49. package/dist/lib/doctor/registry.js +4 -0
  50. package/dist/lib/lanes/accounts.js +3 -3
  51. package/dist/lib/lanes/admission-host.js +1 -1
  52. package/dist/lib/lanes/admission.js +4 -4
  53. package/dist/lib/lanes/autopilot.js +2 -2
  54. package/dist/lib/lanes/blocker-freshness.js +1 -1
  55. package/dist/lib/lanes/compaction.js +5 -5
  56. package/dist/lib/lanes/delivery.js +1 -1
  57. package/dist/lib/lanes/depth-cap.js +1 -1
  58. package/dist/lib/lanes/disk-guard.js +1 -1
  59. package/dist/lib/lanes/dropbox.js +1 -1
  60. package/dist/lib/lanes/hooks-install.js +1 -1
  61. package/dist/lib/lanes/imported-question.js +1 -1
  62. package/dist/lib/lanes/keep-alive.d.ts +2 -2
  63. package/dist/lib/lanes/keep-alive.js +3 -3
  64. package/dist/lib/lanes/kr-freshness.js +1 -1
  65. package/dist/lib/lanes/links.js +4 -4
  66. package/dist/lib/lanes/loop.js +2 -2
  67. package/dist/lib/lanes/machine-identity.js +3 -3
  68. package/dist/lib/lanes/models.js +6 -6
  69. package/dist/lib/lanes/quota.js +1 -1
  70. package/dist/lib/lanes/reconcile-install.js +3 -3
  71. package/dist/lib/lanes/reconcile.js +16 -16
  72. package/dist/lib/lanes/remote-control-lane.js +6 -6
  73. package/dist/lib/lanes/reviews.js +2 -2
  74. package/dist/lib/lanes/spawn.js +24 -24
  75. package/dist/lib/lanes/status-fields.js +4 -4
  76. package/dist/lib/lanes/wait.js +4 -4
  77. package/dist/lib/lanes/watch.js +2 -2
  78. package/dist/lib/lanes/watcher-main.js +1 -1
  79. package/dist/lib/lanes/watcher.js +38 -38
  80. package/dist/lib/lanes/worker-process.js +5 -5
  81. package/dist/lib/mesh/live/daemon/pid-lock.d.ts +2 -4
  82. package/dist/lib/mesh/live/daemon/pid-lock.js +38 -55
  83. package/dist/utils/exclusive-lock.d.ts +60 -0
  84. package/dist/utils/exclusive-lock.js +65 -0
  85. package/package.json +8 -7
  86. package/dist/commands/staff/listings.d.ts +0 -41
  87. package/dist/commands/staff/listings.js +0 -160
  88. package/dist/commands/staff/reset-test-account.d.ts +0 -121
  89. package/dist/commands/staff/reset-test-account.js +0 -285
  90. package/dist/commands/staff/test-account.d.ts +0 -51
  91. package/dist/commands/staff/test-account.js +0 -196
@@ -15,6 +15,8 @@ import { createResolver } from "../lib/daemon/resolver.js";
15
15
  import { readCompaniesManifestMap } from "../lib/work-context/repo-remote.js";
16
16
  import { canonicalDir, keyForDir, readRegistry, registryDir, registryFile, removeEntriesForDir, seedFromManifest, setEntry, wouldBindEnclosingRemote, writeRegistry, } from "../lib/registry/registry.js";
17
17
  import { readHqRoot } from "./mcp-serve.js";
18
+ import { resolveCompany as resolveActiveCompany } from "./core-resolve-company-native.js";
19
+ import { resolveLiveRoot } from "../utils/hq-roots.js";
18
20
  async function requireAnywhereRuntime(deps) {
19
21
  if (!(await (deps.runtimeAllowed ?? (() => anywhereRuntimeAllowed()))())) {
20
22
  throw new Error("HQ Anywhere is disabled until both the runtime flag and your person setting are on.");
@@ -172,7 +174,34 @@ export function registerResolveCompanyCommand(program, deps = {}) {
172
174
  .description("Print the HQ company linked to this folder (never guesses)")
173
175
  .option("--path <dir>", "Folder to resolve (default: current directory)")
174
176
  .option("--json", "Print JSON output")
177
+ .option("--prompt <text>", "Resolve the active company for skills and routing: whole-token manifest slug in <text>, then session, then device default; prints JSON and exits 0")
178
+ .option("--root <dir>", "HQ root for --prompt (default: the live HQ root)")
175
179
  .action(async (opts) => {
180
+ if (opts.prompt !== undefined) {
181
+ if (opts.path !== undefined) {
182
+ console.error("hq resolve-company: --prompt and --path cannot be used together");
183
+ process.exitCode = 1;
184
+ return;
185
+ }
186
+ // US-030 c1: one resolver. This is the same function behind
187
+ // `hq core resolve-company --prompt`; it reads no anywhere registry,
188
+ // so it is not behind the anywhere runtime gate.
189
+ let hqRoot;
190
+ try {
191
+ hqRoot = resolveLiveRoot({ hqRoot: opts.root });
192
+ }
193
+ catch (err) {
194
+ fail(err);
195
+ return;
196
+ }
197
+ const result = await resolveActiveCompany(opts.root !== undefined ? ["--root", opts.root, "--prompt", opts.prompt] : ["--prompt", opts.prompt], { cwd: process.cwd(), hqRoot, stdinIsTty: true });
198
+ process.stdout.write(result.stdout);
199
+ if (result.stderr.length)
200
+ process.stderr.write(result.stderr);
201
+ if (result.code !== 0)
202
+ process.exitCode = result.code;
203
+ return;
204
+ }
176
205
  try {
177
206
  await requireAnywhereRuntime(deps);
178
207
  }
@@ -65,6 +65,7 @@ import { requeueQuarantinedOutbox } from "../lib/work-context/outbox.js";
65
65
  import { handOffInstallHere } from "../lib/daemon/handoff.js";
66
66
  import { repairServiceUnitsFromOtherHome } from "../lib/daemon/mesh-owner.js";
67
67
  import { runResidentCommandWithPackageLease } from "../utils/resident-package-preload.js";
68
+ import { exitCli } from "../utils/exit-after-worker.js";
68
69
  export function formatCheckLines(threads, company, projectId) {
69
70
  if (threads.length === 0) {
70
71
  return ["Work mesh: no active project threads found."];
@@ -2801,7 +2802,8 @@ function wrap(action) {
2801
2802
  await action();
2802
2803
  }
2803
2804
  catch (err) {
2804
- fail(err instanceof Error ? err.message : String(err));
2805
+ console.error(chalk.red(err instanceof Error ? err.message : String(err)));
2806
+ return await exitCli(1);
2805
2807
  }
2806
2808
  };
2807
2809
  }
@@ -6,7 +6,7 @@ import * as path from "node:path";
6
6
  import { ensureCognitoToken, } from "../utils/cognito-session.js";
7
7
  import { vaultApiFetch } from "../utils/vault-api.js";
8
8
  import { DEPLOY_API_URL, deployApiRequest, deployHeaders } from "../lib/deploy-api.js";
9
- import { listDeployApps } from "../lib/deploy-apps.js";
9
+ import { listAllDeployApps, matchDeployApp } from "../lib/deploy-apps.js";
10
10
  import { listReportTemplates } from "../lib/report-templates.js";
11
11
  import { stopFlagRegistryWorker } from "../lib/flag-registry.js";
12
12
  import { adoptReport, buildReportTarball, conventionReportDir, deployOrgContext, ReportPublishError, plainFailureReason, publishReport, } from "../lib/report-publish.js";
@@ -263,16 +263,15 @@ async function orgFor(token, report) {
263
263
  return deployOrgContext(report, slug);
264
264
  }
265
265
  export async function findOrCreateApp(token, slug, org) {
266
- const apps = await listDeployApps((cursor) => {
267
- const route = cursor ? `/api/apps?cursor=${encodeURIComponent(cursor)}` : "/api/apps";
268
- return deployJson(token, route, "GET", undefined, org.headers);
269
- });
270
- const mine = (name) => apps.find((app) => !!app && typeof app === "object" && (app.subdomain === name || app.name === name));
266
+ const apps = await listAllDeployApps((route) => deployJson(token, route, "GET", undefined, org.headers));
271
267
  let app;
272
268
  for (const name of candidateSlugs(slug)) {
273
- const existing = mine(name);
274
- if (existing) {
275
- app = existing;
269
+ const existing = matchDeployApp(apps, name, { exact: true });
270
+ if (existing.kind === "many") {
271
+ throw new ReportPublishError(`More than one hq-deploy app is called '${name}'. Remove the extra app and retry.`);
272
+ }
273
+ if (existing.kind === "found") {
274
+ app = existing.record;
276
275
  break;
277
276
  }
278
277
  try {
@@ -27,12 +27,15 @@
27
27
  "report discard-draft": { "state": "retiring" },
28
28
  "report promote": { "state": "retiring" },
29
29
  "report templates": { "state": "retiring" },
30
- "staff listings approve": { "state": "retiring", "replacedBy": "the staff-only hq-staff script outside the public CLI" },
31
- "staff listings queue": { "state": "retiring", "replacedBy": "the staff-only hq-staff script outside the public CLI" },
32
- "staff listings reject": { "state": "retiring", "replacedBy": "the staff-only hq-staff script outside the public CLI" },
33
- "staff reset-test-account": { "state": "retiring", "replacedBy": "the staff-only hq-staff script outside the public CLI" },
34
- "staff test-account add": { "state": "retiring", "replacedBy": "the staff-only hq-staff script outside the public CLI" },
35
- "staff test-account list": { "state": "retiring", "replacedBy": "the staff-only hq-staff script outside the public CLI" },
36
- "staff test-account remove": { "state": "retiring", "replacedBy": "the staff-only hq-staff script outside the public CLI" }
30
+ "staff": { "state": "removed", "replacedBy": "the staff-only hq-staff tool outside the public CLI (hq-core-rust US-053)" },
31
+ "staff listings": { "state": "removed", "replacedBy": "the staff-only hq-staff tool outside the public CLI (hq-core-rust US-053)" },
32
+ "staff listings approve": { "state": "removed", "replacedBy": "the staff-only hq-staff tool outside the public CLI (hq-core-rust US-053)" },
33
+ "staff listings queue": { "state": "removed", "replacedBy": "the staff-only hq-staff tool outside the public CLI (hq-core-rust US-053)" },
34
+ "staff listings reject": { "state": "removed", "replacedBy": "the staff-only hq-staff tool outside the public CLI (hq-core-rust US-053)" },
35
+ "staff reset-test-account": { "state": "removed", "replacedBy": "the staff-only hq-staff tool outside the public CLI (hq-core-rust US-053)" },
36
+ "staff test-account": { "state": "removed", "replacedBy": "the staff-only hq-staff tool outside the public CLI (hq-core-rust US-053)" },
37
+ "staff test-account add": { "state": "removed", "replacedBy": "the staff-only hq-staff tool outside the public CLI (hq-core-rust US-053)" },
38
+ "staff test-account list": { "state": "removed", "replacedBy": "the staff-only hq-staff tool outside the public CLI (hq-core-rust US-053)" },
39
+ "staff test-account remove": { "state": "removed", "replacedBy": "the staff-only hq-staff tool outside the public CLI (hq-core-rust US-053)" }
37
40
  }
38
41
  }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * One fleet-bots-update pass: move each installed HQ Fleet bot to the current
3
+ * runtime release while it is idle, and restart it. Shared by
4
+ * `hq daemon service fleet-bots-update` and the daemon's internal task, so the
5
+ * update eligibility and the update steps are the same code on both paths.
6
+ */
7
+ export declare function runInstalledFleetBotsUpdate(log: (line: string) => void): Promise<void>;
8
+ //# sourceMappingURL=fleet-bots-update-pass.d.ts.map
@@ -0,0 +1,40 @@
1
+ /**
2
+ * One fleet-bots-update pass: move each installed HQ Fleet bot to the current
3
+ * runtime release while it is idle, and restart it. Shared by
4
+ * `hq daemon service fleet-bots-update` and the daemon's internal task, so the
5
+ * update eligibility and the update steps are the same code on both paths.
6
+ */
7
+ export async function runInstalledFleetBotsUpdate(log) {
8
+ const [{ runFleetBotsUpdate, listFleetBots }, local, bot, { botsRoot }, { hasPromotionHold }] = await Promise.all([
9
+ import("./fleet-watch.js"),
10
+ import("./fleet-local.js"),
11
+ import("../../commands/bot.js"),
12
+ import("./paths.js"),
13
+ import("./promotion-hold.js"),
14
+ ]);
15
+ const alive = (pid) => {
16
+ try {
17
+ process.kill(pid, 0);
18
+ return true;
19
+ }
20
+ catch (error) {
21
+ return error.code === "EPERM";
22
+ }
23
+ };
24
+ await runFleetBotsUpdate({
25
+ listBots: () => listFleetBots(botsRoot()),
26
+ target: () => local.resolveFleetLocalPointerTarget(),
27
+ installed: (b) => {
28
+ if (b.config.enabled === false)
29
+ return false;
30
+ const pid = local.fleetLocalGatewayPid(b.config.agentUid);
31
+ return pid !== null && alive(pid);
32
+ },
33
+ heldForPromotion: (b) => hasPromotionHold(b.dir),
34
+ needsAdoption: (b, release) => local.fleetLocalProfileNeedsAdoption(b.config.agentUid, { release }),
35
+ busy: (b) => local.fleetLocalBusyReason(b.config.agentUid),
36
+ update: (b) => bot.updateFleetRuntimeBot(b.name, { busy: () => local.fleetLocalBusyReason(b.config.agentUid) }),
37
+ log,
38
+ });
39
+ }
40
+ //# sourceMappingURL=fleet-bots-update-pass.js.map
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Run one fleet-bots-update pass for the daemon without starting a process.
3
+ * The pass runs on a worker thread, so its synchronous runtime helper calls
4
+ * stay off the supervisor thread and anything it throws (or a crash of the
5
+ * thread) ends only this pass: the promise resolves false or rejects, and the
6
+ * supervisor records the run as failed. Resolves true when the pass finished.
7
+ */
8
+ export declare function runFleetBotsUpdateWorker(options: {
9
+ env: NodeJS.ProcessEnv;
10
+ log: (line: string) => void;
11
+ }, entry?: URL): Promise<boolean>;
12
+ //# sourceMappingURL=fleet-bots-update-task.d.ts.map
@@ -0,0 +1,52 @@
1
+ import { Worker } from "node:worker_threads";
2
+ // The pass itself (runInstalledFleetBotsUpdate) lives in fleet-bots-update-pass.ts,
3
+ // so the supervisor, which imports this module, reaches no lazy package import.
4
+ const fleetBotsUpdateWorkerEntry = new URL("./fleet-bots-update-worker-v1.js", import.meta.url);
5
+ /**
6
+ * Run one fleet-bots-update pass for the daemon without starting a process.
7
+ * The pass runs on a worker thread, so its synchronous runtime helper calls
8
+ * stay off the supervisor thread and anything it throws (or a crash of the
9
+ * thread) ends only this pass: the promise resolves false or rejects, and the
10
+ * supervisor records the run as failed. Resolves true when the pass finished.
11
+ */
12
+ export function runFleetBotsUpdateWorker(options, entry = fleetBotsUpdateWorkerEntry) {
13
+ return new Promise((resolve, reject) => {
14
+ let worker;
15
+ try {
16
+ worker = new Worker(entry, { env: options.env, stdout: true, stderr: true });
17
+ }
18
+ catch (error) {
19
+ reject(error);
20
+ return;
21
+ }
22
+ let failure;
23
+ const lines = (stream) => {
24
+ let rest = "";
25
+ stream.setEncoding("utf8");
26
+ stream.on("data", (chunk) => {
27
+ const parts = (rest + chunk).split("\n");
28
+ rest = parts.pop() ?? "";
29
+ for (const line of parts)
30
+ if (line)
31
+ options.log(line);
32
+ });
33
+ stream.on("end", () => {
34
+ if (rest)
35
+ options.log(rest);
36
+ rest = "";
37
+ });
38
+ };
39
+ lines(worker.stdout);
40
+ lines(worker.stderr);
41
+ worker.once("error", (err) => {
42
+ failure ??= err;
43
+ });
44
+ worker.once("exit", (code) => {
45
+ if (failure)
46
+ reject(failure);
47
+ else
48
+ resolve(code === 0);
49
+ });
50
+ });
51
+ }
52
+ //# sourceMappingURL=fleet-bots-update-task.js.map
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=fleet-bots-update-worker-v1.d.ts.map
@@ -0,0 +1,5 @@
1
+ // Worker-thread entry for the daemon's fleet-bots-update internal task.
2
+ // It starts no process of its own; see runFleetBotsUpdateWorker.
3
+ import { runInstalledFleetBotsUpdate } from "./fleet-bots-update-pass.js";
4
+ await runInstalledFleetBotsUpdate((line) => console.log(line));
5
+ //# sourceMappingURL=fleet-bots-update-worker-v1.js.map
@@ -47,11 +47,14 @@ type UnitCommand = {
47
47
  task: "search-index";
48
48
  };
49
49
  /** Work the daemon does in its own process on a schedule, without starting a child. */
50
- export type InternalTask = "rotate-logs" | "lanes-reconcile";
51
- /** Compatibility path for installations that do not contain the versioned worker. */
52
- export declare function legacySearchIndexCommand(root: string | undefined): Extract<UnitCommand, {
53
- type: "hq";
54
- }>;
50
+ export type InternalTask = "rotate-logs" | "lanes-reconcile" | "fleet-bots-update";
51
+ /**
52
+ * Why the daemon schedules no search-index pass. The timer never starts `hq`
53
+ * (hq-core-rust US-051): when the in-process worker cannot run, the unit is
54
+ * planned unavailable with this reason, which `hq daemon status` and
55
+ * `hq doctor` show. `hq index sync` still works by hand.
56
+ */
57
+ export declare const SEARCH_INDEX_WORKER_UNAVAILABLE: string;
55
58
  interface UnitBlock {
56
59
  /** `waiting` clears when requirements appear; `unavailable` needs a newer CLI; `paused` needs an explicit resume. */
57
60
  state: "waiting" | "unavailable" | "paused";
@@ -93,10 +93,14 @@ export function enabledServices(machineType, overrides) {
93
93
  };
94
94
  return SERVICE_NAMES.filter((s) => wanted(s) || implied(s));
95
95
  }
96
- /** Compatibility path for installations that do not contain the versioned worker. */
97
- export function legacySearchIndexCommand(root) {
98
- return { type: "hq", args: ["index", "sync", "--hq-root", root ?? ""] };
99
- }
96
+ /**
97
+ * Why the daemon schedules no search-index pass. The timer never starts `hq`
98
+ * (hq-core-rust US-051): when the in-process worker cannot run, the unit is
99
+ * planned unavailable with this reason, which `hq daemon status` and
100
+ * `hq doctor` show. `hq index sync` still works by hand.
101
+ */
102
+ export const SEARCH_INDEX_WORKER_UNAVAILABLE = "this daemon cannot run the search index worker (the installed CLI has no worker, or the daemon could not hand its package lease to it), " +
103
+ "so it does not refresh the HQ search index on a timer; restart the daemon (`hq daemon restart --daemon`) or run `hq index sync` by hand";
100
104
  export const FLEET_BOT_STOP_GRACE_MS = 30_000;
101
105
  export const FLEET_BOTS_UPDATE_UNIT = "fleet-bots-update";
102
106
  export const FLEET_BOTS_UPDATE_INTERVAL_SEC = 30 * 60;
@@ -378,7 +382,9 @@ function planService(service, ctx) {
378
382
  kind: "scheduled",
379
383
  intervalSec: FLEET_BOTS_UPDATE_INTERVAL_SEC,
380
384
  initialDelaySec: FLEET_BOTS_UPDATE_INITIAL_DELAY_SEC,
381
- command: { type: "hq", args: ["daemon", "service", "fleet-bots-update"] },
385
+ // Runs in the daemon's own process (on a worker thread) instead of
386
+ // starting a fresh `hq` every 30 minutes (hq-core-rust US-051).
387
+ command: { type: "internal", task: "fleet-bots-update" },
382
388
  env: { HQ_NO_UPDATE_CHECK: "1" },
383
389
  blocked: firstBlock([[!ctx.signedIn, NOT_SIGNED_IN]]),
384
390
  }),
@@ -459,14 +465,15 @@ function planService(service, ctx) {
459
465
  case "search-index":
460
466
  if (ctx.searchIndexOwnedBySyncRunner)
461
467
  return [];
468
+ // No `hq index sync` fallback: the timer never starts hq (US-051).
469
+ if (ctx.searchIndexWorkerAvailable === false)
470
+ return [unavailable(service, SEARCH_INDEX_WORKER_UNAVAILABLE)];
462
471
  return [
463
472
  base(service, {
464
473
  kind: "scheduled",
465
474
  intervalSec: 900,
466
475
  initialDelaySec: 120,
467
- command: ctx.searchIndexWorkerAvailable === false
468
- ? legacySearchIndexCommand(ctx.hqRoot)
469
- : { type: "worker", task: "search-index" },
476
+ command: { type: "worker", task: "search-index" },
470
477
  env: ctx.hqRoot ? { HQ_ROOT: ctx.hqRoot } : {},
471
478
  // A full qmd pass rereads every indexed file; at default priority it
472
479
  // got HQ listed under macOS "Using Significant Energy".
@@ -12,6 +12,7 @@ import { spawnSync } from "node:child_process";
12
12
  import * as fs from "node:fs";
13
13
  import * as path from "node:path";
14
14
  import { readPidLock } from "../mesh/live/daemon/pid-lock.js";
15
+ import { createLockFile, lockIsStale, releaseLockFile } from "../../utils/exclusive-lock.js";
15
16
  import { ensurePrivateDir } from "./paths.js";
16
17
  export const TAKEOVER_TTL_MS = 30_000;
17
18
  /**
@@ -109,46 +110,45 @@ export function verifyDaemonForKill(owner, run) {
109
110
  }
110
111
  return { verdict: "daemon" };
111
112
  }
113
+ /** Stale policy of the takeover claim: age only, reclaimed once older than TAKEOVER_TTL_MS (by mtime). */
114
+ const TAKEOVER_CLAIM_STALE = { kind: "age", maxAgeMs: TAKEOVER_TTL_MS };
112
115
  function claimTakeover(claim, pid, now) {
113
116
  for (let attempt = 0; attempt < 2; attempt++) {
114
- try {
115
- fs.writeFileSync(claim, `pid=${pid}\n`, { flag: "wx", mode: 0o600 });
117
+ if (createLockFile(claim, `pid=${pid}\n`))
116
118
  return true;
119
+ let age;
120
+ try {
121
+ age = now() - fs.statSync(claim).mtimeMs;
117
122
  }
118
- catch (err) {
119
- if (err.code !== "EEXIST")
120
- throw err;
121
- let age;
122
- try {
123
- age = now() - fs.statSync(claim).mtimeMs;
124
- }
125
- catch (statErr) {
126
- if (statErr.code === "ENOENT")
127
- continue;
128
- throw statErr;
129
- }
130
- if (age <= TAKEOVER_TTL_MS)
131
- return false;
132
- fs.rmSync(claim, { force: true });
123
+ catch (statErr) {
124
+ if (statErr.code === "ENOENT")
125
+ continue;
126
+ throw statErr;
133
127
  }
128
+ if (!lockIsStale(TAKEOVER_CLAIM_STALE, { ageMs: age }))
129
+ return false;
130
+ fs.rmSync(claim, { force: true });
134
131
  }
135
132
  return false;
136
133
  }
134
+ /**
135
+ * Stale policy of the daemon lock: pid only. The lock is reclaimed when its
136
+ * owner is unreadable, is this starter's own pid, or is not a live daemon;
137
+ * a live daemon keeps it at any age.
138
+ */
139
+ function daemonLockStale(pid, alive) {
140
+ return { kind: "pid", alive, self: pid };
141
+ }
137
142
  export function acquireDaemonLock(lockPath, pid = process.pid, alive = isDaemonProcess, now = Date.now) {
138
143
  ensurePrivateDir(path.dirname(lockPath));
139
144
  const body = `pid=${pid}\nts=${Math.floor(now() / 1000)}\n`;
140
145
  const claim = `${lockPath}.takeover`;
146
+ const stale = daemonLockStale(pid, alive);
141
147
  for (let attempt = 0; attempt < 3; attempt++) {
142
- try {
143
- fs.writeFileSync(lockPath, body, { flag: "wx", mode: 0o600 });
148
+ if (createLockFile(lockPath, body))
144
149
  return { ok: true };
145
- }
146
- catch (err) {
147
- if (err.code !== "EEXIST")
148
- throw err;
149
- }
150
150
  const owner = readPidLock(lockPath);
151
- if (owner && owner.pid !== pid && alive(owner.pid))
151
+ if (owner && !lockIsStale(stale, { owner }))
152
152
  return { ok: false, owner };
153
153
  // Another starter is replacing the same stale lock; let it.
154
154
  if (!claimTakeover(claim, pid, now))
@@ -156,17 +156,11 @@ export function acquireDaemonLock(lockPath, pid = process.pid, alive = isDaemonP
156
156
  try {
157
157
  // Re-check under the claim: the lock may have been replaced since the read above.
158
158
  const current = readPidLock(lockPath);
159
- if (current && current.pid !== pid && alive(current.pid))
159
+ if (current && !lockIsStale(stale, { owner: current }))
160
160
  return { ok: false, owner: current };
161
161
  fs.rmSync(lockPath, { force: true });
162
- try {
163
- fs.writeFileSync(lockPath, body, { flag: "wx", mode: 0o600 });
162
+ if (createLockFile(lockPath, body))
164
163
  return { ok: true };
165
- }
166
- catch (err) {
167
- if (err.code !== "EEXIST")
168
- throw err;
169
- }
170
164
  }
171
165
  finally {
172
166
  fs.rmSync(claim, { force: true });
@@ -175,14 +169,16 @@ export function acquireDaemonLock(lockPath, pid = process.pid, alive = isDaemonP
175
169
  throw new Error(`could not take the daemon lock at ${lockPath}`);
176
170
  }
177
171
  export function releaseDaemonLock(lockPath, pid = process.pid) {
178
- const owner = readPidLock(lockPath);
179
- if (owner?.pid === pid)
180
- fs.rmSync(lockPath, { force: true });
172
+ releaseLockFile(lockPath, {
173
+ read: (p) => readPidLock(p),
174
+ owns: (owner) => owner.pid === pid,
175
+ remove: (p) => fs.rmSync(p, { force: true }),
176
+ });
181
177
  }
182
178
  /** The live supervisor's lock record (pid and start time), or null when none is running. */
183
179
  export function liveDaemonLock(lockPath, alive = isDaemonProcess) {
184
180
  const owner = readPidLock(lockPath);
185
- return owner && alive(owner.pid) ? owner : null;
181
+ return owner && !lockIsStale({ kind: "pid", alive }, { owner }) ? owner : null;
186
182
  }
187
183
  /** The live supervisor's pid, or null when none is running. */
188
184
  export function runningDaemonPid(lockPath, alive = isDaemonProcess) {
@@ -0,0 +1,99 @@
1
+ /**
2
+ * skill.command op (hq-core-rust US-049, 40-skill-command-script, ANSWERS-1645 option (c)).
3
+ *
4
+ * hq-hook starts no program on UserPromptSubmit, so when the native
5
+ * classifier (`crates/hq-hook/src/skill_command_script.rs`) finds that the
6
+ * released hook would run a skill's `command.sh`, the hook asks hqd to do it
7
+ * over the socket and waits a bounded time for the answer.
8
+ *
9
+ * For exact parity hqd runs the released hook itself, byte-checked against
10
+ * the pinned copy (hq-core-staging v16.0.48-beta.124, b1e484afe): the hook
11
+ * and the `hook-lib.sh` it sources must hash to the pinned sha256 values,
12
+ * and so must `session-scope-capability.sh` and `perl-child-locale.sh`
13
+ * when present (the hook sources them only then), or the op refuses. The hook gets the caller's payload on stdin and the
14
+ * caller's cwd. Its stdout (one `{"systemMessage":...}` line, or nothing) is
15
+ * returned as is.
16
+ *
17
+ * hqd builds the hook's environment itself (`childEnv`; Reviewer O2,
18
+ * ANSWERS-1736): only the hook's own settings and a few plain locale and
19
+ * user variables are taken from the request, PATH is hqd's own, HQ_ROOT is
20
+ * the root hqd verified, and BASH_ENV, ENV, BASH_FUNC_*, SHELLOPTS, BASHOPTS
21
+ * and CDPATH are never set. A request that carries any of these, or a
22
+ * hostile PATH or HQ_ROOT, has them ignored, so a caller cannot make the
23
+ * pinned hook source or run anything else.
24
+ *
25
+ * The op refuses (never answers "nothing") when it cannot run the hook as
26
+ * released: a root that is not hqd's own, a hook or library that differs
27
+ * from the pinned bytes, bash missing, or the hook still running at the
28
+ * request deadline (it is killed then).
29
+ */
30
+ /** The hook, relative to the HQ root. */
31
+ export declare const SKILL_COMMAND_HOOK = "core/hooks/UserPromptSubmit/40-skill-command-script.sh";
32
+ /** The library the hook sources, relative to the HQ root. */
33
+ export declare const SKILL_COMMAND_LIB = "core/scripts/hook-lib.sh";
34
+ /** sha256 of the pinned hook (same value as `skill_command_script::HOOK_SHA256`). */
35
+ export declare const SKILL_COMMAND_HOOK_SHA256 = "e6ddbaf1fe8f996fa0ade56cc89c3634782db49ab90becff3380bcb0ef6c5c3c";
36
+ /** sha256 of the pinned `hook-lib.sh` (same value as `skill_command_script::LIB_SHA256`). */
37
+ export declare const SKILL_COMMAND_LIB_SHA256 = "9133295e5ce523bf8355a093bbea5a1c19682ec42b59ab6b626dffbc33544f3f";
38
+ /**
39
+ * The libraries the hook sources only when they are present (ANSWERS-1817
40
+ * Q-SCS8 (b)): absent is the released behaviour; present, they must be the
41
+ * pinned bytes (same values as `skill_command_script::SCOPE_LIB_SHA256` and
42
+ * `PERL_LOCALE_LIB_SHA256`).
43
+ */
44
+ export declare const SKILL_COMMAND_OPTIONAL_LIBS: readonly {
45
+ readonly rel: string;
46
+ readonly sha256: string;
47
+ }[];
48
+ export declare class SkillCommandOpError extends Error {
49
+ readonly code: string;
50
+ constructor(code: string, message: string);
51
+ }
52
+ export interface SkillCommandRequest {
53
+ /** The caller's HQ root; must be hqd's own. */
54
+ hqRoot: string;
55
+ /** The UserPromptSubmit payload, as the hook read it on stdin. */
56
+ input: string;
57
+ /** The caller's environment; only `CHILD_ENV_FROM_REQUEST` is used. */
58
+ env: Record<string, string>;
59
+ /** The caller's working directory. */
60
+ cwd: string;
61
+ }
62
+ export interface SkillCommandResult {
63
+ /** The hook's stdout: one `{"systemMessage":...}` line, or empty. */
64
+ stdout: string;
65
+ }
66
+ export interface SkillCommandDeps {
67
+ /** hqd's configured HQ root. */
68
+ daemonRoot: string;
69
+ /** When the request must be answered by. */
70
+ deadlineMs: number;
71
+ now?: () => number;
72
+ bash?: string;
73
+ }
74
+ /**
75
+ * The only variables taken from the request: the released hook's own
76
+ * settings (its header's Env list and the master-hook exports it reads), and
77
+ * plain user and locale variables a skill's command.sh may print with.
78
+ * Nothing here names a program, a file to source or a search path.
79
+ */
80
+ export declare const CHILD_ENV_FROM_REQUEST: readonly string[];
81
+ /** Never set in the hook's environment, whatever the request holds. */
82
+ export declare const CHILD_ENV_NEVER: readonly string[];
83
+ /**
84
+ * The hook's environment, built by hqd: `CHILD_ENV_FROM_REQUEST` from the
85
+ * request, PATH from hqd's own environment, HQ_ROOT the verified root.
86
+ */
87
+ export declare function childEnv(requested: Record<string, string>, verifiedRoot: string, ownPath: string | undefined): Record<string, string>;
88
+ /**
89
+ * Kill the hook and everything it started. The released hook runs
90
+ * `command.sh` under coreutils `timeout`, which moves itself into its own
91
+ * process group, so killing the hook's group alone would leave the script
92
+ * running: every descendant is found from the process table and killed.
93
+ */
94
+ export declare function killTree(pid: number | undefined): void;
95
+ /** Parse and check the op's arguments. Never trusts a path but the root, which must be hqd's own. */
96
+ export declare function parseSkillCommandArgs(args: Record<string, unknown>): SkillCommandRequest;
97
+ /** Run the pinned hook for one prompt. */
98
+ export declare function runSkillCommand(req: SkillCommandRequest, deps: SkillCommandDeps): Promise<SkillCommandResult>;
99
+ //# sourceMappingURL=skill-command.d.ts.map