@tpsdev-ai/flair 0.56.0 → 0.58.0

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 (153) hide show
  1. package/README.md +19 -20
  2. package/SECURITY.md +4 -1
  3. package/dist/build-info.json +3 -3
  4. package/dist/cli.js +1800 -293
  5. package/dist/commands/agent.js +22 -15
  6. package/dist/commands/bridge.js +40 -3
  7. package/dist/commands/doctor.js +214 -4
  8. package/dist/commands/federation.js +265 -38
  9. package/dist/commands/hook.js +10 -2
  10. package/dist/commands/init.js +179 -48
  11. package/dist/commands/memory.js +24 -2
  12. package/dist/commands/quality.js +26 -18
  13. package/dist/commands/service.js +137 -22
  14. package/dist/commands/status.js +114 -3
  15. package/dist/commands/upgrade.js +204 -84
  16. package/dist/doctor-client.js +50 -4
  17. package/dist/federation/scheduler.js +253 -4
  18. package/dist/install/clients.js +89 -23
  19. package/dist/install/global-bin-path.js +26 -6
  20. package/dist/lib/atomic-write.js +256 -0
  21. package/dist/lib/auth-resolve.js +46 -0
  22. package/dist/lib/daemon-liveness.js +61 -0
  23. package/dist/lib/doctor-run.js +5 -0
  24. package/dist/lib/embed-gpu-doctor.js +49 -26
  25. package/dist/lib/federation-memory-attributes.js +15 -0
  26. package/dist/lib/init-admin-pass.js +4 -2
  27. package/dist/lib/init-listener-environ.js +38 -0
  28. package/dist/lib/init-occupied-listener.js +165 -0
  29. package/dist/lib/instance-identity-row.js +580 -0
  30. package/dist/lib/launchd-domain-preflight.js +448 -0
  31. package/dist/lib/launchd-management.js +176 -6
  32. package/dist/lib/launchd-repair.js +95 -0
  33. package/dist/lib/memory-attributes.js +77 -0
  34. package/dist/lib/node-alias-path.js +95 -0
  35. package/dist/lib/npm-registry.js +119 -6
  36. package/dist/lib/owned-pins.js +20 -6
  37. package/dist/lib/redact-token-id.js +197 -0
  38. package/dist/lib/service-repoint-apply.js +267 -0
  39. package/dist/lib/service-repoint.js +575 -0
  40. package/dist/lib/toml-string-array.js +104 -0
  41. package/dist/lib/tree-divergence.js +716 -0
  42. package/dist/lib/upgrade-plain-tree.js +18 -8
  43. package/dist/lib/upgrade-prior-liveness.js +69 -0
  44. package/dist/lib/upgrade-rollback.js +116 -0
  45. package/dist/rem/runner.js +11 -0
  46. package/dist/resources/Agent.js +27 -14
  47. package/dist/resources/AgentSeed.js +39 -2
  48. package/dist/resources/Asset.js +3 -11
  49. package/dist/resources/Credential.js +4 -10
  50. package/dist/resources/Federation.js +299 -127
  51. package/dist/resources/Integration.js +8 -32
  52. package/dist/resources/Memory.js +623 -86
  53. package/dist/resources/MemoryArchive.js +9 -0
  54. package/dist/resources/MemoryBootstrap.js +23 -12
  55. package/dist/resources/MemoryCandidate.js +3 -11
  56. package/dist/resources/MemoryDedupStats.js +1 -1
  57. package/dist/resources/MemoryFeed.js +214 -5
  58. package/dist/resources/MemoryGrant.js +19 -40
  59. package/dist/resources/MemoryHostSource.js +90 -0
  60. package/dist/resources/MemoryMaintenance.js +121 -32
  61. package/dist/resources/MemoryReflect.js +4 -1
  62. package/dist/resources/MemoryReindex.js +7 -4
  63. package/dist/resources/MemoryUsage.js +55 -18
  64. package/dist/resources/Presence.js +18 -10
  65. package/dist/resources/RecordUsage.js +30 -40
  66. package/dist/resources/Relationship.js +170 -89
  67. package/dist/resources/SemanticSearch.js +44 -19
  68. package/dist/resources/Soul.js +31 -19
  69. package/dist/resources/XAA.js +7 -3
  70. package/dist/resources/agent-auth.js +16 -10
  71. package/dist/resources/auth-middleware.js +164 -50
  72. package/dist/resources/auto-promote-lib.js +4 -4
  73. package/dist/resources/bm25-index-service.js +246 -32
  74. package/dist/resources/bm25-status.js +132 -0
  75. package/dist/resources/bm25.js +13 -14
  76. package/dist/resources/ed25519-auth.js +11 -54
  77. package/dist/resources/embed-gpu.js +262 -47
  78. package/dist/resources/embeddings-boot.js +52 -17
  79. package/dist/resources/federation-classify.js +12 -0
  80. package/dist/resources/federation-cleanup.js +289 -51
  81. package/dist/resources/federation-crypto.js +65 -19
  82. package/dist/resources/health.js +105 -22
  83. package/dist/resources/host-pointer/registry.js +35 -0
  84. package/dist/resources/host-pointer-adapter.js +15 -0
  85. package/dist/resources/host-source-visibility.js +167 -0
  86. package/dist/resources/host-source.js +151 -0
  87. package/dist/resources/in-process-api.js +2 -1
  88. package/dist/resources/instance-create-lock.js +363 -0
  89. package/dist/resources/instance-identity-rows.js +43 -0
  90. package/dist/resources/instance-identity.js +97 -12
  91. package/dist/resources/mcp-handler.js +155 -51
  92. package/dist/resources/mcp-tool-arguments.js +83 -0
  93. package/dist/resources/mcp-tools.js +28 -25
  94. package/dist/resources/memory-consolidate-lib.js +3 -1
  95. package/dist/resources/memory-declared-attributes.js +103 -0
  96. package/dist/resources/memory-feed-lib.js +5 -1
  97. package/dist/resources/memory-host-source.js +163 -0
  98. package/dist/resources/memory-visibility.js +10 -7
  99. package/dist/resources/migrations/synthetic-test-migration.js +4 -1
  100. package/dist/resources/migrations/visibility-backfill.js +4 -1
  101. package/dist/resources/originator-instance.js +235 -0
  102. package/dist/resources/promotion-stamp.js +2 -0
  103. package/dist/resources/provenance.js +111 -11
  104. package/dist/resources/rate-limit.js +6 -4
  105. package/dist/resources/record-owner-guard.js +19 -0
  106. package/dist/resources/record-type-kit.js +44 -23
  107. package/dist/resources/record-types.js +6 -6
  108. package/dist/resources/relay-ops.js +28 -3
  109. package/dist/resources/replay-store.js +289 -0
  110. package/dist/resources/request-transaction.js +78 -0
  111. package/dist/resources/search-readiness.js +26 -22
  112. package/dist/resources/semantic-retrieval-core.js +103 -4
  113. package/dist/resources/table-helpers.js +33 -0
  114. package/dist/resources/table-patch-policy.js +109 -0
  115. package/dist/resources/table-patches.js +17 -0
  116. package/dist/resources/table-post-policy.js +138 -0
  117. package/dist/resources/table-posts.js +22 -0
  118. package/dist/resources/table-subscription-policy.js +135 -0
  119. package/dist/resources/table-subscriptions.js +19 -0
  120. package/dist/resources/tool-descriptors/index.js +15 -15
  121. package/dist/resources/trust-block.js +10 -3
  122. package/dist/resources/usage-recording.js +169 -41
  123. package/dist/src/lib/instance-identity-row.js +580 -0
  124. package/dist/src/lib/memory-attributes.js +77 -0
  125. package/dist/src/lib/redact-token-id.js +197 -0
  126. package/docs/api-reference.md +80 -16
  127. package/docs/auth.md +5 -5
  128. package/docs/claude-code.md +137 -6
  129. package/docs/deploying-on-fabric.md +6 -3
  130. package/docs/deployment.md +1 -1
  131. package/docs/embedding-in-a-harper-app.md +3 -3
  132. package/docs/federation.md +17 -10
  133. package/docs/hosted-on-fabric.md +4 -3
  134. package/docs/integrations.md +28 -19
  135. package/docs/mcp-clients.md +26 -32
  136. package/docs/n8n.md +8 -8
  137. package/docs/notes/mcp-oauth-model2.md +27 -18
  138. package/docs/openclaw.md +29 -28
  139. package/docs/quickstart.md +5 -0
  140. package/docs/releasing.md +134 -2
  141. package/docs/spoke-bringup.md +14 -11
  142. package/docs/standalone-local.md +2 -2
  143. package/docs/supply-chain-policy.md +28 -10
  144. package/docs/system-requirements.md +1 -1
  145. package/docs/troubleshooting.md +11 -0
  146. package/docs/upgrade.md +189 -63
  147. package/package.json +9 -5
  148. package/schemas/agent.graphql +9 -6
  149. package/schemas/federation.graphql +2 -11
  150. package/schemas/memory.graphql +106 -17
  151. package/schemas/replay.graphql +18 -0
  152. package/templates/launchd/start-flair-with-admin-pass.sh +22 -0
  153. package/dist/resources/federation-nonce-store.js +0 -195
package/dist/cli.js CHANGED
@@ -24,18 +24,28 @@ import { flairConfigPath, flairDataDir } from "./lib/flair-paths.js";
24
24
  import { httpBind, httpCorsAccessList, preserveHttpPortValue, preserveSecurePort, qualifySecureBindValue, DEFAULT_HTTP_BIND_HOST, } from "./lib/http-bind.js";
25
25
  import { isNodeKeyId, partitionKeyIds, } from "./doctor-client.js";
26
26
  import { cliBootPathWarning, } from "./install/global-bin-path.js";
27
- import { readSecretFileSecure, readAdminPassFileSecure, defaultAdminPassPath, defaultKeysDir, resolveLocalAdminPass, DEFAULT_ADMIN_USER, resolveAdminUser, resolveKeyPath, buildEd25519Auth, authFetch, KeyLoadError, isLocalBase, authedRequest, } from "./lib/auth-resolve.js";
27
+ import { readSecretFileSecure, readAdminPassFileSecure, defaultAdminPassPath, defaultKeysDir, resolveLocalAdminPass, resolveAdminPassFromSources, ADMIN_PASS_FLAG, ADMIN_PASS_HELP, ADMIN_PASS_FILE_FLAG, ADMIN_PASS_FILE_HELP, DEFAULT_ADMIN_USER, resolveAdminUser, resolveKeyPath, buildEd25519Auth, authFetch, KeyLoadError, isLocalBase, authedRequest, } from "./lib/auth-resolve.js";
28
28
  import { resolveSigningIdentity, emitSigningIdentityDebug, } from "./lib/signing-identity.js";
29
29
  import { entityFormatHint, parseEntitiesCsv } from "./lib/entity-vocab-cli.js";
30
30
  import { escapeXml, unescapeXml } from "./lib/xml-escape.js";
31
- import { assessLaunchdManagement, diagnoseLaunchdPlistPaths, isDetached, pickInstancePid, plistCarriesInlineAdminPassword, readLaunchctlJobState, readPlistProgramRefs, LAUNCHCTL_QUERY_TIMEOUT_MS, } from "./lib/launchd-management.js";
32
- import { classifyPlist, planLaunchdRepair, mapRepairThrow, decideAdoptStopWithWait, verifyAdoptServingWithWait, } from "./lib/launchd-repair.js";
31
+ import { assessLaunchdManagement, verifyLaunchdManagement, checkLaunchdPlistBeforeLoad, diagnoseLaunchdPlistPaths, isDetached, pickInstancePid, plistCarriesInlineAdminPassword, readLaunchctlJobState, readPlistProgramRefs, LAUNCHCTL_QUERY_TIMEOUT_MS, } from "./lib/launchd-management.js";
32
+ import { classifyPlist, planLaunchdRepair, mapRepairThrow, decideAdoptStopWithWait, verifyAdoptServingWithWait, awaitLaunchdJobServing, judgeLaunchdJobServing, domainPreflightRefusal, } from "./lib/launchd-repair.js";
33
+ import { assessLaunchdLoadability, describeLoadabilityProblem, ensureLaunchdJobAbsent, firstLaunchdJobNotProvenAbsent, isLaunchdValidationRefusal, launchdJobPresence, launchdGuiDomain, loadabilityAllowsAttempt, loadabilityRemedy, loadLaunchdJob, LaunchdValidationRefusal, renderStartLaunchdFailed, renderStartLaunchdUnavailable, renderStartLaunchdUnloadUncertain, renderStartLaunchdValidationBlocked, renderStartLaunchdValidationRefused, DIRECT_PROCESS_GUARD_NOTE, DOMAIN_PROBE_TIMEOUT_MS, RUN_AT_LOAD_NOTE, } from "./lib/launchd-domain-preflight.js";
34
+ import { assessTreeDivergence, linuxUnitProbe, mainPidFromShow, proveServingTree, systemdUnitStateFromShow, } from "./lib/tree-divergence.js";
35
+ import { planPlistRuntimeRepoint } from "./lib/service-repoint.js";
36
+ import { applyRepointPlan, repointSystemdUserUnit, restartOnLinux } from "./lib/service-repoint-apply.js";
37
+ // Aliased: this file also declares its own FileSnapshot (flair#2040's raw-bytes
38
+ // snapshot for byte-exact restores); this is atomic-write's regular-file snapshot.
39
+ import { snapshotRegularFile } from "./lib/atomic-write.js";
40
+ import { preferVersionManagerAlias } from "./lib/node-alias-path.js";
33
41
  import { stabilizeMqttNetworkKeyOrder } from "./lib/stabilize-mqtt-network.js";
34
42
  import { detectOpsApiAllInterfacesBind } from "./lib/ops-api-bind.js";
35
43
  import { applyUpgradeHookConsent, runDoctorChecks, } from "./lib/doctor-run.js";
36
44
  import { classifyInstalledVersion, shouldPrintUpgradeLine, upgradeStatusSuffix } from "./lib/upgrade-status.js";
37
- import { classifyDaemonState, verifyIdentity, parseSidecarJson, classifyHealthProbe, classifyPortOwner, classifyInstanceMatch, shouldAdoptMissingSidecar, parseNullSeparatedEnviron, extractRootPath, } from "./lib/daemon-liveness.js";
45
+ import { classifyDaemonState, verifyIdentity, parseSidecarJson, classifyHealthProbe, classifyPortOwner, classifyInstanceMatch, shouldAdoptMissingSidecar, classifySidecarStaleness, shouldRemoveSidecarAfterStop, livenessFromKillError, parseNullSeparatedEnviron, extractRootPath, } from "./lib/daemon-liveness.js";
38
46
  import { readProcessStartTimeMs } from "./lib/process-start-time.js";
47
+ import { readInitListenerRootPath } from "./lib/init-listener-environ.js";
48
+ import { listenerFromLookup, occupiedListenerAuthFailure, stableAnsweredHolder, } from "./lib/init-occupied-listener.js";
39
49
  import { bindCli as bindFederationCli, register as registerFederation, signRequestBody, parseTokenFromFile, runFederationSyncOnce, persistLocalPeerLastSyncAt, runFederationWatch, federationStatusUrlSetting, describeFederationStatusFetchFailed, isFederationStatusConnectFailure, rewriteFederationStatusFetchFailed, isFederationStatusAuthFailure, isFederationStatusAuthRemedy, } from "./commands/federation.js";
40
50
  import { describeFederationPairHubAccessError, describeFederationPairLocalAccessError, rewriteFederationPairHubAccessError, rewriteFederationPairLocalAccessError, } from "./lib/federation-pair-access.js";
41
51
  import { bindCli as bindMemoryCli, register as registerMemory, categorizeForHygiene, HYGIENE_TEST_CONTENT_PATTERNS, } from "./commands/memory.js";
