@indigoai-us/hq-cli 5.345.207 → 5.345.210

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 (129) hide show
  1. package/CHANGELOG.md +105 -0
  2. package/assets/scaffold/core/scripts/derive-trigger-facts.sh +22 -3
  3. package/dist/command-catalog.generated.d.ts +33 -8
  4. package/dist/command-catalog.generated.js +40 -8
  5. package/dist/command-registration-plan.d.ts +2 -2
  6. package/dist/command-registration-plan.js +1 -1
  7. package/dist/commands/access.js +11 -5
  8. package/dist/commands/agents.d.ts +8 -0
  9. package/dist/commands/agents.js +5 -0
  10. package/dist/commands/bot.d.ts +8 -0
  11. package/dist/commands/bot.js +67 -7
  12. package/dist/commands/channels.js +4 -0
  13. package/dist/commands/cloud.d.ts +83 -2
  14. package/dist/commands/cloud.js +161 -31
  15. package/dist/commands/company.d.ts +9 -0
  16. package/dist/commands/company.js +44 -14
  17. package/dist/commands/core-checkpoint-native.js +21 -0
  18. package/dist/commands/core-derive-trigger-facts-native.js +14 -3
  19. package/dist/commands/core-generate-workers-registry-fast.d.ts +1 -1
  20. package/dist/commands/core-generate-workers-registry-fast.js +7 -1
  21. package/dist/commands/core-job-run-native.d.ts +8 -0
  22. package/dist/commands/core-job-run-native.js +11 -3
  23. package/dist/commands/core-jobs-native.js +1 -1
  24. package/dist/commands/core-register-project-native.js +31 -1
  25. package/dist/commands/core-scan-packages-fast.d.ts +1 -1
  26. package/dist/commands/core-scan-packages-fast.js +8 -1
  27. package/dist/commands/core.js +12 -3
  28. package/dist/commands/dm-attach.d.ts +10 -0
  29. package/dist/commands/dm-attach.js +33 -5
  30. package/dist/commands/integrations-connect.js +47 -2
  31. package/dist/commands/lanes-session-start.d.ts +17 -0
  32. package/dist/commands/lanes-session-start.js +281 -13
  33. package/dist/commands/lanes-watch.js +11 -3
  34. package/dist/commands/lanes.d.ts +4 -0
  35. package/dist/commands/lanes.js +95 -22
  36. package/dist/commands/library.d.ts +10 -0
  37. package/dist/commands/library.js +30 -3
  38. package/dist/commands/meetings.d.ts +42 -0
  39. package/dist/commands/meetings.js +157 -12
  40. package/dist/commands/mesh.js +3 -0
  41. package/dist/commands/monitor.d.ts +6 -0
  42. package/dist/commands/monitor.js +29 -19
  43. package/dist/commands/onboard.js +8 -1
  44. package/dist/commands/sources.js +7 -3
  45. package/dist/commands/storage-offload.d.ts +3 -2
  46. package/dist/commands/storage-offload.js +30 -16
  47. package/dist/commands/storage.js +2 -1
  48. package/dist/index.js +9 -0
  49. package/dist/lanes-monitor-check-argv.d.ts +1 -1
  50. package/dist/lanes-monitor-check-argv.js +2 -2
  51. package/dist/lanes-session-start-argv.d.ts +4 -1
  52. package/dist/lanes-session-start-argv.js +5 -2
  53. package/dist/lib/bot/fleet-daemon.d.ts +101 -0
  54. package/dist/lib/bot/fleet-daemon.js +227 -0
  55. package/dist/lib/bot/fleet-local.d.ts +26 -0
  56. package/dist/lib/bot/fleet-local.js +51 -2
  57. package/dist/lib/bot/index.d.ts +1 -0
  58. package/dist/lib/bot/index.js +1 -0
  59. package/dist/lib/bot/jobs/hot-signal-sync.d.ts +4 -0
  60. package/dist/lib/bot/jobs/hot-signal-sync.js +8 -1
  61. package/dist/lib/bot/log.js +3 -1
  62. package/dist/lib/bot/probe.js +2 -0
  63. package/dist/lib/bot/run.js +28 -3
  64. package/dist/lib/bot/runtime-failure.d.ts +4 -2
  65. package/dist/lib/bot/runtime-failure.js +9 -1
  66. package/dist/lib/bot/status.d.ts +17 -0
  67. package/dist/lib/bot/status.js +53 -2
  68. package/dist/lib/capacity/collectors/claude-oauth.d.ts +5 -5
  69. package/dist/lib/capacity/collectors/claude-oauth.js +6 -6
  70. package/dist/lib/core-utils/native-scaffold-help.d.ts +16 -0
  71. package/dist/lib/core-utils/native-scaffold-help.js +26 -0
  72. package/dist/lib/core-utils/session-company.d.ts +25 -8
  73. package/dist/lib/core-utils/session-company.js +59 -17
  74. package/dist/lib/daemon/catalog.d.ts +25 -1
  75. package/dist/lib/daemon/catalog.js +29 -2
  76. package/dist/lib/daemon/run.d.ts +0 -1
  77. package/dist/lib/daemon/run.js +3 -11
  78. package/dist/lib/daemon/server.js +26 -7
  79. package/dist/lib/daemon/supervisor.js +1 -1
  80. package/dist/lib/daemon/tools.js +17 -1
  81. package/dist/lib/db/sqlite-binding.js +2 -1
  82. package/dist/lib/doctor/checks/bots.d.ts +2 -0
  83. package/dist/lib/doctor/checks/bots.js +11 -0
  84. package/dist/lib/doctor/checks/runtime-health.js +3 -2
  85. package/dist/lib/doctor/checks/work-context.js +5 -2
  86. package/dist/lib/hook-engine/resolve.d.ts +1 -1
  87. package/dist/lib/hook-engine/resolve.js +4 -1
  88. package/dist/lib/hot-channels/adapters/meeting-providers.d.ts +2 -0
  89. package/dist/lib/hot-channels/adapters/meeting-providers.js +13 -2
  90. package/dist/lib/lanes/index.d.ts +1 -1
  91. package/dist/lib/lanes/index.js +1 -1
  92. package/dist/lib/lanes/monitor.d.ts +14 -0
  93. package/dist/lib/lanes/monitor.js +51 -10
  94. package/dist/lib/lanes/outpost-dispatch.d.ts +3 -0
  95. package/dist/lib/lanes/outpost-dispatch.js +1 -0
  96. package/dist/lib/lanes/store.d.ts +1 -1
  97. package/dist/lib/lanes/store.js +2 -1
  98. package/dist/lib/mesh/client.js +7 -1
  99. package/dist/lib/mesh/live/backfill-held.d.ts +3 -0
  100. package/dist/lib/mesh/live/backfill-held.js +167 -7
  101. package/dist/lib/mesh/live/flush.d.ts +7 -0
  102. package/dist/lib/mesh/live/flush.js +10 -1
  103. package/dist/lib/monitor.d.ts +9 -0
  104. package/dist/lib/monitor.js +33 -7
  105. package/dist/lib/onboarding/orchestrator.js +269 -132
  106. package/dist/lib/onboarding/types.d.ts +2 -0
  107. package/dist/lib/scaffold-cli-floor.js +2 -1
  108. package/dist/lib/signals/failure-alert.js +3 -1
  109. package/dist/lib/work-context/organize.d.ts +6 -0
  110. package/dist/lib/work-context/organize.js +28 -0
  111. package/dist/lib/work-context/paths.d.ts +9 -0
  112. package/dist/lib/work-context/paths.js +15 -0
  113. package/dist/lib/work-context/prd-sync.js +2 -1
  114. package/dist/runners-alias.d.ts +54 -0
  115. package/dist/runners-alias.js +86 -0
  116. package/dist/utils/install-tree-torn.js +5 -3
  117. package/dist/utils/npm-install-flags.d.ts +27 -0
  118. package/dist/utils/npm-install-flags.js +68 -0
  119. package/dist/utils/package-use-lease.js +1 -1
  120. package/dist/utils/qmd-native-binding-error.js +2 -1
  121. package/dist/utils/self-update.js +2 -1
  122. package/dist/utils/staged-install.js +2 -1
  123. package/dist/utils/staged-npm-install.js +2 -1
  124. package/dist/utils/upload-author.d.ts +2 -1
  125. package/dist/utils/upload-author.js +9 -5
  126. package/dist/utils/version-check.js +2 -1
  127. package/dist/utils/version-gate.js +7 -6
  128. package/package.json +7 -7
  129. package/scripts/install-hook-engine.mjs +7 -3
