@tpsdev-ai/flair 0.57.0 → 0.59.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 (143) hide show
  1. package/README.md +7 -6
  2. package/SECURITY.md +4 -1
  3. package/config.yaml +3 -0
  4. package/dist/build-info.json +3 -3
  5. package/dist/cli.js +1726 -376
  6. package/dist/commands/agent.js +160 -2
  7. package/dist/commands/doctor.js +177 -27
  8. package/dist/commands/federation.js +2 -1
  9. package/dist/commands/hook.js +10 -2
  10. package/dist/commands/init.js +150 -44
  11. package/dist/commands/mcp.js +53 -22
  12. package/dist/commands/memory.js +24 -2
  13. package/dist/commands/quality.js +26 -18
  14. package/dist/commands/service.js +137 -22
  15. package/dist/commands/status.js +114 -3
  16. package/dist/commands/upgrade.js +204 -84
  17. package/dist/doctor-client.js +50 -4
  18. package/dist/federation/scheduler.js +253 -4
  19. package/dist/install/clients.js +89 -23
  20. package/dist/install/global-bin-path.js +26 -6
  21. package/dist/lib/atomic-write.js +256 -0
  22. package/dist/lib/daemon-liveness.js +103 -0
  23. package/dist/lib/doctor-run.js +72 -0
  24. package/dist/lib/embed-gpu-doctor.js +49 -26
  25. package/dist/lib/federation-memory-attributes.js +15 -0
  26. package/dist/lib/flair-agent-role.js +116 -0
  27. package/dist/lib/init-admin-pass.js +4 -2
  28. package/dist/lib/init-listener-environ.js +38 -0
  29. package/dist/lib/init-occupied-listener.js +165 -0
  30. package/dist/lib/launchd-domain-preflight.js +448 -0
  31. package/dist/lib/launchd-management.js +179 -8
  32. package/dist/lib/launchd-repair.js +95 -0
  33. package/dist/lib/mcp-enable.js +667 -72
  34. package/dist/lib/memory-attributes.js +77 -0
  35. package/dist/lib/node-alias-path.js +95 -0
  36. package/dist/lib/npm-registry.js +119 -6
  37. package/dist/lib/owned-pins.js +20 -6
  38. package/dist/lib/process-start-time.js +32 -0
  39. package/dist/lib/service-repoint-apply.js +267 -0
  40. package/dist/lib/service-repoint.js +575 -0
  41. package/dist/lib/toml-string-array.js +104 -0
  42. package/dist/lib/tree-divergence.js +716 -0
  43. package/dist/lib/upgrade-plain-tree.js +18 -8
  44. package/dist/lib/upgrade-prior-liveness.js +69 -0
  45. package/dist/lib/upgrade-rollback.js +116 -0
  46. package/dist/rem/runner.js +11 -0
  47. package/dist/resources/Agent.js +54 -21
  48. package/dist/resources/AgentSeed.js +44 -1
  49. package/dist/resources/Federation.js +84 -54
  50. package/dist/resources/Memory.js +567 -72
  51. package/dist/resources/MemoryArchive.js +9 -0
  52. package/dist/resources/MemoryBootstrap.js +125 -29
  53. package/dist/resources/MemoryFeed.js +204 -3
  54. package/dist/resources/MemoryHostSource.js +90 -0
  55. package/dist/resources/MemoryMaintenance.js +121 -32
  56. package/dist/resources/MemoryReflect.js +4 -1
  57. package/dist/resources/MemoryReindex.js +7 -4
  58. package/dist/resources/MemoryUsage.js +53 -3
  59. package/dist/resources/OrgSkillAssignment.js +209 -0
  60. package/dist/resources/Presence.js +18 -10
  61. package/dist/resources/RecordUsage.js +30 -40
  62. package/dist/resources/Relationship.js +167 -78
  63. package/dist/resources/SemanticSearch.js +19 -6
  64. package/dist/resources/Soul.js +31 -19
  65. package/dist/resources/XAA.js +47 -14
  66. package/dist/resources/agent-auth.js +16 -10
  67. package/dist/resources/agent-status-guard.js +63 -0
  68. package/dist/resources/auth-middleware.js +137 -49
  69. package/dist/resources/auto-promote-lib.js +4 -4
  70. package/dist/resources/bm25-index-service.js +246 -32
  71. package/dist/resources/bm25-status.js +132 -0
  72. package/dist/resources/ed25519-auth.js +11 -54
  73. package/dist/resources/embed-gpu.js +262 -47
  74. package/dist/resources/embeddings-boot.js +52 -17
  75. package/dist/resources/federation-classify.js +34 -0
  76. package/dist/resources/federation-crypto.js +65 -19
  77. package/dist/resources/flair-agent-role-boot.js +26 -0
  78. package/dist/resources/health.js +67 -16
  79. package/dist/resources/host-pointer/registry.js +35 -0
  80. package/dist/resources/host-pointer-adapter.js +15 -0
  81. package/dist/resources/host-source-visibility.js +167 -0
  82. package/dist/resources/host-source.js +151 -0
  83. package/dist/resources/instance-identity.js +3 -2
  84. package/dist/resources/key-lock.js +31 -0
  85. package/dist/resources/mcp-handler.js +147 -51
  86. package/dist/resources/mcp-oauth.js +3 -6
  87. package/dist/resources/mcp-tools.js +47 -25
  88. package/dist/resources/memory-consolidate-lib.js +3 -1
  89. package/dist/resources/memory-declared-attributes.js +103 -0
  90. package/dist/resources/memory-feed-lib.js +5 -1
  91. package/dist/resources/memory-host-source.js +163 -0
  92. package/dist/resources/migrations/synthetic-test-migration.js +4 -1
  93. package/dist/resources/migrations/visibility-backfill.js +4 -1
  94. package/dist/resources/multi-worker-guard.js +121 -0
  95. package/dist/resources/oauth-discovery.js +1 -0
  96. package/dist/resources/oauth-wellknown.js +8 -4
  97. package/dist/resources/originator-instance.js +235 -0
  98. package/dist/resources/promotion-stamp.js +2 -0
  99. package/dist/resources/provenance.js +111 -11
  100. package/dist/resources/record-owner-guard.js +19 -0
  101. package/dist/resources/record-type-kit.js +9 -12
  102. package/dist/resources/record-types.js +22 -6
  103. package/dist/resources/relay-ops.js +28 -3
  104. package/dist/resources/replay-store.js +336 -0
  105. package/dist/resources/request-transaction.js +78 -0
  106. package/dist/resources/search-readiness.js +19 -21
  107. package/dist/resources/semantic-retrieval-core.js +5 -1
  108. package/dist/resources/skill-manifest.js +181 -0
  109. package/dist/resources/skill-provenance.js +15 -10
  110. package/dist/resources/table-patch-policy.js +109 -0
  111. package/dist/resources/table-patches.js +17 -0
  112. package/dist/resources/table-post-policy.js +138 -0
  113. package/dist/resources/table-posts.js +22 -0
  114. package/dist/resources/table-subscription-policy.js +135 -0
  115. package/dist/resources/table-subscriptions.js +19 -0
  116. package/dist/resources/tool-descriptors/index.js +15 -15
  117. package/dist/resources/trust-block.js +10 -3
  118. package/dist/resources/usage-recording.js +169 -41
  119. package/dist/src/lib/flair-agent-role.js +116 -0
  120. package/dist/src/lib/memory-attributes.js +77 -0
  121. package/docs/access-control.md +667 -0
  122. package/docs/api-reference.md +85 -17
  123. package/docs/auth.md +4 -0
  124. package/docs/claude-code.md +132 -0
  125. package/docs/deepseek-harness.md +1 -1
  126. package/docs/deployment.md +1 -1
  127. package/docs/federation.md +1 -1
  128. package/docs/integrations.md +6 -6
  129. package/docs/mcp-clients.md +16 -24
  130. package/docs/notes/mcp-oauth-model2.md +15 -1
  131. package/docs/quickstart.md +5 -0
  132. package/docs/releasing.md +152 -20
  133. package/docs/supply-chain-policy.md +10 -5
  134. package/docs/troubleshooting.md +11 -0
  135. package/docs/upgrade.md +187 -61
  136. package/package.json +10 -5
  137. package/schemas/agent.graphql +9 -6
  138. package/schemas/federation.graphql +2 -11
  139. package/schemas/memory.graphql +137 -17
  140. package/schemas/oauth.graphql +8 -4
  141. package/schemas/replay.graphql +18 -0
  142. package/templates/launchd/start-flair-with-admin-pass.sh +95 -0
  143. 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";
