@tpsdev-ai/flair 0.55.1 → 0.56.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 (76) hide show
  1. package/README.md +3 -3
  2. package/dist/bridges/builtins/markdown.js +2 -2
  3. package/dist/bridges/discover.js +2 -2
  4. package/dist/bridges/runtime/allow-list.js +2 -2
  5. package/dist/build-info.json +3 -3
  6. package/dist/cli.js +201 -95
  7. package/dist/commands/attention.js +2 -2
  8. package/dist/commands/backup.js +2 -2
  9. package/dist/commands/doctor.js +168 -37
  10. package/dist/commands/export.js +2 -2
  11. package/dist/commands/federation.js +229 -95
  12. package/dist/commands/hook.js +4 -4
  13. package/dist/commands/init.js +94 -70
  14. package/dist/commands/mcp.js +2 -2
  15. package/dist/commands/migrate-harness-memory.js +8 -8
  16. package/dist/commands/rem.js +31 -4
  17. package/dist/commands/service.js +25 -1
  18. package/dist/commands/session.js +2 -2
  19. package/dist/commands/uninstall.js +2 -2
  20. package/dist/commands/upgrade.js +88 -69
  21. package/dist/doctor-client.js +341 -161
  22. package/dist/engine-version.js +2 -2
  23. package/dist/federation/scheduler.js +5 -5
  24. package/dist/hook-install.js +359 -176
  25. package/dist/install/clients.js +908 -214
  26. package/dist/keystore.js +10 -2
  27. package/dist/lib/auth-resolve.js +5 -5
  28. package/dist/lib/config-critical-section.js +557 -0
  29. package/dist/lib/doctor-config-path.js +2 -2
  30. package/dist/lib/doctor-run.js +107 -27
  31. package/dist/lib/flair-paths.js +29 -0
  32. package/dist/lib/home.js +60 -0
  33. package/dist/lib/launchd-repair.js +109 -0
  34. package/dist/lib/mcp-enable.js +4 -4
  35. package/dist/lib/owned-pins.js +256 -94
  36. package/dist/lib/pin-write-guard.js +87 -0
  37. package/dist/lib/settings-bytes.js +85 -0
  38. package/dist/lib/socket-path-limit.js +120 -0
  39. package/dist/lib/uninstall-purge.js +2 -18
  40. package/dist/lib/upgrade-plain-tree.js +2 -2
  41. package/dist/lib/upgrade-status.js +164 -0
  42. package/dist/lib/wiring-spec.js +238 -0
  43. package/dist/mcp-client-assertion.js +3 -3
  44. package/dist/rem/promote-policy.js +102 -0
  45. package/dist/rem/runner.js +3 -3
  46. package/dist/rem/scheduler.js +5 -5
  47. package/dist/rem/snapshot.js +2 -2
  48. package/dist/resources/MemoryReflect.js +10 -0
  49. package/dist/resources/OAuth.js +62 -11
  50. package/dist/resources/Presence.js +135 -47
  51. package/dist/resources/admin-layout.js +7 -2
  52. package/dist/resources/auto-promote-lib.js +56 -0
  53. package/dist/resources/health.js +26 -0
  54. package/dist/resources/memory-reflect-lib.js +215 -6
  55. package/dist/resources/migrations/progress.js +17 -0
  56. package/dist/resources/migrations/runner.js +46 -27
  57. package/dist/resources/migrations/status.js +2 -1
  58. package/dist/src/keystore.js +10 -2
  59. package/dist/src/lib/home.js +60 -0
  60. package/dist/src/rem/promote-policy.js +102 -0
  61. package/dist/src/rem/scheduler.js +5 -5
  62. package/dist/version-check.js +2 -2
  63. package/dist/version-handshake.js +2 -2
  64. package/docs/api-reference.md +31 -6
  65. package/docs/auth.md +14 -2
  66. package/docs/deploying-on-fabric.md +5 -4
  67. package/docs/deployment.md +26 -37
  68. package/docs/embedding-in-a-harper-app.md +4 -2
  69. package/docs/entity-vocabulary.md +5 -5
  70. package/docs/federation.md +58 -19
  71. package/docs/hosted-on-fabric.md +7 -5
  72. package/docs/mcp-clients.md +29 -12
  73. package/docs/releasing.md +66 -22
  74. package/docs/spoke-bringup.md +41 -22
  75. package/docs/standalone-local.md +12 -16
  76. package/package.json +3 -1
