@indigoai-us/hq-cli 5.345.170 → 5.345.171

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 (111) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/assets/scaffold/core/scripts/hq-delegate-send.sh +1 -1
  3. package/dist/command-catalog.generated.d.ts +132 -5
  4. package/dist/command-catalog.generated.js +164 -6
  5. package/dist/commands/access.d.ts +32 -1
  6. package/dist/commands/access.js +112 -3
  7. package/dist/commands/agent-kit.d.ts +1 -1
  8. package/dist/commands/agent-kit.js +3 -1
  9. package/dist/commands/agents.js +2 -1
  10. package/dist/commands/bot.d.ts +3 -0
  11. package/dist/commands/bot.js +137 -14
  12. package/dist/commands/cloud.d.ts +58 -1
  13. package/dist/commands/cloud.js +219 -5
  14. package/dist/commands/core-company-index-scope-flag.d.ts +8 -1
  15. package/dist/commands/core-company-index-scope-flag.js +9 -2
  16. package/dist/commands/core-delegate-w1b.js +5 -2
  17. package/dist/commands/core-dm-bind-native.js +19 -4
  18. package/dist/commands/core-rebuild-index-fast.js +24 -6
  19. package/dist/commands/core.js +18 -6
  20. package/dist/commands/dm.d.ts +17 -3
  21. package/dist/commands/dm.js +121 -26
  22. package/dist/commands/integrations-api.d.ts +4 -0
  23. package/dist/commands/integrations-api.js +18 -2
  24. package/dist/commands/integrations-connect.d.ts +10 -3
  25. package/dist/commands/integrations-connect.js +70 -6
  26. package/dist/commands/integrations-core.d.ts +23 -0
  27. package/dist/commands/integrations-core.js +100 -0
  28. package/dist/commands/integrations-manage.js +8 -1
  29. package/dist/commands/integrations.js +49 -5
  30. package/dist/commands/lanes-loop.d.ts +20 -0
  31. package/dist/commands/lanes-loop.js +69 -11
  32. package/dist/commands/lanes.js +9 -1
  33. package/dist/commands/rescue.d.ts +9 -0
  34. package/dist/commands/rescue.js +31 -0
  35. package/dist/commands/run.js +115 -40
  36. package/dist/commands/scan.d.ts +5 -1
  37. package/dist/commands/scan.js +16 -4
  38. package/dist/commands/secrets.js +50 -9
  39. package/dist/hq-cloud-sync-runner/bin/sync-runner.js +2367 -2109
  40. package/dist/hq-cloud-sync-runner/package.json +1 -1
  41. package/dist/lib/agent-kit/inbox-state.d.ts +17 -0
  42. package/dist/lib/agent-kit/inbox-state.js +41 -20
  43. package/dist/lib/agent-kit/kit-config.d.ts +2 -0
  44. package/dist/lib/agent-kit/kit-config.js +6 -0
  45. package/dist/lib/agent-kit/mcp/tools.js +12 -5
  46. package/dist/lib/agent-kit/run/heartbeat.d.ts +6 -3
  47. package/dist/lib/agent-kit/run/heartbeat.js +6 -3
  48. package/dist/lib/agent-kit/run/inbox.d.ts +8 -3
  49. package/dist/lib/agent-kit/run/inbox.js +42 -10
  50. package/dist/lib/agent-kit/run/request-timeout.d.ts +26 -0
  51. package/dist/lib/agent-kit/run/request-timeout.js +51 -0
  52. package/dist/lib/bot/api.d.ts +1 -1
  53. package/dist/lib/bot/config.d.ts +10 -0
  54. package/dist/lib/bot/config.js +17 -1
  55. package/dist/lib/bot/fleet-local.d.ts +127 -0
  56. package/dist/lib/bot/fleet-local.js +638 -0
  57. package/dist/lib/bot/index.d.ts +1 -0
  58. package/dist/lib/bot/index.js +1 -0
  59. package/dist/lib/bot/local-config.d.ts +3 -2
  60. package/dist/lib/bot/local-config.js +5 -2
  61. package/dist/lib/bot/promote.d.ts +10 -0
  62. package/dist/lib/bot/promote.js +3 -2
  63. package/dist/lib/bot/runtime/index.js +8 -4
  64. package/dist/lib/bot/runtime/scratch-dir.d.ts +24 -0
  65. package/dist/lib/bot/runtime/scratch-dir.js +41 -0
  66. package/dist/lib/caller-principal.d.ts +4 -0
  67. package/dist/lib/caller-principal.js +40 -0
  68. package/dist/lib/capacity/collectors/grok.js +8 -2
  69. package/dist/lib/cli-flag-keys.d.ts +2 -0
  70. package/dist/lib/cli-flag-keys.js +2 -0
  71. package/dist/lib/daemon/catalog.js +4 -1
  72. package/dist/lib/daemon/sync-core-canary.d.ts +3 -0
  73. package/dist/lib/daemon/sync-core-canary.js +8 -3
  74. package/dist/lib/doctor/checks/release-links.d.ts +62 -1
  75. package/dist/lib/doctor/checks/release-links.js +188 -2
  76. package/dist/lib/doctor/fix/apply.js +54 -0
  77. package/dist/lib/doctor/fix/remediation.d.ts +8 -1
  78. package/dist/lib/doctor/fix/remediation.js +22 -0
  79. package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
  80. package/dist/lib/flag-registry-worker-source.generated.js +1 -1
  81. package/dist/lib/index-render/index.d.ts +9 -0
  82. package/dist/lib/index-render/index.js +65 -5
  83. package/dist/lib/index-render/session-scope.d.ts +69 -0
  84. package/dist/lib/index-render/session-scope.js +279 -0
  85. package/dist/lib/lanes/admission.js +7 -20
  86. package/dist/lib/lanes/reconcile.js +13 -15
  87. package/dist/lib/lanes/stale-lock.d.ts +50 -0
  88. package/dist/lib/lanes/stale-lock.js +105 -0
  89. package/dist/lib/lanes/store.js +11 -76
  90. package/dist/lib/notify-recipient.d.ts +10 -4
  91. package/dist/lib/notify-recipient.js +16 -4
  92. package/dist/lib/secret-input-link.d.ts +42 -0
  93. package/dist/lib/secret-input-link.js +93 -0
  94. package/dist/lib/secret-scan/range.d.ts +57 -0
  95. package/dist/lib/secret-scan/range.js +266 -0
  96. package/dist/lib/secret-scan/repo-config.d.ts +18 -3
  97. package/dist/lib/secret-scan/repo-config.js +135 -2
  98. package/dist/run/script-bound-schema.d.ts +27 -0
  99. package/dist/run/script-bound-schema.js +97 -0
  100. package/dist/secrets-env-action.d.ts +2 -0
  101. package/dist/secrets-env-action.js +7 -2
  102. package/dist/utils/cognito-session.d.ts +3 -30
  103. package/dist/utils/cognito-session.js +2 -100
  104. package/dist/utils/machine-principal-state.d.ts +38 -0
  105. package/dist/utils/machine-principal-state.js +110 -0
  106. package/dist/utils/safe-link.js +9 -0
  107. package/dist/utils/script-bound-exec.d.ts +158 -0
  108. package/dist/utils/script-bound-exec.js +568 -0
  109. package/dist/utils/sync-watchdog.d.ts +92 -0
  110. package/dist/utils/sync-watchdog.js +250 -0
  111. package/package.json +8 -8
