@tpsdev-ai/flair 0.59.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 (259) hide show
  1. package/README.md +4 -4
  2. package/SECURITY.md +36 -0
  3. package/config.yaml +12 -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 +991 -248
  10. package/dist/commands/agent.js +224 -43
  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 +592 -146
  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 +97 -35
  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 +41 -10
  59. package/dist/lib/doctor-run.js +75 -37
  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 +4 -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 +24 -0
  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 +1168 -326
  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 +76 -12
  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 +321 -1
  105. package/dist/resources/AgentKeyRegister.js +214 -0
  106. package/dist/resources/AgentKeyRegistration.js +28 -0
  107. package/dist/resources/AgentSeed.js +10 -4
  108. package/dist/resources/AutoPromoteCandidates.js +7 -1
  109. package/dist/resources/Credential.js +177 -2
  110. package/dist/resources/Federation.js +751 -143
  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 +110 -39
  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/Presence.js +144 -49
  129. package/dist/resources/PromoteMemoryCandidate.js +18 -7
  130. package/dist/resources/Relationship.js +23 -0
  131. package/dist/resources/SemanticSearch.js +63 -32
  132. package/dist/resources/Soul.js +189 -76
  133. package/dist/resources/TeamDirectory.js +35 -0
  134. package/dist/resources/WorkspaceState.js +21 -1
  135. package/dist/resources/XAA.js +181 -63
  136. package/dist/resources/agent-auth.js +40 -15
  137. package/dist/resources/auth-middleware.js +400 -161
  138. package/dist/resources/ed25519-auth.js +1 -1
  139. package/dist/resources/embedding-space-guard.js +366 -72
  140. package/dist/resources/engine-version-stamp-boot.js +53 -0
  141. package/dist/resources/federation-classify.js +72 -0
  142. package/dist/resources/federation-crypto.js +5 -5
  143. package/dist/resources/federation-retry-lib.js +135 -0
  144. package/dist/resources/grant-visibility.js +135 -0
  145. package/dist/resources/harper-routing.js +83 -0
  146. package/dist/resources/health.js +120 -18
  147. package/dist/resources/host-source-citation.js +49 -0
  148. package/dist/resources/host-source-visibility.js +7 -6
  149. package/dist/resources/instance-create-lock.js +17 -0
  150. package/dist/resources/instance-identity.js +23 -0
  151. package/dist/resources/instruction-version-record.js +343 -0
  152. package/dist/resources/key-lock.js +3 -3
  153. package/dist/resources/mcp-handler.js +36 -8
  154. package/dist/resources/mcp-oauth-env-guard.js +36 -0
  155. package/dist/resources/mcp-oauth.js +23 -6
  156. package/dist/resources/mcp-tool-arguments.js +4 -6
  157. package/dist/resources/mcp-tools.js +128 -19
  158. package/dist/resources/memory-bootstrap-lib.js +5 -15
  159. package/dist/resources/memory-declared-attributes.js +3 -1
  160. package/dist/resources/memory-deletion-history.js +55 -0
  161. package/dist/resources/memory-durability.js +54 -0
  162. package/dist/resources/memory-embed-hash.js +88 -0
  163. package/dist/resources/memory-embedding-value.js +8 -0
  164. package/dist/resources/memory-host-source.js +27 -5
  165. package/dist/resources/memory-id-guard.js +75 -0
  166. package/dist/resources/memory-redaction.js +236 -0
  167. package/dist/resources/memory-supplied-vector.js +72 -0
  168. package/dist/resources/memory-write-lock.js +310 -0
  169. package/dist/resources/memory-write-response.js +139 -0
  170. package/dist/resources/migrations/data-dir.js +74 -16
  171. package/dist/resources/migrations/dir-safety.js +1 -1
  172. package/dist/resources/migrations/embedding-stamp.js +193 -79
  173. package/dist/resources/migrations/export.js +1 -0
  174. package/dist/resources/migrations/graph-heal.js +18 -25
  175. package/dist/resources/migrations/lock.js +7 -1
  176. package/dist/resources/migrations/snapshot.js +1 -0
  177. package/dist/resources/migrations/source-fields.js +5 -5
  178. package/dist/resources/migrations/synthetic-test-migration.js +14 -11
  179. package/dist/resources/migrations/visibility-backfill.js +29 -29
  180. package/dist/resources/object-body-guard.js +33 -0
  181. package/dist/resources/org-event-created-at.js +133 -0
  182. package/dist/resources/originator-instance.js +39 -7
  183. package/dist/resources/owner-delete-recheck.js +78 -0
  184. package/dist/resources/owner-field-guard.js +39 -5
  185. package/dist/resources/owner-scoped-write-policy.js +212 -0
  186. package/dist/resources/owner-scoped-writes.js +58 -0
  187. package/dist/resources/presence-receipt.js +236 -0
  188. package/dist/resources/promotion-stamp.js +47 -12
  189. package/dist/resources/record-owner-guard.js +74 -26
  190. package/dist/resources/record-types.js +1 -1
  191. package/dist/resources/relay-ops.js +78 -6
  192. package/dist/resources/replay-store.js +96 -19
  193. package/dist/resources/request-target.js +136 -0
  194. package/dist/resources/request-transaction.js +35 -0
  195. package/dist/resources/search-readiness.js +4 -1
  196. package/dist/resources/seed-ids.js +9 -0
  197. package/dist/resources/seed-reservation.js +117 -0
  198. package/dist/resources/semantic-retrieval-core.js +20 -9
  199. package/dist/resources/skill-manifest.js +20 -11
  200. package/dist/resources/skill-subject.js +53 -0
  201. package/dist/resources/skill-version-write.js +432 -0
  202. package/dist/resources/skill-write-fault.js +17 -0
  203. package/dist/resources/skill-write-policy.js +67 -0
  204. package/dist/resources/skill-write.js +67 -7
  205. package/dist/resources/table-helpers.js +10 -7
  206. package/dist/resources/team-directory.js +248 -0
  207. package/dist/resources/tool-descriptors/index.js +69 -8
  208. package/dist/resources/txn-pause-point.js +118 -0
  209. package/dist/resources/usage-recording.js +171 -63
  210. package/dist/resources/write-back.js +218 -0
  211. package/dist/src/engine-version-contract.js +1 -0
  212. package/dist/src/keystore.js +72 -0
  213. package/dist/src/lib/agent-home-fields.js +132 -0
  214. package/dist/src/lib/agent-id-rule.js +46 -0
  215. package/dist/src/lib/agent-key-register.js +80 -0
  216. package/dist/src/lib/atomic-write.js +256 -0
  217. package/dist/src/lib/credential-status-rule.js +78 -0
  218. package/dist/src/lib/expired-by-agent.js +37 -0
  219. package/dist/src/lib/flair-agent-role.js +4 -0
  220. package/dist/src/lib/idp-mapping-rule.js +81 -0
  221. package/dist/src/lib/instance-identity-row.js +20 -0
  222. package/dist/src/lib/mcp-oauth-env-core.js +133 -0
  223. package/dist/src/lib/memory-attributes.js +2 -0
  224. package/dist/src/lib/memory-id-policy.js +46 -0
  225. package/dist/src/lib/principal-status.js +29 -0
  226. package/dist/src/lib/proto-safe-record.js +42 -0
  227. package/dist/src/lib/reembed-server-support.js +66 -0
  228. package/dist/src/lib/scheduler-platform.js +10 -6
  229. package/dist/src/lib/systemd-agent-id.js +38 -0
  230. package/docs/access-control.md +146 -45
  231. package/docs/api-reference.md +46 -11
  232. package/docs/auth.md +6 -12
  233. package/docs/bridges.md +11 -0
  234. package/docs/claude-code.md +34 -4
  235. package/docs/deploying-on-fabric.md +70 -0
  236. package/docs/deployment.md +2 -0
  237. package/docs/embedding-in-a-harper-app.md +1 -1
  238. package/docs/federation.md +33 -2
  239. package/docs/hosted-on-fabric.md +43 -36
  240. package/docs/integrations.md +5 -5
  241. package/docs/mcp-clients.md +5 -2
  242. package/docs/n8n.md +17 -11
  243. package/docs/notes/mcp-agent-auth-consumer.md +12 -4
  244. package/docs/notes/mcp-oauth-model2.md +34 -5
  245. package/docs/quickstart-fabric.md +2 -2
  246. package/docs/quickstart.md +9 -1
  247. package/docs/releasing.md +12 -6
  248. package/docs/rem.md +8 -0
  249. package/docs/secrets-and-keys.md +19 -2
  250. package/docs/standalone-local.md +1 -0
  251. package/docs/supply-chain-policy.md +13 -3
  252. package/docs/upgrade.md +32 -6
  253. package/package.json +10 -5
  254. package/schemas/agent-key-registration.graphql +22 -0
  255. package/schemas/agent.graphql +3 -0
  256. package/schemas/federation.graphql +38 -1
  257. package/schemas/memory.graphql +84 -5
  258. package/schemas/oauth.graphql +19 -0
  259. package/schemas/schema.graphql +2 -0
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,7 +46,7 @@ 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, isHarperProcessCommandLine, sidecarStartAgrees, parseSidecarJson, classifyHealthProbe, classifyPortOwner, classifyInstanceMatch, shouldAdoptMissingSidecar, classifySidecarStaleness, shouldRemoveSidecarAfterStop, livenessFromKillError, parseNullSeparatedEnviron, extractRootPath, } from "./lib/daemon-liveness.js";
49
+ import { classifyDaemonState, verifyIdentity, isHarperProcessCommandLine, sidecarStartAgrees, parseSidecarJson, classifyHealthProbe, classifyPortOwner, classifyInstanceMatch, shouldAdoptMissingSidecar, classifySidecarStaleness, shouldRemoveSidecarAfterStop, livenessFromKillError, parseProcStatState, isExitedState, parseNullSeparatedEnviron, extractRootPath, } from "./lib/daemon-liveness.js";
46
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";
@@ -88,6 +92,7 @@ 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";
92
97
  import { FLAIR_AGENT_PERMISSION } from "./lib/flair-agent-role.js";
