@indigoai-us/hq-cli 5.345.220 → 5.345.221

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (138) hide show
  1. package/CHANGELOG.md +118 -0
  2. package/dist/command-catalog.generated.d.ts +144 -2
  3. package/dist/command-catalog.generated.js +175 -2
  4. package/dist/commands/auth.js +4 -1
  5. package/dist/commands/bot-runtime.d.ts +18 -5
  6. package/dist/commands/bot-runtime.js +29 -12
  7. package/dist/commands/bot.d.ts +39 -2
  8. package/dist/commands/bot.js +140 -11
  9. package/dist/commands/core-stop-autosave.d.ts +21 -0
  10. package/dist/commands/core-stop-autosave.js +300 -0
  11. package/dist/commands/core.js +2 -0
  12. package/dist/commands/daemon.d.ts +5 -0
  13. package/dist/commands/daemon.js +31 -7
  14. package/dist/commands/doctor-usage.d.ts +5 -0
  15. package/dist/commands/doctor-usage.js +25 -0
  16. package/dist/commands/env.d.ts +49 -4
  17. package/dist/commands/env.js +355 -5
  18. package/dist/commands/lanes-shared.d.ts +3 -0
  19. package/dist/commands/lanes.d.ts +3 -0
  20. package/dist/commands/lanes.js +87 -3
  21. package/dist/commands/sources.js +3 -3
  22. package/dist/commands/sync-core.d.ts +1 -0
  23. package/dist/commands/sync-core.js +77 -3
  24. package/dist/commands/whoami.js +96 -80
  25. package/dist/lib/bot/config.d.ts +17 -0
  26. package/dist/lib/bot/config.js +13 -0
  27. package/dist/lib/bot/fleet-cron.js +24 -2
  28. package/dist/lib/bot/fleet-local.d.ts +30 -2
  29. package/dist/lib/bot/fleet-local.js +60 -1
  30. package/dist/lib/bot/grok-login-scope.d.ts +36 -0
  31. package/dist/lib/bot/grok-login-scope.js +93 -0
  32. package/dist/lib/bot/legacy-provider-login.d.ts +32 -9
  33. package/dist/lib/bot/legacy-provider-login.js +28 -22
  34. package/dist/lib/bot/runtime-sign-in-check.js +6 -1
  35. package/dist/lib/bot/runtime-sign-in.d.ts +2 -0
  36. package/dist/lib/core-utils/sentry-report.js +2 -0
  37. package/dist/lib/daemon/machine-checks.d.ts +22 -1
  38. package/dist/lib/daemon/machine-checks.js +54 -12
  39. package/dist/lib/daemon/run.js +66 -8
  40. package/dist/lib/daemon/stop-autosave-lock.d.ts +19 -0
  41. package/dist/lib/daemon/stop-autosave-lock.js +166 -0
  42. package/dist/lib/daemon/stop-autosave.d.ts +28 -0
  43. package/dist/lib/daemon/stop-autosave.js +111 -0
  44. package/dist/lib/daemon/stop-diagnostics.d.ts +11 -0
  45. package/dist/lib/daemon/stop-diagnostics.js +136 -0
  46. package/dist/lib/daemon/stop-job-executor.d.ts +19 -0
  47. package/dist/lib/daemon/stop-job-executor.js +126 -0
  48. package/dist/lib/daemon/stop-jobs.d.ts +93 -0
  49. package/dist/lib/daemon/stop-jobs.js +599 -0
  50. package/dist/lib/doctor/checks/fleet-hook-core.js +1 -1
  51. package/dist/lib/doctor/checks/host-core.js +1 -1
  52. package/dist/lib/environment/access-probes.d.ts +234 -0
  53. package/dist/lib/environment/access-probes.js +918 -0
  54. package/dist/lib/environment/profile.d.ts +15 -2
  55. package/dist/lib/environment/profile.js +55 -20
  56. package/dist/lib/environment/rfc3339.d.ts +8 -0
  57. package/dist/lib/environment/rfc3339.js +26 -0
  58. package/dist/lib/environment/work-requirements.d.ts +169 -0
  59. package/dist/lib/environment/work-requirements.js +389 -0
  60. package/dist/lib/hook-engine/coverage.d.ts +137 -7
  61. package/dist/lib/hook-engine/coverage.js +1424 -4
  62. package/dist/lib/hook-engine/fleet-registration.js +2 -2
  63. package/dist/lib/hook-engine/git-stop-config.json +513 -0
  64. package/dist/lib/hook-engine/native-stop-compatibility.json +311 -0
  65. package/dist/lib/hook-engine/reconcile.js +2 -2
  66. package/dist/lib/hot-channels/alert.d.ts +2 -2
  67. package/dist/lib/hot-channels/alert.js +8 -5
  68. package/dist/lib/hot-channels/signals-pass.d.ts +126 -17
  69. package/dist/lib/hot-channels/signals-pass.js +296 -17
  70. package/dist/lib/hot-channels/signals-runtime.d.ts +30 -0
  71. package/dist/lib/hot-channels/signals-runtime.js +82 -0
  72. package/dist/lib/install/hook-target.js +1 -1
  73. package/dist/lib/lanes/host-capacity.d.ts +26 -2
  74. package/dist/lib/lanes/host-capacity.js +17 -2
  75. package/dist/lib/lanes/host-compute.d.ts +90 -0
  76. package/dist/lib/lanes/host-compute.js +185 -0
  77. package/dist/lib/lanes/index.d.ts +2 -0
  78. package/dist/lib/lanes/index.js +1 -0
  79. package/dist/lib/lanes/reconcile.js +22 -1
  80. package/dist/lib/lanes/resource-usage.d.ts +155 -0
  81. package/dist/lib/lanes/resource-usage.js +589 -0
  82. package/dist/lib/lanes/run-size.d.ts +46 -0
  83. package/dist/lib/lanes/run-size.js +197 -0
  84. package/dist/lib/lanes/store.js +27 -0
  85. package/dist/lib/lanes/throttle.d.ts +36 -1
  86. package/dist/lib/lanes/throttle.js +47 -10
  87. package/dist/lib/lanes/types.d.ts +40 -0
  88. package/dist/lib/lanes/types.js +2 -2
  89. package/dist/lib/lanes/watcher.js +13 -4
  90. package/dist/lib/lanes/worker-process.d.ts +25 -2
  91. package/dist/lib/lanes/worker-process.js +71 -19
  92. package/dist/lib/placement/match.d.ts +192 -0
  93. package/dist/lib/placement/match.js +667 -0
  94. package/dist/lib/safe-store.d.ts +14 -0
  95. package/dist/lib/safe-store.js +77 -4
  96. package/dist/lib/search-index/index.d.ts +88 -4
  97. package/dist/lib/search-index/index.js +288 -24
  98. package/dist/lib/search-index/max-doc-bytes.d.ts +17 -6
  99. package/dist/lib/search-index/max-doc-bytes.js +48 -23
  100. package/dist/lib/signals/codex-lockdown.d.ts +79 -0
  101. package/dist/lib/signals/codex-lockdown.js +271 -0
  102. package/dist/lib/signals/codex-login.d.ts +37 -0
  103. package/dist/lib/signals/codex-login.js +83 -0
  104. package/dist/lib/signals/engine.d.ts +27 -0
  105. package/dist/lib/signals/engine.js +70 -0
  106. package/dist/lib/signals/reply.js +22 -1
  107. package/dist/lib/signals/run-record.js +6 -1
  108. package/dist/lib/signals/settings.d.ts +5 -0
  109. package/dist/lib/signals/settings.js +2 -0
  110. package/dist/lib/signals/steps/extract.d.ts +85 -9
  111. package/dist/lib/signals/steps/extract.js +317 -68
  112. package/dist/lib/signals/steps/types.d.ts +2 -0
  113. package/dist/lib/sync-core/engine-home.d.ts +35 -1
  114. package/dist/lib/sync-core/engine-home.js +119 -16
  115. package/dist/lib/sync-core/rollout-state.d.ts +2 -1
  116. package/dist/lib/sync-core/rollout-state.js +5 -2
  117. package/dist/lib/sync-core/vault-uid.d.ts +2 -0
  118. package/dist/lib/sync-core/vault-uid.js +4 -0
  119. package/dist/schemas/hq-work-requirements.v1.schema.json +145 -0
  120. package/dist/utils/auth-session-check.d.ts +16 -0
  121. package/dist/utils/auth-session-check.js +16 -0
  122. package/dist/utils/client-health-contract.d.ts +6 -0
  123. package/dist/utils/client-health-contract.js +13 -0
  124. package/dist/utils/client-health.d.ts +7 -0
  125. package/dist/utils/client-health.js +22 -1
  126. package/dist/utils/command-usage.d.ts +40 -0
  127. package/dist/utils/command-usage.js +61 -0
  128. package/dist/utils/duplicate-command-usage.d.ts +72 -0
  129. package/dist/utils/duplicate-command-usage.js +125 -0
  130. package/dist/utils/host-registration.js +2 -1
  131. package/dist/utils/resident-package-preload.js +4 -0
  132. package/dist/utils/sentry-fingerprint.js +9 -0
  133. package/dist/utils/windows-bash.d.ts +2 -0
  134. package/dist/utils/windows-bash.js +2 -1
  135. package/package.json +9 -8
  136. package/scripts/bench-core-compare.mjs +313 -0
  137. package/scripts/bench-core.mjs +399 -12
  138. package/scripts/check-function-manifest.mjs +116 -3
