@indigoai-us/hq-cli 5.345.204 → 5.345.206

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 (80) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/dist/command-catalog.generated.d.ts +51 -1
  3. package/dist/command-catalog.generated.js +63 -1
  4. package/dist/commands/bot.d.ts +67 -0
  5. package/dist/commands/bot.js +301 -39
  6. package/dist/commands/cloud-off-gate.d.ts +9 -2
  7. package/dist/commands/cloud-off-gate.js +49 -13
  8. package/dist/commands/feedback.d.ts +26 -0
  9. package/dist/commands/feedback.js +91 -5
  10. package/dist/commands/install-global.d.ts +3 -1
  11. package/dist/commands/install-global.js +15 -4
  12. package/dist/commands/lanes.d.ts +2 -0
  13. package/dist/commands/lanes.js +9 -3
  14. package/dist/commands/mcp-serve.d.ts +5 -2
  15. package/dist/commands/mcp-serve.js +45 -3
  16. package/dist/commands/mcp-status.d.ts +3 -1
  17. package/dist/commands/mcp-status.js +24 -14
  18. package/dist/commands/secrets.js +11 -1
  19. package/dist/commands/sources.js +10 -15
  20. package/dist/index.js +7 -2
  21. package/dist/lib/bot/executive-settings.d.ts +13 -0
  22. package/dist/lib/bot/executive-settings.js +20 -17
  23. package/dist/lib/bot/executive-sync.d.ts +12 -0
  24. package/dist/lib/bot/executive-sync.js +36 -0
  25. package/dist/lib/bot/executive.d.ts +51 -0
  26. package/dist/lib/bot/executive.js +144 -0
  27. package/dist/lib/bot/fleet-cron.d.ts +7 -0
  28. package/dist/lib/bot/fleet-cron.js +2 -1
  29. package/dist/lib/bot/fleet-local.js +9 -9
  30. package/dist/lib/bot/jobs/executive-handover.d.ts +6 -0
  31. package/dist/lib/bot/jobs/executive-handover.js +33 -0
  32. package/dist/lib/bot/jobs/hot-signal-sync.d.ts +22 -0
  33. package/dist/lib/bot/jobs/hot-signal-sync.js +47 -0
  34. package/dist/lib/bot/listed-running.d.ts +16 -0
  35. package/dist/lib/bot/listed-running.js +16 -0
  36. package/dist/lib/bot/pending-switch.d.ts +51 -0
  37. package/dist/lib/bot/pending-switch.js +103 -0
  38. package/dist/lib/bot/run.js +27 -3
  39. package/dist/lib/bot/runtime-failure.js +19 -3
  40. package/dist/lib/bot/status.d.ts +20 -0
  41. package/dist/lib/company-skill-wrapper.js +29 -0
  42. package/dist/lib/daemon/hq-child-bootstrap.mjs +197 -2
  43. package/dist/lib/daemon/resolver.d.ts +14 -0
  44. package/dist/lib/daemon/resolver.js +96 -0
  45. package/dist/lib/daemon/run.d.ts +11 -0
  46. package/dist/lib/daemon/run.js +58 -6
  47. package/dist/lib/daemon/server.d.ts +2 -9
  48. package/dist/lib/daemon/server.js +3 -89
  49. package/dist/lib/doctor/checks/claude-wiring.js +41 -0
  50. package/dist/lib/doctor/checks/sync-health.d.ts +8 -0
  51. package/dist/lib/doctor/checks/sync-health.js +34 -2
  52. package/dist/lib/doctor/duplicate-hook-registrations.d.ts +34 -0
  53. package/dist/lib/doctor/duplicate-hook-registrations.js +130 -0
  54. package/dist/lib/doctor/fix/apply.js +79 -3
  55. package/dist/lib/doctor/fix/remediation.d.ts +1 -1
  56. package/dist/lib/doctor/fix/remediation.js +15 -0
  57. package/dist/lib/doctor/types.d.ts +1 -1
  58. package/dist/lib/doctor/types.js +1 -0
  59. package/dist/lib/lanes/links.d.ts +2 -0
  60. package/dist/lib/lanes/links.js +12 -1
  61. package/dist/lib/mcp/local-native-tools.d.ts +40 -0
  62. package/dist/lib/mcp/local-native-tools.js +111 -0
  63. package/dist/lib/mcp/tools.d.ts +2 -0
  64. package/dist/lib/mcp/tools.js +2 -0
  65. package/dist/lib/signals/steps/extract.d.ts +1 -1
  66. package/dist/lib/signals/steps/extract.js +4 -16
  67. package/dist/sentry-init.js +6 -0
  68. package/dist/utils/cli-network-lifecycle.d.ts +11 -1
  69. package/dist/utils/cli-network-lifecycle.js +36 -2
  70. package/dist/utils/daemon-helper-lifetime.d.ts +39 -0
  71. package/dist/utils/daemon-helper-lifetime.js +209 -0
  72. package/dist/utils/daemon-helper-markers.d.ts +24 -0
  73. package/dist/utils/daemon-helper-markers.js +53 -0
  74. package/dist/utils/mcp-launcher.d.ts +28 -0
  75. package/dist/utils/mcp-launcher.js +117 -0
  76. package/dist/utils/package-use-lease.d.ts +10 -0
  77. package/dist/utils/package-use-lease.js +31 -0
  78. package/dist/utils/resident-package-preload.js +4 -1
  79. package/docs/anywhere-runtime.md +7 -0
  80. package/package.json +7 -7
