@indigoai-us/hq-cli 5.345.222 → 5.345.225

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 (128) hide show
  1. package/CHANGELOG.md +89 -0
  2. package/assets/bot-workers/setup/context/quick-reference.md +2 -2
  3. package/assets/mesh-daemon/README.md +11 -12
  4. package/dist/command-catalog.generated.d.ts +79 -5
  5. package/dist/command-catalog.generated.js +95 -5
  6. package/dist/commands/bot.d.ts +1 -1
  7. package/dist/commands/bot.js +34 -33
  8. package/dist/commands/cloud-provision.d.ts +4 -1
  9. package/dist/commands/cloud-provision.js +7 -3
  10. package/dist/commands/cloud-retire.js +1 -1
  11. package/dist/commands/core-delegate-w1b.js +210 -188
  12. package/dist/commands/core-delegate.d.ts +5 -0
  13. package/dist/commands/core-dm-bind-native.d.ts +5 -1
  14. package/dist/commands/core-dm-bind-native.js +4 -0
  15. package/dist/commands/core-job-notify-native.d.ts +5 -1
  16. package/dist/commands/core-job-notify-native.js +8 -2
  17. package/dist/commands/core-jobs-native.d.ts +27 -1
  18. package/dist/commands/core-jobs-native.js +49 -28
  19. package/dist/commands/core-pipeline-conductor-native.js +7 -7
  20. package/dist/commands/core-pipeline-driver-native.js +5 -5
  21. package/dist/commands/core-refresh-vault-access-native.d.ts +5 -0
  22. package/dist/commands/core-refresh-vault-access-native.js +3 -1
  23. package/dist/commands/core-work-mesh-bind-trusted-native.js +1 -1
  24. package/dist/commands/daemon.d.ts +2 -0
  25. package/dist/commands/daemon.js +67 -1
  26. package/dist/commands/lanes-hold.d.ts +2 -27
  27. package/dist/commands/lanes-hold.js +3 -75
  28. package/dist/commands/lanes-loop.js +1 -1
  29. package/dist/commands/lanes-session-start.js +2 -2
  30. package/dist/commands/mesh.d.ts +12 -0
  31. package/dist/commands/mesh.js +13 -4
  32. package/dist/commands/monitor.js +1 -1
  33. package/dist/commands/packs.js +14 -3
  34. package/dist/commands/sync-core.js +31 -12
  35. package/dist/commands/whoami.d.ts +10 -17
  36. package/dist/commands/whoami.js +7 -79
  37. package/dist/data/command-states.json +13 -0
  38. package/dist/index.js +1 -1
  39. package/dist/lib/bot/fleet-cron.d.ts +26 -3
  40. package/dist/lib/bot/fleet-cron.js +44 -4
  41. package/dist/lib/bot/run.d.ts +4 -4
  42. package/dist/lib/bot/run.js +5 -3
  43. package/dist/lib/bot/signals-engine-flag.d.ts +53 -13
  44. package/dist/lib/bot/signals-engine-flag.js +202 -9
  45. package/dist/lib/daemon/catalog.d.ts +8 -5
  46. package/dist/lib/daemon/catalog.js +13 -7
  47. package/dist/lib/daemon/config.d.ts +5 -0
  48. package/dist/lib/daemon/config.js +6 -0
  49. package/dist/lib/daemon/lanes-monitor-state.d.ts +55 -0
  50. package/dist/lib/daemon/lanes-monitor-state.js +129 -0
  51. package/dist/lib/daemon/lanes-reconcile-loader.d.ts +7 -0
  52. package/dist/lib/daemon/lanes-reconcile-loader.js +13 -0
  53. package/dist/lib/daemon/machine-checks.d.ts +45 -0
  54. package/dist/lib/daemon/machine-checks.js +95 -11
  55. package/dist/lib/daemon/merge-sections.d.ts +165 -0
  56. package/dist/lib/daemon/merge-sections.js +556 -0
  57. package/dist/lib/daemon/native-notice-ledger.d.ts +9 -0
  58. package/dist/lib/daemon/native-notice-ledger.js +43 -0
  59. package/dist/lib/daemon/ops/policy.d.ts +1 -1
  60. package/dist/lib/daemon/ops/policy.js +1 -1
  61. package/dist/lib/daemon/protocol.d.ts +1 -1
  62. package/dist/lib/daemon/protocol.js +0 -6
  63. package/dist/lib/daemon/run.js +76 -3
  64. package/dist/lib/daemon/selfcheck.js +2 -2
  65. package/dist/lib/daemon/server.d.ts +2 -4
  66. package/dist/lib/daemon/server.js +5 -48
  67. package/dist/lib/daemon/state-file.d.ts +74 -4
  68. package/dist/lib/daemon/state-file.js +159 -19
  69. package/dist/lib/daemon/supervisor.d.ts +11 -1
  70. package/dist/lib/daemon/supervisor.js +86 -0
  71. package/dist/lib/daemon/updater.d.ts +2 -6
  72. package/dist/lib/daemon/updater.js +4 -11
  73. package/dist/lib/daemon/whoami-cache.d.ts +96 -0
  74. package/dist/lib/daemon/whoami-cache.js +244 -0
  75. package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
  76. package/dist/lib/flag-registry-worker-source.generated.js +1 -1
  77. package/dist/lib/flag-registry-worker.js +33 -3
  78. package/dist/lib/flag-registry.js +13 -0
  79. package/dist/lib/hook-engine/coverage.d.ts +2 -0
  80. package/dist/lib/hook-engine/coverage.js +71 -0
  81. package/dist/lib/hook-engine/native-precompact-compatibility.json +449 -0
  82. package/dist/lib/hook-engine/reconcile.js +14 -8
  83. package/dist/lib/install/hook-target.d.ts +13 -3
  84. package/dist/lib/install/hook-target.js +14 -11
  85. package/dist/lib/lanes/envelope-repair-dispatch.js +1 -1
  86. package/dist/lib/lanes/monitor.d.ts +2 -0
  87. package/dist/lib/lanes/monitor.js +2 -1
  88. package/dist/lib/lanes/registry-flag.d.ts +6 -0
  89. package/dist/lib/lanes/registry-flag.js +3 -2
  90. package/dist/lib/lanes/repo-merge-hold.d.ts +39 -0
  91. package/dist/lib/lanes/repo-merge-hold.js +90 -0
  92. package/dist/lib/lanes/watcher-main.js +3 -3
  93. package/dist/lib/mesh/live/daemon/doctor.js +1 -1
  94. package/dist/lib/mesh/live/daemon/install.js +2 -2
  95. package/dist/lib/scan-packages/index.js +8 -9
  96. package/dist/lib/signals/engine.d.ts +8 -0
  97. package/dist/lib/signals/engine.js +15 -5
  98. package/dist/lib/sync-core/flag.d.ts +18 -0
  99. package/dist/lib/sync-core/flag.js +66 -0
  100. package/dist/lib/sync-core/reconcile.d.ts +6 -0
  101. package/dist/lib/sync-core/reconcile.js +15 -0
  102. package/dist/lib/sync-core/rollout-state.d.ts +2 -0
  103. package/dist/lib/sync-core/rollout-state.js +7 -0
  104. package/dist/lib/sync-core/vault-settings.d.ts +12 -1
  105. package/dist/lib/sync-core/vault-settings.js +23 -7
  106. package/dist/lib/windows/install-followup.js +1 -1
  107. package/dist/utils/client-health-contract.d.ts +1 -0
  108. package/dist/utils/client-health-contract.js +5 -0
  109. package/dist/utils/client-health.d.ts +2 -0
  110. package/dist/utils/client-health.js +40 -0
  111. package/dist/utils/cognito-session.d.ts +2 -14
  112. package/dist/utils/cognito-session.js +2 -40
  113. package/dist/utils/daemon-cli-version.d.ts +13 -0
  114. package/dist/utils/daemon-cli-version.js +47 -0
  115. package/dist/utils/duplicate-command-usage.js +1 -1
  116. package/dist/utils/machine-token-cache.d.ts +21 -0
  117. package/dist/utils/machine-token-cache.js +49 -0
  118. package/dist/utils/pack-contributions.d.ts +14 -2
  119. package/dist/utils/pack-contributions.js +31 -5
  120. package/dist/utils/resident-package-preload.js +4 -0
  121. package/dist/utils/whoami-identity.d.ts +54 -0
  122. package/dist/utils/whoami-identity.js +108 -0
  123. package/package.json +7 -7
  124. package/scripts/bench-core.mjs +34 -3
  125. package/dist/lib/daemon/ops/memory.d.ts +0 -18
  126. package/dist/lib/daemon/ops/memory.js +0 -65
  127. package/dist/lib/daemon/ops/mesh.d.ts +0 -38
  128. package/dist/lib/daemon/ops/mesh.js +0 -70
