@indigoai-us/hq-cli 5.345.225 → 5.345.228

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 (164) hide show
  1. package/CHANGELOG.md +174 -0
  2. package/dist/command-catalog.generated.d.ts +215 -0
  3. package/dist/command-catalog.generated.js +261 -0
  4. package/dist/commands/auth.d.ts +2 -2
  5. package/dist/commands/auth.js +3 -3
  6. package/dist/commands/core-delegate-w1b.js +92 -69
  7. package/dist/commands/core-delegate.d.ts +19 -1
  8. package/dist/commands/core-delegate.js +411 -6
  9. package/dist/commands/core-dm-bind-native.js +2 -1
  10. package/dist/commands/core-handoff.d.ts +5 -0
  11. package/dist/commands/core-handoff.js +1008 -14
  12. package/dist/commands/core-pin-native.d.ts +1 -0
  13. package/dist/commands/core-pin-native.js +3 -15
  14. package/dist/commands/core-register-project-native.d.ts +6 -0
  15. package/dist/commands/core-register-project-native.js +182 -52
  16. package/dist/commands/core-work-mesh-bind-trusted-native.js +4 -9
  17. package/dist/commands/daemon.js +3 -3
  18. package/dist/commands/deploy-domains.js +38 -2
  19. package/dist/commands/index-cmd.d.ts +3 -1
  20. package/dist/commands/index-cmd.js +12 -0
  21. package/dist/commands/lanes-accounts.d.ts +14 -0
  22. package/dist/commands/lanes-accounts.js +119 -0
  23. package/dist/commands/lanes-checks.js +1 -1
  24. package/dist/commands/lanes-move.js +10 -0
  25. package/dist/commands/lanes-session-start.d.ts +1 -2
  26. package/dist/commands/lanes-session-start.js +9 -145
  27. package/dist/commands/lanes-shared.d.ts +3 -0
  28. package/dist/commands/lanes-shared.js +9 -0
  29. package/dist/commands/lanes.d.ts +3 -0
  30. package/dist/commands/lanes.js +231 -39
  31. package/dist/commands/link.d.ts +8 -3
  32. package/dist/commands/link.js +14 -17
  33. package/dist/commands/mcp-registration.d.ts +65 -7
  34. package/dist/commands/mcp-registration.js +289 -51
  35. package/dist/commands/mesh.d.ts +12 -0
  36. package/dist/commands/mesh.js +92 -10
  37. package/dist/commands/reindex.js +6 -0
  38. package/dist/commands/repo.d.ts +13 -0
  39. package/dist/commands/repo.js +39 -1
  40. package/dist/commands/sync-held.d.ts +22 -0
  41. package/dist/commands/sync-held.js +167 -18
  42. package/dist/commands/sync-mode.d.ts +3 -1
  43. package/dist/commands/sync-mode.js +11 -1
  44. package/dist/hq-cloud-sync-runner/bin/sync-runner.js +4845 -2524
  45. package/dist/hq-cloud-sync-runner/package.json +1 -1
  46. package/dist/lazy-commands.js +3 -4
  47. package/dist/lib/capacity/accounts.d.ts +4 -0
  48. package/dist/lib/capacity/accounts.js +4 -0
  49. package/dist/lib/capacity/route.js +14 -0
  50. package/dist/lib/capacity/sign-in.d.ts +18 -0
  51. package/dist/lib/capacity/sign-in.js +34 -1
  52. package/dist/lib/checkpoint-ontology/entity-file.js +4 -4
  53. package/dist/lib/checkpoint-ontology/merge-copies.js +7 -11
  54. package/dist/lib/checkpoint-ontology/plan.js +2 -1
  55. package/dist/lib/core-utils/archive-old-threads.js +5 -2
  56. package/dist/lib/core-utils/session-company.d.ts +13 -1
  57. package/dist/lib/core-utils/session-company.js +75 -4
  58. package/dist/lib/core-utils/worktree-resume.d.ts +6 -0
  59. package/dist/lib/core-utils/worktree-resume.js +8 -4
  60. package/dist/lib/daemon/background-qos.d.ts +7 -0
  61. package/dist/lib/daemon/background-qos.js +13 -0
  62. package/dist/lib/daemon/catalog.d.ts +10 -0
  63. package/dist/lib/daemon/catalog.js +9 -2
  64. package/dist/lib/daemon/hook-requests-acl-suggest.d.ts +18 -0
  65. package/dist/lib/daemon/hook-requests-acl-suggest.js +245 -0
  66. package/dist/lib/daemon/hook-requests-fleet-session-start.d.ts +32 -0
  67. package/dist/lib/daemon/hook-requests-fleet-session-start.js +214 -0
  68. package/dist/lib/daemon/hook-requests-mesh-tool-writes.d.ts +44 -0
  69. package/dist/lib/daemon/hook-requests-mesh-tool-writes.js +292 -0
  70. package/dist/lib/daemon/hook-requests-mesh.d.ts +54 -0
  71. package/dist/lib/daemon/hook-requests-mesh.js +559 -0
  72. package/dist/lib/daemon/hook-requests.d.ts +417 -0
  73. package/dist/lib/daemon/hook-requests.js +1747 -0
  74. package/dist/lib/daemon/lanes-reconcile-status.d.ts +35 -0
  75. package/dist/lib/daemon/lanes-reconcile-status.js +86 -0
  76. package/dist/lib/daemon/machine-checks.d.ts +12 -2
  77. package/dist/lib/daemon/machine-checks.js +27 -10
  78. package/dist/lib/daemon/merge-sections.d.ts +24 -2
  79. package/dist/lib/daemon/merge-sections.js +58 -16
  80. package/dist/lib/daemon/ops/policy.d.ts +1 -1
  81. package/dist/lib/daemon/ops/policy.js +47 -6
  82. package/dist/lib/daemon/resolver.js +9 -2
  83. package/dist/lib/daemon/run.d.ts +11 -7
  84. package/dist/lib/daemon/run.js +195 -18
  85. package/dist/lib/daemon/search-index-worker-v1.d.ts +2 -0
  86. package/dist/lib/daemon/search-index-worker-v1.js +25 -0
  87. package/dist/lib/daemon/server.js +6 -1
  88. package/dist/lib/daemon/session-registry.d.ts +0 -1
  89. package/dist/lib/daemon/session-registry.js +0 -3
  90. package/dist/lib/daemon/supervisor.d.ts +5 -1
  91. package/dist/lib/daemon/supervisor.js +1 -1
  92. package/dist/lib/daemon/tcc-eperm.d.ts +59 -4
  93. package/dist/lib/daemon/tcc-eperm.js +110 -8
  94. package/dist/lib/doctor/fix/process-identity.d.ts +20 -2
  95. package/dist/lib/doctor/fix/process-identity.js +48 -5
  96. package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
  97. package/dist/lib/flag-registry-worker-source.generated.js +1 -1
  98. package/dist/lib/hook-engine/canary-gate.js +1 -0
  99. package/dist/lib/hook-engine/native-stop-compatibility.json +2 -1
  100. package/dist/lib/hot-channels/adapters/attio.js +2 -1
  101. package/dist/lib/hot-channels/adapters/meetings.js +2 -1
  102. package/dist/lib/lanes/account-company.d.ts +7 -1
  103. package/dist/lib/lanes/account-company.js +22 -4
  104. package/dist/lib/lanes/account-ownership.d.ts +65 -0
  105. package/dist/lib/lanes/account-ownership.js +134 -0
  106. package/dist/lib/lanes/accounts.js +9 -2
  107. package/dist/lib/lanes/claude-balance.js +9 -3
  108. package/dist/lib/lanes/company-outposts.d.ts +37 -0
  109. package/dist/lib/lanes/company-outposts.js +164 -0
  110. package/dist/lib/lanes/config.js +17 -0
  111. package/dist/lib/lanes/host-capacity.d.ts +19 -0
  112. package/dist/lib/lanes/host-capacity.js +37 -0
  113. package/dist/lib/lanes/liveness.d.ts +6 -0
  114. package/dist/lib/lanes/liveness.js +49 -8
  115. package/dist/lib/lanes/orphan-report.d.ts +15 -0
  116. package/dist/lib/lanes/orphan-report.js +223 -0
  117. package/dist/lib/lanes/orphan-sweep.d.ts +26 -0
  118. package/dist/lib/lanes/orphan-sweep.js +152 -0
  119. package/dist/lib/lanes/reaper.d.ts +2 -0
  120. package/dist/lib/lanes/reaper.js +11 -8
  121. package/dist/lib/lanes/reconcile.d.ts +8 -7
  122. package/dist/lib/lanes/reconcile.js +83 -3
  123. package/dist/lib/lanes/spawn.d.ts +0 -10
  124. package/dist/lib/lanes/spawn.js +51 -1
  125. package/dist/lib/lanes/types.d.ts +12 -0
  126. package/dist/lib/mesh/live/backfill-held.d.ts +13 -0
  127. package/dist/lib/mesh/live/backfill-held.js +23 -0
  128. package/dist/lib/mesh/live/daemon/mode.d.ts +8 -4
  129. package/dist/lib/mesh/live/daemon/mode.js +8 -4
  130. package/dist/lib/mesh/live/daemon/run.d.ts +14 -3
  131. package/dist/lib/mesh/live/daemon/run.js +116 -7
  132. package/dist/lib/mesh/live/direct-drain.d.ts +123 -0
  133. package/dist/lib/mesh/live/direct-drain.js +315 -0
  134. package/dist/lib/mesh/live/emit-replay.d.ts +10 -0
  135. package/dist/lib/mesh/live/emit-replay.js +10 -0
  136. package/dist/lib/mesh/live/flush.d.ts +15 -0
  137. package/dist/lib/mesh/live/flush.js +27 -0
  138. package/dist/lib/mesh/live/liveness-carry.d.ts +45 -0
  139. package/dist/lib/mesh/live/liveness-carry.js +141 -0
  140. package/dist/lib/mesh/live/spool.d.ts +19 -0
  141. package/dist/lib/mesh/live/spool.js +80 -0
  142. package/dist/lib/safe-store.d.ts +2 -0
  143. package/dist/lib/safe-store.js +8 -6
  144. package/dist/lib/search-index/index.d.ts +9 -3
  145. package/dist/lib/search-index/index.js +35 -10
  146. package/dist/lib/search-index/worker-process.d.ts +9 -0
  147. package/dist/lib/search-index/worker-process.js +171 -0
  148. package/dist/lib/session-company-lock.d.ts +3 -1
  149. package/dist/lib/session-company-lock.js +3 -2
  150. package/dist/utils/delegate-command-supervisor.d.ts +3 -0
  151. package/dist/utils/delegate-command-supervisor.js +44 -0
  152. package/dist/utils/delegate-lock.d.ts +12 -0
  153. package/dist/utils/delegate-lock.js +88 -0
  154. package/dist/utils/frontmatter.d.ts +27 -0
  155. package/dist/utils/frontmatter.js +33 -0
  156. package/dist/utils/hook-trust.d.ts +1 -0
  157. package/dist/utils/hook-trust.js +18 -2
  158. package/dist/utils/host-registration.d.ts +13 -1
  159. package/dist/utils/host-registration.js +98 -5
  160. package/dist/utils/package-use-lease.d.ts +1 -1
  161. package/dist/utils/package-use-lease.js +15 -7
  162. package/docs/anywhere-runtime.md +17 -0
  163. package/package.json +9 -8
  164. package/scripts/check-function-manifest.mjs +17 -3
