@tpsdev-ai/flair 0.58.0 → 0.62.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 (268) hide show
  1. package/README.md +7 -6
  2. package/SECURITY.md +36 -0
  3. package/config.yaml +15 -1
  4. package/dist/bridges/builtins/mem0.js +63 -28
  5. package/dist/bridges/runtime/import-runner.js +12 -0
  6. package/dist/bridges/runtime/load-plugin.js +42 -13
  7. package/dist/bridges/runtime/yaml-loader.js +4 -2
  8. package/dist/build-info.json +3 -3
  9. package/dist/cli.js +1030 -343
  10. package/dist/commands/agent.js +384 -45
  11. package/dist/commands/attention.js +4 -3
  12. package/dist/commands/backup.js +202 -34
  13. package/dist/commands/bridge.js +172 -119
  14. package/dist/commands/deploy.js +37 -4
  15. package/dist/commands/doctor.js +601 -163
  16. package/dist/commands/export.js +54 -19
  17. package/dist/commands/federation.js +141 -21
  18. package/dist/commands/hook.js +155 -2
  19. package/dist/commands/idp.js +14 -1
  20. package/dist/commands/import.js +7 -3
  21. package/dist/commands/init.js +462 -193
  22. package/dist/commands/integrity.js +388 -0
  23. package/dist/commands/keys.js +247 -58
  24. package/dist/commands/mcp.js +146 -53
  25. package/dist/commands/memory.js +171 -21
  26. package/dist/commands/migrate-harness-memory.js +3 -2
  27. package/dist/commands/orgevent.js +46 -37
  28. package/dist/commands/presence.js +4 -3
  29. package/dist/commands/principal.js +426 -48
  30. package/dist/commands/quality.js +10 -1
  31. package/dist/commands/reembed.js +141 -17
  32. package/dist/commands/relationship.js +2 -1
  33. package/dist/commands/rem.js +56 -18
  34. package/dist/commands/restore.js +101 -61
  35. package/dist/commands/search.js +6 -4
  36. package/dist/commands/service.js +151 -38
  37. package/dist/commands/soul.js +4 -3
  38. package/dist/commands/status.js +43 -5
  39. package/dist/commands/test.js +3 -2
  40. package/dist/commands/upgrade.js +24 -1
  41. package/dist/commands/workspace.js +6 -3
  42. package/dist/component-env.js +31 -41
  43. package/dist/deploy.js +77 -1
  44. package/dist/doctor-client.js +529 -92
  45. package/dist/engine-version-contract.js +1 -0
  46. package/dist/engine-version.js +23 -3
  47. package/dist/federation-verify.js +4 -3
  48. package/dist/hook-install.js +670 -6
  49. package/dist/keystore.js +72 -0
  50. package/dist/lib/action-recall-runtime.js +328 -0
  51. package/dist/lib/agent-home-fields.js +132 -0
  52. package/dist/lib/agent-home.js +427 -0
  53. package/dist/lib/agent-id-rule.js +46 -0
  54. package/dist/lib/agent-roster.js +33 -0
  55. package/dist/lib/auth-resolve.js +49 -16
  56. package/dist/lib/capture-runtime.js +124 -0
  57. package/dist/lib/credential-status-rule.js +78 -0
  58. package/dist/lib/daemon-liveness.js +81 -8
  59. package/dist/lib/doctor-run.js +140 -35
  60. package/dist/lib/durability-copy.js +10 -0
  61. package/dist/lib/embedding-space-doctor.js +75 -0
  62. package/dist/lib/flair-agent-role.js +120 -0
  63. package/dist/lib/hub-url.js +12 -0
  64. package/dist/lib/init-admin-pass.js +88 -12
  65. package/dist/lib/init-listener-environ.js +1 -2
  66. package/dist/lib/init-occupied-listener.js +15 -111
  67. package/dist/lib/init-spawn-attribution.js +73 -0
  68. package/dist/lib/init-tcp-probe.js +33 -0
  69. package/dist/lib/instance-identity-row.js +20 -0
  70. package/dist/lib/launchd-management.js +27 -2
  71. package/dist/lib/listener-table.js +268 -0
  72. package/dist/lib/local-delete-instance.js +27 -0
  73. package/dist/lib/local-instance-pair.js +256 -0
  74. package/dist/lib/mcp-enable.js +1775 -338
  75. package/dist/lib/mcp-oauth-env-core.js +133 -0
  76. package/dist/lib/mcp-oauth-env.js +125 -0
  77. package/dist/lib/mcp-spec.js +17 -1
  78. package/dist/lib/memory-attributes.js +2 -0
  79. package/dist/lib/memory-id-policy.js +46 -0
  80. package/dist/lib/memory-integrity.js +309 -0
  81. package/dist/lib/memory-purge-response.js +20 -0
  82. package/dist/lib/ops-table-count.js +25 -0
  83. package/dist/lib/owned-pins.js +67 -10
  84. package/dist/lib/peer-status.js +27 -0
  85. package/dist/lib/principal-status.js +29 -0
  86. package/dist/lib/process-start-time.js +103 -7
  87. package/dist/lib/proto-safe-record.js +42 -0
  88. package/dist/lib/record-id-path.js +25 -0
  89. package/dist/lib/reembed-server-support.js +66 -0
  90. package/dist/lib/restore-verify.js +104 -0
  91. package/dist/lib/scheduler-platform.js +10 -6
  92. package/dist/lib/secret-keys.js +25 -0
  93. package/dist/lib/secrets-push.js +50 -22
  94. package/dist/lib/skill-seed-pending.js +24 -0
  95. package/dist/lib/skill-seed.js +365 -0
  96. package/dist/lib/stop-start-recovery.js +54 -0
  97. package/dist/lib/using-flair-skill.js +87 -0
  98. package/dist/mcp-client-assertion.js +112 -4
  99. package/dist/memory-id-checkpoint.js +326 -0
  100. package/dist/memory-node-compare.js +207 -0
  101. package/dist/packages/flair-mcp/src/secret-redaction.js +113 -0
  102. package/dist/rem/restore.js +6 -5
  103. package/dist/rem/runner.js +103 -44
  104. package/dist/resources/Agent.js +348 -8
  105. package/dist/resources/AgentKeyRegister.js +214 -0
  106. package/dist/resources/AgentKeyRegistration.js +28 -0
  107. package/dist/resources/AgentSeed.js +19 -4
  108. package/dist/resources/AutoPromoteCandidates.js +7 -1
  109. package/dist/resources/Credential.js +177 -2
  110. package/dist/resources/Federation.js +752 -132
  111. package/dist/resources/FederationRetry.js +140 -0
  112. package/dist/resources/InstructionVersion.js +220 -0
  113. package/dist/resources/Integration.js +300 -25
  114. package/dist/resources/Memory.js +2113 -604
  115. package/dist/resources/MemoryArchive.js +75 -42
  116. package/dist/resources/MemoryBootstrap.js +227 -64
  117. package/dist/resources/MemoryCandidate.js +21 -1
  118. package/dist/resources/MemoryDedupStats.js +30 -1
  119. package/dist/resources/MemoryFeed.js +327 -45
  120. package/dist/resources/MemoryGrant.js +21 -1
  121. package/dist/resources/MemoryMaintenance.js +129 -25
  122. package/dist/resources/MemoryPurge.js +232 -0
  123. package/dist/resources/MemoryReflect.js +7 -2
  124. package/dist/resources/MemoryReindex.js +24 -8
  125. package/dist/resources/Message.js +5 -3
  126. package/dist/resources/OAuth.js +186 -9
  127. package/dist/resources/OrgEvent.js +126 -3
  128. package/dist/resources/OrgSkillAssignment.js +209 -0
  129. package/dist/resources/Presence.js +144 -49
  130. package/dist/resources/PromoteMemoryCandidate.js +18 -7
  131. package/dist/resources/Relationship.js +23 -0
  132. package/dist/resources/SemanticSearch.js +63 -32
  133. package/dist/resources/Soul.js +189 -76
  134. package/dist/resources/TeamDirectory.js +35 -0
  135. package/dist/resources/WorkspaceState.js +21 -1
  136. package/dist/resources/XAA.js +212 -65
  137. package/dist/resources/agent-auth.js +40 -15
  138. package/dist/resources/agent-status-guard.js +63 -0
  139. package/dist/resources/auth-middleware.js +402 -162
  140. package/dist/resources/ed25519-auth.js +1 -1
  141. package/dist/resources/embedding-space-guard.js +366 -72
  142. package/dist/resources/engine-version-stamp-boot.js +53 -0
  143. package/dist/resources/federation-classify.js +94 -0
  144. package/dist/resources/federation-crypto.js +5 -5
  145. package/dist/resources/federation-retry-lib.js +135 -0
  146. package/dist/resources/flair-agent-role-boot.js +26 -0
  147. package/dist/resources/grant-visibility.js +135 -0
  148. package/dist/resources/harper-routing.js +83 -0
  149. package/dist/resources/health.js +130 -20
  150. package/dist/resources/host-source-citation.js +49 -0
  151. package/dist/resources/host-source-visibility.js +7 -6
  152. package/dist/resources/instance-create-lock.js +17 -0
  153. package/dist/resources/instance-identity.js +23 -0
  154. package/dist/resources/instruction-version-record.js +343 -0
  155. package/dist/resources/key-lock.js +31 -0
  156. package/dist/resources/mcp-handler.js +36 -8
  157. package/dist/resources/mcp-oauth-env-guard.js +36 -0
  158. package/dist/resources/mcp-oauth.js +26 -12
  159. package/dist/resources/mcp-tool-arguments.js +4 -6
  160. package/dist/resources/mcp-tools.js +150 -23
  161. package/dist/resources/memory-bootstrap-lib.js +5 -15
  162. package/dist/resources/memory-declared-attributes.js +3 -1
  163. package/dist/resources/memory-deletion-history.js +55 -0
  164. package/dist/resources/memory-durability.js +54 -0
  165. package/dist/resources/memory-embed-hash.js +88 -0
  166. package/dist/resources/memory-embedding-value.js +8 -0
  167. package/dist/resources/memory-host-source.js +27 -5
  168. package/dist/resources/memory-id-guard.js +75 -0
  169. package/dist/resources/memory-redaction.js +236 -0
  170. package/dist/resources/memory-supplied-vector.js +72 -0
  171. package/dist/resources/memory-write-lock.js +310 -0
  172. package/dist/resources/memory-write-response.js +139 -0
  173. package/dist/resources/migrations/data-dir.js +74 -16
  174. package/dist/resources/migrations/dir-safety.js +1 -1
  175. package/dist/resources/migrations/embedding-stamp.js +193 -79
  176. package/dist/resources/migrations/export.js +1 -0
  177. package/dist/resources/migrations/graph-heal.js +18 -25
  178. package/dist/resources/migrations/lock.js +7 -1
  179. package/dist/resources/migrations/snapshot.js +1 -0
  180. package/dist/resources/migrations/source-fields.js +5 -5
  181. package/dist/resources/migrations/synthetic-test-migration.js +14 -11
  182. package/dist/resources/migrations/visibility-backfill.js +29 -29
  183. package/dist/resources/multi-worker-guard.js +121 -0
  184. package/dist/resources/oauth-discovery.js +1 -0
  185. package/dist/resources/oauth-wellknown.js +8 -4
  186. package/dist/resources/object-body-guard.js +33 -0
  187. package/dist/resources/org-event-created-at.js +133 -0
  188. package/dist/resources/originator-instance.js +39 -7
  189. package/dist/resources/owner-delete-recheck.js +78 -0
  190. package/dist/resources/owner-field-guard.js +39 -5
  191. package/dist/resources/owner-scoped-write-policy.js +212 -0
  192. package/dist/resources/owner-scoped-writes.js +58 -0
  193. package/dist/resources/presence-receipt.js +236 -0
  194. package/dist/resources/promotion-stamp.js +47 -12
  195. package/dist/resources/record-owner-guard.js +74 -26
  196. package/dist/resources/record-types.js +17 -1
  197. package/dist/resources/relay-ops.js +78 -6
  198. package/dist/resources/replay-store.js +145 -21
  199. package/dist/resources/request-target.js +136 -0
  200. package/dist/resources/request-transaction.js +35 -0
  201. package/dist/resources/search-readiness.js +4 -1
  202. package/dist/resources/seed-ids.js +9 -0
  203. package/dist/resources/seed-reservation.js +117 -0
  204. package/dist/resources/semantic-retrieval-core.js +20 -9
  205. package/dist/resources/skill-manifest.js +190 -0
  206. package/dist/resources/skill-provenance.js +15 -10
  207. package/dist/resources/skill-subject.js +53 -0
  208. package/dist/resources/skill-version-write.js +432 -0
  209. package/dist/resources/skill-write-fault.js +17 -0
  210. package/dist/resources/skill-write-policy.js +67 -0
  211. package/dist/resources/skill-write.js +67 -7
  212. package/dist/resources/table-helpers.js +10 -7
  213. package/dist/resources/team-directory.js +248 -0
  214. package/dist/resources/tool-descriptors/index.js +69 -8
  215. package/dist/resources/txn-pause-point.js +118 -0
  216. package/dist/resources/usage-recording.js +171 -63
  217. package/dist/resources/write-back.js +218 -0
  218. package/dist/src/engine-version-contract.js +1 -0
  219. package/dist/src/keystore.js +72 -0
  220. package/dist/src/lib/agent-home-fields.js +132 -0
  221. package/dist/src/lib/agent-id-rule.js +46 -0
  222. package/dist/src/lib/agent-key-register.js +80 -0
  223. package/dist/src/lib/atomic-write.js +256 -0
  224. package/dist/src/lib/credential-status-rule.js +78 -0
  225. package/dist/src/lib/expired-by-agent.js +37 -0
  226. package/dist/src/lib/flair-agent-role.js +120 -0
  227. package/dist/src/lib/idp-mapping-rule.js +81 -0
  228. package/dist/src/lib/instance-identity-row.js +20 -0
  229. package/dist/src/lib/mcp-oauth-env-core.js +133 -0
  230. package/dist/src/lib/memory-attributes.js +2 -0
  231. package/dist/src/lib/memory-id-policy.js +46 -0
  232. package/dist/src/lib/principal-status.js +29 -0
  233. package/dist/src/lib/proto-safe-record.js +42 -0
  234. package/dist/src/lib/reembed-server-support.js +66 -0
  235. package/dist/src/lib/scheduler-platform.js +10 -6
  236. package/dist/src/lib/systemd-agent-id.js +38 -0
  237. package/docs/access-control.md +768 -0
  238. package/docs/api-reference.md +52 -13
  239. package/docs/auth.md +10 -12
  240. package/docs/bridges.md +11 -0
  241. package/docs/claude-code.md +34 -4
  242. package/docs/deepseek-harness.md +1 -1
  243. package/docs/deploying-on-fabric.md +70 -0
  244. package/docs/deployment.md +2 -0
  245. package/docs/embedding-in-a-harper-app.md +1 -1
  246. package/docs/federation.md +33 -2
  247. package/docs/hosted-on-fabric.md +43 -36
  248. package/docs/integrations.md +6 -6
  249. package/docs/mcp-clients.md +10 -5
  250. package/docs/n8n.md +17 -11
  251. package/docs/notes/mcp-agent-auth-consumer.md +12 -4
  252. package/docs/notes/mcp-oauth-model2.md +34 -5
  253. package/docs/quickstart-fabric.md +2 -2
  254. package/docs/quickstart.md +9 -1
  255. package/docs/releasing.md +34 -28
  256. package/docs/rem.md +8 -0
  257. package/docs/secrets-and-keys.md +19 -2
  258. package/docs/standalone-local.md +1 -0
  259. package/docs/supply-chain-policy.md +13 -3
  260. package/docs/upgrade.md +32 -6
  261. package/package.json +12 -6
  262. package/schemas/agent-key-registration.graphql +22 -0
  263. package/schemas/agent.graphql +3 -0
  264. package/schemas/federation.graphql +38 -1
  265. package/schemas/memory.graphql +115 -5
  266. package/schemas/oauth.graphql +27 -4
  267. package/schemas/schema.graphql +2 -0
  268. package/templates/launchd/start-flair-with-admin-pass.sh +89 -16
package/dist/cli.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { Command } from "commander";
3
3
  import { load as parseYaml } from "js-yaml";
4
- import { existsSync, mkdirSync, writeFileSync, readFileSync, openSync, closeSync, chmodSync, renameSync, cpSync, rmSync, mkdtempSync, readdirSync, statSync, lstatSync, realpathSync, unlinkSync, chownSync, constants as fsConstants, } from "node:fs";
4
+ import { existsSync, mkdirSync, writeFileSync, readFileSync, openSync, closeSync, chmodSync, renameSync, cpSync, rmSync, mkdtempSync, readdirSync, statSync, lstatSync, fstatSync, fchmodSync, realpathSync, unlinkSync, chownSync, constants as fsConstants, } from "node:fs";
5
5
  import { tmpdir } from "node:os";
6
6
  import { join, resolve, dirname, basename } from "node:path";
7
7
  import { fileURLToPath } from "node:url";
@@ -21,15 +21,19 @@ import { detectClients } from "./install/clients.js";
21
21
  import { flairCliVersion, mcpServerSpec } from "./lib/mcp-spec.js";
22
22
  import { harperPortValue } from "./lib/harper-port-value.js";
23
23
  import { flairConfigPath, flairDataDir } from "./lib/flair-paths.js";
24
+ import { encodeRecordId } from "./lib/record-id-path.js";
25
+ import { invalidAgentIdMessage, isValidAgentId } from "./lib/agent-id-rule.js";
26
+ import { agentHomeEndpoint, decideProbedPairIdentity, readHttpInstanceIdentity, resolveTargetInstanceId, resolveTargetInstanceIdentity, stampAgentHome } from "./lib/agent-home.js";
27
+ import { proveLocalInstancePair } from "./lib/local-instance-pair.js";
24
28
  import { httpBind, httpCorsAccessList, preserveHttpPortValue, preserveSecurePort, qualifySecureBindValue, DEFAULT_HTTP_BIND_HOST, } from "./lib/http-bind.js";