@@ -1,4 +1,5 @@
1
1
  /** Native implementations of the second Wave 1 delegate command family. */
2
+ import { daemonWhoamiOutput } from "../lib/daemon/whoami-cache.js";
2
3
  import { createHash, randomInt } from "node:crypto";
3
4
  import * as fs from "node:fs";
4
5
  import * as os from "node:os";
@@ -292,7 +293,8 @@ function runBundle(args, context, onMalformedWhoami) {
292
293
  const projectRelative = `companies/${company}/projects/${project}`;
293
294
  const brainstormPath = path.join(projectDir, "brainstorm.md");
294
295
  const brainstormRelative = `${projectRelative}/brainstorm.md`;
295
- const who = subprocess("hq", ["whoami", "--json"], context.cwd, { stdout: "capture" });
296
+ const cachedWho = (context.daemonWhoami ?? daemonWhoamiOutput)(true);
297
+ const who = cachedWho !== null ? { code: 0, stdout: cachedWho } : subprocess("hq", ["whoami", "--json"], context.cwd, { stdout: "capture" });
296
298
  if (who.code !== 0)
297
299
  return fail("bundle", "could not read sender identity; update hq-cli if --json is unsupported");
298
300
  let identity;
@@ -518,200 +520,219 @@ function runGrant(args, context) {
518
520
  return fail("grant", "--manifest is required");
519
521
  if (!fs.existsSync(manifestPath) || !fs.statSync(manifestPath).isFile())
520
522
  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`);
523
+ const lock = `${manifestPath}.send-lock`;
524
+ if (yes) {
525
+ try {
526
+ fs.mkdirSync(lock);
591
527
  }
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");
528
+ catch {
529
+ return fail("grant", "verification or delivery is active; retry after it finishes");
606
530
  }
607
531
  }
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;
532
+ try {
533
+ let manifest;
621
534
  try {
622
- response = JSON.parse(resolved.stdout ?? "");
535
+ manifest = readJsonFile(manifestPath);
623
536
  }
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;
537
+ catch {
538
+ return fail("grant", `manifest is not valid JSON: ${delegateDiagnosticPath(manifestPath)}`);
631
539
  }
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;
540
+ if (manifest === null || manifest === false)
541
+ return fail("grant", `manifest is not valid JSON: ${delegateDiagnosticPath(manifestPath)}`);
542
+ if (!isRecord(manifest))
543
+ return fail("grant", "manifest has no company");
544
+ const company = jqRawPath(manifest, "company");
545
+ const project = jqRawPath(manifest, "project.name");
546
+ const principal = jqRawPath(manifest, "to.principal");
547
+ const display = jqRawPaths(manifest, ["to.displayName", "to.principal"]);
548
+ const status = jqRawPath(manifest, "status");
549
+ if (!company)
550
+ return fail("grant", "manifest has no company");
551
+ if (!project)
552
+ return fail("grant", "manifest has no project.name");
553
+ if (!principal)
554
+ return fail("grant", "manifest has no to.principal");
555
+ let grantPrincipal = principal;
556
+ if (principal.startsWith("agt_")) {
557
+ const legacyGroup = "grp_dlg-" + principal.slice(-9).toLowerCase();
558
+ const nextGroup = delegationGroupId(principal);
559
+ const recordedGroup = text(getPath(manifest, "grantPrincipal"));
560
+ grantPrincipal = recordedGroup === legacyGroup || recordedGroup === nextGroup ? recordedGroup : nextGroup;
638
561
  }
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");
562
+ if (status !== "building" && status !== "granted")
563
+ return fail("grant", `manifest status is '${status}' — grants run from 'building' (or re-run from 'granted'), not from there`);
564
+ const prefixes = list(getPath(manifest, "vaultPrefixes"));
565
+ if (prefixes.length === 0)
566
+ return fail("grant", "manifest has no vaultPrefixes");
567
+ const badPrefixes = prefixes.filter((entry) => {
568
+ const prefix = jqRawPath(entry, "prefix");
569
+ return !prefix.endsWith("/") || prefix.startsWith("companies/") || prefix.startsWith("/");
570
+ }).map((entry) => jqRawPath(entry, "prefix"));
571
+ if (badPrefixes.length)
572
+ return fail("grant", `prefix violates the hq-files prefix conventions (must be company-relative folder form ending in '/'): ${badPrefixes.join("\n")}`);
573
+ out(`Delegation grant plan — company '${company}', recipient '${principal}':\n`);
574
+ if (grantPrincipal !== principal)
575
+ out(` 0. Agent recipient: grants flow through group ${grantPrincipal} (created if absent, containing exactly ${display})\n`);
576
+ out(` 1. Push companies/${company}/projects/${project}/ to the vault (on-conflict keep)\n`);
577
+ for (const entry of prefixes)
578
+ out(` 2. Grant ${jqRawPath(entry, "permission")} on ${jqRawPath(entry, "prefix")} — ${jqRawPath(entry, "reason")}\n`);
579
+ const writePrefixes = prefixes.map((entry) => jqRawPath(entry, "permission") === "write" ? jqRawPath(entry, "prefix") : "").filter(Boolean);
580
+ if (writePrefixes.length) {
581
+ 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
582
  }
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 ?? "");
583
+ if (!yes) {
584
+ out("\n");
585
+ err("hq-delegate-grant: confirmation required — re-run with --yes after the user approves\n");
586
+ return 2;
657
587
  }
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);
588
+ let result = runHq(["sync", "push", `companies/${company}/projects/${project}/`, "--company", company, "--on-conflict", "keep"], context, "inherit");
589
+ if (result.code !== 0)
590
+ return fail("grant", `vault push failed for companies/${company}/projects/${project}/`);
591
+ const referencePaths = [
592
+ ...list(getPath(manifest, "knowledge", [])),
593
+ ...list(getPath(manifest, "policies", [])),
594
+ ].filter((entry) => typeof entry === "string" && entry.startsWith(`companies/${company}/`));
595
+ for (const reference of referencePaths) {
596
+ if (fs.existsSync(path.join(context.root ?? context.cwd, reference))) {
597
+ result = runHq(["sync", "push", reference, "--company", company, "--on-conflict", "keep"], context, "inherit");
598
+ if (result.code !== 0)
599
+ return fail("grant", `vault push failed for referenced knowledge: ${reference}`);
600
+ }
601
+ else {
602
+ 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`);
603
+ }
604
+ }
605
+ if (grantPrincipal !== principal) {
606
+ result = runHq(["groups", "create", grantPrincipal, "--name", `Delegation: ${display}`, "--company", company], context, "inherit");
607
+ if (result.code !== 0)
608
+ err("hq-delegate-grant: group create reported an error (may already exist) — continuing\n");
609
+ result = runHq(["groups", "add", grantPrincipal, principal, "--company", company], context, "inherit");
610
+ if (result.code !== 0)
611
+ err("hq-delegate-grant: group add reported an error (may already be a member) — continuing\n");
612
+ const members = subprocess("hq", ["groups", "members", grantPrincipal, "--company", company], context.cwd, { env: { NO_COLOR: "1", FORCE_COLOR: "0" } });
613
+ if (members.code !== 0)
614
+ return fail("grant", "could not verify delegation group membership");
615
+ const memberIds = groupMemberIds(members.stdout ?? "");
616
+ if (memberIds === null || memberIds.length !== 1 || memberIds[0] !== principal) {
617
+ return fail("grant", "delegation group membership does not exactly match recipient");
662
618
  }
663
- value = undefined;
664
619
  }
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 };
620
+ let expectedType = "";
621
+ let expectedId = "";
622
+ let expectedCompany = "";
623
+ if (grantPrincipal.startsWith("grp_")) {
624
+ expectedType = "group";
625
+ expectedId = grantPrincipal;
670
626
  }
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;
627
+ else if (grantPrincipal === "@all") {
628
+ expectedType = "company-wide";
629
+ }
630
+ else {
631
+ const resolved = runHq(["people", "resolve", principal, "--company", company, "--json", "--membership-only"], context);
632
+ let response;
633
+ try {
634
+ response = JSON.parse(resolved.stdout ?? "");
635
+ }
636
+ catch (error) {
637
+ if (error instanceof SyntaxError) {
638
+ const input = commandSubstitutionBytes(resolved);
639
+ emitJqParseDiagnostic(input, ["-e", RESOLVE_FOUND_FILTER], context);
640
+ emitJqParseDiagnostic(input, ["-e", RESOLVE_NOT_FOUND_FILTER], context);
641
+ }
642
+ response = undefined;
643
+ }
644
+ if (isRecord(response) && response.status === "found" && isRecord(response.person) && typeof response.person.personUid === "string" && typeof response.person.companyUid === "string") {
645
+ if (resolved.code !== 0)
646
+ return fail("grant", "recipient resolution failed");
647
+ expectedType = "person";
648
+ expectedId = response.person.personUid;
649
+ expectedCompany = response.person.companyUid;
697
650
  }
651
+ else if (isRecord(response) && response.status === "not_found") {
652
+ if (principal.includes("@")) {
653
+ expectedType = "email";
654
+ expectedId = principal.toLowerCase().trim();
655
+ }
656
+ else
657
+ return fail("grant", "unresolved recipient");
658
+ }
659
+ else
660
+ return fail("grant", "authoritative recipient lookup failed; update hq-cli if --membership-only is unsupported");
698
661
  }
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 };
662
+ const readAcl = (prefix) => {
663
+ const response = runHq(["files", "acl", prefix, "--company", company, "--json"], context);
664
+ if (response.code !== 0)
665
+ return { ok: false };
666
+ let value;
667
+ try {
668
+ value = JSON.parse(response.stdout ?? "");
669
+ }
670
+ catch (error) {
671
+ if (error instanceof SyntaxError) {
672
+ const input = commandSubstitutionBytes(response);
673
+ emitJqParseDiagnostic(input, ["-e", "--arg", "prefix", prefix, "--arg", "company", expectedCompany, ACL_FILTER], context);
674
+ }
675
+ value = undefined;
676
+ }
677
+ const rawPrefix = isRecord(value) ? value.prefix : undefined;
678
+ const expectedPrefix = prefix.endsWith("/*") ? prefix.slice(0, -1) : prefix;
679
+ 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") {
680
+ err(`hq-delegate-grant: invalid structured ACL response for ${prefix}\n`);
681
+ return { ok: false };
682
+ }
683
+ return { value, ok: true };
684
+ };
685
+ const now = currentTime();
686
+ for (let i = 0; i < prefixes.length; i += 1) {
687
+ const entry = prefixes[i];
688
+ if (!isRecord(entry) || !isRecord(manifest))
689
+ return fail("grant", "manifest has an invalid vaultPrefixes entry");
690
+ const prefix = jqRawPath(entry, "prefix");
691
+ const permission = jqRawPath(entry, "permission");
692
+ const aclPattern = `${prefix}*`;
693
+ const before = readAcl(aclPattern);
694
+ if (!before.ok || !before.value)
695
+ return fail("grant", `ACL preflight failed; no share attempted for ${prefix}`);
696
+ expectedCompany = text(before.value.companyUid);
697
+ const share = runHq(["files", "share", aclPattern, "--with", grantPrincipal, "--permission", permission, "--company", company], context, "inherit");
698
+ const shareRc = share.code;
699
+ if (shareRc !== 0)
700
+ err(`hq-delegate-grant: share reported an error on ${prefix}; checking exact grant\n`);
701
+ let landed = false;
702
+ for (const delay of [0, 1, 2]) {
703
+ if (delay)
704
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, delay * 1000);
705
+ const after = readAcl(aclPattern);
706
+ if (after.ok && after.value?.exists === true && list(after.value.direct).some((row) => isRecord(row) && row.granteeType === expectedType && row.granteeId === expectedId && row.permission === permission)) {
707
+ landed = true;
708
+ break;
709
+ }
710
+ }
711
+ if (!landed)
712
+ return fail("grant", `grant outcome unconfirmed for ${principal} on ${prefix}; retain this manifest and resume`);
713
+ const current = list(manifest.vaultPrefixes)[i];
714
+ if (!isRecord(current))
715
+ return fail("grant", "manifest has an invalid vaultPrefixes entry");
716
+ current.verifiedAt = now;
717
+ current.grantReceipt = { companyUid: expectedCompany, granteeType: expectedType, granteeId: expectedId, shareExitCode: shareRc, verifiedAt: now };
718
+ writeJsonAtomically(manifestPath, manifest, true);
719
+ out(`hq-delegate-grant: verified ${permission} on ${prefix} for ${principal}\n`);
720
+ }
721
+ manifest.status = "granted";
722
+ manifest.grantPrincipal = grantPrincipal;
723
+ manifest.vaultPrefixes = list(manifest.vaultPrefixes).map((entry) => isRecord(entry) ? { ...entry, verifiedAt: now } : entry);
706
724
  writeJsonAtomically(manifestPath, manifest, true);
