@tpsdev-ai/flair 0.56.0 → 0.57.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 (63) hide show
  1. package/README.md +16 -17
  2. package/dist/build-info.json +3 -3
  3. package/dist/cli.js +115 -14
  4. package/dist/commands/agent.js +22 -15
  5. package/dist/commands/bridge.js +40 -3
  6. package/dist/commands/doctor.js +52 -0
  7. package/dist/commands/federation.js +263 -37
  8. package/dist/commands/init.js +29 -4
  9. package/dist/lib/auth-resolve.js +46 -0
  10. package/dist/lib/instance-identity-row.js +580 -0
  11. package/dist/lib/redact-token-id.js +197 -0
  12. package/dist/resources/AgentSeed.js +4 -1
  13. package/dist/resources/Asset.js +3 -11
  14. package/dist/resources/Credential.js +4 -10
  15. package/dist/resources/Federation.js +232 -78
  16. package/dist/resources/Integration.js +8 -32
  17. package/dist/resources/Memory.js +58 -16
  18. package/dist/resources/MemoryBootstrap.js +19 -12
  19. package/dist/resources/MemoryCandidate.js +3 -11
  20. package/dist/resources/MemoryDedupStats.js +1 -1
  21. package/dist/resources/MemoryFeed.js +10 -2
  22. package/dist/resources/MemoryGrant.js +19 -40
  23. package/dist/resources/MemoryUsage.js +7 -20
  24. package/dist/resources/Relationship.js +3 -11
  25. package/dist/resources/SemanticSearch.js +25 -13
  26. package/dist/resources/auth-middleware.js +32 -5
  27. package/dist/resources/bm25.js +13 -14
  28. package/dist/resources/federation-cleanup.js +289 -51
  29. package/dist/resources/health.js +48 -8
  30. package/dist/resources/in-process-api.js +2 -1
  31. package/dist/resources/instance-create-lock.js +363 -0
  32. package/dist/resources/instance-identity-rows.js +43 -0
  33. package/dist/resources/instance-identity.js +94 -10
  34. package/dist/resources/mcp-handler.js +9 -1
  35. package/dist/resources/mcp-tool-arguments.js +83 -0
  36. package/dist/resources/mcp-tools.js +4 -5
  37. package/dist/resources/memory-visibility.js +10 -7
  38. package/dist/resources/rate-limit.js +6 -4
  39. package/dist/resources/record-type-kit.js +47 -23
  40. package/dist/resources/search-readiness.js +7 -1
  41. package/dist/resources/semantic-retrieval-core.js +98 -3
  42. package/dist/resources/table-helpers.js +33 -0
  43. package/dist/resources/tool-descriptors/index.js +2 -2
  44. package/dist/src/lib/instance-identity-row.js +580 -0
  45. package/dist/src/lib/redact-token-id.js +197 -0
  46. package/docs/api-reference.md +1 -1
  47. package/docs/auth.md +5 -5
  48. package/docs/claude-code.md +5 -6
  49. package/docs/deploying-on-fabric.md +6 -3
  50. package/docs/embedding-in-a-harper-app.md +3 -3
  51. package/docs/federation.md +16 -9
  52. package/docs/hosted-on-fabric.md +4 -3
  53. package/docs/integrations.md +24 -15
  54. package/docs/mcp-clients.md +16 -12
  55. package/docs/n8n.md +8 -8
  56. package/docs/notes/mcp-oauth-model2.md +12 -17
  57. package/docs/openclaw.md +29 -28
  58. package/docs/spoke-bringup.md +14 -11
  59. package/docs/standalone-local.md +2 -2
  60. package/docs/supply-chain-policy.md +21 -8
  61. package/docs/system-requirements.md +1 -1
  62. package/docs/upgrade.md +2 -2
  63. package/package.json +1 -1
@@ -5,9 +5,11 @@ import { keystore, keyPath as keystoreKeyPath } from "../keystore.js";
5
5
  import * as render from "../render.js";
6
6
  import { runFederationVerify } from "../federation-verify.js";
7
7
  import { resolveHubPeerIdentity } from "../lib/federation-pair-identity.js";
8
+ import { redactTokenMessage } from "../lib/redact-token-id.js";
8
9
  import { rewriteFederationPairHubAccessError, rewriteFederationPairLocalAccessError, } from "../lib/federation-pair-access.js";
