@tpsdev-ai/flair 0.57.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 (122) hide show
  1. package/README.md +4 -4
  2. package/SECURITY.md +4 -1
  3. package/dist/build-info.json +3 -3
  4. package/dist/cli.js +1685 -279
  5. package/dist/commands/doctor.js +162 -4
  6. package/dist/commands/federation.js +2 -1
  7. package/dist/commands/hook.js +10 -2
  8. package/dist/commands/init.js +150 -44
  9. package/dist/commands/memory.js +24 -2
  10. package/dist/commands/quality.js +26 -18
  11. package/dist/commands/service.js +137 -22
  12. package/dist/commands/status.js +114 -3
  13. package/dist/commands/upgrade.js +204 -84
  14. package/dist/doctor-client.js +50 -4
  15. package/dist/federation/scheduler.js +253 -4
  16. package/dist/install/clients.js +89 -23
  17. package/dist/install/global-bin-path.js +26 -6
  18. package/dist/lib/atomic-write.js +256 -0
  19. package/dist/lib/daemon-liveness.js +61 -0
  20. package/dist/lib/doctor-run.js +5 -0
  21. package/dist/lib/embed-gpu-doctor.js +49 -26
  22. package/dist/lib/federation-memory-attributes.js +15 -0
  23. package/dist/lib/init-admin-pass.js +4 -2
  24. package/dist/lib/init-listener-environ.js +38 -0
  25. package/dist/lib/init-occupied-listener.js +165 -0
  26. package/dist/lib/launchd-domain-preflight.js +448 -0
  27. package/dist/lib/launchd-management.js +176 -6
  28. package/dist/lib/launchd-repair.js +95 -0
  29. package/dist/lib/memory-attributes.js +77 -0
  30. package/dist/lib/node-alias-path.js +95 -0
  31. package/dist/lib/npm-registry.js +119 -6
  32. package/dist/lib/owned-pins.js +20 -6
  33. package/dist/lib/service-repoint-apply.js +267 -0
  34. package/dist/lib/service-repoint.js +575 -0
  35. package/dist/lib/toml-string-array.js +104 -0
  36. package/dist/lib/tree-divergence.js +716 -0
  37. package/dist/lib/upgrade-plain-tree.js +18 -8
  38. package/dist/lib/upgrade-prior-liveness.js +69 -0
  39. package/dist/lib/upgrade-rollback.js +116 -0
  40. package/dist/rem/runner.js +11 -0
  41. package/dist/resources/Agent.js +27 -14
  42. package/dist/resources/AgentSeed.js +35 -1
  43. package/dist/resources/Federation.js +70 -52
  44. package/dist/resources/Memory.js +567 -72
  45. package/dist/resources/MemoryArchive.js +9 -0
  46. package/dist/resources/MemoryBootstrap.js +4 -0
  47. package/dist/resources/MemoryFeed.js +204 -3
  48. package/dist/resources/MemoryHostSource.js +90 -0
  49. package/dist/resources/MemoryMaintenance.js +121 -32
  50. package/dist/resources/MemoryReflect.js +4 -1
  51. package/dist/resources/MemoryReindex.js +7 -4
  52. package/dist/resources/MemoryUsage.js +53 -3
  53. package/dist/resources/Presence.js +18 -10
  54. package/dist/resources/RecordUsage.js +30 -40
  55. package/dist/resources/Relationship.js +167 -78
  56. package/dist/resources/SemanticSearch.js +19 -6
  57. package/dist/resources/Soul.js +31 -19
  58. package/dist/resources/XAA.js +7 -3
  59. package/dist/resources/agent-auth.js +16 -10
  60. package/dist/resources/auth-middleware.js +135 -48
  61. package/dist/resources/auto-promote-lib.js +4 -4
  62. package/dist/resources/bm25-index-service.js +246 -32
  63. package/dist/resources/bm25-status.js +132 -0
  64. package/dist/resources/ed25519-auth.js +11 -54
  65. package/dist/resources/embed-gpu.js +262 -47
  66. package/dist/resources/embeddings-boot.js +52 -17
  67. package/dist/resources/federation-classify.js +12 -0
  68. package/dist/resources/federation-crypto.js +65 -19
  69. package/dist/resources/health.js +57 -14
  70. package/dist/resources/host-pointer/registry.js +35 -0
  71. package/dist/resources/host-pointer-adapter.js +15 -0
  72. package/dist/resources/host-source-visibility.js +167 -0
  73. package/dist/resources/host-source.js +151 -0
  74. package/dist/resources/instance-identity.js +3 -2
  75. package/dist/resources/mcp-handler.js +147 -51
  76. package/dist/resources/mcp-tools.js +25 -21
  77. package/dist/resources/memory-consolidate-lib.js +3 -1
  78. package/dist/resources/memory-declared-attributes.js +103 -0
  79. package/dist/resources/memory-feed-lib.js +5 -1
  80. package/dist/resources/memory-host-source.js +163 -0
  81. package/dist/resources/migrations/synthetic-test-migration.js +4 -1
  82. package/dist/resources/migrations/visibility-backfill.js +4 -1
  83. package/dist/resources/originator-instance.js +235 -0
  84. package/dist/resources/promotion-stamp.js +2 -0
  85. package/dist/resources/provenance.js +111 -11
  86. package/dist/resources/record-owner-guard.js +19 -0
  87. package/dist/resources/record-type-kit.js +9 -12
  88. package/dist/resources/record-types.js +6 -6
  89. package/dist/resources/relay-ops.js +28 -3
  90. package/dist/resources/replay-store.js +289 -0
  91. package/dist/resources/request-transaction.js +78 -0
  92. package/dist/resources/search-readiness.js +19 -21
  93. package/dist/resources/semantic-retrieval-core.js +5 -1
  94. package/dist/resources/table-patch-policy.js +109 -0
  95. package/dist/resources/table-patches.js +17 -0
  96. package/dist/resources/table-post-policy.js +138 -0
  97. package/dist/resources/table-posts.js +22 -0
  98. package/dist/resources/table-subscription-policy.js +135 -0
  99. package/dist/resources/table-subscriptions.js +19 -0
  100. package/dist/resources/tool-descriptors/index.js +15 -15
  101. package/dist/resources/trust-block.js +10 -3
  102. package/dist/resources/usage-recording.js +169 -41
  103. package/dist/src/lib/memory-attributes.js +77 -0
  104. package/docs/api-reference.md +79 -15
  105. package/docs/claude-code.md +132 -0
  106. package/docs/deployment.md +1 -1
  107. package/docs/federation.md +1 -1
  108. package/docs/integrations.md +5 -5
  109. package/docs/mcp-clients.md +11 -21
  110. package/docs/notes/mcp-oauth-model2.md +15 -1
  111. package/docs/quickstart.md +5 -0
  112. package/docs/releasing.md +134 -2
  113. package/docs/supply-chain-policy.md +10 -5
  114. package/docs/troubleshooting.md +11 -0
  115. package/docs/upgrade.md +187 -61
  116. package/package.json +9 -5
  117. package/schemas/agent.graphql +9 -6
  118. package/schemas/federation.graphql +2 -11
  119. package/schemas/memory.graphql +106 -17
  120. package/schemas/replay.graphql +18 -0
  121. package/templates/launchd/start-flair-with-admin-pass.sh +22 -0
  122. package/dist/resources/federation-nonce-store.js +0 -195
