@indigoai-us/hq-cli 5.345.206 → 5.345.207

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 (49) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/assets/scaffold/core/scripts/checkpoint-stop-gate.sh +111 -15
  3. package/dist/command-catalog.generated.d.ts +14 -2
  4. package/dist/command-catalog.generated.js +17 -2
  5. package/dist/commands/bot.d.ts +6 -0
  6. package/dist/commands/bot.js +88 -12
  7. package/dist/commands/core-checkpoint-stop-gate-native.js +130 -25
  8. package/dist/commands/files.d.ts +36 -0
  9. package/dist/commands/files.js +80 -1
  10. package/dist/commands/lanes-shared.d.ts +13 -0
  11. package/dist/commands/lanes.d.ts +2 -0
  12. package/dist/commands/lanes.js +44 -4
  13. package/dist/commands/sources.js +1 -1
  14. package/dist/commands/storage-offload.d.ts +8 -1
  15. package/dist/commands/storage-offload.js +6 -1
  16. package/dist/commands/storage.js +4 -0
  17. package/dist/hq-cloud-sync-runner/bin/sync-runner.js +260 -250
  18. package/dist/hq-cloud-sync-runner/package.json +1 -1
  19. package/dist/lib/bot/fleet-cron.js +4 -1
  20. package/dist/lib/bot/fleet-owner-companies.d.ts +7 -0
  21. package/dist/lib/bot/fleet-owner-companies.js +16 -4
  22. package/dist/lib/bot/jobs/hot-signal-sync.d.ts +2 -0
  23. package/dist/lib/bot/jobs/hot-signal-sync.js +18 -1
  24. package/dist/lib/bot/jobs/meeting-detect.d.ts +41 -2
  25. package/dist/lib/bot/jobs/meeting-detect.js +280 -16
  26. package/dist/lib/bot/run.d.ts +1 -0
  27. package/dist/lib/bot/run.js +4 -2
  28. package/dist/lib/bot/runtime-failure.js +4 -2
  29. package/dist/lib/capacity/collect.d.ts +7 -0
  30. package/dist/lib/capacity/collect.js +22 -16
  31. package/dist/lib/capacity/route.d.ts +23 -0
  32. package/dist/lib/capacity/route.js +41 -2
  33. package/dist/lib/company-skill-wrapper.js +33 -4
  34. package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
  35. package/dist/lib/flag-registry-worker-source.generated.js +1 -1
  36. package/dist/lib/hot-channels/alert.d.ts +4 -1
  37. package/dist/lib/hot-channels/alert.js +10 -4
  38. package/dist/lib/hot-channels/ledger.d.ts +4 -4
  39. package/dist/lib/hot-channels/ledger.js +2 -0
  40. package/dist/lib/hot-channels/run.d.ts +6 -0
  41. package/dist/lib/hot-channels/run.js +7 -2
  42. package/dist/lib/hot-channels/signals-pass.d.ts +11 -2
  43. package/dist/lib/hot-channels/signals-pass.js +129 -15
  44. package/dist/lib/live-meetings.js +1 -1
  45. package/dist/lib/sync-core/release.d.ts +1 -1
  46. package/dist/lib/sync-core/release.js +1 -1
  47. package/dist/utils/redact-error-text.js +1 -0
  48. package/dist/utils/resident-package-preload.js +32 -4
  49. package/package.json +8 -8
@@ -299,31 +299,107 @@ function isRecord(value) {
299
299
  return value !== null && typeof value === "object" && !Array.isArray(value);
300
300
  }
301
301
  function nonWhitespaceLength(value) { return Array.from(value.replace(/\s+/g, "")).length; }
