@tpsdev-ai/flair 0.55.1 → 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.
@@ -1,6 +1,6 @@
1
1
  {
2
- "version": "0.55.1",
3
- "commit": "e048d3b1bb538c8c8e5c57df2802f416b3bed104",
4
- "builtAt": "2026-09-21T06:28:01.245Z",
2
+ "version": "0.55.2",
3
+ "commit": "317166c7daa24f519a43dce78571acdf36532ced",
4
+ "builtAt": "2026-09-23T19:19:42.752Z",
5
5
  "builder": "tsc"
6
6
  }
package/dist/cli.js CHANGED
@@ -18,7 +18,7 @@ import { readInstalledHarperVersion, writeEngineVersionStamp, checkEngineVersion
18
18
  import { checkServerHandshake, formatHandshakeNudge, invalidateHandshakeCache } from "./version-handshake.js";
19
19
  import { fleetSweepShouldAbort, } from "./fleet-verify.js";
20
20
  import { detectClients } from "./install/clients.js";
21
- import { flairCliVersion, mcpServerSpec, FLAIR_MCP_PACKAGE } from "./lib/mcp-spec.js";
21
+ import { flairCliVersion, mcpServerSpec } from "./lib/mcp-spec.js";
22
22
  import { harperPortValue } from "./lib/harper-port-value.js";
23
23
  import { httpBind, httpCorsAccessList, preserveHttpPortValue, preserveSecurePort, qualifySecureBindValue, DEFAULT_HTTP_BIND_HOST, } from "./lib/http-bind.js";
24
24
  import { isNodeKeyId, partitionKeyIds, } from "./doctor-client.js";
@@ -28,10 +28,11 @@ import { resolveSigningIdentity, emitSigningIdentityDebug, } from "./lib/signing
28
28
  import { entityFormatHint, parseEntitiesCsv } from "./lib/entity-vocab-cli.js";
29
29
  import { escapeXml, unescapeXml } from "./lib/xml-escape.js";
30
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";
31
+ import { classifyPlist, planLaunchdRepair, mapRepairThrow, decideAdoptStopWithWait, verifyAdoptServingWithWait, } from "./lib/launchd-repair.js";
32
32
  import { stabilizeMqttNetworkKeyOrder } from "./lib/stabilize-mqtt-network.js";
33
33
  import { detectOpsApiAllInterfacesBind } from "./lib/ops-api-bind.js";
34
34
  import { applyUpgradeHookConsent, runDoctorChecks, } from "./lib/doctor-run.js";
35
+ import { classifyInstalledVersion, shouldPrintUpgradeLine, upgradeStatusSuffix } from "./lib/upgrade-status.js";
35
36
  import { classifyDaemonState, verifyIdentity, parseSidecarJson, classifyHealthProbe, classifyPortOwner, classifyInstanceMatch, shouldAdoptMissingSidecar, parseNullSeparatedEnviron, extractRootPath, } from "./lib/daemon-liveness.js";
36
37
  import { readProcessStartTimeMs } from "./lib/process-start-time.js";
37
38
  import { bindCli as bindFederationCli, register as registerFederation, signRequestBody, parseTokenFromFile, runFederationSyncOnce, persistLocalPeerLastSyncAt, runFederationWatch, federationStatusUrlSetting, describeFederationStatusFetchFailed, isFederationStatusConnectFailure, rewriteFederationStatusFetchFailed, isFederationStatusAuthFailure, isFederationStatusAuthRemedy, } from "./commands/federation.js";
@@ -2350,6 +2351,140 @@ function opsAuth401Hint(adminUser) {
2350
2351
  * or hardened instance. Hardening the ops-API loopback posture is tracked in
2351
2352
  * flair#654.
2352
2353
  */
2354
+ // ─── flair#1790: the ops-API seed names its failure and retries once ──────────
2355
+ //
2356
+ // Both seed helpers below insert through the operations API with a single bare
2357
+ // `fetch` under a 10 s client timeout. On a timeout that surfaced ONLY as an
2358
+ // undici `DOMException [TimeoutError]` stack — no operation, no target, no
2359
+ // timeout value — so a post-restart `flair init` that timed out produced an
2360
+ // unactionable failure and no daemon evidence.
2361
+ //
2362
+ // The wrap here names the failure and retries the insert ONCE, on the CLIENT
2363
+ // timeout only. The retry is safe because the insert is idempotent: a duplicate
2364
+ // answers 409 (or a "duplicate"/"already exists" body) and is treated as
2365
+ // success below, so a retried insert cannot double-apply. What is NOT retried:
2366
+ // an auth failure (401 keeps its existing hint) or any other HTTP or network
2367
+ // error — those are answers, not stalls.
2368
+ //
2369
+ // This is diagnosis + ergonomics, NOT a claim about WHY a seed timed out; the
2370
+ // mechanism is unknown (flair#1790).
2371
+ const OPS_AGENT_SEED_TIMEOUT_MS = 10_000;
2372
+ const OPS_AGENT_SEED_ATTEMPTS = 2;
2373
+ /**
2374
+ * A target URL safe to print: userinfo and query/fragment stripped. The seed
2375
+ * target is operator-supplied (`--target` / `--ops-target`), so it may carry
2376
+ * credentials or query values that must never reach init output or a log line.
2377
+ */
2378
+ function sanitizeOpsTargetUrl(raw) {
2379
+ try {
2380
+ const u = new URL(raw);
2381
+ u.username = "";
2382
+ u.password = "";
2383
+ u.search = "";
2384
+ u.hash = "";
2385
+ return u.toString();
2386
+ }
2387
+ catch {
2388
+ return raw.replace(/\/\/[^/@]*@/, "//").split(/[?#]/)[0];
2389
+ }
2390
+ }
2391
+ /**
2392
+ * True only for the abort our OWN AbortSignal.timeout raises (never a server
2393
+ * answer, never a foreign abort). Checked by name AND by the attempt's own
2394
+ * signal being aborted (flair#1790 review S1), so a stray TimeoutError from some
2395
+ * other AbortSignal is not retried as if it were ours.
2396
+ */
2397
+ function isOwnedSeedTimeout(err, signal) {
2398
+ const name = err?.name;
2399
+ if (name !== "TimeoutError" && name !== "AbortError")
2400
+ return false;
2401
+ return signal ? signal.aborted : true;
2402
+ }
2403
+ /**
2404
+ * The concise both-attempts-timed-out CLI error. `flairFriendly` makes runCli
2405
+ * print just this sentence (no undici/Node stack); the cause stays attached for
2406
+ * `--verbose`/diagnostics and is never printed by the default handler.
2407
+ */
2408
+ function opsSeedBothAttemptsTimedOut(req, sanitizedUrl, cause) {
2409
+ const message = `Flair could not seed ${req.noun} '${req.id}': Operations API insert into ${req.tableName} at ` +
2410
+ `${sanitizedUrl} timed out on both attempts (${OPS_AGENT_SEED_TIMEOUT_MS} ms per attempt). ` +
2411
+ `Inspect the target daemon's logs, then rerun the same init command.\n` +
2412
+ `A timed-out insert may still complete; retrying the same ${req.noun} ID is supported.`;
2413
+ const err = new Error(message, { cause });
2414
+ err.flairFriendly = true;
2415
+ return err;
2416
+ }
2417
+ /**
2418
+ * POST one ops-API insert, retrying once on the client timeout. The response
2419
+ * body is read under the SAME attempt's signal, so each attempt's fresh
2420
+ * deadline covers the body read too. Returns normally on success or on the
2421
+ * idempotent duplicate path; throws a named error otherwise.
2422
+ */
2423
+ async function opsSeedInsertWithRetry(req) {
2424
+ const sanitizedUrl = sanitizeOpsTargetUrl(req.url);
2425
+ const headers = {
2426
+ "Content-Type": "application/json",
2427
+ ...(req.auth ? { Authorization: `Basic ${req.auth}` } : {}),
2428
+ };
2429
+ const overallStart = Date.now();
2430
+ for (let attempt = 1; attempt <= OPS_AGENT_SEED_ATTEMPTS; attempt++) {
2431
+ const attemptStart = Date.now();
2432
+ // A FRESH deadline per attempt; the response-body read runs under the SAME
2433
+ // signal, so it too is bounded by this attempt's timeout.
2434
+ const signal = AbortSignal.timeout(OPS_AGENT_SEED_TIMEOUT_MS);
2435
+ try {
2436
+ const res = await fetch(req.url, {
2437
+ method: "POST",
2438
+ headers,
2439
+ body: JSON.stringify(req.body),
2440
+ signal,
2441
+ });
2442
+ let text;
2443
+ try {
2444
+ text = await res.text();
2445
+ }
2446
+ catch (e) {
2447
+ // flair#1790 follow-up (A): an owned BODY-READ timeout is retryable ONLY
2448
+ // for an OK response — a 2xx whose body stalled is OUR stall, so retry
2449
+ // it. For a NON-OK response the STATUS is the answer: use empty text and
2450
+ // fall through to the status handling (401 → auth error first, then
2451
+ // 409/marker → duplicate) instead of retrying away the real error. A 401
2452
+ // whose body read stalls must stay the auth error, not become a
2453
+ // bogus "timed out on both attempts".
2454
+ if (res.ok && isOwnedSeedTimeout(e, signal))
2455
+ throw e;
2456
+ text = "";
2457
+ }
2458
+ // flair#1790 review C2: 401 FIRST. An auth failure must never be masked by
2459
+ // a body that happens to carry a "duplicate"/"already exists" marker.
2460
+ if (res.status === 401)
2461
+ throw new Error(req.auth401Message(text));
2462
+ // THEN the idempotent duplicate path: an unconditional 409, then the
2463
+ // marker match for the remaining non-OK shapes.
2464
+ const duplicate = res.status === 409 || text.includes("duplicate") || text.includes("already exists");
2465
+ if (!res.ok && !duplicate)
2466
+ throw new Error(req.httpErrorMessage(res.status, text));
2467
+ // Success, or the idempotent duplicate path.
2468
+ const outcome = res.ok ? "inserted" : "already exists";
2469
+ if (attempt > 1) {
2470
+ console.log(`${req.kind} seed attempt ${attempt} completed in ${Date.now() - attemptStart} ms (${outcome}); ` +
2471
+ `total ${Date.now() - overallStart} ms.`);
2472
+ }
2473
+ return;
2474
+ }
2475
+ catch (err) {
2476
+ // Auth / HTTP / other network errors are answers, not stalls: never retried.
2477
+ if (!isOwnedSeedTimeout(err, signal))
2478
+ throw err;
2479
+ if (attempt < OPS_AGENT_SEED_ATTEMPTS) {
2480
+ console.warn(`${req.kind} seed attempt ${attempt} timed out after ${OPS_AGENT_SEED_TIMEOUT_MS} ms; retrying once. ` +
2481
+ `Target: ${sanitizedUrl} (${req.noun} '${req.id}').`);
2482
+ continue;
2483
+ }
2484
+ throw opsSeedBothAttemptsTimedOut(req, sanitizedUrl, err);
2485
+ }
2486
+ }
2487
+ }
2353
2488
  export async function seedAgentViaOpsApi(opsPortOrUrl, agentId, pubKeyB64url, adminUser, adminPass) {
2354
2489
  const url = typeof opsPortOrUrl === "number"
2355
2490
  ? `http://127.0.0.1:${opsPortOrUrl}/`
@@ -2381,21 +2516,17 @@ export async function seedAgentViaOpsApi(opsPortOrUrl, agentId, pubKeyB64url, ad
2381
2516
  updatedAt: now,
2382
2517
  }],
2383
2518
  };
2384
- const res = await fetch(url, {
2385
- method: "POST",
2386
- headers: { "Content-Type": "application/json", ...(auth ? { Authorization: `Basic ${auth}` } : {}) },
2387
- body: JSON.stringify(body),
2388
- signal: AbortSignal.timeout(10_000),
2519
+ await opsSeedInsertWithRetry({
2520
+ url,
2521
+ auth,
2522
+ body,
2523
+ kind: "Agent",
2524
+ noun: "agent",
2525
+ tableName: "flair.Agent",
2526
+ id: agentId,
2527
+ auth401Message: (text) => `Operations API insert failed (401): ${text}${opsAuth401Hint(auth === undefined ? undefined : adminUser)}`,
2528
+ httpErrorMessage: (status, text) => `Operations API insert failed (${status}): ${text}`,
2389
2529
  });
2390
- if (!res.ok) {
2391
- const text = await res.text().catch(() => "");
2392
- if (res.status === 409 || text.includes("duplicate") || text.includes("already exists"))
2393
- return;
2394
- if (res.status === 401) {
2395
- throw new Error(`Operations API insert failed (401): ${text}${opsAuth401Hint(auth === undefined ? undefined : adminUser)}`);
2396
- }
2397
- throw new Error(`Operations API insert failed (${res.status}): ${text}`);
2398
- }
2399
2530
  }
2400
2531
  // NOTE: agent records are seeded exclusively via the Harper operations API
2401
2532
  // (seedAgentViaOpsApi above). A former seedAgentViaRestApi() helper POSTed the
@@ -2435,21 +2566,17 @@ export async function seedFederationInstanceViaOpsApi(opsPortOrUrl, instanceId,
2435
2566
  updatedAt: now,
2436
2567
  }],
2437
2568
  };
2438
- const res = await fetch(url, {
2439
- method: "POST",
2440
- headers: { "Content-Type": "application/json", ...(auth ? { Authorization: `Basic ${auth}` } : {}) },
2441
- body: JSON.stringify(body),
2442
- signal: AbortSignal.timeout(10_000),
2569
+ await opsSeedInsertWithRetry({
2570
+ url,
2571
+ auth,
2572
+ body,
2573
+ kind: "Federation Instance",
2574
+ noun: "federation instance",
2575
+ tableName: "flair.Instance",
2576
+ id: instanceId,
2577
+ auth401Message: (text) => `Federation Instance insert via ops API failed (401): ${text}${opsAuth401Hint(auth === undefined ? undefined : adminUser)}`,
2578
+ httpErrorMessage: (status, text) => `Federation Instance insert via ops API failed (${status}): ${text}`,
2443
2579
  });
2444
- if (!res.ok) {
2445
- const text = await res.text().catch(() => "");
2446
- if (res.status === 409 || text.includes("duplicate") || text.includes("already exists"))
2447
- return;
2448
- if (res.status === 401) {
2449
- throw new Error(`Federation Instance insert via ops API failed (401): ${text}${opsAuth401Hint(auth === undefined ? undefined : adminUser)}`);
2450
- }
2451
- throw new Error(`Federation Instance insert via ops API failed (${res.status}): ${text}`);
2452
- }
2453
2580
  }
2454
2581
  // ─── Provision Flair on Harper Fabric ──────────────────────────────────────
2455
2582
  //
@@ -2991,43 +3118,13 @@ export function probeOpenclawPluginVersion(extensionName) {
2991
3118
  }
2992
3119
  }
2993
3120
  /**
2994
- * Whether a package's status line should be printed in the default `flair
2995
- * upgrade` listing. Suppresses optional-because-openclaw-is-absent lines
2996
- * — pure noise on machines without openclaw — unless `--all`
2997
- * (showAll) is set. All other statuses always print.
3121
+ * Per-package status for the `flair upgrade` listing — the state set, the
3122
+ * direction-aware classifier and the renderers live ONCE in
3123
+ * src/lib/upgrade-status.ts and are re-exported here so existing importers keep
3124
+ * working (flair#1778). src/commands/upgrade.ts cannot import this file, so the
3125
+ * shared definition has to live outside both.
2998
3126
  */
2999
- export function shouldPrintUpgradeLine(status, showAll) {
3000
- if (status === "optional" && !showAll)
3001
- return false;
3002
- return true;
3003
- }
3004
- /**
3005
- * Returns the human-readable suffix for a package status line in
3006
- * `flair upgrade` / `flair upgrade --check` output.
3007
- *
3008
- * flair-mcp is zero-install via npx — its suffix must never suggest a
3009
- * global install (flair#1168).
3010
- */
3011
- export function upgradeStatusSuffix(name, status) {
3012
- if (status === "current")
3013
- return " (current)";
3014
- if (status === "missing") {
3015
- return name === FLAIR_MCP_PACKAGE
3016
- ? " (zero-install via npx — run: flair doctor --fix)"
3017
- : " (run: npm install -g)";
3018
- }
3019
- if (status === "optional")
3020
- return " (install via: openclaw plugins install @tpsdev-ai/openclaw-flair)";
3021
- // flair-mcp is refreshed by re-pinning its wiring, never `npm install -g` —
3022
- // a global bin does nothing for an `npx -y -p @tpsdev-ai/flair-mcp`
3023
- // invocation (flair#1208). The re-pin is `flair upgrade`'s own job (the
3024
- // #1135/#1167 pin refresh) — never advise `doctor --fix` for it
3025
- // (flair#1324).
3026
- if (status === "outdated" && name === FLAIR_MCP_PACKAGE) {
3027
- return " (npx-wired — flair upgrade refreshes the pin)";
3028
- }
3029
- return "";
3030
- }
3127
+ export { shouldPrintUpgradeLine, upgradeStatusSuffix };
3031
3128
  /**
3032
3129
  * Resolve the `flair upgrade` finding for flair-mcp from its ACTUAL wiring,
3033
3130
  * not a global-install probe (flair#1208).
@@ -3042,7 +3139,8 @@ export function upgradeStatusSuffix(name, status) {
3042
3139
  * 2. Not wired anywhere — genuinely missing; the remedy (upgradeStatusSuffix)
3043
3140
  * is `flair doctor --fix`, never `npm install -g`.
3044
3141
  * 3. Wired with a concrete pin — that pin IS the installed version
3045
- * (current when it equals latest, else outdated → re-pin via doctor).
3142
+ * (current / ahead / outdated by semver direction; outdated → re-pin via
3143
+ * doctor, ahead never re-pins down — flair#1778).
3046
3144
  * 4. Wired but unpinned (a bare npx spec / a pre-#1143 SessionStart hook) —
3047
3145
  * `npx -y` re-resolves latest every session, so the effective version IS
3048
3146
  * latest → current.
@@ -3050,7 +3148,7 @@ export function upgradeStatusSuffix(name, status) {
3050
3148
  export function resolveFlairMcpFinding(globalProbe, latest, wiring) {
3051
3149
  // 1. Legacy global install.
3052
3150
  if (globalProbe !== null) {
3053
- return { installed: globalProbe, status: globalProbe === latest ? "current" : "outdated" };
3151
+ return { installed: globalProbe, status: classifyInstalledVersion(globalProbe, latest) };
3054
3152
  }
3055
3153
  // 2. Not wired anywhere.
3056
3154
  if (!wiring.wired) {
@@ -3060,7 +3158,7 @@ export function resolveFlairMcpFinding(globalProbe, latest, wiring) {
3060
3158
  if (wiring.pinnedVersion) {
3061
3159
  return {
3062
3160
  installed: wiring.pinnedVersion,
3063
- status: wiring.pinnedVersion === latest ? "current" : "outdated",
3161
+ status: classifyInstalledVersion(wiring.pinnedVersion, latest),
3064
3162
  };
3065
3163
  }
3066
3164
  // 4. Wired but unpinned — npx resolves latest on every session.
@@ -3688,7 +3786,6 @@ bindUpgradeCli({
3688
3786
  probeLibVersion,
3689
3787
  probeOpenclawPluginVersion,
3690
3788
  relativeTime,
3691
- resolveAgentIdOrEnv,
3692
3789
  resolveFabricCredentials,
3693
3790
  resolveFlairMcpFinding,
3694
3791
  resolveHttpPort,
@@ -4763,16 +4860,21 @@ async function repairLaunchdManagement(dataDir, port) {
4763
4860
  // launchd's reported pid for this label.
4764
4861
  if (plan.kind === "adopt") {
4765
4862
  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),
4863
+ // flair#1827: poll — the launchd-started Harper may not have written
4864
+ // hdb.pid or bound the port yet. Wait for it to serve (and for the
4865
+ // pre-adopt process to be gone), THEN prove identity with
4866
+ // verifyAdoptServing UNCHANGED on the final observation.
4867
+ const waited = await verifyAdoptServingWithWait({
4868
+ observe: () => ({
4869
+ directPid,
4870
+ managedPid: readLaunchctlJobState(label, realLaunchctlLister).pid,
4871
+ servingPid: resolveInstanceServingPid(dataDir, port),
4872
+ directPidAlive: directPid !== null && isProcessAlive(directPid),
4873
+ }),
4874
+ deadlineMs: STARTUP_TIMEOUT_MS,
4773
4875
  });
4774
- if (proof) {
4775
- return { kind: "failed", detail: proof.detail, remedy: ["flair stop", "flair doctor --fix"] };
4876
+ if (waited.proof) {
4877
+ return { kind: "failed", detail: waited.proof.detail, remedy: ["flair stop", "flair doctor --fix"] };
4776
4878
  }
4777
4879
  }
4778
4880
  // flair#1701: the launchd bounce (adopt and regenerate) is a first
@@ -4821,10 +4923,16 @@ async function stopDirectProcessForAdopt(port, dataDir) {
4821
4923
  }
4822
4924
  catch { /* best-effort — the port check below surfaces the real problem */ }
4823
4925
  }
