@indigoai-us/hq-cli 5.345.262 → 5.345.264

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 (64) hide show
  1. package/CHANGELOG.md +69 -0
  2. package/contracts/host-canary-release.json +7 -7
  3. package/dist/command-catalog.generated.d.ts +37 -0
  4. package/dist/command-catalog.generated.js +46 -0
  5. package/dist/command-registration-plan.d.ts +6 -0
  6. package/dist/command-registration-plan.js +1 -0
  7. package/dist/commands/bot.d.ts +2 -0
  8. package/dist/commands/bot.js +4 -3
  9. package/dist/commands/core-handoff.js +273 -115
  10. package/dist/commands/sync-held.d.ts +11 -0
  11. package/dist/commands/sync-held.js +65 -1
  12. package/dist/commands/sync-telemetry-report.d.ts +5 -0
  13. package/dist/commands/sync-telemetry-report.js +239 -0
  14. package/dist/commands/sync-telemetry.d.ts +47 -0
  15. package/dist/commands/sync-telemetry.js +309 -0
  16. package/dist/index.js +107 -43
  17. package/dist/lib/bot/runnable.d.ts +17 -7
  18. package/dist/lib/bot/runnable.js +17 -10
  19. package/dist/lib/capacity/available.js +6 -2
  20. package/dist/lib/capacity/collectors/claude-oauth.d.ts +10 -256
  21. package/dist/lib/capacity/collectors/claude-oauth.js +19 -1078
  22. package/dist/lib/capacity/ledger.d.ts +12 -1
  23. package/dist/lib/capacity/ledger.js +15 -5
  24. package/dist/lib/capacity/route.d.ts +2 -0
  25. package/dist/lib/capacity/route.js +21 -4
  26. package/dist/lib/capacity/scheduler.js +2 -3
  27. package/dist/lib/capacity/sign-in.js +4 -4
  28. package/dist/lib/daemon/ops/skill-command.d.ts +2 -0
  29. package/dist/lib/daemon/ops/skill-command.js +7 -1
  30. package/dist/lib/doctor/checks/antigravity-wiring.d.ts +2 -1
  31. package/dist/lib/doctor/checks/antigravity-wiring.js +59 -3
  32. package/dist/lib/doctor/checks/hook-engine.d.ts +2 -0
  33. package/dist/lib/doctor/checks/hook-engine.js +100 -1
  34. package/dist/lib/doctor/checks/host-core.d.ts +1 -1
  35. package/dist/lib/doctor/checks/host-core.js +11 -4
  36. package/dist/lib/hook-engine/coverage.d.ts +19 -10
  37. package/dist/lib/hook-engine/coverage.js +103 -24
  38. package/dist/lib/hook-engine/native-precompact-compatibility.json +7 -1
  39. package/dist/lib/hook-engine/native-stop-compatibility.json +8 -4
  40. package/dist/lib/hook-engine/reconcile.js +49 -1
  41. package/dist/lib/install/antigravity-targets.d.ts +22 -0
  42. package/dist/lib/install/antigravity-targets.js +82 -0
  43. package/dist/main.js +8 -3
  44. package/dist/sentry-init.d.ts +7 -1
  45. package/dist/sentry-init.js +6 -2
  46. package/dist/sentry.d.ts +7 -0
  47. package/dist/sentry.js +16 -1
  48. package/dist/started-version.d.ts +13 -0
  49. package/dist/started-version.js +34 -0
  50. package/dist/startup-registration.d.ts +9 -9
  51. package/dist/startup-registration.js +42 -18
  52. package/dist/utils/client-health.d.ts +1 -0
  53. package/dist/utils/client-health.js +54 -11
  54. package/dist/utils/core-next-kill.d.ts +9 -0
  55. package/dist/utils/core-next-kill.js +22 -0
  56. package/dist/utils/delegate-lock.js +19 -1
  57. package/dist/utils/host-registration.d.ts +4 -2
  58. package/dist/utils/host-registration.js +55 -7
  59. package/dist/utils/install-tree-recovery-markers.d.ts +45 -0
  60. package/dist/utils/install-tree-recovery-markers.js +70 -0
  61. package/dist/utils/install-tree-torn.d.ts +102 -5
  62. package/dist/utils/install-tree-torn.js +199 -2
  63. package/dist/utils/sentry-fingerprint.js +3 -0
  64. package/package.json +7 -7
@@ -39,34 +39,16 @@ const DESCRIPTIONS = {
39
39
  post: "Run best-effort post-handoff maintenance",
40
40
  openSteps: "List and update open handoff steps",
41
41
  };
42
- /** handoff-finalize.sh accepts digit-leading company slugs. */
42
+ /** handoff-finalize.sh, handoff-post.sh, and mirror-thread-to-company.sh accept digit-leading company slugs. */
43
43
  const FINALIZE_COMPANY_SLUG_RE = /^[a-z0-9][a-z0-9_-]*$/;