38
- import { readProcessStartTimeMs } from "./lib/process-start-time.js";
45
+ import { classifyDaemonState, verifyIdentity, isHarperProcessCommandLine, sidecarStartAgrees, parseSidecarJson, classifyHealthProbe, classifyPortOwner, classifyInstanceMatch, shouldAdoptMissingSidecar, classifySidecarStaleness, shouldRemoveSidecarAfterStop, livenessFromKillError, parseNullSeparatedEnviron, extractRootPath, } from "./lib/daemon-liveness.js";
46
+ import { readProcessStartSecondMs, 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";
@@ -78,6 +89,7 @@ import { bindCli as bindDoctorCli, register as registerDoctor, } from "./command
78
89
  import { bindCli as bindQualityCli, register as registerQuality, } from "./commands/quality.js";
79
90
  import { bindCli as bindGrantCli, register as registerGrant, } from "./commands/grant.js";
80
91
  import { resolveHome } from "./lib/home.js";
92
+ import { FLAIR_AGENT_PERMISSION } from "./lib/flair-agent-role.js";
81
93
  // Federation crypto helpers + private-visibility filter live with the
82
94
  // federation command group (src/commands/federation.ts, flair#1620). Inlined
83
95
  // there for the same packaging reason: src/ must not import resources/.
@@ -303,6 +315,34 @@ function resolveLaunchdLabel(dataDir, launchAgentsDir = defaultLaunchAgentsDir()
303
315
  return { label: LEGACY_LAUNCHD_LABEL, plistPath: legacyPlistPath, isLegacy: true };
304
316
  return { label: newLabel, plistPath: newPlistPath, isLegacy: false };
305
317
  }
318
+ /**
319
+ * Test seam (flair#2040): the lint migrateLegacyLaunchdLabel runs when its
320
+ * caller injects none — which is every start path — and the lint `flair init`
321
+ * runs over the plist it writes when it retires a legacy registration
322
+ * (flair#2078). Lets a command-level test drive `flair start`, the start leg
323
+ * and init's launchd step with a lint that throws. Production leaves this
324
+ * unset.
325
+ */
326
+ let launchdMigrationLintForTests = null;
327
+ export function setLaunchdMigrationLintForTests(lint) {
328
+ launchdMigrationLintForTests = lint;
329
+ }
330
+ /**
331
+ * Run `lint` over a replacement plist before anything is unloaded (flair#2040,
332
+ * flair#2078): the problem line it reports, or null when it passed. A lint that
333
+ * THROWS instead of answering (its temporary copy could not be created, written
334
+ * or removed, say) checked nothing. That is a LaunchdValidationRefusal whose
335
+ * message is `refusal("the lint failed: <error>")`: never a pass, and never a
336
+ * plain error that escapes the caller's refusal handling.
337
+ */
338
+ function lintReplacementPlist(content, lint, refusal) {
339
+ try {
340
+ return lint(content);
341
+ }
342
+ catch (err) {
343
+ throw new LaunchdValidationRefusal(refusal(`the lint failed: ${err?.message ?? String(err)}`));
344
+ }
345
+ }
306
346
  /**
307
347
  * Migrate a pre-flair#693 legacy-labeled launchd service to the new
308
348
  * instance-scoped label for `dataDir`: unload the legacy service FIRST,
@@ -311,19 +351,32 @@ function resolveLaunchdLabel(dataDir, launchAgentsDir = defaultLaunchAgentsDir()
311
351
  * file. There is never a moment where both the legacy and new labels are
312
352
  * registered for the same data dir. No-op (migrated: false) if there's
313
353
  * nothing legacy to migrate, or the new label is already registered.
354
+ *
355
+ * flair#2040: before anything is unloaded, the legacy plist must be readable,
356
+ * and the replacement content must carry the expected Label and pass
357
+ * `opts.lint` (plutil -lint by default). Any of these failing throws a
358
+ * LaunchdValidationRefusal with nothing unloaded, written or removed — and so
359
+ * does a lint that throws instead of answering.
314
360
  */
315
- function migrateLegacyLaunchdLabel(dataDir, runLaunchctl, launchAgentsDir = defaultLaunchAgentsDir()) {
361
+ function migrateLegacyLaunchdLabel(dataDir, runLaunchctl, launchAgentsDir = defaultLaunchAgentsDir(), uid = currentUid(), opts = {}) {
316
362
  const resolved = resolveLaunchdLabel(dataDir, launchAgentsDir);
317
363
  if (!resolved.isLegacy) {
318
364
  return { migrated: false, label: resolved.label, plistPath: resolved.plistPath };
319
365
  }
320
366
  const newLabel = launchdLabel(dataDir);
321
367
  const newPlistPath = launchdPlistPath(newLabel, launchAgentsDir);
368
+ // flair#2040: read and validate the plist BEFORE unloading anything. Every
369
+ // refusal up to the legacy bootout below is a LaunchdValidationRefusal:
370
+ // nothing has been loaded or unloaded, and the callers must not boot out the
371
+ // legacy job in response to it.
372
+ let legacyContent;
322
373
  try {
323
- runLaunchctl(`launchctl unload "${resolved.plistPath}"`);
374
+ legacyContent = readFileSync(resolved.plistPath, "utf-8");
375
+ }
376
+ catch (err) {
377
+ throw new LaunchdValidationRefusal(`not migrating off the legacy launchd label: could not read the legacy plist ${resolved.plistPath} (${err?.code ?? err}). ` +
378
+ "Nothing was unloaded, and the legacy plist was left as it was.");
324
379
  }
325
- catch { /* best effort */ }
326
- const legacyContent = readFileSync(resolved.plistPath, "utf-8");
327
380
  // Use a function replacer to avoid $-sensitivity in the replacement
328
381
  // string (flair#919). String.prototype.replace interprets $&, $', $`
329
382
  // etc. in the replacement even when the search value is a plain string.
@@ -333,15 +386,48 @@ function migrateLegacyLaunchdLabel(dataDir, runLaunchctl, launchAgentsDir = defa
333
386
  // Refuse to propagate a malformed plist: if the Label wasn't found,
334
387
  // the plist is not what we expect and migration must not write it.
335
388
  if (newContent === legacyContent) {
336
- throw new Error(`Legacy plist at ${resolved.plistPath} does not contain the expected ` +
389
+ throw new LaunchdValidationRefusal(`Legacy plist at ${resolved.plistPath} does not contain the expected ` +
337
390
  `Label key — it may be malformed or from an unknown Flair version. ` +
338
391
  `Remove it manually and re-run 'flair init'.`);
339
392
  }
393
+ // flair#2040: a plist that still carries the expected Label can be malformed
394
+ // XML, which bootstrap would reject only AFTER the legacy job was unloaded.
395
+ // Lint the replacement content now, before anything is unloaded; a lint that
396
+ // could not run is a failed check, not a pass. So is a lint that THREW (its
397
+ // temporary copy could not be created, written or removed, say): every lint
398
+ // exception is a validation refusal here. A plain error would reach the start
399
+ // paths' failed-LOAD handling, which boots the legacy job out.
400
+ const lint = opts.lint ?? launchdMigrationLintForTests ?? lintLaunchdPlistContent;
401
+ const lintProblem = lintReplacementPlist(newContent, lint, (failure) => `not migrating off the legacy launchd label: the replacement plist for ${newLabel} could not be validated ` +
402
+ `(${failure}). Nothing was unloaded, and the legacy plist ${resolved.plistPath} was left as it was.`);
403
+ if (lintProblem !== null) {
404
+ throw new LaunchdValidationRefusal(`not migrating off the legacy launchd label: the replacement plist for ${newLabel} failed validation ` +
405
+ `(${lintProblem}). Nothing was unloaded, and the legacy plist ${resolved.plistPath} was left as it was.`);
406
+ }
407
+ // Targeted at the GUI domain the preflight probed (flair#2040), not the
408
+ // domain launchctl would infer for this process — and VERIFIED: migrating
409
+ // while the legacy job may still be loaded would leave launchd two jobs for
410
+ // one data directory.
411
+ const legacyGone = ensureLaunchdJobAbsent({ run: runLaunchctl, domain: launchdGuiDomain(uid), label: LEGACY_LAUNCHD_LABEL, settleMs: opts.settleMs, sleep: opts.sleep });
412
+ if (legacyGone !== null) {
413
+ throw new Error(`not migrating off the legacy launchd label: ${legacyGone}. The legacy plist ${resolved.plistPath} was left as it was.`);
414
+ }
340
415
  writeFileSync(newPlistPath, newContent);
416
+ // Two plists for one data directory would give launchd two jobs at the next
417
+ // login: a legacy plist that cannot be removed undoes the migration.
341
418
  try {
342
419
  unlinkSync(resolved.plistPath);
343
420
  }
344
- catch { /* best effort */ }
421
+ catch (err) {
422
+ if (err?.code !== "ENOENT") {
423
+ try {
424
+ unlinkSync(newPlistPath);
425
+ }
426
+ catch { /* reported below */ }
427
+ throw new Error(`not migrating off the legacy launchd label: could not remove ${resolved.plistPath} (${err?.code ?? err}); ` +
428
+ `${newPlistPath} was removed again.`);
429
+ }
430
+ }
345
431
  return { migrated: true, label: newLabel, plistPath: newPlistPath };
346
432
  }
347
433
  /**
@@ -355,35 +441,42 @@ function migrateLegacyLaunchdLabel(dataDir, runLaunchctl, launchAgentsDir = defa
355
441
  * real launchd. The caller (init) passes a real execSync wrapper; tests
356
442
  * pass a recording stub.
357
443
  */
358
- function cleanupLegacyLaunchdPlist(dataDir, plistDir, runLaunchctl) {
444
+ function cleanupLegacyLaunchdPlist(dataDir, plistDir, runLaunchctl, uid = currentUid(), opts = {}) {
359
445
  const legacyPlistPath = launchdPlistPath(LEGACY_LAUNCHD_LABEL, plistDir);
360
446
  if (!existsSync(legacyPlistPath))
361
447
  return { action: "none" };
362
448
  const legacyRootPath = readPlistRootPath(legacyPlistPath);
363
449
  const legacyOwnedByUs = legacyRootPath !== null && resolve(legacyRootPath) === resolve(dataDir);
364
450
  if (legacyOwnedByUs) {
365
- let unloadFailed;
366
451
  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}"`);
452
+ // flair#2040: targeted at the GUI domain, only when the job is loaded
453
+ // there, and VERIFIED gone afterwards (ensureLaunchdJobAbsent) — a bootout
454
+ // error is reported, never read as success. Callers that may be booting
455
+ // out the job SERVING the instance must preflight + restore
456
+ // (registerInitLaunchdService); this helper is the PROVEN-not-serving
457
+ // cleanup.
458
+ const domain = launchdGuiDomain(uid);
459
+ const gone = ensureLaunchdJobAbsent({ run: runLaunchctl, domain, label: LEGACY_LAUNCHD_LABEL, settleMs: opts.settleMs, sleep: opts.sleep });
460
+ if (gone !== null) {
461
+ // The job may still be loaded: its plist is KEPT (removing it would
462
+ // orphan a loaded job), and the caller reports the uncertainty.
463
+ console.error(`Failed to unload legacy launchd service (${LEGACY_LAUNCHD_LABEL}): ${gone}. ` +
464
+ `It may still be loaded, so its plist at ${legacyPlistPath} was left in place — unload it with: ` +
465
+ `launchctl bootout ${domain}/${LEGACY_LAUNCHD_LABEL}`);
466
+ return { action: "unload-unconfirmed", unloadFailed: gone };
376
467
  }
377
468
  try {
378
469
  unlinkSync(legacyPlistPath);
379
- console.log(`Migrated off legacy launchd label (${LEGACY_LAUNCHD_LABEL}) ✓`);
470
+ // No check mark (flair#2040): retiring the legacy plist is not launchd
471
+ // managing this instance — only the strict verifier licenses a ✓.
472
+ console.log(`Retired the legacy launchd plist (${LEGACY_LAUNCHD_LABEL}) at ${legacyPlistPath}; its job is not loaded (verified).`);
380
473
  }
381
474
  catch (err) {
382
475
  deleteFailed = err?.message ?? String(err);
383
476
  console.error(`Failed to remove legacy launchd plist at ${legacyPlistPath}: ` +
384
477
  `${deleteFailed}. Remove it manually.`);
385
478
  }
386
- return { action: "unloaded", unloadFailed, deleteFailed };
479
+ return { action: "unloaded", deleteFailed };
387
480
  }
388
481
  if (legacyRootPath !== null) {
389
482
  console.log(`Skipped legacy launchd cleanup: the plist at ${legacyPlistPath} ` +
@@ -399,28 +492,34 @@ function cleanupLegacyLaunchdPlist(dataDir, plistDir, runLaunchctl) {
399
492
  /**
400
493
  * Load + start `dataDir`'s launchd service, migrating off a pre-flair#693
401
494
  * 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.
495
+ * above). Call order is load-bearing — boot out legacy -> boot out new ->
496
+ * bootstrap new -> kickstart new, never a window with both registered — and
497
+ * pinned by test/unit/launchd-label.test.ts.
498
+ *
499
+ * Every command names the GUI domain (flair#2040): `launchctl bootout
500
+ * gui/<uid>/<label>`, `bootstrap gui/<uid> <plist>`, `kickstart
501
+ * gui/<uid>/<label>` — the domain the preflight probed — instead of the legacy
502
+ * `unload`/`load`/`start`, which act on whatever domain launchctl infers for the
503
+ * calling process. See loadLaunchdJob for the bootout-settle retry and the
504
+ * `strict` option. A `kickstart` failure propagates so callers can fall back
505
+ * to a direct (non-launchd) start or restore.
506
+ *
507
+ * Shared by the `start` command and startFlairProcess() (restart/upgrade/
508
+ * snapshot). Doctor's repair and init's legacy migration run the same
509
+ * sequence — loadLaunchdJob — in `strict` mode, after their own preflight.
409
510
  */
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}`);
511
+ function ensureLaunchdServiceLoaded(dataDir, runLaunchctl, launchAgentsDir = defaultLaunchAgentsDir(), opts = {}) {
512
+ const uid = opts.uid ?? currentUid();
513
+ const migration = migrateLegacyLaunchdLabel(dataDir, runLaunchctl, launchAgentsDir, uid, { settleMs: opts.settleMs, sleep: opts.sleep });
514
+ loadLaunchdJob({
515
+ run: runLaunchctl,
516
+ domain: launchdGuiDomain(uid),
517
+ label: migration.label,
518
+ plistPath: migration.plistPath,
519
+ strict: opts.strict,
520
+ settleMs: opts.settleMs,
521
+ sleep: opts.sleep,
522
+ });
424
523
  return migration;
425
524
  }
426
525
  function configPath() {
@@ -2476,8 +2575,12 @@ async function opsSeedInsertWithRetry(req) {
2476
2575
  }
2477
2576
  // flair#1790 review C2: 401 FIRST. An auth failure must never be masked by
2478
2577
  // a body that happens to carry a "duplicate"/"already exists" marker.
2479
- if (res.status === 401)
2480
- throw new Error(req.auth401Message(text));
2578
+ if (res.status === 401) {
2579
+ const err = new Error(req.auth401Message(text));
2580
+ if (req.auth401Friendly)
2581
+ err.flairFriendly = true;
2582
+ throw err;
2583
+ }
2481
2584
  // THEN the idempotent duplicate path: an unconditional 409, then the
2482
2585
  // marker match for the remaining non-OK shapes.
2483
2586
  const duplicate = res.status === 409 || text.includes("duplicate") || text.includes("already exists");
@@ -2504,7 +2607,19 @@ async function opsSeedInsertWithRetry(req) {
2504
2607
  }
2505
2608
  }
2506
2609
  }
2507
- export async function seedAgentViaOpsApi(opsPortOrUrl, agentId, pubKeyB64url, adminUser, adminPass) {
2610
+ export async function seedAgentViaOpsApi(opsPortOrUrl, agentId, pubKeyB64url, adminUser, adminPass,
2611
+ /**
2612
+ * Set only when `flair init` skipped starting Harper and did not already
2613
+ * stop for a foreign data directory (flair#1749). `before` is who held
2614
+ * THIS operations port immediately before the insert — not the HTTP
2615
+ * port's listener. On a 401, `reread` runs and a pid is named only
2616
+ * when both reads are the same sole PID. Several holders, or a holder
2617
+ * that changed during the request, stay unattributed. Omit this when init
2618
+ * started Harper itself — that 401 keeps the credential hint. A different
2619
+ * data directory does not prove the passwords differ, and the HTTP holder
2620
+ * is not assumed to be the process that rejected this request.
2621
+ */
2622
+ occupiedListener) {
2508
2623
  const url = typeof opsPortOrUrl === "number"
2509
2624
  ? `http://127.0.0.1:${opsPortOrUrl}/`
2510
2625
  : `${opsPortOrUrl.replace(/\/$/, "")}/`;
@@ -2543,7 +2658,24 @@ export async function seedAgentViaOpsApi(opsPortOrUrl, agentId, pubKeyB64url, ad
2543
2658
  noun: "agent",
2544
2659
  tableName: "flair.Agent",
2545
2660
  id: agentId,
2546
- auth401Message: (text) => `Operations API insert failed (401): ${text}${opsAuth401Hint(auth === undefined ? undefined : adminUser)}`,
2661
+ auth401Message: (text) => {
2662
+ if (!occupiedListener) {
2663
+ return `Operations API insert failed (401): ${text}${opsAuth401Hint(auth === undefined ? undefined : adminUser)}`;
2664
+ }
2665
+ let after;
2666
+ try {
2667
+ after = occupiedListener.reread();
2668
+ }
2669
+ catch {
2670
+ after = { port: occupiedListener.before.port, pids: [], dataDirs: [] };
2671
+ }
2672
+ return occupiedListenerAuthFailure({
2673
+ lead: "Operations API insert failed (401): ",
2674
+ bodyText: text,
2675
+ listener: stableAnsweredHolder(occupiedListener.before, after),
2676
+ });
2677
+ },
2678
+ auth401Friendly: occupiedListener !== undefined,
2547
2679
  httpErrorMessage: (status, text) => `Operations API insert failed (${status}): ${text}`,
2548
2680
  });
2549
2681
  }
@@ -2903,6 +3035,18 @@ const PAIR_INITIATOR_PERMISSION = {
2903
3035
  super_user: false,
2904
3036
  structure_user: false,
2905
3037
  };
3038
+ /**
3039
+ * The `id` that `alter_role` addresses a role by. `list_roles` answers with each
3040
+ * role's `id`, and Harper 5.2.8 rejects an `alter_role` that omits it ("Id can't
3041
+ * be blank").
3042
+ */
3043
+ function alterRoleId(roleName, existing) {
3044
+ const id = existing?.id;
3045
+ if (typeof id !== "string" || id.length === 0) {
3046
+ throw new Error(`alter_role for '${roleName}': list_roles returned no id for the role`);
3047
+ }
3048
+ return id;
3049
+ }
2906
3050
  /**
2907
3051
  * Idempotently ensures the `flair_pair_initiator` role exists on the Harper
2908
3052
  * instance at `opsUrl` with the canonical permission spec.
@@ -2947,6 +3091,7 @@ export async function ensureFlairPairInitiatorRole(opsUrl, adminUser, adminPass)
2947
3091
  console.log(`Role '${ROLE_NAME}' exists but permissions differ — updating...`);
2948
3092
  await callOpsApi(opsUrl, {
2949
3093
  operation: "alter_role",
3094
+ id: alterRoleId(ROLE_NAME, existing),
2950
3095
  role: ROLE_NAME,
2951
3096
  permission: PAIR_INITIATOR_PERMISSION,
2952
3097
  }, adminUser, adminPass);
@@ -2954,102 +3099,8 @@ export async function ensureFlairPairInitiatorRole(opsUrl, adminUser, adminPass)
2954
3099
  }
2955
3100
  // ─── flair_agent role ────────────────────────────────────────────────────────
2956
3101
  //
2957
- // The auth reshape replaces the global gate's "verified agent borrows admin
2958
- // super_user" elevation with a real, least-privilege Harper role. After an
2959
- // agent's Ed25519 signature verifies, resources resolve the request to the
2960
- // shared `flair_agent`-roled user instead of admin — so agents get exactly the
2961
- // table CRUD below and nothing more. Critically: with no `super_user` and no
2962
- // operations grants, /sql and /graphql become NATIVELY 403 for agents (the
2963
- // raw-query block the gate hand-rolled is now enforced by Harper itself).
2964
- //
2965
- // Row-level ownership (an agent touches only its OWN memories/soul/events) is
2966
- // NOT expressible in Harper's role model — it stays in each resource's allow*,
2967
- // keyed on the Ed25519-verified agentId. So these per-table grants are the
2968
- // coarse CRUD envelope; allow* is the ownership boundary inside it.
2969
- //
2970
- // VALIDATION GATES (must confirm against a live Harper before this role goes
2971
- // live — flagged for Sherlock + the PR, not assumed):
2972
- // 1. HNSW/vector search (SemanticSearch over Memory) works with table `read`
2973
- // alone — the old elevation comment claimed admin perms were needed for
2974
- // "HNSW-capable" access; confirm `read` suffices or widen precisely.
2975
- // 2. Role table keys must EXACTLY match the @table names (Memory, OrgEvent,
2976
- // WorkspaceState, OAuthClient — NOT the logical Memory/Event/Workspace/OAuth
2977
- // shorthand the flair_pair_initiator spec used, which was harmless only
2978
- // because every grant there is false).
2979
- // Harper 5.0.21 add_role requires an `attribute_permissions` array on EVERY table
2980
- // grant (empty = no attribute-level restriction, so the table-level CRUD applies);
2981
- // omitting it makes add_role reject the whole spec ("Missing 'attribute_permissions'
2982
- // array"). Validated live against a spawned Harper. This helper guarantees the
2983
- // array is never forgotten. Also: `cluster_user` is NOT a valid top-level key —
2984
- // Harper reads unrecognized top-level keys as database names ("database
2985
- // 'cluster_user' does not exist"); only super_user / structure_user are recognized.
2986
- const grant = (read, insert, update, del) => ({ read, insert, update, delete: del, attribute_permissions: [] });
2987
- /** Canonical permission spec for flair_agent (least-privilege; real @table names). */
2988
- const FLAIR_AGENT_PERMISSION = {
2989
- super_user: false,
2990
- structure_user: false,
2991
- flair: {
2992
- tables: {
2993
- // Core agent-owned data — CRUD envelope; ownership enforced in allow*.
2994
- Memory: grant(true, true, true, true),
2995
- MemoryCandidate: grant(true, true, true, true),
2996
- MemoryGrant: grant(true, true, true, true),
2997
- // Asset (images-in-Flair slice 1). Harper authorizes BEFORE Asset.post
2998
- // runs, so a de-elevated flair_agent needs the table grant or signed
2999
- // POST /Asset 403s as AccessViolation (Kern P0). CRUD envelope;
3000
- // owner-only + write-time size/MIME gates live in resources/Asset.ts.
3001
- Asset: grant(true, true, true, true),
3002
- Soul: grant(true, true, true, false),
3003
- OrgEvent: grant(true, true, true, true),
3004
- WorkspaceState: grant(true, true, true, true),
3005
- Relationship: grant(true, true, true, true),
3006
- // Flair Relay S1 (flair#1521). Harper authorizes BEFORE the resource
3007
- // methods run, so a de-elevated flair_agent needs the table grant OR it
3008
- // 403s on POST /Message before relaySend is reached (Kern P0-2). read =
3009
- // the party-scoped collection (Message.search); insert = send via post().
3010
- // update = FALSE (least privilege, Kern P0 blocker): the ack's write goes
3011
- // through the IN-PROCESS static accessor (relayConsume → deps.messages.put),
3012
- // which bypasses role gates entirely — the same raw-put seam Federation.ts
3013
- // relies on — so update:true is NOT needed for any legitimate path. Leaving
3014
- // it granted let PATCH /Message/<id> reach Table's update verb, whose
3015
- // authorize step consults update:true and PASSES for any de-elevated agent,
3016
- // bypassing Message.put()'s FORBIDDEN guard AND relayConsume's recipient-only
3017
- // check (Message has no patch() at the platform level → TableResource.patch
3018
- // runs update()+save() directly). delete = false: direct deletes are
3019
- // admin/internal only. Message.patch() also guards the verb in-resource.
3020
- Message: grant(true, true, false, false),
3021
- Integration: grant(true, true, true, true),
3022
- Credential: grant(true, true, true, true),
3023
- Presence: grant(true, true, true, false),
3024
- // MemoryUsage (flair#683): the usage-feedback dedup ledger. Read (own
3025
- // contributions, scoped in resources/MemoryUsage.ts) + insert (a fresh
3026
- // contribution row) only — NO update/delete. This is load-bearing, not
3027
- // just least-privilege tidiness: the dedup rule ("(agent, memory)
3028
- // contributes ≤ 1") is enforced by requiring a NEW ledger row before
3029
- // any usageCount bump; if an agent could delete its own row, it could
3030
- // re-trigger the /RecordUsage endpoint for the same memory indefinitely
3031
- // (create → count → delete → count again → repeat), defeating the cap
3032
- // entirely. See resources/MemoryUsage.ts's module doc.
3033
- MemoryUsage: grant(true, true, false, false),
3034
- // MemoryHitStat (flair#1528): internal search-hit ledger. No agent REST
3035
- // surface (@table without @export). Counts overlay onto Memory reads.
3036
- MemoryHitStat: grant(false, false, false, false),
3037
- // Agent: read for discovery, update own card; creation/removal is admin.
3038
- Agent: grant(true, false, true, false),
3039
- // Read-only reference data.
3040
- Instance: grant(true, false, false, false),
3041
- // Federation / OAuth / IdP / internal — system + admin only; agents get none.
3042
- Peer: grant(false, false, false, false),
3043
- PairingToken: grant(false, false, false, false),
3044
- SyncLog: grant(false, false, false, false),
3045
- OAuthClient: grant(false, false, false, false),
3046
- OAuthToken: grant(false, false, false, false),
3047
- OAuthAuthCode: grant(false, false, false, false),
3048
- IdpConfig: grant(false, false, false, false),
3049
- IdJagReplay: grant(false, false, false, false),
3050
- },
3051
- },
3052
- };
3102
+ // The grant spec (FLAIR_AGENT_PERMISSION) lives in src/lib/flair-agent-role.ts,
3103
+ // shared with the server's startup check (resources/flair-agent-role-boot.ts).
3053
3104
  /**
3054
3105
  * Idempotently ensures the `flair_agent` role exists on the Harper instance at
3055
3106
  * `opsUrl` with the canonical least-privilege spec. Same list/add/alter shape as
@@ -3091,6 +3142,7 @@ export async function ensureFlairAgentRole(opsUrl, adminUser, adminPass) {
3091
3142
  console.log(`Role '${ROLE_NAME}' exists but permissions differ — updating...`);
3092
3143
  await callOpsApi(opsUrl, {
3093
3144
  operation: "alter_role",
3145
+ id: alterRoleId(ROLE_NAME, existing),
3094
3146
  role: ROLE_NAME,
3095
3147
  permission: FLAIR_AGENT_PERMISSION,
3096
3148
  }, adminUser, adminPass);
@@ -3534,6 +3586,12 @@ program.configureHelp({ showGlobalOptions: true });
3534
3586
  program.hook("preAction", async (_thisCommand, actionCommand) => {
3535
3587
  if (actionCommand.name() === "doctor")
3536
3588
  return;
3589
+ // flair#2034 §2: `status` reports the server's version itself, next to this
3590
+ // CLI's and the install tree that serves it, and decides the advice from
3591
+ // that one comparison — a second, tree-blind "run: flair restart" line here
3592
+ // is the hint that used to contradict it.
3593
+ if (actionCommand.name() === "status" && actionCommand.parent === program)
3594
+ return;
3537
3595
  // Interactive-only: this is a pure stderr UX nudge for a human at a
3538
3596
  // terminal ("bare-npm users must not get stuck"), not a machine-consumed
3539
3597
  // signal — it never changes exit codes or stdout. Gating on TTY means a
@@ -3571,7 +3629,6 @@ bindInitCli({
3571
3629
  api,
3572
3630
  b64url,
3573
3631
  buildOperationsApiConfig,
3574
- cleanupLegacyLaunchdPlist,
3575
3632
  defaultDataDir,
3576
3633
  defaultLaunchAgentsDir,
3577
3634
  ensureFlairAgentRole,
@@ -3589,6 +3646,7 @@ bindInitCli({
3589
3646
  pubKeyPath,
3590
3647
  readyOpsSocketPosture,
3591
3648
  reconcileFederationInstanceViaOpsApi,
3649
+ repointMainServiceUnit,
3592
3650
  resolveHttpPort,
3593
3651
  writeAdminPassFile,
3594
3652
  resolveOpsBindHost,
@@ -3600,12 +3658,13 @@ bindInitCli({
3600
3658
  runSoulWizard,
3601
3659
  seedAgentViaOpsApi,
3602
3660
  seedFederationInstanceViaOpsApi,
3661
+ readOccupiedListener,
3603
3662
  shouldShowInlineSecretWarning,
3604
3663
  verifyAuditLog,
3605
3664
  verifySemanticSearch,
3606
3665
  waitForHealth,
3607
3666
  writeDaemonSidecar,
3608
- writeInitLaunchdPlist,
3667
+ registerInitLaunchdService,
3609
3668
  MQTT_DISABLED_CONFIG,
3610
3669
  STARTUP_TIMEOUT_MS,
3611
3670
  });
@@ -3825,6 +3884,8 @@ bindStatusCli({
3825
3884
  defaultDataDir,
3826
3885
  readHarperConfig,
3827
3886
  readPortFromConfig,
3887
+ resolveHttpPort,
3888
+ assessInstallTree,
3828
3889
  __pkgVersion,
3829
3890
  });
3830
3891
  registerStatus(program);
@@ -3871,12 +3932,14 @@ function stampEngineVersionIfRunning(dataDir) {
3871
3932
  // Command registration lives in src/commands/upgrade.ts (flair#1636).
3872
3933
  // Bind shared cli-locals first so the extracted module never imports this file.
3873
3934
  bindUpgradeCli({
3935
+ assessInstallTree,
3874
3936
  decideAfterRollbackVerify,
3875
3937
  decideAfterVerify,
3876
3938
  defaultDataDir,
3877
3939
  doctorRunAfterUpgrade,
3878
3940
  flairPackageDir,
3879
3941
  fleetSweepCallerExitMessage,
3942
+ gatherDaemonEvidence,
3880
3943
  humanBytes,
3881
3944
  isCredentialOnlyFailure,
3882
3945
  observeLaunchdManagement,
@@ -3892,6 +3955,10 @@ bindUpgradeCli({
3892
3955
  resolveInstanceServingPid,
3893
3956
  resolveUpgradeRestartVerify,
3894
3957
  restartAfterUpgrade,
3958
+ runPackageInstall: (spec) => {
3959
+ execFileSync("npm", ["install", "-g", spec], { stdio: "pipe" });
3960
+ },
3961
+ applyPlainTreeUpgrade,
3895
3962
  shouldPrintUpgradeLine,
3896
3963
  shouldRunFleetVerify,
3897
3964
  startFlairProcess,
@@ -3971,7 +4038,7 @@ function readPidfile(dataDir) {
3971
4038
  return { kind: "present", pid: n };
3972
4039
  }
3973
4040
  /** Read `flair-daemon.json` (O_NOFOLLOW) into a `SidecarRead`. */
3974
- function readSidecar(dataDir) {
4041
+ export function readSidecar(dataDir) {
3975
4042
  const r = readFileNoFollow(join(dataDir, "flair-daemon.json"));
3976
4043
  if (r.kind !== "present")
3977
4044
  return r;
@@ -3981,18 +4048,17 @@ function readSidecar(dataDir) {
3981
4048
  }
3982
4049
  return { kind: "present", ...parsed };
3983
4050
  }
3984
- /** `kill(pid, 0)` as a three-way: alive / gone (ESRCH) / eperm (another user's). */
4051
+ /** `kill(pid, 0)` as a four-way: alive / gone (ESRCH) / eperm (another user's) / unknown. */
3985
4052
  function probePidLiveness(pid) {
3986
4053
  try {
3987
4054
  process.kill(pid, 0);
3988
4055
  return { kind: "alive" };
3989
4056
  }
3990
4057
  catch (err) {
3991
- if (err?.code === "ESRCH")
3992
- return { kind: "gone" };
3993
- if (err?.code === "EPERM")
3994
- return { kind: "eperm" };
3995
- return { kind: "gone" };
4058
+ // `gone` ONLY for ESRCH. Any other errno (EINVAL, EACCES, ...) is `unknown`,
4059
+ // which must never be read as "gone" — that is the whole point of the
4060
+ // classifier's unknown state (flair#2055).
4061
+ return livenessFromKillError(err?.code);
3996
4062
  }
3997
4063
  }
3998
4064
  /**
@@ -4051,7 +4117,14 @@ function canonicalizeExistingPath(p) {
4051
4117
  return resolve(p);
4052
4118
  }
4053
4119
  }
4054
- /** Best-effort ROOTPATH from `/proc/<pid>/environ`. */
4120
+ /**
4121
+ * ROOTPATH for daemon sidecar recovery (flair#1454 / #1478).
4122
+ *
4123
+ * Linux reads `/proc/<pid>/environ`. Every other platform, including macOS,
4124
+ * is "could not read". Init's occupied-listener check uses
4125
+ * `readInitListenerRootPath` instead — a `ps` parse must not feed this
4126
+ * self-heal path.
4127
+ */
4055
4128
  function readProcessRootPath(pid) {
4056
4129
  if (process.platform === "linux") {
4057
4130
  try {
@@ -4064,6 +4137,30 @@ function readProcessRootPath(pid) {
4064
4137
  }
4065
4138
  return { rootPath: null, environReadable: false };
4066
4139
  }
4140
+ /**
4141
+ * Test seam for the pre-auth observation. When set, pid and ROOTPATH reads
4142
+ * replace `lsof` and `/proc` so a test can name a listener without the
4143
+ * host's tools. Production leaves this unset. Never a reason to offer
4144
+ * `flair stop`.
4145
+ */
4146
+ let occupiedListenerLookupForTests = null;
4147
+ export function setOccupiedListenerLookupForTests(lookup) {
4148
+ occupiedListenerLookupForTests = lookup;
4149
+ }
4150
+ /**
4151
+ * Who is listening on `port` (flair#1749). The pre-auth path calls this
4152
+ * once, on the HTTP port. A later operations-port 401 calls it again
4153
+ * before the insert and after the 401 — that pair is the attribution,
4154
+ * not this single read. ROOTPATH comes from init's Linux `/proc` reader,
4155
+ * not the sidecar reader. An unreadable directory is omitted. Never signals.
4156
+ */
4157
+ function readOccupiedListener(port) {
4158
+ const lookup = occupiedListenerLookupForTests ?? {
4159
+ pids: resolveListenerPids,
4160
+ rootPath: readInitListenerRootPath,
4161
+ };
4162
+ return listenerFromLookup(port, lookup);
4163
+ }
4067
4164
  /**
4068
4165
  * Was this pid inspectable as a flair worktree? `null` when cwd and
4069
4166
  * cmdline could not be read — do not treat that as "not flair".
@@ -4076,11 +4173,26 @@ function inspectServingFlairPackage(pid) {
4076
4173
  return resolveServingFlairPackage(pid) !== null;
4077
4174
  }
4078
4175
  /** Gather every piece of evidence the classifier needs, in one place. */
4079
- async function gatherDaemonEvidence(port, dataDir) {
4176
+ export async function gatherDaemonEvidence(port, dataDir) {
4080
4177
  const dataDirUnsafe = checkDataDirSafe(dataDir);
4081
4178
  const pidfile = readPidfile(dataDir);
4082
4179
  const pidLiveness = pidfile.kind === "present" ? probePidLiveness(pidfile.pid) : null;
4083
4180
  let sidecar = readSidecar(dataDir);
4181
+ // flair#2055: a sidecar that names a pid which is CONFIRMED gone is STALE, not
4182
+ // a disagreement with hdb.pid. After `flair stop` ended a directly started
4183
+ // Harper, the sidecar it wrote still names the stopped pid; a later instance
4184
+ // under a different supervisor (a systemd unit's Harper) writes its own pid
4185
+ // to hdb.pid, and the old code read the mismatch as an identity conflict and
4186
+ // refused every stop/restart. Dropping the stale sidecar here (treating it as
4187
+ // absent) lets the self-heal below adopt the identity from the LIVE process
4188
+ // on the evidence that process serves — never from the dead pid's record.
4189
+ // Liveness that cannot be determined is NOT stale: the sidecar stays and the
4190
+ // refusal stands (unknown evidence never licenses an action).
4191
+ if (sidecar.kind === "present" && dataDirUnsafe === null) {
4192
+ if (classifySidecarStaleness(sidecar, probePidLiveness(sidecar.pid)).kind === "stale") {
4193
+ sidecar = { kind: "absent" };
4194
+ }
4195
+ }
4084
4196
  // Probe health first so the self-heal gate below can use it without a
4085
4197
  // second round-trip. Also consumed at the end for the classifier.
4086
4198
  const health = await probeHealth(port);
@@ -4175,6 +4287,54 @@ function writeDaemonSidecar(dataDir, pid, port, startTimeMs = Date.now()) {
4175
4287
  // kernels. An explicit chmod is the only guarantee (flair#1454 decision 6).
4176
4288
  chmodSync(finalPath, 0o600);
4177
4289
  }
4290
+ /**
4291
+ * Remove the identity sidecar left behind by a stop (flair#2055).
4292
+ *
4293
+ * A sidecar that still names a pid which is CONFIRMED gone is a leftover, and
4294
+ * leaving it makes a later instance under a DIFFERENT supervisor refuse
4295
+ * ("its identity could not be verified"). The removal is gated twice:
4296
+ *
4297
+ * 1. the pid the sidecar names must be CONFIRMED gone (ESRCH) — `unknown` or
4298
+ * EPERM liveness removes nothing; and
4299
+ * 2. a FRESH O_NOFOLLOW read taken just before the unlink must still name
4300
+ * that pid. A sidecar another supervisor rewrote in between names a
4301
+ * different pid and is left alone; a symlinked or malformed one reads as
4302
+ * `unreadable` and is not removed either, because the re-read never
4303
+ * followed the link.
4304
+ *
4305
+ * There is no lock: the re-read narrows the window to the gap between the read
4306
+ * and the unlink, and the only loser of that race is a start that rewrote the
4307
+ * sidecar in the gap — a live daemon left with no sidecar, which a later
4308
+ * port-based stop or restart can RECOVER by self-heal once the live process
4309
+ * supplies the required pidfile and health evidence (shouldAdoptMissingSidecar
4310
+ * adopts the identity from the live process; see the recovery test). `flair
4311
+ * status` does not re-adopt. A lock would buy
4312
+ * nothing here and add a crash-recovery hazard, so the design relies on the
4313
+ * self-heal instead. A writer OUTSIDE flair could substitute a symlink after
4314
+ * the final read; that is out of scope (same as any other path flair re-reads
4315
+ * by name). Best-effort: a failure to unlink is reported, never fatal.
4316
+ */
4317
+ export function removeStaleSidecarIfConfirmedDead(dataDir) {
4318
+ const observed = readSidecar(dataDir);
4319
+ if (observed.kind !== "present")
4320
+ return;
4321
+ const observedPid = observed.pid;
4322
+ const observedPidLiveness = probePidLiveness(observedPid);
4323
+ // Re-read: only the sidecar that still names the confirmed-dead pid is ours
4324
+ // to remove (a sidecar rewritten in the gap is left alone).
4325
+ const fresh = readSidecar(dataDir);
4326
+ if (!shouldRemoveSidecarAfterStop({ observedPid, observedPidLiveness, sidecar: fresh }))
4327
+ return;
4328
+ const sidecarPath = join(dataDir, "flair-daemon.json");
4329
+ try {
4330
+ unlinkSync(sidecarPath);
4331
+ }
4332
+ catch (err) {
4333
+ if (err?.code === "ENOENT")
4334
+ return; // raced with another remover
4335
+ console.error(`could not remove the stale daemon sidecar ${sidecarPath}: ${err?.code ?? err?.message}`);
4336
+ }
4337
+ }
4178
4338
  /**
4179
4339
  * Refuse to act on a launchd service that belongs to a DIFFERENT data
4180
4340
  * directory than the one the command is operating on (flair#902).
@@ -4229,6 +4389,8 @@ export function assertLaunchdServiceOwnedBy(dataDir, label, plistPath, action) {
4229
4389
  // Command registration lives in src/commands/service.ts (flair#1636).
4230
4390
  // Bind shared cli-locals first so the extracted module never imports this file.
4231
4391
  bindServiceCli({
4392
+ afterFailedLaunchdAttempt,
4393
+ assessInstallTree,
4232
4394
  buildDirectSpawnEnv,
4233
4395
  closedDirectSpawnEnv,
4234
4396
  defaultDataDir,
@@ -4238,6 +4400,8 @@ bindServiceCli({
4238
4400
  guardEngineNotBackwards,
4239
4401
  harperBinNotFoundMessage,
4240
4402
  harperSearchRoots,
4403
+ launchdLabel,
4404
+ observeLaunchdLoadability,
4241
4405
  observeLaunchdManagement,
4242
4406
  probeHealth,
4243
4407
  readyOpsSocketPosture,
@@ -4248,6 +4412,7 @@ bindServiceCli({
4248
4412
  resolveOpsBindHost,
4249
4413
  resolveOpsPort,
4250
4414
  restartFlair,
4415
+ removeStaleSidecarIfConfirmedDead,
4251
4416
  stampEngineVersionIfRunning,
4252
4417
  waitForHealth,
4253
4418
  waitForProcessExit,
@@ -4269,6 +4434,136 @@ const realLaunchctlLister = (label) => {
4269
4434
  });
4270
4435
  return { code: res.status, stdout: res.stdout ?? "" };
4271
4436
  };
4437
+ /** The current uid. `getuid` is always present on macOS; 0 is a harmless fallback. */
4438
+ function currentUid() {
4439
+ return typeof process.getuid === "function" ? process.getuid() : 0;
4440
+ }
4441
+ /**
4442
+ * `launchctl <verb> <target>` — READ-ONLY queries only (`print`,
4443
+ * `print-disabled`), capped so an unreachable launchd cannot hang the CLI.
4444
+ * These are the preflight runners (flair#2040).
4445
+ */
4446
+ function launchctlQueryRunner(verb, target) {
4447
+ return () => {
4448
+ const res = spawnSync("launchctl", [verb, target], {
4449
+ encoding: "utf-8",
4450
+ timeout: DOMAIN_PROBE_TIMEOUT_MS,
4451
+ });
4452
+ if (res.error && res.status === null)
4453
+ throw res.error;
4454
+ return { code: res.status, stdout: res.stdout ?? "", stderr: res.stderr ?? "" };
4455
+ };
4456
+ }
4457
+ /**
4458
+ * Can this process load and start `label` in the GUI domain right now?
4459
+ * (flair#2040) — `launchctl print gui/<uid>` (is the domain reachable from this
4460
+ * session?) then `launchctl print-disabled gui/<uid>` (is the label disabled
4461
+ * there?). Both read-only.
4462
+ */
4463
+ function observeLaunchdLoadability(label) {
4464
+ const uid = currentUid();
4465
+ const domain = launchdGuiDomain(uid);
4466
+ return assessLaunchdLoadability({
4467
+ platform: process.platform,
4468
+ uid,
4469
+ label,
4470
+ printDomain: launchctlQueryRunner("print", domain),
4471
+ printDisabled: launchctlQueryRunner("print-disabled", domain),
4472
+ });
4473
+ }
4474
+ /** Ceiling on one bootstrap/bootout/kickstart. */
4475
+ const LAUNCHCTL_MUTATION_TIMEOUT_MS = 30_000;
4476
+ /** The real `launchctl …` command runner (execSync; throws on a non-zero exit). */
4477
+ const realLaunchctlCommand = (cmd) => {
4478
+ execSync(cmd, { stdio: "pipe", timeout: LAUNCHCTL_MUTATION_TIMEOUT_MS });
4479
+ };
4480
+ /**
4481
+ * Unload `labels` from the GUI domain and VERIFY each is gone (flair#2040).
4482
+ * Used before a direct-start fallback so a job whose load half-worked cannot be
4483
+ * started by KeepAlive underneath the direct process. Returns null when every
4484
+ * label is PROVEN absent; otherwise which job could not be shown gone, and why
4485
+ * — and then the caller must NOT start directly (nor say the job was unloaded).
4486
+ */
4487
+ function bootoutLaunchdJob(labels) {
4488
+ const domain = launchdGuiDomain(currentUid());
4489
+ for (const label of labels) {
4490
+ const notGone = ensureLaunchdJobAbsent({ run: realLaunchctlCommand, domain, label });
4491
+ if (notGone !== null)
4492
+ return { target: `${domain}/${label}`, detail: notGone };
4493
+ }
4494
+ return null;
4495
+ }
4496
+ /**
4497
+ * After the launchd attempt of `flair start`, or of the start leg of restart /
4498
+ * upgrade / snapshot, failed: may the caller start Flair directly? (flair#2040)
4499
+ * One decision for both start paths.
4500
+ *
4501
+ * - A VALIDATION refusal (isLaunchdValidationRefusal: the plist failed a check
4502
+ * made before any launchctl call that changes state) loaded and unloaded
4503
+ * nothing, so nothing is booted out here either — a loaded legacy job is
4504
+ * left exactly as it was, and so are both plists. The jobs are only READ:
4505
+ * a direct start is allowed only when every one of `labels` is PROVEN
4506
+ * absent. A loaded job, or one whose presence cannot be read, could be
4507
+ * started by launchd underneath the direct process, so the caller must not
4508
+ * start directly.
4509
+ * - A failed LOAD may have left a job loaded: unload `labels` and VERIFY
4510
+ * each is gone (bootoutLaunchdJob) before a direct start.
4511
+ *
4512
+ * `lines` are what the caller reports (stderr), whether or not it starts
4513
+ * directly. `directStart` false means: start nothing and fail.
4514
+ */
4515
+ function afterFailedLaunchdAttempt(actor, jobLabel, labels, err) {
4516
+ const cause = err?.message ?? String(err);
4517
+ if (isLaunchdValidationRefusal(err)) {
4518
+ const blocking = firstLaunchdJobNotProvenAbsent(realLaunchctlCommand, launchdGuiDomain(currentUid()), labels);
4519
+ if (blocking !== null) {
4520
+ return { directStart: false, lines: renderStartLaunchdValidationBlocked(actor, jobLabel, cause, blocking.target, blocking.presence) };
4521
+ }
4522
+ return { directStart: true, lines: [renderStartLaunchdValidationRefused(actor, jobLabel, cause)] };
4523
+ }
4524
+ const notGone = bootoutLaunchdJob(labels);
4525
+ if (notGone !== null) {
4526
+ return { directStart: false, lines: renderStartLaunchdUnloadUncertain(actor, notGone.target, cause, notGone.detail) };
4527
+ }
4528
+ return { directStart: true, lines: [renderStartLaunchdFailed(actor, jobLabel, cause)] };
4529
+ }
4530
+ /**
4531
+ * `plutil -lint` over plist CONTENT, before it is written anywhere launchd
4532
+ * reads (flair#2040). Returns a problem line, or null ONLY when plutil ran and
4533
+ * accepted it. A plutil that cannot be run, times out or dies on a signal is a
4534
+ * problem too: a lint that did not run is not a lint that passed. Creating,
4535
+ * writing or removing its temporary copy can THROW; migrateLegacyLaunchdLabel
4536
+ * and init's launchd step (lintReplacementPlist) turn any throw into a
4537
+ * validation refusal before they unload anything.
4538
+ */
4539
+ function lintLaunchdPlistContent(content) {
4540
+ if (process.platform !== "darwin")
4541
+ return null;
4542
+ const dir = mkdtempSync(join(tmpdir(), "flair-plist-lint-"));
4543
+ try {
4544
+ const file = join(dir, "candidate.plist");
4545
+ writeFileSync(file, content, { mode: 0o600 });
4546
+ const res = spawnSync("plutil", ["-lint", file], { encoding: "utf-8", timeout: DOMAIN_PROBE_TIMEOUT_MS });
4547
+ if (res.error || res.status === null) {
4548
+ const why = res.error ? res.error.message : `it ended on ${res.signal ?? "a signal"}`;
4549
+ return `plutil -lint could not check the plist (${why}), so its syntax is unverified`;
4550
+ }
4551
+ if (res.status === 0)
4552
+ return null;
4553
+ return `plutil -lint rejected the plist (${(res.stdout || res.stderr || "").trim().split("\n")[0].replace(file, "<plist>")})`;
4554
+ }
4555
+ finally {
4556
+ rmSync(dir, { recursive: true, force: true });
4557
+ }
4558
+ }
4559
+ /**
4560
+ * Everything `doctor --fix` / `init` must know about a plist before they stop,
4561
+ * unload or replace anything for it (flair#2040): its paths (launcher, node,
4562
+ * Harper, working directory, data directory) and, on macOS, its syntax.
4563
+ */
4564
+ function validateLaunchdPlistContent(content, lint = lintLaunchdPlistContent) {
4565
+ return checkLaunchdPlistBeforeLoad(content) ?? lint(content);
4566
+ }
4272
4567
  /**
4273
4568
  * Which process is actually serving `dataDir` — Harper's own `hdb.pid` first,
4274
4569
  * then the listener on `port`.
@@ -4287,12 +4582,232 @@ function resolveInstanceServingPid(dataDir, port) {
4287
4582
  listeningPids = listeningPidsOnPort(port, (cmd) => execSync(cmd, { encoding: "utf-8" }));
4288
4583
  }
4289
4584
  catch { /* lsof unavailable — the PID file may still answer */ }
4585
+ // flair#2056: the `hdb.pid` pid is used as PID-file evidence only when it is
4586
+ // alive, its command line passes isHarperProcessCommandLine (node or bun
4587
+ // followed by a Harper entry path; see there for what a `ps` line cannot
4588
+ // establish), and no flair#1454 sidecar disagrees. A sidecar is not
4589
+ // required: an instance started by a pre-sidecar flair, or the one the
4590
+ // launchd launcher execs, has none. A sidecar disagrees when it names a
4591
+ // different pid, or a startTimeMs more than 2000 ms from the pid's start
4592
+ // second (readProcessStartSecondMs). When the pid is not used,
4593
+ // pickInstancePid returns the first process listening on `port`, if any,
4594
+ // which can be the same pid.
4595
+ const sidecar = readSidecar(dataDir);
4596
+ const isPidFileEvidence = (pid) => {
4597
+ if (sidecar.kind === "present") {
4598
+ if (sidecar.pid !== pid)
4599
+ return false;
4600
+ const startSecondMs = readProcessStartSecondMs(pid);
4601
+ if (startSecondMs === null || !sidecarStartAgrees(startSecondMs, sidecar.startTimeMs))
4602
+ return false;
4603
+ }
4604
+ const cmdline = defaultReadProcessCmdline(pid);
4605
+ return cmdline !== null && isHarperProcessCommandLine(cmdline);
4606
+ };
4290
4607
  return pickInstancePid({
4291
4608
  pidFilePid: readHarperPid(dataDir),
4292
4609
  isAlive: isProcessAlive,
4293
4610
  listeningPids,
4611
+ isPidFileEvidence,
4612
+ });
4613
+ }
4614
+ // ─── which install tree serves this instance (flair#2034 §2) ────────────────
4615
+ //
4616
+ // The pure decision lives in src/lib/tree-divergence.ts (proof) and
4617
+ // src/lib/service-repoint.ts (re-point planning). These adapters are the only
4618
+ // places that read the real launchd / systemd / process state or write a unit.
4619
+ /** realpath, or the lexically resolved path when it cannot be resolved. */
4620
+ function canonicalOr(p) {
4621
+ try {
4622
+ return realpathSync(p);
4623
+ }
4624
+ catch {
4625
+ return resolve(p);
4626
+ }
4627
+ }
4628
+ function samePathCanonical(a, b) {
4629
+ return canonicalOr(a) === canonicalOr(b);
4630
+ }
4631
+ function realRepointDeps() {
4632
+ return {
4633
+ exists: existsSync,
4634
+ samePath: samePathCanonical,
4635
+ canonical: canonicalOr,
4636
+ treeVersion: (dir) => readFlairPackageAt(dir)?.version ?? null,
4637
+ };
4638
+ }
4639
+ /**
4640
+ * `systemctl show` for a unit — of this user's manager (`--user`) or the
4641
+ * system's: MainPID, the file it loaded (FragmentPath), every drop-in it
4642
+ * applies (DropInPaths) and its WorkingDirectory. null when it could not be
4643
+ * read. Read-only and bounded; never throws.
4644
+ */
4645
+ function systemctlShow(unitName, manager) {
4646
+ const res = spawnSync("systemctl", [
4647
+ ...(manager === "user" ? ["--user"] : []),
4648
+ "show", "-p", "MainPID", "-p", "FragmentPath", "-p", "DropInPaths", "-p", "WorkingDirectory", "--", unitName,
4649
+ ], { encoding: "utf-8", timeout: LAUNCHCTL_QUERY_TIMEOUT_MS });
4650
+ return res.status === 0 ? String(res.stdout ?? "") : null;
4651
+ }
4652
+ function systemdUserUnitState(unitName) {
4653
+ const out = systemctlShow(unitName, "user");
4654
+ return out === null ? null : systemdUnitStateFromShow(out);
4655
+ }
4656
+ /** The MainPID a manager reports for a unit (0: no main process), or null when it could not be asked. */
4657
+ function systemdUnitMainPid(unitName, manager) {
4658
+ const out = systemctlShow(unitName, manager);
4659
+ return out === null ? null : mainPidFromShow(out);
4660
+ }
4661
+ /** /proc/<pid>/cgroup, read directly. */
4662
+ function readProcCgroup(pid) {
4663
+ return readFileSync(`/proc/${pid}/cgroup`, "utf-8");
4664
+ }
4665
+ /**
4666
+ * What this host knows about which process serves `dataDir` on `port`: the
4667
+ * data dir's PID file (only when that process is alive) and the distinct PIDs
4668
+ * listening on the port (null when they could not be read).
4669
+ */
4670
+ function localPidEvidence(dataDir, port) {
4671
+ let listeners;
4672
+ try {
4673
+ const out = execSync(`lsof -ti :${port} -sTCP:LISTEN`, { encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"] });
4674
+ listeners = [...new Set(parseListeningPids(out, process.pid))];
4675
+ }
4676
+ catch (err) {
4677
+ // lsof exits 1 with no output when nothing listens; anything else is "could not read".
4678
+ listeners = err?.status === 1 && String(err?.stdout ?? "").trim() === "" ? [] : null;
4679
+ }
4680
+ const pidFilePid = readHarperPid(dataDir);
4681
+ return { pidFile: pidFilePid !== null && isProcessAlive(pidFilePid) ? pidFilePid : null, listeners };
4682
+ }
4683
+ /** This CLI's own install tree (realpath) and version. */
4684
+ function cliInstallTree() {
4685
+ const loc = findFlairPackageDir(flairPackageDir());
4686
+ return { dir: loc?.dir ?? canonicalOr(flairPackageDir()), version: __pkgVersion || loc?.version || null };
4687
+ }
4688
+ /** Which install tree serves `dataDir`'s instance — proven from the service manager, or unknown. */
4689
+ function resolveServingTree(dataDir, port, query) {
4690
+ const { label, plistPath } = resolveLaunchdLabel(dataDir);
4691
+ return proveServingTree({
4692
+ platform: process.platform,
4693
+ local: query.local,
4694
+ queryUrl: query.queryUrl ?? `http://127.0.0.1:${port}`,
4695
+ dataDir,
4696
+ respondingPid: query.respondingPid ?? null,
4697
+ localPids: () => localPidEvidence(dataDir, port),
4698
+ launchd: { label, plistPath },
4699
+ launchdJobPid: (l) => readLaunchctlJobState(l, realLaunchctlLister).pid,
4700
+ // Linux: the unit is found from the serving process's cgroup, then checked
4701
+ // against what systemd reports for it (MainPID, FragmentPath, drop-ins).
4702
+ ...linuxUnitProbe({
4703
+ readFile: (p) => readFileSync(p, "utf-8"),
4704
+ systemctlShow,
4705
+ uid: typeof process.getuid === "function" ? process.getuid() : -1,
4706
+ userUnitDir: userSystemdDir(),
4707
+ }),
4708
+ servingPackage: (pid) => resolveServingFlairPackage(pid),
4709
+ exists: existsSync,
4710
+ read: (p) => readFileSync(p, "utf-8"),
4711
+ samePath: samePathCanonical,
4712
+ });
4713
+ }
4714
+ /** This CLI's tree vs the tree proven to serve `dataDir`'s instance. */
4715
+ function assessInstallTree(dataDir, port, query) {
4716
+ return assessTreeDivergence({
4717
+ cli: cliInstallTree(),
4718
+ serving: resolveServingTree(dataDir, port, query),
4719
+ runningVersion: query.runningVersion ?? null,
4720
+ currentNodeBin: process.execPath,
4721
+ samePath: samePathCanonical,
4294
4722
  });
4295
4723
  }
4724
+ /**
4725
+ * Re-point an adopted pass-file plist's runtime paths (see planPlistRuntimeRepoint):
4726
+ * planned from `planned` (a regular-file snapshot), written only over those
4727
+ * same bytes (see applyRepointPlan).
4728
+ */
4729
+ function repointAdoptedPlistFile(planned, targets, owner, opts = {}) {
4730
+ const plan = planPlistRuntimeRepoint(planned.content, targets, realRepointDeps(), planned.path, owner);
4731
+ return applyRepointPlan(plan, planned, { dryRun: opts.dryRun, atomic: opts.atomic });
4732
+ }
4733
+ /**
4734
+ * Re-point THIS instance's own service unit at this CLI's install tree —
4735
+ * `flair init` (Linux) and `flair doctor --fix`. macOS: the data dir's own
4736
+ * pass-file plist (see PlistOwnership for what makes it this instance's).
4737
+ * Linux: the systemd USER unit proven to own the answering process — the file
4738
+ * systemd loaded for it, with no drop-ins. Only runtime paths change; see
4739
+ * src/lib/service-repoint.ts for the shapes and src/lib/service-repoint-apply.ts
4740
+ * for the write.
4741
+ */
4742
+ function repointMainServiceUnit(dataDir, port, opts = {}) {
4743
+ const dryRun = opts.dryRun === true;
4744
+ const cli = cliInstallTree();
4745
+ const harper = harperBin();
4746
+ if (!harper)
4747
+ return { kind: "refused", detail: harperBinNotFoundMessage(harperSearchRoots()) };
4748
+ const targets = {
4749
+ launcher: launchdLauncherPath(cli.dir),
4750
+ nodeBin: preferVersionManagerAlias(process.execPath),
4751
+ harperBin: harper,
4752
+ workingDirectory: cli.dir,
4753
+ cliVersion: cli.version,
4754
+ };
4755
+ if (process.platform === "darwin") {
4756
+ const { label, plistPath } = resolveLaunchdLabel(dataDir);
4757
+ if (!existsSync(plistPath)) {
4758
+ return { kind: "not-applicable", detail: `no launchd service is registered for this data directory (${plistPath})` };
4759
+ }
4760
+ let planned;
4761
+ try {
4762
+ planned = snapshotRegularFile(plistPath);
4763
+ }
4764
+ catch (err) {
4765
+ return {
4766
+ kind: "refused",
4767
+ unitPath: plistPath,
4768
+ detail: `${plistPath} is not re-pointed: ${err?.message ?? err}; flair rewrites only a regular plist file in place. ` +
4769
+ `To move it, set its launcher, node, Harper entry and WorkingDirectory to this CLI's tree (${cli.dir}) by ` +
4770
+ "hand in the file it points to, then run: flair restart",
4771
+ };
4772
+ }
4773
+ const raw = planned.content;
4774
+ const disposition = classifyPlist(plistPath, dataDir, {
4775
+ exists: existsSync,
4776
+ read: () => raw,
4777
+ readRootPath: () => readPlistRootPath(plistPath),
4778
+ });
4779
+ if (disposition !== "ours") {
4780
+ return {
4781
+ kind: "refused",
4782
+ unitPath: plistPath,
4783
+ detail: `${plistPath} cannot be attributed to this data directory (${disposition}); run flair doctor --fix to repair launchd management first.`,
4784
+ };
4785
+ }
4786
+ if (plistCarriesInlineAdminPassword(raw)) {
4787
+ return {
4788
+ kind: "refused",
4789
+ unitPath: plistPath,
4790
+ detail: `${plistPath} still embeds the admin password inline; run flair doctor --fix first (it regenerates the plist in pass-file mode).`,
4791
+ };
4792
+ }
4793
+ return repointAdoptedPlistFile(planned, targets, { label, dataDir, home: resolveHome(), adminPassFile: defaultAdminPassPath() }, { dryRun });
4794
+ }
4795
+ if (process.platform === "linux") {
4796
+ const serving = resolveServingTree(dataDir, port, { local: true });
4797
+ if (serving.kind !== "proven") {
4798
+ return { kind: "not-applicable", detail: `no service unit is proven to serve this instance: ${serving.reason}` };
4799
+ }
4800
+ return repointSystemdUserUnit(serving, targets, {
4801
+ repoint: realRepointDeps(),
4802
+ exists: existsSync,
4803
+ unitState: systemdUserUnitState,
4804
+ reload: () => {
4805
+ execFileSync("systemctl", ["--user", "daemon-reload"], { stdio: "pipe", timeout: 30_000 });
4806
+ },
4807
+ }, { dryRun });
4808
+ }
4809
+ return { kind: "not-applicable", detail: `${process.platform} has no service manager flair re-points` };
4810
+ }
4296
4811
  /** Agent signing-key ids under `keysDir` — node-scoped federation keys excluded. */
4297
4812
  function collectKeyAgentIds(keysDir) {
4298
4813
  if (!existsSync(keysDir))
@@ -4622,9 +5137,11 @@ function validateAdminPassFileForLauncher(path) {
4622
5137
  * is required on `LaunchdPlistOptions`) and makes the writer own its
4623
5138
  * precondition:
4624
5139
  *
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.
5140
+ * 1. An on-disk plist that is provably ours IN THE PASS-FILE SHAPE is never
5141
+ * regenerated. An adopted instance is never downgraded, and a re-run of
5142
+ * init does not churn mtime / flap launchd state. Its runtime paths alone
5143
+ * are re-pointed when it serves another npm-global tree (flair#2034,
5144
+ * src/lib/service-repoint.ts); otherwise it is left byte-for-byte unchanged.
4628
5145
  * 2. A plist that is provably another instance's (`foreign`) or cannot be
4629
5146
  * attributed (`unattributable`) is refused, naming `flair doctor --fix`.
4630
5147
  * 3. Otherwise, resolve the pass file BEFORE writing anything: reuse an
@@ -4671,11 +5188,55 @@ export async function writeInitLaunchdPlist(opts, deps = {}) {
4671
5188
  const passFileShape = !plistCarriesInlineAdminPassword(raw) &&
4672
5189
  basename(launcherArg) === basename(launchdLauncherPath());
4673
5190
  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
- };
5191
+ // flair#2034 §2: never regenerated or downgraded (#1693), but its
5192
+ // RUNTIME paths — launcher, node, Harper entry, working directory —
5193
+ // are re-pointed at this CLI's tree when it serves another
5194
+ // npm-global tree AND it is provably this instance's plist in the
5195
+ // shape flair writes (service-repoint.ts). Every other byte stays. No
5196
+ // credential is needed: the pass-file path it names is left as it is.
5197
+ // The plan is made from a regular-file snapshot and written only over
5198
+ // those same bytes.
5199
+ let planned;
5200
+ try {
5201
+ planned = snapshotRegularFile(opts.plistPath, { lstat: deps.atomic?.lstat, readBytes: deps.atomic?.readBytes });
5202
+ }
5203
+ catch (err) {
5204
+ return {
5205
+ kind: "not-repointed",
5206
+ plistPath: opts.plistPath,
5207
+ detail: `${opts.plistPath} is not re-pointed: ${err?.message ?? err}; flair rewrites only a regular plist file in ` +
5208
+ "place. To move it, set its launcher, node, Harper entry and WorkingDirectory to this CLI's tree " +
5209
+ `(${opts.workingDirectory}) by hand in the file it points to, then run: flair restart`,
5210
+ };
5211
+ }
5212
+ if (planned.content !== raw) {
5213
+ return {
5214
+ kind: "not-repointed",
5215
+ plistPath: opts.plistPath,
5216
+ detail: `${opts.plistPath} changed while flair init was reading it; nothing was written. Re-run flair init.`,
5217
+ };
5218
+ }
5219
+ const r = repointAdoptedPlistFile(planned, {
5220
+ launcher: launchdLauncherPath(opts.workingDirectory),
5221
+ nodeBin: opts.execPath,
5222
+ harperBin: opts.harperBinPath,
5223
+ workingDirectory: opts.workingDirectory,
5224
+ cliVersion: readFlairPackageAt(opts.workingDirectory)?.version ?? null,
5225
+ }, { label: opts.label, dataDir: opts.dataDir, home: resolveHome(), adminPassFile: adminPassPath }, { atomic: deps.atomic });
5226
+ switch (r.kind) {
5227
+ case "repointed":
5228
+ return { kind: "repointed", plistPath: opts.plistPath, detail: r.detail };
5229
+ case "refused":
5230
+ return { kind: "not-repointed", plistPath: opts.plistPath, detail: r.detail };
5231
+ default:
5232
+ return {
5233
+ kind: "unchanged",
5234
+ plistPath: opts.plistPath,
5235
+ detail: `the launchd service is already adopted with the pass-file launcher; leaving ${opts.plistPath} unchanged` +
5236
+ (r.kind === "pinned-node" ? ` (${r.detail})` : ""),
5237
+ ...(r.kind === "pinned-node" ? { pinnedNode: r.detail } : {}),
5238
+ };
5239
+ }
4679
5240
  }
4680
5241
  }
4681
5242
  }
@@ -4731,6 +5292,397 @@ export async function writeInitLaunchdPlist(opts, deps = {}) {
4731
5292
  writeFileAtomic(opts.plistPath, plist, 0o644);
4732
5293
  return { kind: "written", plistPath: opts.plistPath };
4733
5294
  }
5295
+ /**
5296
+ * Put the plist `flair init` wrote back as `prior` recorded it (flair#2040,
5297
+ * flair#2078): its prior bytes, or removed when there was none. Never throws:
5298
+ * `ok` false means the put-back FAILED, and `text` says so with the error.
5299
+ */
5300
+ function putInitPlistBack(path, prior) {
5301
+ try {
5302
+ restoreFile(path, prior);
5303
+ }
5304
+ catch (e) {
5305
+ return { ok: false, text: `putting ${path} back FAILED (${e?.message ?? e})` };
5306
+ }
5307
+ return {
5308
+ ok: true,
5309
+ text: prior.kind === "absent" ? `the new plist ${path} was removed again` : `the plist at ${path} was put back as it was`,
5310
+ };
5311
+ }
5312
+ /**
5313
+ * `flair init`'s launchd step (flair#2040): write this instance's plist, retire
5314
+ * a pre-flair#693 legacy registration, and report ONLY what was verified.
5315
+ *
5316
+ * init starts Flair DIRECTLY and, since 9e3bd9ad, deliberately does not bounce
5317
+ * a running instance into launchd — so the ordinary outcome is "plist on disk,
5318
+ * running directly", and that is what it says. A check mark is printed only
5319
+ * when launchd is verified to run this instance (assessLaunchdManagement:
5320
+ * launchd's pid is the serving pid).
5321
+ *
5322
+ * The one path that stops something is retiring a LEGACY job that is the
5323
+ * process serving this instance: booting it out stops Flair. That path follows
5324
+ * the same rule as `doctor --fix`: preflight first (domain reachable, job
5325
+ * enabled), write + validate the replacement plist while the instance is still
5326
+ * up, and only then boot the legacy job out, load the replacement with
5327
+ * targeted commands and verify it; any failure after the boot-out restores the
5328
+ * legacy plist and job (or, failing that, starts Flair directly) and says so.
5329
+ * If the preflight fails, NOTHING is unloaded, removed or written; if the
5330
+ * validation fails — a lint that throws included (flair#2078) — nothing is
5331
+ * unloaded or removed, and the plist init wrote is put back as it was.
5332
+ */
5333
+ async function registerInitLaunchdService(input) {
5334
+ const { dataDir, port, plistDir, write } = input;
5335
+ const uid = currentUid();
5336
+ const domain = launchdGuiDomain(uid);
5337
+ const lines = [];
5338
+ const out = (text) => lines.push({ stream: "out", text });
5339
+ const err = (text) => lines.push({ stream: "err", text });
5340
+ const legacyPath = launchdPlistPath(LEGACY_LAUNCHD_LABEL, plistDir);
5341
+ const legacyRoot = existsSync(legacyPath) ? readPlistRootPath(legacyPath) : null;
5342
+ const legacyOwned = legacyRoot !== null && resolve(legacyRoot) === resolve(dataDir);
5343
+ if (!legacyOwned) {
5344
+ // A foreign or unattributable legacy plist is left alone (flair#966); the
5345
+ // helper prints why. With no legacy plist it is a no-op.
5346
+ if (existsSync(legacyPath))
5347
+ cleanupLegacyLaunchdPlist(dataDir, plistDir, realLaunchctlCommand, uid);
5348
+ const outcome = await writeInitLaunchdPlist(write);
5349
+ if (outcome.kind === "refused")
5350
+ return { kind: "refused", lines: [{ stream: "err", text: `Error: ${outcome.detail}` }] };
5351
+ return reportInitLaunchd(dataDir, port, write, outcome, lines);
5352
+ }
5353
+ const keptLegacy = `Nothing was unloaded or removed: the legacy job ${LEGACY_LAUNCHD_LABEL} and its plist at ${legacyPath} were left as they were`;
5354
+ // An owned legacy registration. Retiring it may stop the instance (when its
5355
+ // job is what serves), so the preflight gates EVERYTHING below.
5356
+ const loadability = observeLaunchdLoadability(write.label);
5357
+ if (!loadabilityAllowsAttempt(loadability)) {
5358
+ const problem = loadability;
5359
+ err(`⚠️ Launchd: not re-registered — ${describeLoadabilityProblem(problem)}. ${keptLegacy}, and no new ` +
5360
+ "plist was written (two plists for one data directory would give launchd two jobs for it).");
5361
+ err(` Fix: ${loadabilityRemedy(problem, uid, "flair init")}.`);
5362
+ return { kind: "skipped", lines };
5363
+ }
5364
+ // flair#2040: what is the legacy job doing? Only PROVEN answers license a
5365
+ // boot-out. The role is:
5366
+ // absent - launchctl says the job is not loaded: nothing to boot out;
5367
+ // idle - launchd lists the job with no process, or runs a process that
5368
+ // is identified as NOT the one serving this instance;
5369
+ // serving - launchd's pid IS the identified serving pid;
5370
+ // unknown - anything else (the job's state cannot be read, launchd's pid is
5371
+ // not visible from here, or the serving process cannot be
5372
+ // identified). Unknown is treated as possibly serving — and since
5373
+ // neither a boot-out nor a verified replacement is possible on
5374
+ // unknown evidence, init refuses.
5375
+ const presence = launchdJobPresence(realLaunchctlCommand, domain, LEGACY_LAUNCHD_LABEL);
5376
+ const servingPid = resolveInstanceServingPid(dataDir, port);
5377
+ const legacyJob = presence === "loaded"
5378
+ ? readLaunchctlJobState(LEGACY_LAUNCHD_LABEL, realLaunchctlLister)
5379
+ : { registered: false, pid: null, lastExitStatus: null };
5380
+ const role = presence === "absent" ? "absent"
5381
+ : presence === "unknown" ? "unknown"
5382
+ : legacyJob.registered && legacyJob.pid === null ? "idle"
5383
+ : legacyJob.pid !== null && servingPid !== null
5384
+ ? (legacyJob.pid === servingPid ? "serving" : "idle")
5385
+ : "unknown";
5386
+ if (role === "unknown") {
5387
+ const why = presence === "unknown"
5388
+ ? `'launchctl print ${domain}/${LEGACY_LAUNCHD_LABEL}' could not say whether it is loaded`
5389
+ : !legacyJob.registered
5390
+ ? `it is loaded in ${domain}, but launchd's process for it is not visible from this session`
5391
+ : `launchd runs it as process ${legacyJob.pid}, but the process serving this instance could not be identified ` +
5392
+ `(no live hdb.pid, and no listener found on port ${port})`;
5393
+ err(`⚠️ Launchd: not re-registered — the legacy job ${LEGACY_LAUNCHD_LABEL} may be the process serving this instance: ` +
5394
+ `${why}. ${keptLegacy}, and no new plist was written.`);
5395
+ err(" Fix: restart Flair so it rewrites its hdb.pid ('flair restart'), or make lsof available, then re-run 'flair init'.");
5396
+ return { kind: "skipped", lines };
5397
+ }
5398
+ if (role === "serving") {
5399
+ // Replacing a serving job is a boot path: the replacement runs THIS
5400
+ // package's Harper, which may be older than the store (flair#1093). Refuse
5401
+ // here, before anything is unloaded or written.
5402
+ try {
5403
+ guardEngineNotBackwards(dataDir);
5404
+ }
5405
+ catch (e) {
5406
+ if (!e?.engineBackwards)
5407
+ throw e;
5408
+ err(`⚠️ Launchd: not re-registered — ${e.message} ${keptLegacy}.`);
5409
+ return { kind: "skipped", lines };
5410
+ }
5411
+ }
5412
+ // The prior bytes a failed hand-off would put back. A plist that exists but
5413
+ // cannot be read cannot be put back: refuse before anything is written.
5414
+ const priorNew = snapshotFile(write.plistPath);
5415
+ const priorLegacy = snapshotFile(legacyPath);
5416
+ const unreadable = unreadableSnapshot([[write.plistPath, priorNew], [legacyPath, priorLegacy]]);
5417
+ if (unreadable) {
5418
+ err(`⚠️ Launchd: not re-registered — ${unreadable} exists but could not be read, so it could not be put back. ${keptLegacy}.`);
5419
+ return { kind: "skipped", lines };
5420
+ }
5421
+ // The replacement is written and validated while the instance is still up
5422
+ // (the writer proves the credential against it).
5423
+ const outcome = await writeInitLaunchdPlist(write);
5424
+ if (outcome.kind === "refused") {
5425
+ return {
5426
+ kind: "refused",
5427
+ lines: [
5428
+ { stream: "err", text: `Error: ${outcome.detail}` },
5429
+ { stream: "err", text: `${keptLegacy}.` },
5430
+ ],
5431
+ };
5432
+ }
5433
+ // Every failed validation is a refusal made before anything is unloaded: a
5434
+ // problem the checks REPORT, and — as in the start paths' migration — a lint
5435
+ // that THROWS (lintReplacementPlist) or a written plist that cannot be read
5436
+ // back (flair#2078). Each puts the plist just written back as it was, or
5437
+ // removes it when there was none: left beside the legacy plist, it would give
5438
+ // launchd two jobs for one data directory at the next login.
5439
+ const installing = `the plist init would install for ${write.label}`;
5440
+ let refusal = null;
5441
+ try {
5442
+ const problem = validateLaunchdPlistContent(readFileSync(write.plistPath, "utf-8"), (content) => lintReplacementPlist(content, launchdMigrationLintForTests ?? lintLaunchdPlistContent, (failure) => `${installing} could not be validated (${failure})`));
5443
+ if (problem !== null) {
5444
+ refusal = { why: `${installing} cannot be loaded (${problem})`, fix: "npm install -g @tpsdev-ai/flair && flair init" };
5445
+ }
5446
+ }
5447
+ catch (e) {
5448
+ refusal = isLaunchdValidationRefusal(e)
5449
+ ? { why: e.message, fix: `make sure the temporary directory (${tmpdir()}) exists and is writable, and re-run 'flair init'.` }
5450
+ : { why: `${installing} could not be validated (${e?.message ?? String(e)})`, fix: "resolve the error above, and re-run 'flair init'." };
5451
+ }
5452
+ if (refusal !== null) {
5453
+ const putBack = putInitPlistBack(write.plistPath, priorNew);
5454
+ err(`⚠️ Launchd: not re-registered — ${refusal.why}. Nothing was unloaded: the legacy job ${LEGACY_LAUNCHD_LABEL} ` +
5455
+ `and its plist at ${legacyPath} were left as they were, and ${putBack.text}.`);
5456
+ if (!putBack.ok) {
5457
+ err(` Fix: remove ${write.plistPath} (beside the legacy plist, launchd would load two jobs for this data ` +
5458
+ `directory at the next login); then ${refusal.fix}`);
5459
+ return { kind: "uncertain", lines };
5460
+ }
5461
+ err(` Fix: ${refusal.fix}`);
5462
+ return { kind: "skipped", lines };
5463
+ }
5464
+ if (role !== "serving") {
5465
+ // PROVEN not serving (absent, or idle): retiring it stops nothing.
5466
+ const cleanup = cleanupLegacyLaunchdPlist(dataDir, plistDir, realLaunchctlCommand, uid);
5467
+ if (cleanup.action === "unload-unconfirmed") {
5468
+ // flair#2040: the legacy job could not be shown unloaded, and the helper
5469
+ // KEPT its plist. The replacement written above must not stay beside it
5470
+ // (two plists for one data directory would give launchd two jobs), so it
5471
+ // is put back as it was, and nothing is reported as registered.
5472
+ const putBack = putInitPlistBack(write.plistPath, priorNew);
5473
+ err(`⚠️ Launchd: not re-registered — the legacy job ${LEGACY_LAUNCHD_LABEL} could not be shown unloaded ` +
5474
+ `(${cleanup.unloadFailed}), so it may still be loaded. Its plist at ${legacyPath} was left in place, and ${putBack.text}.`);
5475
+ err(` Fix: launchctl bootout ${domain}/${LEGACY_LAUNCHD_LABEL}, then re-run 'flair init'.`);
5476
+ return { kind: "uncertain", lines };
5477
+ }
5478
+ return reportInitLaunchd(dataDir, port, write, outcome, lines);
5479
+ }
5480
+ // flair#2034: what the writer did to the new plist, where no write happened
5481
+ // (a plist that may not be re-pointed; a deliberate node pin). Both stay true
5482
+ // whatever the hand-off below does, so they are said up front, with no check
5483
+ // mark. A re-point is said only once the job it was loaded into is verified:
5484
+ // any failure below puts the pre-re-point bytes back.
5485
+ if (outcome.kind === "not-repointed")
5486
+ err(`Launchd service left unchanged — ${outcome.detail}`);
5487
+ if (outcome.kind === "unchanged" && outcome.pinnedNode)
5488
+ out(`Launchd plist left as it is — ${outcome.pinnedNode}`);
5489
+ // The legacy job IS the serving instance: replace it and verify, or restore.
5490
+ const legacyPid = legacyJob.pid;
5491
+ try {
5492
+ const gone = ensureLaunchdJobAbsent({ run: realLaunchctlCommand, domain, label: LEGACY_LAUNCHD_LABEL });
5493
+ if (gone !== null)
5494
+ throw new Error(`could not unload the legacy job: ${gone}`);
5495
+ await waitForProcessExit(legacyPid, STARTUP_TIMEOUT_MS);
5496
+ unlinkSync(legacyPath);
5497
+ const bounceAt = Date.now();
5498
+ unlinkStaleOpsSocket(dataDir);
5499
+ loadLaunchdJob({ run: realLaunchctlCommand, domain, label: write.label, plistPath: write.plistPath, strict: true });
5500
+ await waitForHealth(port, write.adminUser, write.adminPass, STARTUP_TIMEOUT_MS);
5501
+ // STRICT: launchd's pid must be the IDENTIFIED serving pid (flair#2040).
5502
+ const after = observeLaunchdManagement(dataDir, port);
5503
+ const verdict = verifyLaunchdManagement(after);
5504
+ if (!verdict.verified)
5505
+ throw new Error(after.detail);
5506
+ await readyOpsSocketPostureAfterStart(dataDir, { notBeforeMs: bounceAt });
5507
+ out(`Migrated launchd service off the legacy label (${LEGACY_LAUNCHD_LABEL}) → ${write.label}; ${verdict.detail} ✓`);
5508
+ if (outcome.kind === "repointed") {
5509
+ out(` Its plist was re-pointed at this CLI's install tree before it was loaded (${outcome.detail}).`);
5510
+ }
5511
+ return { kind: "managed", lines };
5512
+ }
5513
+ catch (e) {
5514
+ const cause = e?.message ?? String(e);
5515
+ if (isProcessAlive(legacyPid) && existsSync(legacyPath) && (await probeHealth(port)).kind === "ok") {
5516
+ // Nothing was stopped: the legacy job's process still serves.
5517
+ restoreFile(write.plistPath, priorNew);
5518
+ err(`⚠️ Launchd: not re-registered — ${cause}. The legacy job's process is still serving; its plist was left as it was.`);
5519
+ return { kind: "skipped", lines };
5520
+ }
5521
+ return restoreLegacyAfterFailedMigration({ dataDir, port, write, domain, legacyPath, priorNew, priorLegacy, cause, lines });
5522
+ }
5523
+ }
5524
+ /**
5525
+ * The status lines for the plist writer's outcome: managed only when VERIFIED
5526
+ * (flair#2040). The writer's own result (flair#2034) is reported with it: a
5527
+ * plist that may not be re-pointed names why (no write happened; never a check
5528
+ * mark), a re-point names what changed and the restart that makes it take
5529
+ * effect, and a deliberate node pin names the hand edit that moves it.
5530
+ */
5531
+ function reportInitLaunchd(dataDir, port, write, outcome, lines) {
5532
+ if (outcome.kind === "not-repointed") {
5533
+ lines.push({ stream: "err", text: `Launchd service left unchanged — ${outcome.detail}` });
5534
+ }
5535
+ const unchanged = outcome.kind === "unchanged" || outcome.kind === "not-repointed";
5536
+ const followUps = () => {
5537
+ if (outcome.kind === "repointed") {
5538
+ // The running process keeps its old tree until launchd starts it again.
5539
+ lines.push({ stream: "out", text: " It takes effect when launchd next starts the service: flair restart" });
5540
+ }
5541
+ else if (outcome.kind === "unchanged" && outcome.pinnedNode) {
5542
+ // A deliberate node pin is never changed by init; say so, with the hand edit.
5543
+ lines.push({ stream: "out", text: ` ${outcome.pinnedNode}` });
5544
+ }
5545
+ };
5546
+ const managed = observeLaunchdManagement(dataDir, port);
5547
+ const verdict = verifyLaunchdManagement(managed);
5548
+ if (verdict.verified) {
5549
+ lines.push({
5550
+ stream: "out",
5551
+ text: outcome.kind === "repointed"
5552
+ ? `Launchd service re-pointed at this CLI's install tree — ${outcome.detail}; ${verdict.detail} ✓`
5553
+ : unchanged
5554
+ ? `Launchd service already managed — plist unchanged; ${verdict.detail} ✓`
5555
+ : `Launchd service registered; ${verdict.detail} ✓`,
5556
+ });
5557
+ followUps();
5558
+ return { kind: "managed", lines };
5559
+ }
5560
+ const plistLine = outcome.kind === "repointed"
5561
+ ? `Launchd plist re-pointed at this CLI's install tree (${outcome.detail})`
5562
+ : `Launchd plist ${unchanged ? "unchanged" : "written"} (${write.plistPath})`;
5563
+ if (managed.state === "unverified") {
5564
+ // launchd runs the job, but nothing identifies the serving process: no
5565
+ // claim either way (flair#2040).
5566
+ lines.push({ stream: "out", text: `${plistLine} — launchd management is NOT verified: ${managed.detail}.` });
5567
+ lines.push({ stream: "out", text: " Fix: restart Flair so it rewrites its hdb.pid ('flair restart'), or make lsof available, then run 'flair doctor'." });
5568
+ followUps();
5569
+ return { kind: "unverified", lines };
5570
+ }
5571
+ // No pid in this line: init names only a process it started (flair#1749) —
5572
+ // the serving process may be one it merely found answering the port.
5573
+ const loadability = observeLaunchdLoadability(write.label);
5574
+ const fromHere = loadabilityAllowsAttempt(loadability)
5575
+ ? ""
5576
+ : ` From this session it could not be handed over anyway: ${describeLoadabilityProblem(loadability)}.`;
5577
+ lines.push({
5578
+ stream: "out",
5579
+ text: `${plistLine} — Flair is running directly, NOT launchd-managed: init starts Flair directly and does not hand a ` +
5580
+ `running instance to launchd.${fromHere}`,
5581
+ });
5582
+ lines.push({
5583
+ stream: "out",
5584
+ text: " To hand it to launchd, run 'flair doctor --fix' from a console (GUI) login session. " +
5585
+ `${RUN_AT_LOAD_NOTE[0].toUpperCase()}${RUN_AT_LOAD_NOTE.slice(1)}; ${DIRECT_PROCESS_GUARD_NOTE}.`,
5586
+ });
5587
+ followUps();
5588
+ return { kind: "direct", lines };
5589
+ }
5590
+ /**
5591
+ * Bring back the legacy service after replacing it failed (flair#2040): unload
5592
+ * the new job and VERIFY it is gone, put both plists back, bootstrap the
5593
+ * legacy job and verify it serves — or, if that fails and the legacy job is
5594
+ * verified gone, start Flair directly. Each step is an attempt whose outcome is
5595
+ * reported; when a job cannot be shown unloaded, nothing further is started
5596
+ * (two processes on one data directory is not a restore).
5597
+ */
5598
+ async function restoreLegacyAfterFailedMigration(r) {
5599
+ const { dataDir, port, write, domain, lines } = r;
5600
+ const headline = `⚠️ Launchd: moving the service to ${write.label} failed after the legacy job was unloaded (${r.cause}).`;
5601
+ const newPid = readLaunchctlJobState(write.label, realLaunchctlLister).pid;
5602
+ const servingNow = resolveInstanceServingPid(dataDir, port);
5603
+ const newGone = ensureLaunchdJobAbsent({ run: realLaunchctlCommand, domain, label: write.label });
5604
+ if (newGone !== null) {
5605
+ lines.push({ stream: "err", text: headline });
5606
+ lines.push({
5607
+ stream: "err",
5608
+ text: ` The new job could not be shown unloaded (${newGone}), so the legacy job was NOT reloaded and Flair was ` +
5609
+ "NOT started directly — either could run a second instance on this data directory. Flair may be down, or run by the new job.",
5610
+ });
5611
+ lines.push({ stream: "err", text: ` Fix: launchctl bootout ${domain}/${write.label}, then 'flair init' from a console (GUI) login session.` });
5612
+ return { kind: "uncertain", lines };
5613
+ }
5614
+ for (const pid of new Set([newPid, servingNow])) {
5615
+ if (pid !== null) {
5616
+ try {
5617
+ await waitForProcessExit(pid, STARTUP_TIMEOUT_MS);
5618
+ }
5619
+ catch { /* the health checks below report it */ }
5620
+ }
5621
+ }
5622
+ try {
5623
+ restoreFile(write.plistPath, r.priorNew);
5624
+ restoreFile(r.legacyPath, r.priorLegacy);
5625
+ }
5626
+ catch (e) {
5627
+ lines.push({ stream: "err", text: ` putting the plists back FAILED: ${e?.message ?? e}` });
5628
+ }
5629
+ try {
5630
+ loadLaunchdJob({ run: realLaunchctlCommand, domain, label: LEGACY_LAUNCHD_LABEL, plistPath: r.legacyPath, strict: true });
5631
+ await waitForHealth(port, write.adminUser, write.adminPass, STARTUP_TIMEOUT_MS);
5632
+ const legacy = assessLaunchdManagement({
5633
+ platform: process.platform,
5634
+ label: LEGACY_LAUNCHD_LABEL,
5635
+ plistPath: r.legacyPath,
5636
+ instancePid: resolveInstanceServingPid(dataDir, port),
5637
+ plistExists: existsSync,
5638
+ list: realLaunchctlLister,
5639
+ });
5640
+ const verdict = verifyLaunchdManagement(legacy);
5641
+ lines.push({ stream: "err", text: headline });
5642
+ lines.push({
5643
+ stream: "err",
5644
+ text: verdict.verified
5645
+ ? ` Restored: the legacy job ${LEGACY_LAUNCHD_LABEL} is loaded again and serving (${verdict.detail}); both plists are as they were.`
5646
+ : ` Partly restored: Flair answers on port ${port} again after reloading the legacy job, but launchd serving it is NOT verified (${legacy.detail}).`,
5647
+ });
5648
+ lines.push({ stream: "err", text: " Fix: re-run 'flair init' (or 'flair doctor --fix') from a console (GUI) login session." });
5649
+ return { kind: "restored", lines };
5650
+ }
5651
+ catch (legacyErr) {
5652
+ const legacyGone = ensureLaunchdJobAbsent({ run: realLaunchctlCommand, domain, label: LEGACY_LAUNCHD_LABEL });
5653
+ if (legacyGone !== null) {
5654
+ lines.push({ stream: "err", text: headline });
5655
+ lines.push({
5656
+ stream: "err",
5657
+ text: ` Reloading the legacy job failed (${legacyErr?.message ?? legacyErr}), and it could not be shown unloaded ` +
5658
+ `(${legacyGone}), so Flair was NOT started directly. Flair may be down, or run by the legacy job.`,
5659
+ });
5660
+ lines.push({ stream: "err", text: ` Fix: launchctl bootout ${domain}/${LEGACY_LAUNCHD_LABEL}, then 'flair start'.` });
5661
+ return { kind: "uncertain", lines };
5662
+ }
5663
+ try {
5664
+ const pid = await startFlairDirect(port, dataDir);
5665
+ lines.push({ stream: "err", text: headline });
5666
+ lines.push({
5667
+ stream: "err",
5668
+ text: ` Reloading the legacy job failed too (${legacyErr?.message ?? legacyErr}); Flair was restarted directly` +
5669
+ `${pid ? ` (pid ${pid})` : ""} and is serving on port ${port} — running directly, NOT launchd-managed. Both plists are as they were.`,
5670
+ });
5671
+ lines.push({ stream: "err", text: " Fix: run 'flair doctor --fix' from a console (GUI) login session." });
5672
+ return { kind: "restored", lines };
5673
+ }
5674
+ catch (directErr) {
5675
+ lines.push({ stream: "err", text: headline });
5676
+ lines.push({
5677
+ stream: "err",
5678
+ text: ` Reloading the legacy job failed (${legacyErr?.message ?? legacyErr}) and starting Flair directly failed ` +
5679
+ `(${directErr?.message ?? directErr}): Flair is DOWN.`,
5680
+ });
5681
+ lines.push({ stream: "err", text: " Fix: flair start" });
5682
+ return { kind: "down", lines };
5683
+ }
5684
+ }
5685
+ }
4734
5686
  /**
4735
5687
  * Compute the launchd repair plan for `dataDir` (flair#1573 slice b) WITHOUT
4736
5688
  * executing it — the detect + classify + decide half. The doctor command uses
@@ -4790,43 +5742,50 @@ function planLaunchdRepairFor(dataDir, port) {
4790
5742
  * Repair launchd management for `dataDir` (flair#1573 slice b) — the
4791
5743
  * `doctor --fix` launchd repair for a MISSING, CORRUPT, or DETACHED plist.
4792
5744
  *
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.
5745
+ * TWO PHASES (flair#2040). The rule for this handoff: the running instance
5746
+ * is not stopped, and no launchd job is unloaded, until every check that can
5747
+ * be made about the replacement from THIS session has passed; an UNKNOWN
5748
+ * answer is a failed check, never a pass. Every failure after that point is
5749
+ * followed by an attempt to bring back what was running, and the result
5750
+ * reports the state the instance was left in — including when that state
5751
+ * could not be established.
4806
5752
  *
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.
5753
+ * 1. PREPARE (prepareLaunchdRepair) — reads and validation; the running
5754
+ * instance and launchd are untouched:
5755
+ * - the launchd preflight: is the GUI domain reachable from this
5756
+ * session, and is the job enabled there (read-only `launchctl print`
5757
+ * / `print-disabled`, domainPreflightRefusal — `unknown` refuses);
5758
+ * - the engine guard (flair#1093);
5759
+ * - the prior plist/config bytes (an existing file that cannot be read
5760
+ * refuses — it could not be put back) and which jobs are loaded
5761
+ * (an unanswerable `launchctl print` refuses);
5762
+ * - adopt: the direct process is attributed by the liveness machine
5763
+ * (DISAGREEMENT/UNKNOWN refuses); regenerate: the port must be
5764
+ * provably free (nothing identified as serving is not proof that
5765
+ * nothing serves);
5766
+ * - the credential (flair#1685 — proven against the live instance; the
5767
+ * one write this phase can make is that 0600 admin-pass file, and it
5768
+ * stays if a later check refuses);
5769
+ * - the NEW plist is built in memory and validated: every path it names
5770
+ * exists, the launcher and node are executable, the working and data
5771
+ * directories exist, and `plutil -lint` ran and accepted it.
5772
+ * 2. COMMIT (commitLaunchdRepair) — boot out any loaded job for this
5773
+ * instance and VERIFY it is gone (so KeepAlive cannot race what follows;
5774
+ * if it cannot be shown gone, stop here, before the direct process is
5775
+ * touched), clean-stop the direct process (adopt), write the plist, load
5776
+ * it with commands that NAME the probed domain (bootstrap/kickstart
5777
+ * gui/<uid>), wait (bounded) while launchd reports a pid for the job and
5778
+ * its port does not answer, and verify STRICTLY: Flair's /Health answers
5779
+ * ok and launchd's pid is the IDENTIFIED serving pid
5780
+ * (judgeLaunchdJobServing), and on adopt the serving pid
5781
+ * changed and the old one is dead (flair#1684/#1685). ANY failure here
5782
+ * goes through restoreAfterFailedRepair.
4812
5783
  *
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.
5784
+ * The preflight cannot PROVE a bootstrap will succeed — only loading something
5785
+ * proves that — which is why phase 2 restores rather than assumes.
4820
5786
  *
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.
5787
+ * Never reports success on a direct start or an unattributed process. Every
5788
+ * throw becomes a named result, never a crash mid-report.
4830
5789
  */
4831
5790
  async function repairLaunchdManagement(dataDir, port) {
4832
5791
  const { plan, plistPath, isLegacy, config } = planLaunchdRepairFor(dataDir, port);
@@ -4837,163 +5796,456 @@ async function repairLaunchdManagement(dataDir, port) {
4837
5796
  return { kind: "refused", reason: plan.reason, detail: plan.detail, plistPath: plan.plistPath };
4838
5797
  case "adopt":
4839
5798
  case "regenerate": {
5799
+ let prepared;
4840
5800
  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 };
5801
+ const outcome = await prepareLaunchdRepair(dataDir, port, plan, plistPath, isLegacy, config);
5802
+ if ("kind" in outcome)
5803
+ return outcome;
5804
+ prepared = outcome;
5805
+ }
5806
+ catch (err) {
5807
+ // Phase 1 stops and unloads nothing and writes no plist, so a throw
5808
+ // here is reported as such (it may already have written the admin-pass
5809
+ // file — see prepareLaunchdRepair).
5810
+ const mapped = mapRepairThrow(err);
5811
+ if (mapped.kind === "failed") {
5812
+ return { ...mapped, detail: `${mapped.detail} (nothing was stopped or unloaded, and no plist was written)` };
4954
5813
  }
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
- }
5814
+ return mapped;
5815
+ }
5816
+ return commitLaunchdRepair(prepared);
5817
+ }
5818
+ }
5819
+ }
5820
+ function snapshotFile(path) {
5821
+ try {
5822
+ const bytes = readFileSync(path);
5823
+ return { kind: "present", bytes, mode: statSync(path).mode & 0o777 };
5824
+ }
5825
+ catch (err) {
5826
+ if (err?.code === "ENOENT")
5827
+ return { kind: "absent" };
5828
+ return { kind: "unreadable", error: `${err?.code ?? "error"}: ${err?.message ?? err}` };
5829
+ }
5830
+ }
5831
+ /** The first snapshot that could not be taken, as "<path> (<error>)", or null. */
5832
+ function unreadableSnapshot(entries) {
5833
+ for (const [path, snap] of entries) {
5834
+ if (snap && snap.kind === "unreadable")
5835
+ return `${path} (${snap.error})`;
5836
+ }
5837
+ return null;
5838
+ }
5839
+ /**
5840
+ * Put a file back as `snapshot` recorded it: rewritten byte-for-byte (the raw
5841
+ * buffer) when it was present, removed ONLY when it was proven absent. An
5842
+ * unreadable snapshot is never "restored" — that would delete or clobber a
5843
+ * file whose bytes were never known.
5844
+ */
5845
+ function restoreFile(path, snapshot) {
5846
+ if (snapshot.kind === "unreadable") {
5847
+ throw new Error(`not restoring ${path}: its prior contents could not be read (${snapshot.error})`);
5848
+ }
5849
+ if (snapshot.kind === "absent") {
5850
+ try {
5851
+ unlinkSync(path);
5852
+ }
5853
+ catch (err) {
5854
+ if (err?.code !== "ENOENT")
5855
+ throw err;
5856
+ }
5857
+ return;
5858
+ }
5859
+ writeFileAtomic(path, snapshot.bytes, snapshot.mode);
5860
+ }
5861
+ /**
5862
+ * Phase 1 of the repair: every check that can be made without stopping the
5863
+ * running instance or changing launchd. Returns a refusal/failure or the
5864
+ * prepared repair. Every UNKNOWN answer here refuses (flair#2040): a check
5865
+ * that could not be made is not a check that passed.
5866
+ *
5867
+ * The only write this phase can make is the admin-pass file, and only when the
5868
+ * plan must materialize it from an environment credential that authenticated
5869
+ * against the running instance; that 0600 file stays if a later check refuses.
5870
+ * It is written after every check that does not need it.
5871
+ */
5872
+ async function prepareLaunchdRepair(dataDir, port, plan, resolvedPlistPath, isLegacy, config) {
5873
+ const uid = currentUid();
5874
+ const domain = launchdGuiDomain(uid);
5875
+ const label = launchdLabel(dataDir);
5876
+ const plistPath = launchdPlistPath(label);
5877
+ const untouched = "Nothing was stopped, unloaded or rewritten.";
5878
+ // flair#2040: the launchd preflight comes FIRST. From an ssh session the GUI
5879
+ // domain is not reachable, and the load would fail only AFTER the live
5880
+ // instance was clean-stopped — leaving Flair down. unavailable / unknown /
5881
+ // disabled all REFUSE here: doctor reports an issue, never "fixed".
5882
+ const refusal = domainPreflightRefusal(observeLaunchdLoadability(label), uid);
5883
+ if (refusal)
5884
+ return { ...refusal, plistPath: resolvedPlistPath };
5885
+ // Guard (flair#1093): the repair is a boot path, and an older engine opening
5886
+ // a newer store fails at the storage layer minutes later — same refusal as
5887
+ // startFlairProcess. A pure read, so it refuses WITHOUT bouncing anything.
5888
+ guardEngineNotBackwards(dataDir);
5889
+ // The prior state the restore would need. A file that exists but cannot be
5890
+ // read cannot be put back: refuse now, before anything is stopped.
5891
+ const legacyPlistPath = isLegacy && resolvedPlistPath !== plistPath ? resolvedPlistPath : null;
5892
+ const cfgPath = harperConfigPath(dataDir);
5893
+ const priorPlist = snapshotFile(plistPath);
5894
+ const priorLegacy = legacyPlistPath ? snapshotFile(legacyPlistPath) : null;
5895
+ const priorConfig = cfgPath ? { path: cfgPath, snapshot: snapshotFile(cfgPath) } : null;
5896
+ const unreadable = unreadableSnapshot([
5897
+ [plistPath, priorPlist],
5898
+ [legacyPlistPath ?? "", priorLegacy],
5899
+ [cfgPath ?? "", priorConfig?.snapshot ?? null],
5900
+ ]);
5901
+ if (unreadable) {
5902
+ return {
5903
+ kind: "refused",
5904
+ reason: "unreadable-prior-state",
5905
+ detail: `refusing to repair launchd management: ${unreadable} exists but could not be read, so a failed hand-off ` +
5906
+ `could not put it back. ${untouched}`,
5907
+ plistPath: resolvedPlistPath,
5908
+ };
5909
+ }
5910
+ // Which jobs are loaded — asked, not assumed. "unknown" refuses: the commit
5911
+ // must boot out any loaded job BEFORE the stop, and cannot plan that blind.
5912
+ const jobPresence = launchdJobPresence(realLaunchctlCommand, domain, label);
5913
+ const legacyPresence = legacyPlistPath ? launchdJobPresence(realLaunchctlCommand, domain, LEGACY_LAUNCHD_LABEL) : "absent";
5914
+ if (jobPresence === "unknown" || legacyPresence === "unknown") {
5915
+ const which = jobPresence === "unknown" ? label : LEGACY_LAUNCHD_LABEL;
5916
+ return {
5917
+ kind: "refused",
5918
+ reason: "unverifiable",
5919
+ detail: `refusing to repair launchd management: 'launchctl print ${domain}/${which}' could not say whether the job is ` +
5920
+ `loaded. ${untouched}`,
5921
+ plistPath: resolvedPlistPath,
5922
+ };
5923
+ }
5924
+ let servingPid = null;
5925
+ if (plan.kind === "adopt") {
5926
+ // Adopt: attribute the direct process NOW. A foreign or unattributable
5927
+ // process refuses here, before any job is unloaded (flair#1454 machine).
5928
+ servingPid = resolveInstanceServingPid(dataDir, port);
5929
+ const state = classifyDaemonState(await gatherDaemonEvidence(port, dataDir), { port, dataDir });
5930
+ if (state.state === "DISAGREEMENT" || state.state === "UNKNOWN") {
5931
+ return {
5932
+ kind: "failed",
5933
+ detail: `refusing to adopt: ${state.detail} ${untouched}`,
5934
+ remedy: ["flair stop", "flair doctor --fix"],
5935
+ };
5936
+ }
5937
+ }
5938
+ else {
5939
+ // Regenerate: the planner saw no serving process — but "none identified"
5940
+ // is not "none". Require positive evidence that nothing serves the port
5941
+ // (ECONNREFUSED) before loading a job that would bind it.
5942
+ const health = await probeHealth(port);
5943
+ if (health.kind !== "refused") {
5944
+ return {
5945
+ kind: "refused",
5946
+ reason: "unverifiable",
5947
+ detail: `refusing to repair launchd management: no process was identified as serving this instance, but port ${port} ` +
5948
+ `is not free (health probe: ${health.kind}), so something this repair cannot attribute may be serving it. ${untouched}`,
5949
+ plistPath: resolvedPlistPath,
5950
+ };
5951
+ }
5952
+ }
5953
+ // Credential before plist (flair#1685). When the plan says the pass file must
5954
+ // be materialized (an env candidate), PROVE the credential against the live
5955
+ // instance BEFORE anything is stopped — then write the 0600 file. Refuse,
5956
+ // with no plist and no bounce, when nothing proves.
5957
+ const adminPassPath = defaultAdminPassPath();
5958
+ if (plan.credential.writeAdminPassFile) {
5959
+ const candidate = process.env.FLAIR_ADMIN_PASS ?? process.env.HDB_ADMIN_PASSWORD;
5960
+ if (!candidate) {
5961
+ return {
5962
+ kind: "refused",
5963
+ reason: "missing-credential",
5964
+ detail: `refusing to repair the launchd plist: ${adminPassPath} must be written from a credential, ` +
5965
+ "but no credential is available in the environment.",
5966
+ plistPath: resolvedPlistPath,
5967
+ };
5968
+ }
5969
+ const proof = await proveAdminPassAgainstInstance(port, candidate);
5970
+ if (proof) {
5971
+ return {
5972
+ kind: "refused",
5973
+ reason: "missing-credential",
5974
+ detail: "refusing to repair the launchd plist: the credential in FLAIR_ADMIN_PASS/HDB_ADMIN_PASSWORD " +
5975
+ `does not authenticate against the running instance (${proof}), so writing it to ` +
5976
+ `${adminPassPath} would create a pass file the instance rejects. Run 'flair init' to provision ` +
5977
+ "the correct credential.",
5978
+ plistPath: resolvedPlistPath,
5979
+ };
5980
+ }
5981
+ writeAdminPassFile(adminPassPath, candidate);
5982
+ }
5983
+ // Validate the pass file against the launcher's OWN read contract before any
5984
+ // plist names it: an existing file that drifted to 0644 must refuse here,
5985
+ // never be baked into a plist the launcher will reject at start.
5986
+ const passFileProblem = validateAdminPassFileForLauncher(adminPassPath);
5987
+ if (passFileProblem) {
5988
+ return {
5989
+ kind: "refused",
5990
+ reason: "missing-credential",
5991
+ detail: `refusing to repair the launchd plist: ${passFileProblem}`,
5992
+ plistPath: resolvedPlistPath,
5993
+ };
5994
+ }
5995
+ // Build the replacement in memory and validate it BEFORE anything is stopped
5996
+ // (flair#2040, flair#1685 hardening): launchctl exits 0 for a job whose
5997
+ // program is missing, so a stale launcher or node path would produce a job
5998
+ // that never starts — after the live instance was already down. A lint that
5999
+ // could not run fails here too.
6000
+ const plistContent = buildRepairPlist(dataDir, config);
6001
+ const contentProblem = validateLaunchdPlistContent(plistContent);
6002
+ if (contentProblem) {
6003
+ return {
6004
+ kind: "failed",
6005
+ detail: `refusing to repair launchd management: the plist this repair would install for ${label} cannot be ` +
6006
+ `loaded — ${contentProblem}. Nothing was stopped or unloaded, and no plist was written.`,
6007
+ remedy: ["npm install -g @tpsdev-ai/flair", "flair doctor --fix"],
6008
+ };
6009
+ }
6010
+ return {
6011
+ dataDir,
6012
+ port,
6013
+ arm: plan.kind,
6014
+ uid,
6015
+ domain,
6016
+ label,
6017
+ plistPath,
6018
+ plistContent,
6019
+ legacyPlistPath,
6020
+ prior: {
6021
+ plist: priorPlist,
6022
+ legacyPlist: priorLegacy,
6023
+ config: priorConfig,
6024
+ jobLoaded: jobPresence === "loaded",
6025
+ legacyJobLoaded: legacyPresence === "loaded",
6026
+ servingPid,
6027
+ },
6028
+ };
6029
+ }
6030
+ /** Phase 2: the bounce, with restore on any failure. */
6031
+ async function commitLaunchdRepair(p) {
6032
+ const done = { unloadedPrior: false, stopped: false, wrotePlist: false, removedLegacy: false, wroteConfig: false, loaded: false };
6033
+ try {
6034
+ // 1. Unload whatever launchd holds for this instance FIRST, so KeepAlive
6035
+ // cannot start the job while the direct process is stopping or while the
6036
+ // new plist is loading, and VERIFY it is gone (flair#2040). Such a job is
6037
+ // not serving this instance (the planner only reaches adopt/regenerate
6038
+ // when launchd is not managing it). If it cannot be shown gone, stop here
6039
+ // — before the direct process is touched.
6040
+ for (const [loaded, label] of [[p.prior.jobLoaded, p.label], [p.prior.legacyJobLoaded, LEGACY_LAUNCHD_LABEL]]) {
6041
+ if (!loaded)
6042
+ continue;
6043
+ const gone = ensureLaunchdJobAbsent({ run: realLaunchctlCommand, domain: p.domain, label });
6044
+ if (gone !== null)
6045
+ throw new Error(`could not unload the loaded job before stopping anything: ${gone}`);
6046
+ }
6047
+ done.unloadedPrior = p.prior.jobLoaded || p.prior.legacyJobLoaded;
6048
+ // 2. Adopt (flair#1573 slice b2): clean-stop the direct process so the new
6049
+ // job does not collide on the port. The captured pid is the evidence the
6050
+ // verify uses to prove the serving pid CHANGED.
6051
+ if (p.arm === "adopt") {
6052
+ done.stopped = true;
6053
+ const stop = await stopDirectProcessForAdopt(p.port, p.dataDir);
6054
+ if (stop)
6055
+ throw new Error(stop.kind === "failed" || stop.kind === "refused" ? stop.detail : "the direct process could not be stopped");
6056
+ }
6057
+ // 3. Write the validated plist (pass-file mode, no secret: 0644).
6058
+ done.wrotePlist = true;
6059
+ writeFileAtomic(p.plistPath, p.plistContent, 0o644);
6060
+ // flair#1586 / #1581: a SET_CONFIG-less detach (MQTT_* via
6061
+ // buildDirectSpawnEnv) can persist mqtt.network as mtls, port,
6062
+ // securePort when Harper stored no originals for already-null ports.
6063
+ // Adopt SET_CONFIG updates those keys in place and would otherwise
6064
+ // leave harper-config.yaml not byte-identical to the first-repair
6065
+ // file (port, securePort, mtls). Reorder only those scalar lines
6066
+ // before launchd loads so the next persist matches the settled file.
6067
+ if (p.prior.config && p.prior.config.snapshot.kind === "present") {
6068
+ const { text, changed } = stabilizeMqttNetworkKeyOrder(p.prior.config.snapshot.bytes.toString("utf-8"));
6069
+ if (changed) {
6070
+ done.wroteConfig = true;
6071
+ writeFileAtomic(p.prior.config.path, text, 0o644);
6072
+ }
6073
+ }
6074
+ // A pre-flair#693 legacy plist is retired so it is not orphaned beside the
6075
+ // regenerated one (its job was booted out and verified gone in step 1).
6076
+ if (p.legacyPlistPath) {
6077
+ done.removedLegacy = true;
6078
+ // Not best-effort (flair#2040): a legacy plist left beside the new one
6079
+ // would give launchd two jobs for this instance at the next login.
6080
+ try {
6081
+ unlinkSync(p.legacyPlistPath);
6082
+ }
6083
+ catch (err) {
6084
+ if (err?.code !== "ENOENT")
6085
+ throw new Error(`could not remove the legacy plist ${p.legacyPlistPath}: ${err?.code ?? err}`);
6086
+ }
6087
+ }
6088
+ // 4. Load, with commands that name the probed domain (flair#2040). Drop
6089
+ // the pre-bounce leftover socket first so exists() cannot be true on
6090
+ // the dead inode — Darwin #1704 (`9413a80`) chmod'd that leftover for
6091
+ // 10s and still read 0755 after Harper bind()d a new file.
6092
+ const bounceAt = Date.now();
6093
+ unlinkStaleOpsSocket(p.dataDir);
6094
+ done.loaded = true;
6095
+ loadLaunchdJob({ run: realLaunchctlCommand, domain: p.domain, label: p.label, plistPath: p.plistPath, strict: true });
6096
+ // 5. Verify (fail-loud, STRICT: launchd's pid must be the IDENTIFIED
6097
+ // serving pid — an unidentified one is not proof, flair#2040 — AND
6098
+ // Flair's /Health must answer ok). When kickstart returns, the job has
6099
+ // not bound its port yet (flair#1827), and hdb.pid may already name it:
6100
+ // wait, bounded, while launchd reports a pid and nothing answers its
6101
+ // port, then judge the final observation. Any other observation is
6102
+ // judged at once.
6103
+ const settled = await awaitLaunchdJobServing({
6104
+ observe: async () => {
6105
+ // Health first: a port that answers is then visible to the lsof read.
6106
+ const health = await probeHealth(p.port);
6107
+ return { health, management: observeLaunchdManagement(p.dataDir, p.port) };
6108
+ },
6109
+ deadlineMs: STARTUP_TIMEOUT_MS,
6110
+ });
6111
+ const verdict = judgeLaunchdJobServing(settled);
6112
+ if (!verdict.verified)
6113
+ throw new Error(verdict.detail);
6114
+ // On the adopt arm, port health alone is the green light that lied in
6115
+ // #1684: the pre-adopt direct process answered the port the whole time
6116
+ // the launchd job was failing to start. Prove the launchd job itself
6117
+ // serves — the old pid is dead, the serving pid changed, and it is
6118
+ // launchd's reported pid for this label.
6119
+ if (p.arm === "adopt") {
6120
+ const directPid = p.prior.servingPid;
6121
+ // flair#1827: poll — the launchd-started Harper may not have written
6122
+ // hdb.pid or bound the port yet. Wait for it to serve (and for the
6123
+ // pre-adopt process to be gone), THEN prove identity with
6124
+ // verifyAdoptServing UNCHANGED on the final observation.
6125
+ const waited = await verifyAdoptServingWithWait({
6126
+ observe: () => ({
6127
+ directPid,
6128
+ managedPid: readLaunchctlJobState(p.label, realLaunchctlLister).pid,
6129
+ servingPid: resolveInstanceServingPid(p.dataDir, p.port),
6130
+ directPidAlive: directPid !== null && isProcessAlive(directPid),
6131
+ }),
6132
+ deadlineMs: STARTUP_TIMEOUT_MS,
6133
+ });
6134
+ if (waited.proof)
6135
+ throw new Error(waited.proof.detail);
6136
+ }
6137
+ // flair#1701: the launchd bounce (adopt and regenerate) is a first
6138
+ // start. The product launcher execs Harper and never chmods, so the
6139
+ // new operations-server lands at 0777 & ~umask. Init / start /
6140
+ // restart already call this after health; without it here, doctor
6141
+ // flags ✗ Ops socket permissions until a second start. Wait for
6142
+ // Harper's bind() (HTTP can answer first); ignore leftover mtimes
6143
+ // older than bounceAt.
6144
+ await readyOpsSocketPostureAfterStart(p.dataDir, { notBeforeMs: bounceAt });
6145
+ const detail = p.arm === "adopt"
6146
+ ? `adopted the direct-spawned instance into launchd (bounced the live instance): ${verdict.detail}`
6147
+ : verdict.detail;
6148
+ return { kind: "repaired", detail };
6149
+ }
6150
+ catch (err) {
6151
+ return restoreAfterFailedRepair(p, done, err?.message ?? String(err));
6152
+ }
6153
+ }
6154
+ /**
6155
+ * Undo a failed phase 2 (flair#2040): unload the job this repair loaded and
6156
+ * verify it is gone, put the plist/config files back, and — when an instance
6157
+ * was serving before the repair and this repair stopped it — restart it
6158
+ * DIRECTLY. Every step is an attempt whose outcome is reported: the result is
6159
+ * always `failed` (never "fixed"), and its detail says the state the instance
6160
+ * was left in, including when that state could not be established.
6161
+ */
6162
+ async function restoreAfterFailedRepair(p, done, cause) {
6163
+ const notes = [];
6164
+ // a. Unload the job this repair loaded (or tried to), so KeepAlive cannot
6165
+ // fight the restart, VERIFY it is gone, and wait for its process to exit.
6166
+ if (done.loaded) {
6167
+ const launchdPid = readLaunchctlJobState(p.label, realLaunchctlLister).pid;
6168
+ const servingNow = resolveInstanceServingPid(p.dataDir, p.port);
6169
+ const gone = ensureLaunchdJobAbsent({ run: realLaunchctlCommand, domain: p.domain, label: p.label });
6170
+ if (gone !== null) {
6171
+ // A direct restart now could race the job on the same data directory.
6172
+ return {
6173
+ kind: "failed",
6174
+ detail: `${cause}. Undoing it could not be completed: the job this repair loaded could not be shown unloaded (${gone}), ` +
6175
+ "so Flair was NOT restarted directly — launchd may still run the new job, or Flair may be down. " +
6176
+ "The plist and config files were left as the repair wrote them.",
6177
+ remedy: [`launchctl bootout ${p.domain}/${p.label}`, "flair start"],
6178
+ };
6179
+ }
6180
+ for (const pid of new Set([launchdPid, servingNow])) {
6181
+ if (pid !== null && pid !== p.prior.servingPid) {
6182
+ try {
6183
+ await waitForProcessExit(pid, STARTUP_TIMEOUT_MS);
4978
6184
  }
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 };
6185
+ catch { /* reported by the health probe below */ }
6186
+ }
6187
+ }
6188
+ notes.push(`the launchd job ${p.label} was unloaded again (verified absent)`);
6189
+ }
6190
+ // b. Put the files back (every snapshot was proven readable in phase 1).
6191
+ try {
6192
+ if (done.wrotePlist)
6193
+ restoreFile(p.plistPath, p.prior.plist);
6194
+ if (done.removedLegacy && p.legacyPlistPath && p.prior.legacyPlist)
6195
+ restoreFile(p.legacyPlistPath, p.prior.legacyPlist);
6196
+ if (done.wroteConfig && p.prior.config)
6197
+ restoreFile(p.prior.config.path, p.prior.config.snapshot);
6198
+ if (done.wrotePlist || done.removedLegacy || done.wroteConfig)
6199
+ notes.push("the plist and config files were put back as they were");
6200
+ }
6201
+ catch (err) {
6202
+ notes.push(`putting the plist/config files back FAILED (${err?.message ?? err})`);
6203
+ }
6204
+ if (done.unloadedPrior) {
6205
+ notes.push("the launchd job that was loaded before the repair (it was not serving this instance) is not loaded in this session now");
6206
+ }
6207
+ // c. Bring back the instance that was serving.
6208
+ if (p.arm === "adopt") {
6209
+ const health = await probeHealth(p.port);
6210
+ if (!done.stopped) {
6211
+ notes.push(health.kind === "ok"
6212
+ ? `this repair did not stop the running instance, and Flair is serving on port ${p.port} — directly, NOT under launchd`
6213
+ : `this repair did not stop the running instance, but Flair is not answering on port ${p.port} (${health.kind})`);
6214
+ }
6215
+ else if (health.kind !== "refused") {
6216
+ // The repair stopped the instance, yet the port is not free: something
6217
+ // this repair cannot attribute answers or holds it. Starting a second
6218
+ // instance on top of it is not a restore.
6219
+ return {
6220
+ kind: "failed",
6221
+ detail: `${cause}. The repair had stopped the running instance, and port ${p.port} is not free (${health.kind}) — ` +
6222
+ `what holds it could not be attributed, so Flair was NOT restarted directly. ${notes.length ? `Also: ${notes.join("; ")}.` : ""}`.trim(),
6223
+ remedy: ["flair status", "flair start"],
6224
+ };
6225
+ }
6226
+ else {
6227
+ try {
6228
+ const pid = await startFlairDirect(p.port, p.dataDir);
6229
+ notes.push(`Flair was restarted directly${pid ? ` (pid ${pid})` : ""} and is serving on port ${p.port} — running directly, NOT under launchd`);
4991
6230
  }
4992
6231
  catch (err) {
4993
- return mapRepairThrow(err);
6232
+ return {
6233
+ kind: "failed",
6234
+ detail: `${cause}. The repair had stopped the running instance, and restarting it directly FAILED ` +
6235
+ `(${err?.message ?? err}): Flair is DOWN. ${notes.length ? `Also: ${notes.join("; ")}.` : ""}`.trim(),
6236
+ remedy: ["flair start"],
6237
+ };
4994
6238
  }
4995
6239
  }
4996
6240
  }
6241
+ else {
6242
+ notes.push("Flair was not running before this repair (its port was free) and was not started");
6243
+ }
6244
+ return {
6245
+ kind: "failed",
6246
+ detail: `${cause}. Restored: ${notes.join("; ")}.`,
6247
+ remedy: ["flair doctor --fix"],
6248
+ };
4997
6249
  }
4998
6250
  /**
4999
6251
  * Clean-stop the direct (non-launchd) process serving `dataDir`+`port` for the
@@ -5169,10 +6421,21 @@ async function stopFlairProcess(port, dataDir) {
5169
6421
  await waitForProcessExit(pid, STARTUP_TIMEOUT_MS);
5170
6422
  }
5171
6423
  catch { /* best-effort — the next start will surface the real problem */ }
6424
+ // flair#2055: once the process is CONFIRMED gone, drop the identity
6425
+ // sidecar. Gated on a fresh O_NOFOLLOW read that still names the pid it
6426
+ // named before (a sidecar another supervisor rewrote in between is left
6427
+ // alone); a process that survived the wait (or whose liveness is unknown)
6428
+ // removes nothing.
6429
+ removeStaleSidecarIfConfirmedDead(dataDir);
6430
+ return;
6431
+ }
6432
+ case "NOT_RUNNING": {
6433
+ // Idempotent no-op for the process — but a sidecar left naming a pid that
6434
+ // is CONFIRMED gone is a leftover too (flair#2055), and removing it here
6435
+ // keeps a repeat stop from carrying the refusal forward.
6436
+ removeStaleSidecarIfConfirmedDead(dataDir);
5172
6437
  return;
5173
6438
  }
5174
- case "NOT_RUNNING":
5175
- return; // idempotent no-op
5176
6439
  case "DISAGREEMENT":
5177
6440
  case "UNKNOWN":
5178
6441
  // Deliberately outside any catch: a refusal must reach the caller, not
@@ -5240,34 +6503,65 @@ async function startFlairProcess(port, dataDir) {
5240
6503
  // for health on `port`, see the OTHER instance answer, and report
5241
6504
  // success.
5242
6505
  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;
6506
+ // flair#2040: preflight BEFORE the load — is the GUI domain reachable
6507
+ // from this session, and is the job enabled there? If not, say why and
6508
+ // start directly (a running instance beats a down one). The caller
6509
+ // (`flair restart`, `flair upgrade`) observes launchd management
6510
+ // afterwards and reports a detached instance as such.
6511
+ const loadability = observeLaunchdLoadability(launchdLabel(dataDir));
6512
+ if (!loadabilityAllowsAttempt(loadability)) {
6513
+ console.error(renderStartLaunchdUnavailable("flair", loadability));
5265
6514
  }
5266
- catch (err) {
5267
- console.error(`launchd start failed, falling back to direct start: ${err.message}`);
6515
+ else {
6516
+ try {
6517
+ // flair#1022: launchd will not tell us it cannot exec the job.
6518
+ // `launchctl load` and `launchctl start` BOTH exit 0 for a plist whose
6519
+ // ProgramArguments[0] does not exist (measured, see the module header),
6520
+ // so the only way this loop learns anything is by waiting the full
6521
+ // startup budget for a port that will never open — the reported
6522
+ // incident's second 60-second hang, ending in "did not respond within
6523
+ // 60000ms (120 attempts)", an error about a port that says nothing
6524
+ // about the cause. The paths in the plist are absolute and checkable
6525
+ // with an existsSync, so check them first and turn a two-minute silence
6526
+ // into an immediate, named diagnosis. Still falls back — a running
6527
+ // instance beats a down one — just without the wait or the mystery.
6528
+ // flair#2040: a validation refusal — nothing loaded or unloaded.
6529
+ const stalePlist = diagnoseLaunchdPlistPaths(plistPath);
6530
+ if (stalePlist) {
6531
+ throw new LaunchdValidationRefusal(`${stalePlist.message} Fix it with: ${stalePlist.remedy.join(" && ")}`);
6532
+ }
6533
+ ensureLaunchdServiceLoaded(dataDir, realLaunchctlCommand);
6534
+ await waitForHealth(port, DEFAULT_ADMIN_USER, process.env.HDB_ADMIN_PASSWORD ?? "", STARTUP_TIMEOUT_MS);
6535
+ readyOpsSocketPosture(dataDir); // flair#763: re-assert socket posture across restart/upgrade
6536
+ stampEngineVersionIfRunning(dataDir); // flair#1047: stamp the store with the engine version
6537
+ return;
6538
+ }
6539
+ catch (err) {
6540
+ // flair#2040: start directly only when no job for this instance could
6541
+ // start underneath the direct process. A failed LOAD is unloaded again
6542
+ // and verified gone; a VALIDATION refusal loaded and unloaded nothing,
6543
+ // so nothing is booted out — a loaded job refuses the direct start
6544
+ // instead (afterFailedLaunchdAttempt).
6545
+ const labels = label === LEGACY_LAUNCHD_LABEL ? [launchdLabel(dataDir), LEGACY_LAUNCHD_LABEL] : [launchdLabel(dataDir)];
6546
+ const after = afterFailedLaunchdAttempt("flair", launchdLabel(dataDir), labels, err);
6547
+ if (!after.directStart)
6548
+ throw new Error(after.lines.join("\n"));
6549
+ for (const line of after.lines)
6550
+ console.error(line);
6551
+ }
5268
6552
  }
5269
6553
  }
5270
6554
  }
6555
+ await startFlairDirect(port, dataDir);
6556
+ }
6557
+ /**
6558
+ * Start Flair as a DIRECT (non-launchd) process and wait for it to answer —
6559
+ * the fallback half of startFlairProcess, and what `doctor --fix` / `init` use
6560
+ * to bring back an instance they stopped when the launchd hand-off failed
6561
+ * (flair#2040). Returns the spawned pid. Throws when Harper cannot be found or
6562
+ * does not answer within the startup budget.
6563
+ */
6564
+ async function startFlairDirect(port, dataDir) {
5271
6565
  console.log("Starting...");
5272
6566
  const harper = resolveHarperBin(harperSearchRoots());
5273
6567
  if (!harper.path) {
@@ -5311,6 +6605,7 @@ async function startFlairProcess(port, dataDir) {
5311
6605
  await waitForHealth(port, DEFAULT_ADMIN_USER, adminPass, STARTUP_TIMEOUT_MS);
5312
6606
  readyOpsSocketPosture(dataDir); // flair#763: re-assert socket posture across restart/upgrade
5313
6607
  stampEngineVersionIfRunning(dataDir); // flair#1047: stamp the store with the engine version
6608
+ return proc.pid ?? null;
5314
6609
  }
5315
6610
  /**
5316
6611
  * The ONE restart mechanism for a local Flair install. Shared by `flair
@@ -5329,8 +6624,57 @@ async function startFlairProcess(port, dataDir) {
5329
6624
  * frames down.
5330
6625
  */
5331
6626
  async function restartFlair(port, dataDir) {
5332
- await stopFlairProcess(port, dataDir);
5333
- await startFlairProcess(port, dataDir);
6627
+ // flair#2034 §2: on Linux, an instance proven to run under a systemd USER
6628
+ // unit (found from the serving process's cgroup; its MainPID is that
6629
+ // process) is restarted THROUGH that unit, and the unit's new main process
6630
+ // must run from the unit's WorkingDirectory. The signal-and-respawn path
6631
+ // below would leave a supervised instance running outside its unit — so it
6632
+ // is refused, with the systemctl command, when a process it could stop is
6633
+ // the MainPID of any other unit, or when its cgroup or that unit's MainPID
6634
+ // cannot be read. A process that merely sits in some service's cgroup (a CI
6635
+ // runner agent's child: the unit's MainPID is another process) was started
6636
+ // directly and is restarted directly.
6637
+ if (process.platform === "linux") {
6638
+ const ev = localPidEvidence(dataDir, port);
6639
+ const how = await restartOnLinux({
6640
+ serving: resolveServingTree(dataDir, port, { local: true }),
6641
+ pids: [...(ev.pidFile !== null ? [ev.pidFile] : []), ...(ev.listeners ?? [])],
6642
+ procCgroup: readProcCgroup,
6643
+ uid: typeof process.getuid === "function" ? process.getuid() : -1,
6644
+ unitMainPid: systemdUnitMainPid,
6645
+ systemctl: (args) => {
6646
+ execFileSync("systemctl", args, { stdio: "pipe", timeout: args[1] === "restart" ? STARTUP_TIMEOUT_MS * 2 : 30_000 });
6647
+ },
6648
+ waitHealthy: () => waitForHealth(port, DEFAULT_ADMIN_USER, process.env.HDB_ADMIN_PASSWORD ?? "", STARTUP_TIMEOUT_MS),
6649
+ unitState: systemdUserUnitState,
6650
+ cwdOf: (pid) => {
6651
+ try {
6652
+ return realpathSync(`/proc/${pid}/cwd`);
6653
+ }
6654
+ catch {
6655
+ return null;
6656
+ }
6657
+ },
6658
+ samePath: samePathCanonical,
6659
+ beforeRestart: (s) => {
6660
+ if (s.unitTree !== null && samePathCanonical(s.unitTree, flairPackageDir()))
6661
+ guardEngineNotBackwards(dataDir);
6662
+ },
6663
+ direct: async () => {
6664
+ await stopFlairProcess(port, dataDir);
6665
+ await startFlairProcess(port, dataDir);
6666
+ },
6667
+ log: (line) => console.log(line),
6668
+ });
6669
+ if (how === "systemd") {
6670
+ readyOpsSocketPosture(dataDir);
6671
+ stampEngineVersionIfRunning(dataDir);
6672
+ }
6673
+ }
6674
+ else {
6675
+ await stopFlairProcess(port, dataDir);
6676
+ await startFlairProcess(port, dataDir);
6677
+ }
5334
6678
  // Bust the version-handshake cache so the next preAction nudge re-fetches
5335
6679
  // the LIVE version instead of the pre-restart cached one (the false
5336
6680
  // "server is running <old>" users hit for up to 60s post-upgrade+restart).
@@ -5477,6 +6821,7 @@ registerFleet(program);
5477
6821
  // Bind shared cli-locals first so the extracted module never imports this file.
5478
6822
  bindDoctorCli({
5479
6823
  api,
6824
+ assessInstallTree,
5480
6825
  checkAgentRegistered,
5481
6826
  classifyOpsSocketPosture,
5482
6827
  configPath,
@@ -5490,7 +6835,9 @@ bindDoctorCli({
5490
6835
  readPortFromConfig,
5491
6836
  relativeTime,
5492
6837
  repairLaunchdManagement,
6838
+ repointMainServiceUnit,
5493
6839
  resolveHttpPort,
6840
+ restartFlair,
5494
6841
  resolveOpsPort,
5495
6842
  verifyAuditLog,
5496
6843
  verifySemanticSearch,
@@ -5746,7 +7093,10 @@ harperConfigPath, readHarperConfig, readPortFromHarperConfig, persistDefaultInst
5746
7093
  // launchd label (flair#693)
5747
7094
  LEGACY_LAUNCHD_LABEL, launchdLabel, launchdPlistPath, cleanupLegacyLaunchdPlist, resolveLaunchdLabel, migrateLegacyLaunchdLabel, ensureLaunchdServiceLoaded,
5748
7095
  // launchd management observation (flair#1022)
5749
- observeLaunchdManagement, resolveInstanceServingPid, };
7096
+ observeLaunchdManagement, resolveInstanceServingPid,
7097
+ // launchd preflight, repair and init registration (flair#2040) — exported so
7098
+ // the command-level tests drive them against a stubbed launchctl.
7099
+ observeLaunchdLoadability, repairLaunchdManagement, registerInitLaunchdService, startFlairProcess, };
5750
7100
  // Shared with `flair status` via src/lib/ops-api-bind.ts (flair#852).
5751
7101
  export { detectOpsApiAllInterfacesBind };
5752
7102
  export { searchScoringFormula, buildSearchExplain, formatSearchExplain } from "./commands/search.js";