@indigoai-us/hq-cli 5.345.208 → 5.345.211

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 (133) hide show
  1. package/CHANGELOG.md +106 -0
  2. package/assets/scaffold/core/scripts/derive-trigger-facts.sh +22 -3
  3. package/assets/scaffold/core/scripts/lib/trigger-fact-text.awk +152 -41
  4. package/dist/command-catalog.generated.d.ts +33 -8
  5. package/dist/command-catalog.generated.js +40 -8
  6. package/dist/command-registration-plan.d.ts +2 -2
  7. package/dist/command-registration-plan.js +1 -1
  8. package/dist/commands/access.js +11 -5
  9. package/dist/commands/agents.d.ts +8 -0
  10. package/dist/commands/agents.js +5 -0
  11. package/dist/commands/bot.d.ts +8 -0
  12. package/dist/commands/bot.js +67 -7
  13. package/dist/commands/channels.js +4 -0
  14. package/dist/commands/cloud.d.ts +83 -2
  15. package/dist/commands/cloud.js +161 -31
  16. package/dist/commands/company.d.ts +9 -0
  17. package/dist/commands/company.js +44 -14
  18. package/dist/commands/core-checkpoint-native.js +21 -0
  19. package/dist/commands/core-derive-trigger-facts-native.d.ts +1 -0
  20. package/dist/commands/core-derive-trigger-facts-native.js +75 -14
  21. package/dist/commands/core-generate-workers-registry-fast.d.ts +1 -1
  22. package/dist/commands/core-generate-workers-registry-fast.js +7 -1
  23. package/dist/commands/core-job-run-native.d.ts +8 -0
  24. package/dist/commands/core-job-run-native.js +11 -3
  25. package/dist/commands/core-jobs-native.js +1 -1
  26. package/dist/commands/core-register-project-native.js +31 -1
  27. package/dist/commands/core-scan-packages-fast.d.ts +1 -1
  28. package/dist/commands/core-scan-packages-fast.js +8 -1
  29. package/dist/commands/core-work-mesh-bind-trusted-native.d.ts +14 -2
  30. package/dist/commands/core-work-mesh-bind-trusted-native.js +62 -8
  31. package/dist/commands/core.js +12 -3
  32. package/dist/commands/dm-attach.d.ts +10 -0
  33. package/dist/commands/dm-attach.js +33 -5
  34. package/dist/commands/integrations-connect.d.ts +16 -0
  35. package/dist/commands/integrations-connect.js +70 -6
  36. package/dist/commands/lanes-session-start.d.ts +17 -0
  37. package/dist/commands/lanes-session-start.js +281 -13
  38. package/dist/commands/lanes-watch.js +11 -3
  39. package/dist/commands/lanes.d.ts +4 -0
  40. package/dist/commands/lanes.js +95 -22
  41. package/dist/commands/library.d.ts +10 -0
  42. package/dist/commands/library.js +30 -3
  43. package/dist/commands/meetings.d.ts +42 -0
  44. package/dist/commands/meetings.js +157 -12
  45. package/dist/commands/mesh.js +3 -0
  46. package/dist/commands/monitor.d.ts +6 -0
  47. package/dist/commands/monitor.js +29 -19
  48. package/dist/commands/onboard.js +8 -1
  49. package/dist/commands/sources.js +7 -3
  50. package/dist/index.js +9 -0
  51. package/dist/lanes-monitor-check-argv.d.ts +1 -1
  52. package/dist/lanes-monitor-check-argv.js +2 -2
  53. package/dist/lanes-session-start-argv.d.ts +4 -1
  54. package/dist/lanes-session-start-argv.js +5 -2
  55. package/dist/lib/bot/fleet-daemon.d.ts +101 -0
  56. package/dist/lib/bot/fleet-daemon.js +227 -0
  57. package/dist/lib/bot/fleet-local.d.ts +26 -0
  58. package/dist/lib/bot/fleet-local.js +51 -2
  59. package/dist/lib/bot/index.d.ts +1 -0
  60. package/dist/lib/bot/index.js +1 -0
  61. package/dist/lib/bot/jobs/hot-signal-sync.d.ts +4 -0
  62. package/dist/lib/bot/jobs/hot-signal-sync.js +8 -1
  63. package/dist/lib/bot/log.js +3 -1
  64. package/dist/lib/bot/probe.js +2 -0
  65. package/dist/lib/bot/run.js +28 -3
  66. package/dist/lib/bot/runtime-failure.d.ts +4 -2
  67. package/dist/lib/bot/runtime-failure.js +9 -1
  68. package/dist/lib/bot/status.d.ts +17 -0
  69. package/dist/lib/bot/status.js +53 -2
  70. package/dist/lib/capacity/collectors/claude-oauth.d.ts +5 -5
  71. package/dist/lib/capacity/collectors/claude-oauth.js +6 -6
  72. package/dist/lib/core-utils/native-scaffold-help.d.ts +16 -0
  73. package/dist/lib/core-utils/native-scaffold-help.js +26 -0
  74. package/dist/lib/core-utils/session-company.d.ts +25 -8
  75. package/dist/lib/core-utils/session-company.js +59 -17
  76. package/dist/lib/daemon/catalog.d.ts +34 -1
  77. package/dist/lib/daemon/catalog.js +42 -3
  78. package/dist/lib/daemon/run.d.ts +5 -4
  79. package/dist/lib/daemon/run.js +40 -16
  80. package/dist/lib/daemon/server.js +26 -7
  81. package/dist/lib/daemon/supervisor.d.ts +2 -0
  82. package/dist/lib/daemon/supervisor.js +60 -1
  83. package/dist/lib/daemon/tools.js +17 -1
  84. package/dist/lib/db/sqlite-binding.js +2 -1
  85. package/dist/lib/doctor/checks/bots.d.ts +2 -0
  86. package/dist/lib/doctor/checks/bots.js +11 -0
  87. package/dist/lib/doctor/checks/runtime-health.js +3 -2
  88. package/dist/lib/doctor/checks/work-context.js +5 -2
  89. package/dist/lib/hook-engine/resolve.d.ts +1 -1
  90. package/dist/lib/hook-engine/resolve.js +4 -1
  91. package/dist/lib/hot-channels/adapters/meeting-providers.d.ts +2 -0
  92. package/dist/lib/hot-channels/adapters/meeting-providers.js +13 -2
  93. package/dist/lib/lanes/index.d.ts +1 -1
  94. package/dist/lib/lanes/index.js +1 -1
  95. package/dist/lib/lanes/monitor.d.ts +14 -0
  96. package/dist/lib/lanes/monitor.js +51 -10
  97. package/dist/lib/lanes/outpost-dispatch.d.ts +3 -0
  98. package/dist/lib/lanes/outpost-dispatch.js +1 -0
  99. package/dist/lib/lanes/store.d.ts +1 -1
  100. package/dist/lib/lanes/store.js +2 -1
  101. package/dist/lib/mesh/client.js +7 -1
  102. package/dist/lib/mesh/live/backfill-held.d.ts +3 -0
  103. package/dist/lib/mesh/live/backfill-held.js +167 -7
  104. package/dist/lib/mesh/live/flush.d.ts +7 -0
  105. package/dist/lib/mesh/live/flush.js +10 -1
  106. package/dist/lib/monitor.d.ts +9 -0
  107. package/dist/lib/monitor.js +33 -7
  108. package/dist/lib/onboarding/orchestrator.js +269 -132
  109. package/dist/lib/onboarding/types.d.ts +2 -0
  110. package/dist/lib/scaffold-cli-floor.js +2 -1
  111. package/dist/lib/signals/failure-alert.js +3 -1
  112. package/dist/lib/sync-core/reconcile.js +15 -11
  113. package/dist/lib/work-context/organize.d.ts +6 -0
  114. package/dist/lib/work-context/organize.js +28 -0
  115. package/dist/lib/work-context/paths.d.ts +9 -0
  116. package/dist/lib/work-context/paths.js +15 -0
  117. package/dist/lib/work-context/prd-sync.js +2 -1
  118. package/dist/runners-alias.d.ts +54 -0
  119. package/dist/runners-alias.js +86 -0
  120. package/dist/utils/install-tree-torn.js +5 -3
  121. package/dist/utils/npm-install-flags.d.ts +27 -0
  122. package/dist/utils/npm-install-flags.js +68 -0
  123. package/dist/utils/package-use-lease.js +1 -1
  124. package/dist/utils/qmd-native-binding-error.js +2 -1
  125. package/dist/utils/self-update.js +2 -1
  126. package/dist/utils/staged-install.js +2 -1
  127. package/dist/utils/staged-npm-install.js +2 -1
  128. package/dist/utils/upload-author.d.ts +2 -1
  129. package/dist/utils/upload-author.js +9 -5
  130. package/dist/utils/version-check.js +2 -1
  131. package/dist/utils/version-gate.js +7 -6
  132. package/package.json +7 -7
  133. package/scripts/install-hook-engine.mjs +7 -3