4824
- const postStopHealth = await probeHealth(port);
4825
- const decision = decideAdoptStop(state, postStopHealth);
4826
- if (decision !== "proceed")
4827
- return decision;
4926
+ // flair#1827: poll the post-stop health until the port is provably free — a
4927
+ // single observation that caught the listener mid-release flaked with "port
4928
+ // not confirmed free". decideAdoptStop is UNCHANGED; it decides on the final
4929
+ // observation, and a timeout names the wait and the last probe.
4930
+ const decision = await decideAdoptStopWithWait(state, {
4931
+ observe: () => probeHealth(port),
4932
+ deadlineMs: STARTUP_TIMEOUT_MS,
4933
+ });
4934
+ if (decision.decision !== "proceed")
4935
+ return decision.decision;
4828
4936
  // Belt-and-suspenders: lsof confirms no TCP listener remains before the
4829
4937
  // caller loads the plist. probeHealth "refused" (ECONNREFUSED) already means
4830
4938
  // nothing is listening, but a port that is BOUND yet refuses connections
@@ -1,19 +1,19 @@
1
1
  import { COMPONENT_ENV_FILENAME, PUBLIC_URL_KEY, describePublicUrlFinding, readEnvValue } from "../component-env.js";
2
2
  import { checkClaudeMdBootstrap, checkContinuityCaptureHooks, describeAgentGateFinding, effectiveFlairUrl, embeddingsSkipRemedy, fixClaudeMdBootstrap, fixCommandAgentHint, fixContinuityCaptureHooks, fixSessionStartHook, inspectSessionStartHook, partitionKeyIds, planAgentIterations, readClientMcpBlock, resolveFixAgentId, resolveWireFlairUrl, upgradeSessionStartHookCommand } from "../doctor-client.js";
