@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.
@@ -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,19 +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
- treePlan = planPlainTreeUpgrade({
989
- treeDir: treeLane.dir,
990
- fromVersion: treeLane.version,
991
- toVersion: flairFindingForPlan?.latest ?? treeLane.version ?? "unknown",
992
- systemdUnits: findSystemdUnitsForTree(treeLane.dir),
993
- });
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.
994
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
+ });
995
1018
  console.log("");
996
1019
  console.log(formatPlainTreePlan(treePlan));
997
1020
  }
998
1021
  }
999
1022
  if (outdated.length === 0 && missing.length === 0) {
1000
- 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.");
1001
1036
  return;
1002
1037
  }
1003
1038
  // ONE pin-refresh implementation, two callers (flair#1324): the post-
@@ -1007,33 +1042,14 @@ export function register(program) {
1007
1042
  // `doctor --fix` round-trip. Only refreshes clients that are ALREADY
1008
1043
  // wired — never wires new ones. Best-effort: failures warn but never fail
1009
1044
  // the upgrade.
1010
- async function refreshWiredMcpClientPins(targetPort) {
1011
- const agentId = resolveAgentIdOrEnv({}) ?? (() => {
1012
- try {
1013
- const kd = defaultKeysDir();
1014
- const keyFiles = readdirSync(kd).filter((f) => f.endsWith(".key"));
1015
- // Node-scoped federation keys aren't agents (flair#1193) — never
1016
- // pin-refresh a connector as one.
1017
- const agentKeyFile = keyFiles.find((f) => !isNodeKeyId(f.replace(/\.key$/, ""), kd));
1018
- return agentKeyFile ? agentKeyFile.replace(/\.key$/, "") : null;
1019
- }
1020
- catch {
1021
- return null;
1022
- }
1023
- })();
1024
- // flair#1485: one catalogue (listOwnedPinTargets) for every file we
1025
- // pin — MCP client configs AND SessionStart hooks. A missing agent id
1026
- // skips MCP only; hook re-pin reads the agent from the existing command
1027
- // and must still run (the early return here used to leave hooks stale).
1028
- if (!agentId) {
1029
- console.log("\n (no agent id known — skip MCP client pin refresh; SessionStart hooks still re-pin)");
1030
- }
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.
1031
1051
  const homeDir = process.env.HOME || process.env.USERPROFILE || homedir();
1032
- const results = refreshOwnedPins({
1033
- homeDir,
1034
- agentId: agentId ?? null,
1035
- flairUrl: `http://127.0.0.1:${targetPort}`,
1036
- });
1052
+ const results = refreshOwnedPins({ homeDir });
1037
1053
  const noteworthy = results.filter(ownedPinRefreshShouldReport);
1038
1054
  if (noteworthy.length === 0)
1039
1055
  return;
@@ -1054,7 +1070,16 @@ export function register(program) {
1054
1070
  if (missing.length > 0) {
1055
1071
  const npmMissing = missing.filter((f) => f.name !== FLAIR_MCP_PACKAGE);
1056
1072
  const mcpMissing = missing.some((f) => f.name === FLAIR_MCP_PACKAGE);
1057
- 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}.`);
1058
1083
  if (npmMissing.length > 0) {
1059
1084
  console.log(` Install missing: npm install -g ${npmMissing.map((f) => f.name).join(" ")}`);
1060
1085
  }
@@ -1068,7 +1093,7 @@ export function register(program) {
1068
1093
  console.log(" Run: flair upgrade (refreshes the pin)");
1069
1094
  }
1070
1095
  else {
1071
- await refreshWiredMcpClientPins(resolveHttpPort({}));
1096
+ await refreshWiredMcpClientPins();
1072
1097
  }
1073
1098
  }
1074
1099
  return;
@@ -1308,7 +1333,7 @@ export function register(program) {
1308
1333
  // version. Runs BEFORE the restart so --no-restart and --no-verify paths
1309
1334
  // also get the refresh (flair#1167). Best-effort: failures warn but never
1310
1335
  // fail the upgrade.
1311
- await refreshWiredMcpClientPins(upgradePort);
1336
+ await refreshWiredMcpClientPins();
1312
1337
  // ── Restart + verify + rollback (flair#635) ─────────────────────────────
1313
1338
  // Decision (2026-07-08): restart is now the default post-upgrade step —
1314
1339
  // installing new code without restarting leaves the OLD process serving