@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.
@@ -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
@@ -3,7 +3,7 @@ import { homedir } from "node:os";
3
3
  import { dirname, resolve } from "node:path";
4
4
  import * as render from "../render.js";
5
5
  import { isLocalBase, resolveAdminUser, resolveLocalAdminPass } from "../lib/auth-resolve.js";
6
- import { validatePromoteOpts, validateRejectOpts, decideCandidateAction, derivePromotedTags, validateHumanReviewerId, } from "../rem/promote-policy.js";
6
+ import { validatePromoteOpts, validateRejectOpts, decideCandidateAction, derivePromotedTags, validateHumanReviewerId, structuralImbalance, hasTerminalPunctuation, } from "../rem/promote-policy.js";
7
7
  export { validatePromoteOpts, validateRejectOpts, decideCandidateAction, derivePromotedTags, derivePromotedVisibility, validateHumanReviewerId, isMachineReviewerId, ADK_SCOPE_TAG_PREFIX, CONTINUITY_SCOPE_TAG_PREFIX, MACHINE_REVIEWER_PREFIX, MACHINE_REVIEWER_ADK_AUTO_PROMOTE, } from "../rem/promote-policy.js";
8
8
  let cli;
9
9
  /** Bind shared CLI helpers. cli.ts calls this immediately before register(program). */
@@ -68,6 +68,28 @@ export function formatCandidateLine(candidate, maxClaimLen = 80) {
68
68
  const truncated = claim.length > maxClaimLen ? `${claim.slice(0, maxClaimLen)}…` : claim;
69
69
  return ` [${candidate.id ?? "?"}] ${truncated}`;
70
70
  }
71
+ /**
72
+ * Flag a probable truncated claim for the HUMAN reviewer (flair#1756 slice 2,
73
+ * issue suggestion 3). Returns null when nothing is off; otherwise a short
74
+ * descriptor. This is advisory ONLY — the refusal for structural imbalance
75
+ * lives server-side in decideAutoPromote (the unattended path); a human
76
+ * promote is a legitimate place to look at a fragment and decide.
77
+ *
78
+ * Reports STRUCTURAL imbalance (unbalanced backtick/paren/bracket/brace) and, as
79
+ * a weaker signal, missing terminal punctuation. Neither claims the text is
80
+ * incomplete — a balanced claim can still be a fragment.
81
+ */
82
+ export function candidateIncompleteFlag(claim) {
83
+ // A malformed row can carry a non-string claim; normalize rather than throw,
84
+ // so listing one bad candidate never takes down the whole review surface.
85
+ const text = typeof claim === "string" ? claim : "";
86
+ const imbalance = structuralImbalance(text);
87
+ if (imbalance !== null)
88
+ return `structurally incomplete (${imbalance}); the unattended auto-promote path refuses this`;
89
+ if (!hasTerminalPunctuation(text))
90
+ return "no terminal punctuation — possible fragment";
91
+ return null;
92
+ }
71
93
  /**
72
94
  * Classifies a thrown /ReflectMemories execute-mode error for CLI display.
73
95
  * `api()` throws `Error(responseBodyText)` for non-2xx responses (see api()
@@ -396,7 +418,8 @@ export function register(program) {
396
418
  const candidates = await res.json();
397
419
  const mode = render.resolveOutputMode(opts);
398
420
  if (mode === "json") {
399
- console.log(render.asJSON({ agentId, status, count: candidates.length, candidates }));
421
+ const annotated = candidates.map((c) => ({ ...c, incompleteFlag: candidateIncompleteFlag(c.claim) }));
422
+ console.log(render.asJSON({ agentId, status, count: candidates.length, candidates: annotated }));
400
423
  return;
401
424
  }
402
425
  const statusColor = status === "promoted" ? render.c.green : status === "rejected" ? render.c.red : render.c.yellow;
@@ -423,6 +446,10 @@ export function register(program) {
423
446
  }
424
447
  console.log(` ${render.wrap(render.c.dim, c.id)} ${tag}`);
425
448
  console.log(` ${c.claim}`);
449
+ const incompleteFlag = candidateIncompleteFlag(c.claim);
450
+ if (incompleteFlag) {
451
+ console.log(` ${render.wrap(render.c.yellow, "⚠ possible incomplete claim")} ${render.wrap(render.c.dim, `— ${incompleteFlag}`)}`);
452
+ }
426
453
  if (c.supersedes) {
427
454
  console.log(` ${render.wrap(render.c.dim, `(supersedes ${c.supersedes} — recurring proposal)`)}`);
428
455
  }
@@ -1,4 +1,4 @@
1
- import { detectWiredFlairMcp, isNodeKeyId } from "../doctor-client.js";
1
+ import { detectWiredFlairMcp } from "../doctor-client.js";
2
2
  import { UPGRADE_SNAPSHOT_ROOT, fetchDeclaredHarperVersion, readInstalledHarperVersion } from "../engine-version.js";
3
3
  import { fabricUpgrade } from "../fabric-upgrade.js";
4
4
  import { renderFleetSweepTable, sweepFleet } from "../fleet-verify.js";
@@ -19,6 +19,7 @@ import { chmodSync, existsSync, lstatSync, mkdirSync, readdirSync, realpathSync,
19
19
  import { homedir } from "node:os";
20
20
  import { join, resolve, sep } from "node:path";
21
21
  import { create as tarCreate } from "tar";
22
+ import { classifyInstalledVersion, formatUpgradeStatusLine } from "../lib/upgrade-status.js";
22
23
  let cli;
23
24
  /** Bind the cli-locals this module depends on. */