@@ -14,6 +14,7 @@
14
14
  */
15
15
  import { Command } from "commander";
16
16
  import { type ConflictStrategy, type EntityContext, type MembershipSyncConfig, type SyncMode, type PullScope, type ExplicitGrant, type ShareOptions, type VaultServiceConfig } from "@indigoai-us/hq-cloud";
17
+ import { withSyncWatchdog, type SyncWatchdogLimits } from "../utils/sync-watchdog.js";
17
18
  import { type BannerLevel } from "../lib/narrow-hint-banner.js";
18
19
  import { type PlanLimitRefusalSummary } from "../lib/billing/plan-limit-refusals.js";
19
20
  /**
@@ -45,7 +46,54 @@ export declare class SyncExitError extends Error {
45
46
  * deliberately duck-typed so hq-cli remains compatible while hq-cloud and the
46
47
  * CLI are released independently.
47
48
  */
48
- export declare function formatSyncFailure(err: unknown): string;
49
+ export declare function formatSyncFailure(err: unknown, ctx?: {
50
+ hqRoot?: string;
51
+ cwd?: string;
52
+ companySlug?: string;
53
+ }): string;
54
+ /**
55
+ * The `.hqinclude` line that admits a named path: its HQ-relative spelling,
56
+ * with a trailing slash for a folder. Resolved the way the push resolver
57
+ * reads a named path (absolute, HQ root, the company folder, then the current
58
+ * directory); a path that resolves nowhere inside the HQ tree is suggested as
59
+ * typed.
60
+ */
61
+ export declare function hqincludeEntryFor(namedPath: string, ctx?: {
62
+ hqRoot?: string;
63
+ cwd?: string;
64
+ companySlug?: string;
65
+ }): string;
66
+ /**
67
+ * Re-render hq-cloud's UnreachablePushPathsError with the real blocker per
68
+ * path (feedback_6afa6ce4). The upstream message always ends with advice
69
+ * about symlinks, so a path left out of `.hqinclude` read as a symlink
70
+ * problem. This names the `.hqinclude` line to add, and keeps the symlink
71
+ * advice only for reasons that are about links or paths outside the company
72
+ * folder. Returns null for any other error.
73
+ */
74
+ export declare function formatUnreachablePushPaths(err: unknown, ctx?: {
75
+ hqRoot?: string;
76
+ cwd?: string;
77
+ companySlug?: string;
78
+ }): string | null;
79
+ /**
80
+ * Lines naming the blocker when a push with user-named paths uploaded nothing
81
+ * and every not-uploaded file fell outside write scope (feedback_5baccb9e).
82
+ * The summary before this gave a count and the granted prefixes; this names
83
+ * each requested path as the thing no write grant covers and points at
84
+ * `hq access`, which reports the ACL row that blocks it.
85
+ */
86
+ export declare function explicitPushBlockedLines(input: {
87
+ userNamedPaths: boolean;
88
+ namedPaths: readonly string[];
89
+ filesUploaded: number;
90
+ filesExcludedByScope: number;
91
+ otherNotUploaded: number;
92
+ prefixSet: readonly string[] | undefined;
93
+ hqRoot: string;
94
+ cwd?: string;
95
+ companySlug?: string;
96
+ }): string[];
49
97
  /**
50
98
  * US-003: run one sync fanout under a client-health attempt/outcome report.
51
99
  * The report is best-effort, bounded, and swallowed — it can only append a
@@ -128,6 +176,15 @@ export declare function scopeExcludedPrefixDetail(prefixSet: readonly string[] |
128
176
  * folder foo/ — and grant advice would point the reader the wrong way.
129
177
  */
130
178
  export declare function scopeExcludedLines(count: number, prefixSet: readonly string[] | undefined): string[];
