@indigoai-us/hq-cli 5.345.47 → 5.345.48

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.
@@ -1,9 +1,153 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import * as yaml from "js-yaml";
1
4
  import { buildSecretUsage, extractApiMessage, highSecuritySandboxOnlyMessage, loadRevealedSecrets, normalizeScriptLockMode, normalizeSecretTier, parseSecretNameList, runSecretsEnvCommand, scopeOpts, secretsCredentialOptions, } from "../secrets-env-action.js";
2
5
  export { buildSecretUsage, emitEnvExportsAndExit, loadRevealedSecrets, parseSecretNameList, runSecretsEnvCommand, } from "../secrets-env-action.js";
6
+ export function readSessionCompanyLock(env = process.env) {
7
+ const root = resolveDefaultHqRoot({ env });
8
+ const sessionId = resolveSessionId(root, env);
9
+ if (!sessionId)
10
+ return undefined;
11
+ const sessionDir = path.join(root, "workspace/sessions", sessionId);
12
+ const capabilityPath = path.join(sessionDir, "scope-capability.json");
13
+ const metaPath = path.join(sessionDir, "meta.yaml");
14
+ let primary;
15
+ let companies;
16
+ let hasCapability = false;
17
+ try {
18
+ fs.lstatSync(capabilityPath);
19
+ hasCapability = true;
20
+ }
21
+ catch (error) {
22
+ const code = error.code;
23
+ if (code !== "ENOENT" && code !== "ENOTDIR")
24
+ throw new Error("Cannot verify this session's company lock because its scope capability is unreadable.");
25
+ }
26
+ if (hasCapability) {
27
+ let value;
28
+ try {
29
+ value = JSON.parse(fs.readFileSync(capabilityPath, "utf8"));
30
+ }
31
+ catch {
32
+ throw new Error("Cannot verify this session's company lock because its scope capability is unreadable.");
33
+ }
34
+ if (!value || typeof value !== "object" || Array.isArray(value))
35
+ throw new Error("Cannot verify this session's company lock because its scope capability is invalid.");
36
+ const cap = value;
37
+ if (cap.session_id !== sessionId)
38
+ throw new Error("Cannot verify this session's company lock because its scope capability does not match the active session.");
39
+ if (typeof cap.company_slug !== "string" || !/^[A-Za-z0-9_-]+$/.test(cap.company_slug))
40
+ throw new Error("Cannot verify this session's company lock because its scope capability is invalid.");
41
+ primary = cap.company_slug;
42
+ if (cap.company_slugs === undefined)
43
+ companies = [primary];
44
+ else if (Array.isArray(cap.company_slugs)
45
+ && cap.company_slugs.length > 0
46
+ && cap.company_slugs.every((slug) => typeof slug === "string" && /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(slug))
47
+ && cap.company_slugs[0] === primary
48
+ && new Set(cap.company_slugs).size === cap.company_slugs.length
49
+ && ((primary === "personal" && cap.company_slugs.length === 1)
50
+ || (primary !== "personal" && !cap.company_slugs.includes("personal"))))
51
+ companies = [...cap.company_slugs];
52
+ else
53
+ throw new Error("Cannot verify this session's company lock because its scope capability is invalid.");
54
+ }
55
+ else {
56
+ try {
57
+ const meta = fs.readFileSync(metaPath, "utf8");
58
+ const read = (key) => meta.split(/\r?\n/).find((line) => new RegExp(`^\\s*${key}:`).test(line))?.replace(/^\s*[^:]+:\s*/, "").replace(/^"|"$/g, "") ?? "";
59
+ primary = read("company_slug");
60
+ const hasList = meta.split(/\r?\n/).some((line) => /^\s*company_slugs:/.test(line));
61
+ const listed = hasList ? read("company_slugs") : "";
62
+ if (hasList && (!listed || !primary))
63
+ throw new Error("invalid company lock");
64
+ companies = hasList ? listed.split(",") : primary ? [primary] : [];
65
+ if (companies.some((slug) => !/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/.test(slug)))
66
+ throw new Error("invalid company lock");
67
+ if (new Set(companies).size !== companies.length)
68
+ throw new Error("invalid company lock");
69
+ if (primary && companies[0] !== primary)
70
+ throw new Error("invalid company lock");
71
+ if (companies.length > 1 && companies.includes("personal"))
72
+ throw new Error("invalid company lock");
73
+ }
74
+ catch (error) {
75
+ const code = error.code;
76
+ if (code === "ENOENT" || code === "ENOTDIR" || code === "EACCES")
77
+ return { sessionId, companies: [] };
78
+ throw new Error("Cannot verify this session's company lock because its metadata is invalid.");
79
+ }
80
+ }
81
+ const real = companies.filter((slug) => {
82
+ if (slug === "personal")
83
+ return true;
84
+ try {
85
+ const companyPath = path.join(root, "companies", slug);
86
+ const stat = fs.lstatSync(companyPath);
87
+ return stat.isDirectory() && !stat.isSymbolicLink();
88
+ }
89
+ catch {
90
+ return false;
91
+ }
92
+ });
93
+ if (primary && real[0] !== primary)
94
+ return { sessionId, companies: [] };
95
+ return { sessionId, companies: real };
96
+ }
97
+ function companyUidForSlug(root, slug) {
98
+ try {
99
+ const doc = yaml.load(fs.readFileSync(path.join(root, "companies", "manifest.yaml"), "utf8"));
100
+ const uid = doc.companies?.[slug]?.cloud_uid;
101
+ return typeof uid === "string" && looksLikeCompanyUid(uid) ? uid : undefined;
102
+ }
103
+ catch {
104
+ return undefined;
105
+ }
106
+ }
107
+ function companySlugForUid(root, companies, uid) {
108
+ if (!looksLikeCompanyUid(uid))
109
+ return undefined;
110
+ try {
111
+ const doc = yaml.load(fs.readFileSync(path.join(root, "companies", "manifest.yaml"), "utf8"));
112
+ return companies.find((slug) => doc.companies?.[slug]?.cloud_uid === uid);
113
+ }
114
+ catch {
115
+ return undefined;
116
+ }
117
+ }
118
+ async function resolveApiKeyCompanyWithinLock(input) {
119
+ let candidates = input.companies;
120
+ if (input.requestedCompany) {
121
+ const companySlug = input.companies.includes(input.requestedCompany)
122
+ ? input.requestedCompany
123
+ : companySlugForUid(input.root, input.companies, input.requestedCompany);
124
+ if (!companySlug) {
125
+ throw new Error("HQ_API_KEY is not bound to a company in this session's locked company set.");
126
+ }
127
+ candidates = [companySlug];
128
+ }
129
+ for (const companySlug of candidates) {
130
+ const companyUid = companyUidForSlug(input.root, companySlug);
131
+ if (!companyUid)
132
+ continue;
133
+ const response = await vaultApiFetch({ token: input.token, path: `/v1/keys/secrets/${encodeURIComponent(companyUid)}` });
134
+ if (response.ok)
135
+ return { companyUid, companySlug };
136
+ if (response.status === 401)
137
+ throw new Error("HQ_API_KEY is invalid or no longer active.");
138
+ if (response.status !== 403)
139
+ throw new Error(`Could not verify HQ_API_KEY company scope (HTTP ${response.status}).`);
140
+ }
141
+ throw new Error("HQ_API_KEY is not bound to a company in this session's locked company set.");
142
+ }
3
143
  import chalk from "chalk";
