@tpsdev-ai/flair 0.59.0 → 0.63.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 (359) hide show
  1. package/README.md +10 -10
  2. package/SECURITY.md +49 -5
  3. package/config.yaml +23 -12
  4. package/dist/bridges/builtins/mem0.js +63 -28
  5. package/dist/bridges/runtime/execute.js +1 -0
  6. package/dist/bridges/runtime/import-runner.js +12 -0
  7. package/dist/bridges/runtime/load-plugin.js +42 -13
  8. package/dist/bridges/runtime/yaml-loader.js +4 -2
  9. package/dist/bridges/types.js +1 -0
  10. package/dist/build-info.json +3 -3
  11. package/dist/cli.js +1054 -367
  12. package/dist/commands/agent.js +233 -90
  13. package/dist/commands/attention.js +4 -3
  14. package/dist/commands/backup-approval.js +218 -0
  15. package/dist/commands/backup.js +211 -39
  16. package/dist/commands/bootstrap.js +3 -1
  17. package/dist/commands/bridge.js +172 -119
  18. package/dist/commands/deploy.js +71 -8
  19. package/dist/commands/doctor.js +711 -146
  20. package/dist/commands/export.js +57 -23
  21. package/dist/commands/federation.js +787 -82
  22. package/dist/commands/grant.js +5 -6
  23. package/dist/commands/help.js +25 -0
  24. package/dist/commands/hook.js +155 -2
  25. package/dist/commands/idp.js +27 -19
  26. package/dist/commands/import.js +136 -20
  27. package/dist/commands/init.js +469 -200
  28. package/dist/commands/integrity.js +387 -0
  29. package/dist/commands/keys.js +247 -58
  30. package/dist/commands/mcp.js +108 -52
  31. package/dist/commands/memory.js +203 -35
  32. package/dist/commands/migrate-harness-memory.js +3 -2
  33. package/dist/commands/orgevent.js +51 -47
  34. package/dist/commands/presence.js +4 -3
  35. package/dist/commands/principal.js +428 -62
  36. package/dist/commands/quality.js +13 -1
  37. package/dist/commands/reembed.js +141 -17
  38. package/dist/commands/relationship.js +2 -1
  39. package/dist/commands/rem.js +537 -80
  40. package/dist/commands/restore.js +413 -65
  41. package/dist/commands/search.js +6 -4
  42. package/dist/commands/service.js +235 -40
  43. package/dist/commands/soul.js +4 -9
  44. package/dist/commands/status.js +94 -38
  45. package/dist/commands/test.js +7 -3
  46. package/dist/commands/upgrade.js +77 -23
  47. package/dist/commands/workspace.js +13 -11
  48. package/dist/component-env.js +31 -41
  49. package/dist/deploy.js +136 -4
  50. package/dist/doctor-client.js +534 -92
  51. package/dist/engine-version-contract.js +1 -0
  52. package/dist/engine-version.js +23 -3
  53. package/dist/fabric-upgrade.js +12 -2
  54. package/dist/federation/presence-send.js +139 -0
  55. package/dist/federation-verify.js +273 -180
  56. package/dist/hook-install.js +670 -6
  57. package/dist/install/clients.js +171 -35
  58. package/dist/keystore.js +72 -0
  59. package/dist/lib/action-recall-runtime.js +328 -0
  60. package/dist/lib/agent-home-fields.js +132 -0
  61. package/dist/lib/agent-home.js +427 -0
  62. package/dist/lib/agent-id-rule.js +88 -0
  63. package/dist/lib/agent-roster.js +33 -0
  64. package/dist/lib/atomic-write.js +1 -1
  65. package/dist/lib/auth-resolve.js +1069 -60
  66. package/dist/lib/backup-approval-store.js +612 -0
  67. package/dist/lib/backup-artifact.js +343 -0
  68. package/dist/lib/capture-runtime.js +124 -0
  69. package/dist/lib/config-critical-section.js +212 -25
  70. package/dist/lib/connect-phase.js +33 -0
  71. package/dist/lib/credential-status-rule.js +78 -0
  72. package/dist/lib/daemon-liveness.js +43 -11
  73. package/dist/lib/doctor-run.js +75 -37
  74. package/dist/lib/durability-copy.js +10 -0
  75. package/dist/lib/embedding-space-doctor.js +75 -0
  76. package/dist/lib/federation-pair-access.js +4 -0
  77. package/dist/lib/federation-retry-queue.js +283 -0
  78. package/dist/lib/federation-retry-row.js +101 -0
  79. package/dist/lib/flair-agent-role.js +4 -0
  80. package/dist/lib/hub-url.js +12 -0
  81. package/dist/lib/init-admin-pass.js +88 -12
  82. package/dist/lib/init-listener-environ.js +1 -2
  83. package/dist/lib/init-occupied-listener.js +15 -111
  84. package/dist/lib/init-spawn-attribution.js +73 -0
  85. package/dist/lib/init-tcp-probe.js +33 -0
  86. package/dist/lib/instance-identity-row.js +20 -0
  87. package/dist/lib/instruction-event-contract.js +17 -0
  88. package/dist/lib/instruction-event-doctor.js +102 -0
  89. package/dist/lib/launchd-management.js +38 -3
  90. package/dist/lib/listener-table.js +268 -0
  91. package/dist/lib/local-delete-instance.js +27 -0
  92. package/dist/lib/local-instance-pair.js +256 -0
  93. package/dist/lib/mcp-enable.js +1182 -341
  94. package/dist/lib/mcp-oauth-env-core.js +133 -0
  95. package/dist/lib/mcp-oauth-env.js +125 -0
  96. package/dist/lib/mcp-spec.js +17 -1
  97. package/dist/lib/memory-attributes.js +4 -0
  98. package/dist/lib/memory-id-policy.js +46 -0
  99. package/dist/lib/memory-integrity.js +309 -0
  100. package/dist/lib/memory-provider-timeout.js +33 -0
  101. package/dist/lib/memory-purge-response.js +20 -0
  102. package/dist/lib/mqtt-config.js +132 -0
  103. package/dist/lib/mqtt-listener-doctor.js +104 -0
  104. package/dist/lib/open-live-row.js +20 -0
  105. package/dist/lib/ops-table-count.js +25 -0
  106. package/dist/lib/ops-url.js +52 -0
  107. package/dist/lib/owned-pins.js +67 -10
  108. package/dist/lib/peer-status.js +27 -0
  109. package/dist/lib/principal-status.js +29 -0
  110. package/dist/lib/process-start-time.js +76 -12
  111. package/dist/lib/promotion-content-hash.js +20 -0
  112. package/dist/lib/proto-safe-record.js +42 -0
  113. package/dist/lib/record-id-path.js +25 -0
  114. package/dist/lib/reembed-server-support.js +66 -0
  115. package/dist/lib/restore-archive.js +760 -0
  116. package/dist/lib/restore-verify.js +104 -0
  117. package/dist/lib/scheduler-platform.js +10 -6
  118. package/dist/lib/secret-keys.js +25 -0
  119. package/dist/lib/secrets-push.js +50 -22
  120. package/dist/lib/skill-assignment-preflight.js +159 -0
  121. package/dist/lib/skill-seed-pending.js +24 -0
  122. package/dist/lib/skill-seed.js +448 -0
  123. package/dist/lib/skill-tombstone-doctor.js +133 -0
  124. package/dist/lib/soul-scope-fields.js +26 -0
  125. package/dist/lib/stop-start-recovery.js +54 -0
  126. package/dist/lib/uninstall-purge.js +266 -11
  127. package/dist/lib/upgrade-prior-liveness.js +2 -1
  128. package/dist/lib/using-flair-skill.js +87 -0
  129. package/dist/mcp-client-assertion.js +114 -14
  130. package/dist/memory-id-checkpoint.js +347 -0
  131. package/dist/memory-node-compare.js +207 -0
  132. package/dist/mqtt-off-deploy.js +550 -0
  133. package/dist/packages/flair-mcp/src/secret-redaction.js +113 -0
  134. package/dist/rem/promote-policy.js +3 -3
  135. package/dist/rem/restore.js +303 -26
  136. package/dist/rem/runner.js +317 -96
  137. package/dist/rem/scheduler.js +21 -4
  138. package/dist/resources/A2AAdapter.js +131 -178
  139. package/dist/resources/AdminMemory.js +2 -0
  140. package/dist/resources/AdminMemoryCandidates.js +116 -0
  141. package/dist/resources/Agent.js +463 -33
  142. package/dist/resources/AgentCard.js +4 -0
  143. package/dist/resources/AgentKeyRegister.js +248 -0
  144. package/dist/resources/AgentKeyRegistration.js +28 -0
  145. package/dist/resources/AgentReadPosition.js +7 -0
  146. package/dist/resources/AgentSeed.js +238 -107
  147. package/dist/resources/AutoPromoteCandidates.js +413 -78
  148. package/dist/resources/Credential.js +183 -10
  149. package/dist/resources/Federation.js +915 -145
  150. package/dist/resources/FederationRetry.js +140 -0
  151. package/dist/resources/InstructionVersion.js +220 -0
  152. package/dist/resources/Integration.js +300 -25
  153. package/dist/resources/MCPClientMetadata.js +6 -3
  154. package/dist/resources/Memory.js +3300 -758
  155. package/dist/resources/MemoryArchive.js +171 -53
  156. package/dist/resources/MemoryBootstrap.js +122 -61
  157. package/dist/resources/MemoryCandidate.js +37 -3
  158. package/dist/resources/MemoryConsolidate.js +2 -2
  159. package/dist/resources/MemoryDedupStats.js +30 -1
  160. package/dist/resources/MemoryFeed.js +545 -50
  161. package/dist/resources/MemoryGrant.js +21 -1
  162. package/dist/resources/MemoryMaintenance.js +368 -46
  163. package/dist/resources/MemoryPurge.js +348 -0
  164. package/dist/resources/MemoryReflect.js +71 -12
  165. package/dist/resources/MemoryReindex.js +111 -17
  166. package/dist/resources/Message.js +16 -5
  167. package/dist/resources/OAuth.js +342 -48
  168. package/dist/resources/OAuthClient.js +1 -1
  169. package/dist/resources/OrgEvent.js +405 -19
  170. package/dist/resources/OrgEventCatchup.js +7 -0
  171. package/dist/resources/OrgEventMaintenance.js +48 -10
  172. package/dist/resources/PairingToken.js +1 -1
  173. package/dist/resources/Presence.js +166 -51
  174. package/dist/resources/PromoteMemoryCandidate.js +24 -7
  175. package/dist/resources/RecordUsage.js +2 -4
  176. package/dist/resources/Relationship.js +23 -0
  177. package/dist/resources/SemanticSearch.js +63 -32
  178. package/dist/resources/Soul.js +191 -76
  179. package/dist/resources/SoulFeed.js +2 -1
  180. package/dist/resources/TeamDirectory.js +35 -0
  181. package/dist/resources/WorkspaceLatest.js +4 -0
  182. package/dist/resources/WorkspaceState.js +21 -1
  183. package/dist/resources/XAA.js +207 -63
  184. package/dist/resources/a2a-stream.js +313 -0
  185. package/dist/resources/a2a-url.js +4 -5
  186. package/dist/resources/agent-admin.js +10 -1
  187. package/dist/resources/agent-auth.js +138 -83
  188. package/dist/resources/agent-read-position-lib.js +4 -1
  189. package/dist/resources/agent-status-guard.js +9 -7
  190. package/dist/resources/auth-middleware.js +534 -171
  191. package/dist/resources/authority-field-guard.js +9 -11
  192. package/dist/resources/auto-promote-lib.js +8 -5
  193. package/dist/resources/basic-auth-header.js +21 -0
  194. package/dist/resources/bm25-index-service.js +4 -5
  195. package/dist/resources/dedup-cluster.js +6 -1
  196. package/dist/resources/ed25519-auth.js +1 -1
  197. package/dist/resources/embedding-space-guard.js +366 -72
  198. package/dist/resources/embeddings-provider.js +25 -0
  199. package/dist/resources/engine-version-stamp-boot.js +53 -0
  200. package/dist/resources/federation-classify.js +161 -0
  201. package/dist/resources/federation-crypto.js +5 -5
  202. package/dist/resources/federation-retry-lib.js +60 -0
  203. package/dist/resources/grant-visibility.js +135 -0
  204. package/dist/resources/harper-routing.js +83 -0
  205. package/dist/resources/health.js +163 -22
  206. package/dist/resources/host-pointer/registry.js +29 -0
  207. package/dist/resources/host-pointer-adapter.js +1 -0
  208. package/dist/resources/host-source-citation.js +49 -0
  209. package/dist/resources/host-source-visibility.js +7 -6
  210. package/dist/resources/in-process.js +24 -22
  211. package/dist/resources/instance-create-lock.js +17 -0
  212. package/dist/resources/instance-identity.js +23 -0
  213. package/dist/resources/instruction-version-record.js +587 -0
  214. package/dist/resources/internal-authority.js +13 -0
  215. package/dist/resources/key-lock.js +3 -3
  216. package/dist/resources/mcp-handler.js +141 -19
  217. package/dist/resources/mcp-oauth-env-guard.js +36 -0
  218. package/dist/resources/mcp-oauth-flag.js +12 -14
  219. package/dist/resources/mcp-oauth.js +450 -56
  220. package/dist/resources/mcp-tool-arguments.js +4 -6
  221. package/dist/resources/mcp-tools.js +187 -40
  222. package/dist/resources/memory-bootstrap-lib.js +5 -15
  223. package/dist/resources/memory-declared-attributes.js +4 -1
  224. package/dist/resources/memory-deletion-history.js +55 -0
  225. package/dist/resources/memory-durability.js +54 -0
  226. package/dist/resources/memory-embed-hash.js +144 -0
  227. package/dist/resources/memory-embedding-value.js +8 -0
  228. package/dist/resources/memory-host-source.js +32 -7
  229. package/dist/resources/memory-id-guard.js +75 -0
  230. package/dist/resources/memory-redaction.js +236 -0
  231. package/dist/resources/memory-reflect-lib.js +1 -1
  232. package/dist/resources/memory-supplied-vector.js +72 -0
  233. package/dist/resources/memory-write-lock.js +489 -0
  234. package/dist/resources/memory-write-response.js +139 -0
  235. package/dist/resources/memory-write-transaction.js +243 -0
  236. package/dist/resources/migration-boot.js +17 -12
  237. package/dist/resources/migrations/boot-progress.js +25 -0
  238. package/dist/resources/migrations/data-dir.js +90 -19
  239. package/dist/resources/migrations/dir-safety.js +61 -3
  240. package/dist/resources/migrations/embedding-stamp.js +462 -82
  241. package/dist/resources/migrations/export.js +1 -0
  242. package/dist/resources/migrations/graph-heal.js +27 -27
  243. package/dist/resources/migrations/ledger.js +5 -2
  244. package/dist/resources/migrations/lock.js +870 -77
  245. package/dist/resources/migrations/progress.js +71 -10
  246. package/dist/resources/migrations/runner.js +212 -18
  247. package/dist/resources/migrations/snapshot.js +1 -0
  248. package/dist/resources/migrations/source-fields.js +5 -5
  249. package/dist/resources/migrations/state.js +36 -1
  250. package/dist/resources/migrations/status.js +2 -13
  251. package/dist/resources/migrations/synthetic-test-migration.js +81 -12
  252. package/dist/resources/migrations/types.js +26 -1
  253. package/dist/resources/migrations/visibility-backfill.js +113 -72
  254. package/dist/resources/oauth-discovery.js +0 -5
  255. package/dist/resources/object-body-guard.js +40 -0
  256. package/dist/resources/org-event-created-at.js +133 -0
  257. package/dist/resources/org-event-reserved.js +92 -0
  258. package/dist/resources/org-event-write-fault.js +19 -0
  259. package/dist/resources/originator-instance.js +39 -7
  260. package/dist/resources/owner-delete-recheck.js +78 -0
  261. package/dist/resources/owner-field-guard.js +39 -5
  262. package/dist/resources/owner-scoped-write-policy.js +256 -0
  263. package/dist/resources/owner-scoped-writes.js +89 -0
  264. package/dist/resources/path-id-rewrite.js +76 -0
  265. package/dist/resources/presence-internal.js +5 -5
  266. package/dist/resources/presence-receipt.js +236 -0
  267. package/dist/resources/promotion-binding.js +43 -0
  268. package/dist/resources/promotion-stamp.js +143 -17
  269. package/dist/resources/protocol-context.js +189 -0
  270. package/dist/resources/record-owner-guard.js +74 -26
  271. package/dist/resources/record-type-kit.js +2 -4
  272. package/dist/resources/record-types.js +1 -1
  273. package/dist/resources/relay-ops.js +78 -6
  274. package/dist/resources/replay-store.js +96 -19
  275. package/dist/resources/request-target.js +163 -0
  276. package/dist/resources/request-transaction.js +46 -1
  277. package/dist/resources/search-readiness.js +4 -1
  278. package/dist/resources/seed-ids.js +9 -0
  279. package/dist/resources/seed-reservation.js +116 -0
  280. package/dist/resources/semantic-retrieval-core.js +27 -15
  281. package/dist/resources/server-row-validation.js +71 -0
  282. package/dist/resources/skill-manifest.js +24 -14
  283. package/dist/resources/skill-subject.js +53 -0
  284. package/dist/resources/skill-version-write.js +789 -0
  285. package/dist/resources/skill-write-fault.js +20 -0
  286. package/dist/resources/skill-write-policy.js +68 -0
  287. package/dist/resources/skill-write.js +67 -7
  288. package/dist/resources/soul-write-policy.js +26 -7
  289. package/dist/resources/table-helpers.js +10 -7
  290. package/dist/resources/table-subscription-policy.js +518 -85
  291. package/dist/resources/table-subscriptions.js +20 -7
  292. package/dist/resources/team-directory.js +248 -0
  293. package/dist/resources/tool-descriptors/index.js +69 -8
  294. package/dist/resources/txn-pause-point.js +235 -0
  295. package/dist/resources/usage-recording.js +186 -70
  296. package/dist/resources/write-back.js +383 -0
  297. package/dist/resources/write-journal-context.js +5 -0
  298. package/dist/resources/write-journal.js +289 -0
  299. package/dist/src/engine-version-contract.js +1 -0
  300. package/dist/src/keystore.js +72 -0
  301. package/dist/src/lib/agent-home-fields.js +132 -0
  302. package/dist/src/lib/agent-id-rule.js +88 -0
  303. package/dist/src/lib/agent-key-register.js +80 -0
  304. package/dist/src/lib/atomic-write.js +256 -0
  305. package/dist/src/lib/credential-status-rule.js +78 -0
  306. package/dist/src/lib/expired-by-agent.js +37 -0
  307. package/dist/src/lib/federation-retry-row.js +101 -0
  308. package/dist/src/lib/flair-agent-role.js +4 -0
  309. package/dist/src/lib/idp-mapping-rule.js +81 -0
  310. package/dist/src/lib/instance-identity-row.js +20 -0
  311. package/dist/src/lib/instruction-event-contract.js +17 -0
  312. package/dist/src/lib/mcp-oauth-env-core.js +133 -0
  313. package/dist/src/lib/memory-attributes.js +4 -0
  314. package/dist/src/lib/memory-id-policy.js +46 -0
  315. package/dist/src/lib/open-live-row.js +20 -0
  316. package/dist/src/lib/principal-status.js +29 -0
  317. package/dist/src/lib/proto-safe-record.js +42 -0
  318. package/dist/src/lib/reembed-server-support.js +66 -0
  319. package/dist/src/lib/scheduler-platform.js +10 -6
  320. package/dist/src/lib/soul-scope-fields.js +26 -0
  321. package/dist/src/lib/systemd-agent-id.js +38 -0
  322. package/dist/src/rem/promote-policy.js +3 -3
  323. package/dist/src/rem/scheduler.js +21 -4
  324. package/docs/access-control.md +164 -54
  325. package/docs/api-reference.md +165 -32
  326. package/docs/auth.md +46 -30
  327. package/docs/bridges.md +11 -0
  328. package/docs/claude-code.md +37 -7
  329. package/docs/deploying-on-fabric.md +178 -0
  330. package/docs/deployment.md +19 -0
  331. package/docs/embedding-in-a-harper-app.md +17 -15
  332. package/docs/entity-vocabulary.md +3 -6
  333. package/docs/federation.md +61 -3
  334. package/docs/hosted-on-fabric.md +43 -36
  335. package/docs/integrations.md +14 -14
  336. package/docs/mcp-clients.md +12 -7
  337. package/docs/n8n.md +17 -11
  338. package/docs/notes/mcp-agent-auth-consumer.md +16 -13
  339. package/docs/notes/mcp-oauth-model2.md +40 -11
  340. package/docs/openclaw.md +1 -1
  341. package/docs/quickstart-fabric.md +4 -4
  342. package/docs/quickstart.md +12 -4
  343. package/docs/releasing.md +25 -19
  344. package/docs/rem.md +32 -3
  345. package/docs/secrets-and-keys.md +21 -4
  346. package/docs/standalone-local.md +30 -2
  347. package/docs/supply-chain-policy.md +34 -16
  348. package/docs/the-team.md +2 -2
  349. package/docs/upgrade.md +46 -6
  350. package/package.json +24 -12
  351. package/schemas/agent-key-registration.graphql +22 -0
  352. package/schemas/agent.graphql +6 -3
  353. package/schemas/federation.graphql +41 -1
  354. package/schemas/memory.graphql +91 -7
  355. package/schemas/oauth.graphql +19 -0
  356. package/schemas/schema.graphql +2 -0
  357. package/templates/bin/flair-rem-nightly.sh.tmpl +7 -1
  358. package/templates/launchd/start-flair-with-admin-pass.sh +188 -10
  359. package/dist/resources/soul-adk-guard.js +0 -68
