@tpsdev-ai/flair 0.56.0 → 0.58.0

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.
Files changed (153) hide show
  1. package/README.md +19 -20
  2. package/SECURITY.md +4 -1
  3. package/dist/build-info.json +3 -3
  4. package/dist/cli.js +1800 -293
  5. package/dist/commands/agent.js +22 -15
  6. package/dist/commands/bridge.js +40 -3
  7. package/dist/commands/doctor.js +214 -4
  8. package/dist/commands/federation.js +265 -38
  9. package/dist/commands/hook.js +10 -2
  10. package/dist/commands/init.js +179 -48
  11. package/dist/commands/memory.js +24 -2
  12. package/dist/commands/quality.js +26 -18
  13. package/dist/commands/service.js +137 -22
  14. package/dist/commands/status.js +114 -3
  15. package/dist/commands/upgrade.js +204 -84
  16. package/dist/doctor-client.js +50 -4
  17. package/dist/federation/scheduler.js +253 -4
  18. package/dist/install/clients.js +89 -23
  19. package/dist/install/global-bin-path.js +26 -6
  20. package/dist/lib/atomic-write.js +256 -0
  21. package/dist/lib/auth-resolve.js +46 -0
  22. package/dist/lib/daemon-liveness.js +61 -0
  23. package/dist/lib/doctor-run.js +5 -0
  24. package/dist/lib/embed-gpu-doctor.js +49 -26
  25. package/dist/lib/federation-memory-attributes.js +15 -0
  26. package/dist/lib/init-admin-pass.js +4 -2
  27. package/dist/lib/init-listener-environ.js +38 -0
  28. package/dist/lib/init-occupied-listener.js +165 -0
  29. package/dist/lib/instance-identity-row.js +580 -0
  30. package/dist/lib/launchd-domain-preflight.js +448 -0
  31. package/dist/lib/launchd-management.js +176 -6
  32. package/dist/lib/launchd-repair.js +95 -0
  33. package/dist/lib/memory-attributes.js +77 -0
  34. package/dist/lib/node-alias-path.js +95 -0
  35. package/dist/lib/npm-registry.js +119 -6
  36. package/dist/lib/owned-pins.js +20 -6
  37. package/dist/lib/redact-token-id.js +197 -0
  38. package/dist/lib/service-repoint-apply.js +267 -0
  39. package/dist/lib/service-repoint.js +575 -0
  40. package/dist/lib/toml-string-array.js +104 -0
  41. package/dist/lib/tree-divergence.js +716 -0
  42. package/dist/lib/upgrade-plain-tree.js +18 -8
  43. package/dist/lib/upgrade-prior-liveness.js +69 -0
  44. package/dist/lib/upgrade-rollback.js +116 -0
  45. package/dist/rem/runner.js +11 -0
  46. package/dist/resources/Agent.js +27 -14
  47. package/dist/resources/AgentSeed.js +39 -2
  48. package/dist/resources/Asset.js +3 -11
  49. package/dist/resources/Credential.js +4 -10
  50. package/dist/resources/Federation.js +299 -127
  51. package/dist/resources/Integration.js +8 -32
  52. package/dist/resources/Memory.js +623 -86
  53. package/dist/resources/MemoryArchive.js +9 -0
  54. package/dist/resources/MemoryBootstrap.js +23 -12
  55. package/dist/resources/MemoryCandidate.js +3 -11
  56. package/dist/resources/MemoryDedupStats.js +1 -1
  57. package/dist/resources/MemoryFeed.js +214 -5
  58. package/dist/resources/MemoryGrant.js +19 -40
  59. package/dist/resources/MemoryHostSource.js +90 -0
  60. package/dist/resources/MemoryMaintenance.js +121 -32
  61. package/dist/resources/MemoryReflect.js +4 -1
  62. package/dist/resources/MemoryReindex.js +7 -4
  63. package/dist/resources/MemoryUsage.js +55 -18
  64. package/dist/resources/Presence.js +18 -10
  65. package/dist/resources/RecordUsage.js +30 -40
  66. package/dist/resources/Relationship.js +170 -89
  67. package/dist/resources/SemanticSearch.js +44 -19
  68. package/dist/resources/Soul.js +31 -19
  69. package/dist/resources/XAA.js +7 -3
  70. package/dist/resources/agent-auth.js +16 -10
  71. package/dist/resources/auth-middleware.js +164 -50
  72. package/dist/resources/auto-promote-lib.js +4 -4
  73. package/dist/resources/bm25-index-service.js +246 -32
  74. package/dist/resources/bm25-status.js +132 -0
  75. package/dist/resources/bm25.js +13 -14
  76. package/dist/resources/ed25519-auth.js +11 -54
  77. package/dist/resources/embed-gpu.js +262 -47
  78. package/dist/resources/embeddings-boot.js +52 -17
  79. package/dist/resources/federation-classify.js +12 -0
  80. package/dist/resources/federation-cleanup.js +289 -51
  81. package/dist/resources/federation-crypto.js +65 -19
  82. package/dist/resources/health.js +105 -22
  83. package/dist/resources/host-pointer/registry.js +35 -0
  84. package/dist/resources/host-pointer-adapter.js +15 -0
  85. package/dist/resources/host-source-visibility.js +167 -0
  86. package/dist/resources/host-source.js +151 -0
  87. package/dist/resources/in-process-api.js +2 -1
  88. package/dist/resources/instance-create-lock.js +363 -0
  89. package/dist/resources/instance-identity-rows.js +43 -0
  90. package/dist/resources/instance-identity.js +97 -12
  91. package/dist/resources/mcp-handler.js +155 -51
  92. package/dist/resources/mcp-tool-arguments.js +83 -0
  93. package/dist/resources/mcp-tools.js +28 -25
  94. package/dist/resources/memory-consolidate-lib.js +3 -1
  95. package/dist/resources/memory-declared-attributes.js +103 -0
  96. package/dist/resources/memory-feed-lib.js +5 -1
  97. package/dist/resources/memory-host-source.js +163 -0
  98. package/dist/resources/memory-visibility.js +10 -7
  99. package/dist/resources/migrations/synthetic-test-migration.js +4 -1
  100. package/dist/resources/migrations/visibility-backfill.js +4 -1
  101. package/dist/resources/originator-instance.js +235 -0
  102. package/dist/resources/promotion-stamp.js +2 -0
  103. package/dist/resources/provenance.js +111 -11
  104. package/dist/resources/rate-limit.js +6 -4
  105. package/dist/resources/record-owner-guard.js +19 -0
  106. package/dist/resources/record-type-kit.js +44 -23
  107. package/dist/resources/record-types.js +6 -6
  108. package/dist/resources/relay-ops.js +28 -3
  109. package/dist/resources/replay-store.js +289 -0
  110. package/dist/resources/request-transaction.js +78 -0
  111. package/dist/resources/search-readiness.js +26 -22
  112. package/dist/resources/semantic-retrieval-core.js +103 -4
  113. package/dist/resources/table-helpers.js +33 -0
  114. package/dist/resources/table-patch-policy.js +109 -0
  115. package/dist/resources/table-patches.js +17 -0
  116. package/dist/resources/table-post-policy.js +138 -0
  117. package/dist/resources/table-posts.js +22 -0
  118. package/dist/resources/table-subscription-policy.js +135 -0
  119. package/dist/resources/table-subscriptions.js +19 -0
  120. package/dist/resources/tool-descriptors/index.js +15 -15
  121. package/dist/resources/trust-block.js +10 -3
  122. package/dist/resources/usage-recording.js +169 -41
  123. package/dist/src/lib/instance-identity-row.js +580 -0
  124. package/dist/src/lib/memory-attributes.js +77 -0
  125. package/dist/src/lib/redact-token-id.js +197 -0
  126. package/docs/api-reference.md +80 -16
  127. package/docs/auth.md +5 -5
  128. package/docs/claude-code.md +137 -6
  129. package/docs/deploying-on-fabric.md +6 -3
  130. package/docs/deployment.md +1 -1
  131. package/docs/embedding-in-a-harper-app.md +3 -3
  132. package/docs/federation.md +17 -10
  133. package/docs/hosted-on-fabric.md +4 -3
  134. package/docs/integrations.md +28 -19
  135. package/docs/mcp-clients.md +26 -32
  136. package/docs/n8n.md +8 -8
  137. package/docs/notes/mcp-oauth-model2.md +27 -18
  138. package/docs/openclaw.md +29 -28
  139. package/docs/quickstart.md +5 -0
  140. package/docs/releasing.md +134 -2
  141. package/docs/spoke-bringup.md +14 -11
  142. package/docs/standalone-local.md +2 -2
  143. package/docs/supply-chain-policy.md +28 -10
  144. package/docs/system-requirements.md +1 -1
  145. package/docs/troubleshooting.md +11 -0
  146. package/docs/upgrade.md +189 -63
  147. package/package.json +9 -5
  148. package/schemas/agent.graphql +9 -6
  149. package/schemas/federation.graphql +2 -11
  150. package/schemas/memory.graphql +106 -17
  151. package/schemas/replay.graphql +18 -0
  152. package/templates/launchd/start-flair-with-admin-pass.sh +22 -0
  153. package/dist/resources/federation-nonce-store.js +0 -195