@@ -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
  }
@@ -126,6 +126,12 @@ export declare function submitOrganizeDecision(input: {
126
126
  untracked?: boolean;
127
127
  now?: () => Date;
128
128
  postOrganize?: PostOrganizeFn;
129
+ /**
130
+ * Lists server candidates before an explicit create. The server stamps the
131
+ * per-actor decision window only when candidates are listed, and refuses an
132
+ * organize without one (409 DECISION_WINDOW_MISSING).
133
+ */
134
+ fetchCandidates?: FetchCandidatesFn;
129
135
  }): Promise<OrganizeSubmitResult>;
130
136
  export {};
131
137
  //# sourceMappingURL=organize.d.ts.map
@@ -426,6 +426,27 @@ export async function submitOrganizeDecision(input) {
426
426
  message: "No organize transport; server receipt required for success",
427
427
  };
428
428
  }
429
+ // An explicit --create-project / --create-task does not come from a listed
430
+ // decision, so nothing has opened the server's decision window yet: `--list`
431
+ // only lists candidates once the work-signal threshold is crossed. Open the
432
+ // window here so the create is not refused with DECISION_WINDOW_MISSING.
433
+ if ((decision.kind === "create_project" || decision.kind === "create_task") &&
434
+ input.fetchCandidates) {
435
+ try {
436
+ await input.fetchCandidates({
437
+ sessionId: input.sessionId,
438
+ companyUid: state.companyUid,
439
+ });
440
+ }
441
+ catch (err) {
442
+ const message = err instanceof Error ? err.message : String(err);
443
+ return {
444
+ ok: false,
445
+ errorCode: "CANDIDATES_UNAVAILABLE",
446
+ message: `could not open the organize decision window: ${message}`,
447
+ };
448
+ }
449
+ }
429
450
  // Stale decision → typed error (caller may refresh candidates).