93
98
  // Federation crypto helpers + private-visibility filter live with the
@@ -143,7 +148,12 @@ const DEFAULT_OPS_PORT = 19925;
143
148
  const FABRIC_OPS_PORT = 9925;
144
149
  // DEFAULT_ADMIN_USER + resolveAdminUser (flag > FLAIR_ADMIN_USER env > "admin")
145
150
  // live in src/lib/auth-resolve.ts — imported above (flair#1345).
146
- 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;
147
157
  const HEALTH_POLL_INTERVAL_MS = 500;
148
158
  // flair#670 — single-host default for the Harper ops API bind address.
149
159
  // Loopback-only (+ the domain socket, always provisioned) shrinks the
@@ -267,15 +277,29 @@ export function launchdLauncherPath(packageRoot = flairPackageDir()) {
267
277
  * Write `content` to `path` atomically: write to a temp file in the SAME
268
278
  * directory, then rename over the target. Same-fs rename is atomic on POSIX,
269
279
  * so a reader never observes a half-written file. `mode` is applied to the
270
- * temp file from creation — pass 0o600 when `content` holds a secret, so the
271
- * 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.
272
284
  */
273
- export function writeFileAtomic(path, content, mode) {
285
+ export function writeFileAtomic(path, content, mode, options = {}) {
274
286
  const dir = dirname(path);
275
287
  mkdirSync(dir, { recursive: true });
276
288
  const tmpPath = join(dir, `.${basename(path)}.${process.pid}.${randomBytes(4).toString("hex")}.tmp`);
277
289
  try {
278
- 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
+ }
279
303
  renameSync(tmpPath, path);
280
304
  }
281
305
  catch (err) {
@@ -286,13 +310,25 @@ export function writeFileAtomic(path, content, mode) {
286
310
  throw err;
287
311
  }
288
312
  }
289
- /**
290
- * Write the admin password to `path` with mode 0600 from creation (flair#1573
291
- * slice a). The secret is written to a temp file in the same dir (0600) and
292
- * renamed into place, so it is never briefly world-readable.
293
- */
294
313
  export function writeAdminPassFile(path, content) {
295
- 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 });
296
332
  }
297
333
  /**
298
334
  * Which launchd label an existing installation for `dataDir` is actually
@@ -705,6 +741,27 @@ function readOpsPortFromConfig(path = configPath()) {
705
741
  catch { /* ignore */ }
706
742
  return null;
707
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
+ }
708
765
  /**
709
766
  * Unified port resolution: `--port` flag > `FLAIR_URL` env > Harper's own config
710
767
  * in the instance's data directory > (default install only) the per-user config
@@ -744,17 +801,9 @@ function readOpsPortFromConfig(path = configPath()) {
744
801
  * it is for the default install that has always relied on it.
745
802
  */
746
803
  function resolveHttpPort(opts, mode = "address") {
747
- if (opts.port !== undefined && opts.port !== null) {
748
- const n = Number(opts.port);
749
- if (!isNaN(n) && n > 0)
750
- return n;
751
- }
752
- const envUrl = process.env.FLAIR_URL;
753
- if (envUrl) {
754
- const m = envUrl.match(/:(\d+)/);
755
- if (m)
756
- return Number(m[1]);
757
- }
804
+ const named = namedHttpPort(opts);
805
+ if (named !== null)
806
+ return named;
758
807
  const dataDir = instanceDataDir(opts);
759
808
  // 1. Harper's own config for this instance. Once Harper has written one it is
760
809
  // the only answer — it is maintained by the process that binds the socket.
@@ -924,7 +973,13 @@ function applyAdminPassFile(opts) {
924
973
  process.exit(1);
925
974
  }
926
975
  }
927
- // 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).
928
983
  //
929
984
  // Deliberately NOT routed through Harper's per-instance config the way
930
985
  // resolveHttpPort is (flair#914). The last rung couples the ops port to the HTTP
@@ -934,11 +989,14 @@ function applyAdminPassFile(opts) {
934
989
  // which is the bug flair#914 fixed pointing the other way. The ops port becomes
935
990
  // per-instance when the lifecycle commands grow `--data-dir` and there is a
936
991
  // named instance to attribute it to.
937
- function resolveOpsPort(opts) {
992
+ function resolveOpsPort(opts, httpPortBase) {
938
993
  if (opts.opsPort !== undefined && opts.opsPort !== null) {
939
994
  const n = Number(opts.opsPort);
940
- if (!isNaN(n) && n > 0)
995
+ if (Number.isInteger(n) && n >= 1 && n <= 65535)
941
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);
942
1000
  }
943
1001
  const envOps = process.env.FLAIR_OPS_PORT;
944
1002
  if (envOps)
@@ -955,7 +1013,246 @@ function resolveOpsPort(opts) {
955
1013
  }
956
1014
  catch { /* ignore */ }
957
1015
  // Default: httpPort - 1
958
- 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));
959
1256
  }
960
1257
  // Ops API bind-host resolution (flair#670, #863): --ops-bind flag >
961
1258
  // FLAIR_OPS_BIND env > persisted `opsBind` in ~/.flair/config.yaml > loopback
@@ -1873,6 +2170,7 @@ async function api(method, path, body, options) {
1873
2170
  explicitAdminPass: options?.explicitAdminPass,
1874
2171
  adminUser: options?.adminUser,
1875
2172
  agentIdSource: options?.agentIdSource,
2173
+ signedOnly: options?.signedOnly,
1876
2174
  };
