@tpsdev-ai/flair 0.54.2 → 0.55.1

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 (60) hide show
  1. package/dist/build-info.json +3 -3
  2. package/dist/cli.js +774 -176
  3. package/dist/commands/doctor.js +86 -1
  4. package/dist/commands/federation.js +131 -36
  5. package/dist/commands/hook.js +20 -10
  6. package/dist/commands/init.js +193 -67
  7. package/dist/commands/service.js +16 -12
  8. package/dist/commands/soul.js +10 -5
  9. package/dist/commands/status.js +62 -7
  10. package/dist/commands/upgrade.js +6 -0
  11. package/dist/doctor-client.js +118 -32
  12. package/dist/hook-install.js +170 -16
  13. package/dist/lib/doctor-run.js +49 -3
  14. package/dist/lib/embed-gpu-doctor.js +63 -0
  15. package/dist/lib/federation-pair-access.js +118 -0
  16. package/dist/lib/harper-port-value.js +43 -0
  17. package/dist/lib/http-bind.js +227 -0
  18. package/dist/lib/init-admin-pass.js +316 -0
  19. package/dist/lib/launchd-management.js +16 -0
  20. package/dist/lib/launchd-repair.js +122 -1
  21. package/dist/lib/owned-pins.js +54 -1
  22. package/dist/lib/process-start-time.js +82 -0
  23. package/dist/lib/scratch-owner.js +124 -10
  24. package/dist/lib/stale-client-pin.js +26 -0
  25. package/dist/lib/upgrade-plain-tree.js +293 -48
  26. package/dist/rem/runner.js +10 -1
  27. package/dist/resources/AdminInstance.js +8 -2
  28. package/dist/resources/Memory.js +36 -1
  29. package/dist/resources/MemoryBootstrap.js +23 -32
  30. package/dist/resources/MemoryFeed.js +4 -1
  31. package/dist/resources/MemoryReflect.js +121 -93
  32. package/dist/resources/SkillScan.js +13 -11
  33. package/dist/resources/Soul.js +15 -1
  34. package/dist/resources/XAA.js +16 -1
  35. package/dist/resources/a2a-url.js +5 -2
  36. package/dist/resources/client-version-gate.js +144 -0
  37. package/dist/resources/embed-gpu.js +241 -0
  38. package/dist/resources/embeddings-boot.js +34 -42
  39. package/dist/resources/federation-peer-liveness.js +7 -1
  40. package/dist/resources/health.js +12 -3
  41. package/dist/resources/memory-reflect-lib.js +66 -0
  42. package/dist/resources/memory-reflect-models.js +9 -0
  43. package/dist/resources/migrations/embedding-stamp.js +32 -4
  44. package/dist/resources/oauth-discovery.js +3 -1
  45. package/dist/resources/record-type-kit.js +59 -0
  46. package/dist/resources/scan/skill-markdown.js +166 -0
  47. package/dist/resources/scan/skill-scanner.js +89 -68
  48. package/dist/resources/skill-provenance.js +273 -0
  49. package/dist/resources/skill-write.js +26 -7
  50. package/dist/src/lib/harper-port-value.js +43 -0
  51. package/docs/api-reference.md +35 -2
  52. package/docs/deployment.md +39 -6
  53. package/docs/federation.md +18 -7
  54. package/docs/mcp-clients.md +19 -6
  55. package/docs/releasing.md +79 -13
  56. package/docs/rem.md +1 -1
  57. package/docs/secrets-and-keys.md +1 -0
  58. package/docs/standalone-local.md +8 -5
  59. package/docs/troubleshooting.md +17 -0
  60. package/package.json +1 -1
package/dist/cli.js CHANGED
@@ -6,6 +6,7 @@ import { homedir, tmpdir } from "node:os";
6
6
  import { join, resolve, dirname, basename } from "node:path";
7
7
  import { fileURLToPath } from "node:url";
8
8
  import { spawn, execFileSync, spawnSync, execSync } from "node:child_process";
9
+ import { createConnection } from "node:net";
9
10
  import { createRequire } from "node:module";
10
11
  import { createHash, randomUUID, randomBytes } from "node:crypto";
11
12
  import { create as tarCreate } from "tar";
@@ -18,19 +19,23 @@ import { checkServerHandshake, formatHandshakeNudge, invalidateHandshakeCache }
18
19
  import { fleetSweepShouldAbort, } from "./fleet-verify.js";
19
20
  import { detectClients } from "./install/clients.js";
20
21
  import { flairCliVersion, mcpServerSpec, FLAIR_MCP_PACKAGE } from "./lib/mcp-spec.js";
22
+ import { harperPortValue } from "./lib/harper-port-value.js";
23
+ import { httpBind, httpCorsAccessList, preserveHttpPortValue, preserveSecurePort, qualifySecureBindValue, DEFAULT_HTTP_BIND_HOST, } from "./lib/http-bind.js";
21
24
  import { isNodeKeyId, partitionKeyIds, } from "./doctor-client.js";
22
25
  import { cliBootPathWarning, } from "./install/global-bin-path.js";
23
26
  import { readSecretFileSecure, readAdminPassFileSecure, defaultAdminPassPath, defaultKeysDir, resolveLocalAdminPass, DEFAULT_ADMIN_USER, resolveAdminUser, resolveKeyPath, buildEd25519Auth, authFetch, KeyLoadError, isLocalBase, authedRequest, } from "./lib/auth-resolve.js";
24
27
  import { resolveSigningIdentity, emitSigningIdentityDebug, } from "./lib/signing-identity.js";
25
28
  import { entityFormatHint, parseEntitiesCsv } from "./lib/entity-vocab-cli.js";
26
29
  import { escapeXml, unescapeXml } from "./lib/xml-escape.js";
27
- import { assessLaunchdManagement, diagnoseLaunchdPlistPaths, isDetached, pickInstancePid, LAUNCHCTL_QUERY_TIMEOUT_MS, } from "./lib/launchd-management.js";
28
- import { classifyPlist, planLaunchdRepair, mapRepairThrow, decideAdoptStop, } from "./lib/launchd-repair.js";
30
+ import { assessLaunchdManagement, diagnoseLaunchdPlistPaths, isDetached, pickInstancePid, plistCarriesInlineAdminPassword, readLaunchctlJobState, readPlistProgramRefs, LAUNCHCTL_QUERY_TIMEOUT_MS, } from "./lib/launchd-management.js";
31
+ import { classifyPlist, planLaunchdRepair, mapRepairThrow, decideAdoptStop, verifyAdoptServing, } from "./lib/launchd-repair.js";
29
32
  import { stabilizeMqttNetworkKeyOrder } from "./lib/stabilize-mqtt-network.js";
30
33
  import { detectOpsApiAllInterfacesBind } from "./lib/ops-api-bind.js";
31
34
  import { applyUpgradeHookConsent, runDoctorChecks, } from "./lib/doctor-run.js";
32
- import { classifyDaemonState, verifyIdentity, parseProcStatStartTime, procStartTimeToEpochMs, parsePsLstart, parseSidecarJson, classifyHealthProbe, classifyPortOwner, classifyInstanceMatch, shouldAdoptMissingSidecar, parseNullSeparatedEnviron, extractRootPath, } from "./lib/daemon-liveness.js";
33
- import { bindCli as bindFederationCli, register as registerFederation, signRequestBody, parseTokenFromFile, runFederationSyncOnce, runFederationWatch, federationStatusUrlSetting, describeFederationStatusFetchFailed, isFederationStatusConnectFailure, rewriteFederationStatusFetchFailed, isFederationStatusAuthFailure, isFederationStatusAuthRemedy, } from "./commands/federation.js";
35
+ import { classifyDaemonState, verifyIdentity, parseSidecarJson, classifyHealthProbe, classifyPortOwner, classifyInstanceMatch, shouldAdoptMissingSidecar, parseNullSeparatedEnviron, extractRootPath, } from "./lib/daemon-liveness.js";
36
+ import { readProcessStartTimeMs } from "./lib/process-start-time.js";
37
+ import { bindCli as bindFederationCli, register as registerFederation, signRequestBody, parseTokenFromFile, runFederationSyncOnce, persistLocalPeerLastSyncAt, runFederationWatch, federationStatusUrlSetting, describeFederationStatusFetchFailed, isFederationStatusConnectFailure, rewriteFederationStatusFetchFailed, isFederationStatusAuthFailure, isFederationStatusAuthRemedy, } from "./commands/federation.js";
38
+ import { describeFederationPairHubAccessError, describeFederationPairLocalAccessError, rewriteFederationPairHubAccessError, rewriteFederationPairLocalAccessError, } from "./lib/federation-pair-access.js";
34
39
  import { bindCli as bindMemoryCli, register as registerMemory, categorizeForHygiene, HYGIENE_TEST_CONTENT_PATTERNS, } from "./commands/memory.js";
35
40
  import { bindCli as bindSoulCli, register as registerSoul, } from "./commands/soul.js";
36
41
  import { bindCli as bindRemCli, register as registerRem, } from "./commands/rem.js";
