@indigoai-us/hq-cli 5.345.221 → 5.345.223

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 (87) hide show
  1. package/CHANGELOG.md +70 -1
  2. package/dist/command-catalog.generated.d.ts +31 -0
  3. package/dist/command-catalog.generated.js +38 -0
  4. package/dist/commands/auth.js +2 -1
  5. package/dist/commands/bot.d.ts +1 -1
  6. package/dist/commands/bot.js +34 -33
  7. package/dist/commands/core-delegate-w1b.js +216 -190
  8. package/dist/commands/daemon.d.ts +1 -0
  9. package/dist/commands/daemon.js +15 -1
  10. package/dist/commands/link.d.ts +2 -0
  11. package/dist/commands/link.js +14 -2
  12. package/dist/commands/mesh.js +23 -3
  13. package/dist/commands/packs.js +13 -2
  14. package/dist/commands/sync-core.d.ts +6 -0
  15. package/dist/commands/sync-core.js +75 -1
  16. package/dist/data/command-states.json +3 -0
  17. package/dist/lib/bot/fleet-cron.d.ts +26 -3
  18. package/dist/lib/bot/fleet-cron.js +44 -4
  19. package/dist/lib/bot/run.d.ts +4 -4
  20. package/dist/lib/bot/run.js +5 -3
  21. package/dist/lib/bot/signals-engine-flag.d.ts +53 -13
  22. package/dist/lib/bot/signals-engine-flag.js +202 -9
  23. package/dist/lib/daemon/catalog.js +2 -0
  24. package/dist/lib/daemon/install.d.ts +2 -1
  25. package/dist/lib/daemon/install.js +9 -0
  26. package/dist/lib/daemon/legacy.d.ts +1 -0
  27. package/dist/lib/daemon/legacy.js +5 -2
  28. package/dist/lib/daemon/machine-check-owner.d.ts +2 -0
  29. package/dist/lib/daemon/machine-check-owner.js +6 -1
  30. package/dist/lib/daemon/machine-checks.d.ts +52 -1
  31. package/dist/lib/daemon/machine-checks.js +104 -11
  32. package/dist/lib/daemon/mesh-owner.d.ts +45 -0
  33. package/dist/lib/daemon/mesh-owner.js +166 -0
  34. package/dist/lib/daemon/native-notice-ledger.d.ts +36 -0
  35. package/dist/lib/daemon/native-notice-ledger.js +156 -0
  36. package/dist/lib/daemon/run.d.ts +15 -0
  37. package/dist/lib/daemon/run.js +72 -3
  38. package/dist/lib/daemon/selfcheck.d.ts +35 -2
  39. package/dist/lib/daemon/selfcheck.js +118 -9
  40. package/dist/lib/daemon/supervisor.d.ts +10 -0
  41. package/dist/lib/daemon/supervisor.js +86 -0
  42. package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
  43. package/dist/lib/flag-registry-worker-source.generated.js +1 -1
  44. package/dist/lib/flag-registry-worker.js +33 -3
  45. package/dist/lib/flag-registry.js +13 -0
  46. package/dist/lib/hook-engine/coverage.d.ts +9 -0
  47. package/dist/lib/hook-engine/coverage.js +56 -0
  48. package/dist/lib/hook-engine/native-stop-compatibility.json +56 -5
  49. package/dist/lib/mesh/live/daemon/config.d.ts +8 -1
  50. package/dist/lib/mesh/live/daemon/config.js +16 -0
  51. package/dist/lib/mesh/live/daemon/install.d.ts +31 -2
  52. package/dist/lib/mesh/live/daemon/install.js +142 -1
  53. package/dist/lib/mesh/live/daemon/login-home.d.ts +5 -0
  54. package/dist/lib/mesh/live/daemon/login-home.js +27 -0
  55. package/dist/lib/mesh/live/daemon/unit-home.d.ts +49 -0
  56. package/dist/lib/mesh/live/daemon/unit-home.js +134 -0
  57. package/dist/lib/registry/registry.d.ts +35 -7
  58. package/dist/lib/registry/registry.js +88 -13
  59. package/dist/lib/scan-packages/index.js +23 -2
  60. package/dist/lib/search-index/max-doc-bytes.js +2 -1
  61. package/dist/lib/service-manager/startup-migration.d.ts +1 -0
  62. package/dist/lib/service-manager/startup-migration.js +3 -0
  63. package/dist/lib/signals/engine.d.ts +8 -0
  64. package/dist/lib/signals/engine.js +15 -5
  65. package/dist/lib/sync-core/engine-holds.d.ts +14 -0
  66. package/dist/lib/sync-core/engine-holds.js +60 -0
  67. package/dist/lib/sync-core/engine-home.d.ts +2 -0
  68. package/dist/lib/sync-core/flag.d.ts +18 -0
  69. package/dist/lib/sync-core/flag.js +66 -0
  70. package/dist/lib/sync-core/reconcile.d.ts +6 -0
  71. package/dist/lib/sync-core/reconcile.js +23 -0
  72. package/dist/lib/sync-core/rollout-state.d.ts +2 -0
  73. package/dist/lib/sync-core/rollout-state.js +7 -0
  74. package/dist/lib/sync-core/vault-settings.d.ts +32 -0
  75. package/dist/lib/sync-core/vault-settings.js +147 -0
  76. package/dist/lib/windows/install-followup.d.ts +2 -0
  77. package/dist/lib/windows/install-followup.js +4 -1
  78. package/dist/utils/host-registration.js +3 -1
  79. package/dist/utils/pack-contributions.d.ts +16 -1
  80. package/dist/utils/pack-contributions.js +139 -26
  81. package/dist/utils/self-update.d.ts +3 -1
  82. package/dist/utils/self-update.js +56 -11
  83. package/dist/utils/update-lock.d.ts +151 -14
  84. package/dist/utils/update-lock.js +782 -46
  85. package/dist/utils/version-gate.js +12 -2
  86. package/package.json +7 -7
  87. package/scripts/bench-core.mjs +34 -3