@@ -8,6 +8,7 @@ export type PinDependencies = {
8
8
  now: () => Date;
9
9
  tmpDir?: string;
10
10
  };
11
+ /** The shared session-id resolver (US-030 c2): env keys first, then workspace/sessions/.current. */
11
12
  export declare function resolvePinSessionId(root: string, env: NodeJS.ProcessEnv): string;
12
13
  export declare function runPin(args: string[], deps: PinDependencies): UtilityOutput;
13
14
  export declare function registerCorePinNative(core: Command): void;
@@ -2,6 +2,7 @@
2
2
  import * as fs from "node:fs";
3
3
  import * as os from "node:os";
4
4
  import * as path from "node:path";
5
+ import { resolveSessionId } from "../lib/core-utils/session-id.js";
5
6
  import { resolveLiveRoot } from "../utils/hq-roots.js";
6
7
  import { bundledShellUnboundValue, registerNativeUtility, utilityError } from "./core-native-utilities.js";
7
8
  export const PIN_ASSET = "core/scripts/hq-pin.sh";
@@ -20,23 +21,10 @@ export const PIN_HELP = `# hq-pin.sh — anchor the current session to one goal
20
21
  #
21
22
  # Storage: workspace/sessions/<sid>/pin.md plus \`pin: <goal>\` in the session's
22
23
  `;