44
- /** The bundled handoff-post.sh still requires a letter first; `handoff post` follows it. */
45
- const POST_COMPANY_SLUG_RE = /^[a-z][a-z0-9_-]*$/;
46
- export function boundSessionCompany(root) {
47
- const sessionId = resolveSessionId(root);
48
- if (!sessionId)
49
- return "";
50
- const metadata = path.join(root, "workspace/sessions", sessionId, "meta.yaml");
51
- let contents;
52
- try {
53
- contents = fs.readFileSync(metadata, "utf8");
54
- }
55
- catch {
56
- return "";
57
- }
58
- const line = contents.split(/\r?\n/).find((entry) => /^\s*company_slug:/.test(entry));
59
- if (!line)
60
- return "";
61
- const company = (line.replace(/^\s*company_slug:\s*/, "").replace(/^"|"$/g, ""));
62
- return POST_COMPANY_SLUG_RE.test(company) ? company : "";
63
- }
44
+ const POST_COMPANY_SLUG_RE = FINALIZE_COMPANY_SLUG_RE;
64
45
  /**
65
- * meta.yaml `company_slug` as handoff-finalize.sh and the mirror hook read it:
66
- * awk's `$1 == "company_slug:"` (the key is the whole first field, so
67
- * `company_slug:acme` with no space is not a binding), the first such line,
68
- * with the key, the whitespace after it and one quote at each end removed.
69
- * No slug check here; the helper applies its pattern, the hook does not.
46
+ * meta.yaml `company_slug` as handoff-finalize.sh, handoff-post.sh, and the
47
+ * mirror hook read it: awk's `$1 == "company_slug:"` (the key is the whole
48
+ * first field, so `company_slug:acme` with no space is not a binding), the
49
+ * first such line, preserving any trailing `\r` (CRLF), with the key, the
50
+ * whitespace after it and one quote at each end removed.
51
+ * No slug check here; the helpers apply their pattern, the hook does not.
70
52
  */
71
53
  function metaCompanySlugRaw(root) {
72
54
  const sessionId = resolveSessionId(root);
@@ -86,11 +68,14 @@ function metaCompanySlugRaw(root) {
86
68
  }
87
69
  return "";
88
70
  }
89
- /** bound_session_company in handoff-finalize.sh. */
71
+ /** bound_session_company in handoff-finalize.sh and handoff-post.sh. */
90
72
  function finalizeBoundSessionCompany(root) {
91
73
  const company = metaCompanySlugRaw(root);
92
74
  return FINALIZE_COMPANY_SLUG_RE.test(company) ? company : "";
93
75
  }
76
+ export function boundSessionCompany(root) {
77
+ return finalizeBoundSessionCompany(root);
78
+ }
94
79
  const SESSION_SCOPE_LIB = "core/scripts/lib/session-scope-capability.sh";