25
29
  import { isNodeKeyId, partitionKeyIds, } from "./doctor-client.js";
26
30
  import { cliBootPathWarning, } from "./install/global-bin-path.js";
27
- import { readSecretFileSecure, readAdminPassFileSecure, defaultAdminPassPath, defaultKeysDir, resolveLocalAdminPass, resolveAdminPassFromSources, ADMIN_PASS_FLAG, ADMIN_PASS_HELP, ADMIN_PASS_FILE_FLAG, ADMIN_PASS_FILE_HELP, DEFAULT_ADMIN_USER, resolveAdminUser, resolveKeyPath, buildEd25519Auth, authFetch, KeyLoadError, isLocalBase, authedRequest, } from "./lib/auth-resolve.js";
31
+ import { ApiHttpError, readSecretFileSecure, readAdminPassFileSecure, defaultAdminPassPath, defaultKeysDir, resolveLocalAdminPass, resolveAdminPassFromSources, ADMIN_PASS_FLAG, ADMIN_PASS_HELP, ADMIN_PASS_FILE_FLAG, ADMIN_PASS_FILE_HELP, DEFAULT_ADMIN_USER, resolveAdminUser, resolveKeyPath, buildEd25519Auth, authFetch, KeyLoadError, isLocalBase, authedRequest, } from "./lib/auth-resolve.js";
28
32
  import { resolveSigningIdentity, emitSigningIdentityDebug, } from "./lib/signing-identity.js";
29
33
  import { entityFormatHint, parseEntitiesCsv } from "./lib/entity-vocab-cli.js";
30
34
  import { escapeXml, unescapeXml } from "./lib/xml-escape.js";
31
35
  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";
36
+ import { classifyPlist, planLaunchdRepair, mapRepairThrow, decideAdoptStop, verifyAdoptServingWithWait, awaitLaunchdJobServing, judgeLaunchdJobServing, domainPreflightRefusal, } from "./lib/launchd-repair.js";
33
37
  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
38
  import { assessTreeDivergence, linuxUnitProbe, mainPidFromShow, proveServingTree, systemdUnitStateFromShow, } from "./lib/tree-divergence.js";
35
39
  import { planPlistRuntimeRepoint } from "./lib/service-repoint.js";
@@ -42,8 +46,8 @@ import { stabilizeMqttNetworkKeyOrder } from "./lib/stabilize-mqtt-network.js";
42
46
  import { detectOpsApiAllInterfacesBind } from "./lib/ops-api-bind.js";
43
47
  import { applyUpgradeHookConsent, runDoctorChecks, } from "./lib/doctor-run.js";
44
48
  import { classifyInstalledVersion, shouldPrintUpgradeLine, upgradeStatusSuffix } from "./lib/upgrade-status.js";
45
- import { classifyDaemonState, verifyIdentity, parseSidecarJson, classifyHealthProbe, classifyPortOwner, classifyInstanceMatch, shouldAdoptMissingSidecar, classifySidecarStaleness, shouldRemoveSidecarAfterStop, livenessFromKillError, parseNullSeparatedEnviron, extractRootPath, } from "./lib/daemon-liveness.js";
46
- import { readProcessStartTimeMs } from "./lib/process-start-time.js";
49
+ import { classifyDaemonState, verifyIdentity, isHarperProcessCommandLine, sidecarStartAgrees, parseSidecarJson, classifyHealthProbe, classifyPortOwner, classifyInstanceMatch, shouldAdoptMissingSidecar, classifySidecarStaleness, shouldRemoveSidecarAfterStop, livenessFromKillError, parseProcStatState, isExitedState, parseNullSeparatedEnviron, extractRootPath, } from "./lib/daemon-liveness.js";
50
+ import { readProcessStartSecondMs, readProcessStartTimeMs } from "./lib/process-start-time.js";
47
51
  import { readInitListenerRootPath } from "./lib/init-listener-environ.js";
48
52
  import { listenerFromLookup, occupiedListenerAuthFailure, stableAnsweredHolder, } from "./lib/init-occupied-listener.js";
49
53
  import { bindCli as bindFederationCli, register as registerFederation, signRequestBody, parseTokenFromFile, runFederationSyncOnce, persistLocalPeerLastSyncAt, runFederationWatch, federationStatusUrlSetting, describeFederationStatusFetchFailed, isFederationStatusConnectFailure, rewriteFederationStatusFetchFailed, isFederationStatusAuthFailure, isFederationStatusAuthRemedy, } from "./commands/federation.js";
@@ -88,7 +92,9 @@ import { bindCli as bindServiceCli, register as registerService, } from "./comma
88
92
  import { bindCli as bindDoctorCli, register as registerDoctor, } from "./commands/doctor.js";
89
93
  import { bindCli as bindQualityCli, register as registerQuality, } from "./commands/quality.js";
90
94
  import { bindCli as bindGrantCli, register as registerGrant, } from "./commands/grant.js";
95
+ import { bindIntegrityCli, register as registerIntegrity, } from "./commands/integrity.js";
91
96
  import { resolveHome } from "./lib/home.js";
97
+ import { FLAIR_AGENT_PERMISSION } from "./lib/flair-agent-role.js";
92
98
  // Federation crypto helpers + private-visibility filter live with the
93
99
  // federation command group (src/commands/federation.ts, flair#1620). Inlined
94
100
  // there for the same packaging reason: src/ must not import resources/.
@@ -142,7 +148,12 @@ const DEFAULT_OPS_PORT = 19925;
142
148
  const FABRIC_OPS_PORT = 9925;
143
149
  // DEFAULT_ADMIN_USER + resolveAdminUser (flag > FLAIR_ADMIN_USER env > "admin")
144
150
  // live in src/lib/auth-resolve.ts — imported above (flair#1345).
145
- const STARTUP_TIMEOUT_MS = 60_000;
151
+ //
152
+ // Exported (flair#2568) so the test harness's readiness budget
153
+ // (HARPER_STARTUP_BUDGET_MS in test/helpers/harper-lifecycle.ts) can be pinned
154
+ // equal to the budget `flair init`'s TCP readiness check polls under.
155
+ export const STARTUP_TIMEOUT_MS = 60_000;
156
+ const ADOPT_STOP_TIMEOUT_MS = 60_000;
146
157
  const HEALTH_POLL_INTERVAL_MS = 500;
147
158
  // flair#670 — single-host default for the Harper ops API bind address.
148
159
  // Loopback-only (+ the domain socket, always provisioned) shrinks the
