@indigoai-us/hq-cli 5.345.258 → 5.345.261

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 (47) hide show
  1. package/CHANGELOG.md +58 -0
  2. package/assets/scaffold/core/scripts/handoff-knowledge-commit.sh +163 -5
  3. package/assets/scaffold/core/scripts/handoff-post.sh +30 -0
  4. package/assets/scaffold/core/scripts/handoff-sync-prefetch.sh +39 -0
  5. package/assets/scaffold/core/scripts/handoff-sync-publish.sh +51 -3
  6. package/contracts/host-canary-release.json +7 -7
  7. package/dist/commands/cloud.d.ts +2 -7
  8. package/dist/commands/cloud.js +2 -29
  9. package/dist/commands/core-bucket-c-handoff-knowledge-native.d.ts +24 -2
  10. package/dist/commands/core-bucket-c-handoff-knowledge-native.js +170 -19
  11. package/dist/commands/core-bucket-c-handoff-sync-native.d.ts +4 -2
  12. package/dist/commands/core-bucket-c-handoff-sync-native.js +153 -34
  13. package/dist/commands/core-bucket-c-handoff-sync-worker.cjs +201 -0
  14. package/dist/commands/core-delegate-w1b.js +17 -16
  15. package/dist/commands/core-delegate.js +5 -4
  16. package/dist/commands/core-handoff.d.ts +10 -0
  17. package/dist/commands/core-handoff.js +138 -16
  18. package/dist/commands/reindex.d.ts +3 -0
  19. package/dist/commands/reindex.js +11 -5
  20. package/dist/commands/rescue.js +7 -2
  21. package/dist/commands/sync-core.js +24 -7
  22. package/dist/hq-cloud-sync-runner/bin/sync-runner.js +3227 -2138
  23. package/dist/hq-cloud-sync-runner/package.json +1 -1
  24. package/dist/lib/canonical-person.d.ts +19 -0
  25. package/dist/lib/canonical-person.js +30 -0
  26. package/dist/lib/company-sessions-cli.d.ts +12 -0
  27. package/dist/lib/company-sessions-cli.js +54 -0
  28. package/dist/lib/company-sessions.d.ts +31 -0
  29. package/dist/lib/company-sessions.js +304 -0
  30. package/dist/lib/doctor/fix/process-identity.d.ts +13 -0
  31. package/dist/lib/doctor/fix/process-identity.js +63 -7
  32. package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
  33. package/dist/lib/flag-registry-worker-source.generated.js +1 -1
  34. package/dist/lib/hook-engine/coverage.d.ts +44 -1
  35. package/dist/lib/hook-engine/coverage.js +129 -1
  36. package/dist/lib/onboarding/orchestrator.js +4 -2
  37. package/dist/lib/sync-core/engine-home.d.ts +5 -1
  38. package/dist/lib/sync-core/engine-home.js +6 -2
  39. package/dist/lib/sync-core/reconcile.d.ts +5 -0
  40. package/dist/lib/sync-core/reconcile.js +21 -1
  41. package/dist/lib/sync-core/vault-uid.d.ts +2 -0
  42. package/dist/lib/sync-core/vault-uid.js +4 -0
  43. package/dist/utils/delegate-lock.d.ts +18 -0
  44. package/dist/utils/delegate-lock.js +149 -37
  45. package/dist/utils/sync-operation-lock.d.ts +2 -1
  46. package/dist/utils/sync-operation-lock.js +13 -2
  47. package/package.json +8 -8