@@ -23,6 +23,7 @@
23
23
  * Every dependency is injectable so the family is unit-testable without an HQ
24
24
  * tree, a state dir, or the wall clock.
25
25
  */
26
+ import { type VaultSyncSwitches } from "../../vault-sync-switches.js";
26
27
  import type { CheckContext, CheckFamily, CheckResult } from "../types.js";
27
28
  /** The id of the versions/sync family. */
28
29
  export declare const SYNC_FAMILY_ID = "sync";
@@ -155,6 +156,13 @@ export interface SyncHealthDeps {
155
156
  * than stale (feedback cd56a501).
156
157
  */
157
158
  refreshInProgress?: (fixTarget: string) => number | null;
159
+ /**
160
+ * The HQ app's Settings > Sync switches on this computer. A stale journal
161
+ * for a vault the user switched off is "off by choice" (NA), not a WARN with
162
+ * a `hq sync pull` fix the sync gate would refuse (feedback a73db922).
163
+ * Defaults to reading `~/.hq/menubar.json`.
164
+ */
165
+ vaultSyncSwitches?: () => VaultSyncSwitches;
158
166
  }
159
167
  /**
160
168
  * True when `slug` is a filesystem-safe company folder name. Rejects empty
@@ -36,6 +36,7 @@ import * as hqCloud from "@indigoai-us/hq-cloud";
36
36
  import { loadManifestExports, MANIFEST_UNAVAILABLE_REASON, } from "../../hq-cloud-manifest.js";
37
37
  import { readCompaniesManifestMap } from "../../work-context/repo-remote.js";
38
38
  import { companyRecordedNotResolved } from "../company-resolution-state.js";
39
+ import { readVaultSyncSwitches } from "../../vault-sync-switches.js";
39
40
  import { MANIFEST_DISABLED_ENV, manifestUploadsDisabled, } from "../../manifest-disabled.js";
40
41
  import { CLI_VERSION } from "../../../cli-version.js";
41
42
  import { readSyncVersion } from "../../../utils/feedback-versions.js";
@@ -104,6 +105,7 @@ function withDefaults(deps, hqRoot) {
104
105
  companySyncResolvable: deps.companySyncResolvable ??
105
106
  ((slug, lastSync) => !companyRecordedNotResolved(hqRoot, slug, deps.now().getTime(), lastSync)),
106
107
  manifestUploadsDisabled: deps.manifestUploadsDisabled ?? (() => manifestUploadsDisabled()),
108
+ vaultSyncSwitches: deps.vaultSyncSwitches ?? (() => readVaultSyncSwitches()),
107
109
  refreshInProgress: deps.refreshInProgress ??
108
110
  ((fixTarget) => refreshHandoffStartedAt(hqRoot, fixTarget, deps.now().getTime())),
109
111
  };
@@ -602,7 +604,7 @@ function journalResults(deps, journals) {
602
604
  if (entry.slug === PERSONAL_SCOPE_SLUG) {
603
605
  results.push(leftoverPersonalJournalResult(entry));
604
606
  if (!hasPersonalVaultJournal) {
605
- results.push(withRefreshInProgress(deps, journalFreshnessResult(entry, PERSONAL_VAULT_SCOPE_SLUG, nowMs), "personal"));
607
+ results.push(withRefreshInProgress(deps, withSyncOffByChoice(deps, journalFreshnessResult(entry, PERSONAL_VAULT_SCOPE_SLUG, nowMs), { personal: true }), "personal"));
606
608
  }
607
609
  continue;
608
610
  }
@@ -632,7 +634,7 @@ function journalResults(deps, journals) {
632
634
  continue;
633
635
  }
634
636
  }
635
- const freshness = journalFreshnessResult(entry, entry.slug, nowMs);
637
+ const freshness = withSyncOffByChoice(deps, journalFreshnessResult(entry, entry.slug, nowMs), isPersonalJournalSlug(entry.slug) ? { personal: true } : { company: entry.slug });
636
638
  // A stale company journal whose company the sync service could not
637
639
  // resolve on the last pull would send `--fix` into the same failure, and
638
640
  // the health hook would then report it every day (feedback 9b4a5016).
@@ -648,6 +650,36 @@ function journalResults(deps, journals) {
648
650
  }
649
651
  return results;
650
652
  }
653
+ /**
654
+ * A stale or never-synced journal for a vault the user turned off in Settings >
655
+ * Sync is "off by choice": NA with no remediation, because `hq sync pull`
656
+ * would be refused by the sync gate. Fresh or unreadable journals are untouched.
657
+ */
658
+ function withSyncOffByChoice(deps, result, scope) {
659
+ if (result.status !== "WARN")
660
+ return result;
661
+ if (result.reasonCode !== "stale-threshold" && result.reasonCode !== "never-synced")
662
+ return result;
663
+ let switches;
664
+ try {
665
+ switches = deps.vaultSyncSwitches();
666
+ }
667
+ catch {
668
+ return result;
669
+ }
670
+ const off = switches.allOff ||
671
+ ("personal" in scope ? switches.personalOff : switches.offCompanies.has(scope.company.toLowerCase()));
672
+ if (!off)
673
+ return result;
674
+ const name = "personal" in scope ? "personal vault" : `'${scope.company}' vault`;
675
+ return {
676
+ status: "NA",
677
+ checkId: result.checkId,
678
+ reasonCode: "sync-off-by-choice",
679
+ ...(result.target ? { target: result.target } : {}),
680
+ message: `Sync for the ${name} is off by choice on this computer (Settings > Sync), so its journal is not refreshed. ${result.message}`,
681
+ };
682
+ }
651
683
  /**
652
684
  * A stale or never-synced journal whose `hq doctor --fix` pull is still
653
685
  * running in the background is UNTESTED "refresh in progress", not WARN.
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Hook commands registered twice for the same event.
3
+ *
4
+ * Claude Code merges `.claude/settings.local.json` over `.claude/settings.json`
5
+ * and runs every registered command, so a hook that appears in both files (or
6
+ * twice in one) runs twice per event. The known cause is a `hq rescue`
7
+ * relocate that copied every master-hook.sh registration into
8
+ * settings.local.json as a "user customization" (feedback a73db922): every
9
+ * Work Mesh event was enqueued twice and the Stop hook started two checkpoint
10
+ * sessions per turn.
11
+ *
12
+ * A registration is identified by (event, matcher, full hook object). The same
13
+ * command under a different event or matcher, or with a different `if`,
14
+ * `timeout`, `async` or `shell`, is a different registration and is left
15
+ * alone. The repair only ever edits the local file: settings.json is the
16
+ * release-owned copy and is never touched.
17
+ */
18
+ export interface DuplicateHookReport {
19
+ /** Registrations in settings.json beyond the first copy of the same one. */
20
+ baseInternalDuplicates: number;
21
+ /** Local registrations that repeat settings.json or an earlier local one. */
22
+ localDuplicates: number;
23
+ }
24
+ export declare function findDuplicateHookRegistrations(base: unknown, local: unknown): DuplicateHookReport;
25
+ /**
26
+ * Copy of `local` without the registrations that repeat `base` or an earlier
27
+ * local one. An entry whose hooks all go is dropped, then an emptied event
28
+ * array, then an emptied `hooks` map; everything else is preserved.
29
+ */
30
+ export declare function removeDuplicateHookRegistrations(base: unknown, local: unknown): {
31
+ settings: unknown;
32
+ removed: number;
33
+ };
34
+ //# sourceMappingURL=duplicate-hook-registrations.d.ts.map
@@ -0,0 +1,130 @@
1
+ /**
2
+ * Hook commands registered twice for the same event.
3
+ *
4
+ * Claude Code merges `.claude/settings.local.json` over `.claude/settings.json`
5
+ * and runs every registered command, so a hook that appears in both files (or
6
+ * twice in one) runs twice per event. The known cause is a `hq rescue`
7
+ * relocate that copied every master-hook.sh registration into
8
+ * settings.local.json as a "user customization" (feedback a73db922): every
9
+ * Work Mesh event was enqueued twice and the Stop hook started two checkpoint
10
+ * sessions per turn.
11
+ *
12
+ * A registration is identified by (event, matcher, full hook object). The same
13
+ * command under a different event or matcher, or with a different `if`,
14
+ * `timeout`, `async` or `shell`, is a different registration and is left
15
+ * alone. The repair only ever edits the local file: settings.json is the
16
+ * release-owned copy and is never touched.
17
+ */
18
+ function isObject(v) {
19
+ return !!v && typeof v === "object" && !Array.isArray(v);
20
+ }
21
+ /** JSON with object keys sorted, so field order never changes the identity. */
22
+ function stable(v) {
23
+ if (Array.isArray(v))
24
+ return `[${v.map(stable).join(",")}]`;
25
+ if (isObject(v)) {
26
+ return `{${Object.keys(v)
27
+ .sort()
28
+ .map((k) => `${JSON.stringify(k)}:${stable(v[k])}`)
29
+ .join(",")}}`;
30
+ }
31
+ return JSON.stringify(v) ?? "null";
32
+ }
33
+ function key(event, entry, hook) {
34
+ const matcher = typeof entry.matcher === "string" ? entry.matcher : "";
35
+ return stable([event, matcher, hook]);
36
+ }
37
+ function commandOf(hook) {
38
+ if (!isObject(hook) || hook.type !== "command")
39
+ return null;
40
+ return typeof hook.command === "string" && hook.command.length > 0 ? hook.command : null;
41
+ }
42
+ /** Keys of every command registration in `settings`, in order (repeats included). */
43
+ function registrationKeys(settings) {
44
+ const out = [];
45
+ const hooks = isObject(settings) ? settings.hooks : undefined;
46
+ if (!isObject(hooks))
47
+ return out;
48
+ for (const [event, entries] of Object.entries(hooks)) {
49
+ if (!Array.isArray(entries))
50
+ continue;
51
+ for (const entry of entries) {
52
+ if (!isObject(entry) || !Array.isArray(entry.hooks))
53
+ continue;
54
+ for (const hook of entry.hooks) {
55
+ if (commandOf(hook) !== null)
56
+ out.push(key(event, entry, hook));
57
+ }
58
+ }
59
+ }
60
+ return out;
61
+ }
62
+ export function findDuplicateHookRegistrations(base, local) {
63
+ const seen = new Set();
64
+ let baseInternalDuplicates = 0;
65
+ for (const k of registrationKeys(base)) {
66
+ if (seen.has(k))
67
+ baseInternalDuplicates += 1;
68
+ else
69
+ seen.add(k);
70
+ }
71
+ let localDuplicates = 0;
72
+ for (const k of registrationKeys(local)) {
73
+ if (seen.has(k))
74
+ localDuplicates += 1;
75
+ else
76
+ seen.add(k);
77
+ }
78
+ return { baseInternalDuplicates, localDuplicates };
79
+ }
80
+ /**
81
+ * Copy of `local` without the registrations that repeat `base` or an earlier
82
+ * local one. An entry whose hooks all go is dropped, then an emptied event
83
+ * array, then an emptied `hooks` map; everything else is preserved.
84
+ */
85
+ export function removeDuplicateHookRegistrations(base, local) {
86
+ if (!isObject(local) || !isObject(local.hooks))
87
+ return { settings: local, removed: 0 };
88
+ const seen = new Set(registrationKeys(base));
89
+ let removed = 0;
90
+ const nextHooks = {};
91
+ for (const [event, entries] of Object.entries(local.hooks)) {
92
+ if (!Array.isArray(entries)) {
93
+ nextHooks[event] = entries;
94
+ continue;
95
+ }
96
+ const keptEntries = [];
97
+ for (const entry of entries) {
98
+ if (!isObject(entry) || !Array.isArray(entry.hooks)) {
99
+ keptEntries.push(entry);
100
+ continue;
101
+ }
102
+ const keptHooks = entry.hooks.filter((hook) => {
103
+ if (commandOf(hook) === null)
104
+ return true;
105
+ const k = key(event, entry, hook);
106
+ if (seen.has(k)) {
107
+ removed += 1;
108
+ return false;
109
+ }
110
+ seen.add(k);
111
+ return true;
112
+ });
113
+ if (keptHooks.length === entry.hooks.length)
114
+ keptEntries.push(entry);
115
+ else if (keptHooks.length > 0)
116
+ keptEntries.push({ ...entry, hooks: keptHooks });
117
+ }
118
+ if (keptEntries.length > 0 || entries.length === 0)
119
+ nextHooks[event] = keptEntries;
120
+ }
121
+ if (removed === 0)
122
+ return { settings: local, removed: 0 };
123
+ const next = { ...local };
124
+ if (Object.keys(nextHooks).length > 0)
125
+ next.hooks = nextHooks;
126
+ else
127
+ delete next.hooks;
128
+ return { settings: next, removed };
129
+ }
130
+ //# sourceMappingURL=duplicate-hook-registrations.js.map
@@ -48,6 +48,7 @@ import { repairDanglingReleaseLinks } from "../checks/release-links.js";
48
48
  import { parseHookGateProfiles, requiredMissingProfiles, } from "../hook-gate-profiles.js";