@@ -1,3 +1,20 @@
1
+ /**
2
+ * federation.ts — `flair federation` command group (flair#1620 / epic #1618).
3
+ *
4
+ * Extracted from src/cli.ts with ZERO behavior change. This file owns the
5
+ * group's commander registration, action handlers, and group-specific
6
+ * inline helpers (crypto/sign, status-fetch sentences, pair token parse,
7
+ * sync/watch, prune duration). Shared CLI helpers (api, resolveTarget,
8
+ * credential flags, …) stay in cli.ts and are bound before register().
9
+ *
10
+ * Compiled with the rest of src/ under tsconfig.check.src.json (strict).
11
+ * Do not import src/cli.ts from here — that would cycle and pull the
12
+ * non-strict entry into the strict check.
13
+ */
14
+ import { encodeRecordId } from "../lib/record-id-path.js";
15
+ import { normalizeHubUrl } from "../lib/hub-url.js";
16
+ import { PEER_STATUS, isPeerMemberStatus } from "../lib/peer-status.js";
17
+ import { protoSafeRecord } from "../lib/proto-safe-record.js";
1
18
  import nacl from "tweetnacl";
2
19
  import { existsSync, readFileSync } from "node:fs";
3
20
  import { randomBytes } from "node:crypto";
@@ -7,9 +24,12 @@ import { runFederationVerify } from "../federation-verify.js";
7
24
  import { resolveHubPeerIdentity } from "../lib/federation-pair-identity.js";