23
- const SESSION_ENV_KEYS = ["HQ_SESSION_ID", "CLAUDE_CODE_SESSION_ID", "CLAUDE_SESSION_ID", "CODEX_SESSION_ID", "CODEX_THREAD_ID", "GROK_SESSION_ID", "HQ_FLEET_SESSION_ID"];
24
24
  const stamp = (date) => date.toISOString().replace(/\.\d{3}Z$/, "Z");
25
- function normalizeId(value) { return value.replace(/[\t\n\v\f\r ]/g, ""); }
26
- function validId(value) { return value !== "" && value !== "." && value !== ".." && /^[A-Za-z0-9._-]+$/.test(value); }
25
+ /** The shared session-id resolver (US-030 c2): env keys first, then workspace/sessions/.current. */
27
26
  export function resolvePinSessionId(root, env) {
28
- for (const key of SESSION_ENV_KEYS) {
29
- const value = normalizeId(env[key] ?? "");
30
- if (validId(value))
31
- return value;
32
- }
33
- try {
34
- const value = normalizeId(fs.readFileSync(path.join(root, "workspace/sessions/.current"), "utf8"));
35
- return validId(value) ? value : "";
36
- }
37
- catch {
38
- return "";
39
- }
27
+ return resolveSessionId(root, env);
40
28
  }
41
29
  function pinPath(deps, sid) { return path.join(deps.root, "workspace/sessions", sid, "pin.md"); }
42
30
  function fail(message) { return utilityError(`hq-pin: ${message}`, 2); }
@@ -17,7 +17,13 @@ export type RegisterProjectDeps = {
17
17
  stdout: string;
18
18
  stderr: string;
19
19
  };
20
+ /** Runs `bash <script> get company_slug`; code is null when it did not exit normally. */
21
+ runSession?: (script: string, env: NodeJS.ProcessEnv, cwd: string) => {
22
+ code: number | null;
23
+ stdout: string;
24
+ };
20
25
  };
26
+ export declare function createRegisterProjectSessionRunner(spawn?: typeof spawnSync): NonNullable<RegisterProjectDeps["runSession"]>;
21
27
  export declare function createRegisterProjectHqRunner(spawn?: typeof spawnSync): RegisterProjectDeps["runHq"];