@@ -86,6 +86,13 @@ export interface FlushSummary {
86
86
  * Recovers orphan `*.claimed` files first; restores unprocessed lines on throw.
87
87
  */
88
88
  export declare function flushSessionEvents(inputDeps: FlushDeps): Promise<FlushSummary>;
89
+ /**
90
+ * True when flush holds a session as NEEDS_COMPANY even though its state may
91
+ * carry a companyUid: a device-default binding is not attribution evidence,
92
+ * and needs_company always holds. The held backfill uses this same predicate
93
+ * so it never reports such a session as already attributed.
94
+ */
95
+ export declare function holdsForCompany(state: SessionStateFile): boolean;
89
96
  /**
90
97
  * Assert flush never opens the machine-global bind cache.
91
98
  * Used by tests; production flush has no reference to this path.
@@ -1014,6 +1014,15 @@ function dropOwnerMismatchedSession(input) {
1014
1014
  input.deps.log?.(`work-mesh: session ${input.sessionId} is reported by another actor (403 SESSION_OWNER_MISMATCH); dropped ${input.items.length} event(s), not dead-lettered`);
1015
1015
  }
1016
1016
  }
1017
+ /**
1018
+ * True when flush holds a session as NEEDS_COMPANY even though its state may
1019
+ * carry a companyUid: a device-default binding is not attribution evidence,
1020
+ * and needs_company always holds. The held backfill uses this same predicate
1021
+ * so it never reports such a session as already attributed.
1022
+ */
1023
+ export function holdsForCompany(state) {
1024
+ return state.companyConfidence === "device_default" || state.contextStatus === "needs_company";
1025
+ }
1017
1026
  function classifySession(state) {
1018
1027
  if (!state) {
1019
1028
  return { action: "hold", heldReason: "STATE_ABSENT" };
@@ -1027,7 +1036,7 @@ function classifySession(state) {
1027
1036
  state.companyUid === state.ownerMismatch.companyUid) {
1028
1037
  return { action: "drop", reason: "owner_mismatch" };
1029
1038
  }
1030
- if (state.companyConfidence === "device_default" || state.contextStatus === "needs_company") {
1039
+ if (holdsForCompany(state)) {
1031
1040
  return { action: "hold", heldReason: "NEEDS_COMPANY" };
1032
1041
  }
1033
1042
  if (state.contextStatus === "company_conflict") {
@@ -2,6 +2,7 @@ import type { LaneCompanyRef, LaneProvider } from "./lanes/types.js";
2
2
  export declare const MONITOR_SCHEMA_VERSION: "hq-monitor.v1";
3
3
  export declare const MONITOR_FLAG = "monitor.enabled";
4
4
  export declare const MONITOR_FLAG_DEFAULT = false;
5
+ /** Default lifetime when `hq monitor start` has neither --timeout nor --persistent. */
5
6
  export declare const MONITOR_DEFAULT_TIMEOUT_MS: number;
6
7
  export declare const MONITOR_DEFAULT_CHECKIN_MS: number;
7
8
  export declare const MONITOR_BATCH_WINDOW_MS = 200;
@@ -143,6 +144,14 @@ export declare function recordMonitorTargetActivity(hqRoot: string, targetKey: s
143
144
  export declare function recordMonitorTargetDeliveryAtPath(activityPath: string, now?: () => Date, kind?: MonitorTargetActivity["last_delivery_kind"]): void;
144
145
  /** Elapsed idle time in whole units; live timers never land on exact multiples. */
145
146
  export declare function formatElapsed(ms: number): string;
147
+ /**
148
+ * Scan-free test run before each supervisor tick's check-in. A supervisor only
149
+ * tests its own interval: every eligible monitor has a live supervisor of its
150
+ * own, so the one holding the target's shortest interval passes this test
151
+ * whenever runMonitorCheckinTick would send. A missing or unreadable activity
152
+ * file passes too, so the full path keeps creating or reporting it.
153
+ */
154
+ export declare function monitorCheckinMayBeDue(hqRoot: string, targetKey: string, checkinMs: number | null, nowMs: number, targetActivityAt: number | null): boolean;
146
155
  export declare function runMonitorCheckinTick(hqRoot: string, targetKey: string, deps: MonitorCheckinDeps): Promise<MonitorCheckinResult>;
147
156
  export declare function readMonitorPidLiveness(pid: number | null, starttime: number | null, readStarttime?: (pid: number) => number | null): boolean;
148
157
  export {};
@@ -7,7 +7,8 @@ import { readProcStarttime } from "./lanes/spawn.js";
7
7
  export const MONITOR_SCHEMA_VERSION = "hq-monitor.v1";
8
8
  export const MONITOR_FLAG = "monitor.enabled";
9
9
  export const MONITOR_FLAG_DEFAULT = false;
10
- export const MONITOR_DEFAULT_TIMEOUT_MS = 5 * 60_000;
10
+ /** Default lifetime when `hq monitor start` has neither --timeout nor --persistent. */
11
+ export const MONITOR_DEFAULT_TIMEOUT_MS = 30 * 60_000;
11
12
  export const MONITOR_DEFAULT_CHECKIN_MS = 55 * 60_000;
12
13
  const MONITOR_PROMPT_CACHE_TTL_MS = 60 * 60_000;
13
14
  export const MONITOR_BATCH_WINDOW_MS = 200;
@@ -462,6 +463,35 @@ export function formatElapsed(ms) {
462
463
  return `${minutes}m`;
463
464
  return `${Math.max(0, Math.floor(ms / 1_000))}s`;
464
465
  }
466
+ /** Idle time since the target's last activity when a check-in at this interval is due, otherwise null. */
467
+ function dueCheckinElapsed(activity, targetActivityAt, nowMs, intervalMs) {
468
+ const lastActivityMs = Math.max(activity.last_delivery_ms, activity.last_activity_ms ?? Number.NEGATIVE_INFINITY, targetActivityAt ?? Number.NEGATIVE_INFINITY);
469
+ const elapsed = nowMs - lastActivityMs;
470
+ if (elapsed < intervalMs)
471
+ return null;
472
+ if (activity.last_checkin_attempt_ms !== undefined && nowMs - activity.last_checkin_attempt_ms < intervalMs)
473
+ return null;
474
+ return elapsed;
475
+ }
476
+ /**
477
+ * Scan-free test run before each supervisor tick's check-in. A supervisor only
478
+ * tests its own interval: every eligible monitor has a live supervisor of its
479
+ * own, so the one holding the target's shortest interval passes this test
480
+ * whenever runMonitorCheckinTick would send. A missing or unreadable activity
481
+ * file passes too, so the full path keeps creating or reporting it.
482
+ */
483
+ export function monitorCheckinMayBeDue(hqRoot, targetKey, checkinMs, nowMs, targetActivityAt) {
484
+ if (checkinMs === null || checkinMs <= 0)
485
+ return false;
486
+ let activity;
487
+ try {
488
+ activity = readJson(path.join(targetStorageDir(hqRoot, targetKey), "activity.json"));
489
+ }
490
+ catch {
491
+ return true;
492
+ }
493
+ return activity === null || dueCheckinElapsed(activity, targetActivityAt, nowMs, checkinMs) !== null;
494
+ }
465
495
  function formatCheckinText(elapsedMs, monitors) {
466
496
  const descriptions = monitors.map(({ meta }) => meta.description).join(", ");
467
497
  return `hq monitor check-in — idle for ${formatElapsed(elapsedMs)}; ${monitors.length} monitor(s) still armed: ${descriptions}. If you are idle, confirm nothing needs action and end your turn. If you are mid-task, ignore this and continue.`;
@@ -488,13 +518,9 @@ export async function runMonitorCheckinTick(hqRoot, targetKey, deps) {
488
518
  });
489
519
  return { sent: false, sequence: null, text: null, outcome: null };
490
520
  }
491
- const lastActivityMs = Math.max(activity.last_delivery_ms, activity.last_activity_ms ?? Number.NEGATIVE_INFINITY, targetActivityAt ?? Number.NEGATIVE_INFINITY);
492
- const elapsed = nowMs - lastActivityMs;
493
- if (elapsed < shortestInterval)
521
+ const elapsed = dueCheckinElapsed(activity, targetActivityAt, nowMs, shortestInterval);
522
+ if (elapsed === null)
494
523
  return { sent: false, sequence: null, text: null, outcome: null };
495
- if (activity.last_checkin_attempt_ms !== undefined && nowMs - activity.last_checkin_attempt_ms < shortestInterval) {
496
- return { sent: false, sequence: null, text: null, outcome: null };
497
- }
498
524
  const text = formatCheckinText(elapsed, monitors);
499
525
  const sequence = activity.checkin_count + 1;
500
526
  const delivery = await deps.deliver(text, sequence);
@@ -33,61 +33,9 @@ import { readCheckpoint, writeCheckpoint, isStepComplete, deleteCheckpoint, } fr
33
33
  export async function createCompanyFlow(input, config, onProgress) {
34
34
  const client = new VaultClient(config.vaultConfig);
35
35
  const checkpoint = await readCheckpoint(config.hqRoot) ?? makeCheckpoint("create-company");
36
- // Step 1: Create person
37
- //
38
- // Three-layer idempotency:
39
- // a. Resume from checkpoint UID if present (handles mid-flight retries)
40
- // b. Look up by slug on the server (handles fresh runs against an existing
41
- // account — defends against the server not enforcing slug uniqueness)
42
- // c. Create, with a VaultConflictError fallback for the create-time race
43
- if (!isStepComplete(checkpoint, "create-person")) {
44
- emit(onProgress, "create-person", "running");
45
- try {
46
- const personSlug = slugFromEmail(input.personEmail);
47
- let person = (checkpoint.personUid
48
- ? await safeGetEntity(client, checkpoint.personUid)
49
- : null) ?? (await safeFindBySlug(client, "person", personSlug));
50
- let detail;
51
- if (person) {
52
- detail = `Person already registered (${person.uid})`;
53
- }
54
- else {
55
- try {
56
- person = await client.entity.create({
57
- type: "person",
58
- slug: personSlug,
59
- name: input.personName,
60
- email: input.personEmail,
61
- });
62
- }
63
- catch (err) {
64
- if (err instanceof VaultConflictError) {
65
- // Lost the create-time race — another caller created between our
66
- // findBySlug and create. Re-fetch.
67
- person = await client.entity.findBySlug("person", personSlug);
68
- }
69
- else {
70
- throw err;
71
- }
72
- }
73
- detail = `personUid: ${person.uid}`;
74
- }
75
- checkpoint.personUid = person.uid;
76
- checkpoint.completedSteps.push("create-person");
77
- await writeCheckpoint(config.hqRoot, checkpoint);
78
- emit(onProgress, "create-person", "done", detail);
79
- }
80
- catch (err) {
81
- checkpoint.failedStep = "create-person";
82
- checkpoint.error = String(err);
83
- await writeCheckpoint(config.hqRoot, checkpoint);
84
- emit(onProgress, "create-person", "failed");
85
- throw new PersonCreationError(`Failed to create person entity: ${err}`, err instanceof Error ? err : undefined);
86
- }
87
- }
88
- else {
89
- emit(onProgress, "create-person", "skipped", "Already complete");
90
- }
36
+ // Step 1: Create person (see resolveCallerPerson: only the caller's own
37
+ // person record is ever used).
38
+ await runPersonStep(client, checkpoint, input, config, onProgress);
91
39
  // Step 2: Create company (same three-layer idempotency as step 1)
92
40
  //
93
41
  // The slug lookup is scoped to the CALLER's namespace (owned or member-of):
@@ -124,7 +72,11 @@ export async function createCompanyFlow(input, config, onProgress) {
124
72
  if (err instanceof VaultConflictError) {
125
73
  // Lost the create-time race — re-fetch from our own namespace. A
126
74
  // conflict that is NOT ours means another account holds the slug.
127
- const mine = await client.entity.findInMyNamespace("company", input.companySlug);
75
+ // When another owner holds the base slug the server creates ours
76
+ // as `<slug>-<ownerTag>`, and a repeat create 409s on that
77
+ // candidate, so look that slug up too before calling it taken.
78
+ const mine = (await client.entity.findInMyNamespace("company", input.companySlug)) ??
79
+ (await findOwnerSuffixedCompany(client, config, input.companySlug));
128
80
  if (!mine) {
129
81
  throw new Error(`Company slug "${input.companySlug}" is already taken by another account. Choose another.`);
130
82
  }
@@ -192,10 +144,34 @@ export async function createCompanyFlow(input, config, onProgress) {
192
144
  // Verify no existing memberships (optimistic concurrency guard)
193
145
  const existing = await client.listMembersOfCompany(checkpoint.companyUid);
194
146
  if (existing.length > 0) {
195
- // Already has members — find our membership
196
- const ours = existing.find(m => m.personUid === checkpoint.personUid);
147
+ // Already has members — find our membership. The vault-service makes
148
+ // the caller the owner when it creates the company, under the person
149
+ // record of the caller's sign-in, so accept any member row whose person
150
+ // the caller owns (feedback_a169f6dc).
151
+ let ours = existing.find(m => m.personUid === checkpoint.personUid);
152
+ if (!ours) {
153
+ const owned = new Set((await listOwnedPersons(client)).map((p) => p.uid));
154
+ ours = existing.find(m => owned.has(m.personUid));
155
+ if (ours) {
156
+ checkpoint.personUid = ours.personUid;
157
+ }
158
+ }
159
+ if (ours && ours.role !== "owner") {
160
+ // findInMyNamespace also returns companies the caller only belongs
161
+ // to. create-company adopts only a company the caller owns; drop this
162
+ // one so a run with another slug does not pick it up again.
163
+ const slug = checkpoint.companySlug ?? input.companySlug;
164
+ forgetMembershipState(checkpoint);
165
+ checkpoint.failedStep = "bootstrap-membership";
166
+ checkpoint.error = `caller is ${ours.role} of ${slug}, not its owner`;
167
+ await writeCheckpoint(config.hqRoot, checkpoint);
168
+ emit(onProgress, "bootstrap-membership", "failed");
169
+ throw new MembershipBootstrapError(`You are a ${ours.role} of the company "${slug}", not its owner, so create-company cannot set it up. ` +
170
+ "To work in it, use `hq onboard join` with an invite; to create your own company, run `hq onboard create-company` with another slug.");
171
+ }
197
172
  if (ours) {
198
173
  checkpoint.membershipKey = ours.membershipKey;
174
+ checkpoint.role = ours.role;
199
175
  checkpoint.completedSteps.push("bootstrap-membership");
200
176
  await writeCheckpoint(config.hqRoot, checkpoint);
201
177
  emit(onProgress, "bootstrap-membership", "skipped", "Owner membership already exists");
@@ -214,9 +190,10 @@ export async function createCompanyFlow(input, config, onProgress) {
214
190
  });
215
191
  const accept = await client.acceptInvite(invite.inviteToken, checkpoint.personUid);
216
192
  checkpoint.membershipKey = accept.membership.membershipKey;
193
+ checkpoint.role = accept.membership.role;
217
194
  checkpoint.completedSteps.push("bootstrap-membership");
218
195
  await writeCheckpoint(config.hqRoot, checkpoint);
219
- emit(onProgress, "bootstrap-membership", "done", `role: owner`);
196
+ emit(onProgress, "bootstrap-membership", "done", `role: ${accept.membership.role}`);
220
197
  }
221
198
  }
222
199
  catch (err) {
@@ -255,13 +232,16 @@ export async function createCompanyFlow(input, config, onProgress) {
255
232
  else {
256
233
  emit(onProgress, "verify-sts", "skipped", "Already complete");
257
234
  }
258
- // Step 6: Write .hq/config.json
235
+ // Step 6: Write .hq/config.json. The role comes from the caller's membership
236
+ // row (recorded by bootstrap-membership, or looked up for a checkpoint saved
237
+ // before the role was recorded), never assumed.
259
238
  emit(onProgress, "write-config", "running");
239
+ const createRole = checkpoint.role ?? (await callerMembershipRole(client, checkpoint));
260
240
  const configPath = await writeHqConfig(config.hqRoot, {
261
241
  companyUid: checkpoint.companyUid,
262
242
  companySlug: checkpoint.companySlug ?? input.companySlug,
263
243
  personUid: checkpoint.personUid,
264
- role: "owner",
244
+ role: createRole,
265
245
  bucketName: checkpoint.bucketName,
266
246
  vaultApiUrl: config.vaultConfig.apiUrl,
267
247
  configuredAt: new Date().toISOString(),
@@ -275,7 +255,7 @@ export async function createCompanyFlow(input, config, onProgress) {
275
255
  personUid: checkpoint.personUid,
276
256
  companyUid: checkpoint.companyUid,
277
257
  companySlug: checkpoint.companySlug ?? input.companySlug,
278
- role: "owner",
258
+ role: createRole,
279
259
  bucketName: checkpoint.bucketName,
280
260
  configPath,
281
261
  };
@@ -300,53 +280,8 @@ export async function joinCompanyFlow(input, config, onProgress) {
300
280
  checkpoint.inviteToken = token;
301
281
  await writeCheckpoint(config.hqRoot, checkpoint);
302
282
  emit(onProgress, "parse-token", "done");
303
- // Step 2: Create person (three-layer idempotency — same pattern as createCompanyFlow)
304
- if (!isStepComplete(checkpoint, "create-person")) {
305
- emit(onProgress, "create-person", "running");
306
- try {
307
- const personSlug = slugFromEmail(input.personEmail);
308
- let person = (checkpoint.personUid
309
- ? await safeGetEntity(client, checkpoint.personUid)
310
- : null) ?? (await safeFindBySlug(client, "person", personSlug));
311
- let detail;
312
- if (person) {
313
- detail = `Person already registered (${person.uid})`;
314
- }
315
- else {
316
- try {
317
- person = await client.entity.create({
318
- type: "person",
319
- slug: personSlug,
320
- name: input.personName,
321
- email: input.personEmail,
322
- });
323
- }
324
- catch (err) {
325
- if (err instanceof VaultConflictError) {
326
- person = await client.entity.findBySlug("person", personSlug);
327
- }
328
- else {
329
- throw err;
330
- }
331
- }
332
- detail = `personUid: ${person.uid}`;
333
- }
334
- checkpoint.personUid = person.uid;
335
- checkpoint.completedSteps.push("create-person");
336
- await writeCheckpoint(config.hqRoot, checkpoint);
337
- emit(onProgress, "create-person", "done", detail);
338
- }
339
- catch (err) {
340
- checkpoint.failedStep = "create-person";
341
- checkpoint.error = String(err);
342
- await writeCheckpoint(config.hqRoot, checkpoint);
343
- emit(onProgress, "create-person", "failed");
344
- throw new PersonCreationError(`Failed to create person entity: ${err}`, err instanceof Error ? err : undefined);
345
- }
346
- }
347
- else {
348
- emit(onProgress, "create-person", "skipped", "Already complete");
349
- }
283
+ // Step 2: Create person (same caller-owned resolution as createCompanyFlow)
284
+ await runPersonStep(client, checkpoint, input, config, onProgress);
350
285
  // Step 3: Accept invite
351
286
  if (!isStepComplete(checkpoint, "accept-invite")) {
352
287
  emit(onProgress, "accept-invite", "running");
@@ -368,6 +303,22 @@ export async function joinCompanyFlow(input, config, onProgress) {
368
303
  emit(onProgress, "accept-invite", "done", `role: ${result.membership.role}`);
369
304
  }
370
305
  catch (err) {
306
+ if (err instanceof VaultConflictError && !checkpoint.companyUid) {
307
+ // The invite was used already, and this run has no company recorded
308
+ // for the caller's person: another sign-in accepted it before resume
309
+ // re-linked the person, or the caller's own accept succeeded on the
310
+ // server but the response was lost before the checkpoint was written.
311
+ // Do not guess a company or write a config for one the caller may not
312
+ // belong to.
313
+ checkpoint.failedStep = "accept-invite";
314
+ checkpoint.error = String(err);
315
+ await writeCheckpoint(config.hqRoot, checkpoint);
316
+ emit(onProgress, "accept-invite", "failed");
317
+ throw new InviteAcceptError("This invite has already been accepted, and this run has no record of which company it joined. " +
318
+ "If you accepted it yourself (in an earlier run whose reply was lost, or under another sign-in), you are " +
319
+ "already a member: use the company with the account you accepted it under. " +
320
+ "Otherwise ask the company's owner or an admin for a new invite, then run `hq onboard join` with it.", err instanceof Error ? err : undefined);
321
+ }
371
322
  if (err instanceof VaultConflictError) {
372
323
  // Already accepted — that's fine for resume
373
324
  emit(onProgress, "accept-invite", "skipped", "Already accepted");
@@ -436,10 +387,9 @@ export async function joinCompanyFlow(input, config, onProgress) {
436
387
  }
437
388
  // Step 6: Write config
438
389
  emit(onProgress, "write-config", "running");
439
- // Get membership role from the accepted invite
440
- const members = await client.listMembersOfCompany(checkpoint.companyUid);
441
- const ours = members.find(m => m.personUid === checkpoint.personUid);
442
- const role = ours?.role ?? "member";
390
+ // The role comes from the caller's membership row; with no row, stop instead
391
+ // of guessing one.
392
+ const role = await callerMembershipRole(client, checkpoint);
443
393
  const configPath = await writeHqConfig(config.hqRoot, {
444
394
  companyUid: checkpoint.companyUid,
445
395
  companySlug: checkpoint.companySlug ?? "",
@@ -526,37 +476,224 @@ function emit(cb, step, status, detail) {
526
476
  function slugFromEmail(email) {
527
477
  return email.split("@")[0].toLowerCase().replace(/[^a-z0-9-]/g, "-");
528
478
  }
529
- async function safeGetEntity(client, uid) {
479
+ /** Person entities owned by the caller's sign-in (the server scopes by JWT). */
480
+ async function listOwnedPersons(client) {
481
+ const listed = await client.entity.listByType("person");
482
+ return (listed ?? []).filter((entity) => entity.type === "person");
483
+ }
484
+ /** The caller's person among those they own: email match, then slug, then oldest. */
485
+ function pickOwnedPerson(owned, email) {
486
+ if (owned.length === 0)
487
+ return null;
488
+ const wantedEmail = email.trim().toLowerCase();
489
+ const byEmail = owned.find((p) => {
490
+ const value = p.email;
491
+ return typeof value === "string" && value.trim().toLowerCase() === wantedEmail;
492
+ });
493
+ if (byEmail)
494
+ return byEmail;
495
+ const bySlug = owned.find((p) => p.slug === slugFromEmail(email));
496
+ if (bySlug)
497
+ return bySlug;
498
+ return [...owned].sort((a, b) => {
499
+ const ac = a.createdAt ?? "";
500
+ const bc = b.createdAt ?? "";
501
+ if (ac !== bc)
502
+ return ac < bc ? -1 : 1;
503
+ return a.uid < b.uid ? -1 : 1;
504
+ })[0];
505
+ }
506
+ /**
507
+ * Resolve the person record onboarding acts as (feedback_a169f6dc, DEV-1695).
508
+ *
509
+ * This used to fall back to a GLOBAL slug lookup on the email's local part
510
+ * ("jacob" for jacob@example.com). Another account's person with the same
511
+ * local part was adopted, create-person was marked complete, and the server
512
+ * then refused the owner membership because the caller does not own that
513
+ * person: create-company stopped at bootstrap-membership and resume looped on
514
+ * the identity-link guard. Only a person the caller owns is used now:
515
+ * 1. the checkpoint's person, when the caller owns it;
516
+ * 2. otherwise an owned person (email match, then slug, then oldest);
517
+ * 3. otherwise a new person, re-listing the owned persons on a create race.
518
+ */
519
+ async function resolveCallerPerson(client, checkpoint, input) {
520
+ const owned = await listOwnedPersons(client);
521
+ const fromCheckpoint = checkpoint.personUid
522
+ ? owned.find((p) => p.uid === checkpoint.personUid)
523
+ : undefined;
524
+ const existing = fromCheckpoint ?? pickOwnedPerson(owned, input.personEmail);
525
+ if (existing)
526
+ return { person: existing, detail: `Person already registered (${existing.uid})` };
527
+ if (!input.personEmail.trim()) {
528
+ // `resumeOnboarding` has no email to create a person with.
529
+ throw new Error("Your sign-in has no person record yet, and resume does not know your email to create one. " +
530
+ "Run `hq onboard create-company` (or `hq onboard join` with your invite) again; it continues from the saved progress.");
531
+ }
532
+ const personSlug = slugFromEmail(input.personEmail);
530
533
  try {
531
- return await client.entity.get(uid);
534
+ const person = await client.entity.create({
535
+ type: "person",
536
+ slug: personSlug,
537
+ name: input.personName,
538
+ email: input.personEmail,
539
+ });
540
+ return { person, detail: `personUid: ${person.uid}` };
532
541
  }
533
542
  catch (err) {
534
- if (err instanceof VaultNotFoundError)
535
- return null;
536
- throw err;
543
+ if (!(err instanceof VaultConflictError))
544
+ throw err;
545
+ // Lost a create race with another run under the same sign-in.
546
+ const raced = pickOwnedPerson(await listOwnedPersons(client), input.personEmail);
547
+ if (!raced)
548
+ throw err;
549
+ return { person: raced, detail: `Person already registered (${raced.uid})` };
537
550
  }
538
551
  }
539
552
  /**
540
- * Look up an entity by slug, returning null on 404 instead of throwing.
541
- *
542
- * Used by createCompanyFlow / joinCompanyFlow to detect existing person and
543
- * company entities BEFORE calling entity.create. This is defense-in-depth
544
- * against the vault-service not enforcing slug uniqueness server-side — even
545
- * if the server lets a duplicate create succeed, this guard ensures we never
546
- * issue the create call in the first place when an entity with the same slug
547
- * already exists.
553
+ * The create-person step for both flows. A completed step whose person the
554
+ * caller does not own (an earlier run adopted another account's record, or the
555
+ * checkpoint was left by another sign-in) is resolved again, so the run
556
+ * continues under the caller instead of failing at the membership step or
557
+ * writing the other sign-in's company into the config. The company and
558
+ * membership state is dropped with it. When the caller owns a person it is
559
+ * used; when the caller owns none yet, create-person is dropped too and runs
560
+ * again to create the caller's own person.
548
561
  */
549
- async function safeFindBySlug(client, type, slug) {
562
+ async function runPersonStep(client, checkpoint, input, config, onProgress) {
563
+ let previous;
564
+ if (isStepComplete(checkpoint, "create-person")) {
565
+ const owned = checkpoint.personUid ? await listOwnedPersons(client) : null;
566
+ const stale = owned !== null && !owned.some((p) => p.uid === checkpoint.personUid);
567
+ if (!stale) {
568
+ emit(onProgress, "create-person", "skipped", "Already complete");
569
+ return;
570
+ }
571
+ previous = checkpoint.personUid;
572
+ forgetMembershipState(checkpoint);
573
+ const relinked = pickOwnedPerson(owned, input.personEmail);
574
+ if (relinked) {
575
+ checkpoint.personUid = relinked.uid;
576
+ await writeCheckpoint(config.hqRoot, checkpoint);
577
+ emit(onProgress, "create-person", "done", `Using your sign-in's person record ${relinked.uid}; the saved record ${previous} belongs to another sign-in, ` +
578
+ `so the company and membership steps run again under your sign-in`);
579
+ return;
580
+ }
581
+ // The caller owns no person yet: forget the other sign-in's person as well,
582
+ // so the step below creates the caller's own.
583
+ delete checkpoint.personUid;
584
+ checkpoint.completedSteps = checkpoint.completedSteps.filter((step) => step !== "create-person");
585
+ await writeCheckpoint(config.hqRoot, checkpoint);
586
+ }
587
+ emit(onProgress, "create-person", "running");
550
588
  try {
551
- return await client.entity.findBySlug(type, slug);
589
+ const { person, detail } = await resolveCallerPerson(client, checkpoint, input);
590
+ checkpoint.personUid = person.uid;
591
+ checkpoint.completedSteps.push("create-person");
592
+ await writeCheckpoint(config.hqRoot, checkpoint);
593
+ emit(onProgress, "create-person", "done", previous
594
+ ? `${detail}; the saved record ${previous} belongs to another sign-in, so the company and membership steps run again under your sign-in`
595
+ : detail);
596
+ }
597
+ catch (err) {
598
+ checkpoint.failedStep = "create-person";
599
+ checkpoint.error = String(err);
600
+ await writeCheckpoint(config.hqRoot, checkpoint);
601
+ emit(onProgress, "create-person", "failed");
602
+ throw new PersonCreationError(`Failed to create person entity: ${err}`, err instanceof Error ? err : undefined);
603
+ }
604
+ }
605
+ /**
606
+ * Steps whose result depends on who the person is. They are only valid for the
607
+ * person (and sign-in) they ran under.
608
+ */
609
+ const MEMBERSHIP_DEPENDENT_STEPS = [
610
+ "create-company",
611
+ "provision-bucket",
612
+ "bootstrap-membership",
613
+ "accept-invite",
614
+ "verify-sts",
615
+ "first-sync",
616
+ "write-config",
617
+ ];
618
+ /**
619
+ * Drop everything a run recorded under another sign-in's person: the company,
620
+ * bucket and membership it found or made, and the steps that produced them.
621
+ * Without this, resume kept that run's `companyUid` and completed membership
622
+ * steps after re-linking the person, and `write-config` wrote
623
+ * `.hq/config.json` with `role: owner` for a company the caller never joined
624
+ * (review of hq-cli #2512, feedback_a169f6dc). The steps run again under the
625
+ * caller's own person. create-company looks the slug up only in the caller's
626
+ * namespace (companies they own or belong to), and bootstrap-membership stops
627
+ * unless the caller's own row is the owner, so create-company never sets up a
628
+ * company the caller does not own.
629
+ */
630
+ function forgetMembershipState(checkpoint) {
631
+ checkpoint.completedSteps = checkpoint.completedSteps.filter((step) => !MEMBERSHIP_DEPENDENT_STEPS.includes(step));
632
+ delete checkpoint.companyUid;
633
+ delete checkpoint.membershipKey;
634
+ delete checkpoint.role;
635
+ delete checkpoint.bucketName;
636
+ // For create-company the slug is the founder's own input and resume needs it;
637
+ // for join-company it came from the accepted invite's company.
638
+ if (checkpoint.mode === "join-company")
639
+ delete checkpoint.companySlug;
640
+ delete checkpoint.failedStep;
641
+ delete checkpoint.error;
642
+ }
643
+ /**
644
+ * The role on the caller's membership row in the checkpoint's company. Throws
645
+ * when there is no row for the caller's person, so a config is never written
646
+ * with a guessed role.
647
+ */
648
+ async function callerMembershipRole(client, checkpoint) {
649
+ const members = await client.listMembersOfCompany(checkpoint.companyUid);
650
+ const ours = members.find((m) => m.personUid === checkpoint.personUid);
651
+ if (!ours?.role) {
652
+ throw new Error(`Your person record ${checkpoint.personUid} has no membership in company ${checkpoint.companyUid}, ` +
653
+ "so no config was written. Run `hq onboard resume` again; if this repeats, ask the company's owner to check your invite.");
654
+ }
655
+ return ours.role;
656
+ }
657
+ /** Last `len` lowercase alphanumerics of `source` (hq-pro `companySlugTag`). */
658
+ function companySlugTag(source, len) {
659
+ return source.toLowerCase().replace(/[^a-z0-9]/g, "").slice(-len);
660
+ }
661
+ /** The `sub` claim of the caller's token, or null when it is not a readable JWT. */
662
+ async function callerSubject(config) {
663
+ const raw = config.vaultConfig.authToken;
664
+ const token = typeof raw === "function" ? await raw() : raw;
665
+ const payload = typeof token === "string" ? token.split(".")[1] : undefined;
666
+ if (!payload)
667
+ return null;
668
+ try {
669
+ const claims = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"));
670
+ return typeof claims.sub === "string" && claims.sub ? claims.sub : null;
671
+ }
672
+ catch {
673
+ return null;
674
+ }
675
+ }
676
+ /**
677
+ * The caller's company at `<slug>-<ownerTag>`, the slug hq-pro gives a
678
+ * company whose base slug another owner holds (`companySlugCandidates`; the
679
+ * owner tag is the tail of the owner's sign-in subject). A repeat create of
680
+ * that company 409s on the suffixed slug, so the base-slug lookup alone misses
681
+ * it and the run would say the slug is taken by another account.
682
+ */
683
+ async function findOwnerSuffixedCompany(client, config, baseSlug) {
684
+ const sub = await callerSubject(config);
685
+ const tag = sub ? companySlugTag(sub, 4) : "";
686
+ if (!tag)
687
+ return null;
688
+ return client.entity.findInMyNamespace("company", `${baseSlug}-${tag}`);
689
+ }
690
+ async function safeGetEntity(client, uid) {
691
+ try {
692
+ return await client.entity.get(uid);
552
693
  }
553
694
  catch (err) {
554
695
  if (err instanceof VaultNotFoundError)
555
696
  return null;
556
- // Defense against the mocked-error case where the SDK wrapper isn't an
557
- // instanceof match (mocks across module boundaries can break instanceof).
558
- if (err instanceof Error && err.name === "VaultNotFoundError")
559
- return null;
560
697
  throw err;
561
698
  }
562
699
  }
@@ -51,6 +51,8 @@ export interface OnboardingCheckpoint {
51
51
  companySlug?: string;
52
52
  bucketName?: string;
53
53
  membershipKey?: string;
54
+ /** Role on the caller's membership row, recorded when the membership step finds or makes it. */
55
+ role?: string;
54
56
  inviteToken?: string;
55
57
  completedSteps: OnboardingStep[];
56
58
  failedStep?: OnboardingStep;
@@ -1,5 +1,6 @@
1
1
  import semver from "semver";
2
- const SCAFFOLD_CLI_UPGRADE_COMMAND = "npm install -g @indigoai-us/hq-cli@latest";
2
+ import { HQ_CLI_NPM_UPDATE_COMMAND } from "../utils/npm-install-flags.js";
3
+ const SCAFFOLD_CLI_UPGRADE_COMMAND = HQ_CLI_NPM_UPDATE_COMMAND;
3
4
  const MINIMUM_VERSION_RANGE = /^>=(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;
4
5
  /** Compare an installed CLI version with the scaffold's supported floor. */
5
6
  export function compareScaffoldCliFloor(required, currentVersion) {
@@ -29,7 +29,9 @@ export const SIGNALS_RUN_ALERT_ADAPTER = "signals-run";
29
29
  /** The signed-in person, as `runCompanyHotChannelSync` resolves them; null when no one is signed in. */
30
30
  export function resolveSignedInAlertPerson() {
31
31
  const author = resolveUploadAuthor();
32
- if (!author)
32
+ // A sub-only upload author (machine token with no email) is not a person
33
+ // this alert can address.
34
+ if (!author?.email)
33
35
  return null;
34
36
  return { personKey: audienceKey([author.email]), personName: author.email, personUid: author.userSub };
35
37
  }