@indigoai-us/hq-cli 5.345.241 → 5.345.242

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 (116) hide show
  1. package/CHANGELOG.md +49 -0
  2. package/assets/scaffold/core/scripts/hq-delegate-grant.sh +170 -8
  3. package/assets/scaffold/core/scripts/hq-delegate-publish.sh +21 -1
  4. package/assets/scaffold/core/scripts/lib/delegate-engine.sh +77 -0
  5. package/dist/command-catalog.generated.d.ts +28 -8
  6. package/dist/command-catalog.generated.js +33 -8
  7. package/dist/commands/cloud-off-gate.d.ts +7 -7
  8. package/dist/commands/cloud-off-gate.js +26 -38
  9. package/dist/commands/core-delegate-w1b.js +307 -26
  10. package/dist/commands/core-delegate.js +2 -0
  11. package/dist/commands/core-handoff.js +1 -1
  12. package/dist/commands/core-job-model-auth.d.ts +95 -0
  13. package/dist/commands/core-job-model-auth.js +247 -0
  14. package/dist/commands/core-job-run-native.js +280 -12
  15. package/dist/commands/core.js +1 -0
  16. package/dist/commands/files-browse.js +2 -0
  17. package/dist/commands/files.js +4 -0
  18. package/dist/commands/integrations-core.d.ts +11 -0
  19. package/dist/commands/integrations-core.js +15 -1
  20. package/dist/commands/lanes-link.js +2 -2
  21. package/dist/commands/lanes-loop.d.ts +2 -2
  22. package/dist/commands/lanes-loop.js +5 -5
  23. package/dist/commands/lanes-questions.js +1 -1
  24. package/dist/commands/lanes-stories.js +1 -1
  25. package/dist/commands/lanes.js +80 -14
  26. package/dist/commands/rescue.d.ts +3 -2
  27. package/dist/commands/rescue.js +48 -34
  28. package/dist/commands/search.d.ts +6 -0
  29. package/dist/commands/search.js +24 -4
  30. package/dist/commands/sources.js +6 -2
  31. package/dist/commands/sync-core.d.ts +8 -0
  32. package/dist/commands/sync-core.js +43 -0
  33. package/dist/hq-cloud-sync-runner/bin/sync-runner.js +1737 -1450
  34. package/dist/hq-cloud-sync-runner/package.json +1 -1
  35. package/dist/lib/capacity/accounts.d.ts +1 -1
  36. package/dist/lib/capacity/accounts.js +1 -1
  37. package/dist/lib/capacity/freshness.d.ts +1 -1
  38. package/dist/lib/capacity/freshness.js +1 -1
  39. package/dist/lib/capacity/route.js +1 -1
  40. package/dist/lib/daemon/catalog.d.ts +3 -0
  41. package/dist/lib/daemon/hook-requests.d.ts +1 -1
  42. package/dist/lib/daemon/hook-requests.js +4 -2
  43. package/dist/lib/daemon/run.js +16 -22
  44. package/dist/lib/environment/work-requirements.d.ts +1 -1
  45. package/dist/lib/environment/work-requirements.js +1 -1
  46. package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
  47. package/dist/lib/flag-registry-worker-source.generated.js +1 -1
  48. package/dist/lib/hook-engine/coverage.js +11 -3
  49. package/dist/lib/hook-engine/git-stop-config.json +510 -510
  50. package/dist/lib/hook-engine/native-precompact-compatibility.json +443 -443
  51. package/dist/lib/hook-engine/native-stop-compatibility.json +359 -359
  52. package/dist/lib/hot-channels/adapters/meetings.d.ts +1 -16
  53. package/dist/lib/hot-channels/adapters/meetings.js +3 -28
  54. package/dist/lib/hot-channels/adapters/slack.d.ts +3 -1
  55. package/dist/lib/hot-channels/adapters/slack.js +4 -1
  56. package/dist/lib/hot-channels/contract.d.ts +14 -0
  57. package/dist/lib/hot-channels/fleet-complete.d.ts +18 -2
  58. package/dist/lib/hot-channels/fleet-complete.js +29 -4
  59. package/dist/lib/hot-channels/meeting-source-ref.d.ts +17 -0
  60. package/dist/lib/hot-channels/meeting-source-ref.js +32 -0
  61. package/dist/lib/hot-channels/prompts/signals-pass.md +6 -1
  62. package/dist/lib/hot-channels/run.d.ts +10 -0
  63. package/dist/lib/hot-channels/run.js +34 -0
  64. package/dist/lib/hot-channels/signals-pass.d.ts +27 -0
  65. package/dist/lib/hot-channels/signals-pass.js +57 -2
  66. package/dist/lib/hot-channels/signals-runtime.js +3 -2
  67. package/dist/lib/lanes/accounts.js +2 -2
  68. package/dist/lib/lanes/claude-balance.d.ts +6 -0
  69. package/dist/lib/lanes/claude-balance.js +124 -0
  70. package/dist/lib/lanes/grants.js +15 -2
  71. package/dist/lib/lanes/hq-root.d.ts +1 -1
  72. package/dist/lib/lanes/hq-root.js +1 -1
  73. package/dist/lib/lanes/links.d.ts +1 -1
  74. package/dist/lib/lanes/liveness.d.ts +3 -0
  75. package/dist/lib/lanes/liveness.js +61 -7
  76. package/dist/lib/lanes/models.d.ts +1 -1
  77. package/dist/lib/lanes/models.js +1 -1
  78. package/dist/lib/lanes/questions.d.ts +1 -1
  79. package/dist/lib/lanes/questions.js +2 -2
  80. package/dist/lib/lanes/spawn.js +4 -6
  81. package/dist/lib/lanes/store.d.ts +13 -2
  82. package/dist/lib/lanes/store.js +13 -5
  83. package/dist/lib/lanes/types.d.ts +7 -7
  84. package/dist/lib/lanes/types.js +1 -1
  85. package/dist/lib/lanes/watcher-main.js +1 -1
  86. package/dist/lib/lanes/watcher.d.ts +1 -1
  87. package/dist/lib/lanes/watcher.js +1 -1
  88. package/dist/lib/onboarding/cli/onboard.js +5 -0
  89. package/dist/lib/signals/sanitize.d.ts +19 -0
  90. package/dist/lib/signals/sanitize.js +103 -7
  91. package/dist/lib/signals/steps/upload.d.ts +40 -1
  92. package/dist/lib/signals/steps/upload.js +122 -6
  93. package/dist/lib/sync-core/access-refresh.d.ts +29 -0
  94. package/dist/lib/sync-core/access-refresh.js +97 -0
  95. package/dist/lib/sync-core/company-adoption.d.ts +33 -0
  96. package/dist/lib/sync-core/company-adoption.js +223 -0
  97. package/dist/lib/sync-core/engine-home.d.ts +1 -0
  98. package/dist/lib/sync-core/engine-owned.d.ts +13 -0
  99. package/dist/lib/sync-core/engine-owned.js +38 -0
  100. package/dist/lib/sync-core/hand-back.d.ts +17 -0
  101. package/dist/lib/sync-core/hand-back.js +23 -0
  102. package/dist/lib/sync-core/post-apply-reindex.d.ts +33 -0
  103. package/dist/lib/sync-core/post-apply-reindex.js +149 -0
  104. package/dist/lib/sync-core/reconcile.d.ts +10 -0
  105. package/dist/lib/sync-core/reconcile.js +117 -12
  106. package/dist/lib/sync-core/rollout-state.d.ts +2 -0
  107. package/dist/lib/sync-core/rollout-state.js +6 -0
  108. package/dist/lib/vault-sync-switches.d.ts +14 -0
  109. package/dist/lib/vault-sync-switches.js +22 -0
  110. package/dist/lib/workers-registry/index.d.ts +1 -1
  111. package/dist/lib/workers-registry/index.js +1 -1
  112. package/dist/utils/github-tag-fallback.d.ts +16 -0
  113. package/dist/utils/github-tag-fallback.js +126 -0
  114. package/dist/utils/version-report.d.ts +2 -1
  115. package/dist/utils/version-report.js +40 -27
  116. package/package.json +8 -8