179
+ /**
180
+ * feedback_b7c00a62: run a `sync now` runner under the watchdog (see
181
+ * `utils/sync-watchdog.ts` for the limits). A timeout prints a clear message
182
+ * and unwinds as a failed {@link SyncExitError}, so {@link withSyncHealthReport}
183
+ * records the failure and exits 124. The failure report gets at most
184
+ * {@link SYNC_WATCHDOG_REPORT_GRACE_MS}; after that the process exits 124
185
+ * regardless, and the worker backstop stays armed behind both.
186
+ */
187
+ export declare function runUnderSyncWatchdog<T>(limits: SyncWatchdogLimits, label: string, run: () => Promise<T>, watchdog?: typeof withSyncWatchdog, exit?: (code: number) => void): Promise<T>;
131
188
  /**
132
189
  * Bound foreground waits for a watcher/manual sync that currently owns the
133
190
  * per-root operation lock. The cloud engine reads this environment value on
@@ -18,8 +18,9 @@ import { SERVER_OWNED_FOLDERS, findServerOwnedLocalOnly, } from "../lib/sync/ser
18
18
  import chalk from "chalk";
19
19
  import * as fs from "fs";
20
20
  import * as path from "path";
21
- import { share, getStateDir, listJournals, createIgnoreFilter, VaultClient, computePersonalVaultPaths, PERSONAL_VAULT_JOURNAL_SLUG, resolvePullScope, syncDoctor, } from "@indigoai-us/hq-cloud";
21
+ import { share, getStateDir, listJournals, createIgnoreFilter, VaultClient, computePersonalVaultPaths, PERSONAL_VAULT_JOURNAL_SLUG, resolvePullScope, readSyncProgress, syncDoctor, } from "@indigoai-us/hq-cloud";
22
22
  import { syncLeg } from "../utils/sync-operation-lock.js";
23
+ import { SYNC_WATCHDOG_EXIT_CODE, SYNC_WATCHDOG_REPORT_GRACE_MS, SyncWatchdogTimeoutError, createSnapshotProgressProbe, resolveSyncWatchdogLimits, withSyncWatchdog, } from "../utils/sync-watchdog.js";
23
24
  import { DEFAULT_HQ_ROOT, ensureCognitoToken, buildVaultConfig, loadCachedTokens, } from "../utils/cognito-session.js";
24
25
  import { resolveUploadAuthor } from "../utils/upload-author.js";
25
26
  import { companyFolderExceedsThreshold, emitNarrowHint, isStrictRefusal, resolveBannerLevel, resolveNarrowHintPresentationLevel, resolveNarrowHintMinBytes, } from "../lib/narrow-hint-banner.js";
@@ -69,7 +70,10 @@ async function ensureSyncCognitoToken() {
69
70
  * deliberately duck-typed so hq-cli remains compatible while hq-cloud and the
70
71
  * CLI are released independently.
71
72
  */
