@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.
@@ -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";
@@ -102,6 +102,33 @@ export function summarizeDoctorRun(found, fixed, autoFix) {
102
102
  exitCode: 1,
103
103
  };
104
104
  }
105
+ /**
106
+ * flair#1761 — the single place a Health-derived Metal finding becomes doctor
107
+ * output and exit-code weight. Extracted from the action callback so the
108
+ * detected-vs-env-vs-unrecognized severity is exercised on the real
109
+ * rendering/counting path (the action's Harper probe, console side effects
110
+ * and process.exit cannot be driven directly — see doctor-summary.test.ts for
111
+ * the same extraction convention).
112
+ *
113
+ * The finding carries its own icon and issue weight: a derived ("detected")
114
+ * Metal default is rendered as a persistent warning and does NOT increment
115
+ * the issue count, while an explicit request or an unrecognized source is a
116
+ * blocking `✗` that does. `lines` is returned for tests; production passes a
117
+ * writer (default: console.log).
118
+ */
119
+ export function renderEmbedGpuDoctorFinding(embedding, write = (line) => console.log(line)) {
120
+ const finding = describeEmbedGpuDoctorFinding(embedding);
121
+ if (!finding)
122
+ return { lines: [], issueDelta: 0 };
123
+ const icon = finding.icon === "warn" ? render.icons.warn : render.icons.error;
124
+ const lines = [
125
+ ` ${icon} ${finding.message}`,
126
+ ` ${render.wrap(render.c.dim, "Fix:")} ${finding.fixHint}`,
127
+ ];
128
+ for (const line of lines)
129
+ write(line);
130
+ return { lines, issueDelta: finding.isIssue ? 1 : 0 };
131
+ }
105
132
  // ─── flair doctor ─────────────────────────────────────────────────────────────
106
133
  export function register(program) {
107
134
  const __pkgVersion = cli.__pkgVersion;
@@ -422,14 +449,12 @@ export function register(program) {
422
449
  else {
423
450
  console.log(` ${render.icons.warn} Could not determine the running server's version`);
424
451
  }
425
- // flair#1437: fail-loud Metal fallback. Health states it; operators
426
- // read doctor. A stated CPU default is silent here.
427
- const embedGpuFinding = describeEmbedGpuDoctorFinding(embedGpuFromHealth);
428
- if (embedGpuFinding) {
429
- console.log(` ${render.icons.error} ${embedGpuFinding.message}`);
430
- console.log(` ${render.wrap(render.c.dim, "Fix:")} ${embedGpuFinding.fixHint}`);
431
- issues++;
432
- }
452
+ // flair#1437 (severity split flair#1761): Health states an unconfirmed
453
+ // Metal offload; operators read doctor. The finding carries its own
454
+ // severity — a derived ("detected") default is an advisory warning that
455
+ // does NOT fail the run, while an explicit request or an unrecognized
456
+ // source still fails closed. A stated CPU default is silent here.
457
+ issues += renderEmbedGpuDoctorFinding(embedGpuFromHealth).issueDelta;
433
458
  }
434
459
  // 2. Keys directory
435
460
  const keysDir = defaultKeysDir();
@@ -798,7 +823,17 @@ export function register(program) {
798
823
  agentFlag: typeof opts.agent === "string" ? opts.agent : undefined,
799
824
  };
800
825
  const catalogBefore = runDoctorChecks(doctorCtx, { catalogIds: doctorCatalogIds });
801
- 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) {
802
837
  console.log(` ${render.icons.info} No MCP client detected — skipping client-integration checks`);
803
838
  }
804
839
  else {
@@ -934,6 +969,69 @@ export function register(program) {
934
969
  console.log(` ${render.icons.warn} ${finding?.message ?? `could not verify agent registration (${reg.detail})`}`);
935
970
  }
936
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
+ }
937
1035
  // flair#989: the harness-specific checks below (CLAUDE.md, SessionStart
938
1036
  // hook, continuity, Codex hook) run only for a harness the user actually
939
1037
  // WIRED — its MCP block is present. A harness merely DETECTED on the box