22
28
  type NativeResult = {
23
29
  code: number;
@@ -7,8 +7,20 @@ import { serializeJqJson } from "../lib/core-utils/jq-json-serializer.js";
7
7
  import { resolveBundledAsset } from "../utils/hq-roots-core.js";
8
8
  import { buildSpawnPlan } from "../utils/windows-spawn.js";
9
9
  export const REGISTER_PROJECT_ASSET = "core/scripts/register-project.sh";
10
- const USAGE = "usage: register-project.sh <company> <project> | --brainstorm <company> <board-project-id> | --audit <company> | --backfill <company> --only-active [--yes] | --retry-pending <company>";
10
+ const USAGE = "usage: register-project.sh <company> <project> | --board <company> <board-project-id> | --audit <company> | --backfill <company> --only-active [--yes] | --retry-pending <company>";
11
11
  const MIN_HQ_CLI = "5.139.0";
12
+ // hq-session.sh answers from local files; a hung answer must not hang
13
+ // registration. A run that does not finish in time counts as no answer.
14
+ const SESSION_TIMEOUT_MS = 10_000;
15
+ export function createRegisterProjectSessionRunner(spawn = spawnSync) {
16
+ return (script, env, cwd) => {
17
+ const result = spawn("bash", [script, "get", "company_slug"], {
18
+ cwd, env, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: SESSION_TIMEOUT_MS,
19
+ });
20
+ return { code: result.error ? null : result.status, stdout: String(result.stdout ?? "") };
21
+ };
22
+ }
23
+ const defaultRunSession = createRegisterProjectSessionRunner();
12
24
  export function createRegisterProjectHqRunner(spawn = spawnSync) {
13
25
  return (args, options) => {
14
26
  const plan = buildSpawnPlan("hq", args);
@@ -45,50 +57,140 @@ function readJson(fileSystem, file) {
45
57
  return JSON.parse(fileSystem.readFileSync(file, "utf8"));
46
58
  }
47
59
  function timestamp(deps) { return deps.now().toISOString().replace(/\.\d{3}Z$/, "Z"); }
48
- function companyUid(company, deps) {
49
- const direct = deps.env.HQ_COMPANY_UID ?? "";
50
- if (direct)
51
- return direct;
52
- const file = path.join(deps.root, "companies", company, ".company-uid");
60
+ class UidSourceUnreadable extends Error {
61
+ relative;
62
+ constructor(relative) {
63
+ super(relative);
64
+ this.relative = relative;
65
+ }
66
+ }
67
+ // awk's [[:space:]]: space, tab, newline, vertical tab, form feed, carriage return.
68
+ const AWK_TRAILING_SPACE = /[ \t\n\v\f\r]+$/u;
69
+ const AWK_COMPANIES_LINE = /^companies:[ \t\n\v\f\r]*$/u;
70
+ const AWK_UNINDENTED_LINE = /^[^ \t\n\v\f\r]/u;
71
+ function stripBlanks(value) { return value.replace(/[\s\u0085\u00a0]+/g, ""); }
72
+ function awkFields(line) { return line.split(/[\t ]+/u).filter((field) => field !== ""); }
73
+ function missingPath(err) {
74
+ const code = err?.code;
75
+ return code === "ENOENT" || code === "ENOTDIR";
76
+ }
77
+ /** Contents of `file` when it is a regular file (`[ -f ]`), null when it is not. */
78
+ function readUidSource(file, relative, deps) {
79
+ let stat;
53
80
  try {
54
- const fromFile = deps.fs.readFileSync(file, "utf8").replace(/[\s\u0085\u00a0]+/g, "");
55
- if (fromFile)
56
- return fromFile;
81
+ stat = deps.fs.statSync(file);
57
82
  }
58
- catch { /* shell falls through to companies/manifest.yaml */ }
59
- const manifest = path.join(deps.root, "companies", "manifest.yaml");
60
- let contents;
83
+ catch (err) {
84
+ if (missingPath(err))
85
+ return null;
86
+ throw new UidSourceUnreadable(relative);
87
+ }
88
+ if (!stat.isFile())
89
+ return null;
61
90
  try {
62
- contents = deps.fs.readFileSync(manifest, "utf8");
91
+ return deps.fs.readFileSync(file, "utf8");
63
92
  }
64
93
  catch {
65
- return null;
94
+ throw new UidSourceUnreadable(relative);
66
95
  }
96
+ }
97
+ /** The reference's recorded_uid awk over companies/manifest.yaml (lines 82-90). */
98
+ function manifestCloudUid(contents, company) {
67
99
  let inCompanies = false;
68
100
  let inCompany = false;
69
- for (const line of contents.split(/\r?\n/u)) {
70
- if (/^companies:[\t ]*$/u.test(line)) {
101
+ for (const line of contents.split("\n")) {
102
+ if (AWK_COMPANIES_LINE.test(line)) {
71
103
  inCompanies = true;
72
104
  continue;
73
105
  }
74
- if (inCompanies && /^[^\t ]/u.test(line)) {
106
+ if (inCompanies && AWK_UNINDENTED_LINE.test(line))
75
107
  inCompanies = false;
76
- inCompany = false;
77
- }
78
108
  if (inCompanies && /^ {2}[^ #][^:]*:/u.test(line)) {
79
- const slug = line.trim().split(/[\t ]+/u, 1)[0]?.replace(/:$/u, "");
80
- inCompany = slug === company;
109
+ inCompany = (awkFields(line)[0] ?? "").replace(AWK_TRAILING_SPACE, "").replace(/:$/u, "") === company;
81
110
  continue;
82
111
  }
83
- if (inCompany && /^ {2}[^\t ]/u.test(line))
84
- break;
112
+ if (inCompany && /^ {2}[^ \t\n\v\f\r#]/u.test(line))
113
+ return "";
85
114
  if (inCompany) {
86
- const fields = line.trim().split(/[\t ]+/u);
87
- if (fields[0] === "cloud_uid:" && fields[1])
88
- return fields[1].replace(/["']/gu, "").replace(/[\t ]+$/u, "");
115
+ const fields = awkFields(line);
116
+ if (fields[0] === "cloud_uid:")
117
+ return (fields[1] ?? "").replace(/["']/gu, "").replace(AWK_TRAILING_SPACE, "");
89
118
  }
90
119
  }
91
- return null;
120
+ return "";
121
+ }
122
+ function recordedUid(company, deps) {
123
+ const own = readUidSource(path.join(deps.root, "companies", company, ".company-uid"), `companies/${company}/.company-uid`, deps);
124
+ // An existing .company-uid is the answer even when it is blank (ref lines 76-79).
125
+ if (own !== null)
126
+ return stripBlanks(own);
127
+ const manifest = readUidSource(path.join(deps.root, "companies", "manifest.yaml"), "companies/manifest.yaml", deps);
128
+ return manifest === null ? "" : manifestCloudUid(manifest, company);
129
+ }
130
+ function activeCompanySlug(deps) {
131
+ const slug = deps.env.HQ_COMPANY_SLUG ?? "";
132
+ if (slug)
133
+ return slug;
134
+ const script = path.join(deps.root, "core", "scripts", "hq-session.sh");
135
+ if (!isFile(script, deps))
136
+ return "";
137
+ const answer = (deps.runSession ?? defaultRunSession)(script, { ...deps.env, HQ_ROOT: deps.root, HQ_HQ_SESSION_NO_CLI: "1" }, deps.cwd);
138
+ // The reference keeps whatever a failed run printed (`|| true`); a failed or
139
+ // timed-out answer is no answer here.
140
+ return answer.code === 0 ? stripBlanks(answer.stdout) : "";
141
+ }
142
+ function uidRecordedElsewhere(company, uid, deps) {
143
+ const companies = path.join(deps.root, "companies");
144
+ let names;
145
+ try {
146
+ names = deps.fs.readdirSync(companies).map(String).sort();
147
+ }
148
+ catch (err) {
149
+ if (!missingPath(err))
150
+ throw new UidSourceUnreadable("companies");
151
+ names = [];
152
+ }
153
+ for (const name of names) {
154
+ if (name.startsWith(".") || name === company)
155
+ continue;
156
+ const recorded = readUidSource(path.join(companies, name, ".company-uid"), `companies/${name}/.company-uid`, deps);
157
+ if (recorded !== null && stripBlanks(recorded) === uid)
158
+ return true;
159
+ }
160
+ const manifest = readUidSource(path.join(companies, "manifest.yaml"), "companies/manifest.yaml", deps);
161
+ if (manifest === null)
162
+ return false;
163
+ return manifest.replace(/\r/gu, "").split("\n").some((line) => {
164
+ const fields = awkFields(line);
165
+ return fields[0] === "cloud_uid:" && (fields[1] ?? "").replace(/["']/gu, "") === uid;
166
+ });
167
+ }
168
+ function activeCompanyEnvUid(company, deps) {
169
+ const envUid = deps.env.HQ_COMPANY_UID ?? "";
170
+ if (!/^cmp_[A-Za-z0-9]{3,128}$/u.test(envUid))
171
+ return "";
172
+ const active = activeCompanySlug(deps);
173
+ if (!active || active !== company)
174
+ return "";
175
+ return uidRecordedElsewhere(company, envUid, deps) ? "" : envUid;
176
+ }
177
+ function resolveUid(company, deps) {
178
+ try {
179
+ const recorded = recordedUid(company, deps);
180
+ if (!recorded) {
181
+ const envUid = activeCompanyEnvUid(company, deps);
182
+ return envUid ? { uid: envUid } : { refusal: `no company uid for ${company} (set companies/${company}/.company-uid or manifest cloud_uid, or run with HQ_COMPANY_UID while ${company} is the active company)` };
183
+ }
184
+ const envUid = deps.env.HQ_COMPANY_UID ?? "";
185
+ if (envUid && envUid !== recorded)
186
+ return { refusal: `HQ_COMPANY_UID does not match ${company}'s recorded uid; refusing to register into another company's Work Mesh` };
187
+ return { uid: recorded };
188
+ }
189
+ catch (err) {
190
+ if (err instanceof UidSourceUnreadable)
191
+ return { refusal: `registration refused: cannot read ${err.relative} to decide ${company}'s company uid` };
192
+ throw err;
193
+ }
92
194
  }
93
195
  function boardPath(company, deps) { return path.join(deps.root, "companies", company, "board.json"); }
94
196
  function runHelpProbe(deps) {
@@ -200,6 +302,9 @@ function ensureOne(company, project, deps) {
200
302
  const ambiguous = ambiguousBoardMatch(company, project, deps, (row) => matchesProject(row, project, prdRel, meshProject));
201
303
  if (ambiguous)
202
304
  return ambiguous;
305
+ const resolved = resolveUid(company, deps);
306
+ if (resolved.refusal !== undefined)
307
+ return errorResult(resolved.refusal);
203
308
  if (!runHelpProbe(deps)) {
204
309
  try {
205
310
  markPending(company, project, deps);
@@ -213,7 +318,7 @@ function ensureOne(company, project, deps) {
213
318
  ? `${deps.root.replace(/[\\/]+$/u, "")}/companies/${company}/projects/${project}/prd.json`
214
319
  : prd;
215
320
  const ensure = deps.runHq(["mesh", "project", "ensure", meshProject, "--company", company, "--stories-file", hqPrd, "--json"], {
216
- cwd: deps.cwd, env: deps.env, capture: true,
321
+ cwd: deps.cwd, env: { ...deps.env, HQ_COMPANY_UID: resolved.uid }, capture: true,
217
322
  });
218
323
  if (ensure.code !== 0)
219
324
  return errorResult(`registration incomplete: hq mesh project ensure failed for ${company}/${project}`);
@@ -270,8 +375,11 @@ function ensureOne(company, project, deps) {
270
375
  return { code: 0, stdout: `registered ${company}/${project} thread=${thread} channel=${channel}\n`, stderr: "" };
271
376
  }
272
377
  function registerBrainstorm(company, project, deps) {
273
- if (!companyUid(company, deps))
274
- return errorResult(`no company uid for ${company} (set HQ_COMPANY_UID, companies/${company}/.company-uid, or manifest cloud_uid)`);
378
+ // Pin the child CLI to the named company's uid so an ambient or cached
379
+ // company context cannot send this Board entry to another company's mesh.
380
+ const resolved = resolveUid(company, deps);
381
+ if (resolved.refusal !== undefined)
382
+ return errorResult(resolved.refusal);
275
383
  const board = boardPath(company, deps);
276
384
  if (!deps.fs.existsSync(board))
277
385
  return errorResult(`registration incomplete: missing ${board}`);
@@ -285,33 +393,39 @@ function registerBrainstorm(company, project, deps) {
285
393
  if (!title)
286
394
  return errorResult(`registration incomplete: missing local Board project ${company}/${project}`);
287
395
  const set = deps.runHq(["mesh", "project", "set", project, "--company", company, "--name", title, "--description", description, "--create", "--json"], {
288
- cwd: deps.cwd, env: deps.env, capture: true,
396
+ cwd: deps.cwd, env: { ...deps.env, HQ_COMPANY_UID: resolved.uid }, capture: true,
289
397
  });
290
398
  if (set.code !== 0)
291
399
  return errorResult(`registration incomplete: hq mesh project set failed for ${company}/${project}`);
292
- let result;
400
+ // The shell discards jq errors on this output (`2>/dev/null || thread=""`).
401
+ let result = null;
293
402
  try {
294
403
  result = asRecord(JSON.parse(set.stdout));
295
404
  }
296
- catch {
297
- return errorResult("registration incomplete: project set output missing threadId");
298
- }
405
+ catch { /* falls back to the Board entry below */ }
299
406
  const registration = asRecord(result?.registration);
300
- const thread = jqString(jqOr(registration?.threadId, jqOr(result?.threadId, "")));
407
+ let thread = jqString(jqOr(registration?.threadId, jqOr(result?.threadId, "")));
408
+ let channel = jqString(jqOr(registration?.channelId, jqOr(result?.channelId, "")));
409
+ // `project set` on an already-registered project can return no thread or
410
+ // channel. Fall back to the ids the local Board entry already records.
411
+ if (!thread)
412
+ thread = jqString(jqOr(asRecord(row)?.threadId, ""));
413
+ if (!channel)
414
+ channel = jqString(jqOr(asRecord(row)?.channelId, ""));
301
415
  if (!thread)
302
416
  return errorResult("registration incomplete: project set output missing threadId");
303
- const channel = jqString(jqOr(registration?.channelId, jqOr(result?.channelId, "")));
304
417
  if (!channel)
305
418
  return errorResult("registration incomplete: project set output missing channelId");
306
419
  const now = timestamp(deps);
307
420
  const rows = projectRows(document);
308
- document.projects = rows.map((item) => item.id === project || item.mesh_project_id === project
309
- ? { ...item, threadId: thread, channelId: channel, mesh_project_id: project, mesh_registration_prompt_state: "accepted", updated_at: now }
310
- : item);
311
- for (const updated of document.projects) {
312
- if (updated.id === project || updated.mesh_project_id === project)
313
- delete updated.pending_registration;
314
- }
421
+ document.projects = rows.map((item) => {
422
+ if (item.id !== project && item.mesh_project_id !== project)
423
+ return item;
424
+ const updated = { ...item, threadId: thread, channelId: channel, mesh_project_id: project, updated_at: now };
425
+ delete updated.pending_registration;
426
+ delete updated.mesh_registration_prompt_state;
427
+ return updated;
428
+ });
315
429
  try {
316
430
  atomicJqWrite(board, document, deps);
317
431
  }
@@ -321,7 +435,20 @@ function registerBrainstorm(company, project, deps) {
321
435
  const verified = projectRows(boardData(company, board, deps)).some((item) => (item.id === project || item.mesh_project_id === project) && item.threadId === thread && item.channelId === channel);
322
436
  if (!verified)
323
437
  return errorResult("registration incomplete: local Board registration did not verify");
324
- return { code: 0, stdout: `registered ${company}/${project} thread=${thread} channel=${channel}\n`, stderr: "" };
438
+ const registered = `registered ${company}/${project} thread=${thread} channel=${channel}\n`;
439
+ // Once the project has a prd.json, --board also syncs its stories.
440
+ if (!isFile(path.join(deps.root, "companies", company, "projects", project, "prd.json"), deps))
441
+ return { code: 0, stdout: registered, stderr: "" };
442
+ const sync = ensureOne(company, project, deps);
443
+ return { ...sync, stdout: `${registered}${sync.stdout}` };
444
+ }
445
+ function isFile(file, deps) {
446
+ try {
447
+ return deps.fs.statSync(file).isFile();
448
+ }
449
+ catch {
450
+ return false;
451
+ }
325
452
  }
326
453
  function audit(company, deps) {
327
454
  if (!company)
@@ -342,11 +469,12 @@ function audit(company, deps) {
342
469
  try {
343
470
  if (!deps.fs.statSync(prd).isFile())
344
471
  return false;
345
- const uid = companyUid(company, deps);
346
- if (uid === null) {
347
- stderr += `no company uid for ${company} (set HQ_COMPANY_UID, companies/${company}/.company-uid, or manifest cloud_uid)\n`;
348
- return true;
349
- }
472
+ // The reference reports a refused uid and still looks the project up
473
+ // with an empty uid, so it is listed as unregistered (ref lines 111-117).
474
+ const resolved = resolveUid(company, deps);
475
+ if (resolved.refusal !== undefined)
476
+ stderr += `${resolved.refusal}\n`;
477
+ const uid = resolved.uid ?? "";
350
478
  const cache = path.join(deps.env.HOME || os.homedir(), ".hq/work-mesh/cache/projects", uid);
351
479
  const meshProject = meshProjectIdForPrd(company, project, deps);
352
480
  return !deps.fs.existsSync(path.join(cache, `${meshProject}.json`))
@@ -457,9 +585,11 @@ function retryPending(company, deps) {
457
585
  export function runRegisterProject(args, deps) {
458
586
  try {
459
587
  const [mode, arg1, ...rest] = args;
460
- if (mode === "--brainstorm") {
588
+ // --board registers a Board entry that has no prd.json yet (a brainstorm or
589
+ // PRD that just started). --brainstorm is the older spelling of the same mode.
590
+ if (mode === "--board" || mode === "--brainstorm") {
461
591
  if (args.length !== 3)
462
- return errorResult("usage: register-project.sh --brainstorm <company> <board-project-id>");
592
+ return errorResult("usage: register-project.sh --board <company> <board-project-id>");
463
593
  return registerBrainstorm(arg1 ?? "", rest[0] ?? "", deps);
464
594
  }
465
595
  if (mode === "--audit")
@@ -3,7 +3,7 @@ import * as fs from "node:fs";
3
3
  import * as path from "node:path";
4
4
  import { spawn, spawnSync } from "node:child_process";
5
5
  import { resolveWindowsExecutable } from "../lib/bot/runtime/windows.js";
6
- import { sessionIdFromEnv, validSessionId } from "../lib/core-utils/session-id.js";
6
+ import { resolveSessionId, sessionIdFromEnv, validSessionId } from "../lib/core-utils/session-id.js";
7
7
  import { generateUlid } from "../lib/mesh/live/ulid.js";
8
8
  import { resolveLiveRoot } from "../utils/hq-roots.js";
9
9
  import { planResolvedCommandSpawn } from "../utils/windows-spawn.js";
@@ -118,16 +118,11 @@ export function resolveWorkMeshBindSession(root, env, fileSystem = fs) {
118
118
  const fromEnv = sessionIdFromEnv(env);
119
119
  if (fromEnv)
120
120
  return { sid: fromEnv, trusted: true };
121
- try {
122
- const value = fileSystem.readFileSync(path.join(root, "workspace/sessions/.current"), "utf8").replace(/[\t\n\v\f\r ]/g, "");
123
- return { sid: validSessionId(value) ? value : "", trusted: false };
124
- }
125
- catch {
126
- return { sid: "", trusted: false };
127
- }
121
+ // No env id: the shared resolver's .current fallback (an empty env skips its env step).
122
+ return { sid: resolveSessionId(root, {}, (file, encoding) => fileSystem.readFileSync(file, encoding)), trusted: false };
128
123
  }
129
124
  export function resolveWorkMeshBindSessionId(root, env, fileSystem = fs) {
130
- return resolveWorkMeshBindSession(root, env, fileSystem).sid;
125
+ return resolveSessionId(root, env, (file, encoding) => fileSystem.readFileSync(file, encoding));
131
126
  }
132
127
  function hasExecutable(deps, command) {
133
128
  if (process.platform === "win32") {
@@ -31,7 +31,7 @@ import { daemonUnitInstalled } from "../lib/daemon/handoff.js";
31
31
  import { adoptLegacyUnits, readAdoptedUnits, restoreLegacyUnits } from "../lib/daemon/migrate.js";
32
32
  import { DAEMON_ALIVE_WAIT_MS, ROOT_REFUSAL, SYSTEM_UNIT_DIR, WINDOWS_START_WAIT_MS, waitForLiveDaemon, daemonRootRefusal, installDaemonUnit, installScopeFor, classifyWindowsTask, daemonServiceStatus, describeSupervision, legacyWindowsTask, startDaemonUnit, readWindowsSid, uninstallDaemonUnit, windowsInteractiveSession, windowsTaskName, } from "../lib/daemon/install.js";
33
33
  import { PLIST_REFRESH_MARKER } from "../lib/daemon/plist-refresh.js";
34
- import { FILES_ACCESS_NEEDED_MESSAGE, filesAccessNeeded } from "../lib/daemon/tcc-eperm.js";
34
+ import { filesAccessNeeded, filesAccessNeededMessageFromMarker } from "../lib/daemon/tcc-eperm.js";
35
35
  import { describeLegacyUnit, findLegacyUnits } from "../lib/daemon/legacy.js";
36
36
  import { isDaemonProcess, liveDaemonLock, runningDaemonPid } from "../lib/daemon/lock.js";
37
37
  import { bundledHqCloud, managedHqCloud, managedHqCloudRoot, readHqCloudCopy, readHqCloudUpdateState } from "../lib/daemon/hq-cloud.js";
@@ -498,7 +498,7 @@ function formatUnit(u) {
498
498
  const detail = u.status === "running" && u.pid
499
499
  ? `pid ${u.pid}`
500
500
  : u.status === "idle" && u.lastResult
501
- ? `last run ${u.lastResult}`
501
+ ? `last run ${u.lastResult}${u.lastResult === "failed" && u.lastError ? `: ${u.lastError}` : ""}`
502
502
  : (u.reason ?? "");
503
503
  const restarts = u.restarts > 0 ? ` (restarted ${u.restarts}x)` : "";
504
504
  return ` ${u.id.padEnd(40)} ${u.status.padEnd(12)} ${detail}${restarts}`;
@@ -524,7 +524,7 @@ function statusWarnings(service, paths) {
524
524
  // Written by a daemon that macOS keeps refusing under the HQ root (tcc-eperm.ts).
525
525
  // A stopped daemon's marker is stale: the next daemon clears it on start.
526
526
  if (service.daemonPid !== null && filesAccessNeeded(paths.root))
527
- warnings.push(FILES_ACCESS_NEEDED_MESSAGE);
527
+ warnings.push(filesAccessNeededMessageFromMarker(paths.root));
528
528
  return warnings;
529
529
  }
530
530
  async function runStatus(d, opts) {
@@ -442,6 +442,17 @@ function printDnsRecords(records) {
442
442
  console.log(` ${displayText(record.type)} ${displayText(record.name)} -> ${displayText(record.value)}`);
443
443
  }
444
444
  }
445
+ /**
446
+ * True when hq-deploy writes the DNS records itself: the domain was bought
447
+ * through HQ by this company and its Route 53 zone is HQ's. An older server
448
+ * sends no field, which reads as false.
449
+ */
450
+ function isDnsManaged(body) {
451
+ return body.dnsManaged === true;
452
+ }
453
+ function managedDnsLine(domain) {
454
+ return `HQ manages DNS for ${displayText(domain)}. No records to add.`;
455
+ }
445
456
  function dnsRecords(value) {
446
457
  if (!Array.isArray(value))
447
458
  return [];
@@ -525,6 +536,7 @@ async function listAction(options) {
525
536
  displayText(domain.domain),
526
537
  displayText(domain.environment ?? "production"),
527
538
  displayText(domain.validationState ?? "unknown"),
539
+ ...(isDnsManaged(domain) ? ["DNS managed by HQ"] : []),
528
540
  ].join(" | "));
529
541
  }
530
542
  }
@@ -541,6 +553,7 @@ async function addAction(domainArg, options) {
541
553
  throw await deployError(response, target.orgSlug);
542
554
  const body = await readBody(response);
543
555
  const records = dnsRecords(body.dnsInstructions);
556
+ const dnsManaged = isDnsManaged(body);
544
557
  const apex = body.apex === true;
545
558
  const apexGuidance = typeof body.apexGuidance === "string" ? body.apexGuidance : undefined;
546
559
  const paid = body.billingBasis === "paid";
@@ -553,6 +566,7 @@ async function addAction(domainArg, options) {
553
566
  environment,
554
567
  validationState: body.domain?.validationState ?? "pending",
555
568
  serving: body.serving === true,
569
+ dnsManaged,
556
570
  dnsInstructions: records,
557
571
  apex,
558
572
  ...(apexGuidance ? { apexGuidance } : {}),
@@ -564,6 +578,11 @@ async function addAction(domainArg, options) {
564
578
  console.log(`Added ${displayText(domain)} to ${displayText(environment)}. It is not live yet.`);
565
579
  if (priceLine)
566
580
  console.log(priceLine);
581
+ if (dnsManaged) {
582
+ console.log(managedDnsLine(domain));
583
+ console.log(`To check when it is live, run: hq deploy domains refresh ${displayText(domain)}`);
584
+ return;
585
+ }
567
586
  printDnsRecords(records);
568
587
  if (apex) {
569
588
  console.log(apexGuidance
@@ -582,10 +601,11 @@ async function refreshAction(domainArg, options) {
582
601
  const body = await readBody(response);
583
602
  const serving = body.serving === true;
584
603
  const records = dnsRecords(body.dnsInstructions);
604
+ const dnsManaged = isDnsManaged(body);
585
605
  if (!serving)
586
606
  process.exitCode = REFRESH_NOT_SERVING_EXIT_CODE;
587
607
  if (options.json) {
588
- console.log(safeJson({ ok: true, appId: target.appId, ...body, domain, serving, dnsInstructions: records }));
608
+ console.log(safeJson({ ok: true, appId: target.appId, ...body, domain, serving, dnsManaged, dnsInstructions: records }));
589
609
  return;
590
610
  }
591
611
  if (serving) {
@@ -594,6 +614,11 @@ async function refreshAction(domainArg, options) {
594
614
  }
595
615
  const certStatus = typeof body.certStatus === "string" ? ` (certificate ${displayText(body.certStatus)})` : "";
596
616
  console.log(`${displayText(domain)} is waiting for DNS validation${certStatus}.`);
617
+ if (dnsManaged) {
618
+ console.log(managedDnsLine(domain));
619
+ console.log(`Run this again to check: hq deploy domains refresh ${displayText(domain)}`);
620
+ return;
621
+ }
597
622
  printDnsRecords(records);
598
623
  if (body.apex === true && typeof body.apexGuidance === "string")
599
624
  console.log(displayText(body.apexGuidance));
@@ -718,6 +743,7 @@ function baseState(body) {
718
743
  servingStatus,
719
744
  servingError: typeof serving.error === "string" && serving.error ? serving.error : null,
720
745
  records: dnsRecords(body.records),
746
+ dnsManaged: isDnsManaged(body),
721
747
  live: status === "live" || servingStatus === "live",
722
748
  raw: body,
723
749
  };
@@ -750,6 +776,7 @@ async function baseAddAction(domainArg, options) {
750
776
  baseDomain: state.baseDomain ?? domain,
751
777
  status: state.status,
752
778
  certificate: state.certStatus,
779
+ dnsManaged: state.dnsManaged,
753
780
  records: state.records,
754
781
  ...(typeof body.billingBasis === "string" ? { billingBasis: body.billingBasis } : {}),
755
782
  ...(typeof body.monthlyPriceUsd === "number" ? { monthlyPriceUsd: body.monthlyPriceUsd } : {}),
@@ -760,6 +787,11 @@ async function baseAddAction(domainArg, options) {
760
787
  console.log(`${displayText(domain)} is now the deploy domain of '${orgSlug}'. It is not live yet.`);
761
788
  if (priceLine)
762
789
  console.log(priceLine);
790
+ if (state.dnsManaged) {
791
+ console.log(managedDnsLine(state.baseDomain ?? domain));
792
+ console.log("To wait until it is live, run: hq deploy domains base status --wait");
793
+ return;
794
+ }
763
795
  printDnsRecords(state.records);
764
796
  if (state.records.length < 2) {
765
797
  console.log("The certificate's validation record can take a few seconds to appear; 'hq deploy domains base status' prints it.");
@@ -805,6 +837,7 @@ async function baseStatusAction(options) {
805
837
  certificate: state.certStatus,
806
838
  serving: state.servingStatus,
807
839
  ...(state.servingError ? { servingError: state.servingError } : {}),
840
+ dnsManaged: state.dnsManaged,
808
841
  records: state.live ? [] : state.records,
809
842
  attempts,
810
843
  ...(timedOut ? { timedOut: true } : {}),
@@ -821,7 +854,10 @@ async function baseStatusAction(options) {
821
854
  return;
822
855
  }
823
856
  console.log(`${name} is not live yet: ${describeBaseState(state)}.`);
824
- printDnsRecords(state.records);
857
+ if (state.dnsManaged)
858
+ console.log(managedDnsLine(state.baseDomain ?? "the company deploy domain"));
859
+ else
860
+ printDnsRecords(state.records);
825
861
  console.log(timedOut
826
862
  ? `Stopped waiting after ${minutes} minutes. Run 'hq deploy domains base status --wait' again to keep waiting.`
827
863
  : "Run 'hq deploy domains base status --wait' to wait until it is live.");
@@ -1,5 +1,5 @@
1
1
  import { Command } from 'commander';
2
- import { type RunQmdOptions, type SearchCollection, type QmdProcessResult } from '../lib/search-index/index.js';
2
+ import { type RunQmdOptions, type SearchCollection, type QmdProcessResult, type QmdSpawn } from '../lib/search-index/index.js';
3
3
  import { type BackgroundDependencies, type BackgroundResult, type BackgroundStatus } from '../lib/search-index/background.js';
4
4
  import { type EmbedLockDependencies } from '../lib/search-index/embed-lock.js';
5
5
  import { type LoadGateDependencies } from '../lib/search-index/load-gate.js';
@@ -35,6 +35,8 @@ export type SyncSearchIndexResult = {
35
35
  };
36
36
  /** Incrementally update qmd, embedding only when an operator explicitly asks. */
37
37
  export declare function syncSearchIndex(hqRoot: string, embed: boolean, dependencies?: SearchIndexDependencies): SyncSearchIndexResult;
38
+ /** Update from a daemon worker, with the scheduled job's qmd process policy. */
39
+ export declare function syncScheduledSearchIndex(hqRoot: string, spawn: QmdSpawn, waitForWriter: (milliseconds: number) => void): SyncSearchIndexResult;
38
40
  export declare function collectionStatusLines(expected: SearchCollection[], registered: ReadonlySet<string>): string[];
39
41
  export declare function collectionSummary(expected: SearchCollection[], registered: ReadonlySet<string>): string;
40
42
  export declare function registerIndexCommand(program: Command, dependencies?: SearchIndexDependencies): void;
@@ -129,6 +129,18 @@ export function syncSearchIndex(hqRoot, embed, dependencies = defaults) {
129
129
  writeStderr('hq: cannot access the qmd embed lock; skipping this pass.\n');
130
130
  return { status: 'updated', embedded: outcome === 'ran' && embedded };
131
131
  }
132
+ /** Update from a daemon worker, with the scheduled job's qmd process policy. */
133
+ export function syncScheduledSearchIndex(hqRoot, spawn, waitForWriter) {
134
+ return syncSearchIndex(hqRoot, false, {
135
+ ...defaults,
136
+ sleepSync: waitForWriter,
137
+ reconcileCollections: (root) => reconcileCollections(root, {
138
+ repairPathDrift: qmdCollectionPathRepairEnabled(),
139
+ spawn,
140
+ }),
141
+ runQmd: (args, options) => runQmd(args, { ...options, spawn }),
142
+ });
143
+ }
132
144
  function resolveRoot(hqRoot) {
133
145
  return hqRoot ?? findHqRoot();
134
146
  }
@@ -1,4 +1,14 @@
1
+ import { type AccountConfig, type LaneProvider } from "../lib/lanes/index.js";
1
2
  import type { Ctx, LaneAccountsHandlerDeps } from "./lanes-shared.js";
3
+ /**
4
+ * PS-006 set-owner warnings. The change is still saved; these only flag the
5
+ * likely mistake of recording the owner's own login under his name instead
6
+ * of `owner`, which takes that login away from every lane.
7
+ */
8
+ export declare function setOwnerWarnings(env: NodeJS.ProcessEnv, provider: LaneProvider, id: string, holder: string | undefined, accounts: Record<string, AccountConfig>): Array<{
9
+ code: string;
10
+ message: string;
11
+ }>;
2
12
  export declare function createLaneAccountsHandlers(deps: LaneAccountsHandlerDeps): {
3
13
  runAccountsList: (ctx: Ctx, opts: {
4
14
  provider?: string;
@@ -18,6 +28,10 @@ export declare function createLaneAccountsHandlers(deps: LaneAccountsHandlerDeps
18
28
  host?: string;
19
29
  company?: string;
20
30
  }) => Promise<void>;
31
+ runAccountsSetOwner: (ctx: Ctx, providerRaw: string, accountIdRaw: string, opts: {
32
+ owningCompany?: string;
33
+ holder?: string;
34
+ }) => Promise<void>;
21
35
  runAccountsClearQuota: (ctx: Ctx, providerRaw: string, accountIdRaw: string, opts: {
22
36
  model?: string;
23
37
  }) => Promise<void>;