@@ -53,8 +63,10 @@ import { bindCli as bindPrincipalCli, register as registerPrincipal, agentRecord
53
63
  import { bindCli as bindPresenceCli, register as registerPresence, VALID_PRESENCE_ACTIVITIES, MAX_TASK_LENGTH, } from "./commands/presence.js";
54
64
  import { bindCli as bindRelationshipCli, register as registerRelationship, } from "./commands/relationship.js";
55
65
  import { bindCli as bindWorkspaceCli, register as registerWorkspace, MAX_WORKSPACE_FIELD_LENGTH, } from "./commands/workspace.js";
66
+ import { decideHubReconcile, instanceWriteNotVerifiedMessage, multipleInstanceRowsMessage, readInstanceRows, updateInstanceRole, verifyInstanceWrite, } from "./lib/instance-identity-row.js";
56
67
  import { applyUpgradeMigrations } from "./lib/upgrade-migrations.js";
57
- import { defaultReadProcessCmdline, defaultReadProcessCwd, resolveServingFlairPackage, } from "./lib/upgrade-exec-path.js";
68
+ import { defaultReadProcessCmdline, defaultReadProcessCwd, findFlairPackageDir, readFlairPackageAt, resolveServingFlairPackage, } from "./lib/upgrade-exec-path.js";
69
+ import { applyPlainTreeUpgrade, userSystemdDir, } from "./lib/upgrade-plain-tree.js";
58
70
  import { bindCli as bindOrgeventCli, register as registerOrgevent, MAX_ORGEVENT_DETAIL_LENGTH, MAX_ORGEVENT_SUMMARY_LENGTH, publishOrgEvent, } from "./commands/orgevent.js";
59
71
  import { bindCli as bindAttentionCli, register as registerAttention, } from "./commands/attention.js";
60
72
  import { bindCli as bindBootstrapCli, register as registerBootstrap, } from "./commands/bootstrap.js";
@@ -302,6 +314,34 @@ function resolveLaunchdLabel(dataDir, launchAgentsDir = defaultLaunchAgentsDir()
302
314
  return { label: LEGACY_LAUNCHD_LABEL, plistPath: legacyPlistPath, isLegacy: true };
303
315
  return { label: newLabel, plistPath: newPlistPath, isLegacy: false };
304
316
  }
317
+ /**
318
+ * Test seam (flair#2040): the lint migrateLegacyLaunchdLabel runs when its
319
+ * caller injects none — which is every start path — and the lint `flair init`
320
+ * runs over the plist it writes when it retires a legacy registration
321
+ * (flair#2078). Lets a command-level test drive `flair start`, the start leg
322
+ * and init's launchd step with a lint that throws. Production leaves this
323
+ * unset.
324
+ */
325
+ let launchdMigrationLintForTests = null;
326
+ export function setLaunchdMigrationLintForTests(lint) {
327
+ launchdMigrationLintForTests = lint;
328
+ }
329
+ /**
330
+ * Run `lint` over a replacement plist before anything is unloaded (flair#2040,
331
+ * flair#2078): the problem line it reports, or null when it passed. A lint that
332
+ * THROWS instead of answering (its temporary copy could not be created, written
333
+ * or removed, say) checked nothing. That is a LaunchdValidationRefusal whose
334
+ * message is `refusal("the lint failed: <error>")`: never a pass, and never a
335
+ * plain error that escapes the caller's refusal handling.
336
+ */
337
+ function lintReplacementPlist(content, lint, refusal) {
338
+ try {
339
+ return lint(content);
340
+ }
341
+ catch (err) {
342
+ throw new LaunchdValidationRefusal(refusal(`the lint failed: ${err?.message ?? String(err)}`));
343
+ }
344
+ }
305
345
  /**
306
346
  * Migrate a pre-flair#693 legacy-labeled launchd service to the new
307
347
  * instance-scoped label for `dataDir`: unload the legacy service FIRST,
@@ -310,19 +350,32 @@ function resolveLaunchdLabel(dataDir, launchAgentsDir = defaultLaunchAgentsDir()
310
350
  * file. There is never a moment where both the legacy and new labels are
311
351
  * registered for the same data dir. No-op (migrated: false) if there's
312
352
  * nothing legacy to migrate, or the new label is already registered.
353
+ *
354
+ * flair#2040: before anything is unloaded, the legacy plist must be readable,
355
+ * and the replacement content must carry the expected Label and pass
356
+ * `opts.lint` (plutil -lint by default). Any of these failing throws a
357
+ * LaunchdValidationRefusal with nothing unloaded, written or removed — and so
358
+ * does a lint that throws instead of answering.
313
359
  */
314
- function migrateLegacyLaunchdLabel(dataDir, runLaunchctl, launchAgentsDir = defaultLaunchAgentsDir()) {
360
+ function migrateLegacyLaunchdLabel(dataDir, runLaunchctl, launchAgentsDir = defaultLaunchAgentsDir(), uid = currentUid(), opts = {}) {
315
361
  const resolved = resolveLaunchdLabel(dataDir, launchAgentsDir);
316
362
  if (!resolved.isLegacy) {
317
363
  return { migrated: false, label: resolved.label, plistPath: resolved.plistPath };
318
364
  }
319
365
  const newLabel = launchdLabel(dataDir);
320
366
  const newPlistPath = launchdPlistPath(newLabel, launchAgentsDir);
367
+ // flair#2040: read and validate the plist BEFORE unloading anything. Every
368
+ // refusal up to the legacy bootout below is a LaunchdValidationRefusal:
369
+ // nothing has been loaded or unloaded, and the callers must not boot out the
370
+ // legacy job in response to it.
371
+ let legacyContent;
321
372
  try {
322
- runLaunchctl(`launchctl unload "${resolved.plistPath}"`);
373
+ legacyContent = readFileSync(resolved.plistPath, "utf-8");
374
+ }
375
+ catch (err) {
376
+ throw new LaunchdValidationRefusal(`not migrating off the legacy launchd label: could not read the legacy plist ${resolved.plistPath} (${err?.code ?? err}). ` +
377
+ "Nothing was unloaded, and the legacy plist was left as it was.");
323
378
  }
324
- catch { /* best effort */ }
325
- const legacyContent = readFileSync(resolved.plistPath, "utf-8");
326
379
  // Use a function replacer to avoid $-sensitivity in the replacement
327
380
  // string (flair#919). String.prototype.replace interprets $&, $', $`
328
381
  // etc. in the replacement even when the search value is a plain string.
@@ -332,15 +385,48 @@ function migrateLegacyLaunchdLabel(dataDir, runLaunchctl, launchAgentsDir = defa
332
385
  // Refuse to propagate a malformed plist: if the Label wasn't found,
333
386
  // the plist is not what we expect and migration must not write it.
334
387
  if (newContent === legacyContent) {
335
- throw new Error(`Legacy plist at ${resolved.plistPath} does not contain the expected ` +
388
+ throw new LaunchdValidationRefusal(`Legacy plist at ${resolved.plistPath} does not contain the expected ` +
336
389
  `Label key — it may be malformed or from an unknown Flair version. ` +
337
390
  `Remove it manually and re-run 'flair init'.`);
338
391
  }
392
+ // flair#2040: a plist that still carries the expected Label can be malformed
393
+ // XML, which bootstrap would reject only AFTER the legacy job was unloaded.
394
+ // Lint the replacement content now, before anything is unloaded; a lint that
395
+ // could not run is a failed check, not a pass. So is a lint that THREW (its
396
+ // temporary copy could not be created, written or removed, say): every lint
397
+ // exception is a validation refusal here. A plain error would reach the start
398
+ // paths' failed-LOAD handling, which boots the legacy job out.
399
+ const lint = opts.lint ?? launchdMigrationLintForTests ?? lintLaunchdPlistContent;
400
+ const lintProblem = lintReplacementPlist(newContent, lint, (failure) => `not migrating off the legacy launchd label: the replacement plist for ${newLabel} could not be validated ` +
401
+ `(${failure}). Nothing was unloaded, and the legacy plist ${resolved.plistPath} was left as it was.`);
402
+ if (lintProblem !== null) {
403
+ throw new LaunchdValidationRefusal(`not migrating off the legacy launchd label: the replacement plist for ${newLabel} failed validation ` +
404
+ `(${lintProblem}). Nothing was unloaded, and the legacy plist ${resolved.plistPath} was left as it was.`);
405
+ }
406
+ // Targeted at the GUI domain the preflight probed (flair#2040), not the
407
+ // domain launchctl would infer for this process — and VERIFIED: migrating
408
+ // while the legacy job may still be loaded would leave launchd two jobs for
409
+ // one data directory.
410
+ const legacyGone = ensureLaunchdJobAbsent({ run: runLaunchctl, domain: launchdGuiDomain(uid), label: LEGACY_LAUNCHD_LABEL, settleMs: opts.settleMs, sleep: opts.sleep });
411
+ if (legacyGone !== null) {
412
+ throw new Error(`not migrating off the legacy launchd label: ${legacyGone}. The legacy plist ${resolved.plistPath} was left as it was.`);
413
+ }
339
414
  writeFileSync(newPlistPath, newContent);
415
+ // Two plists for one data directory would give launchd two jobs at the next
416
+ // login: a legacy plist that cannot be removed undoes the migration.
340
417
  try {
341
418
  unlinkSync(resolved.plistPath);
342
419
  }
343
- catch { /* best effort */ }
420
+ catch (err) {
421
+ if (err?.code !== "ENOENT") {
422
+ try {
423
+ unlinkSync(newPlistPath);
424
+ }
425
+ catch { /* reported below */ }
426
+ throw new Error(`not migrating off the legacy launchd label: could not remove ${resolved.plistPath} (${err?.code ?? err}); ` +
427
+ `${newPlistPath} was removed again.`);
428
+ }
429
+ }
344
430
  return { migrated: true, label: newLabel, plistPath: newPlistPath };
345
431
  }
346
432
  /**
@@ -354,35 +440,42 @@ function migrateLegacyLaunchdLabel(dataDir, runLaunchctl, launchAgentsDir = defa
354
440
  * real launchd. The caller (init) passes a real execSync wrapper; tests
355
441
  * pass a recording stub.
356
442
  */
357
- function cleanupLegacyLaunchdPlist(dataDir, plistDir, runLaunchctl) {
443
+ function cleanupLegacyLaunchdPlist(dataDir, plistDir, runLaunchctl, uid = currentUid(), opts = {}) {
358
444
  const legacyPlistPath = launchdPlistPath(LEGACY_LAUNCHD_LABEL, plistDir);
359
445
  if (!existsSync(legacyPlistPath))
360
446
  return { action: "none" };
361
447
  const legacyRootPath = readPlistRootPath(legacyPlistPath);
362
448
  const legacyOwnedByUs = legacyRootPath !== null && resolve(legacyRootPath) === resolve(dataDir);
363
449
  if (legacyOwnedByUs) {
364
- let unloadFailed;
365
450
  let deleteFailed;
366
- try {
367
- runLaunchctl(`launchctl unload "${legacyPlistPath}"`);
368
- }
369
- catch (err) {
370
- unloadFailed = err?.message ?? String(err);
371
- console.error(`Failed to unload legacy launchd service (${LEGACY_LAUNCHD_LABEL}): ` +
372
- `${unloadFailed}. ` +
373
- `The plist at ${legacyPlistPath} may still be loaded — ` +
374
- `unload it manually with: launchctl unload "${legacyPlistPath}"`);
451
+ // flair#2040: targeted at the GUI domain, only when the job is loaded
452
+ // there, and VERIFIED gone afterwards (ensureLaunchdJobAbsent) — a bootout
453
+ // error is reported, never read as success. Callers that may be booting
454
+ // out the job SERVING the instance must preflight + restore
455
+ // (registerInitLaunchdService); this helper is the PROVEN-not-serving
456
+ // cleanup.
457
+ const domain = launchdGuiDomain(uid);
458
+ const gone = ensureLaunchdJobAbsent({ run: runLaunchctl, domain, label: LEGACY_LAUNCHD_LABEL, settleMs: opts.settleMs, sleep: opts.sleep });
459
+ if (gone !== null) {
460
+ // The job may still be loaded: its plist is KEPT (removing it would
461
+ // orphan a loaded job), and the caller reports the uncertainty.
462
+ console.error(`Failed to unload legacy launchd service (${LEGACY_LAUNCHD_LABEL}): ${gone}. ` +
463
+ `It may still be loaded, so its plist at ${legacyPlistPath} was left in place — unload it with: ` +
464
+ `launchctl bootout ${domain}/${LEGACY_LAUNCHD_LABEL}`);
465
+ return { action: "unload-unconfirmed", unloadFailed: gone };
375
466
  }
376
467
  try {
377
468
  unlinkSync(legacyPlistPath);
378
- console.log(`Migrated off legacy launchd label (${LEGACY_LAUNCHD_LABEL}) ✓`);
469
+ // No check mark (flair#2040): retiring the legacy plist is not launchd
470
+ // managing this instance — only the strict verifier licenses a ✓.
471
+ console.log(`Retired the legacy launchd plist (${LEGACY_LAUNCHD_LABEL}) at ${legacyPlistPath}; its job is not loaded (verified).`);
379
472
  }
380
473
  catch (err) {
381
474
  deleteFailed = err?.message ?? String(err);
382
475
  console.error(`Failed to remove legacy launchd plist at ${legacyPlistPath}: ` +
383
476
  `${deleteFailed}. Remove it manually.`);
384
477
  }
385
- return { action: "unloaded", unloadFailed, deleteFailed };
478
+ return { action: "unloaded", deleteFailed };
386
479
  }
387
480
  if (legacyRootPath !== null) {
388
481
  console.log(`Skipped legacy launchd cleanup: the plist at ${legacyPlistPath} ` +
@@ -398,28 +491,34 @@ function cleanupLegacyLaunchdPlist(dataDir, plistDir, runLaunchctl) {
398
491
  /**
399
492
  * Load + start `dataDir`'s launchd service, migrating off a pre-flair#693
400
493
  * legacy registration FIRST if one is found (migrateLegacyLaunchdLabel
401
- * above). Call order is load-bearing — unload legacy -> load new -> start
402
- * new, never a window with both registered — and pinned by
403
- * test/unit/launchd-label.test.ts. `load` failure is tolerated (e.g.
404
- * "already loaded" is a common, harmless nonzero exit); `start` failure
405
- * propagates so callers can fall back to a direct (non-launchd) start.
406
- * Shared by the `start` command and startFlairProcess() (used by restart/
407
- * upgrade/snapshot) so this sequence is expressed in exactly one place.
494
+ * above). Call order is load-bearing — boot out legacy -> boot out new ->
495
+ * bootstrap new -> kickstart new, never a window with both registered — and
496
+ * pinned by test/unit/launchd-label.test.ts.
497
+ *
498
+ * Every command names the GUI domain (flair#2040): `launchctl bootout
499
+ * gui/<uid>/<label>`, `bootstrap gui/<uid> <plist>`, `kickstart
500
+ * gui/<uid>/<label>` — the domain the preflight probed — instead of the legacy
501
+ * `unload`/`load`/`start`, which act on whatever domain launchctl infers for the
502
+ * calling process. See loadLaunchdJob for the bootout-settle retry and the
503
+ * `strict` option. A `kickstart` failure propagates so callers can fall back
504
+ * to a direct (non-launchd) start or restore.
505
+ *
506
+ * Shared by the `start` command and startFlairProcess() (restart/upgrade/
507
+ * snapshot). Doctor's repair and init's legacy migration run the same
508
+ * sequence — loadLaunchdJob — in `strict` mode, after their own preflight.
408
509
  */
409
- function ensureLaunchdServiceLoaded(dataDir, runLaunchctl, launchAgentsDir = defaultLaunchAgentsDir()) {
410
- const migration = migrateLegacyLaunchdLabel(dataDir, runLaunchctl, launchAgentsDir);
411
- // Unload first so a rewritten plist is re-read (flair#872).
412
- // launchd caches the environment of an already-loaded job; load
413
- // alone does not pick up changes to the plist on disk.
414
- try {
415
- runLaunchctl(`launchctl unload "${migration.plistPath}"`);
416
- }
417
- catch { /* not loaded, etc. — best effort */ }
418
- try {
419
- runLaunchctl(`launchctl load "${migration.plistPath}"`);
420
- }
421
- catch { /* already loaded, etc. — best effort */ }
422
- runLaunchctl(`launchctl start ${migration.label}`);
510
+ function ensureLaunchdServiceLoaded(dataDir, runLaunchctl, launchAgentsDir = defaultLaunchAgentsDir(), opts = {}) {
511
+ const uid = opts.uid ?? currentUid();
512
+ const migration = migrateLegacyLaunchdLabel(dataDir, runLaunchctl, launchAgentsDir, uid, { settleMs: opts.settleMs, sleep: opts.sleep });
513
+ loadLaunchdJob({
514
+ run: runLaunchctl,
515
+ domain: launchdGuiDomain(uid),
516
+ label: migration.label,
517
+ plistPath: migration.plistPath,
518
+ strict: opts.strict,
519
+ settleMs: opts.settleMs,
520
+ sleep: opts.sleep,
521
+ });
423
522
  return migration;
424
523
  }
425
524
  function configPath() {
@@ -781,27 +880,47 @@ export const SHARED_IDENTITY_FLAGS = {
781
880
  };
782
881
  function addSharedCredentialOptions(cmd) {
783
882
  return cmd
784
- .option(SHARED_CREDENTIAL_FLAGS.adminPass, "Admin password (or set FLAIR_ADMIN_PASS env, or use --admin-pass-file)")
785
- .option(SHARED_CREDENTIAL_FLAGS.adminPassFile, "Read admin password from a file (e.g., ~/.flair/admin-pass). Preferred over --admin-pass for launchd/cron — keeps the secret out of ps and shell history.")
883
+ .option(ADMIN_PASS_FLAG, ADMIN_PASS_HELP)
884
+ .option(ADMIN_PASS_FILE_FLAG, ADMIN_PASS_FILE_HELP)
786
885
  .option(SHARED_CREDENTIAL_FLAGS.adminUser, "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)");
787
886
  }
788
887
  function addSharedIdentityOption(cmd) {
789
888
  return cmd.option(SHARED_IDENTITY_FLAGS.agent, "Agent ID (or set FLAIR_AGENT_ID env)");
790
889
  }
791
890
  /**
792
- * Resolve `--admin-pass-file` into the same `adminPass` slot the inline flag
793
- * uses. Shared so sibling commands cannot drift on how the file is read
794
- * (mode 0600 via readAdminPassFileSecure).
891
+ * Resolve the admin password for the commands that declare the shared
892
+ * credential flags, through the ONE resolver (`resolveAdminPassFromSources` —
893
+ * the same one `federation token`/`pair` use, flair#1873/#1910). The resolved
894
+ * value is written back into the `adminPass` slot every call site reads.
895
+ *
896
+ * Precedence, as the usage text states: an explicit `--admin-pass-file` or
897
+ * `--admin-pass` over the ambient `FLAIR_ADMIN_PASS`/`HDB_ADMIN_PASSWORD`.
898
+ * Supplying BOTH the file and the flag is a usage error (it used to let the
899
+ * flag silently win); a file that is missing, empty or group-/world-readable
900
+ * is refused naming the path and its mode. Never prints the value.
795
901
  */
796
902
  function applyAdminPassFile(opts) {
797
- if (!opts.adminPass && opts.adminPassFile) {
798
- try {
799
- opts.adminPass = readAdminPassFileSecure(opts.adminPassFile);
800
- }
801
- catch (err) {
802
- console.error(`Error reading --admin-pass-file ${opts.adminPassFile}: ${err.message}`);
803
- process.exit(1);
804
- }
903
+ try {
904
+ // envPass is DELIBERATELY omitted: this wrapper folds an explicit
905
+ // `--admin-pass-file` (or `--admin-pass`) into `opts.adminPass`, and each
906
+ // call site keeps its own `opts.adminPass ?? FLAIR_ADMIN_PASS` fallback —
907
+ // exactly main's shape. Resolving the ambient env HERE would pre-fill
908
+ // `opts.adminPass`, and a call site that threads it as `explicitAdminPass`
909
+ // (memory add, soul, …) would then send ambient admin Basic auth where it
910
+ // used to send nothing and let the `--agent`/env tier decide (flair#1910
911
+ // round 2: `federation sync` merged nothing in the mixed-version compat
912
+ // lane because `memory add --agent X` with FLAIR_ADMIN_PASS set signed as
913
+ // admin, not as X).
914
+ const pass = resolveAdminPassFromSources({
915
+ adminPassFile: opts.adminPassFile,
916
+ adminPass: opts.adminPass,
917
+ });
918
+ if (pass)
919
+ opts.adminPass = pass;
920
+ }
921
+ catch (err) {
922
+ console.error(`Error: ${err.message}`);
923
+ process.exit(1);
805
924
  }
806
925
  }
807
926
  // Ops port resolution: --ops-port flag > FLAIR_OPS_PORT env > config opsPort > httpPort - 1
@@ -2455,8 +2574,12 @@ async function opsSeedInsertWithRetry(req) {
2455
2574
  }
2456
2575
  // flair#1790 review C2: 401 FIRST. An auth failure must never be masked by
2457
2576
  // a body that happens to carry a "duplicate"/"already exists" marker.
2458
- if (res.status === 401)
2459
- throw new Error(req.auth401Message(text));
2577
+ if (res.status === 401) {
2578
+ const err = new Error(req.auth401Message(text));
2579
+ if (req.auth401Friendly)
2580
+ err.flairFriendly = true;
2581
+ throw err;
2582
+ }
2460
2583
  // THEN the idempotent duplicate path: an unconditional 409, then the
2461
2584
  // marker match for the remaining non-OK shapes.
2462
2585
  const duplicate = res.status === 409 || text.includes("duplicate") || text.includes("already exists");
@@ -2483,7 +2606,19 @@ async function opsSeedInsertWithRetry(req) {
2483
2606
  }
2484
2607
  }
2485
2608
  }
2486
- export async function seedAgentViaOpsApi(opsPortOrUrl, agentId, pubKeyB64url, adminUser, adminPass) {
2609
+ export async function seedAgentViaOpsApi(opsPortOrUrl, agentId, pubKeyB64url, adminUser, adminPass,
2610
+ /**
2611
+ * Set only when `flair init` skipped starting Harper and did not already
2612
+ * stop for a foreign data directory (flair#1749). `before` is who held
2613
+ * THIS operations port immediately before the insert — not the HTTP
2614
+ * port's listener. On a 401, `reread` runs and a pid is named only
2615
+ * when both reads are the same sole PID. Several holders, or a holder
2616
+ * that changed during the request, stay unattributed. Omit this when init
2617
+ * started Harper itself — that 401 keeps the credential hint. A different
2618
+ * data directory does not prove the passwords differ, and the HTTP holder
2619
+ * is not assumed to be the process that rejected this request.
2620
+ */
2621
+ occupiedListener) {
2487
2622
  const url = typeof opsPortOrUrl === "number"
2488
2623
  ? `http://127.0.0.1:${opsPortOrUrl}/`
2489
2624
  : `${opsPortOrUrl.replace(/\/$/, "")}/`;
@@ -2522,7 +2657,24 @@ export async function seedAgentViaOpsApi(opsPortOrUrl, agentId, pubKeyB64url, ad
2522
2657
  noun: "agent",
2523
2658
  tableName: "flair.Agent",
2524
2659
  id: agentId,
2525
- auth401Message: (text) => `Operations API insert failed (401): ${text}${opsAuth401Hint(auth === undefined ? undefined : adminUser)}`,
2660
+ auth401Message: (text) => {
2661
+ if (!occupiedListener) {
2662
+ return `Operations API insert failed (401): ${text}${opsAuth401Hint(auth === undefined ? undefined : adminUser)}`;
2663
+ }
2664
+ let after;
2665
+ try {
2666
+ after = occupiedListener.reread();
2667
+ }
2668
+ catch {
2669
+ after = { port: occupiedListener.before.port, pids: [], dataDirs: [] };
2670
+ }
2671
+ return occupiedListenerAuthFailure({
2672
+ lead: "Operations API insert failed (401): ",
2673
+ bodyText: text,
2674
+ listener: stableAnsweredHolder(occupiedListener.before, after),
2675
+ });
2676
+ },
2677
+ auth401Friendly: occupiedListener !== undefined,
2526
2678
  httpErrorMessage: (status, text) => `Operations API insert failed (${status}): ${text}`,
2527
2679
  });
2528
2680
  }
@@ -2576,6 +2728,85 @@ export async function seedFederationInstanceViaOpsApi(opsPortOrUrl, instanceId,
2576
2728
  httpErrorMessage: (status, text) => `Federation Instance insert via ops API failed (${status}): ${text}`,
2577
2729
  });
2578
2730
  }
2731
+ // ─── Federation instance identity (flair#1883) ───────────────────────────────
2732
+ //
2733
+ // A hub's identity is ONE `flair.Instance` row. `GET /FederationInstance`
2734
+ // find-or-creates it (`role: "spoke"`); `flair init --remote` used to INSERT a
2735
+ // second row under a fresh id, so a hub could hold a spoke row and a hub row and
2736
+ // every reader that took "the first row" answered from whichever the table
2737
+ // yielded first. `reconcileFederationInstanceViaOpsApi` is init's writer: it
2738
+ // reads the rows and decides (create / set the ONE row's role to hub / no-op /
2739
+ // refuse), never inserting over an existing identity. The decisions themselves
2740
+ // live in src/lib/instance-identity-row.ts, shared with the cleanup sweep and
2741
+ // doctor. After it writes, it RE-READS: a row that appeared in its read-then-
2742
+ // insert window (a concurrent `GET /FederationInstance` find-or-creates one) is
2743
+ // reported with the prune remedy rather than counted as a successful init. The
2744
+ // re-read must also hold the row it just WROTE (flair#1883 round 6): an empty
2745
+ // table or one different row is refused, naming what was found, because an
2746
+ // absent or wrong hub identity is not a completed init.
2747
+ /** The ops endpoint trio (URL, user, optional pass) as the identity helpers want it. */
2748
+ function federationInstanceEndpoint(opsPortOrUrl, adminUser, adminPass, fetchImpl) {
2749
+ const opsUrl = typeof opsPortOrUrl === "number" ? `http://127.0.0.1:${opsPortOrUrl}` : opsPortOrUrl;
2750
+ return {
2751
+ opsUrl,
2752
+ // A caller without a pass sends no Authorization header — same posture as
2753
+ // seedFederationInstanceViaOpsApi (loopback authorizeLocal).
2754
+ ...(adminPass !== undefined ? { credentials: { user: adminUser, pass: adminPass } } : {}),
2755
+ ...(fetchImpl ? { fetchImpl } : {}),
2756
+ };
2757
+ }
2758
+ /**
2759
+ * Reconcile the hub identity row for `flair init --remote`.
2760
+ *
2761
+ * Returns what actually happened so the caller's log line can name it: an
2762
+ * `already-hub` re-run must not claim it wrote anything.
2763
+ *
2764
+ * The write is verified by re-reading, not assumed (flair#1883 round 2): the
2765
+ * read-then-write window is real, and a `GET /FederationInstance` landing in it
2766
+ * leaves two rows. Reporting that as `created` would claim an identity this
2767
+ * instance does not have.
2768
+ *
2769
+ * The re-read must hold the row it just wrote (flair#1883 round 6): an empty
2770
+ * table (the insert never landed) or one different row (the update went
2771
+ * elsewhere) used to verify as success, and the caller adopted the id anyway.
2772
+ */
2773
+ export async function reconcileFederationInstanceViaOpsApi(opsPortOrUrl, create, adminUser, adminPass, opts) {
2774
+ const endpoint = federationInstanceEndpoint(opsPortOrUrl, adminUser, adminPass, opts?.fetchImpl);
2775
+ const rows = await readInstanceRows(endpoint);
2776
+ const decision = decideHubReconcile(rows);
2777
+ switch (decision.kind) {
2778
+ case "refuse-multiple":
2779
+ throw new Error(multipleInstanceRowsMessage(decision.rows));
2780
+ case "already-hub":
2781
+ return { action: "already-hub", id: decision.id };
2782
+ case "update-role":
2783
+ await updateInstanceRole(endpoint, decision.id, "hub");
2784
+ await assertSingleInstanceRowAfterWrite(endpoint, decision.id);
2785
+ return { action: "updated", id: decision.id };
2786
+ default:
2787
+ // The create path keeps the insert (and its retry/401 guidance) unchanged.
2788
+ await seedFederationInstanceViaOpsApi(opsPortOrUrl, create.instanceId, create.publicKey, "hub", adminUser, adminPass);
2789
+ await assertSingleInstanceRowAfterWrite(endpoint, create.instanceId);
2790
+ return { action: "created", id: create.instanceId };
2791
+ }
2792
+ }
2793
+ /**
2794
+ * Re-read after a write: it must hold exactly the ONE hub row that was written.
2795
+ *
2796
+ * More than one row now means the write raced another writer (a `GET
2797
+ * /FederationInstance` creates one), and the caller must hear the refusal — with
2798
+ * the prune remedy — instead of a success line. An EMPTY table, one OTHER row,
2799
+ * or the expected id with a non-hub role is a failure too (flair#1883 round 6):
2800
+ * each names what the re-read found, because "the write did not land" and "the
2801
+ * write landed elsewhere" are different operator problems.
2802
+ */
2803
+ async function assertSingleInstanceRowAfterWrite(endpoint, expectedId) {
2804
+ const verification = verifyInstanceWrite(await readInstanceRows(endpoint), expectedId);
2805
+ if (verification.kind === "refuse-multiple")
2806
+ throw new Error(multipleInstanceRowsMessage(verification.rows));
2807
+ if (verification.kind === "not-verified")
2808
+ throw new Error(instanceWriteNotVerifiedMessage(expectedId, verification.found));
2809
+ }
2579
2810
  // ─── Provision Flair on Harper Fabric ──────────────────────────────────────
2580
2811
  //
2581
2812
  // Atomic provisioning for a fresh Harper Fabric cluster: builds a deploy
@@ -3434,6 +3665,12 @@ program.configureHelp({ showGlobalOptions: true });
3434
3665
  program.hook("preAction", async (_thisCommand, actionCommand) => {
3435
3666
  if (actionCommand.name() === "doctor")
3436
3667
  return;
3668
+ // flair#2034 §2: `status` reports the server's version itself, next to this
3669
+ // CLI's and the install tree that serves it, and decides the advice from
3670
+ // that one comparison — a second, tree-blind "run: flair restart" line here
3671
+ // is the hint that used to contradict it.
3672
+ if (actionCommand.name() === "status" && actionCommand.parent === program)
3673
+ return;
3437
3674
  // Interactive-only: this is a pure stderr UX nudge for a human at a
3438
3675
  // terminal ("bare-npm users must not get stuck"), not a machine-consumed
3439
3676
  // signal — it never changes exit codes or stdout. Gating on TTY means a
@@ -3471,7 +3708,6 @@ bindInitCli({
3471
3708
  api,
3472
3709
  b64url,
3473
3710
  buildOperationsApiConfig,
3474
- cleanupLegacyLaunchdPlist,
3475
3711
  defaultDataDir,
3476
3712
  defaultLaunchAgentsDir,
3477
3713
  ensureFlairAgentRole,
@@ -3488,6 +3724,8 @@ bindInitCli({
3488
3724
  provisionFabric,
3489
3725
  pubKeyPath,
3490
3726
  readyOpsSocketPosture,
3727
+ reconcileFederationInstanceViaOpsApi,
3728
+ repointMainServiceUnit,
3491
3729
  resolveHttpPort,
3492
3730
  writeAdminPassFile,
3493
3731
  resolveOpsBindHost,
@@ -3499,12 +3737,13 @@ bindInitCli({
3499
3737
  runSoulWizard,
3500
3738
  seedAgentViaOpsApi,
3501
3739
  seedFederationInstanceViaOpsApi,
3740
+ readOccupiedListener,
3502
3741
  shouldShowInlineSecretWarning,
3503
3742
  verifyAuditLog,
3504
3743
  verifySemanticSearch,
3505
3744
  waitForHealth,
3506
3745
  writeDaemonSidecar,
3507
- writeInitLaunchdPlist,
3746
+ registerInitLaunchdService,
3508
3747
  MQTT_DISABLED_CONFIG,
3509
3748
  STARTUP_TIMEOUT_MS,
3510
3749
  });
@@ -3724,6 +3963,8 @@ bindStatusCli({
3724
3963
  defaultDataDir,
3725
3964
  readHarperConfig,
3726
3965
  readPortFromConfig,
3966
+ resolveHttpPort,
3967
+ assessInstallTree,
3727
3968
  __pkgVersion,
3728
3969
  });
3729
3970
  registerStatus(program);
@@ -3770,12 +4011,14 @@ function stampEngineVersionIfRunning(dataDir) {
3770
4011
  // Command registration lives in src/commands/upgrade.ts (flair#1636).
3771
4012
  // Bind shared cli-locals first so the extracted module never imports this file.
3772
4013
  bindUpgradeCli({
4014
+ assessInstallTree,
3773
4015
  decideAfterRollbackVerify,
3774
4016
  decideAfterVerify,
3775
4017
  defaultDataDir,
3776
4018
  doctorRunAfterUpgrade,
3777
4019
  flairPackageDir,
3778
4020
  fleetSweepCallerExitMessage,
4021
+ gatherDaemonEvidence,
3779
4022
  humanBytes,
3780
4023
  isCredentialOnlyFailure,
3781
4024
  observeLaunchdManagement,
@@ -3791,6 +4034,10 @@ bindUpgradeCli({
3791
4034
  resolveInstanceServingPid,
3792
4035
  resolveUpgradeRestartVerify,
3793
4036
  restartAfterUpgrade,
4037
+ runPackageInstall: (spec) => {
4038
+ execFileSync("npm", ["install", "-g", spec], { stdio: "pipe" });
4039
+ },
4040
+ applyPlainTreeUpgrade,
3794
4041
  shouldPrintUpgradeLine,
3795
4042
  shouldRunFleetVerify,
3796
4043
  startFlairProcess,
@@ -3870,7 +4117,7 @@ function readPidfile(dataDir) {
3870
4117
  return { kind: "present", pid: n };
3871
4118
  }
3872
4119
  /** Read `flair-daemon.json` (O_NOFOLLOW) into a `SidecarRead`. */
3873
- function readSidecar(dataDir) {
4120
+ export function readSidecar(dataDir) {
3874
4121
  const r = readFileNoFollow(join(dataDir, "flair-daemon.json"));
3875
4122
  if (r.kind !== "present")
3876
4123
  return r;
@@ -3880,18 +4127,17 @@ function readSidecar(dataDir) {
3880
4127
  }
3881
4128
  return { kind: "present", ...parsed };
3882
4129
  }
3883
- /** `kill(pid, 0)` as a three-way: alive / gone (ESRCH) / eperm (another user's). */
4130
+ /** `kill(pid, 0)` as a four-way: alive / gone (ESRCH) / eperm (another user's) / unknown. */
3884
4131
  function probePidLiveness(pid) {
3885
4132
  try {
3886
4133
  process.kill(pid, 0);
3887
4134
  return { kind: "alive" };
3888
4135
  }
3889
4136
  catch (err) {
3890
- if (err?.code === "ESRCH")
3891
- return { kind: "gone" };
3892
- if (err?.code === "EPERM")
3893
- return { kind: "eperm" };
3894
- return { kind: "gone" };
4137
+ // `gone` ONLY for ESRCH. Any other errno (EINVAL, EACCES, ...) is `unknown`,
4138
+ // which must never be read as "gone" — that is the whole point of the
4139
+ // classifier's unknown state (flair#2055).
4140
+ return livenessFromKillError(err?.code);
3895
4141
  }
3896
4142
  }
3897
4143
  /**
@@ -3950,7 +4196,14 @@ function canonicalizeExistingPath(p) {
3950
4196
  return resolve(p);
3951
4197
  }
3952
4198
  }
3953
- /** Best-effort ROOTPATH from `/proc/<pid>/environ`. */
4199
+ /**
4200
+ * ROOTPATH for daemon sidecar recovery (flair#1454 / #1478).
4201
+ *
4202
+ * Linux reads `/proc/<pid>/environ`. Every other platform, including macOS,
4203
+ * is "could not read". Init's occupied-listener check uses
4204
+ * `readInitListenerRootPath` instead — a `ps` parse must not feed this
4205
+ * self-heal path.
4206
+ */
3954
4207
  function readProcessRootPath(pid) {
3955
4208
  if (process.platform === "linux") {
3956
4209
  try {
@@ -3963,6 +4216,30 @@ function readProcessRootPath(pid) {
3963
4216
  }
3964
4217
  return { rootPath: null, environReadable: false };
3965
4218
  }
4219
+ /**
4220
+ * Test seam for the pre-auth observation. When set, pid and ROOTPATH reads
4221
+ * replace `lsof` and `/proc` so a test can name a listener without the
4222
+ * host's tools. Production leaves this unset. Never a reason to offer
4223
+ * `flair stop`.
4224
+ */
4225
+ let occupiedListenerLookupForTests = null;
4226
+ export function setOccupiedListenerLookupForTests(lookup) {
4227
+ occupiedListenerLookupForTests = lookup;
4228
+ }
4229
+ /**
4230
+ * Who is listening on `port` (flair#1749). The pre-auth path calls this
4231
+ * once, on the HTTP port. A later operations-port 401 calls it again
4232
+ * before the insert and after the 401 — that pair is the attribution,
4233
+ * not this single read. ROOTPATH comes from init's Linux `/proc` reader,
4234
+ * not the sidecar reader. An unreadable directory is omitted. Never signals.
4235
+ */
4236
+ function readOccupiedListener(port) {
4237
+ const lookup = occupiedListenerLookupForTests ?? {
4238
+ pids: resolveListenerPids,
4239
+ rootPath: readInitListenerRootPath,
4240
+ };
4241
+ return listenerFromLookup(port, lookup);
4242
+ }
3966
4243
  /**
3967
4244
  * Was this pid inspectable as a flair worktree? `null` when cwd and
3968
4245
  * cmdline could not be read — do not treat that as "not flair".
@@ -3975,11 +4252,26 @@ function inspectServingFlairPackage(pid) {
3975
4252
  return resolveServingFlairPackage(pid) !== null;
3976
4253
  }
3977
4254
  /** Gather every piece of evidence the classifier needs, in one place. */
3978
- async function gatherDaemonEvidence(port, dataDir) {
4255
+ export async function gatherDaemonEvidence(port, dataDir) {
3979
4256
  const dataDirUnsafe = checkDataDirSafe(dataDir);
3980
4257
  const pidfile = readPidfile(dataDir);
3981
4258
  const pidLiveness = pidfile.kind === "present" ? probePidLiveness(pidfile.pid) : null;
3982
4259
  let sidecar = readSidecar(dataDir);
4260
+ // flair#2055: a sidecar that names a pid which is CONFIRMED gone is STALE, not
4261
+ // a disagreement with hdb.pid. After `flair stop` ended a directly started
4262
+ // Harper, the sidecar it wrote still names the stopped pid; a later instance
4263
+ // under a different supervisor (a systemd unit's Harper) writes its own pid
4264
+ // to hdb.pid, and the old code read the mismatch as an identity conflict and
4265
+ // refused every stop/restart. Dropping the stale sidecar here (treating it as
4266
+ // absent) lets the self-heal below adopt the identity from the LIVE process
4267
+ // on the evidence that process serves — never from the dead pid's record.
4268
+ // Liveness that cannot be determined is NOT stale: the sidecar stays and the
4269
+ // refusal stands (unknown evidence never licenses an action).
4270
+ if (sidecar.kind === "present" && dataDirUnsafe === null) {
4271
+ if (classifySidecarStaleness(sidecar, probePidLiveness(sidecar.pid)).kind === "stale") {
4272
+ sidecar = { kind: "absent" };
4273
+ }
4274
+ }
3983
4275
  // Probe health first so the self-heal gate below can use it without a
3984
4276
  // second round-trip. Also consumed at the end for the classifier.
3985
4277
  const health = await probeHealth(port);
@@ -4074,6 +4366,54 @@ function writeDaemonSidecar(dataDir, pid, port, startTimeMs = Date.now()) {
4074
4366
  // kernels. An explicit chmod is the only guarantee (flair#1454 decision 6).
4075
4367
  chmodSync(finalPath, 0o600);
4076
4368
  }
4369
+ /**
4370
+ * Remove the identity sidecar left behind by a stop (flair#2055).
4371
+ *
4372
+ * A sidecar that still names a pid which is CONFIRMED gone is a leftover, and
4373
+ * leaving it makes a later instance under a DIFFERENT supervisor refuse
4374
+ * ("its identity could not be verified"). The removal is gated twice:
4375
+ *
4376
+ * 1. the pid the sidecar names must be CONFIRMED gone (ESRCH) — `unknown` or
4377
+ * EPERM liveness removes nothing; and
4378
+ * 2. a FRESH O_NOFOLLOW read taken just before the unlink must still name
4379
+ * that pid. A sidecar another supervisor rewrote in between names a
4380
+ * different pid and is left alone; a symlinked or malformed one reads as
4381
+ * `unreadable` and is not removed either, because the re-read never
4382
+ * followed the link.
4383
+ *
4384
+ * There is no lock: the re-read narrows the window to the gap between the read
4385
+ * and the unlink, and the only loser of that race is a start that rewrote the
4386
+ * sidecar in the gap — a live daemon left with no sidecar, which a later
4387
+ * port-based stop or restart can RECOVER by self-heal once the live process
4388
+ * supplies the required pidfile and health evidence (shouldAdoptMissingSidecar
4389
+ * adopts the identity from the live process; see the recovery test). `flair
4390
+ * status` does not re-adopt. A lock would buy
4391
+ * nothing here and add a crash-recovery hazard, so the design relies on the
4392
+ * self-heal instead. A writer OUTSIDE flair could substitute a symlink after
4393
+ * the final read; that is out of scope (same as any other path flair re-reads
4394
+ * by name). Best-effort: a failure to unlink is reported, never fatal.
4395
+ */
4396
+ export function removeStaleSidecarIfConfirmedDead(dataDir) {
4397
+ const observed = readSidecar(dataDir);
4398
+ if (observed.kind !== "present")
4399
+ return;
4400
+ const observedPid = observed.pid;
4401
+ const observedPidLiveness = probePidLiveness(observedPid);
4402
+ // Re-read: only the sidecar that still names the confirmed-dead pid is ours
4403
+ // to remove (a sidecar rewritten in the gap is left alone).
4404
+ const fresh = readSidecar(dataDir);
4405
+ if (!shouldRemoveSidecarAfterStop({ observedPid, observedPidLiveness, sidecar: fresh }))
4406
+ return;
4407
+ const sidecarPath = join(dataDir, "flair-daemon.json");
4408
+ try {
4409
+ unlinkSync(sidecarPath);
4410
+ }
4411
+ catch (err) {
4412
+ if (err?.code === "ENOENT")
4413
+ return; // raced with another remover
4414
+ console.error(`could not remove the stale daemon sidecar ${sidecarPath}: ${err?.code ?? err?.message}`);
4415
+ }
4416
+ }
4077
4417
  /**
4078
4418
  * Refuse to act on a launchd service that belongs to a DIFFERENT data
4079
4419
  * directory than the one the command is operating on (flair#902).
@@ -4128,6 +4468,8 @@ export function assertLaunchdServiceOwnedBy(dataDir, label, plistPath, action) {
4128
4468
  // Command registration lives in src/commands/service.ts (flair#1636).
4129
4469
  // Bind shared cli-locals first so the extracted module never imports this file.
4130
4470
  bindServiceCli({
4471
+ afterFailedLaunchdAttempt,
4472
+ assessInstallTree,
4131
4473
  buildDirectSpawnEnv,
4132
4474
  closedDirectSpawnEnv,
4133
4475
  defaultDataDir,
@@ -4137,6 +4479,8 @@ bindServiceCli({
4137
4479
  guardEngineNotBackwards,
4138
4480
  harperBinNotFoundMessage,
4139
4481
  harperSearchRoots,
4482
+ launchdLabel,
4483
+ observeLaunchdLoadability,
4140
4484
  observeLaunchdManagement,
4141
4485
  probeHealth,
4142
4486
  readyOpsSocketPosture,
@@ -4147,6 +4491,7 @@ bindServiceCli({
4147
4491
  resolveOpsBindHost,
4148
4492
  resolveOpsPort,
4149
4493
  restartFlair,
4494
+ removeStaleSidecarIfConfirmedDead,
4150
4495
  stampEngineVersionIfRunning,
4151
4496
  waitForHealth,
4152
4497
  waitForProcessExit,
@@ -4168,6 +4513,136 @@ const realLaunchctlLister = (label) => {
4168
4513
  });
4169
4514
  return { code: res.status, stdout: res.stdout ?? "" };
4170
4515
  };
4516
+ /** The current uid. `getuid` is always present on macOS; 0 is a harmless fallback. */
4517
+ function currentUid() {
4518
+ return typeof process.getuid === "function" ? process.getuid() : 0;
4519
+ }
4520
+ /**
4521
+ * `launchctl <verb> <target>` — READ-ONLY queries only (`print`,
4522
+ * `print-disabled`), capped so an unreachable launchd cannot hang the CLI.
4523
+ * These are the preflight runners (flair#2040).
4524
+ */
4525
+ function launchctlQueryRunner(verb, target) {
4526
+ return () => {
4527
+ const res = spawnSync("launchctl", [verb, target], {
4528
+ encoding: "utf-8",
4529
+ timeout: DOMAIN_PROBE_TIMEOUT_MS,
4530
+ });
4531
+ if (res.error && res.status === null)
4532
+ throw res.error;
4533
+ return { code: res.status, stdout: res.stdout ?? "", stderr: res.stderr ?? "" };
4534
+ };
4535
+ }
4536
+ /**
4537
+ * Can this process load and start `label` in the GUI domain right now?
4538
+ * (flair#2040) — `launchctl print gui/<uid>` (is the domain reachable from this
4539
+ * session?) then `launchctl print-disabled gui/<uid>` (is the label disabled
4540
+ * there?). Both read-only.
4541
+ */
4542
+ function observeLaunchdLoadability(label) {
4543
+ const uid = currentUid();
4544
+ const domain = launchdGuiDomain(uid);
4545
+ return assessLaunchdLoadability({
4546
+ platform: process.platform,
4547
+ uid,
4548
+ label,
4549
+ printDomain: launchctlQueryRunner("print", domain),
4550
+ printDisabled: launchctlQueryRunner("print-disabled", domain),
4551
+ });
4552
+ }
4553
+ /** Ceiling on one bootstrap/bootout/kickstart. */
4554
+ const LAUNCHCTL_MUTATION_TIMEOUT_MS = 30_000;
4555
+ /** The real `launchctl …` command runner (execSync; throws on a non-zero exit). */
4556
+ const realLaunchctlCommand = (cmd) => {
4557
+ execSync(cmd, { stdio: "pipe", timeout: LAUNCHCTL_MUTATION_TIMEOUT_MS });
4558
+ };
4559
+ /**
4560
+ * Unload `labels` from the GUI domain and VERIFY each is gone (flair#2040).
4561
+ * Used before a direct-start fallback so a job whose load half-worked cannot be
4562
+ * started by KeepAlive underneath the direct process. Returns null when every
4563
+ * label is PROVEN absent; otherwise which job could not be shown gone, and why
4564
+ * — and then the caller must NOT start directly (nor say the job was unloaded).
4565
+ */
4566
+ function bootoutLaunchdJob(labels) {
4567
+ const domain = launchdGuiDomain(currentUid());
4568
+ for (const label of labels) {
4569
+ const notGone = ensureLaunchdJobAbsent({ run: realLaunchctlCommand, domain, label });
4570
+ if (notGone !== null)
4571
+ return { target: `${domain}/${label}`, detail: notGone };
4572
+ }
4573
+ return null;
4574
+ }
4575
+ /**
4576
+ * After the launchd attempt of `flair start`, or of the start leg of restart /
4577
+ * upgrade / snapshot, failed: may the caller start Flair directly? (flair#2040)
4578
+ * One decision for both start paths.
4579
+ *
4580
+ * - A VALIDATION refusal (isLaunchdValidationRefusal: the plist failed a check
4581
+ * made before any launchctl call that changes state) loaded and unloaded
4582
+ * nothing, so nothing is booted out here either — a loaded legacy job is
4583
+ * left exactly as it was, and so are both plists. The jobs are only READ:
4584
+ * a direct start is allowed only when every one of `labels` is PROVEN
4585
+ * absent. A loaded job, or one whose presence cannot be read, could be
4586
+ * started by launchd underneath the direct process, so the caller must not
4587
+ * start directly.
4588
+ * - A failed LOAD may have left a job loaded: unload `labels` and VERIFY
4589
+ * each is gone (bootoutLaunchdJob) before a direct start.
4590
+ *
4591
+ * `lines` are what the caller reports (stderr), whether or not it starts
4592
+ * directly. `directStart` false means: start nothing and fail.
4593
+ */
4594
+ function afterFailedLaunchdAttempt(actor, jobLabel, labels, err) {
4595
+ const cause = err?.message ?? String(err);
4596
+ if (isLaunchdValidationRefusal(err)) {
4597
+ const blocking = firstLaunchdJobNotProvenAbsent(realLaunchctlCommand, launchdGuiDomain(currentUid()), labels);
4598
+ if (blocking !== null) {
4599
+ return { directStart: false, lines: renderStartLaunchdValidationBlocked(actor, jobLabel, cause, blocking.target, blocking.presence) };
4600
+ }
4601
+ return { directStart: true, lines: [renderStartLaunchdValidationRefused(actor, jobLabel, cause)] };
4602
+ }
4603
+ const notGone = bootoutLaunchdJob(labels);
4604
+ if (notGone !== null) {
4605
+ return { directStart: false, lines: renderStartLaunchdUnloadUncertain(actor, notGone.target, cause, notGone.detail) };
4606
+ }
4607
+ return { directStart: true, lines: [renderStartLaunchdFailed(actor, jobLabel, cause)] };
4608
+ }
4609
+ /**
4610
+ * `plutil -lint` over plist CONTENT, before it is written anywhere launchd
4611
+ * reads (flair#2040). Returns a problem line, or null ONLY when plutil ran and
4612
+ * accepted it. A plutil that cannot be run, times out or dies on a signal is a
4613
+ * problem too: a lint that did not run is not a lint that passed. Creating,
4614
+ * writing or removing its temporary copy can THROW; migrateLegacyLaunchdLabel
4615
+ * and init's launchd step (lintReplacementPlist) turn any throw into a
4616
+ * validation refusal before they unload anything.
4617
+ */
4618
+ function lintLaunchdPlistContent(content) {
4619
+ if (process.platform !== "darwin")
4620
+ return null;
4621
+ const dir = mkdtempSync(join(tmpdir(), "flair-plist-lint-"));
4622
+ try {
4623
+ const file = join(dir, "candidate.plist");
4624
+ writeFileSync(file, content, { mode: 0o600 });
4625
+ const res = spawnSync("plutil", ["-lint", file], { encoding: "utf-8", timeout: DOMAIN_PROBE_TIMEOUT_MS });
4626
+ if (res.error || res.status === null) {
4627
+ const why = res.error ? res.error.message : `it ended on ${res.signal ?? "a signal"}`;
4628
+ return `plutil -lint could not check the plist (${why}), so its syntax is unverified`;
4629
+ }
4630
+ if (res.status === 0)
4631
+ return null;
4632
+ return `plutil -lint rejected the plist (${(res.stdout || res.stderr || "").trim().split("\n")[0].replace(file, "<plist>")})`;
4633
+ }
4634
+ finally {
4635
+ rmSync(dir, { recursive: true, force: true });
4636
+ }
4637
+ }
4638
+ /**
4639
+ * Everything `doctor --fix` / `init` must know about a plist before they stop,
4640
+ * unload or replace anything for it (flair#2040): its paths (launcher, node,
4641
+ * Harper, working directory, data directory) and, on macOS, its syntax.
4642
+ */
4643
+ function validateLaunchdPlistContent(content, lint = lintLaunchdPlistContent) {
4644
+ return checkLaunchdPlistBeforeLoad(content) ?? lint(content);
4645
+ }
4171
4646
  /**
4172
4647
  * Which process is actually serving `dataDir` — Harper's own `hdb.pid` first,
4173
4648
  * then the listener on `port`.
@@ -4192,6 +4667,203 @@ function resolveInstanceServingPid(dataDir, port) {
4192
4667
  listeningPids,
4193
4668
  });
4194
4669
  }
4670
+ // ─── which install tree serves this instance (flair#2034 §2) ────────────────
4671
+ //
4672
+ // The pure decision lives in src/lib/tree-divergence.ts (proof) and
4673
+ // src/lib/service-repoint.ts (re-point planning). These adapters are the only
4674
+ // places that read the real launchd / systemd / process state or write a unit.
4675
+ /** realpath, or the lexically resolved path when it cannot be resolved. */
4676
+ function canonicalOr(p) {
4677
+ try {
4678
+ return realpathSync(p);
4679
+ }
4680
+ catch {
4681
+ return resolve(p);
4682
+ }
4683
+ }
4684
+ function samePathCanonical(a, b) {
4685
+ return canonicalOr(a) === canonicalOr(b);
4686
+ }
4687
+ function realRepointDeps() {
4688
+ return {
4689
+ exists: existsSync,
4690
+ samePath: samePathCanonical,
4691
+ canonical: canonicalOr,
4692
+ treeVersion: (dir) => readFlairPackageAt(dir)?.version ?? null,
4693
+ };
4694
+ }
4695
+ /**
4696
+ * `systemctl show` for a unit — of this user's manager (`--user`) or the
4697
+ * system's: MainPID, the file it loaded (FragmentPath), every drop-in it
4698
+ * applies (DropInPaths) and its WorkingDirectory. null when it could not be
4699
+ * read. Read-only and bounded; never throws.
4700
+ */
4701
+ function systemctlShow(unitName, manager) {
4702
+ const res = spawnSync("systemctl", [
4703
+ ...(manager === "user" ? ["--user"] : []),
4704
+ "show", "-p", "MainPID", "-p", "FragmentPath", "-p", "DropInPaths", "-p", "WorkingDirectory", "--", unitName,
4705
+ ], { encoding: "utf-8", timeout: LAUNCHCTL_QUERY_TIMEOUT_MS });
4706
+ return res.status === 0 ? String(res.stdout ?? "") : null;
4707
+ }
4708
+ function systemdUserUnitState(unitName) {
4709
+ const out = systemctlShow(unitName, "user");
4710
+ return out === null ? null : systemdUnitStateFromShow(out);
4711
+ }
4712
+ /** The MainPID a manager reports for a unit (0: no main process), or null when it could not be asked. */
4713
+ function systemdUnitMainPid(unitName, manager) {
4714
+ const out = systemctlShow(unitName, manager);
4715
+ return out === null ? null : mainPidFromShow(out);
4716
+ }
4717
+ /** /proc/<pid>/cgroup, read directly. */
4718
+ function readProcCgroup(pid) {
4719
+ return readFileSync(`/proc/${pid}/cgroup`, "utf-8");
4720
+ }
4721
+ /**
4722
+ * What this host knows about which process serves `dataDir` on `port`: the
4723
+ * data dir's PID file (only when that process is alive) and the distinct PIDs
4724
+ * listening on the port (null when they could not be read).
4725
+ */
4726
+ function localPidEvidence(dataDir, port) {
4727
+ let listeners;
4728
+ try {
4729
+ const out = execSync(`lsof -ti :${port} -sTCP:LISTEN`, { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] });
4730
+ listeners = [...new Set(parseListeningPids(out, process.pid))];
4731
+ }
4732
+ catch (err) {
4733
+ // lsof exits 1 with no output when nothing listens; anything else is "could not read".
4734
+ listeners = err?.status === 1 && String(err?.stdout ?? "").trim() === "" ? [] : null;
4735
+ }
4736
+ const pidFilePid = readHarperPid(dataDir);
4737
+ return { pidFile: pidFilePid !== null && isProcessAlive(pidFilePid) ? pidFilePid : null, listeners };
4738
+ }
4739
+ /** This CLI's own install tree (realpath) and version. */
4740
+ function cliInstallTree() {
4741
+ const loc = findFlairPackageDir(flairPackageDir());
4742
+ return { dir: loc?.dir ?? canonicalOr(flairPackageDir()), version: __pkgVersion || loc?.version || null };
4743
+ }
4744
+ /** Which install tree serves `dataDir`'s instance — proven from the service manager, or unknown. */
4745
+ function resolveServingTree(dataDir, port, query) {
4746
+ const { label, plistPath } = resolveLaunchdLabel(dataDir);
4747
+ return proveServingTree({
4748
+ platform: process.platform,
4749
+ local: query.local,
4750
+ queryUrl: query.queryUrl ?? `http://127.0.0.1:${port}`,
4751
+ dataDir,
4752
+ respondingPid: query.respondingPid ?? null,
4753
+ localPids: () => localPidEvidence(dataDir, port),
4754
+ launchd: { label, plistPath },
4755
+ launchdJobPid: (l) => readLaunchctlJobState(l, realLaunchctlLister).pid,
4756
+ // Linux: the unit is found from the serving process's cgroup, then checked
4757
+ // against what systemd reports for it (MainPID, FragmentPath, drop-ins).
4758
+ ...linuxUnitProbe({
4759
+ readFile: (p) => readFileSync(p, "utf-8"),
4760
+ systemctlShow,
4761
+ uid: typeof process.getuid === "function" ? process.getuid() : -1,
4762
+ userUnitDir: userSystemdDir(),
4763
+ }),
4764
+ servingPackage: (pid) => resolveServingFlairPackage(pid),
4765
+ exists: existsSync,
4766
+ read: (p) => readFileSync(p, "utf-8"),
4767
+ samePath: samePathCanonical,
4768
+ });
4769
+ }
4770
+ /** This CLI's tree vs the tree proven to serve `dataDir`'s instance. */
4771
+ function assessInstallTree(dataDir, port, query) {
4772
+ return assessTreeDivergence({
4773
+ cli: cliInstallTree(),
4774
+ serving: resolveServingTree(dataDir, port, query),
4775
+ runningVersion: query.runningVersion ?? null,
4776
+ currentNodeBin: process.execPath,
4777
+ samePath: samePathCanonical,
4778
+ });
4779
+ }
4780
+ /**
4781
+ * Re-point an adopted pass-file plist's runtime paths (see planPlistRuntimeRepoint):
4782
+ * planned from `planned` (a regular-file snapshot), written only over those
4783
+ * same bytes (see applyRepointPlan).
4784
+ */
4785
+ function repointAdoptedPlistFile(planned, targets, owner, opts = {}) {
4786
+ const plan = planPlistRuntimeRepoint(planned.content, targets, realRepointDeps(), planned.path, owner);
4787
+ return applyRepointPlan(plan, planned, { dryRun: opts.dryRun, atomic: opts.atomic });
4788
+ }
4789
+ /**
4790
+ * Re-point THIS instance's own service unit at this CLI's install tree —
4791
+ * `flair init` (Linux) and `flair doctor --fix`. macOS: the data dir's own
4792
+ * pass-file plist (see PlistOwnership for what makes it this instance's).
4793
+ * Linux: the systemd USER unit proven to own the answering process — the file
4794
+ * systemd loaded for it, with no drop-ins. Only runtime paths change; see
4795
+ * src/lib/service-repoint.ts for the shapes and src/lib/service-repoint-apply.ts
4796
+ * for the write.
4797
+ */
4798
+ function repointMainServiceUnit(dataDir, port, opts = {}) {
4799
+ const dryRun = opts.dryRun === true;
4800
+ const cli = cliInstallTree();
4801
+ const harper = harperBin();
4802
+ if (!harper)
4803
+ return { kind: "refused", detail: harperBinNotFoundMessage(harperSearchRoots()) };
4804
+ const targets = {
4805
+ launcher: launchdLauncherPath(cli.dir),
4806
+ nodeBin: preferVersionManagerAlias(process.execPath),
4807
+ harperBin: harper,
4808
+ workingDirectory: cli.dir,
4809
+ cliVersion: cli.version,
4810
+ };
4811
+ if (process.platform === "darwin") {
4812
+ const { label, plistPath } = resolveLaunchdLabel(dataDir);
4813
+ if (!existsSync(plistPath)) {
4814
+ return { kind: "not-applicable", detail: `no launchd service is registered for this data directory (${plistPath})` };
4815
+ }
4816
+ let planned;
4817
+ try {
4818
+ planned = snapshotRegularFile(plistPath);
4819
+ }
4820
+ catch (err) {
4821
+ return {
4822
+ kind: "refused",
4823
+ unitPath: plistPath,
4824
+ detail: `${plistPath} is not re-pointed: ${err?.message ?? err}; flair rewrites only a regular plist file in place. ` +
4825
+ `To move it, set its launcher, node, Harper entry and WorkingDirectory to this CLI's tree (${cli.dir}) by ` +
4826
+ "hand in the file it points to, then run: flair restart",
4827
+ };
4828
+ }
4829
+ const raw = planned.content;
4830
+ const disposition = classifyPlist(plistPath, dataDir, {
4831
+ exists: existsSync,
4832
+ read: () => raw,
4833
+ readRootPath: () => readPlistRootPath(plistPath),
4834
+ });
4835
+ if (disposition !== "ours") {
4836
+ return {
4837
+ kind: "refused",
4838
+ unitPath: plistPath,
4839
+ detail: `${plistPath} cannot be attributed to this data directory (${disposition}); run flair doctor --fix to repair launchd management first.`,
4840
+ };
4841
+ }
4842
+ if (plistCarriesInlineAdminPassword(raw)) {
4843
+ return {
4844
+ kind: "refused",
4845
+ unitPath: plistPath,
4846
+ detail: `${plistPath} still embeds the admin password inline; run flair doctor --fix first (it regenerates the plist in pass-file mode).`,
4847
+ };
4848
+ }
4849
+ return repointAdoptedPlistFile(planned, targets, { label, dataDir, home: resolveHome(), adminPassFile: defaultAdminPassPath() }, { dryRun });
4850
+ }
4851
+ if (process.platform === "linux") {
4852
+ const serving = resolveServingTree(dataDir, port, { local: true });
4853
+ if (serving.kind !== "proven") {
4854
+ return { kind: "not-applicable", detail: `no service unit is proven to serve this instance: ${serving.reason}` };
4855
+ }
4856
+ return repointSystemdUserUnit(serving, targets, {
4857
+ repoint: realRepointDeps(),
4858
+ exists: existsSync,
4859
+ unitState: systemdUserUnitState,
4860
+ reload: () => {
4861
+ execFileSync("systemctl", ["--user", "daemon-reload"], { stdio: "pipe", timeout: 30_000 });
4862
+ },
4863
+ }, { dryRun });
4864
+ }
4865
+ return { kind: "not-applicable", detail: `${process.platform} has no service manager flair re-points` };
4866
+ }
4195
4867
  /** Agent signing-key ids under `keysDir` — node-scoped federation keys excluded. */
4196
4868
  function collectKeyAgentIds(keysDir) {
4197
4869
  if (!existsSync(keysDir))
@@ -4521,9 +5193,11 @@ function validateAdminPassFileForLauncher(path) {
4521
5193
  * is required on `LaunchdPlistOptions`) and makes the writer own its
4522
5194
  * precondition:
4523
5195
  *
4524
- * 1. An on-disk plist that is provably ours IN THE PASS-FILE SHAPE is left
4525
- * byte-for-byte unchanged. An adopted instance is never downgraded, and a
4526
- * re-run of init does not churn mtime / flap launchd state.
5196
+ * 1. An on-disk plist that is provably ours IN THE PASS-FILE SHAPE is never
5197
+ * regenerated. An adopted instance is never downgraded, and a re-run of
5198
+ * init does not churn mtime / flap launchd state. Its runtime paths alone
5199
+ * are re-pointed when it serves another npm-global tree (flair#2034,
5200
+ * src/lib/service-repoint.ts); otherwise it is left byte-for-byte unchanged.
4527
5201
  * 2. A plist that is provably another instance's (`foreign`) or cannot be
4528
5202
  * attributed (`unattributable`) is refused, naming `flair doctor --fix`.
4529
5203
  * 3. Otherwise, resolve the pass file BEFORE writing anything: reuse an
@@ -4570,11 +5244,55 @@ export async function writeInitLaunchdPlist(opts, deps = {}) {
4570
5244
  const passFileShape = !plistCarriesInlineAdminPassword(raw) &&
4571
5245
  basename(launcherArg) === basename(launchdLauncherPath());
4572
5246
  if (disposition === "ours" && passFileShape) {
4573
- return {
4574
- kind: "unchanged",
4575
- plistPath: opts.plistPath,
4576
- detail: `the launchd service is already adopted with the pass-file launcher; leaving ${opts.plistPath} unchanged`,
4577
- };
5247
+ // flair#2034 §2: never regenerated or downgraded (#1693), but its
5248
+ // RUNTIME paths — launcher, node, Harper entry, working directory —
5249
+ // are re-pointed at this CLI's tree when it serves another
5250
+ // npm-global tree AND it is provably this instance's plist in the
5251
+ // shape flair writes (service-repoint.ts). Every other byte stays. No
5252
+ // credential is needed: the pass-file path it names is left as it is.
5253
+ // The plan is made from a regular-file snapshot and written only over
5254
+ // those same bytes.
5255
+ let planned;
5256
+ try {
5257
+ planned = snapshotRegularFile(opts.plistPath, { lstat: deps.atomic?.lstat, readBytes: deps.atomic?.readBytes });
5258
+ }
5259
+ catch (err) {
5260
+ return {
5261
+ kind: "not-repointed",
5262
+ plistPath: opts.plistPath,
5263
+ detail: `${opts.plistPath} is not re-pointed: ${err?.message ?? err}; flair rewrites only a regular plist file in ` +
5264
+ "place. To move it, set its launcher, node, Harper entry and WorkingDirectory to this CLI's tree " +
5265
+ `(${opts.workingDirectory}) by hand in the file it points to, then run: flair restart`,
5266
+ };
5267
+ }
5268
+ if (planned.content !== raw) {
5269
+ return {
5270
+ kind: "not-repointed",
5271
+ plistPath: opts.plistPath,
5272
+ detail: `${opts.plistPath} changed while flair init was reading it; nothing was written. Re-run flair init.`,
5273
+ };
5274
+ }
5275
+ const r = repointAdoptedPlistFile(planned, {
5276
+ launcher: launchdLauncherPath(opts.workingDirectory),
5277
+ nodeBin: opts.execPath,
5278
+ harperBin: opts.harperBinPath,
5279
+ workingDirectory: opts.workingDirectory,
5280
+ cliVersion: readFlairPackageAt(opts.workingDirectory)?.version ?? null,
5281
+ }, { label: opts.label, dataDir: opts.dataDir, home: resolveHome(), adminPassFile: adminPassPath }, { atomic: deps.atomic });
5282
+ switch (r.kind) {
5283
+ case "repointed":
5284
+ return { kind: "repointed", plistPath: opts.plistPath, detail: r.detail };
5285
+ case "refused":
5286
+ return { kind: "not-repointed", plistPath: opts.plistPath, detail: r.detail };
5287
+ default:
5288
+ return {
5289
+ kind: "unchanged",
5290
+ plistPath: opts.plistPath,
5291
+ detail: `the launchd service is already adopted with the pass-file launcher; leaving ${opts.plistPath} unchanged` +
5292
+ (r.kind === "pinned-node" ? ` (${r.detail})` : ""),
5293
+ ...(r.kind === "pinned-node" ? { pinnedNode: r.detail } : {}),
5294
+ };
5295
+ }
4578
5296
  }
4579
5297
  }
4580
5298
  }
@@ -4630,6 +5348,397 @@ export async function writeInitLaunchdPlist(opts, deps = {}) {
4630
5348
  writeFileAtomic(opts.plistPath, plist, 0o644);
4631
5349
  return { kind: "written", plistPath: opts.plistPath };
4632
5350
  }
5351
+ /**
5352
+ * Put the plist `flair init` wrote back as `prior` recorded it (flair#2040,
5353
+ * flair#2078): its prior bytes, or removed when there was none. Never throws:
5354
+ * `ok` false means the put-back FAILED, and `text` says so with the error.
5355
+ */
5356
+ function putInitPlistBack(path, prior) {
5357
+ try {
5358
+ restoreFile(path, prior);
5359
+ }
5360
+ catch (e) {
5361
+ return { ok: false, text: `putting ${path} back FAILED (${e?.message ?? e})` };
5362
+ }
5363
+ return {
5364
+ ok: true,
5365
+ text: prior.kind === "absent" ? `the new plist ${path} was removed again` : `the plist at ${path} was put back as it was`,
5366
+ };
5367
+ }
5368
+ /**
5369
+ * `flair init`'s launchd step (flair#2040): write this instance's plist, retire
5370
+ * a pre-flair#693 legacy registration, and report ONLY what was verified.
5371
+ *
5372
+ * init starts Flair DIRECTLY and, since 9e3bd9ad, deliberately does not bounce
5373
+ * a running instance into launchd — so the ordinary outcome is "plist on disk,
5374
+ * running directly", and that is what it says. A check mark is printed only
5375
+ * when launchd is verified to run this instance (assessLaunchdManagement:
5376
+ * launchd's pid is the serving pid).
5377
+ *
5378
+ * The one path that stops something is retiring a LEGACY job that is the
5379
+ * process serving this instance: booting it out stops Flair. That path follows
5380
+ * the same rule as `doctor --fix`: preflight first (domain reachable, job
5381
+ * enabled), write + validate the replacement plist while the instance is still
5382
+ * up, and only then boot the legacy job out, load the replacement with
5383
+ * targeted commands and verify it; any failure after the boot-out restores the
5384
+ * legacy plist and job (or, failing that, starts Flair directly) and says so.
5385
+ * If the preflight fails, NOTHING is unloaded, removed or written; if the
5386
+ * validation fails — a lint that throws included (flair#2078) — nothing is
5387
+ * unloaded or removed, and the plist init wrote is put back as it was.
5388
+ */
5389
+ async function registerInitLaunchdService(input) {
5390
+ const { dataDir, port, plistDir, write } = input;
5391
+ const uid = currentUid();
5392
+ const domain = launchdGuiDomain(uid);
5393
+ const lines = [];
5394
+ const out = (text) => lines.push({ stream: "out", text });
5395
+ const err = (text) => lines.push({ stream: "err", text });
5396
+ const legacyPath = launchdPlistPath(LEGACY_LAUNCHD_LABEL, plistDir);
5397
+ const legacyRoot = existsSync(legacyPath) ? readPlistRootPath(legacyPath) : null;
5398
+ const legacyOwned = legacyRoot !== null && resolve(legacyRoot) === resolve(dataDir);
5399
+ if (!legacyOwned) {
5400
+ // A foreign or unattributable legacy plist is left alone (flair#966); the
5401
+ // helper prints why. With no legacy plist it is a no-op.
5402
+ if (existsSync(legacyPath))
5403
+ cleanupLegacyLaunchdPlist(dataDir, plistDir, realLaunchctlCommand, uid);
5404
+ const outcome = await writeInitLaunchdPlist(write);
5405
+ if (outcome.kind === "refused")
5406
+ return { kind: "refused", lines: [{ stream: "err", text: `Error: ${outcome.detail}` }] };
5407
+ return reportInitLaunchd(dataDir, port, write, outcome, lines);
5408
+ }
5409
+ const keptLegacy = `Nothing was unloaded or removed: the legacy job ${LEGACY_LAUNCHD_LABEL} and its plist at ${legacyPath} were left as they were`;
5410
+ // An owned legacy registration. Retiring it may stop the instance (when its
5411
+ // job is what serves), so the preflight gates EVERYTHING below.
5412
+ const loadability = observeLaunchdLoadability(write.label);
5413
+ if (!loadabilityAllowsAttempt(loadability)) {
5414
+ const problem = loadability;
5415
+ err(`⚠️ Launchd: not re-registered — ${describeLoadabilityProblem(problem)}. ${keptLegacy}, and no new ` +
5416
+ "plist was written (two plists for one data directory would give launchd two jobs for it).");
5417
+ err(` Fix: ${loadabilityRemedy(problem, uid, "flair init")}.`);
5418
+ return { kind: "skipped", lines };
5419
+ }
5420
+ // flair#2040: what is the legacy job doing? Only PROVEN answers license a
5421
+ // boot-out. The role is:
5422
+ // absent - launchctl says the job is not loaded: nothing to boot out;
5423
+ // idle - launchd lists the job with no process, or runs a process that
5424
+ // is identified as NOT the one serving this instance;
5425
+ // serving - launchd's pid IS the identified serving pid;
5426
+ // unknown - anything else (the job's state cannot be read, launchd's pid is
5427
+ // not visible from here, or the serving process cannot be
5428
+ // identified). Unknown is treated as possibly serving — and since
5429
+ // neither a boot-out nor a verified replacement is possible on
5430
+ // unknown evidence, init refuses.
5431
+ const presence = launchdJobPresence(realLaunchctlCommand, domain, LEGACY_LAUNCHD_LABEL);
5432
+ const servingPid = resolveInstanceServingPid(dataDir, port);
5433
+ const legacyJob = presence === "loaded"
5434
+ ? readLaunchctlJobState(LEGACY_LAUNCHD_LABEL, realLaunchctlLister)
5435
+ : { registered: false, pid: null, lastExitStatus: null };
5436
+ const role = presence === "absent" ? "absent"
5437
+ : presence === "unknown" ? "unknown"
5438
+ : legacyJob.registered && legacyJob.pid === null ? "idle"
5439
+ : legacyJob.pid !== null && servingPid !== null
5440
+ ? (legacyJob.pid === servingPid ? "serving" : "idle")
5441
+ : "unknown";
5442
+ if (role === "unknown") {
5443
+ const why = presence === "unknown"
5444
+ ? `'launchctl print ${domain}/${LEGACY_LAUNCHD_LABEL}' could not say whether it is loaded`
5445
+ : !legacyJob.registered
5446
+ ? `it is loaded in ${domain}, but launchd's process for it is not visible from this session`
5447
+ : `launchd runs it as process ${legacyJob.pid}, but the process serving this instance could not be identified ` +
5448
+ `(no live hdb.pid, and no listener found on port ${port})`;
5449
+ err(`⚠️ Launchd: not re-registered — the legacy job ${LEGACY_LAUNCHD_LABEL} may be the process serving this instance: ` +
5450
+ `${why}. ${keptLegacy}, and no new plist was written.`);
5451
+ err(" Fix: restart Flair so it rewrites its hdb.pid ('flair restart'), or make lsof available, then re-run 'flair init'.");
5452
+ return { kind: "skipped", lines };
5453
+ }
5454
+ if (role === "serving") {
5455
+ // Replacing a serving job is a boot path: the replacement runs THIS
5456
+ // package's Harper, which may be older than the store (flair#1093). Refuse
5457
+ // here, before anything is unloaded or written.
5458
+ try {
5459
+ guardEngineNotBackwards(dataDir);
5460
+ }
5461
+ catch (e) {
5462
+ if (!e?.engineBackwards)
5463
+ throw e;
5464
+ err(`⚠️ Launchd: not re-registered — ${e.message} ${keptLegacy}.`);
5465
+ return { kind: "skipped", lines };
5466
+ }
5467
+ }
5468
+ // The prior bytes a failed hand-off would put back. A plist that exists but
5469
+ // cannot be read cannot be put back: refuse before anything is written.
5470
+ const priorNew = snapshotFile(write.plistPath);
5471
+ const priorLegacy = snapshotFile(legacyPath);
5472
+ const unreadable = unreadableSnapshot([[write.plistPath, priorNew], [legacyPath, priorLegacy]]);
5473
+ if (unreadable) {
5474
+ err(`⚠️ Launchd: not re-registered — ${unreadable} exists but could not be read, so it could not be put back. ${keptLegacy}.`);
5475
+ return { kind: "skipped", lines };
5476
+ }
5477
+ // The replacement is written and validated while the instance is still up
5478
+ // (the writer proves the credential against it).
5479
+ const outcome = await writeInitLaunchdPlist(write);
5480
+ if (outcome.kind === "refused") {
5481
+ return {
5482
+ kind: "refused",
5483
+ lines: [
5484
+ { stream: "err", text: `Error: ${outcome.detail}` },
5485
+ { stream: "err", text: `${keptLegacy}.` },
5486
+ ],
5487
+ };
5488
+ }
5489
+ // Every failed validation is a refusal made before anything is unloaded: a
5490
+ // problem the checks REPORT, and — as in the start paths' migration — a lint
5491
+ // that THROWS (lintReplacementPlist) or a written plist that cannot be read
5492
+ // back (flair#2078). Each puts the plist just written back as it was, or
5493
+ // removes it when there was none: left beside the legacy plist, it would give
5494
+ // launchd two jobs for one data directory at the next login.
5495
+ const installing = `the plist init would install for ${write.label}`;
5496
+ let refusal = null;
5497
+ try {
5498
+ const problem = validateLaunchdPlistContent(readFileSync(write.plistPath, "utf-8"), (content) => lintReplacementPlist(content, launchdMigrationLintForTests ?? lintLaunchdPlistContent, (failure) => `${installing} could not be validated (${failure})`));
5499
+ if (problem !== null) {
5500
+ refusal = { why: `${installing} cannot be loaded (${problem})`, fix: "npm install -g @tpsdev-ai/flair && flair init" };
5501
+ }
5502
+ }
5503
+ catch (e) {
5504
+ refusal = isLaunchdValidationRefusal(e)
5505
+ ? { why: e.message, fix: `make sure the temporary directory (${tmpdir()}) exists and is writable, and re-run 'flair init'.` }
5506
+ : { why: `${installing} could not be validated (${e?.message ?? String(e)})`, fix: "resolve the error above, and re-run 'flair init'." };
5507
+ }
5508
+ if (refusal !== null) {
5509
+ const putBack = putInitPlistBack(write.plistPath, priorNew);
5510
+ err(`⚠️ Launchd: not re-registered — ${refusal.why}. Nothing was unloaded: the legacy job ${LEGACY_LAUNCHD_LABEL} ` +
5511
+ `and its plist at ${legacyPath} were left as they were, and ${putBack.text}.`);
5512
+ if (!putBack.ok) {
5513
+ err(` Fix: remove ${write.plistPath} (beside the legacy plist, launchd would load two jobs for this data ` +
5514
+ `directory at the next login); then ${refusal.fix}`);
5515
+ return { kind: "uncertain", lines };
5516
+ }
5517
+ err(` Fix: ${refusal.fix}`);
5518
+ return { kind: "skipped", lines };
5519
+ }
5520
+ if (role !== "serving") {
5521
+ // PROVEN not serving (absent, or idle): retiring it stops nothing.
5522
+ const cleanup = cleanupLegacyLaunchdPlist(dataDir, plistDir, realLaunchctlCommand, uid);
5523
+ if (cleanup.action === "unload-unconfirmed") {
5524
+ // flair#2040: the legacy job could not be shown unloaded, and the helper
5525
+ // KEPT its plist. The replacement written above must not stay beside it
5526
+ // (two plists for one data directory would give launchd two jobs), so it
5527
+ // is put back as it was, and nothing is reported as registered.
5528
+ const putBack = putInitPlistBack(write.plistPath, priorNew);
5529
+ err(`⚠️ Launchd: not re-registered — the legacy job ${LEGACY_LAUNCHD_LABEL} could not be shown unloaded ` +
5530
+ `(${cleanup.unloadFailed}), so it may still be loaded. Its plist at ${legacyPath} was left in place, and ${putBack.text}.`);
5531
+ err(` Fix: launchctl bootout ${domain}/${LEGACY_LAUNCHD_LABEL}, then re-run 'flair init'.`);
5532
+ return { kind: "uncertain", lines };
5533
+ }
5534
+ return reportInitLaunchd(dataDir, port, write, outcome, lines);
5535
+ }
5536
+ // flair#2034: what the writer did to the new plist, where no write happened
5537
+ // (a plist that may not be re-pointed; a deliberate node pin). Both stay true
5538
+ // whatever the hand-off below does, so they are said up front, with no check
5539
+ // mark. A re-point is said only once the job it was loaded into is verified:
5540
+ // any failure below puts the pre-re-point bytes back.
5541
+ if (outcome.kind === "not-repointed")
5542
+ err(`Launchd service left unchanged — ${outcome.detail}`);
5543
+ if (outcome.kind === "unchanged" && outcome.pinnedNode)
5544
+ out(`Launchd plist left as it is — ${outcome.pinnedNode}`);
5545
+ // The legacy job IS the serving instance: replace it and verify, or restore.
5546
+ const legacyPid = legacyJob.pid;
5547
+ try {
5548
+ const gone = ensureLaunchdJobAbsent({ run: realLaunchctlCommand, domain, label: LEGACY_LAUNCHD_LABEL });
5549
+ if (gone !== null)
5550
+ throw new Error(`could not unload the legacy job: ${gone}`);
5551
+ await waitForProcessExit(legacyPid, STARTUP_TIMEOUT_MS);
5552
+ unlinkSync(legacyPath);
5553
+ const bounceAt = Date.now();
5554
+ unlinkStaleOpsSocket(dataDir);
5555
+ loadLaunchdJob({ run: realLaunchctlCommand, domain, label: write.label, plistPath: write.plistPath, strict: true });
5556
+ await waitForHealth(port, write.adminUser, write.adminPass, STARTUP_TIMEOUT_MS);
5557
+ // STRICT: launchd's pid must be the IDENTIFIED serving pid (flair#2040).
5558
+ const after = observeLaunchdManagement(dataDir, port);
5559
+ const verdict = verifyLaunchdManagement(after);
5560
+ if (!verdict.verified)
5561
+ throw new Error(after.detail);
5562
+ await readyOpsSocketPostureAfterStart(dataDir, { notBeforeMs: bounceAt });
5563
+ out(`Migrated launchd service off the legacy label (${LEGACY_LAUNCHD_LABEL}) → ${write.label}; ${verdict.detail} ✓`);
5564
+ if (outcome.kind === "repointed") {
5565
+ out(` Its plist was re-pointed at this CLI's install tree before it was loaded (${outcome.detail}).`);
5566
+ }
5567
+ return { kind: "managed", lines };
5568
+ }
5569
+ catch (e) {
5570
+ const cause = e?.message ?? String(e);
5571
+ if (isProcessAlive(legacyPid) && existsSync(legacyPath) && (await probeHealth(port)).kind === "ok") {
5572
+ // Nothing was stopped: the legacy job's process still serves.
5573
+ restoreFile(write.plistPath, priorNew);
5574
+ err(`⚠️ Launchd: not re-registered — ${cause}. The legacy job's process is still serving; its plist was left as it was.`);
5575
+ return { kind: "skipped", lines };
5576
+ }
5577
+ return restoreLegacyAfterFailedMigration({ dataDir, port, write, domain, legacyPath, priorNew, priorLegacy, cause, lines });
5578
+ }
5579
+ }
5580
+ /**
5581
+ * The status lines for the plist writer's outcome: managed only when VERIFIED
5582
+ * (flair#2040). The writer's own result (flair#2034) is reported with it: a
5583
+ * plist that may not be re-pointed names why (no write happened; never a check
5584
+ * mark), a re-point names what changed and the restart that makes it take
5585
+ * effect, and a deliberate node pin names the hand edit that moves it.
5586
+ */
5587
+ function reportInitLaunchd(dataDir, port, write, outcome, lines) {
5588
+ if (outcome.kind === "not-repointed") {
5589
+ lines.push({ stream: "err", text: `Launchd service left unchanged — ${outcome.detail}` });
5590
+ }
5591
+ const unchanged = outcome.kind === "unchanged" || outcome.kind === "not-repointed";
5592
+ const followUps = () => {
5593
+ if (outcome.kind === "repointed") {
5594
+ // The running process keeps its old tree until launchd starts it again.
5595
+ lines.push({ stream: "out", text: " It takes effect when launchd next starts the service: flair restart" });
5596
+ }
5597
+ else if (outcome.kind === "unchanged" && outcome.pinnedNode) {
5598
+ // A deliberate node pin is never changed by init; say so, with the hand edit.
5599
+ lines.push({ stream: "out", text: ` ${outcome.pinnedNode}` });
5600
+ }
5601
+ };
5602
+ const managed = observeLaunchdManagement(dataDir, port);
5603
+ const verdict = verifyLaunchdManagement(managed);
5604
+ if (verdict.verified) {
5605
+ lines.push({
5606
+ stream: "out",
5607
+ text: outcome.kind === "repointed"
5608
+ ? `Launchd service re-pointed at this CLI's install tree — ${outcome.detail}; ${verdict.detail} ✓`
5609
+ : unchanged
5610
+ ? `Launchd service already managed — plist unchanged; ${verdict.detail} ✓`
5611
+ : `Launchd service registered; ${verdict.detail} ✓`,
5612
+ });
5613
+ followUps();
5614
+ return { kind: "managed", lines };
5615
+ }
5616
+ const plistLine = outcome.kind === "repointed"
5617
+ ? `Launchd plist re-pointed at this CLI's install tree (${outcome.detail})`
5618
+ : `Launchd plist ${unchanged ? "unchanged" : "written"} (${write.plistPath})`;
5619
+ if (managed.state === "unverified") {
5620
+ // launchd runs the job, but nothing identifies the serving process: no
5621
+ // claim either way (flair#2040).
5622
+ lines.push({ stream: "out", text: `${plistLine} — launchd management is NOT verified: ${managed.detail}.` });
5623
+ lines.push({ stream: "out", text: " Fix: restart Flair so it rewrites its hdb.pid ('flair restart'), or make lsof available, then run 'flair doctor'." });
5624
+ followUps();
5625
+ return { kind: "unverified", lines };
5626
+ }
5627
+ // No pid in this line: init names only a process it started (flair#1749) —
5628
+ // the serving process may be one it merely found answering the port.
5629
+ const loadability = observeLaunchdLoadability(write.label);
5630
+ const fromHere = loadabilityAllowsAttempt(loadability)
5631
+ ? ""
5632
+ : ` From this session it could not be handed over anyway: ${describeLoadabilityProblem(loadability)}.`;
5633
+ lines.push({
5634
+ stream: "out",
5635
+ text: `${plistLine} — Flair is running directly, NOT launchd-managed: init starts Flair directly and does not hand a ` +
5636
+ `running instance to launchd.${fromHere}`,
5637
+ });
5638
+ lines.push({
5639
+ stream: "out",
5640
+ text: " To hand it to launchd, run 'flair doctor --fix' from a console (GUI) login session. " +
5641
+ `${RUN_AT_LOAD_NOTE[0].toUpperCase()}${RUN_AT_LOAD_NOTE.slice(1)}; ${DIRECT_PROCESS_GUARD_NOTE}.`,
5642
+ });
5643
+ followUps();
5644
+ return { kind: "direct", lines };
5645
+ }
5646
+ /**
5647
+ * Bring back the legacy service after replacing it failed (flair#2040): unload
5648
+ * the new job and VERIFY it is gone, put both plists back, bootstrap the
5649
+ * legacy job and verify it serves — or, if that fails and the legacy job is
5650
+ * verified gone, start Flair directly. Each step is an attempt whose outcome is
5651
+ * reported; when a job cannot be shown unloaded, nothing further is started
5652
+ * (two processes on one data directory is not a restore).
5653
+ */
5654
+ async function restoreLegacyAfterFailedMigration(r) {
5655
+ const { dataDir, port, write, domain, lines } = r;
5656
+ const headline = `⚠️ Launchd: moving the service to ${write.label} failed after the legacy job was unloaded (${r.cause}).`;
5657
+ const newPid = readLaunchctlJobState(write.label, realLaunchctlLister).pid;
5658
+ const servingNow = resolveInstanceServingPid(dataDir, port);
5659
+ const newGone = ensureLaunchdJobAbsent({ run: realLaunchctlCommand, domain, label: write.label });
5660
+ if (newGone !== null) {
5661
+ lines.push({ stream: "err", text: headline });
5662
+ lines.push({
5663
+ stream: "err",
5664
+ text: ` The new job could not be shown unloaded (${newGone}), so the legacy job was NOT reloaded and Flair was ` +
5665
+ "NOT started directly — either could run a second instance on this data directory. Flair may be down, or run by the new job.",
5666
+ });
5667
+ lines.push({ stream: "err", text: ` Fix: launchctl bootout ${domain}/${write.label}, then 'flair init' from a console (GUI) login session.` });
5668
+ return { kind: "uncertain", lines };
5669
+ }
5670
+ for (const pid of new Set([newPid, servingNow])) {
5671
+ if (pid !== null) {
5672
+ try {
5673
+ await waitForProcessExit(pid, STARTUP_TIMEOUT_MS);
5674
+ }
5675
+ catch { /* the health checks below report it */ }
5676
+ }
5677
+ }
5678
+ try {
5679
+ restoreFile(write.plistPath, r.priorNew);
5680
+ restoreFile(r.legacyPath, r.priorLegacy);
5681
+ }
5682
+ catch (e) {
5683
+ lines.push({ stream: "err", text: ` putting the plists back FAILED: ${e?.message ?? e}` });
5684
+ }
5685
+ try {
5686
+ loadLaunchdJob({ run: realLaunchctlCommand, domain, label: LEGACY_LAUNCHD_LABEL, plistPath: r.legacyPath, strict: true });
5687
+ await waitForHealth(port, write.adminUser, write.adminPass, STARTUP_TIMEOUT_MS);
5688
+ const legacy = assessLaunchdManagement({
5689
+ platform: process.platform,
5690
+ label: LEGACY_LAUNCHD_LABEL,
5691
+ plistPath: r.legacyPath,
5692
+ instancePid: resolveInstanceServingPid(dataDir, port),
5693
+ plistExists: existsSync,
5694
+ list: realLaunchctlLister,
5695
+ });
5696
+ const verdict = verifyLaunchdManagement(legacy);
5697
+ lines.push({ stream: "err", text: headline });
5698
+ lines.push({
5699
+ stream: "err",
5700
+ text: verdict.verified
5701
+ ? ` Restored: the legacy job ${LEGACY_LAUNCHD_LABEL} is loaded again and serving (${verdict.detail}); both plists are as they were.`
5702
+ : ` Partly restored: Flair answers on port ${port} again after reloading the legacy job, but launchd serving it is NOT verified (${legacy.detail}).`,
5703
+ });
5704
+ lines.push({ stream: "err", text: " Fix: re-run 'flair init' (or 'flair doctor --fix') from a console (GUI) login session." });
5705
+ return { kind: "restored", lines };
5706
+ }
5707
+ catch (legacyErr) {
5708
+ const legacyGone = ensureLaunchdJobAbsent({ run: realLaunchctlCommand, domain, label: LEGACY_LAUNCHD_LABEL });
5709
+ if (legacyGone !== null) {
5710
+ lines.push({ stream: "err", text: headline });
5711
+ lines.push({
5712
+ stream: "err",
5713
+ text: ` Reloading the legacy job failed (${legacyErr?.message ?? legacyErr}), and it could not be shown unloaded ` +
5714
+ `(${legacyGone}), so Flair was NOT started directly. Flair may be down, or run by the legacy job.`,
5715
+ });
5716
+ lines.push({ stream: "err", text: ` Fix: launchctl bootout ${domain}/${LEGACY_LAUNCHD_LABEL}, then 'flair start'.` });
5717
+ return { kind: "uncertain", lines };
5718
+ }
5719
+ try {
5720
+ const pid = await startFlairDirect(port, dataDir);
5721
+ lines.push({ stream: "err", text: headline });
5722
+ lines.push({
5723
+ stream: "err",
5724
+ text: ` Reloading the legacy job failed too (${legacyErr?.message ?? legacyErr}); Flair was restarted directly` +
5725
+ `${pid ? ` (pid ${pid})` : ""} and is serving on port ${port} — running directly, NOT launchd-managed. Both plists are as they were.`,
5726
+ });
5727
+ lines.push({ stream: "err", text: " Fix: run 'flair doctor --fix' from a console (GUI) login session." });
5728
+ return { kind: "restored", lines };
5729
+ }
5730
+ catch (directErr) {
5731
+ lines.push({ stream: "err", text: headline });
5732
+ lines.push({
5733
+ stream: "err",
5734
+ text: ` Reloading the legacy job failed (${legacyErr?.message ?? legacyErr}) and starting Flair directly failed ` +
5735
+ `(${directErr?.message ?? directErr}): Flair is DOWN.`,
5736
+ });
5737
+ lines.push({ stream: "err", text: " Fix: flair start" });
5738
+ return { kind: "down", lines };
5739
+ }
5740
+ }
5741
+ }
4633
5742
  /**
4634
5743
  * Compute the launchd repair plan for `dataDir` (flair#1573 slice b) WITHOUT
4635
5744
  * executing it — the detect + classify + decide half. The doctor command uses
@@ -4689,43 +5798,50 @@ function planLaunchdRepairFor(dataDir, port) {
4689
5798
  * Repair launchd management for `dataDir` (flair#1573 slice b) — the
4690
5799
  * `doctor --fix` launchd repair for a MISSING, CORRUPT, or DETACHED plist.
4691
5800
  *
4692
- * detect -> (adopt: clean-stop the direct process) -> regenerate (pass-file
4693
- * mode) -> load -> verify. The DECISION (state matrix + ownership guard +
4694
- * config authority) lives in planLaunchdRepair (src/lib/launchd-repair.ts);
4695
- * this is the EXECUTION, and it is the only place that touches the real
4696
- * filesystem and launchctl.
5801
+ * TWO PHASES (flair#2040). The rule for this handoff: the running instance
5802
+ * is not stopped, and no launchd job is unloaded, until every check that can
5803
+ * be made about the replacement from THIS session has passed; an UNKNOWN
5804
+ * answer is a failed check, never a pass. Every failure after that point is
5805
+ * followed by an attempt to bring back what was running, and the result
5806
+ * reports the state the instance was left in — including when that state
5807
+ * could not be established.
4697
5808
  *
4698
- * Reuses the existing primitives rather than re-inventing them:
4699
- * - observeLaunchdManagement / assessLaunchdManagement is the fail-loud
4700
- * verifier (launchctl PID AND that PID is the serving process).
4701
- * - ensureLaunchdServiceLoaded is the unload -> load -> start.
4702
- * - the five-state liveness machine (gatherDaemonEvidence +
4703
- * classifyDaemonState, flair#1454) attributes and clean-stops the direct
4704
- * process on the adopt path — never a foreign/recycled pid, never kill -9.
5809
+ * 1. PREPARE (prepareLaunchdRepair) — reads and validation; the running
5810
+ * instance and launchd are untouched:
5811
+ * - the launchd preflight: is the GUI domain reachable from this
5812
+ * session, and is the job enabled there (read-only `launchctl print`
5813
+ * / `print-disabled`, domainPreflightRefusal — `unknown` refuses);
5814
+ * - the engine guard (flair#1093);
5815
+ * - the prior plist/config bytes (an existing file that cannot be read
5816
+ * refuses — it could not be put back) and which jobs are loaded
5817
+ * (an unanswerable `launchctl print` refuses);
5818
+ * - adopt: the direct process is attributed by the liveness machine
5819
+ * (DISAGREEMENT/UNKNOWN refuses); regenerate: the port must be
5820
+ * provably free (nothing identified as serving is not proof that
5821
+ * nothing serves);
5822
+ * - the credential (flair#1685 — proven against the live instance; the
5823
+ * one write this phase can make is that 0600 admin-pass file, and it
5824
+ * stays if a later check refuses);
5825
+ * - the NEW plist is built in memory and validated: every path it names
5826
+ * exists, the launcher and node are executable, the working and data
5827
+ * directories exist, and `plutil -lint` ran and accepted it.
5828
+ * 2. COMMIT (commitLaunchdRepair) — boot out any loaded job for this
5829
+ * instance and VERIFY it is gone (so KeepAlive cannot race what follows;
5830
+ * if it cannot be shown gone, stop here, before the direct process is
5831
+ * touched), clean-stop the direct process (adopt), write the plist, load
5832
+ * it with commands that NAME the probed domain (bootstrap/kickstart
5833
+ * gui/<uid>), wait (bounded) while launchd reports a pid for the job and
5834
+ * its port does not answer, and verify STRICTLY: Flair's /Health answers
5835
+ * ok and launchd's pid is the IDENTIFIED serving pid
5836
+ * (judgeLaunchdJobServing), and on adopt the serving pid
5837
+ * changed and the old one is dead (flair#1684/#1685). ANY failure here
5838
+ * goes through restoreAfterFailedRepair.
4705
5839
  *
4706
- * The adopt path (flair#1573 slice b2) BOUNCES the live instance: it
4707
- * clean-stops the direct-spawned process (SIGTERM + wait for exit), confirms
4708
- * the port is free, then regenerates + loads. A foreign/unattributable direct
4709
- * process is refused by the liveness machine (DISAGREEMENT/UNKNOWN), never
4710
- * signalled.
5840
+ * The preflight cannot PROVE a bootstrap will succeed — only loading something
5841
+ * proves that — which is why phase 2 restores rather than assumes.
4711
5842
  *
4712
- * Credential before plist (flair#1685): the generated plist is always
4713
- * pass-file mode, so its launcher cannot start unless ~/.flair/admin-pass
4714
- * exists and is safe. An existing valid file is reused; an env credential is
4715
- * PROVEN against the live instance (before the adopt bounce) and only then
4716
- * written; nothing usable yields a refusal with no plist. The written file is
4717
- * validated against the launcher's own read contract (exists, mode 0600,
4718
- * non-empty) before load.
4719
- *
4720
- * Never reports success on a direct-start fallback: the final verify is
4721
- * assessLaunchdManagement (launchctl PID AND that PID is the serving process),
4722
- * and anything short of `managed` is a `failed` result with the detached detail
4723
- * + remedy, never a silent pass. On the adopt arm the verify additionally
4724
- * proves the serving pid CHANGED and the pre-adopt pid is dead, because port
4725
- * health alone is answered by the old process (flair#1684/#1685). The whole
4726
- * executor arm is wrapped in try/catch (Kern's b1 defect): a throw becomes a
4727
- * named `failed` result (or an engine-backwards `refused`), never a crash
4728
- * mid-report.
5843
+ * Never reports success on a direct start or an unattributed process. Every
5844
+ * throw becomes a named result, never a crash mid-report.
4729
5845
  */
4730
5846
  async function repairLaunchdManagement(dataDir, port) {
4731
5847
  const { plan, plistPath, isLegacy, config } = planLaunchdRepairFor(dataDir, port);
@@ -4736,163 +5852,456 @@ async function repairLaunchdManagement(dataDir, port) {
4736
5852
  return { kind: "refused", reason: plan.reason, detail: plan.detail, plistPath: plan.plistPath };
4737
5853
  case "adopt":
4738
5854
  case "regenerate": {
5855
+ let prepared;
4739
5856
  try {
4740
- // Guard FIRST (flair#1093): the repair is a boot path, and an older
4741
- // engine opening a newer store fails at the storage layer minutes
4742
- // later — same refusal as startFlairProcess. On the adopt arm this
4743
- // must run BEFORE the stop: it is a pure read whose inputs don't
4744
- // change during the repair, so guard-first refuses WITHOUT bouncing
4745
- // the live instance (guard-after-stop would SIGTERM the instance and
4746
- // then refuse, leaving it down with nothing to restart it).
4747
- guardEngineNotBackwards(dataDir);
4748
- // Credential before plist (flair#1685). Resolve and, when the plan says
4749
- // the pass file must be materialized (an env candidate), PROVE the
4750
- // credential against the live instance BEFORE the adopt bounce stops
4751
- // it — then write the 0600 file. Refuse, with no plist and no bounce,
4752
- // when nothing proves.
4753
- const adminPassPath = defaultAdminPassPath();
4754
- if (plan.credential.writeAdminPassFile) {
4755
- const candidate = process.env.FLAIR_ADMIN_PASS ?? process.env.HDB_ADMIN_PASSWORD;
4756
- if (!candidate) {
4757
- return {
4758
- kind: "refused",
4759
- reason: "missing-credential",
4760
- detail: `refusing to repair the launchd plist: ${adminPassPath} must be written from a credential, ` +
4761
- "but no credential is available in the environment.",
4762
- plistPath,
4763
- };
4764
- }
4765
- const proof = await proveAdminPassAgainstInstance(port, candidate);
4766
- if (proof) {
4767
- return {
4768
- kind: "refused",
4769
- reason: "missing-credential",
4770
- detail: "refusing to repair the launchd plist: the credential in FLAIR_ADMIN_PASS/HDB_ADMIN_PASSWORD " +
4771
- `does not authenticate against the running instance (${proof}), so writing it to ` +
4772
- `${adminPassPath} would create a pass file the instance rejects. Run 'flair init' to provision ` +
4773
- "the correct credential.",
4774
- plistPath,
4775
- };
4776
- }
4777
- writeAdminPassFile(adminPassPath, candidate);
4778
- }
4779
- // Validate the pass file against the launcher's OWN read contract before
4780
- // any plist names it: an existing file that drifted to 0644 must refuse
4781
- // here, never be baked into a plist the launcher will reject at start.
4782
- const passFileProblem = validateAdminPassFileForLauncher(adminPassPath);
4783
- if (passFileProblem) {
4784
- return {
4785
- kind: "refused",
4786
- reason: "missing-credential",
4787
- detail: `refusing to repair the launchd plist: ${passFileProblem}`,
4788
- plistPath,
4789
- };
4790
- }
4791
- // Adopt (flair#1573 slice b2): capture the process serving the instance
4792
- // NOW (before the stop), then clean-stop it, so the regenerate + load
4793
- // below does not collide on the port. The captured pid is the evidence
4794
- // the post-load verify uses to prove the serving pid CHANGED.
4795
- let directPid = null;
4796
- if (plan.kind === "adopt") {
4797
- directPid = resolveInstanceServingPid(dataDir, port);
4798
- const stop = await stopDirectProcessForAdopt(port, dataDir);
4799
- if (stop)
4800
- return stop; // a named failed result
4801
- }
4802
- const { execSync } = await import("node:child_process");
4803
- // Regenerate the plist (pass-file mode) and write it atomically.
4804
- // No secret is embedded, so 0644 is correct here.
4805
- const plist = buildRepairPlist(dataDir, config);
4806
- const newPlistPath = launchdPlistPath(launchdLabel(dataDir));
4807
- writeFileAtomic(newPlistPath, plist, 0o644);
4808
- // Validate the plist's absolute paths BEFORE launchd load (flair#1685
4809
- // hardening): launchctl load/start exit 0 for a job whose program is
4810
- // missing, so a stale launcher or node path produces a job that never
4811
- // starts — the same masked failure this repair exists to prevent.
4812
- const stalePlistPath = diagnoseLaunchdPlistPaths(newPlistPath);
4813
- if (stalePlistPath) {
4814
- return { kind: "failed", detail: stalePlistPath.message, remedy: stalePlistPath.remedy };
4815
- }
4816
- // flair#1586 / #1581: a SET_CONFIG-less detach (MQTT_* via
4817
- // buildDirectSpawnEnv) can persist mqtt.network as mtls, port,
4818
- // securePort when Harper stored no originals for already-null ports.
4819
- // Adopt SET_CONFIG updates those keys in place and would otherwise
4820
- // leave harper-config.yaml not byte-identical to the first-repair
4821
- // file (port, securePort, mtls). Reorder only those scalar lines
4822
- // before launchd loads so the next persist matches the settled file.
4823
- const cfgPath = harperConfigPath(dataDir);
4824
- if (cfgPath) {
4825
- const raw = readFileSync(cfgPath, "utf-8");
4826
- const { text, changed } = stabilizeMqttNetworkKeyOrder(raw);
4827
- if (changed)
4828
- writeFileAtomic(cfgPath, text, 0o644);
4829
- }
4830
- // If the resolved plist was a pre-flair#693 legacy label, unload and
4831
- // remove it so it is not orphaned beside the regenerated one.
4832
- if (isLegacy && plistPath !== newPlistPath) {
4833
- try {
4834
- execSync(`launchctl unload "${plistPath}"`, { stdio: "pipe" });
4835
- }
4836
- catch { /* best effort */ }
4837
- try {
4838
- unlinkSync(plistPath);
4839
- }
4840
- catch { /* best effort */ }
4841
- }
4842
- // Load (unload -> load -> start). Drop the pre-bounce leftover
4843
- // socket first so exists() cannot be true on the dead inode —
4844
- // Darwin #1704 (`9413a80`) chmod'd that leftover for 10s and
4845
- // still read 0755 after Harper bind()d a new file.
4846
- const bounceAt = Date.now();
4847
- unlinkStaleOpsSocket(dataDir);
4848
- ensureLaunchdServiceLoaded(dataDir, (cmd) => execSync(cmd, { stdio: "pipe" }));
4849
- // Verify (fail-loud).
4850
- const after = observeLaunchdManagement(dataDir, port);
4851
- if (after.state !== "managed") {
4852
- return { kind: "failed", detail: after.detail, remedy: after.remedy };
5857
+ const outcome = await prepareLaunchdRepair(dataDir, port, plan, plistPath, isLegacy, config);
5858
+ if ("kind" in outcome)
5859
+ return outcome;
5860
+ prepared = outcome;
5861
+ }
5862
+ catch (err) {
5863
+ // Phase 1 stops and unloads nothing and writes no plist, so a throw
5864
+ // here is reported as such (it may already have written the admin-pass
5865
+ // file — see prepareLaunchdRepair).
5866
+ const mapped = mapRepairThrow(err);
5867
+ if (mapped.kind === "failed") {
5868
+ return { ...mapped, detail: `${mapped.detail} (nothing was stopped or unloaded, and no plist was written)` };
4853
5869
  }
4854
- // On the adopt arm, port health alone is the green light that lied in
4855
- // #1684: the pre-adopt direct process answered the port the whole time
4856
- // the launchd job was failing to start. Prove the launchd job itself
4857
- // serves — the old pid is dead, the serving pid changed, and it is
4858
- // launchd's reported pid for this label.
4859
- if (plan.kind === "adopt") {
4860
- const label = after.label ?? resolveLaunchdLabel(dataDir).label;
4861
- // flair#1827: poll — the launchd-started Harper may not have written
4862
- // hdb.pid or bound the port yet. Wait for it to serve (and for the
4863
- // pre-adopt process to be gone), THEN prove identity with
4864
- // verifyAdoptServing UNCHANGED on the final observation.
4865
- const waited = await verifyAdoptServingWithWait({
4866
- observe: () => ({
4867
- directPid,
4868
- managedPid: readLaunchctlJobState(label, realLaunchctlLister).pid,
4869
- servingPid: resolveInstanceServingPid(dataDir, port),
4870
- directPidAlive: directPid !== null && isProcessAlive(directPid),
4871
- }),
4872
- deadlineMs: STARTUP_TIMEOUT_MS,
4873
- });
4874
- if (waited.proof) {
4875
- return { kind: "failed", detail: waited.proof.detail, remedy: ["flair stop", "flair doctor --fix"] };
4876
- }
5870
+ return mapped;
5871
+ }
5872
+ return commitLaunchdRepair(prepared);
5873
+ }
5874
+ }
5875
+ }
5876
+ function snapshotFile(path) {
5877
+ try {
5878
+ const bytes = readFileSync(path);
5879
+ return { kind: "present", bytes, mode: statSync(path).mode & 0o777 };
5880
+ }
5881
+ catch (err) {
5882
+ if (err?.code === "ENOENT")
5883
+ return { kind: "absent" };
5884
+ return { kind: "unreadable", error: `${err?.code ?? "error"}: ${err?.message ?? err}` };
5885
+ }
5886
+ }
5887
+ /** The first snapshot that could not be taken, as "<path> (<error>)", or null. */
5888
+ function unreadableSnapshot(entries) {
5889
+ for (const [path, snap] of entries) {
5890
+ if (snap && snap.kind === "unreadable")
5891
+ return `${path} (${snap.error})`;
5892
+ }
5893
+ return null;
5894
+ }
5895
+ /**
5896
+ * Put a file back as `snapshot` recorded it: rewritten byte-for-byte (the raw
5897
+ * buffer) when it was present, removed ONLY when it was proven absent. An
5898
+ * unreadable snapshot is never "restored" — that would delete or clobber a
5899
+ * file whose bytes were never known.
5900
+ */
5901
+ function restoreFile(path, snapshot) {
5902
+ if (snapshot.kind === "unreadable") {
5903
+ throw new Error(`not restoring ${path}: its prior contents could not be read (${snapshot.error})`);
5904
+ }
5905
+ if (snapshot.kind === "absent") {
5906
+ try {
5907
+ unlinkSync(path);
5908
+ }
5909
+ catch (err) {
5910
+ if (err?.code !== "ENOENT")
5911
+ throw err;
5912
+ }
5913
+ return;
5914
+ }
5915
+ writeFileAtomic(path, snapshot.bytes, snapshot.mode);
5916
+ }
5917
+ /**
5918
+ * Phase 1 of the repair: every check that can be made without stopping the
5919
+ * running instance or changing launchd. Returns a refusal/failure or the
5920
+ * prepared repair. Every UNKNOWN answer here refuses (flair#2040): a check
5921
+ * that could not be made is not a check that passed.
5922
+ *
5923
+ * The only write this phase can make is the admin-pass file, and only when the
5924
+ * plan must materialize it from an environment credential that authenticated
5925
+ * against the running instance; that 0600 file stays if a later check refuses.
5926
+ * It is written after every check that does not need it.
5927
+ */
5928
+ async function prepareLaunchdRepair(dataDir, port, plan, resolvedPlistPath, isLegacy, config) {
5929
+ const uid = currentUid();
5930
+ const domain = launchdGuiDomain(uid);
5931
+ const label = launchdLabel(dataDir);
5932
+ const plistPath = launchdPlistPath(label);
5933
+ const untouched = "Nothing was stopped, unloaded or rewritten.";
5934
+ // flair#2040: the launchd preflight comes FIRST. From an ssh session the GUI
5935
+ // domain is not reachable, and the load would fail only AFTER the live
5936
+ // instance was clean-stopped — leaving Flair down. unavailable / unknown /
5937
+ // disabled all REFUSE here: doctor reports an issue, never "fixed".
5938
+ const refusal = domainPreflightRefusal(observeLaunchdLoadability(label), uid);
5939
+ if (refusal)
5940
+ return { ...refusal, plistPath: resolvedPlistPath };
5941
+ // Guard (flair#1093): the repair is a boot path, and an older engine opening
5942
+ // a newer store fails at the storage layer minutes later — same refusal as
5943
+ // startFlairProcess. A pure read, so it refuses WITHOUT bouncing anything.
5944
+ guardEngineNotBackwards(dataDir);
5945
+ // The prior state the restore would need. A file that exists but cannot be
5946
+ // read cannot be put back: refuse now, before anything is stopped.
5947
+ const legacyPlistPath = isLegacy && resolvedPlistPath !== plistPath ? resolvedPlistPath : null;
5948
+ const cfgPath = harperConfigPath(dataDir);
5949
+ const priorPlist = snapshotFile(plistPath);
5950
+ const priorLegacy = legacyPlistPath ? snapshotFile(legacyPlistPath) : null;
5951
+ const priorConfig = cfgPath ? { path: cfgPath, snapshot: snapshotFile(cfgPath) } : null;
5952
+ const unreadable = unreadableSnapshot([
5953
+ [plistPath, priorPlist],
5954
+ [legacyPlistPath ?? "", priorLegacy],
5955
+ [cfgPath ?? "", priorConfig?.snapshot ?? null],
5956
+ ]);
5957
+ if (unreadable) {
5958
+ return {
5959
+ kind: "refused",
5960
+ reason: "unreadable-prior-state",
5961
+ detail: `refusing to repair launchd management: ${unreadable} exists but could not be read, so a failed hand-off ` +
5962
+ `could not put it back. ${untouched}`,
5963
+ plistPath: resolvedPlistPath,
5964
+ };
5965
+ }
5966
+ // Which jobs are loaded — asked, not assumed. "unknown" refuses: the commit
5967
+ // must boot out any loaded job BEFORE the stop, and cannot plan that blind.
5968
+ const jobPresence = launchdJobPresence(realLaunchctlCommand, domain, label);
5969
+ const legacyPresence = legacyPlistPath ? launchdJobPresence(realLaunchctlCommand, domain, LEGACY_LAUNCHD_LABEL) : "absent";
5970
+ if (jobPresence === "unknown" || legacyPresence === "unknown") {
5971
+ const which = jobPresence === "unknown" ? label : LEGACY_LAUNCHD_LABEL;
5972
+ return {
5973
+ kind: "refused",
5974
+ reason: "unverifiable",
5975
+ detail: `refusing to repair launchd management: 'launchctl print ${domain}/${which}' could not say whether the job is ` +
5976
+ `loaded. ${untouched}`,
5977
+ plistPath: resolvedPlistPath,
5978
+ };
5979
+ }
5980
+ let servingPid = null;
5981
+ if (plan.kind === "adopt") {
5982
+ // Adopt: attribute the direct process NOW. A foreign or unattributable
5983
+ // process refuses here, before any job is unloaded (flair#1454 machine).
5984
+ servingPid = resolveInstanceServingPid(dataDir, port);
5985
+ const state = classifyDaemonState(await gatherDaemonEvidence(port, dataDir), { port, dataDir });
5986
+ if (state.state === "DISAGREEMENT" || state.state === "UNKNOWN") {
5987
+ return {
5988
+ kind: "failed",
5989
+ detail: `refusing to adopt: ${state.detail} ${untouched}`,
5990
+ remedy: ["flair stop", "flair doctor --fix"],
5991
+ };
5992
+ }
5993
+ }
5994
+ else {
5995
+ // Regenerate: the planner saw no serving process — but "none identified"
5996
+ // is not "none". Require positive evidence that nothing serves the port
5997
+ // (ECONNREFUSED) before loading a job that would bind it.
5998
+ const health = await probeHealth(port);
5999
+ if (health.kind !== "refused") {
6000
+ return {
6001
+ kind: "refused",
6002
+ reason: "unverifiable",
6003
+ detail: `refusing to repair launchd management: no process was identified as serving this instance, but port ${port} ` +
6004
+ `is not free (health probe: ${health.kind}), so something this repair cannot attribute may be serving it. ${untouched}`,
6005
+ plistPath: resolvedPlistPath,
6006
+ };
6007
+ }
6008
+ }
6009
+ // Credential before plist (flair#1685). When the plan says the pass file must
6010
+ // be materialized (an env candidate), PROVE the credential against the live
6011
+ // instance BEFORE anything is stopped — then write the 0600 file. Refuse,
6012
+ // with no plist and no bounce, when nothing proves.
6013
+ const adminPassPath = defaultAdminPassPath();
6014
+ if (plan.credential.writeAdminPassFile) {
6015
+ const candidate = process.env.FLAIR_ADMIN_PASS ?? process.env.HDB_ADMIN_PASSWORD;
6016
+ if (!candidate) {
6017
+ return {
6018
+ kind: "refused",
6019
+ reason: "missing-credential",
6020
+ detail: `refusing to repair the launchd plist: ${adminPassPath} must be written from a credential, ` +
6021
+ "but no credential is available in the environment.",
6022
+ plistPath: resolvedPlistPath,
6023
+ };
6024
+ }
6025
+ const proof = await proveAdminPassAgainstInstance(port, candidate);
6026
+ if (proof) {
6027
+ return {
6028
+ kind: "refused",
6029
+ reason: "missing-credential",
6030
+ detail: "refusing to repair the launchd plist: the credential in FLAIR_ADMIN_PASS/HDB_ADMIN_PASSWORD " +
6031
+ `does not authenticate against the running instance (${proof}), so writing it to ` +
6032
+ `${adminPassPath} would create a pass file the instance rejects. Run 'flair init' to provision ` +
6033
+ "the correct credential.",
6034
+ plistPath: resolvedPlistPath,
6035
+ };
6036
+ }
6037
+ writeAdminPassFile(adminPassPath, candidate);
6038
+ }
6039
+ // Validate the pass file against the launcher's OWN read contract before any
6040
+ // plist names it: an existing file that drifted to 0644 must refuse here,
6041
+ // never be baked into a plist the launcher will reject at start.
6042
+ const passFileProblem = validateAdminPassFileForLauncher(adminPassPath);
6043
+ if (passFileProblem) {
6044
+ return {
6045
+ kind: "refused",
6046
+ reason: "missing-credential",
6047
+ detail: `refusing to repair the launchd plist: ${passFileProblem}`,
6048
+ plistPath: resolvedPlistPath,
6049
+ };
6050
+ }
6051
+ // Build the replacement in memory and validate it BEFORE anything is stopped
6052
+ // (flair#2040, flair#1685 hardening): launchctl exits 0 for a job whose
6053
+ // program is missing, so a stale launcher or node path would produce a job
6054
+ // that never starts — after the live instance was already down. A lint that
6055
+ // could not run fails here too.
6056
+ const plistContent = buildRepairPlist(dataDir, config);
6057
+ const contentProblem = validateLaunchdPlistContent(plistContent);
6058
+ if (contentProblem) {
6059
+ return {
6060
+ kind: "failed",
6061
+ detail: `refusing to repair launchd management: the plist this repair would install for ${label} cannot be ` +
6062
+ `loaded — ${contentProblem}. Nothing was stopped or unloaded, and no plist was written.`,
6063
+ remedy: ["npm install -g @tpsdev-ai/flair", "flair doctor --fix"],
6064
+ };
6065
+ }
6066
+ return {
6067
+ dataDir,
6068
+ port,
6069
+ arm: plan.kind,
6070
+ uid,
6071
+ domain,
6072
+ label,
6073
+ plistPath,
6074
+ plistContent,
6075
+ legacyPlistPath,
6076
+ prior: {
6077
+ plist: priorPlist,
6078
+ legacyPlist: priorLegacy,
6079
+ config: priorConfig,
6080
+ jobLoaded: jobPresence === "loaded",
6081
+ legacyJobLoaded: legacyPresence === "loaded",
6082
+ servingPid,
6083
+ },
6084
+ };
6085
+ }
6086
+ /** Phase 2: the bounce, with restore on any failure. */
6087
+ async function commitLaunchdRepair(p) {
6088
+ const done = { unloadedPrior: false, stopped: false, wrotePlist: false, removedLegacy: false, wroteConfig: false, loaded: false };
6089
+ try {
6090
+ // 1. Unload whatever launchd holds for this instance FIRST, so KeepAlive
6091
+ // cannot start the job while the direct process is stopping or while the
6092
+ // new plist is loading, and VERIFY it is gone (flair#2040). Such a job is
6093
+ // not serving this instance (the planner only reaches adopt/regenerate
6094
+ // when launchd is not managing it). If it cannot be shown gone, stop here
6095
+ // — before the direct process is touched.
6096
+ for (const [loaded, label] of [[p.prior.jobLoaded, p.label], [p.prior.legacyJobLoaded, LEGACY_LAUNCHD_LABEL]]) {
6097
+ if (!loaded)
6098
+ continue;
6099
+ const gone = ensureLaunchdJobAbsent({ run: realLaunchctlCommand, domain: p.domain, label });
6100
+ if (gone !== null)
6101
+ throw new Error(`could not unload the loaded job before stopping anything: ${gone}`);
6102
+ }
6103
+ done.unloadedPrior = p.prior.jobLoaded || p.prior.legacyJobLoaded;
6104
+ // 2. Adopt (flair#1573 slice b2): clean-stop the direct process so the new
6105
+ // job does not collide on the port. The captured pid is the evidence the
6106
+ // verify uses to prove the serving pid CHANGED.
6107
+ if (p.arm === "adopt") {
6108
+ done.stopped = true;
6109
+ const stop = await stopDirectProcessForAdopt(p.port, p.dataDir);
6110
+ if (stop)
6111
+ throw new Error(stop.kind === "failed" || stop.kind === "refused" ? stop.detail : "the direct process could not be stopped");
6112
+ }
6113
+ // 3. Write the validated plist (pass-file mode, no secret: 0644).
6114
+ done.wrotePlist = true;
6115
+ writeFileAtomic(p.plistPath, p.plistContent, 0o644);
6116
+ // flair#1586 / #1581: a SET_CONFIG-less detach (MQTT_* via
6117
+ // buildDirectSpawnEnv) can persist mqtt.network as mtls, port,
6118
+ // securePort when Harper stored no originals for already-null ports.
6119
+ // Adopt SET_CONFIG updates those keys in place and would otherwise
6120
+ // leave harper-config.yaml not byte-identical to the first-repair
6121
+ // file (port, securePort, mtls). Reorder only those scalar lines
6122
+ // before launchd loads so the next persist matches the settled file.
6123
+ if (p.prior.config && p.prior.config.snapshot.kind === "present") {
6124
+ const { text, changed } = stabilizeMqttNetworkKeyOrder(p.prior.config.snapshot.bytes.toString("utf-8"));
6125
+ if (changed) {
6126
+ done.wroteConfig = true;
6127
+ writeFileAtomic(p.prior.config.path, text, 0o644);
6128
+ }
6129
+ }
6130
+ // A pre-flair#693 legacy plist is retired so it is not orphaned beside the
6131
+ // regenerated one (its job was booted out and verified gone in step 1).
6132
+ if (p.legacyPlistPath) {
6133
+ done.removedLegacy = true;
6134
+ // Not best-effort (flair#2040): a legacy plist left beside the new one
6135
+ // would give launchd two jobs for this instance at the next login.
6136
+ try {
6137
+ unlinkSync(p.legacyPlistPath);
6138
+ }
6139
+ catch (err) {
6140
+ if (err?.code !== "ENOENT")
6141
+ throw new Error(`could not remove the legacy plist ${p.legacyPlistPath}: ${err?.code ?? err}`);
6142
+ }
6143
+ }
6144
+ // 4. Load, with commands that name the probed domain (flair#2040). Drop
6145
+ // the pre-bounce leftover socket first so exists() cannot be true on
6146
+ // the dead inode — Darwin #1704 (`9413a80`) chmod'd that leftover for
6147
+ // 10s and still read 0755 after Harper bind()d a new file.
6148
+ const bounceAt = Date.now();
6149
+ unlinkStaleOpsSocket(p.dataDir);
6150
+ done.loaded = true;
6151
+ loadLaunchdJob({ run: realLaunchctlCommand, domain: p.domain, label: p.label, plistPath: p.plistPath, strict: true });
6152
+ // 5. Verify (fail-loud, STRICT: launchd's pid must be the IDENTIFIED
6153
+ // serving pid — an unidentified one is not proof, flair#2040 — AND
6154
+ // Flair's /Health must answer ok). When kickstart returns, the job has
6155
+ // not bound its port yet (flair#1827), and hdb.pid may already name it:
6156
+ // wait, bounded, while launchd reports a pid and nothing answers its
6157
+ // port, then judge the final observation. Any other observation is
6158
+ // judged at once.
6159
+ const settled = await awaitLaunchdJobServing({
6160
+ observe: async () => {
6161
+ // Health first: a port that answers is then visible to the lsof read.
6162
+ const health = await probeHealth(p.port);
6163
+ return { health, management: observeLaunchdManagement(p.dataDir, p.port) };
6164
+ },
6165
+ deadlineMs: STARTUP_TIMEOUT_MS,
6166
+ });
6167
+ const verdict = judgeLaunchdJobServing(settled);
6168
+ if (!verdict.verified)
6169
+ throw new Error(verdict.detail);
6170
+ // On the adopt arm, port health alone is the green light that lied in
6171
+ // #1684: the pre-adopt direct process answered the port the whole time
6172
+ // the launchd job was failing to start. Prove the launchd job itself
6173
+ // serves — the old pid is dead, the serving pid changed, and it is
6174
+ // launchd's reported pid for this label.
6175
+ if (p.arm === "adopt") {
6176
+ const directPid = p.prior.servingPid;
6177
+ // flair#1827: poll — the launchd-started Harper may not have written
6178
+ // hdb.pid or bound the port yet. Wait for it to serve (and for the
6179
+ // pre-adopt process to be gone), THEN prove identity with
6180
+ // verifyAdoptServing UNCHANGED on the final observation.
6181
+ const waited = await verifyAdoptServingWithWait({
6182
+ observe: () => ({
6183
+ directPid,
6184
+ managedPid: readLaunchctlJobState(p.label, realLaunchctlLister).pid,
6185
+ servingPid: resolveInstanceServingPid(p.dataDir, p.port),
6186
+ directPidAlive: directPid !== null && isProcessAlive(directPid),
6187
+ }),
6188
+ deadlineMs: STARTUP_TIMEOUT_MS,
6189
+ });
6190
+ if (waited.proof)
6191
+ throw new Error(waited.proof.detail);
6192
+ }
6193
+ // flair#1701: the launchd bounce (adopt and regenerate) is a first
6194
+ // start. The product launcher execs Harper and never chmods, so the
6195
+ // new operations-server lands at 0777 & ~umask. Init / start /
6196
+ // restart already call this after health; without it here, doctor
6197
+ // flags ✗ Ops socket permissions until a second start. Wait for
6198
+ // Harper's bind() (HTTP can answer first); ignore leftover mtimes
6199
+ // older than bounceAt.
6200
+ await readyOpsSocketPostureAfterStart(p.dataDir, { notBeforeMs: bounceAt });
6201
+ const detail = p.arm === "adopt"
6202
+ ? `adopted the direct-spawned instance into launchd (bounced the live instance): ${verdict.detail}`
6203
+ : verdict.detail;
6204
+ return { kind: "repaired", detail };
6205
+ }
6206
+ catch (err) {
6207
+ return restoreAfterFailedRepair(p, done, err?.message ?? String(err));
6208
+ }
6209
+ }
6210
+ /**
6211
+ * Undo a failed phase 2 (flair#2040): unload the job this repair loaded and
6212
+ * verify it is gone, put the plist/config files back, and — when an instance
6213
+ * was serving before the repair and this repair stopped it — restart it
6214
+ * DIRECTLY. Every step is an attempt whose outcome is reported: the result is
6215
+ * always `failed` (never "fixed"), and its detail says the state the instance
6216
+ * was left in, including when that state could not be established.
6217
+ */
6218
+ async function restoreAfterFailedRepair(p, done, cause) {
6219
+ const notes = [];
6220
+ // a. Unload the job this repair loaded (or tried to), so KeepAlive cannot
6221
+ // fight the restart, VERIFY it is gone, and wait for its process to exit.
6222
+ if (done.loaded) {
6223
+ const launchdPid = readLaunchctlJobState(p.label, realLaunchctlLister).pid;
6224
+ const servingNow = resolveInstanceServingPid(p.dataDir, p.port);
6225
+ const gone = ensureLaunchdJobAbsent({ run: realLaunchctlCommand, domain: p.domain, label: p.label });
6226
+ if (gone !== null) {
6227
+ // A direct restart now could race the job on the same data directory.
6228
+ return {
6229
+ kind: "failed",
6230
+ detail: `${cause}. Undoing it could not be completed: the job this repair loaded could not be shown unloaded (${gone}), ` +
6231
+ "so Flair was NOT restarted directly — launchd may still run the new job, or Flair may be down. " +
6232
+ "The plist and config files were left as the repair wrote them.",
6233
+ remedy: [`launchctl bootout ${p.domain}/${p.label}`, "flair start"],
6234
+ };
6235
+ }
6236
+ for (const pid of new Set([launchdPid, servingNow])) {
6237
+ if (pid !== null && pid !== p.prior.servingPid) {
6238
+ try {
6239
+ await waitForProcessExit(pid, STARTUP_TIMEOUT_MS);
4877
6240
  }
4878
- // flair#1701: the launchd bounce (adopt and regenerate) is a first
4879
- // start. The product launcher execs Harper and never chmods, so the
4880
- // new operations-server lands at 0777 & ~umask. Init / start /
4881
- // restart already call this after health; without it here, doctor
4882
- // flags ✗ Ops socket permissions until a second start. Wait for
4883
- // Harper's bind() (HTTP can answer first); ignore leftover mtimes
4884
- // older than bounceAt.
4885
- await readyOpsSocketPostureAfterStart(dataDir, { notBeforeMs: bounceAt });
4886
- const detail = plan.kind === "adopt"
4887
- ? `adopted the direct-spawned instance into launchd (bounced the live instance): ${after.detail}`
4888
- : after.detail;
4889
- return { kind: "repaired", detail };
6241
+ catch { /* reported by the health probe below */ }
6242
+ }
6243
+ }
6244
+ notes.push(`the launchd job ${p.label} was unloaded again (verified absent)`);
6245
+ }
6246
+ // b. Put the files back (every snapshot was proven readable in phase 1).
6247
+ try {
6248
+ if (done.wrotePlist)
6249
+ restoreFile(p.plistPath, p.prior.plist);
6250
+ if (done.removedLegacy && p.legacyPlistPath && p.prior.legacyPlist)
6251
+ restoreFile(p.legacyPlistPath, p.prior.legacyPlist);
6252
+ if (done.wroteConfig && p.prior.config)
6253
+ restoreFile(p.prior.config.path, p.prior.config.snapshot);
6254
+ if (done.wrotePlist || done.removedLegacy || done.wroteConfig)
6255
+ notes.push("the plist and config files were put back as they were");
6256
+ }
6257
+ catch (err) {
6258
+ notes.push(`putting the plist/config files back FAILED (${err?.message ?? err})`);
6259
+ }
6260
+ if (done.unloadedPrior) {
6261
+ notes.push("the launchd job that was loaded before the repair (it was not serving this instance) is not loaded in this session now");
6262
+ }
6263
+ // c. Bring back the instance that was serving.
6264
+ if (p.arm === "adopt") {
6265
+ const health = await probeHealth(p.port);
6266
+ if (!done.stopped) {
6267
+ notes.push(health.kind === "ok"
6268
+ ? `this repair did not stop the running instance, and Flair is serving on port ${p.port} — directly, NOT under launchd`
6269
+ : `this repair did not stop the running instance, but Flair is not answering on port ${p.port} (${health.kind})`);
6270
+ }
6271
+ else if (health.kind !== "refused") {
6272
+ // The repair stopped the instance, yet the port is not free: something
6273
+ // this repair cannot attribute answers or holds it. Starting a second
6274
+ // instance on top of it is not a restore.
6275
+ return {
6276
+ kind: "failed",
6277
+ detail: `${cause}. The repair had stopped the running instance, and port ${p.port} is not free (${health.kind}) — ` +
6278
+ `what holds it could not be attributed, so Flair was NOT restarted directly. ${notes.length ? `Also: ${notes.join("; ")}.` : ""}`.trim(),
6279
+ remedy: ["flair status", "flair start"],
6280
+ };
6281
+ }
6282
+ else {
6283
+ try {
6284
+ const pid = await startFlairDirect(p.port, p.dataDir);
6285
+ notes.push(`Flair was restarted directly${pid ? ` (pid ${pid})` : ""} and is serving on port ${p.port} — running directly, NOT under launchd`);
4890
6286
  }
4891
6287
  catch (err) {
4892
- return mapRepairThrow(err);
6288
+ return {
6289
+ kind: "failed",
6290
+ detail: `${cause}. The repair had stopped the running instance, and restarting it directly FAILED ` +
6291
+ `(${err?.message ?? err}): Flair is DOWN. ${notes.length ? `Also: ${notes.join("; ")}.` : ""}`.trim(),
6292
+ remedy: ["flair start"],
6293
+ };
4893
6294
  }
4894
6295
  }
4895
6296
  }
6297
+ else {
6298
+ notes.push("Flair was not running before this repair (its port was free) and was not started");
6299
+ }
6300
+ return {
6301
+ kind: "failed",
6302
+ detail: `${cause}. Restored: ${notes.join("; ")}.`,
6303
+ remedy: ["flair doctor --fix"],
6304
+ };
4896
6305
  }
4897
6306
  /**
4898
6307
  * Clean-stop the direct (non-launchd) process serving `dataDir`+`port` for the
@@ -5068,10 +6477,21 @@ async function stopFlairProcess(port, dataDir) {
5068
6477
  await waitForProcessExit(pid, STARTUP_TIMEOUT_MS);
5069
6478
  }
5070
6479
  catch { /* best-effort — the next start will surface the real problem */ }
6480
+ // flair#2055: once the process is CONFIRMED gone, drop the identity
6481
+ // sidecar. Gated on a fresh O_NOFOLLOW read that still names the pid it
6482
+ // named before (a sidecar another supervisor rewrote in between is left
6483
+ // alone); a process that survived the wait (or whose liveness is unknown)
6484
+ // removes nothing.
6485
+ removeStaleSidecarIfConfirmedDead(dataDir);
6486
+ return;
6487
+ }
6488
+ case "NOT_RUNNING": {
6489
+ // Idempotent no-op for the process — but a sidecar left naming a pid that
6490
+ // is CONFIRMED gone is a leftover too (flair#2055), and removing it here
6491
+ // keeps a repeat stop from carrying the refusal forward.
6492
+ removeStaleSidecarIfConfirmedDead(dataDir);
5071
6493
  return;
5072
6494
  }
5073
- case "NOT_RUNNING":
5074
- return; // idempotent no-op
5075
6495
  case "DISAGREEMENT":
5076
6496
  case "UNKNOWN":
5077
6497
  // Deliberately outside any catch: a refusal must reach the caller, not
@@ -5139,34 +6559,65 @@ async function startFlairProcess(port, dataDir) {
5139
6559
  // for health on `port`, see the OTHER instance answer, and report
5140
6560
  // success.
5141
6561
  assertLaunchdServiceOwnedBy(dataDir, label, plistPath, "start");
5142
- try {
5143
- // flair#1022: launchd will not tell us it cannot exec the job.
5144
- // `launchctl load` and `launchctl start` BOTH exit 0 for a plist whose
5145
- // ProgramArguments[0] does not exist (measured, see the module header),
5146
- // so the only way this loop learns anything is by waiting the full
5147
- // startup budget for a port that will never open — the reported
5148
- // incident's second 60-second hang, ending in "did not respond within
5149
- // 60000ms (120 attempts)", an error about a port that says nothing
5150
- // about the cause. The paths in the plist are absolute and checkable
5151
- // with an existsSync, so check them first and turn a two-minute silence
5152
- // into an immediate, named diagnosis. Still falls back — a running
5153
- // instance beats a down one — just without the wait or the mystery.
5154
- const stalePlist = diagnoseLaunchdPlistPaths(plistPath);
5155
- if (stalePlist) {
5156
- throw new Error(`${stalePlist.message} Fix it with: ${stalePlist.remedy.join(" && ")}`);
5157
- }
5158
- const { execSync } = await import("node:child_process");
5159
- ensureLaunchdServiceLoaded(dataDir, (cmd) => execSync(cmd, { stdio: "pipe" }));
5160
- await waitForHealth(port, DEFAULT_ADMIN_USER, process.env.HDB_ADMIN_PASSWORD ?? "", STARTUP_TIMEOUT_MS);
5161
- readyOpsSocketPosture(dataDir); // flair#763: re-assert socket posture across restart/upgrade
5162
- stampEngineVersionIfRunning(dataDir); // flair#1047: stamp the store with the engine version
5163
- return;
6562
+ // flair#2040: preflight BEFORE the load — is the GUI domain reachable
6563
+ // from this session, and is the job enabled there? If not, say why and
6564
+ // start directly (a running instance beats a down one). The caller
6565
+ // (`flair restart`, `flair upgrade`) observes launchd management
6566
+ // afterwards and reports a detached instance as such.
6567
+ const loadability = observeLaunchdLoadability(launchdLabel(dataDir));
6568
+ if (!loadabilityAllowsAttempt(loadability)) {
6569
+ console.error(renderStartLaunchdUnavailable("flair", loadability));
5164
6570
  }
5165
- catch (err) {
5166
- console.error(`launchd start failed, falling back to direct start: ${err.message}`);
6571
+ else {
6572
+ try {
6573
+ // flair#1022: launchd will not tell us it cannot exec the job.
6574
+ // `launchctl load` and `launchctl start` BOTH exit 0 for a plist whose
6575
+ // ProgramArguments[0] does not exist (measured, see the module header),
6576
+ // so the only way this loop learns anything is by waiting the full
6577
+ // startup budget for a port that will never open — the reported
6578
+ // incident's second 60-second hang, ending in "did not respond within
6579
+ // 60000ms (120 attempts)", an error about a port that says nothing
6580
+ // about the cause. The paths in the plist are absolute and checkable
6581
+ // with an existsSync, so check them first and turn a two-minute silence
6582
+ // into an immediate, named diagnosis. Still falls back — a running
6583
+ // instance beats a down one — just without the wait or the mystery.
6584
+ // flair#2040: a validation refusal — nothing loaded or unloaded.
6585
+ const stalePlist = diagnoseLaunchdPlistPaths(plistPath);
6586
+ if (stalePlist) {
6587
+ throw new LaunchdValidationRefusal(`${stalePlist.message} Fix it with: ${stalePlist.remedy.join(" && ")}`);
6588
+ }
6589
+ ensureLaunchdServiceLoaded(dataDir, realLaunchctlCommand);
6590
+ await waitForHealth(port, DEFAULT_ADMIN_USER, process.env.HDB_ADMIN_PASSWORD ?? "", STARTUP_TIMEOUT_MS);
6591
+ readyOpsSocketPosture(dataDir); // flair#763: re-assert socket posture across restart/upgrade
6592
+ stampEngineVersionIfRunning(dataDir); // flair#1047: stamp the store with the engine version
6593
+ return;
6594
+ }
6595
+ catch (err) {
6596
+ // flair#2040: start directly only when no job for this instance could
6597
+ // start underneath the direct process. A failed LOAD is unloaded again
6598
+ // and verified gone; a VALIDATION refusal loaded and unloaded nothing,
6599
+ // so nothing is booted out — a loaded job refuses the direct start
6600
+ // instead (afterFailedLaunchdAttempt).
6601
+ const labels = label === LEGACY_LAUNCHD_LABEL ? [launchdLabel(dataDir), LEGACY_LAUNCHD_LABEL] : [launchdLabel(dataDir)];
6602
+ const after = afterFailedLaunchdAttempt("flair", launchdLabel(dataDir), labels, err);
6603
+ if (!after.directStart)
6604
+ throw new Error(after.lines.join("\n"));
6605
+ for (const line of after.lines)
6606
+ console.error(line);
6607
+ }
5167
6608
  }
5168
6609
  }
5169
6610
  }
6611
+ await startFlairDirect(port, dataDir);
6612
+ }
6613
+ /**
6614
+ * Start Flair as a DIRECT (non-launchd) process and wait for it to answer —
6615
+ * the fallback half of startFlairProcess, and what `doctor --fix` / `init` use
6616
+ * to bring back an instance they stopped when the launchd hand-off failed
6617
+ * (flair#2040). Returns the spawned pid. Throws when Harper cannot be found or
6618
+ * does not answer within the startup budget.
6619
+ */
6620
+ async function startFlairDirect(port, dataDir) {
5170
6621
  console.log("Starting...");
5171
6622
  const harper = resolveHarperBin(harperSearchRoots());
5172
6623
  if (!harper.path) {
@@ -5210,6 +6661,7 @@ async function startFlairProcess(port, dataDir) {
5210
6661
  await waitForHealth(port, DEFAULT_ADMIN_USER, adminPass, STARTUP_TIMEOUT_MS);
5211
6662
  readyOpsSocketPosture(dataDir); // flair#763: re-assert socket posture across restart/upgrade
5212
6663
  stampEngineVersionIfRunning(dataDir); // flair#1047: stamp the store with the engine version
6664
+ return proc.pid ?? null;
5213
6665
  }
5214
6666
  /**
5215
6667
  * The ONE restart mechanism for a local Flair install. Shared by `flair
@@ -5228,8 +6680,57 @@ async function startFlairProcess(port, dataDir) {
5228
6680
  * frames down.
5229
6681
  */
5230
6682
  async function restartFlair(port, dataDir) {
5231
- await stopFlairProcess(port, dataDir);
5232
- await startFlairProcess(port, dataDir);
6683
+ // flair#2034 §2: on Linux, an instance proven to run under a systemd USER
6684
+ // unit (found from the serving process's cgroup; its MainPID is that
6685
+ // process) is restarted THROUGH that unit, and the unit's new main process
6686
+ // must run from the unit's WorkingDirectory. The signal-and-respawn path
6687
+ // below would leave a supervised instance running outside its unit — so it
6688
+ // is refused, with the systemctl command, when a process it could stop is
6689
+ // the MainPID of any other unit, or when its cgroup or that unit's MainPID
6690
+ // cannot be read. A process that merely sits in some service's cgroup (a CI
6691
+ // runner agent's child: the unit's MainPID is another process) was started
6692
+ // directly and is restarted directly.
6693
+ if (process.platform === "linux") {
6694
+ const ev = localPidEvidence(dataDir, port);
6695
+ const how = await restartOnLinux({
6696
+ serving: resolveServingTree(dataDir, port, { local: true }),
6697
+ pids: [...(ev.pidFile !== null ? [ev.pidFile] : []), ...(ev.listeners ?? [])],
6698
+ procCgroup: readProcCgroup,
6699
+ uid: typeof process.getuid === "function" ? process.getuid() : -1,
6700
+ unitMainPid: systemdUnitMainPid,
6701
+ systemctl: (args) => {
6702
+ execFileSync("systemctl", args, { stdio: "pipe", timeout: args[1] === "restart" ? STARTUP_TIMEOUT_MS * 2 : 30_000 });
6703
+ },
6704
+ waitHealthy: () => waitForHealth(port, DEFAULT_ADMIN_USER, process.env.HDB_ADMIN_PASSWORD ?? "", STARTUP_TIMEOUT_MS),
6705
+ unitState: systemdUserUnitState,
6706
+ cwdOf: (pid) => {
6707
+ try {
6708
+ return realpathSync(`/proc/${pid}/cwd`);
6709
+ }
6710
+ catch {
6711
+ return null;
6712
+ }
6713
+ },
6714
+ samePath: samePathCanonical,
6715
+ beforeRestart: (s) => {
6716
+ if (s.unitTree !== null && samePathCanonical(s.unitTree, flairPackageDir()))
6717
+ guardEngineNotBackwards(dataDir);
6718
+ },
6719
+ direct: async () => {
6720
+ await stopFlairProcess(port, dataDir);
6721
+ await startFlairProcess(port, dataDir);
6722
+ },
6723
+ log: (line) => console.log(line),
6724
+ });
6725
+ if (how === "systemd") {
6726
+ readyOpsSocketPosture(dataDir);
6727
+ stampEngineVersionIfRunning(dataDir);
6728
+ }
6729
+ }
6730
+ else {
6731
+ await stopFlairProcess(port, dataDir);
6732
+ await startFlairProcess(port, dataDir);
6733
+ }
5233
6734
  // Bust the version-handshake cache so the next preAction nudge re-fetches
5234
6735
  // the LIVE version instead of the pre-restart cached one (the false
5235
6736
  // "server is running <old>" users hit for up to 60s post-upgrade+restart).
@@ -5376,6 +6877,7 @@ registerFleet(program);
5376
6877
  // Bind shared cli-locals first so the extracted module never imports this file.
5377
6878
  bindDoctorCli({
5378
6879
  api,
6880
+ assessInstallTree,
5379
6881
  checkAgentRegistered,
5380
6882
  classifyOpsSocketPosture,
5381
6883
  configPath,
@@ -5389,7 +6891,9 @@ bindDoctorCli({
5389
6891
  readPortFromConfig,
5390
6892
  relativeTime,
5391
6893
  repairLaunchdManagement,
6894
+ repointMainServiceUnit,
5392
6895
  resolveHttpPort,
6896
+ restartFlair,
5393
6897
  resolveOpsPort,
5394
6898
  verifyAuditLog,
5395
6899
  verifySemanticSearch,
@@ -5645,7 +7149,10 @@ harperConfigPath, readHarperConfig, readPortFromHarperConfig, persistDefaultInst
5645
7149
  // launchd label (flair#693)
5646
7150
  LEGACY_LAUNCHD_LABEL, launchdLabel, launchdPlistPath, cleanupLegacyLaunchdPlist, resolveLaunchdLabel, migrateLegacyLaunchdLabel, ensureLaunchdServiceLoaded,
5647
7151
  // launchd management observation (flair#1022)
5648
- observeLaunchdManagement, resolveInstanceServingPid, };
7152
+ observeLaunchdManagement, resolveInstanceServingPid,
7153
+ // launchd preflight, repair and init registration (flair#2040) — exported so
7154
+ // the command-level tests drive them against a stubbed launchctl.
7155
+ observeLaunchdLoadability, repairLaunchdManagement, registerInitLaunchdService, startFlairProcess, };
5649
7156
  // Shared with `flair status` via src/lib/ops-api-bind.ts (flair#852).
5650
7157
  export { detectOpsApiAllInterfacesBind };
5651
7158
  export { searchScoringFormula, buildSearchExplain, formatSearchExplain } from "./commands/search.js";