@indigoai-us/hq-cli 5.345.255 → 5.345.257

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 (56) hide show
  1. package/CHANGELOG.md +61 -0
  2. package/README.md +21 -0
  3. package/assets/scaffold/core/scripts/handoff-finalize.sh +981 -46
  4. package/assets/scaffold/core/scripts/hq-delegate-bundle.sh +51 -2
  5. package/assets/scaffold/core/scripts/hq-delegate-send.sh +49 -6
  6. package/assets/scaffold/core/scripts/hq-delegate-transfer.sh +20 -0
  7. package/assets/scaffold/core/scripts/hq-delegate-verify.sh +56 -10
  8. package/assets/scaffold/core/scripts/lib/fingerprint.sh +423 -0
  9. package/assets/scaffold/core/scripts/rebuild-companies-index.sh +10 -1
  10. package/assets/scaffold/core/scripts/rebuild-company-knowledge-index.sh +10 -1
  11. package/assets/scaffold/core/scripts/rebuild-projects-index.sh +10 -1
  12. package/assets/scaffold/core/scripts/register-project.sh +110 -19
  13. package/contracts/host-canary-release.json +7 -7
  14. package/dist/command-catalog.generated.d.ts +1 -1
  15. package/dist/command-catalog.generated.js +1 -1
  16. package/dist/commands/core-delegate-w1b.js +107 -16
  17. package/dist/commands/core-delegate.d.ts +7 -0
  18. package/dist/commands/core-delegate.js +66 -2
  19. package/dist/commands/core-handoff-fast.d.ts +1 -1
  20. package/dist/commands/core-handoff-fast.js +2 -2
  21. package/dist/commands/core-handoff.d.ts +3 -1
  22. package/dist/commands/core-handoff.js +1407 -177
  23. package/dist/commands/core-register-project-native.js +1 -1
  24. package/dist/commands/core.js +2 -2
  25. package/dist/commands/files.d.ts +2 -0
  26. package/dist/commands/files.js +34 -5
  27. package/dist/commands/team-sync.js +1 -1
  28. package/dist/lib/company-skill-wrapper.js +72 -4
  29. package/dist/lib/daemon/requests.d.ts +14 -1
  30. package/dist/lib/daemon/requests.js +17 -3
  31. package/dist/lib/daemon/run.js +44 -2
  32. package/dist/lib/daemon/supervisor.d.ts +11 -0
  33. package/dist/lib/daemon/supervisor.js +33 -0
  34. package/dist/lib/daemon/sync-perf-telemetry.d.ts +85 -0
  35. package/dist/lib/daemon/sync-perf-telemetry.js +206 -0
  36. package/dist/lib/daemon/windows-relaunch.d.ts +55 -0
  37. package/dist/lib/daemon/windows-relaunch.js +72 -0
  38. package/dist/lib/hook-engine/coverage.d.ts +10 -1
  39. package/dist/lib/hook-engine/coverage.js +40 -5
  40. package/dist/lib/index-render/companies.js +3 -2
  41. package/dist/lib/index-render/index.js +2 -1
  42. package/dist/lib/index-render/session-scope.d.ts +2 -3
  43. package/dist/lib/index-render/session-scope.js +2 -5
  44. package/dist/lib/index-render/shared.d.ts +7 -0
  45. package/dist/lib/index-render/shared.js +9 -0
  46. package/dist/lib/work-context/windows-acl.d.ts +14 -0
  47. package/dist/lib/work-context/windows-acl.js +26 -0
  48. package/dist/utils/cli-telemetry.d.ts +26 -7
  49. package/dist/utils/cli-telemetry.js +70 -13
  50. package/dist/utils/git.js +1 -1
  51. package/dist/utils/resident-package-preload.js +4 -0
  52. package/dist/utils/sync-perf-telemetry-flag.d.ts +26 -0
  53. package/dist/utils/sync-perf-telemetry-flag.js +32 -0
  54. package/dist/utils/telemetry-opt-out.d.ts +13 -0
  55. package/dist/utils/telemetry-opt-out.js +19 -0
  56. package/package.json +8 -8
@@ -15,7 +15,8 @@ import { renderIndexTarget } from "../lib/index-render/index.js";
15
15
  import { defaultBackgroundDependencies, runBackgroundLauncher, } from "../lib/search-index/background.js";
16
16
  import { resolveLiveRoot } from "../utils/hq-roots.js";
17
17
  import { resolveSessionId } from "../lib/core-utils/session-id.js";
18
- import { runBundledScript } from "../utils/run-bundled-script.js";
18
+ import { resolveWindowsBash, runBundledScript } from "../utils/run-bundled-script.js";
19
+ import { isExecutableOnPath } from "../utils/resolve-executable.js";
19
20
  import { describeCoreCommand } from "./core-command-catalog.js";
20
21
  import { subprocess } from "./core-delegate.js";
21
22
  import { CLOUD_OFF_EXIT_CODE } from "./cloud-off-gate.js";
@@ -34,6 +35,10 @@ const DESCRIPTIONS = {
34
35
  post: "Run best-effort post-handoff maintenance",
35
36
  openSteps: "List and update open handoff steps",
36
37
  };