24
25
  export function bindCli(fns) {
@@ -66,9 +67,6 @@ function probeOpenclawPluginVersion(...args) {
66
67
  function relativeTime(...args) {
67
68
  return cli.relativeTime(...args);
68
69
  }
69
- function resolveAgentIdOrEnv(...args) {
70
- return cli.resolveAgentIdOrEnv(...args);
71
- }
72
70
  function resolveFabricCredentials(...args) {
73
71
  return cli.resolveFabricCredentials(...args);
74
72
  }
@@ -841,6 +839,13 @@ export function register(program) {
841
839
  // resolved, so a redirected registry is visible to the operator before
842
840
  // anything is fetched or installed. One line per distinct registry.
843
841
  const noticeRegistry = createRegistryNoticePrinter();
842
+ // An explicit --flair-version pin is the operator's requested target (its
843
+ // downgrade semantics are slice 2, flair#1778 D7) — when set, the
844
+ // plain-tree lane keeps its existing explicit-target behaviour rather than
845
+ // the direction-aware "ahead" gate.
846
+ const flairVersionPin = typeof opts.flairVersion === "string" && opts.flairVersion.trim() !== ""
847
+ ? opts.flairVersion
848
+ : null;
844
849
  for (const { name, probe, kind, transitive } of packages) {
845
850
  if (transitive && !showAll)
846
851
  continue;
@@ -876,7 +881,7 @@ export function register(program) {
876
881
  // that, a requested tarball swap reports up to date and does nothing.
877
882
  const listing = resolvePlainTreeListingTarget({
878
883
  registryLatest,
879
- pin: typeof opts.flairVersion === "string" ? opts.flairVersion : null,
884
+ pin: flairVersionPin,
880
885
  });
881
886
  if (!listing)
882
887
  continue;
@@ -894,12 +899,6 @@ export function register(program) {
894
899
  console.error(` ⚠ ${name}: refusing non-semver install target ${JSON.stringify(latest)} — expected a version like 1.2.3.`);
895
900
  continue;
896
901
  }
897
- if (name === FLAIR_PKG_NAME) {
898
- try {
899
- primeVersionCheckCache(latest);
900
- }
901
- catch { /* best-effort */ }
902
- }
903
902
  const globalProbe = probe();
904
903
  let installed;
905
904
  let status;
@@ -909,10 +908,14 @@ export function register(program) {
909
908
  installed = treeLane.version;
910
909
  if (installed === null)
911
910
  status = "missing";
912
- else if (installed === latest)
913
- status = "current";
911
+ // An explicit --flair-version pin IS the requested target (slice 2
912
+ // owns its downgrade semantics) — do not gate it. Without a pin,
913
+ // classify by semver direction so an install ahead of registry
914
+ // latest is never mistaken for an upgrade (flair#1778).
915
+ else if (flairVersionPin !== null)
916
+ status = installed === latest ? "current" : "outdated";
914
917
  else
915
- status = "outdated";
918
+ status = classifyInstalledVersion(installed, latest);
916
919
  }
917
920
  else if (name === FLAIR_MCP_PACKAGE) {
918
921
  // flair-mcp is zero-install via npx (#1168) — a null global probe is
@@ -929,14 +932,26 @@ export function register(program) {
929
932
  // installed, don't surface a misleading "install with npm" advice.
930
933
  status = kind === "openclaw-plugin" ? "optional" : "missing";
931
934
  }
932
- else if (installed === latest) {
933
- status = "current";
934
- }
935
935
  else {
936
- status = "outdated";
936
+ // Direction-aware (flair#1778): an install ahead of latest is a
937
+ // distinct state, never rendered as an upgrade, never installed.
938
+ status = classifyInstalledVersion(installed, latest);
937
939
  }
938
940
  }
939
941
  findings.push({ name, installed, latest, status, kind });
942
+ // flair#1778 D5: prime the version-check cache with the EFFECTIVE
943
+ // target. When the install is AHEAD of latest nothing will be installed,
944
+ // so priming `latest` would make a later version check nudge a
945
+ // downgrade.
946
+ if (name === FLAIR_PKG_NAME) {
947
+ const effectiveTarget = status === "ahead" ? installed : latest;
948
+ if (effectiveTarget) {
949
+ try {
950
+ primeVersionCheckCache(effectiveTarget);
951
+ }
952
+ catch { /* best-effort */ }
953
+ }
954
+ }
940
955
  // Suppress the line for openclaw plugins that are optional-because-
941
956
  // openclaw-is-absent: on machines without openclaw the
942
957
  // "○ … not installed (openclaw not detected) → … (install via …)"
@@ -944,13 +959,11 @@ export function register(program) {
944
959
  // (current/outdated) or under --all.
945
960
  if (!shouldPrintUpgradeLine(status, showAll))
946
961
  continue;
947
- const icon = status === "current" ? "✅"
948
- : status === "outdated" ? "⬆️"
949
- : status === "optional" ? "○"
950
- : "❔";
951
- const installedLabel = installed ?? (status === "optional" ? "not installed (openclaw not detected)" : "not detected");
962
+ // ONE renderer (src/lib/upgrade-status.ts). An install AHEAD of latest
963
+ // prints with NO arrow and NO remedy (flair#1778); an unparseable
964
+ // installed version prints the raw string as "❔ unknown".
952
965
  const suffix = upgradeStatusSuffix(name, status);
953
- console.log(` ${icon} ${name}: ${installedLabel} → ${latest}${suffix}`);
966
+ console.log(formatUpgradeStatusLine({ name, installed, latest, status, suffix }));
954
967
  }
955
968
  catch { /* skip unavailable packages */ }
956
969
  }
@@ -985,25 +998,41 @@ export function register(program) {
985
998
  let treePlan = null;
986
999
  if (treeLane) {
987
1000
  const flairFindingForPlan = findings.find((f) => f.name === FLAIR_PKG_NAME);
988
- // flair#1758: unit discovery is captured HERE, into the plan, while apply
989
- // later renames the selected canonical tree (applyPlainTreeUpgrade). A
990
- // concurrent symlink retarget between discovery and apply can therefore
991
- // make the restart launch a DIFFERENT tree than the one that matched.
992
- // Resolving both sides fresh narrows the window; it is not transaction
993
- // locking.
994
- treePlan = planPlainTreeUpgrade({
995
- treeDir: treeLane.dir,
996
- fromVersion: treeLane.version,
997
- toVersion: flairFindingForPlan?.latest ?? treeLane.version ?? "unknown",
998
- systemdUnits: findSystemdUnitsForTree(treeLane.dir),
999
- });
1001
+ // flair#1778 D3: CONSTRUCT the plan only when flair is actually being
1002
+ // upgraded. Downstream restart/rollback/cleanup key on `treePlan`'s
1003
+ // presence, so a plan built for an install that is not changing would
1004
+ // stage a swap that never happens.
1000
1005
  if (flairFindingForPlan?.status === "outdated") {
1006
+ // flair#1758: unit discovery is captured HERE, into the plan, while
1007
+ // apply later renames the selected canonical tree
1008
+ // (applyPlainTreeUpgrade). A concurrent symlink retarget between
1009
+ // discovery and apply can therefore make the restart launch a
1010
+ // DIFFERENT tree than the one that matched. Resolving both sides fresh
1011
+ // narrows the window; it is not transaction locking.
1012
+ treePlan = planPlainTreeUpgrade({
1013
+ treeDir: treeLane.dir,
1014
+ fromVersion: treeLane.version,
1015
+ toVersion: flairFindingForPlan.latest,
1016
+ systemdUnits: findSystemdUnitsForTree(treeLane.dir),
1017
+ });
1001
1018
  console.log("");
1002
1019
  console.log(formatPlainTreePlan(treePlan));
1003
1020
  }
1004
1021
  }
1005
1022
  if (outdated.length === 0 && missing.length === 0) {
1006
- console.log("\n✅ Everything is up to date.");
1023
+ // An install AHEAD of latest is not an upgrade (flair#1778), and neither
1024
+ // is one whose installed version we could not PARSE: "unknown" is not
1025
+ // evidence of convergence, so "✅ Everything is up to date." would claim
1026
+ // more than we can see (flair#1778 slice-1 follow-up, N1). Prefer the
1027
+ // neutral summary whenever EITHER state is present, and for an
1028
+ // unparseable version name the package and the raw string that could not
1029
+ // be parsed — the operator gets to see what was unreadable.
1030
+ const anyAhead = findings.some((f) => f.status === "ahead");
1031
+ const unknownFindings = findings.filter((f) => f.status === "unknown");
1032
+ for (const f of unknownFindings) {
1033
+ console.log(`\n❔ ${f.name}: could not parse installed version ${JSON.stringify(f.installed)} — not reporting it as up to date.`);
1034
+ }
1035
+ console.log(anyAhead || unknownFindings.length > 0 ? "\nNo upgrades available." : "\n✅ Everything is up to date.");
1007
1036
  return;
1008
1037
  }
1009
1038
  // ONE pin-refresh implementation, two callers (flair#1324): the post-
@@ -1013,33 +1042,14 @@ export function register(program) {
1013
1042
  // `doctor --fix` round-trip. Only refreshes clients that are ALREADY
1014
1043
  // wired — never wires new ones. Best-effort: failures warn but never fail
1015
1044
  // the upgrade.
1016
- async function refreshWiredMcpClientPins(targetPort) {
1017
- const agentId = resolveAgentIdOrEnv({}) ?? (() => {
1018
- try {
1019
- const kd = defaultKeysDir();
1020
- const keyFiles = readdirSync(kd).filter((f) => f.endsWith(".key"));
1021
- // Node-scoped federation keys aren't agents (flair#1193) — never
1022
- // pin-refresh a connector as one.
1023
- const agentKeyFile = keyFiles.find((f) => !isNodeKeyId(f.replace(/\.key$/, ""), kd));
1024
- return agentKeyFile ? agentKeyFile.replace(/\.key$/, "") : null;
1025
- }
1026
- catch {
1027
- return null;
1028
- }
1029
- })();
1030
- // flair#1485: one catalogue (listOwnedPinTargets) for every file we
1031
- // pin — MCP client configs AND SessionStart hooks. A missing agent id
1032
- // skips MCP only; hook re-pin reads the agent from the existing command
1033
- // and must still run (the early return here used to leave hooks stale).
1034
- if (!agentId) {
1035
- console.log("\n (no agent id known — skip MCP client pin refresh; SessionStart hooks still re-pin)");
1036
- }
1045
+ async function refreshWiredMcpClientPins() {
1046
+ // flair#1834 A1: the refresh is PIN-ONLY. It no longer resolves a
1047
+ // host-wide agent id (the old first-`.key` fallback in this function) or a FLAIR_URL, because those were written into EVERY wired
1048
+ // client's env — rewriting each client's FLAIR_AGENT_ID to whichever key
1049
+ // happened to sort first. The writer preserves each entry's own identity
1050
+ // and changes only the pinned package argument.
1037
1051
  const homeDir = process.env.HOME || process.env.USERPROFILE || homedir();
1038
- const results = refreshOwnedPins({
1039
- homeDir,
1040
- agentId: agentId ?? null,
1041
- flairUrl: `http://127.0.0.1:${targetPort}`,
1042
- });
1052
+ const results = refreshOwnedPins({ homeDir });
1043
1053
  const noteworthy = results.filter(ownedPinRefreshShouldReport);
1044
1054
  if (noteworthy.length === 0)
1045
1055
  return;
@@ -1060,7 +1070,16 @@ export function register(program) {
1060
1070
  if (missing.length > 0) {
1061
1071
  const npmMissing = missing.filter((f) => f.name !== FLAIR_MCP_PACKAGE);
1062
1072
  const mcpMissing = missing.some((f) => f.name === FLAIR_MCP_PACKAGE);
1063
- console.log(`\n❔ ${missing.length} package${missing.length > 1 ? "s" : ""} not detected — all detected packages are up to date.`);
1073
+ // flair#1778 follow-up: "all detected packages are up to date" is the
1074
+ // same false-convergence claim the no-upgrade summary above avoids, so
1075
+ // guard it with the same condition — when any detected package is
1076
+ // `ahead` or `unknown`, say only that there are no upgrades for the
1077
+ // rest, never that they are up to date.
1078
+ const anyAheadOrUnknown = findings.some((f) => f.status === "ahead" || f.status === "unknown");
1079
+ const tail = anyAheadOrUnknown
1080
+ ? "no upgrades available for the rest"
1081
+ : "all detected packages are up to date";
1082
+ console.log(`\n❔ ${missing.length} package${missing.length > 1 ? "s" : ""} not detected — ${tail}.`);
1064
1083
  if (npmMissing.length > 0) {
1065
1084
  console.log(` Install missing: npm install -g ${npmMissing.map((f) => f.name).join(" ")}`);
1066
1085
  }
@@ -1074,7 +1093,7 @@ export function register(program) {
1074
1093
  console.log(" Run: flair upgrade (refreshes the pin)");
1075
1094
  }
1076
1095
  else {
1077
- await refreshWiredMcpClientPins(resolveHttpPort({}));
1096
+ await refreshWiredMcpClientPins();
1078
1097
  }
1079
1098
  }
1080
1099
  return;
@@ -1314,7 +1333,7 @@ export function register(program) {
1314
1333
  // version. Runs BEFORE the restart so --no-restart and --no-verify paths
1315
1334
  // also get the refresh (flair#1167). Best-effort: failures warn but never
1316
1335
  // fail the upgrade.
1317
- await refreshWiredMcpClientPins(upgradePort);
1336
+ await refreshWiredMcpClientPins();
1318
1337
  // ── Restart + verify + rollback (flair#635) ─────────────────────────────
1319
1338
  // Decision (2026-07-08): restart is now the default post-upgrade step —
1320
1339
  // installing new code without restarting leaves the OLD process serving