3
3
  import { markStale, sortOldestVersionFirst } from "../fleet-presence.js";
4
- import { hookSettingsPath, repinSessionStartHook, resolveHookAgentId } from "../hook-install.js";
5
- import { detectClients, wireAntigravity, wireClaudeCode, wireCodex, wireCursor, wireGemini } from "../install/clients.js";
4
+ import { hookSettingsPath, resolveHookAgentId } from "../hook-install.js";
5
+ import { ALL_CLIENTS, decideCodexPinOnly, decideJsonPinOnly, detectClients, wireAntigravity, wireClaudeCode, wireCodex, wireCursor, wireGemini } from "../install/clients.js";
6
6
  import { checkGlobalBinOnPath, resolveNpmGlobalPrefix } from "../install/global-bin-path.js";
7
7
  import { buildEd25519Auth, defaultAdminPassPath, defaultKeysDir, resolveAdminUser, resolveKeyPath, resolveLocalAdminPass } from "../lib/auth-resolve.js";
8
8
  import { flairConfigYamlCandidates, readPortFromYamlFile, resolveFlairConfigYaml } from "../lib/doctor-config-path.js";
9
9
  import { collectFederationEnv, describeFederationDriverFinding, federationPeersConfigured, loadYamlDoc } from "../lib/doctor-federation-driver.js";