@@ -4,27 +4,35 @@ import { fabricUpgrade } from "../fabric-upgrade.js";
4
4
  import { renderFleetSweepTable, sweepFleet } from "../fleet-verify.js";
5
5
  import { resolveNpmGlobalPrefix } from "../install/global-bin-path.js";
6
6
  import { defaultKeysDir } from "../lib/auth-resolve.js";
7
+ import { classifyDaemonState } from "../lib/daemon-liveness.js";
7
8
  import { renderVerifiedSummary } from "../lib/doctor-run.js";
8
9
  import { isDetached, renderDetachedWarning } from "../lib/launchd-management.js";
9
10
  import { FLAIR_MCP_PACKAGE, clearFlairCliVersionCache } from "../lib/mcp-spec.js";
10
- import { createRegistryNoticePrinter, fetchLatestVersion, isStrictSemver } from "../lib/npm-registry.js";
11
+ import { createRegistryNoticePrinter, fetchLatestVersion, fetchVersionDeprecation, isStrictSemver } from "../lib/npm-registry.js";
12
+ import { classifyUpgradePriorLiveness } from "../lib/upgrade-prior-liveness.js";
13
+ import { decideAfterRestartFailure, decideDeprecatedRollback, formatKnownBrokenRollbackRestart } from "../lib/upgrade-rollback.js";
11
14
  import { ownedPinRefreshShouldReport, refreshOwnedPins } from "../lib/owned-pins.js";
12
15
  import { extractSnapshotSafely, validateSnapshotArchive } from "../lib/safe-snapshot-extract.js";
13
16
  import { collectUpgradeExecPathWarning, findFlairPackageDir, resolveNpmGlobalFlairPackage, resolveServingFlairPackage } from "../lib/upgrade-exec-path.js";