@@ -978,6 +1076,19 @@ export function register(program) {
978
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)")}`);
979
1077
  }
980
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;
981
1092
  // flair#1007: presence was never the problem — the failing entry was
982
1093
  // perfectly well-formed. inspectSessionStartHook() additionally RUNS
983
1094
  // the registered command (bounded, side-effect-free via
@@ -985,21 +1096,35 @@ export function register(program) {
985
1096
  // works", and reports the shell-level silencing separately so an
986
1097
  // already-installed loud hook can be upgraded rather than only
987
1098
  // diagnosed.
988
- const hook = inspectSessionStartHook(homedir());
989
1099
  if (hook.present) {
990
1100
  // flair#1485: pin ≠ installed CLI version is a failure, never a
991
1101
  // ✓ "still runs". Check freshness first so a stale pin cannot
992
1102
  // hide behind the execution probe. Catalog owns the issue count.
993
- const claudeStale = staleSessionStartHookPins(homedir()).find((r) => r.target.id === "claude-code");
994
- if (claudeStale) {
995
- 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`);
996
1118
  if (autoFix) {
997
1119
  if (dryRun) {
998
1120
  console.log(` ${render.wrap(render.c.dim, "Would re-pin the SessionStart hook in")} ${hook.path}`);
999
1121
  }
1000
1122
  else {
1001
- const repin = repinSessionStartHook(homedir(), "claude-code");
1002
- 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}`);
1003
1128
  }
1004
1129
  }
1005
1130
  else {
@@ -1098,7 +1223,7 @@ export function register(program) {
1098
1223
  console.log(` ${render.wrap(render.c.dim, "Fix:")} flair doctor --fix ${render.wrap(render.c.dim, "(adds the flair-session-start SessionStart hook)")}`);
1099
1224
  }
1100
1225
  }
1101
- } // end CLAUDE.md + SessionStart hook (claudeCodeConfigured)
1226
+ } // end SessionStart hook (claudeCodeConfigured || hook.present)
1102
1227
  // Continuity capture is a standalone Claude Code opt-in — shown whenever
1103
1228
  // Claude Code is DETECTED, independent of MCP wiring (flair#1324/#1257).