@@ -0,0 +1,201 @@
1
+ "use strict";
2
+
3
+ const { spawn } = require("node:child_process");
4
+ const fs = require("node:fs");
5
+ const path = require("node:path");
6
+
7
+ const TARGETED_REFUSAL_MARKER = "cannot be combined with explicit [paths]";
8
+
9
+ function isPlainFile(candidate) {
10
+ try {
11
+ return fs.statSync(candidate).isFile();
12
+ } catch {
13
+ return false;
14
+ }
15
+ }
16
+
17
+ /**
18
+ * Resolve the absolute paths the continuity push must carry: the pointer and
19
+ * the single thread file it references under `workspace/threads/`. Matches
20
+ * `continuity_paths()` in `core/scripts/handoff-sync-publish.sh`.
21
+ */
22
+ function continuityPaths(hqRoot) {
23
+ const pointer = path.join(hqRoot, "workspace/threads/handoff.json");
24
+ if (!isPlainFile(pointer)) return [];
25
+ const paths = [pointer];
26
+ let content = "";
27
+ try {
28
+ content = fs.readFileSync(pointer, "utf8");
29
+ } catch {
30
+ return paths;
31
+ }
32
+ let threadPath = "";
33
+ for (const line of content.split(/\r?\n/)) {
34
+ const match = /.*"thread_path"[ \t]*:[ \t]*"([^"]*)".*/.exec(line);
35
+ if (match && match[1] !== undefined) {
36
+ threadPath = match[1];
37
+ break;
38
+ }
39
+ }
40
+ if (!threadPath.startsWith("workspace/threads/") || threadPath.includes("\\")) return paths;
41
+ if (`/${threadPath}/`.includes("/../") || `/${threadPath}/`.includes("/./")) return paths;
42
+ const threadFile = path.join(hqRoot, threadPath);
43
+ if (isPlainFile(threadFile)) paths.push(threadFile);
44
+ return paths;
45
+ }
46
+
47
+ function exitCode(code, signal) {
48
+ if (code !== null) return code;
49
+ if (signal === "SIGTERM") return 143;
50
+ if (signal === "SIGKILL") return 137;
51
+ return 1;
52
+ }
53
+
54
+ function quoteForWindowsShell(arg) {
55
+ if (arg === "") return '""';
56
+ if (!/[\s"^&|<>()]/.test(arg)) return arg;
57
+ return `"${arg.replace(/"/g, '\\"')}"`;
58
+ }
59
+
60
+ /**
61
+ * Check whether the output written to `logPath` at or after `startOffset`
62
+ * contains `marker` within its last `lineCount` lines. Reading only from
63
+ * `startOffset` avoids mistaking a refusal marker left by an earlier run for
64
+ * a refusal of the current push.
65
+ */
66
+ function logTailFromOffsetIncludes(logPath, startOffset, marker, lineCount = 20) {
67
+ let readFd;
68
+ try {
69
+ readFd = fs.openSync(logPath, "r");
70
+ const size = fs.fstatSync(readFd).size;
71
+ const offset = Math.max(0, Math.min(startOffset, size));
72
+ const length = size - offset;
73
+ if (length <= 0) return false;
74
+ const buffer = Buffer.alloc(length);
75
+ let bytesRead = 0;
76
+ while (bytesRead < length) {
77
+ const chunk = fs.readSync(readFd, buffer, bytesRead, length - bytesRead, offset + bytesRead);
78
+ if (chunk <= 0) break;
79
+ bytesRead += chunk;
80
+ }
81
+ const content = buffer.subarray(0, bytesRead).toString("utf8");
82
+ const trimmed = content.endsWith("\n") ? content.slice(0, -1) : content;
83
+ return trimmed.split("\n").slice(-lineCount).join("\n").includes(marker);
84
+ } catch {
85
+ return false;
86
+ } finally {
87
+ if (readFd !== undefined) {
88
+ try { fs.closeSync(readFd); } catch { /* ignore */ }
89
+ }
90
+ }
91
+ }
92
+
93
+ /**
94
+ * Single implementation of the continuity publish push and targeted-refusal
95
+ * fallback, shared by both in-process `--sync` runs and the detached
96
+ * background worker.
97
+ */
98
+ async function runPublishPush({ fd, root, logPath, runWithTimeout }) {
99
+ const paths = continuityPaths(root);
100
+ if (paths.length === 0) {
101
+ fs.writeSync(fd, "handoff-sync-publish: no continuity pointer to publish\n");
102
+ return { code: 0, timedOut: false };
103
+ }
104
+ const baseArgs = [
105
+ "sync", "push", "--personal", "--hq-root", root,
106
+ "--lock-timeout", "0", "--message", "handoff continuity pointer",
107
+ ];
108
+ let startOffset = 0;
109
+ try {
110
+ startOffset = fs.fstatSync(fd).size;
111
+ } catch {
112
+ startOffset = 0;
113
+ }
114
+ let run = await runWithTimeout([...baseArgs, ...paths]);
115
+ if (!run.timedOut && run.code !== 0 && logTailFromOffsetIncludes(logPath, startOffset, TARGETED_REFUSAL_MARKER)) {
116
+ fs.writeSync(fd, "handoff-sync-publish: targeted push refused by this CLI; falling back to full personal push\n");
117
+ run = await runWithTimeout(baseArgs);
118
+ }
119
+ return run;
120
+ }
121
+
122
+ function runDetachedChildWithTimeout(root, fd, timeoutText, args) {
123
+ return new Promise((resolve) => {
124
+ const win = process.platform === "win32";
125
+ const cmd = win ? quoteForWindowsShell("hq") : "hq";
126
+ const argv = win ? args.map(quoteForWindowsShell) : args;
127
+ let child;
128
+ try {
129
+ child = spawn(cmd, argv, {
130
+ cwd: root,
131
+ env: process.env,
132
+ stdio: ["ignore", fd, fd],
133
+ windowsHide: true,
134
+ shell: win,
135
+ });
136
+ } catch {
137
+ fs.writeSync(fd, "spawn hq failed\n");
138
+ resolve({ code: 127, timedOut: false });
139
+ return;
140
+ }
141
+ const seconds = Number(timeoutText);
142
+ let timedOut = false;
143
+ let killTimer;
144
+ let timeoutTimer;
145
+ if (Number.isFinite(seconds)) {
146
+ timeoutTimer = setTimeout(() => {
147
+ timedOut = true;
148
+ child.kill("SIGTERM");
149
+ killTimer = setTimeout(() => child.kill("SIGKILL"), 1000);
150
+ }, Math.max(0, seconds) * 1000);
151
+ timeoutTimer.unref();
152
+ }
153
+ child.once("error", () => {
154
+ if (timeoutTimer) clearTimeout(timeoutTimer);
155
+ if (killTimer) clearTimeout(killTimer);
156
+ fs.writeSync(fd, "hq: command not found\n");
157
+ resolve({ code: 127, timedOut });
158
+ });
159
+ child.once("exit", (code, signal) => {
160
+ if (timeoutTimer) clearTimeout(timeoutTimer);
161
+ if (killTimer) clearTimeout(killTimer);
162
+ resolve({ code: exitCode(code, signal), timedOut });
163
+ });
164
+ });
165
+ }
166
+
167
+ if (require.main === module) {
168
+ const [root, timeoutText, logPath] = process.argv.slice(2);
169
+ const fd = fs.openSync(logPath, "a");
170
+ (async () => {
171
+ try {
172
+ const run = await runPublishPush({
173
+ fd,
174
+ root,
175
+ logPath,
176
+ runWithTimeout: (args) => runDetachedChildWithTimeout(root, fd, timeoutText, args),
177
+ });
178
+ const finalCode = run.timedOut ? 124 : run.code;
179
+ fs.writeSync(fd, `exit=${finalCode}\n`);
180
+ fs.closeSync(fd);
181
+ process.exit(finalCode);
182
+ } catch (err) {
183
+ try {
184
+ fs.writeSync(fd, `${String((err && err.message) || err)}\nexit=1\n`);
185
+ fs.closeSync(fd);
186
+ } catch {
187
+ // ignore log write failure on crash exit
188
+ }
189
+ process.exit(1);
190
+ }
191
+ })();
192
+ }
193
+
194
+ module.exports = {
195
+ TARGETED_REFUSAL_MARKER,
196
+ continuityPaths,
197
+ exitCode,
198
+ quoteForWindowsShell,
199
+ logTailFromOffsetIncludes,
200
+ runPublishPush,
201
+ };
@@ -1,7 +1,7 @@
1
1
  /** Native implementations of the second Wave 1 delegate command family. */
2
2
  import { daemonWhoamiOutput } from "../lib/daemon/whoami-cache.js";
3
3
  import { createHash, randomBytes, randomInt } from "node:crypto";
4
- import { acquireDelegateLock } from "../utils/delegate-lock.js";
4
+ import { acquireDelegateLockDetailed, formatDelegateLockError } from "../utils/delegate-lock.js";
5
5
  import * as fs from "node:fs";
6
6
  import * as os from "node:os";
7
7
  import * as path from "node:path";
@@ -516,9 +516,6 @@ function writeBundle(context, input) {
516
516
  function runHq(args, context, stdout = "capture", timeout) {
517
517
  return subprocess("hq", args, context.cwd, { stdout, timeout });
518
518
  }
519
- function delegateLockBusy() {
520
- return "verification or delivery is active; retry after it finishes";
521
- }
522
519
  const runJq = createShellCompatibleJqInvoker((args, input, cwd, options) => subprocess("jq", args, cwd, { input, ...options }), process.platform, process.env, (cwd) => {
523
520
  const bash = resolveWindowsBash(process.env).executable;
524
521
  if (!bash)
@@ -741,9 +738,10 @@ function runGrant(args, context) {
741
738
  if (!fs.existsSync(manifestPath) || !fs.statSync(manifestPath).isFile())
742
739
  return fail("grant", `manifest not found: ${delegateDiagnosticPath(manifestPath)}`);
743
740
  const lock = `${manifestPath}.send-lock`;
744
- const held = yes ? acquireDelegateLock(lock) : null;
745
- if (yes && !held)
746
- return fail("grant", delegateLockBusy());
741
+ const acquired = yes ? acquireDelegateLockDetailed(lock) : null;
742
+ if (acquired && !acquired.ok)
743
+ return fail("grant", formatDelegateLockError(acquired));
744
+ const held = acquired?.ok ? acquired.lock : null;
747
745
  const grantHq = (args, ctx, stdout = "capture") => runHq(args, ctx, stdout, 120_000);
748
746
  try {
749
747
  let manifest;
@@ -1126,9 +1124,10 @@ function runPublish(args, context, legacyHandoff, nativeLock) {
1126
1124
  return fail("publish", "verification lock missing");
1127
1125
  }
1128
1126
  else {
1129
- ownedLock = acquireDelegateLock(lock);
1130
- if (!ownedLock)
1131
- return fail("publish", delegateLockBusy());
1127
+ const acquired = acquireDelegateLockDetailed(lock);
1128
+ if (!acquired.ok)
1129
+ return fail("publish", formatDelegateLockError(acquired));
1130
+ ownedLock = acquired.lock;
1132
1131
  if (args.length !== 2) {
1133
1132
  ownedLock.release();
1134
1133
  return fail("publish", "usage: --manifest <path>");
@@ -1339,9 +1338,10 @@ function runSend(args, context) {
1339
1338
  if (reconcile)
1340
1339
  return reconcileSend(manifestPath, reconcile, context);
1341
1340
  const lock = `${manifestPath}.send-lock`;
1342
- const held = send ? acquireDelegateLock(lock) : null;
1343
- if (send && !held)
1344
- return fail("send", delegateLockBusy());
1341
+ const acquired = send ? acquireDelegateLockDetailed(lock) : null;
1342
+ if (acquired && !acquired.ok)
1343
+ return fail("send", formatDelegateLockError(acquired));
1344
+ const held = acquired?.ok ? acquired.lock : null;
1345
1345
  let lockRemoved = false;
1346
1346
  const removeLock = () => {
1347
1347
  if (!send || lockRemoved)
@@ -1646,9 +1646,10 @@ function runVerify(args, context) {
1646
1646
  if (!manifest)
1647
1647
  return fail("verify", `jq: error: ${delegateDiagnosticPath(manifestPath)}: Invalid JSON`);
1648
1648
  const lock = `${manifestPath}.send-lock`;
1649
- const held = acquireDelegateLock(lock);
1650
- if (!held)
1651
- return fail("verify", delegateLockBusy());
1649
+ const acquired = acquireDelegateLockDetailed(lock);
1650
+ if (!acquired.ok)
1651
+ return fail("verify", formatDelegateLockError(acquired));
1652
+ const held = acquired.lock;
1652
1653
  let cache = "";
1653
1654
  try {
1654
1655
  const company = jqRawPath(manifest, "company");
@@ -11,7 +11,7 @@ import { resolveWindowsExecutable } from "../lib/bot/runtime/windows.js";
11
11
  import { buildCmdExeSpawnPlan, isWindowsBatchFile } from "../utils/windows-spawn.js";
12
12
  import { describeCoreCommand } from "./core-command-catalog.js";
13
13
  import { resolveLiveRoot } from "../utils/hq-roots.js";
14
- import { acquireDelegateLock } from "../utils/delegate-lock.js";
14
+ import { acquireDelegateLockDetailed, formatDelegateLockError } from "../utils/delegate-lock.js";
15
15
  import { runBundledScript } from "../utils/run-bundled-script.js";
16
16
  import { brainstormFrontmatterSet, brainstormSummary, brainstormTitle } from "./core-delegate-brainstorm.js";
17
17
  import { delegateBoardPath, delegateRepoDirectory, secretsSourcePaths } from "../lib/core-utils/delegate-helper-paths.js";
@@ -1302,11 +1302,12 @@ export function runNative(name, args, context) {
1302
1302
  writeErr(`hq-delegate-${name}: cannot check the manifest before locking it\n`);
1303
1303
  return 1;
1304
1304
  }
1305
- const lock = acquireDelegateLock(`${file}.send-lock`);
1306
- if (!lock) {
1307
- writeErr(`hq-delegate-${name}: verification or delivery is active; retry after it finishes\n`);
1305
+ const acquired = acquireDelegateLockDetailed(`${file}.send-lock`);
1306
+ if (!acquired.ok) {
1307
+ writeErr(`hq-delegate-${name}: ${formatDelegateLockError(acquired)}\n`);
1308
1308
  return 1;
1309
1309
  }
1310
+ const lock = acquired.lock;
1310
1311
  try {
1311
1312
  return runNativeUnlocked(name, args, context);
1312
1313
  }
@@ -20,6 +20,16 @@ type HandoffContext = {
20
20
  };
21
21
  export declare function boundSessionCompany(root: string): string;
22
22
  export declare function runHandoffFinalize(args: string[], context: HandoffContext): RunResult;
23
+ /**
24
+ * Matches `handoff_company_is_cloud` in hq-core's `core/scripts/handoff-post.sh`:
25
+ * 1. `companies/<slug>/company.yaml`: `cloud: true` wins immediately; an
26
+ * explicit `cloud: false` keeps the company local even if manifest.yaml
27
+ * carries a `cloud_uid`.
28
+ * 2. `companies/manifest.yaml`: under `companies:` -> ` <slug>:` ->
29
+ * ` cloud_uid:` with a non-empty value that is neither `null` nor `~`.
30
+ * 3. Otherwise local-only (returns false).
31
+ */
32
+ export declare function handoffCompanyIsCloud(root: string, company: string): boolean;
23
33
  export declare function runHandoffPost(args: string[], context: HandoffContext): RunResult | Promise<RunResult>;
24
34
  export declare function runHandoffPostWorker(args: string[], context: HandoffContext): RunResult;
25
35
  export declare function runHandoffPointerCompany(args: string[], context: HandoffContext): RunResult;
@@ -7,13 +7,15 @@ import * as os from "node:os";
7
7
  import * as path from "node:path";
8
8
  import { fileURLToPath } from "node:url";
9
9
  import * as yaml from "js-yaml";
10
+ import { readLocalOverride } from "@indigoai-us/hq-flags-client";
11
+ import { resolveProcessFlagGate } from "../lib/flag-registry.js";
10
12
  import { archiveOldThreads } from "../lib/core-utils/archive-old-threads.js";
11
13
  import { summarizeHqStatus } from "../lib/core-utils/hq-status-summary.js";
12
14
  import { matchingSecretPatterns } from "../lib/core-utils/secret-patterns.js";
13
15
  import { enqueueSessionEvent } from "../lib/mesh/live/enqueue.js";
14
16
  import { renderIndexTarget } from "../lib/index-render/index.js";
15
17
  import { defaultBackgroundDependencies, runBackgroundLauncher, } from "../lib/search-index/background.js";
16
- import { resolveLiveRoot } from "../utils/hq-roots.js";
18
+ import { resolveBundledAsset, resolveLiveRoot } from "../utils/hq-roots.js";
17
19
  import { resolveSessionId } from "../lib/core-utils/session-id.js";
18
20
  import { resolveWindowsBash, runBundledScript } from "../utils/run-bundled-script.js";
19
21
  import { isExecutableOnPath } from "../utils/resolve-executable.js";
@@ -24,6 +26,8 @@ import { shellDisplayPath } from "../lib/core-utils/shell-display-path.js";
24
26
  import { fingerprintTrailerArgs, offlineFingerprint } from "../lib/fingerprint/offline.js";
25
27
  import { compactJson, isRecord, jqTruthy, prettyJson, runHandoffOpenSteps, shellDate, } from "./core-handoff-open-steps.js";
26
28
  import { runHandoffKnowledgeCommit } from "./core-bucket-c-handoff-knowledge-native.js";
29
+ import { HANDOFF_SYNC_PUBLISH_ASSET, runHandoffSyncPublishBackground, } from "./core-bucket-c-handoff-sync-native.js";
30
+ import { CORE_NATIVE_HANDOFF_FLAG } from "./core-native-handoff-flag.js";
27
31
  export { runHandoffOpenSteps };
28
32
  const ASSETS = {
29
33
  finalize: "core/scripts/handoff-finalize.sh",
@@ -188,11 +192,17 @@ function nowFor(context) {
188
192
  function stamp(date) {
189
193
  return date.toISOString().replace(/[-:]/g, "").replace(/\.\d{3}Z$/, "Z");
190
194
  }
195
+ const pad2 = (value) => String(value).padStart(2, "0");
196
+ /**
197
+ * Thread id day and time use the local clock, as handoff-finalize.sh does
198
+ * (`date +%Y%m%d` and `date +%H%M%S`), so native and bash ids sort together.
199
+ * created_at and the other timestamps stay UTC, also as in the helper.
200
+ */
191
201
  function dayStamp(date) {
192
- return date.toISOString().slice(0, 10).replaceAll("-", "");
202
+ return `${String(date.getFullYear()).padStart(4, "0")}${pad2(date.getMonth() + 1)}${pad2(date.getDate())}`;
193
203
  }
194
204
  function timeStamp(date) {
195
- return date.toISOString().slice(11, 19).replaceAll(":", "");
205
+ return `${pad2(date.getHours())}${pad2(date.getMinutes())}${pad2(date.getSeconds())}`;
196
206
  }
197
207
  function runGitWithEnv(args, cwd, envOverrides = {}, input) {
198
208
  const env = Object.keys(envOverrides).length === 0 ? process.env : { ...process.env, ...envOverrides };
@@ -1239,22 +1249,55 @@ function readPointerCreatedAt(file) {
1239
1249
  return "";
1240
1250
  }
1241
1251
  }
1252
+ /** Same default-on rule and kill switch as `coreNativeHandoffEnabled()`. */
1253
+ function nativeHandoffPublishEnabled() {
1254
+ const override = readLocalOverride(CORE_NATIVE_HANDOFF_FLAG, process.env);
1255
+ if (override !== null)
1256
+ return override;
1257
+ return resolveProcessFlagGate(CORE_NATIVE_HANDOFF_FLAG, { fallback: true }, () => true, undefined, {
1258
+ acceptStaleSnapshot: true,
1259
+ killSwitchWithoutCompany: true,
1260
+ });
1261
+ }
1242
1262
  /**
1243
- * Publish the continuity pointer the way the helper does: run the HQ root's
1244
- * handoff-sync-publish.sh, which starts its own bounded background push and
1245
- * prints that job's pid. What is pushed, the time limit, the fallback and the
1246
- * log format are the installed script's, whatever its version.
1263
+ * Publish the continuity pointer after a handoff commit. Follows the same
1264
+ * `core-native-handoff` rule and kill switch as finalize/post/open-steps:
1265
+ * prefer the in-process `runHandoffSyncPublish` path (detached bounded worker
1266
+ * printing its pid) when native handoff is enabled; when the kill switch is
1267
+ * off, run the HQ root's `core/scripts/handoff-sync-publish.sh` if present,
1268
+ * otherwise fall back to the bundled `core/scripts/handoff-sync-publish.sh`
1269
+ * asset (skipping if no bash is available).
1247
1270
  */
1248
1271
  function dispatchHandoffSyncPublish(root, tmpRoot) {
1249
- const script = path.join(root, "core/scripts/handoff-sync-publish.sh");
1250
- if (!statNoThrow(script)?.isFile())
1251
- return { pid: "", status: "skipped" };
1252
- const bash = installedScriptShell();
1253
- if (!bash)
1272
+ if (process.env.HQ_HANDOFF_PUBLISH === "0")
1254
1273
  return { pid: "", status: "skipped" };
1274
+ const logPath = path.join(tmpRoot, "handoff-sync-publish.log");
1275
+ const script = path.join(root, HANDOFF_SYNC_PUBLISH_ASSET);
1276
+ if (!nativeHandoffPublishEnabled()) {
1277
+ const bash = installedScriptShell();
1278
+ if (!bash)
1279
+ return { pid: "", status: "skipped" };
1280
+ let targetScript = script;
1281
+ if (!statNoThrow(targetScript)?.isFile()) {
1282
+ try {
1283
+ targetScript = resolveBundledAsset(HANDOFF_SYNC_PUBLISH_ASSET);
1284
+ }
1285
+ catch {
1286
+ return { pid: "", status: "skipped" };
1287
+ }
1288
+ }
1289
+ try {
1290
+ const run = spawnSync(bash, [shellArgPath(targetScript), "--hq-root", shellArgPath(root), "--log", shellArgPath(logPath)], { cwd: root, env: process.env, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], windowsHide: true });
1291
+ const pid = typeof run.stdout === "string" ? run.stdout.replace(/[\r\n]+$/, "") : "";
1292
+ return pid ? { pid, status: "dispatched" } : { pid: "", status: "skipped" };
1293
+ }
1294
+ catch {
1295
+ return { pid: "", status: "skipped" };
1296
+ }
1297
+ }
1255
1298
  try {
1256
- const run = spawnSync(bash, [shellArgPath(script), "--hq-root", shellArgPath(root), "--log", shellArgPath(path.join(tmpRoot, "handoff-sync-publish.log"))], { cwd: root, env: process.env, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], windowsHide: true });
1257
- const pid = typeof run.stdout === "string" ? run.stdout.replace(/[\r\n]+$/, "") : "";
1299
+ const run = runHandoffSyncPublishBackground(["--hq-root", root, "--log", logPath], root);
1300
+ const pid = run.code === 0 ? run.stdout.replace(/[\r\n]+$/, "") : "";
1258
1301
  return pid ? { pid, status: "dispatched" } : { pid: "", status: "skipped" };
1259
1302
  }
1260
1303
  catch {
@@ -2097,6 +2140,79 @@ function spawnBashDetached(script, args, cwd, root, logFile) {
2097
2140
  }
2098
2141
  }
2099
2142
  }
2143
+ const CLOUD_YAML_SPACE = "[\\t\\v\\f\\r ]";
2144
+ const CLOUD_YAML_TRUE_RE = new RegExp(`^cloud:${CLOUD_YAML_SPACE}*"?true"?(?:${CLOUD_YAML_SPACE}|#|$)`);
2145
+ const CLOUD_YAML_FALSE_RE = new RegExp(`^cloud:${CLOUD_YAML_SPACE}*"?false"?(?:${CLOUD_YAML_SPACE}|#|$)`);
2146
+ const MANIFEST_TOP_LEVEL_RE = /^[^\t\v\f\r #]/;
2147
+ const MANIFEST_COMPANIES_HEADER_RE = new RegExp(`^companies:${CLOUD_YAML_SPACE}*$`);
2148
+ const MANIFEST_COMPANY_KEY_RE = /^ {2}[^\t\v\f\r #][^:]*:/;
2149
+ const MANIFEST_CLOUD_UID_PREFIX_RE = new RegExp(`^ {4}cloud_uid:${CLOUD_YAML_SPACE}*`);
2150
+ const MANIFEST_CLOUD_UID_STRIP_RE = /["'\t\v\f\r ]/g;
2151
+ /**
2152
+ * Matches `handoff_company_is_cloud` in hq-core's `core/scripts/handoff-post.sh`:
2153
+ * 1. `companies/<slug>/company.yaml`: `cloud: true` wins immediately; an
2154
+ * explicit `cloud: false` keeps the company local even if manifest.yaml
2155
+ * carries a `cloud_uid`.
2156
+ * 2. `companies/manifest.yaml`: under `companies:` -> ` <slug>:` ->
2157
+ * ` cloud_uid:` with a non-empty value that is neither `null` nor `~`.
2158
+ * 3. Otherwise local-only (returns false).
2159
+ */
2160
+ export function handoffCompanyIsCloud(root, company) {
2161
+ if (!/^[a-z0-9][a-z0-9_-]*$/.test(company))
2162
+ return false;
2163
+ const companyYaml = path.join(root, "companies", company, "company.yaml");
2164
+ if (isFile(companyYaml)) {
2165
+ let content;
2166
+ try {
2167
+ content = fs.readFileSync(companyYaml, "utf8");
2168
+ }
2169
+ catch {
2170
+ content = undefined;
2171
+ }
2172
+ if (content !== undefined) {
2173
+ const lines = content.split("\n");
2174
+ if (lines.some((line) => CLOUD_YAML_TRUE_RE.test(line)))
2175
+ return true;
2176
+ if (lines.some((line) => CLOUD_YAML_FALSE_RE.test(line)))
2177
+ return false;
2178
+ }
2179
+ }
2180
+ const manifestPath = path.join(root, "companies", "manifest.yaml");
2181
+ if (!isFile(manifestPath))
2182
+ return false;
2183
+ let manifest;
2184
+ try {
2185
+ manifest = fs.readFileSync(manifestPath, "utf8");
2186
+ }
2187
+ catch {
2188
+ return false;
2189
+ }
2190
+ let inCompanies = false;
2191
+ let inCompany = false;
2192
+ let found = false;
2193
+ for (const line of manifest.split("\n")) {
2194
+ if (MANIFEST_TOP_LEVEL_RE.test(line)) {
2195
+ inCompanies = MANIFEST_COMPANIES_HEADER_RE.test(line);
2196
+ inCompany = false;
2197
+ continue;
2198
+ }
2199
+ if (inCompanies && MANIFEST_COMPANY_KEY_RE.test(line)) {
2200
+ const firstField = line.slice(2).split(/[ \t]+/)[0] ?? "";
2201
+ const key = firstField.replace(/:$/, "").replace(/["']/g, "");
2202
+ inCompany = key === company;
2203
+ continue;
2204
+ }
2205
+ if (inCompanies && inCompany && line.startsWith(" cloud_uid:")) {
2206
+ const value = line
2207
+ .replace(MANIFEST_CLOUD_UID_PREFIX_RE, "")
2208
+ .replace(MANIFEST_CLOUD_UID_STRIP_RE, "");
2209
+ if (value !== "" && value !== "null" && value !== "~") {
2210
+ found = true;
2211
+ }
2212
+ }
2213
+ }
2214
+ return found;
2215
+ }
2100
2216
  function parseLearningCount(file) {
2101
2217
  try {
2102
2218
  const value = JSON.parse(fs.readFileSync(file, "utf8"));
@@ -2271,9 +2387,15 @@ export function runHandoffPostWorker(args, context) {
2271
2387
  log("workspace-sync: mirror hook unavailable for handoff thread");
2272
2388
  }
2273
2389
  for (const company of syncCompanies) {
2274
- if (!fs.existsSync(path.join(root, "companies", company, "workspace")))
2390
+ if (!POST_COMPANY_SLUG_RE.test(company))
2391
+ continue;
2392
+ if (!isDirectory(path.join(root, "companies", company, "workspace")))
2275
2393
  continue;
2276
- if (!threadMirrorable || !fs.existsSync(path.join(root, "companies", company, "workspace/sessions", `${threadId}.json`))) {
2394
+ if (!handoffCompanyIsCloud(root, company)) {
2395
+ log("workspace-sync: skipped (company is local-only: no cloud: true and no manifest cloud_uid)");
2396
+ continue;
2397
+ }
2398
+ if (!threadMirrorable || !isFile(path.join(root, "companies", company, "workspace/sessions", `${threadId}.json`))) {
2277
2399
  log(`workspace-sync: skipped (thread mirror missing for ${company})`);
2278
2400
  continue;
2279
2401
  }
@@ -1,4 +1,6 @@
1
1
  import { Command } from 'commander';
2
+ import { type CompanySessionRetentionOptions } from '../lib/company-sessions.js';
3
+ import { type CommandCompanySessionDeps } from '../lib/company-sessions-cli.js';
2
4
  /**
3
5
  * Remove inactive worktrees created by `hq worktree` without ever deleting
4
6
  * directories directly. This runs on the hook path, so it uses a shallow
@@ -20,5 +22,6 @@ export declare function removeStaleHqWorktrees(hqRoot: string, now?: number, dea
20
22
  * and outranks both scopes; it is never touched.
21
23
  */
22
24
  export declare function dropProjectDefaultModeForBypassUser(hqRoot: string): void;
25
+ export declare function companySessionsForReindex(hqRoot: string, fromHook: boolean, deps?: CommandCompanySessionDeps): Promise<CompanySessionRetentionOptions | undefined>;
23
26
  export declare function registerReindexCommand(program: Command): void;
24
27
  //# sourceMappingURL=reindex.d.ts.map
@@ -34,6 +34,8 @@ import * as os from 'node:os';
34
34
  import * as path from 'node:path';
35
35
  import * as yaml from 'js-yaml';
36
36
  import { reindex, rescue } from '@indigoai-us/hq-cloud';
37
+ import { withCompanySessions } from '../lib/company-sessions.js';
38
+ import { companySessionsForCommand } from '../lib/company-sessions-cli.js';
37
39
  import { trustHqRuntimeHooks } from '../utils/hook-trust.js';
38
40
  import { findHqRoot } from '../utils/manifest.js';
39
41
  import { guardLargeFiles } from '../utils/large-file-guard.js';
@@ -574,7 +576,7 @@ function runSilently(operation) {
574
576
  * configuration is repaired only after a successful reindex; partial and
575
577
  * malformed configurations remain untouched and receive recovery guidance.
576
578
  */
577
- function repairExtremeHookDrift(hqRoot, allowRepair = true, timeoutLimitMs) {
579
+ function repairExtremeHookDrift(hqRoot, allowRepair = true, timeoutLimitMs, companySessions) {
578
580
  // `hq reindex` can still be invoked from an arbitrary directory. Never turn
579
581
  // an absent settings file there into a rescue attempt.
580
582
  if (!isHqRoot(hqRoot))
@@ -586,13 +588,13 @@ function repairExtremeHookDrift(hqRoot, allowRepair = true, timeoutLimitMs) {
586
588
  if (health.state === 'minor' || !allowRepair)
587
589
  return;
588
590
  try {
589
- const result = runSilently(() => rescue({
591
+ const result = runSilently(() => rescue(withCompanySessions({
590
592
  hqRoot,
591
593
  source: resolveHqCoreSource().repo,
592
594
  ref: installedCoreRef(hqRoot),
593
595
  paths: ['.claude'],
594
596
  assumeYes: true,
595
- }));
597
+ }, companySessions)));
596
598
  const afterRepair = inspectHookHealth(hqRoot, timeoutLimitMs);
597
599
  if (result.status === 0 && afterRepair.state === 'healthy') {
598
600
  console.log('reindex: repaired HQ hook config');
@@ -737,6 +739,9 @@ function reportLargeFileGuard(hqRoot) {
737
739
  console.log(`reindex: ${file} exceeds GitHub's 100MB limit — added to .gitignore`);
738
740
  }
739
741
  }
742
+ export function companySessionsForReindex(hqRoot, fromHook, deps = {}) {
743
+ return companySessionsForCommand(hqRoot, !fromHook, deps);
744
+ }
740
745
  export function registerReindexCommand(program) {
741
746
  program
742
747
  .command('reindex')
@@ -783,8 +788,9 @@ export function registerReindexCommand(program) {
783
788
  const hqRoot = resolveHqRoot(literalHqRoot);
784
789
  const sweepStartedAt = Date.now();
785
790
  removeStaleHqWorktrees(hqRoot, sweepStartedAt, opts.fromHook ? sweepStartedAt + WORKTREE_HOOK_SWEEP_BUDGET_MS : Number.POSITIVE_INFINITY);
786
- const { status } = reindex({ repoRoot: opts.repoRoot });
787
- repairExtremeHookDrift(hqRoot, status === 0, opts.fromHook ? HOOK_CHECK_FROM_HOOK_TIMEOUT_MS : undefined);
791
+ const companySessions = await companySessionsForReindex(hqRoot, opts.fromHook === true);
792
+ const { status } = reindex(withCompanySessions({ repoRoot: opts.repoRoot }, companySessions));
793
+ repairExtremeHookDrift(hqRoot, status === 0, opts.fromHook ? HOOK_CHECK_FROM_HOOK_TIMEOUT_MS : undefined, companySessions);
788
794
  if (status === 0) {
789
795
  // Only safe once reindex actually ran: a refused --from-hook reindex
790
796
  // means a sync/rescue holds the shared operation lock and may be
@@ -4,6 +4,8 @@ import * as yaml from 'js-yaml';
4
4
  import chalk from 'chalk';
5
5
  import { rescue } from '@indigoai-us/hq-cloud';
6
6
  import { findHqRoot } from '../utils/manifest.js';
7
+ import { withCompanySessions } from '../lib/company-sessions.js';
8
+ import { companySessionsForCommand } from '../lib/company-sessions-cli.js';
7
9
  import { selfUpdateAndReexec } from '../utils/self-update.js';
8
10
  import { retrustCodexHooksAfterRescue, trustCodexUserHooks } from '../utils/hook-trust.js';
9
11
  import { reconcileHookRegistrations } from '../lib/hook-engine/reconcile.js';
@@ -273,7 +275,10 @@ export function registerRescueCommand(program) {
273
275
  console.log(chalk.dim(`Rescuing ${hqRoot} from ${source}${ref ? `@${ref}` : ''}` +
274
276
  `${floorSha ? ` (floor ${floorSha.slice(0, 12)})` : ''}` +
275
277
  `${opts.check ? ' [dry-run]' : ''}`));
276
- const { status } = rescue({
278
+ const companySessions = opts.check
279
+ ? undefined
280
+ : await companySessionsForCommand(hqRoot, true);
281
+ const { status } = rescue(withCompanySessions({
277
282
  hqRoot,
278
283
  source,
279
284
  ref,
@@ -284,7 +289,7 @@ export function registerRescueCommand(program) {
284
289
  noBackup: opts.backup === false,
285
290
  cloudUpdate: opts.cloudUpdate,
286
291
  ghToken: rescueScriptToken(token),
287
- });
292
+ }, companySessions));
288
293
  if (status === 0 && !opts.check) {
289
294
  repairReleaseLinksAfterRescue(hqRoot);
290
295
  await retrustHooksAfterRescue(hqRoot);