95
80
  /**
96
81
  * bash for running the HQ root's own scripts (the mirror hook, the
@@ -630,53 +615,72 @@ function readDeficiencies(root, fileArg, given, stderrParts) {
630
615
  }));
631
616
  return { deficiencies: filtered };
632
617
  }
633
- function mirrorThread(root, threadPath) {
618
+ function mirrorThread(root, threadPath, expectedCompany, logicalRoot) {
634
619
  try {
635
- const thread = JSON.parse(fs.readFileSync(threadPath, "utf8"));
636
- if (!isRecord(thread) || !isRecord(thread.metadata))
620
+ if (!expectedCompany || !POST_COMPANY_SLUG_RE.test(expectedCompany))
621
+ return;
622
+ const ownership = inspectThreadPostOwnership(root, threadPath, logicalRoot);
623
+ if (ownership.refused || ownership.validCompanies.length !== 1)
637
624
  return;
638
- const rawCompanies = thread.metadata.company;
639
- if (!jqTruthy(rawCompanies))
625
+ const company = ownership.validCompanies[0];
626
+ if (company !== expectedCompany)
627
+ return;
628
+ const thread = JSON.parse(stripByteOrderMark(fs.readFileSync(threadPath, "utf8")));
629
+ if (!isRecord(thread) || !isRecord(thread.metadata))
640
630
  return;
641
- const companies = Array.isArray(rawCompanies) ? rawCompanies : [rawCompanies];
642
631
  if (typeof thread.thread_id !== "string" || !thread.thread_id)
643
632
  return;
644
633
  const updatedAt = thread.updated_at ?? thread.created_at ?? "";
645
634
  const kind = thread.type ?? "unknown";
646
635
  const rawTitle = thread.metadata.title ?? thread.conversation_summary ?? "";
647
636
  const title = Buffer.from(typeof rawTitle === "string" ? rawTitle : compactJson(rawTitle)).subarray(0, 200).toString("utf8");
648
- const rowFor = (company) => compactJson({ thread_id: thread.thread_id, ts: updatedAt, kind, company, title }).trimEnd();
649
- for (const company of companies) {
650
- if (company === "")
651
- continue;
652
- const companyRoot = path.join(root, "companies", String(company));
653
- if (!fs.existsSync(companyRoot))
654
- continue;
655
- const workspace = path.join(companyRoot, "workspace");
656
- const sessions = path.join(workspace, "sessions");
657
- const indexFile = path.join(workspace, "index.jsonl");
658
- const ignoreFile = path.join(workspace, ".gitignore");
659
- fs.mkdirSync(sessions, { recursive: true });
660
- if (!fs.existsSync(ignoreFile)) {
661
- fs.writeFileSync(ignoreFile, "# HQ workspace mirror — sessions are gitignored, index.jsonl is committed\nsessions/\n");
662
- }
663
- const target = path.join(sessions, `${thread.thread_id}.json`);
664
- try {
665
- fs.rmSync(target, { force: true });
666
- fs.linkSync(threadPath, target);
667
- }
668
- catch {
637
+ const companyRoot = path.join(root, "companies", company);
638
+ if (!isDirectory(companyRoot))
639
+ return;
640
+ const workspace = path.join(companyRoot, "workspace");
641
+ const sessions = path.join(workspace, "sessions");
642
+ const indexFile = path.join(workspace, "index.jsonl");
643
+ const ignoreFile = path.join(workspace, ".gitignore");
644
+ fs.mkdirSync(sessions, { recursive: true });
645
+ if (!fs.existsSync(ignoreFile)) {
646
+ fs.writeFileSync(ignoreFile, "# HQ workspace mirror — sessions are gitignored, index.jsonl is committed\nsessions/\n");
647
+ }
648
+ const mirroredThread = {
649
+ ...thread,
650
+ metadata: {
651
+ ...thread.metadata,
652
+ company_slugs: [company],
653
+ },
654
+ };
655
+ const target = path.join(sessions, `${thread.thread_id}.json`);
656
+ const temporaryMirror = path.join(sessions, `.mirror-${process.pid}-${Math.random().toString(36).slice(2)}`);
657
+ let temporaryFd;
658
+ try {
659
+ temporaryFd = fs.openSync(temporaryMirror, "wx", 0o600);
660
+ fs.writeFileSync(temporaryFd, `${JSON.stringify(mirroredThread, null, 2)}\n`);
661
+ fs.closeSync(temporaryFd);
662
+ temporaryFd = undefined;
663
+ fs.chmodSync(temporaryMirror, 0o600);
664
+ fs.renameSync(temporaryMirror, target);
665
+ }
666
+ catch {
667
+ if (temporaryFd !== undefined) {
669
668
  try {
670
- fs.copyFileSync(threadPath, target);
669
+ fs.closeSync(temporaryFd);
671
670
  }
672
- catch { /* legacy hook is fail-soft at the caller */ }
671
+ catch { /* temporary cleanup remains best effort */ }
673
672
  }
674
- const row = rowFor(company);
675
- const dedupKey = `"thread_id":"${thread.thread_id}","ts":"${updatedAt}","kind":"${kind}"`;
676
- if (fs.existsSync(indexFile) && fs.readFileSync(indexFile, "utf8").includes(dedupKey))
677
- continue;
678
- fs.appendFileSync(indexFile, `${row}\n`);
673
+ try {
674
+ fs.rmSync(temporaryMirror, { force: true });
675
+ }
676
+ catch { /* temporary cleanup remains best effort */ }
677
+ return;
679
678
  }
679
+ const row = compactJson({ thread_id: thread.thread_id, ts: updatedAt, kind, company, title }).trimEnd();
680
+ const dedupKey = `"thread_id":"${thread.thread_id}","ts":"${updatedAt}","kind":"${kind}"`;
681
+ if (fs.existsSync(indexFile) && fs.readFileSync(indexFile, "utf8").includes(dedupKey))
682
+ return;
683
+ fs.appendFileSync(indexFile, `${row}\n`);
680
684
  }