@@ -0,0 +1,247 @@
1
+ /**
2
+ * Provider sign-in failures for the scheduled-job runner.
3
+ *
4
+ * The 2026-11-19 Outpost outage printed "this login reached its time limit
5
+ * and cannot be renewed". That text matched none of the older auth patterns,
6
+ * so the run was not treated as a sign-in failure.
7
+ *
8
+ * A hold remembers the credential file's size, mtime, and inode, plus the
9
+ * expiry epoch when the file has one. It does not store credential bytes.
10
+ * The next run stays held until a local read says that expiry moved, or,
11
+ * when the file has no readable expiry, until the file is replaced. A still
12
+ * expired file does not resume on a rewrite alone. A hold whose credential
13
+ * still reads healthy runs again about an hour later, even when that expiry
14
+ * epoch did not move, so a false hold cannot pause a job for days. Missed
15
+ * runs are not replayed.
16
+ *
17
+ * Job output can still take today's remediation path on a bare "401",
18
+ * "unauthorized", or a loose "be renewed" line. Those lines do not open an
19
+ * episode or a hold. An episode needs a Claude Code or Codex CLI sign-in
20
+ * line, or a local read that says the credential file is missing. A passed
21
+ * expiry date does not open an episode. Lines from HQ, git, and this runner
22
+ * are not the provider CLI.
23
+ */
24
+ export const PROVIDER_SIGN_IN_TIME_LIMIT_MESSAGE = "this login reached its time limit and cannot be renewed";
25
+ /**
26
+ * Today's remediation match. Includes bare 401 / unauthorized and loose
27
+ * "be renewed" lines. Those stay on the per-job direct-message path.
28
+ */
29
+ const REMEDIATION_AUTH_TEXT = /not logged in|not signed in|please log in|please run[^\n]{0,40}login|oauth session expired|oauth token (?:has expired|revoked)|failed to authenticate|authentication(?:_|\s+)(?:failed|required|error)|invalid authentication|unauthorized|401|invalid[^\n]{0,80}(?:token|credential)|credentials?\s+(?:missing|expired|invalid)|device.?code|login required|reached its time limit|cannot be renewed|can not be renewed|could not be renewed/;
30
+ /**
31
+ * Claude Code and Codex CLI sign-in lines. HQ's own "not signed in" / "hq login"
32
+ * error, git's "Authentication failed", and a tool's "invalid API token" are
33
+ * not in this set. They stay on the remediation path above.
34
+ *
35
+ * Claude: the time-limit sentence, "please run /login", "oauth session expired",
36
+ * "oauth token has expired|revoked", "invalid authentication credentials",
37
+ * "failed to authenticate".
38
+ * Codex: "not logged in", a line that starts "signed out", and "codex login".
39
+ */
40
+ const EPISODE_AUTH_TEXT = /please run\s+\/login\b|oauth session expired|oauth token (?:has expired|revoked)|invalid authentication credentials|failed to authenticate|\bnot logged in\b|^signed out$|^error:\s+signed out$|\bcodex login\b|reached its time limit and (?:cannot|can not|could not) be renewed|login[^\n]{0,80}reached its time limit|login[^\n]{0,80}(?:cannot|can not|could not) be renewed/;
41
+ /**
42
+ * The job log also holds HQ stderr, git stderr, and this runner's own lines.
43
+ * Those are not the provider CLI, even when they quote a sign-in phrase.
44
+ */
45
+ const NON_PROVIDER_LINE = /^(?:hq:|fatal:|remote:|===|started_at=|ended_at=|exit=|failure_class|skip_reason=|remediate=|notify_|runtime=|timeout_seconds=|surface=|job_file=|hq_root=|auth_status=|duration_seconds=|retried=|sign_in_hold=)/;
46
+ /** A healthy hold may run again after this long even if the expiry epoch did not move. */
47
+ export const HEALTHY_HOLD_RETRY_MS = 60 * 60 * 1000;
48
+ const TIME_LIMIT_EPISODE_TEXT = /reached its time limit|login[^\n]{0,80}(?:cannot|can not|could not) be renewed/;
49
+ /** A credential file larger than this is treated as unreadable, not loaded. */
50
+ export const MAX_CREDENTIAL_READ_BYTES = 256 * 1024;
51
+ export function logTextIsProviderSignInFailure(text) {
52
+ return REMEDIATION_AUTH_TEXT.test(text.toLowerCase());
53
+ }
54
+ /** True only for a provider CLI sign-in line. Not for HQ, git, or this runner. */
55
+ export function logTextOpensSignInEpisode(text) {
56
+ return text.split(/\r?\n/).some((line) => {
57
+ const lower = line.trim().toLowerCase();
58
+ if (!lower || NON_PROVIDER_LINE.test(lower))
59
+ return false;
60
+ return EPISODE_AUTH_TEXT.test(lower);
61
+ });
62
+ }
63
+ /**
64
+ * True when a held job may run again because the credential still reads
65
+ * healthy and the hold is at least an hour old. Expired, missing, and
66
+ * unknown reads stay held until the credential itself changes.
67
+ */
68
+ export function healthyCredentialRetryDue(heldAt, nowMs, state) {
69
+ if (state !== "healthy")
70
+ return false;
71
+ const heldMs = Date.parse(heldAt);
72
+ if (!Number.isFinite(heldMs))
73
+ return false;
74
+ return nowMs - heldMs >= HEALTHY_HOLD_RETRY_MS;
75
+ }
76
+ /**
77
+ * Stable reason code for POST /outpost/internal/model-auth-failure.
78
+ * Never a log line. A missing credential file is reported as `missing` by
79
+ * the caller; this function only distinguishes a time-limit sign-in from
80
+ * any other sign-in failure.
81
+ */
82
+ export function modelAuthFailureReason(text) {
83
+ // Same line filter as the episode match. A git or runner line must not
84
+ // turn a real sign-in into a time-limit report.
85
+ const provider = text.split(/\r?\n/).filter((line) => {
86
+ const lower = line.trim().toLowerCase();
87
+ return lower.length > 0 && !NON_PROVIDER_LINE.test(lower);
88
+ }).join("\n");
89
+ return TIME_LIMIT_EPISODE_TEXT.test(provider.toLowerCase()) ? "time_limit" : "auth_failure";
90
+ }
91
+ /**
92
+ * Non-empty `episodeId` on a 2xx body. Anything else, including
93
+ * `{ ok: true, started: false }` with the field omitted, is not confirmation.
94
+ * The id itself is not logged by the caller.
95
+ */
96
+ export function episodeIdFromReportBody(body) {
97
+ try {
98
+ const record = asRecord(JSON.parse(body));
99
+ const id = record?.episodeId;
100
+ if (typeof id !== "string")
101
+ return undefined;
102
+ const trimmed = id.trim();
103
+ return trimmed.length > 0 ? trimmed : undefined;
104
+ }
105
+ catch {
106
+ return undefined;
107
+ }
108
+ }
109
+ /** `absent` / `empty` / `size:mtimeMs:ino`. No credential bytes. */
110
+ export function credentialFingerprint(stat) {
111
+ if (!stat)
112
+ return "absent";
113
+ if (!(stat.size > 0))
114
+ return "empty";
115
+ return `${stat.size}:${Math.trunc(stat.mtimeMs)}:${stat.ino}`;
116
+ }
117
+ /** True when a later stat is a non-empty file other than the one that was held. */
118
+ export function credentialReplaced(heldFingerprint, current) {
119
+ return current !== "absent" && current !== "empty" && current !== heldFingerprint;
120
+ }
121
+ /**
122
+ * Cheap local read of a credential file's expiry. No model call.
123
+ * `undefined` raw means the file is absent. An unreadable file is `unknown`,
124
+ * so the caller keeps the modified-time fingerprint. Never returns token bytes.
125
+ *
126
+ * Claude: `claudeAiOauth.expiresAt` (milliseconds, seconds, or an ISO instant).
127
+ * Codex: `tokens.expires_at` / `expiresAt`, else the access-token JWT `exp`.
128
+ */
129
+ export function localCredentialState(runtime, raw, nowMs) {
130
+ if (raw === undefined || raw.length === 0)
131
+ return { state: "missing" };
132
+ const data = asRecord(parseJson(raw));
133
+ if (!data)
134
+ return { state: "unknown" };
135
+ const expiresAtMs = runtime === "claude" ? claudeExpiresAtMs(data) : codexExpiresAtMs(data);
136
+ if (expiresAtMs === undefined)
137
+ return { state: "unknown" };
138
+ if (expiresAtMs <= nowMs)
139
+ return { state: "expired", expiresAtMs };
140
+ return { state: "healthy", expiresAtMs };
141
+ }
142
+ /**
143
+ * Resume when a readable expiry says the sign-in changed and is current, or
144
+ * when no expiry can be read and the file itself was replaced. A still
145
+ * expired or missing file stays held even if its modified time changed.
146
+ */
147
+ export function signInHoldReleased(heldFingerprint, currentFingerprint, heldExpiresAtMs, current) {
148
+ if (current.state === "expired" || current.state === "missing")
149
+ return false;
150
+ if (current.state === "healthy") {
151
+ // A readable expiry beats the modified time. The same future expiry is
152
+ // not a renewal, even if the file was rewritten.
153
+ return current.expiresAtMs !== undefined
154
+ && (heldExpiresAtMs === undefined || current.expiresAtMs !== heldExpiresAtMs);
155
+ }
156
+ return credentialReplaced(heldFingerprint, currentFingerprint);
157
+ }
158
+ function isReportReason(value) {
159
+ return value === "time_limit" || value === "missing" || value === "auth_failure";
160
+ }
161
+ export function parseSignInHold(text) {
162
+ const record = asRecord(parseJson(text));
163
+ if (!record)
164
+ return undefined;
165
+ if (record.version !== 1 || record.reason !== "sign-in")
166
+ return undefined;
167
+ if (record.runtime !== "claude" && record.runtime !== "codex")
168
+ return undefined;
169
+ if (typeof record.fingerprint !== "string" || record.fingerprint === "")
170
+ return undefined;
171
+ if (typeof record.reported !== "boolean")
172
+ return undefined;
173
+ if (!isReportReason(record.report_reason))
174
+ return undefined;
175
+ if (typeof record.held_at !== "string")
176
+ return undefined;
177
+ let credentialExpiresAtMs;
178
+ if (Object.hasOwn(record, "credential_expires_at_ms")) {
179
+ if (typeof record.credential_expires_at_ms !== "number" || !Number.isFinite(record.credential_expires_at_ms))
180
+ return undefined;
181
+ credentialExpiresAtMs = record.credential_expires_at_ms;
182
+ }
183
+ return {
184
+ version: 1,
185
+ reason: "sign-in",
186
+ runtime: record.runtime,
187
+ fingerprint: record.fingerprint,
188
+ reported: record.reported,
189
+ report_reason: record.report_reason,
190
+ held_at: record.held_at,
191
+ ...(credentialExpiresAtMs !== undefined ? { credential_expires_at_ms: credentialExpiresAtMs } : {}),
192
+ };
193
+ }
194
+ function parseJson(text) {
195
+ try {
196
+ return JSON.parse(text);
197
+ }
198
+ catch {
199
+ return undefined;
200
+ }
201
+ }
202
+ function asRecord(value) {
203
+ if (!value || typeof value !== "object" || Array.isArray(value))
204
+ return undefined;
205
+ return value;
206
+ }
207
+ function scaleEpoch(number) {
208
+ if (!(number > 0) || !Number.isFinite(number))
209
+ return undefined;
210
+ return number < 1e12 ? number * 1000 : number;
211
+ }
212
+ /** Milliseconds. Seconds (below 1e12) are scaled. ISO instants pass through. */
213
+ function expiryMs(value) {
214
+ if (typeof value === "number")
215
+ return scaleEpoch(value);
216
+ if (typeof value !== "string")
217
+ return undefined;
218
+ const trimmed = value.trim();
219
+ if (/^\d+$/.test(trimmed))
220
+ return scaleEpoch(Number(trimmed));
221
+ const parsed = Date.parse(trimmed);
222
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : undefined;
223
+ }
224
+ function jwtExpMs(token) {
225
+ if (typeof token !== "string")
226
+ return undefined;
227
+ const parts = token.split(".");
228
+ if (parts.length < 3 || !parts[1])
229
+ return undefined;
230
+ try {
231
+ const payload = asRecord(JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8")));
232
+ return payload ? expiryMs(payload.exp) : undefined;
233
+ }
234
+ catch {
235
+ return undefined;
236
+ }
237
+ }
238
+ function claudeExpiresAtMs(data) {
239
+ const oauth = asRecord(data.claudeAiOauth);
240
+ return oauth ? expiryMs(oauth.expiresAt) : undefined;
241
+ }
242
+ function codexExpiresAtMs(data) {
243
+ const tokens = asRecord(data.tokens) ?? {};
244
+ return expiryMs(tokens.expires_at ?? data.expires_at ?? tokens.expiresAt)
245
+ ?? jwtExpMs(tokens.access_token ?? tokens.accessToken ?? data.access_token);
246
+ }
247
+ //# sourceMappingURL=core-job-model-auth.js.map
@@ -10,6 +10,7 @@ import { serializeJqJson } from "../lib/core-utils/jq-json-serializer.js";
10
10
  import { resolveLiveRoot } from "../utils/hq-roots.js";
11
11
  import { describeCoreCommand } from "./core-command-catalog.js";
12
12
  import { releaseChildWrapperPackageUseLeaseAfterStart } from "../utils/child-wrapper-lease.js";
13
+ import { credentialFingerprint, episodeIdFromReportBody, healthyCredentialRetryDue, localCredentialState, logTextIsProviderSignInFailure, logTextOpensSignInEpisode, MAX_CREDENTIAL_READ_BYTES, modelAuthFailureReason, parseSignInHold, signInHoldReleased, } from "./core-job-model-auth.js";
13
14
  const RUNNER_NAME = "hq-job-run";
14
15
  const RUNNER_PATH = fileURLToPath(import.meta.url);
15
16
  export const OUTPOST_IDENTITY_FILE = "/etc/outpost/codex-identity.env";
@@ -33,6 +34,13 @@ Behavior:
33
34
  failure_class to hq-pro jobs status (kind=run), bounded self-remediate,
34
35
  then dm-notify via hq-job-notify.sh (collapse 1/24h; never create-thread)
35
36
  - Missing runtime CLI auth: classify auth, notify re-login, exit 0 (unit OK)
37
+ - On an Outpost, a Claude or Codex sign-in failure also POSTs
38
+ /outpost/internal/model-auth-failure (best effort; a failed report does
39
+ not fail the job). When the Outpost confirms an episode, the per-job DM
40
+ is skipped and the Outpost sends one episode notice. The job is held
41
+ until the provider credential file is replaced, then the next scheduled
42
+ run proceeds. Missed runs are not replayed. A missing credential file is
43
+ held only after a confirmed episode. Off-Outpost runs keep the per-job DM.
36
44
 
37
45
  Runtime dispatch (US-001 spike flags):
38
46
  claude → claude -p … --output-format text --permission-mode bypassPermissions
@@ -795,21 +803,24 @@ function nextActionForClass(failureClass, runtime) {
795
803
  default: return "";
796
804
  }
797
805
  }