package/dist/cli.js CHANGED
@@ -28,14 +28,24 @@ import { readSecretFileSecure, readAdminPassFileSecure, defaultAdminPassPath, de
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";
@@ -55,7 +65,8 @@ import { bindCli as bindRelationshipCli, register as registerRelationship, } fro
55
65
  import { bindCli as bindWorkspaceCli, register as registerWorkspace, MAX_WORKSPACE_FIELD_LENGTH, } from "./commands/workspace.js";
56
66
  import { decideHubReconcile, instanceWriteNotVerifiedMessage, multipleInstanceRowsMessage, readInstanceRows, updateInstanceRole, verifyInstanceWrite, } from "./lib/instance-identity-row.js";
57
67
  import { applyUpgradeMigrations } from "./lib/upgrade-migrations.js";
58
- 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";
59
70
  import { bindCli as bindOrgeventCli, register as registerOrgevent, MAX_ORGEVENT_DETAIL_LENGTH, MAX_ORGEVENT_SUMMARY_LENGTH, publishOrgEvent, } from "./commands/orgevent.js";
60
71
  import { bindCli as bindAttentionCli, register as registerAttention, } from "./commands/attention.js";
61
72
  import { bindCli as bindBootstrapCli, register as registerBootstrap, } from "./commands/bootstrap.js";
@@ -303,6 +314,34 @@ function resolveLaunchdLabel(dataDir, launchAgentsDir = defaultLaunchAgentsDir()
303
314
  return { label: LEGACY_LAUNCHD_LABEL, plistPath: legacyPlistPath, isLegacy: true };
304
315
  return { label: newLabel, plistPath: newPlistPath, isLegacy: false };
305
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
+ }
306
345
  /**
307
346
  * Migrate a pre-flair#693 legacy-labeled launchd service to the new
308
347
  * instance-scoped label for `dataDir`: unload the legacy service FIRST,
@@ -311,19 +350,32 @@ function resolveLaunchdLabel(dataDir, launchAgentsDir = defaultLaunchAgentsDir()
311
350
  * file. There is never a moment where both the legacy and new labels are
312
351
  * registered for the same data dir. No-op (migrated: false) if there's
313
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.
314
359
  */
315
- function migrateLegacyLaunchdLabel(dataDir, runLaunchctl, launchAgentsDir = defaultLaunchAgentsDir()) {
360
+ function migrateLegacyLaunchdLabel(dataDir, runLaunchctl, launchAgentsDir = defaultLaunchAgentsDir(), uid = currentUid(), opts = {}) {
316
361
  const resolved = resolveLaunchdLabel(dataDir, launchAgentsDir);
317
362
  if (!resolved.isLegacy) {
318
363
  return { migrated: false, label: resolved.label, plistPath: resolved.plistPath };
319
364
  }
320
365
  const newLabel = launchdLabel(dataDir);
321
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;
322
372
  try {
323
- 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.");
324
378
  }
325
- catch { /* best effort */ }
326
- const legacyContent = readFileSync(resolved.plistPath, "utf-8");
327
379
  // Use a function replacer to avoid $-sensitivity in the replacement
328
380
  // string (flair#919). String.prototype.replace interprets $&, $', $`
329
381
  // etc. in the replacement even when the search value is a plain string.
@@ -333,15 +385,48 @@ function migrateLegacyLaunchdLabel(dataDir, runLaunchctl, launchAgentsDir = defa
333
385
  // Refuse to propagate a malformed plist: if the Label wasn't found,
334
386
  // the plist is not what we expect and migration must not write it.
335
387
  if (newContent === legacyContent) {
336
- 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 ` +
337
389
  `Label key — it may be malformed or from an unknown Flair version. ` +
338
390
  `Remove it manually and re-run 'flair init'.`);
339
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
+ }
340
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.
341
417
  try {
342
418
  unlinkSync(resolved.plistPath);
343
419
  }
344
- 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
+ }
345
430
  return { migrated: true, label: newLabel, plistPath: newPlistPath };
346
431
  }
347
432
  /**
@@ -355,35 +440,42 @@ function migrateLegacyLaunchdLabel(dataDir, runLaunchctl, launchAgentsDir = defa
355
440
  * real launchd. The caller (init) passes a real execSync wrapper; tests
356
441
  * pass a recording stub.
357
442
  */
358
- function cleanupLegacyLaunchdPlist(dataDir, plistDir, runLaunchctl) {
443
+ function cleanupLegacyLaunchdPlist(dataDir, plistDir, runLaunchctl, uid = currentUid(), opts = {}) {
359
444
  const legacyPlistPath = launchdPlistPath(LEGACY_LAUNCHD_LABEL, plistDir);
360
445
  if (!existsSync(legacyPlistPath))
361
446
  return { action: "none" };
362
447
  const legacyRootPath = readPlistRootPath(legacyPlistPath);
363
448
  const legacyOwnedByUs = legacyRootPath !== null && resolve(legacyRootPath) === resolve(dataDir);
364
449
  if (legacyOwnedByUs) {
365
- let unloadFailed;
366
450
  let deleteFailed;
367
- try {
368
- runLaunchctl(`launchctl unload "${legacyPlistPath}"`);
369
- }
370
- catch (err) {
371
- unloadFailed = err?.message ?? String(err);
372
- console.error(`Failed to unload legacy launchd service (${LEGACY_LAUNCHD_LABEL}): ` +
373
- `${unloadFailed}. ` +
374
- `The plist at ${legacyPlistPath} may still be loaded — ` +
375
- `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 };
376
466
  }
377
467
  try {
378
468
  unlinkSync(legacyPlistPath);
379
- 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).`);
380
472
  }
381
473
  catch (err) {
382
474
  deleteFailed = err?.message ?? String(err);
383
475
  console.error(`Failed to remove legacy launchd plist at ${legacyPlistPath}: ` +
384
476
  `${deleteFailed}. Remove it manually.`);
385
477
  }
386
- return { action: "unloaded", unloadFailed, deleteFailed };
478
+ return { action: "unloaded", deleteFailed };
387
479
  }
388
480
  if (legacyRootPath !== null) {
389
481
  console.log(`Skipped legacy launchd cleanup: the plist at ${legacyPlistPath} ` +
@@ -399,28 +491,34 @@ function cleanupLegacyLaunchdPlist(dataDir, plistDir, runLaunchctl) {
399
491
  /**
400
492
  * Load + start `dataDir`'s launchd service, migrating off a pre-flair#693
401
493
  * legacy registration FIRST if one is found (migrateLegacyLaunchdLabel
402
- * above). Call order is load-bearing — unload legacy -> load new -> start
403
- * new, never a window with both registered — and pinned by
404
- * test/unit/launchd-label.test.ts. `load` failure is tolerated (e.g.
405
- * "already loaded" is a common, harmless nonzero exit); `start` failure
406
- * propagates so callers can fall back to a direct (non-launchd) start.
407
- * Shared by the `start` command and startFlairProcess() (used by restart/
408
- * 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.
409
509
  */
410
- function ensureLaunchdServiceLoaded(dataDir, runLaunchctl, launchAgentsDir = defaultLaunchAgentsDir()) {
411
- const migration = migrateLegacyLaunchdLabel(dataDir, runLaunchctl, launchAgentsDir);
412
- // Unload first so a rewritten plist is re-read (flair#872).
413
- // launchd caches the environment of an already-loaded job; load
414
- // alone does not pick up changes to the plist on disk.
415
- try {
416
- runLaunchctl(`launchctl unload "${migration.plistPath}"`);
417
- }
418
- catch { /* not loaded, etc. — best effort */ }
419
- try {
420
- runLaunchctl(`launchctl load "${migration.plistPath}"`);
421
- }
422
- catch { /* already loaded, etc. — best effort */ }
423
- 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
+ });
424
522
  return migration;
425
523
  }
426
524
  function configPath() {
@@ -2476,8 +2574,12 @@ async function opsSeedInsertWithRetry(req) {
2476
2574
  }
2477
2575
  // flair#1790 review C2: 401 FIRST. An auth failure must never be masked by
2478
2576
  // a body that happens to carry a "duplicate"/"already exists" marker.
2479
- if (res.status === 401)
2480
- 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
+ }
2481
2583
  // THEN the idempotent duplicate path: an unconditional 409, then the
2482
2584
  // marker match for the remaining non-OK shapes.
2483
2585
  const duplicate = res.status === 409 || text.includes("duplicate") || text.includes("already exists");
@@ -2504,7 +2606,19 @@ async function opsSeedInsertWithRetry(req) {
2504
2606
  }
2505
2607
  }
2506
2608
  }
2507
- 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) {
2508
2622
  const url = typeof opsPortOrUrl === "number"
2509
2623
  ? `http://127.0.0.1:${opsPortOrUrl}/`
2510
2624
  : `${opsPortOrUrl.replace(/\/$/, "")}/`;
@@ -2543,7 +2657,24 @@ export async function seedAgentViaOpsApi(opsPortOrUrl, agentId, pubKeyB64url, ad
2543
2657
  noun: "agent",
2544
2658
  tableName: "flair.Agent",
2545
2659
  id: agentId,
2546
- 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,
2547
2678
  httpErrorMessage: (status, text) => `Operations API insert failed (${status}): ${text}`,
2548
2679
  });
2549
2680
  }
@@ -3534,6 +3665,12 @@ program.configureHelp({ showGlobalOptions: true });
3534
3665
  program.hook("preAction", async (_thisCommand, actionCommand) => {
3535
3666
  if (actionCommand.name() === "doctor")
3536
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;
3537
3674
  // Interactive-only: this is a pure stderr UX nudge for a human at a
3538
3675
  // terminal ("bare-npm users must not get stuck"), not a machine-consumed
3539
3676
  // signal — it never changes exit codes or stdout. Gating on TTY means a
@@ -3571,7 +3708,6 @@ bindInitCli({
3571
3708
  api,
3572
3709
  b64url,
3573
3710
  buildOperationsApiConfig,
3574
- cleanupLegacyLaunchdPlist,
3575
3711
  defaultDataDir,
3576
3712
  defaultLaunchAgentsDir,
3577
3713
  ensureFlairAgentRole,
@@ -3589,6 +3725,7 @@ bindInitCli({
3589
3725
  pubKeyPath,
3590
3726
  readyOpsSocketPosture,
3591
3727
  reconcileFederationInstanceViaOpsApi,
3728
+ repointMainServiceUnit,
3592
3729
  resolveHttpPort,
3593
3730
  writeAdminPassFile,
3594
3731
  resolveOpsBindHost,
@@ -3600,12 +3737,13 @@ bindInitCli({
3600
3737
  runSoulWizard,
3601
3738
  seedAgentViaOpsApi,
3602
3739
  seedFederationInstanceViaOpsApi,
3740
+ readOccupiedListener,
3603
3741
  shouldShowInlineSecretWarning,
3604
3742
  verifyAuditLog,
3605
3743
  verifySemanticSearch,
3606
3744
  waitForHealth,
3607
3745
  writeDaemonSidecar,
3608
- writeInitLaunchdPlist,
3746
+ registerInitLaunchdService,
3609
3747
  MQTT_DISABLED_CONFIG,
3610
3748
  STARTUP_TIMEOUT_MS,
3611
3749
  });
@@ -3825,6 +3963,8 @@ bindStatusCli({
3825
3963
  defaultDataDir,
3826
3964
  readHarperConfig,
3827
3965
  readPortFromConfig,
3966
+ resolveHttpPort,
3967
+ assessInstallTree,
3828
3968
  __pkgVersion,
3829
3969
  });
3830
3970
  registerStatus(program);
@@ -3871,12 +4011,14 @@ function stampEngineVersionIfRunning(dataDir) {
3871
4011
  // Command registration lives in src/commands/upgrade.ts (flair#1636).
3872
4012
  // Bind shared cli-locals first so the extracted module never imports this file.
3873
4013
  bindUpgradeCli({
4014
+ assessInstallTree,
3874
4015
  decideAfterRollbackVerify,
3875
4016
  decideAfterVerify,
3876
4017
  defaultDataDir,
3877
4018
  doctorRunAfterUpgrade,
3878
4019
  flairPackageDir,
3879
4020
  fleetSweepCallerExitMessage,
4021
+ gatherDaemonEvidence,
3880
4022
  humanBytes,
3881
4023
  isCredentialOnlyFailure,
3882
4024
  observeLaunchdManagement,
@@ -3892,6 +4034,10 @@ bindUpgradeCli({
3892
4034
  resolveInstanceServingPid,
3893
4035
  resolveUpgradeRestartVerify,
3894
4036
  restartAfterUpgrade,
4037
+ runPackageInstall: (spec) => {
4038
+ execFileSync("npm", ["install", "-g", spec], { stdio: "pipe" });
4039
+ },
4040
+ applyPlainTreeUpgrade,
3895
4041
  shouldPrintUpgradeLine,
3896
4042
  shouldRunFleetVerify,
3897
4043
  startFlairProcess,
@@ -3971,7 +4117,7 @@ function readPidfile(dataDir) {
3971
4117
  return { kind: "present", pid: n };
3972
4118
  }
3973
4119
  /** Read `flair-daemon.json` (O_NOFOLLOW) into a `SidecarRead`. */
3974
- function readSidecar(dataDir) {
4120
+ export function readSidecar(dataDir) {
3975
4121
  const r = readFileNoFollow(join(dataDir, "flair-daemon.json"));
3976
4122
  if (r.kind !== "present")
3977
4123
  return r;
@@ -3981,18 +4127,17 @@ function readSidecar(dataDir) {
3981
4127
  }
3982
4128
  return { kind: "present", ...parsed };
3983
4129
  }
3984
- /** `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. */
3985
4131
  function probePidLiveness(pid) {
3986
4132
  try {
3987
4133
  process.kill(pid, 0);
3988
4134
  return { kind: "alive" };
3989
4135
  }
3990
4136
  catch (err) {
3991
- if (err?.code === "ESRCH")
3992
- return { kind: "gone" };
3993
- if (err?.code === "EPERM")
3994
- return { kind: "eperm" };
3995
- 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);
3996
4141
  }
3997
4142
  }
3998
4143
  /**
@@ -4051,7 +4196,14 @@ function canonicalizeExistingPath(p) {
4051
4196
  return resolve(p);
4052
4197
  }
4053
4198
  }
4054
- /** 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
+ */
4055
4207
  function readProcessRootPath(pid) {
4056
4208
  if (process.platform === "linux") {
4057
4209
  try {
@@ -4064,6 +4216,30 @@ function readProcessRootPath(pid) {
4064
4216
  }
4065
4217
  return { rootPath: null, environReadable: false };
4066
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
+ }
4067
4243
  /**
4068
4244
  * Was this pid inspectable as a flair worktree? `null` when cwd and
4069
4245
  * cmdline could not be read — do not treat that as "not flair".
@@ -4076,11 +4252,26 @@ function inspectServingFlairPackage(pid) {
4076
4252
  return resolveServingFlairPackage(pid) !== null;
4077
4253
  }
4078
4254
  /** Gather every piece of evidence the classifier needs, in one place. */
4079
- async function gatherDaemonEvidence(port, dataDir) {
4255
+ export async function gatherDaemonEvidence(port, dataDir) {
4080
4256
  const dataDirUnsafe = checkDataDirSafe(dataDir);
4081
4257
  const pidfile = readPidfile(dataDir);
4082
4258
  const pidLiveness = pidfile.kind === "present" ? probePidLiveness(pidfile.pid) : null;
4083
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
+ }
4084
4275
  // Probe health first so the self-heal gate below can use it without a
4085
4276
  // second round-trip. Also consumed at the end for the classifier.
4086
4277
  const health = await probeHealth(port);
@@ -4175,6 +4366,54 @@ function writeDaemonSidecar(dataDir, pid, port, startTimeMs = Date.now()) {
4175
4366
  // kernels. An explicit chmod is the only guarantee (flair#1454 decision 6).
4176
4367
  chmodSync(finalPath, 0o600);
4177
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
+ }
4178
4417
  /**
4179
4418
  * Refuse to act on a launchd service that belongs to a DIFFERENT data
4180
4419
  * directory than the one the command is operating on (flair#902).
@@ -4229,6 +4468,8 @@ export function assertLaunchdServiceOwnedBy(dataDir, label, plistPath, action) {
4229
4468
  // Command registration lives in src/commands/service.ts (flair#1636).
4230
4469
  // Bind shared cli-locals first so the extracted module never imports this file.
4231
4470
  bindServiceCli({
4471
+ afterFailedLaunchdAttempt,
4472
+ assessInstallTree,
4232
4473
  buildDirectSpawnEnv,
4233
4474
  closedDirectSpawnEnv,
4234
4475
  defaultDataDir,
@@ -4238,6 +4479,8 @@ bindServiceCli({
4238
4479
  guardEngineNotBackwards,
4239
4480
  harperBinNotFoundMessage,
4240
4481
  harperSearchRoots,
4482
+ launchdLabel,
4483
+ observeLaunchdLoadability,
4241
4484
  observeLaunchdManagement,
4242
4485
  probeHealth,
4243
4486
  readyOpsSocketPosture,
@@ -4248,6 +4491,7 @@ bindServiceCli({
4248
4491
  resolveOpsBindHost,
4249
4492
  resolveOpsPort,
4250
4493
  restartFlair,
4494
+ removeStaleSidecarIfConfirmedDead,
4251
4495
  stampEngineVersionIfRunning,
4252
4496
  waitForHealth,
4253
4497
  waitForProcessExit,
@@ -4269,6 +4513,136 @@ const realLaunchctlLister = (label) => {
4269
4513
  });
4270
4514
  return { code: res.status, stdout: res.stdout ?? "" };
4271
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
+ }
4272
4646
  /**
4273
4647
  * Which process is actually serving `dataDir` — Harper's own `hdb.pid` first,
4274
4648
  * then the listener on `port`.
@@ -4293,6 +4667,203 @@ function resolveInstanceServingPid(dataDir, port) {
4293
4667
  listeningPids,
4294
4668
  });
4295
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
+ }
4296
4867
  /** Agent signing-key ids under `keysDir` — node-scoped federation keys excluded. */
4297
4868
  function collectKeyAgentIds(keysDir) {
4298
4869
  if (!existsSync(keysDir))
@@ -4622,9 +5193,11 @@ function validateAdminPassFileForLauncher(path) {
4622
5193
  * is required on `LaunchdPlistOptions`) and makes the writer own its
4623
5194
  * precondition:
4624
5195
  *
4625
- * 1. An on-disk plist that is provably ours IN THE PASS-FILE SHAPE is left
4626
- * byte-for-byte unchanged. An adopted instance is never downgraded, and a
4627
- * 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.
4628
5201
  * 2. A plist that is provably another instance's (`foreign`) or cannot be
4629
5202
  * attributed (`unattributable`) is refused, naming `flair doctor --fix`.
4630
5203
  * 3. Otherwise, resolve the pass file BEFORE writing anything: reuse an
@@ -4671,11 +5244,55 @@ export async function writeInitLaunchdPlist(opts, deps = {}) {
4671
5244
  const passFileShape = !plistCarriesInlineAdminPassword(raw) &&
4672
5245
  basename(launcherArg) === basename(launchdLauncherPath());
4673
5246
  if (disposition === "ours" && passFileShape) {
4674
- return {
4675
- kind: "unchanged",
4676
- plistPath: opts.plistPath,
4677
- detail: `the launchd service is already adopted with the pass-file launcher; leaving ${opts.plistPath} unchanged`,
4678
- };
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
+ }
4679
5296
  }
4680
5297
  }
4681
5298
  }
@@ -4731,6 +5348,397 @@ export async function writeInitLaunchdPlist(opts, deps = {}) {
4731
5348
  writeFileAtomic(opts.plistPath, plist, 0o644);
4732
5349
  return { kind: "written", plistPath: opts.plistPath };
4733
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
+ }
4734
5742
  /**
4735
5743
  * Compute the launchd repair plan for `dataDir` (flair#1573 slice b) WITHOUT
4736
5744
  * executing it — the detect + classify + decide half. The doctor command uses
@@ -4790,43 +5798,50 @@ function planLaunchdRepairFor(dataDir, port) {
4790
5798
  * Repair launchd management for `dataDir` (flair#1573 slice b) — the
4791
5799
  * `doctor --fix` launchd repair for a MISSING, CORRUPT, or DETACHED plist.
4792
5800
  *
4793
- * detect -> (adopt: clean-stop the direct process) -> regenerate (pass-file
4794
- * mode) -> load -> verify. The DECISION (state matrix + ownership guard +
4795
- * config authority) lives in planLaunchdRepair (src/lib/launchd-repair.ts);
4796
- * this is the EXECUTION, and it is the only place that touches the real
4797
- * filesystem and launchctl.
4798
- *
4799
- * Reuses the existing primitives rather than re-inventing them:
4800
- * - observeLaunchdManagement / assessLaunchdManagement is the fail-loud
4801
- * verifier (launchctl PID AND that PID is the serving process).
4802
- * - ensureLaunchdServiceLoaded is the unload -> load -> start.
4803
- * - the five-state liveness machine (gatherDaemonEvidence +
4804
- * classifyDaemonState, flair#1454) attributes and clean-stops the direct
4805
- * process on the adopt path — never a foreign/recycled pid, never kill -9.
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.
4806
5808
  *
4807
- * The adopt path (flair#1573 slice b2) BOUNCES the live instance: it
4808
- * clean-stops the direct-spawned process (SIGTERM + wait for exit), confirms
4809
- * the port is free, then regenerates + loads. A foreign/unattributable direct
4810
- * process is refused by the liveness machine (DISAGREEMENT/UNKNOWN), never
4811
- * signalled.
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.
4812
5839
  *
4813
- * Credential before plist (flair#1685): the generated plist is always
4814
- * pass-file mode, so its launcher cannot start unless ~/.flair/admin-pass
4815
- * exists and is safe. An existing valid file is reused; an env credential is
4816
- * PROVEN against the live instance (before the adopt bounce) and only then
4817
- * written; nothing usable yields a refusal with no plist. The written file is
4818
- * validated against the launcher's own read contract (exists, mode 0600,
4819
- * non-empty) before load.
5840
+ * The preflight cannot PROVE a bootstrap will succeed — only loading something
5841
+ * proves that — which is why phase 2 restores rather than assumes.
4820
5842
  *
4821
- * Never reports success on a direct-start fallback: the final verify is
4822
- * assessLaunchdManagement (launchctl PID AND that PID is the serving process),
4823
- * and anything short of `managed` is a `failed` result with the detached detail
4824
- * + remedy, never a silent pass. On the adopt arm the verify additionally
4825
- * proves the serving pid CHANGED and the pre-adopt pid is dead, because port
4826
- * health alone is answered by the old process (flair#1684/#1685). The whole
4827
- * executor arm is wrapped in try/catch (Kern's b1 defect): a throw becomes a
4828
- * named `failed` result (or an engine-backwards `refused`), never a crash
4829
- * 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.
4830
5845
  */
4831
5846
  async function repairLaunchdManagement(dataDir, port) {
4832
5847
  const { plan, plistPath, isLegacy, config } = planLaunchdRepairFor(dataDir, port);
@@ -4837,163 +5852,456 @@ async function repairLaunchdManagement(dataDir, port) {
4837
5852
  return { kind: "refused", reason: plan.reason, detail: plan.detail, plistPath: plan.plistPath };
4838
5853
  case "adopt":
4839
5854
  case "regenerate": {
5855
+ let prepared;
4840
5856
  try {
4841
- // Guard FIRST (flair#1093): the repair is a boot path, and an older
4842
- // engine opening a newer store fails at the storage layer minutes
4843
- // later — same refusal as startFlairProcess. On the adopt arm this
4844
- // must run BEFORE the stop: it is a pure read whose inputs don't
4845
- // change during the repair, so guard-first refuses WITHOUT bouncing
4846
- // the live instance (guard-after-stop would SIGTERM the instance and
4847
- // then refuse, leaving it down with nothing to restart it).
4848
- guardEngineNotBackwards(dataDir);
4849
- // Credential before plist (flair#1685). Resolve and, when the plan says
4850
- // the pass file must be materialized (an env candidate), PROVE the
4851
- // credential against the live instance BEFORE the adopt bounce stops
4852
- // it — then write the 0600 file. Refuse, with no plist and no bounce,
4853
- // when nothing proves.
4854
- const adminPassPath = defaultAdminPassPath();
4855
- if (plan.credential.writeAdminPassFile) {
4856
- const candidate = process.env.FLAIR_ADMIN_PASS ?? process.env.HDB_ADMIN_PASSWORD;
4857
- if (!candidate) {
4858
- return {
4859
- kind: "refused",
4860
- reason: "missing-credential",
4861
- detail: `refusing to repair the launchd plist: ${adminPassPath} must be written from a credential, ` +
4862
- "but no credential is available in the environment.",
4863
- plistPath,
4864
- };
4865
- }
4866
- const proof = await proveAdminPassAgainstInstance(port, candidate);
4867
- if (proof) {
4868
- return {
4869
- kind: "refused",
4870
- reason: "missing-credential",
4871
- detail: "refusing to repair the launchd plist: the credential in FLAIR_ADMIN_PASS/HDB_ADMIN_PASSWORD " +
4872
- `does not authenticate against the running instance (${proof}), so writing it to ` +
4873
- `${adminPassPath} would create a pass file the instance rejects. Run 'flair init' to provision ` +
4874
- "the correct credential.",
4875
- plistPath,
4876
- };
4877
- }
4878
- writeAdminPassFile(adminPassPath, candidate);
4879
- }
4880
- // Validate the pass file against the launcher's OWN read contract before
4881
- // any plist names it: an existing file that drifted to 0644 must refuse
4882
- // here, never be baked into a plist the launcher will reject at start.
4883
- const passFileProblem = validateAdminPassFileForLauncher(adminPassPath);
4884
- if (passFileProblem) {
4885
- return {
4886
- kind: "refused",
4887
- reason: "missing-credential",
4888
- detail: `refusing to repair the launchd plist: ${passFileProblem}`,
4889
- plistPath,
4890
- };
4891
- }
4892
- // Adopt (flair#1573 slice b2): capture the process serving the instance
4893
- // NOW (before the stop), then clean-stop it, so the regenerate + load
4894
- // below does not collide on the port. The captured pid is the evidence
4895
- // the post-load verify uses to prove the serving pid CHANGED.
4896
- let directPid = null;
4897
- if (plan.kind === "adopt") {
4898
- directPid = resolveInstanceServingPid(dataDir, port);
4899
- const stop = await stopDirectProcessForAdopt(port, dataDir);
4900
- if (stop)
4901
- return stop; // a named failed result
4902
- }
4903
- const { execSync } = await import("node:child_process");
4904
- // Regenerate the plist (pass-file mode) and write it atomically.
4905
- // No secret is embedded, so 0644 is correct here.
4906
- const plist = buildRepairPlist(dataDir, config);
4907
- const newPlistPath = launchdPlistPath(launchdLabel(dataDir));
4908
- writeFileAtomic(newPlistPath, plist, 0o644);
4909
- // Validate the plist's absolute paths BEFORE launchd load (flair#1685
4910
- // hardening): launchctl load/start exit 0 for a job whose program is
4911
- // missing, so a stale launcher or node path produces a job that never
4912
- // starts — the same masked failure this repair exists to prevent.
4913
- const stalePlistPath = diagnoseLaunchdPlistPaths(newPlistPath);
4914
- if (stalePlistPath) {
4915
- return { kind: "failed", detail: stalePlistPath.message, remedy: stalePlistPath.remedy };
4916
- }
4917
- // flair#1586 / #1581: a SET_CONFIG-less detach (MQTT_* via
4918
- // buildDirectSpawnEnv) can persist mqtt.network as mtls, port,
4919
- // securePort when Harper stored no originals for already-null ports.
4920
- // Adopt SET_CONFIG updates those keys in place and would otherwise
4921
- // leave harper-config.yaml not byte-identical to the first-repair
4922
- // file (port, securePort, mtls). Reorder only those scalar lines
4923
- // before launchd loads so the next persist matches the settled file.
4924
- const cfgPath = harperConfigPath(dataDir);
4925
- if (cfgPath) {
4926
- const raw = readFileSync(cfgPath, "utf-8");
4927
- const { text, changed } = stabilizeMqttNetworkKeyOrder(raw);
4928
- if (changed)
4929
- writeFileAtomic(cfgPath, text, 0o644);
4930
- }
4931
- // If the resolved plist was a pre-flair#693 legacy label, unload and
4932
- // remove it so it is not orphaned beside the regenerated one.
4933
- if (isLegacy && plistPath !== newPlistPath) {
4934
- try {
4935
- execSync(`launchctl unload "${plistPath}"`, { stdio: "pipe" });
4936
- }
4937
- catch { /* best effort */ }
4938
- try {
4939
- unlinkSync(plistPath);
4940
- }
4941
- catch { /* best effort */ }
4942
- }
4943
- // Load (unload -> load -> start). Drop the pre-bounce leftover
4944
- // socket first so exists() cannot be true on the dead inode —
4945
- // Darwin #1704 (`9413a80`) chmod'd that leftover for 10s and
4946
- // still read 0755 after Harper bind()d a new file.
4947
- const bounceAt = Date.now();
4948
- unlinkStaleOpsSocket(dataDir);
4949
- ensureLaunchdServiceLoaded(dataDir, (cmd) => execSync(cmd, { stdio: "pipe" }));
4950
- // Verify (fail-loud).
4951
- const after = observeLaunchdManagement(dataDir, port);
4952
- if (after.state !== "managed") {
4953
- 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)` };
4954
5869
  }
4955
- // On the adopt arm, port health alone is the green light that lied in
4956
- // #1684: the pre-adopt direct process answered the port the whole time
4957
- // the launchd job was failing to start. Prove the launchd job itself
4958
- // serves — the old pid is dead, the serving pid changed, and it is
4959
- // launchd's reported pid for this label.
4960
- if (plan.kind === "adopt") {
4961
- const label = after.label ?? resolveLaunchdLabel(dataDir).label;
4962
- // flair#1827: poll — the launchd-started Harper may not have written
4963
- // hdb.pid or bound the port yet. Wait for it to serve (and for the
4964
- // pre-adopt process to be gone), THEN prove identity with
4965
- // verifyAdoptServing UNCHANGED on the final observation.
4966
- const waited = await verifyAdoptServingWithWait({
4967
- observe: () => ({
4968
- directPid,
4969
- managedPid: readLaunchctlJobState(label, realLaunchctlLister).pid,
4970
- servingPid: resolveInstanceServingPid(dataDir, port),
4971
- directPidAlive: directPid !== null && isProcessAlive(directPid),
4972
- }),
4973
- deadlineMs: STARTUP_TIMEOUT_MS,
4974
- });
4975
- if (waited.proof) {
4976
- return { kind: "failed", detail: waited.proof.detail, remedy: ["flair stop", "flair doctor --fix"] };
4977
- }
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);
4978
6240
  }
4979
- // flair#1701: the launchd bounce (adopt and regenerate) is a first
4980
- // start. The product launcher execs Harper and never chmods, so the
4981
- // new operations-server lands at 0777 & ~umask. Init / start /
4982
- // restart already call this after health; without it here, doctor
4983
- // flags ✗ Ops socket permissions until a second start. Wait for
4984
- // Harper's bind() (HTTP can answer first); ignore leftover mtimes
4985
- // older than bounceAt.
4986
- await readyOpsSocketPostureAfterStart(dataDir, { notBeforeMs: bounceAt });
4987
- const detail = plan.kind === "adopt"
4988
- ? `adopted the direct-spawned instance into launchd (bounced the live instance): ${after.detail}`
4989
- : after.detail;
4990
- 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`);
4991
6286
  }
4992
6287
  catch (err) {
4993
- 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
+ };
4994
6294
  }
4995
6295
  }
4996
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
+ };
4997
6305
  }
4998
6306
  /**
4999
6307
  * Clean-stop the direct (non-launchd) process serving `dataDir`+`port` for the
@@ -5169,10 +6477,21 @@ async function stopFlairProcess(port, dataDir) {
5169
6477
  await waitForProcessExit(pid, STARTUP_TIMEOUT_MS);
5170
6478
  }
5171
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);
5172
6493
  return;
5173
6494
  }
5174
- case "NOT_RUNNING":
5175
- return; // idempotent no-op
5176
6495
  case "DISAGREEMENT":
5177
6496
  case "UNKNOWN":
5178
6497
  // Deliberately outside any catch: a refusal must reach the caller, not
@@ -5240,34 +6559,65 @@ async function startFlairProcess(port, dataDir) {
5240
6559
  // for health on `port`, see the OTHER instance answer, and report
5241
6560
  // success.
5242
6561
  assertLaunchdServiceOwnedBy(dataDir, label, plistPath, "start");
5243
- try {
5244
- // flair#1022: launchd will not tell us it cannot exec the job.
5245
- // `launchctl load` and `launchctl start` BOTH exit 0 for a plist whose
5246
- // ProgramArguments[0] does not exist (measured, see the module header),
5247
- // so the only way this loop learns anything is by waiting the full
5248
- // startup budget for a port that will never open — the reported
5249
- // incident's second 60-second hang, ending in "did not respond within
5250
- // 60000ms (120 attempts)", an error about a port that says nothing
5251
- // about the cause. The paths in the plist are absolute and checkable
5252
- // with an existsSync, so check them first and turn a two-minute silence
5253
- // into an immediate, named diagnosis. Still falls back — a running
5254
- // instance beats a down one — just without the wait or the mystery.
5255
- const stalePlist = diagnoseLaunchdPlistPaths(plistPath);
5256
- if (stalePlist) {
5257
- throw new Error(`${stalePlist.message} Fix it with: ${stalePlist.remedy.join(" && ")}`);
5258
- }
5259
- const { execSync } = await import("node:child_process");
5260
- ensureLaunchdServiceLoaded(dataDir, (cmd) => execSync(cmd, { stdio: "pipe" }));
5261
- await waitForHealth(port, DEFAULT_ADMIN_USER, process.env.HDB_ADMIN_PASSWORD ?? "", STARTUP_TIMEOUT_MS);
5262
- readyOpsSocketPosture(dataDir); // flair#763: re-assert socket posture across restart/upgrade
5263
- stampEngineVersionIfRunning(dataDir); // flair#1047: stamp the store with the engine version
5264
- 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));
5265
6570
  }
5266
- catch (err) {
5267
- 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
+ }
5268
6608
  }
5269
6609
  }
5270
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) {
5271
6621
  console.log("Starting...");
5272
6622
  const harper = resolveHarperBin(harperSearchRoots());
5273
6623
  if (!harper.path) {
@@ -5311,6 +6661,7 @@ async function startFlairProcess(port, dataDir) {
5311
6661
  await waitForHealth(port, DEFAULT_ADMIN_USER, adminPass, STARTUP_TIMEOUT_MS);
5312
6662
  readyOpsSocketPosture(dataDir); // flair#763: re-assert socket posture across restart/upgrade
5313
6663
  stampEngineVersionIfRunning(dataDir); // flair#1047: stamp the store with the engine version
6664
+ return proc.pid ?? null;
5314
6665
  }
5315
6666
  /**
5316
6667
  * The ONE restart mechanism for a local Flair install. Shared by `flair
@@ -5329,8 +6680,57 @@ async function startFlairProcess(port, dataDir) {
5329
6680
  * frames down.
5330
6681
  */
5331
6682
  async function restartFlair(port, dataDir) {
5332
- await stopFlairProcess(port, dataDir);
5333
- 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
+ }
5334
6734
  // Bust the version-handshake cache so the next preAction nudge re-fetches
5335
6735
  // the LIVE version instead of the pre-restart cached one (the false
5336
6736
  // "server is running <old>" users hit for up to 60s post-upgrade+restart).
@@ -5477,6 +6877,7 @@ registerFleet(program);
5477
6877
  // Bind shared cli-locals first so the extracted module never imports this file.
5478
6878
  bindDoctorCli({
5479
6879
  api,
6880
+ assessInstallTree,
5480
6881
  checkAgentRegistered,
5481
6882
  classifyOpsSocketPosture,
5482
6883
  configPath,
@@ -5490,7 +6891,9 @@ bindDoctorCli({
5490
6891
  readPortFromConfig,
5491
6892
  relativeTime,
5492
6893
  repairLaunchdManagement,
6894
+ repointMainServiceUnit,
5493
6895
  resolveHttpPort,
6896
+ restartFlair,
5494
6897
  resolveOpsPort,
5495
6898
  verifyAuditLog,
5496
6899
  verifySemanticSearch,
@@ -5746,7 +7149,10 @@ harperConfigPath, readHarperConfig, readPortFromHarperConfig, persistDefaultInst
5746
7149
  // launchd label (flair#693)
5747
7150
  LEGACY_LAUNCHD_LABEL, launchdLabel, launchdPlistPath, cleanupLegacyLaunchdPlist, resolveLaunchdLabel, migrateLegacyLaunchdLabel, ensureLaunchdServiceLoaded,
5748
7151
  // launchd management observation (flair#1022)
5749
- 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, };
5750
7156
  // Shared with `flair status` via src/lib/ops-api-bind.ts (flair#852).
5751
7157
  export { detectOpsApiAllInterfacesBind };
5752
7158
  export { searchScoringFormula, buildSearchExplain, formatSearchExplain } from "./commands/search.js";