@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
@@ -2,6 +2,8 @@ import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
3
  import { spawnSync } from "node:child_process";
4
4
  import { fingerprintTrailerArgs, offlineFingerprint } from "../lib/fingerprint/offline.js";
5
+ import { sessionIdFromEnv } from "../lib/core-utils/session-id.js";
6
+ import { resolveWindowsBash } from "../utils/windows-bash.js";
5
7
  export const HANDOFF_KNOWLEDGE_COMMIT_ASSET = "core/scripts/handoff-knowledge-commit.sh";
6
8
  const USAGE = "Usage: handoff-knowledge-commit.sh --files-touched-json-file <path> [--root <hq-root>]";
7
9
  const fail = (message, code = 1) => ({ code, stdout: "", stderr: message + "\n" });
@@ -75,7 +77,149 @@ function stripTrailingCrFromChangesetPaths(value) {
75
77
  return entry;
76
78
  });
77
79
  }
78
- function entriesUnder(root) {
80
+ /**
81
+ * The whitespace bash's tools match here: awk `[[:space:]]` and
82
+ * `tr -d '[:space:]'` byte-wise, i.e. ASCII only. JavaScript's `\s` also
83
+ * matches Unicode spaces (NBSP, U+2003, U+2028), which the helper does not.
84
+ */
85
+ const ASCII_SPACE = "[\\t\\n\\v\\f\\r ]";
86
+ const MANIFEST_HEADER = new RegExp(`^companies:${ASCII_SPACE}*$`);
87
+ const MANIFEST_SECTION_END = /^[^\t\n\v\f\r #]/;
88
+ const MANIFEST_KEY = /^ {2}([^\t\n\v\f\r #][^:]*):/;
89
+ const ASCII_SPACES = new RegExp(ASCII_SPACE, "g");
90
+ function companyIsRegistered(root, slug) {
91
+ const companyDir = path.join(root, "companies", slug);
92
+ try {
93
+ const stat = fs.lstatSync(companyDir);
94
+ if (stat.isSymbolicLink() || !stat.isDirectory())
95
+ return false;
96
+ }
97
+ catch {
98
+ return false;
99
+ }
100
+ let manifest;
101
+ try {
102
+ manifest = fs.readFileSync(path.join(root, "companies", "manifest.yaml"), "utf8");
103
+ }
104
+ catch {
105
+ return false;
106
+ }
107
+ let inCompanies = false;
108
+ for (const line of manifest.split("\n")) {
109
+ if (MANIFEST_HEADER.test(line)) {
110
+ inCompanies = true;
111
+ continue;
112
+ }
113
+ if (inCompanies && MANIFEST_SECTION_END.test(line))
114
+ inCompanies = false;
115
+ if (!inCompanies)
116
+ continue;
117
+ const key = MANIFEST_KEY.exec(line)?.[1];
118
+ if (key === slug)
119
+ return true;
120
+ }
121
+ return false;
122
+ }
123
+ function shellPath(value) {
124
+ return process.platform === "win32" ? value.replaceAll("\\", "/") : value;
125
+ }
126
+ /** `bash`, or Git Bash on Windows; undefined when the host has none. */
127
+ function lockShell(env) {
128
+ return process.platform === "win32" ? resolveWindowsBash(env).executable : "bash";
129
+ }
130
+ /**
131
+ * HQ_HANDOFF_LOCK_TIMEOUT seconds (default 5). Accepts only positive whole
132
+ * numbers, matching the helper's stock-macOS run_with_timeout fallback (where
133
+ * 0, fractions, signs and unit suffixes fail the lock read and leave the
134
+ * session unbound).
135
+ */
136
+ function lockTimeoutMs(env) {
137
+ const raw = env.HQ_HANDOFF_LOCK_TIMEOUT || "5";
138
+ if (!/^[1-9][0-9]*$/.test(raw))
139
+ return undefined;
140
+ const ms = Number(raw) * 1000;
141
+ return Number.isSafeInteger(ms) ? ms : undefined;
142
+ }
143
+ /**
144
+ * Run the HQ root's hq-session.sh the way the helper does. Returns its stdout,
145
+ * or undefined for anything the helper treats as "session lock unreadable":
146
+ * a non-zero exit, a timeout, no bash, or a spawn error.
147
+ */
148
+ function readLockCompany(root, scripts, sessionId, env) {
149
+ const bash = lockShell(env);
150
+ const timeout = lockTimeoutMs(env);
151
+ if (!bash || timeout === undefined)
152
+ return undefined;
153
+ try {
154
+ const run = spawnSync(bash, [shellPath(path.join(scripts, "hq-session.sh")), "--session-id", sessionId, "get", "company_slug"], {
155
+ cwd: root,
156
+ env: { ...env, HQ_ROOT: shellPath(root), HQ_HQ_SESSION_NO_CLI: "1" },
157
+ encoding: "utf8",
158
+ stdio: ["ignore", "pipe", "ignore"],
159
+ timeout,
160
+ killSignal: "SIGKILL",
161
+ windowsHide: true,
162
+ });
163
+ if (run.error || run.status !== 0)
164
+ return undefined;
165
+ return typeof run.stdout === "string" ? run.stdout : "";
166
+ }
167
+ catch {
168
+ return undefined;
169
+ }
170
+ }
171
+ /** `[ -e meta ] && [ ! -r meta ]`: the helper's unreadable-lock pre-check. */
172
+ function lockMetaUnreadable(meta) {
173
+ if (!fs.existsSync(meta))
174
+ return false;
175
+ try {
176
+ fs.accessSync(meta, fs.constants.R_OK);
177
+ return false;
178
+ }
179
+ catch {
180
+ return true;
181
+ }
182
+ }
183
+ export function resolveBoundKnowledgeCompany(root, env = process.env) {
184
+ let skipReason = "no bound company";
185
+ let company = env.HQ_ACTIVE_COMPANY ?? "";
186
+ if (company === "personal") {
187
+ company = "";
188
+ }
189
+ else if (!company) {
190
+ const scripts = path.join(root, "core", "scripts");
191
+ // The helper takes the session id from lib/session-id.sh; without that
192
+ // library it has no session id and does not read the lock.
193
+ const sessionId = fs.existsSync(path.join(scripts, "lib", "session-id.sh")) ? sessionIdFromEnv(env) : "";
194
+ if (!sessionId) {
195
+ skipReason = "no bound company (no session id in the environment, session lock not read)";
196
+ }
197
+ else if (!fs.existsSync(path.join(scripts, "hq-session.sh"))) {
198
+ skipReason = "session lock unreadable";
199
+ }
200
+ else if (lockMetaUnreadable(path.join(root, "workspace", "sessions", sessionId, "meta.yaml"))) {
201
+ skipReason = "session lock unreadable";
202
+ }
203
+ else {
204
+ const output = readLockCompany(root, scripts, sessionId, env);
205
+ if (output === undefined) {
206
+ skipReason = "session lock unreadable";
207
+ }
208
+ else {
209
+ company = output.replace(ASCII_SPACES, "");
210
+ if (company === "personal")
211
+ company = "";
212
+ }
213
+ }
214
+ }
215
+ if (company) {
216
+ if (/^[A-Za-z0-9_-]+$/.test(company) && companyIsRegistered(root, company))
217
+ return { company, skipReason: "" };
218
+ skipReason = `company '${company}' is not a registered company`;
219
+ }
220
+ return { company: "", skipReason };
221
+ }
222
+ function entriesUnder(root, boundCompany = "") {
79
223
  const paths = [];
80
224
  for (const parent of ["core/knowledge/public", "core/knowledge/private", "personal/knowledge"]) {
81
225
  const dir = path.join(root, parent);
@@ -85,18 +229,15 @@ function entriesUnder(root) {
85
229
  }
86
230
  catch { /* absent subtree */ }
87
231
  }
88
- const companies = path.join(root, "companies");
89
- try {
90
- for (const company of fs.readdirSync(companies)) {
91
- const knowledge = path.join(companies, company, "knowledge");
92
- try {
93
- fs.lstatSync(knowledge);
94
- paths.push(knowledge);
95
- }
96
- catch { /* company has no knowledge root */ }
232
+ // Only the bound company. Never list companies/ or touch another company's folder.
233
+ if (boundCompany) {
234
+ const knowledge = path.join(root, "companies", boundCompany, "knowledge");
235
+ try {
236
+ fs.lstatSync(knowledge);
237
+ paths.push(knowledge);
97
238
  }
239
+ catch { /* company has no knowledge root */ }
98
240
  }
99
- catch { /* no companies tree */ }
100
241
  return paths;
101
242
  }
102
243
  function gitText(git, args, cwd) {
@@ -159,8 +300,8 @@ function parseNulPaths(status) {
159
300
  }
160
301
  return { paths, originals };
161
302
  }
162
- function commitKnowledge(git, root, changes, handled, output, trailer) {
163
- for (const entry of entriesUnder(root)) {
303
+ function commitKnowledge(git, root, changes, handled, output, trailer, boundCompany) {
304
+ for (const entry of entriesUnder(root, boundCompany)) {
164
305
  let stat;
165
306
  try {
166
307
  stat = fs.lstatSync(entry);
@@ -186,8 +327,8 @@ function commitKnowledge(git, root, changes, handled, output, trailer) {
186
327
  output.stdout.push("INVALID-DIRTY: " + relative + " is a legacy knowledge symlink to " + repo + " with uncommitted changes — NOT auto-committed; run hq reindex to materialize it, then commit, before archiving this session\n");
187
328
  continue;
188
329
  }
189
- if (relative.startsWith("companies/") && relative.endsWith("/knowledge"))
190
- continue;
330
+ // A plain company knowledge directory syncs through its vault; only the
331
+ // bound company's knowledge that is its own git repository is committed.
191
332
  if (!fs.existsSync(path.join(entry, ".git")))
192
333
  continue;
193
334
  const repo = gitRoot(git, entry);
@@ -219,7 +360,7 @@ function commitKnowledge(git, root, changes, handled, output, trailer) {
219
360
  }
220
361
  return undefined;
221
362
  }
222
- export function runHandoffKnowledgeCommit(args, cwd = process.cwd(), git = gitDefault, buildFingerprint = fingerprintDefault) {
363
+ export function runHandoffKnowledgeCommit(args, cwd = process.cwd(), git = gitDefault, buildFingerprint = fingerprintDefault, env = process.env) {
223
364
  let changesFile = "";
224
365
  let root = cwd;
225
366
  for (let index = 0; index < args.length;) {
@@ -274,15 +415,25 @@ export function runHandoffKnowledgeCommit(args, cwd = process.cwd(), git = gitDe
274
415
  const handled = new Set();
275
416
  let trailerArgs;
276
417
  const trailer = () => (trailerArgs ??= fingerprintTrailerArgs(buildFingerprint(root)));
277
- const commitFailure = commitKnowledge(git, root, changes, handled, output, trailer);
418
+ const bound = resolveBoundKnowledgeCompany(root, env);
419
+ if (!bound.company) {
420
+ output.stdout.push("SKIPPED-COMPANY-KNOWLEDGE: " + bound.skipReason + "; company knowledge repositories were not processed\n");
421
+ }
422
+ const commitFailure = commitKnowledge(git, root, changes, handled, output, trailer, bound.company);
278
423
  if (commitFailure)
279
424
  return commitFailure;
425
+ const boundKnowledge = bound.company ? "companies/" + bound.company + "/knowledge/" : "";
426
+ const boundKnowledgeIsRepo = Boolean(bound.company) && fs.existsSync(path.join(root, "companies", bound.company, "knowledge", ".git"));
280
427
  for (const touched of changes) {
281
- if (/^(core\/knowledge\/public|core\/knowledge\/private|personal\/knowledge)\//.test(touched) && !handled.has(touched)) {
428
+ if (handled.has(touched))
429
+ continue;
430
+ const personalOrCore = /^(core\/knowledge\/public|core\/knowledge\/private|personal\/knowledge)\//.test(touched);
431
+ const boundRepo = boundKnowledgeIsRepo && touched.startsWith(boundKnowledge);
432
+ if (personalOrCore || boundRepo) {
282
433
  output.stdout.push("NOT-COMMITTED: " + touched + " is listed in the handoff changeset but no knowledge repository committed it\n");
283
434
  }
284
435
  }
285
436
  return { code: 0, stdout: output.stdout.join(""), stderr: output.stderr.join("") };
286
437
  }
287
- export const __handoffKnowledgeTest = { safePath, validChangeset, entriesUnder, statusPaths, parseNulPaths, expandTouched, gitRoot, samePath, windowsNativePath };
438
+ export const __handoffKnowledgeTest = { safePath, validChangeset, entriesUnder, companyIsRegistered, statusPaths, parseNulPaths, expandTouched, gitRoot, samePath, windowsNativePath };
288
439
  //# sourceMappingURL=core-bucket-c-handoff-knowledge-native.js.map
@@ -24,22 +24,24 @@ declare function parseArgs(args: readonly string[], kind: "prefetch" | "publish"
24
24
  sync: boolean;
25
25
  child: boolean;
26
26
  } | HandoffSyncResult;
27
- declare function exitCode(code: number | null, signal: NodeJS.Signals | null): number;
28
27
  declare function runWithTimeout(deps: Dependencies, logFd: number, timeoutText: string, args: string[]): Promise<ChildResult>;
29
28
  declare function openLog(log: string): number | HandoffSyncResult;
30
29
  declare function header(deps: Dependencies, root: string, kind: "prefetch" | "publish", timeout: string, mode?: string): string;
31
30
  declare function resolveRoot(root: string, deps: Dependencies): string;
32
31
  declare function commandOnPath(name: string, env: NodeJS.ProcessEnv): boolean;
33
32
  export declare function runHandoffSyncPrefetch(args: readonly string[], hqRoot: string, deps?: Dependencies): Promise<HandoffSyncResult>;
33
+ /** Synchronous background dispatch used by in-process `runHandoffFinalize`. */
34
+ export declare function runHandoffSyncPublishBackground(args: readonly string[], hqRoot: string, deps?: Dependencies): HandoffSyncResult;
34
35
  export declare function runHandoffSyncPublish(args: readonly string[], hqRoot: string, deps?: Dependencies): Promise<HandoffSyncResult>;
35
36
  export declare const __handoffSyncTest: {
36
37
  parseArgs: typeof parseArgs;
37
- exitCode: typeof exitCode;
38
+ exitCode: (code: number | null, signal: NodeJS.Signals | null) => number;
38
39
  runWithTimeout: typeof runWithTimeout;
39
40
  openLog: typeof openLog;
40
41
  header: typeof header;
41
42
  resolveRoot: typeof resolveRoot;
42
43
  commandOnPath: typeof commandOnPath;
44
+ continuityPaths: (root: string) => string[];
43
45
  };
44
46
  export {};
45
47
  //# sourceMappingURL=core-bucket-c-handoff-sync-native.d.ts.map
@@ -1,8 +1,22 @@
1
+ import * as crypto from "node:crypto";
1
2
  import * as fs from "node:fs";
3
+ import { createRequire } from "node:module";
2
4
  import * as path from "node:path";
3
5
  import { spawn } from "node:child_process";
4
6
  import { fileURLToPath } from "node:url";
5
7
  import { buildSpawnPlan } from "../utils/windows-spawn.js";
8
+ const requireFromHere = createRequire(import.meta.url);
9
+ const DETACHED_PUBLISH_WORKER_PATH = fileURLToPath(new URL("./core-bucket-c-handoff-sync-worker.cjs", import.meta.url));
10
+ let cachedSyncWorker;
11
+ function loadSyncWorker() {
12
+ if (!cachedSyncWorker) {
13
+ cachedSyncWorker = requireFromHere("./core-bucket-c-handoff-sync-worker.cjs");
14
+ }
15
+ return cachedSyncWorker;
16
+ }
17
+ const continuityPaths = (root) => loadSyncWorker().continuityPaths(root);
18
+ const exitCode = (code, signal) => loadSyncWorker().exitCode(code, signal);
19
+ const runSharedPublishPush = (params) => loadSyncWorker().runPublishPush(params);
6
20
  export const HANDOFF_SYNC_PREFETCH_ASSET = "core/scripts/handoff-sync-prefetch.sh";
7
21
  export const HANDOFF_SYNC_PUBLISH_ASSET = "core/scripts/handoff-sync-publish.sh";
8
22
  const PREFETCH_HELP = [
@@ -124,15 +138,6 @@ function shellScriptPath(value) {
124
138
  const drivePath = normalized.match(/^([A-Za-z]):\/(.*)$/);
125
139
  return drivePath ? `/${drivePath[1].toLowerCase()}/${drivePath[2]}` : normalized;
126
140
  }
127
- function exitCode(code, signal) {
128
- if (code !== null)
129
- return code;
130
- if (signal === "SIGTERM")
131
- return 143;
132
- if (signal === "SIGKILL")
133
- return 137;
134
- return 1;
135
- }
136
141
  function runWithTimeout(deps, logFd, timeoutText, args) {
137
142
  return new Promise((resolve) => {
138
143
  let child;
@@ -220,6 +225,58 @@ function commandOnPath(name, env) {
220
225
  }
221
226
  return false;
222
227
  }
228
+ // Strip one leading UTF-8 BOM before JSON.parse so Windows-authored pointers
229
+ // (e.g. PowerShell 5 Set-Content -Encoding UTF8) match jq 1.7 while keeping
230
+ // the original raw bytes intact for atomic restore. Intentionally stays strict
231
+ // standard JSON (rejecting jq extensions such as NaN or concatenated top-level
232
+ // values) so malformed pulls restore the valid local pointer.
233
+ function readPointerObject(pointerPath) {
234
+ try {
235
+ if (!fs.statSync(pointerPath).isFile())
236
+ return null;
237
+ const raw = fs.readFileSync(pointerPath);
238
+ const text = raw.toString("utf8").replace(/^\uFEFF/, "");
239
+ const parsed = JSON.parse(text);
240
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed))
241
+ return null;
242
+ return { raw, data: parsed };
243
+ }
244
+ catch {
245
+ return null;
246
+ }
247
+ }
248
+ // Mirror bash `$(jq -r '.created_at // empty' ...)` which strips trailing LFs.
249
+ function extractCreatedAt(data) {
250
+ const value = data.created_at;
251
+ if (value === undefined || value === null || value === false)
252
+ return "";
253
+ const text = typeof value === "string"
254
+ ? value
255
+ : (typeof value === "number" || typeof value === "boolean")
256
+ ? String(value)
257
+ : JSON.stringify(value);
258
+ return text.replace(/\n+$/, "");
259
+ }
260
+ // Same-directory temp + atomic rename. Unlike bash `mv -f`, rename fails when
261
+ // the target was replaced by a directory instead of dropping the file inside
262
+ // it, so the caller logs a restore failure rather than falsely logging kept.
263
+ function restorePointerAtomic(pointerPath, raw, pid) {
264
+ const dir = path.dirname(pointerPath);
265
+ const tmpPath = path.join(dir, `.handoff-pointer.${pid}.${crypto.randomBytes(6).toString("hex")}`);
266
+ try {
267
+ fs.mkdirSync(dir, { recursive: true });
268
+ fs.writeFileSync(tmpPath, raw, { flag: "wx" });
269
+ fs.renameSync(tmpPath, pointerPath);
270
+ return true;
271
+ }
272
+ catch {
273
+ try {
274
+ fs.rmSync(tmpPath, { force: true });
275
+ }
276
+ catch { /* ignore cleanup failure */ }
277
+ return false;
278
+ }
279
+ }
223
280
  export async function runHandoffSyncPrefetch(args, hqRoot, deps = defaults()) {
224
281
  const parsed = parseArgs(args, "prefetch", deps.env);
225
282
  if ("code" in parsed)
@@ -232,8 +289,36 @@ export async function runHandoffSyncPrefetch(args, hqRoot, deps = defaults()) {
232
289
  return fd;
233
290
  try {
234
291
  fs.writeSync(fd, header(deps, root, "prefetch", parsed.timeout));
292
+ // Snapshot a valid local continuity pointer before pulling so an older,
293
+ // missing, or invalid vault copy cannot overwrite a newer local handoff.
294
+ const pointerPath = path.join(root, "workspace", "threads", "handoff.json");
295
+ const snapshot = readPointerObject(pointerPath);
235
296
  const run = await runWithTimeout(deps, fd, parsed.timeout, ["sync", "pull", "--personal", "--hq-root", root, "--lock-timeout", "0"]);
236
297
  fs.writeSync(fd, `exit=${run.timedOut ? 124 : run.code}\n`);
298
+ if (snapshot) {
299
+ const pulled = readPointerObject(pointerPath);
300
+ let keepLocal = false;
301
+ let localTs = "";
302
+ let pulledTs = "";
303
+ if (!pulled) {
304
+ keepLocal = true;
305
+ }
306
+ else {
307
+ localTs = extractCreatedAt(snapshot.data);
308
+ pulledTs = extractCreatedAt(pulled.data);
309
+ if (localTs.length > 0 && pulledTs.length > 0 && pulledTs < localTs) {
310
+ keepLocal = true;
311
+ }
312
+ }
313
+ if (keepLocal) {
314
+ if (restorePointerAtomic(pointerPath, snapshot.raw, deps.pid)) {
315
+ fs.writeSync(fd, `kept newer local handoff pointer (local created_at=${localTs || "?"}, pulled created_at=${pulledTs || "invalid"})\n`);
316
+ }
317
+ else {
318
+ fs.writeSync(fd, "could not restore the newer local handoff pointer\n");
319
+ }
320
+ }
321
+ }
237
322
  const text = fs.readFileSync(parsed.log, "utf8");
238
323
  if (run.timedOut)
239
324
  return result(0, "timed-out\n");
@@ -245,6 +330,59 @@ export async function runHandoffSyncPrefetch(args, hqRoot, deps = defaults()) {
245
330
  fs.closeSync(fd);
246
331
  }
247
332
  }
333
+ async function runPublishPush(deps, fd, root, timeout, logPath) {
334
+ return runSharedPublishPush({
335
+ fd,
336
+ root,
337
+ logPath,
338
+ runWithTimeout: (args) => runWithTimeout(deps, fd, timeout, args),
339
+ });
340
+ }
341
+ function startDetachedPublish(root, timeout, logPath, deps) {
342
+ let output;
343
+ try {
344
+ output = fs.openSync(logPath, "a");
345
+ }
346
+ catch (cause) {
347
+ return { result: fail(String(cause.message)) };
348
+ }
349
+ let child;
350
+ try {
351
+ child = deps.spawn(process.execPath, [DETACHED_PUBLISH_WORKER_PATH, root, timeout, logPath], {
352
+ cwd: deps.cwd,
353
+ env: deps.env,
354
+ detached: true,
355
+ windowsHide: true,
356
+ stdio: ["ignore", output, output],
357
+ });
358
+ }
359
+ catch {
360
+ fs.closeSync(output);
361
+ return { result: fail("handoff-sync-publish: failed to detach hq") };
362
+ }
363
+ fs.closeSync(output);
364
+ return { child };
365
+ }
366
+ /** Synchronous background dispatch used by in-process `runHandoffFinalize`. */
367
+ export function runHandoffSyncPublishBackground(args, hqRoot, deps = defaults()) {
368
+ const parsed = parseArgs(args, "publish", deps.env);
369
+ if ("code" in parsed)
370
+ return parsed;
371
+ if (!commandOnPath("hq", deps.env))
372
+ return result(0);
373
+ const root = resolveRoot(parsed.root || hqRoot, deps);
374
+ const fd = openLog(parsed.log);
375
+ if (typeof fd !== "number")
376
+ return fd;
377
+ fs.writeSync(fd, header(deps, root, "publish", parsed.timeout, "background"));
378
+ fs.closeSync(fd);
379
+ const launch = startDetachedPublish(root, parsed.timeout, parsed.log, { ...deps, cwd: root });
380
+ if (launch.result)
381
+ return launch.result;
382
+ launch.child.once("error", () => { });
383
+ launch.child.unref();
384
+ return result(0, launch.child.pid ? `${launch.child.pid}\n` : "");
385
+ }
248
386
  export async function runHandoffSyncPublish(args, hqRoot, deps = defaults()) {
249
387
  const parsed = parseArgs(args, "publish", deps.env);
250
388
  if ("code" in parsed)
@@ -259,36 +397,17 @@ export async function runHandoffSyncPublish(args, hqRoot, deps = defaults()) {
259
397
  fs.writeSync(fd, header(deps, root, "publish", parsed.timeout, parsed.sync ? "sync" : "background"));
260
398
  if (!parsed.sync) {
261
399
  fs.closeSync(fd);
262
- let output;
263
- try {
264
- output = fs.openSync(parsed.log, "a");
265
- }
266
- catch (cause) {
267
- return fail(String(cause.message));
268
- }
269
- let child;
270
- try {
271
- const args = ["core", "--hq-root", root, "handoff-sync-publish", "--timeout", parsed.timeout, "--log", parsed.log, "--child"];
272
- const plan = buildSpawnPlan("hq", args);
273
- child = deps.spawn(plan.cmd, plan.args, {
274
- cwd: deps.cwd, env: deps.env, detached: true, windowsHide: true, stdio: ["ignore", output, output],
275
- shell: plan.shell,
276
- ...(plan.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}),
277
- });
278
- }
279
- catch {
280
- if (typeof output === "number")
281
- fs.closeSync(output);
282
- return fail("handoff-sync-publish: failed to detach hq");
283
- }
284
- fs.closeSync(output);
400
+ const launch = startDetachedPublish(root, parsed.timeout, parsed.log, deps);
401
+ if (launch.result)
402
+ return launch.result;
403
+ const { child } = launch;
285
404
  return new Promise((resolve) => {
286
405
  child.once("spawn", () => { child.unref(); resolve(result(0, `${child.pid ?? 0}\n`)); });
287
406
  child.once("error", () => resolve(result(0, `${child.pid ?? 0}\n`)));
288
407
  });
289
408
  }
290
409
  try {
291
- const run = await runWithTimeout(deps, fd, parsed.timeout, ["sync", "push", "--personal", "--hq-root", root, "--lock-timeout", "0", "--message", "handoff continuity pointer"]);
410
+ const run = await runPublishPush(deps, fd, root, parsed.timeout, parsed.log);
292
411
  fs.writeSync(fd, `exit=${run.timedOut ? 124 : run.code}\n`);
293
412
  return result(run.timedOut ? 124 : run.code);
294
413
  }
@@ -296,5 +415,5 @@ export async function runHandoffSyncPublish(args, hqRoot, deps = defaults()) {
296
415
  fs.closeSync(fd);
297
416
  }
298
417
  }
299
- export const __handoffSyncTest = { parseArgs, exitCode, runWithTimeout, openLog, header, resolveRoot, commandOnPath };
418
+ export const __handoffSyncTest = { parseArgs, exitCode, runWithTimeout, openLog, header, resolveRoot, commandOnPath, continuityPaths };
300
419
  //# sourceMappingURL=core-bucket-c-handoff-sync-native.js.map