@indigoai-us/hq-cli 5.345.245 → 5.345.246

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 (113) hide show
  1. package/CHANGELOG.md +82 -0
  2. package/dist/command-catalog.generated.d.ts +93 -6
  3. package/dist/command-catalog.generated.js +114 -6
  4. package/dist/commands/bot.js +1 -1
  5. package/dist/commands/core-checkpoint-native.d.ts +5 -1
  6. package/dist/commands/core-checkpoint-native.js +13 -5
  7. package/dist/commands/deploy-comments.js +139 -0
  8. package/dist/commands/deploy-list.d.ts +5 -0
  9. package/dist/commands/deploy-list.js +8 -0
  10. package/dist/commands/dm.d.ts +4 -1
  11. package/dist/commands/dm.js +11 -2
  12. package/dist/commands/files.d.ts +11 -2
  13. package/dist/commands/files.js +48 -3
  14. package/dist/commands/lanes-loop.js +4 -1
  15. package/dist/commands/lanes.js +16 -5
  16. package/dist/commands/mesh.d.ts +2 -0
  17. package/dist/commands/mesh.js +26 -6
  18. package/dist/commands/reindex.js +2 -1
  19. package/dist/commands/rescue.d.ts +22 -1
  20. package/dist/commands/rescue.js +56 -9
  21. package/dist/commands/sources.d.ts +1 -1
  22. package/dist/commands/sources.js +1 -1
  23. package/dist/commands/storage.d.ts +15 -2
  24. package/dist/commands/storage.js +74 -7
  25. package/dist/hq-cloud-sync-runner/bin/sync-runner.js +232 -225
  26. package/dist/hq-cloud-sync-runner/package.json +1 -1
  27. package/dist/lib/agent-kit/mcp/tools.js +22 -0
  28. package/dist/lib/bot/jobs/hot-signal-sync.js +4 -1
  29. package/dist/lib/daemon/fleet-members-cache.d.ts +55 -0
  30. package/dist/lib/daemon/fleet-members-cache.js +266 -0
  31. package/dist/lib/daemon/handoff.d.ts +4 -0
  32. package/dist/lib/daemon/handoff.js +2 -1
  33. package/dist/lib/daemon/hook-requests.d.ts +2 -1
  34. package/dist/lib/daemon/hook-requests.js +19 -2
  35. package/dist/lib/daemon/install.d.ts +9 -1
  36. package/dist/lib/daemon/install.js +11 -2
  37. package/dist/lib/daemon/ops/policy.d.ts +23 -3
  38. package/dist/lib/daemon/ops/policy.js +62 -15
  39. package/dist/lib/daemon/run.js +12 -0
  40. package/dist/lib/daemon/server.d.ts +5 -0
  41. package/dist/lib/daemon/server.js +1 -1
  42. package/dist/lib/daemon/supervisor.d.ts +6 -0
  43. package/dist/lib/daemon/supervisor.js +31 -2
  44. package/dist/lib/doctor/checks/sync-runtime.js +8 -1
  45. package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
  46. package/dist/lib/flag-registry-worker-source.generated.js +1 -1
  47. package/dist/lib/hook-engine/coverage.d.ts +68 -0
  48. package/dist/lib/hook-engine/coverage.js +163 -0
  49. package/dist/lib/hook-engine/native-precompact-compatibility.json +1 -0
  50. package/dist/lib/hot-channels/signals-pass.d.ts +52 -2
  51. package/dist/lib/hot-channels/signals-pass.js +65 -3
  52. package/dist/lib/install/claude-targets.d.ts +6 -0
  53. package/dist/lib/install/claude-targets.js +9 -1
  54. package/dist/lib/lanes/reconcile-result.d.ts +1 -1
  55. package/dist/lib/lanes/reconcile.js +19 -4
  56. package/dist/lib/lanes/remote-control-lane.d.ts +6 -0
  57. package/dist/lib/lanes/remote-control-lane.js +10 -1
  58. package/dist/lib/lanes/spawn.d.ts +2 -0
  59. package/dist/lib/lanes/spawn.js +19 -3
  60. package/dist/lib/lanes/worker-env-scrub.d.ts +48 -0
  61. package/dist/lib/lanes/worker-env-scrub.js +146 -0
  62. package/dist/lib/lanes/worker-process.js +4 -1
  63. package/dist/lib/mesh/client.js +5 -1
  64. package/dist/lib/mesh/live/daemon/doctor.d.ts +9 -0
  65. package/dist/lib/mesh/live/daemon/doctor.js +51 -6
  66. package/dist/lib/mesh/live/daemon/install.d.ts +39 -0
  67. package/dist/lib/mesh/live/daemon/install.js +70 -0
  68. package/dist/lib/mesh/live/daemon/outbox-company.d.ts +47 -0
  69. package/dist/lib/mesh/live/daemon/outbox-company.js +77 -0
  70. package/dist/lib/mesh/live/daemon/run.d.ts +2 -0
  71. package/dist/lib/mesh/live/daemon/run.js +48 -3
  72. package/dist/lib/mesh/live/daemon/state.d.ts +5 -0
  73. package/dist/lib/mesh/live/daemon/system-unit.d.ts +21 -0
  74. package/dist/lib/mesh/live/daemon/system-unit.js +80 -0
  75. package/dist/lib/mesh/live/daemon/transcript-watch.d.ts +4 -1
  76. package/dist/lib/mesh/live/daemon/transcript-watch.js +42 -38
  77. package/dist/lib/mesh/live/direct-drain.js +3 -1
  78. package/dist/lib/mesh/live/emit.js +4 -2
  79. package/dist/lib/mesh/live/flush.d.ts +61 -0
  80. package/dist/lib/mesh/live/flush.js +434 -114
  81. package/dist/lib/mesh/live/paths.d.ts +10 -0
  82. package/dist/lib/mesh/live/paths.js +14 -0
  83. package/dist/lib/mesh/live/reporting-privacy.d.ts +41 -1
  84. package/dist/lib/mesh/live/reporting-privacy.js +81 -7
  85. package/dist/lib/mesh/live/spool.d.ts +171 -17
  86. package/dist/lib/mesh/live/spool.js +777 -62
  87. package/dist/lib/signals/engine.d.ts +82 -2
  88. package/dist/lib/signals/engine.js +389 -53
  89. package/dist/lib/signals/steps/extract.js +5 -0
  90. package/dist/lib/work-context/organize.d.ts +22 -4
  91. package/dist/lib/work-context/organize.js +50 -21
  92. package/dist/lib/work-context/paths.d.ts +6 -0
  93. package/dist/lib/work-context/paths.js +9 -0
  94. package/dist/lib/work-context/reconcile.d.ts +1 -1
  95. package/dist/lib/work-context/reconcile.js +1 -1
  96. package/dist/startup-registration.d.ts +14 -0
  97. package/dist/startup-registration.js +26 -0
  98. package/dist/utils/cli-telemetry.d.ts +6 -0
  99. package/dist/utils/cli-telemetry.js +154 -9
  100. package/dist/utils/github-tag-fallback.d.ts +7 -2
  101. package/dist/utils/github-tag-fallback.js +17 -8
  102. package/dist/utils/hq-core-source.d.ts +31 -0
  103. package/dist/utils/hq-core-source.js +144 -0
  104. package/dist/utils/interactive-caller.d.ts +6 -0
  105. package/dist/utils/interactive-caller.js +8 -0
  106. package/dist/utils/shipped-codex-hooks.d.ts +6 -4
  107. package/dist/utils/shipped-codex-hooks.js +22 -10
  108. package/dist/utils/vault-api.js +1 -0
  109. package/dist/utils/version-report.d.ts +3 -1
  110. package/dist/utils/version-report.js +13 -5
  111. package/docs/anywhere-runtime.md +2 -2
  112. package/package.json +8 -8
  113. package/scripts/check-function-manifest.mjs +99 -18