4
144
  import { ensureCognitoToken } from "../utils/cognito-session.js";
5
145
  import { removeCacheEntry, clearAllCache } from "../utils/secrets-cache.js";
6
146
  import { isHqCliChild, releaseChildWrapperPackageUseLeaseAfterStart } from "../utils/child-wrapper-lease.js";
147
+ import { resolveDefaultHqRoot } from "../utils/hq-root-resolver.js";
148
+ import { fastFlagEnabled } from "../native-fast-route.js";
149
+ import { MULTI_COMPANY_SESSION_LOCK_FLAG } from "../lib/cli-flag-keys.js";
150
+ import { resolveSessionId } from "../lib/core-utils/session-id.js";
7
151
  import { secretsExecChildExitCode } from "../utils/child-wrapper-exit.js";
8
152
  import { isPlanGateError } from "../utils/plan-gate-error.js";
9
153
  import { SECRET_NAME_PATTERN, GROUP_ID_PATTERN, EMAIL_PATTERN } from "./_patterns.js";
@@ -1085,6 +1229,7 @@ export function registerSecretsCommand(program) {
1085
1229
  .command("exec")
1086
1230
  .description("Run a command with secrets injected as env vars")
1087
1231
  .requiredOption("--only <keys>", "Secret names to inject (comma-separated; may be repeated) (required)", collectSecretNames)
1232
+ .option("--company <slug>", "Company slug (resolves to companyUid)")
1088
1233
  .option("--script <path>", "Attach local script identity for script-locked secrets")
1089
1234
  .option("--script-id <id>", "Stable script identifier approved by policy")
1090
1235
  .allowUnknownOption(true)
@@ -1104,10 +1249,44 @@ export function registerSecretsCommand(program) {
1104
1249
  process.exit(1);
1105
1250
  }
1106
1251
  const keys = parseSecretNameList(_opts.only);
1252
+ const multiCompanyLockEnabled = await fastFlagEnabled(MULTI_COMPANY_SESSION_LOCK_FLAG);
1253
+ const sessionLock = multiCompanyLockEnabled ? readSessionCompanyLock(process.env) : undefined;
1254
+ const parentScope = secrets.opts();
1255
+ const inheritedCompany = parentScope.company;
1256
+ const requestedCompany = _opts.company ?? inheritedCompany;
1257
+ const hasLockedCompanies = (sessionLock?.companies.length ?? 0) > 0;
1258
+ const lockRoot = hasLockedCompanies ? resolveDefaultHqRoot({ env: process.env }) : undefined;
1259
+ const selectedCompany = (hasLockedCompanies && requestedCompany && looksLikeCompanyUid(requestedCompany)
1260
+ ? companySlugForUid(lockRoot, sessionLock.companies, requestedCompany) ?? requestedCompany
1261
+ : requestedCompany)
1262
+ ?? (multiCompanyLockEnabled && !parentScope.personal ? sessionLock?.companies[0] : undefined);
1263
+ if (hasLockedCompanies && selectedCompany && !sessionLock.companies.includes(selectedCompany)) {
1264
+ throw new Error(`Company '${selectedCompany}' is outside this session's locked company set.`);
1265
+ }
1266
+ if (hasLockedCompanies && parentScope.personal && !sessionLock.companies.includes("personal")) {
1267
+ throw new Error("Personal scope is outside this session's locked company set.");
1268
+ }
1269
+ if (hasLockedCompanies && !selectedCompany && !parentScope.personal) {
1270
+ throw new Error("This session has no locked company scope for secrets exec.");
1271
+ }
1272
+ if (hasLockedCompanies && !requestedCompany && sessionLock.companies.length > 1) {
1273
+ console.error(`Using primary company ${sessionLock.companies[0]} from this session's lock; pass --company <slug> to choose another locked company.`);
1274
+ }
1275
+ const secretScope = selectedCompany === "personal"
1276
+ ? scopeOpts({ personal: true })
1277
+ : scopeOpts({ ...parentScope, ...(selectedCompany ? { company: selectedCompany } : {}) });
1107
1278
  const cred = await resolveVaultCredentialForCapability("secrets:read", "secrets exec", secretsCredentialOptions());
1279
+ const apiKeyCompany = cred.kind === "api-key" && hasLockedCompanies
1280
+ ? await resolveApiKeyCompanyWithinLock({
1281
+ token: cred.token,
1282
+ root: lockRoot,
1283
+ companies: sessionLock.companies,
1284
+ ...(requestedCompany ? { requestedCompany } : {}),
1285
+ })
1286
+ : undefined;
1108
1287
  const companyUid = cred.kind === "api-key"
1109
- ? "__api_key__"
1110
- : await getEntityUid(cred.token, scopeOpts(secrets.opts()), { allowOfflineScopeFallback: true });
1288
+ ? (apiKeyCompany?.companyUid ?? "__api_key__")
1289
+ : await getEntityUid(cred.token, secretScope, { allowOfflineScopeFallback: true });
1111
1290
  const readSecrets = async () => loadRevealedSecrets(cred.token, companyUid, keys, cred.kind === "cognito"
1112
1291
  ? await buildSecretUsage("exec", _opts.script, _opts.scriptId)
1113
1292
  : undefined, { allowOfflineFallback: true });
@@ -6,12 +6,15 @@ import { type RegistryWorker } from "../lib/workers-registry/read.js";
6
6
  * company_slug. Undefined when no session context is set. Pure/read-only.
7
7
  */
8
8
  export declare function resolveActiveCompany(hqRoot: string): string | undefined;
9
+ /** Resolve the active ordered lock set; default-off preserves primary-only access. */
10
+ export declare function resolveActiveCompanies(hqRoot: string, multiCompanyLockEnabled: boolean): string[] | undefined;
11
+ export declare function denyWorkerCompanyOutsideLock(company: string, lockedCompanies: string[] | undefined): boolean;
9
12
  /**
10
13
  * Membership-aware access filter for worker discovery: public workers always;
11
14
  * company workers only for the active company. Mirrors the /run skill and the
12
15
  * inject-worker-suggestion hook so all three surfaces agree.
13
16
  */
14
- export declare function filterAccessibleWorkers(workers: RegistryWorker[], activeCompany: string | undefined): RegistryWorker[];
17
+ export declare function filterAccessibleWorkers(workers: RegistryWorker[], activeCompany: string | string[] | undefined): RegistryWorker[];
15
18
  /**
16
19
  * The company-relative vault prefix for a worker, e.g.
17
20
  * companies/indigo/workers/deal-brain/ -> workers/deal-brain/. Returns null for
@@ -7,6 +7,9 @@ import { ensureCognitoToken } from "../utils/cognito-session.js";
7
7
  import { vaultApiFetch, getCompanyUid } from "./secrets.js";
8
8
  import { GROUP_ID_PATTERN, EMAIL_PATTERN, toSharedFolderGlob } from "./_patterns.js";
9
9
  import { findHqRoot } from "../utils/manifest.js";
10
+ import { fastFlagEnabled } from "../native-fast-route.js";
11
+ import { MULTI_COMPANY_SESSION_LOCK_FLAG } from "../lib/cli-flag-keys.js";
12
+ import { resolveSessionId } from "../lib/core-utils/session-id.js";
10
13
  export { readWorkerRegistry } from "../lib/workers-registry/read.js";
11
14
  import { readWorkerRegistry } from "../lib/workers-registry/read.js";
12
15
  /**
@@ -14,34 +17,68 @@ import { readWorkerRegistry } from "../lib/workers-registry/read.js";
14
17
  * company_slug. Undefined when no session context is set. Pure/read-only.
15
18
  */
16
19
  export function resolveActiveCompany(hqRoot) {
20
+ return resolveActiveCompanies(hqRoot, false)?.[0];
21
+ }
22
+ /** Resolve the active ordered lock set; default-off preserves primary-only access. */
23
+ export function resolveActiveCompanies(hqRoot, multiCompanyLockEnabled) {
24
+ const current = resolveSessionId(hqRoot);
25
+ if (!current)
26
+ return undefined;
17
27
  try {
18
- const currentFile = path.join(hqRoot, "workspace/sessions/.current");
19
- const current = fs.readFileSync(currentFile, "utf8").trim();
20
- if (!current)
21
- return undefined;
22
28
  const metaPath = path.join(hqRoot, "workspace/sessions", current, "meta.yaml");
23
29
  if (!fs.existsSync(metaPath))
24
- return undefined;
30
+ return multiCompanyLockEnabled ? [] : undefined;
25
31
  const meta = yaml.load(fs.readFileSync(metaPath, "utf8"));
26
- const co = meta?.company_slug;
27
- return typeof co === "string" && co ? co : undefined;
32
+ const primary = meta?.company_slug;
33
+ if (typeof primary !== "string" || !/^[A-Za-z0-9_-]+$/.test(primary))
34
+ return multiCompanyLockEnabled ? [] : undefined;
35
+ const rawListed = meta?.company_slugs;
36
+ const listed = multiCompanyLockEnabled && typeof rawListed === "string"
37
+ ? rawListed.split(",")
38
+ : [primary];
39
+ if (!multiCompanyLockEnabled)
40
+ return [primary];
41
+ const companies = [...new Set(listed.filter((slug) => {
42
+ if (typeof slug !== "string" || !/^[A-Za-z0-9_-]+$/.test(slug))
43
+ return false;
44
+ if (slug === "personal")
45
+ return true;
46
+ try {
47
+ const stat = fs.lstatSync(path.join(hqRoot, "companies", slug));
48
+ return stat.isDirectory() && !stat.isSymbolicLink();
49
+ }
50
+ catch {
51
+ return false;
52
+ }
53
+ }))];
54
+ if (companies.length > 1 && companies.includes("personal"))
55
+ return [primary];
56
+ return companies[0] === primary ? companies : undefined;
28
57
  }
29
58
  catch {
30
- return undefined;
59
+ return multiCompanyLockEnabled ? [] : undefined;
31
60
  }
32
61
  }
62
+ export function denyWorkerCompanyOutsideLock(company, lockedCompanies) {
63
+ if (lockedCompanies === undefined || lockedCompanies.includes(company))
64
+ return false;
65
+ console.error(`Company '${company}' is outside this session's locked company set.`);
66
+ process.exitCode = 1;
67
+ return true;
68
+ }
33
69
  /**
34
70
  * Membership-aware access filter for worker discovery: public workers always;
35
71
  * company workers only for the active company. Mirrors the /run skill and the
36
72
  * inject-worker-suggestion hook so all three surfaces agree.
37
73
  */
38
74
  export function filterAccessibleWorkers(workers, activeCompany) {
75
+ const allowed = new Set(Array.isArray(activeCompany) ? activeCompany : activeCompany ? [activeCompany] : []);
39
76
  return workers.filter((w) => {
40
77
  if (w.visibility === "public")
41
78
  return true;
42
79
  if (!w.company)
43
80
  return false;
44
- return activeCompany !== undefined && w.company === activeCompany;
81
+ return allowed.has(w.company);
45
82
  });
46
83
  }
47
84
  /**
@@ -159,14 +196,18 @@ async function runWorkersShare(workerId, opts) {
159
196
  console.log(chalk.green("✓"), `Shared worker '${workerId}' with ${classified.label} (${permission}).`);
160
197
  console.log(chalk.dim(` Vault prefix ${prefix} granted in company '${companySlug}'. It will sync to granted members and appear in their /run list.`));
161
198
  }
162
- function runWorkersList(opts) {
199
+ async function runWorkersList(opts) {
163
200
  const hqRoot = findHqRoot();
164
- const activeCompany = opts.company ?? resolveActiveCompany(hqRoot);
165
- let workers = filterAccessibleWorkers(readWorkerRegistry(hqRoot), activeCompany);
201
+ const enabled = await fastFlagEnabled(MULTI_COMPANY_SESSION_LOCK_FLAG);
202
+ const lockedCompanies = resolveActiveCompanies(hqRoot, enabled);
203
+ if (enabled && opts.company && denyWorkerCompanyOutsideLock(opts.company, lockedCompanies))
204
+ return;
205
+ const activeCompanies = opts.company ? [opts.company] : lockedCompanies;
206
+ let workers = filterAccessibleWorkers(readWorkerRegistry(hqRoot), activeCompanies);
166
207
  if (opts.shared)
167
208
  workers = workers.filter((w) => Boolean(w.grants && w.grants.trim()));
168
209
  if (opts.mine)
169
- workers = workers.filter((w) => Boolean(w.company) && w.company === activeCompany);
210
+ workers = workers.filter((w) => Boolean(w.company) && activeCompanies?.includes(w.company) === true);
170
211
  if (workers.length === 0) {
171
212
  console.log("No accessible workers.");
172
213
  return;
@@ -185,8 +226,9 @@ function runWorkersList(opts) {
185
226
  }
186
227
  };
187
228
  printGroup("Public", publicWorkers);
188
- if (activeCompany)
189
- printGroup(activeCompany, companyWorkers);
229
+ for (const company of activeCompanies ?? []) {
230
+ printGroup(company, companyWorkers.filter((worker) => worker.company === company));
231
+ }
190
232
  console.log(chalk.dim("\nUsage: hq run {worker-id} [skill] [args]"));
191
233
  console.log(chalk.dim("Share a company worker: hq workers share {worker-id} --with {grp_<name>|@all} --permission read"));
192
234
  }
@@ -1,3 +1,4 @@
1
1
  /** hq-flags keys used by CLI-wide routes. */
2
2
  export declare const CLI_COMMAND_HELP_CATALOG_FLAG = "cli.command-help-catalog";
3
+ export declare const MULTI_COMPANY_SESSION_LOCK_FLAG = "hooks.multi-company-session-lock";
3
4
  //# sourceMappingURL=cli-flag-keys.d.ts.map
@@ -1,3 +1,4 @@
1
1
  /** hq-flags keys used by CLI-wide routes. */
2
2
  export const CLI_COMMAND_HELP_CATALOG_FLAG = "cli.command-help-catalog";
3
+ export const MULTI_COMPANY_SESSION_LOCK_FLAG = "hooks.multi-company-session-lock";
3
4
  //# sourceMappingURL=cli-flag-keys.js.map
@@ -0,0 +1,6 @@
1
+ export declare const SESSION_ID_ENV_KEYS: readonly ["HQ_SESSION_ID", "CLAUDE_CODE_SESSION_ID", "CLAUDE_SESSION_ID", "CODEX_SESSION_ID", "CODEX_THREAD_ID", "GROK_SESSION_ID"];
2
+ export declare function validSessionId(value: string): boolean;
3
+ export declare function sessionIdFromEnv(env: NodeJS.ProcessEnv): string;
4
+ /** Resolve the caller's session before using the global, last-writer-wins .current fallback. */
5
+ export declare function resolveSessionId(root: string, env?: NodeJS.ProcessEnv, readFile?: (filePath: string, encoding: BufferEncoding) => string): string;
6
+ //# sourceMappingURL=session-id.d.ts.map
@@ -0,0 +1,35 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ export const SESSION_ID_ENV_KEYS = [
4
+ "HQ_SESSION_ID",
5
+ "CLAUDE_CODE_SESSION_ID",
6
+ "CLAUDE_SESSION_ID",
7
+ "CODEX_SESSION_ID",
8
+ "CODEX_THREAD_ID",
9
+ "GROK_SESSION_ID",
10
+ ];
11
+ export function validSessionId(value) {
12
+ return Boolean(value) && value !== "." && value !== ".." && /^[A-Za-z0-9._-]+$/.test(value);
13
+ }
14
+ export function sessionIdFromEnv(env) {
15
+ for (const key of SESSION_ID_ENV_KEYS) {
16
+ const value = (env[key] ?? "").replace(/[\t\n\v\f\r ]/g, "");
17
+ if (validSessionId(value))
18
+ return value;
19
+ }
20
+ return "";
21
+ }
22
+ /** Resolve the caller's session before using the global, last-writer-wins .current fallback. */
23
+ export function resolveSessionId(root, env = process.env, readFile = (filePath, encoding) => fs.readFileSync(filePath, encoding)) {
24
+ const fromEnv = sessionIdFromEnv(env);
25
+ if (fromEnv)
26
+ return fromEnv;
27
+ try {
28
+ const current = readFile(path.join(root, "workspace", "sessions", ".current"), "utf8").replace(/[\t\n\v\f\r ]/g, "");
29
+ return validSessionId(current) ? current : "";
30
+ }
31
+ catch {
32
+ return "";
33
+ }
34
+ }
35
+ //# sourceMappingURL=session-id.js.map
@@ -230,7 +230,7 @@ function planService(service, ctx) {
230
230
  return [
231
231
  base(service, {
232
232
  kind: "scheduled",
233
- // Polls every 15 s so keep-alive resumes are admitted on time (#1396).
233
+ // Polls every 15 s so local keep-alive resumes are admitted on time (#1396).
234
234
  // Each pass is a fresh `hq` node process (~1.8 s CPU, ~200 MB RSS), so
235
235
  // desktops first check the lane store in-process
236
236
  // (lanes-reconcile-guard.ts) and fall back to the pre-#1396 60 s
@@ -7,12 +7,13 @@
7
7
  * JSON reads, no child process) and tells the supervisor how urgent the next
8
8
  * pass is:
9
9
  *
10
- * - `spawn`: something the 15-second cadence exists for may be due — lane
11
- * admission, a running lane's heartbeat, or a keep-alive resume (#1396).
10
+ * - `spawn`: something the desktop's 15-second cadence exists for may be due —
11
+ * local lane admission/heartbeat, a local keep-alive resume (#1396), or a
12
+ * pending question.
12
13
  * - `idle`: only work that ran on the pre-#1396 60-second cadence remains
13
- * (terminal lanes, worker-profile resumes, question aging, Codex rollout
14
- * retention, lead-autopilot registry). The supervisor runs it at most once
15
- * per `idleIntervalSec`.
14
+ * (terminal lanes, worker-profile resumes, question aging, outpost mirror
15
+ * refresh, Codex retention, lead-autopilot registry). The supervisor runs it
16
+ * at most once per `idleIntervalSec`.
16
17
  * - `skip`: the store holds no lane or question records, no lead registry and
17
18
  * no lanes config, so a reconcile pass has no input to act on.
18
19
  *
@@ -7,12 +7,13 @@
7
7
  * JSON reads, no child process) and tells the supervisor how urgent the next
8
8
  * pass is:
9
9
  *
10
- * - `spawn`: something the 15-second cadence exists for may be due — lane
11
- * admission, a running lane's heartbeat, or a keep-alive resume (#1396).
10
+ * - `spawn`: something the desktop's 15-second cadence exists for may be due —
11
+ * local lane admission/heartbeat, a local keep-alive resume (#1396), or a
12
+ * pending question.
12
13
  * - `idle`: only work that ran on the pre-#1396 60-second cadence remains
13
- * (terminal lanes, worker-profile resumes, question aging, Codex rollout
14
- * retention, lead-autopilot registry). The supervisor runs it at most once
15
- * per `idleIntervalSec`.
14
+ * (terminal lanes, worker-profile resumes, question aging, outpost mirror
15
+ * refresh, Codex retention, lead-autopilot registry). The supervisor runs it
16
+ * at most once per `idleIntervalSec`.
16
17
  * - `skip`: the store holds no lane or question records, no lead registry and
17
18
  * no lanes config, so a reconcile pass has no input to act on.
18
19
  *
@@ -38,6 +39,9 @@ export const LEAD_REGISTRY_FILE = path.join("workspace", "lane-briefs", "juniors
38
39
  * keep-alive, which is checked separately.
39
40
  */
40
41
  const QUIET_LANE_STATES = new Set(["done", "failed", "interrupted", "cancelled", "killed", "blocked"]);
42
+ const KNOWN_LANE_STATES = new Set([
43
+ "queued", "running", "awaiting_input", "blocked", "done", "failed", "interrupted", "cancelled", "killed",
44
+ ]);
41
45
  const realFs = {
42
46
  readdirSync: (dir) => fs.readdirSync(dir),
43
47
  readFileSync: (file, encoding) => fs.readFileSync(file, encoding),
@@ -63,9 +67,24 @@ function readRecord(fsDeps, file) {
63
67
  }
64
68
  return parsed;
65
69
  }
66
- /** A lane that may need the 15-second cadence. Unknown shapes count as urgent. */
70
+ /** A lane that may need the desktop's 15-second cadence. Unknown shapes count as urgent. */
67
71
  function laneIsUrgent(lane) {
68
- if (typeof lane.state !== "string" || !QUIET_LANE_STATES.has(lane.state))
72
+ if (typeof lane.state !== "string" || !KNOWN_LANE_STATES.has(lane.state))
73
+ return true;
74
+ const host = lane.host;
75
+ if (typeof host !== "object" || host === null || Array.isArray(host))
76
+ return true;
77
+ const hostRecord = host;
78
+ if (typeof hostRecord.id !== "string" || hostRecord.id.length === 0)
79
+ return true;
80
+ // This guard is installed only on desktops. The outpost's own daemon keeps
81
+ // its 15-second cadence; the desktop's outpost mirror/registry refresh can
82
+ // use the 60-second idle cadence. Pending questions remain urgent below.
83
+ if (hostRecord.kind === "outpost")
84
+ return false;
85
+ if (hostRecord.kind !== "local")
86
+ return true;
87
+ if (!QUIET_LANE_STATES.has(lane.state))
69
88
  return true;
70
89
  if (lane.keep_alive === true)
71
90
  return true;
@@ -14,6 +14,12 @@ import { type HostApp } from "./supervisor.js";
14
14
  export declare const LOG_ROTATE_BYTES: number;
15
15
  /** Exit code for "restart me": non-zero so every service manager relaunches (Windows tasks only restart on failure). */
16
16
  export declare const RESTART_EXIT_CODE = 75;
17
+ /** A bounded shutdown deadline that can account for sync push persistence. */
18
+ export declare function createShutdownCap(): {
19
+ promise: Promise<"timeout">;
20
+ extendForSyncRunnerPersist(): void;
21
+ clear(): void;
22
+ };
17
23
  export interface DaemonLockConflictOutcome {
18
24
  exitCode: 0 | 1;
19
25
  stdout?: string;
@@ -45,12 +45,36 @@ import { stageHqChildBootstrap } from "./hq-child-bootstrap-stage.js";
45
45
  import { runnerSessionName } from "./remote-control.js";
46
46
  import { adoptChild, createChildTracker, finishSuccession, handoffEligible, readProcStart, stopOrphans, successionPaths, systemdKillMode, takeSuccession, writeHandoff, } from "./succession.js";
47
47
  import { listSyncRunnerProcesses, readWatchRunnerOwnerStatus, syncHeartbeatTimeoutMs, syncRunnerNodeOptions, watchRunnerOwnerStatusPath, } from "./sync-runner.js";
48
- import { STOP_ESCALATION_MS, createSupervisor, } from "./supervisor.js";
48
+ import { STOP_ESCALATION_MS, SYNC_RUNNER_PERSIST_GRACE_MS, createSupervisor, } from "./supervisor.js";
49
49
  import { userToolDirs } from "./tools.js";
50
50
  import { daemonRunGuard } from "./lanes-reconcile-guard.js";
51
51
  export const LOG_ROTATE_BYTES = 5 * 1024 * 1024;
52
52
  /** Exit code for "restart me": non-zero so every service manager relaunches (Windows tasks only restart on failure). */
53
53
  export const RESTART_EXIT_CODE = 75;
54
+ const NON_SYNC_SHUTDOWN_CAP_MS = STOP_ESCALATION_MS + 5_000;
55
+ const SYNC_RUNNER_SHUTDOWN_CAP_MS = STOP_ESCALATION_MS + SYNC_RUNNER_PERSIST_GRACE_MS + 5_000;
56
+ /** A bounded shutdown deadline that can account for sync push persistence. */
57
+ export function createShutdownCap() {
58
+ const startedAt = Date.now();
59
+ let deadline = startedAt + NON_SYNC_SHUTDOWN_CAP_MS;
60
+ let resolveCap;
61
+ let timer;
62
+ const promise = new Promise((resolve) => { resolveCap = resolve; });
63
+ const arm = () => {
64
+ if (timer)
65
+ clearTimeout(timer);
66
+ timer = setTimeout(() => resolveCap("timeout"), Math.max(0, deadline - Date.now()));
67
+ };
68
+ arm();
69
+ return {
70
+ promise,
71
+ extendForSyncRunnerPersist() {
72
+ deadline = Math.max(deadline, startedAt + SYNC_RUNNER_SHUTDOWN_CAP_MS);
73
+ arm();
74
+ },
75
+ clear() { clearTimeout(timer); },
76
+ };
77
+ }
54
78
  /** Preserve the legacy lock failure unless Anywhere explicitly enables the no-op behavior. */
55
79
  export function daemonLockConflictOutcome(lock, anywhereEnabled) {
56
80
  if (lock.ok)
@@ -772,6 +796,7 @@ export async function runDaemon(opts) {
772
796
  };
773
797
  // Set once the shutdown path exists below; a restart request before then is dropped.
774
798
  let restartDaemon = () => false;
799
+ let extendSyncShutdownCap;
775
800
  const supervisor = createSupervisor({
776
801
  machineType,
777
802
  host: opts.host,
@@ -794,6 +819,7 @@ export async function runDaemon(opts) {
794
819
  runGuard: daemonRunGuard,
795
820
  writeState: (state) => writeJsonAtomic(paths.statePath, state),
796
821
  log,
822
+ onSyncRunnerStopping: () => extendSyncShutdownCap?.(),
797
823
  syncOwnerBlockReason: () => {
798
824
  const config = readDaemonConfig(paths.configPath);
799
825
  const hqRoot = config.hqRoot ?? env.HQ_ROOT?.trim();
@@ -891,14 +917,15 @@ export async function runDaemon(opts) {
891
917
  stopping = true;
892
918
  log("info", `${why}; stopping services`);
893
919
  closeHqd();
894
- // The supervisor escalates to SIGKILL after STOP_ESCALATION_MS; the extra
895
- // margin only covers a child that survives even that.
896
- let capTimer;
897
- const cap = new Promise((r) => {
898
- capTimer = setTimeout(() => r("timeout"), STOP_ESCALATION_MS + 5_000);
899
- });
900
- void Promise.race([supervisor.stop(), cap]).then((result) => {
901
- clearTimeout(capTimer);
920
+ // Keep shutdown bounded, but let a stopping sync runner reach its persist deadline.
921
+ const cap = createShutdownCap();
922
+ extendSyncShutdownCap = cap.extendForSyncRunnerPersist;
923
+ if (supervisor.hasStoppingSyncRunner())
924
+ cap.extendForSyncRunnerPersist();
925
+ const servicesStopped = supervisor.stop();
926
+ void Promise.race([servicesStopped, cap.promise]).then((result) => {
927
+ cap.clear();
928
+ extendSyncShutdownCap = undefined;
902
929
  if (result === "timeout")
903
930
  log("error", "some services did not exit after SIGKILL; releasing the lock anyway");
904
931
  else
@@ -13,7 +13,8 @@
13
13
  * - restart/trigger/stop requests from the CLI are polled and applied; a
14
14
  * request for a unit that is not planned yet re-reads the plan first;
15
15
  * - stop() sends SIGTERM to every child, escalates to SIGKILL after
16
- * STOP_ESCALATION_MS, and resolves once every child has exited;
16
+ * STOP_ESCALATION_MS except for a sync runner already stopping, which it lets
17
+ * finish persisting pending pushes before resolving;
17
18
  * - release() instead leaves every child running and reports the long-running
18
19
  * ones, so the next daemon can adopt them (`adopt`). Adopted units whose
19
20
  * command is unchanged keep running; changed ones are replaced one at a
@@ -26,6 +27,7 @@ import type { MachineType } from "./machine-type.js";
26
27
  import type { ControlRequest } from "./requests.js";
27
28
  import { syncPassResult } from "./sync-runner.js";
28
29
  export declare const STOP_ESCALATION_MS = 10000;
30
+ export declare const SYNC_RUNNER_PERSIST_GRACE_MS = 60000;
29
31
  export declare const CLI_UPDATE_SYNC_IDLE_KILL_GRACE_MS = 60000;
30
32
  /** After a handoff, how long a replaced unit must stay up before the next one is replaced. */
31
33
  export declare const HANDOFF_STAGGER_MS = 15000;
@@ -98,6 +100,8 @@ export interface SupervisorDeps {
98
100
  restartDaemon?: () => void | boolean | Promise<boolean | void>;
99
101
  writeState: (state: DaemonState) => void;
100
102
  log: (level: "info" | "warn" | "error", msg: string) => void;
103
+ /** Extend the daemon shutdown deadline when a sync runner reports stopping. */
104
+ onSyncRunnerStopping?: () => void;
101
105
  now?: () => number;
102
106
  setTimeout?: (fn: () => void, ms: number) => unknown;
103
107
  clearTimeout?: (handle: unknown) => void;
@@ -120,6 +124,8 @@ export interface Supervisor {
120
124
  stop(): Promise<void>;
121
125
  reconcile(): void;
122
126
  state(): DaemonState;
127
+ /** True while a live sync runner has reported that it is persisting pushes. */
128
+ hasStoppingSyncRunner(): boolean;
123
129
  /** Stop supervising without signalling any child; returns the long-running units left running. */
124
130
  release(): ReleasedUnit[];
125
131
  }