707
- out(`hq-delegate-grant: verified ${permission} on ${prefix} for ${principal}\n`);
725
+ out(`hq-delegate-grant: all ${prefixes.length} grants verified — manifest status advanced to 'granted'\n`);
726
+ return 0;
727
+ }
728
+ finally {
729
+ if (yes) {
730
+ try {
731
+ fs.rmdirSync(lock);
732
+ }
733
+ catch { /* Preserve the grant result. */ }
734
+ }
708
735
  }
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
736
  }
716
737
  function atomicCopy(source, target, mode) {
717
738
  const temporary = `${target}.tmp.${process.pid}.${Math.random().toString(16).slice(2)}`;
@@ -931,15 +952,6 @@ function runSend(args, context) {
931
952
  return fail("send", "--manifest is required");
932
953
  if (!fs.existsSync(manifestPath) || !fs.statSync(manifestPath).isFile())
933
954
  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
955
  const lock = `${manifestPath}.send-lock`;
944
956
  if (send) {
945
957
  try {
@@ -960,6 +972,16 @@ function runSend(args, context) {
960
972
  catch { /* Preserve the command result if a concurrent process removed it. */ }
961
973
  };
962
974
  try {
975
+ const manifest = jsonFile(manifestPath);
976
+ if (!manifest)
977
+ return fail("send", `manifest is not valid JSON: ${delegateDiagnosticPath(manifestPath)}`);
978
+ if (send) {
979
+ const publishedPath = path.join(context.root ?? context.cwd, jqRawPath(manifest, "publication.manifestPath"));
980
+ if (malformedJsonFile(publishedPath)) {
981
+ removeLock();
982
+ return runShellFallback("send", args, context);
983
+ }
984
+ }
963
985
  const bundleDir = path.dirname(path.resolve(manifestPath));
964
986
  const brief = path.join(bundleDir, "BRIEF.md");
965
987
  const prompt = path.join(bundleDir, "PICKUP-PROMPT.md");
@@ -6,6 +6,11 @@ export declare const CORE_NATIVE_DELEGATE_FLAG = "core-native-delegate";
6
6
  export type DelegateContext = {
7
7
  cwd: string;
8
8
  root?: string;
9
+ /**
10
+ * The daemon's cached `hq whoami` output (json or plain), or null to run
11
+ * `hq whoami` (hq-core-rust US-036). Default: src/lib/daemon/whoami-cache.ts.
12
+ */
13
+ daemonWhoami?: (json: boolean) => string | null;
9
14
  atomicWriteFileSystem?: DelegateAtomicWriteFileSystem;
10
15
  bundleFileSystem?: DelegateBundleFileSystem;
11
16
  };
@@ -1,10 +1,14 @@
1
- /** Native implementation of core/scripts/hq-dm-bind.sh. */
2
1
  import * as fs from "node:fs";
3
2
  import type { Command } from "commander";
4
3
  import { type UtilityOutput } from "./core-native-utilities.js";
5
4
  export declare const DM_BIND_ASSET = "core/scripts/hq-dm-bind.sh";
6
5
  export declare const DM_BIND_HELP = "# hq-dm-bind.sh \u2014 bind the current session to one HQ DM channel, post\n# structured updates to it, and listen for replies (feedback / requests).\n#\n# Usage:\n# core/scripts/hq-dm-bind.sh bind <channel> # bind + set the read cursor to \"now\"\n# core/scripts/hq-dm-bind.sh status # show the binding and cursor\n# core/scripts/hq-dm-bind.sh post --title <t> [--state <s>] [--line <l>]... [--next <l>]... [--ask <l>]... [--to <name>]... [--topic <t>] [--under <id>] [--new-thread]\n# core/scripts/hq-dm-bind.sh post --title <t> - < body.md # body from stdin (already structured)\n# core/scripts/hq-dm-bind.sh threads # list the channel's recent top-level threads (id, replies, author, text)\n# core/scripts/hq-dm-bind.sh roster # print the channel members a post will @-mention\n# core/scripts/hq-dm-bind.sh poll # print new messages since the cursor, advance it\n# core/scripts/hq-dm-bind.sh listen [--interval 60] [--timeout 1800]\n# # block until a new message arrives (or timeout)\n# core/scripts/hq-dm-bind.sh unbind\n#\n# The binding lives in the session's meta.yaml (`dm_channel`) via hq-session.sh;\n# the cursor is `workspace/sessions/<sid>/dm-bind.cursor` (the last seen sort\n# key from `hq dm channel --json`). `listen` is meant to run detached\n# (Bash run_in_background): it exits 0 and prints the new messages the moment\n# one lands, exits 3 on timeout with nothing new.\n#\n# Every post opens with an @-mention of every other member of the channel, so\n# the update reaches people (HQ mentions are structured: the `hq` CLI resolves\n# the `@\"Display Name\"` tokens against the roster and sends the real mention\n# list; an unresolvable name fails the post rather than posting text that looks\n# addressed but is not). The CLI rewrites a resolved `@\"Display Name\"` token to\n# `@Display Name`, so the room never shows the quotes.\n#\n# Posts thread by topic. The first post on a topic (`--topic`, else the title)\n# is a top-level root; every later post on the same topic in this session goes\n# out as a reply under it. `--under <id>` replies under an existing thread that\n# someone else (or an earlier session) started \u2014 a top-level post is only for a\n# subject the channel has no thread for yet. `--new-thread` starts a fresh root. The topic \u2192 root\n# map is `workspace/sessions/<sid>/dm-bind.threads`.\n#\n# A post ALWAYS mentions someone. `--to <name>` (repeatable) narrows the line to\n# the named members, for a reply to one person; without it the line names every\n# other human member (bots are left out unless named with --to, because a tagged\n# bot wakes and replies). There is no way to post unmentioned: an update nobody is\n# notified about does not get read. `post` refuses when the roster cannot be\n# read rather than sending a silent update.\n#\n# Post format (kept deliberately plain \u2014 see .claude/skills/dm-bind/SKILL.md):\n# @\"Ada Lovelace\" @\"Grace Hopper\"\n#\n# <title> \u2014 <state>\n#\n# \u2022 line\n# \u2022 line\n#\n# Next: line\n# Need from you: line\n";
7
6
  export type DmBindDeps = {
7
+ /**
8
+ * The daemon's cached `hq whoami` output (json or plain), or null to run
9
+ * `hq whoami` (hq-core-rust US-036). Default: src/lib/daemon/whoami-cache.ts.
10
+ */
11
+ daemonWhoami?: (json: boolean) => string | null;
8
12
  root: string;
9
13
  cwd: string;
10
14
  env: NodeJS.ProcessEnv;
@@ -1,4 +1,5 @@
1
1
  /** Native implementation of core/scripts/hq-dm-bind.sh. */
2
+ import { daemonWhoamiOutput } from "../lib/daemon/whoami-cache.js";
2
3
  import * as fs from "node:fs";
3
4
  import * as os from "node:os";
4
5
  import * as path from "node:path";
@@ -177,6 +178,9 @@ function usesCliAuth(d) {
177
178
  }
178
179
  }
179
180
  function whoamiText(d, json = false) {
181
+ const cached = (d.daemonWhoami ?? ((asJson) => daemonWhoamiOutput(asJson, d.env)))(json);
182
+ if (cached !== null)
183
+ return cached;
180
184
  const result = d.runHq(json ? ["whoami", "--json"] : ["whoami"], { ...d.env, HQ_ROOT: d.root });
181
185
  return result.code === 0 ? result.stdout : "";
182
186
  }
@@ -1,4 +1,3 @@
1
- /** Native TypeScript port of hq-job-notify.sh. */
2
1
  import { Command } from "commander";
3
2
  type Environment = Record<string, string | undefined>;
4
3
  export type JobNotifyProcessResult = {
@@ -12,6 +11,11 @@ export type JobNotifyRunOptions = {
12
11
  logPath?: string;
13
12
  };
14
13
  export type JobNotifyDependencies = {
14
+ /**
15
+ * The daemon's cached `hq whoami` output (json or plain), or null to run
16
+ * `hq whoami` (hq-core-rust US-036). Default: src/lib/daemon/whoami-cache.ts.
17
+ */
18
+ daemonWhoami?: (json: boolean) => string | null;
15
19
  env: Environment;
16
20
  cwd: string;
17
21
  now: () => Date;
@@ -1,3 +1,5 @@
1
+ /** Native TypeScript port of hq-job-notify.sh. */
2
+ import { daemonWhoamiOutput } from "../lib/daemon/whoami-cache.js";
1
3
  import * as fs from "node:fs";
2
4
  import * as os from "node:os";
3
5
  import * as path from "node:path";
@@ -205,12 +207,16 @@ const COGNITO_SUB = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{1
205
207
  * to the signed-in identity's email when `hq whoami --json` reports the same
206
208
  * subject, directly or as the human an Outpost session acts for.
207
209
  */
210
+ function cachedWhoami(deps, json) {
211
+ return (deps.daemonWhoami ?? ((asJson) => daemonWhoamiOutput(asJson, deps.env)))(json);
212
+ }
208
213
  function resolveCognitoOwner(owner, deps) {
209
214
  if (!deps.commandExists("hq"))
210
215
  return "";
211
216
  let parsed;
212
217
  try {
213
- const raw = deps.run("hq", ["whoami", "--json"], { cwd: deps.cwd, env: deps.env, captureStdout: true }).stdout;
218
+ const raw = cachedWhoami(deps, true)
219
+ ?? deps.run("hq", ["whoami", "--json"], { cwd: deps.cwd, env: deps.env, captureStdout: true }).stdout;
214
220
  const value = JSON.parse(raw);
215
221
  if (!value || typeof value !== "object" || Array.isArray(value))
216
222
  return "";
@@ -285,7 +291,7 @@ export function runJobNotify(argv, options = {}) {
285
291
  if (!owner || owner === "null") {
286
292
  owner = "";
287
293
  if (deps.commandExists("hq")) {
288
- owner = emailFromWhoami(deps.run("hq", ["whoami"], {
294
+ owner = emailFromWhoami(cachedWhoami(deps, false) ?? deps.run("hq", ["whoami"], {
289
295
  cwd: deps.cwd, env: deps.env, captureStdout: true,
290
296
  }).stdout);
291
297
  }
@@ -1,4 +1,3 @@
1
- /** Native TypeScript ports for the Wave 4a scheduled-jobs scaffold tools. */
2
1
  import { Command } from "commander";
3
2
  export { detectHostTimezone, runScheduleParse, type ScheduleParseWriters } from "./core-jobs-schedule.js";
4
3
  export declare function validateJobs(args: string[]): number;
@@ -9,6 +8,11 @@ type ReconcileCommandResult = {
9
8
  };
10
9
  export type ReconcileRunner = (command: string, args: string[]) => ReconcileCommandResult;
11
10
  export type ReconcileOptions = {
11
+ /**
12
+ * The daemon's cached `hq whoami` output (json or plain), or null to run
13
+ * `hq whoami` (hq-core-rust US-036). Default: src/lib/daemon/whoami-cache.ts.
14
+ */
15
+ daemonWhoami?: (json: boolean) => string | null;
12
16
  schedulerRunner?: ReconcileRunner;
13
17
  commandRunner?: ReconcileRunner;
14
18
  identityFileReader?: (file: string) => string | undefined;
@@ -23,6 +27,28 @@ export type ReconcileOptions = {
23
27
  * exists, point systemctl at it. Caller-provided values are kept.
24
28
  */
25
29
  export declare function withUserBusEnvironment(env: NodeJS.ProcessEnv, uid: number | undefined, runtimeBase?: string, exists?: (file: string) => boolean): NodeJS.ProcessEnv;
30
+ /**
31
+ * How a PATH value is separated and which of its entries are absolute. The
32
+ * host's own rules by default: `:` and a leading `/` on POSIX, `;` and a drive
33
+ * or UNC root on Windows. Read with the POSIX rules, a Windows PATH has no
34
+ * entry left, so the service PATH was empty there and no `hq` was ever found.
35
+ */
36
+ export type ServicePathRules = {
37
+ delimiter: string;
38
+ isAbsolute: (entry: string) => boolean;
39
+ };
40
+ /**
41
+ * One `hq` lookup for the service PATH and the unit's ExecStart. ExecStart
42
+ * uses the PATH entry as found (`hq`), not its realpath: mise and Volta
43
+ * install `hq` as a symlink to one multi-call shim that dispatches on argv[0],
44
+ * so exec'ing the symlink target would run the shim as itself instead of as
45
+ * `hq`. `servicePath` is the absolute, de-duplicated entries of `pathValue`,
46
+ * with the real directory of that `hq` in front when it is not already listed.
47
+ */
48
+ export declare function resolveServicePath(pathValue: string | undefined, rules?: ServicePathRules): {
49
+ servicePath: string;
50
+ hq: string | undefined;
51
+ };
26
52
  export declare function runReconcile(argv: string[], rootArg?: string, options?: ReconcileOptions): Promise<number>;
27
53
  export declare function registerCoreJobsNativeCommand(core: Command): void;
28
54
  export declare function rawArgumentsForCommand(command: Command, fallback: string[], raw?: string[]): string[];