@@ -182,27 +187,19 @@ function launchdPlistPath(label, launchAgentsDir = defaultLaunchAgentsDir()) {
182
187
  export function buildLaunchdPlist(opts) {
183
188
  const e = escapeXml;
184
189
  const passFile = opts.passFile;
185
- // ProgramArguments: inline mode execs node directly; pass-file mode execs
186
- // the launcher, which reads the secret from a 0600 file and then execs node
187
- // itself (so launchd still tracks Harper as the job).
188
- const programArguments = passFile
189
- ? `<array>
190
+ // ProgramArguments: exec the launcher, which reads the secret from a 0600
191
+ // file and then execs node itself (so launchd still tracks Harper as the
192
+ // job). There is deliberately no inline branch (flair#1693).
193
+ const programArguments = `<array>
190
194
  <string>${e(passFile.launcher)}</string>
191
195
  <string>${e(passFile.adminPassFile)}</string>
192
196
  <string>${e(opts.execPath)}</string>
193
197
  <string>${e(opts.harperBinPath)}</string>
194
- </array>`
195
- : `<array>
196
- <string>${e(opts.execPath)}</string>
197
- <string>${e(opts.harperBinPath)}</string>
198
- <string>run</string>
199
- <string>.</string>
200
198
  </array>`;
201
- // EnvironmentVariables: pass-file mode drops HDB_ADMIN_PASSWORD (the secret
202
- // is read from the file by the launcher) and adds HOME + PATH, which the
203
- // launcher needs under launchd's minimal env to start Harper non-interactively.
204
- const environmentVariables = passFile
205
- ? `<dict>
199
+ // EnvironmentVariables: no HDB_ADMIN_PASSWORD (the secret is read from the
200
+ // file by the launcher), plus HOME + PATH, which the launcher needs under
201
+ // launchd's minimal env to start Harper non-interactively.
202
+ const environmentVariables = `<dict>
206
203
  <key>ROOTPATH</key><string>${e(opts.dataDir)}</string>
207
204
  <key>FLAIR_MODELS_DIR</key><string>${e(opts.modelsDir)}</string>
208
205
  <key>HARPER_SET_CONFIG</key><string>${e(opts.setConfig)}</string>
@@ -218,23 +215,10 @@ export function buildLaunchdPlist(opts) {
218
215
  <key>MQTT_WEBSOCKET</key><string>false</string>
219
216
  <key>HOME</key><string>${e(passFile.home)}</string>
220
217
  <key>PATH</key><string>${e(passFile.path)}</string>
221
- </dict>`
222
- : `<dict>
223
- <key>ROOTPATH</key><string>${e(opts.dataDir)}</string>
224
- <key>FLAIR_MODELS_DIR</key><string>${e(opts.modelsDir)}</string>
225
- <key>HARPER_SET_CONFIG</key><string>${e(opts.setConfig)}</string>
226
- <key>DEFAULTS_MODE</key><string>dev</string>
227
- <key>HDB_ADMIN_USERNAME</key><string>${e(opts.adminUser)}</string>
228
- <key>HDB_ADMIN_PASSWORD</key><string>${e(opts.adminPass)}</string>
229
- <key>THREADS_COUNT</key><string>1</string>
230
- <key>NODE_HOSTNAME</key><string>localhost</string>
231
- <key>HTTP_PORT</key><string>${e(String(opts.httpPort))}</string>
232
- <key>OPERATIONSAPI_NETWORK_PORT</key><string>${e(opts.opsNetworkPort)}</string>
233
- <key>LOCAL_STUDIO</key><string>false</string>
234
- <key>MQTT_NETWORK_PORT</key><string>null</string>
235
- <key>MQTT_NETWORK_SECUREPORT</key><string>null</string>
236
- <key>MQTT_WEBSOCKET</key><string>false</string>
237
218
  </dict>`;
219
+ // Umask 077 (decimal 63): Harper bind()s operations-server at
220
+ // 0777 & ~umask = 0700. Darwin #1704: chmod on that AF_UNIX inode
221
+ // does not persist 0600. 0700 is owner-only; doctor classify is clean.
238
222
  return `<?xml version="1.0" encoding="UTF-8"?>
239
223
  <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
240
224
  <plist version="1.0">
@@ -247,6 +231,8 @@ export function buildLaunchdPlist(opts) {
247
231
  ${environmentVariables}
248
232
  <key>RunAtLoad</key><true/>
249
233
  <key>KeepAlive</key><true/>
234
+ <key>Umask</key>
235
+ <integer>63</integer>
250
236
  <key>StandardOutPath</key><string>${e(join(opts.dataDir, "log", "launchd-stdout.log"))}</string>
251
237
  <key>StandardErrorPath</key><string>${e(join(opts.dataDir, "log", "launchd-stderr.log"))}</string>
252
238
  </dict>
@@ -449,15 +435,22 @@ function configPath() {
449
435
  * genuinely mean the default instance, and as the source the instance-local
450
436
  * migration reads from. Anything that resolves a port for a NAMED instance
451
437
  * must go through `resolveHttpPort`, not this.
438
+ *
439
+ * Parsed as YAML, never regex-matched (flair#1719). A line-anchored
440
+ * `/port:\s*(\d+)/` misses valid configs the moment the value is quoted
441
+ * (`port: "9926"`), has whitespace before the colon (`port : 9926`), or a
442
+ * commented-out prior value appears first (`# port: 19926`) — in those cases
443
+ * the reader silently fell through to DEFAULT_PORT and the CLI talked to
444
+ * 19926 while the file said 9926. Parsing the document reads the value the
445
+ * user actually wrote, regardless of quoting or surrounding comments.
452
446
  */
453
- function readPortFromConfig() {
447
+ function readPortFromConfig(path = configPath()) {
454
448
  try {
455
- const p = configPath();
456
- if (existsSync(p)) {
457
- const yaml = readFileSync(p, "utf-8");
458
- const m = yaml.match(/port:\s*(\d+)/);
459
- if (m)
460
- return Number(m[1]);
449
+ if (existsSync(path)) {
450
+ const parsed = parseYaml(readFileSync(path, "utf-8"));
451
+ if (parsed && typeof parsed === "object") {
452
+ return harperPortValue(parsed.port);
453
+ }
461
454
  }
462
455
  }
463
456
  catch { /* ignore */ }
@@ -543,30 +536,11 @@ function readHarperConfig(dataDir) {
543
536
  catch { /* ignore — see doc comment */ }
544
537
  return null;
545
538
  }
546
- /**
547
- * A Harper port config value as a number.
548
- *
549
- * Harper accepts both a bare port (`9926`, all interfaces) and the
550
- * host-qualified `host:port` form flair writes for the ops API (`127.0.0.1:9925`
551
- * — see `opsNetworkPortValue`). Both name the same port; only the bind differs,
552
- * and `detectOpsApiAllInterfacesBind` is what reads the host half. Splits on the
553
- * LAST colon so an IPv6 literal (`[::1]:9925`) keeps its port.
554
- */
555
- export function harperPortValue(value) {
556
- if (value === undefined || value === null)
557
- return null;
558
- if (typeof value === "number")
559
- return Number.isInteger(value) && value > 0 ? value : null;
560
- const str = String(value).trim();
561
- if (str === "")
562
- return null;
563
- const lastColon = str.lastIndexOf(":");
564
- const portPart = lastColon > 0 ? str.slice(lastColon + 1) : str;
565
- if (!/^\d+$/.test(portPart))
566
- return null;
567
- const n = Number(portPart);
568
- return n > 0 ? n : null;
569
- }
539
+ // `harperPortValue` lives in `./lib/harper-port-value.js` so the runtime
540
+ // resources under `resources/` share the ONE parser with the CLI, rather than
541
+ // each interpolating `HTTP_PORT` by hand. Re-exported here for existing
542
+ // importers of this module (e.g. the launchd doctor integration test).
543
+ export { harperPortValue };
570
544
  /** This instance's HTTP port, from Harper's own config in its data directory. */
571
545
  function readPortFromHarperConfig(dataDir) {
572
546
  return harperPortValue(readHarperConfig(dataDir)?.http?.port);
@@ -599,6 +573,26 @@ function readOpsBindFromConfig(path = configPath()) {
599
573
  catch { /* ignore */ }
600
574
  return null;
601
575
  }
576
+ /**
577
+ * Read the persisted HTTP bind host from ~/.flair/config.yaml.
578
+ *
579
+ * Same shape and rationale as `readOpsBindFromConfig`: line-anchored so another
580
+ * key ending in `httpBind` cannot satisfy it, quote-tolerant because a
581
+ * hand-edited config may quote it. `path` is injectable so tests exercise the
582
+ * real parse against a temp file.
583
+ */
584
+ export function readHttpBindFromConfig(path = configPath()) {
585
+ try {
586
+ if (existsSync(path)) {
587
+ const yaml = readFileSync(path, "utf-8");
588
+ const m = yaml.match(/^\s*httpBind:\s*["']?([^"'\s#]+)["']?/m);
589
+ if (m && m[1])
590
+ return m[1];
591
+ }
592
+ }
593
+ catch { /* ignore */ }
594
+ return null;
595
+ }
602
596
  /** Read the persisted ops-API port from ~/.flair/config.yaml (flair#863). */
603
597
  function readOpsPortFromConfig(path = configPath()) {
604
598
  try {
@@ -699,6 +693,30 @@ function resolveBaseUrl(opts) {
699
693
  || process.env.FLAIR_URL
700
694
  || `http://127.0.0.1:${resolveHttpPort(opts)}`);
701
695
  }
696
+ /**
697
+ * The `~/.flair/config.yaml` port when it differs from the port
698
+ * `resolveHttpPort` would use — the fallback candidate for flair#1719.
699
+ *
700
+ * For the default install `resolveHttpPort` reads Harper's own boot record
701
+ * (`<dataDir>/harper-config.yaml`), which is authoritative for the port the
702
+ * instance *last* bound but can be stale relative to the per-user config the
703
+ * operator edits (the config says 9926 while Harper's record still says
704
+ * 19926 from an earlier boot). When the recorded port has no daemon and the
705
+ * configured port does, callers use this to reach the daemon the operator
706
+ * actually configured instead of reporting the recorded port unreachable.
707
+ *
708
+ * Returns `null` when an explicit override is in play (nothing to fall back
709
+ * from) or when the two ports already agree.
710
+ */
711
+ function alternateConfiguredLocalPort(opts) {
712
+ if (opts.target || opts.url || process.env.FLAIR_TARGET || process.env.FLAIR_URL)
713
+ return null;
714
+ const configured = readPortFromConfig();
715
+ if (configured === null)
716
+ return null;
717
+ const resolved = resolveHttpPort(opts);
718
+ return configured === resolved ? null : configured;
719
+ }
702
720
  // Resolve agent id from --agent flag or FLAIR_AGENT_ID env (flag > env).
703
721
  // The low-level helper with no debug line — used where only the flag/env pair
704
722
  // is wanted (e.g. the upgrade path that then applies its own key-dir floor).
@@ -847,6 +865,43 @@ export function resolveOpsBindHostFrom(flag, envBind, configuredBind) {
847
865
  function resolveOpsBindHost(opts) {
848
866
  return resolveOpsBindHostFrom(opts.opsBind, process.env.FLAIR_OPS_BIND, readOpsBindFromConfig());
849
867
  }
868
+ // HTTP bind-host resolution (ops-nv9d slice 2): --http-bind flag >
869
+ // FLAIR_HTTP_BIND env > persisted `httpBind` in ~/.flair/config.yaml > loopback
870
+ // default. Mirrors the ops-API escape hatch (resolveOpsBindHostFrom) so the two
871
+ // binds cannot drift in how a deliberate widening is recorded, with ONE
872
+ // deliberate difference: the ops resolver accepts an arbitrary string (Harper
873
+ // parses whatever it can from `host:port`), while this one VALIDATES. The value
874
+ // is built through `httpBind()`, which refuses any host that does not guarantee
875
+ // IPv4-loopback reachability — a specific non-loopback host or an IPv6-only
876
+ // loopback would leave every hardcoded `127.0.0.1` self-call pointing at a dead
877
+ // port while the bind itself looked fine. Widening is still available, but only
878
+ // to a wildcard.
879
+ //
880
+ // The config-file rung is what makes `--http-bind` durable: every Harper spawn
881
+ // re-asserts the bind, and those spawns happen in `flair start` / `restart` /
882
+ // `upgrade`, none of which take an `--http-bind` flag.
883
+ export function resolveHttpBindHostFrom(flag, envBind, configuredBind) {
884
+ if (flag !== undefined && flag !== null && String(flag).trim() !== "")
885
+ return String(flag).trim();
886
+ if (envBind && envBind.trim() !== "")
887
+ return envBind.trim();
888
+ if (configuredBind && configuredBind.trim() !== "")
889
+ return configuredBind.trim();
890
+ return null;
891
+ }
892
+ function resolveHttpBindHost(opts) {
893
+ return resolveHttpBindHostFrom(opts.httpBind, process.env.FLAIR_HTTP_BIND, readHttpBindFromConfig())
894
+ ?? DEFAULT_HTTP_BIND_HOST;
895
+ }
896
+ /**
897
+ * The validated HTTP bind (host-qualified string + its two halves) for a spawn
898
+ * env, a launchd plist, or a `HARPER_SET_CONFIG` payload. Throws
899
+ * `UnreachableHttpBindHostError` for a host outside {loopback, wildcard}; the
900
+ * caller must refuse before writing anything.
901
+ */
902
+ export function resolveHttpBindFor(port, opts) {
903
+ return httpBind(resolveHttpBindHost(opts), port);
904
+ }
850
905
  /**
851
906
  * The one place that renders Harper's `operationsApi.network.port` value
852
907
  * (flair#863). Used by both the HARPER_SET_CONFIG block
@@ -945,7 +1000,12 @@ export function buildDirectSpawnEnv(opts) {
945
1000
  FLAIR_MODELS_DIR: opts.modelsDir,
946
1001
  DEFAULTS_MODE: "dev",
947
1002
  HDB_ADMIN_USERNAME: opts.adminUser,
948
- HTTP_PORT: String(opts.httpPort),
1003
+ // Host-qualified through the ONE bind constructor (ops-nv9d slice 2). A bare
1004
+ // number here would bind all interfaces, which is exactly the widening this
1005
+ // slice removes; qualification is what narrows it. The value is the same
1006
+ // shape the consumers parse (slice 1). Refuses a host that cannot reach
1007
+ // IPv4 loopback rather than silently producing an unreachable bind.
1008
+ HTTP_PORT: httpBind(opts.httpBindHost, opts.httpPort).bindValue,
949
1009
  OPERATIONSAPI_NETWORK_PORT: opsNetworkPortValue(opts.opsBindHost, opts.opsPort),
950
1010
  // flair#1586: fully disable the MQTT broker (Flair does not use it). "null"
951
1011
  // casts to a null port (Harper's castConfigValue), which passes config
@@ -969,36 +1029,40 @@ export function buildDirectSpawnEnv(opts) {
969
1029
  env.HDB_ADMIN_PASSWORD = opts.adminPass;
970
1030
  return env;
971
1031
  }
1032
+ /**
1033
+ * Harper config env vars that outrank the individual bind vars. Harper filters
1034
+ * its env/argv against `HARPER_SET_CONFIG` before applying anything
1035
+ * (`filterArgsAgainstRuntimeConfig`), and `http.port` is a key flair's own
1036
+ * SET_CONFIG names — so an ambient `HARPER_SET_CONFIG` left in `process.env`
1037
+ * would DROP the qualified `HTTP_PORT` the direct-spawn path writes, bind the
1038
+ * port wide, and leave every bind assertion green.
1039
+ */
1040
+ export const HARPER_CONFIG_ENV_VARS = ["HARPER_DEFAULT_CONFIG", "HARPER_CONFIG", "HARPER_SET_CONFIG"];
1041
+ /**
1042
+ * A CLOSED direct-spawn environment: `base` with every Harper config env var
1043
+ * removed, then `overrides` applied. The direct-spawn paths (`flair start`'s
1044
+ * fallback, `restart`, `upgrade`) do not set `HARPER_SET_CONFIG` themselves and
1045
+ * their whole contract is the INDIVIDUAL vars — so an inherited SET_CONFIG from
1046
+ * the operator's shell must not survive into the spawn and outrank them. (The
1047
+ * `init` install path DOES set SET_CONFIG deliberately and does not use this.)
1048
+ */
1049
+ export function closedDirectSpawnEnv(base, overrides) {
1050
+ const env = { ...base };
1051
+ for (const key of HARPER_CONFIG_ENV_VARS)
1052
+ delete env[key];
1053
+ return { ...env, ...overrides };
1054
+ }
972
1055
  // detectOpsApiAllInterfacesBind now lives in src/lib/ops-api-bind.ts so
973
1056
  // `flair doctor` and `flair status` share one decision (flair#852). Re-exported
974
1057
  // at the bottom of this file to preserve the public CLI module surface.
975
1058
  /**
976
- * Decide the source `flair init` should use for the admin password when no
977
- * explicit `--admin-pass` / `--admin-pass-file` / env var was given
978
- * (flair#827).
979
- *
980
- * Before this existed, init ALWAYS generated a fresh random password and
981
- * overwrote `~/.flair/admin-pass` on every run — including a re-run against
982
- * an install that was already bootstrapped and working (e.g. following
983
- * `flair doctor`'s ops-bind finding, whose only prescribed remedy is
984
- * re-running `flair init`). Harper's `HDB_ADMIN_PASSWORD` env var only seeds
985
- * a brand-new install's user record — it does NOT rotate an existing user's
986
- * stored password hash on every boot. So overwriting the file desynced it
987
- * from what Harper actually had persisted, and the very next ops-API call in
988
- * that SAME init run (seeding the agent) failed with a 401 "Login failed",
989
- * breaking working auth on an install that had nothing wrong with its
990
- * credentials.
991
- *
992
- * An admin-pass file that already exists on disk IS the working install's
993
- * password — `flair init` is the only thing that ever writes it — so reuse
994
- * it instead of generating a new one. That makes re-init idempotent: safe to
995
- * run again at any time without risking the instance's auth. Deliberately
996
- * rotating the admin password is a separate operation, not a `flair init`
997
- * side effect.
1059
+ * Decide the source `flair init` should use for the admin password
1060
+ * (flair#827 + flair#837). Implementation lives in `src/lib/init-admin-pass.ts`
1061
+ * so the persisted-user / rotate / refuse branches stay strictly typed and
1062
+ * unit-tested without expanding this file. Re-exported here so existing
1063
+ * imports of the CLI module surface keep working.
998
1064
  */
999
- export function resolveInitAdminPasswordSource(adminPassFileExists) {
1000
- return adminPassFileExists ? "reuse-existing" : "generate-new";
1001
- }
1065
+ export { resolveInitAdminPasswordSource, detectPersistedAdminUser, initAdminPassRefusalMessage, adminPassDesyncFinding, rotateAdminPasswordViaOpsSocket, prepareAdminPasswordRotate, formatAdminPasswordRotatePreflight, assertExplicitAdminPasswordRotate, assertOwnerOnlyOpsSocket, isOwnerOnlyOpsSocketPosture, callOpsSocket, waitForOpsSocketReady, executeAdminPasswordRotate, probeOpsSocketAccepting, INIT_RESET_ADMIN_PASS_COMMAND, INIT_ADMIN_PASS_FILE_COMMAND, INIT_STOP_FOREIGN_COMMAND, ADMIN_PASS_DESYNC_REMEDY, } from "./lib/init-admin-pass.js";
1002
1066
  // ─── Ops-socket permission posture (flair#763) ─────────────────────────────────
1003
1067
  //
1004
1068
  // The ops API domain socket (dataDir/operations-server) is protected by a
@@ -1107,6 +1171,12 @@ export function applyOpsSocketPosture(opts) {
1107
1171
  let socketApplied = false;
1108
1172
  if (fs.existsSync(opts.socketPath)) {
1109
1173
  fs.chmodSync(opts.socketPath, posture.socketMode);
1174
+ // Darwin: Node chmodSync on a unix socket can report success while
1175
+ // stat still shows 0777 & ~umask. `/bin/chmod` is the same tool the
1176
+ // operator would use; only on the real fs (tests inject FakeFs).
1177
+ if (fs === NODE_SOCKET_FS) {
1178
+ enforceSocketMode(opts.socketPath, posture.socketMode);
1179
+ }
1110
1180
  if (gid !== null) {
1111
1181
  const st = fs.statSync(opts.socketPath);
1112
1182
  try {
@@ -1130,6 +1200,17 @@ export function applyOpsSocketPosture(opts) {
1130
1200
  broadGroup,
1131
1201
  };
1132
1202
  }
1203
+ /** If Node chmodSync did not stick (Darwin unix sockets), use /bin/chmod. */
1204
+ function enforceSocketMode(path, mode) {
1205
+ const wanted = mode & 0o777;
1206
+ const got = statSync(path).mode & 0o777;
1207
+ if (got === wanted)
1208
+ return;
1209
+ execFileSync("chmod", [wanted.toString(8).padStart(3, "0"), path], {
1210
+ encoding: "utf-8",
1211
+ stdio: ["ignore", "pipe", "pipe"],
1212
+ });
1213
+ }
1133
1214
  /**
1134
1215
  * Resolve + apply the ops-socket posture for a data dir, with the right
1135
1216
  * fatal-vs-warn handling. A broken FLAIR_SOCKET_GROUP opt-in is a hard error
@@ -1158,6 +1239,121 @@ function readyOpsSocketPosture(dataDir) {
1158
1239
  return null;
1159
1240
  }
1160
1241
  }
1242
+ /** How long the first-start path waits for Harper to create operations-server. */
1243
+ export const OPS_SOCKET_AFTER_START_TIMEOUT_MS = 10_000;
1244
+ const OPS_SOCKET_AFTER_START_POLL_MS = 50;
1245
+ const OPS_SOCKET_AFTER_START_HOLD_MS = 500;
1246
+ function statOpsSocket(path) {
1247
+ try {
1248
+ const s = statSync(path);
1249
+ return { mode: s.mode & 0o777, ino: s.ino, mtimeMs: s.mtimeMs };
1250
+ }
1251
+ catch {
1252
+ return null;
1253
+ }
1254
+ }
1255
+ /**
1256
+ * Drop `operations-server` while no process owns it (after the adopt stop,
1257
+ * before launchd load). Darwin #1704: chmod on the leftover inode never
1258
+ * became 0600 (`9413a80` burned the 10s wait, test still saw 0755). Harper
1259
+ * bind()s a new file; the helper must wait for that one.
1260
+ */
1261
+ export function unlinkStaleOpsSocket(dataDir) {
1262
+ try {
1263
+ unlinkSync(join(dataDir, "operations-server"));
1264
+ }
1265
+ catch {
1266
+ /* ENOENT or busy — helper waits for a post-bounce inode */
1267
+ }
1268
+ }
1269
+ /** True when something is accepting on `path` (dead leftover → false). */
1270
+ export function probeOpsSocketListening(socketPath, timeoutMs = 250) {
1271
+ return new Promise((resolve) => {
1272
+ let settled = false;
1273
+ const finish = (ok) => {
1274
+ if (settled)
1275
+ return;
1276
+ settled = true;
1277
+ sock.removeAllListeners();
1278
+ sock.destroy();
1279
+ resolve(ok);
1280
+ };
1281
+ const sock = createConnection(socketPath);
1282
+ sock.setTimeout(timeoutMs);
1283
+ sock.once("connect", () => finish(true));
1284
+ sock.once("error", () => finish(false));
1285
+ sock.once("timeout", () => finish(false));
1286
+ });
1287
+ }
1288
+ /**
1289
+ * Apply the ops-socket posture after a start that did not go through
1290
+ * `waitForHealth` in this process (the launchd adopt/regenerate bounce).
1291
+ *
1292
+ * Darwin adopt CI on #1704 measured two races:
1293
+ * 1. HTTP can answer before Harper bind()s `operations-server`.
1294
+ * 2. A leftover socket from the pre-adopt direct process makes
1295
+ * exists() true immediately; chmod'ing that inode is wasted —
1296
+ * Harper unlinks and bind()s a new file at 0777 & ~umask (0755
1297
+ * on the canary host). `76a9a15` hit (2): dir 0700, socket 0755.
1298
+ *
1299
+ * Keep applying while the socket exists until the wanted mode *holds*
1300
+ * for `holdMs` (Harper replacing the file during the hold restarts it).
1301
+ * A socket older than `notBeforeMs` is leftover — unlink it, do not chmod it.
1302
+ * A path that exists but is not accepting connections is leftover too
1303
+ * (`b381b5b` Darwin: chmod'd a dead inode to 0600, held 500ms, returned;
1304
+ * Harper then bind()d 0755).
1305
+ */
1306
+ export async function readyOpsSocketPostureAfterStart(dataDir, opts = {}) {
1307
+ const socketPath = join(dataDir, "operations-server");
1308
+ const timeoutMs = opts.timeoutMs ?? OPS_SOCKET_AFTER_START_TIMEOUT_MS;
1309
+ const pollMs = opts.pollMs ?? OPS_SOCKET_AFTER_START_POLL_MS;
1310
+ const holdMs = opts.holdMs ?? OPS_SOCKET_AFTER_START_HOLD_MS;
1311
+ const notBeforeMs = opts.notBeforeMs;
1312
+ const sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
1313
+ const exists = opts.exists ?? existsSync;
1314
+ const ready = opts.ready ?? readyOpsSocketPosture;
1315
+ const stat = opts.stat ?? statOpsSocket;
1316
+ const unlink = opts.unlink ?? ((p) => { try {
1317
+ unlinkSync(p);
1318
+ }
1319
+ catch { /* leftover busy */ } });
1320
+ const isLive = opts.isLive ?? ((p) => probeOpsSocketListening(p));
1321
+ const wanted = resolveSocketPosture(process.env.FLAIR_SOCKET_GROUP).socketMode;
1322
+ ready(dataDir); // dir gate now — the live socket may not exist yet
1323
+ const deadline = Date.now() + timeoutMs;
1324
+ let last = null;
1325
+ while (Date.now() < deadline) {
1326
+ if (exists(socketPath)) {
1327
+ const seen = stat(socketPath);
1328
+ const live = await isLive(socketPath);
1329
+ if (!live || (seen && notBeforeMs != null && seen.mtimeMs < notBeforeMs)) {
1330
+ unlink(socketPath);
1331
+ await sleep(pollMs);
1332
+ continue;
1333
+ }
1334
+ last = ready(dataDir);
1335
+ const applied = stat(socketPath);
1336
+ if (applied && applied.mode === wanted) {
1337
+ const holdDeadline = Date.now() + holdMs;
1338
+ let held = true;
1339
+ while (Date.now() < holdDeadline) {
1340
+ await sleep(pollMs);
1341
+ const now = exists(socketPath) ? stat(socketPath) : null;
1342
+ const stillLive = now ? await isLive(socketPath) : false;
1343
+ if (!now || now.mode !== wanted || !stillLive || (notBeforeMs != null && now.mtimeMs < notBeforeMs)) {
1344
+ held = false;
1345
+ break;
1346
+ }
1347
+ }
1348
+ if (held)
1349
+ return last;
1350
+ continue;
1351
+ }
1352
+ }
1353
+ await sleep(pollMs);
1354
+ }
1355
+ return last ?? ready(dataDir);
1356
+ }
1161
1357
  /**
1162
1358
  * The `flair doctor` detection matrix for the ops-socket posture (flair#763,
1163
1359
  * Sherlock's exact six rows). Report-only — never auto-remediated (changing a
@@ -1296,21 +1492,24 @@ function resolveOpsUrlFromTarget(targetUrl) {
1296
1492
  * Persist the instance coordinates other commands need to find and re-assert
1297
1493
  * this install (flair#863).
1298
1494
  *
1299
- * This rewrites the file wholesale, so `opsPort`/`opsBind` default to whatever
1300
- * is already persisted rather than being dropped — otherwise an unrelated
1301
- * caller (e.g. `flair doctor --fix` correcting a drifted HTTP port) would
1302
- * silently erase the operator's `--ops-bind` choice and the next restart would
1303
- * revert the bind.
1495
+ * This rewrites the file wholesale, so `opsPort`/`opsBind`/`httpBind` default to
1496
+ * whatever is already persisted rather than being dropped — otherwise an
1497
+ * unrelated caller (e.g. `flair doctor --fix` correcting a drifted HTTP port)
1498
+ * would silently erase the operator's `--ops-bind` or `--http-bind` choice and
1499
+ * the next restart would revert the bind.
1304
1500
  */
1305
- function writeConfig(port, opsPort, opsBind, path = configPath()) {
1501
+ function writeConfig(port, opsPort, opsBind, path = configPath(), httpBind) {
1306
1502
  const resolvedOpsPort = opsPort ?? readOpsPortFromConfig(path);
1307
1503
  const resolvedOpsBind = opsBind ?? readOpsBindFromConfig(path);
1504
+ const resolvedHttpBind = httpBind ?? readHttpBindFromConfig(path);
1308
1505
  mkdirSync(dirname(path), { recursive: true });
1309
1506
  let body = `# Flair configuration\nport: ${port}\n`;
1310
1507
  if (resolvedOpsPort !== null && resolvedOpsPort !== undefined)
1311
1508
  body += `opsPort: ${resolvedOpsPort}\n`;
1312
1509
  if (resolvedOpsBind)
1313
1510
  body += `opsBind: ${resolvedOpsBind}\n`;
1511
+ if (resolvedHttpBind)
1512
+ body += `httpBind: ${resolvedHttpBind}\n`;
1314
1513
  writeFileSync(path, body);
1315
1514
  }
1316
1515
  /**
@@ -1339,9 +1538,9 @@ function writeConfig(port, opsPort, opsBind, path = configPath()) {
1339
1538
  * Those read Harper's config directly when the lifecycle commands grow the flag,
1340
1539
  * and this file goes with them.
1341
1540
  */
1342
- function persistDefaultInstallCoordinates(dataDir, port, opsPort, opsBind) {
1541
+ function persistDefaultInstallCoordinates(dataDir, port, opsPort, opsBind, httpBind) {
1343
1542
  if (isDefaultDataDir(dataDir))
1344
- writeConfig(port, opsPort, opsBind);
1543
+ writeConfig(port, opsPort, opsBind, configPath(), httpBind);
1345
1544
  }
1346
1545
  function privKeyPath(agentId, keysDir) {
1347
1546
  return join(keysDir, `${agentId}.key`);
@@ -1527,6 +1726,7 @@ function b64url(bytes) {
1527
1726
  async function api(method, path, body, options) {
1528
1727
  // Resolve port via the canonical path (flair#1129): options.baseUrl > FLAIR_URL > resolveHttpPort.
1529
1728
  // api() callers mean the default install, so resolveHttpPort({}) with no --data-dir is correct.
1729
+ const hasExplicitBase = !!(options?.baseUrl || process.env.FLAIR_URL);
1530
1730
  const base = options?.baseUrl ?? (process.env.FLAIR_URL || `http://127.0.0.1:${resolveHttpPort({})}`);
1531
1731
  let agentId;
1532
1732
  if (options && "agentId" in options) {
@@ -1547,14 +1747,51 @@ async function api(method, path, body, options) {
1547
1747
  agentId = decodeURIComponent(match[1]);
1548
1748
  }
1549
1749
  }
1550
- return authedRequest(method, path, body, {
1750
+ const requestOptions = {
1551
1751
  baseUrl: base,
1552
1752
  agentId,
1553
1753
  keysDir: options?.keysDir,
1554
1754
  explicitAdminPass: options?.explicitAdminPass,
1555
1755
  adminUser: options?.adminUser,
1556
1756
  agentIdSource: options?.agentIdSource,
1557
- });
1757
+ };
1758
+ try {
1759
+ return await authedRequest(method, path, body, requestOptions);
1760
+ }
1761
+ catch (err) {
1762
+ // flair#1719: the resolved port came from Harper's boot record, which can
1763
+ // be stale for the default install. Before surfacing a connect failure,
1764
+ // try the port the operator actually wrote in ~/.flair/config.yaml.
1765
+ const altPort = hasExplicitBase ? null : alternateConfiguredLocalPort({});
1766
+ if (altPort !== null && isFederationStatusConnectFailure(err)) {
1767
+ const altUrl = `http://127.0.0.1:${altPort}`;
1768
+ try {
1769
+ return await authedRequest(method, path, body, { ...requestOptions, baseUrl: altUrl });
1770
+ }
1771
+ catch (altErr) {
1772
+ throw describeApiConnectFailure(altErr, altUrl);
1773
+ }
1774
+ }
1775
+ throw describeApiConnectFailure(err, base);
1776
+ }
1777
+ }
1778
+ /**
1779
+ * Turn undici/Node's bare `TypeError: fetch failed` into a sentence naming the
1780
+ * actor (the Flair instance URL), the state (no HTTP response) and a remedy
1781
+ * the operator can act on — flair#1719 requirement 3. Non-connect errors
1782
+ * (HTTP 401/403/5xx, auth failures) pass through unchanged so callers keep
1783
+ * their own handling. The `flairFriendly` marker lets the top-level CLI entry
1784
+ * print just the message instead of a stack.
1785
+ */
1786
+ function describeApiConnectFailure(err, url) {
1787
+ if (!isFederationStatusConnectFailure(err))
1788
+ return err;
1789
+ const friendly = new Error(`Cannot reach the Flair instance at ${url} — the connection failed (no HTTP response).\n`
1790
+ + ` Start it with \`flair start\`, or point this command at the right instance with `
1791
+ + `FLAIR_URL=http://127.0.0.1:<port> (or --url on commands that accept it).`);
1792
+ friendly.flairFriendly = true;
1793
+ friendly.cause = err;
1794
+ return friendly;
1558
1795
  }
1559
1796
  /**
1560
1797
  * The authedGet `flair upgrade` verification (flair#635/#741) hands to
@@ -3137,7 +3374,6 @@ program.hook("preAction", async (_thisCommand, actionCommand) => {
3137
3374
  bindInitCli({
3138
3375
  api,
3139
3376
  b64url,
3140
- buildLaunchdPlist,
3141
3377
  buildOperationsApiConfig,
3142
3378
  cleanupLegacyLaunchdPlist,
3143
3379
  defaultDataDir,
@@ -3157,8 +3393,9 @@ bindInitCli({
3157
3393
  pubKeyPath,
3158
3394
  readyOpsSocketPosture,
3159
3395
  resolveHttpPort,
3160
- resolveInitAdminPasswordSource,
3396
+ writeAdminPassFile,
3161
3397
  resolveOpsBindHost,
3398
+ resolveHttpBindFor,
3162
3399
  resolveOpsPort,
3163
3400
  resolveOpsTarget,
3164
3401
  resolveOpsUrlFromTarget,
@@ -3171,6 +3408,7 @@ bindInitCli({
3171
3408
  verifySemanticSearch,
3172
3409
  waitForHealth,
3173
3410
  writeDaemonSidecar,
3411
+ writeInitLaunchdPlist,
3174
3412
  MQTT_DISABLED_CONFIG,
3175
3413
  STARTUP_TIMEOUT_MS,
3176
3414
  });
@@ -3307,7 +3545,7 @@ function relativeTime(iso) {
3307
3545
  async function fetchHealthDetail(opts, signingAgentIdOverride, signingAgentSource) {
3308
3546
  const port = resolveHttpPort(opts);
3309
3547
  // --target takes precedence, then --url, then FLAIR_TARGET, then FLAIR_URL, then localhost
3310
- const baseUrl = opts.target || opts.url || process.env.FLAIR_TARGET || (process.env.FLAIR_URL ?? `http://127.0.0.1:${port}`);
3548
+ let baseUrl = opts.target || opts.url || process.env.FLAIR_TARGET || (process.env.FLAIR_URL ?? `http://127.0.0.1:${port}`);
3311
3549
  let healthy = false;
3312
3550
  let healthData = null;
3313
3551
  try {
@@ -3324,6 +3562,34 @@ async function fetchHealthDetail(opts, signingAgentIdOverride, signingAgentSourc
3324
3562
  healthy = res.ok;
3325
3563
  }
3326
3564
  catch { /* unreachable */ }
3565
+ // flair#1719: the resolved URL for the default install comes from Harper's
3566
+ // boot record, which can be stale relative to ~/.flair/config.yaml. If that
3567
+ // port is dead and the configured port has a live daemon, treat the
3568
+ // configured port as the resolved URL rather than reporting the stale one
3569
+ // unreachable (and then telling the user to edit a config that is correct).
3570
+ if (!healthy) {
3571
+ const altPort = alternateConfiguredLocalPort(opts);
3572
+ if (altPort !== null) {
3573
+ const altUrl = `http://127.0.0.1:${altPort}`;
3574
+ try {
3575
+ let res = await fetch(`${altUrl}/Health`, { signal: AbortSignal.timeout(5000) });
3576
+ if (!res.ok && res.status === 401) {
3577
+ const adminPass = process.env.FLAIR_ADMIN_PASS ?? process.env.HDB_ADMIN_PASSWORD;
3578
+ if (adminPass) {
3579
+ res = await fetch(`${altUrl}/Health`, {
3580
+ headers: { Authorization: `Basic ${Buffer.from(`${resolveAdminUser(undefined)}:${adminPass}`).toString("base64")}` },
3581
+ signal: AbortSignal.timeout(5000),
3582
+ });
3583
+ }
3584
+ }
3585
+ if (res.ok) {
3586
+ baseUrl = altUrl;
3587
+ healthy = true;
3588
+ }
3589
+ }
3590
+ catch { /* configured port also unreachable — fall through to the primary */ }
3591
+ }
3592
+ }
3327
3593
  if (healthy) {
3328
3594
  // flair#747: /HealthDetail is a verified-read (any registered agent, not
3329
3595
  // just admins — see verifyAuthedGet's doc). Previously this tried the
@@ -3361,6 +3627,7 @@ bindStatusCli({
3361
3627
  sortSoulKeyEntries,
3362
3628
  defaultDataDir,
3363
3629
  readHarperConfig,
3630
+ readPortFromConfig,
3364
3631
  __pkgVersion,
3365
3632
  });
3366
3633
  registerStatus(program);
@@ -3532,45 +3799,6 @@ function probePidLiveness(pid) {
3532
3799
  return { kind: "gone" };
3533
3800
  }
3534
3801
  }
3535
- /**
3536
- * The live process's start time in epoch ms, or null when it cannot be read.
3537
- * Linux reads `/proc/<pid>/stat` field 22 (starttime in clock ticks) plus
3538
- * `/proc/uptime`; macOS shells out to `ps -o lstart=`. A null answer degrades
3539
- * to "identity unverified" — it never decides a verdict toward the destructive
3540
- * branch (flair#1454 decision 4).
3541
- */
3542
- function readProcessStartTimeMs(pid) {
3543
- if (process.platform === "linux") {
3544
- try {
3545
- const stat = readFileSync(`/proc/${pid}/stat`, "utf-8");
3546
- const starttime = parseProcStatStartTime(stat);
3547
- if (starttime === null)
3548
- return null;
3549
- const uptimeRaw = readFileSync("/proc/uptime", "utf-8").trim().split(/\s+/)[0];
3550
- const uptime = Number(uptimeRaw);
3551
- if (!Number.isFinite(uptime))
3552
- return null;
3553
- return procStartTimeToEpochMs(starttime, uptime, Date.now());
3554
- }
3555
- catch {
3556
- return null;
3557
- }
3558
- }
3559
- if (process.platform === "darwin") {
3560
- try {
3561
- const out = execFileSync("ps", ["-o", "lstart=", "-p", String(pid)], {
3562
- encoding: "utf-8",
3563
- env: { ...process.env, LC_ALL: "C" },
3564
- timeout: 2000,
3565
- });
3566
- return parsePsLstart(out);
3567
- }
3568
- catch {
3569
- return null;
3570
- }
3571
- }
3572
- return null;
3573
- }
3574
3802
  /**
3575
3803
  * The health probe (flair#1478): ok only when the response is 2xx AND the
3576
3804
  * body is flair's /Health shape. A decoy that answers 200 is `foreign`,
@@ -3806,6 +4034,7 @@ export function assertLaunchdServiceOwnedBy(dataDir, label, plistPath, action) {
3806
4034
  // Bind shared cli-locals first so the extracted module never imports this file.
3807
4035
  bindServiceCli({
3808
4036
  buildDirectSpawnEnv,
4037
+ closedDirectSpawnEnv,
3809
4038
  defaultDataDir,
3810
4039
  ensureLaunchdServiceLoaded,
3811
4040
  flairPackageDir,
@@ -3817,6 +4046,7 @@ bindServiceCli({
3817
4046
  probeHealth,
3818
4047
  readyOpsSocketPosture,
3819
4048
  resolveHarperBin,
4049
+ resolveHttpBindHost,
3820
4050
  resolveHttpPort,
3821
4051
  resolveLaunchdLabel,
3822
4052
  resolveOpsBindHost,
@@ -4006,6 +4236,12 @@ function observeLaunchdManagement(dataDir, port) {
4006
4236
  list: realLaunchctlLister,
4007
4237
  });
4008
4238
  }
4239
+ // `preserveHttpPortValue` / `preserveSecurePort` / `bindHostOf` live in
4240
+ // src/lib/http-bind.ts so the CLI's plist writer and the pure repair PLANNER
4241
+ // (src/lib/launchd-repair.ts) share the exact same preservation rules, and the
4242
+ // planner can refuse an unsupported configuration BEFORE the executor stops
4243
+ // anything. Re-exported here for existing importers of this module.
4244
+ export { preserveHttpPortValue, preserveSecurePort };
4009
4245
  /**
4010
4246
  * Build the launchd plist for a `doctor --fix` repair (flair#1573 slice b).
4011
4247
  *
@@ -4017,15 +4253,28 @@ function observeLaunchdManagement(dataDir, port) {
4017
4253
  * or defaults, so the repair cannot re-bootstrap Harper against a different
4018
4254
  * directory or port.
4019
4255
  *
4256
+ * REPAIR IS AN EXPLICIT EXCEPTION TO "every bind goes through the
4257
+ * constructor". Credential repair promises not to move the instance's
4258
+ * coordinates (see the repair contract above this function), so it PRESERVES
4259
+ * the existing bind — host and port, in whatever form the instance recorded
4260
+ * them — rather than qualifying, narrowing or widening it. A bare legacy port
4261
+ * stays bare; an already-qualified `host:port` keeps its host; a wildcard TLS
4262
+ * listener with no intent marker is preserved as-is (changing it is migration's
4263
+ * job, not repair's). An unsupported (unparseable) or disabled value is
4264
+ * REFUSED rather than defaulted: substituting DEFAULT_PORT is itself a
4265
+ * coordinate change and would enable a plaintext listener on a TLS-only
4266
+ * instance.
4267
+ *
4020
4268
  * `config` is the parsed harper-config.yaml, already gated readable by the
4021
4269
  * caller. Throws when the Harper binary cannot be resolved — a plist pointing
4022
4270
  * at a missing binary is the stale-plist failure this repair must not write.
4023
4271
  */
4024
- function buildRepairPlist(dataDir, config) {
4025
- // The DEFAULT_PORT / httpPort-1 fallbacks below are practically unreachable:
4026
- // Harper writes harper-config.yaml ports on every boot (flair#914), so a
4027
- // readable config always carries them. They exist only as a last resort.
4028
- const httpPort = harperPortValue(config?.http?.port) ?? DEFAULT_PORT;
4272
+ export function buildRepairPlist(dataDir, config) {
4273
+ const httpRaw = config?.http?.port;
4274
+ // Preserved verbatim (bare stays bare, qualified keeps its host). Throws for a
4275
+ // disabled or unparseable value — refuse rather than replace the plist.
4276
+ const httpBindValue = preserveHttpPortValue(httpRaw);
4277
+ const httpPort = harperPortValue(httpRaw);
4029
4278
  const opsPortRaw = config?.operationsApi?.network?.port;
4030
4279
  const opsPort = harperPortValue(opsPortRaw) ?? (httpPort - 1);
4031
4280
  const opsBind = detectOpsApiAllInterfacesBind(opsPortRaw);
@@ -4037,10 +4286,32 @@ function buildRepairPlist(dataDir, config) {
4037
4286
  const opsNetworkPort = typeof opsPortRaw === "string" && opsPortRaw.trim() !== ""
4038
4287
  ? opsPortRaw.trim()
4039
4288
  : opsNetworkPortValue(opsBindHost, opsPort);
4289
+ // TLS is preserved, never defaulted in and never enabled. The secure host
4290
+ // follows a "both or neither" rule with the plaintext bind: a secure value
4291
+ // that already names a host is preserved verbatim; a BARE secure value with a
4292
+ // BARE plaintext port is preserved bare too (repair moves neither — narrowing
4293
+ // TLS while plaintext stays wide would move a coordinate and drop LAN TLS
4294
+ // clients); and a bare secure value with a qualified plaintext bind is
4295
+ // qualified the same way as the plaintext host. A DISABLED secure listener
4296
+ // stays disabled (the key is not emitted).
4297
+ const httpSecureBind = qualifySecureBindValue(config?.http?.securePort, httpBindValue);
4298
+ const opsSecureBind = qualifySecureBindValue(config?.operationsApi?.network?.securePort, opsNetworkPort);
4040
4299
  const setConfig = JSON.stringify({
4041
4300
  rootPath: dataDir,
4042
- http: { port: httpPort, cors: true, corsAccessList: [`http://127.0.0.1:${httpPort}`, `http://localhost:${httpPort}`] },
4043
- operationsApi: { network: { port: opsNetworkPort, cors: true, domainSocket: opsSocket } },
4301
+ http: {
4302
+ port: httpBindValue,
4303
+ cors: true,
4304
+ corsAccessList: httpCorsAccessList(httpPort),
4305
+ ...(httpSecureBind === undefined ? {} : { securePort: httpSecureBind }),
4306
+ },
4307
+ operationsApi: {
4308
+ network: {
4309
+ port: opsNetworkPort,
4310
+ cors: true,
4311
+ domainSocket: opsSocket,
4312
+ ...(opsSecureBind === undefined ? {} : { securePort: opsSecureBind }),
4313
+ },
4314
+ },
4044
4315
  mqtt: MQTT_DISABLED_CONFIG,
4045
4316
  localStudio: { enabled: false },
4046
4317
  authentication: { authorizeLocal: false, enableSessions: true },
@@ -4059,8 +4330,7 @@ function buildRepairPlist(dataDir, config) {
4059
4330
  modelsDir,
4060
4331
  setConfig,
4061
4332
  adminUser: DEFAULT_ADMIN_USER,
4062
- adminPass: "", // ignored in pass-file mode
4063
- httpPort,
4333
+ httpPort: httpBindValue,
4064
4334
  opsNetworkPort,
4065
4335
  passFile: {
4066
4336
  launcher: launchdLauncherPath(),
@@ -4070,6 +4340,201 @@ function buildRepairPlist(dataDir, config) {
4070
4340
  },
4071
4341
  });
4072
4342
  }
4343
+ /**
4344
+ * Resolve whether the pass-file launcher's argv is satisfiable (flair#1685),
4345
+ * WITHOUT touching the network or writing anything. Pure filesystem + env:
4346
+ *
4347
+ * - an existing valid 0600 non-empty file -> reuse, never rewrite
4348
+ * - FLAIR_ADMIN_PASS / HDB_ADMIN_PASSWORD -> a candidate the executor must
4349
+ * prove against the live instance before it may write it
4350
+ * - neither -> missing (refuse)
4351
+ *
4352
+ * An existing file that does not pass readSecretFileSecure (wrong mode, empty)
4353
+ * is reported missing rather than reused: the launcher re-checks the mode at
4354
+ * start time and would refuse the same file, so writing the plist around it
4355
+ * would reproduce #1685 one level down.
4356
+ */
4357
+ function resolveAdminPassAvailability(path) {
4358
+ if (existsSync(path)) {
4359
+ try {
4360
+ readAdminPassFileSecure(path);
4361
+ return { kind: "existing-valid" };
4362
+ }
4363
+ catch (err) {
4364
+ const msg = err instanceof Error ? err.message : String(err);
4365
+ return {
4366
+ kind: "missing",
4367
+ detail: `the admin-pass file at ${path} is unusable (${msg})`,
4368
+ };
4369
+ }
4370
+ }
4371
+ if (process.env.FLAIR_ADMIN_PASS || process.env.HDB_ADMIN_PASSWORD) {
4372
+ return { kind: "candidate", source: "env" };
4373
+ }
4374
+ return {
4375
+ kind: "missing",
4376
+ detail: `the admin-pass file at ${path} does not exist and no credential is available in the environment. ` +
4377
+ `Run 'flair init' to provision ${path}, or start the instance and re-run 'flair doctor --fix'.`,
4378
+ };
4379
+ }
4380
+ /**
4381
+ * Prove an admin credential belongs to the running instance before adoption
4382
+ * materializes it into the 0600 pass file (flair#1685). The admin-gated
4383
+ * /HealthDetail read is the proof: a rejected Basic credential produces 401 and
4384
+ * is NOT retried through the agent-key floor (that floor only engages when no
4385
+ * credential was sent at all), so success here means THIS credential was
4386
+ * accepted by THIS instance. Never logs the secret.
4387
+ */
4388
+ async function proveAdminPassAgainstInstance(port, adminPass) {
4389
+ try {
4390
+ await api("GET", "/HealthDetail", undefined, {
4391
+ baseUrl: `http://127.0.0.1:${port}`,
4392
+ explicitAdminPass: adminPass,
4393
+ });
4394
+ return null;
4395
+ }
4396
+ catch (err) {
4397
+ return err instanceof Error ? err.message : String(err);
4398
+ }
4399
+ }
4400
+ /**
4401
+ * Validate the pass file against the launcher's OWN read contract before the
4402
+ * plist that names it is written (flair#1685): exists, readable, owner-only
4403
+ * (no group/other bits), non-empty. This is exactly the four checks
4404
+ * templates/launchd/start-flair-with-admin-pass.sh runs at start time; the
4405
+ * write side applies them so a plist is never written around a file the
4406
+ * launcher would refuse. Returns the problem, or null when the file is safe.
4407
+ */
4408
+ function validateAdminPassFileForLauncher(path) {
4409
+ try {
4410
+ readAdminPassFileSecure(path);
4411
+ return null;
4412
+ }
4413
+ catch (err) {
4414
+ return err instanceof Error ? err.message : String(err);
4415
+ }
4416
+ }
4417
+ /**
4418
+ * Write the launchd plist for `flair init`, with the SAME credential discipline
4419
+ * as the `doctor --fix` arms (flair#1693, closing flair#1685's other half).
4420
+ *
4421
+ * The old `flair init` wrote an INLINE plist (ProgramArguments = [node,
4422
+ * harper.js, run, .] + HDB_ADMIN_PASSWORD in EnvironmentVariables) unconditionally,
4423
+ * which downgraded an instance already adopted into the flair#1573 pass-file
4424
+ * shape and put the admin password into a config file. This function removes
4425
+ * that path structurally (there is no inline branch left to call — `passFile`
4426
+ * is required on `LaunchdPlistOptions`) and makes the writer own its
4427
+ * precondition:
4428
+ *
4429
+ * 1. An on-disk plist that is provably ours IN THE PASS-FILE SHAPE is left
4430
+ * byte-for-byte unchanged. An adopted instance is never downgraded, and a
4431
+ * re-run of init does not churn mtime / flap launchd state.
4432
+ * 2. A plist that is provably another instance's (`foreign`) or cannot be
4433
+ * attributed (`unattributable`) is refused, naming `flair doctor --fix`.
4434
+ * 3. Otherwise, resolve the pass file BEFORE writing anything: reuse an
4435
+ * existing valid 0600 file; else prove the credential in hand against the
4436
+ * running instance and write it 0600 atomically; else refuse with the
4437
+ * file and the command named and write NO plist. Never a plist whose
4438
+ * launcher argv cannot be satisfied.
4439
+ *
4440
+ * The proof uses the same authed `GET /HealthDetail` as the doctor arms (a
4441
+ * rejected Basic credential is a 401 and never falls through to the agent-key
4442
+ * floor), so a credential that does not belong to THIS instance is refused
4443
+ * rather than baked into a pass file the instance would reject.
4444
+ */
4445
+ export async function writeInitLaunchdPlist(opts, deps = {}) {
4446
+ const prove = deps.prove ?? proveAdminPassAgainstInstance;
4447
+ const adminPassPath = opts.adminPassPath ?? defaultAdminPassPath();
4448
+ // Already adopted: ours, pass-file shape -> leave the bytes alone (#1693).
4449
+ if (existsSync(opts.plistPath)) {
4450
+ let raw = null;
4451
+ try {
4452
+ raw = readFileSync(opts.plistPath, "utf-8");
4453
+ }
4454
+ catch {
4455
+ raw = null;
4456
+ }
4457
+ if (raw !== null) {
4458
+ const disposition = classifyPlist(opts.plistPath, opts.dataDir, {
4459
+ exists: existsSync,
4460
+ read: () => raw,
4461
+ readRootPath: () => readPlistRootPath(opts.plistPath),
4462
+ });
4463
+ if (disposition === "foreign" || disposition === "unattributable") {
4464
+ return {
4465
+ kind: "refused",
4466
+ detail: `refusing to write the launchd plist at ${opts.plistPath}: ` +
4467
+ (disposition === "foreign"
4468
+ ? "it is registered to a different data directory, so it belongs to a different Flair instance."
4469
+ : "it has no ROOTPATH, so it cannot be proven to belong to this instance.") +
4470
+ " Run 'flair doctor --fix' to repair launchd management.",
4471
+ };
4472
+ }
4473
+ const refs = readPlistProgramRefs(opts.plistPath, () => raw);
4474
+ const launcherArg = refs?.programArguments[0] ?? "";
4475
+ const passFileShape = !plistCarriesInlineAdminPassword(raw) &&
4476
+ basename(launcherArg) === basename(launchdLauncherPath());
4477
+ if (disposition === "ours" && passFileShape) {
4478
+ return {
4479
+ kind: "unchanged",
4480
+ plistPath: opts.plistPath,
4481
+ detail: `the launchd service is already adopted with the pass-file launcher; leaving ${opts.plistPath} unchanged`,
4482
+ };
4483
+ }
4484
+ }
4485
+ }
4486
+ // Credential before plist (flair#1685): reuse an existing valid 0600 file,
4487
+ // else prove the in-hand credential against the live instance and write it
4488
+ // 0600, else refuse with no plist.
4489
+ if (resolveAdminPassAvailability(adminPassPath).kind !== "existing-valid") {
4490
+ const candidate = opts.adminPass || process.env.FLAIR_ADMIN_PASS || process.env.HDB_ADMIN_PASSWORD;
4491
+ if (!candidate) {
4492
+ return {
4493
+ kind: "refused",
4494
+ detail: `refusing to write the launchd plist: the admin-pass file at ${adminPassPath} does not exist and no ` +
4495
+ "admin credential is available to provision it. Set FLAIR_ADMIN_PASS or pass --admin-pass-file <path>, " +
4496
+ "then re-run 'flair init'.",
4497
+ };
4498
+ }
4499
+ if (opts.liveInstance !== false) {
4500
+ const proof = await prove(opts.port, candidate);
4501
+ if (proof) {
4502
+ return {
4503
+ kind: "refused",
4504
+ detail: "refusing to write the launchd plist: the admin credential does not authenticate against the running " +
4505
+ `instance (${proof}), so writing it to ${adminPassPath} would create a pass file the instance rejects. ` +
4506
+ "Run 'flair init' with the instance's current credential.",
4507
+ };
4508
+ }
4509
+ }
4510
+ writeAdminPassFile(adminPassPath, candidate);
4511
+ }
4512
+ const passFileProblem = validateAdminPassFileForLauncher(adminPassPath);
4513
+ if (passFileProblem) {
4514
+ return { kind: "refused", detail: `refusing to write the launchd plist: ${passFileProblem}` };
4515
+ }
4516
+ const plist = buildLaunchdPlist({
4517
+ label: opts.label,
4518
+ execPath: opts.execPath,
4519
+ harperBinPath: opts.harperBinPath,
4520
+ workingDirectory: opts.workingDirectory,
4521
+ dataDir: opts.dataDir,
4522
+ modelsDir: opts.modelsDir,
4523
+ setConfig: opts.setConfig,
4524
+ adminUser: opts.adminUser,
4525
+ httpPort: opts.httpPort,
4526
+ opsNetworkPort: opts.opsNetworkPort,
4527
+ passFile: {
4528
+ launcher: launchdLauncherPath(),
4529
+ adminPassFile: adminPassPath,
4530
+ home: homedir(),
4531
+ path: process.env.PATH ?? "/usr/bin:/bin:/usr/sbin:/sbin",
4532
+ },
4533
+ });
4534
+ // No secret is embedded (pass-file mode), so 0644 matches the doctor arm.
4535
+ writeFileAtomic(opts.plistPath, plist, 0o644);
4536
+ return { kind: "written", plistPath: opts.plistPath };
4537
+ }
4073
4538
  /**
4074
4539
  * Compute the launchd repair plan for `dataDir` (flair#1573 slice b) WITHOUT
4075
4540
  * executing it — the detect + classify + decide half. The doctor command uses
@@ -4098,7 +4563,31 @@ function planLaunchdRepairFor(dataDir, port) {
4098
4563
  // Is a direct (non-launchd) process serving this instance right now?
4099
4564
  const instancePid = resolveInstanceServingPid(dataDir, port);
4100
4565
  const directProcessRunning = instancePid !== null && observation.state !== "managed";
4101
- const plan = planLaunchdRepair({ observation, disposition, plistPath, directProcessRunning, configReadable });
4566
+ // Credential before plist (flair#1685): the plan may only authorize a
4567
+ // pass-file plist whose launcher argv is satisfiable.
4568
+ const adminPassPath = defaultAdminPassPath();
4569
+ const adminPass = resolveAdminPassAvailability(adminPassPath);
4570
+ const plan = planLaunchdRepair({
4571
+ observation,
4572
+ disposition,
4573
+ plistPath,
4574
+ directProcessRunning,
4575
+ configReadable,
4576
+ adminPassPath,
4577
+ adminPass,
4578
+ // Hand the instance's own bind values to the PLANNER so an unsupported one
4579
+ // (a disabled or unparseable http.port) refuses BEFORE the executor's adopt
4580
+ // arm clean-stops the live instance. Deciding this in the executor's writer
4581
+ // would bounce first and refuse after — leaving the instance down with a
4582
+ // remedy that re-runs this very command.
4583
+ configBindValues: config
4584
+ ? {
4585
+ httpPort: config.http?.port,
4586
+ httpSecurePort: config.http?.securePort,
4587
+ opsSecurePort: config.operationsApi?.network?.securePort,
4588
+ }
4589
+ : undefined,
4590
+ });
4102
4591
  return { plan, plistPath, isLegacy, config };
4103
4592
  }
4104
4593
  /**
@@ -4125,11 +4614,23 @@ function planLaunchdRepairFor(dataDir, port) {
4125
4614
  * process is refused by the liveness machine (DISAGREEMENT/UNKNOWN), never
4126
4615
  * signalled.
4127
4616
  *
4617
+ * Credential before plist (flair#1685): the generated plist is always
4618
+ * pass-file mode, so its launcher cannot start unless ~/.flair/admin-pass
4619
+ * exists and is safe. An existing valid file is reused; an env credential is
4620
+ * PROVEN against the live instance (before the adopt bounce) and only then
4621
+ * written; nothing usable yields a refusal with no plist. The written file is
4622
+ * validated against the launcher's own read contract (exists, mode 0600,
4623
+ * non-empty) before load.
4624
+ *
4128
4625
  * Never reports success on a direct-start fallback: the final verify is
4129
- * assessLaunchdManagement, and anything short of `managed` is a `failed` result
4130
- * with the detached detail + remedy, never a silent pass. The whole executor
4131
- * arm is wrapped in try/catch (Kern's b1 defect): a throw becomes a named
4132
- * `failed` result (or an engine-backwards `refused`), never a crash mid-report.
4626
+ * assessLaunchdManagement (launchctl PID AND that PID is the serving process),
4627
+ * and anything short of `managed` is a `failed` result with the detached detail
4628
+ * + remedy, never a silent pass. On the adopt arm the verify additionally
4629
+ * proves the serving pid CHANGED and the pre-adopt pid is dead, because port
4630
+ * health alone is answered by the old process (flair#1684/#1685). The whole
4631
+ * executor arm is wrapped in try/catch (Kern's b1 defect): a throw becomes a
4632
+ * named `failed` result (or an engine-backwards `refused`), never a crash
4633
+ * mid-report.
4133
4634
  */
4134
4635
  async function repairLaunchdManagement(dataDir, port) {
4135
4636
  const { plan, plistPath, isLegacy, config } = planLaunchdRepairFor(dataDir, port);
@@ -4149,9 +4650,56 @@ async function repairLaunchdManagement(dataDir, port) {
4149
4650
  // the live instance (guard-after-stop would SIGTERM the instance and
4150
4651
  // then refuse, leaving it down with nothing to restart it).
4151
4652
  guardEngineNotBackwards(dataDir);
4152
- // Adopt (flair#1573 slice b2): clean-stop the direct process first, so
4153
- // the regenerate + load below does not collide on the port.
4653
+ // Credential before plist (flair#1685). Resolve and, when the plan says
4654
+ // the pass file must be materialized (an env candidate), PROVE the
4655
+ // credential against the live instance BEFORE the adopt bounce stops
4656
+ // it — then write the 0600 file. Refuse, with no plist and no bounce,
4657
+ // when nothing proves.
4658
+ const adminPassPath = defaultAdminPassPath();
4659
+ if (plan.credential.writeAdminPassFile) {
4660
+ const candidate = process.env.FLAIR_ADMIN_PASS ?? process.env.HDB_ADMIN_PASSWORD;
4661
+ if (!candidate) {
4662
+ return {
4663
+ kind: "refused",
4664
+ reason: "missing-credential",
4665
+ detail: `refusing to repair the launchd plist: ${adminPassPath} must be written from a credential, ` +
4666
+ "but no credential is available in the environment.",
4667
+ plistPath,
4668
+ };
4669
+ }
4670
+ const proof = await proveAdminPassAgainstInstance(port, candidate);
4671
+ if (proof) {
4672
+ return {
4673
+ kind: "refused",
4674
+ reason: "missing-credential",
4675
+ detail: "refusing to repair the launchd plist: the credential in FLAIR_ADMIN_PASS/HDB_ADMIN_PASSWORD " +
4676
+ `does not authenticate against the running instance (${proof}), so writing it to ` +
4677
+ `${adminPassPath} would create a pass file the instance rejects. Run 'flair init' to provision ` +
4678
+ "the correct credential.",
4679
+ plistPath,
4680
+ };
4681
+ }
4682
+ writeAdminPassFile(adminPassPath, candidate);
4683
+ }
4684
+ // Validate the pass file against the launcher's OWN read contract before
4685
+ // any plist names it: an existing file that drifted to 0644 must refuse
4686
+ // here, never be baked into a plist the launcher will reject at start.
4687
+ const passFileProblem = validateAdminPassFileForLauncher(adminPassPath);
4688
+ if (passFileProblem) {
4689
+ return {
4690
+ kind: "refused",
4691
+ reason: "missing-credential",
4692
+ detail: `refusing to repair the launchd plist: ${passFileProblem}`,
4693
+ plistPath,
4694
+ };
4695
+ }
4696
+ // Adopt (flair#1573 slice b2): capture the process serving the instance
4697
+ // NOW (before the stop), then clean-stop it, so the regenerate + load
4698
+ // below does not collide on the port. The captured pid is the evidence
4699
+ // the post-load verify uses to prove the serving pid CHANGED.
4700
+ let directPid = null;
4154
4701
  if (plan.kind === "adopt") {
4702
+ directPid = resolveInstanceServingPid(dataDir, port);
4155
4703
  const stop = await stopDirectProcessForAdopt(port, dataDir);
4156
4704
  if (stop)
4157
4705
  return stop; // a named failed result
@@ -4162,6 +4710,14 @@ async function repairLaunchdManagement(dataDir, port) {
4162
4710
  const plist = buildRepairPlist(dataDir, config);
4163
4711
  const newPlistPath = launchdPlistPath(launchdLabel(dataDir));
4164
4712
  writeFileAtomic(newPlistPath, plist, 0o644);
4713
+ // Validate the plist's absolute paths BEFORE launchd load (flair#1685
4714
+ // hardening): launchctl load/start exit 0 for a job whose program is
4715
+ // missing, so a stale launcher or node path produces a job that never
4716
+ // starts — the same masked failure this repair exists to prevent.
4717
+ const stalePlistPath = diagnoseLaunchdPlistPaths(newPlistPath);
4718
+ if (stalePlistPath) {
4719
+ return { kind: "failed", detail: stalePlistPath.message, remedy: stalePlistPath.remedy };
4720
+ }
4165
4721
  // flair#1586 / #1581: a SET_CONFIG-less detach (MQTT_* via
4166
4722
  // buildDirectSpawnEnv) can persist mqtt.network as mtls, port,
4167
4723
  // securePort when Harper stored no originals for already-null ports.
@@ -4188,13 +4744,45 @@ async function repairLaunchdManagement(dataDir, port) {
4188
4744
  }
4189
4745
  catch { /* best effort */ }
4190
4746
  }
4191
- // Load (unload -> load -> start).
4747
+ // Load (unload -> load -> start). Drop the pre-bounce leftover
4748
+ // socket first so exists() cannot be true on the dead inode —
4749
+ // Darwin #1704 (`9413a80`) chmod'd that leftover for 10s and
4750
+ // still read 0755 after Harper bind()d a new file.
4751
+ const bounceAt = Date.now();
4752
+ unlinkStaleOpsSocket(dataDir);
4192
4753
  ensureLaunchdServiceLoaded(dataDir, (cmd) => execSync(cmd, { stdio: "pipe" }));
4193
4754
  // Verify (fail-loud).
4194
4755
  const after = observeLaunchdManagement(dataDir, port);
4195
4756
  if (after.state !== "managed") {
4196
4757
  return { kind: "failed", detail: after.detail, remedy: after.remedy };
4197
4758
  }
4759
+ // On the adopt arm, port health alone is the green light that lied in
4760
+ // #1684: the pre-adopt direct process answered the port the whole time
4761
+ // the launchd job was failing to start. Prove the launchd job itself
4762
+ // serves — the old pid is dead, the serving pid changed, and it is
4763
+ // launchd's reported pid for this label.
4764
+ if (plan.kind === "adopt") {
4765
+ const label = after.label ?? resolveLaunchdLabel(dataDir).label;
4766
+ const managedPid = readLaunchctlJobState(label, realLaunchctlLister).pid;
4767
+ const servingPid = resolveInstanceServingPid(dataDir, port);
4768
+ const proof = verifyAdoptServing({
4769
+ directPid,
4770
+ managedPid,
4771
+ servingPid,
4772
+ directPidAlive: directPid !== null && isProcessAlive(directPid),
4773
+ });
4774
+ if (proof) {
4775
+ return { kind: "failed", detail: proof.detail, remedy: ["flair stop", "flair doctor --fix"] };
4776
+ }
4777
+ }
4778
+ // flair#1701: the launchd bounce (adopt and regenerate) is a first
4779
+ // start. The product launcher execs Harper and never chmods, so the
4780
+ // new operations-server lands at 0777 & ~umask. Init / start /
4781
+ // restart already call this after health; without it here, doctor
4782
+ // flags ✗ Ops socket permissions until a second start. Wait for
4783
+ // Harper's bind() (HTTP can answer first); ignore leftover mtimes
4784
+ // older than bounceAt.
4785
+ await readyOpsSocketPostureAfterStart(dataDir, { notBeforeMs: bounceAt });
4198
4786
  const detail = plan.kind === "adopt"
4199
4787
  ? `adopted the direct-spawned instance into launchd (bounced the live instance): ${after.detail}`
4200
4788
  : after.detail;
@@ -4495,18 +5083,16 @@ async function startFlairProcess(port, dataDir) {
4495
5083
  // value is what the next boot reads. It also made doctor's
4496
5084
  // `flair init && flair restart` remedy a no-op: the restart undid whatever
4497
5085
  // init had just written.
4498
- const env = {
4499
- ...process.env,
4500
- ...buildDirectSpawnEnv({
4501
- dataDir,
4502
- modelsDir: process.env.FLAIR_MODELS_DIR ?? join(dataDir, "models"),
4503
- httpPort: port,
4504
- opsPort: resolveOpsPort({ port }),
4505
- opsBindHost: resolveOpsBindHost({}),
4506
- adminUser: DEFAULT_ADMIN_USER,
4507
- adminPass,
4508
- }),
4509
- };
5086
+ const env = closedDirectSpawnEnv(process.env, buildDirectSpawnEnv({
5087
+ dataDir,
5088
+ modelsDir: process.env.FLAIR_MODELS_DIR ?? join(dataDir, "models"),
5089
+ httpPort: port,
5090
+ httpBindHost: resolveHttpBindHost({}),
5091
+ opsPort: resolveOpsPort({ port }),
5092
+ opsBindHost: resolveOpsBindHost({}),
5093
+ adminUser: DEFAULT_ADMIN_USER,
5094
+ adminPass,
5095
+ }));
4510
5096
  const proc = spawn(process.execPath, [bin, "run", "."], {
4511
5097
  cwd: flairPackageDir(), env, detached: true, stdio: "ignore",
4512
5098
  });
@@ -4921,7 +5507,18 @@ async function runCli() {
4921
5507
  program.outputHelp();
4922
5508
  process.exit(0);
4923
5509
  }
4924
- await program.parseAsync();
5510
+ try {
5511
+ await program.parseAsync();
5512
+ }
5513
+ catch (err) {
5514
+ // Errors the API layer already translated (flair#1719) carry a sentence
5515
+ // naming the actor, state and remedy; print it without the undici stack.
5516
+ if (err && typeof err === "object" && err.flairFriendly === true) {
5517
+ console.error(err.message);
5518
+ process.exit(1);
5519
+ }
5520
+ throw err;
5521
+ }
4925
5522
  }
4926
5523
  // Run CLI directly when this file is the entry point — covers `node dist/cli.js`,
4927
5524
  // `bun src/cli.ts`, and the test harness (which spawns src/cli.ts under bun).
@@ -4931,7 +5528,8 @@ if (import.meta.main) {
4931
5528
  }
4932
5529
  // ─── Exported for testing ─────────────────────────────────────────────────────
4933
5530
  export { classifyKeysDir, applyKeyPrune } from "./commands/keys.js";
4934
- export { runFederationSyncOnce, runFederationWatch, federationStatusUrlSetting, describeFederationStatusFetchFailed, isFederationStatusConnectFailure, rewriteFederationStatusFetchFailed, isFederationStatusAuthFailure, isFederationStatusAuthRemedy, };
5531
+ export { runFederationSyncOnce, persistLocalPeerLastSyncAt, runFederationWatch, federationStatusUrlSetting, describeFederationStatusFetchFailed, isFederationStatusConnectFailure, rewriteFederationStatusFetchFailed, isFederationStatusAuthFailure, isFederationStatusAuthRemedy, };
5532
+ export { describeFederationPairHubAccessError, describeFederationPairLocalAccessError, rewriteFederationPairHubAccessError, rewriteFederationPairLocalAccessError, };
4935
5533
  export { categorizeForHygiene, HYGIENE_TEST_CONTENT_PATTERNS, };
4936
5534
  export { formatCandidateLine, describeReflectError, validatePromoteOpts, validateRejectOpts, decideCandidateAction, derivePromotedTags, derivePromotedVisibility, validateHumanReviewerId, isMachineReviewerId, ADK_SCOPE_TAG_PREFIX, CONTINUITY_SCOPE_TAG_PREFIX, MACHINE_REVIEWER_PREFIX, MACHINE_REVIEWER_ADK_AUTO_PROMOTE, } from "./commands/rem.js";
4937
5535
  export { grantMcpClient, revokeMcpClient, readMcpClientManifest, buildMcpGrantConfig, defaultMcpClientManifestPath, McpClientNameExistsError, McpClientAgentIdCollisionError, McpClientNotFoundError, } from "./commands/mcp.js";