302
- function codexCommand(payload) {
303
- const name = toShellString(payload.name);
304
- const input = payload.input;
305
- if (name === "exec" && typeof input === "string") {
306
- const match = input.match(/tools\.exec_command\((\{.*\})\);/s);
307
- if (match) {
308
- try {
309
- const args = JSON.parse(match[1]);
310
- const command = toShellString(record(args).cmd);
311
- if (command)
312
- return command;
313
- }
314
- catch { /* shell filter falls back to a JS object literal probe */ }
315
- const cmdMatch = input.match(/(?:^|[,{}])\s*cmd\s*:\s*("(?:\\.|[^"\\])*")/s);
316
- if (cmdMatch) {
317
- try {
318
- return JSON.parse(cmdMatch[1]);
319
- }
320
- catch {
321
- return "";
322
- }
302
+ // Codex code mode runs tools from JavaScript in one "exec" call:
303
+ // `const r = await tools.exec_command({...});`, `text(await tools.exec_command({...}));`,
304
+ // `Promise.allSettled([...])`, multi-line call objects, or other tools such as
305
+ // `tools.apply_patch(...)`. Match the call object as a JS object literal
306
+ // (string-aware, one level of nesting). Mirrors codex_command in
307
+ // assets/scaffold/core/scripts/checkpoint-stop-gate.sh.
308
+ const JS_STRING = String.raw `"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|` + "`(?:\\\\.|[^`\\\\])*`";
309
+ const JS_FLAT_OBJECT = String.raw `\{(?:` + JS_STRING + String.raw `|[^{}"'` + "`" + String.raw `])*\}`;
310
+ const JS_OBJECT = String.raw `\{(?:` + JS_STRING + "|" + JS_FLAT_OBJECT + String.raw `|[^{}"'` + "`" + String.raw `])*\}`;
311
+ const CODE_MODE_CALL_ARGS = new RegExp(String.raw `^\s*(` + JS_OBJECT + ")");
312
+ const JS_TOKEN = new RegExp(JS_STRING + String.raw `|[A-Za-z_$][A-Za-z0-9_$]*|\S`, "g");
313
+ /** One JS string literal token (quotes included, any quote style) to its
314
+ * value, or null when it cannot be read statically: a template literal with
315
+ * ${...}, or an escape JSON cannot decode. Mirrors js_decode_string in the
316
+ * shell gate. */
317
+ function jsDecodeString(token) {
318
+ const quote = token.slice(0, 1);
319
+ const body = token.slice(1, -1);
320
+ if (quote === "`" && /(^|[^\\])(\\\\)*\$\{/.test(body))
321
+ return null;
322
+ const json = body.replace(/(\\[\s\S])|(")|(\n)|(\r)|(\t)/g, (_m, e, q, nl, cr) => {
323
+ if (e !== undefined)
324
+ return e === "\\'" || e === "\\`" || e === "\\$" ? e.slice(1) : e;
325
+ if (q !== undefined)
326
+ return '\\"';
327
+ if (nl !== undefined)
328
+ return "\\n";
329
+ if (cr !== undefined)
330
+ return "\\r";
331
+ return "\\t";
332
+ });
333
+ try {
334
+ const value = JSON.parse(`"${json}"`);
335
+ return typeof value === "string" ? value : null;
336
+ }
337
+ catch {
338
+ return null;
339
+ }
340
+ }
341
+ /** The value of a top-level `cmd` key (bare or quoted) in one JS object
342
+ * literal, when it is a static string literal in any quote style; the last
343
+ * one wins, as in JavaScript. A string literal is one token, so text inside a
344
+ * string never reads as a key. "" when absent or not a static string. Mirrors
345
+ * js_top_level_cmd in the shell gate. */
346
+ function jsTopLevelCmd(objectSource) {
347
+ const tokens = Array.from(objectSource.matchAll(JS_TOKEN), (m) => m[0]);
348
+ let depth = 0;
349
+ let key = false;
350
+ let cmd = null;
351
+ for (let i = 0; i < tokens.length; i += 1) {
352
+ const tok = tokens[i];
353
+ if (tok === "{" || tok === "[" || tok === "(") {
354
+ depth += 1;
355
+ key = tok === "{" && depth === 1;
356
+ }
357
+ else if (tok === "}" || tok === "]" || tok === ")") {
358
+ depth -= 1;
359
+ key = false;
360
+ }
361
+ else if (depth === 1 && tok === ",") {
362
+ key = true;
363
+ }
364
+ else if (depth === 1 && key) {
365
+ key = false;
366
+ const isCmdKey = tok === "cmd" || (/^["']/.test(tok) && jsDecodeString(tok) === "cmd");
367
+ if (isCmdKey && tokens[i + 1] === ":") {
368
+ const value = tokens[i + 2] ?? "";
369
+ cmd = /^["'`]/.test(value) ? (jsDecodeString(value) ?? "") : "";
323
370
  }
324
371
  }
372
+ }
373
+ return cmd ?? "";
374
+ }
375
+ function codeModeExecCommand(afterOpener) {
376
+ const match = afterOpener.match(CODE_MODE_CALL_ARGS);
377
+ if (!match)
325
378
  return "";
379
+ const args = match[1];
380
+ try {
381
+ const parsed = JSON.parse(args);
382
+ const cmd = record(parsed).cmd;
383
+ return typeof cmd === "string" ? cmd : "";
326
384
  }
385
+ catch { /* JS object literal: read its top-level cmd key */ }
386
+ return jsTopLevelCmd(args);
387
+ }
388
+ /** One command per tool event. A code-mode exec yields one entry per
389
+ * tools.exec_command call in source order, and at least one ("" when none is
390
+ * readable) so the call always counts as a work tool. */
391
+ function codexCommands(payload) {
392
+ const name = toShellString(payload.name);
393
+ const input = payload.input;
394
+ if (name === "exec" && typeof input === "string") {
395
+ const commands = input.split(/tools\.exec_command\(/).slice(1).map(codeModeExecCommand);
396
+ return commands.length ? commands : [""];
397
+ }
398
+ return [codexCommand(payload)];
399
+ }
400
+ function codexCommand(payload) {
401
+ const name = toShellString(payload.name);
402
+ const input = payload.input;
327
403
  if (name === "exec_command" || name === "Bash") {
328
404
  if (isRecord(input))
329
405
  return toShellString(input.cmd ?? input.command);
@@ -398,6 +474,14 @@ function parseTranscript(contents) {
398
474
  record(entry.message).content.startsWith("Stop hook feedback:"));
399
475
  });
400
476
  const genuineIndex = genuine.length ? genuine[genuine.length - 1] : userIndexes[0];
477
+ // A Codex automation wake-up: the user row is a <heartbeat> prompt, and the
478
+ // agent may end the turn with an intentionally empty answer.
479
+ const genuineEntry = rows[genuineIndex].entry;
480
+ const genuinePayload = record(genuineEntry.payload);
481
+ const heartbeat = genuineEntry.type === "response_item" && isUser(genuineEntry) && Array.isArray(genuinePayload.content) &&
482
+ /^\s*<heartbeat[\s>/]/.test(genuinePayload.content
483
+ .filter((item) => record(item).type === "input_text").map((item) => toShellString(record(item).text)).join(""));
484
+ const unreplied = heartbeat ? { kind: "heartbeat" } : { kind: "unreplied" };
401
485
  const events = [];
402
486
  rows.forEach(({ entry }, row) => {
403
487
  if (row <= genuineIndex)
@@ -419,7 +503,9 @@ function parseTranscript(contents) {
419
503
  else if (entry.type === "response_item") {
420
504
  const payload = record(entry.payload);
421
505
  if (payload.type === "custom_tool_call" || payload.type === "function_call") {
422
- events.push({ row, kind: "tool", runtime: "codex", id: toShellString(payload.call_id ?? payload.id), name: toShellString(payload.name), command: codexCommand(payload) });
506
+ for (const command of codexCommands(payload)) {
507
+ events.push({ row, kind: "tool", runtime: "codex", id: toShellString(payload.call_id ?? payload.id), name: toShellString(payload.name), command });
508
+ }
423
509
  }
424
510
  else if (payload.type === "message" && payload.role === "assistant" && Array.isArray(payload.content)) {
425
511
  const text = payload.content.map((item) => toShellString(record(item).text)).join("");
@@ -452,11 +538,11 @@ function parseTranscript(contents) {
452
538
  }
453
539
  if (lastTool.runtime === "codex")
454
540
  return { kind: "stamp" };
455
- return segmentReplyChars > 0 ? { kind: "replied" } : { kind: "unreplied" };
541
+ return segmentReplyChars > 0 ? { kind: "replied" } : unreplied;
456
542
  }
457
543
  if (workTools.length === 0)
458
544
  return { kind: "idle" };
459
- return segmentReplyChars > 0 ? { kind: "replied" } : { kind: "unreplied" };
545
+ return segmentReplyChars > 0 ? { kind: "replied" } : unreplied;
460
546
  }
461
547
  function countFile(filePath, deps) {
462
548
  const text = readIfReadable(filePath, deps) ?? "";
@@ -617,6 +703,7 @@ export function executeCheckpointStopGate(input, context, overrides = {}) {
617
703
  }
618
704
  let satisfied = "0";
619
705
  let replied = verdict.kind === "replied" ? 1 : 0;
706
+ const heartbeat = verdict.kind === "heartbeat";
620
707
  let toolId = "";
621
708
  let replyChars = 0;
622
709
  let replyRequired = "";
@@ -630,7 +717,9 @@ export function executeCheckpointStopGate(input, context, overrides = {}) {
630
717
  satisfied = "stamp";
631
718
  else if (verdict.kind === "idle")
632
719
  satisfied = "idle";
633
- if (evidence.state === "present" && runtime === "claude") {
720
+ // A present Stop-payload reply counts for Claude and Codex alike; only the
721
+ // absent/invalid ambiguity handling below is Claude-only.
722
+ if (evidence.state === "present" && (runtime === "claude" || runtime === "codex")) {
634
723
  if (satisfied === "1")
635
724
  replyChars = Math.max(replyChars, evidence.chars);
636
725
  else if (satisfied === "0" && evidence.chars > 0)
@@ -713,6 +802,22 @@ export function executeCheckpointStopGate(input, context, overrides = {}) {
713
802
  catch { /* fail-open */ }
714
803
  return { code: 0, stdout: "", stderr };
715
804
  }
805
+ // A Codex automation <heartbeat> turn owes no reply: record its work out of
806
+ // band instead of re-prompting every wake-up.
807
+ if (heartbeat && runtime === "codex") {
808
+ try {
809
+ deps.spawnHqDetached([
810
+ "core", "checkpoint", "--session-id", sessionId, "--trigger", "stop-gate-auto",
811
+ "--transcript", transcriptPath, "--summary", "automation heartbeat turn ended without a user-facing reply",
812
+ ]);
813
+ }
814
+ catch { /* an automatic checkpoint is best-effort */ }
815
+ try {
816
+ deps.remove(blockCountFile);
817
+ }
818
+ catch { /* fail-open */ }
819
+ return { code: 0, stdout: "", stderr };
820
+ }
716
821
  if (blockCount >= 3)
717
822
  return { code: 0, stdout: "", stderr };
718
823
  try {
@@ -66,6 +66,42 @@ export declare class ShareSessionHttpError extends Error {
66
66
  */
67
67
  export declare function formatShareSessionError(err: ShareSessionHttpError): string;
68
68
  export declare function registerFilesCommand(program: Command): Command;
69
+ /**
70
+ * Seams for the @all notification prompt (DEV-5263). Tests replace them; the
71
+ * real ones read the process TTY and prompt on stdin.
72
+ */
73
+ export interface ShareNotifyPromptDeps {
74
+ isInteractive: () => boolean;
75
+ confirm: (message: string) => Promise<boolean>;
76
+ countMembers: (token: string, companyUid: string) => Promise<number | null>;
77
+ }
78
+ export declare function __setShareNotifyPromptDepsForTest(deps: Partial<ShareNotifyPromptDeps> | null): void;
79
+ /**
80
+ * Decide the `notify` field for a direct grant (DEV-5263,
81
+ * feedback_a7f33826). An @all grant reaches every active member, so it
82
+ * notifies only with --notify, or after a yes at a terminal prompt that shows
83
+ * the member count. Without a terminal it requests no notifications. Other
84
+ * grants keep the server default unless --notify / --no-notify was passed.
85
+ *
86
+ * The messages here say what was REQUESTED, never that nothing was sent: an
87
+ * hq-pro without notify support ignores the flag and still notifies. The
88
+ * "no member notifications sent" confirmation is printed after the grant, and
89
+ * only when the response carries `memberNotificationsSuppressed: true`.
90
+ */
91
+ export declare function resolveShareNotify(input: {
92
+ isAll: boolean;
93
+ notify: boolean | undefined;
94
+ channelTarget: boolean;
95
+ token: string;
96
+ companyUid: string;
97
+ deps?: ShareNotifyPromptDeps;
98
+ }): Promise<boolean | undefined>;
99
+ /** Pre-grant wording: accurate whether or not the server honours `notify`. */
100
+ export declare const SHARE_NOTIFY_REQUESTED_OFF = "Requested no member notifications (needs hq-pro with notify support; older servers still notify).";
101
+ /** Post-grant confirmation, printed only when the server says it suppressed them. */
102
+ export declare const SHARE_NOTIFY_CONFIRMED_OFF = "No member notifications were sent for this grant.";
103
+ /** Post-grant notice for @all + --channel with no flag, when the server confirms it. */
104
+ export declare const SHARE_NOTIFY_CHANNEL_ONLY = "Members were not notified of this @all grant (channel post only). Pass --notify to notify every active member.";
69
105
  /**
70
106
  * True for a prefix that might name a folder without saying so: no trailing
71
107
  * `/` (private folder), no `/*` (shared folder glob), and not the `*`
@@ -193,13 +193,15 @@ export function registerFilesCommand(program) {
193
193
  });
194
194
  files
195
195
  .command("share [paths...]")
196
- .description("Share file paths. foo/ is a private folder (children stay creator-only); quote the shared-folder glob 'foo/*', or a one-folder wildcard such as 'clients/*/reports', so the shell passes it literally. Without --with: mint a share-session URL and open it in the browser. With --with: grant access directly to a person, group, or @all.")
196
+ .description("Share file paths. foo/ is a private folder (children stay creator-only); quote the shared-folder glob 'foo/*', or a one-folder wildcard such as 'clients/*/reports', so the shell passes it literally. Without --with: mint a share-session URL and open it in the browser. With --with: grant access directly to a person, group, or @all. A new person, group or email grant notifies the grantee (DM, in-app notice, email) unless --no-notify. An @all grant notifies every active member only with --notify; in a terminal it asks first and shows the member count, and without a terminal it sends no notifications.")
197
197
  .option("--with <principal>", "Email address, group id, company Outpost id (out_...), or '@all' to share with every active company member")
198
198
  .option("--permission <level>", "Permission level (only with --with): read | write")
199
199
  .option("--exact", "With --with: grant exactly the object named by <prefix>, even when it looks like a folder (by default a bare folder name such as 'knowledge' is granted as the folder glob 'knowledge/*').")
200
200
  .option("--full", "Grant access to the ENTIRE vault (the '*' wildcard prefix) — no need to quote a glob. Requires --with; defaults to write permission.")
201
201
  .option("--expires <duration>", "Token expiry duration for share-session URL (e.g. 15m, 1h, 24h). Default 15m. Max 24h.")
202
202
  .option("--no-open", "Print the share-session URL but do not launch the browser")
203
+ .option("--notify", "With --with: send the share notification (DM, in-app notice, email). Required to notify members on an @all grant; in a terminal, @all asks first and shows how many members would be notified.")
204
+ .option("--no-notify", "With --with: grant access without notifying anyone. Person, group and email grants notify by default; @all grants never notify without --notify.")
203
205
  .option("--channel <name>", "Post the share record to this named channel instead of a DM")
204
206
  .option("--mention <person>", "Mention a person on the channel share record (repeatable)", collectMentions, [])
205
207
  .action(async (paths, opts) => {
@@ -246,6 +248,7 @@ export function registerFilesCommand(program) {
246
248
  permission: opts.permission ?? "write",
247
249
  companySlug,
248
250
  fullVault: true,
251
+ ...(opts.notify !== undefined ? { notify: opts.notify } : {}),
249
252
  ...channelTarget,
250
253
  });
251
254
  return;
@@ -268,6 +271,7 @@ export function registerFilesCommand(program) {
268
271
  permission: opts.permission,
269
272
  companySlug,
270
273
  ...(opts.exact ? { exact: true } : {}),
274
+ ...(opts.notify !== undefined ? { notify: opts.notify } : {}),
271
275
  ...channelTarget,
272
276
  });
273
277
  return;
@@ -289,6 +293,7 @@ export function registerFilesCommand(program) {
289
293
  permission,
290
294
  companySlug,
291
295
  ...(opts.exact ? { exact: true } : {}),
296
+ ...(opts.notify !== undefined ? { notify: opts.notify } : {}),
292
297
  ...(index === 0
293
298
  ? {
294
299
  channelId: channelTarget.channelId,
@@ -793,6 +798,60 @@ export function registerFilesCommand(program) {
793
798
  // files-browse.ts) onto the same group without re-creating it.
794
799
  return files;
795
800
  }
801
+ const realShareNotifyPromptDeps = {
802
+ isInteractive: () => process.stdin.isTTY === true && process.stdout.isTTY === true,
803
+ confirm: (message) => realConfirm(message),
804
+ countMembers: async (token, companyUid) => {
805
+ try {
806
+ const { listCompanyRoster } = await import("./members.js");
807
+ const roster = await listCompanyRoster(token, companyUid);
808
+ return roster.members.length;
809
+ }
810
+ catch {
811
+ return null;
812
+ }
813
+ },
814
+ };
815
+ let shareNotifyPromptDeps = realShareNotifyPromptDeps;
816
+ export function __setShareNotifyPromptDepsForTest(deps) {
817
+ shareNotifyPromptDeps = deps ? { ...realShareNotifyPromptDeps, ...deps } : realShareNotifyPromptDeps;
818
+ }
819
+ /**
820
+ * Decide the `notify` field for a direct grant (DEV-5263,
821
+ * feedback_a7f33826). An @all grant reaches every active member, so it
822
+ * notifies only with --notify, or after a yes at a terminal prompt that shows
823
+ * the member count. Without a terminal it requests no notifications. Other
824
+ * grants keep the server default unless --notify / --no-notify was passed.
825
+ *
826
+ * The messages here say what was REQUESTED, never that nothing was sent: an
827
+ * hq-pro without notify support ignores the flag and still notifies. The
828
+ * "no member notifications sent" confirmation is printed after the grant, and
829
+ * only when the response carries `memberNotificationsSuppressed: true`.
830
+ */
831
+ export async function resolveShareNotify(input) {
832
+ if (input.notify !== undefined)
833
+ return input.notify;
834
+ if (!input.isAll || input.channelTarget)
835
+ return undefined;
836
+ const deps = input.deps ?? shareNotifyPromptDeps;
837
+ if (!deps.isInteractive()) {
838
+ console.error(chalk.yellow(`@all grant: ${SHARE_NOTIFY_REQUESTED_OFF} Pass --notify to notify every active member.`));
839
+ return false;
840
+ }
841
+ const count = await deps.countMembers(input.token, input.companyUid);
842
+ const who = count === null ? "every active member" : `${count} active member${count === 1 ? "" : "s"}`;
843
+ const yes = await deps.confirm(`Notify ${who} of this @all share?`);
844
+ if (!yes) {
845
+ console.error(chalk.gray(SHARE_NOTIFY_REQUESTED_OFF));
846
+ }
847
+ return yes;
848
+ }
849
+ /** Pre-grant wording: accurate whether or not the server honours `notify`. */
850
+ export const SHARE_NOTIFY_REQUESTED_OFF = "Requested no member notifications (needs hq-pro with notify support; older servers still notify).";
851
+ /** Post-grant confirmation, printed only when the server says it suppressed them. */
852
+ export const SHARE_NOTIFY_CONFIRMED_OFF = "No member notifications were sent for this grant.";
853
+ /** Post-grant notice for @all + --channel with no flag, when the server confirms it. */
854
+ export const SHARE_NOTIFY_CHANNEL_ONLY = "Members were not notified of this @all grant (channel post only). Pass --notify to notify every active member.";
796
855
  /** Best-effort, default-off warning after the ACL grant has succeeded. */
797
856
  async function warnIfEmptySharePrefix(params) {
798
857
  if (isPrivateFolderPattern(params.prefix))
@@ -1096,6 +1155,13 @@ async function runDirectGrant(params) {
1096
1155
  exact: params.exact,
1097
1156
  });
1098
1157
  }
1158
+ const notify = await resolveShareNotify({
1159
+ isAll,
1160
+ notify: params.notify,
1161
+ channelTarget: params.channelId !== undefined,
1162
+ token,
1163
+ companyUid,
1164
+ });
1099
1165
  let res = await vaultApiFetch({
1100
1166
  token,
1101
1167
  path: `/files/${encodeURIComponent(companyUid)}/acl/grant`,
@@ -1105,6 +1171,7 @@ async function runDirectGrant(params) {
1105
1171
  granteeType,
1106
1172
  granteeId,
1107
1173
  permission: params.permission,
1174
+ ...(notify !== undefined ? { notify } : {}),
1108
1175
  ...(params.channelId ? { channelId: params.channelId } : {}),
1109
1176
  ...(params.mentionPersonUids && params.mentionPersonUids.length > 0
1110
1177
  ? { mentionPersonUids: params.mentionPersonUids }
@@ -1123,6 +1190,7 @@ async function runDirectGrant(params) {
1123
1190
  body: {
1124
1191
  prefix: canonicalPrefix,
1125
1192
  entries: [{ granteeType, granteeId, permission: params.permission }],
1193
+ ...(notify !== undefined ? { notify } : {}),
1126
1194
  ...(params.channelId ? { channelId: params.channelId } : {}),
1127
1195
  ...(params.mentionPersonUids && params.mentionPersonUids.length > 0
1128
1196
  ? { mentionPersonUids: params.mentionPersonUids }
@@ -1180,6 +1248,17 @@ async function runDirectGrant(params) {
1180
1248
  if (isPrivateFolderPattern(printedPrefix)) {
1181
1249
  console.log(chalk.gray(privateFolderExplanation(printedPrefix)));
1182
1250
  }
1251
+ if (notify === false && data.memberNotificationsSuppressed === true) {
1252
+ console.log(chalk.gray(SHARE_NOTIFY_CONFIRMED_OFF));
1253
+ }
1254
+ else if (isAll &&
1255
+ notify === undefined &&
1256
+ params.channelId !== undefined &&
1257
+ data.memberNotificationsSuppressed === true) {
1258
+ // @all + --channel with neither flag: the server writes only the channel
1259
+ // post. Say so, so the sharer does not assume every member was told.
1260
+ console.log(chalk.gray(SHARE_NOTIFY_CHANNEL_ONLY));
1261
+ }
1183
1262
  if (Array.isArray(data.maskedBy) && data.maskedBy.length > 0) {
1184
1263
  console.warn(chalk.yellow(formatShadowedGrantWarning({
1185
1264
  prefix: printedPrefix,
@@ -12,6 +12,8 @@ import type { RunCompactionFn } from "../lib/lanes/compaction.js";
12
12
  import type { LaneMesh, LaneMeshEvent } from "../lib/lanes/mesh-events.js";
13
13
  import type { BalanceHostGap, BalanceHostSnapshot } from "../lib/lanes/claude-balance.js";
14
14
  import type { HostCapacitySnapshot } from "../lib/lanes/host-capacity.js";
15
+ import type { NowView } from "../lib/capacity/ledger.js";
16
+ import type { StaleReadingTarget } from "../lib/capacity/route.js";
15
17
  import { LANE_OUTPOST_LOAD_BALANCING_FLAG } from "../lib/lanes/flag-keys.js";
16
18
  import { type ResolvedEffort } from "../lib/lanes/effort.js";
17
19
  import type { SessionCopyResult } from "../lib/lanes/move-account.js";
@@ -322,6 +324,17 @@ export interface Ctx {
322
324
  }) => Promise<OutpostDispatchResult>;
323
325
  backfillOutpostIdentity: (expectedId: string) => "created" | "unchanged";
324
326
  fetchText: (url: string) => Promise<string>;
327
+ /**
328
+ * Take one fresh capacity reading before `--account auto` refuses on a
329
+ * stale reading (feedback_94446741). `targets` are the accounts the refusal
330
+ * skipped as stale; only those are read. Defaults to collectCapacityOnce.
331
+ */
332
+ refreshCapacity?: (input: {
333
+ env: NodeJS.ProcessEnv;
334
+ hqRoot: string;
335
+ targets: readonly StaleReadingTarget[];
336
+ now?: () => Date;
337
+ }) => Promise<NowView>;
325
338
  lanePlacementEnabled: (company: LaneCompanyRef | undefined) => Promise<boolean>;
326
339
  readLeadAutopilotFlag: (flag: string, options: {
327
340
  company: LaneCompanyRef;
@@ -103,6 +103,8 @@ export interface LanesCommandDeps {
103
103
  /** Test seam for the atomic, non-overwriting marker repair. */
104
104
  backfillOutpostIdentity?: (expectedId: string) => "created" | "unchanged";
105
105
  fetchText?: (url: string) => Promise<string>;
106
+ /** Test seam for the one capacity refresh before `--account auto` refuses on a stale reading. */
107
+ refreshCapacity?: Ctx["refreshCapacity"];
106
108
  runCompaction?: RunCompactionFn;
107
109
  locateTranscript?: (home: string, sessionId: string) => string | null;
108
110
  monitorEvidence?: MonitorEvidenceReader;
@@ -95,7 +95,7 @@ import { compactionAfterUsage, } from "../lib/lanes/compaction.js";
95
95
  import { parseCliEffort, resolveLaneEffort, } from "../lib/lanes/effort.js";
96
96
  import { LanesError } from "../lib/lanes/errors.js";
97
97
  import { LedgerCorrupt, capacityOptionsFromEnv, readCollectorMark, readNow, rebuildNow, } from "../lib/capacity/ledger.js";
98
- import { pickAccount } from "../lib/capacity/route.js";
98
+ import { pickAccount, refusalHasStaleReading, staleReadingTargets, } from "../lib/capacity/route.js";
99
99
  import { capacityViewAge } from "../lib/capacity/freshness.js";
100
100
  import { applyTerminalToLane, classifyLaneExit, readLatestEnvelopeRecord } from "../lib/lanes/watcher.js";
101
101
  import { isSubagentLane, parseLaneEnvelope, parseLaneRunner } from "../lib/lanes/types.js";
@@ -392,6 +392,25 @@ function createDefaultMesh() {
392
392
  // login is acceptable. The watcher builds its own non-interactive mesh.
393
393
  return createLaneMesh({ interactive: true });
394
394
  }
395
+ async function defaultRefreshCapacity(input) {
396
+ const { collectCapacityOnce } = await import("../lib/capacity/collect.js");
397
+ const { listCapacityAccounts } = await import("../lib/capacity/accounts.js");
398
+ // Read only the accounts the refusal skipped as stale, not every provider.
399
+ const wanted = new Set(input.targets.map((t) => `${t.provider}\u0000${t.account}`));
400
+ const accounts = listCapacityAccounts({ hqRoot: input.hqRoot, env: input.env })
401
+ .filter((account) => wanted.has(`${account.provider}\u0000${account.label}`));
402
+ if (accounts.length === 0)
403
+ throw new Error("no skipped account to refresh");
404
+ return collectCapacityOnce({
405
+ env: input.env,
406
+ hqRoot: input.hqRoot,
407
+ accounts,
408
+ providers: [...new Set(accounts.map((account) => account.provider))],
409
+ // A partial account list must not label the whole statusline spool.
410
+ includeSpool: false,
411
+ ...(input.now ? { now: input.now } : {}),
412
+ });
413
+ }
395
414
  function defaultSleep(ms) {
396
415
  return new Promise((resolve) => {
397
416
  setTimeout(resolve, ms);
@@ -484,6 +503,7 @@ function resolveDeps(deps = {}) {
484
503
  createIfMissing: createOutpostIdentityMarkerIfMissing,
485
504
  })),
486
505
  fetchText: deps.fetchText ?? defaultFetchText,
506
+ refreshCapacity: deps.refreshCapacity ?? defaultRefreshCapacity,
487
507
  lanePlacementEnabled: deps.lanePlacementEnabled ?? defaultLanePlacementEnabled,
488
508
  storyLedgerEnabled: deps.storyLedgerEnabled ?? laneStoryLedgerEnabled,
489
509
  focusGuardEnabled: deps.focusGuardEnabled,
@@ -3589,18 +3609,38 @@ async function runCreate(ctx, opts) {
3589
3609
  catch (err) {
3590
3610
  routeLanesError = err instanceof Error ? err.message : String(err);
3591
3611
  }
3592
- const result = pickAccount({
3593
- view,
3612
+ const routeOn = (routeView) => pickAccount({
3613
+ view: routeView,
3594
3614
  lanes: routeLanes,
3595
3615
  lanesConfig: routeConfig,
3596
3616
  ...(explicitProvider ? { providers: [explicitProvider] } : {}),
3597
3617
  model: opts.model ?? null,
3598
3618
  now: ctx.now(),
3599
3619
  collectorEnabled: readCollectorMark(ledgerOptions)?.enabled ?? null,
3600
- capacityStale: capacityViewAge(view.generatedAt, ctx.now().getTime()).stale,
3620
+ capacityStale: capacityViewAge(routeView.generatedAt, ctx.now().getTime()).stale,
3601
3621
  lanesError: routeLanesError,
3602
3622
  allowExtraUsage: opts.allowExtraUsage === true,
3603
3623
  });
3624
+ let result = routeOn(view);
3625
+ // feedback_94446741: a refusal that rests on a missing or day-old reading
3626
+ // is not evidence that the account is full. Take one fresh reading and
3627
+ // route again; refuse only if there is still no room.
3628
+ if (refusalHasStaleReading(result) && ctx.refreshCapacity) {
3629
+ try {
3630
+ const refreshed = await ctx.refreshCapacity({
3631
+ env: ctx.env,
3632
+ hqRoot,
3633
+ // Only the skipped-as-stale accounts. pickAccount already limited
3634
+ // them to --provider; the filter keeps that explicit.
3635
+ targets: staleReadingTargets(result).filter((target) => !explicitProvider || target.provider === explicitProvider),
3636
+ ...(ledgerOptions.now ? { now: ledgerOptions.now } : {}),
3637
+ });
3638
+ result = routeOn(refreshed);
3639
+ }
3640
+ catch {
3641
+ // A failed refresh leaves the original refusal in place.
3642
+ }
3643
+ }
3604
3644
  if (!result.ok || !result.pick) {
3605
3645
  const resetSuffix = result.next_reset ? `; next reset ${result.next_reset}` : "";
3606
3646
  throw new LanesError("no_account_with_room", `No account has room${resetSuffix}`, {
@@ -566,7 +566,7 @@ async function runLockedCompanySync(input, vaultRoot, personKey, author, session
566
566
  if (input.signalsAlert) {
567
567
  const postCompanyChannel = input.signalsAlert.postCompanyChannel ??
568
568
  createSignalsAlertChannelPoster({ hqRoot: input.hqRoot, company: input.company, deps });
569
- await raiseSignalsFailureAlerts({
569
+ report.signalsAlert = await raiseSignalsFailureAlerts({
570
570
  vaultRoot,
571
571
  personKey,
572
572
  entries: report.entries,
@@ -265,6 +265,13 @@ export interface OffloadDeps {
265
265
  * rule does (hq-cloud createIgnoreExplainer). Null or absent: not excluded.
266
266
  */
267
267
  syncExclusion?: (rel: string) => SyncExclusion | null;
268
+ /**
269
+ * True for a company path the server owns (sources/, signals/, ontology/,
270
+ * company-brief.md: hq-cloud isLocallyIneligibleForPush). HQ sync never
271
+ * pushes these, so offload must not upload them either, even when an
272
+ * .hqinclude allowlist no longer excludes them.
273
+ */
274
+ serverOwned?: (rel: string) => boolean;
268
275
  /**
269
276
  * Open a multipart uploader for a company vault. Called only for a company
270
277
  * the caller is an active member of. Absent: company files over the sync
@@ -282,7 +289,7 @@ export interface OffloadDeps {
282
289
  /** Why HQ sync skips a path: the ignore layer that excludes it. */
283
290
  export interface SyncExclusion {
284
291
  excluded: boolean;
285
- /** "built-in", "defaults", ".hqignore", ".hqsyncignore" or ".hqinclude allowlist". */
292
+ /** "built-in", "defaults", ".hqignore", ".hqsyncignore", ".hqinclude allowlist" or "server-owned". */
286
293
  layer: string | null;
287
294
  /** For the .hqinclude allowlist: the line that would include the path. */
288
295
  includeLine?: string;
@@ -985,6 +985,9 @@ async function uploadCompanyFile(file, uploader, vault, deps, fsOps) {
985
985
  }
986
986
  /** Plain name of an HQ sync ignore layer, for skip reasons. */
987
987
  function exclusionReason(ex) {
988
+ if (ex.layer === "server-owned") {
989
+ return "HQ sync never uploads this path: the server owns this company folder and replaces local copies with the cloud copy.";
990
+ }
988
991
  if (ex.layer === ".hqinclude allowlist") {
989
992
  const add = ex.includeLine ? ` To sync and offload it, add this line to .hqinclude: ${ex.includeLine}` : "";
990
993
  return `HQ sync skips this path because the .hqinclude allowlist does not list it.${add}`;
@@ -1140,7 +1143,9 @@ async function planCurrentFiles(rels, opts, deps, openVault) {
1140
1143
  plan.placeholder = "written";
1141
1144
  }
1142
1145
  else if (target.vault === "company") {
1143
- const ex = deps.syncExclusion?.(rel);
1146
+ const ex = deps.serverOwned?.(rel)
1147
+ ? { excluded: true, layer: "server-owned" }
1148
+ : deps.syncExclusion?.(rel);
1144
1149
  if (ex?.excluded) {
1145
1150
  plan.excluded_by = ex.layer ?? "ignore rules";
1146
1151
  plan.reason = exclusionReason(ex);
@@ -1110,6 +1110,10 @@ export async function buildOffloadDeps() {
1110
1110
  return s3VaultObjectStore(bucket, client, { where: `company vault '${company.slug}'`, revend });
1111
1111
  },
1112
1112
  syncMaxFileBytes: typeof cloud.SYNC_MAX_FILE_BYTES === "number" ? cloud.SYNC_MAX_FILE_BYTES : undefined,
1113
+ // Server-owned company paths sync only from the cloud. Called directly so
1114
+ // that an hq-cloud without this export fails the build, where an optional
1115
+ // lookup would turn the refusal off.
1116
+ serverOwned: (rel) => hqCloud.isLocallyIneligibleForPush(rel),
1113
1117
  syncExclusion: explainIgnore
1114
1118
  ? (rel) => {
1115
1119
  explainer ??= explainIgnore(hqRoot);