8
25
  import { redactTokenMessage } from "../lib/redact-token-id.js";
9
26
  import { rewriteFederationPairHubAccessError, rewriteFederationPairLocalAccessError, } from "../lib/federation-pair-access.js";
10
- import { defaultAdminPassPath, isLocalBase, resolveAdminPassFromSources, resolveAdminUser, ADMIN_PASS_FILE_FLAG, ADMIN_PASS_FILE_HELP, ADMIN_PASS_HELP, } from "../lib/auth-resolve.js";
27
+ import { ApiHttpError, apiErrorRawBody, defaultAdminPassPath, isLocalBase, resolveAdminUser, addAdminPassOptions, applyAdminPassFile, ApiRequestOutcomeUnknown, } from "../lib/auth-resolve.js";
11
28
  import { DEFAULT_INTERVAL_SECONDS as FEDERATION_SYNC_DEFAULT_INTERVAL } from "../federation/scheduler.js";
12
29
  import { FEDERATION_MEMORY_SELECT } from "../lib/federation-memory-attributes.js";
30
+ import { retryEntryKey } from "../lib/federation-retry-row.js";
31
+ import { MEMORY_RETRY_REASONS, dueRetryRows, retryOfferProblem, retryRowConfirmation, retryRowForAttempt, retryRowForRefusal, retryRowMalformedness, terminalRetryRow, } from "../lib/federation-retry-queue.js";
32
+ import { presenceCursorMs, presenceSendEnabled, presenceWatermarkMs, presenceWireRecord, PRESENCE_SEND_FUTURE_ALLOWANCE_MS, PRESENCE_SEND_OVERLAP_MS, PRESENCE_SEND_RECEIVE_DISABLED_SKIP_REASON, PRESENCE_SEND_RETRYABLE_SKIP_REASONS, selectPresenceRowsToSend, } from "../federation/presence-send.js";
13
33
  import { decideInstancePrune, formatInstanceRow, INSTANCE_ROW_PRUNE_REMEDY, prunePeerWarningLines, readInstanceRows, pruneInstanceRows, writeConfirmed, } from "../lib/instance-identity-row.js";
14
34
  let cli;
15
35
  /** Bind shared CLI helpers. cli.ts calls this immediately before register(program). */
@@ -31,36 +51,20 @@ function resolveEffectiveOpsUrl(opts) {
31
51
  function resolveOpsPort(opts) {
32
52
  return cli.resolveOpsPort(opts);
33
53
  }
34
- function applyAdminPassFile(opts) {
35
- cli.applyAdminPassFile(opts);
36
- }
37
54
  /** `federation token` / `federation pair` credential flags (flair#1873).
38
55
  * The flag/help strings live in auth-resolve.ts next to the resolver, shared
39
56
  * with every sibling command's credential options (flair#1910). */
40
57
  /**
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.
58
+ * `federation token`/`pair`'s admin password: an explicit `--admin-pass-file`
59
+ * or `--admin-pass` was already applied to `opts.adminPass` by
60
+ * addAdminPassOptions' preAction hook (which also refuses both at once); the
61
+ * environment is the fallback. Never prints the value.
48
62
  */
49
63
  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
+ const pass = opts.adminPass ?? envPass ?? "";
65
+ if (pass)
66
+ opts.adminPass = pass;
67
+ return pass;
64
68
  }