1104
1229
  if (claudeCodeDetected) {
@@ -1159,19 +1284,39 @@ export function register(program) {
1159
1284
  // command Claude Code uses, written to ~/.codex/hooks.json. Continuity
1160
1285
  // and CLAUDE.md stay Claude-Code-only; Codex's session-start mechanism
1161
1286
  // is the hook file.
1162
- if (codexConfigured) {
1163
- 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;
1164
1298
  if (hook.present) {
1165
- const codexStale = staleSessionStartHookPins(homedir()).find((r) => r.target.id === "codex");
1166
- if (codexStale) {
1167
- 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`);
1168
1310
  if (autoFix) {
1169
1311
  if (dryRun) {
1170
1312
  console.log(` ${render.wrap(render.c.dim, "Would re-pin the SessionStart hook in")} ${hook.path}`);
1171
1313
  }
1172
1314
  else {
1173
- const repin = repinSessionStartHook(homedir(), "codex");
1174
- 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}`);
1175
1320
  }
1176
1321
  }
1177
1322
  else {
@@ -159,78 +159,65 @@ export function signRequestBody(body, secretKey) {
159
159
  }
160
160
  // Alias: signBodyFresh for clarity at call sites
161
161
  const signBodyFresh = signRequestBody;
162
- function isCompletePeerRow(row) {
163
- if (!row || typeof row !== "object")
164
- return false;
165
- const r = row;
166
- return typeof r.id === "string" && r.id.length > 0
167
- && typeof r.publicKey === "string" && r.publicKey.length > 0;
168
- }
169
162
  /**
170
163
  * Persist last-contact on the local Peer row after confirmed hub contact.
171
164
  *
172
- * Callers must invoke this only after a FederationSync 200 (sendBatch or
173
- * the no-change liveness ping). lastSyncAt is the value HealthDetail counts
174
- * as `connected` (flair#1499 / flair#1146). A failed ping must leave the
175
- * stamp untouched so the answer stays `unknown`.
165
+ * Callers must invoke this only after a FederationSync 200 (sendBatch or the
166
+ * no-change liveness ping). lastSyncAt is the value HealthDetail counts as
167
+ * `connected` (flair#1499 / flair#1146) AND the spoke's OUTBOUND sync cursor
168
+ * (`federation sync` re-sends from it) — so a frozen value re-sends from the
169
+ * frozen point forever and goes stale on the hub dashboard.
170
+ *
171
+ * SEMANTICS (flair#1835): `connected` means RECENT CONTACT. It does not mean a
172
+ * verified hub identity or pull readiness. Inbound federation separately
173
+ * verifies the pinned key (resources/Federation.ts post — verifyBodySignatureFresh),
174
+ * so a keyless row reading `connected` is correct under that definition. The
175
+ * missing key is repaired by #1837, not here.
176
+ *
177
+ * WHY A FIELD-ONLY UPDATE (flair#1835, was flair#1146): the 0.55.0 write was a
178
+ * read + FULL-row upsert gated on `isCompletePeerRow` (id + non-empty
179
+ * `publicKey`). A legacy pairing's local hub row has `publicKey: ""`, so the
180
+ * gate refused on every poll and the cursor froze. The read + full upsert also
181
+ * races: a key repair or a revocation written between the read and the upsert
182
+ * is reverted, and a row deleted in that window is recreated. The field-only
183
+ * `update` carries only {id, lastSyncAt, updatedAt}, so it cannot revert
184
+ * `publicKey`/`status`, and it never inserts.
176
185
  *
177
- * Why a full-row upsert rather than the `{id, lastSyncAt}` `update` that
178
- * has shipped since #426: Kern probed that partial update on Harper 5.2.8
179
- * and 5.1.22 — it already lands, `publicKey` intact. We keep read-then-upsert
180
- * to harden against a future Harper that treats an incomplete upsert as
181
- * replace. On search-miss we refuse to write rather than depend on merge.
186
+ * HTTP 200 is NOT success: an update that matched no row (deleted or missing)
187
+ * is a REFUSAL, never an insert. Harper reports which ids matched in
188
+ * `update_hashes`; we require ours there.
182
189
  */
183
190
  export async function persistLocalPeerLastSyncAt(args) {
184
191
  const headers = { "Content-Type": "application/json", Authorization: args.auth };
185
- let existing = null;
186
- try {
187
- const searchRes = await fetch(`${args.opsEndpoint}/`, {
188
- method: "POST",
189
- headers,
190
- body: JSON.stringify({
191
- operation: "search_by_value",
192
- schema: "flair",
193
- table: "Peer",
194
- search_attribute: "id",
195
- search_type: "equals",
196
- search_value: args.peerId,
197
- get_attributes: ["*"],
198
- }),
199
- signal: AbortSignal.timeout(10_000),
200
- });
201
- if (searchRes.ok) {
202
- const rows = await searchRes.json();
203
- const row = Array.isArray(rows) ? rows[0] : rows;
204
- if (isCompletePeerRow(row) && row.id === args.peerId)
205
- existing = row;
206
- }
207
- }
208
- catch {
209
- // Search miss — refuse to upsert an incomplete Peer.
210
- }
211
- if (!existing) {
212
- return { ok: false, status: 0, error: "peer row missing or incomplete — refused to upsert a partial Peer" };
213
- }
214
- const upsertRes = await fetch(`${args.opsEndpoint}/`, {
192
+ const updateRes = await fetch(`${args.opsEndpoint}/`, {
215
193
  method: "POST",
216
194
  headers,
217
195
  body: JSON.stringify({
218
- operation: "upsert",
196
+ operation: "update",
219
197
  database: "flair",
220
198
  table: "Peer",
221
- records: [{
222
- ...existing,
223
- id: args.peerId,
224
- lastSyncAt: args.lastSyncAt,
225
- updatedAt: args.lastSyncAt,
226
- }],
199
+ records: [{ id: args.peerId, lastSyncAt: args.lastSyncAt, updatedAt: args.lastSyncAt }],
227
200
  }),
228
201
  signal: AbortSignal.timeout(10_000),
229
202
  });
230
- if (upsertRes.ok)
231
- return { ok: true, status: upsertRes.status };
232
- const txt = await upsertRes.text().catch(() => "");
233
- return { ok: false, status: upsertRes.status, error: txt.slice(0, 200) };
203
+ if (!updateRes.ok) {
204
+ const txt = await updateRes.text().catch(() => "");
205
+ return { ok: false, status: updateRes.status, error: txt.slice(0, 200) };
206
+ }
207
+ // The result check — HTTP 200 alone is not success. A miss (deleted/missing
208
+ // row) is reported in skipped_hashes with an empty update_hashes; refuse and
209
+ // never insert.
210
+ const parsed = (await updateRes.json().catch(() => null));
211
+ const matched = !!parsed && Array.isArray(parsed.update_hashes) && parsed.update_hashes.includes(args.peerId);
212
+ if (!matched) {
213
+ return {
214
+ ok: false,
215
+ status: updateRes.status,
216
+ error: `Peer row ${args.peerId} was not matched by the cursor update (deleted or missing) — ` +
217
+ `the sync cursor stays frozen; re-pair the hub. Not inserting a Peer row.`,
218
+ };
219
+ }
220
+ return { ok: true, status: updateRes.status };
234
221
  }
235
222
  /**
236
223
  * The most recent CONTACT with any peer (max of peer.lastSyncAt), or null.
@@ -1,6 +1,6 @@
1
1
  import { applyOrReportClaudeMdBootstrap, applyOrReportSessionStartHook } from "../doctor-client.js";
2
2
  import { hookSettingsPath } from "../hook-install.js";
3
- import { detectClients, renderWiringSummary, wireAntigravity, wireCodex, wireCursor, wireGemini, wirePi } from "../install/clients.js";
3
+ import { claudeCodeMcpEntry, detectClients, renderWiringSummary, wireAntigravity, wireClaudeCodeJson, wireCodex, wireCursor, wireGemini, wirePi } from "../install/clients.js";
4
4
  import { DEFAULT_ADMIN_USER, authFetch, defaultAdminPassPath, defaultKeysDir, readAdminPassFileSecure, resolveAdminUser } from "../lib/auth-resolve.js";
5
5
  import { detectPersistedAdminUser, executeAdminPasswordRotate, initAdminPassRefusalMessage, resolveInitAdminPasswordRefuseReason, resolveInitAdminPasswordSource, } from "../lib/init-admin-pass.js";
6
6
  import { mcpServerSpec, unpinnedSpecWarning } from "../lib/mcp-spec.js";
@@ -1045,66 +1045,65 @@ export function register(program) {
1045
1045
  // Claude Code gets real auto-wiring into ~/.claude.json (zero-install
1046
1046
  // npx form; matches the snippets everywhere else). Other clients only
1047
1047
  // get printed instructions — the CLI can't safely edit their configs.
1048
- const claudeJsonPath = join(homedir(), ".claude.json");
1049
- const flairMcpConfig = {
1050
- type: "stdio",
1051
- command: "npx",
1052
- args: ["-y", mcpServerSpec()],
1053
- // flair#718 authorship-provenance: each client's wired env block
1054
- // gets its OWN FLAIR_CLIENT label (never the shared mcpEnv
1055
- // object directly — that would stamp the same label into every
1056
- // client's config) so writes from THIS client's proxy stamp
1057
- // provenance.claimed.client = "claude-code".
1058
- env: { ...mcpEnv, FLAIR_CLIENT: "claude-code" },
1059
- };
1060
- // ~/.claude.json exists once Claude Code has been RUN, not once it
1061
- // is installed — so gating the write on it skipped every user who
1062
- // installed Claude Code and Flair in the same sitting (flair#906).
1063
- // The file is Claude Code's own and creating it with a single
1064
- // `mcpServers` key is exactly what `claude mcp add` does, so an
1065
- // absent file is created rather than turned into a printed snippet
1066
- // the user has to notice and act on.
1067
- try {
1068
- const claudeJsonExisted = existsSync(claudeJsonPath);
1069
- const claudeJson = claudeJsonExisted
1070
- ? JSON.parse(readFileSync(claudeJsonPath, "utf-8"))
1071
- : {};
1072
- const existing = claudeJson.mcpServers?.flair;
1073
- const currentSpec = mcpServerSpec();
1074
- const existingArgs = existing?.args;
1075
- const argsMatch = Array.isArray(existingArgs) && existingArgs.includes(currentSpec);
1076
- const urlAgentMatch = existing && existing.env?.FLAIR_URL === httpUrl && existing.env?.FLAIR_AGENT_ID === agentId;
1077
- // flair#1135: the pin in `args` must match the current mcpServerSpec().
1078
- // A matching pin stays a no-op (idempotent); only a stale pin triggers a re-write.
1079
- if (urlAgentMatch && argsMatch) {
1080
- console.log(` ✓ Claude Code already wired in ~/.claude.json`);
1081
- wiringResults.push({ client: "claude-code", message: "already wired", wired: true });
1082
- }
1083
- else {
1084
- claudeJson.mcpServers = claudeJson.mcpServers || {};
1085
- claudeJson.mcpServers.flair = flairMcpConfig;
1086
- writeFileSync(claudeJsonPath, JSON.stringify(claudeJson, null, 2));
1087
- const action = urlAgentMatch ? "refreshed pin in ~/.claude.json"
1088
- : claudeJsonExisted ? "wired in ~/.claude.json"
1089
- : "wired in ~/.claude.json (created)";
1090
- console.log(` ✓ Claude Code ${action} (restart Claude Code to pick it up)`);
1091
- wiringResults.push({
1092
- client: "claude-code",
1093
- message: urlAgentMatch ? "refreshed pin in ~/.claude.json"
1094
- : claudeJsonExisted ? "wired ~/.claude.json"
1095
- : "created and wired ~/.claude.json",
1096
- wired: true,
1097
- });
1098
- }
1048
+ //
1049
+ // flair#1778 2c-i-d1: init no longer writes ~/.claude.json itself. It
1050
+ // DELEGATES to the shared clients.ts writer (wireClaudeCodeJson) — the
1051
+ // SAME critical section, resolveHome() and entry builder that doctor
1052
+ // --fix and the owned-pin refresh use — and renders its own lines from
1053
+ // the STRUCTURED outcome. Both writers of this file now emit ONE shape
1054
+ // (`type: "stdio"` KEPT, a trailing newline added); an empty file now
1055
+ // reads as {} instead of throwing. resolveHome() (not os.homedir(),
1056
+ // which is fixed at LAUNCH under Bun) is what makes an in-process HOME
1057
+ // override take effect — os.homedir() would still write the REAL
1058
+ // ~/.claude.json.
1059
+ // flair#718 authorship-provenance: the Claude Code env block gets its
1060
+ // OWN FLAIR_CLIENT label (never the shared mcpEnv object directly —
1061
+ // that would stamp the same label into every client's config) so
1062
+ // writes from THIS client's proxy stamp
1063
+ // provenance.claimed.client = "claude-code".
1064
+ const claudeEnv = { ...mcpEnv, FLAIR_CLIENT: "claude-code" };
1065
+ const wireOutcome = wireClaudeCodeJson(claudeEnv);
1066
+ if (wireOutcome.kind === "already") {
1067
+ console.log(` ✓ Claude Code already wired in ~/.claude.json`);
1068
+ wiringResults.push({ client: "claude-code", message: "already wired", wired: true });
1099
1069
  }
1100
- catch (err) {
1101
- // Only a genuine read/parse/write failure lands here now (bad
1102
- // permissions, malformed existing JSON) — never merely "the file
1103
- // does not exist yet".
1104
- const reason = err instanceof Error ? err.message : String(err);
1070
+ else if (wireOutcome.kind === "held") {
1071
+ console.log(` ${render.icons.warn} ${wireOutcome.line}`);
1072
+ wiringResults.push({
1073
+ client: "claude-code",
1074
+ message: "held the existing pin in ~/.claude.json",
1075
+ wired: wireOutcome.entryPresent,
1076
+ });
1077
+ }
1078
+ else if (wireOutcome.kind === "refused") {
1079
+ console.log(` ${render.icons.warn} ${wireOutcome.line}`);
1080
+ wiringResults.push({
1081
+ client: "claude-code",
1082
+ message: "refused to write ~/.claude.json (unreadable CLI version)",
1083
+ wired: wireOutcome.entryPresent,
1084
+ });
1085
+ }
1086
+ else if (wireOutcome.kind === "written") {
1087
+ const action = wireOutcome.refreshed ? "refreshed pin in ~/.claude.json"
1088
+ : wireOutcome.existed ? "wired in ~/.claude.json"
1089
+ : "wired in ~/.claude.json (created)";
1090
+ console.log(` ✓ Claude Code ${action} (restart Claude Code to pick it up)`);
1091
+ wiringResults.push({
1092
+ client: "claude-code",
1093
+ message: wireOutcome.refreshed ? "refreshed pin in ~/.claude.json"
1094
+ : wireOutcome.existed ? "wired ~/.claude.json"
1095
+ : "created and wired ~/.claude.json",
1096
+ wired: true,
1097
+ });
1098
+ }
1099
+ else {
1100
+ // A genuine read/parse/write/lock failure (bad permissions,
1101
+ // malformed existing JSON, a held lock) — never merely "the file
1102
+ // does not exist yet" (an absent file is created).
1103
+ const reason = wireOutcome.reason ?? "unknown error";
1105
1104
  console.log(` ${render.icons.warn} Claude Code: could not write ~/.claude.json (${reason})`);
1106
1105
  console.log(` MCP config (add manually to ~/.claude.json):`);
1107
- console.log(` { "mcpServers": { "flair": ${JSON.stringify(flairMcpConfig)} } }`);
1106
+ console.log(` { "mcpServers": { "flair": ${JSON.stringify(claudeCodeMcpEntry(claudeEnv))} } }`);
1108
1107
  wiringResults.push({ client: "claude-code", message: `snippet printed (${reason})`, wired: false });
1109
1108
  }
1110
1109
  // ── CLAUDE.md bootstrap line (flair#597) ──────────────────────────
@@ -1188,8 +1187,11 @@ export function register(program) {
1188
1187
  if (!opts.skipSmoke && !noMcp && clientOpt !== "none" && wiringResults.length > 0 && wiredAnyMcpClient) {
1189
1188
  console.log("\n Smoke-testing MCP server...");
1190
1189
  try {
1191
- // Same spec that gets WIRED above — the smoke test must exercise the
1192
- // exact version the user will run, not whatever npm resolves latest to.
1190
+ // The RUNNING CLI's own server: mcpServerSpec() pins to THIS
1191
+ // CLI's version. That is not necessarily the version a client
1192
+ // config ends up keeping — on a HELD pin the config is deliberately
1193
+ // left on a HIGHER version than this CLI — so the smoke exercises
1194
+ // what this CLI can run, not the held pin.
1193
1195
  const mcpProc = spawn("npx", ["-y", mcpServerSpec()], {
1194
1196
  env: { ...process.env, FLAIR_AGENT_ID: agentId, FLAIR_URL: httpUrl },
1195
1197
  stdio: ["pipe", "pipe", "pipe"],
@@ -1229,13 +1231,13 @@ export function register(program) {
1229
1231
  for (const line of lines) {
1230
1232
  const parsed = JSON.parse(line);
1231
1233
  if (parsed.jsonrpc === "2.0" && parsed.id === 1 && !parsed.error) {
1232
- console.log(" ✓ MCP server responded");
1234
+ console.log(` ✓ MCP server responded (this CLI's ${mcpServerSpec()} server, not the pinned config's)`);
1233
1235
  break;
1234
1236
  }
1235
1237
  }
1236
1238
  }
1237
1239
  catch {
1238
- console.log(" ⚠ MCP server responded but response could not be parsed");
1240
+ console.log(" ⚠ MCP server responded but response could not be parsed (this CLI's server, not the pinned config's)");
1239
1241
  }
1240
1242
  finally {
1241
1243
  // Reap the child even on the resolve path: the MCP server exits on