9
- import { defaultAdminPassPath, isLocalBase, resolveAdminUser, } from "../lib/auth-resolve.js";
10
+ import { defaultAdminPassPath, isLocalBase, resolveAdminPassFromSources, resolveAdminUser, ADMIN_PASS_FILE_FLAG, ADMIN_PASS_FILE_HELP, ADMIN_PASS_HELP, } from "../lib/auth-resolve.js";
10
11
  import { DEFAULT_INTERVAL_SECONDS as FEDERATION_SYNC_DEFAULT_INTERVAL } from "../federation/scheduler.js";
12
+ import { decideInstancePrune, formatInstanceRow, INSTANCE_ROW_PRUNE_REMEDY, prunePeerWarningLines, readInstanceRows, pruneInstanceRows, writeConfirmed, } from "../lib/instance-identity-row.js";
11
13
  let cli;
12
14
  /** Bind shared CLI helpers. cli.ts calls this immediately before register(program). */
13
15
  export function bindCli(fns) {
@@ -31,6 +33,34 @@ function resolveOpsPort(opts) {
31
33
  function applyAdminPassFile(opts) {
32
34
  cli.applyAdminPassFile(opts);
33
35
  }
36
+ /** `federation token` / `federation pair` credential flags (flair#1873).
37
+ * The flag/help strings live in auth-resolve.ts next to the resolver, shared
38
+ * with every sibling command's credential options (flair#1910). */
39
+ /**
40
+ * Resolve `federation token`/`pair`'s admin password through the SAME reader
41
+ * `flair backup` uses (`readAdminPassFileSecure`), with the precedence the
42
+ * usage text states: an explicit `--admin-pass-file` or `--admin-pass` over
43
+ * `FLAIR_ADMIN_PASS`; combining the file and the flag is a usage error. The resolved value is written back to
44
+ * `opts.adminPass`, the slot the ops preflight and `loadInstanceSecretKey`
45
+ * read — mirroring `applyAdminPassFile` for the sibling commands. Never prints
46
+ * the value.
47
+ */
48
+ function resolveFederationAdminPass(opts, envPass) {
49
+ try {
50
+ const pass = resolveAdminPassFromSources({
51
+ adminPassFile: opts.adminPassFile,
52
+ adminPass: opts.adminPass,
53
+ envPass,
54
+ });
55
+ if (pass)
56
+ opts.adminPass = pass;
57
+ return pass;
58
+ }
59
+ catch (err) {
60
+ console.error(`Error: ${err.message}`);
61
+ process.exit(1);
62
+ }
63
+ }
34
64
  function addSharedCredentialOptions(cmd) {
35
65
  return cli.addSharedCredentialOptions(cmd);
36
66
  }
@@ -151,6 +181,66 @@ function fetchErrorLabel(err) {
151
181
  function redactMessage(text) {
152
182
  return text.replace(/\/\/[^/@\s]+@/g, "//");
153
183
  }
184
+ /**
185
+ * The one line `flair federation token` prints about its PairingToken rollback.
186
+ *
187
+ * A rollback is only real if Harper CONFIRMS the delete. A `delete` answers 200
188
+ * even when it removes nothing, naming what it removed in `deleted_hashes` and a
189
+ * record it did NOT remove in `skipped_hashes`; a body that names no ids at all
190
+ * is also not a confirmation. One rule, shared with the identity-row writes and
191
+ * the cleanup sweep — `writeConfirmed` (flair#1899). A confirmed rollback is
192
+ * reported as such; anything else is reported as a FAILED rollback that names
193
+ * the token by its 8-character prefix only.
194
+ */
195
+ export function pairingTokenRollbackLine(result, tokenId) {
196
+ const prefix = tokenId.slice(0, 8);
197
+ if (writeConfirmed(result, "deleted_hashes", tokenId)) {
198
+ // Only the delete is claimed. A LOST add_user response does not establish
199
+ // that the user was not created, so the line says nothing about it.
200
+ return `Rolled back pairing token ${prefix}…: Harper confirmed it was deleted.`;
201
+ }
202
+ const body = (result ?? {});
203
+ const why = body.error !== undefined && body.error !== null
204
+ ? `Harper reported: ${redactTokenMessage(String(body.error), [tokenId])}`
205
+ : Array.isArray(body.skipped_hashes) && body.skipped_hashes.map(String).includes(tokenId)
206
+ ? "Harper named it in skipped_hashes"
207
+ : "Harper's result did not name it as deleted";
208
+ // An unconfirmed delete is NOT proof the row survived: the response may have
209
+ // been lost. Report what is known (the delete is unconfirmed), not the state
210
+ // we cannot see.
211
+ return (`Pairing token rollback FAILED: Harper did not confirm that token ${prefix}… was deleted — ${why}. ` +
212
+ `A lost response does not mean the row survived; check the PairingToken table.`);
213
+ }
214
+ /**
215
+ * Delete the PairingToken a failed `flair federation token` persisted, and
216
+ * return the one-line outcome for the caller to print.
217
+ *
218
+ * Never throws: the caller is already failing, and its ORIGINAL error is what
219
+ * must reach the exit code, so a rollback that itself fails is reported, not
220
+ * raised. Sends `hash_values` (a list) — the field Harper's delete schema
221
+ * REQUIRES; the singular `hash_value` is refused with a 400, which left the
222
+ * token in the table so it outlived the user it was minted for (flair#1895).
223
+ */
224
+ export async function rollbackPairingToken(opsEndpoint, auth, tokenId) {
225
+ try {
226
+ const res = await fetch(`${opsEndpoint}/`, {
227
+ method: "POST",
228
+ headers: { "Content-Type": "application/json", Authorization: auth },
229
+ body: JSON.stringify({
230
+ operation: "delete",
231
+ database: "flair",
232
+ table: "PairingToken",
233
+ hash_values: [tokenId],
234
+ }),
235
+ signal: AbortSignal.timeout(10_000),
236
+ });
237
+ const result = await res.json().catch(() => null);
238
+ return pairingTokenRollbackLine(result, tokenId);
239
+ }
240
+ catch (err) {
241
+ return pairingTokenRollbackLine({ error: String(err?.message ?? err) }, tokenId);
242
+ }
243
+ }
154
244
  /**
155
245
  * Whether a Harper permission object can WRITE the Peer table: a super_user, or
156
246
  * an explicit flair.Peer insert+update grant. A restrictive `operations`
@@ -1166,7 +1256,8 @@ export function register(program) {
1166
1256
  .command("pair <hub-url>")
1167
1257
  .description("Pair this spoke with a hub instance")
1168
1258
  .option("--port <port>", "Harper HTTP port")
1169
- .option("--admin-pass <pass>", "Admin password")
1259
+ .option(ADMIN_PASS_FILE_FLAG, ADMIN_PASS_FILE_HELP)
1260
+ .option("--admin-pass <pass>", ADMIN_PASS_HELP)
1170
1261
  .option("--admin-user <name>", "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)")
1171
1262
  .option("--ops-port <port>", "Harper operations API port")
1172
1263
  .option("--token <token>", "One-time pairing token from hub admin (env: FLAIR_PAIRING_TOKEN) [deprecated: use --token-from]")
@@ -1175,6 +1266,12 @@ export function register(program) {
1175
1266
  .option("--ops-target <url>", "Explicit ops API URL (env: FLAIR_OPS_TARGET; bypasses port derivation)")
1176
1267
  .action(async (hubUrl, opts) => {
1177
1268
  const target = resolveTarget(opts);
1269
+ // flair#1873: resolve the SPOKE admin credential FIRST, before any
1270
+ // request. `--admin-pass-file` is read in-process (mode 0600 enforced),
1271
+ // so a refusal sends nothing anywhere; combining it with --admin-pass is
1272
+ // a usage error. The value is written back into opts.adminPass, which the
1273
+ // ops preflight and the signing-key fallback below both read.
1274
+ const adminPass = resolveFederationAdminPass(opts, process.env.FLAIR_ADMIN_PASS ?? process.env.HDB_ADMIN_PASSWORD);
1178
1275
  // One URL for the identity GET and the named error. resolveBaseUrl
1179
1276
  // honors --target / FLAIR_TARGET / FLAIR_URL / --port — the same host
1180
1277
  // the GET actually probes (do not cite resolveBaseUrl only in the
@@ -1189,7 +1286,15 @@ export function register(program) {
1189
1286
  // Rewrite Harper's raw AccessViolation into a named role/grant error.
1190
1287
  let instance;
1191
1288
  try {
1192
- instance = await api("GET", "/FederationInstance", undefined, { baseUrl: identityUrl });
1289
+ // flair#1873: hand the identity GET the credential the operator
1290
+ // provided (--admin-pass-file / --admin-pass), not only baseUrl — a
1291
+ // protected instance refuses this allowAdmin GET before pair ever
1292
+ // reaches the authenticated ops preflight.
1293
+ instance = await api("GET", "/FederationInstance", undefined, {
1294
+ baseUrl: identityUrl,
1295
+ explicitAdminPass: opts.adminPass,
1296
+ adminUser: opts.adminUser,
1297
+ });
1193
1298
  }
1194
1299
  catch (err) {
1195
1300
  throw rewriteFederationPairLocalAccessError(err, {
@@ -1227,15 +1332,15 @@ export function register(program) {
1227
1332
  console.error("Error: --token or --token-from is required. Ask the hub admin to run 'flair federation token' and provide the token.");
1228
1333
  process.exit(1);
1229
1334
  }
1230
- // flair#1875: resolve the SPOKE admin credential and preflight it BEFORE
1231
- // any request that consumes the one-time token. The hub's FederationPair
1232
- // burns the token, so a missing or refused admin credential must be
1233
- // caught here — while the token is still valid — not after the hub has
1234
- // already paired us. Zero hub requests happen on this path.
1235
- const adminPass = opts.adminPass ?? process.env.FLAIR_ADMIN_PASS ?? process.env.HDB_ADMIN_PASSWORD ?? "";
1335
+ // flair#1875: the SPOKE admin credential was resolved at the top of this
1336
+ // action (flair#1873) and preflighted BEFORE any request that consumes the
1337
+ // one-time token. The hub's FederationPair burns the token, so a missing or
1338
+ // refused admin credential must be caught here — while the token is still
1339
+ // valid — not after the hub has already paired us. Zero hub requests happen
1340
+ // on this path.
1236
1341
  if (!adminPass) {
1237
1342
  console.error("Error: refusing to contact the hub: the local hub-peer record needs admin auth to write — " +
1238
- "pass --admin-pass, or set FLAIR_ADMIN_PASS / HDB_ADMIN_PASSWORD (the SPOKE admin password), then re-run pair. " +
1343
+ "pass --admin-pass-file (preferred), --admin-pass, or set FLAIR_ADMIN_PASS / HDB_ADMIN_PASSWORD (the SPOKE admin password), then re-run pair. " +
1239
1344
  NOTHING_SENT_TO_HUB);
1240
1345
  process.exit(1);
1241
1346
  }
@@ -1399,7 +1504,8 @@ export function register(program) {
1399
1504
  .command("token")
1400
1505
  .description("Generate a one-time pairing token (run on the hub)")
1401
1506
  .option("--port <port>", "Harper HTTP port")
1402
- .option("--admin-pass <pass>", "Admin password")
1507
+ .option(ADMIN_PASS_FILE_FLAG, ADMIN_PASS_FILE_HELP)
1508
+ .option("--admin-pass <pass>", ADMIN_PASS_HELP)
1403
1509
  .option("--admin-user <name>", "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)")
1404
1510
  .option("--ops-port <port>", "Harper operations API port")
1405
1511
  .option("--ttl <minutes>", "Token TTL in minutes (default: 60)", "60")
@@ -1414,7 +1520,10 @@ export function register(program) {
1414
1520
  const ttlMinutes = parseInt(opts.ttl, 10) || 60;
1415
1521
  const expiresAt = new Date(Date.now() + ttlMinutes * 60 * 1000).toISOString();
1416
1522
  const opsEndpoint = resolveEffectiveOpsUrl(opts) ?? `http://127.0.0.1:${resolveOpsPort(opts)}`;
1417
- const adminPass = opts.adminPass ?? process.env.FLAIR_ADMIN_PASS ?? "";
1523
+ // flair#1873: read --admin-pass-file in-process (mode 0600 enforced);
1524
+ // an explicit --admin-pass-file or --admin-pass overrides FLAIR_ADMIN_PASS,
1525
+ // and file+flag is a usage error.
1526
+ const adminPass = resolveFederationAdminPass(opts, process.env.FLAIR_ADMIN_PASS);
1418
1527
  const auth = `Basic ${Buffer.from(`${resolveAdminUser(opts.adminUser)}:${adminPass}`).toString("base64")}`;
1419
1528
  // 1. Persist the PairingToken record
1420
1529
  const opsRes = await fetch(`${opsEndpoint}/`, {
@@ -1432,7 +1541,10 @@ export function register(program) {
1432
1541
  });
1433
1542
  if (!opsRes.ok) {
1434
1543
  const detail = await opsRes.text().catch(() => "");
1435
- throw new Error(`Failed to persist pairing token (${opsRes.status}): ${detail || "no body"}`);
1544
+ // Harper's error body can echo the upsert's record, whose `id` IS the
1545
+ // pairing token. Cut the token id to its prefix before it reaches the
1546
+ // thrown message, which this command's catch prints (flair#1902).
1547
+ throw new Error(`Failed to persist pairing token (${opsRes.status}): ${redactTokenMessage(detail || "no body", [token])}`);
1436
1548
  }
1437
1549
  // 2. Create bootstrap user for this token
1438
1550
  const bootstrapPassword = randomBytes(32).toString("base64url");
@@ -1453,33 +1565,17 @@ export function register(program) {
1453
1565
  });
1454
1566
  }
1455
1567
  catch (err) {
1456
- // Network failure creating bootstrap user — roll back PairingToken
1457
- await fetch(`${opsEndpoint}/`, {
1458
- method: "POST",
1459
- headers: { "Content-Type": "application/json", Authorization: auth },
1460
- body: JSON.stringify({
1461
- operation: "delete",
1462
- database: "flair",
1463
- table: "PairingToken",
1464
- hash_value: token,
1465
- }),
1466
- signal: AbortSignal.timeout(10_000),
1467
- }).catch(() => { });
1568
+ // Network failure creating bootstrap user — roll back PairingToken. The
1569
+ // rollback outcome is an ADDITIONAL line; the command still exits on the
1570
+ // original (network) failure below.
1571
+ console.error(await rollbackPairingToken(opsEndpoint, auth, token));
1468
1572
  throw new Error(`Failed to create bootstrap user (network): ${err.message}`);
1469
1573
  }
1470
1574
  if (!addUserRes.ok) {
1471
- // add_user failed — roll back PairingToken so the two stay in sync
1472
- await fetch(`${opsEndpoint}/`, {
1473
- method: "POST",
1474
- headers: { "Content-Type": "application/json", Authorization: auth },
1475
- body: JSON.stringify({
1476
- operation: "delete",
1477
- database: "flair",
1478
- table: "PairingToken",
1479
- hash_value: token,
1480
- }),
1481
- signal: AbortSignal.timeout(10_000),
1482
- }).catch(() => { });
1575
+ // add_user failed — roll back PairingToken so the two stay in sync. The
1576
+ // rollback outcome is an ADDITIONAL line; the command still exits on the
1577
+ // original add_user failure below.
1578
+ console.error(await rollbackPairingToken(opsEndpoint, auth, token));
1483
1579
  const detail = await addUserRes.text().catch(() => "");
1484
1580
  throw new Error(`Failed to create bootstrap user (${addUserRes.status}): ${detail || "no body"}`);
1485
1581
  }
@@ -1753,6 +1849,136 @@ export function register(program) {
1753
1849
  if (errors > 0)
1754
1850
  process.exit(1);
1755
1851
  });
1852
+ // ── flair federation instance — the identity row (flair#1883) ────────────
1853
+ //
1854
+ // A hub's identity is ONE `flair.Instance` row and the pairing-cleanup sweep
1855
+ // reads its role. `GET /FederationInstance` find-or-creates one, `flair init
1856
+ // --remote` used to insert a SECOND, and everything downstream that took "the
1857
+ // first row" then read whichever row the table yielded first. `list` shows the
1858
+ // rows; `prune` gets back to one.
1859
+ const instanceCmd = federation
1860
+ .command("instance")
1861
+ .description("Inspect and repair this instance's federation identity row");
1862
+ /** The ops endpoint these two subcommands read and write. */
1863
+ const instanceOpsEndpoint = (opts) => {
1864
+ // --admin-pass-file resolves into the same `adminPass` slot the inline flag
1865
+ // uses (the shared idiom: the secret stays out of ps and shell history).
1866
+ applyAdminPassFile(opts);
1867
+ const opsUrl = resolveEffectiveOpsUrl(opts) ?? `http://127.0.0.1:${resolveOpsPort(opts)}`;
1868
+ const adminPass = opts.adminPass ?? process.env.FLAIR_ADMIN_PASS ?? "";
1869
+ return { opsUrl, credentials: { user: resolveAdminUser(opts.adminUser), pass: adminPass } };
1870
+ };
1871
+ addSharedCredentialOptions(instanceCmd.command("list"))
1872
+ .description("List every Instance row on this instance (a hub should have exactly one)")
1873
+ .option("--port <port>", "Harper HTTP port")
1874
+ .option("--ops-port <port>", "Harper operations API port")
1875
+ .option("--target <url>", "Remote Flair URL (env: FLAIR_TARGET)")
1876
+ .option("--ops-target <url>", "Explicit ops API URL (env: FLAIR_OPS_TARGET)")
1877
+ .option("--json", "Emit JSON")
1878
+ .action(async (opts) => {
1879
+ let rows;
1880
+ try {
1881
+ rows = await readInstanceRows(instanceOpsEndpoint(opts));
1882
+ }
1883
+ catch (err) {
1884
+ console.error(`Error: ${err?.message ?? err}`);
1885
+ process.exit(1);
1886
+ }
1887
+ if (opts.json) {
1888
+ console.log(JSON.stringify({ rows }, null, 2));
1889
+ return;
1890
+ }
1891
+ if (rows.length === 0) {
1892
+ console.log("No Instance rows. This instance has no federation identity yet (it is created on the first `GET /FederationInstance`, or by `flair init --remote`).");
1893
+ return;
1894
+ }
1895
+ console.log(`${rows.length} Instance row(s):`);
1896
+ for (const row of rows)
1897
+ console.log(` ${formatInstanceRow(row)}`);
1898
+ if (rows.length > 1) {
1899
+ console.log(`\nMore than one row means there is no canonical identity. Keep one and delete the rest:`);
1900
+ console.log(` ${INSTANCE_ROW_PRUNE_REMEDY}`);
1901
+ }
1902
+ });
1903
+ addSharedCredentialOptions(instanceCmd.command("prune"))
1904
+ .description("Delete every Instance row except --keep <id> (dry-run by default)")
1905
+ .option("--keep <id>", "The Instance row to keep; the rest are deleted")
1906
+ .option("--apply", "Actually delete (default is dry-run)")
1907
+ .option("--port <port>", "Harper HTTP port")
1908
+ .option("--ops-port <port>", "Harper operations API port")
1909
+ .option("--target <url>", "Remote Flair URL (env: FLAIR_TARGET)")
1910
+ .option("--ops-target <url>", "Explicit ops API URL (env: FLAIR_OPS_TARGET)")
1911
+ .action(async (opts) => {
1912
+ const endpoint = instanceOpsEndpoint(opts);
1913
+ if (!opts.keep) {
1914
+ // No --keep: show what is there. Never guess which row is the identity —
1915
+ // the id and key peers know is the operator's fact, not this command's.
1916
+ try {
1917
+ const rows = await readInstanceRows(endpoint);
1918
+ if (rows.length === 0) {
1919
+ console.log("No Instance rows — nothing to prune.");
1920
+ return;
1921
+ }
1922
+ console.log(`${rows.length} Instance row(s):`);
1923
+ for (const row of rows)
1924
+ console.log(` ${formatInstanceRow(row)}`);
1925
+ console.error(`\nError: --keep <id> is required: name the row to keep.`);
1926
+ }
1927
+ catch (err) {
1928
+ console.error(`Error: ${err?.message ?? err}`);
1929
+ }
1930
+ process.exit(1);
1931
+ }
1932
+ let decision;
1933
+ try {
1934
+ decision = decideInstancePrune(await readInstanceRows(endpoint), opts.keep);
1935
+ }
1936
+ catch (err) {
1937
+ console.error(`Error: ${err?.message ?? err}`);
1938
+ process.exit(1);
1939
+ }
1940
+ if (decision.kind === "unknown-id") {
1941
+ console.error(`Error: --keep ${opts.keep} names no Instance row on this instance. Rows present:`);
1942
+ for (const row of decision.rows)
1943
+ console.error(` ${formatInstanceRow(row)}`);
1944
+ process.exit(1);
1945
+ }
1946
+ if (decision.kind === "nothing") {
1947
+ console.log(`Nothing to prune — --keep names the only Instance row this instance has.`);
1948
+ return;
1949
+ }
1950
+ // What a prune must tell the operator (flair#1883 round 3; tense
1951
+ // corrected in round 4): a paired peer pinned this instance's identity from
1952
+ // the `POST /FederationPair` response, which — while the table held several
1953
+ // rows — was whichever row the search yielded first. A peer that paired in
1954
+ // that state may have pinned ANY of the rows being deleted, and which one
1955
+ // it pinned is NOT determinable here, so the warning does not name one. (The
1956
+ // response is a 409 now, so this is history, not the current behaviour — but
1957
+ // those peers are still out there.) A peer paired with a deleted identity
1958
+ // must re-pair.
1959
+ const peerWarnings = prunePeerWarningLines({ drop: decision.drop });
1960
+ if (!opts.apply) {
1961
+ console.log(`── flair federation instance prune — dry-run (use --apply to delete) ──`);
1962
+ console.log(`Keeping ${formatInstanceRow(decision.keep)}`);
1963
+ console.log(`Would delete ${decision.drop.length} row(s):`);
1964
+ for (const row of decision.drop)
1965
+ console.log(` ${formatInstanceRow(row)}`);
1966
+ for (const line of peerWarnings)
1967
+ console.log(line);
1968
+ return;
1969
+ }
1970
+ try {
1971
+ const { dropped } = await pruneInstanceRows(endpoint, opts.keep);
1972
+ console.log(`Kept ${decision.keep.id}; deleted ${dropped.length} row(s): ${dropped.join(", ")}`);
1973
+ for (const line of peerWarnings)
1974
+ console.log(line);
1975
+ console.log("Re-run `flair init --remote` to set the kept row's role to hub.");
1976
+ }
1977
+ catch (err) {
1978
+ console.error(`Error: ${err?.message ?? err}`);
1979
+ process.exit(1);
1980
+ }
1981
+ });
1756
1982
  // `flair federation verify` — end-to-end roundtrip: write a tagged memory
1757
1983
  // locally, push it (bring-up has no daemon yet), probe peers for the tag.
1758
1984
  // Same class as fleet-verify / flair#988: 401/403 and unreachable are
@@ -105,6 +105,9 @@ function resolveTarget(...args) {
105
105
  function runSoulWizard(...args) {
106
106
  return cli.runSoulWizard(...args);
107
107
  }
108
+ function reconcileFederationInstanceViaOpsApi(...args) {
109
+ return cli.reconcileFederationInstanceViaOpsApi(...args);
110
+ }
108
111
  function seedAgentViaOpsApi(...args) {
109
112
  return cli.seedAgentViaOpsApi(...args);
110
113
  }
@@ -287,16 +290,38 @@ export function register(program) {
287
290
  else {
288
291
  console.log("No --agent-id provided -- skipping agent registration");
289
292
  }
290
- // Write FederationInstance row if --remote (hub role)
293
+ // Reconcile the federation Instance identity row if --remote (hub role).
294
+ // flair#1883: this used to INSERT a row with a fresh random id on every
295
+ // run, so a hub that had already answered a `GET /FederationInstance`
296
+ // (which find-or-creates a `spoke` row) ended up with TWO rows and no
297
+ // canonical identity. Reconciling keeps the row peers already know.
291
298
  if (role) {
292
299
  if (!pubKeyB64url) {
293
300
  const kp = nacl.sign.keyPair();
294
301
  pubKeyB64url = b64url(kp.publicKey);
295
302
  }
296
303
  instanceId = randomUUID();
297
- console.log(`Writing federation Instance (role=${role}) via ops API...`);
298
- await seedFederationInstanceViaOpsApi(opsUrl, instanceId, pubKeyB64url, role, adminUser, flairAdminPass);
299
- console.log(`Federation Instance created: ${instanceId} (${role}) ✓`);
304
+ console.log(`Reconciling federation Instance (role=${role}) via ops API...`);
305
+ let reconciled;
306
+ try {
307
+ reconciled = await reconcileFederationInstanceViaOpsApi(opsUrl, { instanceId, publicKey: pubKeyB64url }, adminUser, flairAdminPass);
308
+ }
309
+ catch (err) {
310
+ // A refusal (two rows) or an unreachable ops API — both are this
311
+ // command failing, and both already name what to do.
312
+ console.error(`Error: ${err?.message ?? err}`);
313
+ process.exit(1);
314
+ }
315
+ instanceId = reconciled.id;
316
+ if (reconciled.action === "created") {
317
+ console.log(`Federation Instance created: ${reconciled.id} (role=${role}) ✓`);
318
+ }
319
+ else if (reconciled.action === "updated") {
320
+ console.log(`Federation Instance reconciled: ${reconciled.id} is now role=${role} (id and key kept) ✓`);
321
+ }
322
+ else {
323
+ console.log(`Federation Instance already role=${role}: ${reconciled.id} — no change ✓`);
324
+ }
300
325
  }
301
326
  // Verify connectivity
302
327
  if (didProvision) {
@@ -128,9 +128,55 @@ export function readSecretFileSecure(path, flagName) {
128
128
  export function readAdminPassFileSecure(path) {
129
129
  return readSecretFileSecure(path, "--admin-pass-file");
130
130
  }
131
+ /** Thrown by `resolveAdminPassFromSources` when two credential sources are given at once. */
132
+ export class AdminPassSourceError extends Error {
133
+ }
134
+ /**
135
+ * Resolve an admin password from the credential sources a command exposes, in
136
+ * the precedence its usage text states: an explicit option — `--admin-pass-file`
137
+ * or `--admin-pass` (the form the help warns against) — over the ambient
138
+ * `FLAIR_ADMIN_PASS`/`HDB_ADMIN_PASSWORD`. Explicit beats ambient, the same rule
139
+ * `resolveLocalAdminPass` applies to `--admin-pass`, so a value the operator
140
+ * typed is never silently replaced by one the shell happened to carry.
141
+ * Supplying BOTH `--admin-pass-file` and `--admin-pass` is refused: two explicit
142
+ * sources at once is ambiguous, and one of them is the discouraged argv form. The file is read through `readAdminPassFileSecure` — the same
143
+ * reader `flair backup` uses — so a group- or world-readable file is refused
144
+ * with a message naming the path and its mode.
145
+ *
146
+ * Returns "" when no source is set, so the caller owns its own "credential
147
+ * required" message; throws `AdminPassSourceError` on a conflict, or
148
+ * `readAdminPassFileSecure`'s error when the file is missing, empty or too
149
+ * open. Neither message carries the password value.
150
+ */
151
+ export function resolveAdminPassFromSources(input) {
152
+ const { adminPassFile, adminPass, envPass } = input;
153
+ if (adminPassFile && adminPass) {
154
+ throw new AdminPassSourceError("--admin-pass and --admin-pass-file cannot be combined; pass exactly one. " +
155
+ "Prefer --admin-pass-file: it keeps the password out of shell history and the process list.");
156
+ }
157
+ if (adminPassFile)
158
+ return readAdminPassFileSecure(adminPassFile);
159
+ if (adminPass)
160
+ return adminPass;
161
+ return envPass ?? "";
162
+ }
131
163
  export function defaultAdminPassPath() {
132
164
  return join(resolveHome(), ".flair", "admin-pass");
133
165
  }
166
+ // ─── The ONE admin-password option surface (flair#1910) ─────────────────────
167
+ //
168
+ // Every command that declares the admin-password pair declares the SAME two
169
+ // flags with the SAME help, so the file form is recommended identically
170
+ // everywhere and the argv form always carries its leak warning. Defined here,
171
+ // next to the resolver both forms feed (`resolveAdminPassFromSources`), so the
172
+ // two surfaces cannot drift between `federation token`/`pair` (which declared
173
+ // these strings locally, flair#1873) and the shared credential-option helper
174
+ // every sibling command uses.
175
+ export const ADMIN_PASS_FILE_FLAG = "--admin-pass-file <path>";
176
+ export const ADMIN_PASS_FILE_HELP = "Read the admin password from an owner-only file (mode 0600 enforced), keeping it out of shell history and the process list. " +
177
+ "An explicit option (this or --admin-pass) overrides FLAIR_ADMIN_PASS; combining it with --admin-pass is a usage error.";
178
+ export const ADMIN_PASS_FLAG = "--admin-pass <pass>";
179
+ export const ADMIN_PASS_HELP = "Admin password (legacy: lands in shell history and the process list — prefer --admin-pass-file or FLAIR_ADMIN_PASS)";
134
180
  /** The admin username Harper's bootstrap creates and every Basic-auth path
135
181
  * historically hardcoded. Kept as the default; overridable per call via
136
182
  * `resolveAdminUser` (flair#1345). */