@indigoai-us/hq-cli 5.345.257 → 5.345.260

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 (45) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/assets/scaffold/core/scripts/handoff-knowledge-commit.sh +163 -5
  3. package/assets/scaffold/core/scripts/handoff-sync-prefetch.sh +39 -0
  4. package/assets/scaffold/core/scripts/handoff-sync-publish.sh +51 -3
  5. package/contracts/host-canary-release.json +7 -7
  6. package/dist/commands/cloud.d.ts +2 -7
  7. package/dist/commands/cloud.js +6 -30
  8. package/dist/commands/core-bucket-c-handoff-knowledge-native.d.ts +24 -2
  9. package/dist/commands/core-bucket-c-handoff-knowledge-native.js +170 -19
  10. package/dist/commands/core-bucket-c-handoff-sync-native.d.ts +4 -2
  11. package/dist/commands/core-bucket-c-handoff-sync-native.js +153 -34
  12. package/dist/commands/core-bucket-c-handoff-sync-worker.cjs +201 -0
  13. package/dist/commands/core-handoff.js +57 -14
  14. package/dist/commands/keyed-sync-pull.d.ts +7 -3
  15. package/dist/commands/keyed-sync-pull.js +90 -22
  16. package/dist/commands/reindex.d.ts +3 -0
  17. package/dist/commands/reindex.js +11 -5
  18. package/dist/commands/rescue.js +7 -2
  19. package/dist/commands/sync-core.js +24 -7
  20. package/dist/hq-cloud-sync-runner/bin/sync-runner.js +3227 -2138
  21. package/dist/hq-cloud-sync-runner/package.json +1 -1
  22. package/dist/lib/canonical-person.d.ts +19 -0
  23. package/dist/lib/canonical-person.js +30 -0
  24. package/dist/lib/company-sessions-cli.d.ts +12 -0
  25. package/dist/lib/company-sessions-cli.js +54 -0
  26. package/dist/lib/company-sessions.d.ts +31 -0
  27. package/dist/lib/company-sessions.js +304 -0
  28. package/dist/lib/doctor/checks/replay-recorder.js +3 -3
  29. package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
  30. package/dist/lib/flag-registry-worker-source.generated.js +1 -1
  31. package/dist/lib/flag-snapshot-file.d.ts +47 -1
  32. package/dist/lib/flag-snapshot-file.js +143 -20
  33. package/dist/lib/hook-engine/coverage.d.ts +115 -7
  34. package/dist/lib/hook-engine/coverage.js +280 -10
  35. package/dist/lib/mesh/live/company-flag-refresh.js +2 -2
  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/sync-operation-lock.d.ts +2 -1
  44. package/dist/utils/sync-operation-lock.js +13 -2
  45. 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
