@tpsdev-ai/flair 0.55.0 → 0.55.2

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.
@@ -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}` };
@@ -1,17 +1,36 @@
1
1
  /**
2
- * embed-gpu-doctor.ts — the flair doctor line for a failed Metal offload
3
- * (flair#1437 PLAN ACCEPTED condition 1).
2
+ * embed-gpu-doctor.ts — the flair doctor line for an unconfirmed Metal offload
3
+ * (flair#1437 PLAN ACCEPTED condition 1; severity split added by flair#1761).
4
4
  *
5
5
  * /Health already carries `embedding.fallback` when offload was requested
6
- * and Metal did not engage. Operators read `flair doctor`, not Health.
7
- * This is the single decision: given the public Health embedding field,
8
- * what (if anything) doctor prints. Harper-free; unit-tested.
6
+ * and the GPU log heuristic did not confirm Metal. Operators read
7
+ * `flair doctor`, not Health. This is the single decision: given the public
8
+ * Health embedding field, what (if anything) doctor prints, and whether it
9
+ * weighs on doctor's exit code.
10
+ *
11
+ * flair#1761: the finding is NOT one severity. The fallback sentence is a log
12
+ * heuristic, not an observation (it can err in both directions), and since
13
+ * 0.55.0 the derived Metal default requests offload on every darwin-arm64
14
+ * host without the operator asking. So the severity is read off `source`:
15
+ *
16
+ * source === "detected" → the default chose for the operator; advisory
17
+ * WARNING, does not count as an issue.
18
+ * source === "env" → the operator explicitly set
19
+ * FLAIR_EMBED_GPU_LAYERS; blocking ERROR.
20
+ * missing / unrecognized → FAIL CLOSED: blocking ERROR, exactly as before.
21
+ * An unknown state is never softened to advisory.
9
22
  */
10
23
  export const EMBED_GPU_DOCTOR_MARKER = "requested GPU offload; Metal did not engage";
24
+ /** Advisory wording (flair#1761). We cannot observe engagement, only that it
25
+ * was NOT confirmed — the old "did not engage" over-claimed. */
26
+ export const EMBED_GPU_DETECTED_MESSAGE = "Automatic Metal acceleration was requested, but engagement could not be verified.";
11
27
  /**
12
- * Fail-loud doctor finding, or null when there is nothing to say.
28
+ * Doctor finding, or null when there is nothing to say.
13
29
  * Only the Health `fallback` sentence is a finding — a stated CPU default
14
- * or a confirmed Metal run is not an issue.
30
+ * or a confirmed Metal run is not an issue. The severity depends on
31
+ * `source` (flair#1761): an operator-requested offload that was not
32
+ * confirmed still fails loud, but the derived Metal default is advisory and
33
+ * an unrecognized source fails closed.
15
34
  */
16
35
  export function describeEmbedGpuDoctorFinding(embedding) {
17
36
  if (embedding == null || typeof embedding !== "object" || Array.isArray(embedding)) {
@@ -21,6 +40,20 @@ export function describeEmbedGpuDoctorFinding(embedding) {
21
40
  if (typeof fallback !== "string" || !fallback.includes(EMBED_GPU_DOCTOR_MARKER)) {
22
41
  return null;
23
42
  }
43
+ const source = embedding.source;
44
+ if (source === "detected") {
45
+ // The Metal default requested offload for the operator; nothing was
46
+ // chosen. Working embeddings on CPU is a standing, benign condition —
47
+ // keep it visible as a persistent warning, never a blocking finding.
48
+ return {
49
+ isIssue: false,
50
+ icon: "warn",
51
+ message: EMBED_GPU_DETECTED_MESSAGE,
52
+ fixHint: "Pin CPU with FLAIR_EMBED_GPU_LAYERS=0.",
53
+ };
54
+ }
55
+ // A source the operator set ("env"), or one we do not recognize at all
56
+ // (missing/unknown) — fail closed and keep the existing fail-loud finding.
24
57
  return {
25
58
  isIssue: true,
26
59
  icon: "error",
@@ -318,3 +318,106 @@ export function decideAdoptStop(state, postStopHealth) {
318
318
  }
319
319
  return "proceed";
320
320
  }
321
+ /**
322
+ * Poll `observe` until `until(value)` holds or `deadlineMs` elapses (measured on
323
+ * the injected `now`). No global timers live in the logic — `sleep` is injected
324
+ * too — so the whole loop is deterministic and unit-testable. Returns the LAST
325
+ * observation plus whether it timed out.
326
+ */
327
+ export async function pollUntil(opts) {
328
+ const now = opts.now ?? (() => Date.now());
329
+ const sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
330
+ const intervalMs = opts.intervalMs ?? 250;
331
+ const start = now();
332
+ let value = await opts.observe();
333
+ let observations = 1;
334
+ while (!opts.until(value)) {
335
+ if (now() - start >= opts.deadlineMs) {
336
+ return { value, timedOut: true, waitedMs: now() - start, observations };
337
+ }
338
+ await sleep(intervalMs);
339
+ value = await opts.observe();
340
+ observations++;
341
+ }
342
+ return { value, timedOut: false, waitedMs: now() - start, observations };
343
+ }
344
+ function fmtPid(pid) {
345
+ return pid === null ? "null" : String(pid);
346
+ }
347
+ /**
348
+ * Wait for the adopted job to actually serve, then prove it with
349
+ * `verifyAdoptServing` UNCHANGED (flair#1827). Polls `{managedPid, servingPid,
350
+ * directPidAlive}` until `servingPid !== null && !directPidAlive` (the launchd
351
+ * job has written hdb.pid / bound the port AND the pre-adopt process is gone) or
352
+ * the deadline. On timeout the failure detail names the wait and the last
353
+ * observation. All three identity rules of the proof are preserved.
354
+ */
355
+ export async function verifyAdoptServingWithWait(opts) {
356
+ const poll = await pollUntil({
357
+ observe: opts.observe,
358
+ until: (e) => e.servingPid !== null && !e.directPidAlive,
359
+ deadlineMs: opts.deadlineMs,
360
+ intervalMs: opts.intervalMs,
361
+ now: opts.now,
362
+ sleep: opts.sleep,
363
+ });
364
+ const proof = verifyAdoptServing(poll.value);
365
+ if (proof && poll.timedOut) {
366
+ return {
367
+ evidence: poll.value,
368
+ proof: {
369
+ detail: `${proof.detail} (waited ${poll.waitedMs}ms for the launchd job to serve; last observation: ` +
370
+ `managedPid=${fmtPid(poll.value.managedPid)}, servingPid=${fmtPid(poll.value.servingPid)}, ` +
371
+ `directPidAlive=${poll.value.directPidAlive})`,
372
+ },
373
+ timedOut: true,
374
+ waitedMs: poll.waitedMs,
375
+ observations: poll.observations,
376
+ };
377
+ }
378
+ return { evidence: poll.value, proof, timedOut: poll.timedOut, waitedMs: poll.waitedMs, observations: poll.observations };
379
+ }
380
+ /**
381
+ * Wait for the port to be provably free, then apply `decideAdoptStop` UNCHANGED
382
+ * (flair#1827). Polls the post-stop health until `refused` (ECONNREFUSED) or the
383
+ * deadline; on timeout the failure keeps the existing refusal wording and adds
384
+ * how long it waited and the last health observed.
385
+ */
386
+ export async function decideAdoptStopWithWait(state, opts) {
387
+ // flair#1827 review: a STATE refusal (DISAGREEMENT / UNKNOWN) does not depend on
388
+ // the port probe, and the caller sends no SIGTERM for it — so decide it BEFORE
389
+ // polling, with ONE health observation. Otherwise the poll could wait the full
390
+ // deadline on a process that is still serving and append a misleading
391
+ // "waited … for the port to free" suffix. decideAdoptStop with a `refused`
392
+ // probe returns "proceed" for RUNNING/WEDGED/NOT_RUNNING (so those still poll)
393
+ // and the refusal for the state cases.
394
+ const stateDecision = decideAdoptStop(state, { kind: "refused" });
395
+ if (stateDecision !== "proceed") {
396
+ const now = opts.now ?? (() => Date.now());
397
+ const start = now();
398
+ const health = await opts.observe();
399
+ return { health, decision: stateDecision, timedOut: false, waitedMs: now() - start, observations: 1 };
400
+ }
401
+ const poll = await pollUntil({
402
+ observe: opts.observe,
403
+ until: (h) => h.kind === "refused",
404
+ deadlineMs: opts.deadlineMs,
405
+ intervalMs: opts.intervalMs,
406
+ now: opts.now,
407
+ sleep: opts.sleep,
408
+ });
409
+ const decision = decideAdoptStop(state, poll.value);
410
+ if (decision !== "proceed" && poll.timedOut) {
411
+ return {
412
+ health: poll.value,
413
+ decision: {
414
+ ...decision,
415
+ detail: `${decision.detail} (waited ${poll.waitedMs}ms for the port to free; last health probe: ${poll.value.kind})`,
416
+ },
417
+ timedOut: true,
418
+ waitedMs: poll.waitedMs,
419
+ observations: poll.observations,
420
+ };
421
+ }
422
+ return { health: poll.value, decision, timedOut: poll.timedOut, waitedMs: poll.waitedMs, observations: poll.observations };
423
+ }