681
685
  catch {
682
686
  // The legacy finalizer ignores every mirror-hook error.
@@ -1992,20 +1996,126 @@ function runIndexBackground(root, logPath) {
1992
1996
  : "";
1993
1997
  return { output, stderr };
1994
1998
  }
1995
- function readThreadCompanyNames(file) {
1999
+ /**
2000
+ * Validate single-owner company metadata and `files_touched` company paths for
2001
+ * `handoff post`. Mirrors the ownership rules from hq-core's `handoff-post.sh`
2002
+ * and `mirror-thread-to-company.sh`:
2003
+ * - `metadata.company` may be empty (`null`, `[]`, `""`), a single valid
2004
+ * company slug string, or a 1-element array containing one valid slug.
2005
+ * - Arrays with >1 entry (even duplicates or mixed valid/invalid entries) are
2006
+ * ambiguous and refused so no tenant mirrors are created or pushed.
2007
+ * - `files_touched` spanning >1 company, or naming a company that disagrees
2008
+ * with `metadata.company`, is refused as well.
2009
+ */
2010
+ function inspectThreadPostOwnership(root, file, logicalRoot) {
2011
+ let thread;
1996
2012
  try {
1997
- const thread = JSON.parse(fs.readFileSync(file, "utf8"));
1998
- if (!isRecord(thread) || !isRecord(thread.metadata))
1999
- return [];
2000
- const value = thread.metadata.company;
2001
- if (!jqTruthy(value))
2002
- return [];
2003
- const values = Array.isArray(value) ? value : [value];
2004
- return [...new Set(values.filter((item) => typeof item === "string" && /^[a-z][a-z0-9_-]*$/.test(item)))].sort();
2013
+ thread = JSON.parse(stripByteOrderMark(fs.readFileSync(file, "utf8")));
2005
2014
  }
2006
2015
  catch {
2007
- return [];
2016
+ return {
2017
+ validCompanies: [],
2018
+ pathCompanies: [],
2019
+ fileCount: 0,
2020
+ companyishCount: 0,
2021
+ hasInvalidJson: true,
2022
+ hasAmbiguousMetadata: false,
2023
+ hasInvalidMetadata: false,
2024
+ refused: true,
2025
+ };
2026
+ }
2027
+ if (!isRecord(thread)) {
2028
+ return {
2029
+ validCompanies: [],
2030
+ pathCompanies: [],
2031
+ fileCount: 0,
2032
+ companyishCount: 0,
2033
+ hasInvalidJson: false,
2034
+ hasAmbiguousMetadata: false,
2035
+ hasInvalidMetadata: true,
2036
+ refused: true,
2037
+ };
2038
+ }
2039
+ const rawCompany = isRecord(thread.metadata) ? thread.metadata.company : undefined;
2040
+ let validCompanies = [];
2041
+ let hasAmbiguousMetadata = false;
2042
+ let hasInvalidMetadata = false;
2043
+ if (rawCompany === undefined
2044
+ || rawCompany === null
2045
+ || rawCompany === ""
2046
+ || (Array.isArray(rawCompany) && rawCompany.length === 0)) {
2047
+ // Empty metadata.company is valid (may still bind to session company).
2048
+ }
2049
+ else if (typeof rawCompany === "string") {
2050
+ if (POST_COMPANY_SLUG_RE.test(rawCompany))
2051
+ validCompanies = [rawCompany];
2052
+ else
2053
+ hasInvalidMetadata = true;
2054
+ }
2055
+ else if (Array.isArray(rawCompany)) {
2056
+ validCompanies = [
2057
+ ...new Set(rawCompany.filter((item) => typeof item === "string" && POST_COMPANY_SLUG_RE.test(item))),
2058
+ ].sort();
2059
+ if (rawCompany.length > 1) {
2060
+ hasAmbiguousMetadata = true;
2061
+ if (rawCompany.some((item) => typeof item !== "string" || !POST_COMPANY_SLUG_RE.test(item))) {
2062
+ hasInvalidMetadata = true;
2063
+ }
2064
+ }
2065
+ else if (validCompanies.length === 0) {
2066
+ hasInvalidMetadata = true;
2067
+ }
2068
+ }
2069
+ else {
2070
+ hasInvalidMetadata = true;
2071
+ }
2072
+ const rootsToStrip = [
2073
+ root.replaceAll("\\", "/").replace(/\/+$/, ""),
2074
+ ...(logicalRoot ? [logicalRoot.replaceAll("\\", "/").replace(/\/+$/, "")] : []),
2075
+ ];
2076
+ const rawFiles = Array.isArray(thread.files_touched) ? thread.files_touched : [];
2077
+ const pathCompanySet = new Set();
2078
+ let fileCount = 0;
2079
+ let companyishCount = 0;
2080
+ for (const entry of rawFiles) {
2081
+ const rawPath = typeof entry === "string"
2082
+ ? entry
2083
+ : isRecord(entry) && typeof entry.path === "string"
2084
+ ? entry.path
2085
+ : "";
2086
+ if (!rawPath)
2087
+ continue;
2088
+ fileCount += 1;
2089
+ let normalized = rawPath.replaceAll("\\", "/");
2090
+ for (const prefix of rootsToStrip) {
2091
+ if (prefix && normalized.startsWith(`${prefix}/`)) {
2092
+ normalized = normalized.slice(prefix.length + 1);
2093
+ break;
2094
+ }
2095
+ }
2096
+ normalized = normalized.replace(/^\.\//, "");
2097
+ if (normalized.startsWith("companies/") || normalized.startsWith("repos/")) {
2098
+ companyishCount += 1;
2099
+ }
2100
+ const match = /^companies\/([a-z0-9][a-z0-9_-]*)\//.exec(normalized);
2101
+ if (match?.[1])
2102
+ pathCompanySet.add(match[1]);
2008
2103
  }
2104
+ const pathCompanies = [...pathCompanySet].sort();
2105
+ const refused = hasAmbiguousMetadata
2106
+ || hasInvalidMetadata
2107
+ || pathCompanies.length > 1
2108
+ || (validCompanies.length === 1 && pathCompanies.length === 1 && pathCompanies[0] !== validCompanies[0]);
2109
+ return {
2110
+ validCompanies,
2111
+ pathCompanies,
2112
+ fileCount,
2113
+ companyishCount,
2114
+ hasInvalidJson: false,
2115
+ hasAmbiguousMetadata,
2116
+ hasInvalidMetadata,
2117
+ refused,
2118
+ };
2009
2119
  }
2010
2120
  function documentReleaseCounts(file) {
2011
2121
  try {
@@ -2319,54 +2429,98 @@ export function runHandoffPostWorker(args, context) {
2319
2429
  else
2320
2430
  log("document-release: skipped (no thread path)");
2321
2431
  if (threadFile && fs.existsSync(threadFile) && commandAvailable("hq")) {
2322
- let syncCompanies = readThreadCompanyNames(threadFile);
2432
+ const ownership = inspectThreadPostOwnership(root, threadFile, context.logicalRoot);
2433
+ let syncCompanies = [...ownership.validCompanies];
2434
+ let ownershipRefused = ownership.refused;
2323
2435
  const sessionCompany = boundSessionCompany(root);
2324
- if (sessionCompany) {
2325
- const updatedCompanies = [...new Set([...syncCompanies, sessionCompany])].sort();
2326
- const companyListChanged = JSON.stringify(syncCompanies) !== JSON.stringify(updatedCompanies);
2327
- syncCompanies = updatedCompanies;
2328
- if (companyListChanged) {
2436
+ const sessionId = resolveSessionId(root);
2437
+ const sessionScope = sessionId ? readSessionLockedCompanies(root, sessionId) : undefined;
2438
+ if (ownership.hasInvalidJson || ownership.hasAmbiguousMetadata || ownership.hasInvalidMetadata) {
2439
+ // Unlike bash handoff-post.sh (which exits 2 immediately), the worker
2440
+ // records the refusal, skips mirroring/pushing, and continues to return 0:
2441
+ // hq-core-staging's handoff-thread-isolation.test.sh expects the
2442
+ // missing-mirror skip log line on 11-company metadata, existing POSIX
2443
+ // worker tests assert code 0 on invalid slugs, and the detached launcher
2444
+ // returns 0 in both implementations.
2445
+ ownershipRefused = true;
2446
+ log("workspace-sync: refused invalid or ambiguous ownership");
2447
+ if (!ownership.hasAmbiguousMetadata)
2448
+ syncCompanies = [];
2449
+ }
2450
+ else if (ownership.pathCompanies.length > 1) {
2451
+ ownershipRefused = true;
2452
+ syncCompanies = [];
2453
+ log("workspace-sync: skipped (handoff spans multiple companies)");
2454
+ }
2455
+ else if (!sessionCompany || !isDirectory(path.join(root, "companies", sessionCompany))) {
2456
+ ownershipRefused = true;
2457
+ syncCompanies = [];
2458
+ log("workspace-sync: skipped (no bound company for this session)");
2459
+ }
2460
+ else if (syncCompanies.length === 0 && ownership.fileCount > 0 && ownership.companyishCount === 0) {
2461
+ ownershipRefused = true;
2462
+ syncCompanies = [];
2463
+ log("workspace-sync: skipped (handoff touched no company or repo paths; personal or HQ-only work)");
2464
+ }
2465
+ else if ((syncCompanies.length === 1 && syncCompanies[0] !== sessionCompany)
2466
+ || (ownership.pathCompanies.length === 1 && ownership.pathCompanies[0] !== sessionCompany)) {
2467
+ ownershipRefused = true;
2468
+ syncCompanies = [];
2469
+ log("workspace-sync: skipped (handoff paths do not match the bound company)");
2470
+ }
2471
+ else if (sessionScope?.capFile && sessionScope.companies.length === 0) {
2472
+ ownershipRefused = true;
2473
+ syncCompanies = [];
2474
+ log("workspace-sync: mirror hook failed for handoff thread");
2475
+ }
2476
+ else if (sessionScope?.capFile && !sessionScope.companies.includes(sessionCompany)) {
2477
+ ownershipRefused = true;
2478
+ syncCompanies = [];
2479
+ log("workspace-sync: skipped (handoff paths do not match the bound company)");
2480
+ }
2481
+ else {
2482
+ syncCompanies = [sessionCompany];
2483
+ try {
2484
+ const thread = JSON.parse(stripByteOrderMark(fs.readFileSync(threadFile, "utf8")));
2485
+ if (!isRecord(thread))
2486
+ throw new Error("thread is not an object");
2487
+ let metadata;
2488
+ if (thread.metadata === null || thread.metadata === undefined)
2489
+ metadata = {};
2490
+ else if (isRecord(thread.metadata))
2491
+ metadata = thread.metadata;
2492
+ else
2493
+ throw new Error("thread metadata is not an object");
2494
+ metadata.company = syncCompanies;
2495
+ metadata.company_slugs = syncCompanies;
2496
+ thread.metadata = metadata;
2497
+ const temporaryThread = path.join(path.dirname(threadFile), `.handoff-post-${process.pid}-${Math.random().toString(36).slice(2)}`);
2498
+ let temporaryFd;
2329
2499
  try {
2330
- const thread = JSON.parse(fs.readFileSync(threadFile, "utf8"));
2331
- if (!isRecord(thread))
2332
- throw new Error("thread is not an object");
2333
- let metadata;
2334
- if (thread.metadata === null || thread.metadata === undefined)
2335
- metadata = {};
2336
- else if (isRecord(thread.metadata))
2337
- metadata = thread.metadata;
2338
- else
2339
- throw new Error("thread metadata is not an object");
2340
- metadata.company = syncCompanies;
2341
- thread.metadata = metadata;
2342
- const temporaryThread = path.join(path.dirname(threadFile), `.handoff-post-${process.pid}-${Math.random().toString(36).slice(2)}`);
2343
- let temporaryFd;
2344
- try {
2345
- temporaryFd = fs.openSync(temporaryThread, "wx", 0o600);
2346
- fs.writeFileSync(temporaryFd, `${compactJson(thread).trimEnd()}\n`);
2347
- fs.closeSync(temporaryFd);
2348
- temporaryFd = undefined;
2349
- fs.chmodSync(temporaryThread, 0o600);
2350
- fs.renameSync(temporaryThread, threadFile);
2351
- }
2352
- catch (error) {
2353
- if (temporaryFd !== undefined) {
2354
- try {
2355
- fs.closeSync(temporaryFd);
2356
- }
2357
- catch { /* temporary output cleanup remains best effort */ }
2358
- }
2500
+ temporaryFd = fs.openSync(temporaryThread, "wx", 0o600);
2501
+ fs.writeFileSync(temporaryFd, `${compactJson(thread).trimEnd()}\n`);
2502
+ fs.closeSync(temporaryFd);
2503
+ temporaryFd = undefined;
2504
+ fs.chmodSync(temporaryThread, 0o600);
2505
+ fs.renameSync(temporaryThread, threadFile);
2506
+ }
2507
+ catch (error) {
2508
+ if (temporaryFd !== undefined) {
2359
2509
  try {
2360
- fs.rmSync(temporaryThread, { force: true });
2510
+ fs.closeSync(temporaryFd);
2361
2511
  }
2362
- catch { /* jq/mv cleanup is fail-soft */ }
2363
- throw error;
2512
+ catch { /* temporary output cleanup remains best effort */ }
2364
2513
  }
2514
+ try {
2515
+ fs.rmSync(temporaryThread, { force: true });
2516
+ }
2517
+ catch { /* jq/mv cleanup is fail-soft */ }
2518
+ throw error;
2365
2519
  }
2366
- catch {
2367
- log("workspace-sync: skipped (could not add bound company to handoff thread)");
2368
- syncCompanies = [];
2369
- }
2520
+ }
2521
+ catch {
2522
+ log("workspace-sync: skipped (could not add bound company to handoff thread)");
2523
+ syncCompanies = [];
2370
2524
  }
2371
2525
  }
2372
2526
  let threadId = "";
@@ -2379,10 +2533,10 @@ export function runHandoffPostWorker(args, context) {
2379
2533
  && /^T-[A-Za-z0-9._-]+$/.test(threadId);
2380
2534
  }
2381
2535
  catch { /* shell helper treats an invalid thread as non-mirrorable */ }
2382
- if (threadMirrorable && syncCompanies.length > 0) {
2536
+ if (!ownershipRefused && threadMirrorable && syncCompanies.length === 1 && sessionCompany && syncCompanies[0] === sessionCompany) {
2383
2537
  const mirrorHook = path.join(root, ".claude/hooks/mirror-thread-to-company.sh");
2384
2538
  if (fs.existsSync(mirrorHook))
2385
- mirrorThread(root, threadFile);
2539
+ mirrorThread(root, threadFile, sessionCompany, context.logicalRoot);
2386
2540
  else
2387
2541
  log("workspace-sync: mirror hook unavailable for handoff thread");
2388
2542
  }
@@ -2399,6 +2553,10 @@ export function runHandoffPostWorker(args, context) {
2399
2553
  log(`workspace-sync: skipped (thread mirror missing for ${company})`);
2400
2554
  continue;
2401
2555
  }
2556
+ if (ownershipRefused) {
2557
+ log(`workspace-sync: skipped (ambiguous ownership for ${company})`);
2558
+ continue;
2559
+ }
2402
2560
  const syncArgs = ["sync", "push", "--company", company, `companies/${company}/workspace`];
2403
2561
  const spawnPlan = planHqSpawn(syncArgs, process.env, root);
2404
2562
  const pushed = spawnSync(spawnPlan.cmd, spawnPlan.args, {
@@ -44,6 +44,17 @@ interface FenceExports {
44
44
  confirmUnproven?: boolean;
45
45
  }) => CorruptIdentityRecovery;
46
46
  readPersonalVaultOwnerUid?: () => string | null;
47
+ noOriginIdentityMarker?: (stateDir: string) => {
48
+ sinceMs: number;
49
+ } | undefined;
50
+ confirmUnprovenIdentityHold?: (identity: {
51
+ sub: string;
52
+ personalUid?: string;
53
+ }) => UnprovenHoldRelease;
54
+ }
55
+ export interface UnprovenHoldRelease {
56
+ cleared: boolean;
57
+ sinceMs?: number;
47
58
  }
48
59
  export declare const HELD_UNAVAILABLE_MESSAGE = "this HQ build cannot list or release held uploads yet; update HQ and try again";
49
60
  export declare function fenceExports(mod?: Record<string, unknown>): FenceExports | undefined;
@@ -29,12 +29,16 @@ export function fenceExports(mod = hqCloud) {
29
29
  const corrupt = mod.corruptPushIdentityHold;
30
30
  const recover = mod.recoverCorruptPushIdentity;
31
31
  const readOwner = mod.readPersonalVaultOwnerUid;
32
+ const noOriginMarker = mod.noOriginIdentityMarker;
33
+ const confirmUnproven = mod.confirmUnprovenIdentityHold;
32
34
  return {
33
35
  listPushIdentityFences: list,
34
36
  releasePushIdentityFences: release,
35
37
  ...(typeof corrupt === "function" ? { corruptPushIdentityHold: corrupt } : {}),
36
38
  ...(typeof recover === "function" ? { recoverCorruptPushIdentity: recover } : {}),
37
39
  ...(typeof readOwner === "function" ? { readPersonalVaultOwnerUid: readOwner } : {}),
40
+ ...(typeof noOriginMarker === "function" ? { noOriginIdentityMarker: noOriginMarker } : {}),
41
+ ...(typeof confirmUnproven === "function" ? { confirmUnprovenIdentityHold: confirmUnproven } : {}),
38
42
  };
39
43
  }
40
44
  export function scopeLabel(slug) {
@@ -116,11 +120,14 @@ export async function runReleaseHeld(deps, options) {
116
120
  if (options.company)
117
121
  scopes = scopes.filter((scope) => scope.slug === options.company);
118
122
  const corrupt = corruptHoldRequested(deps, options);
123
+ const unprovenHold = unprovenHoldRequested(deps, options);
119
124
  if (scopes.length === 0 && !corrupt) {
125
+ if (unprovenHold)
126
+ return clearUnprovenHoldOnly(deps, options, unprovenHold);
120
127
  deps.log(options.json ? JSON.stringify({ released: [] }) : "No held uploads match.");
121
128
  return 0;
122
129
  }
123
- const needPersonal = corrupt || scopes.some((scope) => scope.slug === PERSONAL_VAULT_JOURNAL_SLUG || scope.slug === "personal");
130
+ const needPersonal = corrupt || unprovenHold !== undefined || scopes.some((scope) => scope.slug === PERSONAL_VAULT_JOURNAL_SLUG || scope.slug === "personal");
124
131
  const snapshot = await deps.identity({ needPersonal, interactive: true });
125
132
  const identities = [snapshot.sub, ...(snapshot.personalUid ? [snapshot.personalUid] : [])];
126
133
  const mine = scopes.filter((scope) => identities.includes(scope.uid));
@@ -197,6 +204,12 @@ export async function runReleaseHeld(deps, options) {
197
204
  : corruptRefusal(recovery.reason, released.length > 0));
198
205
  return 1;
199
206
  }
207
+ const clearedHold = unprovenHold && !withheldListed
208
+ ? deps.exports.confirmUnprovenIdentityHold?.({
209
+ sub: current.sub,
210
+ ...(current.personalUid ? { personalUid: current.personalUid } : {}),
211
+ })
212
+ : undefined;
200
213
  const restored = recovery?.recovered === true;
201
214
  const heldScopeFiles = recovery?.heldScopeFiles ?? 0;
202
215
  const stayHeld = heldScopeFiles > 0 || recovery?.uploadsStayHeld === true || withheldListed;
@@ -208,6 +221,7 @@ export async function runReleaseHeld(deps, options) {
208
221
  ...(reportCorrupt ? { identityRestored: restored } : {}),
209
222
  ...(recovery?.uploadsStayHeld === true || withheldListed ? { uploadsStayHeld: true } : {}),
210
223
  ...(needsSync ? { needsSync, ...(released.length === 0 && !withheldListed ? { reason: "no-file-list" } : {}) } : {}),
224
+ ...(clearedHold ? unprovenHoldJson(clearedHold, unprovenHold) : {}),
211
225
  }));
212
226
  }
213
227
  else if (restored && stayHeld && released.length === 0) {
@@ -233,8 +247,58 @@ export async function runReleaseHeld(deps, options) {
233
247
  else {
234
248
  deps.log(`Released ${released.map(scopeLabel).join(", ")}. The next sync uploads these files.`);
235
249
  }
250
+ if (!options.json && clearedHold && unprovenHold)
251
+ deps.log(unprovenHoldLine(clearedHold, unprovenHold));
236
252
  return 0;
237
253
  }
254
+ function unprovenHoldRequested(deps, options) {
255
+ if (options.company || options.personal || options.confirmUnproven)
256
+ return undefined;
257
+ if (!deps.exports?.confirmUnprovenIdentityHold)
258
+ return undefined;
259
+ return deps.exports.noOriginIdentityMarker?.(deps.stateDir);
260
+ }
261
+ function holdDay(sinceMs) {
262
+ return new Date(sinceMs).toISOString().slice(0, 10);
263
+ }
264
+ function unprovenHoldJson(result, marker) {
265
+ const sinceMs = result.sinceMs ?? marker?.sinceMs;
266
+ return {
267
+ clearedIdentityHold: result.cleared,
268
+ ...(sinceMs !== undefined ? { identityHoldSince: new Date(sinceMs).toISOString() } : {}),
269
+ };
270
+ }
271
+ function unprovenHoldLine(result, marker) {
272
+ const day = holdDay(result.sinceMs ?? marker.sinceMs);
273
+ return result.cleared
274
+ ? `Cleared the upload hold recorded on ${day}. The identity history on this computer could not be proven then. The sign-in records, the personal vault owner and every sync scope on this computer now name the signed-in account, so new companies sync without a hold.`
275
+ : `The upload hold recorded on ${day} stays, so new companies are still held. It clears when every held upload on this computer is released and the sign-in records, the personal vault owner and every sync scope name the signed-in account.`;
276
+ }
277
+ async function clearUnprovenHoldOnly(deps, options, marker) {
278
+ const snapshot = await deps.identity({ needPersonal: true, interactive: true });
279
+ if (!options.yes) {
280
+ const ok = await deps.confirm(`No uploads are waiting. This computer has an upload hold recorded on ${holdDay(marker.sinceMs)} because its identity history could not be proven. Clear it for the signed-in account? [y/N] `);
281
+ if (!ok) {
282
+ deps.log(options.json ? JSON.stringify({ released: [] }) : "Nothing released.");
283
+ return 1;
284
+ }
285
+ }
286
+ const current = await deps.identity({ needPersonal: true, interactive: false });
287
+ if (current.sub !== snapshot.sub || current.personalUid !== snapshot.personalUid) {
288
+ deps.log(options.json
289
+ ? JSON.stringify({ released: [], reason: "identity-changed" })
290
+ : "The signed-in account changed while releasing. Nothing was released; run the command again.");
291
+ return 1;
292
+ }
293
+ const result = deps.exports?.confirmUnprovenIdentityHold?.({
294
+ sub: current.sub,
295
+ ...(current.personalUid ? { personalUid: current.personalUid } : {}),
296
+ }) ?? { cleared: false };
297
+ deps.log(options.json
298
+ ? JSON.stringify({ released: [], ...unprovenHoldJson(result, marker) })
299
+ : unprovenHoldLine(result, marker));
300
+ return result.cleared ? 0 : 1;
301
+ }
238
302
  function corruptHoldRequested(deps, options) {
239
303
  const probe = deps.exports?.corruptPushIdentityHold;
240
304
  if (!probe || !deps.exports?.recoverCorruptPushIdentity)
@@ -0,0 +1,5 @@
1
+ export declare const SUPPORTED_SCHEMA_VERSION = 1;
2
+ export declare const TELEMETRY_VIEWS: readonly ["summary", "machines", "errors", "people", "folders", "loops", "ranking"];
3
+ export type TelemetryView = (typeof TELEMETRY_VIEWS)[number];
4
+ export declare function renderTelemetryReport(body: unknown, view: TelemetryView): string[];
5
+ //# sourceMappingURL=sync-telemetry-report.d.ts.map