@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
@@ -5,9 +5,12 @@ 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 { FEDERATION_MEMORY_SELECT } from "../lib/federation-memory-attributes.js";
13
+ import { decideInstancePrune, formatInstanceRow, INSTANCE_ROW_PRUNE_REMEDY, prunePeerWarningLines, readInstanceRows, pruneInstanceRows, writeConfirmed, } from "../lib/instance-identity-row.js";
11
14
  let cli;
12
15
  /** Bind shared CLI helpers. cli.ts calls this immediately before register(program). */
13
16
  export function bindCli(fns) {
@@ -31,6 +34,34 @@ function resolveOpsPort(opts) {
31
34
  function applyAdminPassFile(opts) {
32
35
  cli.applyAdminPassFile(opts);
33
36
  }
37
+ /** `federation token` / `federation pair` credential flags (flair#1873).
38
+ * The flag/help strings live in auth-resolve.ts next to the resolver, shared
39
+ * with every sibling command's credential options (flair#1910). */
40
+ /**
41
+ * Resolve `federation token`/`pair`'s admin password through the SAME reader
42
+ * `flair backup` uses (`readAdminPassFileSecure`), with the precedence the
43
+ * usage text states: an explicit `--admin-pass-file` or `--admin-pass` over
44
+ * `FLAIR_ADMIN_PASS`; combining the file and the flag is a usage error. The resolved value is written back to
45
+ * `opts.adminPass`, the slot the ops preflight and `loadInstanceSecretKey`
46
+ * read — mirroring `applyAdminPassFile` for the sibling commands. Never prints
47
+ * the value.
48
+ */
49
+ function resolveFederationAdminPass(opts, envPass) {
50
+ try {
51
+ const pass = resolveAdminPassFromSources({
52
+ adminPassFile: opts.adminPassFile,
53
+ adminPass: opts.adminPass,
54
+ envPass,
55
+ });
56
+ if (pass)
57
+ opts.adminPass = pass;
58
+ return pass;
59
+ }
60
+ catch (err) {
61
+ console.error(`Error: ${err.message}`);
62
+ process.exit(1);
63
+ }
64
+ }
34
65
  function addSharedCredentialOptions(cmd) {
35
66
  return cli.addSharedCredentialOptions(cmd);
36
67
  }
@@ -151,6 +182,66 @@ function fetchErrorLabel(err) {
151
182
  function redactMessage(text) {
152
183
  return text.replace(/\/\/[^/@\s]+@/g, "//");
153
184
  }
185
+ /**
186
+ * The one line `flair federation token` prints about its PairingToken rollback.
187
+ *
188
+ * A rollback is only real if Harper CONFIRMS the delete. A `delete` answers 200
189
+ * even when it removes nothing, naming what it removed in `deleted_hashes` and a
190
+ * record it did NOT remove in `skipped_hashes`; a body that names no ids at all
191
+ * is also not a confirmation. One rule, shared with the identity-row writes and
192
+ * the cleanup sweep — `writeConfirmed` (flair#1899). A confirmed rollback is
193
+ * reported as such; anything else is reported as a FAILED rollback that names
194
+ * the token by its 8-character prefix only.
195
+ */
196
+ export function pairingTokenRollbackLine(result, tokenId) {
197
+ const prefix = tokenId.slice(0, 8);
198
+ if (writeConfirmed(result, "deleted_hashes", tokenId)) {
199
+ // Only the delete is claimed. A LOST add_user response does not establish
200
+ // that the user was not created, so the line says nothing about it.
201
+ return `Rolled back pairing token ${prefix}…: Harper confirmed it was deleted.`;
202
+ }
203
+ const body = (result ?? {});
204
+ const why = body.error !== undefined && body.error !== null
205
+ ? `Harper reported: ${redactTokenMessage(String(body.error), [tokenId])}`
206
+ : Array.isArray(body.skipped_hashes) && body.skipped_hashes.map(String).includes(tokenId)
207
+ ? "Harper named it in skipped_hashes"
208
+ : "Harper's result did not name it as deleted";
209
+ // An unconfirmed delete is NOT proof the row survived: the response may have
210
+ // been lost. Report what is known (the delete is unconfirmed), not the state
211
+ // we cannot see.
212
+ return (`Pairing token rollback FAILED: Harper did not confirm that token ${prefix}… was deleted — ${why}. ` +
213
+ `A lost response does not mean the row survived; check the PairingToken table.`);
214
+ }
215
+ /**
216
+ * Delete the PairingToken a failed `flair federation token` persisted, and
217
+ * return the one-line outcome for the caller to print.
218
+ *
219
+ * Never throws: the caller is already failing, and its ORIGINAL error is what
220
+ * must reach the exit code, so a rollback that itself fails is reported, not
221
+ * raised. Sends `hash_values` (a list) — the field Harper's delete schema
222
+ * REQUIRES; the singular `hash_value` is refused with a 400, which left the
223
+ * token in the table so it outlived the user it was minted for (flair#1895).
224
+ */
225
+ export async function rollbackPairingToken(opsEndpoint, auth, tokenId) {
226
+ try {
227
+ const res = await fetch(`${opsEndpoint}/`, {
228
+ method: "POST",
229
+ headers: { "Content-Type": "application/json", Authorization: auth },
230
+ body: JSON.stringify({
231
+ operation: "delete",
232
+ database: "flair",
233
+ table: "PairingToken",
234
+ hash_values: [tokenId],
235
+ }),
236
+ signal: AbortSignal.timeout(10_000),
237
+ });
238
+ const result = await res.json().catch(() => null);
239
+ return pairingTokenRollbackLine(result, tokenId);
240
+ }
241
+ catch (err) {
242
+ return pairingTokenRollbackLine({ error: String(err?.message ?? err) }, tokenId);
243
+ }
244
+ }
154
245
  /**
155
246
  * Whether a Harper permission object can WRITE the Peer table: a super_user, or
156
247
  * an explicit flair.Peer insert+update grant. A restrictive `operations`
@@ -587,7 +678,7 @@ export async function runFederationSyncOnce(opts) {
587
678
  res = await fetch(`${opsEndpoint}/`, {
588
679
  method: "POST",
589
680
  headers: { "Content-Type": "application/json", Authorization: auth },
590
- body: JSON.stringify({ operation: "search_by_conditions", schema: "flair", table, operator: "and", conditions: [query], get_attributes: ["*"] }),
681
+ body: JSON.stringify({ operation: "search_by_conditions", schema: "flair", table, operator: "and", conditions: [query], get_attributes: table === "Memory" ? [...FEDERATION_MEMORY_SELECT] : ["*"] }),
591
682
  signal: AbortSignal.timeout(15_000),
592
683
  });
593
684
  }
@@ -1166,7 +1257,8 @@ export function register(program) {
1166
1257
  .command("pair <hub-url>")
1167
1258
  .description("Pair this spoke with a hub instance")
1168
1259
  .option("--port <port>", "Harper HTTP port")
1169
- .option("--admin-pass <pass>", "Admin password")
1260
+ .option(ADMIN_PASS_FILE_FLAG, ADMIN_PASS_FILE_HELP)
1261
+ .option("--admin-pass <pass>", ADMIN_PASS_HELP)
1170
1262
  .option("--admin-user <name>", "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)")
1171
1263
  .option("--ops-port <port>", "Harper operations API port")
1172
1264
  .option("--token <token>", "One-time pairing token from hub admin (env: FLAIR_PAIRING_TOKEN) [deprecated: use --token-from]")
@@ -1175,6 +1267,12 @@ export function register(program) {
1175
1267
  .option("--ops-target <url>", "Explicit ops API URL (env: FLAIR_OPS_TARGET; bypasses port derivation)")
1176
1268
  .action(async (hubUrl, opts) => {
1177
1269
  const target = resolveTarget(opts);
1270
+ // flair#1873: resolve the SPOKE admin credential FIRST, before any
1271
+ // request. `--admin-pass-file` is read in-process (mode 0600 enforced),
1272
+ // so a refusal sends nothing anywhere; combining it with --admin-pass is
1273
+ // a usage error. The value is written back into opts.adminPass, which the
1274
+ // ops preflight and the signing-key fallback below both read.
1275
+ const adminPass = resolveFederationAdminPass(opts, process.env.FLAIR_ADMIN_PASS ?? process.env.HDB_ADMIN_PASSWORD);
1178
1276
  // One URL for the identity GET and the named error. resolveBaseUrl
1179
1277
  // honors --target / FLAIR_TARGET / FLAIR_URL / --port — the same host
1180
1278
  // the GET actually probes (do not cite resolveBaseUrl only in the
@@ -1189,7 +1287,15 @@ export function register(program) {
1189
1287
  // Rewrite Harper's raw AccessViolation into a named role/grant error.
1190
1288
  let instance;
1191
1289
  try {
1192
- instance = await api("GET", "/FederationInstance", undefined, { baseUrl: identityUrl });
1290
+ // flair#1873: hand the identity GET the credential the operator
1291
+ // provided (--admin-pass-file / --admin-pass), not only baseUrl — a
1292
+ // protected instance refuses this allowAdmin GET before pair ever
1293
+ // reaches the authenticated ops preflight.
1294
+ instance = await api("GET", "/FederationInstance", undefined, {
1295
+ baseUrl: identityUrl,
1296
+ explicitAdminPass: opts.adminPass,
1297
+ adminUser: opts.adminUser,
1298
+ });
1193
1299
  }
1194
1300
  catch (err) {
1195
1301
  throw rewriteFederationPairLocalAccessError(err, {
@@ -1227,15 +1333,15 @@ export function register(program) {
1227
1333
  console.error("Error: --token or --token-from is required. Ask the hub admin to run 'flair federation token' and provide the token.");
1228
1334
  process.exit(1);
1229
1335
  }
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 ?? "";
1336
+ // flair#1875: the SPOKE admin credential was resolved at the top of this
1337
+ // action (flair#1873) and preflighted BEFORE any request that consumes the
1338
+ // one-time token. The hub's FederationPair burns the token, so a missing or
1339
+ // refused admin credential must be caught here — while the token is still
1340
+ // valid — not after the hub has already paired us. Zero hub requests happen
1341
+ // on this path.
1236
1342
  if (!adminPass) {
1237
1343
  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. " +
1344
+ "pass --admin-pass-file (preferred), --admin-pass, or set FLAIR_ADMIN_PASS / HDB_ADMIN_PASSWORD (the SPOKE admin password), then re-run pair. " +
1239
1345
  NOTHING_SENT_TO_HUB);
1240
1346
  process.exit(1);
1241
1347
  }
@@ -1399,7 +1505,8 @@ export function register(program) {
1399
1505
  .command("token")
1400
1506
  .description("Generate a one-time pairing token (run on the hub)")
1401
1507
  .option("--port <port>", "Harper HTTP port")
1402
- .option("--admin-pass <pass>", "Admin password")
1508
+ .option(ADMIN_PASS_FILE_FLAG, ADMIN_PASS_FILE_HELP)
1509
+ .option("--admin-pass <pass>", ADMIN_PASS_HELP)
1403
1510
  .option("--admin-user <name>", "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)")
1404
1511
  .option("--ops-port <port>", "Harper operations API port")
1405
1512
  .option("--ttl <minutes>", "Token TTL in minutes (default: 60)", "60")
@@ -1414,7 +1521,10 @@ export function register(program) {
1414
1521
  const ttlMinutes = parseInt(opts.ttl, 10) || 60;
1415
1522
  const expiresAt = new Date(Date.now() + ttlMinutes * 60 * 1000).toISOString();
1416
1523
  const opsEndpoint = resolveEffectiveOpsUrl(opts) ?? `http://127.0.0.1:${resolveOpsPort(opts)}`;
1417
- const adminPass = opts.adminPass ?? process.env.FLAIR_ADMIN_PASS ?? "";
1524
+ // flair#1873: read --admin-pass-file in-process (mode 0600 enforced);
1525
+ // an explicit --admin-pass-file or --admin-pass overrides FLAIR_ADMIN_PASS,
1526
+ // and file+flag is a usage error.
1527
+ const adminPass = resolveFederationAdminPass(opts, process.env.FLAIR_ADMIN_PASS);
1418
1528
  const auth = `Basic ${Buffer.from(`${resolveAdminUser(opts.adminUser)}:${adminPass}`).toString("base64")}`;
1419
1529
  // 1. Persist the PairingToken record
1420
1530
  const opsRes = await fetch(`${opsEndpoint}/`, {
@@ -1432,7 +1542,10 @@ export function register(program) {
1432
1542
  });
1433
1543
  if (!opsRes.ok) {
1434
1544
  const detail = await opsRes.text().catch(() => "");
1435
- throw new Error(`Failed to persist pairing token (${opsRes.status}): ${detail || "no body"}`);
1545
+ // Harper's error body can echo the upsert's record, whose `id` IS the
1546
+ // pairing token. Cut the token id to its prefix before it reaches the
1547
+ // thrown message, which this command's catch prints (flair#1902).
1548
+ throw new Error(`Failed to persist pairing token (${opsRes.status}): ${redactTokenMessage(detail || "no body", [token])}`);
1436
1549
  }
1437
1550
  // 2. Create bootstrap user for this token
1438
1551
  const bootstrapPassword = randomBytes(32).toString("base64url");
@@ -1453,33 +1566,17 @@ export function register(program) {
1453
1566
  });
1454
1567
  }
1455
1568
  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(() => { });
1569
+ // Network failure creating bootstrap user — roll back PairingToken. The
1570
+ // rollback outcome is an ADDITIONAL line; the command still exits on the
1571
+ // original (network) failure below.
1572
+ console.error(await rollbackPairingToken(opsEndpoint, auth, token));
1468
1573
  throw new Error(`Failed to create bootstrap user (network): ${err.message}`);
1469
1574
  }
1470
1575
  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(() => { });
1576
+ // add_user failed — roll back PairingToken so the two stay in sync. The
1577
+ // rollback outcome is an ADDITIONAL line; the command still exits on the
1578
+ // original add_user failure below.
1579
+ console.error(await rollbackPairingToken(opsEndpoint, auth, token));
1483
1580
  const detail = await addUserRes.text().catch(() => "");
1484
1581
  throw new Error(`Failed to create bootstrap user (${addUserRes.status}): ${detail || "no body"}`);
1485
1582
  }
@@ -1753,6 +1850,136 @@ export function register(program) {
1753
1850
  if (errors > 0)
1754
1851
  process.exit(1);
1755
1852
  });
1853
+ // ── flair federation instance — the identity row (flair#1883) ────────────
1854
+ //
1855
+ // A hub's identity is ONE `flair.Instance` row and the pairing-cleanup sweep
1856
+ // reads its role. `GET /FederationInstance` find-or-creates one, `flair init
1857
+ // --remote` used to insert a SECOND, and everything downstream that took "the
1858
+ // first row" then read whichever row the table yielded first. `list` shows the
1859
+ // rows; `prune` gets back to one.
1860
+ const instanceCmd = federation
1861
+ .command("instance")
1862
+ .description("Inspect and repair this instance's federation identity row");
1863
+ /** The ops endpoint these two subcommands read and write. */
1864
+ const instanceOpsEndpoint = (opts) => {
1865
+ // --admin-pass-file resolves into the same `adminPass` slot the inline flag
1866
+ // uses (the shared idiom: the secret stays out of ps and shell history).
1867
+ applyAdminPassFile(opts);
1868
+ const opsUrl = resolveEffectiveOpsUrl(opts) ?? `http://127.0.0.1:${resolveOpsPort(opts)}`;
1869
+ const adminPass = opts.adminPass ?? process.env.FLAIR_ADMIN_PASS ?? "";
1870
+ return { opsUrl, credentials: { user: resolveAdminUser(opts.adminUser), pass: adminPass } };
1871
+ };
1872
+ addSharedCredentialOptions(instanceCmd.command("list"))
1873
+ .description("List every Instance row on this instance (a hub should have exactly one)")
1874
+ .option("--port <port>", "Harper HTTP port")
1875
+ .option("--ops-port <port>", "Harper operations API port")
1876
+ .option("--target <url>", "Remote Flair URL (env: FLAIR_TARGET)")
1877
+ .option("--ops-target <url>", "Explicit ops API URL (env: FLAIR_OPS_TARGET)")
1878
+ .option("--json", "Emit JSON")
1879
+ .action(async (opts) => {
1880
+ let rows;
1881
+ try {
1882
+ rows = await readInstanceRows(instanceOpsEndpoint(opts));
1883
+ }
1884
+ catch (err) {
1885
+ console.error(`Error: ${err?.message ?? err}`);
1886
+ process.exit(1);
1887
+ }
1888
+ if (opts.json) {
1889
+ console.log(JSON.stringify({ rows }, null, 2));
1890
+ return;
1891
+ }
1892
+ if (rows.length === 0) {
1893
+ 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`).");
1894
+ return;
1895
+ }
1896
+ console.log(`${rows.length} Instance row(s):`);
1897
+ for (const row of rows)
1898
+ console.log(` ${formatInstanceRow(row)}`);
1899
+ if (rows.length > 1) {
1900
+ console.log(`\nMore than one row means there is no canonical identity. Keep one and delete the rest:`);
1901
+ console.log(` ${INSTANCE_ROW_PRUNE_REMEDY}`);
1902
+ }
1903
+ });
1904
+ addSharedCredentialOptions(instanceCmd.command("prune"))
1905
+ .description("Delete every Instance row except --keep <id> (dry-run by default)")
1906
+ .option("--keep <id>", "The Instance row to keep; the rest are deleted")
1907
+ .option("--apply", "Actually delete (default is dry-run)")
1908
+ .option("--port <port>", "Harper HTTP port")
1909
+ .option("--ops-port <port>", "Harper operations API port")
1910
+ .option("--target <url>", "Remote Flair URL (env: FLAIR_TARGET)")
1911
+ .option("--ops-target <url>", "Explicit ops API URL (env: FLAIR_OPS_TARGET)")
1912
+ .action(async (opts) => {
1913
+ const endpoint = instanceOpsEndpoint(opts);
1914
+ if (!opts.keep) {
1915
+ // No --keep: show what is there. Never guess which row is the identity —
1916
+ // the id and key peers know is the operator's fact, not this command's.
1917
+ try {
1918
+ const rows = await readInstanceRows(endpoint);
1919
+ if (rows.length === 0) {
1920
+ console.log("No Instance rows — nothing to prune.");
1921
+ return;
1922
+ }
1923
+ console.log(`${rows.length} Instance row(s):`);
1924
+ for (const row of rows)
1925
+ console.log(` ${formatInstanceRow(row)}`);
1926
+ console.error(`\nError: --keep <id> is required: name the row to keep.`);
1927
+ }
1928
+ catch (err) {
1929
+ console.error(`Error: ${err?.message ?? err}`);
1930
+ }
1931
+ process.exit(1);
1932
+ }
1933
+ let decision;
1934
+ try {
1935
+ decision = decideInstancePrune(await readInstanceRows(endpoint), opts.keep);
1936
+ }
1937
+ catch (err) {
1938
+ console.error(`Error: ${err?.message ?? err}`);
1939
+ process.exit(1);
1940
+ }
1941
+ if (decision.kind === "unknown-id") {
1942
+ console.error(`Error: --keep ${opts.keep} names no Instance row on this instance. Rows present:`);
1943
+ for (const row of decision.rows)
1944
+ console.error(` ${formatInstanceRow(row)}`);
1945
+ process.exit(1);
1946
+ }
1947
+ if (decision.kind === "nothing") {
1948
+ console.log(`Nothing to prune — --keep names the only Instance row this instance has.`);
1949
+ return;
1950
+ }
1951
+ // What a prune must tell the operator (flair#1883 round 3; tense
1952
+ // corrected in round 4): a paired peer pinned this instance's identity from
1953
+ // the `POST /FederationPair` response, which — while the table held several
1954
+ // rows — was whichever row the search yielded first. A peer that paired in
1955
+ // that state may have pinned ANY of the rows being deleted, and which one
1956
+ // it pinned is NOT determinable here, so the warning does not name one. (The
1957
+ // response is a 409 now, so this is history, not the current behaviour — but
1958
+ // those peers are still out there.) A peer paired with a deleted identity
1959
+ // must re-pair.
1960
+ const peerWarnings = prunePeerWarningLines({ drop: decision.drop });
1961
+ if (!opts.apply) {
1962
+ console.log(`── flair federation instance prune — dry-run (use --apply to delete) ──`);
1963
+ console.log(`Keeping ${formatInstanceRow(decision.keep)}`);
1964
+ console.log(`Would delete ${decision.drop.length} row(s):`);
1965
+ for (const row of decision.drop)
1966
+ console.log(` ${formatInstanceRow(row)}`);
1967
+ for (const line of peerWarnings)
1968
+ console.log(line);
1969
+ return;
1970
+ }
1971
+ try {
1972
+ const { dropped } = await pruneInstanceRows(endpoint, opts.keep);
1973
+ console.log(`Kept ${decision.keep.id}; deleted ${dropped.length} row(s): ${dropped.join(", ")}`);
1974
+ for (const line of peerWarnings)
1975
+ console.log(line);
1976
+ console.log("Re-run `flair init --remote` to set the kept row's role to hub.");
1977
+ }
1978
+ catch (err) {
1979
+ console.error(`Error: ${err?.message ?? err}`);
1980
+ process.exit(1);
1981
+ }
1982
+ });
1756
1983
  // `flair federation verify` — end-to-end roundtrip: write a tagged memory
1757
1984
  // locally, push it (bring-up has no daemon yet), probe peers for the tag.
1758
1985
  // Same class as fleet-verify / flair#988: 401/403 and unreachable are
@@ -1,6 +1,6 @@
1
1
  import * as render from "../render.js";
2
2
  import { unpinnedSpecWarning } from "../lib/mcp-spec.js";
3
- import { probeSessionStartHookDelivery, readClientMcpBlock } from "../doctor-client.js";
3
+ import { continuityWriteBlockers, probeSessionStartHookDelivery, readClientMcpBlock } from "../doctor-client.js";
4
4
  import { installHook, uninstallHook, hookStatus, hookStatusHeadline, hookStatusFailureLine, hookStatusIdentityLines, HOOK_STATUS_UNPARSED, installContinuityHooks, uninstallContinuityHooks, continuityHookStatus, isSupportedHarness, SUPPORTED_HARNESSES, hookInstallHint, harnessSupportsContinuity, resolveHookAgentId, } from "../hook-install.js";
5
5
  import { resolveHome } from "../lib/home.js";
6
6
  let cli;
@@ -153,7 +153,15 @@ export function register(program) {
153
153
  }
154
154
  else {
155
155
  const missing = !cont.postToolUse.present ? "PostToolUse missing" : !cont.stop.present ? "Stop missing" : "stale form";
156
- console.log(` ${render.icons.warn} continuity capture: ${cont.state} (${missing}) ${render.wrap(render.c.dim, `— re-run: ${hookInstallHint(harness, "--continuity")}`)}`);
156
+ const blockers = continuityWriteBlockers(cont);
157
+ let advice = `— re-run: ${hookInstallHint(harness, "--continuity")}`;
158
+ if (blockers.length > 0) {
159
+ const resolution = cont.postToolUse.reason || cont.stop.reason
160
+ ? "resolve the non-version pin manually"
161
+ : "rewrite held or refused; resolve the listed reason(s) manually";
162
+ advice = `— ${resolution}; ${blockers.join(" ")}`;
163
+ }
164
+ console.log(` ${render.icons.warn} continuity capture: ${cont.state} (${missing}) ${render.wrap(render.c.dim, advice)}`);
157
165
  }
158
166
  };
159
167
  console.log(`\n${render.wrap(render.c.bold, "🪝 flair hook status")}\n`);