@@ -155,6 +155,10 @@ export interface OpenStoreDirOptions {
155
155
  export interface ReadOptions {
156
156
  /** Refuse a file larger than this. Default 1 MiB. */
157
157
  maxBytes?: number;
158
+ /** Read a bounded window from an append-only queue rather than the whole file. */
159
+ offset?: number;
160
+ /** Include the opened file's device/inode identity for queue cursors. */
161
+ identity?: boolean;
158
162
  }
159
163
  export interface AppendOptions {
160
164
  /** Refuse to append when the file is already this size or larger. */
@@ -173,6 +177,7 @@ export interface FileFacts {
173
177
  /** FileFacts plus the exact modification time in nanoseconds (mtimeMs is a float and can round across a millisecond). */
174
178
  export interface ReadFacts extends FileFacts {
175
179
  mtimeNs: bigint;
180
+ fileIdentity?: string;
176
181
  }
177
182
  export interface RenameOptions {
178
183
  /** Waits in milliseconds between rename attempts on EPERM, EACCES or EBUSY (Windows). Empty: no retry. */
@@ -212,9 +217,18 @@ export interface SafeStore {
212
217
  remove(name: string): SafeStoreResult<boolean>;
213
218
  /** The names in the folder. */
214
219
  list(): SafeStoreResult<string[]>;
220
+ /** Read directory names in bounded batches without materializing the directory. */
221
+ nameCursor(): SafeStoreResult<SafeStoreNameCursor>;
215
222
  /** Release the held folder. Later calls are refused with "closed". */
216
223
  close(): void;
217
224
  }
225
+ export interface SafeStoreNameCursor {
226
+ read(maxNames: number): SafeStoreResult<{
227
+ names: string[];
228
+ done: boolean;
229
+ }>;
230
+ close(): void;
231
+ }
218
232
  /** A plain file name: no separator, no NUL, not "." or "..", at most 255 bytes. */
219
233
  export declare function isPlainName(name: string): boolean;
220
234
  /** Owner and mode facts a check needs, from fs.Stats or fs.BigIntStats. */
@@ -602,12 +602,17 @@ class HeldStore {
602
602
  return opened;
603
603
  const { fd, stat } = opened.value;
604
604
  try {
605
- if (stat.size > BigInt(maxBytes))
605
+ const offset = options.offset ?? 0;
606
+ if (!Number.isSafeInteger(offset) || offset < 0)
607
+ return refusal("io-error", "invalid read offset");
608
+ if (options.offset === undefined && stat.size > BigInt(maxBytes))
606
609
  return refusal("too-large", `the file is larger than ${maxBytes} bytes`);
607
- const buffer = Buffer.alloc(maxBytes + 1);
610
+ const buffer = Buffer.alloc(maxBytes + (options.offset === undefined ? 1 : 0));
608
611
  let length = 0;
609
612
  for (;;) {
610
- const count = fs.readSync(fd, buffer, length, buffer.length - length, null);
613
+ if (length === buffer.length)
614
+ break;
615
+ const count = fs.readSync(fd, buffer, length, buffer.length - length, offset + length);
611
616
  if (count === 0)
612
617
  break;
613
618
  length += count;
@@ -615,7 +620,8 @@ class HeldStore {
615
620
  return refusal("too-large", `the file is larger than ${maxBytes} bytes`);
616
621
  }
617
622
  // Bigint stats round mtimeMs down to a whole millisecond; mtimeNs keeps the fraction.
618
- const facts = { size: length, mtimeMs: Number(stat.mtimeNs) / 1e6, mtimeNs: stat.mtimeNs };
623
+ const facts = { size: length, mtimeMs: Number(stat.mtimeNs) / 1e6, mtimeNs: stat.mtimeNs,
624
+ ...(options.identity ? { fileIdentity: `${stat.dev}:${stat.ino}` } : {}) };
619
625
  return { ok: true, value: { data: Buffer.from(buffer.subarray(0, length)), facts } };
620
626
  }
621
627
  catch (error) {
@@ -759,6 +765,73 @@ class HeldStore {
759
765
  return afterList;
760
766
  return { ok: true, value: names };
761
767
  }
768
+ nameCursor() {
769
+ const refused = this.start("list");
770
+ if (refused)
771
+ return refused;
772
+ let directory;
773
+ try {
774
+ directory = fs.opendirSync(this.base, { bufferSize: 32 });
775
+ }
776
+ catch (error) {
777
+ return ioError("opening directory cursor", error);
778
+ }
779
+ let closed = false;
780
+ const close = () => {
781
+ if (closed)
782
+ return;
783
+ closed = true;
784
+ try {
785
+ directory.closeSync();
786
+ }
787
+ catch { /* already closed */ }
788
+ };
789
+ const checked = this.check();
790
+ if (checked) {
791
+ close();
792
+ return checked;
793
+ }
794
+ return { ok: true, value: {
795
+ close,
796
+ read: (maxNames) => {
797
+ const before = this.start("list");
798
+ if (before) {
799
+ close();
800
+ return before;
801
+ }
802
+ if (closed)
803
+ return { ok: true, value: { names: [], done: true } };
804
+ if (!Number.isSafeInteger(maxNames) || maxNames < 1 || maxNames > 256) {
805
+ close();
806
+ return ioError("reading directory cursor", new Error("invalid batch size"));
807
+ }
808
+ const names = [];
809
+ let done = false;
810
+ try {
811
+ while (names.length < maxNames) {
812
+ const entry = directory.readSync();
813
+ if (!entry) {
814
+ done = true;
815
+ close();
816
+ break;
817
+ }
818
+ names.push(entry.name);
819
+ }
820
+ }
821
+ catch (error) {
822
+ close();
823
+ return ioError("reading directory cursor", error);
824
+ }
825
+ this.at("after-list", "list");
826
+ const after = this.check();
827
+ if (after) {
828
+ close();
829
+ return after;
830
+ }
831
+ return { ok: true, value: { names, done } };
832
+ },
833
+ } };
834
+ }
762
835
  close() {
763
836
  if (this.closed)
764
837
  return;
@@ -141,6 +141,77 @@ export declare class QmdCollectionExistsError extends QmdExitError {
141
141
  name: string;
142
142
  constructor(message: string, args: string[], status: number | null, stdout: string, stderr: string, collectionName: string);
143
143
  }
144
+ /**
145
+ * qmd's `collection add` exited non-zero because ANOTHER collection already
146
+ * covers exactly this path and pattern (qmd 2.5.3 prints "A collection already
147
+ * exists for this path and pattern:" and then `Name: <other> (qmd://<other>/)`).
148
+ * For unmanaged names, reconciliation skips its own add, prints a notice and
149
+ * carries on. HQ-managed name collisions remain fatal and captured. Before
150
+ * this, the duplicate aborted the whole `hq index sync`, so no collection was
151
+ * ever updated again on that machine (HQ-CLI-GJ).
152
+ */
153
+ export declare class QmdCollectionPathTakenError extends QmdExitError {
154
+ readonly existingName: string;
155
+ name: string;
156
+ constructor(message: string, args: string[], status: number | null, stdout: string, stderr: string, existingName: string);
157
+ }
158
+ /**
159
+ * hq or its qmd child was refused READ access to the HQ folder: EPERM/EACCES on
160
+ * `uv_cwd` (qmd's process.cwd() in the HQ root), or on a scandir/open of a path
161
+ * inside the HQ root. On macOS an EPERM there is the privacy (TCC) gate on a
162
+ * protected location such as Documents, Desktop or iCloud Drive. The message is
163
+ * the platform-specific remedy; the carrier is thrown marked expected, so the
164
+ * boundary prints it and skips capture (HQ-CLI-EJ, HQ-CLI-FV, HQ-CLI-BV,
165
+ * HQ-CLI-FF).
166
+ */
167
+ export declare class QmdAccessDeniedError extends QmdExitError {
168
+ readonly deniedPath: string;
169
+ readonly errnoCode: 'EPERM' | 'EACCES';
170
+ readonly syscall: string;
171
+ name: string;
172
+ constructor(message: string, args: string[], status: number | null, stdout: string, stderr: string, deniedPath: string, errnoCode: 'EPERM' | 'EACCES', syscall: string);
173
+ }
174
+ /**
175
+ * qmd could not create or write its own settings folder (QMD_CONFIG_DIR,
176
+ * $XDG_CONFIG_HOME/qmd or ~/.config/qmd): EPERM/EACCES on a path at or above
177
+ * that folder. The user's account cannot write there, typically because the
178
+ * folder was created by a command run with sudo. Thrown marked expected with
179
+ * the remedy as its message (HQ-CLI-GJ).
180
+ */
181
+ export declare class QmdConfigUnwritableError extends QmdExitError {
182
+ readonly configDir: string;
183
+ readonly errnoCode: 'EPERM' | 'EACCES';
184
+ name: string;
185
+ constructor(message: string, args: string[], status: number | null, stdout: string, stderr: string, configDir: string, errnoCode: 'EPERM' | 'EACCES');
186
+ }
187
+ /**
188
+ * qmd's SQLite index file is damaged (SQLITE_CORRUPT / SQLITE_NOTADB). qmd
189
+ * reports it as "sqlite-vec extension is unavailable ... Install Homebrew
190
+ * SQLite", which cannot fix a damaged file. hq names the file and the rebuild
191
+ * step instead. Still captured, because a trend of damaged index files would
192
+ * point at a writer bug (HQ-CLI-EJ).
193
+ */
194
+ export declare class QmdStoreCorruptError extends QmdExitError {
195
+ readonly storeFile: string | undefined;
196
+ name: string;
197
+ constructor(message: string, args: string[], status: number | null, stdout: string, stderr: string, storeFile: string | undefined);
198
+ }
199
+ type QmdPermissionFailure = {
200
+ code: 'EPERM' | 'EACCES';
201
+ syscall: string;
202
+ path?: string;
203
+ };
204
+ /**
205
+ * Parse an unambiguous fatal Node permission error from stderr, for example
206
+ * `Error: EPERM: operation not permitted, uv_cwd` or
207
+ * `[Error: EACCES: permission denied, mkdir '/home/u/.config/qmd']`.
208
+ * Incidental warnings and output containing another thrown error stay captured.
209
+ */
210
+ export declare function parseQmdPermissionFailure(text: string): QmdPermissionFailure | undefined;
211
+ /** Remedy for a refused read of the HQ folder, worded for the platform. */
212
+ export declare function qmdAccessDeniedMessage(deniedPath: string, code: 'EPERM' | 'EACCES', platform?: NodeJS.Platform): string;
213
+ /** Remedy for a qmd settings folder the user cannot write. */
214
+ export declare function qmdConfigUnwritableMessage(configDir: string, deniedPath: string, syscall: string, platform?: NodeJS.Platform): string;
144
215
  /**
145
216
  * qmd did NOT exit — it was KILLED BY A SIGNAL before it finished (spawnSync
146
217
  * reports `status: null` with a non-null `signal`). hq-cli passes qmd no timeout
@@ -553,6 +624,13 @@ export type ReconcileCollectionsOptions = {
553
624
  runner?: QmdProcessRunner;
554
625
  /** Test seam for the default-off collection-path repair rollout. */
555
626
  repairPathDrift?: boolean;
627
+ /** Where reconciliation notices go (default: process.stderr). */
628
+ writeStderr?: (text: string) => void;
629
+ /**
630
+ * File that records one-time notices already shown (default
631
+ * `<hqRoot>/.hq/search-index-notices.json`); `null` disables the record.
632
+ */
633
+ noticesFile?: string | null;
556
634
  };
557
635
  /**
558
636
  * Register expected collections that qmd does not yet know about, returning the
@@ -566,10 +644,16 @@ export type ReconcileCollectionsOptions = {
566
644
  * NOT a failure. Reconciliation still issues the `context add`, whose qmd-side
567
645
  * resyncConfig re-syncs YAML into SQLite and heals the divergence that provoked
568
646
  * the retry, then continues with later collections; such a pre-existing
569
- * collection is excluded from the returned list. Every other qmd failure still
570
- * propagates: the DIFFERENT path+pattern duplicate, a same-name duplicate that
571
- * named a different collection, a missing collection, a `context add` failure,
572
- * a missing/unbuilt qmd binary. HQ-CLI-Q (Sentry 7670823899).
647
+ * collection is excluded from the returned list.
648
+ *
649
+ * An unmanaged path+pattern duplicate is not fatal: the files are indexed under
650
+ * that name, but scoped search misses them. Print a notice, skip this add and
651
+ * its `context add`, and continue. It used to abort the whole sync, so
652
+ * `qmd update` never ran again on that machine (HQ-CLI-GJ).
653
+ *
654
+ * Every other qmd failure still propagates: a same-name duplicate that named a
655
+ * different collection, a missing collection, a `context add` failure, a
656
+ * missing/unbuilt qmd binary. HQ-CLI-Q (Sentry 7670823899).
573
657
  */
574
658
  export declare function reconcileCollections(hqRoot: string, options?: ReconcileCollectionsOptions): SearchCollection[];
575
659
  export declare function listRegisteredCollections(hqRoot: string, options?: RunQmdOptions): Set<string>;
@@ -109,6 +109,155 @@ export class QmdCollectionExistsError extends QmdExitError {
109
109
  this.collectionName = collectionName;
110
110
  }
111
111
  }
112
+ /**
113
+ * qmd's `collection add` exited non-zero because ANOTHER collection already
114
+ * covers exactly this path and pattern (qmd 2.5.3 prints "A collection already
115
+ * exists for this path and pattern:" and then `Name: <other> (qmd://<other>/)`).
116
+ * For unmanaged names, reconciliation skips its own add, prints a notice and
117
+ * carries on. HQ-managed name collisions remain fatal and captured. Before
118
+ * this, the duplicate aborted the whole `hq index sync`, so no collection was
119
+ * ever updated again on that machine (HQ-CLI-GJ).
120
+ */
121
+ export class QmdCollectionPathTakenError extends QmdExitError {
122
+ existingName;
123
+ name = 'QmdCollectionPathTakenError';
124
+ constructor(message, args, status, stdout, stderr, existingName) {
125
+ super(message, args, status, stdout, stderr);
126
+ this.existingName = existingName;
127
+ }
128
+ }
129
+ /**
130
+ * hq or its qmd child was refused READ access to the HQ folder: EPERM/EACCES on
131
+ * `uv_cwd` (qmd's process.cwd() in the HQ root), or on a scandir/open of a path
132
+ * inside the HQ root. On macOS an EPERM there is the privacy (TCC) gate on a
133
+ * protected location such as Documents, Desktop or iCloud Drive. The message is
134
+ * the platform-specific remedy; the carrier is thrown marked expected, so the
135
+ * boundary prints it and skips capture (HQ-CLI-EJ, HQ-CLI-FV, HQ-CLI-BV,
136
+ * HQ-CLI-FF).
137
+ */
138
+ export class QmdAccessDeniedError extends QmdExitError {
139
+ deniedPath;
140
+ errnoCode;
141
+ syscall;
142
+ name = 'QmdAccessDeniedError';
143
+ constructor(message, args, status, stdout, stderr, deniedPath, errnoCode, syscall) {
144
+ super(message, args, status, stdout, stderr);
145
+ this.deniedPath = deniedPath;
146
+ this.errnoCode = errnoCode;
147
+ this.syscall = syscall;
148
+ }
149
+ }
150
+ /**
151
+ * qmd could not create or write its own settings folder (QMD_CONFIG_DIR,
152
+ * $XDG_CONFIG_HOME/qmd or ~/.config/qmd): EPERM/EACCES on a path at or above
153
+ * that folder. The user's account cannot write there, typically because the
154
+ * folder was created by a command run with sudo. Thrown marked expected with
155
+ * the remedy as its message (HQ-CLI-GJ).
156
+ */
157
+ export class QmdConfigUnwritableError extends QmdExitError {
158
+ configDir;
159
+ errnoCode;
160
+ name = 'QmdConfigUnwritableError';
161
+ constructor(message, args, status, stdout, stderr, configDir, errnoCode) {
162
+ super(message, args, status, stdout, stderr);
163
+ this.configDir = configDir;
164
+ this.errnoCode = errnoCode;
165
+ }
166
+ }
167
+ /**
168
+ * qmd's SQLite index file is damaged (SQLITE_CORRUPT / SQLITE_NOTADB). qmd
169
+ * reports it as "sqlite-vec extension is unavailable ... Install Homebrew
170
+ * SQLite", which cannot fix a damaged file. hq names the file and the rebuild
171
+ * step instead. Still captured, because a trend of damaged index files would
172
+ * point at a writer bug (HQ-CLI-EJ).
173
+ */
174
+ export class QmdStoreCorruptError extends QmdExitError {
175
+ storeFile;
176
+ name = 'QmdStoreCorruptError';
177
+ constructor(message, args, status, stdout, stderr, storeFile) {
178
+ super(message, args, status, stdout, stderr);
179
+ this.storeFile = storeFile;
180
+ }
181
+ }
182
+ /**
183
+ * Parse an unambiguous fatal Node permission error from stderr, for example
184
+ * `Error: EPERM: operation not permitted, uv_cwd` or
185
+ * `[Error: EACCES: permission denied, mkdir '/home/u/.config/qmd']`.
186
+ * Incidental warnings and output containing another thrown error stay captured.
187
+ */
188
+ export function parseQmdPermissionFailure(text) {
189
+ const errors = text.match(/^\[?(?:[A-Za-z_$][\w$]*Error|Error):[^\r\n]*/gm);
190
+ if (errors?.length !== 1)
191
+ return undefined;
192
+ const match = /^\[?Error: (EPERM|EACCES): [^\n,]*, ([a-z_]+)(?: '([^'\n]+)')?(?:\]?\s*\{?)?$/.exec(errors[0]);
193
+ if (!match)
194
+ return undefined;
195
+ const code = match[1];
196
+ const syscall = match[2] ?? '';
197
+ return match[3] ? { code, syscall, path: match[3] } : { code, syscall };
198
+ }
199
+ function isSameOrInside(candidate, parent) {
200
+ const relative = path.relative(comparablePath(path.resolve(parent)), comparablePath(path.resolve(candidate)));
201
+ return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));
202
+ }
203
+ /** qmd's global settings folder for this env (no project-local `.qmd/`). */
204
+ function qmdGlobalConfigDir(env) {
205
+ const configPath = resolveQmdConfigPath({
206
+ env: { ...env, HOME: env.HOME ?? env.USERPROFILE ?? os.homedir() },
207
+ });
208
+ return configPath ? path.dirname(configPath) : undefined;
209
+ }
210
+ /** Remedy for a refused read of the HQ folder, worded for the platform. */
211
+ export function qmdAccessDeniedMessage(deniedPath, code, platform = process.platform) {
212
+ if (platform === 'darwin' && code === 'EPERM') {
213
+ return (`macOS blocked hq's search index from reading ${deniedPath} (operation not permitted). ` +
214
+ 'Your HQ folder is probably in a privacy-protected location such as Documents, Desktop or iCloud Drive, ' +
215
+ 'and the app that runs hq has not been given access to it. Allow it in System Settings > Privacy & Security > ' +
216
+ 'Full Disk Access (or Files and Folders), or move your HQ folder out of that location, then run: hq index sync');
217
+ }
218
+ if (platform === 'win32') {
219
+ return (`hq's search index could not read ${deniedPath} (access denied). Check that your Windows account can read ` +
220
+ 'that folder and that Controlled folder access or OneDrive is not blocking it, then run: hq index sync');
221
+ }
222
+ if (code === 'EPERM') {
223
+ // EPERM is not a file-mode refusal on Linux and other Unix systems: it comes
224
+ // from an immutable attribute or a security module.
225
+ return (`hq's search index could not read ${deniedPath} (operation not permitted). This is not a file permission ` +
226
+ 'setting: the folder or a file in it may be marked immutable (lsattr), or a security policy such as SELinux ' +
227
+ 'or AppArmor may be blocking it. Clear that block, then run: hq index sync');
228
+ }
229
+ return (`hq's search index could not read ${deniedPath} (permission denied). Give your user read access to that folder, ` +
230
+ 'then run: hq index sync');
231
+ }
232
+ /** Remedy for a qmd settings folder the user cannot write. */
233
+ export function qmdConfigUnwritableMessage(configDir, deniedPath, syscall, platform = process.platform) {
234
+ // A failed mkdir means the PARENT could not be written; anything else names the
235
+ // path itself.
236
+ const fixTarget = syscall === 'mkdir' ? path.dirname(deniedPath) : deniedPath;
237
+ const lead = `qmd could not save its search settings in ${configDir} because your user cannot write to ${fixTarget}, ` +
238
+ 'so hq could not register its search collections. ';
239
+ if (platform === 'win32') {
240
+ // Windows has no sudo; the usual cause is another account or an elevated prompt.
241
+ return (lead +
242
+ 'This usually happens when the folder was created by another account or from an administrator prompt. ' +
243
+ 'Set QMD_CONFIG_DIR to a folder owned by your Windows account where you have Full control ' +
244
+ '(Properties > Security), then run: hq index sync');
245
+ }
246
+ return (lead +
247
+ 'Set QMD_CONFIG_DIR to a folder owned by your user where you have write access, then run: hq index sync');
248
+ }
249
+ function qmdStoreFile(env, cwd) {
250
+ try {
251
+ const base = cwd ?? os.homedir();
252
+ if (env.INDEX_PATH)
253
+ return path.resolve(base, env.INDEX_PATH);
254
+ return path.join(resolveQmdStoreDir(env, base), 'index.sqlite');
255
+ }
256
+ catch {
257
+ return undefined;
258
+ }
259
+ }
260
+ const QMD_STORE_CORRUPT = /database disk image is malformed|\bSQLITE_CORRUPT\b|file is not a database|\bSQLITE_NOTADB\b/;
112
261
  /**
113
262
  * qmd did NOT exit — it was KILLED BY A SIGNAL before it finished (spawnSync
114
263
  * reports `status: null` with a non-null `signal`). hq-cli passes qmd no timeout
@@ -1051,7 +1200,7 @@ function isExpectedQmdCallerFailure(args, stderr) {
1051
1200
  return false;
1052
1201
  }
1053
1202
  /** Normalise a spawn result and raise the typed qmd failures. */
1054
- function finishRunQmd(result, bin, args, attribution) {
1203
+ function finishRunQmd(result, bin, args, attribution, context = {}) {
1055
1204
  const normalized = {
1056
1205
  status: result.status,
1057
1206
  stdout: result.stdout ?? '',
@@ -1250,6 +1399,41 @@ function finishRunQmd(result, bin, args, attribution) {
1250
1399
  if (isQmdModelDownloadError({ stderr: normalized.stderr, stdout: normalized.stdout })) {
1251
1400
  throw new QmdModelDownloadError(`qmd ${subcommand} could not run: a model download did not finish (its partial file disappeared)`, args, normalized.status, normalized.stdout, normalized.stderr);
1252
1401
  }
1402
+ // qmd died on a PERMISSION error from Node. Two shapes are the caller's
1403
+ // machine, not an hq defect, and get a typed carrier with a remedy:
1404
+ // - a read refused inside the HQ root, including qmd's own process.cwd()
1405
+ // (`uv_cwd`) in it: macOS privacy (TCC) on Documents/Desktop/iCloud, or
1406
+ // folder permissions (HQ-CLI-EJ, HQ-CLI-FV, HQ-CLI-BV, HQ-CLI-FF);
1407
+ // - qmd's settings folder cannot be created or written (HQ-CLI-GJ).
1408
+ // Any other permission failure keeps the generic, captured QmdExitError.
1409
+ // Reads qmd's own captured streams only, never the synthesized message.
1410
+ const permission = parseQmdPermissionFailure(normalized.stderr);
1411
+ if (permission) {
1412
+ const platform = context.platform ?? process.platform;
1413
+ const deniedPath = permission.syscall === 'uv_cwd' ? context.cwd : permission.path;
1414
+ // open alone does not distinguish a read from a write. Require a read
1415
+ // stack frame; ambiguous open failures remain reportable.
1416
+ const isRead = ['uv_cwd', 'scandir', 'stat', 'lstat'].includes(permission.syscall) ||
1417
+ (permission.syscall === 'open' && /^\s+at (?:async )?(?:Object\.)?readFile(?:Sync)?\b/m.test(normalized.stderr));
1418
+ if (isRead && deniedPath && context.cwd && isSameOrInside(deniedPath, context.cwd)) {
1419
+ throw markExpectedUserError(new QmdAccessDeniedError(qmdAccessDeniedMessage(deniedPath, permission.code, platform), args, normalized.status, normalized.stdout, normalized.stderr, deniedPath, permission.code, permission.syscall));
1420
+ }
1421
+ const configDir = qmdGlobalConfigDir(context.env ?? process.env);
1422
+ if (permission.path &&
1423
+ configDir &&
1424
+ // A recursive mkdir reports the first ANCESTOR it could not create, so an
1425
+ // ancestor counts only for mkdir.
1426
+ (isSameOrInside(permission.path, configDir) ||
1427
+ (permission.syscall === 'mkdir' && isSameOrInside(configDir, permission.path)))) {
1428
+ throw markExpectedUserError(new QmdConfigUnwritableError(qmdConfigUnwritableMessage(configDir, permission.path, permission.syscall, platform), args, normalized.status, normalized.stdout, normalized.stderr, configDir, permission.code));
1429
+ }
1430
+ }
1431
+ if (QMD_STORE_CORRUPT.test(`${normalized.stderr}\n${normalized.stdout}`)) {
1432
+ const storeFile = qmdStoreFile(context.env ?? process.env, context.cwd);
1433
+ throw new QmdStoreCorruptError(`qmd ${subcommand} could not run: hq's local search index${storeFile ? ` (${storeFile})` : ''} is damaged ` +
1434
+ '(SQLite reports the database file is malformed). It only holds data rebuilt from your HQ files: ' +
1435
+ 'delete that file, then run: hq index sync', args, normalized.status, normalized.stdout, normalized.stderr, storeFile);
1436
+ }
1253
1437
  if (/(?:collection|qmd:\/\/).*(?:not found|does not exist|unknown)|(?:not found|does not exist).*collection/i.test(classifyText)) {
1254
1438
  throw new QmdCollectionMissingError(message, args, normalized.status, normalized.stdout, normalized.stderr);
1255
1439
  }
@@ -1257,14 +1441,18 @@ function finishRunQmd(result, bin, args, attribution) {
1257
1441
  // owns (`Collection '<name>' already exists.`). Reconciliation treats this
1258
1442
  // exact shape as already-satisfied (HQ-CLI-Q). The DIFFERENT path+pattern
1259
1443
  // duplicate ("A collection already exists for this path and pattern:") names
1260
- // another collection and carries no quoted-name form, so it never matches and
1261
- // stays a plain QmdExitError. Colour is off under capture (qmd gates on
1262
- // isTTY) and any surrounding ANSI sits outside this substring, so the plain
1263
- // match is robust either way.
1444
+ // another collection and carries no quoted-name form, so it never matches
1445
+ // here; it is typed QmdCollectionPathTakenError below. Colour is off under
1446
+ // capture (qmd gates on isTTY) and any surrounding ANSI sits outside this
1447
+ // substring, so the plain match is robust either way.
1264
1448
  const alreadyExists = /Collection '([^']+)' already exists\./.exec(classifyText);
1265
1449
  if (alreadyExists) {
1266
1450
  throw new QmdCollectionExistsError(message, args, normalized.status, normalized.stdout, normalized.stderr, alreadyExists[1]);
1267
1451
  }
1452
+ const pathTaken = /A collection already exists for this path and pattern:[\s\S]*?Name:\s*(.+?)\s+\(qmd:\/\//.exec(classifyText);
1453
+ if (pathTaken?.[1]) {
1454
+ throw new QmdCollectionPathTakenError(message, args, normalized.status, normalized.stdout, normalized.stderr, pathTaken[1]);
1455
+ }
1268
1456
  const exitError = new QmdExitError(message, args, normalized.status, normalized.stdout, normalized.stderr);
1269
1457
  if (isExpectedQmdCallerFailure(args, normalized.stderr)) {
1270
1458
  throw markExpectedUserError(exitError);
@@ -1273,7 +1461,7 @@ function finishRunQmd(result, bin, args, attribution) {
1273
1461
  }
1274
1462
  function finishRunQmdWithDiagnostics(result, bin, args, options, attribution) {
1275
1463
  try {
1276
- return finishRunQmd(result, bin, args, attribution);
1464
+ return finishRunQmd(result, bin, args, attribution, { cwd: options.cwd, env: options.env, platform: options.platform });
1277
1465
  }
1278
1466
  catch (error) {
1279
1467
  if (error instanceof QmdExitError) {
@@ -1339,10 +1527,29 @@ export function runQmd(args, options = {}) {
1339
1527
  exists: options.exists,
1340
1528
  });
1341
1529
  }
1530
+ /**
1531
+ * List a folder for collection derivation. A path that is missing or is not a
1532
+ * folder (a file, or a symlink to one, named `knowledge` or `projects`) has
1533
+ * nothing to index, so it lists as empty instead of throwing ENOTDIR out of
1534
+ * the whole sync (HQ-CLI-ED). A refused read becomes the typed, expected
1535
+ * QmdAccessDeniedError with the platform remedy. Anything else still throws.
1536
+ */
1537
+ function readCollectionDir(directory) {
1538
+ try {
1539
+ return fs.readdirSync(directory, { withFileTypes: true });
1540
+ }
1541
+ catch (error) {
1542
+ const code = error?.code;
1543
+ if (code === 'ENOENT' || code === 'ENOTDIR')
1544
+ return [];
1545
+ if (code === 'EPERM' || code === 'EACCES') {
1546
+ throw markExpectedUserError(new QmdAccessDeniedError(qmdAccessDeniedMessage(directory, code), [], null, '', '', directory, code, 'scandir'));
1547
+ }
1548
+ throw error;
1549
+ }
1550
+ }
1342
1551
  function containsIndexedMarkdown(directory) {
1343
- if (!fs.existsSync(directory))
1344
- return false;
1345
- for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
1552
+ for (const entry of readCollectionDir(directory)) {
1346
1553
  const child = path.join(directory, entry.name);
1347
1554
  if (entry.isDirectory() && containsIndexedMarkdown(child))
1348
1555
  return true;
@@ -1352,9 +1559,7 @@ function containsIndexedMarkdown(directory) {
1352
1559
  return false;
1353
1560
  }
1354
1561
  function containsProjectSource(directory) {
1355
- if (!fs.existsSync(directory))
1356
- return false;
1357
- for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
1562
+ for (const entry of readCollectionDir(directory)) {
1358
1563
  const child = path.join(directory, entry.name);
1359
1564
  if (entry.isDirectory() && containsProjectSource(child))
1360
1565
  return true;
@@ -1367,9 +1572,7 @@ function containsProjectSource(directory) {
1367
1572
  export const ASSET_COLLECTION_MASK = '**/*.hqcloud';
1368
1573
  const ASSET_SCAN_SKIP_DIRS = new Set(['.git', 'node_modules']);
1369
1574
  function containsAssetPlaceholder(directory) {
1370
- if (!fs.existsSync(directory))
1371
- return false;
1372
- for (const entry of fs.readdirSync(directory, { withFileTypes: true })) {
1575
+ for (const entry of readCollectionDir(directory)) {
1373
1576
  const child = path.join(directory, entry.name);
1374
1577
  if (entry.isDirectory()) {
1375
1578
  if (!ASSET_SCAN_SKIP_DIRS.has(entry.name) && containsAssetPlaceholder(child))
@@ -1385,11 +1588,9 @@ function containsAssetPlaceholder(directory) {
1385
1588
  export function deriveCollections(hqRoot) {
1386
1589
  const root = path.resolve(hqRoot);
1387
1590
  const companiesDir = path.join(root, 'companies');
1388
- const companies = fs.existsSync(companiesDir)
1389
- ? fs.readdirSync(companiesDir, { withFileTypes: true })
1390
- .filter((entry) => entry.isDirectory())
1391
- .sort((a, b) => a.name.localeCompare(b.name))
1392
- : [];
1591
+ const companies = readCollectionDir(companiesDir)
1592
+ .filter((entry) => entry.isDirectory())
1593
+ .sort((a, b) => a.name.localeCompare(b.name));
1393
1594
  const collections = [];
1394
1595
  for (const entry of companies) {
1395
1596
  const knowledge = path.join(companiesDir, entry.name, 'knowledge');
@@ -1531,15 +1732,22 @@ function isPreviousHqManagedPath(hqRoot, collection, configuredPath) {
1531
1732
  * NOT a failure. Reconciliation still issues the `context add`, whose qmd-side
1532
1733
  * resyncConfig re-syncs YAML into SQLite and heals the divergence that provoked
1533
1734
  * the retry, then continues with later collections; such a pre-existing
1534
- * collection is excluded from the returned list. Every other qmd failure still
1535
- * propagates: the DIFFERENT path+pattern duplicate, a same-name duplicate that
1536
- * named a different collection, a missing collection, a `context add` failure,
1537
- * a missing/unbuilt qmd binary. HQ-CLI-Q (Sentry 7670823899).
1735
+ * collection is excluded from the returned list.
1736
+ *
1737
+ * An unmanaged path+pattern duplicate is not fatal: the files are indexed under
1738
+ * that name, but scoped search misses them. Print a notice, skip this add and
1739
+ * its `context add`, and continue. It used to abort the whole sync, so
1740
+ * `qmd update` never ran again on that machine (HQ-CLI-GJ).
1741
+ *
1742
+ * Every other qmd failure still propagates: a same-name duplicate that named a
1743
+ * different collection, a missing collection, a `context add` failure, a
1744
+ * missing/unbuilt qmd binary. HQ-CLI-Q (Sentry 7670823899).
1538
1745
  */
1539
1746
  export function reconcileCollections(hqRoot, options = {}) {
1540
1747
  const runOptions = { bin: options.bin, runner: options.runner, cwd: hqRoot };
1541
1748
  const registered = listRegisteredCollections(hqRoot, runOptions);
1542
1749
  const expected = deriveCollections(hqRoot);
1750
+ const managedNames = new Set(expected.map((collection) => collection.name));
1543
1751
  const repairPathDrift = options.repairPathDrift ?? false;
1544
1752
  const configured = repairPathDrift ? configuredCollections(hqRoot) : new Map();
1545
1753
  const stale = repairPathDrift
@@ -1565,6 +1773,31 @@ export function reconcileCollections(hqRoot, options = {}) {
1565
1773
  created.push(collection);
1566
1774
  }
1567
1775
  catch (error) {
1776
+ if (error instanceof QmdCollectionPathTakenError) {
1777
+ // Reserve the company-slug namespace, including -projects/-assets and
1778
+ // personal-knowledge, even when that company's folders are absent here.
1779
+ // A collision can otherwise expose one company's files under another.
1780
+ if (managedNames.has(error.existingName) || isSafeQmdCollectionName(error.existingName))
1781
+ throw error;
1782
+ // Shown once per folder and covering collection, so background syncs do
1783
+ // not repeat it on every run.
1784
+ const noticesFile = options.noticesFile === undefined ? defaultNoticesFile(hqRoot) : options.noticesFile;
1785
+ const noticeKey = `${collection.name}\u0000${error.existingName}\u0000${collection.path}`;
1786
+ const seenNotices = readSeenNotices(noticesFile);
1787
+ if (!seenNotices.has(noticeKey)) {
1788
+ const writeStderr = options.writeStderr ?? ((text) => process.stderr.write(text));
1789
+ const removalGuidance = isSafeQmdCollectionName(error.existingName)
1790
+ ? `run: qmd collection remove ${error.existingName}, then: hq index sync. `
1791
+ : `remove the qmd collection named ${JSON.stringify(error.existingName)} using qmd, then synchronize the HQ index again. `;
1792
+ writeStderr(`hq: ${collection.path} is already indexed by the qmd collection '${error.existingName}', ` +
1793
+ `so hq did not add it again as '${collection.name}'. Scoped search misses this folder until the other collection is removed. ` +
1794
+ `To use hq's name instead, ${removalGuidance}` +
1795
+ 'This notice is shown once.\n');
1796
+ seenNotices.add(noticeKey);
1797
+ writeSeenNotices(noticesFile, seenNotices);
1798
+ }
1799
+ continue;
1800
+ }
1568
1801
  // Only the exact same-name duplicate for THIS collection is already
1569
1802
  // satisfied. Anything else — including a same-name duplicate that names a
1570
1803
  // different collection — stays fatal.
@@ -1578,6 +1811,37 @@ export function reconcileCollections(hqRoot, options = {}) {
1578
1811
  }
1579
1812
  return created;
1580
1813
  }
1814
+ function isSafeQmdCollectionName(name) {
1815
+ return /^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(name);
1816
+ }
1817
+ function defaultNoticesFile(hqRoot) {
1818
+ return path.join(hqRoot, '.hq', 'search-index-notices.json');
1819
+ }
1820
+ /** Read the set of one-time reconcile notices already shown. Best-effort. */
1821
+ function readSeenNotices(file) {
1822
+ if (!file)
1823
+ return new Set();
1824
+ try {
1825
+ const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
1826
+ const shown = isRecord(parsed) && Array.isArray(parsed.shown) ? parsed.shown : [];
1827
+ return new Set(shown.filter((value) => typeof value === 'string'));
1828
+ }
1829
+ catch {
1830
+ return new Set();
1831
+ }
1832
+ }
1833
+ /** Record shown notices. Best-effort: a read-only `.hq/` only means the notice repeats. */
1834
+ function writeSeenNotices(file, shown) {
1835
+ if (!file)
1836
+ return;
1837
+ try {
1838
+ fs.mkdirSync(path.dirname(file), { recursive: true });
1839
+ fs.writeFileSync(file, `${JSON.stringify({ shown: [...shown].sort() }, null, 2)}\n`);
1840
+ }
1841
+ catch {
1842
+ /* the notice repeats next run; indexing is unaffected */
1843
+ }
1844
+ }
1581
1845
  export function listRegisteredCollections(hqRoot, options = {}) {
1582
1846
  const result = runQmd(['collection', 'list'], { ...options, cwd: options.cwd ?? hqRoot });
1583
1847
  return new Set([...result.stdout.matchAll(/qmd:\/\/([^/\s]+)/g)].map((match) => match[1]));