72
- export function formatSyncFailure(err) {
73
+ export function formatSyncFailure(err, ctx = {}) {
74
+ const unreachable = formatUnreachablePushPaths(err, ctx);
75
+ if (unreachable)
76
+ return unreachable;
73
77
  // A plan-limit refusal the runner threw (a 402 on the whole request) renders
74
78
  // with the same reason, fix options and upgrade link as every other refusal.
75
79
  const planGate = planGateErrorFromVaultError(err);
@@ -105,6 +109,150 @@ export function formatSyncFailure(err) {
105
109
  }
106
110
  return err instanceof Error ? err.message : String(err);
107
111
  }
112
+ function asUnreachablePushPaths(err) {
113
+ if (!(err instanceof Error) || err.name !== "UnreachablePushPathsError")
114
+ return null;
115
+ const candidate = err;
116
+ if (!Array.isArray(candidate.paths))
117
+ return null;
118
+ if (typeof candidate.reasons !== "object" || candidate.reasons === null)
119
+ return null;
120
+ const paths = candidate.paths.filter((p) => typeof p === "string");
121
+ return {
122
+ message: err.message,
123
+ paths,
124
+ reasons: candidate.reasons,
125
+ };
126
+ }
127
+ /**
128
+ * The `.hqinclude` line that admits a named path: its HQ-relative spelling,
129
+ * with a trailing slash for a folder. Resolved the way the push resolver
130
+ * reads a named path (absolute, HQ root, the company folder, then the current
131
+ * directory); a path that resolves nowhere inside the HQ tree is suggested as
132
+ * typed.
133
+ */
134
+ export function hqincludeEntryFor(namedPath, ctx = {}) {
135
+ const toEntry = (rel, isDir) => {
136
+ const posix = rel.split(path.sep).join("/").replace(/\/+$/, "");
137
+ return isDir ? posix + "/" : posix;
138
+ };
139
+ const hqRoot = ctx.hqRoot ? path.resolve(ctx.hqRoot) : undefined;
140
+ if (hqRoot) {
141
+ const candidates = path.isAbsolute(namedPath)
142
+ ? [namedPath]
143
+ : [
144
+ path.join(hqRoot, namedPath),
145
+ ...(ctx.companySlug
146
+ ? [path.join(hqRoot, "companies", ctx.companySlug, namedPath)]
147
+ : []),
148
+ path.resolve(ctx.cwd ?? process.cwd(), namedPath),
149
+ ];
150
+ for (const candidate of candidates) {
151
+ const rel = path.relative(hqRoot, candidate);
152
+ if (rel === "" ||
153
+ rel === ".." ||
154
+ rel.startsWith(".." + path.sep) ||
155
+ path.isAbsolute(rel)) {
156
+ continue;
157
+ }
158
+ let stat;
159
+ try {
160
+ stat = fs.statSync(candidate);
161
+ }
162
+ catch {
163
+ stat = undefined;
164
+ }
165
+ if (stat)
166
+ return toEntry(rel, stat.isDirectory());
167
+ }
168
+ }
169
+ return toEntry(namedPath.replace(/^\.\//, ""), namedPath.endsWith("/"));
170
+ }
171
+ /**
172
+ * Re-render hq-cloud's UnreachablePushPathsError with the real blocker per
173
+ * path (feedback_6afa6ce4). The upstream message always ends with advice
174
+ * about symlinks, so a path left out of `.hqinclude` read as a symlink
175
+ * problem. This names the `.hqinclude` line to add, and keeps the symlink
176
+ * advice only for reasons that are about links or paths outside the company
177
+ * folder. Returns null for any other error.
178
+ */
179
+ export function formatUnreachablePushPaths(err, ctx = {}) {
180
+ const parsed = asUnreachablePushPaths(err);
181
+ if (!parsed || parsed.paths.length === 0)
182
+ return null;
183
+ const upstreamLines = parsed.message.split("\n");
184
+ const upstreamLine = (p) => upstreamLines.find((l) => l.startsWith(" · " + p + " — "));
185
+ const ruleFor = (p) => {
186
+ const line = upstreamLine(p);
187
+ if (!line)
188
+ return undefined;
189
+ return line.slice((" · " + p + " — ").length).replace(/; it was not uploaded$/, "");
190
+ };
191
+ const includeEntries = [];
192
+ let linkAdvice = false;
193
+ const lines = parsed.paths.map((p) => {
194
+ const reason = parsed.reasons[p];
195
+ if (reason === "ignored") {
196
+ const rule = ruleFor(p) ?? "excluded by a sync ignore rule";
197
+ if (rule === "not listed in .hqinclude") {
198
+ const entry = hqincludeEntryFor(p, ctx);
199
+ includeEntries.push(entry);
200
+ return " · " + p + " — not listed in .hqinclude, so sync skips it. Add this line to .hqinclude: " + entry;
201
+ }
202
+ return " · " + p + " — " + rule + "; it was not uploaded";
203
+ }
204
+ if (reason === "outside-company" || reason === "unreadable-link") {
205
+ linkAdvice = true;
206
+ }
207
+ return upstreamLine(p) ?? " · " + p + " — could not be pushed (" + String(reason) + ")";
208
+ });
209
+ const count = parsed.paths.length;
210
+ const out = [
211
+ count + " named path" + (count === 1 ? "" : "s") + " could not be pushed; nothing was uploaded.",
212
+ ...lines,
213
+ ];
214
+ if (includeEntries.length > 0) {
215
+ out.push("Your HQ root has a .hqinclude allowlist, so only listed paths sync. Add the line" +
216
+ (includeEntries.length === 1 ? "" : "s") +
217
+ " above to .hqinclude at the HQ root, then push again.");
218
+ }
219
+ if (linkAdvice) {
220
+ out.push("A path reached through a symlink is only pushable when it stays inside the HQ tree " +
221
+ "(e.g. companies/<slug>/knowledge → repos/private/knowledge-<slug>); one that points " +
222
+ "outside HQ has to sync through whatever owns it, not the vault.");
223
+ }
224
+ return out.join("\n");
225
+ }
226
+ /**
227
+ * Lines naming the blocker when a push with user-named paths uploaded nothing
228
+ * and every not-uploaded file fell outside write scope (feedback_5baccb9e).
229
+ * The summary before this gave a count and the granted prefixes; this names
230
+ * each requested path as the thing no write grant covers and points at
231
+ * `hq access`, which reports the ACL row that blocks it.
232
+ */
233
+ export function explicitPushBlockedLines(input) {
234
+ if (!input.userNamedPaths || input.namedPaths.length === 0)
235
+ return [];
236
+ if (input.filesUploaded > 0 || input.filesExcludedByScope <= 0)
237
+ return [];
238
+ if (input.otherNotUploaded > 0)
239
+ return [];
240
+ const keys = input.namedPaths.map((p) => hqincludeEntryFor(p, {
241
+ hqRoot: input.hqRoot,
242
+ cwd: input.cwd,
243
+ companySlug: input.companySlug,
244
+ }).replace(/\/$/, ""));
245
+ const lines = [
246
+ "✗ None of the paths you named were uploaded: every file in them is outside your write access.",
247
+ ];
248
+ for (const key of keys) {
249
+ lines.push(input.prefixSet === undefined
250
+ ? " · " + key + " — the server refused writes here (an ACL on this path or a parent blocks you)"
251
+ : " · " + key + " — no write prefix you hold covers this path");
252
+ }
253
+ lines.push(" Run `hq access " + keys[0] + "` to see which ACL row blocks the write, then ask its creator or a company admin for write access.");
254
+ return lines;
255
+ }
108
256
  /**
109
257
  * US-003: run one sync fanout under a client-health attempt/outcome report.
110
258
  * The report is best-effort, bounded, and swallowed — it can only append a
@@ -298,6 +446,34 @@ function resolveDeletePolicy() {
298
446
  return "currency-gated";
299
447
  }
300
448
  const DEFAULT_SYNC_LOCK_TIMEOUT_SECONDS = 300;
449
+ /**
450
+ * feedback_b7c00a62: run a `sync now` runner under the watchdog (see
451
+ * `utils/sync-watchdog.ts` for the limits). A timeout prints a clear message
452
+ * and unwinds as a failed {@link SyncExitError}, so {@link withSyncHealthReport}
453
+ * records the failure and exits 124. The failure report gets at most
454
+ * {@link SYNC_WATCHDOG_REPORT_GRACE_MS}; after that the process exits 124
455
+ * regardless, and the worker backstop stays armed behind both.
456
+ */
457
+ export async function runUnderSyncWatchdog(limits, label, run, watchdog = withSyncWatchdog, exit = (code) => process.exit(code)) {
458
+ try {
459
+ return await watchdog(run, {
460
+ idleMs: limits.idleSeconds * 1000,
461
+ maxRuntimeMs: limits.maxRuntimeSeconds * 1000,
462
+ label,
463
+ probeProgress: createSnapshotProgressProbe(readSyncProgress),
464
+ });
465
+ }
466
+ catch (err) {
467
+ if (err instanceof SyncWatchdogTimeoutError) {
468
+ console.error(chalk.red("\n\u2717 " + err.message));
469
+ process.exitCode = SYNC_WATCHDOG_EXIT_CODE;
470
+ const forceExit = setTimeout(() => exit(SYNC_WATCHDOG_EXIT_CODE), SYNC_WATCHDOG_REPORT_GRACE_MS);
471
+ forceExit.unref();
472
+ throw new SyncExitError(SYNC_WATCHDOG_EXIT_CODE);
473
+ }
474
+ throw err;
475
+ }
476
+ }
301
477
  /**
302
478
  * Bound foreground waits for a watcher/manual sync that currently owns the
303
479
  * per-root operation lock. The cloud engine reads this environment value on
@@ -947,6 +1123,9 @@ export function registerCloudCommands(program) {
947
1123
  // failures never count as a sync attempt (US-003).
948
1124
  let syncHealth;
949
1125
  let explicitPersonalPaths;
1126
+ // Company folder the push resolves relative paths against; names the
1127
+ // .hqinclude line and the blocked path in failure output.
1128
+ let pushCompanySlug;
950
1129
  try {
951
1130
  if (options.personal && options.credsFromStdin) {
952
1131
  throw new Error("`--personal` cannot be combined with --creds-from-stdin: " +
@@ -1063,6 +1242,14 @@ export function registerCloudCommands(program) {
1063
1242
  companyRef: targetCompany ?? readActiveCompany(options.hqRoot),
1064
1243
  });
1065
1244
  const planLimitTracker = createPlanLimitRefusalTracker(companySlugForBilling(progressCompany));
1245
+ // A cmp_ uid target has no slug in progressCompany; fall back to
1246
+ // the entity slug, then the company folder the paths sit in.
1247
+ pushCompanySlug =
1248
+ companySlugForBilling(progressCompany).companySlug ??
1249
+ (entityContext && !entityContext.uid.startsWith("prs_")
1250
+ ? entityContext.slug
1251
+ : undefined) ??
1252
+ (personalMode ? undefined : companySlugFromSyncPaths(options.hqRoot, targetPaths));
1066
1253
  const identityHeld = createIdentityHeldTracker();
1067
1254
  syncHealth = beginSyncHealthReport();
1068
1255
  if (!personalMode) {
@@ -1191,6 +1378,18 @@ export function registerCloudCommands(program) {
1191
1378
  for (const line of scopeExcludedLines(result.filesExcludedByScope, pushPrefixSet)) {
1192
1379
  log(chalk.yellow(line));
1193
1380
  }
1381
+ for (const line of explicitPushBlockedLines({
1382
+ userNamedPaths,
1383
+ namedPaths: targetPaths,
1384
+ filesUploaded: result.filesUploaded,
1385
+ filesExcludedByScope: result.filesExcludedByScope,
1386
+ otherNotUploaded: staleRefusalCount + uploadFailed.count + identityHeldCount,
1387
+ prefixSet: pushPrefixSet,
1388
+ hqRoot: options.hqRoot,
1389
+ companySlug: pushCompanySlug,
1390
+ })) {
1391
+ log(chalk.red(line));
1392
+ }
1194
1393
  for (const line of staleUploadRefusalLines(staleRefusalCount, result.filesRefusedStalePaths)) {
1195
1394
  log(chalk.yellow(line));
1196
1395
  }
@@ -1220,7 +1419,10 @@ export function registerCloudCommands(program) {
1220
1419
  }
1221
1420
  if (syncHealth)
1222
1421
  await syncHealth.failed();
1223
- const message = formatSyncFailure(err);
1422
+ const message = formatSyncFailure(err, {
1423
+ hqRoot: options.hqRoot,
1424
+ companySlug: pushCompanySlug,
1425
+ });
1224
1426
  if (jsonMode) {
1225
1427
  // In JSON mode, the parent process is parsing stderr for ndjson —
1226
1428
  // human-formatted error lines would corrupt the stream. Emit a
@@ -1509,6 +1711,14 @@ export function registerCloudCommands(program) {
1509
1711
  .option("--force-scope-shrink", "When a scope shrink would un-track locally-modified files, proceed " +
1510
1712
  "anyway. Dirty files are KEPT on disk (only un-tracked); clean " +
1511
1713
  "out-of-scope files are quarantined under .hq/scope-quarantine/.")
1714
+ .option("--max-idle <seconds>", "For scheduled or unattended runs: stop with exit code " + SYNC_WATCHDOG_EXIT_CODE +
1715
+ " after this many seconds with no file planned, transferred or skipped. The remote " +
1716
+ "listing and planning phase of a leg reports no progress, so set this longer than " +
1717
+ "your slowest planning phase. Laptop sleep does not count. " +
1718
+ "(default: HQ_SYNC_MAX_IDLE, else off)")
1719
+ .option("--max-runtime <seconds>", "For scheduled or unattended runs: stop with exit code " + SYNC_WATCHDOG_EXIT_CODE +
1720
+ " if the run has not finished after this many seconds, even while it is making progress. " +
1721
+ "Laptop sleep does not count. (default: HQ_SYNC_MAX_RUNTIME, else off)")
1512
1722
  .action(async (options) => {
1513
1723
  const skips = refuseSyncForOffVaults("now", {
1514
1724
  all: options.all,
@@ -1519,15 +1729,19 @@ export function registerCloudCommands(program) {
1519
1729
  try {
1520
1730
  configureSyncLockTimeout(options.lockTimeout);
1521
1731
  assertSingleSelector(options, "now");
1732
+ const watchdogLimits = resolveSyncWatchdogLimits({
1733
+ maxIdle: options.maxIdle,
1734
+ maxRuntime: options.maxRuntime,
1735
+ });
1522
1736
  if (options.all) {
1523
1737
  // `options.personal === false` is Commander's auto-negation
1524
1738
  // of `--personal`; in `--all` mode that means "drop the
1525
1739
  // personal leg from both legs of the bidirectional fanout"
1526
1740
  // (see `--no-personal` option above).
1527
- await withSyncHealthReport(() => runNowAll(options.hqRoot, options.message, options.onConflict, options.modeAll === true, skips.skipPersonal, options.forceScopeShrink === true, skips.skipCompanies));
1741
+ await withSyncHealthReport(() => runUnderSyncWatchdog(watchdogLimits, "hq sync now --all", () => runNowAll(options.hqRoot, options.message, options.onConflict, options.modeAll === true, skips.skipPersonal, options.forceScopeShrink === true, skips.skipCompanies)));
1528
1742
  return;
1529
1743
  }
1530
- await withSyncHealthReport(() => runNowSingle(options.hqRoot, options.company, options.personal === true, options.message, options.onConflict, options.modeAll === true, options.forceScopeShrink === true));
1744
+ await withSyncHealthReport(() => runUnderSyncWatchdog(watchdogLimits, "hq sync now", () => runNowSingle(options.hqRoot, options.company, options.personal === true, options.message, options.onConflict, options.modeAll === true, options.forceScopeShrink === true)));
1531
1745
  }
1532
1746
  catch (err) {
1533
1747
  console.error(chalk.red("\n✗ Sync now failed:"), err instanceof Error ? err.message : String(err));
@@ -1,3 +1,10 @@
1
- export declare const CORE_COMPANY_INDEX_SCOPE_FLAG = "cli.rebuild-index-company-scope";
1
+ import { CORE_COMPANY_INDEX_SCOPE_FLAG } from "../lib/cli-flag-keys.js";
2
+ export { CORE_COMPANY_INDEX_SCOPE_FLAG };
3
+ /**
4
+ * Kill switch for company-scoped index rebuilds, default ON
5
+ * (indigo-feature-flags-default-on-as-fail-safes). An absent, archived or
6
+ * unreadable flag row keeps scoping on; only an explicit false turns it off,
7
+ * and then `companies` rebuilds every company as it did before scoping.
8
+ */
2
9
  export declare function coreCompanyIndexScopeEnabled(): boolean;
3
10
  //# sourceMappingURL=core-company-index-scope-flag.d.ts.map
@@ -1,6 +1,13 @@
1
1
  import { resolveProcessFlagGate } from "../lib/flag-registry.js";
2
- export const CORE_COMPANY_INDEX_SCOPE_FLAG = "cli.rebuild-index-company-scope";
2
+ import { CORE_COMPANY_INDEX_SCOPE_FLAG } from "../lib/cli-flag-keys.js";
3
+ export { CORE_COMPANY_INDEX_SCOPE_FLAG };
4
+ /**
5
+ * Kill switch for company-scoped index rebuilds, default ON
6
+ * (indigo-feature-flags-default-on-as-fail-safes). An absent, archived or
7
+ * unreadable flag row keeps scoping on; only an explicit false turns it off,
8
+ * and then `companies` rebuilds every company as it did before scoping.
9
+ */
3
10
  export function coreCompanyIndexScopeEnabled() {
4
- return resolveProcessFlagGate(CORE_COMPANY_INDEX_SCOPE_FLAG, { fallback: false }, () => false);
11
+ return resolveProcessFlagGate(CORE_COMPANY_INDEX_SCOPE_FLAG, { fallback: true }, () => true, undefined, { acceptStaleSnapshot: true, killSwitchWithoutCompany: true });
5
12
  }
6
13
  //# sourceMappingURL=core-company-index-scope-flag.js.map
@@ -3,6 +3,7 @@ import { createHash, randomInt } from "node:crypto";
3
3
  import * as fs from "node:fs";
4
4
  import * as os from "node:os";
5
5
  import * as path from "node:path";
6
+ import { callerIsMachinePrincipal } from "../lib/caller-principal.js";
6
7
  import { serializeJqJson } from "../lib/core-utils/jq-json-serializer.js";
7
8
  import { shellDisplayPath } from "../lib/core-utils/shell-display-path.js";
8
9
  import { matchingSecretPatterns } from "../lib/core-utils/secret-patterns.js";
@@ -1079,8 +1080,10 @@ function runSend(args, context) {
1079
1080
  catch {
1080
1081
  return fail("send", "could not persist sending state; no DM attempted");
1081
1082
  }
1082
- // The pickup DM is read by the person and acted on by their agent.
1083
- const dm = runHq(["dm", principal, headline, "--audience", "both", "--prompt-file", prompt, "--details-file", brief], context);
1083
+ // The pickup DM is read by the person and acted on by their agent. Only an
1084
+ // agent or bot may tag it `both`; a person login sends `human`.
1085
+ const audience = callerIsMachinePrincipal() ? "both" : "human";
1086
+ const dm = runHq(["dm", principal, headline, "--audience", audience, "--prompt-file", prompt, "--details-file", brief], context);
1084
1087
  if (dm.code !== 0)
1085
1088
  return fail("send", "hq dm delivery outcome is uncertain; status is sending, inspect DM history before retrying");
1086
1089
  const event = /eventId[: ]+([A-Za-z0-9_-]+)/.exec(dm.stdout ?? "")?.[1] ?? "";
@@ -2,6 +2,7 @@
2
2
  import * as fs from "node:fs";
3
3
  import * as os from "node:os";
4
4
  import * as path from "node:path";
5
+ import { tokenIsMachinePrincipal } from "../lib/caller-principal.js";
5
6
  import { spawnSync } from "node:child_process";
6
7
  import { resolveWindowsExecutable } from "../lib/bot/runtime/windows.js";
7
8
  import { resolveLiveRoot } from "../utils/hq-roots.js";
@@ -329,9 +330,12 @@ function latestCliEventId(d, ch) {
329
330
  });
330
331
  return String(jqAlternative(rows.at(-1)?.eventId, jqAlternative(rows.at(-1)?.messageId, "")));
331
332
  }
332
- async function sendHuman(d, ch, payload) {
333
+ /** The ID token every human-API request in this file sends as its bearer. */
334
+ function humanApiToken(d) {
335
+ return JSON.parse(d.fs.readFileSync(path.join(d.home, ".hq/cognito-tokens.json"), "utf8")).idToken;
336
+ }
337
+ async function sendHuman(d, ch, payload, token = humanApiToken(d)) {
333
338
  const config = JSON.parse(d.fs.readFileSync(path.join(d.home, ".hq/config.json"), "utf8"));
334
- const token = JSON.parse(d.fs.readFileSync(path.join(d.home, ".hq/cognito-tokens.json"), "utf8")).idToken;
335
339
  const headers = { Authorization: `Bearer ${token}`, "Content-Type": "application/json" };
336
340
  const channelsResponse = await d.fetch(`${config.vaultApiUrl}/v1/notify/channels`, { headers, signal: AbortSignal.timeout(DM_BIND_API_TIMEOUT_MS) });
337
341
  const channels = await channelsResponse.json();
@@ -596,11 +600,22 @@ async function post(d, args) {
596
600
  const mentions = mentionsJson(d, sid, names);
597
601
  if (!mentions.length)
598
602
  return fail("no mention resolved to a channel member id — not posting an update that notifies nobody");
599
- const payload = { body: postedMessage, mentions, audience: "agent" };
603
+ // People never send agent-tagged messages: a person login posts `human`.
604
+ // The audience is read from the token this request sends as its bearer, so
605
+ // a box with machine creds plus a person cache cannot tag a person-token
606
+ // post `agent` (the server rejects that with 403).
607
+ let token;
608
+ try {
609
+ token = humanApiToken(d);
610
+ }
611
+ catch (error) {
612
+ return utilityError(`hq-dm-bind: ${error.message}\n`, 1);
613
+ }
614
+ const payload = { body: postedMessage, mentions, audience: tokenIsMachinePrincipal(token) ? "agent" : "human" };
600
615
  if (root)
601
616
  payload.rootEventId = root;
602
617
  try {
603
- eventId = await sendHuman(d, ch, payload);
618
+ eventId = await sendHuman(d, ch, payload, token);
604
619
  }
605
620
  catch (error) {
606
621
  return utilityError(`hq-dm-bind: ${error.message}\n`, 1);
@@ -1,5 +1,7 @@
1
1
  /** Isolated fast-entry adapter for rebuild-index native renderers. */
2
2
  import { CompanyIndexUserError, renderIndexTarget } from "../lib/index-render/index.js";
3
+ import { planScopedRebuild } from "../lib/index-render/session-scope.js";
4
+ import { CORE_COMPANY_INDEX_SCOPE_FLAG } from "../lib/cli-flag-keys.js";
3
5
  const targets = new Set([
4
6
  "all", "companies", "company-knowledge", "orchestrator", "projects",
5
7
  "public-knowledge", "reports", "social-drafts", "threads", "workers",
@@ -10,7 +12,10 @@ const targets = new Set([
10
12
  */
11
13
  export async function runRebuildIndexFast(args, _stdin, _cwd, hqRoot) {
12
14
  const [target, ...rest] = args;
13
- if (!target || !targets.has(target) || rest.length > 0 || !hqRoot)
15
+ // The only argument the fast route takes is --all-companies; anything else
16
+ // needs the full graph's argument handling.
17
+ const allCompanies = rest.length === 1 && rest[0] === "--all-companies";
18
+ if (!target || !targets.has(target) || (rest.length > 0 && !allCompanies) || !hqRoot)
14
19
  return undefined;
15
20
  const logs = [];
16
21
  const flushLogs = () => {
@@ -19,11 +24,24 @@ export async function runRebuildIndexFast(args, _stdin, _cwd, hqRoot) {
19
24
  };
20
25
  try {
21
26
  const refused = [];
22
- renderIndexTarget(target, {
23
- root: hqRoot,
24
- log: (message) => logs.push(message),
25
- refused,
26
- });
27
+ // Same session company scope as the full command, resolved before any
28
+ // write. A refusal falls back to the full graph, which reports it.
29
+ // The full flag registry is off-limits on the fast route; read the
30
+ // default-on kill switch from the lightweight snapshot reader, and only for
31
+ // the targets that need it.
32
+ const companyIndexScopeEnabled = target === "companies" || target === "all"
33
+ ? await (await import("../native-fast-route.js")).fastFlagEnabledDefaultOn(CORE_COMPANY_INDEX_SCOPE_FLAG)
34
+ : true;
35
+ const plan = planScopedRebuild(target, rest, hqRoot, process.env, { companyIndexScopeEnabled });
36
+ if (plan.warning)
37
+ logs.push(plan.warning);
38
+ for (const run of plan.runs) {
39
+ renderIndexTarget(run.target, {
40
+ root: hqRoot,
41
+ log: (message) => logs.push(message),
42
+ refused,
43
+ }, run.args);
44
+ }
27
45
  if (refused.length > 0)
28
46
  return undefined;
29
47
  flushLogs();
@@ -57,6 +57,7 @@ import { registerCoreWorkflowRunCommand } from "./core-workflow-run-command.js";
57
57
  import { resolveLiveRoot } from "../utils/hq-roots.js";
58
58
  import { interpreterFor, runBundledScript } from "../utils/run-bundled-script.js";
59
59
  import { CompanyIndexUserError, renderIndexTarget } from "../lib/index-render/index.js";
60
+ import { planScopedRebuild, SESSION_SCOPE_HELP } from "../lib/index-render/session-scope.js";
60
61
  import { generateWorkersRegistry } from "../lib/workers-registry/index.js";
61
62
  import { scanPackages } from "../lib/scan-packages/index.js";
62
63
  import { detectStaleCorePolicyMirror } from "../lib/core-utils/detect-stale-core-policy-mirror.js";
@@ -671,6 +672,7 @@ export function registerCoreCommands(program) {
671
672
  const wantsHelp = rendererArgs.some((arg) => arg === "--help" || arg === "-h");
672
673
  if (wantsHelp && ["companies", "company-knowledge", "projects"].includes(entry.renderer)) {
673
674
  renderIndexTarget(entry.renderer, { root: "", output: (message) => process.stdout.write(message) }, rendererArgs);
675
+ process.stdout.write(SESSION_SCOPE_HELP);
674
676
  return;
675
677
  }
676
678
  if (wantsHelp) {
@@ -686,12 +688,22 @@ export function registerCoreCommands(program) {
686
688
  const hqRoot = resolveLiveRoot({ hqRoot: scope.hqRoot });
687
689
  const refused = [];
688
690
  try {
689
- renderIndexTarget(entry.renderer, {
690
- root: hqRoot,
691
- log: (message) => process.stderr.write(`${message}\n`),
692
- force,
693
- refused,
694
- }, rendererArgs);
691
+ // Resolve the session's company scope before any write: a bound
692
+ // session rebuilds only its bound companies, and an unbound one must
693
+ // name a company or pass --all-companies.
694
+ const plan = planScopedRebuild(entry.renderer, rendererArgs, hqRoot, process.env, {
695
+ companyIndexScopeEnabled: coreCompanyIndexScopeEnabled(),
696
+ });
697
+ if (plan.warning)
698
+ process.stderr.write(`${plan.warning}\n`);
699
+ for (const run of plan.runs) {
700
+ renderIndexTarget(run.target, {
701
+ root: hqRoot,
702
+ log: (message) => process.stderr.write(`${message}\n`),
703
+ force,
704
+ refused,
705
+ }, run.args);
706
+ }
695
707
  }
696
708
  catch (error) {
697
709
  if (error instanceof CompanyIndexUserError)
@@ -77,6 +77,14 @@ export interface DmContact {
77
77
  * eba06f59). Returns null when nothing or more than one contact matches. Pure.
78
78
  */
79
79
  export declare function matchContactByName(contacts: DmContact[], name: string): DmContact | null;
80
+ /**
81
+ * Every distinct contact (person or bot) whose display name matches `name`,
82
+ * using the same rule as matchContactByName. A leading '@' is the explicit
83
+ * person/bot selector and is ignored for matching. Pure.
84
+ */
85
+ export declare function matchContactsByName(contacts: DmContact[], name: string): DmContact[];
86
+ /** One line per ambiguous contact match, for a refusal message. Pure. */
87
+ export declare function formatContactMatches(matches: DmContact[]): string;
80
88
  /**
81
89
  * The confirmation line for a channel send. When the typed target is not the
82
90
  * channel's own display name (for example `hq dm setup` matching a channel
@@ -236,15 +244,21 @@ export declare function fetchChannels(token: string): Promise<ChannelSummary[]>;
236
244
  * post itself passes. Used to resolve `@name` mentions into participant uids.
237
245
  */
238
246
  export declare function fetchChannelMembers(token: string, channelId: string): Promise<ChannelMember[]>;
247
+ /** An explicit agent/both audience from a person login. */
248
+ export declare class PersonAudienceError extends Error {
249
+ constructor();
250
+ }
239
251
  /**
240
252
  * Resolve the audience for a send. The default comes from the recipient kind
241
- * (`defaultAudienceFor`); `--for-human` maps to `human`; an explicit
242
- * `--audience` wins over `--for-human` (with a warning) and is validated.
253
+ * and the caller (`defaultAudienceFor`: always `human` for a person login);
254
+ * `--for-human` maps to `human`; an explicit `--audience` wins over
255
+ * `--for-human` (with a warning) and is validated. A person login passing
256
+ * `--audience agent|both` throws PersonAudienceError.
243
257
  */
244
258
  export declare function resolveSendAudience(opts: {
245
259
  audience?: string;
246
260
  forHuman?: boolean;
247
- }, recipientKind: DmRecipientKind, warn?: (msg: string) => void): string;
261
+ }, recipientKind: DmRecipientKind, warn?: (msg: string) => void, machineCaller?: boolean): string;
248
262
  /** One incoming DM as returned by GET /v1/notify/inbox. */
249
263
  export interface DmInboxEvent {
250
264
  eventId: string;