@@ -23,7 +23,7 @@ import { existsSync, readFileSync, readdirSync } from "node:fs";
23
23
  import { join } from "node:path";
24
24
  import { checkClaudeMdBootstrap, checkSessionStartHook, effectiveFlairUrl, hookCommandIsSilenced, isFlairHookCommand, partitionKeyIds, planAgentIterations, readClientMcpBlock, } from "../doctor-client.js";
25
25
  import { hookInstallHint, hookSettingsPath, installHook, SUPPORTED_HARNESSES, } from "../hook-install.js";
26
- import { findUnsafeWiredPins, staleHookRemedy, staleMcpClientPins, staleSessionStartHookPins } from "./owned-pins.js";
26
+ import { findUnsafeWiredPins, mcpClientPinFindings, sessionStartHookPinFindings, staleHookRemedy } from "./owned-pins.js";
27
27
  import { flairCliVersion, isResolvedVersion } from "./mcp-spec.js";
28
28
  import { unsafeAdapterPinDetail } from "./stale-client-pin.js";
29
29
  import { isDetached, plistCarriesInlineAdminPassword, renderDetachedWarning, } from "./launchd-management.js";
@@ -50,6 +50,18 @@ const MCP_CLIENT_IDS = ["claude-code", "codex", "gemini", "cursor", "antigravity
50
50
  function result(id, label, status, extra = {}) {
51
51
  return { id, label, status, ...extra };
52
52
  }
53
+ /**
54
+ * flair#1834 round 3 (CodeRabbit): the icon for a `doctor --fix` MCP re-pin line.
55
+ * An ATTEMPTED-but-SKIPPED fix (e.g. a behind Codex pin until A2 lands, or any
56
+ * other skip) is not a success — render it with the warn icon, never ok. A hold
57
+ * and a failed write are also warn. Only an actual update, or an already-current
58
+ * noop, is ok.
59
+ */
60
+ export function mcpRepinIcon(action, ok) {
61
+ if (!ok)
62
+ return "warn";
63
+ return action === "update" || action === "noop" ? "ok" : "warn";
64
+ }
53
65
  function runMcpBlock(ctx) {
54
66
  const id = "mcp-block";
55
67
  const label = "MCP server block";
@@ -65,7 +77,12 @@ function runMcpBlock(ctx) {
65
77
  // client is surfaced as info by `flair doctor`, never counted as a failure
66
78
  // here (which used to inflate the ✗ count with clients the user never chose).
67
79
  const wired = mcp.filter((clientId) => readClientMcpBlock(clientId, ctx.homeDir).present);
68
- if (wired.length === 0) {
80
+ // flair#1834 A1 round 2: the PIN finding (and the opted-in check) keys on
81
+ // STRUCTURAL presence — an entry without an identity is still an entry the
82
+ // refresh repairs, so the catalog must flag it too. `present` stays for the
83
+ // identity-keyed checks (unsafeWired below).
84
+ const visitable = mcp.filter((clientId) => readClientMcpBlock(clientId, ctx.homeDir).entryExists);
85
+ if (visitable.length === 0) {
69
86
  // Detected clients exist, but Flair is wired to none of them. Not a
70
87
  // per-client failure (nothing was opted in) — a skip that names the
71
88
  // detected clients, so a zero-wiring run neither invents a failure the
@@ -82,7 +99,7 @@ function runMcpBlock(ctx) {
82
99
  // Independent of "pin !== CLI version": a current MCP pin next to
83
100
  // flair-client@0.17.0 still silently drops writes.
84
101
  const unsafeWired = findUnsafeWiredPins(ctx.homeDir, ctx.cwd).filter((p) => p.source === "package.json"
85
- || (p.source === "mcp-client" && wired.includes(p.id)));
102
+ || (p.source === "mcp-client" && visitable.includes(p.id)));
86
103
  if (unsafeWired.length > 0) {
87
104
  const first = unsafeWired[0];
88
105
  return result(id, label, "fail", {
@@ -92,20 +109,60 @@ function runMcpBlock(ctx) {
92
109
  }
93
110
  const expected = flairCliVersion();
94
111
  if (isResolvedVersion(expected)) {
95
- const stale = staleMcpClientPins(ctx.homeDir, expected)
96
- .filter((r) => wired.includes(r.target.id));
97
- if (stale.length > 0) {
98
- const first = stale[0];
99
- const detail = stale.length === 1
100
- ? `MCP server (${first.target.id}): pinned to flair-mcp@${first.pin} (installed CLI is ${expected})`
101
- : `MCP server: stale pins ${stale.map((s) => `${s.target.id}@${s.pin}`).join(", ")} (installed CLI is ${expected})`;
102
- return result(id, label, "fail", {
103
- detail,
104
- remedy: "flair upgrade",
105
- });
112
+ const findings = mcpClientPinFindings(ctx.homeDir, expected)
113
+ .filter((f) => visitable.includes(f.reading.target.id));
114
+ if (findings.length > 0) {
115
+ // flair#1789: the same three-valued treatment the SessionStart hook gets.
116
+ // behind -> stale, blocking: today's error + `flair doctor --fix`,
117
+ // which now re-pins a behind MCP block (flair#1779). It used
118
+ // to say `flair upgrade`, which in this state says
119
+ // up-to-date and acts on nothing.
120
+ // ahead -> a held PASS: the refresh HOLDS an ahead pin (re-pinning
121
+ // would LOWER it), so a failure here would be a dead-end
122
+ // remedy that cannot act.
123
+ // unknown -> a pin we cannot compare: its own non-blocking warn, naming
124
+ // the raw value; the refresh holds it too, so it is not a
125
+ // failure and is never worded as an old adapter.
126
+ const behind = findings.filter((f) => f.direction === "behind");
127
+ const unknownFindings = findings.filter((f) => f.direction === "unknown");
128
+ const aheadFindings = findings.filter((f) => f.direction === "ahead");
129
+ if (behind.length > 0) {
130
+ const readings = behind.map((f) => f.reading);
131
+ const first = readings[0];
132
+ const detail = behind.length === 1
133
+ ? `MCP server (${first.target.id}): pinned to flair-mcp@${first.pin} (installed CLI is ${expected})`
134
+ : `MCP server: stale pins ${readings.map((r) => `${r.target.id}@${r.pin}`).join(", ")} (installed CLI is ${expected})`;
135
+ return result(id, label, "fail", {
136
+ detail,
137
+ remedy: "flair doctor --fix",
138
+ });
139
+ }
140
+ if (unknownFindings.length > 0) {
141
+ const detail = unknownFindings.length === 1
142
+ ? `MCP server (${unknownFindings[0].reading.target.id}): pin is not a version I can compare: ${unknownFindings[0].reading.pin} — not re-pinned; edit the client config or run flair init if this is unintended`
143
+ : `MCP server: pins I cannot compare: ${unknownFindings.map((f) => `${f.reading.target.id}@${f.reading.pin}`).join(", ")} — not re-pinned; edit the client config or run flair init if this is unintended`;
144
+ return result(id, label, "warn", { detail });
145
+ }
146
+ const aheadDetail = aheadFindings.length === 1
147
+ ? `MCP server (${aheadFindings[0].reading.target.id}): pinned to flair-mcp@${aheadFindings[0].reading.pin}, ahead of the installed CLI ${expected} — held`
148
+ : `MCP server: pins ahead of the installed CLI ${expected} — held (${aheadFindings.map((f) => `${f.reading.target.id}@${f.reading.pin}`).join(", ")})`;
149
+ return result(id, label, "pass", { detail: aheadDetail });
106
150
  }
107
151
  }
108
- return result(id, label, "pass", { detail: `configured for ${wired.join(", ")}` });
152
+ // flair#1834 round 3 (CodeRabbit MAJOR): a VISITABLE entry with no
153
+ // FLAIR_AGENT_ID is an INCOMPLETE configuration — flair-mcp refuses to start
154
+ // without one, and the client-integration path treats the entry as not wired.
155
+ // The catalog must not report it "configured". Keep the structural entry for
156
+ // pin findings (the checks above); say the identity is missing, with a remedy.
157
+ const identityless = visitable.filter((clientId) => !readClientMcpBlock(clientId, ctx.homeDir).present);
158
+ if (identityless.length > 0) {
159
+ return result(id, label, "warn", {
160
+ detail: `MCP server (${identityless.join(", ")}): a Flair entry is present but carries no FLAIR_AGENT_ID — ` +
161
+ `set FLAIR_AGENT_ID in the entry, or run flair init / flair doctor --fix to wire it`,
162
+ remedy: "flair doctor --fix",
163
+ });
164
+ }
165
+ return result(id, label, "pass", { detail: `configured for ${visitable.join(", ")}` });
109
166
  }
110
167
  function runFlairUrl(ctx) {
111
168
  const id = "flair-url";
@@ -205,17 +262,40 @@ function runSessionStartHook(ctx) {
205
262
  }
206
263
  const expected = flairCliVersion();
207
264
  if (isResolvedVersion(expected)) {
208
- const stale = staleSessionStartHookPins(ctx.homeDir, expected)
209
- .filter((r) => harnesses.includes(r.target.id));
210
- if (stale.length > 0) {
211
- const first = stale[0];
212
- const detail = stale.length === 1
213
- ? `SessionStart hook (${first.target.id}): pinned to flair-mcp@${first.pin} (installed CLI is ${expected})`
214
- : `SessionStart hook: stale pins ${stale.map((s) => `${s.target.id}@${s.pin}`).join(", ")} (installed CLI is ${expected})`;
215
- return result(id, label, "fail", {
216
- detail,
217
- remedy: staleHookRemedy(stale),
218
- });
265
+ const findings = sessionStartHookPinFindings(ctx.homeDir, expected)
266
+ .filter((f) => harnesses.includes(f.reading.target.id));
267
+ if (findings.length > 0) {
268
+ // flair#1778 follow-up: PIN DIRECTION matters, and there are THREE cases.
269
+ // behind -> stale, blocking: today's error + re-pin.
270
+ // ahead -> a held PASS: re-pinning would LOWER it, so it is not a
271
+ // failure and doctor exits on the state it preserves.
272
+ // unknown -> a pin we cannot compare: its OWN warn finding. It is NOT
273
+ // blocking, NOT auto-re-pinned, and never worded as an old
274
+ // adapter — the guard holds an unreadable pin.
275
+ const behind = findings.filter((f) => f.direction === "behind");
276
+ const unknownFindings = findings.filter((f) => f.direction === "unknown");
277
+ const aheadFindings = findings.filter((f) => f.direction === "ahead");
278
+ if (behind.length > 0) {
279
+ const readings = behind.map((f) => f.reading);
280
+ const first = readings[0];
281
+ const detail = behind.length === 1
282
+ ? `SessionStart hook (${first.target.id}): pinned to flair-mcp@${first.pin} (installed CLI is ${expected})`
283
+ : `SessionStart hook: stale pins ${readings.map((r) => `${r.target.id}@${r.pin}`).join(", ")} (installed CLI is ${expected})`;
284
+ return result(id, label, "fail", {
285
+ detail,
286
+ remedy: staleHookRemedy(readings),
287
+ });
288
+ }
289
+ if (unknownFindings.length > 0) {
290
+ const detail = unknownFindings.length === 1
291
+ ? `SessionStart hook (${unknownFindings[0].reading.target.id}): pin is not a version I can compare: ${unknownFindings[0].reading.pin} — not re-pinned; re-run flair init or edit the hook if this is unintended`
292
+ : `SessionStart hook: pins I cannot compare: ${unknownFindings.map((f) => `${f.reading.target.id}@${f.reading.pin}`).join(", ")} — not re-pinned; re-run flair init or edit the hook if this is unintended`;
293
+ return result(id, label, "warn", { detail });
294
+ }
295
+ const aheadDetail = aheadFindings.length === 1
296
+ ? `SessionStart hook (${aheadFindings[0].reading.target.id}): pinned to flair-mcp@${aheadFindings[0].reading.pin}, ahead of the installed CLI ${expected} — held`
297
+ : `SessionStart hook: pins ahead of the installed CLI ${expected} — held (${aheadFindings.map((f) => `${f.reading.target.id}@${f.reading.pin}`).join(", ")})`;
298
+ return result(id, label, "pass", { detail: aheadDetail });
219
299
  }
220
300
  }
221
301
  return result(id, label, "pass", {
@@ -495,7 +575,7 @@ export function catalogIssueDelta(before, after) {
495
575
  /** Compact catalog lines for doctor's Install health section. */
496
576
  export function renderCatalogDoctorLines(run) {
497
577
  return run.results.map((r) => {
498
- const icon = r.status === "pass" || r.status === "skip" ? "ok" : r.status === "unrun" ? "warn" : "error";
578
+ const icon = r.status === "pass" || r.status === "skip" ? "ok" : r.status === "fail" ? "error" : "warn";
499
579
  const word = r.status === "skip" ? "n/a" : r.status;
500
580
  const detail = r.detail ? ` — ${r.detail}` : "";
501
581
  return { icon, line: `${r.label}: ${word}${detail}` };
@@ -0,0 +1,29 @@
1
+ /**
2
+ * flair-paths.ts — the home-derived paths every subsystem must agree on (flair#1858).
3
+ *
4
+ * Each of these used to compute `~` itself (`os.homedir()` in cli.ts and
5
+ * backup.ts). `os.homedir()` is cached at process START, so a `HOME` set later in
6
+ * the process — which the keystore and the client writers now honour — was
7
+ * invisible to them, and doctor could inspect a different home from the one the
8
+ * writers used. They all resolve through `resolveHome()` now, with an explicit
9
+ * `home` argument available to tests and callers that already resolved one.
10
+ */
11
+ import { existsSync } from "node:fs";
12
+ import { join } from "node:path";
13
+ import { resolveHome } from "./home.js";
14
+ /** `~/.flair/data` — the instance data dir. */
15
+ export function flairDataDir(home = resolveHome()) {
16
+ return join(home, ".flair", "data");
17
+ }
18
+ /** `~/.flair/config.yaml`, or `config.yml` when only that exists. */
19
+ export function flairConfigPath(home = resolveHome()) {
20
+ const yamlPath = join(home, ".flair", "config.yaml");
21
+ const ymlPath = join(home, ".flair", "config.yml");
22
+ if (existsSync(ymlPath) && !existsSync(yamlPath))
23
+ return ymlPath;
24
+ return yamlPath;
25
+ }
26
+ /** Default `flair backup` output: `~/.flair/backups/flair-backup-<timestamp>.json`. */
27
+ export function flairBackupOutputPath(timestamp, home = resolveHome()) {
28
+ return join(home, ".flair", "backups", `flair-backup-${timestamp}.json`);
29
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * The user's home directory, resolved at CALL time (flair#1853).
3
+ *
4
+ * `os.homedir()` is cached at process start, so a HOME set later in the same
5
+ * process is invisible to it. Every Flair surface that resolves `~` — the
6
+ * keystore and the client config writers — must land on the SAME home, and it
7
+ * must be the one the calling shell actually uses.
8
+ *
9
+ * Which environment variable names that home differs by platform:
10
+ *
11
+ * - **Windows** — `USERPROFILE` is authoritative. Node's `os.homedir()` reads
12
+ * it, but a POSIX-style shell (Git Bash, MSYS, Cygwin) may set `HOME` to a
13
+ * different path. Preferring `HOME` there would move `~/.flair/keys` away
14
+ * from where the keys actually live, so an existing key would read as
15
+ * missing (and a new one would be written somewhere nothing looks).
16
+ * - **Everywhere else** — `HOME` is authoritative (and is how the test harness
17
+ * redirects a process), with `os.homedir()` as the fallback.
18
+ */
19
+ import { homedir } from "node:os";
20
+ /** The home directory for this invocation, resolved at call time. */
21
+ export function resolveHome() {
22
+ return process.platform === "win32"
23
+ ? process.env.USERPROFILE || homedir()
24
+ : process.env.HOME || homedir();
25
+ }
26
+ /**
27
+ * Run `fn` with BOTH `HOME` and `USERPROFILE` pointed at `homeDir`, then restore
28
+ * both to exactly what they were — including the previously-UNSET case, and even
29
+ * when `fn` throws. Returns `fn`'s value.
30
+ *
31
+ * `resolveHome()` reads `USERPROFILE` on win32 and `HOME` elsewhere, so setting
32
+ * only `HOME` silently ignored the override on Windows: doctor, the pin refresh
33
+ * and uninstall's `unwire()` then acted on the real profile instead of the
34
+ * directory the caller named. Both are set here, so the override holds on every
35
+ * platform.
36
+ *
37
+ * `fn` MUST be synchronous. The parameter type REJECTS a Promise-returning
38
+ * callback at compile time (a Promise is not assignable to the `never` branch),
39
+ * because a sync save/restore around async work would restore the environment
40
+ * before the work runs.
41
+ */
42
+ export function withHome(homeDir, fn) {
43
+ const prevHome = process.env.HOME;
44
+ const prevProfile = process.env.USERPROFILE;
45
+ process.env.HOME = homeDir;
46
+ process.env.USERPROFILE = homeDir;
47
+ try {
48
+ return fn();
49
+ }
50
+ finally {
51
+ if (prevHome === undefined)
52
+ delete process.env.HOME;
53
+ else
54
+ process.env.HOME = prevHome;
55
+ if (prevProfile === undefined)
56
+ delete process.env.USERPROFILE;
57
+ else
58
+ process.env.USERPROFILE = prevProfile;
59
+ }
60
+ }
@@ -240,6 +240,12 @@ export function verifyAdoptServing(input) {
240
240
  detail: `the serving process is still pid ${servingPid}, the pre-adopt process — adoption did not bounce the live instance`,
241
241
  };
242
242
  }
243
+ if (managedPid === null) {
244
+ return {
245
+ detail: "the launchd job reports no pid after load - the adopted job's identity cannot be confirmed, " +
246
+ "so the listener cannot be attributed to it",
247
+ };
248
+ }
243
249
  if (managedPid !== null && servingPid !== managedPid) {
244
250
  return {
245
251
  detail: `the instance is served by pid ${servingPid}, but launchd reports pid ${managedPid} for the adopted ` +
@@ -318,3 +324,106 @@ export function decideAdoptStop(state, postStopHealth) {
318
324
  }
319
325
  return "proceed";
320
326
  }
327
+ /**
328
+ * Poll `observe` until `until(value)` holds or `deadlineMs` elapses (measured on
329
+ * the injected `now`). No global timers live in the logic — `sleep` is injected
330
+ * too — so the whole loop is deterministic and unit-testable. Returns the LAST
331
+ * observation plus whether it timed out.
332
+ */
333
+ export async function pollUntil(opts) {
334
+ const now = opts.now ?? (() => Date.now());
335
+ const sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
336
+ const intervalMs = opts.intervalMs ?? 250;
337
+ const start = now();
338
+ let value = await opts.observe();
339
+ let observations = 1;
340
+ while (!opts.until(value)) {
341
+ if (now() - start >= opts.deadlineMs) {
342
+ return { value, timedOut: true, waitedMs: now() - start, observations };
343
+ }
344
+ await sleep(intervalMs);
345
+ value = await opts.observe();
346
+ observations++;
347
+ }
348
+ return { value, timedOut: false, waitedMs: now() - start, observations };
349
+ }
350
+ function fmtPid(pid) {
351
+ return pid === null ? "null" : String(pid);
352
+ }
353
+ /**
354
+ * Wait for the adopted job to actually serve, then prove it with
355
+ * `verifyAdoptServing` UNCHANGED (flair#1827). Polls `{managedPid, servingPid,
356
+ * directPidAlive}` until `servingPid !== null && !directPidAlive` (the launchd
357
+ * job has written hdb.pid / bound the port AND the pre-adopt process is gone) or
358
+ * the deadline. On timeout the failure detail names the wait and the last
359
+ * observation. All three identity rules of the proof are preserved.
360
+ */
361
+ export async function verifyAdoptServingWithWait(opts) {
362
+ const poll = await pollUntil({
363
+ observe: opts.observe,
364
+ until: (e) => e.servingPid !== null && !e.directPidAlive,
365
+ deadlineMs: opts.deadlineMs,
366
+ intervalMs: opts.intervalMs,
367
+ now: opts.now,
368
+ sleep: opts.sleep,
369
+ });
370
+ const proof = verifyAdoptServing(poll.value);
371
+ if (proof && poll.timedOut) {
372
+ return {
373
+ evidence: poll.value,
374
+ proof: {
375
+ detail: `${proof.detail} (waited ${poll.waitedMs}ms for the launchd job to serve; last observation: ` +
376
+ `managedPid=${fmtPid(poll.value.managedPid)}, servingPid=${fmtPid(poll.value.servingPid)}, ` +
377
+ `directPidAlive=${poll.value.directPidAlive})`,
378
+ },
379
+ timedOut: true,
380
+ waitedMs: poll.waitedMs,
381
+ observations: poll.observations,
382
+ };
383
+ }
384
+ return { evidence: poll.value, proof, timedOut: poll.timedOut, waitedMs: poll.waitedMs, observations: poll.observations };
385
+ }
386
+ /**
387
+ * Wait for the port to be provably free, then apply `decideAdoptStop` UNCHANGED
388
+ * (flair#1827). Polls the post-stop health until `refused` (ECONNREFUSED) or the
389
+ * deadline; on timeout the failure keeps the existing refusal wording and adds
390
+ * how long it waited and the last health observed.
391
+ */
392
+ export async function decideAdoptStopWithWait(state, opts) {
393
+ // flair#1827 review: a STATE refusal (DISAGREEMENT / UNKNOWN) does not depend on
394
+ // the port probe, and the caller sends no SIGTERM for it — so decide it BEFORE
395
+ // polling, with ONE health observation. Otherwise the poll could wait the full
396
+ // deadline on a process that is still serving and append a misleading
397
+ // "waited … for the port to free" suffix. decideAdoptStop with a `refused`
398
+ // probe returns "proceed" for RUNNING/WEDGED/NOT_RUNNING (so those still poll)
399
+ // and the refusal for the state cases.
400
+ const stateDecision = decideAdoptStop(state, { kind: "refused" });
401
+ if (stateDecision !== "proceed") {
402
+ const now = opts.now ?? (() => Date.now());
403
+ const start = now();
404
+ const health = await opts.observe();
405
+ return { health, decision: stateDecision, timedOut: false, waitedMs: now() - start, observations: 1 };
406
+ }
407
+ const poll = await pollUntil({
408
+ observe: opts.observe,
409
+ until: (h) => h.kind === "refused",
410
+ deadlineMs: opts.deadlineMs,
411
+ intervalMs: opts.intervalMs,
412
+ now: opts.now,
413
+ sleep: opts.sleep,
414
+ });
415
+ const decision = decideAdoptStop(state, poll.value);
416
+ if (decision !== "proceed" && poll.timedOut) {
417
+ return {
418
+ health: poll.value,
419
+ decision: {
420
+ ...decision,
421
+ detail: `${decision.detail} (waited ${poll.waitedMs}ms for the port to free; last health probe: ${poll.value.kind})`,
422
+ },
423
+ timedOut: true,
424
+ waitedMs: poll.waitedMs,
425
+ observations: poll.observations,
426
+ };
427
+ }
428
+ return { health: poll.value, decision, timedOut: poll.timedOut, waitedMs: poll.waitedMs, observations: poll.observations };
429
+ }
@@ -141,10 +141,10 @@
141
141
  */
142
142
  import { probeSecretsCapability, pushSecrets, PROCESS_ENV_TIER } from "./secrets-push.js";
143
143
  import { existsSync, mkdirSync, writeFileSync, chmodSync, readFileSync } from "node:fs";
144
- import { homedir } from "node:os";
145
144
  import { join, dirname } from "node:path";
146
145
  import { generateKeyPairSync, randomBytes } from "node:crypto";
147
146
  import yaml from "js-yaml";
147
+ import { resolveHome } from "./home.js";
148
148
  // ─── CIMD constants ──────────────────────────────────────────────────────────
149
149
  /** Default `clientIdMetadataDocuments.allowedHosts` allowlist — see the
150
150
  * module header's "claude.ai CIMD/redirect-URI allowlist hosts" note for
@@ -262,7 +262,7 @@ export function generateRsaSigningKeyPair() {
262
262
  return { publicKey, privateKey };
263
263
  }
264
264
  export function defaultSigningKeyFilePath() {
265
- return join(homedir(), ".flair", "mcp-signing-key.pem");
265
+ return join(resolveHome(), ".flair", "mcp-signing-key.pem");
266
266
  }
267
267
  /** Write the RS256 private key PEM to a 0600 file (idempotent — reuses an
268
268
  * existing file rather than silently rotating the signing key). */
@@ -377,7 +377,7 @@ export const MCP_ENABLED_ENV_REFERENCE = "${FLAIR_MCP_OAUTH}";
377
377
  export function updateLocalConfigMcpEnabled(enabled, explicitPath) {
378
378
  const candidates = explicitPath
379
379
  ? [explicitPath]
380
- : ["config.yaml", join(homedir(), ".flair", "config.yaml")];
380
+ : ["config.yaml", join(resolveHome(), ".flair", "config.yaml")];
381
381
  let configPath = null;
382
382
  for (const p of candidates) {
383
383
  if (existsSync(p)) {
@@ -481,7 +481,7 @@ export function defaultSecretsStagingPath(issuer) {
481
481
  /* fall through to the generic name */
482
482
  }
483
483
  const safe = host.replace(/[^a-zA-Z0-9.-]/g, "_");
484
- return join(homedir(), ".flair", `mcp-enable-secrets-${safe}.env`);
484
+ return join(resolveHome(), ".flair", `mcp-enable-secrets-${safe}.env`);
485
485
  }
486
486
  /** Write the secrets bundle to a 0600 staging file, `KEY=VALUE` per line.
487
487
  * This file legitimately carries secret material (like `grant`'s 0600 key