14
- import { applyPlainTreeUpgrade, decidePlainTreeRollback, discardPlainTreePrevious, findSystemdUnitsForTree, formatPlainTreeBanner, formatPlainTreePlan, formatPlainTreeScopeFooter, planPlainTreeUpgrade, resolvePlainTreeListingTarget, resolvePlainTreeTarget, restartSystemdUnits, restorePlainTreePrevious } from "../lib/upgrade-plain-tree.js";
17
+ import { UPGRADE_FAILED_SUFFIX, decidePlainTreeRollback, discardPlainTreePrevious, findSystemdUnitsForTree, formatPlainTreeBanner, formatPlainTreePlan, formatPlainTreeScopeFooter, planPlainTreeUpgrade, resolvePlainTreeListingTarget, resolvePlainTreeTarget, restartSystemdUnits, stopSystemdUnits, restorePlainTreePrevious, treeSibling } from "../lib/upgrade-plain-tree.js";
15
18
  import { probeInstance } from "../probe.js";
16
19
  import * as render from "../render.js";
17
- import { FLAIR_PKG_NAME, primeVersionCheckCache } from "../version-check.js";
18
- import { chmodSync, existsSync, lstatSync, mkdirSync, readdirSync, realpathSync, rmSync, statSync } from "node:fs";
20
+ import { FLAIR_PKG_NAME, primeVersionCheckCache, probeInstanceVersion } from "../version-check.js";
21
+ import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, realpathSync, renameSync, rmSync, statSync } from "node:fs";
19
22
  import { join, resolve, sep } from "node:path";
20
23
  import { create as tarCreate } from "tar";
21
24
  import { classifyInstalledVersion, formatUpgradeStatusLine } from "../lib/upgrade-status.js";
22
25
  import { resolveHome } from "../lib/home.js";
26
+ import { formatTreeAssessmentLines, withRunningVersion } from "../lib/tree-divergence.js";
23
27
  let cli;
24
28
  /** Bind the cli-locals this module depends on. */
25
29
  export function bindCli(fns) {
26
30
  cli = fns;
27
31
  }
32
+ /** Shallow-merge the supplied bindings into cli. */
33
+ export function rebindCli(partial) {
34
+ cli = { ...cli, ...partial };
35
+ }
28
36
  function decideAfterRollbackVerify(...args) {
29
37
  return cli.decideAfterRollbackVerify(...args);
30
38
  }