@@ -518,200 +518,219 @@ function runGrant(args, context) {
518
518
  return fail("grant", "--manifest is required");
519
519
  if (!fs.existsSync(manifestPath) || !fs.statSync(manifestPath).isFile())
520
520
  return fail("grant", `manifest not found: ${delegateDiagnosticPath(manifestPath)}`);
521
- let manifest;
522
- try {
523
- manifest = readJsonFile(manifestPath);
524
- }
525
- catch {
526
- return fail("grant", `manifest is not valid JSON: ${delegateDiagnosticPath(manifestPath)}`);
527
- }
528
- if (manifest === null || manifest === false)
529
- return fail("grant", `manifest is not valid JSON: ${delegateDiagnosticPath(manifestPath)}`);
530
- if (!isRecord(manifest))
531
- return fail("grant", "manifest has no company");
532
- const company = jqRawPath(manifest, "company");
533
- const project = jqRawPath(manifest, "project.name");
534
- const principal = jqRawPath(manifest, "to.principal");
535
- const display = jqRawPaths(manifest, ["to.displayName", "to.principal"]);
536
- const status = jqRawPath(manifest, "status");
537
- if (!company)
538
- return fail("grant", "manifest has no company");
539
- if (!project)
540
- return fail("grant", "manifest has no project.name");
541
- if (!principal)
542
- return fail("grant", "manifest has no to.principal");
543
- let grantPrincipal = principal;
544
- if (principal.startsWith("agt_")) {
545
- const legacyGroup = "grp_dlg-" + principal.slice(-9).toLowerCase();
546
- const nextGroup = delegationGroupId(principal);
547
- const recordedGroup = text(getPath(manifest, "grantPrincipal"));
548
- grantPrincipal = recordedGroup === legacyGroup || recordedGroup === nextGroup ? recordedGroup : nextGroup;
549
- }
550
- if (status !== "building" && status !== "granted")
551
- return fail("grant", `manifest status is '${status}' — grants run from 'building' (or re-run from 'granted'), not from there`);
552
- const prefixes = list(getPath(manifest, "vaultPrefixes"));
553
- if (prefixes.length === 0)
554
- return fail("grant", "manifest has no vaultPrefixes");
555
- const badPrefixes = prefixes.filter((entry) => {
556
- const prefix = jqRawPath(entry, "prefix");
557
- return !prefix.endsWith("/") || prefix.startsWith("companies/") || prefix.startsWith("/");
558
- }).map((entry) => jqRawPath(entry, "prefix"));
559
- if (badPrefixes.length)
560
- return fail("grant", `prefix violates the hq-files prefix conventions (must be company-relative folder form ending in '/'): ${badPrefixes.join("\n")}`);
561
- out(`Delegation grant plan — company '${company}', recipient '${principal}':\n`);
562
- if (grantPrincipal !== principal)
563
- out(` 0. Agent recipient: grants flow through group ${grantPrincipal} (created if absent, containing exactly ${display})\n`);
564
- out(` 1. Push companies/${company}/projects/${project}/ to the vault (on-conflict keep)\n`);
565
- for (const entry of prefixes)
566
- out(` 2. Grant ${jqRawPath(entry, "permission")} on ${jqRawPath(entry, "prefix")} — ${jqRawPath(entry, "reason")}\n`);
567
- const writePrefixes = prefixes.map((entry) => jqRawPath(entry, "permission") === "write" ? jqRawPath(entry, "prefix") : "").filter(Boolean);
568
- if (writePrefixes.length) {
569
- out(`\nNOTE: granting 'write' is a privilege escalation. The recipient will be able\nto upload, overwrite, and delete under: ${writePrefixes.map((prefix) => `${prefix} `).join("")}\n`);
570
- }
571
- if (!yes) {
572
- out("\n");
573
- err("hq-delegate-grant: confirmation required — re-run with --yes after the user approves\n");
574
- return 2;
575
- }
576
- let result = runHq(["sync", "push", `companies/${company}/projects/${project}/`, "--company", company, "--on-conflict", "keep"], context, "inherit");
577
- if (result.code !== 0)
578
- return fail("grant", `vault push failed for companies/${company}/projects/${project}/`);
579
- const referencePaths = [
580
- ...list(getPath(manifest, "knowledge", [])),
581
- ...list(getPath(manifest, "policies", [])),
582
- ].filter((entry) => typeof entry === "string" && entry.startsWith(`companies/${company}/`));
583
- for (const reference of referencePaths) {
584
- if (fs.existsSync(path.join(context.root ?? context.cwd, reference))) {
585
- result = runHq(["sync", "push", reference, "--company", company, "--on-conflict", "keep"], context, "inherit");
586
- if (result.code !== 0)
587
- return fail("grant", `vault push failed for referenced knowledge: ${reference}`);
588
- }
589
- else {
590
- err(`hq-delegate-grant: referenced path missing locally (cannot push): ${reference} — the verify probe will fail if it is not already in the vault\n`);
521
+ const lock = `${manifestPath}.send-lock`;
522
+ if (yes) {
523
+ try {
524
+ fs.mkdirSync(lock);
591
525
  }
592
- }
593
- if (grantPrincipal !== principal) {
594
- result = runHq(["groups", "create", grantPrincipal, "--name", `Delegation: ${display}`, "--company", company], context, "inherit");
595
- if (result.code !== 0)
596
- err("hq-delegate-grant: group create reported an error (may already exist) — continuing\n");
597
- result = runHq(["groups", "add", grantPrincipal, principal, "--company", company], context, "inherit");
598
- if (result.code !== 0)
599
- err("hq-delegate-grant: group add reported an error (may already be a member) — continuing\n");
600
- const members = subprocess("hq", ["groups", "members", grantPrincipal, "--company", company], context.cwd, { env: { NO_COLOR: "1", FORCE_COLOR: "0" } });
601
- if (members.code !== 0)
602
- return fail("grant", "could not verify delegation group membership");
603
- const memberIds = groupMemberIds(members.stdout ?? "");
604
- if (memberIds === null || memberIds.length !== 1 || memberIds[0] !== principal) {
605
- return fail("grant", "delegation group membership does not exactly match recipient");
526
+ catch {
527
+ return fail("grant", "verification or delivery is active; retry after it finishes");
606
528
  }
607
529
  }
608
- let expectedType = "";
609
- let expectedId = "";
610
- let expectedCompany = "";
611
- if (grantPrincipal.startsWith("grp_")) {
612
- expectedType = "group";
613
- expectedId = grantPrincipal;
614
- }
615
- else if (grantPrincipal === "@all") {
616
- expectedType = "company-wide";
617
- }
618
- else {
619
- const resolved = runHq(["people", "resolve", principal, "--company", company, "--json", "--membership-only"], context);
620
- let response;
530
+ try {
531
+ let manifest;
621
532
  try {
622
- response = JSON.parse(resolved.stdout ?? "");
533
+ manifest = readJsonFile(manifestPath);
623
534
  }
624
- catch (error) {
625
- if (error instanceof SyntaxError) {
626
- const input = commandSubstitutionBytes(resolved);
627
- emitJqParseDiagnostic(input, ["-e", RESOLVE_FOUND_FILTER], context);
628
- emitJqParseDiagnostic(input, ["-e", RESOLVE_NOT_FOUND_FILTER], context);
629
- }
630
- response = undefined;
535
+ catch {
536
+ return fail("grant", `manifest is not valid JSON: ${delegateDiagnosticPath(manifestPath)}`);
631
537
  }
632
- if (isRecord(response) && response.status === "found" && isRecord(response.person) && typeof response.person.personUid === "string" && typeof response.person.companyUid === "string") {
633
- if (resolved.code !== 0)
634
- return fail("grant", "recipient resolution failed");
635
- expectedType = "person";
636
- expectedId = response.person.personUid;
637
- expectedCompany = response.person.companyUid;
538
+ if (manifest === null || manifest === false)
539
+ return fail("grant", `manifest is not valid JSON: ${delegateDiagnosticPath(manifestPath)}`);
540
+ if (!isRecord(manifest))
541
+ return fail("grant", "manifest has no company");
542
+ const company = jqRawPath(manifest, "company");
543
+ const project = jqRawPath(manifest, "project.name");
544
+ const principal = jqRawPath(manifest, "to.principal");
545
+ const display = jqRawPaths(manifest, ["to.displayName", "to.principal"]);
546
+ const status = jqRawPath(manifest, "status");
547
+ if (!company)
548
+ return fail("grant", "manifest has no company");
549
+ if (!project)
550
+ return fail("grant", "manifest has no project.name");
551
+ if (!principal)
552
+ return fail("grant", "manifest has no to.principal");
553
+ let grantPrincipal = principal;
554
+ if (principal.startsWith("agt_")) {
555
+ const legacyGroup = "grp_dlg-" + principal.slice(-9).toLowerCase();
556
+ const nextGroup = delegationGroupId(principal);
557
+ const recordedGroup = text(getPath(manifest, "grantPrincipal"));
558
+ grantPrincipal = recordedGroup === legacyGroup || recordedGroup === nextGroup ? recordedGroup : nextGroup;
638
559
  }
639
- else if (isRecord(response) && response.status === "not_found") {
640
- if (principal.includes("@")) {
641
- expectedType = "email";
642
- expectedId = principal.toLowerCase().trim();
643
- }
644
- else
645
- return fail("grant", "unresolved recipient");
560
+ if (status !== "building" && status !== "granted")
561
+ return fail("grant", `manifest status is '${status}' — grants run from 'building' (or re-run from 'granted'), not from there`);
562
+ const prefixes = list(getPath(manifest, "vaultPrefixes"));
563
+ if (prefixes.length === 0)
564
+ return fail("grant", "manifest has no vaultPrefixes");
565
+ const badPrefixes = prefixes.filter((entry) => {
566
+ const prefix = jqRawPath(entry, "prefix");
567
+ return !prefix.endsWith("/") || prefix.startsWith("companies/") || prefix.startsWith("/");
568
+ }).map((entry) => jqRawPath(entry, "prefix"));
569
+ if (badPrefixes.length)
570
+ return fail("grant", `prefix violates the hq-files prefix conventions (must be company-relative folder form ending in '/'): ${badPrefixes.join("\n")}`);
571
+ out(`Delegation grant plan — company '${company}', recipient '${principal}':\n`);
572
+ if (grantPrincipal !== principal)
573
+ out(` 0. Agent recipient: grants flow through group ${grantPrincipal} (created if absent, containing exactly ${display})\n`);
574
+ out(` 1. Push companies/${company}/projects/${project}/ to the vault (on-conflict keep)\n`);
575
+ for (const entry of prefixes)
576
+ out(` 2. Grant ${jqRawPath(entry, "permission")} on ${jqRawPath(entry, "prefix")} — ${jqRawPath(entry, "reason")}\n`);
577
+ const writePrefixes = prefixes.map((entry) => jqRawPath(entry, "permission") === "write" ? jqRawPath(entry, "prefix") : "").filter(Boolean);
578
+ if (writePrefixes.length) {
579
+ out(`\nNOTE: granting 'write' is a privilege escalation. The recipient will be able\nto upload, overwrite, and delete under: ${writePrefixes.map((prefix) => `${prefix} `).join("")}\n`);
646
580
  }
647
- else
648
- return fail("grant", "authoritative recipient lookup failed; update hq-cli if --membership-only is unsupported");
649
- }
650
- const readAcl = (prefix) => {
651
- const response = runHq(["files", "acl", prefix, "--company", company, "--json"], context);
652
- if (response.code !== 0)
653
- return { ok: false };
654
- let value;
655
- try {
656
- value = JSON.parse(response.stdout ?? "");
581
+ if (!yes) {
582
+ out("\n");
583
+ err("hq-delegate-grant: confirmation required — re-run with --yes after the user approves\n");
584
+ return 2;
657
585
  }
658
- catch (error) {
659
- if (error instanceof SyntaxError) {
660
- const input = commandSubstitutionBytes(response);
661
- emitJqParseDiagnostic(input, ["-e", "--arg", "prefix", prefix, "--arg", "company", expectedCompany, ACL_FILTER], context);
586
+ let result = runHq(["sync", "push", `companies/${company}/projects/${project}/`, "--company", company, "--on-conflict", "keep"], context, "inherit");
587
+ if (result.code !== 0)
588
+ return fail("grant", `vault push failed for companies/${company}/projects/${project}/`);
589
+ const referencePaths = [
590
+ ...list(getPath(manifest, "knowledge", [])),
591
+ ...list(getPath(manifest, "policies", [])),
592
+ ].filter((entry) => typeof entry === "string" && entry.startsWith(`companies/${company}/`));
593
+ for (const reference of referencePaths) {
594
+ if (fs.existsSync(path.join(context.root ?? context.cwd, reference))) {
595
+ result = runHq(["sync", "push", reference, "--company", company, "--on-conflict", "keep"], context, "inherit");
596
+ if (result.code !== 0)
597
+ return fail("grant", `vault push failed for referenced knowledge: ${reference}`);
598
+ }
599
+ else {
600
+ err(`hq-delegate-grant: referenced path missing locally (cannot push): ${reference} — the verify probe will fail if it is not already in the vault\n`);
662
601
  }
663
- value = undefined;
664
602
  }
665
- const rawPrefix = isRecord(value) ? value.prefix : undefined;
666
- const expectedPrefix = prefix.endsWith("/*") ? prefix.slice(0, -1) : prefix;
667
- if (!isRecord(value) || value.schemaVersion !== 1 || (rawPrefix !== prefix && rawPrefix !== expectedPrefix) || typeof value.companyUid !== "string" || (expectedCompany !== "" && value.companyUid !== expectedCompany) || !Array.isArray(value.direct) || typeof value.exists !== "boolean") {
668
- err(`hq-delegate-grant: invalid structured ACL response for ${prefix}\n`);
669
- return { ok: false };
603
+ if (grantPrincipal !== principal) {
604
+ result = runHq(["groups", "create", grantPrincipal, "--name", `Delegation: ${display}`, "--company", company], context, "inherit");
605
+ if (result.code !== 0)
606
+ err("hq-delegate-grant: group create reported an error (may already exist) — continuing\n");
607
+ result = runHq(["groups", "add", grantPrincipal, principal, "--company", company], context, "inherit");
608
+ if (result.code !== 0)
609
+ err("hq-delegate-grant: group add reported an error (may already be a member) — continuing\n");
610
+ const members = subprocess("hq", ["groups", "members", grantPrincipal, "--company", company], context.cwd, { env: { NO_COLOR: "1", FORCE_COLOR: "0" } });
611
+ if (members.code !== 0)
612
+ return fail("grant", "could not verify delegation group membership");
613
+ const memberIds = groupMemberIds(members.stdout ?? "");
614
+ if (memberIds === null || memberIds.length !== 1 || memberIds[0] !== principal) {
615
+ return fail("grant", "delegation group membership does not exactly match recipient");
616
+ }
670
617
  }
671
- return { value, ok: true };
672
- };
673
- const now = currentTime();
674
- for (let i = 0; i < prefixes.length; i += 1) {
675
- const entry = prefixes[i];
676
- if (!isRecord(entry) || !isRecord(manifest))
677
- return fail("grant", "manifest has an invalid vaultPrefixes entry");
678
- const prefix = jqRawPath(entry, "prefix");
679
- const permission = jqRawPath(entry, "permission");
680
- const aclPattern = `${prefix}*`;
681
- const before = readAcl(aclPattern);
682
- if (!before.ok || !before.value)
683
- return fail("grant", `ACL preflight failed; no share attempted for ${prefix}`);
684
- expectedCompany = text(before.value.companyUid);
685
- const share = runHq(["files", "share", aclPattern, "--with", grantPrincipal, "--permission", permission, "--company", company], context, "inherit");
686
- const shareRc = share.code;
687
- if (shareRc !== 0)
688
- err(`hq-delegate-grant: share reported an error on ${prefix}; checking exact grant\n`);
689
- let landed = false;
690
- for (const delay of [0, 1, 2]) {
691
- if (delay)
692
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, delay * 1000);
693
- const after = readAcl(aclPattern);
694
- if (after.ok && after.value?.exists === true && list(after.value.direct).some((row) => isRecord(row) && row.granteeType === expectedType && row.granteeId === expectedId && row.permission === permission)) {
695
- landed = true;
696
- break;
618
+ let expectedType = "";
619
+ let expectedId = "";
620
+ let expectedCompany = "";
621
+ if (grantPrincipal.startsWith("grp_")) {
622
+ expectedType = "group";
623
+ expectedId = grantPrincipal;
624
+ }
625
+ else if (grantPrincipal === "@all") {
626
+ expectedType = "company-wide";
627
+ }
628
+ else {
629
+ const resolved = runHq(["people", "resolve", principal, "--company", company, "--json", "--membership-only"], context);
630
+ let response;
631
+ try {
632
+ response = JSON.parse(resolved.stdout ?? "");
633
+ }
634
+ catch (error) {
635
+ if (error instanceof SyntaxError) {
636
+ const input = commandSubstitutionBytes(resolved);
637
+ emitJqParseDiagnostic(input, ["-e", RESOLVE_FOUND_FILTER], context);
638
+ emitJqParseDiagnostic(input, ["-e", RESOLVE_NOT_FOUND_FILTER], context);
639
+ }
640
+ response = undefined;
641
+ }
642
+ if (isRecord(response) && response.status === "found" && isRecord(response.person) && typeof response.person.personUid === "string" && typeof response.person.companyUid === "string") {
643
+ if (resolved.code !== 0)
644
+ return fail("grant", "recipient resolution failed");
645
+ expectedType = "person";
646
+ expectedId = response.person.personUid;
647
+ expectedCompany = response.person.companyUid;
697
648
  }
649
+ else if (isRecord(response) && response.status === "not_found") {
650
+ if (principal.includes("@")) {
651
+ expectedType = "email";
652
+ expectedId = principal.toLowerCase().trim();
653
+ }
654
+ else
655
+ return fail("grant", "unresolved recipient");
656
+ }
657
+ else
658
+ return fail("grant", "authoritative recipient lookup failed; update hq-cli if --membership-only is unsupported");
698
659
  }
699
- if (!landed)
700
- return fail("grant", `grant outcome unconfirmed for ${principal} on ${prefix}; retain this manifest and resume`);
701
- const current = list(manifest.vaultPrefixes)[i];
702
- if (!isRecord(current))
703
- return fail("grant", "manifest has an invalid vaultPrefixes entry");
704
- current.verifiedAt = now;
705
- current.grantReceipt = { companyUid: expectedCompany, granteeType: expectedType, granteeId: expectedId, shareExitCode: shareRc, verifiedAt: now };
660
+ const readAcl = (prefix) => {
661
+ const response = runHq(["files", "acl", prefix, "--company", company, "--json"], context);
662
+ if (response.code !== 0)
663
+ return { ok: false };
664
+ let value;
665
+ try {
666
+ value = JSON.parse(response.stdout ?? "");
667
+ }
668
+ catch (error) {
669
+ if (error instanceof SyntaxError) {
670
+ const input = commandSubstitutionBytes(response);
671
+ emitJqParseDiagnostic(input, ["-e", "--arg", "prefix", prefix, "--arg", "company", expectedCompany, ACL_FILTER], context);
672
+ }
673
+ value = undefined;
674
+ }
675
+ const rawPrefix = isRecord(value) ? value.prefix : undefined;
676
+ const expectedPrefix = prefix.endsWith("/*") ? prefix.slice(0, -1) : prefix;
677
+ if (!isRecord(value) || value.schemaVersion !== 1 || (rawPrefix !== prefix && rawPrefix !== expectedPrefix) || typeof value.companyUid !== "string" || (expectedCompany !== "" && value.companyUid !== expectedCompany) || !Array.isArray(value.direct) || typeof value.exists !== "boolean") {
678
+ err(`hq-delegate-grant: invalid structured ACL response for ${prefix}\n`);
679
+ return { ok: false };
680
+ }
681
+ return { value, ok: true };
682
+ };
683
+ const now = currentTime();
684
+ for (let i = 0; i < prefixes.length; i += 1) {
685
+ const entry = prefixes[i];
686
+ if (!isRecord(entry) || !isRecord(manifest))
687
+ return fail("grant", "manifest has an invalid vaultPrefixes entry");
688
+ const prefix = jqRawPath(entry, "prefix");
689
+ const permission = jqRawPath(entry, "permission");
690
+ const aclPattern = `${prefix}*`;
691
+ const before = readAcl(aclPattern);
692
+ if (!before.ok || !before.value)
693
+ return fail("grant", `ACL preflight failed; no share attempted for ${prefix}`);
694
+ expectedCompany = text(before.value.companyUid);
695
+ const share = runHq(["files", "share", aclPattern, "--with", grantPrincipal, "--permission", permission, "--company", company], context, "inherit");
696
+ const shareRc = share.code;
697
+ if (shareRc !== 0)
698
+ err(`hq-delegate-grant: share reported an error on ${prefix}; checking exact grant\n`);
699
+ let landed = false;
700
+ for (const delay of [0, 1, 2]) {
701
+ if (delay)
702
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, delay * 1000);
703
+ const after = readAcl(aclPattern);
704
+ if (after.ok && after.value?.exists === true && list(after.value.direct).some((row) => isRecord(row) && row.granteeType === expectedType && row.granteeId === expectedId && row.permission === permission)) {
705
+ landed = true;
706
+ break;
707
+ }
708
+ }
709
+ if (!landed)
710
+ return fail("grant", `grant outcome unconfirmed for ${principal} on ${prefix}; retain this manifest and resume`);
711
+ const current = list(manifest.vaultPrefixes)[i];
712
+ if (!isRecord(current))
713
+ return fail("grant", "manifest has an invalid vaultPrefixes entry");
714
+ current.verifiedAt = now;
715
+ current.grantReceipt = { companyUid: expectedCompany, granteeType: expectedType, granteeId: expectedId, shareExitCode: shareRc, verifiedAt: now };
716
+ writeJsonAtomically(manifestPath, manifest, true);
717
+ out(`hq-delegate-grant: verified ${permission} on ${prefix} for ${principal}\n`);
718
+ }
719
+ manifest.status = "granted";
720
+ manifest.grantPrincipal = grantPrincipal;
721
+ manifest.vaultPrefixes = list(manifest.vaultPrefixes).map((entry) => isRecord(entry) ? { ...entry, verifiedAt: now } : entry);
706
722
  writeJsonAtomically(manifestPath, manifest, true);
707
- out(`hq-delegate-grant: verified ${permission} on ${prefix} for ${principal}\n`);
723
+ out(`hq-delegate-grant: all ${prefixes.length} grants verified — manifest status advanced to 'granted'\n`);
724
+ return 0;
725
+ }
726
+ finally {
727
+ if (yes) {
728
+ try {
729
+ fs.rmdirSync(lock);
730
+ }
731
+ catch { /* Preserve the grant result. */ }
732
+ }
708
733
  }
709
- manifest.status = "granted";
710
- manifest.grantPrincipal = grantPrincipal;
711
- manifest.vaultPrefixes = list(manifest.vaultPrefixes).map((entry) => isRecord(entry) ? { ...entry, verifiedAt: now } : entry);
712
- writeJsonAtomically(manifestPath, manifest, true);
713
- out(`hq-delegate-grant: all ${prefixes.length} grants verified — manifest status advanced to 'granted'\n`);
714
- return 0;
715
734
  }
716
735
  function atomicCopy(source, target, mode) {
717
736
  const temporary = `${target}.tmp.${process.pid}.${Math.random().toString(16).slice(2)}`;
@@ -931,15 +950,6 @@ function runSend(args, context) {
931
950
  return fail("send", "--manifest is required");
932
951
  if (!fs.existsSync(manifestPath) || !fs.statSync(manifestPath).isFile())
933
952
  return fail("send", `manifest not found: ${delegateDiagnosticPath(manifestPath)}`);
934
- const manifest = jsonFile(manifestPath);
935
- if (!manifest)
936
- return fail("send", `manifest is not valid JSON: ${delegateDiagnosticPath(manifestPath)}`);
937
- if (send) {
938
- const publishedPath = path.join(context.root ?? context.cwd, jqRawPath(manifest, "publication.manifestPath"));
939
- if (malformedJsonFile(publishedPath)) {
940
- return runShellFallback("send", args, context);
941
- }
942
- }
943
953
  const lock = `${manifestPath}.send-lock`;
944
954
  if (send) {
945
955
  try {
@@ -960,6 +970,16 @@ function runSend(args, context) {
960
970
  catch { /* Preserve the command result if a concurrent process removed it. */ }
961
971
  };
962
972
  try {
973
+ const manifest = jsonFile(manifestPath);
974
+ if (!manifest)
975
+ return fail("send", `manifest is not valid JSON: ${delegateDiagnosticPath(manifestPath)}`);
976
+ if (send) {
977
+ const publishedPath = path.join(context.root ?? context.cwd, jqRawPath(manifest, "publication.manifestPath"));
978
+ if (malformedJsonFile(publishedPath)) {
979
+ removeLock();
980
+ return runShellFallback("send", args, context);
981
+ }
982
+ }
963
983
  const bundleDir = path.dirname(path.resolve(manifestPath));
964
984
  const brief = path.join(bundleDir, "BRIEF.md");
965
985
  const prompt = path.join(bundleDir, "PICKUP-PROMPT.md");
@@ -1307,9 +1327,15 @@ function runVerify(args, context) {
1307
1327
  const publishCode = runPublish(["--manifest", manifestPath, "--lock-held"], context);
1308
1328
  if (publishCode !== 0)
1309
1329
  return fail("verify", "final dossier publication failed; notification blocked");
1310
- manifest.status = "verified";
1311
- manifest.verifiedAt = currentTime();
1312
- writeJsonAtomically(manifestPath, manifest, true);
1330
+ // Publish rewrote the manifest with its checksums and publication receipt,
1331
+ // so the copy read above is stale. Re-read it, as the shell companion's jq
1332
+ // update does, so the verified write keeps the receipt send requires.
1333
+ const published = jsonFile(manifestPath);
1334
+ if (!published)
1335
+ return fail("verify", "published manifest is unreadable; notification blocked");
1336
+ published.status = "verified";
1337
+ published.verifiedAt = currentTime();
1338
+ writeJsonAtomically(manifestPath, published, true);
1313
1339
  out(`hq-delegate-verify: all ${prefixes.length} prefix(es) reachable — manifest status advanced to 'verified'\n`);
1314
1340
  return 0;
1315
1341
  }
@@ -27,6 +27,7 @@ export declare function loadDaemonRunner(release?: () => void, load?: () => Prom
27
27
  export interface DaemonCommandDeps {
28
28
  env: NodeJS.ProcessEnv;
29
29
  home: string;
30
+ loginHome?: string;
30
31
  platform: NodeJS.Platform;
31
32
  out: (line: string) => void;
32
33
  err: (line: string) => void;
@@ -17,6 +17,8 @@
17
17
  import * as fs from "node:fs";
18
18
  import * as os from "node:os";
19
19
  import * as path from "node:path";
20
+ import { SYNC_WAKE_STATE_BASENAME, workMeshRoot } from "../lib/mesh/live/paths.js";
21
+ import { homeIsLoginSafe, meshJobLoadedForHome } from "../lib/mesh/live/daemon/unit-home.js";
20
22
  import { randomBytes } from "node:crypto";
21
23
  import { spawn, spawnSync } from "node:child_process";
22
24
  import { once } from "node:events";
@@ -110,6 +112,7 @@ async function loadDefaults(over) {
110
112
  return {
111
113
  env,
112
114
  home,
115
+ loginHome: over.loginHome,
113
116
  platform,
114
117
  out: over.out ?? ((l) => console.log(l)),
115
118
  err: over.err ?? ((l) => console.error(l)),
@@ -134,7 +137,8 @@ async function loadDefaults(over) {
134
137
  home: dir ?? home,
135
138
  existsSync: fs.existsSync,
136
139
  listDir: (dir) => fs.readdirSync(dir),
137
- launchdJobLoaded: (label) => run("launchctl", ["print", `gui/${process.getuid?.() ?? 0}/${label}`]).status === 0,
140
+ launchdJobLoaded: (label) => meshJobLoadedForHome(run("launchctl", ["print", `gui/${process.getuid?.() ?? 0}/${label}`]), dir ?? home),
141
+ homeIsLogin: platform === "darwin" ? homeIsLoginSafe(dir ?? home) : true,
138
142
  windowsTaskOwner: (task) => classifyWindowsTask(run, task, {
139
143
  windowsSid: over.windowsSid ?? readWindowsSid(run),
140
144
  windowsUser: over.windowsUser ?? mesh.resolveWindowsUser(env),
@@ -211,6 +215,7 @@ function hostFor(d, paths, pathEnv) {
211
215
  windowsHeadlessLauncher: d.windowsHeadlessLauncher,
212
216
  systemUnitDir: d.systemUnitDir ?? SYSTEM_UNIT_DIR,
213
217
  env,
218
+ loginHome: d.loginHome,
214
219
  };
215
220
  }
216
221
  /**
@@ -1934,6 +1939,15 @@ export function registerDaemonCommand(program, over = {}) {
1934
1939
  }
1935
1940
  },
1936
1941
  sendToOwner: (message) => sendDmToMachineOwner(message),
1942
+ wake: {
1943
+ markerPath: path.join(workMeshRoot(d.home, d.env), SYNC_WAKE_STATE_BASENAME),
1944
+ watchPath: path.join(paths.root, "selfcheck-wake.json"),
1945
+ meshWanted: () => {
1946
+ const config = readDaemonConfig(paths.configPath);
1947
+ const { detected } = currentHost(d);
1948
+ return enabledServices(detected.type, config).includes("mesh");
1949
+ },
1950
+ },
1937
1951
  ...(await selfCheckVaults(d.home)),
1938
1952
  log: (line) => d.out(line),
1939
1953
  });
@@ -14,6 +14,8 @@ export interface LinkDeps {
14
14
  /** Active memberships for the signed-in user (reuses GET /membership/me). */
15
15
  listMemberships?: () => Promise<MembershipCompany[]>;
16
16
  now?: () => Date;
17
+ /** HQ root for the companies/<slug> layout fallback (default: $HQ_ROOT). */
18
+ hqRoot?: string;
17
19
  }
18
20
  export interface LinkCommandDeps {
19
21
  /** Test seam for the combined hq-flags and person-setting gate. */
@@ -11,7 +11,7 @@ import { ensureCognitoToken } from "../utils/cognito-session.js";
11
11
  import { listActiveMembershipCompanies } from "../lib/mesh/api.js";
12
12
  import { anywhereRuntimeAllowed } from "../lib/anywhere-person-setting.js";
13
13
  import { readCompaniesManifestMap } from "../lib/work-context/repo-remote.js";
14
- import { canonicalDir, keyForDir, readRegistry, registryDir, registryFile, removeEntriesForDir, resolveCompanyForDir, seedFromManifest, setEntry, writeRegistry, } from "../lib/registry/registry.js";
14
+ import { canonicalDir, keyForDir, readRegistry, registryDir, registryFile, removeEntriesForDir, resolveCompanyForDir, seedFromManifest, setEntry, wouldBindEnclosingRemote, writeRegistry, } from "../lib/registry/registry.js";
15
15
  async function requireAnywhereRuntime(deps) {
16
16
  if (!(await (deps.runtimeAllowed ?? (() => anywhereRuntimeAllowed()))())) {
17
17
  throw new Error("HQ Anywhere is disabled until both the runtime flag and your person setting are on.");
@@ -34,6 +34,9 @@ export async function linkFolder(company, dir, deps = {}) {
34
34
  if (!slug)
35
35
  throw Object.assign(new Error("Company slug is required."), { expected: true });
36
36
  const folder = targetDir(dir);
37
+ if (wouldBindEnclosingRemote(folder)) {
38
+ throw Object.assign(new Error(`Refusing to link ${folder}: it sits inside another git work tree, so the registry key would be that repo's origin and every folder in the repo would resolve to '${slug}'. Link a standalone checkout instead.`), { expected: true });
39
+ }
37
40
  const memberships = await (deps.listMemberships ?? defaultListMemberships)();
38
41
  const match = memberships.find((m) => m.companySlug.toLowerCase() === slug.toLowerCase() || m.companyUid === slug);
39
42
  if (!match) {
@@ -63,7 +66,16 @@ export function resolveCompany(dir, deps = {}) {
63
66
  catch (err) {
64
67
  return { company: null, reason: err.message };
65
68
  }
66
- return resolveCompanyForDir(registry, folder);
69
+ return resolveCompanyForDir(registry, folder, { hqRoot: layoutHqRoot(deps) });
70
+ }
71
+ /**
72
+ * The HQ root the companies/<slug> layout fallback may trust: an explicit
73
+ * dependency or $HQ_ROOT only. Never a cwd walk or CLAUDE_PROJECT_DIR, which
74
+ * in a session started outside HQ is that foreign folder.
75
+ */
76
+ function layoutHqRoot(deps) {
77
+ const raw = deps.hqRoot ?? process.env.HQ_ROOT ?? "";
78
+ return raw.trim() ? path.resolve(raw.trim()) : null;
67
79
  }
68
80
  /** Seed manifest-sourced entries; called by `hq install --global` (US-005). */
69
81
  export function seedRegistryFromHqRoot(hqRoot, deps = {}) {
@@ -40,8 +40,9 @@ import { generateUlid } from "../lib/mesh/live/ulid.js";
40
40
  import { readLegacyBacklog } from "../lib/mesh/live/emit-replay.js";
41
41
  import { resolveMeshEmitMode, writeMeshConfigMode, } from "../lib/mesh/live/daemon/mode.js";
42
42
  import { workMeshRoot } from "../lib/mesh/live/paths.js";
43
- import { buildInstallPaths, daemonServiceIsLoaded, daemonServiceStatus, detectPlatform, installDaemonIfStale, installDaemonService, resolveAbsoluteNodeBinary, resolveRunningCliEntry, uninstallDaemonService, } from "../lib/mesh/live/daemon/install.js";
44
- import { findAncestorHqRoot, resolveInstallHqRoot, } from "../lib/mesh/live/daemon/config.js";
43
+ import { buildInstallPaths, daemonServiceIsLoaded, daemonServiceStatus, detectPlatform, installDaemonIfStale, installDaemonService, resolveAbsoluteNodeBinary, resolveRunningCliEntry, uninstallDaemonService, installedUnitHqRoot, } from "../lib/mesh/live/daemon/install.js";
44
+ import { findAncestorHqRoot, resolveIfStaleHqRoot, resolveInstallHqRoot, } from "../lib/mesh/live/daemon/config.js";
45
+ import { daemonDir as meshDaemonDir } from "../lib/mesh/live/daemon/paths.js";
45
46
  import { collectDaemonDoctor, formatCliIdentityLines, formatDaemonDoctor, } from "../lib/mesh/live/daemon/doctor.js";
46
47
  import { readDaemonState } from "../lib/mesh/live/daemon/state.js";
47
48
  import { defaultRunCommand } from "../lib/service-manager/launchd.js";
@@ -62,6 +63,7 @@ import { deriveRemoteOwnerSlug, deriveRepoIdentityKey, } from "../lib/work-conte
62
63
  import { promptRepoCompany, } from "../lib/work-context/repo-prompt.js";
63
64
  import { requeueQuarantinedOutbox } from "../lib/work-context/outbox.js";
64
65
  import { handOffInstallHere } from "../lib/daemon/handoff.js";
66
+ import { repairServiceUnitsFromOtherHome } from "../lib/daemon/mesh-owner.js";
65
67
  import { runResidentCommandWithPackageLease } from "../utils/resident-package-preload.js";
66
68
  export function formatCheckLines(threads, company, projectId) {
67
69
  if (threads.length === 0) {
@@ -3139,6 +3141,18 @@ async function runDaemonInstall(opts) {
3139
3141
  // `hq daemon` runs mesh on this machine: installing a second unit would run it twice.
3140
3142
  // An explicit --hq-root is verified the same way as below and saved for the daemon.
3141
3143
  const explicitRoot = opts.hqRoot ? resolveInstallHqRoot({ explicit: opts.hqRoot }).root : undefined;
3144
+ if (opts.ifStale && !opts.systemUser) {
3145
+ const repair = repairServiceUnitsFromOtherHome({ home: os.homedir(), env: process.env, hqRoot: explicitRoot ?? process.env.HQ_ROOT });
3146
+ for (const message of repair.messages)
3147
+ console.error(message);
3148
+ if (repair.failed)
3149
+ process.exitCode = 1;
3150
+ if (repair.meshReplaced) {
3151
+ const message = repair.messages.join(" ");
3152
+ console.log(opts.json ? JSON.stringify({ ok: true, action: "repaired", reinstalled: true, message }) : message);
3153
+ return;
3154
+ }
3155
+ }
3142
3156
  const handedOff = opts.systemUser
3143
3157
  ? null
3144
3158
  : handOffInstallHere(["mesh"], process.env, { hqRoot: explicitRoot, ifStale: opts.ifStale });
@@ -3148,7 +3162,13 @@ async function runDaemonInstall(opts) {
3148
3162
  }
3149
3163
  // Verified root only: a repo's own .claude/ must never become the daemon's
3150
3164
  // HQ root (that path is persisted as trusted and used for attribution).
3151
- const hqRoot = resolveInstallHqRoot({ explicit: opts.hqRoot });
3165
+ const hqRoot = opts.ifStale
3166
+ ? resolveIfStaleHqRoot({
3167
+ explicit: opts.hqRoot,
3168
+ daemonDirectory: meshDaemonDir(undefined, os.homedir(), process.env),
3169
+ installedUnitRoot: installedUnitHqRoot(os.homedir()),
3170
+ })
3171
+ : resolveInstallHqRoot({ explicit: opts.hqRoot });
3152
3172
  const paths = buildInstallPaths({
3153
3173
  systemUser: opts.systemUser,
3154
3174
  hqRoot: hqRoot.root,