@@ -266,15 +277,29 @@ export function launchdLauncherPath(packageRoot = flairPackageDir()) {
266
277
  * Write `content` to `path` atomically: write to a temp file in the SAME
267
278
  * directory, then rename over the target. Same-fs rename is atomic on POSIX,
268
279
  * so a reader never observes a half-written file. `mode` is applied to the
269
- * temp file from creation — pass 0o600 when `content` holds a secret, so the
270
- * secret is never briefly world-readable on disk (flair#1573 slice a).
280
+ * temp file from creation (subject to umask) — pass 0o600 when `content`
281
+ * holds a secret, so the secret is never briefly world-readable on disk
282
+ * (flair#1573 slice a). `exactMode` is for restoring a captured file mode:
283
+ * it sets that mode on the temporary file's descriptor before the rename.
271
284
  */
272
- export function writeFileAtomic(path, content, mode) {
285
+ export function writeFileAtomic(path, content, mode, options = {}) {
273
286
  const dir = dirname(path);
274
287
  mkdirSync(dir, { recursive: true });
275
288
  const tmpPath = join(dir, `.${basename(path)}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`);
276
289
  try {
277
- writeFileSync(tmpPath, content, { mode });
290
+ if (options.exactMode) {
291
+ const fd = openSync(tmpPath, fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL, mode);
292
+ try {
293
+ writeFileSync(fd, content);
294
+ fchmodSync(fd, mode);
295
+ }
296
+ finally {
297
+ closeSync(fd);
298
+ }
299
+ }
300
+ else {
301
+ writeFileSync(tmpPath, content, { mode });
302
+ }
278
303
  renameSync(tmpPath, path);
279
304
  }
280
305
  catch (err) {
@@ -285,13 +310,25 @@ export function writeFileAtomic(path, content, mode) {
285
310
  throw err;
286
311
  }
287
312
  }
288
- /**
289
- * Write the admin password to `path` with mode 0600 from creation (flair#1573
290
- * slice a). The secret is written to a temp file in the same dir (0600) and
291
- * renamed into place, so it is never briefly world-readable.
292
- */
293
313
  export function writeAdminPassFile(path, content) {
294
- writeFileAtomic(path, content, 0o600);
314
+ let target;
315
+ try {
316
+ target = lstatSync(path);
317
+ }
318
+ catch (err) {
319
+ if (err.code !== "ENOENT")
320
+ throw err;
321
+ }
322
+ if (target) {
323
+ if (target.isSymbolicLink())
324
+ throw new Error(`Refusing to write admin password at ${path}: symbolic link`);
325
+ if (!target.isFile())
326
+ throw new Error(`Refusing to write admin password at ${path}: not a regular file`);
327
+ if (typeof process.getuid === "function" && target.uid !== process.getuid()) {
328
+ throw new Error(`Refusing to write admin password at ${path}: owned by another user`);
329
+ }
330
+ }
331
+ writeFileAtomic(path, content, 0o600, { exactMode: true });
295
332
  }
296
333
  /**
297
334
  * Which launchd label an existing installation for `dataDir` is actually
@@ -704,6 +741,27 @@ function readOpsPortFromConfig(path = configPath()) {
704
741
  catch { /* ignore */ }
705
742
  return null;
706
743
  }
744
+ /**
745
+ * The HTTP value treated as NAMED: a `--port` value accepted by the existing
746
+ * resolver, else the first `:digits` match in `FLAIR_URL` converted to a number;
747
+ * null when neither supplies one. These are the first two rungs of
748
+ * `resolveHttpPort`, which reads them through this function, so
749
+ * `resolveAgentHomeTarget` and `resolveHttpPort` agree on what was named.
750
+ */
751
+ function namedHttpPort(opts) {
752
+ if (opts.port !== undefined && opts.port !== null) {
753
+ const n = Number(opts.port);
754
+ if (!isNaN(n) && n > 0)
755
+ return n;
756
+ }
757
+ const envUrl = process.env.FLAIR_URL;
758
+ if (envUrl) {
759
+ const m = envUrl.match(/:(\d+)/);
760
+ if (m)
761
+ return Number(m[1]);
762
+ }
763
+ return null;
764
+ }
707
765
  /**
708
766
  * Unified port resolution: `--port` flag > `FLAIR_URL` env > Harper's own config
709
767
  * in the instance's data directory > (default install only) the per-user config
@@ -743,17 +801,9 @@ function readOpsPortFromConfig(path = configPath()) {
743
801
  * it is for the default install that has always relied on it.
744
802
  */
745
803
  function resolveHttpPort(opts, mode = "address") {
746
- if (opts.port !== undefined && opts.port !== null) {
747
- const n = Number(opts.port);
748
- if (!isNaN(n) && n > 0)
749
- return n;
750
- }
751
- const envUrl = process.env.FLAIR_URL;
752
- if (envUrl) {
753
- const m = envUrl.match(/:(\d+)/);
754
- if (m)
755
- return Number(m[1]);
756
- }
804
+ const named = namedHttpPort(opts);
805
+ if (named !== null)
806
+ return named;
757
807
  const dataDir = instanceDataDir(opts);
758
808
  // 1. Harper's own config for this instance. Once Harper has written one it is
759
809
  // the only answer — it is maintained by the process that binds the socket.
@@ -923,7 +973,13 @@ function applyAdminPassFile(opts) {
923
973
  process.exit(1);
924
974
  }
925
975
  }
926
- // Ops port resolution: --ops-port flag > FLAIR_OPS_PORT env > config opsPort > httpPort - 1
976
+ // Ops port resolution: valid --ops-port flag > FLAIR_OPS_PORT env > config opsPort > httpPort - 1.
977
+ // An explicit invalid --ops-port refuses; it never falls through to another rung.
978
+ //
979
+ // `httpPortBase` is the HTTP port the last rung derives from. A caller that
980
+ // already resolved the HTTP port — or, for `flair doctor`, probed the port it
981
+ // actually reached — passes it so that rung matches that port rather than
982
+ // re-resolving the configured one (flair#2562).
927
983
  //
928
984
  // Deliberately NOT routed through Harper's per-instance config the way
929
985
  // resolveHttpPort is (flair#914). The last rung couples the ops port to the HTTP
@@ -933,11 +989,14 @@ function applyAdminPassFile(opts) {
933
989
  // which is the bug flair#914 fixed pointing the other way. The ops port becomes
934
990
  // per-instance when the lifecycle commands grow `--data-dir` and there is a
935
991
  // named instance to attribute it to.
936
- function resolveOpsPort(opts) {
992
+ function resolveOpsPort(opts, httpPortBase) {
937
993
  if (opts.opsPort !== undefined && opts.opsPort !== null) {
938
994
  const n = Number(opts.opsPort);
939
- if (!isNaN(n) && n > 0)
995
+ if (Number.isInteger(n) && n >= 1 && n <= 65535)
940
996
  return n;
997
+ console.error(`Error: invalid --ops-port ${JSON.stringify(String(opts.opsPort))}. `
998
+ + "Pass an integer from 1 to 65535, or omit --ops-port to use FLAIR_OPS_PORT, local config, or the resolved HTTP port minus one.");
999
+ process.exit(1);
941
1000
  }
942
1001
  const envOps = process.env.FLAIR_OPS_PORT;
943
1002
  if (envOps)
@@ -954,7 +1013,246 @@ function resolveOpsPort(opts) {
954
1013
  }
955
1014
  catch { /* ignore */ }
956
1015
  // Default: httpPort - 1
957
- return resolveHttpPort(opts) - 1;
1016
+ return (httpPortBase ?? resolveHttpPort(opts)) - 1;
1017
+ }
1018
+ /** The named refusal for a configured-pair conflict or an unpaired one-sided target (flair#2474). */
1019
+ export const AMBIGUOUS_INSTANCE_TARGET_ERROR = "ambiguous_instance_target";
1020
+ /** The remedy appended to an {@link AMBIGUOUS_INSTANCE_TARGET_ERROR} refusal. */
1021
+ export const INSTANCE_TARGET_REMEDY = "Pass both ports (--port and --ops-port) for one instance.";
1022
+ /**
1023
+ * The pairing rule of {@link resolveAgentHomeTarget} (flair#2474).
1024
+ * With a COMPLETE configured pair (both ports recorded):
1025
+ * - an ops port that is not named is the pair's ops port;
1026
+ * - if exactly ONE of the two ports equals its side of the pair, the target is
1027
+ * REFUSED: the target conflicts with the configured pair;
1028
+ * - if both equal the pair, the pair is used; if NEITHER does, the ports are
1029
+ * used as given (from resolveAgentHomeTarget that happens only when the
1030
+ * caller named both, since a port it does not name is the pair's).
1031
+ *
1032
+ * With NO complete configured pair resolved (one side or both null):
1033
+ * - exactly one port named is REFUSED: its counterpart cannot be established
1034
+ * from a configured pair, so the two could address different instances;
1035
+ * - both named: used as given;
1036
+ * - neither named: the HTTP port as resolved and the ops port from `deriveOps`.
1037
+ *
1038
+ * Ports used "as given" are NOT VERIFIED: nothing here contacts an instance to
1039
+ * confirm that two named ports belong to one instance.
1040
+ */
1041
+ export function decideAgentHomeTarget(i) {
1042
+ const { httpPort, httpNamed, namedOps, configuredHttp, configuredOps } = i;
1043
+ const remedy = INSTANCE_TARGET_REMEDY;
1044
+ if (configuredHttp !== null && configuredOps !== null) {
1045
+ const opsPort = namedOps ?? configuredOps;
1046
+ const httpMatches = httpPort === configuredHttp;
1047
+ const opsMatches = opsPort === configuredOps;
1048
+ if (httpMatches !== opsMatches) {
1049
+ throw new Error(`${AMBIGUOUS_INSTANCE_TARGET_ERROR}: the target (HTTP port ${httpPort}, ops port ${opsPort}) conflicts with the configured pair — `
1050
+ + `the config pairs HTTP ${configuredHttp} with ops ${configuredOps}. ${remedy}`);
1051
+ }
1052
+ return { httpPort, opsPort };
1053
+ }
1054
+ const opsNamed = namedOps !== null;
1055
+ if (httpNamed !== opsNamed) {
1056
+ const [named, namedPort, other] = httpNamed ? ["HTTP", httpPort, "ops"] : ["ops", namedOps, "HTTP"];
1057
+ throw new Error(`${AMBIGUOUS_INSTANCE_TARGET_ERROR}: only the ${named} port (${namedPort}) was named, and no complete port pair could be resolved from config `
1058
+ + `(HTTP ${configuredHttp ?? "none"}, ops ${configuredOps ?? "none"}) to take the ${other} port from, so the two ports could address different instances. ${remedy}`);
1059
+ }
1060
+ if (namedOps !== null)
1061
+ return { httpPort, opsPort: namedOps };
1062
+ return { httpPort, opsPort: i.deriveOps() };
1063
+ }
1064
+ /**
1065
+ * The ports `flair agent stamp-home` and `flair principal add` address
1066
+ * (flair#2474). Each command talks to an ops API (stamp-home's roster read and
1067
+ * read-backs; principal add's stored-home reads and its insert) AND sends its
1068
+ * guarded PATCH to the Agent resource on the HTTP port. Resolving the two
1069
+ * INDEPENDENTLY — `resolveOpsPort(opts)` and `resolveHttpPort(opts)` — let
1070
+ * `--ops-port` name one instance and `--port` another, so the read landed on the
1071
+ * first and the write on the second.
1072
+ *
1073
+ * The configured pair is what the instance's config records: Harper's config in
1074
+ * its data directory records `http.port` and `operationsApi.network.port`; for
1075
+ * the default install, `~/.flair/config.yaml`'s `port`/`opsPort` supplies a side
1076
+ * Harper's config does not record. The pairing rule is
1077
+ * {@link decideAgentHomeTarget}: a port that matches its side of a COMPLETE
1078
+ * configured pair binds the other to that pair; a target with only ONE port
1079
+ * named is refused when no complete configured pair is resolved; two ports the
1080
+ * caller names that match neither side of a complete pair (or any two named
1081
+ * ports when there is no complete pair) are used as given, without
1082
+ * verification. Every refusal is `ambiguous_instance_target`.
1083
+ */
1084
+ export function resolveAgentHomeTarget(opts, httpPortOverride) {
1085
+ // `flair doctor` probes the port it actually reached (a PID-discovered
1086
+ // `effectivePort` can differ from the configured one), so it passes that port
1087
+ // here; every other caller lets the resolver resolve it. When neither port is
1088
+ // named and the config records no complete pair, `deriveOps` takes THIS port
1089
+ // as the base for its port-minus-one default, so the fallback matches the
1090
+ // port doctor reached rather than the configured one (flair#2562).
1091
+ const httpPort = httpPortOverride ?? resolveHttpPort(opts);
1092
+ const dataDir = instanceDataDir(opts);
1093
+ const fromHarper = harperPortValue(readHarperConfig(dataDir)?.operationsApi?.network?.port);
1094
+ const configuredOps = fromHarper ?? (isDefaultDataDir(dataDir) ? readOpsPortFromConfig() : null);
1095
+ const configuredHttp = readPortFromHarperConfig(dataDir) ?? (isDefaultDataDir(dataDir) ? readPortFromConfig() : null);
1096
+ let namedOps = null;
1097
+ if (opts.opsPort !== undefined && opts.opsPort !== null) {
1098
+ const n = Number(opts.opsPort);
1099
+ if (!(Number.isInteger(n) && n >= 1 && n <= 65535)) {
1100
+ // An invalid --ops-port is refused by resolveOpsPort, which exits.
1101
+ return { httpPort, opsPort: resolveOpsPort(opts) };
1102
+ }
1103
+ namedOps = n;
1104
+ }
1105
+ else if (process.env.FLAIR_OPS_PORT) {
1106
+ const n = Number(process.env.FLAIR_OPS_PORT);
1107
+ namedOps = Number.isInteger(n) && n >= 1 && n <= 65535 ? n : null;
1108
+ }
1109
+ return decideAgentHomeTarget({
1110
+ httpPort,
1111
+ httpNamed: namedHttpPort(opts) !== null,
1112
+ namedOps,
1113
+ configuredHttp,
1114
+ configuredOps,
1115
+ deriveOps: () => resolveOpsPort(opts, httpPort),
1116
+ });
1117
+ }
1118
+ /**
1119
+ * The remedy `flair doctor` prints when it cannot establish the pair check
1120
+ * between the HTTP port it probed and the ops endpoint (flair#2483): select the
1121
+ * actual instance's ports, or correct that instance's configuration and restart
1122
+ * it. Recording a pair that merely matches is not a remedy: configured ports
1123
+ * are not proof of the live process.
1124
+ */
1125
+ export const DOCTOR_ROSTER_TARGET_REMEDY = "Pass --port with the HTTP port of the instance to inspect, and unset FLAIR_OPS_PORT or set it to that instance's ops port; "
1126
+ + "if that instance's configuration records ports it does not serve, correct its configuration and restart it.";
1127
+ /**
1128
+ * The remedy `flair doctor` prints when the ops endpoint refuses its admin
1129
+ * credential, so the configuration check could not run (flair#2483).
1130
+ */
1131
+ export const DOCTOR_ROSTER_CREDENTIAL_REMEDY = "Check that the admin credential doctor reads (FLAIR_ADMIN_USER, and FLAIR_ADMIN_PASS or ~/.flair/admin-pass) "
1132
+ + "is the probed instance's, and unset or correct FLAIR_OPS_PORT if it is set.";
1133
+ /**
1134
+ * The candidate ops endpoint for `flair doctor`'s instance reads (flair#2483,
1135
+ * #2520), picked by {@link resolveAgentHomeTarget}'s pairing rule
1136
+ * (flair#2474/#2491) against the HTTP port doctor actually probed.
1137
+ *
1138
+ * This only picks the candidate: the pairing rule works from config and named
1139
+ * ports and cannot show which instance an ops port addresses — it DELIBERATELY
1140
+ * trusts two ports the caller names. Doctor therefore checks the candidate
1141
+ * before the reads ({@link verifyDoctorRosterInstance}). A refusal here (a
1142
+ * probed port that conflicts with the configured pair, or exactly one port
1143
+ * named with no complete pair to complete it) is likewise NOT RUN, naming the
1144
+ * reason and the remedy.
1145
+ */
1146
+ export function resolveDoctorRosterTarget(opts, probedHttpPort) {
1147
+ try {
1148
+ return { kind: "run", opsPort: resolveAgentHomeTarget(opts, probedHttpPort).opsPort };
1149
+ }
1150
+ catch (err) {
1151
+ const message = err instanceof Error ? err.message : String(err);
1152
+ // The resolver's refusal ends with the stamp-home-shaped remedy; doctor has
1153
+ // no --ops-port flag, so drop it and let the caller print doctor's own.
1154
+ const reason = message.endsWith(INSTANCE_TARGET_REMEDY)
1155
+ ? message.slice(0, -INSTANCE_TARGET_REMEDY.length).trimEnd()
1156
+ : message;
1157
+ return { kind: "not-run", reason, remedy: DOCTOR_ROSTER_TARGET_REMEDY };
1158
+ }
1159
+ }
1160
+ /**
1161
+ * Whether the candidate ops endpoint pairs with the HTTP port doctor probed
1162
+ * (flair#2483). `proof` is {@link proveLocalInstancePair}'s answer for
1163
+ * `opsPort`, the check the local delete paths use
1164
+ * (src/lib/local-delete-instance.ts): the configuration records `opsPort` as
1165
+ * its ops port and an HTTP port bound on loopback or on all interfaces, and the
1166
+ * OS listener table shows one process listening on both, with a recognized
1167
+ * Harper command line and the same pid and start time on two reads. This
1168
+ * decides `run` only when that configured HTTP port is `probedHttpPort`. An unproven
1169
+ * pair, or a proven one naming another HTTP port, is `not-run`, with the
1170
+ * proof's own remedy when it carries one.
1171
+ */
1172
+ export function decideDoctorRosterPair(opsPort, probedHttpPort, proof) {
1173
+ if (proof.kind === "unproven") {
1174
+ const credentialRefused = proof.status === 401 || proof.status === 403;
1175
+ return {
1176
+ kind: "not-run",
1177
+ reason: `the ops endpoint on port ${opsPort} did not prove a live HTTP/ops pair (${proof.detail}), so this check cannot be established for the probed HTTP port ${probedHttpPort}`,
1178
+ remedy: proof.remedy ?? (credentialRefused ? DOCTOR_ROSTER_CREDENTIAL_REMEDY : DOCTOR_ROSTER_TARGET_REMEDY),
1179
+ ...(credentialRefused ? { credentialRefused: true } : {}),
1180
+ };
1181
+ }
1182
+ if (proof.httpPort !== probedHttpPort) {
1183
+ return {
1184
+ kind: "not-run",
1185
+ reason: `the configured HTTP/ops pair does not match: the ops endpoint on port ${opsPort} is configured with HTTP port ${proof.httpPort}, not the probed HTTP port ${probedHttpPort}, so this check cannot be established`,
1186
+ remedy: DOCTOR_ROSTER_TARGET_REMEDY,
1187
+ };
1188
+ }
1189
+ return { kind: "run", opsPort };
1190
+ }
1191
+ /**
1192
+ * The instance-identity comparison behind doctor's instance reads
1193
+ * (flair#2483), applied only after {@link decideDoctorRosterPair} decided
1194
+ * `run`. When the probed HTTP port and the ops endpoint each report one
1195
+ * `flair.Instance` id and the two differ, they are two instances: `not-run`.
1196
+ * Every other identity outcome (equal ids, no row on either side as on a fresh
1197
+ * install, several rows, or an unread table) leaves the pair check's `run`
1198
+ * standing.
1199
+ */
1200
+ export function decideDoctorRosterIdentity(opsPort, pair) {
1201
+ if (pair.kind === "different") {
1202
+ return {
1203
+ kind: "not-run",
1204
+ reason: `the ops endpoint on port ${opsPort} is configured with the probed HTTP port, but the two report different instance identities, so they are not one instance`,
1205
+ remedy: DOCTOR_ROSTER_TARGET_REMEDY,
1206
+ };
1207
+ }
1208
+ return { kind: "run", opsPort };
1209
+ }
1210
+ /**
1211
+ * The ops endpoint `flair doctor` may read the probed instance from, or a
1212
+ * refusal naming why it may not (flair#2483).
1213
+ *
1214
+ * 1. Picks the candidate with {@link resolveDoctorRosterTarget} against the HTTP
1215
+ * port doctor actually probed (a PID-discovered port included).
1216
+ * 2. Asks the candidate for its configuration ({@link proveLocalInstancePair},
1217
+ * the check the local delete paths use) and requires it to record the
1218
+ * candidate as its ops port and the probed port as its HTTP port, bound on
1219
+ * loopback or on all interfaces, with the OS listener table showing one
1220
+ * process listening on both, with a recognized Harper command line and the
1221
+ * same pid and start time on two reads ({@link decideDoctorRosterPair}). No
1222
+ * Instance row is needed, so a fresh install passes.
1223
+ * 3. Only then compares the instance identities both endpoints report
1224
+ * ({@link decideDoctorRosterIdentity}): two different single ids refuse.
1225
+ *
1226
+ * Any `not-run` means doctor reports the sections that use this answer NOT
1227
+ * RUN, and their diagnostic reads do not run: all four section reads, unless a
1228
+ * `--fix` step that may have changed the serving process made the roster and
1229
+ * home sections ask again (the answer describes the process serving the probed
1230
+ * port when it was taken). Doctor also derives from it whether its later
1231
+ * diagnostic requests to the probed HTTP port may be sent (flair#2526); the
1232
+ * pair proof (step 2) precedes any credentialed HTTP request, and step 3's
1233
+ * Basic identity read on the HTTP port follows only a proven pair. Reaching a
1234
+ * `not-run` may itself have read the candidate's configuration (step 2) and
1235
+ * both endpoints' instance identities (step 3).
1236
+ * Step 2 sees only the listeners this CLI can see: one outside that view
1237
+ * (another network namespace or container, or a user this CLI may not
1238
+ * inspect), or a port held by a forwarder whose command line does not match
1239
+ * Harper's, is NOT RUN; step 3 adds a
1240
+ * check only when both endpoints have exactly one Instance row.
1241
+ */
1242
+ export async function verifyDoctorRosterInstance(opts, probedHttpPort, adminPass) {
1243
+ const candidate = resolveDoctorRosterTarget(opts, probedHttpPort);
1244
+ if (candidate.kind === "not-run")
1245
+ return candidate;
1246
+ const adminUser = resolveAdminUser(undefined);
1247
+ const authorization = `Basic ${Buffer.from(`${adminUser}:${adminPass}`).toString("base64")}`;
1248
+ const configured = decideDoctorRosterPair(candidate.opsPort, probedHttpPort, await proveLocalInstancePair(candidate.opsPort, authorization));
1249
+ if (configured.kind === "not-run")
1250
+ return configured;
1251
+ const [httpIdentity, opsIdentity] = await Promise.all([
1252
+ readHttpInstanceIdentity(`http://127.0.0.1:${probedHttpPort}`, adminUser, adminPass),
1253
+ resolveTargetInstanceIdentity(agentHomeEndpoint(candidate.opsPort, adminUser, adminPass)),
1254
+ ]);
1255
+ return decideDoctorRosterIdentity(candidate.opsPort, decideProbedPairIdentity(httpIdentity, opsIdentity));
958
1256
  }
959
1257
  // Ops API bind-host resolution (flair#670, #863): --ops-bind flag >
960
1258
  // FLAIR_OPS_BIND env > persisted `opsBind` in ~/.flair/config.yaml > loopback
@@ -1872,6 +2170,7 @@ async function api(method, path, body, options) {
1872
2170
  explicitAdminPass: options?.explicitAdminPass,
1873
2171
  adminUser: options?.adminUser,
1874
2172
  agentIdSource: options?.agentIdSource,
2173
+ signedOnly: options?.signedOnly,
1875
2174
  };
1876
2175
  try {
1877
2176
  return await authedRequest(method, path, body, requestOptions);
@@ -1945,12 +2244,13 @@ export async function verifyAuthedGet(baseUrl, path, keysDir) {
1945
2244
  export function isCredentialOnlyFailure(result) {
1946
2245
  return result.healthy === true && result.authFailureKind === "credentials";
1947
2246
  }
1948
- async function waitForHealth(httpPort, adminUser, adminPass, timeoutMs) {
2247
+ async function waitForHealth(httpPort, adminUser, adminPass, timeoutMs, beforeRequest) {
1949
2248
  const url = `http://127.0.0.1:${httpPort}/Health`;
1950
2249
  const deadline = Date.now() + timeoutMs;
1951
2250
  let attempt = 0;
1952
2251
  while (Date.now() < deadline) {
1953
2252
  attempt++;
2253
+ await beforeRequest?.();
1954
2254
  try {
1955
2255
  const res = await fetch(url, {
1956
2256
  headers: { Authorization: `Basic ${Buffer.from(`${adminUser}:${adminPass}`).toString("base64")}` },
@@ -2068,7 +2368,7 @@ export async function verifySemanticSearch(baseUrl, agentIdOpt, keysDir) {
2068
2368
  let stored = false;
2069
2369
  try {
2070
2370
  // Write the test memory (ephemeral so it's never durable). PUT /Memory/<id>.
2071
- const writeRes = await authFetch(baseUrl, agentId, keyPath, "PUT", `/Memory/${id}`, {
2371
+ const writeRes = await authFetch(baseUrl, agentId, keyPath, "PUT", `/Memory/${encodeRecordId(id)}`, {
2072
2372
  id, agentId, content, durability: "ephemeral", createdAt: new Date().toISOString(),
2073
2373
  });
2074
2374
  if (!writeRes.ok && writeRes.status !== 204) {
@@ -2134,7 +2434,7 @@ export async function verifySemanticSearch(baseUrl, agentIdOpt, keysDir) {
2134
2434
  // Best-effort cleanup of the ephemeral probe memory.
2135
2435
  if (stored) {
2136
2436
  try {
2137
- await authFetch(baseUrl, agentId, keyPath, "DELETE", `/Memory/${id}`);
2437
+ await authFetch(baseUrl, agentId, keyPath, "DELETE", `/Memory/${encodeRecordId(id)}`);
2138
2438
  }
2139
2439
  catch { /* leave the ephemeral row; it'll age out */ }
2140
2440
  }
@@ -2193,7 +2493,7 @@ export async function verifyAuditLog(baseUrl, agentIdOpt, keysDir, opsUrl, admin
2193
2493
  };
2194
2494
  }
2195
2495
  const id = `flair-doctor-audit-probe-${randomUUID()}`;
2196
- const path = `/Memory/${id}`;
2496
+ const path = `/Memory/${encodeRecordId(id)}`;
2197
2497
  let stored = false;
2198
2498
  try {
2199
2499
  // Write 1: PUT the probe row. Ephemeral durability — TTL is the cleanup
@@ -2368,7 +2668,7 @@ export async function checkAgentRegistered(baseUrl, agentId, keysDir) {
2368
2668
  return { state: "no-key", detail: `no local key for agent '${agentId}' to sign the check` };
2369
2669
  }
2370
2670
  try {
2371
- const res = await authFetch(baseUrl, agentId, keyPath, "GET", `/Agent/${agentId}`);
2671
+ const res = await authFetch(baseUrl, agentId, keyPath, "GET", `/Agent/${encodeRecordId(agentId)}`);
2372
2672
  if (res.ok)
2373
2673
  return { state: "registered" };
2374
2674
  if (res.status === 404)
@@ -2391,10 +2691,6 @@ export async function checkAgentRegistered(baseUrl, agentId, keysDir) {
2391
2691
  return { state: "unreachable", detail: `instance unreachable: ${message.slice(0, 100)}` };
2392
2692
  }
2393
2693
  }
2394
- // Blocks until the given PID is gone (ESRCH from signal 0), or timeout.
2395
- // Used during restart to confirm the old Harper process actually exited before
2396
- // we start polling /Health — otherwise the still-shutting-down old process can
2397
- // answer and we'd declare restart success while a gap is still ahead.
2398
2694
  /**
2399
2695
  * Is `pid` a process that exists right now? Signal 0 performs the permission
2400
2696
  * and existence checks without delivering anything (flair#1022) — a `hdb.pid`
@@ -2410,16 +2706,19 @@ function isProcessAlive(pid) {
2410
2706
  return false;
2411
2707
  }
2412
2708
  }
2413
- async function waitForProcessExit(pid, timeoutMs) {
2709
+ // Used during restart to confirm the old Harper process actually exited before
2710
+ // we start polling /Health — otherwise the still-shutting-down old process can
2711
+ // answer and we'd declare restart success while a gap is still ahead.
2712
+ // Cap sleeps at the remaining time; probe once after the last wake, then stop (flair#2357).
2713
+ export async function waitForProcessExit(pid, timeoutMs, probe = probePidLiveness) {
2414
2714
  const deadline = Date.now() + timeoutMs;
2415
- while (Date.now() < deadline) {
2416
- try {
2417
- process.kill(pid, 0);
2418
- }
2419
- catch {
2715
+ while (true) {
2716
+ if (probe(pid).kind === "gone")
2420
2717
  return;
2421
- }
2422
- await new Promise((r) => setTimeout(r, HEALTH_POLL_INTERVAL_MS));
2718
+ const remaining = deadline - Date.now();
2719
+ if (remaining <= 0)
2720
+ break;
2721
+ await new Promise((r) => setTimeout(r, Math.min(HEALTH_POLL_INTERVAL_MS, remaining)));
2423
2722
  }
2424
2723
  throw new Error(`Process ${pid} did not exit within ${timeoutMs}ms`);
2425
2724
  }
@@ -2618,7 +2917,21 @@ export async function seedAgentViaOpsApi(opsPortOrUrl, agentId, pubKeyB64url, ad
2618
2917
  * data directory does not prove the passwords differ, and the HTTP holder
2619
2918
  * is not assumed to be the process that rejected this request.
2620
2919
  */
2621
- occupiedListener) {
2920
+ occupiedListener,
2921
+ /**
2922
+ * The target instance's own federation id, resolved by the caller through
2923
+ * the rule in src/lib/agent-home.ts. When supplied (including an explicit
2924
+ * null), the new Agent row carries it as its home (`originatorInstanceId`),
2925
+ * and the create ignores any other source. When omitted, the field is left
2926
+ * off the row.
2927
+ */
2928
+ homeInstanceId) {
2929
+ // flair#2359 — the ONE agent-ID rule, before the operations-API insert. This
2930
+ // is the write path for `flair agent add`, `flair import` and `flair init`,
2931
+ // so a caller-supplied id is refused here by name before any HTTP call.
2932
+ if (!isValidAgentId(agentId)) {
2933
+ throw new Error(invalidAgentIdMessage(agentId));
2934
+ }
2622
2935
  const url = typeof opsPortOrUrl === "number"
2623
2936
  ? `http://127.0.0.1:${opsPortOrUrl}/`
2624
2937
  : `${opsPortOrUrl.replace(/\/$/, "")}/`;
@@ -2631,23 +2944,30 @@ occupiedListener) {
2631
2944
  // and is invisible to roster/presence/Office-Space queries that filter on
2632
2945
  // status='active' or kind='agent' (#521). Mirror Agent.post() exactly here.
2633
2946
  const now = new Date().toISOString();
2947
+ const record = {
2948
+ id: agentId,
2949
+ name: agentId,
2950
+ type: "agent",
2951
+ kind: "agent",
2952
+ status: "active",
2953
+ displayName: agentId,
2954
+ admin: false,
2955
+ defaultTrustTier: "unverified",
2956
+ publicKey: pubKeyB64url,
2957
+ createdAt: now,
2958
+ updatedAt: now,
2959
+ };
2960
+ // flair#2433 — the new row's home is the creating instance's id. A create
2961
+ // stamps it and ignores anything else; the caller passes the id it resolved
2962
+ // through the one shared rule (src/lib/agent-home.ts). An omitted id leaves the
2963
+ // field off (the pre-fix shape, for callers that do not stamp).
2964
+ if (homeInstanceId !== undefined)
2965
+ stampAgentHome(record, homeInstanceId);
2634
2966
  const body = {
2635
2967
  operation: "insert",
2636
2968
  database: "flair",
2637
2969
  table: "Agent",
2638
- records: [{
2639
- id: agentId,
2640
- name: agentId,
2641
- type: "agent",
2642
- kind: "agent",
2643
- status: "active",
2644
- displayName: agentId,
2645
- admin: false,
2646
- defaultTrustTier: "unverified",
2647
- publicKey: pubKeyB64url,
2648
- createdAt: now,
2649
- updatedAt: now,
2650
- }],
2970
+ records: [record],
2651
2971
  };
2652
2972
  await opsSeedInsertWithRetry({
2653
2973
  url,
@@ -2666,7 +2986,7 @@ occupiedListener) {
2666
2986
  after = occupiedListener.reread();
2667
2987
  }
2668
2988
  catch {
2669
- after = { port: occupiedListener.before.port, pids: [], dataDirs: [] };
2989
+ after = { port: occupiedListener.before.port, pids: [], dataDirs: [], pidsKnown: false };
2670
2990
  }
2671
2991
  return occupiedListenerAuthFailure({
2672
2992
  lead: "Operations API insert failed (401): ",
@@ -2683,6 +3003,18 @@ occupiedListener) {
2683
3003
  // ops-insert body to the REST root, which Harper 405s as a collection POST to
2684
3004
  // /Agent (the Agent table resource has no POST handler). It was removed in the
2685
3005
  // #499 fix; do not reintroduce a REST-root insert path.
3006
+ /**
3007
+ * Seed an agent through the ops API, stamping the TARGET instance's own
3008
+ * federation id as the new row's home (flair#2433). The id is resolved through
3009
+ * the one shared rule (src/lib/agent-home.ts, over the same
3010
+ * src/lib/instance-identity-row.ts decision the server uses), so this path
3011
+ * cannot disagree with the Agent resource's own stamp. A null id (no single
3012
+ * Instance row) writes an explicit null — the defined local-origin state.
3013
+ */
3014
+ export async function seedAgentWithLocalHome(opsPortOrUrl, agentId, pubKeyB64url, adminUser, adminPass, occupiedListener) {
3015
+ const home = await resolveTargetInstanceId(agentHomeEndpoint(opsPortOrUrl, adminUser, adminPass));
3016
+ await seedAgentViaOpsApi(opsPortOrUrl, agentId, pubKeyB64url, adminUser, adminPass, occupiedListener, home);
3017
+ }
2686
3018
  // ─── FederationInstance seed via ops API ──────────────────────────────────────
2687
3019
  //
2688
3020
  // Remote init writes FederationInstance through the ops API (Basic auth with
@@ -3034,6 +3366,18 @@ const PAIR_INITIATOR_PERMISSION = {
3034
3366
  super_user: false,
3035
3367
  structure_user: false,
3036
3368
  };
3369
+ /**
3370
+ * The `id` that `alter_role` addresses a role by. `list_roles` answers with each
3371
+ * role's `id`, and Harper 5.2.8 rejects an `alter_role` that omits it ("Id can't
3372
+ * be blank").
3373
+ */
3374
+ function alterRoleId(roleName, existing) {
3375
+ const id = existing?.id;
3376
+ if (typeof id !== "string" || id.length === 0) {
3377
+ throw new Error(`alter_role for '${roleName}': list_roles returned no id for the role`);
3378
+ }
3379
+ return id;
3380
+ }
3037
3381
  /**
3038
3382
  * Idempotently ensures the `flair_pair_initiator` role exists on the Harper
3039
3383
  * instance at `opsUrl` with the canonical permission spec.
@@ -3078,6 +3422,7 @@ export async function ensureFlairPairInitiatorRole(opsUrl, adminUser, adminPass)
3078
3422
  console.log(`Role '${ROLE_NAME}' exists but permissions differ — updating...`);
3079
3423
  await callOpsApi(opsUrl, {
3080
3424
  operation: "alter_role",
3425
+ id: alterRoleId(ROLE_NAME, existing),
3081
3426
  role: ROLE_NAME,
3082
3427
  permission: PAIR_INITIATOR_PERMISSION,
3083
3428
  }, adminUser, adminPass);
@@ -3085,102 +3430,8 @@ export async function ensureFlairPairInitiatorRole(opsUrl, adminUser, adminPass)
3085
3430
  }
3086
3431
  // ─── flair_agent role ────────────────────────────────────────────────────────
3087
3432
  //
3088
- // The auth reshape replaces the global gate's "verified agent borrows admin
3089
- // super_user" elevation with a real, least-privilege Harper role. After an
3090
- // agent's Ed25519 signature verifies, resources resolve the request to the
3091
- // shared `flair_agent`-roled user instead of admin — so agents get exactly the
3092
- // table CRUD below and nothing more. Critically: with no `super_user` and no
3093
- // operations grants, /sql and /graphql become NATIVELY 403 for agents (the
3094
- // raw-query block the gate hand-rolled is now enforced by Harper itself).
3095
- //
3096
- // Row-level ownership (an agent touches only its OWN memories/soul/events) is
3097
- // NOT expressible in Harper's role model — it stays in each resource's allow*,
3098
- // keyed on the Ed25519-verified agentId. So these per-table grants are the
3099
- // coarse CRUD envelope; allow* is the ownership boundary inside it.
3100
- //
3101
- // VALIDATION GATES (must confirm against a live Harper before this role goes
3102
- // live — flagged for Sherlock + the PR, not assumed):
3103
- // 1. HNSW/vector search (SemanticSearch over Memory) works with table `read`
3104
- // alone — the old elevation comment claimed admin perms were needed for
3105
- // "HNSW-capable" access; confirm `read` suffices or widen precisely.
3106
- // 2. Role table keys must EXACTLY match the @table names (Memory, OrgEvent,
3107
- // WorkspaceState, OAuthClient — NOT the logical Memory/Event/Workspace/OAuth
3108
- // shorthand the flair_pair_initiator spec used, which was harmless only
3109
- // because every grant there is false).
3110
- // Harper 5.0.21 add_role requires an `attribute_permissions` array on EVERY table
3111
- // grant (empty = no attribute-level restriction, so the table-level CRUD applies);
3112
- // omitting it makes add_role reject the whole spec ("Missing 'attribute_permissions'
3113
- // array"). Validated live against a spawned Harper. This helper guarantees the
3114
- // array is never forgotten. Also: `cluster_user` is NOT a valid top-level key —
3115
- // Harper reads unrecognized top-level keys as database names ("database
3116
- // 'cluster_user' does not exist"); only super_user / structure_user are recognized.
3117
- const grant = (read, insert, update, del) => ({ read, insert, update, delete: del, attribute_permissions: [] });
3118
- /** Canonical permission spec for flair_agent (least-privilege; real @table names). */
3119
- const FLAIR_AGENT_PERMISSION = {
3120
- super_user: false,
3121
- structure_user: false,
3122
- flair: {
3123
- tables: {
3124
- // Core agent-owned data — CRUD envelope; ownership enforced in allow*.
3125
- Memory: grant(true, true, true, true),
3126
- MemoryCandidate: grant(true, true, true, true),
3127
- MemoryGrant: grant(true, true, true, true),
3128
- // Asset (images-in-Flair slice 1). Harper authorizes BEFORE Asset.post
3129
- // runs, so a de-elevated flair_agent needs the table grant or signed
3130
- // POST /Asset 403s as AccessViolation (Kern P0). CRUD envelope;
3131
- // owner-only + write-time size/MIME gates live in resources/Asset.ts.
3132
- Asset: grant(true, true, true, true),
3133
- Soul: grant(true, true, true, false),
3134
- OrgEvent: grant(true, true, true, true),
3135
- WorkspaceState: grant(true, true, true, true),
3136
- Relationship: grant(true, true, true, true),
3137
- // Flair Relay S1 (flair#1521). Harper authorizes BEFORE the resource
3138
- // methods run, so a de-elevated flair_agent needs the table grant OR it
3139
- // 403s on POST /Message before relaySend is reached (Kern P0-2). read =
3140
- // the party-scoped collection (Message.search); insert = send via post().
3141
- // update = FALSE (least privilege, Kern P0 blocker): the ack's write goes
3142
- // through the IN-PROCESS static accessor (relayConsume → deps.messages.put),
3143
- // which bypasses role gates entirely — the same raw-put seam Federation.ts
3144
- // relies on — so update:true is NOT needed for any legitimate path. Leaving
3145
- // it granted let PATCH /Message/<id> reach Table's update verb, whose
3146
- // authorize step consults update:true and PASSES for any de-elevated agent,
3147
- // bypassing Message.put()'s FORBIDDEN guard AND relayConsume's recipient-only
3148
- // check (Message has no patch() at the platform level → TableResource.patch
3149
- // runs update()+save() directly). delete = false: direct deletes are
3150
- // admin/internal only. Message.patch() also guards the verb in-resource.
3151
- Message: grant(true, true, false, false),
3152
- Integration: grant(true, true, true, true),
3153
- Credential: grant(true, true, true, true),
3154
- Presence: grant(true, true, true, false),
3155
- // MemoryUsage (flair#683): the usage-feedback dedup ledger. Read (own
3156
- // contributions, scoped in resources/MemoryUsage.ts) + insert (a fresh
3157
- // contribution row) only — NO update/delete. This is load-bearing, not
3158
- // just least-privilege tidiness: the dedup rule ("(agent, memory)
3159
- // contributes ≤ 1") is enforced by requiring a NEW ledger row before
3160
- // any usageCount bump; if an agent could delete its own row, it could
3161
- // re-trigger the /RecordUsage endpoint for the same memory indefinitely
3162
- // (create → count → delete → count again → repeat), defeating the cap
3163
- // entirely. See resources/MemoryUsage.ts's module doc.
3164
- MemoryUsage: grant(true, true, false, false),
3165
- // MemoryHitStat (flair#1528): internal search-hit ledger. No agent REST
3166
- // surface (@table without @export). Counts overlay onto Memory reads.
3167
- MemoryHitStat: grant(false, false, false, false),
3168
- // Agent: read for discovery, update own card; creation/removal is admin.
3169
- Agent: grant(true, false, true, false),
3170
- // Read-only reference data.
3171
- Instance: grant(true, false, false, false),
3172
- // Federation / OAuth / IdP / internal — system + admin only; agents get none.
3173
- Peer: grant(false, false, false, false),
3174
- PairingToken: grant(false, false, false, false),
3175
- SyncLog: grant(false, false, false, false),
3176
- OAuthClient: grant(false, false, false, false),
3177
- OAuthToken: grant(false, false, false, false),
3178
- OAuthAuthCode: grant(false, false, false, false),
3179
- IdpConfig: grant(false, false, false, false),
3180
- IdJagReplay: grant(false, false, false, false),
3181
- },
3182
- },
3183
- };
3433
+ // The grant spec (FLAIR_AGENT_PERMISSION) lives in src/lib/flair-agent-role.ts,
3434
+ // shared with the server's startup check (resources/flair-agent-role-boot.ts).
3184
3435
  /**
3185
3436
  * Idempotently ensures the `flair_agent` role exists on the Harper instance at
3186
3437
  * `opsUrl` with the canonical least-privilege spec. Same list/add/alter shape as
@@ -3222,6 +3473,7 @@ export async function ensureFlairAgentRole(opsUrl, adminUser, adminPass) {
3222
3473
  console.log(`Role '${ROLE_NAME}' exists but permissions differ — updating...`);
3223
3474
  await callOpsApi(opsUrl, {
3224
3475
  operation: "alter_role",
3476
+ id: alterRoleId(ROLE_NAME, existing),
3225
3477
  role: ROLE_NAME,
3226
3478
  permission: FLAIR_AGENT_PERMISSION,
3227
3479
  }, adminUser, adminPass);
@@ -3728,6 +3980,7 @@ bindInitCli({
3728
3980
  repointMainServiceUnit,
3729
3981
  resolveHttpPort,
3730
3982
  writeAdminPassFile,
3983
+ proveAdminPassAgainstInstance,
3731
3984
  resolveOpsBindHost,
3732
3985
  resolveHttpBindFor,
3733
3986
  resolveOpsPort,
@@ -3736,14 +3989,17 @@ bindInitCli({
3736
3989
  resolveTarget,
3737
3990
  runSoulWizard,
3738
3991
  seedAgentViaOpsApi,
3992
+ seedAgentWithLocalHome,
3739
3993
  seedFederationInstanceViaOpsApi,
3740
3994
  readOccupiedListener,
3995
+ resolveInstanceServingPid,
3741
3996
  shouldShowInlineSecretWarning,
3742
3997
  verifyAuditLog,
3743
3998
  verifySemanticSearch,
3744
3999
  waitForHealth,
3745
4000
  writeDaemonSidecar,
3746
4001
  registerInitLaunchdService,
4002
+ initLaunchdExitCode,
3747
4003
  MQTT_DISABLED_CONFIG,
3748
4004
  STARTUP_TIMEOUT_MS,
3749
4005
  });
@@ -3759,8 +4015,10 @@ bindAgentCli({
3759
4015
  shouldShowInlineSecretWarning,
3760
4016
  resolveHttpPort,
3761
4017
  resolveOpsPort,
4018
+ resolveAgentHomeTarget,
3762
4019
  resolveEffectiveOpsUrl,
3763
4020
  seedAgentViaOpsApi,
4021
+ seedAgentWithLocalHome,
3764
4022
  agentRecordIsAdmin,
3765
4023
  });
3766
4024
  registerAgent(program);
@@ -3771,6 +4029,9 @@ bindKeysCli({
3771
4029
  checkAgentRegistered,
3772
4030
  probeFlairReachable,
3773
4031
  resolveBaseUrl,
4032
+ resolveOpsPort,
4033
+ resolveHttpPort,
4034
+ readPortFromHarperConfig,
3774
4035
  });
3775
4036
  registerKeys(program);
3776
4037
  // ─── flair hook ──────────────────────────────────────────────────────────────
@@ -3800,6 +4061,8 @@ bindPrincipalCli({
3800
4061
  pubKeyPath,
3801
4062
  relativeTime,
3802
4063
  resolveOpsPort,
4064
+ resolveHttpPort,
4065
+ resolveAgentHomeTarget,
3803
4066
  });
3804
4067
  registerPrincipal(program);
3805
4068
  // ─── flair idp ───────────────────────────────────────────────────────────────
@@ -3819,6 +4082,14 @@ bindGrantCli({
3819
4082
  resolveAdminUser,
3820
4083
  });
3821
4084
  registerGrant(program);
4085
+ // ─── flair integrity ──────────────────────────────────────────────────────────
4086
+ // Command group lives in src/commands/integrity.ts (flair#2213). Bind shared
4087
+ // helpers first so the extracted module never imports this file.
4088
+ bindIntegrityCli({
4089
+ resolveOpsPort,
4090
+ resolveAdminUser,
4091
+ });
4092
+ registerIntegrity(program);
3822
4093
  // ─── flair federation ────────────────────────────────────────────────────────
3823
4094
  // Command group lives in src/commands/federation.ts (flair#1620). Bind shared
3824
4095
  // helpers first so the extracted module never imports this file.
@@ -4127,11 +4398,61 @@ export function readSidecar(dataDir) {
4127
4398
  }
4128
4399
  return { kind: "present", ...parsed };
4129
4400
  }
4130
- /** `kill(pid, 0)` as a four-way: alive / gone (ESRCH) / eperm (another user's) / unknown. */
4131
- function probePidLiveness(pid) {
4401
+ export const DARWIN_STATE_READ_TIMEOUT_MS = 5_000;
4402
+ const DARWIN_STATE_READ_MIN_MS = 1_000;
4403
+ function readDarwinProcessState(pid, timeoutMs, onReadError) {
4404
+ try {
4405
+ const out = execFileSync("/bin/ps", ["-o", "stat=", "-p", String(pid)], {
4406
+ encoding: "utf-8",
4407
+ env: { ...process.env, LC_ALL: "C" },
4408
+ timeout: timeoutMs,
4409
+ killSignal: "SIGKILL",
4410
+ stdio: ["ignore", "pipe", "ignore"],
4411
+ }).trim();
4412
+ return out.length > 0 ? out[0] : null;
4413
+ }
4414
+ catch (error) {
4415
+ onReadError?.(error, timeoutMs);
4416
+ return null;
4417
+ }
4418
+ }
4419
+ /**
4420
+ * The kernel's state character for an existing pid, or null when it cannot be
4421
+ * read (flair#2313). Linux reads field 3 of `/proc/<pid>/stat`; Darwin reads the
4422
+ * first character of `/bin/ps -o stat=` (flair#2330). A read failure returns
4423
+ * null — the caller treats that as "not exited", never as exited (fail safe).
4424
+ */
4425
+ function readProcessState(pid, timeoutMs, onReadError) {
4426
+ if (process.platform === "linux") {
4427
+ try {
4428
+ return parseProcStatState(readFileSync(`/proc/${pid}/stat`, "utf-8"));
4429
+ }
4430
+ catch {
4431
+ return null;
4432
+ }
4433
+ }
4434
+ if (process.platform === "darwin")
4435
+ return readDarwinProcessState(pid, timeoutMs, onReadError);
4436
+ return null;
4437
+ }
4438
+ /**
4439
+ * Process liveness: alive / gone (ESRCH or zombie) / eperm (another user's) /
4440
+ * unknown.
4441
+ *
4442
+ * Signal 0 says the pid EXISTS, which is not the same as running: an exited
4443
+ * child whose parent has not reaped it is a zombie (state `Z`, `<defunct>`) that
4444
+ * still answers signal 0. After the signal-0 probe succeeds, read the process
4445
+ * state and report a zombie as `gone`, so `flair doctor`'s stop wait stops
4446
+ * waiting on a process that has already exited (flair#2313). An unreadable
4447
+ * state stays `alive` — a read failure must never report a live process as
4448
+ * exited.
4449
+ *
4450
+ * The state reader is injectable so the unreadable and retried branches are
4451
+ * unit-testable without a real unreadable process.
4452
+ */
4453
+ export function probePidLiveness(pid, readState = readProcessState, deadlineMs = Infinity, onReadError) {
4132
4454
  try {
4133
4455
  process.kill(pid, 0);
4134
- return { kind: "alive" };
4135
4456
  }
4136
4457
  catch (err) {
4137
4458
  // `gone` ONLY for ESRCH. Any other errno (EINVAL, EACCES, ...) is `unknown`,
@@ -4139,15 +4460,56 @@ function probePidLiveness(pid) {
4139
4460
  // classifier's unknown state (flair#2055).
4140
4461
  return livenessFromKillError(err?.code);
4141
4462
  }
4463
+ let state = null;
4464
+ for (let attempt = 0; attempt < 2; attempt++) {
4465
+ const remainingMs = deadlineMs - Date.now();
4466
+ if (remainingMs <= 0)
4467
+ break;
4468
+ const timeoutMs = Math.min(DARWIN_STATE_READ_TIMEOUT_MS, Math.max(DARWIN_STATE_READ_MIN_MS, remainingMs));
4469
+ state = readState(pid, timeoutMs, onReadError);
4470
+ if (state !== null)
4471
+ break;
4472
+ }
4473
+ return isExitedState(state) ? { kind: "gone" } : { kind: "alive" };
4474
+ }
4475
+ /**
4476
+ * Poll the process-liveness probe for `pid` until it reports `gone` or
4477
+ * `deadlineMs` passes; return whether `gone` was read and the last read
4478
+ * (flair#2330). This is `flair doctor`'s stop wait.
4479
+ *
4480
+ * If both state reads fail, that poll stays `alive`.
4481
+ * Check expiry before each read; an admitted read gets at least 1s to finish.
4482
+ * Readers honoring their timeout allow deadline + 1s, plus scheduling and subprocess overhead.
4483
+ */
4484
+ export async function waitForPidGone(pid, deadlineMs, readState = readProcessState, pollMs = HEALTH_POLL_INTERVAL_MS, onReadError) {
4485
+ let last = { kind: "unknown", reason: "the stop deadline passed before a probe" };
4486
+ while (Date.now() < deadlineMs) {
4487
+ last = probePidLiveness(pid, readState, deadlineMs, onReadError);
4488
+ if (last.kind === "gone")
4489
+ return { gone: true, last };
4490
+ if (Date.now() >= deadlineMs)
4491
+ return { gone: false, last };
4492
+ const remaining = deadlineMs - Date.now();
4493
+ if (remaining <= 0)
4494
+ break;
4495
+ await new Promise((r) => setTimeout(r, Math.min(pollMs, remaining)));
4496
+ }
4497
+ return { gone: false, last };
4142
4498
  }
4143
4499
  /**
4144
4500
  * The health probe (flair#1478): ok only when the response is 2xx AND the
4145
4501
  * body is flair's /Health shape. A decoy that answers 200 is `foreign`,
4146
4502
  * not healed.
4503
+ *
4504
+ * flair#2485: the probe answers only for the port it probed. `redirect:
4505
+ * "manual"` stops it following a 3xx — a redirect from this port is a
4506
+ * response that is not a Flair health answer (`foreign`), so a port that
4507
+ * merely forwards elsewhere is never reported as ours (a followed redirect
4508
+ * could land on a Flair instance on another port and pass the fingerprint).
4147
4509
  */
4148
4510
  async function probeHealth(port) {
4149
4511
  try {
4150
- const res = await fetch(`http://127.0.0.1:${port}/Health`, { signal: AbortSignal.timeout(2000) });
4512
+ const res = await fetch(`http://127.0.0.1:${port}/Health`, { redirect: "manual", signal: AbortSignal.timeout(2000) });
4151
4513
  let body;
4152
4514
  try {
4153
4515
  body = await res.json();
@@ -4158,12 +4520,56 @@ async function probeHealth(port) {
4158
4520
  return classifyHealthProbe({ kind: "response", status: res.status, body });
4159
4521
  }
4160
4522
  catch (err) {
4161
- // Node's undici fetch reports ECONNREFUSED on `err.cause.code`; Bun reports
4162
- // `ConnectionRefused` on `err.code`. Both mean "nothing is listening".
4163
4523
  const code = err?.cause?.code ?? err?.code;
4164
4524
  return classifyHealthProbe({ kind: "network-error", code });
4165
4525
  }
4166
4526
  }
4527
+ /**
4528
+ * The adopt stop path's port-free probe (stopDirectProcessForAdopt). It
4529
+ * classifies the response with classifyHealthProbe, as probeHealth does, and
4530
+ * returns `unreachable` after 2 s or at `deadline`, whichever comes first.
4531
+ * Exported for tests.
4532
+ *
4533
+ * flair#2485: like probeHealth, it answers only for the port it probed —
4534
+ * `redirect: "manual"` stops it following a 3xx, so a redirect from this port
4535
+ * is a response that is not a Flair health answer (`foreign`).
4536
+ */
4537
+ export async function probeHealthBeforeDeadline(port, deadline) {
4538
+ const timeoutMs = Math.min(2000, deadline - Date.now());
4539
+ if (timeoutMs <= 0)
4540
+ return { kind: "unreachable" };
4541
+ const controller = new AbortController();
4542
+ let timer;
4543
+ const timeout = new Promise((resolve) => {
4544
+ timer = setTimeout(() => {
4545
+ controller.abort();
4546
+ resolve({ kind: "unreachable" });
4547
+ }, timeoutMs);
4548
+ });
4549
+ const observe = async () => {
4550
+ try {
4551
+ const res = await fetch(`http://127.0.0.1:${port}/Health`, { redirect: "manual", signal: controller.signal });
4552
+ let body;
4553
+ try {
4554
+ body = await res.json();
4555
+ }
4556
+ catch {
4557
+ body = null;
4558
+ }
4559
+ return classifyHealthProbe({ kind: "response", status: res.status, body });
4560
+ }
4561
+ catch (err) {
4562
+ const code = err?.cause?.code ?? err?.code;
4563
+ return classifyHealthProbe({ kind: "network-error", code });
4564
+ }
4565
+ };
4566
+ try {
4567
+ return await Promise.race([observe(), timeout]);
4568
+ }
4569
+ finally {
4570
+ clearTimeout(timer);
4571
+ }
4572
+ }
4167
4573
  /**
4168
4574
  * PIDs LISTENING on `port` via `lsof -ti :<port> -sTCP:LISTEN`, or null
4169
4575
  * when lsof is absent / unusable. Empty array means lsof ran and saw no
@@ -4251,12 +4657,22 @@ function inspectServingFlairPackage(pid) {
4251
4657
  return null;
4252
4658
  return resolveServingFlairPackage(pid) !== null;
4253
4659
  }
4254
- /** Gather every piece of evidence the classifier needs, in one place. */
4255
- export async function gatherDaemonEvidence(port, dataDir) {
4660
+ export function gatherDaemonOwnerEvidence(dataDir) {
4256
4661
  const dataDirUnsafe = checkDataDirSafe(dataDir);
4257
4662
  const pidfile = readPidfile(dataDir);
4258
- const pidLiveness = pidfile.kind === "present" ? probePidLiveness(pidfile.pid) : null;
4259
- let sidecar = readSidecar(dataDir);
4663
+ const sidecar = readSidecar(dataDir);
4664
+ const sidecarLiveness = sidecar.kind === "present" ? probePidLiveness(sidecar.pid) : null;
4665
+ const lastKnownPid = pidfile.kind === "absent" && sidecar.kind === "present" ? sidecar.pid : undefined;
4666
+ const pidLiveness = pidfile.kind === "present" ? probePidLiveness(pidfile.pid)
4667
+ : lastKnownPid !== undefined ? probePidLiveness(lastKnownPid)
4668
+ : pidfile.kind === "absent" && sidecar.kind === "unreadable" ? { kind: "unknown", reason: sidecar.reason } : null;
4669
+ return { dataDirUnsafe, pidfile, lastKnownPid, pidLiveness, sidecar, sidecarLiveness };
4670
+ }
4671
+ /** Gather every piece of evidence the classifier needs, in one place. */
4672
+ export async function gatherDaemonEvidence(port, dataDir) {
4673
+ const owner = gatherDaemonOwnerEvidence(dataDir);
4674
+ const { dataDirUnsafe, pidfile, lastKnownPid, pidLiveness, sidecarLiveness } = owner;
4675
+ let sidecar = owner.sidecar;
4260
4676
  // flair#2055: a sidecar that names a pid which is CONFIRMED gone is STALE, not
4261
4677
  // a disagreement with hdb.pid. After `flair stop` ended a directly started
4262
4678
  // Harper, the sidecar it wrote still names the stopped pid; a later instance
@@ -4268,7 +4684,7 @@ export async function gatherDaemonEvidence(port, dataDir) {
4268
4684
  // Liveness that cannot be determined is NOT stale: the sidecar stays and the
4269
4685
  // refusal stands (unknown evidence never licenses an action).
4270
4686
  if (sidecar.kind === "present" && dataDirUnsafe === null) {
4271
- if (classifySidecarStaleness(sidecar, probePidLiveness(sidecar.pid)).kind === "stale") {
4687
+ if (classifySidecarStaleness(sidecar, sidecarLiveness).kind === "stale") {
4272
4688
  sidecar = { kind: "absent" };
4273
4689
  }
4274
4690
  }
@@ -4289,8 +4705,7 @@ export async function gatherDaemonEvidence(port, dataDir) {
4289
4705
  // A stale or foreign pid holding the port is NOT healed. False-green is
4290
4706
  // worse than no self-heal.
4291
4707
  //
4292
- // The write uses the same O_NOFOLLOW / 0600 / atomic-rename posture as every
4293
- // other sidecar write. We skip self-heal when the dataDir is unsafe
4708
+ // The write uses mode 0600 and atomic rename. We skip self-heal when the dataDir is unsafe
4294
4709
  // (symlink / world-writable) — the check has already happened above.
4295
4710
  let portOwner = { kind: "unavailable" };
4296
4711
  let instanceMatch = { kind: "unavailable" };
@@ -4336,15 +4751,14 @@ export async function gatherDaemonEvidence(port, dataDir) {
4336
4751
  sidecar,
4337
4752
  readStartTime: readProcessStartTimeMs,
4338
4753
  });
4339
- return { dataDirUnsafe, pidfile, pidLiveness, identity, health };
4754
+ return { ...owner, identity, health };
4340
4755
  }
4341
4756
  /**
4342
- * Write the identity sidecar atomically (temp + rename) at spawn time or
4343
- * during self-heal (flair#1454 decision 3). `pid` is the spawned process's
4344
- * pid — the same number Harper writes to `hdb.pid`, since Harper runs
4345
- * in-process. `startTimeMs` defaults to `Date.now()` for a fresh spawn.
4757
+ * Write the identity sidecar atomically (temp + rename) for direct starts,
4758
+ * confirmed managed starts, or self-heal (flair#1454 decision 3).
4759
+ * `startTimeMs` defaults to `Date.now()` for a fresh direct spawn.
4346
4760
  *
4347
- * Self-heal callers pass the live process's actual start time (from
4761
+ * Managed start and self-heal callers pass the live process's actual start time (from
4348
4762
  * readProcessStartTimeMs) so the sidecar records an accurate epoch, not a
4349
4763
  * wall-clock approximation. Note: in the self-heal path the ±2s start-time
4350
4764
  * check in verifyIdentity is NOT what prevents recycled-pid adoption —
@@ -4367,40 +4781,17 @@ function writeDaemonSidecar(dataDir, pid, port, startTimeMs = Date.now()) {
4367
4781
  chmodSync(finalPath, 0o600);
4368
4782
  }
4369
4783
  /**
4370
- * Remove the identity sidecar left behind by a stop (flair#2055).
4371
- *
4372
- * A sidecar that still names a pid which is CONFIRMED gone is a leftover, and
4373
- * leaving it makes a later instance under a DIFFERENT supervisor refuse
4374
- * ("its identity could not be verified"). The removal is gated twice:
4375
- *
4376
- * 1. the pid the sidecar names must be CONFIRMED gone (ESRCH) — `unknown` or
4377
- * EPERM liveness removes nothing; and
4378
- * 2. a FRESH O_NOFOLLOW read taken just before the unlink must still name
4379
- * that pid. A sidecar another supervisor rewrote in between names a
4380
- * different pid and is left alone; a symlinked or malformed one reads as
4381
- * `unreadable` and is not removed either, because the re-read never
4382
- * followed the link.
4383
- *
4384
- * There is no lock: the re-read narrows the window to the gap between the read
4385
- * and the unlink, and the only loser of that race is a start that rewrote the
4386
- * sidecar in the gap — a live daemon left with no sidecar, which a later
4387
- * port-based stop or restart can RECOVER by self-heal once the live process
4388
- * supplies the required pidfile and health evidence (shouldAdoptMissingSidecar
4389
- * adopts the identity from the live process; see the recovery test). `flair
4390
- * status` does not re-adopt. A lock would buy
4391
- * nothing here and add a crash-recovery hazard, so the design relies on the
4392
- * self-heal instead. A writer OUTSIDE flair could substitute a symlink after
4393
- * the final read; that is out of scope (same as any other path flair re-reads
4394
- * by name). Best-effort: a failure to unlink is reported, never fatal.
4395
- */
4396
- export function removeStaleSidecarIfConfirmedDead(dataDir) {
4784
+ * Best-effort removal of a sidecar naming a PID the probe observed gone.
4785
+ * A matching confirmedGonePid skips another liveness probe; null probes it.
4786
+ * A fresh O_NOFOLLOW read must still name that PID. Non-ENOENT unlink errors are logged.
4787
+ */
4788
+ export function removeStaleSidecarIfConfirmedDead(dataDir, confirmedGonePid = null, probe = probePidLiveness) {
4397
4789
  const observed = readSidecar(dataDir);
4398
4790
  if (observed.kind !== "present")
4399
4791
  return;
4400
4792
  const observedPid = observed.pid;
4401
- const observedPidLiveness = probePidLiveness(observedPid);
4402
- // Re-read: only the sidecar that still names the confirmed-dead pid is ours
4403
- // to remove (a sidecar rewritten in the gap is left alone).
4793
+ const observedPidLiveness = confirmedGonePid !== null && confirmedGonePid === observedPid ? { kind: "gone" } : probe(observedPid);
4794
+ // A re-read naming a different PID is left alone.
4404
4795
  const fresh = readSidecar(dataDir);
4405
4796
  if (!shouldRemoveSidecarAfterStop({ observedPid, observedPidLiveness, sidecar: fresh }))
4406
4797
  return;
@@ -4476,6 +4867,7 @@ bindServiceCli({
4476
4867
  ensureLaunchdServiceLoaded,
4477
4868
  flairPackageDir,
4478
4869
  gatherDaemonEvidence,
4870
+ gatherDaemonOwnerEvidence,
4479
4871
  guardEngineNotBackwards,
4480
4872
  harperBinNotFoundMessage,
4481
4873
  harperSearchRoots,
@@ -4484,6 +4876,7 @@ bindServiceCli({
4484
4876
  observeLaunchdManagement,
4485
4877
  probeHealth,
4486
4878
  readyOpsSocketPosture,
4879
+ recordManagedStartSidecar,
4487
4880
  resolveHarperBin,
4488
4881
  resolveHttpBindHost,
4489
4882
  resolveHttpPort,
@@ -4655,16 +5048,40 @@ function validateLaunchdPlistContent(content, lint = lintLaunchdPlistContent) {
4655
5048
  * `null` (neither available) is handled by the caller as "no evidence", never
4656
5049
  * as "detached".
4657
5050
  */
4658
- function resolveInstanceServingPid(dataDir, port) {
5051
+ function resolveInstanceServingPid(dataDir, port, deps = {}) {
4659
5052
  let listeningPids = [];
4660
5053
  try {
4661
- listeningPids = listeningPidsOnPort(port, (cmd) => execSync(cmd, { encoding: "utf-8" }));
5054
+ listeningPids = deps.findListeningPids?.(port)
5055
+ ?? listeningPidsOnPort(port, () => execFileSync("lsof", ["-ti", `:${port}`, "-sTCP:LISTEN"], { encoding: "utf-8", timeout: 2_000, killSignal: "SIGKILL" }));
4662
5056
  }
4663
5057
  catch { /* lsof unavailable — the PID file may still answer */ }
5058
+ // flair#2056: the `hdb.pid` pid is used as PID-file evidence only when it is
5059
+ // alive, its command line passes isHarperProcessCommandLine (node or bun
5060
+ // followed by a Harper entry path; see there for what a `ps` line cannot
5061
+ // establish), and no flair#1454 sidecar disagrees. A sidecar is not
5062
+ // required: an instance started by a pre-sidecar flair, or the one the
5063
+ // launchd launcher execs, has none. A sidecar disagrees when it names a
5064
+ // different pid, or a startTimeMs more than 2000 ms from the pid's start
5065
+ // second (readProcessStartSecondMs). When the pid is not used,
5066
+ // pickInstancePid returns the first process listening on `port`, if any,
5067
+ // which can be the same pid.
5068
+ const sidecar = readSidecar(dataDir);
5069
+ const isPidFileEvidence = (pid) => {
5070
+ if (sidecar.kind === "present") {
5071
+ if (sidecar.pid !== pid)
5072
+ return false;
5073
+ const startSecondMs = (deps.readStartSecondMs ?? readProcessStartSecondMs)(pid);
5074
+ if (startSecondMs === null || !sidecarStartAgrees(startSecondMs, sidecar.startTimeMs))
5075
+ return false;
5076
+ }
5077
+ const cmdline = (deps.readCmdline ?? defaultReadProcessCmdline)(pid);
5078
+ return cmdline !== null && isHarperProcessCommandLine(cmdline);
5079
+ };
4664
5080
  return pickInstancePid({
4665
5081
  pidFilePid: readHarperPid(dataDir),
4666
5082
  isAlive: isProcessAlive,
4667
5083
  listeningPids,
5084
+ isPidFileEvidence,
4668
5085
  });
4669
5086
  }
4670
5087
  // ─── which install tree serves this instance (flair#2034 §2) ────────────────
@@ -5003,6 +5420,92 @@ function observeLaunchdManagement(dataDir, port) {
5003
5420
  list: realLaunchctlLister,
5004
5421
  });
5005
5422
  }
5423
+ /**
5424
+ * Record the identity sidecar for the instance a launchd-managed start brought
5425
+ * up during a CLI-managed start (flair#2411). The direct start path writes one
5426
+ * immediately after spawn. A launchd KeepAlive relaunch does not write one.
5427
+ *
5428
+ * The sidecar is written after launchd reports the same pid before and after a
5429
+ * Flair-shaped health response and matching serving-pid and hdb.pid reads.
5430
+ * The writer uses an atomic temp+rename and mode 0600; pidfile and sidecar
5431
+ * reads use O_NOFOLLOW.
5432
+ *
5433
+ * A throwing waitForHealth call rethrows its original error so the caller's
5434
+ * existing fallback still runs; a failed Flair fingerprint and the other
5435
+ * unconfirmed cases return `recorded: false`. Each unconfirmed return also
5436
+ * names what the confirmation probe saw in `confirmation`, so the caller's
5437
+ * warning can report it (flair#2422).
5438
+ */
5439
+ export async function recordManagedStartSidecar(dataDir, port, label, deps = {}) {
5440
+ const warn = deps.warn ?? ((line) => console.error(line));
5441
+ const timeoutMs = deps.timeoutMs ?? STARTUP_TIMEOUT_MS;
5442
+ try {
5443
+ await (deps.waitForHealth ?? waitForHealth)(port, deps.adminUser ?? DEFAULT_ADMIN_USER, deps.adminPass ?? process.env.HDB_ADMIN_PASSWORD ?? "", timeoutMs);
5444
+ }
5445
+ catch (err) {
5446
+ warn(`⚠️ the instance for launchd job ${label} did not answer health within ${timeoutMs}ms, so its identity sidecar was not written (${err?.message ?? err})`);
5447
+ throw err;
5448
+ }
5449
+ // flair#2422: read launchd's job state, then probe health BEFORE branching on
5450
+ // that read. The probe is the confirmation's second look at the port, and its
5451
+ // result is what an unconfirmed start's warning reports.
5452
+ const job = readLaunchctlJobState(label, deps.list ?? realLaunchctlLister);
5453
+ const health = await (deps.probeHealth ?? probeHealth)(port);
5454
+ if (health.kind !== "ok") {
5455
+ const detail = `the instance for launchd job ${label} did not return Flair health (${health.kind}), so its identity sidecar was not written`;
5456
+ warn(`⚠️ ${detail}`);
5457
+ return { recorded: false, confirmation: health.kind, detail };
5458
+ }
5459
+ if (!job.registered) {
5460
+ const detail = `could not read launchd job ${label}, so its identity sidecar was not written`;
5461
+ warn(`⚠️ ${detail}`);
5462
+ return { recorded: false, confirmation: "flair", detail };
5463
+ }
5464
+ if (job.pid === null) {
5465
+ const detail = `launchd did not report a running pid for job ${label}, so its identity sidecar was not written`;
5466
+ warn(`⚠️ ${detail}`);
5467
+ return { recorded: false, confirmation: "flair", detail };
5468
+ }
5469
+ const serving = (deps.servingPid ?? ((_dataDir, httpPort) => {
5470
+ const listeners = resolveListenerPids(httpPort);
5471
+ return listeners?.length === 1 ? listeners[0] : null;
5472
+ }))(dataDir, port);
5473
+ if (serving === null) {
5474
+ const detail = `launchd job ${label} runs as process ${job.pid}, but the process serving this instance could not be identified, so its identity sidecar was not written`;
5475
+ warn(`⚠️ ${detail}`);
5476
+ return { recorded: false, confirmation: "flair", detail };
5477
+ }
5478
+ if (serving !== job.pid) {
5479
+ const detail = `the process answering on port ${port} is ${serving}, not launchd's process ${job.pid} for job ${label}, so its identity sidecar was not written`;
5480
+ warn(`⚠️ ${detail}`);
5481
+ return { recorded: false, confirmation: "flair", detail };
5482
+ }
5483
+ const again = readLaunchctlJobState(label, deps.list ?? realLaunchctlLister);
5484
+ if (!again.registered) {
5485
+ const detail = `could not re-read launchd job ${label}, so its identity sidecar was not written`;
5486
+ warn(`⚠️ ${detail}`);
5487
+ return { recorded: false, confirmation: "flair", detail };
5488
+ }
5489
+ if (again.pid !== job.pid) {
5490
+ const detail = `launchd job ${label} changed pid during health confirmation, so its identity sidecar was not written`;
5491
+ warn(`⚠️ ${detail}`);
5492
+ return { recorded: false, confirmation: "flair", detail };
5493
+ }
5494
+ const pidfile = readPidfile(dataDir);
5495
+ if (pidfile.kind !== "present" || pidfile.pid !== job.pid) {
5496
+ const detail = `hdb.pid does not confirm launchd job ${label}'s process ${job.pid}, so its identity sidecar was not written`;
5497
+ warn(`⚠️ ${detail}`);
5498
+ return { recorded: false, confirmation: "flair", detail };
5499
+ }
5500
+ const startTimeMs = (deps.readStartTime ?? readProcessStartTimeMs)(job.pid);
5501
+ if (startTimeMs === null) {
5502
+ const detail = `could not read the start time of launchd job ${label}'s process ${job.pid}, so its identity sidecar was not written`;
5503
+ warn(`⚠️ ${detail}`);
5504
+ return { recorded: false, confirmation: "flair", detail };
5505
+ }
5506
+ (deps.write ?? writeDaemonSidecar)(dataDir, job.pid, port, startTimeMs);
5507
+ return { recorded: true, pid: job.pid, detail: `launchd job ${label} is running as process ${job.pid}` };
5508
+ }
5006
5509
  // `preserveHttpPortValue` / `preserveSecurePort` / `bindHostOf` live in
5007
5510
  // src/lib/http-bind.ts so the CLI's plist writer and the pure repair PLANNER
5008
5511
  // (src/lib/launchd-repair.ts) share the exact same preservation rules, and the
@@ -5144,24 +5647,24 @@ function resolveAdminPassAvailability(path) {
5144
5647
  `Run 'flair init' to provision ${path}, or start the instance and re-run 'flair doctor --fix'.`,
5145
5648
  };
5146
5649
  }
5147
- /**
5148
- * Prove an admin credential belongs to the running instance before adoption
5149
- * materializes it into the 0600 pass file (flair#1685). The admin-gated
5150
- * /HealthDetail read is the proof: a rejected Basic credential produces 401 and
5151
- * is NOT retried through the agent-key floor (that floor only engages when no
5152
- * credential was sent at all), so success here means THIS credential was
5153
- * accepted by THIS instance. Never logs the secret.
5154
- */
5155
- async function proveAdminPassAgainstInstance(port, adminPass) {
5650
+ export async function proveAdminPassAgainstInstance(port, adminPass) {
5156
5651
  try {
5157
- await api("GET", "/HealthDetail", undefined, {
5652
+ await api("GET", "/FederationPeers", undefined, {
5158
5653
  baseUrl: `http://127.0.0.1:${port}`,
5159
5654
  explicitAdminPass: adminPass,
5655
+ adminUser: DEFAULT_ADMIN_USER,
5160
5656
  });
5161
5657
  return null;
5162
5658
  }
5163
5659
  catch (err) {
5164
- return err instanceof Error ? err.message : String(err);
5660
+ if (err instanceof Error && err.cause instanceof ApiHttpError)
5661
+ err = err.cause;
5662
+ if (err instanceof ApiHttpError && (err.status === 401 || err.status === 403)) {
5663
+ return `the supplied admin credential was rejected (HTTP ${err.status})`;
5664
+ }
5665
+ const detail = err instanceof Error ? err.message : String(err);
5666
+ const status = err instanceof ApiHttpError ? `HTTP ${err.status}: ` : "";
5667
+ return `admin credential verification could not be completed (${status}${detail})`;
5165
5668
  }
5166
5669
  }
5167
5670
  /**
@@ -5206,10 +5709,6 @@ function validateAdminPassFileForLauncher(path) {
5206
5709
  * file and the command named and write NO plist. Never a plist whose
5207
5710
  * launcher argv cannot be satisfied.
5208
5711
  *
5209
- * The proof uses the same authed `GET /HealthDetail` as the doctor arms (a
5210
- * rejected Basic credential is a 401 and never falls through to the agent-key
5211
- * floor), so a credential that does not belong to THIS instance is refused
5212
- * rather than baked into a pass file the instance would reject.
5213
5712
  */
5214
5713
  export async function writeInitLaunchdPlist(opts, deps = {}) {
5215
5714
  const prove = deps.prove ?? proveAdminPassAgainstInstance;
@@ -5349,8 +5848,16 @@ export async function writeInitLaunchdPlist(opts, deps = {}) {
5349
5848
  return { kind: "written", plistPath: opts.plistPath };
5350
5849
  }
5351
5850
  /**
5352
- * Put the plist `flair init` wrote back as `prior` recorded it (flair#2040,
5353
- * flair#2078): its prior bytes, or removed when there was none. Never throws:
5851
+ * The exit code `flair init` uses for its launchd step's outcome (flair#2040):
5852
+ * 1 for the refused, down and uncertain failure outcomes; 0 otherwise.
5853
+ * A refusal may leave an existing launchd registration serving normally.
5854
+ */
5855
+ function initLaunchdExitCode(kind) {
5856
+ return kind === "refused" || kind === "down" || kind === "uncertain" ? 1 : 0;
5857
+ }
5858
+ /**
5859
+ * Restore the plist path to `prior` (flair#2040, flair#2078): its prior bytes,
5860
+ * or absent when there was none. Never throws:
5354
5861
  * `ok` false means the put-back FAILED, and `text` says so with the error.
5355
5862
  */
5356
5863
  function putInitPlistBack(path, prior) {
@@ -5362,12 +5869,29 @@ function putInitPlistBack(path, prior) {
5362
5869
  }
5363
5870
  return {
5364
5871
  ok: true,
5365
- text: prior.kind === "absent" ? `the new plist ${path} was removed again` : `the plist at ${path} was put back as it was`,
5872
+ text: prior.kind === "absent" ? `the new plist ${path} was removed again` : `the prior plist bytes and mode at ${path} were restored`,
5366
5873
  };
5367
5874
  }
5875
+ function validateInitPlistAfterWrite(write) {
5876
+ const installing = `the plist init would install for ${write.label}`;
5877
+ let refusal = null;
5878
+ try {
5879
+ const problem = validateLaunchdPlistContent(readFileSync(write.plistPath, "utf-8"), (content) => lintReplacementPlist(content, launchdMigrationLintForTests ?? lintLaunchdPlistContent, (failure) => `${installing} could not be validated (${failure})`));
5880
+ if (problem !== null) {
5881
+ refusal = { why: `${installing} cannot be loaded (${problem})`, fix: "npm install -g @tpsdev-ai/flair && flair init" };
5882
+ }
5883
+ }
5884
+ catch (e) {
5885
+ refusal = isLaunchdValidationRefusal(e)
5886
+ ? { why: e.message, fix: `make sure the temporary directory (${tmpdir()}) exists and is writable, and re-run 'flair init'.` }
5887
+ : { why: `${installing} could not be validated (${e?.message ?? String(e)})`, fix: "resolve the error above, and re-run 'flair init'." };
5888
+ }
5889
+ return refusal;
5890
+ }
5368
5891
  /**
5369
- * `flair init`'s launchd step (flair#2040): write this instance's plist, retire
5370
- * a pre-flair#693 legacy registration, and report ONLY what was verified.
5892
+ * `flair init`'s launchd step (flair#2040): may write or repoint this
5893
+ * instance's plist, retire a pre-flair#693 legacy registration, and report ONLY
5894
+ * what was verified.
5371
5895
  *
5372
5896
  * init starts Flair DIRECTLY and, since 9e3bd9ad, deliberately does not bounce
5373
5897
  * a running instance into launchd — so the ordinary outcome is "plist on disk,
@@ -5378,21 +5902,29 @@ function putInitPlistBack(path, prior) {
5378
5902
  * The one path that stops something is retiring a LEGACY job that is the
5379
5903
  * process serving this instance: booting it out stops Flair. That path follows
5380
5904
  * the same rule as `doctor --fix`: preflight first (domain reachable, job
5381
- * enabled), write + validate the replacement plist while the instance is still
5905
+ * enabled), prepare + validate the replacement plist while the instance is still
5382
5906
  * up, and only then boot the legacy job out, load the replacement with
5383
- * targeted commands and verify it; any failure after the boot-out restores the
5384
- * legacy plist and job (or, failing that, starts Flair directly) and says so.
5907
+ * targeted commands, and verify it.
5385
5908
  * If the preflight fails, NOTHING is unloaded, removed or written; if the
5386
- * validation fails — a lint that throws included (flair#2078) — nothing is
5387
- * unloaded or removed, and the plist init wrote is put back as it was.
5909
+ * validation fails — a lint that throws included (flair#2078) — no job is
5910
+ * unloaded and plist rollback is attempted; failure returns `uncertain`. The
5911
+ * non-legacy path uses the same rule (flair#2085).
5388
5912
  */
5389
- async function registerInitLaunchdService(input) {
5913
+ async function registerInitLaunchdService(input, validateAfterWrite = validateInitPlistAfterWrite) {
5390
5914
  const { dataDir, port, plistDir, write } = input;
5391
5915
  const uid = currentUid();
5392
5916
  const domain = launchdGuiDomain(uid);
5393
5917
  const lines = [];
5394
5918
  const out = (text) => lines.push({ stream: "out", text });
5395
5919
  const err = (text) => lines.push({ stream: "err", text });
5920
+ const refuseInvalidPlist = (prior, frame) => {
5921
+ const refusal = validateAfterWrite(write);
5922
+ if (refusal === null)
5923
+ return null;
5924
+ const putBack = putInitPlistBack(write.plistPath, prior);
5925
+ frame(refusal, putBack);
5926
+ return { kind: putBack.ok ? "skipped" : "uncertain", lines };
5927
+ };
5396
5928
  const legacyPath = launchdPlistPath(LEGACY_LAUNCHD_LABEL, plistDir);
5397
5929
  const legacyRoot = existsSync(legacyPath) ? readPlistRootPath(legacyPath) : null;
5398
5930
  const legacyOwned = legacyRoot !== null && resolve(legacyRoot) === resolve(dataDir);
@@ -5401,9 +5933,35 @@ async function registerInitLaunchdService(input) {
5401
5933
  // helper prints why. With no legacy plist it is a no-op.
5402
5934
  if (existsSync(legacyPath))
5403
5935
  cleanupLegacyLaunchdPlist(dataDir, plistDir, realLaunchctlCommand, uid);
5936
+ // flair#2085: with no owned legacy job, the writer may write, repoint or
5937
+ // leave the plist unchanged. Validate the target (a thrown lint refuses).
5938
+ // On failure, attempt rollback; failure returns `uncertain`. No launchctl
5939
+ // mutation occurs on this path. Refuse an unsafe snapshot before writing.
5940
+ const priorNew = snapshotFile(write.plistPath);
5941
+ if (priorNew.kind === "symlink") {
5942
+ err(`⚠️ Launchd: not registered — ${write.plistPath} is a symbolic link, so no plist was written.`);
5943
+ err(` Fix: move or remove the symbolic link at ${write.plistPath}, then re-run 'flair init'.`);
5944
+ return { kind: "skipped", lines };
5945
+ }
5946
+ const unreadableNew = unreadableSnapshot([[write.plistPath, priorNew]]);
5947
+ if (unreadableNew) {
5948
+ err(`⚠️ Launchd: not registered — ${unreadableNew} could not be safely snapshotted, so it could not be put back. No plist was written.`);
5949
+ return { kind: "skipped", lines };
5950
+ }
5404
5951
  const outcome = await writeInitLaunchdPlist(write);
5405
5952
  if (outcome.kind === "refused")
5406
5953
  return { kind: "refused", lines: [{ stream: "err", text: `Error: ${outcome.detail}` }] };
5954
+ const refused = refuseInvalidPlist(priorNew, (refusal, putBack) => {
5955
+ err(`⚠️ Launchd: not registered — ${refusal.why}. ${putBack.text}.`);
5956
+ if (!putBack.ok) {
5957
+ err(` Fix: remove ${write.plistPath} (its loadability is unverified and rollback failed); then ${refusal.fix}`);
5958
+ }
5959
+ else {
5960
+ err(` Fix: ${refusal.fix}`);
5961
+ }
5962
+ });
5963
+ if (refused)
5964
+ return refused;
5407
5965
  return reportInitLaunchd(dataDir, port, write, outcome, lines);
5408
5966
  }
5409
5967
  const keptLegacy = `Nothing was unloaded or removed: the legacy job ${LEGACY_LAUNCHD_LABEL} and its plist at ${legacyPath} were left as they were`;
@@ -5469,13 +6027,18 @@ async function registerInitLaunchdService(input) {
5469
6027
  // cannot be read cannot be put back: refuse before anything is written.
5470
6028
  const priorNew = snapshotFile(write.plistPath);
5471
6029
  const priorLegacy = snapshotFile(legacyPath);
6030
+ if (priorNew.kind === "symlink") {
6031
+ err(`⚠️ Launchd: not re-registered — ${write.plistPath} is a symbolic link, so no new plist was written. ${keptLegacy}.`);
6032
+ err(` Fix: move or remove the symbolic link at ${write.plistPath}, then re-run 'flair init'.`);
6033
+ return { kind: "skipped", lines };
6034
+ }
5472
6035
  const unreadable = unreadableSnapshot([[write.plistPath, priorNew], [legacyPath, priorLegacy]]);
5473
6036
  if (unreadable) {
5474
- err(`⚠️ Launchd: not re-registered — ${unreadable} exists but could not be read, so it could not be put back. ${keptLegacy}.`);
6037
+ err(`⚠️ Launchd: not re-registered — ${unreadable} could not be safely snapshotted, so it could not be put back. ${keptLegacy}.`);
5475
6038
  return { kind: "skipped", lines };
5476
6039
  }
5477
- // The replacement is written and validated while the instance is still up
5478
- // (the writer proves the credential against it).
6040
+ // The writer may write, repoint or leave the plist unchanged. Validate the
6041
+ // target while the instance is up.
5479
6042
  const outcome = await writeInitLaunchdPlist(write);
5480
6043
  if (outcome.kind === "refused") {
5481
6044
  return {
@@ -5486,45 +6049,26 @@ async function registerInitLaunchdService(input) {
5486
6049
  ],
5487
6050
  };
5488
6051
  }
5489
- // Every failed validation is a refusal made before anything is unloaded: a
5490
- // problem the checks REPORT, and — as in the start paths' migration — a lint
5491
- // that THROWS (lintReplacementPlist) or a written plist that cannot be read
5492
- // back (flair#2078). Each puts the plist just written back as it was, or
5493
- // removes it when there was none: left beside the legacy plist, it would give
5494
- // launchd two jobs for one data directory at the next login.
5495
- const installing = `the plist init would install for ${write.label}`;
5496
- let refusal = null;
5497
- try {
5498
- const problem = validateLaunchdPlistContent(readFileSync(write.plistPath, "utf-8"), (content) => lintReplacementPlist(content, launchdMigrationLintForTests ?? lintLaunchdPlistContent, (failure) => `${installing} could not be validated (${failure})`));
5499
- if (problem !== null) {
5500
- refusal = { why: `${installing} cannot be loaded (${problem})`, fix: "npm install -g @tpsdev-ai/flair && flair init" };
5501
- }
5502
- }
5503
- catch (e) {
5504
- refusal = isLaunchdValidationRefusal(e)
5505
- ? { why: e.message, fix: `make sure the temporary directory (${tmpdir()}) exists and is writable, and re-run 'flair init'.` }
5506
- : { why: `${installing} could not be validated (${e?.message ?? String(e)})`, fix: "resolve the error above, and re-run 'flair init'." };
5507
- }
5508
- if (refusal !== null) {
5509
- const putBack = putInitPlistBack(write.plistPath, priorNew);
6052
+ const refused = refuseInvalidPlist(priorNew, (refusal, putBack) => {
5510
6053
  err(`⚠️ Launchd: not re-registered — ${refusal.why}. Nothing was unloaded: the legacy job ${LEGACY_LAUNCHD_LABEL} ` +
5511
6054
  `and its plist at ${legacyPath} were left as they were, and ${putBack.text}.`);
5512
6055
  if (!putBack.ok) {
5513
6056
  err(` Fix: remove ${write.plistPath} (beside the legacy plist, launchd would load two jobs for this data ` +
5514
6057
  `directory at the next login); then ${refusal.fix}`);
5515
- return { kind: "uncertain", lines };
5516
6058
  }
5517
- err(` Fix: ${refusal.fix}`);
5518
- return { kind: "skipped", lines };
5519
- }
6059
+ else {
6060
+ err(` Fix: ${refusal.fix}`);
6061
+ }
6062
+ });
6063
+ if (refused)
6064
+ return refused;
5520
6065
  if (role !== "serving") {
5521
6066
  // PROVEN not serving (absent, or idle): retiring it stops nothing.
5522
6067
  const cleanup = cleanupLegacyLaunchdPlist(dataDir, plistDir, realLaunchctlCommand, uid);
5523
6068
  if (cleanup.action === "unload-unconfirmed") {
5524
6069
  // flair#2040: the legacy job could not be shown unloaded, and the helper
5525
- // KEPT its plist. The replacement written above must not stay beside it
5526
- // (two plists for one data directory would give launchd two jobs), so it
5527
- // is put back as it was, and nothing is reported as registered.
6070
+ // KEPT its plist. Rollback attempts to restore the target's prior state;
6071
+ // the result is uncertain even if rollback succeeds.
5528
6072
  const putBack = putInitPlistBack(write.plistPath, priorNew);
5529
6073
  err(`⚠️ Launchd: not re-registered — the legacy job ${LEGACY_LAUNCHD_LABEL} could not be shown unloaded ` +
5530
6074
  `(${cleanup.unloadFailed}), so it may still be loaded. Its plist at ${legacyPath} was left in place, and ${putBack.text}.`);
@@ -5801,10 +6345,7 @@ function planLaunchdRepairFor(dataDir, port) {
5801
6345
  * TWO PHASES (flair#2040). The rule for this handoff: the running instance
5802
6346
  * is not stopped, and no launchd job is unloaded, until every check that can
5803
6347
  * be made about the replacement from THIS session has passed; an UNKNOWN
5804
- * answer is a failed check, never a pass. Every failure after that point is
5805
- * followed by an attempt to bring back what was running, and the result
5806
- * reports the state the instance was left in — including when that state
5807
- * could not be established.
6348
+ * answer is a failed check, never a pass.
5808
6349
  *
5809
6350
  * 1. PREPARE (prepareLaunchdRepair) — reads and validation; the running
5810
6351
  * instance and launchd are untouched:
@@ -5834,14 +6375,7 @@ function planLaunchdRepairFor(dataDir, port) {
5834
6375
  * its port does not answer, and verify STRICTLY: Flair's /Health answers
5835
6376
  * ok and launchd's pid is the IDENTIFIED serving pid
5836
6377
  * (judgeLaunchdJobServing), and on adopt the serving pid
5837
- * changed and the old one is dead (flair#1684/#1685). ANY failure here
5838
- * goes through restoreAfterFailedRepair.
5839
- *
5840
- * The preflight cannot PROVE a bootstrap will succeed — only loading something
5841
- * proves that — which is why phase 2 restores rather than assumes.
5842
- *
5843
- * Never reports success on a direct start or an unattributed process. Every
5844
- * throw becomes a named result, never a crash mid-report.
6378
+ * changed and the old one is dead (flair#1684/#1685).
5845
6379
  */
5846
6380
  async function repairLaunchdManagement(dataDir, port) {
5847
6381
  const { plan, plistPath, isLegacy, config } = planLaunchdRepairFor(dataDir, port);
@@ -5874,31 +6408,54 @@ async function repairLaunchdManagement(dataDir, port) {
5874
6408
  }
5875
6409
  }
5876
6410
  function snapshotFile(path) {
6411
+ let stat;
5877
6412
  try {
5878
- const bytes = readFileSync(path);
5879
- return { kind: "present", bytes, mode: statSync(path).mode & 0o777 };
6413
+ stat = lstatSync(path);
5880
6414
  }
5881
6415
  catch (err) {
5882
6416
  if (err?.code === "ENOENT")
5883
6417
  return { kind: "absent" };
5884
6418
  return { kind: "unreadable", error: `${err?.code ?? "error"}: ${err?.message ?? err}` };
5885
6419
  }
6420
+ if (stat.isSymbolicLink())
6421
+ return { kind: "symlink" };
6422
+ try {
6423
+ // O_NOFOLLOW also rejects a link substituted after lstat. Read and stat
6424
+ // the same opened file, so a replacement cannot mix bytes with old mode.
6425
+ const fd = openSync(path, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);
6426
+ try {
6427
+ const opened = fstatSync(fd);
6428
+ if (!opened.isFile())
6429
+ return { kind: "unreadable", error: "not a regular file" };
6430
+ return { kind: "present", bytes: readFileSync(fd), mode: opened.mode & 0o7777 };
6431
+ }
6432
+ finally {
6433
+ closeSync(fd);
6434
+ }
6435
+ }
6436
+ catch (err) {
6437
+ return { kind: "unreadable", error: `${err?.code ?? "error"}: ${err?.message ?? err}` };
6438
+ }
5886
6439
  }
5887
6440
  /** The first snapshot that could not be taken, as "<path> (<error>)", or null. */
5888
6441
  function unreadableSnapshot(entries) {
5889
6442
  for (const [path, snap] of entries) {
5890
- if (snap && snap.kind === "unreadable")
6443
+ if (snap?.kind === "symlink")
6444
+ return `${path} (symbolic link)`;
6445
+ if (snap?.kind === "unreadable")
5891
6446
  return `${path} (${snap.error})`;
5892
6447
  }
5893
6448
  return null;
5894
6449
  }
5895
6450
  /**
5896
6451
  * Put a file back as `snapshot` recorded it: rewritten byte-for-byte (the raw
5897
- * buffer) when it was present, removed ONLY when it was proven absent. An
5898
- * unreadable snapshot is never "restored" — that would delete or clobber a
5899
- * file whose bytes were never known.
6452
+ * buffer) when it was present, removed ONLY when it was proven absent. A
6453
+ * symlink or unreadable snapshot is never "restored" as a regular file.
5900
6454
  */
5901
6455
  function restoreFile(path, snapshot) {
6456
+ if (snapshot.kind === "symlink") {
6457
+ throw new Error(`not restoring ${path}: its prior state was a symbolic link`);
6458
+ }
5902
6459
  if (snapshot.kind === "unreadable") {
5903
6460
  throw new Error(`not restoring ${path}: its prior contents could not be read (${snapshot.error})`);
5904
6461
  }
@@ -5912,7 +6469,7 @@ function restoreFile(path, snapshot) {
5912
6469
  }
5913
6470
  return;
5914
6471
  }
5915
- writeFileAtomic(path, snapshot.bytes, snapshot.mode);
6472
+ writeFileAtomic(path, snapshot.bytes, snapshot.mode, { exactMode: true });
5916
6473
  }
5917
6474
  /**
5918
6475
  * Phase 1 of the repair: every check that can be made without stopping the
@@ -5958,7 +6515,7 @@ async function prepareLaunchdRepair(dataDir, port, plan, resolvedPlistPath, isLe
5958
6515
  return {
5959
6516
  kind: "refused",
5960
6517
  reason: "unreadable-prior-state",
5961
- detail: `refusing to repair launchd management: ${unreadable} exists but could not be read, so a failed hand-off ` +
6518
+ detail: `refusing to repair launchd management: ${unreadable} could not be safely snapshotted, so a failed hand-off ` +
5962
6519
  `could not put it back. ${untouched}`,
5963
6520
  plistPath: resolvedPlistPath,
5964
6521
  };
@@ -6083,7 +6640,6 @@ async function prepareLaunchdRepair(dataDir, port, plan, resolvedPlistPath, isLe
6083
6640
  },
6084
6641
  };
6085
6642
  }
6086
- /** Phase 2: the bounce, with restore on any failure. */
6087
6643
  async function commitLaunchdRepair(p) {
6088
6644
  const done = { unloadedPrior: false, stopped: false, wrotePlist: false, removedLegacy: false, wroteConfig: false, loaded: false };
6089
6645
  try {
@@ -6105,10 +6661,18 @@ async function commitLaunchdRepair(p) {
6105
6661
  // job does not collide on the port. The captured pid is the evidence the
6106
6662
  // verify uses to prove the serving pid CHANGED.
6107
6663
  if (p.arm === "adopt") {
6108
- done.stopped = true;
6109
6664
  const stop = await stopDirectProcessForAdopt(p.port, p.dataDir);
6110
- if (stop)
6111
- throw new Error(stop.kind === "failed" || stop.kind === "refused" ? stop.detail : "the direct process could not be stopped");
6665
+ if (stop) {
6666
+ if (done.unloadedPrior && (stop.failure.kind === "failed" || stop.failure.kind === "refused")) {
6667
+ stop.failure.detail += " Previously loaded launchd jobs were unloaded.";
6668
+ }
6669
+ if (stop.observedExit && stop.failure.kind === "failed") {
6670
+ done.stopped = true;
6671
+ throw new Error(stop.failure.detail);
6672
+ }
6673
+ return stop.failure;
6674
+ }
6675
+ done.stopped = true;
6112
6676
  }
6113
6677
  // 3. Write the validated plist (pass-file mode, no secret: 0644).
6114
6678
  done.wrotePlist = true;
@@ -6305,7 +6869,7 @@ async function restoreAfterFailedRepair(p, done, cause) {
6305
6869
  }
6306
6870
  /**
6307
6871
  * Clean-stop the direct (non-launchd) process serving `dataDir`+`port` for the
6308
- * adopt path (flair#1573 slice b2). Returns a `failed` result when the process
6872
+ * adopt path (flair#1573 slice b2). Returns a failure outcome when the process
6309
6873
  * cannot be attributed (never stop a foreign process) or the port is still
6310
6874
  * occupied after the stop; returns null when the port is free and the caller
6311
6875
  * should proceed to regenerate + load.
@@ -6318,41 +6882,104 @@ async function restoreAfterFailedRepair(p, done, cause) {
6318
6882
  async function stopDirectProcessForAdopt(port, dataDir) {
6319
6883
  const evidence = await gatherDaemonEvidence(port, dataDir);
6320
6884
  const state = classifyDaemonState(evidence, { port, dataDir });
6321
- // SIGTERM + wait for exit for a verified live pid (RUNNING or WEDGED — a
6322
- // wedged daemon is recovery, not a recycled-pid gamble).
6885
+ const stopDeadline = Date.now() + ADOPT_STOP_TIMEOUT_MS;
6886
+ let observedExit = false;
6887
+ const failure = (result) => ({ failure: result, observedExit });
6888
+ const timeoutResult = (stage) => ({
6889
+ kind: "failed",
6890
+ detail: `Timed out after ${ADOPT_STOP_TIMEOUT_MS}ms ${stage} for ${dataDir}. No replacement launchd job was loaded.`,
6891
+ remedy: [`Inspect ${dataDir}/log/hdb.log; run flair doctor --fix after resolving the stop failure`],
6892
+ });
6323
6893
  if (state.state === "RUNNING" || state.state === "WEDGED") {
6894
+ let signalResult = "SIGTERM sent";
6324
6895
  try {
6325
6896
  process.kill(state.pid, "SIGTERM");
6326
6897
  }
6327
- catch { /* already gone */ }
6328
- try {
6329
- await waitForProcessExit(state.pid, STARTUP_TIMEOUT_MS);
6898
+ catch (err) {
6899
+ signalResult = err?.code === "ESRCH" ? "SIGTERM found no process (ESRCH)" : `SIGTERM failed (${err?.code ?? "unknown error"})`;
6900
+ }
6901
+ const identity = verifyIdentity({
6902
+ pidfilePid: state.pid,
6903
+ sidecar: evidence.identity.kind === "verified" ? readSidecar(dataDir) : { kind: "absent" },
6904
+ readStartTime: (pid) => readProcessStartTimeMs(pid, Math.min(stopDeadline, Date.now() + 2_000)),
6905
+ });
6906
+ const identityObservedAt = Date.now();
6907
+ const stopGone = await waitForPidGone(state.pid, stopDeadline);
6908
+ if (!stopGone.gone) {
6909
+ const liveness = stopGone.last;
6910
+ const result = timeoutResult(`waiting for direct Harper process ${state.pid} to exit`);
6911
+ const identityDetail = identityObservedAt < stopDeadline
6912
+ ? `${identity.kind}, observed at ${new Date(identityObservedAt).toISOString()}`
6913
+ : "not observed before the deadline";
6914
+ if (result.kind === "failed")
6915
+ result.detail += ` ${signalResult}; not observed to exit before the deadline (liveness: ${liveness.kind}; identity: ${identityDetail}).`;
6916
+ return failure(result);
6330
6917
  }
6331
- catch { /* best-effort — the port check below surfaces the real problem */ }
6918
+ observedExit = true;
6919
+ }
6920
+ const stateDecision = decideAdoptStop(state, { kind: "refused" });
6921
+ if (stateDecision !== "proceed")
6922
+ return failure(stateDecision);
6923
+ let health = { kind: "unreachable" };
6924
+ while (Date.now() < stopDeadline) {
6925
+ health = await probeHealthBeforeDeadline(port, stopDeadline);
6926
+ if (Date.now() >= stopDeadline)
6927
+ break;
6928
+ if (health.kind === "refused")
6929
+ break;
6930
+ const remaining = stopDeadline - Date.now();
6931
+ if (remaining <= 0)
6932
+ break;
6933
+ await new Promise((r) => setTimeout(r, Math.min(250, remaining)));
6934
+ }
6935
+ if (Date.now() >= stopDeadline)
6936
+ return failure(timeoutResult(`waiting for port ${port} to free (last health probe: ${health.kind})`));
6937
+ const decision = decideAdoptStop(state, health);
6938
+ if (decision !== "proceed")
6939
+ return failure(decision);
6940
+ const listenerTimeout = Math.min(2_000, stopDeadline - Date.now());
6941
+ if (listenerTimeout <= 0)
6942
+ return failure(timeoutResult(`checking the final listener on port ${port}`));
6943
+ let output;
6944
+ let noMatch = false;
6945
+ try {
6946
+ output = execFileSync("lsof", ["-ti", `:${port}`, "-sTCP:LISTEN"], {
6947
+ encoding: "utf-8", timeout: listenerTimeout, killSignal: "SIGKILL",
6948
+ });
6332
6949
  }
6333
- // flair#1827: poll the post-stop health until the port is provably free — a
6334
- // single observation that caught the listener mid-release flaked with "port
6335
- // not confirmed free". decideAdoptStop is UNCHANGED; it decides on the final
6336
- // observation, and a timeout names the wait and the last probe.
6337
- const decision = await decideAdoptStopWithWait(state, {
6338
- observe: () => probeHealth(port),
6339
- deadlineMs: STARTUP_TIMEOUT_MS,
6340
- });
6341
- if (decision.decision !== "proceed")
6342
- return decision.decision;
6343
- // Belt-and-suspenders: lsof confirms no TCP listener remains before the
6344
- // caller loads the plist. probeHealth "refused" (ECONNREFUSED) already means
6345
- // nothing is listening, but a port that is BOUND yet refuses connections
6346
- // (backlog-full, or a non-HTTP listener) would still EADDRINUSE on load —
6347
- // this catches that rare case the HTTP probe cannot see.
6348
- const { execSync } = await import("node:child_process");
6349
- const listeners = listeningPidsOnPort(port, (cmd) => execSync(cmd, { encoding: "utf-8" }));
6950
+ catch (err) {
6951
+ if (err?.status === 1 && !err?.error && !err?.code && !err?.signal &&
6952
+ typeof err?.stdout === "string" && err.stdout.trim() === "" &&
6953
+ typeof err?.stderr === "string" && err.stderr.trim() === "") {
6954
+ output = "";
6955
+ noMatch = true;
6956
+ }
6957
+ else {
6958
+ return failure({
6959
+ kind: "failed",
6960
+ detail: `Final listener probe failed for port ${port} (${err?.code ?? err?.signal ?? err?.status ?? "unknown error"}). No replacement launchd job was loaded.`,
6961
+ remedy: ["Check lsof; run flair doctor --fix after resolving the probe failure"],
6962
+ });
6963
+ }
6964
+ }
6965
+ if (Date.now() >= stopDeadline)
6966
+ return failure(timeoutResult(`checking the final listener on port ${port}`));
6967
+ if (noMatch)
6968
+ return null;
6969
+ if (typeof output !== "string" || output.trim() === "") {
6970
+ return failure({ kind: "failed", detail: `Final listener probe failed for port ${port} (unusable lsof output).`, remedy: ["Check lsof", "flair doctor --fix"] });
6971
+ }
6972
+ const lines = output.trim().split("\n");
6973
+ if (lines.some((line) => !/^[1-9][0-9]*$/.test(line.trim()) || !Number.isSafeInteger(Number(line.trim())))) {
6974
+ return failure({ kind: "failed", detail: `Final listener probe failed for port ${port} (unusable lsof output).`, remedy: ["Check lsof", "flair doctor --fix"] });
6975
+ }
6976
+ const listeners = lines.map(Number);
6350
6977
  if (listeners.length > 0) {
6351
- return {
6978
+ return failure({
6352
6979
  kind: "failed",
6353
6980
  detail: `port still occupied after stopping the direct process (listener pid ${listeners.join(", ")})`,
6354
6981
  remedy: ["flair stop", "flair doctor --fix"],
6355
- };
6982
+ });
6356
6983
  }
6357
6984
  return null;
6358
6985
  }
@@ -6380,7 +7007,16 @@ async function stopDirectProcessForAdopt(port, dataDir) {
6380
7007
  * the liveness machine. Callers already treat a failed stop as fatal, which
6381
7008
  * is the point: refusing beats quiescing the wrong install.
6382
7009
  */
6383
- async function stopFlairProcess(port, dataDir) {
7010
+ async function stopFlairProcess(port, dataDir, opts = {}) {
7011
+ const waitForExit = opts.waitForExit ?? waitForProcessExit;
7012
+ let launchdExitFailure = null;
7013
+ const fallbackOutcome = (outcome) => {
7014
+ if (!launchdExitFailure)
7015
+ return outcome;
7016
+ if (probePidLiveness(launchdExitFailure.pid).kind !== "gone")
7017
+ return launchdExitFailure;
7018
+ return { pid: outcome.pid ?? launchdExitFailure.pid, exited: outcome.exited };
7019
+ };
6384
7020
  if (process.platform === "darwin") {
6385
7021
  // resolveLaunchdLabel (flair#693) finds whichever label this data dir
6386
7022
  // is currently registered under (new instance-scoped, or a
@@ -6428,22 +7064,33 @@ async function stopFlairProcess(port, dataDir) {
6428
7064
  plistPath,
6429
7065
  instancePid: oldPid,
6430
7066
  plistExists: existsSync,
6431
- list: realLaunchctlLister,
7067
+ list: opts.launchctl?.list ?? realLaunchctlLister,
6432
7068
  })
6433
7069
  : null;
6434
7070
  // unload stops the job AND prevents KeepAlive from respawning it.
6435
7071
  // launchctl stop alone is insufficient for a KeepAlive job (flair#874).
6436
7072
  try {
6437
- execSync(`launchctl unload "${plistPath}"`, { stdio: "pipe" });
7073
+ if (opts.launchctl)
7074
+ opts.launchctl.unload(plistPath);
7075
+ else
7076
+ execSync(`launchctl unload "${plistPath}"`, { stdio: "pipe" });
6438
7077
  }
6439
7078
  catch { }
6440
7079
  if (managed && isDetached(managed)) {
6441
7080
  throw new Error(`launchd is not running this instance — ${managed.detail}`
6442
7081
  + `${managed.remedy?.length ? ` Fix it with: ${managed.remedy.join(" && ")}` : ""}`);
6443
7082
  }
6444
- if (oldPid)
6445
- await waitForProcessExit(oldPid, STARTUP_TIMEOUT_MS);
6446
- return;
7083
+ if (oldPid) {
7084
+ try {
7085
+ await waitForExit(oldPid, STARTUP_TIMEOUT_MS);
7086
+ }
7087
+ catch (err) {
7088
+ launchdExitFailure = { pid: oldPid, exited: false };
7089
+ throw err;
7090
+ }
7091
+ }
7092
+ removeStaleSidecarIfConfirmedDead(dataDir, oldPid);
7093
+ return { pid: oldPid ?? null, exited: true };
6447
7094
  }
6448
7095
  catch (err) {
6449
7096
  console.error(`launchd stop failed, falling back to port-based stop: ${err.message}`);
@@ -6473,29 +7120,30 @@ async function stopFlairProcess(port, dataDir) {
6473
7120
  // blind sleep is not a guarantee — Harper may be flushing RocksDB
6474
7121
  // WAL/MANIFEST, and the next start fails with a locked data directory if
6475
7122
  // the old process hasn't released it yet.
7123
+ let exited = true;
6476
7124
  try {
6477
- await waitForProcessExit(pid, STARTUP_TIMEOUT_MS);
7125
+ await waitForExit(pid, STARTUP_TIMEOUT_MS);
6478
7126
  }
6479
- catch { /* best-effort — the next start will surface the real problem */ }
6480
- // flair#2055: once the process is CONFIRMED gone, drop the identity
6481
- // sidecar. Gated on a fresh O_NOFOLLOW read that still names the pid it
6482
- // named before (a sidecar another supervisor rewrote in between is left
6483
- // alone); a process that survived the wait (or whose liveness is unknown)
6484
- // removes nothing.
6485
- removeStaleSidecarIfConfirmedDead(dataDir);
6486
- return;
7127
+ catch {
7128
+ exited = false; /* best-effort — the restart leg refuses instead (flair#2365) */
7129
+ }
7130
+ // Use the PID the exit probe observed gone; null makes cleanup probe
7131
+ // the sidecar's PID. A re-read naming a different PID is left alone.
7132
+ removeStaleSidecarIfConfirmedDead(dataDir, exited ? pid : null);
7133
+ return fallbackOutcome({ pid, exited });
6487
7134
  }
6488
7135
  case "NOT_RUNNING": {
6489
- // Idempotent no-op for the process — but a sidecar left naming a pid that
6490
- // is CONFIRMED gone is a leftover too (flair#2055), and removing it here
6491
- // keeps a repeat stop from carrying the refusal forward.
7136
+ // Probe the sidecar's PID before best-effort removal.
6492
7137
  removeStaleSidecarIfConfirmedDead(dataDir);
6493
- return;
7138
+ return fallbackOutcome({ pid: null, exited: true });
6494
7139
  }
6495
7140
  case "DISAGREEMENT":
6496
7141
  case "UNKNOWN":
6497
7142
  // Deliberately outside any catch: a refusal must reach the caller, not
6498
7143
  // be swallowed as "not running" and reported as a successful stop.
7144
+ if (launchdExitFailure && !fallbackOutcome({ pid: null, exited: true }).exited) {
7145
+ throw new StopExitWaitError(launchdExitFailure, `refusing to stop: ${state.detail}`);
7146
+ }
6499
7147
  throw new Error(`refusing to stop: ${state.detail}`);
6500
7148
  }
6501
7149
  }
@@ -6587,7 +7235,9 @@ async function startFlairProcess(port, dataDir) {
6587
7235
  throw new LaunchdValidationRefusal(`${stalePlist.message} Fix it with: ${stalePlist.remedy.join(" && ")}`);
6588
7236
  }
6589
7237
  ensureLaunchdServiceLoaded(dataDir, realLaunchctlCommand);
6590
- await waitForHealth(port, DEFAULT_ADMIN_USER, process.env.HDB_ADMIN_PASSWORD ?? "", STARTUP_TIMEOUT_MS);
7238
+ await recordManagedStartSidecar(dataDir, port, launchdLabel(dataDir), {
7239
+ adminPass: process.env.HDB_ADMIN_PASSWORD ?? "",
7240
+ });
6591
7241
  readyOpsSocketPosture(dataDir); // flair#763: re-assert socket posture across restart/upgrade
6592
7242
  stampEngineVersionIfRunning(dataDir); // flair#1047: stamp the store with the engine version
6593
7243
  return;
@@ -6663,6 +7313,21 @@ async function startFlairDirect(port, dataDir) {
6663
7313
  stampEngineVersionIfRunning(dataDir); // flair#1047: stamp the store with the engine version
6664
7314
  return proc.pid ?? null;
6665
7315
  }
7316
+ class StopExitWaitError extends Error {
7317
+ outcome;
7318
+ detail;
7319
+ constructor(outcome, detail) {
7320
+ super(`${detail ? `${detail}. ` : ""}Could not confirm that the old Flair process (pid ${outcome.pid ?? "unknown"}) exited within ${STARTUP_TIMEOUT_MS}ms`);
7321
+ this.outcome = outcome;
7322
+ this.detail = detail;
7323
+ }
7324
+ }
7325
+ function refuseReplacementAfterExitTimeout(outcome, detail) {
7326
+ if (outcome.exited)
7327
+ return;
7328
+ throw new Error(`${detail ? `${detail}. ` : ""}Could not confirm that the old Flair process (pid ${outcome.pid ?? "unknown"}) exited within ${STARTUP_TIMEOUT_MS}ms; refusing to start a replacement. `
7329
+ + `Stop it, then re-run 'flair restart'.`);
7330
+ }
6666
7331
  /**
6667
7332
  * The ONE restart mechanism for a local Flair install. Shared by `flair
6668
7333
  * restart` and `flair upgrade`'s post-install restart step (flair#635) so
@@ -6679,7 +7344,20 @@ async function startFlairDirect(port, dataDir) {
6679
7344
  * named at the call site rather than assumed from `defaultDataDir()` two
6680
7345
  * frames down.
6681
7346
  */
6682
- async function restartFlair(port, dataDir) {
7347
+ export async function restartFlair(port, dataDir, deps = {}) {
7348
+ const startReplacement = deps.startReplacement ?? startFlairProcess;
7349
+ const stopForRestart = async () => {
7350
+ let outcome;
7351
+ try {
7352
+ outcome = await stopFlairProcess(port, dataDir, deps);
7353
+ }
7354
+ catch (err) {
7355
+ if (err instanceof StopExitWaitError)
7356
+ refuseReplacementAfterExitTimeout(err.outcome, err.detail);
7357
+ throw err;
7358
+ }
7359
+ refuseReplacementAfterExitTimeout(outcome);
7360
+ };
6683
7361
  // flair#2034 §2: on Linux, an instance proven to run under a systemd USER
6684
7362
  // unit (found from the serving process's cgroup; its MainPID is that
6685
7363
  // process) is restarted THROUGH that unit, and the unit's new main process
@@ -6717,8 +7395,8 @@ async function restartFlair(port, dataDir) {
6717
7395
  guardEngineNotBackwards(dataDir);
6718
7396
  },
6719
7397
  direct: async () => {
6720
- await stopFlairProcess(port, dataDir);
6721
- await startFlairProcess(port, dataDir);
7398
+ await stopForRestart();
7399
+ await startReplacement(port, dataDir);
6722
7400
  },
6723
7401
  log: (line) => console.log(line),
6724
7402
  });
@@ -6728,8 +7406,8 @@ async function restartFlair(port, dataDir) {
6728
7406
  }
6729
7407
  }
6730
7408
  else {
6731
- await stopFlairProcess(port, dataDir);
6732
- await startFlairProcess(port, dataDir);
7409
+ await stopForRestart();
7410
+ await startReplacement(port, dataDir);
6733
7411
  }
6734
7412
  // Bust the version-handshake cache so the next preAction nudge re-fetches
6735
7413
  // the LIVE version instead of the pre-restart cached one (the false
@@ -6860,6 +7538,7 @@ registerTest(program);
6860
7538
  // Command registration lives in src/commands/deploy.ts (flair#1636).
6861
7539
  // Bind shared cli-locals first so the extracted module never imports this file.
6862
7540
  bindDeployCli({
7541
+ resolveEffectiveOpsUrl,
6863
7542
  fleetSweepCallerExitMessage,
6864
7543
  resolveFabricCredentials,
6865
7544
  shouldRunFleetVerify,
@@ -6893,6 +7572,7 @@ bindDoctorCli({
6893
7572
  repairLaunchdManagement,
6894
7573
  repointMainServiceUnit,
6895
7574
  resolveHttpPort,
7575
+ verifyDoctorRosterInstance,
6896
7576
  restartFlair,
6897
7577
  resolveOpsPort,
6898
7578
  verifyAuditLog,
@@ -6949,6 +7629,7 @@ const ENTITIES_OPTION_DESCRIPTION = "Comma-separated entity vocabulary strings t
6949
7629
  // Command group lives in src/commands/memory.ts (flair#1621). Bind shared
6950
7630
  // helpers first so the extracted module never imports this file.
6951
7631
  bindMemoryCli({
7632
+ resolveEffectiveOpsUrl,
6952
7633
  api,
6953
7634
  resolveBaseUrl,
6954
7635
  resolveSigningAgentId,
@@ -6956,8 +7637,10 @@ bindMemoryCli({
6956
7637
  addSharedCredentialOptions,
6957
7638
  addSharedIdentityOption,
6958
7639
  resolveOpsPort,
7640
+ resolveHttpPort,
6959
7641
  parseEntitiesOptionOrExit,
6960
7642
  ENTITIES_OPTION_DESCRIPTION,
7643
+ resolveFabricCredentials,
6961
7644
  });
6962
7645
  registerMemory(program);
6963
7646
  // ─── flair search ────────────────────────────────────────────────────────────
@@ -7009,6 +7692,9 @@ bindBackupCli({
7009
7692
  addSharedCredentialOptions,
7010
7693
  applyAdminPassFile,
7011
7694
  resolveHttpPort,
7695
+ resolveOpsPort,
7696
+ resolveOpsTarget,
7697
+ resolveOpsUrlFromTarget,
7012
7698
  });
7013
7699
  registerBackup(program);
7014
7700
  // ─── flair restore ────────────────────────────────────────────────────────────
@@ -7036,6 +7722,7 @@ bindImportCli({
7036
7722
  resolveHttpPort,
7037
7723
  resolveOpsPort,
7038
7724
  seedAgentViaOpsApi,
7725
+ seedAgentWithLocalHome,
7039
7726
  });
7040
7727
  registerImport(program);
7041
7728
  // ─── flair inspect ────────────────────────────────────────────────────────────
@@ -7152,7 +7839,7 @@ LEGACY_LAUNCHD_LABEL, launchdLabel, launchdPlistPath, cleanupLegacyLaunchdPlist,
7152
7839
  observeLaunchdManagement, resolveInstanceServingPid,
7153
7840
  // launchd preflight, repair and init registration (flair#2040) — exported so
7154
7841
  // the command-level tests drive them against a stubbed launchctl.
7155
- observeLaunchdLoadability, repairLaunchdManagement, registerInitLaunchdService, startFlairProcess, };
7842
+ observeLaunchdLoadability, repairLaunchdManagement, registerInitLaunchdService, validateInitPlistAfterWrite, initLaunchdExitCode, startFlairProcess, };
7156
7843
  // Shared with `flair status` via src/lib/ops-api-bind.ts (flair#852).
7157
7844
  export { detectOpsApiAllInterfacesBind };
7158
7845
  export { searchScoringFormula, buildSearchExplain, formatSearchExplain } from "./commands/search.js";