@@ -1,3 +1,4 @@
1
+ import * as fs from "node:fs";
1
2
  import { deployApiRequest } from "../lib/deploy-api.js";
2
3
  import { findDeployApp } from "../lib/deploy-apps.js";
3
4
  import { DEFAULT_HQ_ROOT, ensureCognitoToken } from "../utils/cognito-session.js";
@@ -179,6 +180,124 @@ async function toggleAction(appId, mode, options) {
179
180
  }
180
181
  console.log(options.json ? safeJson({ appId, commentsEnabled }) : `Comments turned ${mode} for ${appId}.`);
181
182
  }
183
+ /** Writes take exactly one explicit scope, like toggle and hq deploy events. */
184
+ function writeScopeHeaders(options) {
185
+ if (Boolean(options.company) === Boolean(options.personal)) {
186
+ throw new DeployCommentsError("Choose exactly one of --company <slug> or --personal.");
187
+ }
188
+ return options.personal ? { "X-HQ-Deploy-Scope": "personal" } : callerOrgHeaders(options.company);
189
+ }
190
+ async function writeError(response, action) {
191
+ const body = await response.json().catch(() => ({}));
192
+ const code = errorCode(body, response.status);
193
+ const prefix = `Could not ${action} (HTTP ${response.status}, ${code}).`;
194
+ switch (response.status) {
195
+ case 401:
196
+ return new DeployCommentsError(`${prefix} Run hq login and retry.`);
197
+ case 403:
198
+ return new DeployCommentsError(`${prefix} Only the app owner or an org admin can do this; check the scope.`);
199
+ case 404:
200
+ return new DeployCommentsError(`${prefix} Check the app and comment id and the scope.`);
201
+ case 429: {
202
+ const value = response.headers.get("Retry-After");
203
+ const retryAfter = value && /^\d+$/.test(value) ? value : "unknown";
204
+ return new DeployCommentsError(`${prefix} Retry-After: ${retryAfter} seconds.`);
205
+ }
206
+ default:
207
+ return new DeployCommentsError(prefix);
208
+ }
209
+ }
210
+ async function writeJson(token, route, method, body, headers, action) {
211
+ let response;
212
+ try {
213
+ response = await deployApiRequest(token, route, method, body, headers);
214
+ }
215
+ catch {
216
+ throw new DeployCommentsError(`Could not reach hq-deploy to ${action}; it may or may not have happened. Check with hq deploy comments list.`);
217
+ }
218
+ if (!response.ok)
219
+ throw await writeError(response, action);
220
+ return response.json().catch(() => ({}));
221
+ }
222
+ function replyText(options) {
223
+ if ((options.text === undefined) === (options.textFile === undefined)) {
224
+ throw new DeployCommentsError("Give the comment text with exactly one of --text or --text-file.");
225
+ }
226
+ let text = options.text;
227
+ if (options.textFile !== undefined) {
228
+ try {
229
+ text = fs.readFileSync(options.textFile, "utf8");
230
+ }
231
+ catch {
232
+ throw new DeployCommentsError("Could not read the --text-file.");
233
+ }
234
+ }
235
+ if (!text || text.trim().length === 0)
236
+ throw new DeployCommentsError("The comment text is empty.");
237
+ return text;
238
+ }
239
+ function parseAnchor(json) {
240
+ let anchor;
241
+ try {
242
+ anchor = JSON.parse(json);
243
+ }
244
+ catch {
245
+ throw new DeployCommentsError("--anchor-json is not valid JSON.");
246
+ }
247
+ if (typeof anchor !== "object" || anchor === null || Array.isArray(anchor)
248
+ || typeof anchor.mode !== "string") {
249
+ throw new DeployCommentsError("--anchor-json must be an object with a mode.");
250
+ }
251
+ return anchor;
252
+ }
253
+ function jsonObject(value, fallback) {
254
+ return typeof value === "object" && value !== null ? value : fallback;
255
+ }
256
+ async function replyAction(appNameOrId, options) {
257
+ const body = replyText(options);
258
+ if (options.replyTo !== undefined && options.anchorJson !== undefined) {
259
+ throw new DeployCommentsError("Choose one of --reply-to or --anchor-json, not both.");
260
+ }
261
+ const headers = writeScopeHeaders(options);
262
+ let anchor = { mode: "unanchored" };
263
+ if (options.anchorJson !== undefined)
264
+ anchor = parseAnchor(options.anchorJson);
265
+ const token = await ensureCognitoToken();
266
+ const appId = await resolveAppId(token, appNameOrId, headers);
267
+ if (options.replyTo !== undefined) {
268
+ const { comments } = await listComments(token, appId, headers);
269
+ const original = comments.find((entry) => entry.id === options.replyTo);
270
+ if (!original)
271
+ throw new DeployCommentsError(`Comment '${displayText(options.replyTo)}' was not found on that app.`);
272
+ if (typeof original.anchor !== "object" || original.anchor === null) {
273
+ throw new DeployCommentsError("That comment has no anchor to reply next to.");
274
+ }
275
+ anchor = original.anchor;
276
+ }
277
+ const payload = { body, anchor };
278
+ if (options.deployId !== undefined)
279
+ payload.deployId = options.deployId;
280
+ const created = await writeJson(token, `/api/apps/${encodeURIComponent(appId)}/manage/comments`, "POST", payload, headers, "add the comment");
281
+ if (options.json) {
282
+ console.log(safeJson(jsonObject(created, {})));
283
+ return;
284
+ }
285
+ const id = jsonObject(created, {}).id;
286
+ console.log(`Comment added to ${displayText(appId)}${typeof id === "string" ? ` (${displayText(id)})` : ""}.`);
287
+ }
288
+ async function resolveCommentAction(appNameOrId, commentId, options) {
289
+ const headers = writeScopeHeaders(options);
290
+ const status = options.reopen ? "open" : "resolved";
291
+ const token = await ensureCognitoToken();
292
+ const appId = await resolveAppId(token, appNameOrId, headers);
293
+ const route = `/api/apps/${encodeURIComponent(appId)}/manage/comments/${encodeURIComponent(commentId)}`;
294
+ const updated = await writeJson(token, route, "PATCH", { status }, headers, `mark the comment ${status}`);
295
+ if (options.json) {
296
+ console.log(safeJson(jsonObject(updated, { id: commentId, status })));
297
+ return;
298
+ }
299
+ console.log(`Comment ${displayText(commentId)} is ${status}.`);
300
+ }
182
301
  export function registerDeployCommentsCommand(deploy) {
183
302
  const comments = deploy.command("comments").description("Read and configure comments on your deployed apps");
184
303
  comments
@@ -201,5 +320,25 @@ export function registerDeployCommentsCommand(deploy) {
201
320
  .option("--personal", "use personal scope")
202
321
  .option("--json", "print the updated comments setting as JSON")
203
322
  .action((appId, mode, options) => run(() => toggleAction(appId, mode, options)));
323
+ comments
324
+ .command("reply <app>")
325
+ .description("Add a comment to an app as yourself, next to another comment or unanchored")
326
+ .option("--company <slug>", "company owning the app")
327
+ .option("--personal", "use personal scope")
328
+ .option("--text <text>", "the comment text")
329
+ .option("--text-file <path>", "read the comment text from a file")
330
+ .option("--reply-to <commentId>", "place the comment at that comment's anchor")
331
+ .option("--anchor-json <json>", "anchor object to use instead (default: unanchored)")
332
+ .option("--deploy-id <id>", "the deploy the comment is about")
333
+ .option("--json", "print the created comment as JSON")
334
+ .action((app, options) => run(() => replyAction(app, options)));
335
+ comments
336
+ .command("resolve <app> <commentId>")
337
+ .description("Mark a comment resolved, or open again with --reopen")
338
+ .option("--company <slug>", "company owning the app")
339
+ .option("--personal", "use personal scope")
340
+ .option("--reopen", "mark the comment open instead of resolved")
341
+ .option("--json", "print the updated comment as JSON")
342
+ .action((app, commentId, options) => run(() => resolveCommentAction(app, commentId, options)));
204
343
  }
205
344
  //# sourceMappingURL=deploy-comments.js.map
@@ -12,6 +12,11 @@ export interface DeployAppSummary {
12
12
  createdAt: string | null;
13
13
  updatedAt: string | null;
14
14
  lastVisitAt: string | null;
15
+ ownerId: string | null;
16
+ /** Gate fields, kept as hq-deploy sent them so callers can resolve the gate fail-closed. */
17
+ privateMode: unknown;
18
+ passwordProtected: unknown;
19
+ accessPolicy: unknown;
15
20
  }
16
21
  /** Public app base domain, derived from the deploy API host (api.<base>). */
17
22
  export declare function appBaseDomain(apiUrl?: string): string | null;
@@ -15,6 +15,10 @@ function resolveCompany(companyFlag) {
15
15
  throw new DeployListError("The company slug is not valid.");
16
16
  return slug;
17
17
  }
18
+ /** A gate field as hq-deploy sent it; only a missing field becomes null. */
19
+ function gate(value) {
20
+ return value === undefined ? null : value;
21
+ }
18
22
  function str(value) {
19
23
  return typeof value === "string" && value.length > 0 ? value : null;
20
24
  }
@@ -49,6 +53,10 @@ export function summarizeApp(app) {
49
53
  createdAt: str(app.createdAt),
50
54
  updatedAt: str(app.updatedAt),
51
55
  lastVisitAt: str(app.lastVisitAt),
56
+ ownerId: str(app.ownerId),
57
+ privateMode: gate(app.privateMode),
58
+ passwordProtected: gate(app.passwordProtected),
59
+ accessPolicy: gate(app.accessPolicy),
52
60
  };
53
61
  }