49
49
  import { createBackup } from "./backup.js";
50
50
  import { removeStrayGateEntries } from "../stray-gate-entries.js";
51
+ import { removeDuplicateHookRegistrations } from "../duplicate-hook-registrations.js";
51
52
  import { deriveRemediation } from "./remediation.js";
52
53
  import { HQ_CLI_BINS, removeHqCliPs1Shims } from "../../windows/ps1-shims.js";
53
54
  import { botDir } from "../../bot/paths.js";
@@ -902,6 +903,8 @@ function planFix(hqRoot, result, rem, refreshSync, rewriteBotNodePath = defaultR
902
903
  return planGateProfile(hqRoot, result, rem);
903
904
  case "remove-stray-gate-entries":
904
905
  return planRemoveStrayGateEntries(hqRoot, result, rem);
906
+ case "remove-duplicate-hook-registrations":
907
+ return planRemoveDuplicateHookRegistrations(hqRoot, result, rem);
905
908
  case "refresh-sync":
906
909
  return planRefreshSync(hqRoot, result, rem, refreshSync);
907
910
  case "refresh-manifest":
@@ -1213,13 +1216,59 @@ function planRemoveStrayGateEntries(hqRoot, result, rem) {
1213
1216
  ` - ${removed} matcher-less hook-gate.sh registration${removed === 1 ? "" : "s"} (they fire on every tool call)`,
1214
1217
  summary: `remove ${removed} stray hook registration${removed === 1 ? "" : "s"} from ${relpath}`,
1215
1218
  apply: () => {
1216
- const latest = readJson(settingsPath) ?? {};
1217
- const cleaned = removeStrayGateEntries(latest).settings;
1218
- fs.writeFileSync(settingsPath, JSON.stringify(cleaned, null, 2) + "\n");
1219
+ // Unparseable now (Claude Code may be mid-write): leave it untouched.
1220
+ const latest = readJson(settingsPath);
1221
+ if (!latest) {
1222
+ process.stderr.write(`hq doctor --fix: skipped ${relpath}; it could not be read as JSON right now and was left unchanged.\n`);
1223
+ return;
1224
+ }
1225
+ const { settings: cleaned, removed: again } = removeStrayGateEntries(latest);
1226
+ if (again === 0)
1227
+ return;
1228
+ writeJsonAtomic(settingsPath, cleaned);
1219
1229
  },
1220
1230
  postStatus: (results) => statusForTarget(results, ".stray-gate-registration", settingsPath),
1221
1231
  };
1222
1232
  }