10
10
  import { plistCarriesInlineAdminPassword } from "../lib/launchd-management.js";
11
- import { DOCTOR_CHECK_IDS, catalogIssueDelta, renderCatalogDoctorLines, runDoctorChecks } from "../lib/doctor-run.js";
11
+ import { DOCTOR_CHECK_IDS, catalogIssueDelta, mcpRepinIcon, renderCatalogDoctorLines, runDoctorChecks } from "../lib/doctor-run.js";
12
12
  import { describeEmbedGpuDoctorFinding } from "../lib/embed-gpu-doctor.js";
13
13
  import { adminPassDesyncFinding, detectPersistedAdminUser } from "../lib/init-admin-pass.js";
14
14
  import { opsApiBindFinding } from "../lib/ops-api-bind.js";
15
15
  import { flairCliVersion, unpinnedSpecWarning } from "../lib/mcp-spec.js";
16
- import { staleSessionStartHookPins } from "../lib/owned-pins.js";
16
+ import { mcpClientPinFindings, refreshOwnedPins, repinSessionStartHookGuarded, sessionStartHookPinFindings } from "../lib/owned-pins.js";
17
17
  import * as render from "../render.js";
18
18
  import { checkVersion, formatVersionNudge, probeInstanceVersion, FLAIR_PKG_NAME } from "../version-check.js";