1877
2175
  try {
1878
2176
  return await authedRequest(method, path, body, requestOptions);
@@ -1946,12 +2244,13 @@ export async function verifyAuthedGet(baseUrl, path, keysDir) {
1946
2244
  export function isCredentialOnlyFailure(result) {
1947
2245
  return result.healthy === true && result.authFailureKind === "credentials";
1948
2246
  }
1949
- async function waitForHealth(httpPort, adminUser, adminPass, timeoutMs) {
2247
+ async function waitForHealth(httpPort, adminUser, adminPass, timeoutMs, beforeRequest) {
1950
2248
  const url = `http://127.0.0.1:${httpPort}/Health`;
1951
2249
  const deadline = Date.now() + timeoutMs;
1952
2250
  let attempt = 0;
1953
2251
  while (Date.now() < deadline) {
1954
2252
  attempt++;
2253
+ await beforeRequest?.();
1955
2254
  try {
1956
2255
  const res = await fetch(url, {
1957
2256
  headers: { Authorization: `Basic ${Buffer.from(`${adminUser}:${adminPass}`).toString("base64")}` },
@@ -2069,7 +2368,7 @@ export async function verifySemanticSearch(baseUrl, agentIdOpt, keysDir) {
2069
2368
  let stored = false;
2070
2369
  try {
2071
2370
  // Write the test memory (ephemeral so it's never durable). PUT /Memory/<id>.
2072
- const writeRes = await authFetch(baseUrl, agentId, keyPath, "PUT", `/Memory/${id}`, {
2371
+ const writeRes = await authFetch(baseUrl, agentId, keyPath, "PUT", `/Memory/${encodeRecordId(id)}`, {
2073
2372
  id, agentId, content, durability: "ephemeral", createdAt: new Date().toISOString(),
2074
2373
  });
2075
2374
  if (!writeRes.ok && writeRes.status !== 204) {
@@ -2135,7 +2434,7 @@ export async function verifySemanticSearch(baseUrl, agentIdOpt, keysDir) {
2135
2434
  // Best-effort cleanup of the ephemeral probe memory.
2136
2435
  if (stored) {
2137
2436
  try {
2138
- await authFetch(baseUrl, agentId, keyPath, "DELETE", `/Memory/${id}`);
2437
+ await authFetch(baseUrl, agentId, keyPath, "DELETE", `/Memory/${encodeRecordId(id)}`);
2139
2438
  }
2140
2439
  catch { /* leave the ephemeral row; it'll age out */ }
2141
2440
  }
@@ -2194,7 +2493,7 @@ export async function verifyAuditLog(baseUrl, agentIdOpt, keysDir, opsUrl, admin
2194
2493
  };
2195
2494
  }
2196
2495
  const id = `flair-doctor-audit-probe-${randomUUID()}`;
2197
- const path = `/Memory/${id}`;
2496
+ const path = `/Memory/${encodeRecordId(id)}`;
2198
2497
  let stored = false;
2199
2498
  try {
2200
2499
  // Write 1: PUT the probe row. Ephemeral durability — TTL is the cleanup
@@ -2369,7 +2668,7 @@ export async function checkAgentRegistered(baseUrl, agentId, keysDir) {
2369
2668
  return { state: "no-key", detail: `no local key for agent '${agentId}' to sign the check` };
2370
2669
  }
2371
2670
  try {
2372
- const res = await authFetch(baseUrl, agentId, keyPath, "GET", `/Agent/${agentId}`);
2671
+ const res = await authFetch(baseUrl, agentId, keyPath, "GET", `/Agent/${encodeRecordId(agentId)}`);
2373
2672
  if (res.ok)
2374
2673
  return { state: "registered" };
2375
2674
  if (res.status === 404)
@@ -2392,10 +2691,6 @@ export async function checkAgentRegistered(baseUrl, agentId, keysDir) {
2392
2691
  return { state: "unreachable", detail: `instance unreachable: ${message.slice(0, 100)}` };
2393
2692
  }
2394
2693
  }
2395
- // Blocks until the given PID is gone (ESRCH from signal 0), or timeout.
2396
- // Used during restart to confirm the old Harper process actually exited before
2397
- // we start polling /Health — otherwise the still-shutting-down old process can
2398
- // answer and we'd declare restart success while a gap is still ahead.
2399
2694
  /**
2400
2695
  * Is `pid` a process that exists right now? Signal 0 performs the permission
2401
2696
  * and existence checks without delivering anything (flair#1022) — a `hdb.pid`
@@ -2411,16 +2706,19 @@ function isProcessAlive(pid) {
2411
2706
  return false;
2412
2707
  }
2413
2708
  }
2414
- 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) {
2415
2714
  const deadline = Date.now() + timeoutMs;
2416
- while (Date.now() < deadline) {
2417
- try {
2418
- process.kill(pid, 0);
2419
- }
2420
- catch {
2715
+ while (true) {
2716
+ if (probe(pid).kind === "gone")
2421
2717
  return;
2422
- }
2423
- 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)));
2424
2722
  }
2425
2723
  throw new Error(`Process ${pid} did not exit within ${timeoutMs}ms`);
2426
2724
  }
@@ -2619,7 +2917,21 @@ export async function seedAgentViaOpsApi(opsPortOrUrl, agentId, pubKeyB64url, ad
2619
2917
  * data directory does not prove the passwords differ, and the HTTP holder
2620
2918
  * is not assumed to be the process that rejected this request.
2621
2919
  */
2622
- 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
+ }
2623
2935
  const url = typeof opsPortOrUrl === "number"
2624
2936
  ? `http://127.0.0.1:${opsPortOrUrl}/`
2625
2937
  : `${opsPortOrUrl.replace(/\/$/, "")}/`;
@@ -2632,23 +2944,30 @@ occupiedListener) {
2632
2944
  // and is invisible to roster/presence/Office-Space queries that filter on
2633
2945
  // status='active' or kind='agent' (#521). Mirror Agent.post() exactly here.
2634
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);
2635
2966
  const body = {
2636
2967
  operation: "insert",
2637
2968
  database: "flair",
2638
2969
  table: "Agent",
2639
- records: [{
2640
- id: agentId,
2641
- name: agentId,
2642
- type: "agent",
2643
- kind: "agent",
2644
- status: "active",
2645
- displayName: agentId,
2646
- admin: false,
2647
- defaultTrustTier: "unverified",
2648
- publicKey: pubKeyB64url,
2649
- createdAt: now,
2650
- updatedAt: now,
2651
- }],
2970
+ records: [record],
2652
2971
  };
2653
2972
  await opsSeedInsertWithRetry({
2654
2973
  url,
@@ -2667,7 +2986,7 @@ occupiedListener) {
2667
2986
  after = occupiedListener.reread();
2668
2987
  }
2669
2988
  catch {
2670
- after = { port: occupiedListener.before.port, pids: [], dataDirs: [] };
2989
+ after = { port: occupiedListener.before.port, pids: [], dataDirs: [], pidsKnown: false };
2671
2990
  }
2672
2991
  return occupiedListenerAuthFailure({
2673
2992
  lead: "Operations API insert failed (401): ",
@@ -2684,6 +3003,18 @@ occupiedListener) {
2684
3003
  // ops-insert body to the REST root, which Harper 405s as a collection POST to
2685
3004
  // /Agent (the Agent table resource has no POST handler). It was removed in the
2686
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
+ }
2687
3018
  // ─── FederationInstance seed via ops API ──────────────────────────────────────
2688
3019
  //
2689
3020
  // Remote init writes FederationInstance through the ops API (Basic auth with
@@ -3649,6 +3980,7 @@ bindInitCli({
3649
3980
  repointMainServiceUnit,
3650
3981
  resolveHttpPort,
3651
3982
  writeAdminPassFile,
3983
+ proveAdminPassAgainstInstance,
3652
3984
  resolveOpsBindHost,
3653
3985
  resolveHttpBindFor,
3654
3986
  resolveOpsPort,
@@ -3657,14 +3989,17 @@ bindInitCli({
3657
3989
  resolveTarget,
3658
3990
  runSoulWizard,
3659
3991
  seedAgentViaOpsApi,
3992
+ seedAgentWithLocalHome,
3660
3993
  seedFederationInstanceViaOpsApi,
3661
3994
  readOccupiedListener,
3995
+ resolveInstanceServingPid,
3662
3996
  shouldShowInlineSecretWarning,
3663
3997
  verifyAuditLog,
3664
3998
  verifySemanticSearch,
3665
3999
  waitForHealth,
3666
4000
  writeDaemonSidecar,
3667
4001
  registerInitLaunchdService,
4002
+ initLaunchdExitCode,
3668
4003
  MQTT_DISABLED_CONFIG,
3669
4004
  STARTUP_TIMEOUT_MS,
3670
4005
  });
@@ -3680,8 +4015,10 @@ bindAgentCli({
3680
4015
  shouldShowInlineSecretWarning,
3681
4016
  resolveHttpPort,
3682
4017
  resolveOpsPort,
4018
+ resolveAgentHomeTarget,
3683
4019
  resolveEffectiveOpsUrl,
3684
4020
  seedAgentViaOpsApi,
4021
+ seedAgentWithLocalHome,
3685
4022
  agentRecordIsAdmin,
3686
4023
  });
3687
4024
  registerAgent(program);
@@ -3692,6 +4029,9 @@ bindKeysCli({
3692
4029
  checkAgentRegistered,
3693
4030
  probeFlairReachable,
3694
4031
  resolveBaseUrl,
4032
+ resolveOpsPort,
4033
+ resolveHttpPort,
4034
+ readPortFromHarperConfig,
3695
4035
  });
3696
4036
  registerKeys(program);
3697
4037
  // ─── flair hook ──────────────────────────────────────────────────────────────
@@ -3721,6 +4061,8 @@ bindPrincipalCli({
3721
4061
  pubKeyPath,
3722
4062
  relativeTime,
3723
4063
  resolveOpsPort,
4064
+ resolveHttpPort,
4065
+ resolveAgentHomeTarget,
3724
4066
  });
3725
4067
  registerPrincipal(program);
3726
4068
  // ─── flair idp ───────────────────────────────────────────────────────────────
@@ -3740,6 +4082,14 @@ bindGrantCli({
3740
4082
  resolveAdminUser,
3741
4083
  });
3742
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);
3743
4093
  // ─── flair federation ────────────────────────────────────────────────────────
3744
4094
  // Command group lives in src/commands/federation.ts (flair#1620). Bind shared
3745
4095
  // helpers first so the extracted module never imports this file.
@@ -4048,11 +4398,61 @@ export function readSidecar(dataDir) {
4048
4398
  }
4049
4399
  return { kind: "present", ...parsed };
4050
4400
  }
4051
- /** `kill(pid, 0)` as a four-way: alive / gone (ESRCH) / eperm (another user's) / unknown. */
4052
- 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) {
4053
4454
  try {
4054
4455
  process.kill(pid, 0);
4055
- return { kind: "alive" };
4056
4456
  }
4057
4457
  catch (err) {
4058
4458
  // `gone` ONLY for ESRCH. Any other errno (EINVAL, EACCES, ...) is `unknown`,
@@ -4060,15 +4460,56 @@ function probePidLiveness(pid) {
4060
4460
  // classifier's unknown state (flair#2055).
4061
4461
  return livenessFromKillError(err?.code);
4062
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 };
4063
4498
  }
4064
4499
  /**
4065
4500
  * The health probe (flair#1478): ok only when the response is 2xx AND the
4066
4501
  * body is flair's /Health shape. A decoy that answers 200 is `foreign`,
4067
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).
4068
4509
  */
4069
4510
  async function probeHealth(port) {
4070
4511
  try {
4071
- 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) });
4072
4513
  let body;
4073
4514
  try {
4074
4515
  body = await res.json();
@@ -4079,12 +4520,56 @@ async function probeHealth(port) {
4079
4520
  return classifyHealthProbe({ kind: "response", status: res.status, body });
4080
4521
  }
4081
4522
  catch (err) {
4082
- // Node's undici fetch reports ECONNREFUSED on `err.cause.code`; Bun reports
4083
- // `ConnectionRefused` on `err.code`. Both mean "nothing is listening".
4084
4523
  const code = err?.cause?.code ?? err?.code;
4085
4524
  return classifyHealthProbe({ kind: "network-error", code });
4086
4525
  }
4087
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
+ }
4088
4573
  /**
4089
4574
  * PIDs LISTENING on `port` via `lsof -ti :<port> -sTCP:LISTEN`, or null
4090
4575
  * when lsof is absent / unusable. Empty array means lsof ran and saw no
@@ -4172,12 +4657,22 @@ function inspectServingFlairPackage(pid) {
4172
4657
  return null;
4173
4658
  return resolveServingFlairPackage(pid) !== null;
4174
4659
  }
4175
- /** Gather every piece of evidence the classifier needs, in one place. */
4176
- export async function gatherDaemonEvidence(port, dataDir) {
4660
+ export function gatherDaemonOwnerEvidence(dataDir) {
4177
4661
  const dataDirUnsafe = checkDataDirSafe(dataDir);
4178
4662
  const pidfile = readPidfile(dataDir);
4179
- const pidLiveness = pidfile.kind === "present" ? probePidLiveness(pidfile.pid) : null;
4180
- 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;
4181
4676
  // flair#2055: a sidecar that names a pid which is CONFIRMED gone is STALE, not
4182
4677
  // a disagreement with hdb.pid. After `flair stop` ended a directly started
4183
4678
  // Harper, the sidecar it wrote still names the stopped pid; a later instance
@@ -4189,7 +4684,7 @@ export async function gatherDaemonEvidence(port, dataDir) {
4189
4684
  // Liveness that cannot be determined is NOT stale: the sidecar stays and the
4190
4685
  // refusal stands (unknown evidence never licenses an action).
4191
4686
  if (sidecar.kind === "present" && dataDirUnsafe === null) {
4192
- if (classifySidecarStaleness(sidecar, probePidLiveness(sidecar.pid)).kind === "stale") {
4687
+ if (classifySidecarStaleness(sidecar, sidecarLiveness).kind === "stale") {
4193
4688
  sidecar = { kind: "absent" };
4194
4689
  }
4195
4690
  }
@@ -4210,8 +4705,7 @@ export async function gatherDaemonEvidence(port, dataDir) {
4210
4705
  // A stale or foreign pid holding the port is NOT healed. False-green is
4211
4706
  // worse than no self-heal.
4212
4707
  //
4213
- // The write uses the same O_NOFOLLOW / 0600 / atomic-rename posture as every
4214
- // 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
4215
4709
  // (symlink / world-writable) — the check has already happened above.
4216
4710
  let portOwner = { kind: "unavailable" };
4217
4711
  let instanceMatch = { kind: "unavailable" };
@@ -4257,15 +4751,14 @@ export async function gatherDaemonEvidence(port, dataDir) {
4257
4751
  sidecar,
4258
4752
  readStartTime: readProcessStartTimeMs,
4259
4753
  });
4260
- return { dataDirUnsafe, pidfile, pidLiveness, identity, health };
4754
+ return { ...owner, identity, health };
4261
4755
  }
4262
4756
  /**
4263
- * Write the identity sidecar atomically (temp + rename) at spawn time or
4264
- * during self-heal (flair#1454 decision 3). `pid` is the spawned process's
4265
- * pid — the same number Harper writes to `hdb.pid`, since Harper runs
4266
- * 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.
4267
4760
  *
4268
- * 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
4269
4762
  * readProcessStartTimeMs) so the sidecar records an accurate epoch, not a
4270
4763
  * wall-clock approximation. Note: in the self-heal path the ±2s start-time
4271
4764
  * check in verifyIdentity is NOT what prevents recycled-pid adoption —
@@ -4288,40 +4781,17 @@ function writeDaemonSidecar(dataDir, pid, port, startTimeMs = Date.now()) {
4288
4781
  chmodSync(finalPath, 0o600);
4289
4782
  }
4290
4783
  /**
4291
- * Remove the identity sidecar left behind by a stop (flair#2055).
4292
- *
4293
- * A sidecar that still names a pid which is CONFIRMED gone is a leftover, and
4294
- * leaving it makes a later instance under a DIFFERENT supervisor refuse
4295
- * ("its identity could not be verified"). The removal is gated twice:
4296
- *
4297
- * 1. the pid the sidecar names must be CONFIRMED gone (ESRCH) — `unknown` or
4298
- * EPERM liveness removes nothing; and
4299
- * 2. a FRESH O_NOFOLLOW read taken just before the unlink must still name
4300
- * that pid. A sidecar another supervisor rewrote in between names a
4301
- * different pid and is left alone; a symlinked or malformed one reads as
4302
- * `unreadable` and is not removed either, because the re-read never
4303
- * followed the link.
4304
- *
4305
- * There is no lock: the re-read narrows the window to the gap between the read
4306
- * and the unlink, and the only loser of that race is a start that rewrote the
4307
- * sidecar in the gap — a live daemon left with no sidecar, which a later
4308
- * port-based stop or restart can RECOVER by self-heal once the live process
4309
- * supplies the required pidfile and health evidence (shouldAdoptMissingSidecar
4310
- * adopts the identity from the live process; see the recovery test). `flair
4311
- * status` does not re-adopt. A lock would buy
4312
- * nothing here and add a crash-recovery hazard, so the design relies on the
4313
- * self-heal instead. A writer OUTSIDE flair could substitute a symlink after
4314
- * the final read; that is out of scope (same as any other path flair re-reads
4315
- * by name). Best-effort: a failure to unlink is reported, never fatal.
4316
- */
4317
- export function removeStaleSidecarIfConfirmedDead(dataDir) {
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) {
4318
4789
  const observed = readSidecar(dataDir);
4319
4790
  if (observed.kind !== "present")
4320
4791
  return;
4321
4792
  const observedPid = observed.pid;
4322
- const observedPidLiveness = probePidLiveness(observedPid);
4323
- // Re-read: only the sidecar that still names the confirmed-dead pid is ours
4324
- // to remove (a sidecar rewritten in the gap is left alone).
4793
+ const observedPidLiveness = confirmedGonePid !== null && confirmedGonePid === observedPid ? { kind: "gone" } : probe(observedPid);
4794
+ // A re-read naming a different PID is left alone.
4325
4795
  const fresh = readSidecar(dataDir);
4326
4796
  if (!shouldRemoveSidecarAfterStop({ observedPid, observedPidLiveness, sidecar: fresh }))
4327
4797
  return;
@@ -4397,6 +4867,7 @@ bindServiceCli({
4397
4867
  ensureLaunchdServiceLoaded,
4398
4868
  flairPackageDir,
4399
4869
  gatherDaemonEvidence,
4870
+ gatherDaemonOwnerEvidence,
4400
4871
  guardEngineNotBackwards,
4401
4872
  harperBinNotFoundMessage,
4402
4873
  harperSearchRoots,
@@ -4405,6 +4876,7 @@ bindServiceCli({
4405
4876
  observeLaunchdManagement,
4406
4877
  probeHealth,
4407
4878
  readyOpsSocketPosture,
4879
+ recordManagedStartSidecar,
4408
4880
  resolveHarperBin,
4409
4881
  resolveHttpBindHost,
4410
4882
  resolveHttpPort,
@@ -4576,10 +5048,11 @@ function validateLaunchdPlistContent(content, lint = lintLaunchdPlistContent) {
4576
5048
  * `null` (neither available) is handled by the caller as "no evidence", never
4577
5049
  * as "detached".
4578
5050
  */
4579
- function resolveInstanceServingPid(dataDir, port) {
5051
+ function resolveInstanceServingPid(dataDir, port, deps = {}) {
4580
5052
  let listeningPids = [];
4581
5053
  try {
4582
- 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" }));
4583
5056
  }
4584
5057
  catch { /* lsof unavailable — the PID file may still answer */ }
4585
5058
  // flair#2056: the `hdb.pid` pid is used as PID-file evidence only when it is
@@ -4597,11 +5070,11 @@ function resolveInstanceServingPid(dataDir, port) {
4597
5070
  if (sidecar.kind === "present") {
4598
5071
  if (sidecar.pid !== pid)
4599
5072
  return false;
4600
- const startSecondMs = readProcessStartSecondMs(pid);
5073
+ const startSecondMs = (deps.readStartSecondMs ?? readProcessStartSecondMs)(pid);
4601
5074
  if (startSecondMs === null || !sidecarStartAgrees(startSecondMs, sidecar.startTimeMs))
4602
5075
  return false;
4603
5076
  }
4604
- const cmdline = defaultReadProcessCmdline(pid);
5077
+ const cmdline = (deps.readCmdline ?? defaultReadProcessCmdline)(pid);
4605
5078
  return cmdline !== null && isHarperProcessCommandLine(cmdline);
4606
5079
  };
4607
5080
  return pickInstancePid({
@@ -4947,6 +5420,92 @@ function observeLaunchdManagement(dataDir, port) {
4947
5420
  list: realLaunchctlLister,
4948
5421
  });
4949
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
+ }
4950
5509
  // `preserveHttpPortValue` / `preserveSecurePort` / `bindHostOf` live in
4951
5510
  // src/lib/http-bind.ts so the CLI's plist writer and the pure repair PLANNER
4952
5511
  // (src/lib/launchd-repair.ts) share the exact same preservation rules, and the
@@ -5088,24 +5647,24 @@ function resolveAdminPassAvailability(path) {
5088
5647
  `Run 'flair init' to provision ${path}, or start the instance and re-run 'flair doctor --fix'.`,
5089
5648
  };
5090
5649
  }
5091
- /**
5092
- * Prove an admin credential belongs to the running instance before adoption
5093
- * materializes it into the 0600 pass file (flair#1685). The admin-gated
5094
- * /HealthDetail read is the proof: a rejected Basic credential produces 401 and
5095
- * is NOT retried through the agent-key floor (that floor only engages when no
5096
- * credential was sent at all), so success here means THIS credential was
5097
- * accepted by THIS instance. Never logs the secret.
5098
- */
5099
- async function proveAdminPassAgainstInstance(port, adminPass) {
5650
+ export async function proveAdminPassAgainstInstance(port, adminPass) {
5100
5651
  try {
5101
- await api("GET", "/HealthDetail", undefined, {
5652
+ await api("GET", "/FederationPeers", undefined, {
5102
5653
  baseUrl: `http://127.0.0.1:${port}`,
5103
5654
  explicitAdminPass: adminPass,
5655
+ adminUser: DEFAULT_ADMIN_USER,
5104
5656
  });
5105
5657
  return null;
5106
5658
  }
5107
5659
  catch (err) {
5108
- 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})`;
5109
5668
  }
5110
5669
  }
5111
5670
  /**
@@ -5150,10 +5709,6 @@ function validateAdminPassFileForLauncher(path) {
5150
5709
  * file and the command named and write NO plist. Never a plist whose
5151
5710
  * launcher argv cannot be satisfied.
5152
5711
  *
5153
- * The proof uses the same authed `GET /HealthDetail` as the doctor arms (a
5154
- * rejected Basic credential is a 401 and never falls through to the agent-key
5155
- * floor), so a credential that does not belong to THIS instance is refused
5156
- * rather than baked into a pass file the instance would reject.
5157
5712
  */
5158
5713
  export async function writeInitLaunchdPlist(opts, deps = {}) {
5159
5714
  const prove = deps.prove ?? proveAdminPassAgainstInstance;
@@ -5293,8 +5848,16 @@ export async function writeInitLaunchdPlist(opts, deps = {}) {
5293
5848
  return { kind: "written", plistPath: opts.plistPath };
5294
5849
  }
5295
5850
  /**
5296
- * Put the plist `flair init` wrote back as `prior` recorded it (flair#2040,
5297
- * flair#2078): its prior bytes, or removed when there was none. Never throws:
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:
5298
5861
  * `ok` false means the put-back FAILED, and `text` says so with the error.
5299
5862
  */
5300
5863
  function putInitPlistBack(path, prior) {
@@ -5306,12 +5869,29 @@ function putInitPlistBack(path, prior) {
5306
5869
  }
5307
5870
  return {
5308
5871
  ok: true,
5309
- 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`,
5310
5873
  };
5311
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
+ }
5312
5891
  /**
5313
- * `flair init`'s launchd step (flair#2040): write this instance's plist, retire
5314
- * a pre-flair#693 legacy registration, and report ONLY what was verified.
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.
5315
5895
  *
5316
5896
  * init starts Flair DIRECTLY and, since 9e3bd9ad, deliberately does not bounce
5317
5897
  * a running instance into launchd — so the ordinary outcome is "plist on disk,
@@ -5322,21 +5902,29 @@ function putInitPlistBack(path, prior) {
5322
5902
  * The one path that stops something is retiring a LEGACY job that is the
5323
5903
  * process serving this instance: booting it out stops Flair. That path follows
5324
5904
  * the same rule as `doctor --fix`: preflight first (domain reachable, job
5325
- * enabled), write + validate the replacement plist while the instance is still
5905
+ * enabled), prepare + validate the replacement plist while the instance is still
5326
5906
  * up, and only then boot the legacy job out, load the replacement with
5327
- * targeted commands and verify it; any failure after the boot-out restores the
5328
- * legacy plist and job (or, failing that, starts Flair directly) and says so.
5907
+ * targeted commands, and verify it.
5329
5908
  * If the preflight fails, NOTHING is unloaded, removed or written; if the
5330
- * validation fails — a lint that throws included (flair#2078) — nothing is
5331
- * unloaded or removed, and the plist init wrote is put back as it was.
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).
5332
5912
  */
5333
- async function registerInitLaunchdService(input) {
5913
+ async function registerInitLaunchdService(input, validateAfterWrite = validateInitPlistAfterWrite) {
5334
5914
  const { dataDir, port, plistDir, write } = input;
5335
5915
  const uid = currentUid();
5336
5916
  const domain = launchdGuiDomain(uid);
5337
5917
  const lines = [];
5338
5918
  const out = (text) => lines.push({ stream: "out", text });
5339
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
+ };
5340
5928
  const legacyPath = launchdPlistPath(LEGACY_LAUNCHD_LABEL, plistDir);
5341
5929
  const legacyRoot = existsSync(legacyPath) ? readPlistRootPath(legacyPath) : null;
5342
5930
  const legacyOwned = legacyRoot !== null && resolve(legacyRoot) === resolve(dataDir);
@@ -5345,9 +5933,35 @@ async function registerInitLaunchdService(input) {
5345
5933
  // helper prints why. With no legacy plist it is a no-op.
5346
5934
  if (existsSync(legacyPath))
5347
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
+ }
5348
5951
  const outcome = await writeInitLaunchdPlist(write);
5349
5952
  if (outcome.kind === "refused")
5350
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;
5351
5965
  return reportInitLaunchd(dataDir, port, write, outcome, lines);
5352
5966
  }
5353
5967
  const keptLegacy = `Nothing was unloaded or removed: the legacy job ${LEGACY_LAUNCHD_LABEL} and its plist at ${legacyPath} were left as they were`;
@@ -5413,13 +6027,18 @@ async function registerInitLaunchdService(input) {
5413
6027
  // cannot be read cannot be put back: refuse before anything is written.
5414
6028
  const priorNew = snapshotFile(write.plistPath);
5415
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
+ }
5416
6035
  const unreadable = unreadableSnapshot([[write.plistPath, priorNew], [legacyPath, priorLegacy]]);
5417
6036
  if (unreadable) {
5418
- 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}.`);
5419
6038
  return { kind: "skipped", lines };
5420
6039
  }
5421
- // The replacement is written and validated while the instance is still up
5422
- // (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.
5423
6042
  const outcome = await writeInitLaunchdPlist(write);
5424
6043
  if (outcome.kind === "refused") {
5425
6044
  return {
@@ -5430,45 +6049,26 @@ async function registerInitLaunchdService(input) {
5430
6049
  ],
5431
6050
  };
5432
6051
  }
5433
- // Every failed validation is a refusal made before anything is unloaded: a
5434
- // problem the checks REPORT, and — as in the start paths' migration — a lint
5435
- // that THROWS (lintReplacementPlist) or a written plist that cannot be read
5436
- // back (flair#2078). Each puts the plist just written back as it was, or
5437
- // removes it when there was none: left beside the legacy plist, it would give
5438
- // launchd two jobs for one data directory at the next login.
5439
- const installing = `the plist init would install for ${write.label}`;
5440
- let refusal = null;
5441
- try {
5442
- const problem = validateLaunchdPlistContent(readFileSync(write.plistPath, "utf-8"), (content) => lintReplacementPlist(content, launchdMigrationLintForTests ?? lintLaunchdPlistContent, (failure) => `${installing} could not be validated (${failure})`));
5443
- if (problem !== null) {
5444
- refusal = { why: `${installing} cannot be loaded (${problem})`, fix: "npm install -g @tpsdev-ai/flair && flair init" };
5445
- }
5446
- }
5447
- catch (e) {
5448
- refusal = isLaunchdValidationRefusal(e)
5449
- ? { why: e.message, fix: `make sure the temporary directory (${tmpdir()}) exists and is writable, and re-run 'flair init'.` }
5450
- : { why: `${installing} could not be validated (${e?.message ?? String(e)})`, fix: "resolve the error above, and re-run 'flair init'." };
5451
- }
5452
- if (refusal !== null) {
5453
- const putBack = putInitPlistBack(write.plistPath, priorNew);
6052
+ const refused = refuseInvalidPlist(priorNew, (refusal, putBack) => {
5454
6053
  err(`⚠️ Launchd: not re-registered — ${refusal.why}. Nothing was unloaded: the legacy job ${LEGACY_LAUNCHD_LABEL} ` +
5455
6054
  `and its plist at ${legacyPath} were left as they were, and ${putBack.text}.`);
5456
6055
  if (!putBack.ok) {
5457
6056
  err(` Fix: remove ${write.plistPath} (beside the legacy plist, launchd would load two jobs for this data ` +
5458
6057
  `directory at the next login); then ${refusal.fix}`);
5459
- return { kind: "uncertain", lines };
5460
6058
  }
5461
- err(` Fix: ${refusal.fix}`);
5462
- return { kind: "skipped", lines };
5463
- }
6059
+ else {
6060
+ err(` Fix: ${refusal.fix}`);
6061
+ }
6062
+ });
6063
+ if (refused)
6064
+ return refused;
5464
6065
  if (role !== "serving") {
5465
6066
  // PROVEN not serving (absent, or idle): retiring it stops nothing.
5466
6067
  const cleanup = cleanupLegacyLaunchdPlist(dataDir, plistDir, realLaunchctlCommand, uid);
5467
6068
  if (cleanup.action === "unload-unconfirmed") {
5468
6069
  // flair#2040: the legacy job could not be shown unloaded, and the helper
5469
- // KEPT its plist. The replacement written above must not stay beside it
5470
- // (two plists for one data directory would give launchd two jobs), so it
5471
- // is put back as it was, and nothing is reported as registered.
6070
+ // KEPT its plist. Rollback attempts to restore the target's prior state;
6071
+ // the result is uncertain even if rollback succeeds.
5472
6072
  const putBack = putInitPlistBack(write.plistPath, priorNew);
5473
6073
  err(`⚠️ Launchd: not re-registered — the legacy job ${LEGACY_LAUNCHD_LABEL} could not be shown unloaded ` +
5474
6074
  `(${cleanup.unloadFailed}), so it may still be loaded. Its plist at ${legacyPath} was left in place, and ${putBack.text}.`);
@@ -5745,10 +6345,7 @@ function planLaunchdRepairFor(dataDir, port) {
5745
6345
  * TWO PHASES (flair#2040). The rule for this handoff: the running instance
5746
6346
  * is not stopped, and no launchd job is unloaded, until every check that can
5747
6347
  * be made about the replacement from THIS session has passed; an UNKNOWN
5748
- * answer is a failed check, never a pass. Every failure after that point is
5749
- * followed by an attempt to bring back what was running, and the result
5750
- * reports the state the instance was left in — including when that state
5751
- * could not be established.
6348
+ * answer is a failed check, never a pass.
5752
6349
  *
5753
6350
  * 1. PREPARE (prepareLaunchdRepair) — reads and validation; the running
5754
6351
  * instance and launchd are untouched:
@@ -5778,14 +6375,7 @@ function planLaunchdRepairFor(dataDir, port) {
5778
6375
  * its port does not answer, and verify STRICTLY: Flair's /Health answers
5779
6376
  * ok and launchd's pid is the IDENTIFIED serving pid
5780
6377
  * (judgeLaunchdJobServing), and on adopt the serving pid
5781
- * changed and the old one is dead (flair#1684/#1685). ANY failure here
5782
- * goes through restoreAfterFailedRepair.
5783
- *
5784
- * The preflight cannot PROVE a bootstrap will succeed — only loading something
5785
- * proves that — which is why phase 2 restores rather than assumes.
5786
- *
5787
- * Never reports success on a direct start or an unattributed process. Every
5788
- * throw becomes a named result, never a crash mid-report.
6378
+ * changed and the old one is dead (flair#1684/#1685).
5789
6379
  */
5790
6380
  async function repairLaunchdManagement(dataDir, port) {
5791
6381
  const { plan, plistPath, isLegacy, config } = planLaunchdRepairFor(dataDir, port);
@@ -5818,31 +6408,54 @@ async function repairLaunchdManagement(dataDir, port) {
5818
6408
  }
5819
6409
  }
5820
6410
  function snapshotFile(path) {
6411
+ let stat;
5821
6412
  try {
5822
- const bytes = readFileSync(path);
5823
- return { kind: "present", bytes, mode: statSync(path).mode & 0o777 };
6413
+ stat = lstatSync(path);
5824
6414
  }
5825
6415
  catch (err) {
5826
6416
  if (err?.code === "ENOENT")
5827
6417
  return { kind: "absent" };
5828
6418
  return { kind: "unreadable", error: `${err?.code ?? "error"}: ${err?.message ?? err}` };
5829
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
+ }
5830
6439
  }
5831
6440
  /** The first snapshot that could not be taken, as "<path> (<error>)", or null. */
5832
6441
  function unreadableSnapshot(entries) {
5833
6442
  for (const [path, snap] of entries) {
5834
- if (snap && snap.kind === "unreadable")
6443
+ if (snap?.kind === "symlink")
6444
+ return `${path} (symbolic link)`;
6445
+ if (snap?.kind === "unreadable")
5835
6446
  return `${path} (${snap.error})`;
5836
6447
  }
5837
6448
  return null;
5838
6449
  }
5839
6450
  /**
5840
6451
  * Put a file back as `snapshot` recorded it: rewritten byte-for-byte (the raw
5841
- * buffer) when it was present, removed ONLY when it was proven absent. An
5842
- * unreadable snapshot is never "restored" — that would delete or clobber a
5843
- * file whose bytes were never known.
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.
5844
6454
  */
5845
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
+ }
5846
6459
  if (snapshot.kind === "unreadable") {
5847
6460
  throw new Error(`not restoring ${path}: its prior contents could not be read (${snapshot.error})`);
5848
6461
  }
@@ -5856,7 +6469,7 @@ function restoreFile(path, snapshot) {
5856
6469
  }
5857
6470
  return;
5858
6471
  }
5859
- writeFileAtomic(path, snapshot.bytes, snapshot.mode);
6472
+ writeFileAtomic(path, snapshot.bytes, snapshot.mode, { exactMode: true });
5860
6473
  }
5861
6474
  /**
5862
6475
  * Phase 1 of the repair: every check that can be made without stopping the
@@ -5902,7 +6515,7 @@ async function prepareLaunchdRepair(dataDir, port, plan, resolvedPlistPath, isLe
5902
6515
  return {
5903
6516
  kind: "refused",
5904
6517
  reason: "unreadable-prior-state",
5905
- 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 ` +
5906
6519
  `could not put it back. ${untouched}`,
5907
6520
  plistPath: resolvedPlistPath,
5908
6521
  };
@@ -6027,7 +6640,6 @@ async function prepareLaunchdRepair(dataDir, port, plan, resolvedPlistPath, isLe
6027
6640
  },
6028
6641
  };
6029
6642
  }
6030
- /** Phase 2: the bounce, with restore on any failure. */
6031
6643
  async function commitLaunchdRepair(p) {
6032
6644
  const done = { unloadedPrior: false, stopped: false, wrotePlist: false, removedLegacy: false, wroteConfig: false, loaded: false };
6033
6645
  try {
@@ -6049,10 +6661,18 @@ async function commitLaunchdRepair(p) {
6049
6661
  // job does not collide on the port. The captured pid is the evidence the
6050
6662
  // verify uses to prove the serving pid CHANGED.
6051
6663
  if (p.arm === "adopt") {
6052
- done.stopped = true;
6053
6664
  const stop = await stopDirectProcessForAdopt(p.port, p.dataDir);
6054
- if (stop)
6055
- throw new Error(stop.kind === "failed" || stop.kind === "refused" ? stop.detail : "the direct process could not be stopped");
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;
6056
6676
  }
6057
6677
  // 3. Write the validated plist (pass-file mode, no secret: 0644).
6058
6678
  done.wrotePlist = true;
@@ -6249,7 +6869,7 @@ async function restoreAfterFailedRepair(p, done, cause) {
6249
6869
  }
6250
6870
  /**
6251
6871
  * Clean-stop the direct (non-launchd) process serving `dataDir`+`port` for the
6252
- * 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
6253
6873
  * cannot be attributed (never stop a foreign process) or the port is still
6254
6874
  * occupied after the stop; returns null when the port is free and the caller
6255
6875
  * should proceed to regenerate + load.
@@ -6262,41 +6882,104 @@ async function restoreAfterFailedRepair(p, done, cause) {
6262
6882
  async function stopDirectProcessForAdopt(port, dataDir) {
6263
6883
  const evidence = await gatherDaemonEvidence(port, dataDir);
6264
6884
  const state = classifyDaemonState(evidence, { port, dataDir });
6265
- // SIGTERM + wait for exit for a verified live pid (RUNNING or WEDGED — a
6266
- // 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
+ });
6267
6893
  if (state.state === "RUNNING" || state.state === "WEDGED") {
6894
+ let signalResult = "SIGTERM sent";
6268
6895
  try {
6269
6896
  process.kill(state.pid, "SIGTERM");
6270
6897
  }
6271
- catch { /* already gone */ }
6272
- try {
6273
- 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"})`;
6274
6900
  }
6275
- catch { /* best-effort — the port check below surfaces the real problem */ }
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);
6917
+ }
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
+ });
6276
6949
  }
6277
- // flair#1827: poll the post-stop health until the port is provably free — a
6278
- // single observation that caught the listener mid-release flaked with "port
6279
- // not confirmed free". decideAdoptStop is UNCHANGED; it decides on the final
6280
- // observation, and a timeout names the wait and the last probe.
6281
- const decision = await decideAdoptStopWithWait(state, {
6282
- observe: () => probeHealth(port),
6283
- deadlineMs: STARTUP_TIMEOUT_MS,
6284
- });
6285
- if (decision.decision !== "proceed")
6286
- return decision.decision;
6287
- // Belt-and-suspenders: lsof confirms no TCP listener remains before the
6288
- // caller loads the plist. probeHealth "refused" (ECONNREFUSED) already means
6289
- // nothing is listening, but a port that is BOUND yet refuses connections
6290
- // (backlog-full, or a non-HTTP listener) would still EADDRINUSE on load —
6291
- // this catches that rare case the HTTP probe cannot see.
6292
- const { execSync } = await import("node:child_process");
6293
- 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);
6294
6977
  if (listeners.length > 0) {
6295
- return {
6978
+ return failure({
6296
6979
  kind: "failed",
6297
6980
  detail: `port still occupied after stopping the direct process (listener pid ${listeners.join(", ")})`,
6298
6981
  remedy: ["flair stop", "flair doctor --fix"],
6299
- };
6982
+ });
6300
6983
  }
6301
6984
  return null;
6302
6985
  }
@@ -6324,7 +7007,16 @@ async function stopDirectProcessForAdopt(port, dataDir) {
6324
7007
  * the liveness machine. Callers already treat a failed stop as fatal, which
6325
7008
  * is the point: refusing beats quiescing the wrong install.
6326
7009
  */
6327
- 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
+ };
6328
7020
  if (process.platform === "darwin") {
6329
7021
  // resolveLaunchdLabel (flair#693) finds whichever label this data dir
6330
7022
  // is currently registered under (new instance-scoped, or a
@@ -6372,22 +7064,33 @@ async function stopFlairProcess(port, dataDir) {
6372
7064
  plistPath,
6373
7065
  instancePid: oldPid,
6374
7066
  plistExists: existsSync,
6375
- list: realLaunchctlLister,
7067
+ list: opts.launchctl?.list ?? realLaunchctlLister,
6376
7068
  })
6377
7069
  : null;
6378
7070
  // unload stops the job AND prevents KeepAlive from respawning it.
6379
7071
  // launchctl stop alone is insufficient for a KeepAlive job (flair#874).
6380
7072
  try {
6381
- execSync(`launchctl unload "${plistPath}"`, { stdio: "pipe" });
7073
+ if (opts.launchctl)
7074
+ opts.launchctl.unload(plistPath);
7075
+ else
7076
+ execSync(`launchctl unload "${plistPath}"`, { stdio: "pipe" });
6382
7077
  }
6383
7078
  catch { }
6384
7079
  if (managed && isDetached(managed)) {
6385
7080
  throw new Error(`launchd is not running this instance — ${managed.detail}`
6386
7081
  + `${managed.remedy?.length ? ` Fix it with: ${managed.remedy.join(" && ")}` : ""}`);
6387
7082
  }
6388
- if (oldPid)
6389
- await waitForProcessExit(oldPid, STARTUP_TIMEOUT_MS);
6390
- 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 };
6391
7094
  }
6392
7095
  catch (err) {
6393
7096
  console.error(`launchd stop failed, falling back to port-based stop: ${err.message}`);
@@ -6417,29 +7120,30 @@ async function stopFlairProcess(port, dataDir) {
6417
7120
  // blind sleep is not a guarantee — Harper may be flushing RocksDB
6418
7121
  // WAL/MANIFEST, and the next start fails with a locked data directory if
6419
7122
  // the old process hasn't released it yet.
7123
+ let exited = true;
6420
7124
  try {
6421
- await waitForProcessExit(pid, STARTUP_TIMEOUT_MS);
7125
+ await waitForExit(pid, STARTUP_TIMEOUT_MS);
6422
7126
  }
6423
- catch { /* best-effort — the next start will surface the real problem */ }
6424
- // flair#2055: once the process is CONFIRMED gone, drop the identity
6425
- // sidecar. Gated on a fresh O_NOFOLLOW read that still names the pid it
6426
- // named before (a sidecar another supervisor rewrote in between is left
6427
- // alone); a process that survived the wait (or whose liveness is unknown)
6428
- // removes nothing.
6429
- removeStaleSidecarIfConfirmedDead(dataDir);
6430
- return;
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 });
6431
7134
  }
6432
7135
  case "NOT_RUNNING": {
6433
- // Idempotent no-op for the process — but a sidecar left naming a pid that
6434
- // is CONFIRMED gone is a leftover too (flair#2055), and removing it here
6435
- // keeps a repeat stop from carrying the refusal forward.
7136
+ // Probe the sidecar's PID before best-effort removal.
6436
7137
  removeStaleSidecarIfConfirmedDead(dataDir);
6437
- return;
7138
+ return fallbackOutcome({ pid: null, exited: true });
6438
7139
  }
6439
7140
  case "DISAGREEMENT":
6440
7141
  case "UNKNOWN":
6441
7142
  // Deliberately outside any catch: a refusal must reach the caller, not
6442
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
+ }
6443
7147
  throw new Error(`refusing to stop: ${state.detail}`);
6444
7148
  }
6445
7149
  }
@@ -6531,7 +7235,9 @@ async function startFlairProcess(port, dataDir) {
6531
7235
  throw new LaunchdValidationRefusal(`${stalePlist.message} Fix it with: ${stalePlist.remedy.join(" && ")}`);
6532
7236
  }
6533
7237
  ensureLaunchdServiceLoaded(dataDir, realLaunchctlCommand);
6534
- 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
+ });
6535
7241
  readyOpsSocketPosture(dataDir); // flair#763: re-assert socket posture across restart/upgrade
6536
7242
  stampEngineVersionIfRunning(dataDir); // flair#1047: stamp the store with the engine version
6537
7243
  return;
@@ -6607,6 +7313,21 @@ async function startFlairDirect(port, dataDir) {
6607
7313
  stampEngineVersionIfRunning(dataDir); // flair#1047: stamp the store with the engine version
6608
7314
  return proc.pid ?? null;
6609
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
+ }
6610
7331
  /**
6611
7332
  * The ONE restart mechanism for a local Flair install. Shared by `flair
6612
7333
  * restart` and `flair upgrade`'s post-install restart step (flair#635) so
@@ -6623,7 +7344,20 @@ async function startFlairDirect(port, dataDir) {
6623
7344
  * named at the call site rather than assumed from `defaultDataDir()` two
6624
7345
  * frames down.
6625
7346
  */
6626
- 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
+ };
6627
7361
  // flair#2034 §2: on Linux, an instance proven to run under a systemd USER
6628
7362
  // unit (found from the serving process's cgroup; its MainPID is that
6629
7363
  // process) is restarted THROUGH that unit, and the unit's new main process
@@ -6661,8 +7395,8 @@ async function restartFlair(port, dataDir) {
6661
7395
  guardEngineNotBackwards(dataDir);
6662
7396
  },
6663
7397
  direct: async () => {
6664
- await stopFlairProcess(port, dataDir);
6665
- await startFlairProcess(port, dataDir);
7398
+ await stopForRestart();
7399
+ await startReplacement(port, dataDir);
6666
7400
  },
6667
7401
  log: (line) => console.log(line),
6668
7402
  });
@@ -6672,8 +7406,8 @@ async function restartFlair(port, dataDir) {
6672
7406
  }
6673
7407
  }
6674
7408
  else {
6675
- await stopFlairProcess(port, dataDir);
6676
- await startFlairProcess(port, dataDir);
7409
+ await stopForRestart();
7410
+ await startReplacement(port, dataDir);
6677
7411
  }
6678
7412
  // Bust the version-handshake cache so the next preAction nudge re-fetches
6679
7413
  // the LIVE version instead of the pre-restart cached one (the false
@@ -6804,6 +7538,7 @@ registerTest(program);
6804
7538
  // Command registration lives in src/commands/deploy.ts (flair#1636).
6805
7539
  // Bind shared cli-locals first so the extracted module never imports this file.
6806
7540
  bindDeployCli({
7541
+ resolveEffectiveOpsUrl,
6807
7542
  fleetSweepCallerExitMessage,
6808
7543
  resolveFabricCredentials,
6809
7544
  shouldRunFleetVerify,
@@ -6837,6 +7572,7 @@ bindDoctorCli({
6837
7572
  repairLaunchdManagement,
6838
7573
  repointMainServiceUnit,
6839
7574
  resolveHttpPort,
7575
+ verifyDoctorRosterInstance,
6840
7576
  restartFlair,
6841
7577
  resolveOpsPort,
6842
7578
  verifyAuditLog,
@@ -6893,6 +7629,7 @@ const ENTITIES_OPTION_DESCRIPTION = "Comma-separated entity vocabulary strings t
6893
7629
  // Command group lives in src/commands/memory.ts (flair#1621). Bind shared
6894
7630
  // helpers first so the extracted module never imports this file.
6895
7631
  bindMemoryCli({
7632
+ resolveEffectiveOpsUrl,
6896
7633
  api,
6897
7634
  resolveBaseUrl,
6898
7635
  resolveSigningAgentId,
@@ -6900,8 +7637,10 @@ bindMemoryCli({
6900
7637
  addSharedCredentialOptions,
6901
7638
  addSharedIdentityOption,
6902
7639
  resolveOpsPort,
7640
+ resolveHttpPort,
6903
7641
  parseEntitiesOptionOrExit,
6904
7642
  ENTITIES_OPTION_DESCRIPTION,
7643
+ resolveFabricCredentials,
6905
7644
  });
6906
7645
  registerMemory(program);
6907
7646
  // ─── flair search ────────────────────────────────────────────────────────────
@@ -6953,6 +7692,9 @@ bindBackupCli({
6953
7692
  addSharedCredentialOptions,
6954
7693
  applyAdminPassFile,
6955
7694
  resolveHttpPort,
7695
+ resolveOpsPort,
7696
+ resolveOpsTarget,
7697
+ resolveOpsUrlFromTarget,
6956
7698
  });
6957
7699
  registerBackup(program);
6958
7700
  // ─── flair restore ────────────────────────────────────────────────────────────
@@ -6980,6 +7722,7 @@ bindImportCli({
6980
7722
  resolveHttpPort,
6981
7723
  resolveOpsPort,
6982
7724
  seedAgentViaOpsApi,
7725
+ seedAgentWithLocalHome,
6983
7726
  });
6984
7727
  registerImport(program);
6985
7728
  // ─── flair inspect ────────────────────────────────────────────────────────────
@@ -7096,7 +7839,7 @@ LEGACY_LAUNCHD_LABEL, launchdLabel, launchdPlistPath, cleanupLegacyLaunchdPlist,
7096
7839
  observeLaunchdManagement, resolveInstanceServingPid,
7097
7840
  // launchd preflight, repair and init registration (flair#2040) — exported so
7098
7841
  // the command-level tests drive them against a stubbed launchctl.
7099
- observeLaunchdLoadability, repairLaunchdManagement, registerInitLaunchdService, startFlairProcess, };
7842
+ observeLaunchdLoadability, repairLaunchdManagement, registerInitLaunchdService, validateInitPlistAfterWrite, initLaunchdExitCode, startFlairProcess, };
7100
7843
  // Shared with `flair status` via src/lib/ops-api-bind.ts (flair#852).
7101
7844
  export { detectOpsApiAllInterfacesBind };
7102
7845
  export { searchScoringFormula, buildSearchExplain, formatSearchExplain } from "./commands/search.js";