1233
+ /** Remove hook registrations from settings.local.json that settings.json already has. */
1234
+ function planRemoveDuplicateHookRegistrations(hqRoot, result, rem) {
1235
+ const localPath = rem.fixTarget;
1236
+ if (!localPath)
1237
+ return null;
1238
+ // The shipped file is only read, never written.
1239
+ const basePath = path.join(path.dirname(localPath), "settings.json");
1240
+ const base = readJson(basePath);
1241
+ const current = readJson(localPath);
1242
+ if (!base || !current)
1243
+ return null;
1244
+ const { removed } = removeDuplicateHookRegistrations(base, current);
1245
+ if (removed === 0)
1246
+ return null;
1247
+ const relpath = toRelpath(hqRoot, localPath);
1248
+ return {
1249
+ checkId: result.checkId,
1250
+ fixClass: "remove-duplicate-hook-registrations",
1251
+ target: localPath,
1252
+ relpath,
1253
+ preview: ` ${relpath}\n` +
1254
+ ` - ${removed} hook registration${removed === 1 ? "" : "s"} that settings.json already registers (they run twice)`,
1255
+ summary: `remove ${removed} duplicate hook registration${removed === 1 ? "" : "s"} from ${relpath}`,
1256
+ apply: () => {
1257
+ // Either file unparseable now (Claude Code may be mid-write): leave both untouched.
1258
+ const latestBase = readJson(basePath);
1259
+ const latest = readJson(localPath);
1260
+ if (!latestBase || !latest) {
1261
+ process.stderr.write(`hq doctor --fix: skipped ${relpath}; it or settings.json could not be read as JSON right now and was left unchanged.\n`);
1262
+ return;
1263
+ }
1264
+ const { settings: cleaned, removed: again } = removeDuplicateHookRegistrations(latestBase, latest);
1265
+ if (again === 0)
1266
+ return;
1267
+ writeJsonAtomic(localPath, cleaned);
1268
+ },
1269
+ postStatus: (results) => statusForTarget(results, ".duplicate-registration", localPath),
1270
+ };
1271
+ }
1223
1272
  // --- Shell / JSON edit primitives ---------------------------------------------