54
62
  export function matchesQuery(app, query) {
@@ -206,8 +206,11 @@ export declare function buildDmBody(args: {
206
206
  * There is no separate "person by email" route on the vault API, and a DM to
207
207
  * someone outside your contacts is a connection request anyway, which the
208
208
  * server holds without delivering files.
209
+ *
210
+ * The caller's own email is not a contact. `--attach` to that address uses
211
+ * the caller's person uid (JWT `custom:entityUid`, else the person lookup).
209
212
  */
210
- export declare function resolveDmPeerUid(token: string, recipient: string): Promise<string>;
213
+ export declare function resolveDmPeerUid(token: string, recipient: string, knownCallerUid?: string): Promise<string>;
211
214
  /**
212
215
  * Error text for an agent's `hq dm thread` read. The agent route has its own
213
216
  * refusals (hq-pro-core 1.165.0): 403 when the server predates it or the route
@@ -424,14 +424,23 @@ export function buildDmBody(args) {
424
424
  * There is no separate "person by email" route on the vault API, and a DM to
425
425
  * someone outside your contacts is a connection request anyway, which the
426
426
  * server holds without delivering files.
427
+ *
428
+ * The caller's own email is not a contact. `--attach` to that address uses
429
+ * the caller's person uid (JWT `custom:entityUid`, else the person lookup).
427
430
  */
428
- export async function resolveDmPeerUid(token, recipient) {
431
+ export async function resolveDmPeerUid(token, recipient, knownCallerUid) {
429
432
  const rcpt = detectRecipient(recipient);
430
433
  if (!rcpt)
431
434
  throw new Error(`Invalid recipient '${recipient}'.`);
432
435
  if (rcpt.toPersonUid)
433
436
  return rcpt.toPersonUid;
434
437
  const email = rcpt.toEmail.toLowerCase();
438
+ const me = callerFromToken(token);
439
+ if (me.email && me.email === email) {
440
+ if (knownCallerUid)
441
+ return knownCallerUid;
442
+ return callerUidForAttach(token);
443
+ }
435
444
  const res = await vaultApiFetch({ token, path: "/v1/notify/contacts" });
436
445
  if (!res.ok) {
437
446
  const err = (await res.json().catch(() => ({})));
@@ -1010,7 +1019,7 @@ async function runDmSend(recipient, message, rawOpts) {
1010
1019
  // sorted participant pair; the server lets either member read it.
1011
1020
  const callerUid = await callerUidForAttach(token);
1012
1021
  const scopeUid = personalScopeForCaller(callerUid);
1013
- const peerUid = await resolveDmPeerUid(token, recipient);
1022
+ const peerUid = await resolveDmPeerUid(token, recipient, callerUid);
1014
1023
  uploaded = await uploadDmAttachments({
1015
1024
  token,
1016
1025
  scopeUid,
@@ -162,10 +162,16 @@ export declare class FilesDeleteHttpError extends Error {
162
162
  readonly code?: string | undefined;
163
163
  constructor(status: number, message: string, code?: string | undefined);
164
164
  }
165
+ /** Client-side ceiling: more objects than this in one delete needs a typed confirmation. */
166
+ export declare const DELETE_CEILING_COUNT = 1000;
167
+ /** Why a previewed delete is over the client-side ceiling, or undefined. */
168
+ export declare function clientCeilingReason(preview: FilesDeleteResponse): string | undefined;
165
169
  /** Map a FilesDeleteHttpError to user-facing copy. */
166
170
  export declare function formatFilesDeleteError(err: FilesDeleteHttpError, prefix: string): string;
167
171
  /** Injectable yes/no confirmation seam (stubbed in tests). */
168
172
  export type ConfirmFn = (message: string) => Promise<boolean>;
173
+ /** Injectable free-text prompt seam for typed confirmations (stubbed in tests). */
174
+ export type PromptFn = (message: string) => Promise<string>;
169
175
  /**
170
176
  * POST /v1/files/delete. Throws FilesDeleteHttpError on any non-2xx so the one
171
177
  * caller renders a single consistent error path.
@@ -220,9 +226,12 @@ export declare function stripRedundantCompanyScope(prefix: string): {
220
226
  * `--company` (or is refused), or BECOMES the company when none was given.
221
227
  */
222
228
  export declare function companySlugFromAnchor(prefix: string, personal?: boolean): string | undefined;
223
- export declare function runFilesDelete(params: RunFilesDeleteParams, deps?: {
229
+ export interface RunFilesDeleteDeps {
224
230
  confirm?: ConfirmFn;
225
- }): Promise<void>;
231
+ prompt?: PromptFn;
232
+ isInteractive?: () => boolean;
233
+ }
234
+ export declare function runFilesDelete(params: RunFilesDeleteParams, deps?: RunFilesDeleteDeps): Promise<void>;
226
235
  export interface FileVersionRow {
227
236
  versionId: string;
228
237
  isLatest: boolean;
@@ -674,10 +674,10 @@ export function registerFilesCommand(program) {
674
674
  });
675
675
  files
676
676
  .command("delete <prefix>")
677
- .description("Delete vault objects by exact key or bounded prefix. A trailing slash expands recursively; use * for an explicit wildcard prefix. Always previews the exact count first; prompts for confirmation unless --yes. Use --personal to target your own personal vault instead of a company.")
677
+ .description("Delete vault objects by exact key or bounded prefix. A trailing slash expands recursively; use * for an explicit wildcard prefix. Always previews the exact count first; prompts for confirmation unless --yes. Over 1000 objects it asks you to type a confirmation in a terminal, and --yes does not skip that. Use --personal to target your own personal vault instead of a company.")
678
678
  .option("--dry-run", "List what WOULD be deleted without deleting anything")
679
679
  .option("--personal", "Target your own personal vault instead of a company vault (mutually exclusive with --company)")
680
- .option("-y, --yes", "Skip the confirmation prompt (for scripts)")
680
+ .option("-y, --yes", "Skip the confirmation prompt (for scripts); not above 1000 objects")
681
681
  .action(async (prefix, opts) => {
682
682
  try {
683
683
  const companySlug = files.opts().company;
@@ -1360,6 +1360,15 @@ export class FilesDeleteHttpError extends Error {
1360
1360
  this.name = "FilesDeleteHttpError";
1361
1361
  }
1362
1362
  }
1363
+ /** Client-side ceiling: more objects than this in one delete needs a typed confirmation. */
1364
+ export const DELETE_CEILING_COUNT = 1000;
1365
+ /** Why a previewed delete is over the client-side ceiling, or undefined. */
1366
+ export function clientCeilingReason(preview) {
1367
+ if (preview.matched > DELETE_CEILING_COUNT) {
1368
+ return `${preview.matched} objects is over the limit of ${DELETE_CEILING_COUNT} for one delete`;
1369
+ }
1370
+ return undefined;
1371
+ }
1363
1372
  /** Map a FilesDeleteHttpError to user-facing copy. */
1364
1373
  export function formatFilesDeleteError(err, prefix) {
1365
1374
  if (err.status === 401) {
@@ -1388,6 +1397,19 @@ function realConfirm(message) {
1388
1397
  });
1389
1398
  });
1390
1399
  }
1400
+ function realPrompt(message) {
1401
+ const rl = readline.createInterface({
1402
+ input: process.stdin,
1403
+ output: process.stdout,
1404
+ });
1405
+ return new Promise((resolve) => {
1406
+ rl.once("close", () => resolve(""));
1407
+ rl.question(message, (answer) => {
1408
+ resolve(answer);
1409
+ rl.close();
1410
+ });
1411
+ });
1412
+ }
1391
1413
  /**
1392
1414
  * POST /v1/files/delete. Throws FilesDeleteHttpError on any non-2xx so the one
1393
1415
  * caller renders a single consistent error path.
@@ -1604,6 +1626,8 @@ function normalizeCompanyFilePrefix(prefix, options = {}) {
1604
1626
  }
1605
1627
  export async function runFilesDelete(params, deps = {}) {
1606
1628
  const confirm = deps.confirm ?? realConfirm;
1629
+ const prompt = deps.prompt ?? realPrompt;
1630
+ const isInteractive = deps.isInteractive ?? (() => process.stdin.isTTY === true && process.stdout.isTTY === true);
1607
1631
  // Strip the local company anchor before preview/confirmation (HQ-8F/HQ-CA).
1608
1632
  // Personal keys are already bucket-relative and must keep any such anchor.
1609
1633
  // Deletion intentionally expands a folder spelling to a recursive glob, then
@@ -1661,12 +1685,16 @@ export async function runFilesDelete(params, deps = {}) {
1661
1685
  return;
1662
1686
  }
1663
1687
  const noun = preview.matched === 1 ? "object" : "objects";
1688
+ const overCeiling = clientCeilingReason(preview);
1664
1689
  if (params.dryRun) {
1665
1690
  console.log(chalk.green(`[dry-run] Would delete ${preview.matched} ${noun} under '${normalized}':`));
1666
1691
  printKeyPreview(preview);
1667
1692
  if (preview.skipped > 0) {
1668
1693
  console.log(chalk.dim(` (${preview.skipped} more under this prefix you can't delete would be left untouched)`));
1669
1694
  }
1695
+ if (overCeiling) {
1696
+ console.log(chalk.yellow(`A real delete would stop here: ${overCeiling}. It needs the confirmation typed in a terminal; --yes does not skip it.`));
1697
+ }
1670
1698
  console.log(chalk.dim("Nothing was deleted (--dry-run)."));
1671
1699
  return;
1672
1700
  }
@@ -1676,7 +1704,24 @@ export async function runFilesDelete(params, deps = {}) {
1676
1704
  if (preview.skipped > 0) {
1677
1705
  console.log(chalk.dim(` (${preview.skipped} more under this prefix you can't delete will be left untouched)`));
1678
1706
  }
1679
- if (!params.yes) {
1707
+ if (overCeiling) {
1708
+ if (!isInteractive()) {
1709
+ console.error(chalk.red(`Refusing to delete: ${overCeiling}. --yes does not apply above this limit. ` +
1710
+ "Run the command in a terminal and type the confirmation it asks for. Nothing was deleted."));
1711
+ process.exit(1);
1712
+ }
1713
+ const phrase = `delete ${preview.matched}`;
1714
+ const answer = await prompt(`${overCeiling}. ` +
1715
+ (params.personal
1716
+ ? "This removes them from your personal vault."
1717
+ : "This removes them from the shared vault for everyone.") +
1718
+ ` Type '${phrase}' to go ahead: `);
1719
+ if (answer.trim() !== phrase) {
1720
+ console.log(chalk.dim("Aborted — nothing was deleted."));
1721
+ return;
1722
+ }
1723
+ }
1724
+ else if (!params.yes) {
1680
1725
  const ok = await confirm(params.personal
1681
1726
  ? `Delete ${preview.matched} ${noun}? This removes them from your personal vault.`
1682
1727
  : `Delete ${preview.matched} ${noun}? This removes them from the shared vault for everyone.`);
@@ -13,6 +13,7 @@ import { HANDOFF_HOLD_CHOICES, clearLoopControllerPid, loopAdmissionPath, loopCo
13
13
  import { laneStories } from "../lib/lanes/stories.js";
14
14
  import { readLanesRegistryFlagFailOpen } from "../lib/lanes/registry-flag.js";
15
15
  import { LANE_LOOP_HANDOFF_REPAIR_FLAG } from "../lib/lanes/flag-keys.js";
16
+ import { laneWorkerEnv } from "../lib/lanes/worker-env-scrub.js";
16
17
  const LOOP_RUNS_REL = path.join("workspace", "lanes-runs");
17
18
  function loopRunDir(hqRoot, laneId) {
18
19
  return path.join(hqRoot, LOOP_RUNS_REL, laneId);
@@ -123,7 +124,9 @@ export function startLaneLoopControllerWithAdmissionLockHeld(ctx, laneId, initia
123
124
  if (!entry)
124
125
  throw new LanesError("loop_controller_entry_missing", "Cannot resolve the hq CLI entry point for the loop controller", { lane_id: laneId });
125
126
  const args = [entry, "runners", "_loop-worker", laneId];
126
- const env = { ...ctx.env, HQ_LANE_LOOP_CONTROLLER: "1", ...(initialAdmission ? { HQ_LANE_LOOP_INITIAL: "1" } : {}) };
127
+ // The loop controller lives as long as the loop and runs as the same user as
128
+ // its workers, so it starts without secret-bearing variables too.
129
+ const env = { ...laneWorkerEnv(ctx.env), HQ_LANE_LOOP_CONTROLLER: "1", ...(initialAdmission ? { HQ_LANE_LOOP_INITIAL: "1" } : {}) };
127
130
  const child = ctx.spawnProcess
128
131
  ? ctx.spawnProcess(liveNodeBinary(), args, { cwd: ctx.hqRoot(), detached: true, windowsHide: true, stdio: ["ignore", 1, 2], env })
129
132
  : spawn(liveNodeBinary(), args, { cwd: ctx.hqRoot(), detached: true, stdio: "ignore", env });
@@ -35,6 +35,7 @@ import { registerLaneRepoMergeHoldCommand } from "./lanes-hold.js";
35
35
  import { registerLaneReviewCommand } from "./lanes-review.js";
36
36
  import { ensureCognitoToken } from "../utils/cognito-session.js";
37
37
  import { withCliFeatureUsed } from "../utils/cli-telemetry.js";
38
+ import { isNonInteractiveLoginError } from "../utils/interactive-caller.js";
38
39
  import { resolveLanesHqRoot } from "../lib/lanes/hq-root.js";
39
40
  import { registerLaneSessionStartCommand } from "./lanes-session-start.js";
40
41
  import { registerLanesLinkCommand } from "./lanes-link.js";
@@ -10772,11 +10773,21 @@ async function runReconcile(ctx, opts, recoverQueuedMessages) {
10772
10773
  });
10773
10774
  }
10774
10775
  catch (error) {
10775
- const code = error instanceof LanesError ? error.error : "lead_autopilot_registry_sync_failed";
10776
- const message = error instanceof Error ? error.message : String(error);
10777
- summary.ok = false;
10778
- summary.errors.push({ code, message });
10779
- process.stderr.write(`hq lanes autopilot registry: ${message}\n`);
10776
+ if (isNonInteractiveLoginError(error)) {
10777
+ // Signed out: there is no Outpost list to read and nothing to sync.
10778
+ // The daemon already reports this unit as waiting for sign-in, so the
10779
+ // pass records a note and stays healthy instead of failing every 15 s.
10780
+ summary.notes ??= [];
10781
+ summary.notes.push("Lead autopilot registry sync skipped: not signed in");
10782
+ process.stderr.write("hq lanes autopilot registry: note: skipped, not signed in\n");
10783
+ }
10784
+ else {
10785
+ const code = error instanceof LanesError ? error.error : "lead_autopilot_registry_sync_failed";
10786
+ const message = error instanceof Error ? error.message : String(error);
10787
+ summary.ok = false;
10788
+ summary.errors.push({ code, message });
10789
+ process.stderr.write(`hq lanes autopilot registry: ${message}\n`);
10790
+ }
10780
10791
  }
10781
10792
  }
10782
10793
  let autopilot;
@@ -96,6 +96,8 @@ export declare function runDaemonStatus(opts: {
96
96
  daemonPid: number;
97
97
  pid?: number;
98
98
  } | null;
99
+ /** Linux: directory holding the box's system units (tests pass a fake root). */
100
+ systemUnitDir?: string;
99
101
  }): Promise<void>;
100
102
  /** Work Mesh health report: `hq daemon doctor` (and the retiring `hq mesh daemon doctor`). */
101
103
  export declare function runMeshDaemonDoctor(opts: {
@@ -40,9 +40,10 @@ import { generateUlid } from "../lib/mesh/live/ulid.js";
40
40
  import { readLegacyBacklogForMode } from "../lib/mesh/live/emit-replay.js";
41
41
  import { resolveMeshEmitMode, writeMeshConfigMode, } from "../lib/mesh/live/daemon/mode.js";
42
42
  import { workMeshRoot } from "../lib/mesh/live/paths.js";
43
- import { buildInstallPaths, daemonServiceIsLoaded, daemonServiceStatus, detectPlatform, installDaemonIfStale, installDaemonService, resolveAbsoluteNodeBinary, resolveRunningCliEntry, uninstallDaemonService, installedUnitHqRoot, } from "../lib/mesh/live/daemon/install.js";
43
+ import { buildInstallPaths, daemonServiceIsLoaded, daemonServiceStatus, detectPlatform, installDaemonIfStale, installDaemonService, MESH_DAEMON_SYSTEM_UNIT_EXIT, meshSystemUnitBlockingInstall, meshSystemUnitInChargeMessage, resolveAbsoluteNodeBinary, resolveRunningCliEntry, uninstallDaemonService, installedUnitHqRoot, } from "../lib/mesh/live/daemon/install.js";
44
44
  import { findAncestorHqRoot, resolveIfStaleHqRoot, resolveInstallHqRoot, } from "../lib/mesh/live/daemon/config.js";
45
45
  import { daemonDir as meshDaemonDir } from "../lib/mesh/live/daemon/paths.js";
46
+ import { readMeshSystemUnitState } from "../lib/mesh/live/daemon/system-unit.js";
46
47
  import { collectDaemonDoctor, formatCliIdentityLines, formatDaemonDoctor, } from "../lib/mesh/live/daemon/doctor.js";
47
48
  import { readDaemonState } from "../lib/mesh/live/daemon/state.js";
48
49
  import { defaultRunCommand } from "../lib/service-manager/launchd.js";
@@ -2094,7 +2095,8 @@ async function runContextOrganize(opts) {
2094
2095
  fail("`--session <sid>` is required and must be a valid session id");
2095
2096
  }
2096
2097
  const root = workContextHomeRoot();
2097
- // Cancel / timeout / incapable → leave unresolved; never invent a project.
2098
+ // Cancel / timeout / incapable → no project is chosen and the ask is not
2099
+ // repeated; a session that has its company keeps it (needs_project).
2098
2100
  if (opts.cancel || opts.settle) {
2099
2101
  const reason = opts.settle === "timeout"
2100
2102
  ? "timeout"
@@ -2106,7 +2108,7 @@ async function runContextOrganize(opts) {
2106
2108
  console.log(JSON.stringify({ ok: true, action: "settle", reason, state }, null, opts.machine ? 0 : 2));
2107
2109
  return;
2108
2110
  }
2109
- console.log(`Work mesh: session ${sessionId} left unresolved (${reason}); ask will not repeat.`);
2111
+ console.log(`Work mesh: session ${sessionId} settled as ${state?.contextStatus ?? "unknown"} (${reason}); ask will not repeat.`);
2110
2112
  return;
2111
2113
  }
2112
2114
  const isList = opts.list ||
@@ -3065,8 +3067,8 @@ export function registerMeshCommand(program, deps = {}) {
3065
3067
  .option("--create-project <title>", "Create a new project then bind")
3066
3068
  .option("--create-task <title>", "Create a new task on the session project then bind")
3067
3069
  .option("--untracked", "Mark the session untracked (local receipt only)")
3068
- .option("--cancel", "Settle ask without binding (leave unresolved; never repeat)")
3069
- .option("--settle <reason>", "Settle ask: cancelled|timeout|incapable (leave unresolved)")
3070
+ .option("--cancel", "Settle ask without binding a project (keeps the company; never repeat)")
3071
+ .option("--settle <reason>", "Settle ask: cancelled|timeout|incapable (keeps the company; never repeat)")
3070
3072
  .option("--offline", "Do not fetch candidates / submit to server")
3071
3073
  .option("--json", "Print machine-readable JSON")
3072
3074
  .option("--machine", "Compact JSON on stdout")
@@ -3253,6 +3255,20 @@ async function runDaemonRun(opts = {}) {
3253
3255
  });
3254
3256
  }
3255
3257
  async function runDaemonInstall(opts) {
3258
+ // A Linux box whose Work Mesh runs from /etc/systemd/system/hq-mesh-daemon.service:
3259
+ // a user unit would start a second daemon that crash-loops on the pid lock.
3260
+ const systemUnit = meshSystemUnitBlockingInstall({ platform: detectPlatform(), systemUser: opts.systemUser });
3261
+ if (systemUnit) {
3262
+ const message = meshSystemUnitInChargeMessage(systemUnit);
3263
+ if (opts.json) {
3264
+ console.log(JSON.stringify({ ok: false, action: "refused", reason: "system-unit", systemUnit, message }, null, 2));
3265
+ }
3266
+ else {
3267
+ console.error(message);
3268
+ }
3269
+ process.exitCode = MESH_DAEMON_SYSTEM_UNIT_EXIT;
3270
+ return;
3271
+ }
3256
3272
  // `hq daemon` runs mesh on this machine: installing a second unit would run it twice.
3257
3273
  // An explicit --hq-root is verified the same way as below and saved for the daemon.
3258
3274
  const explicitRoot = opts.hqRoot ? resolveInstallHqRoot({ explicit: opts.hqRoot }).root : undefined;
@@ -3355,11 +3371,14 @@ async function runDaemonUninstall(opts) {
3355
3371
  }
3356
3372
  export async function runDaemonStatus(opts, deps = {}) {
3357
3373
  const paths = deps.paths ?? buildInstallPaths({});
3374
+ const run = deps.run ?? defaultRunCommand;
3358
3375
  const result = daemonServiceStatus({
3359
3376
  platform: deps.platform ?? detectPlatform(),
3360
3377
  paths,
3361
- isLoaded: daemonServiceIsLoaded(deps.run ?? defaultRunCommand, deps.uid),
3378
+ isLoaded: daemonServiceIsLoaded(run, deps.uid),
3362
3379
  hqDaemonMesh: (deps.hqDaemonMesh ?? (() => hqDaemonMeshService(paths.home)))(),
3380
+ systemUnitDir: deps.systemUnitDir,
3381
+ systemUnitState: () => readMeshSystemUnitState(run),
3363
3382
  });
3364
3383
  const state = readDaemonState(paths.daemonDir);
3365
3384
  const presenceRefusal = state?.presenceRefusal ?? null;
@@ -3376,6 +3395,7 @@ export async function runDaemonStatus(opts, deps = {}) {
3376
3395
  ...(result.recordedHqRoot !== undefined ? { hqRoot: result.recordedHqRoot } : {}),
3377
3396
  ...(result.rootValid !== undefined ? { rootValid: result.rootValid } : {}),
3378
3397
  ...(result.notice ? { notice: result.notice } : {}),
3398
+ ...(result.systemUnit ? { systemUnit: result.systemUnit } : {}),
3379
3399
  mqttState: state?.mqttState,
3380
3400
  presenceRefusal,
3381
3401
  }, null, 2));
@@ -37,6 +37,7 @@ import { reindex, rescue } from '@indigoai-us/hq-cloud';
37
37
  import { trustHqRuntimeHooks } from '../utils/hook-trust.js';
38
38
  import { findHqRoot } from '../utils/manifest.js';
39
39
  import { guardLargeFiles } from '../utils/large-file-guard.js';
40
+ import { resolveHqCoreSource } from '../utils/hq-core-source.js';
40
41
  import { liveProcessCwds, recentTranscriptCwds, sessionOwnerReason, } from '../lib/core-utils/worktree-session-owner.js';
41
42
  const HOOK_EVENTS = ['SessionStart', 'UserPromptSubmit', 'PreToolUse'];
42
43
  const BYPASS_MODE = 'bypassPermissions';
@@ -587,7 +588,7 @@ function repairExtremeHookDrift(hqRoot, allowRepair = true, timeoutLimitMs) {
587
588
  try {
588
589
  const result = runSilently(() => rescue({
589
590
  hqRoot,
590
- source: 'indigoai-us/hq-core',
591
+ source: resolveHqCoreSource().repo,
591
592
  ref: installedCoreRef(hqRoot),
592
593
  paths: ['.claude'],
593
594
  assumeYes: true,
@@ -20,7 +20,8 @@
20
20
  * `HQ_NO_UPDATE_CHECK=1`; always best-effort.
21
21
  */
22
22
  import { Command } from 'commander';
23
- import { retrustCodexHooksAfterRescue } from '../utils/hook-trust.js';
23
+ import { retrustCodexHooksAfterRescue, trustCodexUserHooks } from '../utils/hook-trust.js';
24
+ import { reconcileHookRegistrations } from '../lib/hook-engine/reconcile.js';
24
25
  import { repairDanglingReleaseLinks } from '../lib/doctor/checks/release-links.js';
25
26
  import { type GitHubLookupDeps } from '../utils/github-tag-fallback.js';
26
27
  export interface RescueTarget {
@@ -38,6 +39,13 @@ export declare function resolveRescueTarget(opts: {
38
39
  source?: string;
39
40
  ref?: string;
40
41
  }, latestTag?: string): RescueTarget;
42
+ /**
43
+ * The GitHub token to hand the rescue script, which clones and downloads from
44
+ * the HQ_CORE_SOURCE web and codeload bases. Exported for tests. Returns
45
+ * undefined unless both bases are GitHub hosts, so a GitHub token never
46
+ * reaches an overridden non-GitHub host.
47
+ */
48
+ export declare function rescueScriptToken(token: string | undefined): string | undefined;
41
49
  /**
42
50
  * Whether this invocation should try the CLI self-update. Pure + exported for
43
51
  * tests. A dry-run (`--check`) must not mutate the global install, and
@@ -54,6 +62,19 @@ export declare function shouldAttemptSelfUpdate(opts: {
54
62
  * changes the rescue's exit status, because the core update itself succeeded.
55
63
  */
56
64
  export declare function retrustHooksAfterRescue(hqRoot: string, retrust?: typeof retrustCodexHooksAfterRescue): Promise<void>;
65
+ /**
66
+ * Re-plan HQ's hook registrations after a rescue that changed files on disk,
67
+ * the same step `hq reindex` runs. The registration that points an event at
68
+ * the new core lives partly outside the HQ root (the user-scope Codex
69
+ * hooks.json), so a core apply never replaces it. Without this step, an event
70
+ * whose coverage hold now applies to the files the core apply put on disk (for
71
+ * example a Stop or SubagentStop the native engine does not model for the new
72
+ * adapter) stays on the new core and is refused natively on every call until
73
+ * someone runs `hq reindex` by hand. Exported for tests. Best-effort: a failure
74
+ * leaves the current registrations in place and is reported, but never changes
75
+ * the rescue's exit status, because the core update itself succeeded.
76
+ */
77
+ export declare function reconcileHooksAfterRescue(hqRoot: string, reconcile?: (root: string) => ReturnType<typeof reconcileHookRegistrations>, trust?: typeof trustCodexUserHooks): Promise<void>;
57
78
  /**
58
79
  * Repair HQ-managed release links (`.agents/skills`, `.codex/claude`, ...)
59
80
  * that do not resolve after a rescue, for example because they were laid at