65
69
  function addSharedCredentialOptions(cmd) {
66
70
  return cli.addSharedCredentialOptions(cmd);
@@ -71,6 +75,25 @@ function addSharedIdentityOption(cmd) {
71
75
  function shouldShowInlineSecretWarning(optValue, fromEnv, secretFlagNames, flagName) {
72
76
  return cli.shouldShowInlineSecretWarning(optValue, fromEnv, secretFlagNames, flagName);
73
77
  }
78
+ /**
79
+ * Apply the admin-password pair inherited by `federation sync status` and
80
+ * `federation sync disable`. The parent (`flair federation sync`) declares the
81
+ * pair, so commander stores the values there.
82
+ * Resolve an explicitly supplied pair before the action body runs and store the
83
+ * password on the leaf, where `status` reads it for its request. `enable`
84
+ * stores the path only and does not call this.
85
+ */
86
+ function applyInheritedAdminPass(actionCommand) {
87
+ const inherited = actionCommand.parent?.opts();
88
+ if (!inherited)
89
+ return;
90
+ if (inherited.adminPass === undefined && inherited.adminPassFile === undefined)
91
+ return;
92
+ const opts = { adminPass: inherited.adminPass, adminPassFile: inherited.adminPassFile };
93
+ applyAdminPassFile(opts);
94
+ actionCommand.setOptionValue("adminPass", opts.adminPass);
95
+ actionCommand.setOptionValue("adminPassFile", opts.adminPassFile);
96
+ }
74
97
  // Federation crypto helpers — inlined to avoid cross-boundary imports from
75
98
  // src/ into resources/, which don't survive npm packaging (see also
76
99
  // resources/federation-crypto.ts; the two must stay in sync).
@@ -79,11 +102,10 @@ function sortKeys(val) {
79
102
  return val;
80
103
  if (Array.isArray(val))
81
104
  return val.map(sortKeys);
82
- const sorted = {};
83
- for (const key of Object.keys(val).sort()) {
84
- sorted[key] = sortKeys(val[key]);
85
- }
86
- return sorted;
105
+ const src = val;
106
+ // Shared null-prototype copy: an own `__proto__` key is kept in the signing
107
+ // input rather than silently dropped (flair#2235).
108
+ return protoSafeRecord(src, { keys: Object.keys(src).sort(), map: sortKeys });
87
109
  }
88
110
  function canonicalize(obj) {
89
111
  return JSON.stringify(sortKeys(obj));
@@ -149,7 +171,8 @@ const PAIR_TOKEN_MAYBE_CONSUMED = "The request may not have reached the hub; ver
149
171
  /**
150
172
  * Strip any userinfo (user:password) and query string from a URL before printing
151
173
  * it. An --ops-target like https://user:pass@host/?token=... must never put the
152
- * credential or the query token on stderr.
174
+ * credential or the query token on stderr. If parsing fails, none of the
175
+ * caller-controlled text is safe to classify, so print a fixed placeholder.
153
176
  */
154
177
  export function redactUrl(u) {
155
178
  try {
@@ -157,11 +180,11 @@ export function redactUrl(u) {
157
180
  url.username = "";
158
181
  url.password = "";
159
182
  url.search = "";
183
+ url.hash = "";
160
184
  return url.toString();
161
185
  }
162
186
  catch {
163
- // Not a parseable absolute URL: strip a userinfo-looking prefix and any query.
164
- return u.replace(/\/\/[^/@]*@/, "//").replace(/\?.*$/, "");
187
+ return "<unparseable URL>";
165
188
  }
166
189
  }
167
190
  /**
@@ -169,7 +192,7 @@ export function redactUrl(u) {
169
192
  * fetch to a user-supplied URL can carry the full URL (credentials included)
170
193
  * in err.message, so the message must never reach an error line.
171
194
  */
172
- function fetchErrorLabel(err) {
195
+ export function fetchErrorLabel(err) {
173
196
  // Node's fetch wraps the OS error: the useful code (ECONNREFUSED, ENOTFOUND,
174
197
  // …) is on err.cause.code, so prefer it over the wrapper's code/name.
175
198
  const e = err;
@@ -315,7 +338,7 @@ const signBodyFresh = signRequestBody;
315
338
  /**
316
339
  * Persist last-contact on the local Peer row after confirmed hub contact.
317
340
  *
318
- * Callers must invoke this only after a FederationSync 200 (sendBatch or the
341
+ * Callers must invoke this only after a successful FederationSync response (sendBatch or the
319
342
  * no-change liveness ping). lastSyncAt is the value HealthDetail counts as
320
343
  * `connected` (flair#1499 / flair#1146) AND the spoke's OUTBOUND sync cursor
321
344
  * (`federation sync` re-sends from it) — so a frozen value re-sends from the
@@ -372,6 +395,48 @@ export async function persistLocalPeerLastSyncAt(args) {
372
395
  }
373
396
  return { ok: true, status: updateRes.status };
374
397
  }
398
+ /**
399
+ * Attempt the Presence watermark update after contact. Presence has no `updatedAt`, so
400
+ * the row cursor over `lastHeartbeatAt` / `activityUpdatedAt` is compared against
401
+ * this field instead of `lastSyncAt`.
402
+ *
403
+ * Same shape and same result contract as {@link persistLocalPeerLastSyncAt}: a
404
+ * field-only `update` carrying `{id, presenceLastSyncAt, updatedAt}`, so it
405
+ * cannot revert `publicKey`/`status` or re-create a deleted row, and HTTP 200 is
406
+ * not success — the id must appear in `update_hashes`; otherwise the update is
407
+ * unconfirmed (a committed update with an unreadable response also reads as
408
+ * unconfirmed), unless Harper explicitly reports a miss.
409
+ * Callers invoke it only after contact — a confirmed batch, or a successful
410
+ * liveness ping on a no-change pass.
411
+ */
412
+ export async function persistLocalPeerPresenceSyncAt(args) {
413
+ const headers = { "Content-Type": "application/json", Authorization: args.auth };
414
+ const updateRes = await fetch(`${args.opsEndpoint}/`, {
415
+ method: "POST",
416
+ headers,
417
+ body: JSON.stringify({
418
+ operation: "update",
419
+ database: "flair",
420
+ table: "Peer",
421
+ records: [{ id: args.peerId, presenceLastSyncAt: args.presenceLastSyncAt, updatedAt: args.presenceLastSyncAt }],
422
+ }),
423
+ signal: AbortSignal.timeout(10_000),
424
+ });
425
+ if (!updateRes.ok) {
426
+ const txt = await updateRes.text().catch(() => "");
427
+ return { ok: false, status: updateRes.status, error: txt.slice(0, 200) };
428
+ }
429
+ const parsed = (await updateRes.json().catch(() => null));
430
+ const matched = !!parsed && Array.isArray(parsed.update_hashes) && parsed.update_hashes.includes(args.peerId);
431
+ if (!matched) {
432
+ return {
433
+ ok: false,
434
+ status: updateRes.status,
435
+ error: `Presence watermark update for Peer ${args.peerId} was not confirmed.`,
436
+ };
437
+ }
438
+ return { ok: true, status: updateRes.status };
439
+ }
375
440
  /**
376
441
  * The most recent CONTACT with any peer (max of peer.lastSyncAt), or null.
377
442
  *
@@ -388,7 +453,14 @@ async function latestPeerContact(opts) {
388
453
  try {
389
454
  const target = resolveTarget(opts);
390
455
  const baseUrl = target ? target.replace(/\/$/, "") : undefined;
391
- const { peers } = await api("GET", "/FederationPeers", undefined, baseUrl ? { baseUrl } : undefined);
456
+ const requestOptions = {};
457
+ if (baseUrl)
458
+ requestOptions.baseUrl = baseUrl;
459
+ if (opts.adminPass)
460
+ requestOptions.explicitAdminPass = opts.adminPass;
461
+ if (opts.adminUser)
462
+ requestOptions.adminUser = opts.adminUser;
463
+ const { peers } = await api("GET", "/FederationPeers", undefined, Object.keys(requestOptions).length ? requestOptions : undefined);
392
464
  let best = null;
393
465
  for (const p of peers ?? []) {
394
466
  if (!p?.lastSyncAt)
@@ -440,6 +512,11 @@ export function describeFederationStatusFetchFailed(url, setting) {
440
512
  * `TypeError: fetch failed`, Bun's `Unable to connect…`, or a cause
441
513
  * carrying a connect/DNS errno. Auth and HTTP errors stay out. */
442
514
  export function isFederationStatusConnectFailure(err) {
515
+ // Every ApiHttpError is excluded: the ones sendJsonRequest raises are built
516
+ // only after a response arrived, so that connection did not fail, whatever
517
+ // the body says (flair#2764).
518
+ if (err instanceof ApiHttpError)
519
+ return false;
443
520
  const msg = err instanceof Error ? err.message : String(err);
444
521
  if (/\bfetch failed\b/i.test(msg))
445
522
  return true;
@@ -477,11 +554,11 @@ export function isFederationStatusAuthFailure(err) {
477
554
  if (status === 401 || status === 403)
478
555
  return true;
479
556
  }
480
- const m = err instanceof Error
557
+ const m = apiErrorRawBody(err) || (err instanceof Error
481
558
  ? err.message
482
559
  : String(typeof err === "object" && err && "message" in err
483
560
  ? err.message ?? err
484
- : err);
561
+ : err));
485
562
  return m.includes("missing_or_invalid_authorization") || /(?:^|\D)401(?:\D|$)/.test(m);
486
563
  }
487
564
  /**
@@ -497,11 +574,11 @@ export function isFederationStatusAuthRemedy(err) {
497
574
  if (typeof err === "object" && "status" in err && err.status === 401) {
498
575
  return true;
499
576
  }
500
- const m = err instanceof Error
577
+ const m = apiErrorRawBody(err) || (err instanceof Error
501
578
  ? err.message
502
579
  : String(typeof err === "object" && err && "message" in err
503
580
  ? err.message ?? err
504
- : err);
581
+ : err));
505
582
  return m.includes("missing_or_invalid_authorization") || /(?:^|\D)401(?:\D|$)/.test(m);
506
583
  }
507
584
  /** Parse a JSON triple file for --token-from.
@@ -558,6 +635,85 @@ export function parseTokenFromFile(filePath) {
558
635
  expiresAt: parsed.expiresAt.trim(),
559
636
  };
560
637
  }
638
+ /**
639
+ * The counts of one FederationSync batch response, or null when they are not
640
+ * counts (flair#2455 rev 2.1 N2).
641
+ *
642
+ * The response body is receiver-authored. Its `merged` and `skipped` reach the
643
+ * sender's success log and the watch loop's line, so each must be an integer
644
+ * from 0 to the number of records in the batch it answers; anything else
645
+ * (text, a fraction, a negative, a count larger than the batch, a missing
646
+ * field) makes the whole response invalid. Their sum must also be at most the
647
+ * batch size: a receiver cannot report more outcomes than records it was
648
+ * offered. The bound is "at most", not "equal", because older receivers send
649
+ * counts without refusal lists and indeterminate rows fall in neither count.
650
+ * The caller reports a rejection in local text, never a received value that is
651
+ * not an in-range count.
652
+ */
653
+ export function parseSyncBatchCounts(body, batchSize) {
654
+ if (body === null || typeof body !== "object" || Array.isArray(body))
655
+ return null;
656
+ const { merged, skipped } = body;
657
+ if (!isSyncBatchCount(merged, batchSize) || !isSyncBatchCount(skipped, batchSize))
658
+ return null;
659
+ if (merged + skipped > batchSize)
660
+ return null;
661
+ return { merged, skipped };
662
+ }
663
+ function isSyncBatchCount(v, batchSize) {
664
+ return typeof v === "number" && Number.isSafeInteger(v) && v >= 0 && v <= batchSize;
665
+ }
666
+ /** Local text naming why a batch response's counts were rejected: the table
667
+ * and, when both counts are in range individually, their values. Other
668
+ * receiver-authored values stay out of the message. */
669
+ export function describeSyncBatchCountsRejection(body, batchSize, table) {
670
+ const counts = body !== null && typeof body === "object" && !Array.isArray(body)
671
+ ? body
672
+ : {};
673
+ if (isSyncBatchCount(counts.merged, batchSize) && isSyncBatchCount(counts.skipped, batchSize)) {
674
+ return `${table}: merged ${counts.merged} + skipped ${counts.skipped} exceeds ${batchSize} records offered`;
675
+ }
676
+ return `${table}: merged/skipped are not counts from 0 to ${batchSize}`;
677
+ }
678
+ /** One receiver-authored refusal from a FederationSync batch: which record the
679
+ * receiver refused and under which name. Only well-formed entries are kept; a
680
+ * refused field that is absent or not an array of {table,id,reason} strings is
681
+ * ignored (the sender acts on a retryable name, never on a shape it invented). */
682
+ export function parseSyncBatchRefused(body) {
683
+ if (body === null || typeof body !== "object" || Array.isArray(body))
684
+ return [];
685
+ const refused = body.refused;
686
+ if (!Array.isArray(refused))
687
+ return [];
688
+ const out = [];
689
+ for (const entry of refused) {
690
+ if (entry === null || typeof entry !== "object")
691
+ continue;
692
+ const { table, id, reason } = entry;
693
+ if (typeof table !== "string" || typeof id !== "string" || typeof reason !== "string")
694
+ continue;
695
+ out.push({ table, id, reason });
696
+ }
697
+ return out;
698
+ }
699
+ /** Keep well-formed indeterminate entries from a FederationSync batch. */
700
+ export function parseSyncBatchIndeterminate(body) {
701
+ if (body === null || typeof body !== "object" || Array.isArray(body))
702
+ return [];
703
+ const indeterminate = body.indeterminate;
704
+ if (!Array.isArray(indeterminate))
705
+ return [];
706
+ const out = [];
707
+ for (const entry of indeterminate) {
708
+ if (entry === null || typeof entry !== "object")
709
+ continue;
710
+ const { table, id } = entry;
711
+ if (typeof table !== "string" || typeof id !== "string")
712
+ continue;
713
+ out.push({ table, id });
714
+ }
715
+ return out;
716
+ }
561
717
  export async function runFederationSyncOnce(opts) {
562
718
  const target = resolveTarget(opts);
563
719
  const baseUrl = target ? target.replace(/\/$/, "") : undefined;
@@ -593,7 +749,224 @@ export async function runFederationSyncOnce(opts) {
593
749
  const auth = `Basic ${Buffer.from(`${resolveAdminUser(opts.adminUser)}:${adminPass}`).toString("base64")}`;
594
750
  const tables = ["Memory", "Soul", "Agent", "Relationship"];
595
751
  const instance = await api("GET", "/FederationInstance", undefined, apiOpts);
596
- const hubUrl = hub.endpoint ?? hub.id;
752
+ // ── federation retry bookkeeping (flair#2797) ─────────────────────────
753
+ // An eligible generic Memory row the hub refused for a retryable reason is
754
+ // kept in FederationRetry and offered again on a later cycle while its
755
+ // pending row is valid, its backoff is due and the source row is still
756
+ // eligible, independent of the since cursor. A source the cursor selects
757
+ // that also has a pending row gets the same treatment: a valid row's
758
+ // attempt is reserved before the send and the outcome updates or resolves
759
+ // it; a malformed row is reported and left as stored. A non-retryable
760
+ // refusal ends the obligation; the retry path in one sender run does not
761
+ // select a terminal row again, and concurrent sender runs for one peer are
762
+ // not serialized (a separate issue).
763
+ const retryHeaders = { "Content-Type": "application/json", Authorization: auth };
764
+ // One projection for every Memory read: the cursor query and the retry
765
+ // re-read must not differ in what a row exposes to the signed batch.
766
+ const memorySelect = [...FEDERATION_MEMORY_SELECT];
767
+ const pendingRetries = new Map();
768
+ /** Pending rows whose attempt this run reserved before sending. */
769
+ const reservedOffers = new Set();
770
+ /** Pending retry rows to reserve when their batch is reached. */
771
+ const reservationTargets = new Map();
772
+ /** Retry row ids already reported malformed in this run. */
773
+ const reportedMalformedRetries = new Set();
774
+ function reportMalformedRetryRow(id, malformed) {
775
+ if (reportedMalformedRetries.has(id))
776
+ return;
777
+ reportedMalformedRetries.add(id);
778
+ console.warn(`⚠️ FederationRetry row ${id} is malformed (${malformed.problem}: ${malformed.field}); left as stored.`);
779
+ }
780
+ async function loadPendingRetries() {
781
+ const res = await fetch(`${opsEndpoint}/`, {
782
+ method: "POST",
783
+ headers: retryHeaders,
784
+ body: JSON.stringify({
785
+ operation: "search_by_conditions",
786
+ schema: "flair",
787
+ table: "FederationRetry",
788
+ operator: "and",
789
+ conditions: [
790
+ { search_attribute: "peerId", search_type: "equals", search_value: hub.id },
791
+ { search_attribute: "table", search_type: "equals", search_value: "Memory" },
792
+ { search_attribute: "state", search_type: "equals", search_value: "pending" },
793
+ ],
794
+ get_attributes: ["*"],
795
+ }),
796
+ signal: AbortSignal.timeout(15_000),
797
+ });
798
+ if (!res.ok)
799
+ throw new Error(`FederationRetry read failed (${res.status})`);
800
+ const list = await res.json();
801
+ if (!Array.isArray(list))
802
+ throw new Error("FederationRetry read failed: body is not a row list");
803
+ for (const row of list)
804
+ pendingRetries.set(row.id, row);
805
+ }
806
+ /** Read the stored retry rows for `keys`, whatever their state. */
807
+ async function readStoredRetryRows(keys) {
808
+ const out = new Map();
809
+ if (keys.length === 0)
810
+ return out;
811
+ const res = await fetch(`${opsEndpoint}/`, {
812
+ method: "POST",
813
+ headers: retryHeaders,
814
+ body: JSON.stringify({ operation: "search_by_hash", database: "flair", table: "FederationRetry", hash_values: keys, get_attributes: ["*"] }),
815
+ signal: AbortSignal.timeout(15_000),
816
+ });
817
+ if (!res.ok)
818
+ throw new Error(`FederationRetry read failed (${res.status})`);
819
+ const rows = await res.json();
820
+ if (!Array.isArray(rows))
821
+ throw new Error("FederationRetry read failed: body is not a row list");
822
+ for (const row of rows) {
823
+ if (typeof row.id === "string")
824
+ out.set(row.id, row);
825
+ }
826
+ return out;
827
+ }
828
+ /** Read one retry row back and check it with retryRowConfirmation. */
829
+ async function confirmRetryRow(operation, record) {
830
+ const read = await fetch(`${opsEndpoint}/`, {
831
+ method: "POST",
832
+ headers: retryHeaders,
833
+ body: JSON.stringify({ operation: "search_by_hash", database: "flair", table: "FederationRetry", hash_values: [record.id], get_attributes: ["*"] }),
834
+ signal: AbortSignal.timeout(15_000),
835
+ });
836
+ if (!read.ok)
837
+ throw new Error(`FederationRetry read-back failed (${read.status})`);
838
+ const rows = await read.json();
839
+ if (!Array.isArray(rows))
840
+ throw new Error("FederationRetry read-back failed: body is not a row list");
841
+ const stored = rows.find((r) => r.id === record.id) ?? null;
842
+ const mismatch = retryRowConfirmation(record, stored);
843
+ if (mismatch !== null) {
844
+ throw new Error(`FederationRetry ${operation} was not confirmed for ${String(record.id)} (${mismatch})`);
845
+ }
846
+ }
847
+ /** Write one retry row; an unconfirmed write is an error, never a silent success. */
848
+ async function writeRetryRow(operation, record) {
849
+ const res = await fetch(`${opsEndpoint}/`, {
850
+ method: "POST",
851
+ headers: retryHeaders,
852
+ body: JSON.stringify({ operation, database: "flair", table: "FederationRetry", records: [record] }),
853
+ signal: AbortSignal.timeout(15_000),
854
+ });
855
+ if (!res.ok)
856
+ throw new Error(`FederationRetry ${operation} failed (${res.status})`);
857
+ if (operation === "update") {
858
+ const body = await res.json().catch(() => null);
859
+ if (!Array.isArray(body?.update_hashes) || !body.update_hashes.map(String).includes(String(record.id))) {
860
+ throw new Error(`FederationRetry update was not confirmed for ${String(record.id)}`);
861
+ }
862
+ }
863
+ // The upsert answer does not name the row and an update's hash only says
864
+ // it matched one. Read the row back: a write the sender cannot see is not
865
+ // a recorded obligation.
866
+ await confirmRetryRow(operation, record);
867
+ }
868
+ async function retireRetry(row, resolution, nowIso = new Date().toISOString()) {
869
+ await writeRetryRow("update", terminalRetryRow(row, resolution, nowIso));
870
+ pendingRetries.delete(row.id);
871
+ }
872
+ async function loadMemoryRow(id) {
873
+ const res = await fetch(`${opsEndpoint}/`, {
874
+ method: "POST",
875
+ headers: retryHeaders,
876
+ body: JSON.stringify({
877
+ operation: "search_by_conditions",
878
+ schema: "flair",
879
+ table: "Memory",
880
+ operator: "and",
881
+ conditions: [{ search_attribute: "id", search_type: "equals", search_value: id }],
882
+ get_attributes: memorySelect,
883
+ }),
884
+ signal: AbortSignal.timeout(15_000),
885
+ });
886
+ if (!res.ok)
887
+ throw new Error(`Memory read failed (${res.status})`);
888
+ const rows = await res.json();
889
+ if (!Array.isArray(rows))
890
+ throw new Error("Memory read failed: body is not a row list");
891
+ return rows[0] ?? null;
892
+ }
893
+ async function applyMemoryOutcomes(batch, result) {
894
+ const keyOf = (table, id) => JSON.stringify([table, id]);
895
+ const refused = new Map(result.refused.map((r) => [keyOf(r.table, r.id), r.reason]));
896
+ const undecided = new Set(result.indeterminate.map((r) => keyOf(r.table, r.id)));
897
+ const nowIso = new Date().toISOString();
898
+ // Read what is stored for this batch whatever each row's state: a
899
+ // malformed row is left as stored and its outcome write is skipped.
900
+ const storedRows = await readStoredRetryRows(batch.filter((record) => record.table === "Memory").map((record) => retryEntryKey(hub.id, "Memory", record.id)));
901
+ for (const record of batch) {
902
+ if (record.table !== "Memory")
903
+ continue;
904
+ const key = retryEntryKey(hub.id, "Memory", record.id);
905
+ const attemptReserved = reservedOffers.delete(key);
906
+ const prior = pendingRetries.get(key) ?? null;
907
+ const stored = storedRows.get(key) ?? null;
908
+ if (stored !== null) {
909
+ const malformed = retryRowMalformedness(stored);
910
+ if (malformed !== null) {
911
+ reportMalformedRetryRow(key, malformed);
912
+ continue;
913
+ }
914
+ }
915
+ // A row the shared validator names malformed is reported before the
916
+ // offer and left as stored: the outcome does not transition it.
917
+ if (prior !== null && retryOfferProblem(prior) !== null)
918
+ continue;
919
+ if (undecided.has(keyOf(record.table, record.id))) {
920
+ // The receiver did not decide this record. Offering it again is safe
921
+ // (the merge is idempotent); `retry_unknown` is the sender's own name.
922
+ // A first offer records the obligation too, or the cursor advance
923
+ // would lose it.
924
+ const row = retryRowForRefusal({ peerId: hub.id, recordId: record.id, reason: "retry_unknown", nowIso, existing: prior, attemptReserved });
925
+ await writeRetryRow("upsert", row);
926
+ pendingRetries.set(String(row.id), row);
927
+ continue;
928
+ }
929
+ const reason = refused.get(keyOf(record.table, record.id));
930
+ if (reason !== undefined) {
931
+ if (MEMORY_RETRY_REASONS.has(reason)) {
932
+ const row = retryRowForRefusal({ peerId: hub.id, recordId: record.id, reason, nowIso, existing: prior, attemptReserved });
933
+ await writeRetryRow("upsert", row);
934
+ pendingRetries.set(String(row.id), row);
935
+ }
936
+ else if (prior) {
937
+ await retireRetry(prior, "refused_terminal", nowIso);
938
+ }
939
+ continue;
940
+ }
941
+ if (prior)
942
+ await retireRetry(prior, "merged", nowIso);
943
+ }
944
+ }
945
+ /**
946
+ * Reserve one attempt for each Memory record in `batch` that selection recorded
947
+ * in `reservationTargets` (a record with a valid pending retry row).
948
+ * Called immediately before that batch is sent, so a
949
+ * batch the run never reaches leaves its rows' attempts and lastAttemptAt
950
+ * as stored. A reservation write that fails throws here, before the send.
951
+ */
952
+ async function reserveBatchAttempts(batch) {
953
+ const nowIso = new Date().toISOString();
954
+ for (const record of batch) {
955
+ if (record.table !== "Memory")
956
+ continue;
957
+ const pending = reservationTargets.get(String(record.id));
958
+ if (!pending)
959
+ continue;
960
+ reservationTargets.delete(String(record.id));
961
+ const reserved = retryRowForAttempt(pending, nowIso);
962
+ await writeRetryRow("upsert", reserved);
963
+ pendingRetries.set(String(reserved.id), reserved);
964
+ reservedOffers.add(String(reserved.id));
965
+ }
966
+ }
967
+ await loadPendingRetries();
968
+ // A stored endpoint with a trailing slash still yields `<hub>/FederationSync`.
969
+ const hubUrl = normalizeHubUrl(hub.endpoint ?? hub.id);
597
970
  // ── Batching constants ──────────────────────────────────────────────
598
971
  // 2MB JSON budget (server cap is 10MB; 2MB leaves headroom for headers
599
972
  // and signature metadata) + 50 records max per batch. The hub merge itself
@@ -620,7 +993,7 @@ export async function runFederationSyncOnce(opts) {
620
993
  // a healthy 50-record batch merges in <2s — so a trip means a real stall,
621
994
  // and we split-and-retry rather than wait it out.
622
995
  const BATCH_TIMEOUT_MS = 45_000;
623
- async function sendBatch(batch) {
996
+ async function sendBatch(batch, validatePresence = false) {
624
997
  if (!secretKey)
625
998
  secretKey = await loadInstanceSecretKey(instance.id, opts);
626
999
  const syncBody = { instanceId: instance.id, records: batch, lamportClock: Date.now() };
@@ -631,9 +1004,14 @@ export async function runFederationSyncOnce(opts) {
631
1004
  const splittable = (status) => batch.length > 1 && (status === null || TIMEOUT_STATUSES.has(status));
632
1005
  const split = async () => {
633
1006
  const mid = Math.floor(batch.length / 2);
634
- const left = await sendBatch(batch.slice(0, mid));
635
- const right = await sendBatch(batch.slice(mid));
636
- return { merged: left.merged + right.merged, skipped: left.skipped + right.skipped };
1007
+ const left = await sendBatch(batch.slice(0, mid), validatePresence);
1008
+ const right = await sendBatch(batch.slice(mid), validatePresence);
1009
+ return {
1010
+ merged: left.merged + right.merged,
1011
+ skipped: left.skipped + right.skipped,
1012
+ refused: [...left.refused, ...right.refused],
1013
+ indeterminate: [...left.indeterminate, ...right.indeterminate],
1014
+ };
637
1015
  };
638
1016
  let syncRes;
639
1017
  try {
@@ -653,10 +1031,47 @@ export async function runFederationSyncOnce(opts) {
653
1031
  if (!syncRes.ok) {
654
1032
  if (splittable(syncRes.status))
655
1033
  return await split();
656
- const text = await syncRes.text().catch(() => "");
657
- throw new Error(`Sync batch failed: ${syncRes.status} ${text}`);
1034
+ // flair#2455 rev 2.1 N2: the receiver's response body is receiver-authored
1035
+ // text and is never logged. Report the status only.
1036
+ throw new Error(`Sync batch failed: HTTP ${syncRes.status}`);
1037
+ }
1038
+ // A 200 is still receiver-authored: a body that is not JSON (the parser's
1039
+ // own error quotes part of it) or whose counts are not counts is an
1040
+ // invalid response, reported in local text only (flair#2455 N2).
1041
+ let body;
1042
+ try {
1043
+ body = await syncRes.json();
1044
+ }
1045
+ catch {
1046
+ throw new Error(`Sync batch failed: invalid response (HTTP ${syncRes.status}, body is not JSON)`);
1047
+ }
1048
+ const counts = parseSyncBatchCounts(body, batch.length);
1049
+ if (!counts) {
1050
+ const table = typeof batch[0]?.table === "string" ? batch[0].table : "batch";
1051
+ throw new Error(`Sync batch failed: invalid response (HTTP ${syncRes.status}, ${describeSyncBatchCountsRejection(body, batch.length, table)})`);
1052
+ }
1053
+ const refused = parseSyncBatchRefused(body);
1054
+ const indeterminate = parseSyncBatchIndeterminate(body);
1055
+ // A Memory batch changes the sender's retry state and advances its
1056
+ // cursor, so its response must account for every offered record. Presence
1057
+ // already requires the same. Other generic tables are checked on their
1058
+ // counts.
1059
+ if (validatePresence || batch[0]?.table === "Memory") {
1060
+ const outcomeBody = body;
1061
+ const validList = (raw, parsed) => raw === undefined || (Array.isArray(raw) && raw.length === parsed.length);
1062
+ const key = (row) => JSON.stringify([row.table, row.id]);
1063
+ const offered = new Set(batch.map(key));
1064
+ const unresolved = [...refused, ...indeterminate].map(key);
1065
+ if (!validList(outcomeBody.refused, refused) ||
1066
+ !validList(outcomeBody.indeterminate, indeterminate) ||
1067
+ unresolved.some((entry) => !offered.has(entry)) ||
1068
+ new Set(unresolved).size !== unresolved.length ||
1069
+ counts.skipped !== refused.length ||
1070
+ counts.merged + refused.length + indeterminate.length !== batch.length) {
1071
+ throw new Error(`Sync batch failed: invalid response (HTTP ${syncRes.status}, outcomes do not account for ${batch.length} offered records)`);
1072
+ }
658
1073
  }
659
- return await syncRes.json();
1074
+ return { ...counts, refused, indeterminate };
660
1075
  }
661
1076
  let totalBatches = 0;
662
1077
  // Memory rows that passed the since-cursor filter but were excluded as
@@ -678,7 +1093,7 @@ export async function runFederationSyncOnce(opts) {
678
1093
  res = await fetch(`${opsEndpoint}/`, {
679
1094
  method: "POST",
680
1095
  headers: { "Content-Type": "application/json", Authorization: auth },
681
- body: JSON.stringify({ operation: "search_by_conditions", schema: "flair", table, operator: "and", conditions: [query], get_attributes: table === "Memory" ? [...FEDERATION_MEMORY_SELECT] : ["*"] }),
1096
+ body: JSON.stringify({ operation: "search_by_conditions", schema: "flair", table, operator: "and", conditions: [query], get_attributes: table === "Memory" ? memorySelect : ["*"] }),
682
1097
  signal: AbortSignal.timeout(15_000),
683
1098
  });
684
1099
  }
@@ -703,6 +1118,46 @@ export async function runFederationSyncOnce(opts) {
703
1118
  privateHeldBack += sinceCursor.length - federable.length;
704
1119
  rows = rows.concat(federable);
705
1120
  }
1121
+ if (table === "Memory" && pendingRetries.size > 0) {
1122
+ // Re-offer the pending rows whose backoff has elapsed. A row still
1123
+ // selected by the since cursor is offered once (the set below). A row
1124
+ // that is gone or has become private ends its obligation here.
1125
+ const seen = new Set(rows.map((r) => r.id));
1126
+ for (const pending of pendingRetries.values()) {
1127
+ const malformed = retryRowMalformedness(pending);
1128
+ if (malformed !== null)
1129
+ reportMalformedRetryRow(pending.id, malformed);
1130
+ }
1131
+ // A source the cursor selects that also has a valid pending row is
1132
+ // offered now — a new change is not a retry, so the backoff does not
1133
+ // hold it back. Its attempt is reserved immediately before the batch
1134
+ // carrying it is sent, as on the re-offer path. A malformed row
1135
+ // reserves nothing.
1136
+ for (const row of rows) {
1137
+ const pending = pendingRetries.get(retryEntryKey(hub.id, "Memory", row.id));
1138
+ if (!pending || retryOfferProblem(pending) !== null)
1139
+ continue;
1140
+ reservationTargets.set(String(row.id), pending);
1141
+ }
1142
+ for (const pending of dueRetryRows([...pendingRetries.values()], Date.now())) {
1143
+ if (seen.has(pending.recordId))
1144
+ continue;
1145
+ const row = await loadMemoryRow(pending.recordId);
1146
+ if (!row) {
1147
+ await retireRetry(pending, "source_deleted");
1148
+ continue;
1149
+ }
1150
+ if (isFederationPrivateVisibility(row.visibility)) {
1151
+ await retireRetry(pending, "source_ineligible");
1152
+ continue;
1153
+ }
1154
+ // An unconfirmed send keeps the reservation; retry backoff applies
1155
+ // while the row remains behind the cursor.
1156
+ reservationTargets.set(String(row.id), pending);
1157
+ rows.push(row);
1158
+ seen.add(pending.recordId);
1159
+ }
1160
+ }
706
1161
  if (rows.length === 0)
707
1162
  continue;
708
1163
  // Records are signed (below) before they're batched, so the secret key
@@ -761,7 +1216,11 @@ export async function runFederationSyncOnce(opts) {
761
1216
  sr.principalId = principalId;
762
1217
  const srBytes = JSON.stringify(sr).length;
763
1218
  if (batch.length >= BUDGET_RECORDS || (batch.length > 0 && batchBytes + srBytes > BUDGET_BYTES)) {
1219
+ if (table === "Memory")
1220
+ await reserveBatchAttempts(batch);
764
1221
  const result = await sendBatch(batch);
1222
+ if (table === "Memory")
1223
+ await applyMemoryOutcomes(batch, result);
765
1224
  totalMerged += result.merged;
766
1225
  totalSkipped += result.skipped;
767
1226
  totalBatches++;
@@ -773,14 +1232,18 @@ export async function runFederationSyncOnce(opts) {
773
1232
  }
774
1233
  // Send final partial batch for this table
775
1234
  if (batch.length > 0) {
1235
+ if (table === "Memory")
1236
+ await reserveBatchAttempts(batch);
776
1237
  const result = await sendBatch(batch);
1238
+ if (table === "Memory")
1239
+ await applyMemoryOutcomes(batch, result);
777
1240
  totalMerged += result.merged;
778
1241
  totalSkipped += result.skipped;
779
1242
  totalBatches++;
780
1243
  }
781
1244
  }
782
1245
  // lastSyncAt is contact, not "the driver ran" (flair#1146). Persist only
783
- // after a FederationSync 200 — sendBatch already threw on non-ok, so
1246
+ // after a successful FederationSync response — sendBatch already threw on non-ok or invalid JSON, so
784
1247
  // totalBatches > 0 means the hub answered. The no-change path must ping
785
1248
  // first; a failed ping leaves the stamp untouched → unknown.
786
1249
  const stampLocalContact = async () => {
@@ -799,6 +1262,137 @@ export async function runFederationSyncOnce(opts) {
799
1262
  console.warn(`⚠️ Local hub.lastSyncAt advance error: ${advErr?.message ?? advErr}. Next poll will re-send memories.`);
800
1263
  }
801
1264
  };
1265
+ const genericBatches = totalBatches;
1266
+ const failPresence = async (err) => {
1267
+ if (genericBatches > 0)
1268
+ await stampLocalContact();
1269
+ return { pushed: totalMerged, skipped: totalSkipped, error: err instanceof Error ? err : new Error(String(err)) };
1270
+ };
1271
+ // ── flair#2578 slice 2: Presence push (P6) ──────────────────────────────
1272
+ // Presence has no updatedAt/createdAt, so the generic cursor above cannot
1273
+ // select it. Home rows travel by their OWN per-table watermark on
1274
+ // lastHeartbeatAt / activityUpdatedAt, sent AFTER the generic tables so the
1275
+ // receiver can bind Presence to an accepted Agent row.
1276
+ // A scan, send or response failure returns before watermark persistence.
1277
+ let presenceAdvanceMs = null;
1278
+ let presenceCapMs = Number.POSITIVE_INFINITY;
1279
+ try {
1280
+ if (presenceSendEnabled()) {
1281
+ const presenceScanAtMs = Date.now();
1282
+ const presenceRes = await fetch(`${opsEndpoint}/`, {
1283
+ method: "POST",
1284
+ headers: { "Content-Type": "application/json", Authorization: auth },
1285
+ body: JSON.stringify({ operation: "sql", sql: "SELECT * FROM flair.Presence" }),
1286
+ signal: AbortSignal.timeout(15_000),
1287
+ });
1288
+ if (!presenceRes.ok) {
1289
+ const text = await presenceRes.text().catch(() => "");
1290
+ throw new Error(`Presence scan failed (${presenceRes.status}): ${text.slice(0, 200)}`);
1291
+ }
1292
+ const parsed = await presenceRes.json();
1293
+ const list = Array.isArray(parsed) ? parsed : Array.isArray(parsed?.results) ? parsed.results : null;
1294
+ if (!list) {
1295
+ throw new Error("Presence scan failed: body is not a row list");
1296
+ }
1297
+ const presenceRows = list;
1298
+ const watermarkMs = presenceWatermarkMs(hub.presenceLastSyncAt);
1299
+ // Clamp selection to scan time.
1300
+ const effectiveWatermarkMs = Math.min(watermarkMs, presenceScanAtMs);
1301
+ // Re-scan from the effective watermark minus the overlap.
1302
+ const scanFloorMs = Math.max(0, effectiveWatermarkMs - PRESENCE_SEND_OVERLAP_MS);
1303
+ const toSend = selectPresenceRowsToSend(presenceRows, instance.id, scanFloorMs);
1304
+ if (toSend.length === 0 && watermarkMs > effectiveWatermarkMs) {
1305
+ presenceAdvanceMs = effectiveWatermarkMs;
1306
+ }
1307
+ if (toSend.length > 0) {
1308
+ if (!secretKey)
1309
+ secretKey = await loadInstanceSecretKey(instance.id, opts);
1310
+ let presenceBatch = [];
1311
+ let presenceBatchBytes = 0;
1312
+ // Overlap resends retain the effective watermark unless capped below.
1313
+ let advanceMs = effectiveWatermarkMs;
1314
+ const flushPresence = async () => {
1315
+ const result = await sendBatch(presenceBatch, true);
1316
+ totalMerged += result.merged;
1317
+ totalSkipped += result.skipped;
1318
+ totalBatches++;
1319
+ // Cap the candidate below retryable refusals, and below a row
1320
+ // refused because the hub's Presence receipt is off: enabling it
1321
+ // later must not need a new heartbeat to re-offer that row.
1322
+ for (const refusal of result.refused) {
1323
+ if (refusal.table !== "Presence")
1324
+ continue;
1325
+ if (!PRESENCE_SEND_RETRYABLE_SKIP_REASONS.has(refusal.reason) &&
1326
+ refusal.reason !== PRESENCE_SEND_RECEIVE_DISABLED_SKIP_REASON)
1327
+ continue;
1328
+ const sent = presenceBatch.find((r) => r.id === refusal.id);
1329
+ if (!sent)
1330
+ continue;
1331
+ const refusedCursor = Date.parse(sent.updatedAt);
1332
+ if (Number.isFinite(refusedCursor))
1333
+ presenceCapMs = Math.min(presenceCapMs, refusedCursor - 1);
1334
+ }
1335
+ // Apply the same cap to indeterminate outcomes.
1336
+ for (const undecided of result.indeterminate) {
1337
+ if (undecided.table !== "Presence")
1338
+ continue;
1339
+ const sent = presenceBatch.find((r) => r.id === undecided.id);
1340
+ if (!sent)
1341
+ continue;
1342
+ const undecidedCursor = Date.parse(sent.updatedAt);
1343
+ if (Number.isFinite(undecidedCursor))
1344
+ presenceCapMs = Math.min(presenceCapMs, undecidedCursor - 1);
1345
+ }
1346
+ presenceBatch = [];
1347
+ presenceBatchBytes = 0;
1348
+ };
1349
+ for (const row of toSend) {
1350
+ const cursor = presenceCursorMs(row);
1351
+ // A row dated more than the receiver's future allowance past this
1352
+ // scan is left out of the batch: the receiver may refuse it, and
1353
+ // its cursor must not count toward the watermark.
1354
+ if (cursor != null && cursor > presenceScanAtMs + PRESENCE_SEND_FUTURE_ALLOWANCE_MS)
1355
+ continue;
1356
+ const payload = presenceWireRecord(row, instance.id);
1357
+ if (!payload)
1358
+ continue;
1359
+ const sr = { ...payload, signature: signBody(payload, secretKey) };
1360
+ const srBytes = JSON.stringify(sr).length;
1361
+ if (presenceBatch.length >= BUDGET_RECORDS || (presenceBatch.length > 0 && presenceBatchBytes + srBytes > BUDGET_BYTES)) {
1362
+ await flushPresence();
1363
+ }
1364
+ presenceBatch.push(sr);
1365
+ presenceBatchBytes += srBytes;
1366
+ // Clamp the candidate to scan time.
1367
+ if (cursor != null && Math.min(cursor, presenceScanAtMs) > advanceMs)
1368
+ advanceMs = Math.min(cursor, presenceScanAtMs);
1369
+ }
1370
+ if (presenceBatch.length > 0)
1371
+ await flushPresence();
1372
+ presenceAdvanceMs = Math.min(advanceMs, presenceCapMs);
1373
+ }
1374
+ }
1375
+ }
1376
+ catch (err) {
1377
+ return await failPresence(err);
1378
+ }
1379
+ // Attempt the watermark update after contact.
1380
+ const persistPresence = async (presenceMs) => {
1381
+ try {
1382
+ const advanced = await persistLocalPeerPresenceSyncAt({
1383
+ opsEndpoint,
1384
+ auth,
1385
+ peerId: hub.id,
1386
+ presenceLastSyncAt: new Date(presenceMs).toISOString(),
1387
+ });
1388
+ if (!advanced.ok) {
1389
+ console.warn(`⚠️ Local hub.presenceLastSyncAt advance failed (${advanced.status}): ${advanced.error ?? ""}.`);
1390
+ }
1391
+ }
1392
+ catch (advErr) {
1393
+ console.warn(`⚠️ Local hub.presenceLastSyncAt advance error: ${advErr?.message ?? advErr}.`);
1394
+ }
1395
+ };
802
1396
  if (totalBatches === 0) {
803
1397
  // No-change syncs must still ping the hub so it updates the
804
1398
  // spoke's lastSyncAt (liveness). Without this, idle-but-alive spokes
@@ -819,8 +1413,8 @@ export async function runFederationSyncOnce(opts) {
819
1413
  signal: AbortSignal.timeout(10_000),
820
1414
  });
821
1415
  if (!pingRes.ok) {
822
- const txt = await pingRes.text().catch(() => "");
823
- console.warn(`⚠️ Liveness ping to hub failed (${pingRes.status}): ${txt.slice(0, 200)}. Hub won't update spoke liveness.`);
1416
+ // flair#2455 rev 2.1 N2: no receiver-authored body in the sender's log.
1417
+ console.warn(`⚠️ Liveness ping to hub failed (HTTP ${pingRes.status}). Hub won't update spoke liveness.`);
824
1418
  }
825
1419
  else {
826
1420
  pingOk = true;
@@ -831,6 +1425,8 @@ export async function runFederationSyncOnce(opts) {
831
1425
  }
832
1426
  if (pingOk)
833
1427
  await stampLocalContact();
1428
+ if (pingOk && presenceAdvanceMs != null)
1429
+ await persistPresence(presenceAdvanceMs);
834
1430
  // flair#1232: "No changes" is true only when nothing was found since
835
1431
  // the cursor. If rows were found and every one was withheld as private,
836
1432
  // say so — count and reason only, never content. A zero withheld count
@@ -841,6 +1437,8 @@ export async function runFederationSyncOnce(opts) {
841
1437
  return { pushed: 0, skipped: 0 };
842
1438
  }
843
1439
  await stampLocalContact();
1440
+ if (presenceAdvanceMs != null)
1441
+ await persistPresence(presenceAdvanceMs);
844
1442
  console.log(`✅ Synced ${totalMerged} records (${totalSkipped} skipped) across ${totalBatches} batches`);
845
1443
  return { pushed: totalMerged, skipped: totalSkipped };
846
1444
  }
@@ -943,6 +1541,18 @@ export function register(program) {
943
1541
  catch (err) {
944
1542
  peersErr = rewriteFederationStatusFetchFailed(err, baseUrl, urlSetting);
945
1543
  }
1544
+ // Federation retry rows (flair#2455): the sender's pending, terminal and
1545
+ // malformed retry rows, read through the admin-only /FederationRetries
1546
+ // resource. null = unverifiable (the read failed), like peers.
1547
+ let retries = null;
1548
+ let retriesErr = null;
1549
+ try {
1550
+ const r = await api("GET", "/FederationRetries", undefined, { baseUrl });
1551
+ retries = { pending: r.pending ?? [], terminal: r.terminal ?? [], malformed: r.malformed ?? [] };
1552
+ }
1553
+ catch (err) {
1554
+ retriesErr = err;
1555
+ }
946
1556
  // Auth-shaped failures stay FATAL even when the other read succeeded:
947
1557
  // both endpoints sit behind the same allowAdmin gate, so a 401/403 is a
948
1558
  // property of the session's credentials, not of one endpoint — and
@@ -1005,16 +1615,18 @@ export function register(program) {
1005
1615
  console.log(render.asJSON({
1006
1616
  instance,
1007
1617
  peers,
1618
+ retries,
1008
1619
  driver,
1009
1620
  driverAssessment: assessment,
1010
1621
  // flair#1233: name what could not be read, so a partial result is
1011
1622
  // distinguishable from "verified absent" (instance/peers stay null
1012
1623
  // when their read failed).
1013
- ...(instanceErr || peersErr
1624
+ ...(instanceErr || peersErr || retriesErr
1014
1625
  ? {
1015
1626
  unverifiable: {
1016
1627
  ...(instanceErr ? { instance: String(instanceErr.message ?? instanceErr) } : {}),
1017
1628
  ...(peersErr ? { peers: String(peersErr.message ?? peersErr) } : {}),
1629
+ ...(retriesErr ? { retries: String(retriesErr.message ?? retriesErr) } : {}),
1018
1630
  },
1019
1631
  }
1020
1632
  : {}),
@@ -1042,6 +1654,52 @@ export function register(program) {
1042
1654
  // Instance read failed but peers succeeded — render what we have.
1043
1655
  console.log(render.kv("Instance", `${render.icons.warn} unverifiable — ${render.wrap(render.c.dim, String(instanceErr?.message ?? instanceErr))}`));
1044
1656
  }
1657
+ // Federation retry rows (flair#2455): the sender's retry bookkeeping per
1658
+ // peer, table and record. Rendered after the peer table, and also on the
1659
+ // two early returns below (no peers configured; a peer read that fails
1660
+ // while the instance read succeeds). The fatal exits above (an instance or
1661
+ // peer read auth failure, or both those reads failing) render nothing. A
1662
+ // retry-row read that fails, including on auth, renders the section as
1663
+ // unverifiable and does not by itself make the command exit non-zero.
1664
+ // No production sender path creates rows yet; admin-written rows show.
1665
+ // Once the sender is active, it re-offers pending rows; a terminal row
1666
+ // ended with a named resolution; a malformed row breaks a sender
1667
+ // convention and is never transitioned.
1668
+ const renderRetrySection = () => {
1669
+ if (retriesErr) {
1670
+ console.log();
1671
+ console.log(`${render.icons.warn} ${render.wrap(render.c.yellow, "Federation retries unverifiable — the retry read failed.")}`);
1672
+ console.log(` ${render.wrap(render.c.dim, String(retriesErr?.message ?? retriesErr))}`);
1673
+ return;
1674
+ }
1675
+ if (!retries || (retries.pending.length === 0 && retries.terminal.length === 0 && retries.malformed.length === 0))
1676
+ return;
1677
+ console.log();
1678
+ console.log(render.wrap(render.c.bold, "Federation retries"));
1679
+ const retryCols = [
1680
+ { label: "state", key: "state" },
1681
+ { label: "peer", key: "peerId" },
1682
+ { label: "table", key: "table" },
1683
+ { label: "id", key: "id" },
1684
+ { label: "reason", key: "reason", format: (v) => String(v ?? "—") },
1685
+ { label: "attempts", key: "attempts", format: (v) => String(v ?? "—") },
1686
+ { label: "bound", key: "bound", format: (v) => String(v ?? "—") },
1687
+ { label: "resolution", key: "resolution", format: (v) => String(v ?? "—") },
1688
+ ];
1689
+ if (retries.pending.length > 0 || retries.terminal.length > 0) {
1690
+ console.log(render.table(retryCols, [...retries.pending, ...retries.terminal]));
1691
+ }
1692
+ if (retries.malformed.length > 0) {
1693
+ console.log();
1694
+ console.log(`${render.icons.warn} ${render.wrap(render.c.yellow, `${retries.malformed.length} malformed retry row${retries.malformed.length === 1 ? "" : "s"}: not pending, never transitioned.`)}`);
1695
+ const malformedCols = [
1696
+ { label: "problem", key: "problem" },
1697
+ { label: "key", key: "key", format: (v) => String(v ?? "—") },
1698
+ { label: "state", key: "state", format: (v) => String(v ?? "—") },
1699
+ ];
1700
+ console.log(render.table(malformedCols, retries.malformed));
1701
+ }
1702
+ };
1045
1703
  if (peers === null) {
1046
1704
  // Peer read failed but the instance rendered — say so explicitly
1047
1705
  // instead of aborting: "unverifiable" is a different claim from "no
@@ -1049,10 +1707,12 @@ export function register(program) {
1049
1707
  console.log();
1050
1708
  console.log(`${render.icons.warn} ${render.wrap(render.c.yellow, "Peers unverifiable — the peer read failed. This says nothing about whether peers exist or sync runs.")}`);
1051
1709
  console.log(` ${render.wrap(render.c.dim, String(peersErr?.message ?? peersErr))}`);
1710
+ renderRetrySection();
1052
1711
  return;
1053
1712
  }
1054
1713
  if (peers.length === 0) {
1055
1714
  console.log(`\n${render.icons.info} ${render.wrap(render.c.dim, "No peers configured. Use 'flair federation pair' to connect to a hub.")}`);
1715
+ renderRetrySection();
1056
1716
  return;
1057
1717
  }
1058
1718
  // Print the driver line BEFORE the per-peer table: "is anything running
@@ -1099,7 +1759,7 @@ export function register(program) {
1099
1759
  key: "status",
1100
1760
  format: (v) => {
1101
1761
  const s = String(v ?? "—");
1102
- const color = s === "paired" || s === "connected" || s === "active" ? render.c.green : s === "revoked" ? render.c.red : render.c.yellow;
1762
+ const color = isPeerMemberStatus(s) ? render.c.green : s === PEER_STATUS.REVOKED ? render.c.red : render.c.yellow;
1103
1763
  return render.wrap(color, s);
1104
1764
  },
1105
1765
  },
@@ -1124,6 +1784,7 @@ export function register(program) {
1124
1784
  },
1125
1785
  ];
1126
1786
  console.log(render.table(cols, peers));
1787
+ renderRetrySection();
1127
1788
  // Stale warning is gated on lastMergeAt (real progress), not lastSyncAt.
1128
1789
  // A peer that "syncs" every 5min but hasn't merged a record in 24h is
1129
1790
  // exactly the failure mode we want surfaced.
@@ -1253,19 +1914,21 @@ export function register(program) {
1253
1914
  if (failures > 0)
1254
1915
  process.exit(1);
1255
1916
  });
1256
- federation
1917
+ addAdminPassOptions(federation
1257
1918
  .command("pair <hub-url>")
1258
1919
  .description("Pair this spoke with a hub instance")
1259
- .option("--port <port>", "Harper HTTP port")
1260
- .option(ADMIN_PASS_FILE_FLAG, ADMIN_PASS_FILE_HELP)
1261
- .option("--admin-pass <pass>", ADMIN_PASS_HELP)
1920
+ .option("--port <port>", "Harper HTTP port"))
1262
1921
  .option("--admin-user <name>", "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)")
1263
1922
  .option("--ops-port <port>", "Harper operations API port")
1264
1923
  .option("--token <token>", "One-time pairing token from hub admin (env: FLAIR_PAIRING_TOKEN) [deprecated: use --token-from]")
1265
1924
  .option("--token-from <file>", "Read bootstrap triple from JSON file (use '-' for stdin)")
1266
1925
  .option("--target <url>", "Remote Flair URL (env: FLAIR_TARGET)")
1267
1926
  .option("--ops-target <url>", "Explicit ops API URL (env: FLAIR_OPS_TARGET; bypasses port derivation)")
1268
- .action(async (hubUrl, opts) => {
1927
+ .action(async (hubUrlArg, opts) => {
1928
+ // Strip trailing slashes once, before the hub URL is used or stored, so a
1929
+ // trailing slash on the typed URL does not add an empty path segment to
1930
+ // the appended pairing route or the stored hub-peer endpoint.
1931
+ const hubUrl = normalizeHubUrl(hubUrlArg);
1269
1932
  const target = resolveTarget(opts);
1270
1933
  // flair#1873: resolve the SPOKE admin credential FIRST, before any
1271
1934
  // request. `--admin-pass-file` is read in-process (mode 0600 enforced),
@@ -1501,12 +2164,10 @@ export function register(program) {
1501
2164
  process.exit(1);
1502
2165
  }
1503
2166
  });
1504
- federation
2167
+ addAdminPassOptions(federation
1505
2168
  .command("token")
1506
2169
  .description("Generate a one-time pairing token (run on the hub)")
1507
- .option("--port <port>", "Harper HTTP port")
1508
- .option(ADMIN_PASS_FILE_FLAG, ADMIN_PASS_FILE_HELP)
1509
- .option("--admin-pass <pass>", ADMIN_PASS_HELP)
2170
+ .option("--port <port>", "Harper HTTP port"))
1510
2171
  .option("--admin-user <name>", "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)")
1511
2172
  .option("--ops-port <port>", "Harper operations API port")
1512
2173
  .option("--ttl <minutes>", "Token TTL in minutes (default: 60)", "60")
@@ -1604,7 +2265,6 @@ export function register(program) {
1604
2265
  .option("--ops-target <url>", "Explicit ops API URL (env: FLAIR_OPS_TARGET; bypasses port derivation)")).action(async (opts) => {
1605
2266
  // --admin-pass-file resolves into the same `adminPass` slot the inline
1606
2267
  // flag uses, so the scheduler never has to embed a secret in a unit file.
1607
- applyAdminPassFile(opts);
1608
2268
  const r = await runFederationSyncOnce(opts);
1609
2269
  if (r.error) {
1610
2270
  console.error(`Error: ${r.error.message}`);
@@ -1688,6 +2348,7 @@ export function register(program) {
1688
2348
  .command("disable")
1689
2349
  .description("Remove the sync driver (peers and sync history are preserved)")
1690
2350
  .option("--remove-shim", "Also delete the ~/.flair/bin/flair-federation-sync shim")
2351
+ .hook("preAction", (_thisCommand, actionCommand) => applyInheritedAdminPass(actionCommand))
1691
2352
  .action(async (opts) => {
1692
2353
  const { disableScheduler } = await import("../federation/scheduler.js");
1693
2354
  try {
@@ -1720,6 +2381,7 @@ export function register(program) {
1720
2381
  // `flair federation sync` owns them and commander binds them there. They
1721
2382
  // still work on this command, via optsWithGlobals() below.
1722
2383
  .option("--json", "Emit JSON")
2384
+ .hook("preAction", (_thisCommand, actionCommand) => applyInheritedAdminPass(actionCommand))
1723
2385
  .action(async (_opts, cmd) => {
1724
2386
  // See the comment on `enable` above: `--target`/`--port` live on the
1725
2387
  // parent, so commander binds them there and only optsWithGlobals() sees
@@ -1749,12 +2411,11 @@ export function register(program) {
1749
2411
  process.exit(1);
1750
2412
  }
1751
2413
  });
1752
- federation
2414
+ addAdminPassOptions(federation
1753
2415
  .command("watch")
1754
2416
  .description("Run federation sync in a loop (foreground daemon)")
1755
2417
  .option("--interval <seconds>", "Seconds between syncs", "30")
1756
- .option("--port <port>", "Harper HTTP port")
1757
- .option("--admin-pass <pass>", "Admin password")
2418
+ .option("--port <port>", "Harper HTTP port"), "Admin password")
1758
2419
  .option("--admin-user <name>", "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)")
1759
2420
  .option("--ops-port <port>", "Harper operations API port")
1760
2421
  .option("--target <url>", "Remote Flair URL")
@@ -1822,31 +2483,77 @@ export function register(program) {
1822
2483
  console.log(`Run with --apply to actually delete.`);
1823
2484
  return;
1824
2485
  }
1825
- // Apply path. Delete each peer via the Harper ops API. We use the
1826
- // domain-socket form when local; otherwise we fall back to the resource
1827
- // DELETE which requires admin auth.
2486
+ // Apply path: delete each peer's `flair.Peer` row through the admin-only
2487
+ // `/Peer/{id}` REST resource and read it back to confirm it is gone.
1828
2488
  let deleted = 0;
1829
2489
  let errors = 0;
2490
+ let unknown = 0;
2491
+ const requestOptions = baseUrl ? { baseUrl } : undefined;
2492
+ // The DELETE's own body is not evidence, so a 2xx whose body is empty or
2493
+ // not JSON must not throw: the server may already have deleted the row.
2494
+ const deleteOptions = { ...(requestOptions ?? {}), tolerateUnparsedSuccessBody: true };
1830
2495
  for (const p of candidates) {
2496
+ let refusal;
1831
2497
  try {
1832
- const res = await api("DELETE", `/FederationPeers/${encodeURIComponent(p.id)}`, undefined, baseUrl ? { baseUrl } : undefined);
1833
- const ok = res?.ok ?? res?.deleted ?? true;
1834
- if (ok) {
1835
- deleted++;
1836
- const ts = p.lastSyncAt ?? p.pairedAt ?? "never";
1837
- console.log(`Deleted ${p.id} (last seen ${ts}).`);
2498
+ await api("DELETE", `/Peer/${encodeRecordId(p.id)}`, undefined, deleteOptions);
2499
+ }
2500
+ catch (e) {
2501
+ if (e instanceof ApiRequestOutcomeUnknown) {
2502
+ // An expired request is reported as an unknown outcome, like every
2503
+ // other non-GET/HEAD request through the shared REST sender: the client cannot tell
2504
+ // whether the server acted. Count it apart from a definite failure
2505
+ // and exit 3 for it (unknown outranks a known failure, as rem's
2506
+ // `unresolved` does).
2507
+ unknown++;
2508
+ console.log(`Unknown outcome for ${p.id}: ${e.message}`);
2509
+ continue;
1838
2510
  }
2511
+ if (e instanceof ApiHttpError)
2512
+ refusal = e;
1839
2513
  else {
1840
2514
  errors++;
1841
- console.log(`Failed to delete ${p.id}: ${JSON.stringify(res)}`);
2515
+ console.log(`Failed to delete ${p.id}: ${e.message}`);
2516
+ continue;
1842
2517
  }
1843
2518
  }
2519
+ // 404 or a null body means absent; a row means it is still there. A
2520
+ // read failure after a successful DELETE is an unknown outcome.
2521
+ let present;
2522
+ try {
2523
+ const row = await api("GET", `/Peer/${encodeRecordId(p.id)}`, undefined, requestOptions);
2524
+ present = row != null;
2525
+ }
1844
2526
  catch (e) {
2527
+ if (e instanceof ApiHttpError && e.status === 404)
2528
+ present = false;
2529
+ else if (refusal) {
2530
+ errors++;
2531
+ console.log(`Failed to delete ${p.id}: ${refusal.message}`);
2532
+ continue;
2533
+ }
2534
+ else {
2535
+ unknown++;
2536
+ console.log(`Unknown outcome for ${p.id}: the delete returned, but reading the row back failed: ${e.message}`);
2537
+ continue;
2538
+ }
2539
+ }
2540
+ if (refusal) {
2541
+ errors++;
2542
+ console.log(`Failed to delete ${p.id}: ${refusal.message}`);
2543
+ }
2544
+ else if (!present) {
2545
+ deleted++;
2546
+ const ts = p.lastSyncAt ?? p.pairedAt ?? "never";
2547
+ console.log(`Deleted ${p.id} (last seen ${ts}).`);
2548
+ }
2549
+ else {
1845
2550
  errors++;
1846
- console.log(`Failed to delete ${p.id}: ${e.message}`);
2551
+ console.log(`Failed to delete ${p.id}: the row is still present after the DELETE.`);
1847
2552
  }
1848
2553
  }
1849
- console.log(`${deleted} peer(s) deleted; ${errors} error(s).`);
2554
+ console.log(`${deleted} peer(s) deleted; ${errors} error(s); ${unknown} unknown outcome(s).`);
2555
+ if (unknown > 0)
2556
+ process.exit(3);
1850
2557
  if (errors > 0)
1851
2558
  process.exit(1);
1852
2559
  });
@@ -1864,7 +2571,6 @@ export function register(program) {
1864
2571
  const instanceOpsEndpoint = (opts) => {
1865
2572
  // --admin-pass-file resolves into the same `adminPass` slot the inline flag
1866
2573
  // uses (the shared idiom: the secret stays out of ps and shell history).
1867
- applyAdminPassFile(opts);
1868
2574
  const opsUrl = resolveEffectiveOpsUrl(opts) ?? `http://127.0.0.1:${resolveOpsPort(opts)}`;
1869
2575
  const adminPass = opts.adminPass ?? process.env.FLAIR_ADMIN_PASS ?? "";
1870
2576
  return { opsUrl, credentials: { user: resolveAdminUser(opts.adminUser), pass: adminPass } };
@@ -1994,7 +2700,6 @@ export function register(program) {
1994
2700
  .option("--ops-port <port>", "Harper operations API port")
1995
2701
  .option("--target <url>", "Remote Flair URL (env: FLAIR_TARGET)")
1996
2702
  .option("--ops-target <url>", "Explicit ops API URL (env: FLAIR_OPS_TARGET; bypasses port derivation)"))).action(async (opts) => {
1997
- applyAdminPassFile(opts);
1998
2703
  const target = resolveTarget(opts);
1999
2704
  const baseUrl = target ? target.replace(/\/$/, "") : undefined;
2000
2705
  const waitSeconds = Number(opts.wait) || 60;
@@ -2012,7 +2717,7 @@ export function register(program) {
2012
2717
  peerId: opts.peer,
2013
2718
  baseUrl,
2014
2719
  syncOpts: opts,
2015
- // GET /FederationPeers is allowAdmin. applyAdminPassFile already
2720
+ // GET /FederationPeers is allowAdmin. The preAction hook already
2016
2721
  // folded --admin-pass-file into opts.adminPass; without this the
2017
2722
  // injected api only sees { baseUrl } and flag-only creds never
2018
2723
  // reach the listing (UNVERIFIABLE, check never runs).