1224
1273
  /**
1225
1274
  * Insert a new `case` arm allowlisting `hookId` (leading to `return 0`) at the
@@ -1299,6 +1348,33 @@ function readJson(file) {
1299
1348
  return null;
1300
1349
  }
1301
1350
  }
1351
+ /**
1352
+ * Write JSON via a temp file next to the real target, then rename over it.
1353
+ * A symlinked target is resolved first so the link stays and its target is
1354
+ * updated. The temp is fsynced and given the original mode exactly (the mode
1355
+ * passed to openSync is masked by umask) before the rename.
1356
+ */
1357
+ function writeJsonAtomic(file, value) {
1358
+ const real = fs.realpathSync(file);
1359
+ const tmp = `${real}.${process.pid}.tmp`;
1360
+ try {
1361
+ const mode = fs.statSync(real).mode & 0o7777;
1362
+ const fd = fs.openSync(tmp, "w", mode);
1363
+ try {
1364
+ fs.writeSync(fd, JSON.stringify(value, null, 2) + "\n");
1365
+ fs.fsyncSync(fd);
1366
+ }
1367
+ finally {
1368
+ fs.closeSync(fd);
1369
+ }
1370
+ fs.chmodSync(tmp, mode);
1371
+ fs.renameSync(tmp, real);
1372
+ }
1373
+ catch (err) {
1374
+ fs.rmSync(tmp, { force: true });
1375
+ throw err;
1376
+ }
1377
+ }
1302
1378
  function toRelpath(hqRoot, abs) {
1303
1379
  const rel = path.relative(hqRoot, abs);
1304
1380
  return rel === "" ? abs : rel;
@@ -61,7 +61,7 @@
61
61
  */
62
62
  import type { CheckResult } from "../types.js";
63
63
  /** The allowlisted safe repair classes `--fix` is permitted to apply. */
64
- export type FixClass = "executable-bit" | "gate-profile" | "remove-stray-gate-entries" | "refresh-sync" | "refresh-manifest" | "bot-node-path" | "bot-hq-binary" | "remove-ps1-shims" | "repair-release-link";
64
+ export type FixClass = "executable-bit" | "gate-profile" | "remove-stray-gate-entries" | "remove-duplicate-hook-registrations" | "refresh-sync" | "refresh-manifest" | "bot-node-path" | "bot-hq-binary" | "remove-ps1-shims" | "repair-release-link";
65
65
  /**
66
66
  * A finding's structured remediation. `autoFixable`, `action`, and `command`
67
67
  * are the `--json` surface (AC1); `fixTarget`/`fixClass` are the internal handle
@@ -131,6 +131,21 @@ export function deriveRemediation(result) {
131
131
  command: remediation ?? `Remove the matcher-less hook-gate.sh entries from ${target}.`,
132
132
  };
133
133
  }
134
+ // remove-duplicate-hook-registrations — hooks registered in settings.local.json
135
+ // that settings.json already registers, so each runs twice. Only the local
136
+ // overlay is repaired; a repeat inside settings.json stays manual.
137
+ if (checkId.endsWith(".duplicate-registration") &&
138
+ result.status === "WARN" &&
139
+ target &&
140
+ path.basename(target) === "settings.local.json") {
141
+ return {
142
+ autoFixable: true,
143
+ fixClass: "remove-duplicate-hook-registrations",
144
+ fixTarget: target,
145
+ action: `Remove hook registrations from ${target} that settings.json already registers (settings.json is not changed).`,
146
+ command: remediation ?? `Remove the repeated hook entries from ${target}.`,
147
+ };
148
+ }
134
149
  // bot-node-path — a bot LaunchAgent that names node by a versioned path
135
150
  // (…/Cellar/node/<v>/bin/node) that an upgrade removed or will remove.
136
151
  // The repair rewrites only the plist file; it never reloads launchd, so it
@@ -19,7 +19,7 @@ export declare const DOCTOR_STATUSES: readonly ["PASS", "FAIL", "WARN", "UNTESTE
19
19
  */
20
20
  export type DoctorStatus = (typeof DOCTOR_STATUSES)[number];
21
21
  /** Stable, privacy-safe diagnostics emitted by the sync health family. */
22
- export declare const SYNC_REASON_CODES: readonly ["core-version-unavailable", "core-update-available", "no-local-tree", "company-not-resolved", "legacy-personal-journal", "never-synced", "invalid-last-sync", "stale-threshold", "refresh-in-progress", "refresh-lock-held", "manifest-unavailable", "manifest-state-unavailable", "no-manifest-scopes", "never-uploaded", "invalid-upload-time", "manifest-upload-rejected", "unresolved-company-uid", "realtime-lag-stuck", "receiver-permission-denied", "pull-access-denied", "runner-restart-loop", "device-limit-backoff", "repeated-conflicts"];
22
+ export declare const SYNC_REASON_CODES: readonly ["core-version-unavailable", "core-update-available", "no-local-tree", "company-not-resolved", "legacy-personal-journal", "never-synced", "invalid-last-sync", "stale-threshold", "sync-off-by-choice", "refresh-in-progress", "refresh-lock-held", "manifest-unavailable", "manifest-state-unavailable", "no-manifest-scopes", "never-uploaded", "invalid-upload-time", "manifest-upload-rejected", "unresolved-company-uid", "realtime-lag-stuck", "receiver-permission-denied", "pull-access-denied", "runner-restart-loop", "device-limit-backoff", "repeated-conflicts"];
23
23
  export type SyncReasonCode = (typeof SYNC_REASON_CODES)[number];
24
24
  /** Runtime type guard: true only for a member of the fixed vocabulary. */
25
25
  export declare function isDoctorStatus(value: unknown): value is DoctorStatus;
@@ -31,6 +31,7 @@ export const SYNC_REASON_CODES = [
31
31
  "never-synced",
32
32
  "invalid-last-sync",
33
33
  "stale-threshold",
34
+ "sync-off-by-choice",
34
35
  "refresh-in-progress",
35
36
  "refresh-lock-held",
36
37
  "manifest-unavailable",
@@ -24,6 +24,8 @@ export interface LinkOptions {
24
24
  claims?: string;
25
25
  now?: () => Date;
26
26
  sleep?: (milliseconds: number) => Promise<void>;
27
+ /** Injected in tests; defaults to the real package-use lease drop/retake. */
28
+ withLeaseReleased?: <T>(wait: () => Promise<T>) => Promise<T>;
27
29
  }
28
30
  export interface LinkResult {
29
31
  output?: Record<string, unknown>;
@@ -4,6 +4,7 @@ import * as path from "node:path";
4
4
  import { appendDropboxMessageAtPath } from "./dropbox.js";
5
5
  import { readLane, withLaneRecordFileLock } from "./store.js";
6
6
  import { LanesError } from "./errors.js";
7
+ import { withPackageUseLeaseReleasedDuring } from "../../utils/package-use-lease.js";
7
8
  export const LANE_SESSION_LINKS_FLAG = "lanes.session-links";
8
9
  const ID_PATTERN = /^[A-Za-z0-9._-]+$/;
9
10
  export class LaneLinkError extends Error {
@@ -507,6 +508,13 @@ function listChildren(root, dir) {
507
508
  return [{ ...readJson(metaPath), undelivered: unread, quarantined_claims: countQuarantined(path.join(cdir, "inbox")) }];
508
509
  });
509
510
  }
511
+ /**
512
+ * Poll the conductor inbox until a report lands or the timeout passes. A wait
513
+ * runs for up to 30 minutes and only reads files with modules already loaded,
514
+ * so it drops this process's package-use lease while it waits: holding it
515
+ * blocked every desktop CLI update (30s lease budget) for as long as a
516
+ * conductor was waiting.
517
+ */
510
518
  async function waitForReport(dir, timeoutSeconds, sleep) {
511
519
  if (!Number.isInteger(timeoutSeconds) || timeoutSeconds < 0)
512
520
  throw new LaneLinkError("timeout_invalid", "--timeout must be whole seconds");
@@ -726,7 +734,10 @@ export async function runLaneLink(subcommand, options) {
726
734
  if (options.link !== undefined)
727
735
  linkPath(root, options.link);
728
736
  const resolved = resolvePointer(root, requireSid(), "conductor", options);
729
- return await waitForReport(linkPath(root, resolved.link), options.timeout ?? 1800, options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms))));
737
+ const dir = linkPath(root, resolved.link);
738
+ const sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
739
+ const withLeaseReleased = options.withLeaseReleased ?? ((wait) => withPackageUseLeaseReleasedDuring(wait));
740
+ return await withLeaseReleased(() => waitForReport(dir, options.timeout ?? 1800, sleep));
730
741
  }