38
+ /** handoff-finalize.sh accepts digit-leading company slugs. */
39
+ const FINALIZE_COMPANY_SLUG_RE = /^[a-z0-9][a-z0-9_-]*$/;
40
+ /** The bundled handoff-post.sh still requires a letter first; `handoff post` follows it. */
41
+ const POST_COMPANY_SLUG_RE = /^[a-z][a-z0-9_-]*$/;
37
42
  export function boundSessionCompany(root) {
38
43
  const sessionId = resolveSessionId(root);
39
44
  if (!sessionId)
@@ -50,24 +55,133 @@ export function boundSessionCompany(root) {
50
55
  if (!line)
51
56
  return "";
52
57
  const company = (line.replace(/^\s*company_slug:\s*/, "").replace(/^"|"$/g, ""));
53
- return /^[a-z][a-z0-9_-]*$/.test(company) ? company : "";
58
+ return POST_COMPANY_SLUG_RE.test(company) ? company : "";
59
+ }
60
+ /**
61
+ * meta.yaml `company_slug` as handoff-finalize.sh and the mirror hook read it:
62
+ * awk's `$1 == "company_slug:"` (the key is the whole first field, so
63
+ * `company_slug:acme` with no space is not a binding), the first such line,
64
+ * with the key, the whitespace after it and one quote at each end removed.
65
+ * No slug check here; the helper applies its pattern, the hook does not.
66
+ */
67
+ function metaCompanySlugRaw(root) {
68
+ const sessionId = resolveSessionId(root);
69
+ if (!sessionId)
70
+ return "";
71
+ let contents;
72
+ try {
73
+ contents = fs.readFileSync(path.join(root, "workspace/sessions", sessionId, "meta.yaml"), "utf8");
74
+ }
75
+ catch {
76
+ return "";
77
+ }
78
+ for (const line of contents.split("\n")) {
79
+ if (/^[ \t]*([^ \t]+)/.exec(line)?.[1] !== "company_slug:")
80
+ continue;
81
+ return line.replace(/^[^:]+:\s*/, "").replace(/^"|"$/g, "");
82
+ }
83
+ return "";
54
84
  }
55
- class HandoffJsonOptionError extends Error {
56
- flag;
57
- constructor(flag, cause) {
58
- super(cause instanceof Error ? cause.message : String(cause));
59
- this.flag = flag;
60
- this.name = "HandoffJsonOptionError";
85
+ /** bound_session_company in handoff-finalize.sh. */
86
+ function finalizeBoundSessionCompany(root) {
87
+ const company = metaCompanySlugRaw(root);
88
+ return FINALIZE_COMPANY_SLUG_RE.test(company) ? company : "";
89
+ }
90
+ const SESSION_SCOPE_LIB = "core/scripts/lib/session-scope-capability.sh";
91
+ /**
92
+ * bash for running the HQ root's own scripts (the mirror hook, the
93
+ * session-scope library, the publish script), or undefined when the host has
94
+ * none. handoff-finalize.sh executes those installed files, and they ship with
95
+ * hq-core and change without a CLI release, so native executes them too
96
+ * rather than carrying copies. With no bash the callers take the refusing
97
+ * side: an empty lock set, no mirror, no publish.
98
+ */
99
+ function installedScriptShell() {
100
+ return process.platform === "win32" ? resolveWindowsBash(process.env).executable : "bash";
101
+ }
102
+ /**
103
+ * Why the installed hq-core files cannot do their work on this host, or "".
104
+ * The mirror hook and the session-scope library are bash scripts that call jq.
105
+ * The helper stops such a host earlier (exit 6, "jq is required"); native has
106
+ * no jq dependency of its own, so it names the missing tool where it refuses.
107
+ */
108
+ function installedScriptToolNote() {
109
+ const bash = installedScriptShell();
110
+ if (!bash || (process.platform !== "win32" && !isExecutableOnPath(bash))) {
111
+ return "bash was not found, so the HQ root's hook, session-scope library and publish script were not run";
112
+ }
113
+ if (!isExecutableOnPath("jq")) {
114
+ return "jq was not found on PATH; the HQ root's mirror hook and session-scope library need it";
61
115
  }
116
+ return "";
62
117
  }
63
- function parseHandoffJson(value, flag) {
118
+ /** A path as a bash started from this process accepts it (forward slashes on Windows). */
119
+ function shellArgPath(value) {
120
+ return process.platform === "win32" ? value.replaceAll("\\", "/") : value;
121
+ }
122
+ /**
123
+ * The session's locked company set, read the way the helper reads it: by
124
+ * sourcing the HQ root's session-scope-capability.sh and calling
125
+ * session_scope_read_companies. Validation of the capability file, the
126
+ * multi-company gate and the company-folder checks are all the installed
127
+ * library's. Any failure (no bash, no jq, a library error) is an empty set, as
128
+ * in the helper's `2>/dev/null || true`.
129
+ */
130
+ function readSessionLockedCompanies(root, sessionId) {
131
+ if (!sessionId)
132
+ return { capFile: false, libFile: false, companies: [] };
133
+ const lib = path.join(root, SESSION_SCOPE_LIB);
134
+ const capFile = Boolean(statNoThrow(path.join(root, "workspace/sessions", sessionId, "scope-capability.json"))?.isFile());
135
+ const libFile = Boolean(statNoThrow(lib)?.isFile());
136
+ if (!capFile || !libFile)
137
+ return { capFile, libFile, companies: [] };
138
+ const bash = installedScriptShell();
139
+ if (!bash)
140
+ return { capFile, libFile, companies: [] };
64
141
  try {
65
- return JSON.parse(value);
142
+ const run = spawnSync(bash, [
143
+ "-c",
144
+ '. "$1" 2>/dev/null || exit 0; session_scope_read_companies "$2" "$3" 2>/dev/null || true',
145
+ "hq-handoff-lock-set",
146
+ shellArgPath(lib),
147
+ shellArgPath(root),
148
+ sessionId,
149
+ ], { cwd: root, env: process.env, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], windowsHide: true });
150
+ const companies = typeof run.stdout === "string" ? run.stdout.split(/\r?\n/).filter((line) => line !== "") : [];
151
+ return { capFile, libFile, companies };
66
152
  }
67
- catch (error) {
68
- throw new HandoffJsonOptionError(flag, error);
153
+ catch {
154
+ return { capFile, libFile, companies: [] };
155
+ }
156
+ }
157
+ /**
158
+ * Replay the installed mirror hook exactly as handoff-finalize.sh does: the
159
+ * Write payload for the thread on stdin, `bash <hook>`, and only the exit
160
+ * status read. The hook decides whether anything is written under
161
+ * companies/<co>/workspace/; a refusal (or no bash to run it) writes nothing.
162
+ */
163
+ function runInstalledMirrorHook(root, hookPath, threadFile) {
164
+ const bash = installedScriptShell();
165
+ if (!bash)
166
+ return false;
167
+ try {
168
+ const run = spawnSync(bash, [shellArgPath(hookPath)], {
169
+ cwd: root,
170
+ env: process.env,
171
+ input: `${JSON.stringify({ tool_name: "Write", tool_input: { file_path: shellArgPath(threadFile) } })}\n`,
172
+ stdio: ["pipe", "ignore", "ignore"],
173
+ windowsHide: true,
174
+ });
175
+ return !run.error && run.status === 0;
176
+ }
177
+ catch {
178
+ return false;
69
179
  }
70
180
  }
181
+ /** jq skips a UTF-8 byte order mark at the start of a file it reads. */
182
+ function stripByteOrderMark(text) {
183
+ return text.replace(/^\uFEFF/, "");
184
+ }
71
185
  function nowFor(context) {
72
186
  return context.now?.() ?? new Date();
73
187
  }
@@ -80,10 +194,11 @@ function dayStamp(date) {
80
194
  function timeStamp(date) {
81
195
  return date.toISOString().slice(11, 19).replaceAll(":", "");
82
196
  }
83
- function git(args, cwd, input) {
197
+ function runGitWithEnv(args, cwd, envOverrides = {}, input) {
198
+ const env = Object.keys(envOverrides).length === 0 ? process.env : { ...process.env, ...envOverrides };
84
199
  const result = spawnSync("git", args, {
85
200
  cwd,
86
- env: process.env,
201
+ env,
87
202
  encoding: "utf8",
88
203
  ...(input === undefined ? { stdio: ["ignore", "pipe", "pipe"] } : { input, stdio: ["pipe", "pipe", "pipe"] }),
89
204
  });
@@ -95,6 +210,12 @@ function git(args, cwd, input) {
95
210
  stderr: typeof result.stderr === "string" ? result.stderr : "",
96
211
  };
97
212
  }
213
+ function git(args, cwd, input) {
214
+ return runGitWithEnv(args, cwd, {}, input);
215
+ }
216
+ function gitLiteral(args, cwd, input) {
217
+ return runGitWithEnv(args, cwd, { GIT_LITERAL_PATHSPECS: "1" }, input);
218
+ }
98
219
  function commandAvailable(name) {
99
220
  for (const entry of (process.env.PATH ?? "").split(path.delimiter)) {
100
221
  const candidates = process.platform === "win32" && path.extname(name) === ""
@@ -165,38 +286,339 @@ function globMatches(value, pattern) {
165
286
  const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replaceAll("*", ".*").replaceAll("?", ".");
166
287
  return new RegExp(`^${escaped}$`).test(value);
167
288
  }
168
- function normalizeRelativePath(raw, root) {
169
- let relative = raw;
170
- if (raw.startsWith(`${root}/`))
171
- relative = raw.slice(root.length + 1);
172
- else if (raw.startsWith("/"))
289
+ function statNoThrow(file) {
290
+ try {
291
+ return fs.statSync(file, { throwIfNoEntry: false });
292
+ }
293
+ catch {
173
294
  return undefined;
174
- if (relative.startsWith("./"))
175
- relative = relative.slice(2);
176
- if (!relative || relative.startsWith("-") || relative === ".." || relative.startsWith("../")
177
- || relative.includes("/../") || relative === ".git" || relative.startsWith(".git/"))
295
+ }
296
+ }
297
+ function lstatNoThrow(file) {
298
+ try {
299
+ return fs.lstatSync(file, { throwIfNoEntry: false });
300
+ }
301
+ catch {
178
302
  return undefined;
179
- return relative;
303
+ }
180
304
  }
305
+ function firstSegmentSpoofed(rel, physicalRoot) {
306
+ const slash = rel.indexOf("/");
307
+ const first = slash === -1 ? rel : rel.slice(0, slash);
308
+ const lower = first.toLowerCase();
309
+ if ((lower === "companies" || lower === ".git") && first !== lower)
310
+ return true;
311
+ for (const real of ["companies", ".git"]) {
312
+ if (first === real)
313
+ continue;
314
+ try {
315
+ const candidateStat = fs.statSync(path.resolve(physicalRoot, first));
316
+ const realStat = fs.statSync(path.resolve(physicalRoot, real));
317
+ if (candidateStat.dev === realStat.dev && candidateStat.ino === realStat.ino)
318
+ return true;
319
+ }
320
+ catch { /* absent paths are not filesystem aliases */ }
321
+ }
322
+ return false;
323
+ }
324
+ /** Canonicalize one changeset path against physical and logical roots, refusing traversal, symlinks outside owner scope, and root spoofs. */
325
+ function canonicalRelPath(rawInput, physicalRootInput, logicalRootInput) {
326
+ // Every comparison below is on forward-slash text. On Windows the roots and
327
+ // what realpath returns use backslashes, and a backslash in a changeset path
328
+ // is a separator there, so all of them are rewritten first. Without this a
329
+ // path in a subfolder never matched the root prefix, and a backslash
330
+ // spelling of companies\<other>\... was not seen as a company path.
331
+ const raw = shellArgPath(rawInput);
332
+ const physicalRoot = shellArgPath(physicalRootInput);
333
+ const logicalRoot = shellArgPath(logicalRootInput);
334
+ let rel = raw;
335
+ if (raw.startsWith(`${physicalRoot}/`))
336
+ rel = raw.slice(physicalRoot.length + 1);
337
+ else if (logicalRoot && raw.startsWith(`${logicalRoot}/`))
338
+ rel = raw.slice(logicalRoot.length + 1);
339
+ else if (raw.startsWith("/") || (process.platform === "win32" && path.win32.isAbsolute(raw)))
340
+ return undefined;
341
+ if (rel.startsWith("-"))
342
+ return undefined;
343
+ const cleanParts = [];
344
+ for (const seg of rel.split("/")) {
345
+ if (seg === "" || seg === ".")
346
+ continue;
347
+ if (seg === "..")
348
+ return undefined;
349
+ cleanParts.push(seg);
350
+ }
351
+ if (cleanParts.length === 0)
352
+ return undefined;
353
+ rel = cleanParts.join("/");
354
+ if (rel.startsWith("-") || rel === ".git" || rel.startsWith(".git/") || rel === "companies")
355
+ return undefined;
356
+ const leaf = cleanParts[cleanParts.length - 1];
357
+ const parentParts = cleanParts.slice(0, -1);
358
+ const tail = [];
359
+ while (parentParts.length > 0) {
360
+ const parentCandidate = path.join(physicalRoot, ...parentParts);
361
+ // `[[ -d ]]` is false for any error (name too long, symlink loop), never fatal.
362
+ if (statNoThrow(parentCandidate)?.isDirectory())
363
+ break;
364
+ tail.unshift(parentParts.pop());
365
+ }
366
+ let physParent;
367
+ try {
368
+ physParent = shellArgPath(fs.realpathSync(parentParts.length > 0 ? path.join(physicalRoot, ...parentParts) : physicalRoot));
369
+ }
370
+ catch {
371
+ return undefined;
372
+ }
373
+ let resolvedBase;
374
+ if (physParent === physicalRoot)
375
+ resolvedBase = "";
376
+ else if (physParent.startsWith(`${physicalRoot}/`))
377
+ resolvedBase = physParent.slice(physicalRoot.length + 1);
378
+ else
379
+ return undefined;
380
+ rel = [...(resolvedBase ? [resolvedBase] : []), ...tail, leaf].join("/");
381
+ if (rel === ".git" || rel.startsWith(".git/") || rel === "companies")
382
+ return undefined;
383
+ if (firstSegmentSpoofed(rel, physicalRoot))
384
+ return undefined;
385
+ const leafFull = path.join(physicalRoot, rel);
386
+ if (lstatNoThrow(leafFull)?.isSymbolicLink()) {
387
+ // The helper resolves a directory link fully (cd + pwd -P) and a file link
388
+ // by ONE hop: the physical directory of the link text plus its last name.
389
+ // A second link behind the first hop is not followed, so a link whose
390
+ // first hop leaves the company or the root is refused even when the chain
391
+ // ends back inside.
392
+ const leafStat = statNoThrow(leafFull);
393
+ if (!leafStat)
394
+ return undefined;
395
+ let targetPhys;
396
+ try {
397
+ if (leafStat.isDirectory()) {
398
+ targetPhys = shellArgPath(fs.realpathSync(leafFull));
399
+ }
400
+ else {
401
+ const linkText = shellArgPath(fs.readlinkSync(leafFull));
402
+ const hopDir = shellArgPath(fs.realpathSync(path.resolve(path.dirname(leafFull), path.dirname(linkText))));
403
+ targetPhys = `${hopDir === "/" ? "" : hopDir}/${path.basename(linkText)}`;
404
+ }
405
+ }
406
+ catch {
407
+ return undefined;
408
+ }
409
+ if (targetPhys !== physicalRoot && !targetPhys.startsWith(`${physicalRoot}/`))
410
+ return undefined;
411
+ const targetRel = targetPhys === physicalRoot ? "" : targetPhys.slice(physicalRoot.length + 1);
412
+ if (targetRel && firstSegmentSpoofed(targetRel, physicalRoot))
413
+ return undefined;
414
+ const lcoMatch = /^companies\/([^/]+)\/.+/.exec(rel);
415
+ const lco = lcoMatch?.[1] ?? "";
416
+ let tco = "";
417
+ if (targetRel === "companies" || targetRel.startsWith("companies/")) {
418
+ tco = targetRel.slice("companies".length).replace(/^\//, "").split("/")[0] ?? "";
419
+ if (!tco)
420
+ return undefined;
421
+ }
422
+ if (tco !== lco)
423
+ return undefined;
424
+ }
425
+ return rel;
426
+ }
427
+ /**
428
+ * The changeset entries as the helper's staging loop receives them. The helper
429
+ * pipes `jq -r '... | @tsv'` into `IFS=$'\t' read -r raw_path deleted_flag`,
430
+ * and three properties of that pipe decide what can be staged:
431
+ * - @tsv writes a tab, newline, carriage return or backslash in a path as a
432
+ * two-character escape, so such a path is looked up under the escaped
433
+ * spelling (and is normally reported missing);
434
+ * - an entry jq cannot turn into a row (a number, boolean or array, or an
435
+ * object whose path is an array or object) stops jq, and no later entry is
436
+ * read;
437
+ * - an empty path leaves a row that starts with a tab, which `read` drops, so
438
+ * the flag column becomes the path ("false" or "true").
439
+ * Following all three keeps native from staging a path the helper never sees.
440
+ */
181
441
  function pathEntries(value) {
182
442
  if (!Array.isArray(value))
183
443
  return [];
444
+ const tsv = (text) => text.replace(/\\/g, "\\\\").replace(/\t/g, "\\t").replace(/\n/g, "\\n").replace(/\r/g, "\\r");
184
445
  const entries = [];
185
446
  for (const entry of value) {
186
- if (typeof entry === "string")
187
- entries.push({ raw: entry, deleted: false });
447
+ let raw;
448
+ let deleted = false;
449
+ if (typeof entry === "string") {
450
+ raw = tsv(entry);
451
+ }
452
+ else if (entry === null) {
453
+ raw = "";
454
+ }
188
455
  else if (isRecord(entry)) {
189
- const deleted = entry.deleted === true || entry.status === "deleted";
190
- entries.push({ raw: typeof entry.path === "string" ? entry.path : "", deleted });
456
+ const candidate = entry.path;
457
+ if (candidate === undefined || candidate === null || candidate === false)
458
+ raw = "";
459
+ else if (typeof candidate === "string")
460
+ raw = tsv(candidate);
461
+ else if (typeof candidate === "number" || candidate === true)
462
+ raw = String(candidate);
463
+ else
464
+ break;
465
+ deleted = entry.deleted === true || entry.status === "deleted";
466
+ }
467
+ else {
468
+ break;
469
+ }
470
+ if (raw === "") {
471
+ raw = String(deleted);
472
+ deleted = false;
191
473
  }
474
+ entries.push({ raw, deleted });
192
475
  }
193
476
  return entries;
194
477
  }
478
+ function companyOfRelative(pathname) {
479
+ const match = /^companies\/([a-z0-9][a-z0-9_-]*)\//.exec(pathname);
480
+ return match?.[1] ?? "";
481
+ }
482
+ /**
483
+ * company_of_rel in the helper: for a canonical path, whatever follows
484
+ * `companies/` up to the next slash, with no slug pattern and no trailing
485
+ * slash needed. `companies/acme` (the folder itself), `companies/manifest.yaml`
486
+ * and `companies/Acme_Corp/x` all name a company here. companyOfRelative keeps
487
+ * the slug pattern and is only for the raw changeset scan, where the helper's
488
+ * jq uses the same pattern.
489
+ */
490
+ function companyOfCanonical(rel) {
491
+ if (!rel.startsWith("companies/"))
492
+ return "";
493
+ const rest = rel.slice("companies/".length);
494
+ const slash = rest.indexOf("/");
495
+ return slash === -1 ? rest : rest.slice(0, slash);
496
+ }
195
497
  function touchedCompanyPaths(paths) {
196
- return [...new Set(paths.flatMap((item) => {
197
- const match = /^companies\/([a-z][a-z0-9_-]*)\//.exec(item);
198
- return match?.[1] ? [match[1]] : [];
199
- }))].sort();
498
+ return [...new Set(paths.map((item) => companyOfCanonical(item)).filter(Boolean))].sort();
499
+ }
500
+ function stripRootPrefix(rawInput, physicalRootInput, logicalRootInput) {
501
+ // Forward-slash text on Windows, as in canonicalRelPath.
502
+ const physicalRoot = shellArgPath(physicalRootInput);
503
+ const logicalRoot = shellArgPath(logicalRootInput);
504
+ let stripped = shellArgPath(rawInput);
505
+ if (stripped.startsWith(`${physicalRoot}/`))
506
+ stripped = stripped.slice(physicalRoot.length + 1);
507
+ else if (logicalRoot && stripped.startsWith(`${logicalRoot}/`))
508
+ stripped = stripped.slice(logicalRoot.length + 1);
509
+ return stripped.replace(/^\.\//, "");
510
+ }
511
+ function rawTouchedCompanyScope(touchedValue, physicalRoot, logicalRoot) {
512
+ if (!Array.isArray(touchedValue))
513
+ return { touchedCompanies: [], personalOnly: false };
514
+ const relEntries = [];
515
+ const companySet = new Set();
516
+ for (const item of touchedValue) {
517
+ const raw = typeof item === "string"
518
+ ? item
519
+ : (isRecord(item) && typeof item.path === "string" ? item.path : "");
520
+ if (!raw)
521
+ continue;
522
+ const rel = stripRootPrefix(raw, physicalRoot, logicalRoot);
523
+ relEntries.push(rel);
524
+ const co = companyOfRelative(rel);
525
+ if (co)
526
+ companySet.add(co);
527
+ }
528
+ const personalOnly = relEntries.length > 0
529
+ && relEntries.every((entry) => !entry.startsWith("companies/") && !entry.startsWith("repos/"));
530
+ return { touchedCompanies: [...companySet].sort(), personalOnly };
531
+ }
532
+ function readSystemInfo(root) {
533
+ let hqVersion = "";
534
+ try {
535
+ const yamlText = fs.readFileSync(path.join(root, "core/core.yaml"), "utf8");
536
+ for (const line of yamlText.split(/\r?\n/)) {
537
+ const match = /^hqVersion:[ \t]*"?([^"]*)"?[ \t]*$/.exec(line);
538
+ if (match?.[1] !== undefined) {
539
+ hqVersion = match[1].replace(/"$/, "").trim();
540
+ break;
541
+ }
542
+ }
543
+ }
544
+ catch { /* missing core.yaml yields empty hq_version */ }
545
+ let hqCliVersion = "";
546
+ if (commandAvailable("hq")) {
547
+ // planHqSpawn: on Windows the installed hq is hq.cmd, which a plain
548
+ // spawn of "hq" does not find.
549
+ const probePlan = planHqSpawn(["--version"], process.env, root);
550
+ const probe = spawnSync(probePlan.cmd, probePlan.args, {
551
+ cwd: root,
552
+ env: process.env,
553
+ encoding: "utf8",
554
+ stdio: ["ignore", "pipe", "ignore"],
555
+ windowsHide: true,
556
+ shell: probePlan.shell,
557
+ ...(probePlan.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}),
558
+ });
559
+ if (!probe.error && probe.status === 0 && typeof probe.stdout === "string") {
560
+ const firstLine = probe.stdout.split(/\r?\n/, 1)[0] ?? "";
561
+ const semver = /[0-9]+\.[0-9]+\.[0-9]+[0-9A-Za-z.+-]*/.exec(firstLine);
562
+ if (semver?.[0])
563
+ hqCliVersion = semver[0];
564
+ }
565
+ }
566
+ const hostEnv = process.env.HQ_HANDOFF_HOST || process.env.CLAUDE_CODE_ENTRYPOINT || "cli";
567
+ const host = hostEnv.startsWith("sdk") ? "sdk" : hostEnv.includes("desktop") ? "desktop" : "cli";
568
+ const hooksScript = path.join(root, "core", "scripts", "check-hq-hooks.sh");
569
+ let hooksEnforced = false;
570
+ if (fs.statSync(hooksScript, { throwIfNoEntry: false })?.isFile()) {
571
+ const hookRun = spawnSync("bash", ["core/scripts/check-hq-hooks.sh", "--root", root, "--require-ledger"], {
572
+ cwd: root,
573
+ env: process.env,
574
+ stdio: "ignore",
575
+ });
576
+ hooksEnforced = !hookRun.error && hookRun.status === 0;
577
+ }
578
+ return {
579
+ hq_version: hqVersion,
580
+ hq_cli_version: hqCliVersion,
581
+ host,
582
+ os: process.platform,
583
+ hooks_enforced: hooksEnforced,
584
+ };
585
+ }
586
+ function readDeficiencies(root, fileArg, given, stderrParts) {
587
+ if (given && !fileArg) {
588
+ stderrParts.push("handoff-finalize: --deficiencies-json value is empty, expected a file path — deficiencies will be empty\n");
589
+ }
590
+ if (!fileArg)
591
+ return { deficiencies: [] };
592
+ const resolved = path.isAbsolute(fileArg) ? fileArg : path.join(root, fileArg);
593
+ if (!statNoThrow(resolved)?.isFile()) {
594
+ return {
595
+ deficiencies: [],
596
+ error: { code: 3, stdout: "", stderr: `handoff-finalize: deficiencies file not found: ${fileArg}\n` },
597
+ };
598
+ }
599
+ let parsed;
600
+ try {
601
+ parsed = JSON.parse(stripByteOrderMark(fs.readFileSync(resolved, "utf8")));
602
+ }
603
+ catch {
604
+ return {
605
+ deficiencies: [],
606
+ error: { code: 2, stdout: "", stderr: `handoff-finalize: deficiencies file is not valid JSON: ${fileArg}\n` },
607
+ };
608
+ }
609
+ if (!Array.isArray(parsed))
610
+ return { deficiencies: [] };
611
+ const filtered = parsed
612
+ .filter((item) => isRecord(item) && typeof item.evidence === "string" && item.evidence.trim() !== "")
613
+ .map((item) => ({
614
+ lever: item.lever ?? null,
615
+ kind: item.kind ?? null,
616
+ severity: item.severity ?? null,
617
+ summary: item.summary ?? null,
618
+ evidence: item.evidence ?? null,
619
+ proposed_fix: item.proposed_fix ?? null,
620
+ }));
621
+ return { deficiencies: filtered };
200
622
  }
201
623
  function mirrorThread(root, threadPath) {
202
624
  try {
@@ -302,48 +724,578 @@ function finalizeGitProbe(root) {
302
724
  function printGitStatus(root) {
303
725
  return git(["status", "--porcelain"], root).stdout;
304
726
  }
727
+ const HANDOFF_MEDIA_EXTENSIONS = new Set([
728
+ "mp4", "mov", "m4v", "avi", "mkv", "webm", "wmv", "flv", "mpg", "mpeg", "prores",
729
+ "wav", "mp3", "m4a", "aac", "flac", "aif", "aiff", "ogg", "opus",
730
+ "png", "jpg", "jpeg", "gif", "webp", "heic", "heif", "tif", "tiff", "bmp", "psd", "exr", "raw",
731
+ "zip", "tar", "gz", "tgz", "bz2", "xz", "7z", "rar", "dmg", "iso",
732
+ ]);
733
+ function isHandoffMediaPath(pathname) {
734
+ const base = pathname.slice(pathname.lastIndexOf("/") + 1);
735
+ const dot = base.lastIndexOf(".");
736
+ // The helper's `*.png` patterns also match a file named exactly ".png".
737
+ if (dot < 0)
738
+ return false;
739
+ return HANDOFF_MEDIA_EXTENSIONS.has(base.slice(dot + 1).toLowerCase());
740
+ }
741
+ function isHandoffFilterExempt(pathname) {
742
+ return pathname.endsWith(".hqcloud")
743
+ || pathname.startsWith("workspace/threads/")
744
+ || pathname === "workspace/orchestrator/INDEX.md"
745
+ || pathname === "INDEX.md";
746
+ }
747
+ function normalizeFilterPath(pathname) {
748
+ let out = pathname.replace(/\/+/g, "/");
749
+ while (out.includes("/./"))
750
+ out = out.replace(/\/\.\//g, "/");
751
+ while (out.startsWith("./"))
752
+ out = out.slice(2);
753
+ while (out.length > 1 && out.endsWith("/"))
754
+ out = out.slice(0, -1);
755
+ return out;
756
+ }
757
+ function sleepSyncMs(ms) {
758
+ if (ms <= 0)
759
+ return;
760
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
761
+ }
762
+ function parseNonNegativeEnvInt(raw, fallback) {
763
+ return raw && /^\d+$/.test(raw) ? Number(raw) : fallback;
764
+ }
765
+ function parsePsEtimeSeconds(etime) {
766
+ const trimmed = etime.trim();
767
+ let days = 0;
768
+ let rest = trimmed;
769
+ if (rest.includes("-")) {
770
+ const [dPart, hmsPart] = rest.split("-", 2);
771
+ if (!dPart || !/^\d+$/.test(dPart) || !hmsPart)
772
+ return undefined;
773
+ days = Number(dPart);
774
+ rest = hmsPart;
775
+ }
776
+ const parts = rest.split(":");
777
+ if (parts.length === 3 && parts.every((part) => /^\d+$/.test(part))) {
778
+ return days * 86400 + Number(parts[0]) * 3600 + Number(parts[1]) * 60 + Number(parts[2]);
779
+ }
780
+ if (parts.length === 2 && parts.every((part) => /^\d+$/.test(part))) {
781
+ return days * 86400 + Number(parts[0]) * 60 + Number(parts[1]);
782
+ }
783
+ return undefined;
784
+ }
785
+ function anyGitProcessOlderThan(minSeconds) {
786
+ // The helper reads whatever ps printed and ignores its exit status, so a ps
787
+ // that lists an old git and then exits non-zero still keeps the lock. Only
788
+ // no output at all (ps missing, nothing printed) means "no older git".
789
+ const probe = spawnSync("ps", ["-axo", "etime=,comm="], {
790
+ encoding: "utf8",
791
+ stdio: ["ignore", "pipe", "ignore"],
792
+ maxBuffer: 64 * 1024 * 1024,
793
+ });
794
+ if (typeof probe.stdout !== "string" || probe.stdout === "")
795
+ return false;
796
+ for (const rawLine of probe.stdout.split(/\r?\n/)) {
797
+ const line = rawLine.trim();
798
+ if (!line)
799
+ continue;
800
+ const match = /^(\S+)\s+(.+)$/.exec(line);
801
+ if (!match)
802
+ continue;
803
+ const comm = match[2].trim();
804
+ if (comm !== "git" && !comm.endsWith("/git"))
805
+ continue;
806
+ const secs = parsePsEtimeSeconds(match[1]);
807
+ if (secs === undefined || secs >= minSeconds)
808
+ return true;
809
+ }
810
+ return false;
811
+ }
812
+ function createIndexRetryState(root) {
813
+ const rawIndexPath = gitLiteral(["rev-parse", "--git-path", "index.lock"], root).stdout.trim();
814
+ return {
815
+ maxRetries: parseNonNegativeEnvInt(process.env.HQ_HANDOFF_INDEX_LOCK_RETRIES, 0),
816
+ waitBudgetMs: parseNonNegativeEnvInt(process.env.HQ_HANDOFF_INDEX_LOCK_WAIT_SECONDS, 60) * 1000,
817
+ staleSeconds: parseNonNegativeEnvInt(process.env.HQ_HANDOFF_STALE_LOCK_SECONDS, 600),
818
+ waitedMs: 0,
819
+ waits: 0,
820
+ staleChecked: false,
821
+ staleRemoved: false,
822
+ gitIndexPath: rawIndexPath,
823
+ };
824
+ }
825
+ function clearStaleIndexFile(root, state, stderrParts) {
826
+ if (state.staleChecked)
827
+ return false;
828
+ state.staleChecked = true;
829
+ if (!state.gitIndexPath)
830
+ return false;
831
+ const resolved = path.isAbsolute(state.gitIndexPath) ? state.gitIndexPath : path.join(root, state.gitIndexPath);
832
+ if (!statNoThrow(resolved)?.isFile())
833
+ return false;
834
+ // `stat` in the helper does not follow links: a lock that is a symlink is
835
+ // aged by the link, not by an old file it points at.
836
+ const stat = lstatNoThrow(resolved);
837
+ if (!stat)
838
+ return false;
839
+ const nowSec = Math.floor(Date.now() / 1000);
840
+ const ageSec = nowSec - Math.floor(stat.mtimeMs / 1000);
841
+ if (ageSec < state.staleSeconds)
842
+ return false;
843
+ if (anyGitProcessOlderThan(ageSec)) {
844
+ stderrParts.push(`handoff-finalize: ${state.gitIndexPath} is ${ageSec}s old but a git process older than it is still running; leaving it alone\n`);
845
+ return false;
846
+ }
847
+ try {
848
+ fs.rmSync(resolved, { force: true });
849
+ }
850
+ catch {
851
+ return false;
852
+ }
853
+ state.staleRemoved = true;
854
+ stderrParts.push(`handoff-finalize: removed stale ${state.gitIndexPath} (${ageSec}s old, no git process older than it); retrying the stage\n`);
855
+ return true;
856
+ }
857
+ function runGitWithIndexRetry(root, state, stderrParts, action,
858
+ /** A failed attempt already made for this operation; used once in place of the first run. */
859
+ firstAttempt) {
860
+ const lockAbs = state.gitIndexPath
861
+ ? (path.isAbsolute(state.gitIndexPath) ? state.gitIndexPath : path.join(root, state.gitIndexPath))
862
+ : "";
863
+ let attempt = 0;
864
+ let pending = firstAttempt;
865
+ for (;;) {
866
+ const res = pending ?? action();
867
+ pending = undefined;
868
+ // The helper greps git's stderr only (stdout is the caller's).
869
+ const combinedErr = res.stderr;
870
+ if (res.code === 0 || !combinedErr.includes("index.lock"))
871
+ return res;
872
+ if (clearStaleIndexFile(root, state, stderrParts))
873
+ continue;
874
+ const lockPresent = Boolean(lockAbs && fs.existsSync(lockAbs));
875
+ if ((!/File exists/i.test(combinedErr) && !lockPresent)
876
+ || state.waitedMs >= state.waitBudgetMs
877
+ || (state.maxRetries > 0 && attempt >= state.maxRetries)) {
878
+ return res;
879
+ }
880
+ attempt += 1;
881
+ state.waits += 1;
882
+ const polls = attempt === 1 ? 1 : attempt === 2 ? 2 : attempt === 3 ? 4 : attempt === 4 ? 8 : 10;
883
+ for (let i = 0; i < polls; i += 1) {
884
+ sleepSyncMs(100);
885
+ state.waitedMs += 100;
886
+ if (lockAbs && !fs.existsSync(lockAbs))
887
+ break;
888
+ }
889
+ }
890
+ }
891
+ function chunkPathspecs(paths, maxBytes = 24_000) {
892
+ if (paths.length === 0)
893
+ return [];
894
+ const chunks = [];
895
+ let current = [];
896
+ let bytes = 0;
897
+ for (const item of paths) {
898
+ const len = Buffer.byteLength(item) + 1;
899
+ if (current.length > 0 && bytes + len > maxBytes) {
900
+ chunks.push(current);
901
+ current = [];
902
+ bytes = 0;
903
+ }
904
+ current.push(item);
905
+ bytes += len;
906
+ }
907
+ if (current.length > 0)
908
+ chunks.push(current);
909
+ return chunks;
910
+ }
911
+ function readGitlinks(root) {
912
+ const res = gitLiteral(["ls-files", "-s", "-z"], root);
913
+ const links = new Set();
914
+ if (res.code !== 0 || !res.stdout)
915
+ return links;
916
+ for (const entry of res.stdout.split("\0")) {
917
+ if (!entry.startsWith("160000 "))
918
+ continue;
919
+ const tab = entry.indexOf("\t");
920
+ if (tab !== -1)
921
+ links.add(entry.slice(tab + 1));
922
+ }
923
+ return links;
924
+ }
925
+ function findNestedRepoRoot(pathname, gitlinks) {
926
+ if (gitlinks.size === 0)
927
+ return "";
928
+ let d = pathname;
929
+ while (d.includes("/")) {
930
+ d = d.slice(0, d.lastIndexOf("/"));
931
+ if (!d)
932
+ break;
933
+ if (gitlinks.has(d))
934
+ return d;
935
+ }
936
+ return "";
937
+ }
938
+ function firstLineOfError(text) {
939
+ for (const rawLine of text.split(/\r?\n/)) {
940
+ const trimmed = rawLine.replace(/\r/g, "");
941
+ if (/\S/.test(trimmed))
942
+ return trimmed.slice(0, 300);
943
+ }
944
+ return "";
945
+ }
946
+ function classifyStageError(firstErr, failureCount) {
947
+ if (failureCount <= 0)
948
+ return "";
949
+ if (/Operation not permitted|Permission denied|Read-only file system/.test(firstErr))
950
+ return "permission";
951
+ if (firstErr.includes("index.lock"))
952
+ return "index-lock";
953
+ return "other";
954
+ }
305
955
  function stagePathExists(root, pathname) {
306
- return fs.existsSync(path.join(root, pathname)) || git(["status", "--porcelain", "--", pathname], root).stdout !== "";
307
- }
308
- function stagePath(root, pathname) {
309
- if (!stagePathExists(root, pathname))
310
- return { attempted: false, ok: false, failed: false };
311
- if (git(["add", "--", pathname], root).code === 0)
312
- return { attempted: true, ok: true, failed: false };
313
- if (git(["ls-files", "--error-unmatch", "--", pathname], root).code === 0) {
314
- return git(["add", "-f", "--", pathname], root).code === 0
315
- ? { attempted: true, ok: true, failed: false }
316
- : { attempted: true, ok: false, failed: true };
317
- }
318
- if (git(["check-ignore", "--no-index", "-q", "--", pathname], root).code === 0) {
319
- return { attempted: true, ok: false, failed: false };
320
- }
321
- return { attempted: true, ok: false, failed: true };
322
- }
323
- // Stages every path with one `git add` instead of one per path. The paths go
324
- // to git on stdin, NUL-separated, never through a shell. A dry run comes first:
325
- // it stages nothing and fails on the inputs that make a real `git add` stage
326
- // some paths and still exit non-zero (ignored paths), so the real batch only
327
- // runs when it is expected to succeed, and a real batch that fails anyway dies
328
- // before git writes the index. Whenever either step fails (an ignored or
329
- // unstageable path, or a git older than 2.25 without --pathspec-from-file),
330
- // every path goes through the per-path stagePath() exactly as before, from an
331
- // unchanged index, so staged, skipped and failed paths are reported as today.
332
- function stagePaths(root, pathnames) {
333
- const perPath = () => pathnames.map((pathname) => stagePath(root, pathname));
334
- if (pathnames.some((pathname) => pathname.includes("\0")))
335
- return perPath();
336
- const exists = pathnames.map((pathname) => stagePathExists(root, pathname));
337
- const candidates = pathnames.filter((_, index) => exists[index]);
338
- if (candidates.length === 0)
339
- return pathnames.map(() => ({ attempted: false, ok: false, failed: false }));
340
- const input = `${candidates.join("\0")}\0`;
341
- const batchArgs = ["--pathspec-from-file=-", "--pathspec-file-nul"];
342
- if (git(["add", "--dry-run", ...batchArgs], root, input).code !== 0)
343
- return perPath();
344
- if (git(["add", ...batchArgs], root, input).code !== 0)
345
- return perPath();
346
- return exists.map((attempted) => ({ attempted, ok: attempted, failed: false }));
956
+ return fs.existsSync(path.join(root, pathname))
957
+ || gitLiteral(["status", "--porcelain", "--", pathname], root).stdout !== "";
958
+ }
959
+ function unstageUnwantedFiles(root, state, stderrParts, addedPaths, skipped, stageFailures, setFilterFailed) {
960
+ if (addedPaths.length === 0)
961
+ return;
962
+ const failFilter = (reason) => {
963
+ setFilterFailed();
964
+ stageFailures.push(`handoff-filter: ${reason}`);
965
+ for (const chunk of chunkPathspecs(addedPaths)) {
966
+ runGitWithIndexRetry(root, state, stderrParts, () => gitLiteral(["reset", "-q", "--pathspec-from-file=-", "--pathspec-file-nul"], root, `${chunk.join("\0")}\0`));
967
+ }
968
+ };
969
+ const addedNorm = new Set(addedPaths.map(normalizeFilterPath));
970
+ const rawRecords = [];
971
+ const renamed = new Set();
972
+ const chunks = chunkPathspecs(addedPaths);
973
+ for (const chunk of chunks) {
974
+ const rawRes = gitLiteral(["diff", "--cached", "--raw", "-z", "--no-abbrev", "--no-renames", "--diff-filter=AMT", "--", ...chunk], root);
975
+ if (rawRes.code !== 0) {
976
+ failFilter("could not list staged changes");
977
+ return;
978
+ }
979
+ const rawTokens = rawRes.stdout.split("\0");
980
+ for (let idx = 0; idx + 1 < rawTokens.length; idx += 2) {
981
+ const meta = rawTokens[idx];
982
+ const filePath = rawTokens[idx + 1];
983
+ if (!meta || filePath === undefined)
984
+ break;
985
+ const metaParts = meta.trim().split(" ");
986
+ const status = metaParts[metaParts.length - 1] ?? "";
987
+ const sha = metaParts[3] ?? "";
988
+ rawRecords.push({ path: filePath, status, sha });
989
+ }
990
+ const renRes = gitLiteral(["diff", "--cached", "-z", "--name-status", "-M", "--diff-filter=R", "--", ...chunk], root);
991
+ if (renRes.code !== 0) {
992
+ failFilter("could not list staged renames");
993
+ return;
994
+ }
995
+ const renTokens = renRes.stdout.split("\0");
996
+ for (let idx = 0; idx + 2 < renTokens.length; idx += 3) {
997
+ if (!renTokens[idx])
998
+ break;
999
+ const newPath = renTokens[idx + 2];
1000
+ if (newPath)
1001
+ renamed.add(newPath);
1002
+ }
1003
+ }
1004
+ if (rawRecords.length === 0)
1005
+ return;
1006
+ // The helper lists every staged file in one git call (sorted, each file
1007
+ // once). Several pathspec chunks can repeat a file and break that order.
1008
+ if (chunks.length > 1) {
1009
+ const seenRaw = new Set();
1010
+ const unique = rawRecords.filter((rec) => (seenRaw.has(rec.path) ? false : (seenRaw.add(rec.path), true)));
1011
+ unique.sort((a, b) => Buffer.compare(Buffer.from(a.path), Buffer.from(b.path)));
1012
+ rawRecords.splice(0, rawRecords.length, ...unique);
1013
+ }
1014
+ const maxBytesEnv = process.env.HQ_OFFLOAD_MIN_BYTES;
1015
+ const maxBytes = maxBytesEnv && /^\d+$/.test(maxBytesEnv) && Number(maxBytesEnv) > 0
1016
+ ? Number(maxBytesEnv)
1017
+ : 52428800;
1018
+ const allowMedia = process.env.HQ_HANDOFF_ALLOW_MEDIA === "1";
1019
+ const shasInput = `${rawRecords.map((rec) => rec.sha).join("\n")}\n`;
1020
+ const sizeRes = gitLiteral(["cat-file", "--batch-check=%(objectsize)"], root, shasInput);
1021
+ if (sizeRes.code !== 0) {
1022
+ failFilter("could not size staged files");
1023
+ return;
1024
+ }
1025
+ const sizeLines = sizeRes.stdout.split(/\r?\n/);
1026
+ if (sizeLines.length > 0 && sizeLines[sizeLines.length - 1] === "")
1027
+ sizeLines.pop();
1028
+ if (sizeLines.length !== rawRecords.length) {
1029
+ failFilter(`sized ${sizeLines.length} of ${rawRecords.length} staged files`);
1030
+ return;
1031
+ }
1032
+ const unstageList = [];
1033
+ for (let idx = 0; idx < rawRecords.length; idx += 1) {
1034
+ const rec = rawRecords[idx];
1035
+ if (isHandoffFilterExempt(rec.path))
1036
+ continue;
1037
+ const rawSize = sizeLines[idx] ?? "";
1038
+ const size = /^\d+$/.test(rawSize) ? Number(rawSize) : 0;
1039
+ let reason = "";
1040
+ if (size > maxBytes)
1041
+ reason = "oversize";
1042
+ else if (rec.status === "A"
1043
+ && !allowMedia
1044
+ && isHandoffMediaPath(rec.path)
1045
+ && !addedNorm.has(rec.path)
1046
+ && !renamed.has(rec.path)) {
1047
+ reason = "media-in-directory";
1048
+ }
1049
+ if (!reason)
1050
+ continue;
1051
+ unstageList.push(rec.path);
1052
+ skipped.push({ path: rec.path, reason });
1053
+ }
1054
+ if (unstageList.length > 0) {
1055
+ for (const chunk of chunkPathspecs(unstageList)) {
1056
+ const resetRes = runGitWithIndexRetry(root, state, stderrParts, () => gitLiteral(["reset", "-q", "--pathspec-from-file=-", "--pathspec-file-nul"], root, `${chunk.join("\0")}\0`));
1057
+ if (resetRes.code !== 0) {
1058
+ failFilter("could not unstage filtered files");
1059
+ return;
1060
+ }
1061
+ }
1062
+ }
1063
+ }
1064
+ function stageExplicitPaths(root, explicit, gitlinks, state, stderrParts, skipped) {
1065
+ let staged = 0;
1066
+ const addedPaths = [];
1067
+ const stageFailures = [];
1068
+ let firstStageError = "";
1069
+ const nestedRepoPaths = [];
1070
+ const nestedDirtyMessages = [];
1071
+ let filterFailed = false;
1072
+ const noteFailure = (pathname, errText) => {
1073
+ stageFailures.push(pathname);
1074
+ if (!firstStageError)
1075
+ firstStageError = firstLineOfError(errText);
1076
+ };
1077
+ const regularPaths = [];
1078
+ for (const pathname of explicit) {
1079
+ if (!pathname)
1080
+ continue;
1081
+ const nested = findNestedRepoRoot(pathname, gitlinks);
1082
+ if (nested) {
1083
+ const inner = pathname.slice(nested.length + 1);
1084
+ const innerStatus = gitLiteral(["-C", nested, "status", "--porcelain", "--", inner], root).stdout;
1085
+ if (innerStatus !== "") {
1086
+ noteFailure(pathname, "");
1087
+ nestedDirtyMessages.push(`${pathname} is uncommitted inside nested repository ${nested} (commit it there, then re-run)`);
1088
+ continue;
1089
+ }
1090
+ if (!nestedRepoPaths.includes(pathname))
1091
+ nestedRepoPaths.push(pathname);
1092
+ const nestedDirty = gitLiteral(["status", "--porcelain", "--ignore-submodules=untracked", "--", nested], root).stdout !== "";
1093
+ const nestedTracked = gitLiteral(["ls-files", "--error-unmatch", "--", nested], root).code === 0;
1094
+ if (nestedDirty && nestedTracked) {
1095
+ const res = runGitWithIndexRetry(root, state, stderrParts, () => gitLiteral(["add", "--", nested], root));
1096
+ if (res.code === 0) {
1097
+ staged += 1;
1098
+ addedPaths.push(nested);
1099
+ }
1100
+ else {
1101
+ noteFailure(nested, res.stderr);
1102
+ }
1103
+ }
1104
+ continue;
1105
+ }
1106
+ regularPaths.push(pathname);
1107
+ }
1108
+ // The helper has no batch: its first `git add` is the first path's. When the
1109
+ // batch pre-flight below is refused because index.lock is held, that refusal
1110
+ // stands in for the first path's first attempt, so the wait it causes is
1111
+ // counted once (index_lock_waits) and the lock is retried, not skipped.
1112
+ let lockedPreflight;
1113
+ const stageOnePath = (pathname) => {
1114
+ if (!stagePathExists(root, pathname))
1115
+ return;
1116
+ const firstAttempt = lockedPreflight;
1117
+ lockedPreflight = undefined;
1118
+ const addRes = runGitWithIndexRetry(root, state, stderrParts, () => gitLiteral(["add", "--", pathname], root), firstAttempt);
1119
+ if (addRes.code === 0) {
1120
+ staged += 1;
1121
+ addedPaths.push(pathname);
1122
+ return;
1123
+ }
1124
+ const isDir = Boolean(fs.statSync(path.join(root, pathname), { throwIfNoEntry: false })?.isDirectory());
1125
+ const ignored = runGitWithEnv(["check-ignore", "--no-index", "-q", "--", pathname], root, { GIT_LITERAL_PATHSPECS: "0" }).code === 0;
1126
+ const tracked = gitLiteral(["ls-files", "--error-unmatch", "--", pathname], root).code === 0;
1127
+ if (isDir && ignored && tracked) {
1128
+ const updateRes = runGitWithIndexRetry(root, state, stderrParts, () => gitLiteral(["add", "-u", "--", pathname], root));
1129
+ if (updateRes.code === 0) {
1130
+ const ignoredList = gitLiteral(["ls-files", "-z", "-o", "-i", "--exclude-standard", "--directory", "--", pathname], root);
1131
+ for (const item of ignoredList.stdout.split("\0")) {
1132
+ if (item)
1133
+ skipped.push({ path: item, reason: "ignored-untracked" });
1134
+ }
1135
+ staged += 1;
1136
+ addedPaths.push(pathname);
1137
+ }
1138
+ else {
1139
+ noteFailure(pathname, updateRes.stderr);
1140
+ }
1141
+ return;
1142
+ }
1143
+ if (!isDir && tracked) {
1144
+ const forceRes = runGitWithIndexRetry(root, state, stderrParts, () => gitLiteral(["add", "-f", "--", pathname], root));
1145
+ if (forceRes.code === 0) {
1146
+ staged += 1;
1147
+ addedPaths.push(pathname);
1148
+ }
1149
+ else {
1150
+ noteFailure(pathname, forceRes.stderr);
1151
+ }
1152
+ return;
1153
+ }
1154
+ if (ignored)
1155
+ return;
1156
+ noteFailure(pathname, addRes.stderr);
1157
+ };
1158
+ if (regularPaths.length > 0) {
1159
+ const canBatch = !regularPaths.some((pathname) => pathname.includes("\0"));
1160
+ let batchedOk = false;
1161
+ if (canBatch) {
1162
+ const exists = regularPaths.map((pathname) => stagePathExists(root, pathname));
1163
+ const candidates = regularPaths.filter((_, index) => exists[index]);
1164
+ if (candidates.length === 0) {
1165
+ batchedOk = true;
1166
+ }
1167
+ else {
1168
+ const input = `${candidates.join("\0")}\0`;
1169
+ const batchArgs = ["--pathspec-from-file=-", "--pathspec-file-nul"];
1170
+ const dryRun = gitLiteral(["add", "--dry-run", ...batchArgs], root, input);
1171
+ if (dryRun.code !== 0 && dryRun.stderr.includes("index.lock"))
1172
+ lockedPreflight = dryRun;
1173
+ if (dryRun.code === 0) {
1174
+ const addRes = runGitWithIndexRetry(root, state, stderrParts, () => gitLiteral(["add", ...batchArgs], root, input));
1175
+ if (addRes.code === 0) {
1176
+ staged += candidates.length;
1177
+ addedPaths.push(...candidates);
1178
+ batchedOk = true;
1179
+ }
1180
+ }
1181
+ }
1182
+ }
1183
+ if (!batchedOk) {
1184
+ for (const pathname of regularPaths)
1185
+ stageOnePath(pathname);
1186
+ }
1187
+ }
1188
+ unstageUnwantedFiles(root, state, stderrParts, addedPaths, skipped, stageFailures, () => {
1189
+ filterFailed = true;
1190
+ });
1191
+ return {
1192
+ staged,
1193
+ addedPaths,
1194
+ stageFailures,
1195
+ firstStageError,
1196
+ stageFailureClass: classifyStageError(firstStageError, stageFailures.length),
1197
+ nestedRepoPaths,
1198
+ nestedDirtyMessages,
1199
+ filterFailed,
1200
+ };
1201
+ }
1202
+ function directoryHasFileNamed(dir, targetName) {
1203
+ let entries;
1204
+ try {
1205
+ entries = fs.readdirSync(dir, { withFileTypes: true });
1206
+ }
1207
+ catch {
1208
+ return false;
1209
+ }
1210
+ for (const entry of entries) {
1211
+ if (entry.isDirectory()) {
1212
+ if (directoryHasFileNamed(path.join(dir, entry.name), targetName))
1213
+ return true;
1214
+ }
1215
+ else if (entry.name === targetName) {
1216
+ return true;
1217
+ }
1218
+ }
1219
+ return false;
1220
+ }
1221
+ function isThreadIdTaken(root, candidate, lockedCompanies) {
1222
+ const filename = `${candidate}.json`;
1223
+ if (fs.existsSync(path.join(root, "workspace/threads", filename)))
1224
+ return true;
1225
+ if (directoryHasFileNamed(path.join(root, "workspace/threads/archive"), filename))
1226
+ return true;
1227
+ for (const co of lockedCompanies) {
1228
+ if (co && fs.existsSync(path.join(root, "companies", co, "workspace/sessions", filename)))
1229
+ return true;
1230
+ }
1231
+ return false;
1232
+ }
1233
+ function readPointerCreatedAt(file) {
1234
+ try {
1235
+ const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
1236
+ return isRecord(parsed) && typeof parsed.created_at === "string" ? parsed.created_at : "";
1237
+ }
1238
+ catch {
1239
+ return "";
1240
+ }
1241
+ }
1242
+ /**
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.
1247
+ */
1248
+ 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)
1254
+ return { pid: "", status: "skipped" };
1255
+ 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]+$/, "") : "";
1258
+ return pid ? { pid, status: "dispatched" } : { pid: "", status: "skipped" };
1259
+ }
1260
+ catch {
1261
+ return { pid: "", status: "skipped" };
1262
+ }
1263
+ }
1264
+ /** `_hq_fp_yaml_scalar <file> enabled`: undefined when the file or the key is missing. */
1265
+ function fingerprintEnabledScalar(file) {
1266
+ let text;
1267
+ try {
1268
+ if (!fs.statSync(file).isFile())
1269
+ return undefined;
1270
+ text = fs.readFileSync(file, "utf8");
1271
+ }
1272
+ catch {
1273
+ return undefined;
1274
+ }
1275
+ const line = text.split("\n").find((entry) => /^enabled:\s*/.test(entry));
1276
+ if (line === undefined)
1277
+ return undefined;
1278
+ return line.slice(line.indexOf(":") + 1).replace(/\s*#.*$/, "").trim();
1279
+ }
1280
+ /**
1281
+ * The gates lib/fingerprint.sh applies before it builds a trailer: the setting
1282
+ * (`enabled:` in personal/settings/fingerprint.yaml, then core/settings/) is
1283
+ * not false, and a session id is present in the environment (the library has
1284
+ * no cache key without one and prints nothing).
1285
+ */
1286
+ function fingerprintTrailerWanted(root) {
1287
+ const raw = fingerprintEnabledScalar(path.join(root, "personal/settings/fingerprint.yaml"))
1288
+ ?? fingerprintEnabledScalar(path.join(root, "core/settings/fingerprint.yaml"))
1289
+ ?? "";
1290
+ if (["false", "no", "off", "0"].includes(raw.replace(/["']/g, "").toLowerCase()))
1291
+ return false;
1292
+ for (const key of ["HQ_SESSION_ID", "CLAUDE_CODE_SESSION_ID", "CLAUDE_SESSION_ID", "CODEX_SESSION_ID", "CODEX_THREAD_ID", "GROK_SESSION_ID"]) {
1293
+ const value = (process.env[key] ?? "").replace(/\s/g, "");
1294
+ if (!value || value === "." || value === ".." || /[^A-Za-z0-9._-]/.test(value))
1295
+ continue;
1296
+ return true;
1297
+ }
1298
+ return false;
347
1299
  }
348
1300
  function tidyGitMessage(value) {
349
1301
  const flattened = value.replace(/[\r\n]/g, " ").replace(/ */g, " ").replace(/^ | $/g, "");
@@ -351,70 +1303,100 @@ function tidyGitMessage(value) {
351
1303
  }
352
1304
  function resolveFinalizeOptions(args) {
353
1305
  const values = {
354
- title: "Handoff: session continuation", summary: "", message: "", nextSteps: "[]",
355
- filesTouched: "[]", filesTouchedFile: "", learnings: "[]", tags: '["handoff"]',
1306
+ company: "", title: "Handoff: session continuation", summary: "", message: "", nextSteps: "[]",
1307
+ filesTouched: "[]", filesTouchedFile: "", learnings: "[]", learningsFile: "",
1308
+ deficienciesFile: "", deficienciesGiven: false, tags: '["handoff"]',
356
1309
  slug: "handoff", nextCommand: "__auto__",
357
1310
  };
358
1311
  const map = {
359
- "--title": "title", "--summary": "summary", "--message": "message",
360
- "--next-steps-json": "nextSteps", "--files-touched-json": "filesTouched",
361
- "--files-touched-json-file": "filesTouchedFile", "--learnings-json": "learnings",
362
- "--tags-json": "tags", "--slug": "slug", "--next-command": "nextCommand",
1312
+ "--company": { target: "company", line: 140 },
1313
+ "--title": { target: "title", line: 141 },
1314
+ "--summary": { target: "summary", line: 142 },
1315
+ "--message": { target: "message", line: 143 },
1316
+ "--next-steps-json": { target: "nextSteps", line: 144 },
1317
+ "--files-touched-json": { target: "filesTouched", line: 145 },
1318
+ "--files-touched-json-file": { target: "filesTouchedFile", line: 146 },
1319
+ "--learnings-json": { target: "learnings", line: 147 },
1320
+ "--learnings-json-file": { target: "learningsFile", line: 148 },
1321
+ "--deficiencies-json": { target: "deficienciesFile", line: 149 },
1322
+ "--tags-json": { target: "tags", line: 150 },
1323
+ "--slug": { target: "slug", line: 151 },
1324
+ "--next-command": { target: "nextCommand", line: 152 },
363
1325
  };
364
1326
  for (let index = 0; index < args.length;) {
365
1327
  const key = args[index] ?? "";
366
- const target = map[key];
367
- if (!target)
1328
+ const spec = map[key];
1329
+ if (!spec)
368
1330
  return { values, error: { code: 2, stdout: "", stderr: `Unknown arg: ${key}\n` } };
369
1331
  if (index + 1 >= args.length) {
370
1332
  const shellAsset = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../assets/scaffold", ASSETS.finalize);
371
- return { values, error: { code: 1, stdout: "", stderr: `${shellAsset}: line 93: $2: unbound variable\n` } };
1333
+ return { values, error: { code: 1, stdout: "", stderr: `${shellAsset}: line ${spec.line}: $2: unbound variable\n` } };
372
1334
  }
373
- values[target] = args[index + 1] ?? "";
1335
+ if (key === "--deficiencies-json")
1336
+ values.deficienciesGiven = true;
1337
+ values[spec.target] = args[index + 1] ?? "";
374
1338
  index += 2;
375
1339
  }
376
1340
  return { values };
377
1341
  }
1342
+ function parseFinalizeJson(raw, flag) {
1343
+ try {
1344
+ return { ok: true, value: JSON.parse(raw) };
1345
+ }
1346
+ catch {
1347
+ return {
1348
+ ok: false,
1349
+ error: {
1350
+ code: 2,
1351
+ stdout: "",
1352
+ stderr: `handoff-finalize: ${flag} is not valid JSON (expected one JSON value). Nothing was written.\n`,
1353
+ },
1354
+ };
1355
+ }
1356
+ }
378
1357
  export function runHandoffFinalize(args, context) {
379
1358
  const root = fs.realpathSync(context.root);
1359
+ const logicalRoot = path.resolve(context.logicalRoot ?? context.root);
380
1360
  const probe = finalizeGitProbe(root);
381
1361
  if ("code" in probe)
382
1362
  return probe;
383
- let gitBgErrors = "";
384
- const tmpRoot = context.tmpDir ?? "/tmp";
385
- const gitPidFile = path.join(tmpRoot, "handoff-git-bg.pid");
386
- if (fs.existsSync(gitPidFile)) {
387
- let pid = "";
388
- try {
389
- pid = fs.readFileSync(gitPidFile, "utf8").trim();
390
- }
391
- catch { /* legacy reads fail-soft */ }
392
- if (pid) {
393
- const gitLog = path.join(tmpRoot, "handoff-git-bg.log");
394
- if (fs.existsSync(gitLog)) {
395
- try {
396
- gitBgErrors = fs.readFileSync(gitLog, "utf8").split(/\r?\n/).filter((entry) => entry.startsWith("ERR:")).join("\n");
397
- }
398
- catch {
399
- gitBgErrors = "";
400
- }
401
- }
402
- }
403
- try {
404
- fs.rmSync(gitPidFile, { force: true });
405
- }
406
- catch { /* shell cleanup ignores rm failures */ }
407
- }
408
1363
  const { values, error } = resolveFinalizeOptions(args);
409
1364
  if (error)
410
1365
  return error;
1366
+ const stepsParsed = parseFinalizeJson(values.nextSteps, "--next-steps-json");
1367
+ if (!stepsParsed.ok)
1368
+ return stepsParsed.error;
1369
+ const tagsParsed = parseFinalizeJson(values.tags, "--tags-json");
1370
+ if (!tagsParsed.ok)
1371
+ return tagsParsed.error;
1372
+ let learningsValue;
1373
+ if (values.learningsFile) {
1374
+ const resolvedLearnings = path.isAbsolute(values.learningsFile) ? values.learningsFile : path.join(root, values.learningsFile);
1375
+ if (!statNoThrow(resolvedLearnings)?.isFile()) {
1376
+ return { code: 3, stdout: "", stderr: `handoff-finalize: --learnings-json-file not found: ${values.learningsFile}\n` };
1377
+ }
1378
+ const learningsFileParsed = parseFinalizeJson(stripByteOrderMark(fs.readFileSync(resolvedLearnings, "utf8")), "--learnings-json-file");
1379
+ if (!learningsFileParsed.ok)
1380
+ return learningsFileParsed.error;
1381
+ learningsValue = learningsFileParsed.value;
1382
+ }
1383
+ else {
1384
+ const learningsInlineParsed = parseFinalizeJson(values.learnings, "--learnings-json");
1385
+ if (!learningsInlineParsed.ok)
1386
+ return learningsInlineParsed.error;
1387
+ learningsValue = learningsInlineParsed.value;
1388
+ }
1389
+ let inlineTouchedValue;
1390
+ if (!values.filesTouchedFile) {
1391
+ const touchedInlineParsed = parseFinalizeJson(values.filesTouched, "--files-touched-json");
1392
+ if (!touchedInlineParsed.ok)
1393
+ return touchedInlineParsed.error;
1394
+ inlineTouchedValue = touchedInlineParsed.value;
1395
+ }
411
1396
  const timestamp = nowFor(context);
412
1397
  const ts = stamp(timestamp);
413
1398
  const date = dayStamp(timestamp);
414
1399
  const clock = timeStamp(timestamp);
415
- const threadId = `T-${date}-${clock}-${values.slug}`;
416
- const threadPath = `workspace/threads/${threadId}.json`;
417
- const changesetPath = `workspace/threads/${threadId}.changeset.json`;
418
1400
  const threadsDir = path.join(root, "workspace/threads");
419
1401
  const tempDirectory = path.join(threadsDir, ".handoff-tmp");
420
1402
  fs.mkdirSync(tempDirectory, { recursive: true });
@@ -429,24 +1411,38 @@ export function runHandoffFinalize(args, context) {
429
1411
  const safePaths = [];
430
1412
  const skipped = [];
431
1413
  let touchedValue;
1414
+ let touchedFile;
432
1415
  if (values.filesTouchedFile) {
433
1416
  const file = path.isAbsolute(values.filesTouchedFile) ? values.filesTouchedFile : path.join(root, values.filesTouchedFile);
434
- if (!fs.existsSync(file))
1417
+ if (!statNoThrow(file)?.isFile()) {
435
1418
  return { code: 3, stdout: "", stderr: `handoff-finalize: --files-touched-json-file not found: ${values.filesTouchedFile}\n` };
436
- touchedValue = parseHandoffJson(fs.readFileSync(file, "utf8"), "--files-touched-json-file");
1419
+ }
1420
+ // jq reads the file with --slurpfile: a UTF-8 byte order mark is skipped
1421
+ // and an empty file is "no value" (`$files_touched[0] // []`), not an error.
1422
+ const touchedText = stripByteOrderMark(fs.readFileSync(file, "utf8"));
1423
+ if (touchedText.trim() === "") {
1424
+ touchedValue = undefined;
1425
+ }
1426
+ else {
1427
+ const touchedFileParsed = parseFinalizeJson(touchedText, "--files-touched-json-file");
1428
+ if (!touchedFileParsed.ok)
1429
+ return touchedFileParsed.error;
1430
+ touchedValue = touchedFileParsed.value;
1431
+ }
1432
+ touchedFile = file;
1433
+ // The helper always has temp files in .handoff-tmp/ by the time the status
1434
+ // summary runs, so the folder shows up there for both changeset forms.
1435
+ tempFile();
437
1436
  }
438
1437
  else {
439
- touchedValue = parseHandoffJson(values.filesTouched, "--files-touched-json");
440
- }
441
- const touchedFile = values.filesTouchedFile
442
- ? (path.isAbsolute(values.filesTouchedFile) ? values.filesTouchedFile : path.join(root, values.filesTouchedFile))
443
- : tempFile();
444
- if (!values.filesTouchedFile)
1438
+ touchedValue = inlineTouchedValue;
1439
+ touchedFile = tempFile();
445
1440
  fs.writeFileSync(touchedFile, values.filesTouched);
1441
+ }
446
1442
  for (const entry of pathEntries(touchedValue)) {
447
1443
  if (!entry.raw)
448
1444
  continue;
449
- const relative = normalizeRelativePath(entry.raw, root);
1445
+ const relative = canonicalRelPath(entry.raw, root, logicalRoot);
450
1446
  if (relative === undefined) {
451
1447
  skipped.push({ path: entry.raw, reason: "unsafe-path" });
452
1448
  continue;
@@ -456,7 +1452,7 @@ export function runHandoffFinalize(args, context) {
456
1452
  continue;
457
1453
  }
458
1454
  if (!fs.existsSync(path.join(root, relative))) {
459
- if (probe.hasGit && entry.deleted && git(["ls-files", "--error-unmatch", relative], root).code === 0)
1455
+ if (probe.hasGit && entry.deleted && gitLiteral(["ls-files", "--error-unmatch", "--", relative], root).code === 0)
460
1456
  safePaths.push(relative);
461
1457
  else
462
1458
  skipped.push({ path: relative, reason: "missing" });
@@ -464,21 +1460,145 @@ export function runHandoffFinalize(args, context) {
464
1460
  }
465
1461
  safePaths.push(relative);
466
1462
  }
467
- const sessionCompany = boundSessionCompany(root);
468
- const companyDirectory = sessionCompany
469
- ? fs.statSync(path.join(root, "companies", sessionCompany), { throwIfNoEntry: false })
470
- : undefined;
471
- const companies = [...new Set([
472
- ...touchedCompanyPaths(safePaths),
473
- ...(companyDirectory?.isDirectory() ? [sessionCompany] : []),
474
- ])].sort();
1463
+ const stderrParts = [];
1464
+ const { touchedCompanies: rawCompanies } = rawTouchedCompanyScope(touchedValue, root, logicalRoot);
1465
+ // The helper's "personal work" test reads the INLINE --files-touched-json
1466
+ // value, never the file form (where the inline value is its default `[]`
1467
+ // and the test cannot pass). Same input here so both skip the same handoffs.
1468
+ let inlineForPersonal;
1469
+ try {
1470
+ inlineForPersonal = JSON.parse(values.filesTouched);
1471
+ }
1472
+ catch {
1473
+ inlineForPersonal = undefined;
1474
+ }
1475
+ const { personalOnly } = rawTouchedCompanyScope(inlineForPersonal, root, logicalRoot);
1476
+ const touchedCompanies = [...new Set([...rawCompanies, ...touchedCompanyPaths(safePaths)])].sort();
1477
+ const handoffSessionId = resolveSessionId(root);
1478
+ let sessionCompany = finalizeBoundSessionCompany(root);
1479
+ const sessionLock = readSessionLockedCompanies(root, handoffSessionId);
1480
+ // owner_in_locked_set: needs the capability file and the session-scope library.
1481
+ const ownerInLockedSet = (company) => sessionLock.capFile && sessionLock.libFile && sessionLock.companies.includes(company);
1482
+ const ownerCompany = values.company;
1483
+ if (ownerCompany) {
1484
+ const ownerDirOk = FINALIZE_COMPANY_SLUG_RE.test(ownerCompany)
1485
+ && Boolean(fs.statSync(path.join(root, "companies", ownerCompany), { throwIfNoEntry: false })?.isDirectory());
1486
+ if (!ownerDirOk) {
1487
+ return { code: 2, stdout: "", stderr: `handoff-finalize: invalid or missing owner company: ${ownerCompany}\n` };
1488
+ }
1489
+ if (sessionCompany && sessionCompany !== ownerCompany && !ownerInLockedSet(ownerCompany)) {
1490
+ return {
1491
+ code: 2,
1492
+ stdout: "",
1493
+ stderr: `handoff-finalize: --company ${ownerCompany} does not match the bound session company ${sessionCompany}\n`,
1494
+ };
1495
+ }
1496
+ sessionCompany = ownerCompany;
1497
+ }
1498
+ let lockedCompanies = [];
1499
+ if (sessionCompany) {
1500
+ lockedCompanies = [sessionCompany];
1501
+ // The capability replaces the bound company only when the helper can read
1502
+ // it, which takes the session-scope library in the HQ root.
1503
+ if (sessionLock.capFile && sessionLock.libFile) {
1504
+ lockedCompanies = sessionLock.companies;
1505
+ const toolNote = sessionLock.companies.length === 0 ? installedScriptToolNote() : "";
1506
+ if (toolNote) {
1507
+ stderrParts.push(`handoff-finalize: the session's company lock set was not read (${toolNote}); only ${sessionCompany} is treated as owned\n`);
1508
+ }
1509
+ }
1510
+ }
1511
+ if (sessionCompany) {
1512
+ const owned = new Set([...lockedCompanies, sessionCompany]);
1513
+ const kept = [];
1514
+ for (const rel of safePaths) {
1515
+ const co = companyOfCanonical(rel);
1516
+ if (co && !owned.has(co)) {
1517
+ skipped.push({ path: rel, reason: "foreign-company" });
1518
+ continue;
1519
+ }
1520
+ kept.push(rel);
1521
+ }
1522
+ safePaths.splice(0, safePaths.length, ...kept);
1523
+ }
1524
+ else {
1525
+ const distinct = new Set(safePaths.map((rel) => companyOfCanonical(rel)).filter(Boolean));
1526
+ if (distinct.size > 1) {
1527
+ const kept = [];
1528
+ for (const rel of safePaths) {
1529
+ if (companyOfCanonical(rel)) {
1530
+ skipped.push({ path: rel, reason: "multi-company-no-owner" });
1531
+ continue;
1532
+ }
1533
+ kept.push(rel);
1534
+ }
1535
+ safePaths.splice(0, safePaths.length, ...kept);
1536
+ }
1537
+ }
1538
+ let mirrorCompanies = [];
1539
+ const boundDirOk = Boolean(sessionCompany)
1540
+ && Boolean(fs.statSync(path.join(root, "companies", sessionCompany), { throwIfNoEntry: false })?.isDirectory());
1541
+ if (touchedCompanies.length > 1) {
1542
+ stderrParts.push("handoff-finalize: company mirror skipped (handoff spans multiple companies)\n");
1543
+ }
1544
+ else if (!boundDirOk) {
1545
+ stderrParts.push("handoff-finalize: company mirror skipped (no bound company for this session)\n");
1546
+ }
1547
+ else if (touchedCompanies.length === 1 && touchedCompanies[0] !== sessionCompany) {
1548
+ stderrParts.push("handoff-finalize: company mirror skipped (handoff paths do not match the bound company)\n");
1549
+ }
1550
+ else if (!ownerCompany && touchedCompanies.length === 0 && personalOnly) {
1551
+ stderrParts.push(`handoff-finalize: company mirror skipped (handoff touched no company or repo paths; pass --company ${sessionCompany} to file it there)\n`);
1552
+ }
1553
+ else {
1554
+ mirrorCompanies = [sessionCompany];
1555
+ }
1556
+ let gitBgErrors = "";
1557
+ const tmpRoot = context.tmpDir ?? "/tmp";
1558
+ const gitPidFile = path.join(tmpRoot, "handoff-git-bg.pid");
1559
+ if (fs.existsSync(gitPidFile)) {
1560
+ let pid = "";
1561
+ try {
1562
+ pid = fs.readFileSync(gitPidFile, "utf8").trim();
1563
+ }
1564
+ catch { /* legacy reads fail-soft */ }
1565
+ if (pid) {
1566
+ const gitLog = path.join(tmpRoot, "handoff-git-bg.log");
1567
+ if (fs.existsSync(gitLog)) {
1568
+ try {
1569
+ gitBgErrors = fs.readFileSync(gitLog, "utf8").split(/\r?\n/).filter((entry) => entry.startsWith("ERR:")).join("\n");
1570
+ }
1571
+ catch {
1572
+ gitBgErrors = "";
1573
+ }
1574
+ }
1575
+ }
1576
+ try {
1577
+ fs.rmSync(gitPidFile, { force: true });
1578
+ }
1579
+ catch { /* shell cleanup ignores rm failures */ }
1580
+ }
1581
+ let threadId = `T-${date}-${clock}-${values.slug}`;
1582
+ if (isThreadIdTaken(root, threadId, lockedCompanies)) {
1583
+ let suffix = 2;
1584
+ while (isThreadIdTaken(root, `${threadId}-${suffix}`, lockedCompanies))
1585
+ suffix += 1;
1586
+ threadId = `${threadId}-${suffix}`;
1587
+ }
1588
+ const threadPath = `workspace/threads/${threadId}.json`;
1589
+ const changesetPath = `workspace/threads/${threadId}.changeset.json`;
475
1590
  const dirty = probe.hasGit && printGitStatus(root) !== "";
476
1591
  const branchResult = probe.hasGit ? git(["symbolic-ref", "--short", "HEAD"], root) : { code: 1, stdout: "", stderr: "" };
477
1592
  const commitResult = probe.hasGit ? git(["rev-parse", "--short", "HEAD"], root) : { code: 1, stdout: "", stderr: "" };
478
1593
  const branch = branchResult.code === 0 ? branchResult.stdout.trim() : "DETACHED";
479
1594
  const startCommit = commitResult.code === 0 ? commitResult.stdout.trim() : "unknown";
480
1595
  const status = statusSummary(root, touchedFile);
481
- const stepsInput = parseHandoffJson(values.nextSteps, "--next-steps-json");
1596
+ const { deficiencies, error: deficienciesError } = readDeficiencies(root, values.deficienciesFile, values.deficienciesGiven, stderrParts);
1597
+ if (deficienciesError)
1598
+ return { ...deficienciesError, stderr: `${stderrParts.join("")}${deficienciesError.stderr}` };
1599
+ const systemInfo = readSystemInfo(root);
1600
+ const stepsInput = stepsParsed.value;
1601
+ const tagsInput = tagsParsed.value;
482
1602
  const nextSteps = Array.isArray(stepsInput) ? stepsInput.map((raw, index) => {
483
1603
  const step = typeof raw === "string" ? { step: raw } : isRecord(raw) ? { ...raw } : {};
484
1604
  if (!jqTruthy(step.id))
@@ -486,6 +1606,19 @@ export function runHandoffFinalize(args, context) {
486
1606
  if (!jqTruthy(step.status))
487
1607
  step.status = "open";
488
1608
  delete step.key;
1609
+ if (step.step === undefined || step.step === null) {
1610
+ if (step.text !== undefined && step.text !== null) {
1611
+ step.step = step.text;
1612
+ delete step.text;
1613
+ }
1614
+ else if (step.content !== undefined && step.content !== null) {
1615
+ step.step = step.content;
1616
+ delete step.content;
1617
+ }
1618
+ else {
1619
+ step.step = "";
1620
+ }
1621
+ }
489
1622
  return step;
490
1623
  }) : [];
491
1624
  const thread = {
@@ -494,23 +1627,52 @@ export function runHandoffFinalize(args, context) {
494
1627
  type: "handoff",
495
1628
  created_at: ts,
496
1629
  updated_at: ts,
1630
+ session_id: handoffSessionId || null,
497
1631
  workspace_root: root,
498
- cwd: root,
1632
+ cwd: logicalRoot,
499
1633
  git: { branch, current_commit: startCommit, dirty },
500
1634
  changeset_path: changesetPath,
501
1635
  conversation_summary: values.summary,
502
1636
  next_steps: nextSteps,
503
- files_touched: touchedValue,
504
- learnings: parseHandoffJson(values.learnings, "--learnings-json"),
505
- metadata: { title: values.title, tags: parseHandoffJson(values.tags, "--tags-json"), company: companies },
1637
+ files_touched: jqTruthy(touchedValue) ? touchedValue : [],
1638
+ learnings: jqTruthy(learningsValue) ? learningsValue : [],
1639
+ deficiencies,
1640
+ system_info: systemInfo,
1641
+ metadata: {
1642
+ title: values.title,
1643
+ tags: tagsInput,
1644
+ company: mirrorCompanies,
1645
+ company_slugs: lockedCompanies,
1646
+ },
506
1647
  };
507
1648
  fs.mkdirSync(threadsDir, { recursive: true });
508
1649
  fs.writeFileSync(path.join(root, threadPath), prettyJson(thread));
509
- // Replay the old PostToolUse mirror in process; the hook was fail-soft.
510
- if (fs.existsSync(path.join(root, ".claude/hooks/mirror-thread-to-company.sh"))) {
511
- mirrorThread(root, path.join(root, threadPath));
1650
+ let companyMirrorFailed = false;
1651
+ const mirrorHookPath = path.join(root, ".claude/hooks/mirror-thread-to-company.sh");
1652
+ const emitLockHint = () => {
1653
+ if (ownerCompany && !ownerInLockedSet(ownerCompany)) {
1654
+ stderrParts.push(`handoff-finalize: session has no company lock for ${ownerCompany}; run core/scripts/hq-session.sh add company ${ownerCompany}, then re-run /handoff to mirror\n`);
1655
+ }
1656
+ };
1657
+ if (statNoThrow(mirrorHookPath)?.isFile()) {
1658
+ // The hook runs for every handoff, as in the helper; its exit status
1659
+ // matters only when a mirror was asked for.
1660
+ const hookOk = runInstalledMirrorHook(root, mirrorHookPath, path.join(root, threadPath));
1661
+ if (!hookOk && mirrorCompanies.length > 0) {
1662
+ companyMirrorFailed = true;
1663
+ stderrParts.push("handoff-finalize: company mirror failed; canonical thread retained\n");
1664
+ const toolNote = installedScriptToolNote();
1665
+ if (toolNote)
1666
+ stderrParts.push(`handoff-finalize: ${toolNote}\n`);
1667
+ emitLockHint();
1668
+ }
1669
+ }
1670
+ else if (mirrorCompanies.length > 0) {
1671
+ companyMirrorFailed = true;
1672
+ stderrParts.push("handoff-finalize: company mirror hook missing; canonical thread retained\n");
1673
+ emitLockHint();
512
1674
  }
513
- const mirrored = companies.filter((company) => fs.existsSync(path.join(root, "companies", company, "workspace/sessions", `${threadId}.json`)));
1675
+ const mirrored = mirrorCompanies.filter((company) => fs.existsSync(path.join(root, "companies", company, "workspace/sessions", `${threadId}.json`)));
514
1676
  const mirrorStagePaths = mirrored.flatMap((company) => [
515
1677
  `companies/${company}/workspace/index.jsonl`,
516
1678
  `companies/${company}/workspace/.gitignore`,
@@ -526,32 +1688,44 @@ export function runHandoffFinalize(args, context) {
526
1688
  finalized_commit: null,
527
1689
  finalized_commit_note: "The exact handoff commit is emitted by handoff-finalize.sh as commit_after_finalize; a file cannot contain the hash of the commit that contains itself.",
528
1690
  },
529
- files_touched: touchedValue,
1691
+ files_touched: jqTruthy(touchedValue) ? touchedValue : [],
530
1692
  staged_paths: probe.hasGit ? safePaths : [],
531
- skipped_paths: skipped,
1693
+ skipped_paths: [...skipped],
532
1694
  verification: { notes: [], upstream_refs_compared: [] },
533
1695
  status_summary: status,
534
1696
  };
535
1697
  fs.writeFileSync(path.join(root, changesetPath), prettyJson(changeset));
536
- const pointerPath = path.join(root, "workspace/threads/handoff.json");
537
- writeAtomic(pointerPath, prettyJson({
1698
+ let pointerKeptNewer = false;
1699
+ const pointerBody = {
538
1700
  created_at: ts,
539
1701
  message: values.message,
540
1702
  last_thread: threadId,
541
1703
  thread_path: threadPath,
542
1704
  context_notes: values.summary,
543
- }), 0o600);
1705
+ companies: mirrorCompanies,
1706
+ session_id: handoffSessionId || null,
1707
+ };
1708
+ if (mirrorCompanies.length === 1)
1709
+ pointerBody.company = mirrorCompanies[0];
1710
+ const pointerJson = prettyJson(pointerBody);
1711
+ const writeMonotonicPointer = (destination, displayDest) => {
1712
+ if (fs.statSync(destination, { throwIfNoEntry: false })?.isFile()) {
1713
+ const existingTs = readPointerCreatedAt(destination);
1714
+ if (existingTs && existingTs > ts) {
1715
+ stderrParts.push(`handoff-finalize: kept newer handoff pointer at ${displayDest} (${existingTs} > ${ts}); this thread stays at ${threadPath}\n`);
1716
+ pointerKeptNewer = true;
1717
+ return;
1718
+ }
1719
+ }
1720
+ writeAtomic(destination, pointerJson, 0o600);
1721
+ };
1722
+ writeMonotonicPointer(path.join(root, "workspace/threads/handoff.json"), "workspace/threads/handoff.json");
544
1723
  if (probe.hasGit) {
545
1724
  const main = mainCheckoutRoot(probe.commonDir, root);
546
1725
  if (main !== root) {
547
1726
  writeAtomic(path.join(main, threadPath), fs.readFileSync(path.join(root, threadPath), "utf8"), 0o600);
548
- writeAtomic(path.join(main, "workspace/threads/handoff.json"), prettyJson({
549
- created_at: ts,
550
- message: values.message,
551
- last_thread: threadId,
552
- thread_path: threadPath,
553
- context_notes: values.summary,
554
- }), 0o600);
1727
+ const mainPointerDisplay = `${main}/workspace/threads/handoff.json`;
1728
+ writeMonotonicPointer(mainPointerDisplay, mainPointerDisplay);
555
1729
  }
556
1730
  }
557
1731
  renderIndex(root, "threads", ["--both"]);
@@ -573,32 +1747,65 @@ export function runHandoffFinalize(args, context) {
573
1747
  "workspace/orchestrator/INDEX.md",
574
1748
  "INDEX.md",
575
1749
  ];
576
- let staged = 0;
577
- const stageFailures = [];
1750
+ let stageOutcome = {
1751
+ staged: 0,
1752
+ addedPaths: [],
1753
+ stageFailures: [],
1754
+ firstStageError: "",
1755
+ stageFailureClass: "",
1756
+ nestedRepoPaths: [],
1757
+ nestedDirtyMessages: [],
1758
+ filterFailed: false,
1759
+ };
1760
+ const indexState = probe.hasGit ? createIndexRetryState(root) : {
1761
+ maxRetries: 0,
1762
+ waitBudgetMs: 60000,
1763
+ staleSeconds: 600,
1764
+ waitedMs: 0,
1765
+ waits: 0,
1766
+ staleChecked: false,
1767
+ staleRemoved: false,
1768
+ gitIndexPath: "",
1769
+ };
578
1770
  if (probe.hasGit) {
579
- const stageable = explicit.filter((pathname) => pathname);
580
- const results = stagePaths(root, stageable);
581
- stageable.forEach((pathname, index) => {
582
- const result = results[index];
583
- if (result.ok)
584
- staged += 1;
585
- else if (result.failed)
586
- stageFailures.push(pathname);
587
- });
1771
+ const gitlinks = readGitlinks(root);
1772
+ stageOutcome = stageExplicitPaths(root, explicit, gitlinks, indexState, stderrParts, skipped);
588
1773
  }
589
1774
  let hqCommitted = false;
590
1775
  let commitStatus = probe.hasGit ? "nothing-to-commit" : "no-git-checkout";
591
1776
  let commitError = "";
592
1777
  let committedPaths = [];
593
- if (probe.hasGit && staged > 0) {
594
- const pending = git(["diff", "--cached", "--name-only"], root).stdout.split(/\r?\n/).filter(Boolean);
595
- if (pending.length > 0) {
596
- const fingerprint = (context.buildFingerprint ?? ((hqRoot) => offlineFingerprint(hqRoot, process.env, "hq handoff", { readOnly: true })))(root);
597
- const committed = git(["commit", "-m", `checkpoint: handoff ${threadId}`, ...fingerprintTrailerArgs(fingerprint)], root);
1778
+ if (probe.hasGit && stageOutcome.staged > 0 && !stageOutcome.filterFailed && stageOutcome.addedPaths.length > 0) {
1779
+ const ownStagedSet = new Set();
1780
+ const ownChunks = chunkPathspecs(stageOutcome.addedPaths);
1781
+ for (const chunk of ownChunks) {
1782
+ const diffRes = gitLiteral(["-c", "core.quotePath=false", "diff", "--cached", "--name-only", "--no-renames", "--", ...chunk], root);
1783
+ for (const item of diffRes.stdout.split(/\r?\n/)) {
1784
+ if (item)
1785
+ ownStagedSet.add(item);
1786
+ }
1787
+ }
1788
+ const ownStaged = [...ownStagedSet];
1789
+ // One git call (the helper's xargs, up to 5,000 paths) prints the staged
1790
+ // files in index order. Chunked calls are merged back into that order.
1791
+ if (ownChunks.length > 1)
1792
+ ownStaged.sort((a, b) => Buffer.compare(Buffer.from(a), Buffer.from(b)));
1793
+ if (ownStaged.length > 0) {
1794
+ const totalStagedCount = gitLiteral(["diff", "--cached", "--name-only", "--no-renames"], root)
1795
+ .stdout.split(/\r?\n/).filter(Boolean).length;
1796
+ const globalHooksPath = git(["config", "--global", "--get", "core.hooksPath"], root).stdout.trim();
1797
+ const trailerArgs = globalHooksPath || !fingerprintTrailerWanted(root)
1798
+ ? []
1799
+ : fingerprintTrailerArgs((context.buildFingerprint ?? ((hqRoot) => offlineFingerprint(hqRoot, process.env, "hq handoff", { readOnly: true })))(root));
1800
+ const commitArgs = totalStagedCount === ownStaged.length
1801
+ ? ["commit", "-m", `checkpoint: handoff ${threadId}`, ...trailerArgs]
1802
+ : ["commit", "--only", "--pathspec-from-file=-", "--pathspec-file-nul", "-m", `checkpoint: handoff ${threadId}`, ...trailerArgs];
1803
+ const commitStdin = totalStagedCount === ownStaged.length ? undefined : `${ownStaged.join("\0")}\0`;
1804
+ const committed = runGitWithIndexRetry(root, indexState, stderrParts, () => gitLiteral(commitArgs, root, commitStdin));
598
1805
  if (committed.code === 0) {
599
1806
  hqCommitted = true;
600
1807
  commitStatus = "committed";
601
- committedPaths = pending;
1808
+ committedPaths = ownStaged;
602
1809
  }
603
1810
  else {
604
1811
  commitStatus = "failed";
@@ -606,11 +1813,26 @@ export function runHandoffFinalize(args, context) {
606
1813
  }
607
1814
  }
608
1815
  }
609
- if (stageFailures.length > 0 && commitStatus !== "failed") {
1816
+ if (stageOutcome.stageFailures.length > 0 && commitStatus !== "failed") {
610
1817
  commitStatus = "stage-failed";
611
- if (!commitError)
612
- commitError = `git add failed for ${stageFailures.length} path(s) — see stage_failures`;
1818
+ if (!commitError) {
1819
+ commitError = `git add failed for ${stageOutcome.stageFailures.length} path(s) — see stage_failures`;
1820
+ if (stageOutcome.stageFailureClass === "permission") {
1821
+ commitError += "; permission denied writing the git repository (a sandboxed run cannot write .git; re-run /handoff outside the sandbox)";
1822
+ }
1823
+ else if (stageOutcome.stageFailureClass === "index-lock") {
1824
+ commitError += "; another git process holds .git/index.lock (wait for it and re-run /handoff)";
1825
+ }
1826
+ if (stageOutcome.firstStageError)
1827
+ commitError += `; first git error: ${stageOutcome.firstStageError}`;
1828
+ if (stageOutcome.nestedDirtyMessages.length > 0) {
1829
+ commitError += `: ${stageOutcome.nestedDirtyMessages.join("; ")}`;
1830
+ }
1831
+ }
613
1832
  }
1833
+ const publishOutcome = hqCommitted
1834
+ ? dispatchHandoffSyncPublish(root, tmpRoot)
1835
+ : { pid: "", status: "skipped" };
614
1836
  let qmdPid = "";
615
1837
  // This is the same TypeScript launcher reached by qmd-reindex-bg.sh.
616
1838
  try {
@@ -621,18 +1843,24 @@ export function runHandoffFinalize(args, context) {
621
1843
  catch { /* the shell helper is fail-soft */ }
622
1844
  const nextCommand = values.nextCommand === "__auto__" ? `/resumework ${threadId}` : values.nextCommand;
623
1845
  const clipboardCopied = copyClipboardText(nextCommand, root);
1846
+ const stageFailures = stageOutcome.stageFailures;
624
1847
  const payload = {
625
1848
  thread_id: threadId,
626
1849
  thread_path: threadPath,
627
1850
  changeset_path: changesetPath,
628
1851
  handoff_path: "workspace/threads/handoff.json",
1852
+ pointer_kept_newer: pointerKeptNewer,
629
1853
  hq_committed: hqCommitted,
630
1854
  hq_commit_status: commitStatus,
631
1855
  hq_commit_error: commitError,
632
1856
  commit_after_finalize: probe.hasGit ? (git(["rev-parse", "--short", "HEAD"], root).stdout.trim() || "unknown") : "unknown",
633
1857
  committed_paths: committedPaths,
634
1858
  stage_failures: stageFailures,
1859
+ stage_failure_class: stageOutcome.stageFailureClass,
1860
+ index_lock_waits: indexState.waits,
1861
+ stale_index_lock_removed: indexState.staleRemoved,
635
1862
  skipped_paths: skipped,
1863
+ nested_repo_paths: stageOutcome.nestedRepoPaths,
636
1864
  baseline_noise_count: isRecord(status) && isRecord(status.counts) ? status.counts.baseline_noise ?? 0 : 0,
637
1865
  indexes_regen: true,
638
1866
  qmd_pid: qmdPid,
@@ -640,9 +1868,10 @@ export function runHandoffFinalize(args, context) {
640
1868
  next_command: nextCommand,
641
1869
  clipboard_copied: clipboardCopied,
642
1870
  mirror_companies: mirrored,
1871
+ handoff_publish_pid: publishOutcome.pid,
1872
+ handoff_publish_status: publishOutcome.status,
643
1873
  };
644
1874
  const stdout = prettyJson(payload);
645
- const stderrParts = [];
646
1875
  if (gitBgErrors)
647
1876
  stderrParts.push(`handoff-finalize: WARNING background git step reported errors: ${gitBgErrors}\n`);
648
1877
  if (stageFailures.length > 0) {
@@ -656,12 +1885,11 @@ export function runHandoffFinalize(args, context) {
656
1885
  stderrParts.push("handoff-finalize: resolve the git error and re-run /handoff before ending the session.\n");
657
1886
  return { code: 4, stdout, stderr: stderrParts.join("") };
658
1887
  }
1888
+ if (companyMirrorFailed)
1889
+ return { code: 5, stdout, stderr: stderrParts.join("") };
659
1890
  return { code: 0, stdout, stderr: stderrParts.join("") };
660
1891
  }
661
1892
  catch (error) {
662
- if (error instanceof HandoffJsonOptionError) {
663
- return { code: 2, stdout: "", stderr: `handoff-finalize: invalid JSON for ${error.flag}: ${error.message}\n` };
664
- }
665
1893
  const message = error instanceof Error ? error.message : String(error);
666
1894
  return { code: 1, stdout: "", stderr: `${message}\n` };
667
1895
  }
@@ -2072,9 +3300,10 @@ function emitResult(result) {
2072
3300
  process.exit(result.code);
2073
3301
  }
2074
3302
  /** Fast-entry adapter; the shared family flag is resolved before this module loads. */
2075
- export async function runHandoffFast(args, _stdin, _cwd, hqRoot, commandName) {
3303
+ export async function runHandoffFast(args, _stdin, _cwd, hqRoot, commandName, hqRootArg) {
3304
+ const logicalRoot = hqRootArg || process.env.HQ_ROOT || hqRoot;
2076
3305
  const liveRoot = hqRoot ?? resolveLiveRoot();
2077
- const context = { root: liveRoot, cwd: liveRoot };
3306
+ const context = { root: liveRoot, cwd: liveRoot, logicalRoot: logicalRoot || liveRoot };
2078
3307
  const result = await withRootEnvironment(liveRoot, () => {
2079
3308
  if (commandName === "finalize")
2080
3309
  return runHandoffFinalize([...args], context);
@@ -2110,6 +3339,7 @@ export function registerCoreHandoffCommand(core) {
2110
3339
  .argument("[args...]", "arguments accepted for shell ABI compatibility")
2111
3340
  .action(async (args = [], _options, cmd) => {
2112
3341
  const scope = core.opts();
3342
+ const logicalRoot = scope.hqRoot || process.env.HQ_ROOT;
2113
3343
  const root = resolveLiveRoot({ hqRoot: scope.hqRoot });
2114
3344
  const operands = cmd.args.length > 0 ? cmd.args : args;
2115
3345
  const { coreNativeHandoffEnabled } = await import("./core-native-handoff-flag.js");
@@ -2120,7 +3350,7 @@ export function registerCoreHandoffCommand(core) {
2120
3350
  return;
2121
3351
  }
2122
3352
  const result = withRootEnvironment(root, () => {
2123
- const context = { root, cwd: root };
3353
+ const context = { root, cwd: root, logicalRoot: logicalRoot || root };
2124
3354
  if (name === "finalize")
2125
3355
  return runHandoffFinalize(operands, context);
2126
3356
  if (name === "post")