19
19
  import { resolveRegistryNotice } from "../lib/npm-registry.js";
@@ -823,7 +823,17 @@ export function register(program) {
823
823
  agentFlag: typeof opts.agent === "string" ? opts.agent : undefined,
824
824
  };
825
825
  const catalogBefore = runDoctorChecks(doctorCtx, { catalogIds: doctorCatalogIds });
826
- if (detectedClients.length === 0) {
826
+ // flair#1834 PR-H: a hook file on disk IS the wiring — the same rule the
827
+ // hook arms below apply. A SessionStart hook wired in ~/.claude/settings.json
828
+ // (or ~/.codex/hooks.json) is a Flair client integration even when the MCP
829
+ // server is configured PROJECT-scoped (a project's .mcp.json) rather than in
830
+ // ~/.claude.json — and even when the harness binary is not on this shell's
831
+ // PATH. Without this the whole section was skipped outright ("No MCP client
832
+ // detected") and a HOLD on that wired hook was silently missed. Presence-only
833
+ // here (probe:false); the arms below run the bounded execution probe.
834
+ const anyWiredSessionStartHook = inspectSessionStartHook(homedir(), { settingsPath: hookSettingsPath(homedir(), "claude-code"), probe: false }).present ||
835
+ inspectSessionStartHook(homedir(), { settingsPath: hookSettingsPath(homedir(), "codex"), probe: false }).present;
836
+ if (detectedClients.length === 0 && !anyWiredSessionStartHook) {
827
837
  console.log(` ${render.icons.info} No MCP client detected — skipping client-integration checks`);
828
838
  }
829
839
  else {
@@ -959,6 +969,69 @@ export function register(program) {
959
969
  console.log(` ${render.icons.warn} ${finding?.message ?? `could not verify agent registration (${reg.detail})`}`);
960
970
  }
961
971
  }
972
+ // flair#1779: `doctor --fix` re-pins a BEHIND MCP-client block the same
973
+ // way it re-pins a behind SessionStart hook. It routes through the ONE
974
+ // guarded writer the upgrade refresh uses (refreshOwnedPins), restricted
975
+ // to the behind wired clients and preserving each block's OWN agent id
976
+ // and FLAIR_URL. ahead/unknown are HELD (already a pass/warn), so only
977
+ // `behind` is written; the catalog delta below counts the fix.
978
+ if (autoFix) {
979
+ const behindMcp = mcpClientPinFindings(homedir(), flairCliVersion())
980
+ .filter((f) => f.direction === "behind")
981
+ // flair#1834 A1: key off STRUCTURAL presence (entryExists), not
982
+ // `present` (= agent id set). A behind entry without an identity is
983
+ // still a pin we own and re-pin — the pin-only writer preserves
984
+ // whatever identity the entry carries.
985
+ .filter((f) => f.reading.entryExists);
986
+ if (behindMcp.length > 0) {
987
+ if (dryRun) {
988
+ // flair#1834 A2: derive each dry-run line from the SAME
989
+ // classification the real run uses, so there is never a "Would
990
+ // re-pin" for a target the real run would HOLD or skip.
991
+ for (const f of behindMcp) {
992
+ const id = f.reading.target.id;
993
+ const label = ALL_CLIENTS.find((c) => c.id === id)?.label ?? id;
994
+ let dec;
995
+ try {
996
+ const raw = readFileSync(f.reading.target.path, "utf-8");
997
+ dec = id === "codex" ? decideCodexPinOnly(raw, label) : decideJsonPinOnly(raw, label, f.reading.target.path);
998
+ }
999
+ catch (err) {
1000
+ console.log(` ${render.icons.warn} ${label}: could not read ${f.reading.target.path} (${err instanceof Error ? err.message : String(err)}) — would not re-pin`);
1001
+ continue;
1002
+ }
1003
+ if (dec.result.kind === "repinned") {
1004
+ // flair#1834 A2 round 2: `oldPin` is already the full pinned spec
1005
+ // (`@tpsdev-ai/flair-mcp@<ver>`); do NOT re-prefix the package.
1006
+ // Match the real run's format: `(<oldPin> -> <newPin>)`.
1007
+ console.log(` ${render.wrap(render.c.dim, "Would re-pin the MCP server block in")} ${f.reading.target.path} (${dec.result.oldPin} -> ${dec.result.newPin})`);
1008
+ }
1009
+ else if (dec.result.kind === "hold") {
1010
+ // Match the real run's HOLD format, which names the client so a
1011
+ // multi-client dry-run says which hold is whose.
1012
+ console.log(` ${render.icons.warn} HOLD ${label}: ${dec.result.line ?? "refusing to rewrite this entry"}`);
1013
+ }
1014
+ else {
1015
+ console.log(` ${render.icons.warn} ${dec.result.line ?? `${label}: ${dec.result.kind} — would not re-pin`}`);
1016
+ }
1017
+ }
1018
+ }
1019
+ else {
1020
+ const overrides = behindMcp.map((f) => {
1021
+ const id = f.reading.target.id;
1022
+ return { kind: "mcp-client", id };
1023
+ });
1024
+ const results = refreshOwnedPins({ homeDir: homedir(), targets: overrides });
1025
+ for (const r of results) {
1026
+ if (r.target.kind !== "mcp-client")
1027
+ continue;
1028
+ // flair#1834 round 3: an attempted-but-skipped fix (e.g. a behind
1029
+ // Codex pin until A2 lands) is not a success — never ✓.
1030
+ console.log(` ${render.icons[mcpRepinIcon(r.action, r.ok)]} ${r.message}`);
1031
+ }
1032
+ }
1033
+ }
1034
+ }
962
1035
  // flair#989: the harness-specific checks below (CLAUDE.md, SessionStart
963
1036
  // hook, continuity, Codex hook) run only for a harness the user actually
964
1037
  // WIRED — its MCP block is present. A harness merely DETECTED on the box
@@ -1003,6 +1076,19 @@ export function register(program) {
1003
1076
  console.log(` ${render.wrap(render.c.dim, "Fix:")} flair doctor --fix ${render.wrap(render.c.dim, "(adds the mcp__flair__bootstrap line to ./CLAUDE.md)")}`);
1004
1077
  }
1005
1078
  }