731
742
  if (subcommand === "list") {
732
743
  let link = options.link;
@@ -0,0 +1,40 @@
1
+ /**
2
+ * In-process answers for the hqd-native MCP tools that only touch the local HQ
3
+ * checkout: hq_resolve_company, hq_policy_check and hq_journal_append.
4
+ *
5
+ * `hq mcp serve` forwards every call to hqd. The HQ desktop app registers the
6
+ * `hq` connector whenever HQ Anywhere is on, but it runs hqd only when its
7
+ * `desktop.hq-daemon` flag is on, and a terminal install can register the
8
+ * connector before `hq daemon install`. Without this fallback those sessions
9
+ * got `hqd_unreachable` for a journal line (feedback_31380021). The hooks
10
+ * already work the same way: they route through hqd when it is running and use
11
+ * the direct engine when it is stopped.
12
+ *
13
+ * The checks match hqd's `mcp.call`: the server's cwd binds the company, an
14
+ * explicit company must match it, the HQ Anywhere gate is read before the call
15
+ * and again before the journal write, and the write runs only after the policy
16
+ * engine allows it. hq_run_worker and the hosted hq-mcp tools still need hqd.
17
+ */
18
+ import { type ResolveResult } from "../registry/registry.js";
19
+ import { type JournalAppendResult } from "../daemon/ops/journal.js";
20
+ import { type PolicyCheckResult } from "../daemon/ops/policy.js";
21
+ export declare const LOCAL_NATIVE_TOOL_NAMES: ReadonlySet<string>;
22
+ export declare class LocalToolError extends Error {
23
+ readonly code: string;
24
+ constructor(code: string, message: string);
25
+ }
26
+ /** Error classes whose code and message reach the MCP client unchanged, as they do through hqd. */
27
+ export declare function localToolErrorCode(err: unknown): string | null;
28
+ export interface LocalNativeContext {
29
+ hqRoot: string;
30
+ home: string;
31
+ env: NodeJS.ProcessEnv;
32
+ /** The server's working directory; it binds the company, as the caller cwd does in hqd. */
33
+ cwd: string;
34
+ /** HQ Anywhere gate (runtime flag and person setting). */
35
+ runtimeEnabled: () => boolean | Promise<boolean>;
36
+ now?: () => Date;
37
+ }
38
+ /** Run one native tool without hqd. Returns the value hqd would wrap as the tool result. */
39
+ export declare function callLocalNativeTool(name: string, raw: Record<string, unknown>, ctx: LocalNativeContext): Promise<ResolveResult | PolicyCheckResult | JournalAppendResult>;
40
+ //# sourceMappingURL=local-native-tools.d.ts.map
@@ -0,0 +1,111 @@
1
+ /**
2
+ * In-process answers for the hqd-native MCP tools that only touch the local HQ
3
+ * checkout: hq_resolve_company, hq_policy_check and hq_journal_append.
4
+ *
5
+ * `hq mcp serve` forwards every call to hqd. The HQ desktop app registers the
6
+ * `hq` connector whenever HQ Anywhere is on, but it runs hqd only when its
7
+ * `desktop.hq-daemon` flag is on, and a terminal install can register the
8
+ * connector before `hq daemon install`. Without this fallback those sessions
9
+ * got `hqd_unreachable` for a journal line (feedback_31380021). The hooks
10
+ * already work the same way: they route through hqd when it is running and use
11
+ * the direct engine when it is stopped.
12
+ *
13
+ * The checks match hqd's `mcp.call`: the server's cwd binds the company, an
14
+ * explicit company must match it, the HQ Anywhere gate is read before the call
15
+ * and again before the journal write, and the write runs only after the policy
16
+ * engine allows it. hq_run_worker and the hosted hq-mcp tools still need hqd.
17
+ */
18
+ import { registryDir, registryFile } from "../registry/registry.js";
19
+ import { createResolver } from "../daemon/resolver.js";
20
+ import { journalAppend, JournalOpError } from "../daemon/ops/journal.js";
21
+ import { PolicyIndex, PolicyOpError, policyCheck } from "../daemon/ops/policy.js";
22
+ import { HQ_ANYWHERE_RUNTIME_FLAG } from "../anywhere-runtime-flag-key.js";
23
+ export const LOCAL_NATIVE_TOOL_NAMES = new Set(["hq_resolve_company", "hq_policy_check", "hq_journal_append"]);
24
+ export class LocalToolError extends Error {
25
+ code;
26
+ constructor(code, message) {
27
+ super(message);
28
+ this.code = code;
29
+ this.name = "LocalToolError";
30
+ }
31
+ }
32
+ /** Error classes whose code and message reach the MCP client unchanged, as they do through hqd. */
33
+ export function localToolErrorCode(err) {
34
+ return err instanceof LocalToolError || err instanceof JournalOpError || err instanceof PolicyOpError ? err.code : null;
35
+ }
36
+ function stringArg(args, name, required = true) {
37
+ const value = args[name];
38
+ if (typeof value === "string" && value.trim())
39
+ return value;
40
+ if (value === undefined && !required)
41
+ return undefined;
42
+ throw new LocalToolError("bad_args", `${name} must be a non-empty string`);
43
+ }
44
+ async function requireEnabled(ctx) {
45
+ if (!(await ctx.runtimeEnabled())) {
46
+ throw new LocalToolError("anywhere_disabled", `HQ Anywhere is disabled by the ${HQ_ANYWHERE_RUNTIME_FLAG} flag.`);
47
+ }
48
+ }
49
+ /** Run one native tool without hqd. Returns the value hqd would wrap as the tool result. */
50
+ export async function callLocalNativeTool(name, raw, ctx) {
51
+ if (!LOCAL_NATIVE_TOOL_NAMES.has(name))
52
+ throw new LocalToolError("unknown_tool", `unknown tool ${name}`);
53
+ await requireEnabled(ctx);
54
+ const clock = ctx.now ?? (() => new Date());
55
+ const resolve = createResolver(registryFile(registryDir(ctx.home, ctx.env)), { hqRoot: ctx.hqRoot });
56
+ const toolArgs = { cwd: ctx.cwd, ...raw };
57
+ const companyArgs = { ...toolArgs, cwd: ctx.cwd };
58
+ delete companyArgs.runtime;
59
+ delete companyArgs.sessionId;
60
+ const companyFor = (args) => {
61
+ const explicit = stringArg(args, "company", false);
62
+ const cwd = stringArg(args, "cwd", false);
63
+ const bound = cwd ? (resolve(cwd).company ?? undefined) : undefined;
64
+ if (explicit && bound && explicit !== bound) {
65
+ throw new LocalToolError("company_mismatch", `explicit company ${explicit} conflicts with bound company ${bound}`);
66
+ }
67
+ return explicit ?? bound;
68
+ };
69
+ const index = new PolicyIndex(ctx.hqRoot);
70
+ const check = (args) => {
71
+ const company = companyFor(args);
72
+ if (!company)
73
+ throw new LocalToolError("bad_args", "company is required (or a cwd linked to a company)");
74
+ const input = args.input;
75
+ if (input !== undefined && (input === null || typeof input !== "object" || Array.isArray(input))) {
76
+ throw new LocalToolError("bad_args", "input must be an object");
77
+ }
78
+ return policyCheck({
79
+ company,
80
+ event: stringArg(args, "event", false),
81
+ tool: stringArg(args, "tool"),
82
+ input: input,
83
+ sessionId: stringArg(args, "sessionId", false),
84
+ cwd: stringArg(args, "cwd", false),
85
+ }, { hqRoot: ctx.hqRoot, index, env: ctx.env, now: clock });
86
+ };
87
+ try {
88
+ switch (name) {
89
+ case "hq_resolve_company":
90
+ return resolve(stringArg(toolArgs, "cwd"));
91
+ case "hq_policy_check":
92
+ return await check(companyArgs);
93
+ default: {
94
+ // hq_journal_append: policy first, then the gate again, then the write.
95
+ const company = companyFor(companyArgs);
96
+ if (!company)
97
+ throw new LocalToolError("bad_args", "company is required for a write-capable MCP tool");
98
+ const verdict = await check({ company, cwd: typeof toolArgs.cwd === "string" ? toolArgs.cwd : ctx.cwd, tool: name, input: raw });
99
+ if (verdict.decision !== "allow") {
100
+ throw new LocalToolError("policy_blocked", verdict.reasons.join("; ") || "policy check did not allow this tool");
101
+ }
102
+ await requireEnabled(ctx);
103
+ return journalAppend({ company, project: stringArg(companyArgs, "project"), section: stringArg(companyArgs, "section"), text: stringArg(companyArgs, "text") }, ctx.hqRoot, clock());
104
+ }
105
+ }
106
+ }
107
+ finally {
108
+ index.close();
109
+ }
110
+ }
111
+ //# sourceMappingURL=local-native-tools.js.map
@@ -10,6 +10,8 @@
10
10
  * hqd answers every one of these through the `mcp.call` op, so a subagent
11
11
  * without MCP can call the same tool with
12
12
  * `hq daemon call mcp.call --json '{"name":"hq_journal_append","arguments":{...}}'`.
13
+ * When hqd is not running, `hq mcp serve` answers the three local-only tools
14
+ * itself (local-native-tools.ts).
13
15
  */
14
16
  import type { McpToolDefinition } from "./types.js";
15
17
  export type { McpToolDefinition } from "./types.js";
@@ -10,6 +10,8 @@
10
10
  * hqd answers every one of these through the `mcp.call` op, so a subagent
11
11
  * without MCP can call the same tool with
12
12
  * `hq daemon call mcp.call --json '{"name":"hq_journal_append","arguments":{...}}'`.
13
+ * When hqd is not running, `hq mcp serve` answers the three local-only tools
14
+ * itself (local-native-tools.ts).
13
15
  */
14
16
  import { HQ_MCP_TOOLS } from "./hq-mcp-tools.generated.js";
15
17
  import { HOSTED_SEARCH_FETCH_TOOLS } from "./hosted-search-tools.js";
@@ -68,7 +68,7 @@ interface WorkItem {
68
68
  audience?: string[];
69
69
  skip?: string;
70
70
  }
71
- /** First personal bot under ~/.hq/bots (by name) with a readable config. */
71
+ /** The Executive bot's runtime (lib/bot/executive.ts), or null when there is no personal bot. */
72
72
  export declare function defaultResolveBotRuntime(root?: string): BotRuntimeId | null;
73
73
  /**
74
74
  * The channel of a `--redo` item, which must be written `sources/<channel>/<file>.md`,