430
451
  if (decisionExpiresAt) {
431
452
  const exp = Date.parse(decisionExpiresAt);
@@ -459,6 +480,13 @@ export async function submitOrganizeDecision(input) {
459
480
  }
460
481
  catch (err) {
461
482
  const message = err instanceof Error ? err.message : String(err);
483
+ if (/DECISION_WINDOW_MISSING/.test(message)) {
484
+ return {
485
+ ok: false,
486
+ errorCode: "DECISION_WINDOW_MISSING",
487
+ message: `${message} (the server opens the decision window when candidates are listed for this session)`,
488
+ };
489
+ }
462
490
  if (/DECISION_EXPIRED|409/.test(message)) {
463
491
  return { ok: false, errorCode: "DECISION_EXPIRED", message };
464
492
  }
@@ -7,6 +7,15 @@ export declare function workContextRoot(home?: string, env?: NodeJS.ProcessEnv):
7
7
  export declare function workContextConfigPath(root?: string): string;
8
8
  export declare function workContextSessionsDir(root?: string): string;
9
9
  export declare function workContextSessionPath(sessionId: string, root?: string): string;
10
+ /**
11
+ * Per-session sidecar files kept beside `<sessionId>.json` in the sessions
12
+ * directory. They are not session state files, so readers that scan the
13
+ * directory for session state (doctor state-file health) must skip them.
14
+ */
15
+ export declare const WORK_CONTEXT_PRD_SNAPSHOT_SUFFIX = ".prd-snapshot.json";
16
+ export declare const WORK_CONTEXT_SESSION_SIDECAR_SUFFIXES: readonly string[];
17
+ /** True for `<sessionId>.json`, false for sidecars and non-JSON entries. */
18
+ export declare function isWorkContextSessionStateFileName(name: string): boolean;
10
19
  export declare function workContextOutboxDir(root?: string): string;
11
20
  export declare function workContextOutboxPath(operationId: string, root?: string): string;
12
21
  /** Safe path segment for session/operation ids (no traversal). */
@@ -20,6 +20,21 @@ export function workContextSessionsDir(root) {
20
20
  export function workContextSessionPath(sessionId, root) {
21
21
  return path.join(workContextSessionsDir(root), `${sessionId}.json`);
22
22
  }
23
+ /**
24
+ * Per-session sidecar files kept beside `<sessionId>.json` in the sessions
25
+ * directory. They are not session state files, so readers that scan the
26
+ * directory for session state (doctor state-file health) must skip them.
27
+ */
28
+ export const WORK_CONTEXT_PRD_SNAPSHOT_SUFFIX = ".prd-snapshot.json";
29
+ export const WORK_CONTEXT_SESSION_SIDECAR_SUFFIXES = [
30
+ WORK_CONTEXT_PRD_SNAPSHOT_SUFFIX,
31
+ ];
32
+ /** True for `<sessionId>.json`, false for sidecars and non-JSON entries. */
33
+ export function isWorkContextSessionStateFileName(name) {
34
+ if (!name.endsWith(".json"))
35
+ return false;
36
+ return !WORK_CONTEXT_SESSION_SIDECAR_SUFFIXES.some((suffix) => name.endsWith(suffix));
37
+ }
23
38
  export function workContextOutboxDir(root) {
24
39
  return path.join(root ?? workContextRoot(), "outbox");
25
40
  }
@@ -9,8 +9,9 @@ import * as fs from "node:fs";
9
9
  import * as path from "node:path";
10
10
  import { readSessionState, updateSessionState } from "./state.js";
11
11
  import { mapReaderStoryStatus } from "../mesh/story-status.js";
12
+ import { WORK_CONTEXT_PRD_SNAPSHOT_SUFFIX } from "./paths.js";
12
13
  export function prdSnapshotPath(sessionId, root) {
13
- return path.join(root, "sessions", `${sessionId}.prd-snapshot.json`);
14
+ return path.join(root, "sessions", `${sessionId}${WORK_CONTEXT_PRD_SNAPSHOT_SUFFIX}`);
14
15
  }
15
16
  export function readPrdSnapshot(sessionId, root) {
16
17
  try {