1079
+ } // end CLAUDE.md (claudeCodeConfigured)
1080
+ // flair#1834 PR-H: a hook file on disk IS the wiring — the same rule as
1081
+ // the Codex hook below. A realistic setup keeps the SessionStart hook in
1082
+ // ~/.claude/settings.json while the flair MCP server is configured
1083
+ // PROJECT-scoped (a project's .mcp.json) rather than in ~/.claude.json.
1084
+ // claudeCodeConfigured is then false and the hook never ran — a silently
1085
+ // skipped HOLD, the exact state PR-H exists to prevent. Inspect the
1086
+ // Claude Code hook whenever one is PRESENT on disk; a
1087
+ // `claudeCodeConfigured` box with NO hook still falls through to the
1088
+ // "not found / add" report below.
1089
+ const claudeHook = inspectSessionStartHook(homedir(), { settingsPath: hookSettingsPath(homedir(), "claude-code") });
1090
+ if (claudeCodeConfigured || claudeHook.present) {
1091
+ const hook = claudeHook;
1006
1092
  // flair#1007: presence was never the problem — the failing entry was
1007
1093
  // perfectly well-formed. inspectSessionStartHook() additionally RUNS
1008
1094
  // the registered command (bounded, side-effect-free via
@@ -1010,21 +1096,35 @@ export function register(program) {
1010
1096
  // works", and reports the shell-level silencing separately so an
1011
1097
  // already-installed loud hook can be upgraded rather than only
1012
1098
  // diagnosed.
1013
- const hook = inspectSessionStartHook(homedir());
1014
1099
  if (hook.present) {
1015
1100
  // flair#1485: pin ≠ installed CLI version is a failure, never a
1016
1101
  // ✓ "still runs". Check freshness first so a stale pin cannot
1017
1102
  // hide behind the execution probe. Catalog owns the issue count.
1018
- const claudeStale = staleSessionStartHookPins(homedir()).find((r) => r.target.id === "claude-code");
1019
- if (claudeStale) {
1020
- console.log(` ${render.icons.error} SessionStart hook: pinned to flair-mcp@${claudeStale.pin} (installed CLI is ${flairCliVersion()}) — the hook still launches the OLD adapter on every session`);
1103
+ const claudeStale = sessionStartHookPinFindings(homedir()).find((f) => f.reading.target.id === "claude-code");
1104
+ if (claudeStale && claudeStale.direction === "unknown") {
1105
+ // flair#1778: a pin we cannot compare is its OWN finding — a warn,
1106
+ // never the stale "old adapter" error, and NOT re-pinned (the
1107
+ // refresh holds an unreadable pin). Needs no --fix.
1108
+ console.log(` ${render.icons.warn} SessionStart hook: pin is not a version I can compare: ${claudeStale.reading.pin} — not re-pinned; re-run flair init or edit the hook if this is unintended`);
1109
+ }
1110
+ else if (claudeStale && claudeStale.direction === "ahead") {
1111
+ // flair#1778 follow-up: a pin AHEAD of the running CLI is not stale
1112
+ // — re-pinning would LOWER it and the refresh HOLDS it. Report a
1113
+ // held pass: no ✗, no issue count (the catalog agrees), no --fix.
1114
+ console.log(` ${render.icons.ok} SessionStart hook: pinned to flair-mcp@${claudeStale.reading.pin}, ahead of the installed CLI ${flairCliVersion()} — held`);
1115
+ }
1116
+ else if (claudeStale) {
1117
+ console.log(` ${render.icons.error} SessionStart hook: pinned to flair-mcp@${claudeStale.reading.pin} (installed CLI is ${flairCliVersion()}) — the hook still launches the OLD adapter on every session`);
1021
1118
  if (autoFix) {
1022
1119
  if (dryRun) {
1023
1120
  console.log(` ${render.wrap(render.c.dim, "Would re-pin the SessionStart hook in")} ${hook.path}`);
1024
1121
  }
1025
1122
  else {
1026
- const repin = repinSessionStartHook(homedir(), "claude-code");
1027
- console.log(` ${repin.ok ? render.icons.ok : render.icons.warn} ${repin.message}`);
1123
+ const repin = repinSessionStartHookGuarded(homedir(), "claude-code");
1124
+ // flair#1834 A1 round 3 + PR-H: the SAME icon rule as the MCP
1125
+ // re-pin line — a hold (or a failed write) renders ⚠, never a
1126
+ // false ✓ for an attempted-but-held fix.
1127
+ console.log(` ${render.icons[mcpRepinIcon(repin.action, repin.ok)]} ${repin.message}`);
1028
1128
  }
1029
1129
  }
1030
1130
  else {
@@ -1123,7 +1223,7 @@ export function register(program) {
1123
1223
  console.log(` ${render.wrap(render.c.dim, "Fix:")} flair doctor --fix ${render.wrap(render.c.dim, "(adds the flair-session-start SessionStart hook)")}`);
1124
1224
  }
1125
1225
  }
1126
- } // end CLAUDE.md + SessionStart hook (claudeCodeConfigured)
1226
+ } // end SessionStart hook (claudeCodeConfigured || hook.present)
1127
1227
  // Continuity capture is a standalone Claude Code opt-in — shown whenever
1128
1228
  // Claude Code is DETECTED, independent of MCP wiring (flair#1324/#1257).
1129
1229
  if (claudeCodeDetected) {
@@ -1184,19 +1284,39 @@ export function register(program) {
1184
1284
  // command Claude Code uses, written to ~/.codex/hooks.json. Continuity
1185
1285
  // and CLAUDE.md stay Claude-Code-only; Codex's session-start mechanism
1186
1286
  // is the hook file.
1187
- if (codexConfigured) {
1188
- const hook = inspectSessionStartHook(homedir(), { settingsPath: hookSettingsPath(homedir(), "codex") });
1287
+ // flair#1834 PR-H: a hook file on disk IS the wiring. Inspect Codex's
1288
+ // SessionStart hook whenever one is PRESENT on disk, not only when Codex
1289
+ // is otherwise detected/configured on this box (a `codex` binary on PATH
1290
+ // or a wired ~/.codex/config.toml). Gating the whole block on Codex's MCP
1291
+ // configuration silently skipped a wired ~/.codex/hooks.json when Codex
1292
+ // was not installed — exactly the quiet skip PR-H exists to prevent (a
1293
+ // HOLD must be printed). A `codexConfigured` box with NO hook still falls
1294
+ // through to the "not found / add" report below.
1295
+ const codexHook = inspectSessionStartHook(homedir(), { settingsPath: hookSettingsPath(homedir(), "codex") });
1296
+ if (codexConfigured || codexHook.present) {
1297
+ const hook = codexHook;
1189
1298
  if (hook.present) {
1190
- const codexStale = staleSessionStartHookPins(homedir()).find((r) => r.target.id === "codex");
1191
- if (codexStale) {
1192
- console.log(` ${render.icons.error} SessionStart hook (codex): pinned to flair-mcp@${codexStale.pin} (installed CLI is ${flairCliVersion()}) — the hook still launches the OLD adapter on every session`);
1299
+ const codexStale = sessionStartHookPinFindings(homedir()).find((f) => f.reading.target.id === "codex");
1300
+ if (codexStale && codexStale.direction === "unknown") {
1301
+ // flair#1778: same direction rule as Claude Code above.
1302
+ console.log(` ${render.icons.warn} SessionStart hook (codex): pin is not a version I can compare: ${codexStale.reading.pin} — not re-pinned; re-run flair init or edit the hook if this is unintended`);
1303
+ }
1304
+ else if (codexStale && codexStale.direction === "ahead") {
1305
+ // flair#1778 follow-up: same direction rule as Claude Code above.
1306
+ console.log(` ${render.icons.ok} SessionStart hook (codex): pinned to flair-mcp@${codexStale.reading.pin}, ahead of the installed CLI ${flairCliVersion()} — held`);
1307
+ }
1308
+ else if (codexStale) {
1309
+ console.log(` ${render.icons.error} SessionStart hook (codex): pinned to flair-mcp@${codexStale.reading.pin} (installed CLI is ${flairCliVersion()}) — the hook still launches the OLD adapter on every session`);
1193
1310
  if (autoFix) {
1194
1311
  if (dryRun) {
1195
1312
  console.log(` ${render.wrap(render.c.dim, "Would re-pin the SessionStart hook in")} ${hook.path}`);
1196
1313
  }
1197
1314
  else {
1198
- const repin = repinSessionStartHook(homedir(), "codex");
1199
- console.log(` ${repin.ok ? render.icons.ok : render.icons.warn} ${repin.message}`);
1315
+ const repin = repinSessionStartHookGuarded(homedir(), "codex");
1316
+ // flair#1834 A1 round 3 + PR-H: the SAME icon rule as the MCP
1317
+ // re-pin line — a hold (or a failed write) renders ⚠, never a
1318
+ // false ✓ for an attempted-but-held fix.
1319
+ console.log(` ${render.icons[mcpRepinIcon(repin.action, repin.ok)]} ${repin.message}`);
1200
1320
  }
1201
1321
  }
1202
1322
  else {