@@ -88,6 +96,12 @@ function resolveUpgradeRestartVerify(...args) {
88
96
  function restartAfterUpgrade(...args) {
89
97
  return cli.restartAfterUpgrade(...args);
90
98
  }
99
+ function applyPlainTreeUpgrade(plan) {
100
+ return cli.applyPlainTreeUpgrade(plan);
101
+ }
102
+ function runPackageInstall(spec) {
103
+ cli.runPackageInstall(spec);
104
+ }
91
105
  function shouldPrintUpgradeLine(...args) {
92
106
  return cli.shouldPrintUpgradeLine(...args);
93
107
  }
@@ -410,23 +424,28 @@ export const UPGRADE_SNAPSHOT_NUDGE_LINES = [
410
424
  "To capture one first: `flair snapshot create` (physical) or `flair backup` (logical export), or re-run with --snapshot.",
411
425
  ];
412
426
  /**
413
- * Run the stop → snapshot → prune → restart dance for a pre-upgrade snapshot.
427
+ * Run the stop → snapshot → prune → conditional restart sequence for a
428
+ * pre-upgrade snapshot.
414
429
  * Extracted from the upgrade action so the --snapshot and engine-version-change
415
430
  * branches share the same mechanism (flair#1047).
416
431
  *
417
432
  * On snapshot failure: aborts the upgrade (process.exit(1)), restarting Flair
418
- * first if it was stopped. On restart-after-snapshot failure: also exits.
433
+ * first only if the initial /Health probe did not refuse. On restart-after-
434
+ * snapshot failure: also exits.
419
435
  */
420
- async function runUpgradeSnapshot(port, dataDir) {
436
+ async function runUpgradeSnapshot(port, dataDir, restartAfterSnapshot) {
421
437
  // Consistency: a running Harper's data dir can be mid-write, and a
422
438
  // plain file copy of a live database directory isn't guaranteed
423
439
  // point-in-time consistent (Harper 5.x = RocksDB: WAL/SST/MANIFEST
424
- // can tear under a live copy). Stopping first — then immediately
425
- // restarting the OLD version, before any package changes — gives a
426
- // quiesced, safe-to-copy directory with only a brief blip, even for
440
+ // can tear under a live copy). Stopping first gives a quiesced,
441
+ // safe-to-copy directory. When restartAfterSnapshot is true (the initial
442
+ // /Health probe did not refuse the connection), the OLD version is then
443
+ // restarted before any package changes — a brief blip, even for
427
444
  // --no-restart (the snapshot's correctness doesn't depend on
428
445
  // whether the caller wants a restart AFTER the upgrade — those are
429
- // orthogonal). See docs/upgrade.md for the native-backup alternative
446
+ // orthogonal). A refused probe leaves the instance stopped, so the
447
+ // restart-failure decision's `stopped` reading still holds after the
448
+ // package swap. See docs/upgrade.md for the native-backup alternative
430
449
  // considered and rejected (Harper's `get_backup` op backs up one
431
450
  // table/schema at a time over the running HTTP API — not the whole
432
451
  // data dir — and rejecting it here means this path never depends on
@@ -448,7 +467,7 @@ async function runUpgradeSnapshot(port, dataDir) {
448
467
  catch (err) {
449
468
  console.error(`❌ snapshot failed: ${err.message}`);
450
469
  console.error(" Aborting upgrade — no packages were changed.");
451
- if (stoppedForSnapshot) {
470
+ if (stoppedForSnapshot && restartAfterSnapshot) {
452
471
  try {
453
472
  await startFlairProcess(port, dataDir);
454
473
  }
@@ -456,14 +475,19 @@ async function runUpgradeSnapshot(port, dataDir) {
456
475
  }
457
476
  process.exit(1);
458
477
  }
459
- try {
460
- await startFlairProcess(port, dataDir);
461
- }
462
- catch (err) {
463
- console.error(`❌ failed to restart Flair after the pre-upgrade snapshot: ${err.message}`);
464
- console.error(` The snapshot itself succeeded (${snapshotPath}) — no packages were changed. Check: flair doctor`);
465
- process.exit(1);
478
+ if (restartAfterSnapshot) {
479
+ try {
480
+ await startFlairProcess(port, dataDir);
481
+ }
482
+ catch (err) {
483
+ console.error(`❌ failed to restart Flair after the pre-upgrade snapshot: ${err.message}`);
484
+ console.error(` The snapshot itself succeeded (${snapshotPath}) — no packages were changed. Check: flair doctor`);
485
+ process.exit(1);
486
+ }
466
487
  }
488
+ if (!snapshotPath)
489
+ throw new Error("pre-upgrade snapshot finished without a path");
490
+ return snapshotPath;
467
491
  }
468
492
  function resolveHttpPortForDataDir(opts) {
469
493
  try {
@@ -778,21 +802,46 @@ export function register(program) {
778
802
  process.exit(1);
779
803
  }
780
804
  const treeLane = treeDecision.kind === "use" ? treeDecision.inspection : null;
805
+ // flair#2034 §2: compare this CLI's install tree with the tree PROVEN to
806
+ // serve the instance (the service manager owns the serving process), once,
807
+ // before any branch — and with the version the instance actually runs.
808
+ // Not on the plain-tree lane: there a separate tree serving is the point.
809
+ let treeAssessment = null;
810
+ if (!treeLane) {
811
+ try {
812
+ const upgradePort = resolveHttpPort({});
813
+ treeAssessment = cli.assessInstallTree(defaultDataDir(), upgradePort, { local: true });
814
+ if (treeAssessment.state !== "unknown") {
815
+ treeAssessment = withRunningVersion(treeAssessment, await probeInstanceVersion(`http://127.0.0.1:${upgradePort}`, 2000));
816
+ }
817
+ }
818
+ catch {
819
+ treeAssessment = null;
820
+ }
821
+ }
822
+ const treesDiverge = treeAssessment?.state === "diverged";
781
823
  // flair#1109 (b): print the mismatch warning only when this run will
782
824
  // still treat npm-global as the install. Collect always, so the (b)
783
- // wiring test keeps seeing the call.
825
+ // wiring test keeps seeing the call. A PROVEN tree divergence (#2034)
826
+ // says the same thing with the serving tree named and the remedy, so it
827
+ // replaces this warning rather than printing beside it.
784
828
  try {
785
829
  const execPathWarning = collectUpgradeExecPathWarning({
786
830
  servingPid: upgradeServingPid,
787
831
  cliPackageDir: flairPackageDir(),
788
832
  npmGlobalPrefix: upgradeNpmPrefix,
789
833
  });
790
- if (execPathWarning && !treeLane) {
834
+ if (execPathWarning && !treeLane && !treesDiverge) {
791
835
  console.log(execPathWarning);
792
836
  console.log("");
793
837
  }
794
838
  }
795
839
  catch { /* never fail upgrade over a path probe */ }
840
+ if (treesDiverge && treeAssessment) {
841
+ for (const line of formatTreeAssessmentLines(treeAssessment, { context: "upgrade" }))
842
+ console.log(line);
843
+ console.log("");
844
+ }
796
845
  if (treeLane) {
797
846
  console.log(formatPlainTreeBanner(treeLane));
798
847
  console.log("");
@@ -1032,6 +1081,15 @@ export function register(program) {
1032
1081
  for (const f of unknownFindings) {
1033
1082
  console.log(`\n❔ ${f.name}: could not parse installed version ${JSON.stringify(f.installed)} — not reporting it as up to date.`);
1034
1083
  }
1084
+ // flair#2034 §2: never claim convergence while a DIFFERENT install tree
1085
+ // is proven to serve the instance — the listing above is about this
1086
+ // CLI's tree, not the one serving. The divergence block was printed once,
1087
+ // above the listing.
1088
+ if (treesDiverge) {
1089
+ console.log("\nNo upgrades available for this CLI's tree — but the instance is served from a different install tree " +
1090
+ "(see above), so that is not a statement about what is running.");
1091
+ return;
1092
+ }
1035
1093
  console.log(anyAhead || unknownFindings.length > 0 ? "\nNo upgrades available." : "\n✅ Everything is up to date.");
1036
1094
  return;
1037
1095
  }
@@ -1125,43 +1183,15 @@ export function register(program) {
1125
1183
  // verification steps (further down) all target the same URL — upgrade
1126
1184
  // never restarts Flair onto a different port.
1127
1185
  const baseUrl = `http://127.0.0.1:${upgradePort}`;
1128
- // ── Credential pre-flight (flair#741 fix #1) ────────────────────────────
1129
- // Post-restart verification (below) needs to authenticate against the
1130
- // running instance. If it can't do that RIGHT NOW, against the CURRENT,
1131
- // pre-upgrade instance, every upgrade on this machine is structurally
1132
- // doomed before a single package is touched: post-restart verify fails
1133
- // for the exact same credential reason, the rollback fires, and the
1134
- // rollback's own re-verify fails identically — producing "ROLLBACK ALSO
1135
- // FAILED VERIFICATION / state UNKNOWN" for an instance that was healthy
1136
- // the entire time. That is exactly the flair#741 incident report (a
1137
- // real 0.22.0→0.22.1 upgrade, healthy Flair, no ~/.flair/admin-pass, no
1138
- // FLAIR_ADMIN_PASS). Catch it here, before any mutation, with a message
1139
- // that says plainly: nothing was touched.
1140
- //
1141
- // Runs the SAME verification call (probeInstance + the agent-key-aware
1142
- // verifyAuthedGet, fix #2) that post-restart verification uses below —
1143
- // just against the pre-upgrade instance, with no expectVersion (there's
1144
- // no target version to compare against yet; the question here is purely
1145
- // "does an authenticated read work at all").
1146
- //
1147
- // Gated on --verify (shouldVerify): this check exists ONLY to keep
1148
- // post-restart verification honest. A user who already opted out of
1149
- // that verification with --no-verify has no use for a pre-flight that
1150
- // protects it, and blocking their upgrade on a check they didn't ask
1151
- // for would be a new, surprising failure mode of its own.
1152
- //
1153
- // Deliberately does NOT abort when the pre-flight instance is merely
1154
- // UNREACHABLE (down/timeout) rather than reachable-but-unauthenticated.
1155
- // `flair upgrade` may be the user's way of FIXING a down instance (bad
1156
- // code on disk that a newer version resolves) — today's behavior
1157
- // (pre-flair#741, no pre-flight at all) already lets that proceed, and
1158
- // a new hard block here would take away a legitimate recovery path for
1159
- // a failure mode this issue was never about. Only the specific
1160
- // "server responded, credentials didn't work" case is structurally
1161
- // doomed in a way a fresh install/restart can't fix on its own — so
1162
- // only that case aborts. (If a down instance turns out to ALSO lack
1163
- // credentials, that surfaces the normal way: post-restart verification
1164
- // fails and rolls back, same as any other post-restart failure.)
1186
+ // Probe prior /Health, including under --no-verify: the pre-upgrade
1187
+ // snapshot and the restart-failure decision both read it. A --no-restart
1188
+ // upgrade probes only if a snapshot is needed.
1189
+ // The separate credential preflight runs when shouldVerify is true and
1190
+ // exits only when isCredentialOnlyFailure(preflight) is true.
1191
+ let priorLiveness = { kind: "indeterminate", reason: "prior /Health was not probed" };
1192
+ if (shouldRestart) {
1193
+ priorLiveness = await classifyUpgradePriorLiveness(baseUrl, { timeoutMs: 3000 });
1194
+ }
1165
1195
  if (shouldVerify) {
1166
1196
  const preflight = await probeInstance(baseUrl, {
1167
1197
  // A short, bounded budget — this instance is presumed already
@@ -1236,6 +1266,9 @@ export function register(program) {
1236
1266
  }
1237
1267
  }
1238
1268
  const snapshotDecision = decideUpgradeSnapshotAction(flairIsUpgrading, !!opts.snapshot, hasDataDir, engineVersionChanging, !!opts.noEngineSnapshot);
1269
+ if (!shouldRestart && (snapshotDecision === "snapshot" || snapshotDecision === "engine-version-change")) {
1270
+ priorLiveness = await classifyUpgradePriorLiveness(baseUrl, { timeoutMs: 3000 });
1271
+ }
1239
1272
  let snapshotPath = null;
1240
1273
  if (snapshotDecision === "nudge") {
1241
1274
  // Non-blocking nudge only — never prompt/block here, this must stay
@@ -1259,11 +1292,11 @@ export function register(program) {
1259
1292
  console.log(`\nHarper engine version changing (${fromLabel} → ${toLabel}) — snapshotting data before upgrade...`);
1260
1293
  console.log(render.wrap(render.c.dim, "The tested-downgrade guarantee does not hold across engine version boundaries."));
1261
1294
  console.log(render.wrap(render.c.dim, "Pass --no-engine-snapshot to skip this (not recommended)."));
1262
- await runUpgradeSnapshot(upgradePort, upgradeDataDir);
1295
+ snapshotPath = await runUpgradeSnapshot(upgradePort, upgradeDataDir, priorLiveness.kind !== "stopped");
1263
1296
  }
1264
1297
  else if (snapshotDecision === "snapshot") {
1265
1298
  console.log("\nSnapshotting data before upgrade...");
1266
- await runUpgradeSnapshot(upgradePort, upgradeDataDir);
1299
+ snapshotPath = await runUpgradeSnapshot(upgradePort, upgradeDataDir, priorLiveness.kind !== "stopped");
1267
1300
  }
1268
1301
  // Perform upgrade. `latest` comes from the npm registry's HTTP
1269
1302
  // response, so CodeQL (correctly) treats it as untrusted input.
@@ -1293,7 +1326,7 @@ export function register(program) {
1293
1326
  continue;
1294
1327
  }
1295
1328
  console.log(` Installing ${pkg}@${latest}...`);
1296
- execFileSync("npm", ["install", "-g", `${pkg}@${latest}`], { stdio: "pipe" });
1329
+ runPackageInstall(`${pkg}@${latest}`);
1297
1330
  console.log(` ✅ ${pkg}@${latest} installed`);
1298
1331
  }
1299
1332
  catch (err) {
@@ -1340,8 +1373,12 @@ export function register(program) {
1340
1373
  // while the version on disk lies about what's actually running.
1341
1374
  // --no-restart opts back out for the "stage now, bounce later" case.
1342
1375
  // --restart is kept as a deprecated no-op for old muscle memory.
1343
- // Upgrade = install → restart → verify → (rollback on failure), one
1344
- // transaction — never report success on a broken restart.
1376
+ // Restart failure: no swap yields no-target; a swap after a refused
1377
+ // pre-upgrade /Health connection yields keep (exit success). Otherwise a
1378
+ // nonempty previous version selects rollback, or no-target without one.
1379
+ // Verification has its own ok/healthy-unverified/rollback/cannot-rollback
1380
+ // decision. Rollback refuses reported deprecation; plain-tree restoration
1381
+ // is skipped when the saved tree is missing. See docs/upgrade.md.
1345
1382
  const previousFlairVersion = flairFinding?.installed ?? null;
1346
1383
  const expectedFlairVersion = flairFinding?.status === "outdated" && !flairInstallFailed
1347
1384
  ? flairFinding.latest
@@ -1362,27 +1399,46 @@ export function register(program) {
1362
1399
  console.log("\nRestarting Flair...");
1363
1400
  const port = upgradePort;
1364
1401
  // baseUrl was hoisted above (pre-flight, fix #1) — same URL, no redeclaration.
1365
- /**
1366
- * Roll @tpsdev-ai/flair back to `toVersion`, restart on it, re-verify, and
1367
- * exit. Shared by the two ways an upgrade can fail after the package swap:
1368
- * the restart itself (flair#905) and post-restart verification (flair#635).
1369
- *
1370
- * flair#905 found the restart leg wired straight to `process.exit(1)` — so
1371
- * `docs/upgrade.md`'s "install → restart → verify → rollback-on-failure, in
1372
- * one step" was only ever true for the verify leg. An upgrade that installed
1373
- * new packages and then failed to start them left the operator on the new
1374
- * version with nothing running and no rollback, which is the one outcome the
1375
- * whole transaction exists to prevent.
1376
- */
1402
+ /** Map deprecation lookup results other than active/deprecated to unknown. */
1403
+ const readRollbackDeprecation = async (version) => {
1404
+ try {
1405
+ const res = await fetchVersionDeprecation(FLAIR_PKG_NAME, version);
1406
+ if (res.kind === "deprecated")
1407
+ return { kind: "deprecated", message: res.message };
1408
+ if (res.kind === "active")
1409
+ return { kind: "active" };
1410
+ return { kind: "unknown" };
1411
+ }
1412
+ catch {
1413
+ return { kind: "unknown" };
1414
+ }
1415
+ };
1377
1416
  const rollbackTo = async (toVersion, reason) => {
1417
+ let rollbackSnapshotRestored = false;
1418
+ let plainTreeRestored = false;
1419
+ let plainTreeLiveSetAside = false;
1420
+ const deprecation = decideDeprecatedRollback({
1421
+ toVersion,
1422
+ lookup: await readRollbackDeprecation(toVersion),
1423
+ installedVersion: expectedFlairVersion,
1424
+ reason,
1425
+ });
1426
+ if (deprecation.kind === "refuse") {
1427
+ for (const line of deprecation.lines)
1428
+ console.error(line);
1429
+ process.exit(1);
1430
+ }
1378
1431
  console.log(`\nRolling back @tpsdev-ai/flair to ${toVersion}...`);
1379
1432
  try {
1380
1433
  if (treePlan) {
1381
1434
  const rollbackDecision = decidePlainTreeRollback(existsSync(treePlan.previousDir));
1382
1435
  if (rollbackDecision.kind === "restore") {
1383
- if (!restorePlainTreePrevious(treePlan)) {
1436
+ const restored = restorePlainTreePrevious(treePlan);
1437
+ if (!restored.restored) {
1384
1438
  throw new Error(`no previous tree at ${treePlan.previousDir} to restore`);
1385
1439
  }
1440
+ plainTreeRestored = true;
1441
+ plainTreeLiveSetAside = restored.liveTreeSetAside;
1386
1442
  console.log(` ✅ restored previous tree from ${treePlan.previousDir}`);
1387
1443
  }
1388
1444
  else {
@@ -1390,7 +1446,7 @@ export function register(program) {
1390
1446
  }
1391
1447
  }
1392
1448
  else {
1393
- execFileSync("npm", ["install", "-g", `@tpsdev-ai/flair@${toVersion}`], { stdio: "pipe" });
1449
+ runPackageInstall(`@tpsdev-ai/flair@${toVersion}`);
1394
1450
  }
1395
1451
  }
1396
1452
  catch (err) {
@@ -1413,16 +1469,44 @@ export function register(program) {
1413
1469
  console.log(`\nEngine version changed — restoring pre-upgrade snapshot before rollback...`);
1414
1470
  console.log(` snapshot: ${snapshotPath}`);
1415
1471
  console.log(` target: ${upgradeDataDir}`);
1472
+ let retainedDataDir;
1416
1473
  try {
1474
+ // A failed restart/verify does not prove the daemon stopped.
1475
+ // stopFlairProcess can return after a best-effort wait; require
1476
+ // fresh pid AND health evidence before touching the directory.
1477
+ if (treePlan)
1478
+ stopSystemdUnits(treePlan.systemdUnits);
1479
+ await stopFlairProcess(port, upgradeDataDir);
1480
+ const state = classifyDaemonState(await cli.gatherDaemonEvidence(port, upgradeDataDir), { port, dataDir: upgradeDataDir });
1481
+ if (state.state !== "NOT_RUNNING") {
1482
+ throw new Error(`instance is not confirmed stopped (${state.state})`);
1483
+ }
1417
1484
  await validateSnapshotArchive({ file: snapshotPath, targetDir: upgradeDataDir });
1418
- rmSync(upgradeDataDir, { recursive: true, force: true });
1485
+ // Reserve a unique sibling, even for two rollbacks in the same
1486
+ // millisecond. Rename preserves post-snapshot writes; never prune
1487
+ // this directory or put it inside the tree being restored.
1488
+ const destination = mkdtempSync(`${resolve(upgradeDataDir)}.pre-rollback-${new Date().toISOString().replace(/[:.]/g, "-")}-`);
1489
+ renameSync(upgradeDataDir, destination);
1490
+ retainedDataDir = destination;
1491
+ }
1492
+ catch (err) {
1493
+ console.error(`❌ refusing snapshot restore: could not stop and retain the current data: ${err.message}`);
1494
+ console.error(` ${upgradeDataDir} was not moved or replaced; no snapshot was restored.`);
1495
+ console.error(` Resolve the stop or move-aside failure before retrying; snapshot: ${snapshotPath}`);
1496
+ process.exit(1);
1497
+ }
1498
+ console.log(` Current data retained at: ${retainedDataDir}`);
1499
+ console.log(` To recover writes made after the snapshot: stop Flair, set aside ${upgradeDataDir}, move ${retainedDataDir} back to ${upgradeDataDir}, and start with the Harper engine version that wrote it.`);
1500
+ try {
1419
1501
  mkdirSync(upgradeDataDir, { recursive: true, mode: 0o700 });
1420
1502
  await extractSnapshotSafely({ file: snapshotPath, targetDir: upgradeDataDir });
1503
+ rollbackSnapshotRestored = true;
1421
1504
  console.log(` ✅ snapshot restored`);
1422
1505
  }
1423
1506
  catch (err) {
1424
1507
  console.error(`❌ snapshot restore failed: ${err.message}`);
1425
1508
  console.error(` @tpsdev-ai/flair@${toVersion} is installed but the data directory could not be restored.`);
1509
+ console.error(` Pre-restore data remains intact at ${retainedDataDir}.`);
1426
1510
  console.error(` The snapshot itself is intact at ${snapshotPath} — restore it by hand:`);
1427
1511
  console.error(` flair snapshot restore "${snapshotPath}"`);
1428
1512
  console.error(` Then: flair start`);
@@ -1462,9 +1546,28 @@ export function register(program) {
1462
1546
  }
1463
1547
  }
1464
1548
  catch (err) {
1465
- console.error(`❌ rollback restart failed: ${err.message}`);
1466
- console.error(` @tpsdev-ai/flair@${toVersion} is installed but NOT running. Start it with: flair start`);
1467
- console.error(" Then check: flair status");
1549
+ // Report the install lane, tree-restore results and snapshot-restore
1550
+ // result to formatKnownBrokenRollbackRestart.
1551
+ const lane = treePlan
1552
+ ? {
1553
+ kind: "plain-tree",
1554
+ treeDir: treePlan.treeDir,
1555
+ failedDir: treeSibling(treePlan.treeDir, UPGRADE_FAILED_SUFFIX),
1556
+ previousDir: treePlan.previousDir,
1557
+ restored: plainTreeRestored,
1558
+ liveTreeSetAside: plainTreeLiveSetAside,
1559
+ }
1560
+ : { kind: "npm-global" };
1561
+ for (const line of formatKnownBrokenRollbackRestart({
1562
+ toVersion,
1563
+ error: err?.message ?? String(err),
1564
+ recoveryVersion: expectedFlairVersion,
1565
+ lane,
1566
+ snapshotRestored: rollbackSnapshotRestored,
1567
+ snapshotPath,
1568
+ })) {
1569
+ console.error(line);
1570
+ }
1468
1571
  process.exit(1);
1469
1572
  }
1470
1573
  const rollbackVerify = await probeInstance(baseUrl, {
@@ -1537,9 +1640,26 @@ export function register(program) {
1537
1640
  }
1538
1641
  catch (err) {
1539
1642
  console.error(`❌ restart failed: ${err.message}`);
1540
- console.error(" Flair is NOT running. Your data in ~/.flair was not touched by this upgrade.");
1541
- if (flairWasSwapped && previousFlairVersion) {
1542
- await rollbackTo(previousFlairVersion, `restart failed: ${err.message}`);
1643
+ const restartDecision = decideAfterRestartFailure({
1644
+ priorLiveness: priorLiveness.kind,
1645
+ flairWasSwapped,
1646
+ previousVersion: previousFlairVersion,
1647
+ installedVersion: expectedFlairVersion,
1648
+ startError: err?.message ?? String(err),
1649
+ });
1650
+ // decideAfterRestartFailure: no swap -> no-target; swapped + stopped ->
1651
+ // keep; otherwise a nonempty previous version -> rollback, else no-target.
1652
+ // keep exits successfully; rollbackTo and no-target exit with failure.
1653
+ if (restartDecision.kind === "keep") {
1654
+ for (const line of restartDecision.lines)
1655
+ console.error(line);
1656
+ process.exit(0);
1657
+ }
1658
+ if (restartDecision.kind === "rollback") {
1659
+ if (priorLiveness.kind === "indeterminate") {
1660
+ console.error(` Prior /Health was indeterminate (${priorLiveness.reason}) — not confirmed stopped, so this failure still rolls back.`);
1661
+ }
1662
+ await rollbackTo(restartDecision.toVersion, restartDecision.reason);
1543
1663
  }
1544
1664
  // Not reached when a rollback ran — rollbackTo always exits. Say WHICH of
1545
1665
  // the two "no rollback" cases this is; "nothing to roll back" is not the
@@ -220,6 +220,24 @@ export const CONTINUITY_CAPTURE_HOOK_MARKER = "flair-continuity-capture";
220
220
  * the current shape, while an unsilenced / non-`-p` hand-edit still reads stale.
221
221
  */
222
222
  const CONTINUITY_INVOCATION_RE = /npx -y -p @tpsdev-ai\/flair-mcp(?:@[^\s"']+)? flair-continuity-capture/;
223
+ // Share whole-command recognition with the writer. A matching invocation
224
+ // substring alone cannot establish the current form; pin direction is separate.
225
+ const CONTINUITY_PACKAGE_COMMAND_RE = /^FLAIR_AGENT_ID=([^\s'"]+)(?: FLAIR_URL=([^\s'"]+))? npx -y (?:-p )?(@tpsdev-ai\/flair-mcp(?:@[^\s"']+)?) flair-continuity-capture$/;
226
+ /** The report and writer must decode the same package argument. */
227
+ function continuityPackageArgument(command) {
228
+ if (command === null || !command.includes(FLAIR_MCP_PACKAGE))
229
+ return null;
230
+ const prefix = "sh -c '";
231
+ const suffix = " >/dev/null 2>/dev/null || true'";
232
+ const invocation = command.startsWith(prefix) && command.endsWith(suffix)
233
+ ? command.slice(prefix.length, -suffix.length)
234
+ : command;
235
+ const match = invocation.match(CONTINUITY_PACKAGE_COMMAND_RE);
236
+ if (!match || !isHookCommandValueSafe(match[1]) || (match[2] !== undefined && !isHookCommandValueSafe(match[2]))) {
237
+ return `${FLAIR_MCP_PACKAGE}@unknown`;
238
+ }
239
+ return match[3];
240
+ }
223
241
  /**
224
242
  * The PostToolUse matcher written alongside our hook entry — the EXACT
225
243
  * mutating-tool allowlist the capture binary enforces internally
@@ -285,11 +303,16 @@ function continuityEventReport(config, event) {
285
303
  const hook = found.group.hooks[found.hookIndex];
286
304
  const command = typeof hook?.command === "string" ? hook.command : "";
287
305
  const matcher = typeof found.group?.matcher === "string" ? found.group.matcher : undefined;
306
+ const pinText = continuityPackageArgument(command);
288
307
  const shapeOk = hook?.type === "command" &&
289
308
  CONTINUITY_INVOCATION_RE.test(command) &&
290
309
  hookCommandIsSilenced(command);
291
310
  const matcherOk = event !== "PostToolUse" || matcher === CONTINUITY_POST_TOOL_USE_MATCHER;
292
- return { present: true, command, matcher, currentForm: shapeOk && matcherOk };
311
+ const spec = decodeWiringSpec(pinText ?? "", FLAIR_MCP_PACKAGE);
312
+ const pinOk = spec?.token.kind === "none" || spec?.token.kind === "version";
313
+ const reason = !spec || pinOk ? undefined
314
+ : "pin " + (spec?.token.kind ?? "malformed") + ": " + (spec?.token.value ?? "missing package");
315
+ return { present: true, command, matcher, currentForm: shapeOk && matcherOk && pinOk, reason };
293
316
  }
294
317
  /**
295
318
  * Doctor's check-5 twin of checkSessionStartHook for the continuity pair —
@@ -321,6 +344,25 @@ export function checkContinuityCaptureHooks(homeDir, settingsPath) {
321
344
  state = "stale";
322
345
  return { path, postToolUse, stop, state };
323
346
  }
347
+ /**
348
+ * Advice uses the same decision as the continuity writer, for both events.
349
+ * Include an absent sibling: an unreadable CLI version also refuses additions.
350
+ * Only the execution banner becomes an advice label; the writer's reason stays.
351
+ */
352
+ export function continuityWriteBlockers(report) {
353
+ const blockers = [];
354
+ for (const [event, entry] of [
355
+ ["PostToolUse", report.postToolUse],
356
+ ["Stop", report.stop],
357
+ ]) {
358
+ const label = `${event} continuity capture hook`;
359
+ const decision = decideContinuityWrite(entry.present ? entry.command ?? "" : null, label);
360
+ if (decision.action !== "write") {
361
+ blockers.push((decision.line ?? `${label}: ${decision.action}`).replace(": holding — ", ": held — "));
362
+ }
363
+ }
364
+ return blockers;
365
+ }
324
366
  /**
325
367
  * The never-lower decision for ONE continuity event's entry, in
326
368
  * continuity-preserve mode (flair#1778 2c-i-a3).
@@ -337,17 +379,21 @@ export function checkContinuityCaptureHooks(homeDir, settingsPath) {
337
379
  * never repins a BEHIND entry UP; it repairs shape only.
338
380
  */
339
381
  function decideContinuityWrite(existingCommand, entryLabel) {
382
+ // No package reference means a shape repair, not an unreadable pin (#1819).
383
+ // Keep the unknown sentinel for package-bearing commands whose argument we
384
+ // cannot locate safely; never decode the whole command as a pin (#1848).
385
+ const pinText = continuityPackageArgument(existingCommand);
340
386
  const decision = decidePinWrite({
341
387
  pkg: FLAIR_MCP_PACKAGE,
342
388
  entry: entryLabel,
343
- existingText: existingCommand,
389
+ existingText: pinText,
344
390
  runningVersion: flairCliVersion(),
345
391
  });
346
392
  if (decision.action !== "write")
347
393
  return decision;
348
394
  if (existingCommand === null)
349
395
  return decision; // absent → provision at the running CLI
350
- const spec = decodeWiringSpec(existingCommand, FLAIR_MCP_PACKAGE);
396
+ const spec = decodeWiringSpec(pinText ?? "", FLAIR_MCP_PACKAGE);
351
397
  if (isComparableWiringPin(spec))
352
398
  return { action: "write", pin: wiringPinString(spec), line: null };
353
399
  return { action: "write", pin: null, line: null }; // unpinned → repair, stay unpinned
@@ -1337,7 +1383,7 @@ export function upgradeSessionStartHookCommand(homeDir, settingsPath) {
1337
1383
  const decision = decidePinWrite({
1338
1384
  pkg: FLAIR_MCP_PACKAGE,
1339
1385
  entry: `SessionStart hook in ${path}`,
1340
- existingText: hook.command,
1386
+ existingText: FLAIR_MCP_PACKAGE, // The matched legacy form is unpinned.
1341
1387
  runningVersion: flairCliVersion(),
1342
1388
  });
1343
1389
  if (decision.action !== "write") {