798
- function classifyFailure(exitCode, logFile, authHint = "", deps) {
799
- if (authHint && authHint !== "ok")
800
- return "auth";
801
- if (exitCode === 124 || exitCode === 137)
802
- return "timeout";
803
- let text = "";
806
+ function tailLog(logFile, deps) {
804
807
  try {
805
808
  const lines = deps.readFile(logFile).toString("utf8").split(/\r?\n/);
806
809
  if (lines[lines.length - 1] === "")
807
810
  lines.pop();
808
- text = lines.slice(-80).join("\n");
811
+ return lines.slice(-80).join("\n");
812
+ }
813
+ catch {
814
+ return "";
809
815
  }
810
- catch { /* tail ignores a missing log */ }
811
- const lower = text.toLowerCase();
812
- if (/not logged in|please log in|authentication (failed|required)|unauthorized|401|invalid.*(token|credential)|credentials? (missing|expired|invalid)|device.?code|login required/.test(lower))
816
+ }
817
+ function classifyFailure(exitCode, logFile, authHint = "", deps) {
818
+ if (authHint && authHint !== "ok")
819
+ return "auth";
820
+ if (exitCode === 124 || exitCode === 137)
821
+ return "timeout";
822
+ const lower = tailLog(logFile, deps).toLowerCase();
823
+ if (logTextIsProviderSignInFailure(lower))
813
824
  return "auth";
814
825
  if (/secret.*(not found|missing|denied|not visible|not shared)|hq secrets.*(fail|error|denied)|missing vault|access denied.*secret/.test(lower))
815
826
  return "secrets";
@@ -819,6 +830,175 @@ function classifyFailure(exitCode, logFile, authHint = "", deps) {
819
830
  return "infra";
820
831
  return exitCode === 0 ? "" : "agent_error";
821
832
  }
833
+ function isModelRuntime(runtime) {
834
+ return runtime === "claude" || runtime === "codex";
835
+ }
836
+ function credentialPath(runtime, env, home) {
837
+ return runtime === "claude"
838
+ ? env.HQ_JOB_PROBE_CLAUDE_CRED || path.join(home, ".claude/.credentials.json")
839
+ : env.HQ_JOB_PROBE_CODEX_AUTH || path.join(home, ".codex/auth.json");
840
+ }
841
+ function currentCredentialFingerprint(runtime, env, home, deps) {
842
+ if (!isModelRuntime(runtime))
843
+ return "absent";
844
+ try {
845
+ const info = deps.stat(credentialPath(runtime, env, home));
846
+ return credentialFingerprint({ size: info.size, mtimeMs: info.mtimeMs, ino: info.ino });
847
+ }
848
+ catch {
849
+ return "absent";
850
+ }
851
+ }
852
+ /** Expiry only. A file over the cap, or one that cannot be parsed, is `unknown`. */
853
+ function readLocalCredential(runtime, env, home, deps) {
854
+ try {
855
+ const file = credentialPath(runtime, env, home);
856
+ const info = deps.stat(file);
857
+ if (!(info.size > 0))
858
+ return { state: "missing" };
859
+ if (info.size > MAX_CREDENTIAL_READ_BYTES)
860
+ return { state: "unknown" };
861
+ return localCredentialState(runtime, deps.readFile(file).toString("utf8"), deps.now().getTime());
862
+ }
863
+ catch (error) {
864
+ const code = error.code;
865
+ if (code === "ENOENT" || code === "ENOTDIR")
866
+ return { state: "missing" };
867
+ return { state: "unknown" };
868
+ }
869
+ }
870
+ /**
871
+ * Episode reason. A provider CLI sign-in line wins. Otherwise only a missing
872
+ * credential file. A passed expiry date is not a failure.
873
+ */
874
+ function signInReportReason(logText, local) {
875
+ if (logTextOpensSignInEpisode(logText))
876
+ return modelAuthFailureReason(logText);
877
+ if (local.state === "missing")
878
+ return "missing";
879
+ return "";
880
+ }
881
+ function signInHoldPath(home, jobId) {
882
+ if (!/^[\w.-]+$/.test(jobId))
883
+ return undefined;
884
+ return path.join(home, ".hq", "jobs", "holds", `${jobId}.json`);
885
+ }
886
+ function readSignInHold(home, jobId, deps) {
887
+ const file = signInHoldPath(home, jobId);
888
+ if (!file)
889
+ return undefined;
890
+ try {
891
+ return parseSignInHold(deps.readFile(file).toString("utf8"));
892
+ }
893
+ catch {
894
+ return undefined;
895
+ }
896
+ }
897
+ function writeSignInHold(home, jobId, hold, deps) {
898
+ const file = signInHoldPath(home, jobId);
899
+ if (!file)
900
+ return;
901
+ try {
902
+ deps.mkdir(path.dirname(file));
903
+ deps.writeFile(file, compactJson(hold));
904
+ try {
905
+ deps.chmod(file, 0o600);
906
+ }
907
+ catch { /* chmod failure is ignored */ }
908
+ }
909
+ catch {
910
+ emitLog("sign-in hold was not saved (logged; not failing run)");
911
+ }
912
+ }
913
+ function clearSignInHold(home, jobId, deps) {
914
+ const file = signInHoldPath(home, jobId);
915
+ if (!file)
916
+ return;
917
+ try {
918
+ deps.remove(file);
919
+ }
920
+ catch { /* rm -f */ }
921
+ }
922
+ /**
923
+ * True only when the backend confirmed an episode: HTTP 2xx and a non-empty
924
+ * `episodeId`. The body is not logged. A 200 without that id, a 404, and a
925
+ * network error are all unconfirmed.
926
+ */
927
+ async function reportModelAuthFailure(identity, runtime, reason, deps) {
928
+ const controller = new AbortController();
929
+ const timeout = setTimeout(() => controller.abort(), 20_000);
930
+ let status;
931
+ let confirmed = false;
932
+ try {
933
+ const response = await deps.fetch(`${apiBase(deps.env)}/outpost/internal/model-auth-failure`, {
934
+ method: "POST",
935
+ redirect: "manual",
936
+ headers: {
937
+ "content-type": "application/json",
938
+ "x-outpost-instance-token": identity.instanceToken,
939
+ },
940
+ body: compactJson({
941
+ userId: identity.userId,
942
+ ...(identity.outpostId ? { outpostId: identity.outpostId } : {}),
943
+ runtime,
944
+ reason,
945
+ source: "job-runner",
946
+ }),
947
+ signal: controller.signal,
948
+ });
949
+ status = response.status;
950
+ if (status >= 200 && status < 300) {
951
+ try {
952
+ const body = typeof response.text === "function" ? await response.text() : "";
953
+ confirmed = episodeIdFromReportBody(body) !== undefined;
954
+ }
955
+ catch {
956
+ confirmed = false;
957
+ }
958
+ }
959
+ }
960
+ catch {
961
+ status = 0;
962
+ confirmed = false;
963
+ }
964
+ finally {
965
+ clearTimeout(timeout);
966
+ }
967
+ if (confirmed) {
968
+ emitLog(`model auth failure reported runtime=${runtime} http=${status}`);
969
+ return true;
970
+ }
971
+ emitLog(`model auth failure report failed runtime=${runtime} http=${status} (logged; not failing run)`);
972
+ return false;
973
+ }
974
+ /**
975
+ * Returns whether the backend confirmed an episode. The hold is written either way.
976
+ * The snapshot is the credential from before the run, so a renewal during the
977
+ * run still looks like a change on the next check.
978
+ */
979
+ async function openSignInHold(jobId, runtime, reason, identity, home, env, deps, snapshot) {
980
+ const fingerprint = snapshot?.fingerprint ?? currentCredentialFingerprint(runtime, env, home, deps);
981
+ const expiresAtMs = snapshot ? snapshot.expiresAtMs : readLocalCredential(runtime, env, home, deps).expiresAtMs;
982
+ const reported = await reportModelAuthFailure(identity, runtime, reason, deps);
983
+ saveSignInHold(jobId, runtime, reason, reported, fingerprint, expiresAtMs, home, deps);
984
+ return reported;
985
+ }
986
+ function saveSignInHold(jobId, runtime, reason, reported, fingerprint, expiresAtMs, home, deps) {
987
+ writeSignInHold(home, jobId, {
988
+ version: 1,
989
+ reason: "sign-in",
990
+ runtime,
991
+ fingerprint,
992
+ reported,
993
+ report_reason: reason,
994
+ held_at: isoNow(deps),
995
+ ...(expiresAtMs !== undefined ? { credential_expires_at_ms: expiresAtMs } : {}),
996
+ }, deps);
997
+ }
998
+ function noteOutpostSignInNotifySkipped(logFile, deps) {
999
+ deps.appendFile(logFile, "notify_skipped=outpost_sign_in_episode\n");
1000
+ emitLog("notify skipped — Outpost sign-in failure uses the single episode notice");
1001
+ }
822
1002
  function canonicalPath(candidate) {
823
1003
  const absolute = path.resolve(candidate);
824
1004
  let cursor = absolute;
@@ -1050,6 +1230,20 @@ async function recordSkip(jobId, jobName, runtime, skipReason, failureClass, act
1050
1230
  const actions = nextAction ? [nextAction] : [];
1051
1231
  const runId = `run-${jobId}-${stamp}-${statusSuffix}`;
1052
1232
  await ingestRunStatus(jobId, endedAt, runId, 1, failureClass, actions, logFile, deps);
1233
+ if (failureClass === "auth" && authStatus === "missing" && isModelRuntime(runtime)) {
1234
+ const identity = resolveBoxIdentity(deps.env, deps);
1235
+ if (identity) {
1236
+ const fingerprint = currentCredentialFingerprint(runtime, deps.env, deps.home, deps);
1237
+ const expiresAtMs = readLocalCredential(runtime, deps.env, deps.home, deps).expiresAtMs;
1238
+ const confirmed = await reportModelAuthFailure(identity, runtime, "missing", deps);
1239
+ if (confirmed) {
1240
+ saveSignInHold(jobId, runtime, "missing", true, fingerprint, expiresAtMs, deps.home, deps);
1241
+ noteOutpostSignInNotifySkipped(logFile, deps);
1242
+ void logDir;
1243
+ return 0;
1244
+ }
1245
+ }
1246
+ }
1053
1247
  await callNotify(jobId, jobName, notifyOutcome, skipReason, duration, logFile, failureClass, nextAction, owner, notifyMode, hqRoot, notifyBin, deps);
1054
1248
  void logDir;
1055
1249
  return 0;
@@ -1146,6 +1340,44 @@ export async function runJob(argv, hqRootOverride, injected) {
1146
1340
  deps.appendFile(logFile, `=== hq-job-run ${jobId} ===\nstarted_at=${startedAt}\nruntime=${runtime}\ntimeout_seconds=${timeoutSeconds}\nsurface=${surface}\njob_file=${jobFile}\nhq_root=${hqRoot}\n`);
1147
1341
  const notifyBin = env.HQ_JOB_NOTIFY_BIN ?? "";
1148
1342
  const remediateBin = env.HQ_JOB_REMEDIATE_BIN ?? "";
1343
+ const boxIdentity = resolveBoxIdentity(env, deps);
1344
+ if (boxIdentity && isModelRuntime(runtime)) {
1345
+ const hold = readSignInHold(deps.home, jobId, deps);
1346
+ if (hold) {
1347
+ const current = currentCredentialFingerprint(runtime, env, deps.home, deps);
1348
+ const local = readLocalCredential(runtime, env, deps.home, deps);
1349
+ const released = signInHoldReleased(hold.fingerprint, current, hold.credential_expires_at_ms, local);
1350
+ // A healthy read whose expiry did not move still runs about hourly.
1351
+ // That is the only way a false hold cannot pause the job for days.
1352
+ const healthyRetry = !released && healthyCredentialRetryDue(hold.held_at, deps.now().getTime(), local.state);
1353
+ if (!released && !healthyRetry) {
1354
+ let reported = hold.reported;
1355
+ if (!reported) {
1356
+ reported = await reportModelAuthFailure(boxIdentity, hold.runtime, hold.report_reason, deps);
1357
+ if (reported)
1358
+ writeSignInHold(deps.home, jobId, { ...hold, reported: true }, deps);
1359
+ }
1360
+ const endedAt = isoNow(deps);
1361
+ const duration = elapsed(startedEpoch, deps);
1362
+ const skipReason = "sign-in hold";
1363
+ deps.appendFile(logFile, `skip_reason=${skipReason}\nsign_in_hold=waiting\nfailure_class=auth\n`);
1364
+ emitLog(`sign-in hold waiting for ${jobId}; credential unchanged`);
1365
+ deps.writeFile(statusFile, `exit=0\nskip_reason=${skipReason}\nfailure_class=auth\nstarted_at=${startedAt}\nended_at=${endedAt}\n`);
1366
+ appendMeterMarker(jobId, runtime, startedAt, endedAt, 0, duration, skipReason, deps);
1367
+ if (!reported) {
1368
+ await callNotify(jobId, jobName, "failed", skipReason, duration, logFile, "auth", nextActionForClass("auth", runtime), owner, notifyMode, hqRoot, notifyBin, deps);
1369
+ }
1370
+ return 0;
1371
+ }
1372
+ clearSignInHold(deps.home, jobId, deps);
1373
+ emitLog(healthyRetry
1374
+ ? `sign-in hold cleared — healthy credential retried, running ${jobId}`
1375
+ : local.state === "healthy"
1376
+ ? `sign-in hold cleared — credential is current, running ${jobId}`
1377
+ : `sign-in hold cleared — credential changed, running ${jobId}`);
1378
+ deps.appendFile(logFile, "sign_in_hold=cleared\n");
1379
+ }
1380
+ }
1149
1381
  const authStatus = readAuthStatus(runtime, env, deps.home, deps);
1150
1382
  if (authStatus !== "ok") {
1151
1383
  const reason = authStatus === "no_cli"
@@ -1167,12 +1399,34 @@ export async function runJob(argv, hqRootOverride, injected) {
1167
1399
  return emitDie(error instanceof Error ? error.message : String(error));
1168
1400
  }
1169
1401
  const secretNames = jobSecretNames(job);
1402
+ const credentialAtStart = boxIdentity && isModelRuntime(runtime)
1403
+ ? {
1404
+ fingerprint: currentCredentialFingerprint(runtime, env, deps.home, deps),
1405
+ expiresAtMs: readLocalCredential(runtime, env, deps.home, deps).expiresAtMs,
1406
+ }
1407
+ : undefined;
1170
1408
  let exitCode = await runAgent(runtime, surface, prompt, runCwd, timeoutSeconds, secretNames, company, logFile, stamp, jobId, logDir, deps, true);
1171
1409
  let failureClass = "";
1172
1410
  let nextAction = "";
1173
1411
  let retried = 0;
1412
+ let signInReason = "";
1413
+ const assignSignInReason = () => {
1414
+ signInReason = "";
1415
+ if (exitCode === 0 || !boxIdentity || !isModelRuntime(runtime))
1416
+ return;
1417
+ const local = readLocalCredential(runtime, env, deps.home, deps);
1418
+ const fingerprint = currentCredentialFingerprint(runtime, env, deps.home, deps);
1419
+ // A renewal that landed during this run is already current. The same
1420
+ // future expiry is not a renewal, even if the file was rewritten.
1421
+ if (credentialAtStart
1422
+ && local.state === "healthy"
1423
+ && signInHoldReleased(credentialAtStart.fingerprint, fingerprint, credentialAtStart.expiresAtMs, local))
1424
+ return;
1425
+ signInReason = signInReportReason(tailLog(logFile, deps), local);
1426
+ };
1174
1427
  if (exitCode !== 0) {
1175
1428
  failureClass = classifyFailure(exitCode, logFile, "", deps);
1429
+ assignSignInReason();
1176
1430
  deps.appendFile(logFile, `failure_class=${failureClass}\n`);
1177
1431
  const remediation = await callRemediate(failureClass, jobId, company, hqRoot, remediateBin, logFile, deps);
1178
1432
  deps.appendFile(logFile, `remediate=${remediation}\n`);
@@ -1192,12 +1446,14 @@ export async function runJob(argv, hqRootOverride, injected) {
1192
1446
  exitCode = await runAgent(runtime, surface, prompt, runCwd, timeoutSeconds, secretNames, company, logFile, stamp, jobId, logDir, deps, true);
1193
1447
  if (exitCode !== 0) {
1194
1448
  failureClass = classifyFailure(exitCode, logFile, "", deps);
1449
+ assignSignInReason();
1195
1450
  deps.appendFile(logFile, `failure_class_after_retry=${failureClass}\n`);
1196
1451
  nextAction = nextActionForClass(failureClass, runtime);
1197
1452
  }
1198
1453
  else {
1199
1454
  failureClass = "";
1200
1455
  nextAction = "";
1456
+ signInReason = "";
1201
1457
  }
1202
1458
  }
1203
1459
  }
@@ -1209,6 +1465,7 @@ export async function runJob(argv, hqRootOverride, injected) {
1209
1465
  appendMeterMarker(jobId, runtime, startedAt, endedAt, exitCode, duration, "", deps);
1210
1466
  const runId = `run-${jobId}-${stamp}`;
1211
1467
  if (exitCode === 0) {
1468
+ clearSignInHold(deps.home, jobId, deps);
1212
1469
  await ingestRunStatus(jobId, endedAt, runId, 0, "", [], logFile, deps);
1213
1470
  const summary = retried === 1 ? "completed ok after self-remediation retry" : "completed ok";
1214
1471
  await callNotify(jobId, jobName, "ok", summary, duration, logFile, "", "", owner, notifyMode, hqRoot, notifyBin, deps);
@@ -1216,8 +1473,19 @@ export async function runJob(argv, hqRootOverride, injected) {
1216
1473
  return 0;
1217
1474
  }
1218
1475
  await ingestRunStatus(jobId, endedAt, runId, Math.max(0, Math.min(255, exitCode)), failureClass, nextAction ? [nextAction] : [], logFile, deps);
1219
- const summary = `exit=${exitCode} class=${failureClass}`;
1220
- await callNotify(jobId, jobName, "failed", summary, duration, logFile, failureClass, nextAction, owner, notifyMode, hqRoot, notifyBin, deps);
1476
+ if (signInReason && boxIdentity && isModelRuntime(runtime)) {
1477
+ const confirmed = await openSignInHold(jobId, runtime, signInReason, boxIdentity, deps.home, env, deps, credentialAtStart);
1478
+ if (confirmed)
1479
+ noteOutpostSignInNotifySkipped(logFile, deps);
1480
+ else {
1481
+ const summary = `exit=${exitCode} class=${failureClass}`;
1482
+ await callNotify(jobId, jobName, "failed", summary, duration, logFile, failureClass, nextAction, owner, notifyMode, hqRoot, notifyBin, deps);
1483
+ }
1484
+ }
1485
+ else {
1486
+ const summary = `exit=${exitCode} class=${failureClass}`;
1487
+ await callNotify(jobId, jobName, "failed", summary, duration, logFile, failureClass, nextAction, owner, notifyMode, hqRoot, notifyBin, deps);
1488
+ }
1221
1489
  emitLog(`job ${jobId} failed exit=${exitCode} class=${failureClass} (${duration}s) log=${logFile}`);
1222
1490
  return exitCode;
1223
1491
  }
@@ -324,6 +324,7 @@ export const SCAFFOLD_ONLY_ASSETS = [
324
324
  { asset: "core/scripts/lib/session-id.sh", root: "live", summary: "Session-id resolver lib sourced by hq-session" },
325
325
  { asset: "core/scripts/lib/hq-cli-floor.sh", root: "live", summary: "Shared CLI version-floor helper sourced by generated forwarders" },
326
326
  { asset: "core/scripts/lib/delegate-brainstorm.sh", root: "live", summary: "Shared brainstorm-stage data helper sourced by delegate assets" },
327
+ { asset: "core/scripts/lib/delegate-engine.sh", root: "live", summary: "Sync-engine vault helpers sourced by the bundled delegate grant helper" },
327
328
  { asset: "core/scripts/lib/forwarder.sh", root: "live", summary: "Shared runtime sourced by generated scaffold forwarders" },
328
329
  { asset: "core/scripts/lib/epochrealtime.sh", root: "live", summary: "Locale-safe epoch-realtime helper sourced by work-mesh-enqueue.sh" },
329
330
  { asset: "core/scripts/lib/work-mesh-enqueue.sh", root: "live", summary: "Work Mesh Live spool enqueue lib sourced by hooks" },
@@ -39,6 +39,7 @@ import * as fs from "node:fs";
39
39
  import * as path from "node:path";
40
40
  import { Readable } from "node:stream";
41
41
  import { pipeline } from "node:stream/promises";
42
+ import { raiseAccessRefresh } from "../lib/sync-core/access-refresh.js";
42
43
  import { S3Client, ListObjectsV2Command, GetObjectCommand, } from "@aws-sdk/client-s3";
43
44
  import { VaultClient, } from "@indigoai-us/hq-cloud";
44
45
  import { isPrivateFolderPattern } from "./_patterns.js";
@@ -694,6 +695,7 @@ export async function runGet(input) {
694
695
  if (input.into === undefined) {
695
696
  addPin(hqRoot, slug, bucketPrefix);
696
697
  pinned = { companySlug: slug, prefix: bucketPrefix };
698
+ raiseAccessRefresh({ companyUid: entity.uid, companySlug: slug });
697
699
  }
698
700
  return { filesWritten: keys.length, bytesWritten, destinations, pinned };
699
701
  }