+ };
@@ -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 {
@@ -4,9 +4,13 @@ export interface KeyedPullOptions {
4
4
  companySlug?: string;
5
5
  token: string;
6
6
  }
7
+ /** Why a listed key was not written. Counted per reason in the result. */
8
+ export type KeyedPullSkipReason = "unsafe-path" | "directory-marker" | "sync-ignored" | "case-collision" | "overlay-marker" | "forbidden";
9
+ export interface KeyedPullResult {
10
+ filesDownloaded: number;
11
+ skipped: Record<KeyedPullSkipReason, number>;
12
+ }
7
13
  /** No session discovery, journal, deletes or tombstones: absence from an
8
14
  * ACL-filtered inventory never proves deletion. */
9
- export declare function keyedSyncPull(options: KeyedPullOptions): Promise<{
10
- filesDownloaded: number;
11
- }>;
15
+ export declare function keyedSyncPull(options: KeyedPullOptions): Promise<KeyedPullResult>;
12
16
  //# sourceMappingURL=keyed-sync-pull.d.ts.map
@@ -3,12 +3,46 @@ import path from "node:path";
3
3
  import { Transform } from "node:stream";
4
4
  import { pipeline } from "node:stream/promises";
5
5
  import { GetObjectCommand } from "@aws-sdk/client-s3";
6
+ import { createIgnoreFilter, relativePathRejectionReason } from "@indigoai-us/hq-cloud";
6
7
  import { vaultApiFetch } from "../utils/vault-api.js";
7
8
  const fail = (message) => Object.assign(new Error(message), { expected: true });
8
- function safeKey(value) {
9
- return typeof value === "string" && value.length > 0 &&
10
- !/[\\:]/.test(value) && ![...value].some(char => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127) &&
11
- value.split("/").every(part => part.length > 0 && ![".", "..", ".git", ".hq"].includes(part.toLowerCase()) && !/[. ]$/.test(part));
9
+ /** The hq-cloud push/pull path grammar (traversal, absolute, empty segments,
10
+ * backslashes, NUL), plus the stricter local rules this pull has always had:
11
+ * control characters, drive colons and segments ending in a dot or space. */
12
+ function unsafePath(key) {
13
+ return relativePathRejectionReason(key) !== null || key.includes(":") ||
14
+ [...key].some(char => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127) ||
15
+ key.split("/").some(part => /[. ]$/.test(part));
16
+ }
17
+ /** Normal sync never writes `.git` internals or `.hq` reserved files. The
18
+ * ignore filter already excludes both; this keeps them out if an
19
+ * `.hqinclude` re-includes them. */
20
+ /** One object the key may not read: the presign route or its row refused
21
+ * the key (403), or storage itself refused the signed GET (403). A 403 that
22
+ * did not come from storage (a proxy or egress rule), a 401, a 5xx and every
23
+ * other failure stay fatal; a 403 on the list call never reaches here. */
24
+ function objectForbidden(err) {
25
+ if (!err || typeof err !== "object")
26
+ return false;
27
+ const e = err;
28
+ // presignedDownloadError (files-browse.ts) marks storage refusals with fromStorage.
29
+ if ("fromStorage" in e)
30
+ return e.httpStatus === 403 && e.fromStorage === true;
31
+ return e.status === 403 && e.httpStatus === undefined;
32
+ }
33
+ const reservedSegment = (key) => key.split("/").some(part => [".git", ".hq"].includes(part.toLowerCase()));
34
+ /** Classify one listed key the way the normal sync pull planner does:
35
+ * folder markers and invalid key grammar are skipped (never presigned), then
36
+ * the HQ ignore rules decide. `excluded` probes both file and directory
37
+ * hints, as the planner does, because the listing has no kind. */
38
+ function skipReason(key, excluded) {
39
+ if (key.length > 1 && key.endsWith("/") && !unsafePath(key.slice(0, -1)))
40
+ return "directory-marker";
41
+ if (unsafePath(key))
42
+ return "unsafe-path";
43
+ if (reservedSegment(key) || excluded(key))
44
+ return "sync-ignored";
45
+ return null;
12
46
  }
13
47
  /** Require a real directory chain. Hydration runs before workload execution,
14
48
  * in a launcher-owned tree without concurrent writers. */
@@ -54,8 +88,14 @@ export async function keyedSyncPull(options) {
54
88
  if (!companySlug || !/^[a-z0-9][a-z0-9_-]*$/.test(companySlug))
55
89
  throw fail("Keyed pull requires a safe --company-slug from the trusted launcher");
56
90
  const root = path.resolve(options.hqRoot, "companies", companySlug);
57
- const files = [];
58
- const names = new Set();
91
+ const listed = [];
92
+ const skipped = { "unsafe-path": 0, "directory-marker": 0, "sync-ignored": 0, "case-collision": 0, "overlay-marker": 0, forbidden: 0 };
93
+ let shouldSync;
94
+ const excluded = (key) => {
95
+ shouldSync ??= createIgnoreFilter(options.hqRoot);
96
+ const local = path.join(root, key);
97
+ return !shouldSync(local, false) && !shouldSync(local, true);
98
+ };
59
99
  const cursors = new Set();
60
100
  let cursor;
61
101
  for (let page = 0;; page++) {
@@ -81,13 +121,14 @@ export async function keyedSyncPull(options) {
81
121
  throw fail("Keyed pull inventory is incomplete or malformed");
82
122
  for (const value of body.objects) {
83
123
  const row = value;
84
- if (!row || !safeKey(row.key) || !Number.isSafeInteger(row.size) || row.size < 0)
85
- throw fail("Keyed pull inventory contains an unsafe file");
86
- const name = row.key.normalize("NFC").toLowerCase();
87
- if (names.has(name))
88
- throw fail("Keyed pull inventory contains colliding files");
89
- names.add(name);
90
- files.push({ key: row.key, size: row.size });
124
+ if (!row || typeof row.key !== "string" || !Number.isSafeInteger(row.size) || row.size < 0)
125
+ throw fail("Keyed pull inventory is incomplete or malformed");
126
+ const reason = skipReason(row.key, excluded);
127
+ if (reason) {
128
+ skipped[reason]++;
129
+ continue;
130
+ }
131
+ listed.push({ key: row.key, size: row.size });
91
132
  }
92
133
  if (!body.truncated) {
93
134
  if (body.cursor !== undefined && body.cursor !== null && body.cursor !== "")
@@ -99,17 +140,26 @@ export async function keyedSyncPull(options) {
99
140
  cursor = body.cursor;
100
141
  cursors.add(cursor);
101
142
  }
102
- for (const name of names) {
103
- const parts = name.split("/");
104
- for (let i = 1; i < parts.length; i++) {
105
- if (names.has(parts.slice(0, i).join("/")))
106
- throw fail("Keyed pull inventory has a file/directory collision");
107
- }
143
+ // Keys that differ only in case share one file on a case-folding disk.
144
+ // Normal sync has no rule for picking one live spelling, so write neither.
145
+ const fold = (key) => key.normalize("NFC").toLowerCase();
146
+ const spellings = new Map();
147
+ for (const file of listed)
148
+ spellings.set(fold(file.key), (spellings.get(fold(file.key)) ?? 0) + 1);
149
+ const unique = listed.filter(file => spellings.get(fold(file.key)) === 1 || (skipped["case-collision"]++, false));
150
+ // An object whose key is also a parent of listed objects is a directory
151
+ // overlay marker; normal sync skips it and materializes the children.
152
+ const parents = new Set();
153
+ for (const file of unique) {
154
+ const parts = fold(file.key).split("/");
155
+ for (let i = 1; i < parts.length; i++)
156
+ parents.add(parts.slice(0, i).join("/"));
108
157
  }
158
+ const files = unique.filter(file => !parents.has(fold(file.key)) || (skipped["overlay-marker"]++, false));
109
159
  for (const file of files)
110
160
  await destination(path.join(root, file.key));
111
161
  if (files.length === 0)
112
- return { filesDownloaded: 0 };
162
+ return { filesDownloaded: 0, skipped };
113
163
  await directories(root, true);
114
164
  const stage = await fs.mkdtemp(path.join(root, ".keyed-pull-"));
115
165
  try {
@@ -117,9 +167,22 @@ export async function keyedSyncPull(options) {
117
167
  // identity resolution; defer it here to avoid a static command cycle.
118
168
  const { createCompanyPresignClient } = await import("./files-browse.js");
119
169
  const client = createCompanyPresignClient({ token, companyUid: company, companySlug });
170
+ const forbidden = new Set();
120
171
  for (const [index, file] of files.entries()) {
172
+ let result;
173
+ try {
174
+ result = await client.send(new GetObjectCommand({ Bucket: "resolved-server-side", Key: file.key }));
175
+ }
176
+ catch (err) {
177
+ // Not readable with this key: count it, write nothing, keep going.
178
+ if (objectForbidden(err)) {
179
+ forbidden.add(index);
180
+ skipped.forbidden++;
181
+ continue;
182
+ }
183
+ throw fail("Keyed pull download failed; no staged files were applied");
184
+ }
121
185
  try {
122
- const result = await client.send(new GetObjectCommand({ Bucket: "resolved-server-side", Key: file.key }));
123
186
  if (!result.Body)
124
187
  throw fail("Missing body");
125
188
  let size = 0;
@@ -136,13 +199,18 @@ export async function keyedSyncPull(options) {
136
199
  throw fail("Keyed pull download failed; no staged files were applied");
137
200
  }
138
201
  }
202
+ // A key refused on every listed object is the wrong key, not a few private files.
203
+ if (forbidden.size === files.length)
204
+ throw fail("Keyed pull key could not read any listed file");
139
205
  for (const [index, file] of files.entries()) {
206
+ if (forbidden.has(index))
207
+ continue;
140
208
  const target = path.join(root, file.key);
141
209
  await destination(target);
142
210
  await directories(path.dirname(target), true);
143
211
  await fs.rename(path.join(stage, String(index)), target);
144
212
  }
145
- return { filesDownloaded: files.length };
213
+ return { filesDownloaded: files.length - forbidden.size, skipped };
146
214
  }
147
215
  finally {
148
216
  await fs.rm(stage, { recursive: true, force: true });
@@ -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);