@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,20 +1,34 @@
1
+ import { normalizeEmptyEmbedding } from "./memory-embedding-value.js";
1
2
  import { Resource, databases, server } from "harper";
2
3
  import { randomBytes, randomUUID } from "node:crypto";
3
4
  import nacl from "tweetnacl";
4
5
  import { allowAdmin } from "./agent-auth.js";
6
+ import { configuredAdminAgentIds } from "./agent-admin.js";
5
7
  import { canonicalize, signBody, verifyBodySignature, signBodyFresh, verifyBodySignatureFresh, generateNonce, } from "./federation-crypto.js";
6
8
  import { reconcileState } from "./relay-lib.js";
7
9
  import { decideInstanceAnswer, INSTANCE_ROW_PRUNE_REMEDY, multipleInstanceRowsMessage, } from "../src/lib/instance-identity-row.js";
8
10
  import { readAllInstanceRows } from "./instance-identity-rows.js";
9
- import { findOrCreateInstance } from "./instance-create-lock.js";
11
+ import { findOrCreateInstance, storeInstanceSeed } from "./instance-create-lock.js";
10
12
  import { withDetachedTxnAsync } from "./table-helpers.js";
11
13
  import { isSkillWrite } from "./skill-write.js";
14
+ import { stampEphemeralExpiry } from "./memory-durability.js";
15
+ import { isReservedSeedId } from "./seed-reservation.js";
16
+ import { AGENT_ID_ERROR, isValidAgentId } from "../src/lib/agent-id-rule.js";
17
+ import { endsWithContentSelectorSuffix } from "../src/lib/memory-id-policy.js";
12
18
  import { stripInboundMemoryRow, stripServerStampedFields } from "./memory-declared-attributes.js";
13
19
  import { noteWriteStamp } from "./embedding-space-guard.js";
14
20
  import { initFederationCleanup } from "./federation-cleanup.js";
15
21
  import { verifyFederationRequestBody } from "./replay-store.js";
16
- import { classifyRecord, reconstructRecordVerifyBody, checkPrincipalEntitlement, inboundChangesExistingPrincipalStatus, } from "./federation-classify.js";
17
- export { classifyRecord, reconstructRecordVerifyBody, checkPrincipalEntitlement, inboundChangesExistingPrincipalStatus, recordSignatureVersion, PRINCIPAL_OWNING_TABLES, FEDERATION_TABLE_POLICY, FEDERATION_SYNC_TABLES, } from "./federation-classify.js";
22
+ import { CommittedRowChanged, confirmCommittedRow, verifyCommittedFields, withoutHarperManagedFields, writeBackCommittedRow, WriteBackConflictError } from "./write-back.js";
23
+ import { withKeyLock } from "./key-lock.js";
24
+ import { withOwnedTransaction } from "./request-transaction.js";
25
+ import { txnFault, txnPausePoint } from "./txn-pause-point.js";
26
+ import { withMemoryWriteLockOnce, writeOutcomeUnknownResponse } from "./memory-write-lock.js";
27
+ import { isDeepStrictEqual } from "node:util";
28
+ import { retryRowProblem } from "./federation-retry-lib.js";
29
+ import { classifyRecord, reconstructRecordVerifyBody, checkPrincipalEntitlement, inboundChangesExistingPrincipalStatus, inboundChangesExistingPendingKey, agentAdminIdCreateRefusal, agentIdentityRefusal, keepReceiverAgentAuthority, } from "./federation-classify.js";
30
+ import { mergePresenceReceipt, presenceHomeBindingReason, presenceReceiveEnabled, validatePresenceReceipt, } from "./presence-receipt.js";
31
+ export { classifyRecord, reconstructRecordVerifyBody, checkPrincipalEntitlement, inboundChangesExistingPrincipalStatus, inboundChangesExistingPendingKey, recordSignatureVersion, PRINCIPAL_OWNING_TABLES, FEDERATION_TABLE_POLICY, FEDERATION_SYNC_TABLES, SKIP_REASON_CLASS, SKIP_REASONS, RETRYABLE_SKIP_REASONS, isSkipReason, } from "./federation-classify.js";
18
32
  // Federation anti-replay: FederationPair and FederationSync both verify through
19
33
  // verifyFederationRequestBody (resources/replay-store.ts), which claims each
20
34
  // body nonce ONCE in the instance-wide `ReplayNonce` table after the signature
@@ -105,18 +119,18 @@ export function mergeRecord(local, remote) {
105
119
  * cosine that foreign vector = mixed-space garbage — exactly the failure the
106
120
  * guard exists to kill. Trip the latch here.
107
121
  *
108
- * `noteWriteStamp` no-ops for a current/bare stamp (a self-originated or
109
- * same-space sync) and for a non-Memory table (no `embeddingModel`), so only a
110
- * genuinely foreign Memory sync trips it. Kept as a note-ONLY helper — the raw
111
- * `table.put(mergedData)` stays INLINE at the call site so the raw-writer
112
- * coverage gates (authority-field-guard.test.ts / memory-embedding-writer-
113
- * coverage.test.ts) still enumerate the Memory writer — while the trip decision
114
- * itself is unit-testable without standing up the full signed sync-in path (see
122
+ * Kept as a note-ONLY helper — the
123
+ * merge's row write stays INLINE at the call site (every synced table's merge
124
+ * through the shared write-back helper, write-back.ts, flair#2441/flair#2450),
125
+ * so the raw-writer coverage gates
126
+ * (authority-field-guard.test.ts / memory-embedding-writer-coverage.test.ts)
127
+ * still enumerate the writer — while the trip decision itself is
128
+ * unit-testable without standing up the full signed sync-in path (see
115
129
  * test/unit-isolated/embedding-space-guard-federation.test.ts).
116
130
  */
117
- export function noteFederationMergedMemory(recordTable, mergedData) {
131
+ export function noteFederationMergedMemory(recordTable, mergedData, previous) {
118
132
  if (recordTable === "Memory") {
119
- noteWriteStamp(mergedData.embeddingModel);
133
+ noteWriteStamp(mergedData.embeddingModel, previous);
120
134
  }
121
135
  }
122
136
  // ─── Instance identity ───────────────────────────────────────────────────────
@@ -240,10 +254,7 @@ export class FederationInstance extends Resource {
240
254
  // the request (the lock cannot serialise a write that commits after the
241
255
  // method returns — the earlier BLOCKED finding, flair#1897 slice 1).
242
256
  put: (row) => withDetachedTxnAsync(this.getContext?.(), () => databases.flair.Instance.put(row)),
243
- setSeed: (createdId, seed) => withDetachedTxnAsync(this.getContext?.(), async () => {
244
- const { keystore } = await import("../src/keystore.js");
245
- keystore.setPrivateKeySeed(createdId, seed);
246
- }),
257
+ setSeed: (createdId, seed) => withDetachedTxnAsync(this.getContext?.(), () => storeInstanceSeed(createdId, seed)),
247
258
  seedPresent: async (rowId) => {
248
259
  try {
249
260
  const { keystore } = await import("../src/keystore.js");
@@ -325,7 +336,34 @@ export class FederationInstance extends Resource {
325
336
  /**
326
337
  * POST /FederationPair — one-shot pairing handshake.
327
338
  * A spoke sends its instance identity; the hub records it as a peer.
328
- * Requires a one-time pairing token generated by `flair federation token`.
339
+ * A FIRST-time pair requires a one-time pairing token generated by
340
+ * `flair federation token`. An otherwise valid, non-revoked RE-pair of an
341
+ * existing peer (same instance id, and a signed request whose key equals the
342
+ * pinned public key) requires NO token — the protocol requires none for an
343
+ * existing peer — though it validates and consumes a supplied one. A re-pair of
344
+ * a revoked peer is refused.
345
+ *
346
+ * Before writing, a re-pair rechecks the pinned key and status inside its owned
347
+ * transaction; a supplied token must pass validation before that Peer re-read.
348
+ * A key that differs is refused (409); otherwise a revoked
349
+ * row is refused (403 peer_revoked). Either refusal writes no Peer row and
350
+ * consumes no token. A row deleted before that re-read is no longer an existing
351
+ * peer: with a valid token the request is paired as a first-time pair with that
352
+ * token; without one it is refused (401, a pairing token is required). On the
353
+ * token path the owned transaction's first read is its token read, so these
354
+ * re-read checks cover a change committed before that read, not after it.
355
+ *
356
+ * A first-time pair (no Peer row at the pre-transaction read) stages its token
357
+ * consume and its Peer write in one owned transaction, then confirms against
358
+ * committed state that the Peer row is still absent before that transaction
359
+ * commits. If that confirm read finds a row for the instance in committed state
360
+ * although the pre-transaction read returned none, the pair is refused (409
361
+ * peer_row_appeared): the transaction aborts, so this request writes no Peer row
362
+ * and the token stays unconsumed. The confirm reports only a row present when it
363
+ * runs, not when that row was committed; it also detects a row committed after
364
+ * the transaction's token read, if that row is still present. Harper has no
365
+ * compare-and-set on a table write, so a row committed after the confirm read
366
+ * and before the commit is not seen by it.
329
367
  */
330
368
  export class FederationPair extends Resource {
331
369
  // Pairing is a public endpoint by design — spokes have no Harper credentials
@@ -405,87 +443,254 @@ export class FederationPair extends Resource {
405
443
  INSTANCE_ROW_PRUNE_REMEDY,
406
444
  }), { status: 409, headers: { "content-type": "application/json" } });
407
445
  }
408
- // Check if already paired (re-pairing doesn't need a token)
446
+ // Check for an existing peer; an otherwise valid, non-revoked re-pair needs no token.
409
447
  const existing = await databases.flair.Peer.get(instanceId);
410
448
  if (existing) {
411
- // Re-pairing: verify public key matches (prevents impersonation)
412
- if (existing.publicKey !== publicKey) {
413
- return new Response(JSON.stringify({
414
- error: "public key mismatch — peer already paired with different key",
415
- }), { status: 409, headers: { "content-type": "application/json" } });
416
- }
417
- // Update endpoint and status
418
- await databases.flair.Peer.put({
419
- ...existing,
420
- endpoint: endpoint ?? existing.endpoint,
449
+ // Re-pairing: verify public key matches (prevents impersonation). Both
450
+ // owned-transaction writes below repeat this comparison on their re-read.
451
+ if (existing.publicKey !== publicKey)
452
+ return publicKeyMismatchRefusal();
453
+ // A revoked peer does not re-pair (flair#2333): a revoke is a local
454
+ // decision, and a re-pair does not restore it. This runs BEFORE any token
455
+ // is consumed, so this refusal changes neither the Peer row nor a token.
456
+ if (existing.status === "revoked")
457
+ return peerRevokedRefusal();
458
+ // An otherwise valid, non-revoked re-pair validates and consumes a supplied
459
+ // token as the first-pair path does (flair#2333), under this node's token
460
+ // lock; a consumed token cannot pair a later new peer. Such a re-pair with
461
+ // NO token still proceeds — the protocol requires none (docs/federation.md,
462
+ // "Pairing tokens"). The supplied token is not the request's credential;
463
+ // the request still has to prove key ownership above (`verifyResult`).
464
+ //
465
+ // With a supplied token, the consume AND this peer write run in a FRESH
466
+ // OWNED transaction committed BEFORE the lock releases (withOwnedTransaction).
467
+ // Harper commits the request's own transaction only after this handler
468
+ // returns, so a consume that joined it would still be invisible when the lock
469
+ // frees and a pairing taking the lock right after would read the token
470
+ // unconsumed. The consume and the peer write commit together or neither does:
471
+ // a Peer write that REJECTS inside this transaction callback aborts the owned
472
+ // transaction, so the token is left unconsumed and this re-pair is refused by
473
+ // name (a commit-time error propagates unnamed).
474
+ //
475
+ // Both paths build an existing peer's updated row from their transactional
476
+ // re-read, never from the pre-transaction read above.
477
+ const rePairedRow = (base) => ({
478
+ ...base,
479
+ endpoint: endpoint ?? base.endpoint,
421
480
  status: "paired",
422
481
  updatedAt: new Date().toISOString(),
423
482
  });
483
+ const writePeerRow = (owned, row) => databases.flair.Peer.put(row, owned);
484
+ if (pairingToken) {
485
+ const ctx = this.getContext?.() ?? {};
486
+ // Test-only: inert unless the fault-injection env opt-in is set and armed.
487
+ // Pause AFTER the pre-transaction read of the Peer row and BEFORE the owned
488
+ // transaction, so a competing revoke, key change or delete can commit in
489
+ // between (flair#2333).
490
+ const tokenRepairPause = txnPausePoint("federation-pair-repair-token-pre");
491
+ if (tokenRepairPause)
492
+ await tokenRepairPause;
493
+ let refusal;
494
+ let stagedFirstPeer;
495
+ let stagedPeer;
496
+ let stagedToken;
497
+ try {
498
+ refusal = await withPairingTokenClaim(pairingToken, () => withOwnedTransaction(ctx, async (owned) => {
499
+ const claim = await consumePairingToken(pairingToken, instanceId, owned);
500
+ if (claim.kind !== "consumed")
501
+ return claim;
502
+ stagedToken = claim;
503
+ // The Peer re-read sees a change committed before the owned
504
+ // transaction's first read (its token read); a change committed
505
+ // after that read is not covered by this re-read. A pinned key that
506
+ // differs from the signed request's key is refused 409, a revoked row
507
+ // 403 peer_revoked; throwing aborts the transaction, so the staged
508
+ // consume rolls back and no Peer row is written.
509
+ const current = await databases.flair.Peer.get(instanceId, owned);
510
+ if (current && current.publicKey !== publicKey)
511
+ throw new PeerKeyChangedDuringRepairError();
512
+ if (current?.status === "revoked")
513
+ throw new PeerRevokedDuringRepairError();
514
+ // A row deleted before the re-read: this is no longer a re-pair, and
515
+ // the valid token just consumed makes it a first-time pair. Write the
516
+ // row the first-pair path writes, built from the verified request —
517
+ // no field of the deleted row survives.
518
+ if (!current)
519
+ stagedFirstPeer = { ...firstPairPeerRow(instanceId, publicKey, role, endpoint), pairAttemptWriteId: claim.pairAttemptWriteId };
520
+ try {
521
+ // The marker is this attempt's last-writer id for the field (see
522
+ // StagedPairPeer): a field-level competitor merged in this window
523
+ // can leave it on the committed row alongside its own fields.
524
+ stagedPeer = current ? { ...rePairedRow(current), pairAttemptWriteId: claim.pairAttemptWriteId } : stagedFirstPeer;
525
+ await writePeerRow(owned, stagedPeer);
526
+ }
527
+ catch (err) {
528
+ // Rethrow so the owned transaction ABORTS: the consume rolls back
529
+ // with the peer write (both commit or neither does). Tagged so the
530
+ // caller answers a named refusal, not a bare 500.
531
+ throw new PeerWriteFailedError(err);
532
+ }
533
+ if (stagedFirstPeer)
534
+ await confirmFirstPairBeforeCommit(instanceId);
535
+ // Test-only: inert unless the fault-injection env opt-in is set and
536
+ // armed. Holds the existing-Peer re-pair after its Peer write and
537
+ // before the owned transaction commits, so a competing write to
538
+ // the same Peer can commit in between (flair#2691).
539
+ const beforeCommit = txnPausePoint("federation-pair-repair-token-before-commit");
540
+ if (beforeCommit)
541
+ await beforeCommit;
542
+ return claim;
543
+ }));
544
+ }
545
+ catch (err) {
546
+ if (err instanceof CommittedRowChanged)
547
+ return firstPairRowAppearedRefusal();
548
+ if (err instanceof PeerWriteFailedError) {
549
+ const cause = err.cause;
550
+ console.error(`[federation] POST /FederationPair re-pair: the Peer write failed; the owned transaction aborted, so the pairing token is NOT consumed (unconsumed and retryable while valid). ` +
551
+ `${cause?.constructor?.name ?? "Error"}: ${cause?.message ?? cause}`);
552
+ return peerWriteFailedRefusal();
553
+ }
554
+ if (err instanceof PeerRevokedDuringRepairError) {
555
+ console.error("[federation] POST /FederationPair re-pair: the Peer row was revoked before the owned transaction read it; the owned transaction aborted, so the pairing token is NOT consumed.");
556
+ return peerRevokedRefusal();
557
+ }
558
+ if (err instanceof PeerKeyChangedDuringRepairError) {
559
+ console.error("[federation] POST /FederationPair re-pair: the Peer row's pinned key no longer matches the signed request's key; the owned transaction aborted, so the pairing token is NOT consumed and no peer was written.");
560
+ return publicKeyMismatchRefusal();
561
+ }
562
+ throw err;
563
+ }
564
+ if (refusal)
565
+ return refusal;
566
+ const commitPause = txnPausePoint("federation-pair-repair-token-commit");
567
+ if (commitPause)
568
+ await commitPause;
569
+ if (!stagedPeer || !stagedToken)
570
+ return firstPairCommitUnconfirmedRefusal();
571
+ const unconfirmed = await confirmTokenPairAfterCommit(pairingToken, stagedPeer, stagedToken, !!stagedFirstPeer);
572
+ if (unconfirmed)
573
+ return unconfirmed;
574
+ if (stagedFirstPeer)
575
+ await dropPairBootstrapUser(pairingToken, ctx);
576
+ }
577
+ // The NO-token re-pair's peer write: the token path wrote the row inside the
578
+ // owned transaction above, so its consume and write committed together before
579
+ // the lock released. This path spends no token, but the same shape applies: the
580
+ // write runs in a FRESH OWNED transaction (withOwnedTransaction) that RE-READS
581
+ // the Peer row the pre-transaction read above decided on. A row whose pinned
582
+ // key now differs from the signed request's key is refused 409 (the key
583
+ // mismatch above); a row that is now revoked is refused with the token path's
584
+ // 403 peer_revoked; a row that is now gone means this is no longer a re-pair,
585
+ // and with no token it is refused like a first-time pair without one (401, a
586
+ // pairing token is required). None of these writes a row. The pause below
587
+ // still sits BEFORE that owned transaction, so a competing change commits in
588
+ // between (the guard tests).
589
+ const repairPause = txnPausePoint("federation-pair-repair-pre");
590
+ if (repairPause)
591
+ await repairPause;
592
+ if (!pairingToken) {
593
+ const ctx = this.getContext?.() ?? {};
594
+ let stagedPeer;
595
+ const refusal = await withOwnedTransaction(ctx, async (owned) => {
596
+ const current = await databases.flair.Peer.get(instanceId, owned);
597
+ if (!current)
598
+ return pairingTokenRequiredRefusal();
599
+ if (current.publicKey !== publicKey)
600
+ return publicKeyMismatchRefusal();
601
+ if (current.status === "revoked")
602
+ return peerRevokedRefusal();
603
+ // Same last-writer marker as the token route (see StagedPairPeer).
604
+ stagedPeer = { ...rePairedRow(current), pairAttemptWriteId: randomUUID() };
605
+ await writePeerRow(owned, stagedPeer);
606
+ // Test-only: inert unless the fault-injection env opt-in is set and
607
+ // armed. Holds the no-token re-pair after its Peer write and before
608
+ // the owned transaction commits, so a competing write to the same
609
+ // Peer can commit in between (flair#2691).
610
+ const beforeCommit = txnPausePoint("federation-pair-repair-before-commit");
611
+ if (beforeCommit)
612
+ await beforeCommit;
613
+ return undefined;
614
+ });
615
+ if (refusal)
616
+ return refusal;
617
+ const commitPause = txnPausePoint("federation-pair-repair-commit");
618
+ if (commitPause)
619
+ await commitPause;
620
+ // The staged row spreads the re-read row, so the compared fields are its
621
+ // application fields: Harper's own timestamps are left out.
622
+ if (!stagedPeer || await verifyCommittedFields(databases.flair.Peer, instanceId, stagedPeer, withoutHarperManagedFields(stagedPeer)) !== "shown")
623
+ return writeOutcomeUnknownResponse();
624
+ }
424
625
  }
425
626
  else {
426
627
  // New peer — require a valid pairing token in the request body.
427
628
  // The handler self-validates because the endpoint is public at the
428
629
  // Harper-auth and middleware layers (Bearer is not usable on Harper —
429
630
  // its auth layer claims unknown Bearer values and 401s).
430
- if (!pairingToken) {
431
- return new Response(JSON.stringify({
432
- error: "pairingToken required in body for first-time pair",
433
- }), { status: 401, headers: { "content-type": "application/json" } });
434
- }
435
- // Fetch the token record for consumption
436
- let tokenRecord = null;
437
- try {
438
- tokenRecord = await databases.flair.PairingToken.get(pairingToken);
439
- }
440
- catch { /* table may not exist */ }
441
- if (!tokenRecord || tokenRecord.consumedBy) {
442
- return new Response(JSON.stringify({ error: "invalid_or_expired_pairing_token" }), {
443
- status: 401, headers: { "content-type": "application/json" },
444
- });
445
- }
446
- if (tokenRecord.expiresAt && new Date(tokenRecord.expiresAt) < new Date()) {
447
- return new Response(JSON.stringify({ error: "invalid_or_expired_pairing_token" }), {
448
- status: 401, headers: { "content-type": "application/json" },
449
- });
450
- }
451
- // PR-4: bind authenticated bootstrap user to specific pairing token
631
+ if (!pairingToken)
632
+ return pairingTokenRequiredRefusal();
633
+ // Consume the token under its per-key lock (flair#2333): the claim is
634
+ // check-then-consume, so two pairings on this node using the same token
635
+ // cannot both commit a successful claim. The lock is this ONE Flair node's
636
+ // PairingToken store lock, so it excludes concurrent pairings on this node; it
637
+ // is not shared across the nodes of a Fabric instance (see the PR body).
638
+ // A contender exhausting lock attempts while the lock is held gets 409;
639
+ // one acquiring it after a successful claim commits sees the consumed
640
+ // token and gets 401.
641
+ //
642
+ // The consume AND the Peer write run in a FRESH OWNED transaction that is
643
+ // COMMITTED before the lock releases (withOwnedTransaction). Harper wraps
644
+ // POST /FederationPair in a REQUEST transaction that commits only after the
645
+ // handler returns, so writes that joined it would still be invisible when
646
+ // the lock frees: a pairing that takes the lock right after release could
647
+ // re-read the token unconsumed and pair a second peer. Detaching the request
648
+ // transaction re-reads the token from committed state and commits the
649
+ // consume and the Peer write while the lock is held.
452
650
  const ctx = this.getContext?.() ?? {};
453
- const authedUser = ctx.request?.tpsAgent;
454
- const isAdmin = ctx.request?.tpsAgentIsAdmin === true;
455
- if (!isAdmin && authedUser) {
456
- const expectedBootstrap = `pair-bootstrap-${pairingToken.slice(0, 8)}`;
457
- if (authedUser !== expectedBootstrap) {
458
- return new Response(JSON.stringify({
459
- error: "bootstrap_user_token_mismatch",
460
- }), { status: 401, headers: { "content-type": "application/json" } });
461
- }
462
- }
463
- // Consume the token
464
- await databases.flair.PairingToken.put({
465
- ...tokenRecord,
466
- consumedBy: instanceId,
467
- consumedAt: new Date().toISOString(),
468
- });
469
- await databases.flair.Peer.put({
470
- id: instanceId,
471
- publicKey,
472
- role: role ?? "spoke",
473
- endpoint: endpoint ?? null,
474
- status: "paired",
475
- relayOnly: false,
476
- pairedAt: new Date().toISOString(),
477
- createdAt: new Date().toISOString(),
478
- updatedAt: new Date().toISOString(),
479
- });
480
- // Drop the bootstrap user that was created alongside this pairing token.
481
- // Failure here is non-fatal: the cleanup sweep (PR-5) will catch stragglers.
651
+ // Test-only: inert unless the fault-injection env opt-in is set and armed.
652
+ // Pause AFTER the pre-transaction read of the Peer row and BEFORE the owned
653
+ // transaction, so a competing pair or revoke for this instance commits in
654
+ // between (flair#2512).
655
+ const firstPairPause = txnPausePoint("federation-pair-first-pre");
656
+ if (firstPairPause)
657
+ await firstPairPause;
658
+ let refusal;
659
+ let stagedFirstPeer;
660
+ let stagedToken;
482
661
  try {
483
- const bootstrapUsername = `pair-bootstrap-${pairingToken.slice(0, 8)}`;
484
- await server.operation({ operation: "drop_user", username: bootstrapUsername }, ctx, false);
662
+ refusal = await withPairingTokenClaim(pairingToken, () => withOwnedTransaction(ctx, async (owned) => {
663
+ const claim = await consumePairingToken(pairingToken, instanceId, owned);
664
+ if (claim.kind !== "consumed")
665
+ return claim;
666
+ stagedToken = claim;
667
+ stagedFirstPeer = { ...firstPairPeerRow(instanceId, publicKey, role, endpoint), pairAttemptWriteId: claim.pairAttemptWriteId };
668
+ await databases.flair.Peer.put(stagedFirstPeer, owned);
669
+ await confirmFirstPairBeforeCommit(instanceId);
670
+ return claim;
671
+ }));
485
672
  }
486
673
  catch (err) {
487
- console.warn(`[federation] drop_user failed: ${err?.message} — cleanup sweep will retry`);
674
+ if (err instanceof CommittedRowChanged)
675
+ return firstPairRowAppearedRefusal();
676
+ throw err;
488
677
  }
678
+ if (refusal)
679
+ return refusal;
680
+ if (!stagedFirstPeer || !stagedToken)
681
+ return firstPairReadBackUnconfirmedRefusal();
682
+ const unconfirmed = await confirmTokenPairAfterCommit(pairingToken, stagedFirstPeer, stagedToken);
683
+ if (unconfirmed)
684
+ return unconfirmed;
685
+ // Test-only: inert unless the fault-injection env opt-in is set and armed.
686
+ // Pause AFTER the token lock released (and the consume is committed) but
687
+ // BEFORE this request's own transaction commits (Harper commits it when the
688
+ // handler returns). A pairing that takes the now-free lock here must read
689
+ // the token consumed; a request-transaction write would not (flair#2333).
690
+ const claimed = txnPausePoint("federation-pair-claim-done");
691
+ if (claimed)
692
+ await claimed;
693
+ await dropPairBootstrapUser(pairingToken, ctx);
489
694
  }
490
695
  // Return our own identity for the peer to record — `{ id, publicKey, role }`,
491
696
  // decided BEFORE the token was consumed (above; flair#1883 round 3). An
@@ -502,7 +707,272 @@ export class FederationPair extends Resource {
502
707
  };
503
708
  }
504
709
  }
505
- // ─── Sync endpoint ───────────────────────────────────────────────────────────
710
+ /** The per-token lock namespace (resources/key-lock.ts); a token's lock key is its own. */
711
+ const PAIRING_TOKEN_LOCK_NAMESPACE = "flair-pairing-token";
712
+ /**
713
+ * The token lock gets up to `PAIR_LOCK_ATTEMPTS` acquisition attempts, with
714
+ * at most one fewer waits of `PAIR_LOCK_WAIT_MS` nominally between attempts.
715
+ * Exhaustion refuses the pairing; timer spacing does not bound elapsed time.
716
+ */
717
+ const PAIR_LOCK_ATTEMPTS = 200;
718
+ const PAIR_LOCK_WAIT_MS = 10;
719
+ /** 401 for a pair with no pairing token: a first-time pair, and a re-pair whose Peer row was deleted, both require one. */
720
+ function pairingTokenRequiredRefusal() {
721
+ return new Response(JSON.stringify({
722
+ error: "pairingToken required in body for first-time pair",
723
+ }), { status: 401, headers: { "content-type": "application/json" } });
724
+ }
725
+ /** 409 for a re-pair whose signed request's key is not the peer row's pinned public key. */
726
+ function publicKeyMismatchRefusal() {
727
+ return new Response(JSON.stringify({
728
+ error: "public key mismatch — peer already paired with different key",
729
+ }), { status: 409, headers: { "content-type": "application/json" } });
730
+ }
731
+ /** The Peer row a first-time pair builds without an earlier Peer row. */
732
+ function firstPairPeerRow(instanceId, publicKey, role, endpoint) {
733
+ const at = new Date().toISOString();
734
+ return {
735
+ id: instanceId,
736
+ publicKey,
737
+ role: role ?? "spoke",
738
+ endpoint: endpoint ?? null,
739
+ status: "paired",
740
+ relayOnly: false,
741
+ pairedAt: at,
742
+ createdAt: at,
743
+ updatedAt: at,
744
+ };
745
+ }
746
+ async function confirmFirstPairBeforeCommit(instanceId) {
747
+ await confirmCommittedRow(databases.flair.Peer, instanceId, (committed) => committed == null);
748
+ const commitPause = txnPausePoint("federation-pair-first-commit");
749
+ if (commitPause)
750
+ await commitPause;
751
+ }
752
+ async function confirmTokenPairAfterCommit(pairingToken, stagedPeer, stagedToken, firstPair = true) {
753
+ if (firstPair) {
754
+ const readBackPause = txnPausePoint("federation-pair-first-read-back");
755
+ if (readBackPause)
756
+ await readBackPause;
757
+ }
758
+ const unreadableRefusal = firstPair ? firstPairReadBackUnconfirmedRefusal : firstPairCommitUnconfirmedRefusal;
759
+ // A re-pair's staged row spreads the re-read row, so its compared fields are
760
+ // its application fields (Harper's own timestamps left out); a first pair's
761
+ // staged row is built from the request and is compared whole.
762
+ const peerFields = firstPair ? stagedPeer : withoutHarperManagedFields(stagedPeer);
763
+ const peerVerdict = await verifyCommittedFields(databases.flair.Peer, stagedPeer.id, stagedPeer, peerFields);
764
+ let tokenRow;
765
+ try {
766
+ tokenRow = await databases.flair.PairingToken.get(pairingToken, {});
767
+ }
768
+ catch {
769
+ return unreadableRefusal();
770
+ }
771
+ if (peerVerdict === "unreadable")
772
+ return unreadableRefusal();
773
+ if (peerVerdict !== "shown" || tokenRow?.pairAttemptWriteId !== stagedToken.pairAttemptWriteId ||
774
+ tokenRow?.consumedBy !== stagedToken.consumedBy || tokenRow?.consumedAt !== stagedToken.consumedAt)
775
+ return firstPairCommitUnconfirmedRefusal();
776
+ return undefined;
777
+ }
778
+ /**
779
+ * Drop the bootstrap user that was created alongside this pairing token, after a
780
+ * first-time pair consumed it. Failure here is logged and non-fatal.
781
+ */
782
+ async function dropPairBootstrapUser(pairingToken, ctx) {
783
+ try {
784
+ const bootstrapUsername = `pair-bootstrap-${pairingToken.slice(0, 8)}`;
785
+ await server.operation({ operation: "drop_user", username: bootstrapUsername }, ctx, false);
786
+ }
787
+ catch (err) {
788
+ console.warn(`[federation] drop_user failed: ${err?.message} — cleanup sweep will retry`);
789
+ }
790
+ }
791
+ /** 403 for a re-pair of a revoked peer: a revoke is a local decision, and a re-pair does not restore it. */
792
+ function peerRevokedRefusal() {
793
+ return new Response(JSON.stringify({
794
+ error: "peer_revoked",
795
+ message: "this Peer row is revoked; it stays revoked",
796
+ }), { status: 403, headers: { "content-type": "application/json" } });
797
+ }
798
+ /**
799
+ * 409 for a first-time pair whose committed-state confirm found a Peer row for
800
+ * the instance although its earlier read returned none. The owned
801
+ * transaction aborted: this request wrote no Peer row and did not consume the
802
+ * pairing token.
803
+ * Signature verification recorded the request's replay nonce before pairing
804
+ * began; that record stays.
805
+ */
806
+ function firstPairRowAppearedRefusal() {
807
+ return new Response(JSON.stringify({
808
+ error: "peer_row_appeared",
809
+ outcome: "conflict",
810
+ message: "a Peer row for this instance is in committed state although this pairing's earlier read found none; this request wrote no Peer row and did not consume the pairing token",
811
+ }), { status: 409, headers: { "content-type": "application/json" } });
812
+ }
813
+ /** 409 for a token pair whose committed Peer row and pairing token consume
814
+ * could not be confirmed as this attempt's after the commit: on a first-time
815
+ * pair, the committed rows do not show the staged values; on a token re-pair of
816
+ * an existing Peer, they do not show them or could not be read. The
817
+ * non-idempotent pair is not retried and is not reported as `paired`. */
818
+ function firstPairCommitUnconfirmedRefusal() {
819
+ return new Response(JSON.stringify({
820
+ error: "peer_pair_unconfirmed",
821
+ outcome: "unconfirmed",
822
+ message: "this pairing attempt's committed Peer row and pairing token consume could not be confirmed; the paired state is unconfirmed",
823
+ }), { status: 409, headers: { "content-type": "application/json" } });
824
+ }
825
+ /** 503 for a first-time pair whose committed Peer row or PairingToken row
826
+ * could not be read back; the stored state is unconfirmed and the request did
827
+ * not answer `paired`. */
828
+ function firstPairReadBackUnconfirmedRefusal() {
829
+ return new Response(JSON.stringify({
830
+ error: "peer_read_back_unconfirmed",
831
+ outcome: "unconfirmed",
832
+ message: "the committed Peer row or pairing token could not be read back; this pairing's stored state is unconfirmed",
833
+ }), { status: 503, headers: { "content-type": "application/json" } });
834
+ }
835
+ /**
836
+ * Tag a token-supplying re-pair's Peer.put rejection inside the owned transaction
837
+ * callback (flair#2333), so it aborts before the caller returns peer_write_failed.
838
+ */
839
+ class PeerWriteFailedError extends Error {
840
+ cause;
841
+ constructor(cause) {
842
+ super("re-pair Peer write failed");
843
+ this.cause = cause;
844
+ this.name = "PeerWriteFailedError";
845
+ }
846
+ }
847
+ /**
848
+ * A token-supplying re-pair's Peer re-read found a revoked row (flair#2333).
849
+ * The transaction aborts, so the token claim that ran with it
850
+ * rolls back and the token is left unconsumed; the caller answers the revoked
851
+ * refusal, not a bare 500.
852
+ */
853
+ class PeerRevokedDuringRepairError extends Error {
854
+ constructor() {
855
+ super("re-pair Peer row revoked inside the owned transaction");
856
+ this.name = "PeerRevokedDuringRepairError";
857
+ }
858
+ }
859
+ /**
860
+ * A token-supplying re-pair's Peer re-read found a pinned key unlike the request's
861
+ * key (flair#2333). The transaction aborts, so the token claim that ran with it
862
+ * rolls back and the token is left unconsumed; the caller answers the key-mismatch
863
+ * refusal, not a bare 500.
864
+ */
865
+ class PeerKeyChangedDuringRepairError extends Error {
866
+ constructor() {
867
+ super("re-pair Peer row's pinned key differs from the signed request's key on the owned transaction's re-read");
868
+ this.name = "PeerKeyChangedDuringRepairError";
869
+ }
870
+ }
871
+ /**
872
+ * 503 for a token-supplying re-pair whose Peer.put rejected inside the owned
873
+ * transaction callback. The token consume and Peer write rolled back; the
874
+ * replay nonce remains recorded. The token is retryable while valid.
875
+ */
876
+ function peerWriteFailedRefusal() {
877
+ return new Response(JSON.stringify({
878
+ error: "peer_write_failed",
879
+ message: "the re-pair's Peer write failed; neither the token consume nor the Peer write committed — the pairing token is unconsumed and retryable while valid, retry",
880
+ }), { status: 503, headers: { "content-type": "application/json" } });
881
+ }
882
+ /**
883
+ * Run one pairing token's check-and-consume under that token's per-key lock
884
+ * (flair#2333), and map the outcome to the refusal the caller returns. `fn`
885
+ * runs only when the lock is held and the store has a lock; `undefined` means
886
+ * `fn` ran and its claim consumed the token (any other claim maps to its refusal
887
+ * through `pairingTokenRefusal`).
888
+ *
889
+ * The lock is the PairingToken store's per-key lock (resources/key-lock.ts): it
890
+ * is shared by this ONE Harper node's threads, so it excludes concurrent
891
+ * pairings of the same token WITHIN one Flair node. Harper can run several
892
+ * nodes for one instance; the lock is not shared across them (see the PR body).
893
+ */
894
+ async function withPairingTokenClaim(pairingToken, fn) {
895
+ const outcome = await withKeyLock(databases.flair.PairingToken?.primaryStore, [PAIRING_TOKEN_LOCK_NAMESPACE, pairingToken], fn, PAIR_LOCK_ATTEMPTS, PAIR_LOCK_WAIT_MS);
896
+ if (outcome.kind === "busy") {
897
+ return new Response(JSON.stringify({
898
+ error: "pairing_in_progress",
899
+ message: "another pairing of this token is still in progress; retry",
900
+ }), { status: 409, headers: { "content-type": "application/json" } });
901
+ }
902
+ if (outcome.kind === "unavailable") {
903
+ return new Response(JSON.stringify({
904
+ error: "pairing_lock_unavailable",
905
+ message: "this instance's PairingToken store has no per-key lock, so the pairing was refused",
906
+ }), { status: 503, headers: { "content-type": "application/json" } });
907
+ }
908
+ return pairingTokenRefusal(outcome.value);
909
+ }
910
+ /** The refusal a finished pairing-token claim maps to, or `undefined` when it consumed the token. */
911
+ function pairingTokenRefusal(claim) {
912
+ if (claim.kind === "consumed")
913
+ return undefined;
914
+ if (claim.kind === "bootstrap_mismatch") {
915
+ return new Response(JSON.stringify({
916
+ error: "bootstrap_user_token_mismatch",
917
+ }), { status: 401, headers: { "content-type": "application/json" } });
918
+ }
919
+ return new Response(JSON.stringify({ error: "invalid_or_expired_pairing_token" }), {
920
+ status: 401, headers: { "content-type": "application/json" },
921
+ });
922
+ }
923
+ /**
924
+ * The check-then-consume of one pairing token, run while holding that token's
925
+ * per-key lock (FederationPair.post). The token is re-read on entry: a pairing
926
+ * that consumed it first makes this one refuse. On success the token records
927
+ * `consumerInstanceId` and is consumed.
928
+ */
929
+ async function consumePairingToken(pairingToken, consumerInstanceId, ctx) {
930
+ // Fetch the token record for consumption IN the caller's transaction — the
931
+ // fresh OWNED one the claim runs in (withOwnedTransaction), never the request's
932
+ // earlier read snapshot. Harper's transaction() set `ctx.transaction`, so the
933
+ // read sees committed state and the write below commits with it.
934
+ let tokenRecord = null;
935
+ try {
936
+ tokenRecord = await databases.flair.PairingToken.get(pairingToken, ctx);
937
+ }
938
+ catch { /* table may not exist */ }
939
+ const pause = txnPausePoint("federation-pair-token");
940
+ if (pause)
941
+ await pause;
942
+ if (!tokenRecord || tokenRecord.consumedBy) {
943
+ return { kind: "refused" };
944
+ }
945
+ if (tokenRecord.expiresAt && new Date(tokenRecord.expiresAt) < new Date()) {
946
+ return { kind: "refused" };
947
+ }
948
+ // PR-4: bind authenticated bootstrap user to specific pairing token.
949
+ // The middleware annotates the REQUEST (request.tpsAgent); getContext() IS
950
+ // that request (resources/Resource.js getResource), not a wrapper with a
951
+ // `.request` field — the same read A2AAdapter uses (`ctx.request ?? ctx`).
952
+ const ctxRequest = ctx?.request ?? ctx ?? {};
953
+ const authedUser = ctxRequest.tpsAgent;
954
+ const isAdmin = ctxRequest.tpsAgentIsAdmin === true;
955
+ if (!isAdmin && authedUser) {
956
+ const expectedBootstrap = `pair-bootstrap-${pairingToken.slice(0, 8)}`;
957
+ if (authedUser !== expectedBootstrap) {
958
+ return { kind: "bootstrap_mismatch" };
959
+ }
960
+ }
961
+ // Consume the token. A fresh random `pairAttemptWriteId` is written here in
962
+ // the same transaction as the first-pair Peer write; after the commit,
963
+ // both first-pair routes confirm BOTH committed rows by that marker, so an attempt
964
+ // that merely shares `consumedAt` or staged Peer values cannot pass.
965
+ const consumedAt = new Date().toISOString();
966
+ const pairAttemptWriteId = randomUUID();
967
+ await databases.flair.PairingToken.put({
968
+ ...tokenRecord,
969
+ consumedBy: consumerInstanceId,
970
+ consumedAt,
971
+ pairAttemptWriteId,
972
+ }, ctx);
973
+ return { kind: "consumed", consumedBy: consumerInstanceId, consumedAt, pairAttemptWriteId };
974
+ }
975
+ const RECORD_MERGE_DEADLINE_MS = 5_000;
506
976
  /**
507
977
  * POST /FederationSync — push sync records from a peer.
508
978
  * In 1.0, this is a simple HTTP push (not WebSocket).
@@ -540,14 +1010,34 @@ export class FederationSync extends Resource {
540
1010
  const verifyResult = await verifyFederationRequestBody(data, peer.publicKey);
541
1011
  if (!verifyResult.ok)
542
1012
  return federationVerifyRefusal(verifyResult.reason);
1013
+ const offeredKeys = new Set();
1014
+ for (const record of records) {
1015
+ if (typeof record?.table !== "string" || record.table.length === 0 ||
1016
+ typeof record?.id !== "string" || record.id.length === 0 ||
1017
+ record?.data?.id !== record.id) {
1018
+ return new Response(JSON.stringify({ error: "invalid_sync_batch_key" }), {
1019
+ status: 400, headers: { "content-type": "application/json" },
1020
+ });
1021
+ }
1022
+ const key = JSON.stringify([record.table, record.id]);
1023
+ if (offeredKeys.has(key)) {
1024
+ return new Response(JSON.stringify({ error: "duplicate_sync_batch_key" }), {
1025
+ status: 400, headers: { "content-type": "application/json" },
1026
+ });
1027
+ }
1028
+ offeredKeys.add(key);
1029
+ }
543
1030
  const startTime = Date.now();
544
1031
  let merged = 0;
545
1032
  let skipped = 0;
546
1033
  const skippedReasons = {};
1034
+ const refused = [];
1035
+ const indeterminate = [];
547
1036
  const mergeErrors = [];
548
- function recordSkip(reason) {
1037
+ function recordSkip(reason, record) {
549
1038
  skipped++;
550
1039
  skippedReasons[reason] = (skippedReasons[reason] ?? 0) + 1;
1040
+ refused.push({ table: record.table, id: record.id, reason });
551
1041
  }
552
1042
  // Table name → Harper database table mapping.
553
1043
  // Typed against FEDERATION_TABLE_POLICY so adding a federated table
@@ -573,13 +1063,80 @@ export class FederationSync extends Resource {
573
1063
  // trust delegation to the originator's send-time check) alongside adding
574
1064
  // Message to the push list — do not inherit this as a silent gap.
575
1065
  Message: databases.flair.Message,
1066
+ // flair#2578 slice 1: Presence is REGISTERED so the receive path can carry
1067
+ // it (the receiver writes it through the write-back helper). The sender
1068
+ // ships in a later slice — this is the RECEIVE side only.
1069
+ Presence: databases.flair.Presence,
576
1070
  };
577
1071
  const knownTables = new Set(Object.keys(tableMap));
578
- for (const record of records) {
1072
+ /** The per-id Memory write lock store (flair#2478 slice 3c). */
1073
+ const memoryLockStore = () => databases?.flair?.Memory?.primaryStore;
1074
+ /** Read the local Agent row for an id, or null when there is none.
1075
+ * Read failures throw: before write-back starts they become retryable
1076
+ * `merge_error`; after it starts they are indeterminate. */
1077
+ const readAgentRow = async (agentId) => {
1078
+ const row = await databases.flair.Agent.get(agentId);
1079
+ return row ?? null;
1080
+ };
1081
+ // ── flair#2578 slice 1: Presence receipt (P1, P4, P5) ──
1082
+ // The batch-verified sender (`sender`) is the home authority. Write-back
1083
+ // rechecks the home fresh and reads the Presence row in its owned transaction.
1084
+ const mergePresence = async (record, sender, local, table, markWriteStarted) => {
1085
+ const receivedAt = Date.now();
1086
+ // P5: strip to the declared Presence fields and validate. The wire record
1087
+ // id IS the primary key (agentId).
1088
+ const validated = validatePresenceReceipt(record.id, record.data, receivedAt, sender);
1089
+ if (!validated.ok)
1090
+ return { reason: validated.reason };
1091
+ const agentId = validated.row.agentId;
1092
+ // P1: the Agent row must be homed on the batch-verified sender.
1093
+ const homeReason = presenceHomeBindingReason(await readAgentRow(agentId), sender);
1094
+ if (homeReason)
1095
+ return { reason: homeReason };
1096
+ // P4: Presence-specific merge (heartbeat, then activity stamp).
1097
+ const planned = mergePresenceReceipt(local, validated.row, receivedAt);
1098
+ if (planned.action === "skip")
1099
+ return { reason: planned.reason };
1100
+ // As in the generic merge: write-back conflicts aborted before commit are
1101
+ // merge_target_changed; other errors after write-back starts are indeterminate.
1102
+ let outcome;
1103
+ markWriteStarted();
1104
+ try {
1105
+ outcome = await writeBackCommittedRow(table, record.id, async (row) => {
1106
+ // Fresh home recheck during write-back; `row` is the transaction-scoped
1107
+ // Presence read.
1108
+ const currentHome = presenceHomeBindingReason(await readAgentRow(agentId), sender);
1109
+ if (currentHome)
1110
+ return { skip: true, reason: currentHome };
1111
+ const current = mergePresenceReceipt(row, validated.row, receivedAt);
1112
+ if (current.action === "skip")
1113
+ return { skip: true, reason: current.reason };
1114
+ return { idempotent: true, write: current.row };
1115
+ }, {
1116
+ label: "FederationSync",
1117
+ expectedRow: local,
1118
+ attempts: 1,
1119
+ wholeRow: true,
1120
+ pausePre: () => txnPausePoint("presence-merge-pre"),
1121
+ pausePoint: () => txnPausePoint("presence-merge"),
1122
+ });
1123
+ }
1124
+ catch (err) {
1125
+ if (err instanceof WriteBackConflictError) {
1126
+ return err.outcome === "conflict" ? { reason: "merge_target_changed" } : { indeterminate: true };
1127
+ }
1128
+ throw err;
1129
+ }
1130
+ if ("skip" in outcome) {
1131
+ return { reason: outcome.reason ?? "presence_invalid_shape" };
1132
+ }
1133
+ return { merged: true };
1134
+ };
1135
+ const mergeOne = async (record) => {
1136
+ let writeBackStarted = false;
579
1137
  try {
580
1138
  if (payloadIdMismatch(record)) {
581
- recordSkip("id_mismatch");
582
- continue;
1139
+ return { reason: "id_mismatch" };
583
1140
  }
584
1141
  const table = (record.table in tableMap)
585
1142
  ? tableMap[record.table]
@@ -587,8 +1144,12 @@ export class FederationSync extends Resource {
587
1144
  const local = table ? await table.get(record.id) : null;
588
1145
  const decision = classifyRecord(record, peer.role, instanceId, local, knownTables);
589
1146
  if (decision.action === "skip") {
590
- recordSkip(decision.reason);
591
- continue;
1147
+ return { reason: decision.reason };
1148
+ }
1149
+ // With the flag OFF, an eligible Presence record reaching receipt skips
1150
+ // as presence_receive_disabled; earlier key/classifier refusals answer first.
1151
+ if (record.table === "Presence" && !presenceReceiveEnabled()) {
1152
+ return { reason: "presence_receive_disabled" };
592
1153
  }
593
1154
  // ── Per-record signature verification (federation-edge-hardening slice 3b) ──
594
1155
  // classifyRecord's "merge" verdict above only proves the record is
@@ -614,8 +1175,7 @@ export class FederationSync extends Resource {
614
1175
  ? peer.publicKey
615
1176
  : (await databases.flair.Peer.get(originator))?.publicKey;
616
1177
  if (!originatorPublicKey) {
617
- recordSkip("unknown_originator_key");
618
- continue;
1178
+ return { reason: "unknown_originator_key" };
619
1179
  }
620
1180
  // CONTRACT — reconstruct from the record (v defaults to 1 when
621
1181
  // absent — v is NOT on the wire today). Must match
@@ -627,16 +1187,14 @@ export class FederationSync extends Resource {
627
1187
  // records. See flair#1416.
628
1188
  const signatureValid = verifyBodySignature(reconstructRecordVerifyBody(record, originator), originatorPublicKey);
629
1189
  if (!signatureValid) {
630
- recordSkip("invalid_signature");
631
- continue;
1190
+ return { reason: "invalid_signature" };
632
1191
  }
633
1192
  }
634
1193
  else if (requireRecordSignatures()) {
635
1194
  // require-mode: unsigned records are no longer trusted on
636
1195
  // batch-level auth alone. Default mode (verify-if-present) falls
637
1196
  // through here and merges — see requireRecordSignatures() above.
638
- recordSkip("missing_signature");
639
- continue;
1197
+ return { reason: "missing_signature" };
640
1198
  }
641
1199
  // ── Per-record principal entitlement (flair#1416 / slice 3a) ──
642
1200
  // After signature verification, before table.put. Scoped by the
@@ -648,22 +1206,30 @@ export class FederationSync extends Resource {
648
1206
  enforceV1Principal: requireRecordPrincipal(),
649
1207
  });
650
1208
  if (principalSkip) {
651
- recordSkip(principalSkip);
652
- continue;
1209
+ return { reason: principalSkip };
1210
+ }
1211
+ // ── flair#2578 slice 1: Presence receipt ──
1212
+ if (record.table === "Presence") {
1213
+ return await mergePresence(record, instanceId, local, table, () => { writeBackStarted = true; });
653
1214
  }
654
- // ── flair#2108: skip an inbound Agent record whose `status` differs
655
- // from an existing local principal's stored value, whether or not it
656
- // would win the last-write-wins merge below. The federation path
657
- // carries no verified administrator authority for that principal (the
658
- // batch is signed, and a record signature may also be present; neither
659
- // is an admin claim). The whole record is skipped rather than merged
660
- // with a pinned status, so the merge stays atomic and the other fields
661
- // in the record do not land either.
662
- if (inboundChangesExistingPrincipalStatus(record, local)) {
663
- recordSkip("agent_status_not_federated");
664
- continue;
1215
+ const incoming = { ...record.data };
1216
+ if (record.table === "Memory") {
1217
+ // Ephemeral peer expiry must be a valid UTC ISO date from the Unix
1218
+ // epoch through receiver time + 365 days. Missing expiry uses the receiver's
1219
+ // clock and configured TTL when the incoming row wins last-write-wins.
1220
+ // Malformed or out-of-bound ephemeral expiry skips the record before merging.
1221
+ const expiryError = stampEphemeralExpiry(incoming, local, { incoming: true });
1222
+ if (expiryError) {
1223
+ return { reason: "invalid_expiry" };
1224
+ }
1225
+ }
1226
+ const mergedData = mergeRecord(local, { ...record, data: incoming });
1227
+ // ── flair#2359: an inbound Agent row must satisfy the same agent-ID
1228
+ // rule as a locally-created one. This raw merge is the receiver's write
1229
+ // path, so a peer pushing a malformed id must not land a row here.
1230
+ if (record.table === "Agent" && !isValidAgentId(record.id)) {
1231
+ return { reason: AGENT_ID_ERROR };
665
1232
  }
666
- const mergedData = mergeRecord(local, record);
667
1233
  // ── flair#1940 A1'' item 8: the SAME declared-attribute whitelist the
668
1234
  // writers apply. A dirty pushed row (a legacy direct-insert, or a raw
669
1235
  // writer that slipped a pointer field past the writers) must not carry
@@ -679,32 +1245,20 @@ export class FederationSync extends Resource {
679
1245
  // would land an unscanned, possibly non-persistent skill — bypassing the
680
1246
  // gate. Skip it: skills are written locally via skill_store, never synced.
681
1247
  if (record.table === "Memory" && isSkillWrite(mergedData)) {
682
- recordSkip("skill_not_federated");
683
- continue;
1248
+ return { reason: "skill_not_federated" };
684
1249
  }
685
- // Absorbing-state guard for the Message table (flair#1521 §12 P0-3).
686
- // Generic newer-wins LWW would let a deadline-sweep `failed` (or any
687
- // other state) written on a peer overwrite a locally-CONSUMED message,
688
- // telling the sender "failed" about a message the recipient actually
689
- // consumed — the exact inversion Relay exists to kill. `consumed` is
690
- // absorbing: reconcileState pins it regardless of updatedAt. The guard
691
- // lives HERE, in the raw-put apply path, because sync-in bypasses the
692
- // Message resource's methods (Federation.ts uses table.put directly).
693
- if (record.table === "Message") {
694
- const reconciled = reconcileState(local?.state, mergedData.state);
695
- mergedData.state = reconciled;
696
- // P1-3 (flair#1521): reconcile the SATELLITE lifecycle fields too, not
697
- // just `state`. Generic LWW keeps the incoming (newer) record's
698
- // failureReason/consumedAt, so a locally-CONSUMED row could end up
699
- // `consumed` while carrying a remote `failureReason: "deadline"` — the
700
- // sender-visible "failed" about a message the recipient actually
701
- // consumed, the exact inversion the absorbing rule exists to kill. A
702
- // consumed row NEVER has a failureReason; keep the consumed row's own
703
- // consumedAt (local's when local was the consumer).
704
- if (reconciled === "consumed") {
705
- mergedData.failureReason = null;
706
- mergedData.consumedAt = local?.consumedAt ?? mergedData.consumedAt ?? null;
707
- }
1250
+ // flair#2141 S2: the merge skips a row on the seed's fixed id
1251
+ // (resources/seed-reservation.ts), whatever its tags.
1252
+ if (isReservedSeedId(record.table, record.id)) {
1253
+ return { reason: "seed_id_not_federated" };
1254
+ }
1255
+ // flair#2307: Harper's REST by-id path reads a trailing `.content` as a
1256
+ // property selector, and the Memory write paths refuse such an id, so a
1257
+ // federated Memory row whose id ends in `.content` is skipped, as the
1258
+ // seed reservation does just above. A legacy row with such an id that
1259
+ // already exists on the sending peer is therefore not federated.
1260
+ if (record.table === "Memory" && endsWithContentSelectorSuffix(mergedData.id)) {
1261
+ return { reason: "content_suffix_id_not_federated" };
708
1262
  }
709
1263
  mergedData._originatorInstanceId = decision.originator;
710
1264
  mergedData._syncedFrom = instanceId;
@@ -736,17 +1290,154 @@ export class FederationSync extends Resource {
736
1290
  ? local.instanceToken
737
1291
  : randomUUID();
738
1292
  }
739
- await table.put(mergedData);
740
- // embedding-space-guard slice 1: a federation-merged Memory can carry a
741
- // FOREIGN embeddingModel (LWW remote-win) — trip the guard's latch so
742
- // recall/dedup degrade instead of cosining a foreign vector. See
743
- // noteFederationMergedMemory's doc.
744
- noteFederationMergedMemory(record.table, mergedData);
745
- merged++;
1293
+ // flair#2441 / flair#2450 / flair#2475: every synced table uses the
1294
+ // write-back helper (one attempt, no retry). The plan reads the
1295
+ // in-transaction row. The Agent status guard can skip as
1296
+ // agent_status_not_federated before row comparison. For planned writes,
1297
+ // every table compares the WHOLE stored row against `local` (the row the
1298
+ // merge read and built from): a change to any field committed between that
1299
+ // read and the helper's in-transaction read skips the record as
1300
+ // merge_target_changed. The committed row is checked again before commit.
1301
+ //
1302
+ // flair#2450 set `wholeRow` for Soul, Agent, Relationship and Message;
1303
+ // flair#2475 extends it to Memory: Memory's identity fields
1304
+ // (instanceToken, contentHash, createdAt, agentId) do not move on a
1305
+ // field-only update, so an identity-only check let the merge put back
1306
+ // a changed field's pre-change value. For an existing row, Memory
1307
+ // writes the fields that differ from the in-transaction row as an
1308
+ // incremental update, and rewrites the whole row only when a stripped
1309
+ // field must be removed; a new row is a full put.
1310
+ let outcome;
1311
+ writeBackStarted = true;
1312
+ try {
1313
+ const writeMerge = async () => await writeBackCommittedRow(table, record.id, (row) => {
1314
+ // flair#2108: an inbound Agent record whose `status` differs from
1315
+ // the in-transaction local principal's stored value is skipped WHOLE,
1316
+ // whether or not it would win the last-write-wins merge — the
1317
+ // federation path carries no verified administrator authority for
1318
+ // that principal (the batch is signed, and a record signature may
1319
+ // also be present; neither is an admin claim), so a second field
1320
+ // in the record does not land either.
1321
+ if (record.table === "Agent" && inboundChangesExistingPrincipalStatus(record, row)) {
1322
+ return { skip: true, reason: "agent_status_not_federated" };
1323
+ }
1324
+ // flair#2266: skip an inbound Agent record carrying a publicKey
1325
+ // different from stored `pending`, regardless of timestamps.
1326
+ if (record.table === "Agent" && inboundChangesExistingPendingKey(record, row)) {
1327
+ return { skip: true, reason: "agent_pending_key_not_federated" };
1328
+ }
1329
+ // flair#2665: a new row whose id the receiver's FLAIR_ADMIN_AGENTS
1330
+ // names is not created. An existing row's publicKey and home
1331
+ // change only through a record whose batch-verified sender
1332
+ // (`instanceId`) is the row's stored home; a record from another
1333
+ // sender that would change either is skipped whole. The merge
1334
+ // does not set or change the `role: "admin"` / `admin: true`
1335
+ // fields.
1336
+ if (record.table === "Agent") {
1337
+ const agentRefusal = agentAdminIdCreateRefusal(record, row, configuredAdminAgentIds()) ??
1338
+ agentIdentityRefusal(record, row, instanceId);
1339
+ if (agentRefusal)
1340
+ return { skip: true, reason: agentRefusal };
1341
+ keepReceiverAgentAuthority(mergedData, row);
1342
+ }
1343
+ // Absorbing-state guard for the Message table (flair#1521 §12
1344
+ // P0-3). Generic newer-wins LWW would let a deadline-sweep `failed`
1345
+ // (or any other state) written on a peer overwrite a locally-
1346
+ // CONSUMED message, telling the sender "failed" about a message the
1347
+ // recipient actually consumed — the exact inversion Relay exists to
1348
+ // kill. `consumed` is absorbing: reconcileState pins it regardless
1349
+ // of updatedAt, against the in-transaction row's state. For consumed
1350
+ // state, clear failureReason and prefer the in-transaction row's
1351
+ // consumedAt when non-null.
1352
+ if (record.table === "Message") {
1353
+ const reconciled = reconcileState(row?.state, mergedData.state);
1354
+ mergedData.state = reconciled;
1355
+ if (reconciled === "consumed") {
1356
+ mergedData.failureReason = null;
1357
+ mergedData.consumedAt = row?.consumedAt ?? mergedData.consumedAt ?? null;
1358
+ }
1359
+ }
1360
+ if (record.table === "Memory") {
1361
+ normalizeEmptyEmbedding(mergedData);
1362
+ // flair#2478 slice 3c: mergedData was built before the id's
1363
+ // lock was taken; this write decision runs under the lock, on
1364
+ // the in-transaction row, and the whole-row check against
1365
+ // `local` follows it. A new row is a full put. An existing row
1366
+ // gets an incremental update of the fields where mergedData
1367
+ // differs from it, unless the strip fallback below rewrites
1368
+ // the whole row.
1369
+ if (row == null)
1370
+ return { idempotent: true, write: mergedData };
1371
+ // A field the merge stripped (a pointer attribute on a dirty
1372
+ // row) is absent from mergedData; an incremental update cannot
1373
+ // remove it, so rewrite the whole row as before.
1374
+ if (Object.keys(row).some((field) => !Object.hasOwn(mergedData, field))) {
1375
+ return { idempotent: true, write: mergedData };
1376
+ }
1377
+ const patch = {};
1378
+ for (const [field, value] of Object.entries(mergedData)) {
1379
+ if (!isDeepStrictEqual(row[field], value))
1380
+ patch[field] = value;
1381
+ }
1382
+ return { idempotent: true, update: patch };
1383
+ }
1384
+ return { idempotent: true, write: mergedData };
1385
+ }, {
1386
+ label: "FederationSync",
1387
+ expectedRow: local,
1388
+ attempts: 1,
1389
+ // Planned writes compare the whole stored row, not just
1390
+ // sameStoredRow's identity fields: Memory's identity fields do not
1391
+ // move on a field-only update (flair#2475), and the other tables'
1392
+ // identity fields do not move on one either (flair#2450 — see
1393
+ // above).
1394
+ wholeRow: true,
1395
+ pausePre: () => txnPausePoint("federation-merge-pre"),
1396
+ pausePoint: () => txnPausePoint("federation-merge"),
1397
+ pauseAfterStage: () => txnPausePoint("federation-merge-staged"),
1398
+ pauseBeforeCommit: () => txnPausePoint("federation-merge-commit"),
1399
+ });
1400
+ if (record.table === "Memory") {
1401
+ // flair#2478 slice 3c: the merge takes the id's per-id Memory write
1402
+ // lock, once and without waiting, around its write-back. The lock
1403
+ // does not serialize it against a PUT that joined another
1404
+ // transaction, which can commit after that PUT releases the lock
1405
+ // (resources/memory-write-lock.ts). A held id, an unresolved earlier
1406
+ // write or a store with no lock writes nothing for the record and is
1407
+ // reported as merge_target_busy (a retryable skip reason: the
1408
+ // response carries it, the best-effort SyncLog row records it when
1409
+ // that write succeeds, and a later re-offer can merge it).
1410
+ const locked = await withMemoryWriteLockOnce(memoryLockStore(), [record.id], writeMerge, { phase: "federation-merge" });
1411
+ if (locked.kind !== "done")
1412
+ return { reason: "merge_target_busy" };
1413
+ outcome = locked.value;
1414
+ }
1415
+ else {
1416
+ outcome = await writeMerge();
1417
+ }
1418
+ }
1419
+ catch (err) {
1420
+ if (err instanceof WriteBackConflictError) {
1421
+ return err.outcome === "conflict" ? { reason: "merge_target_changed" } : { indeterminate: true };
1422
+ }
1423
+ throw err;
1424
+ }
1425
+ // Each skip above carries its OWN name on the plan's `reason`; the
1426
+ // fallback is the status rule's name for any future skip that does not.
1427
+ // (Every skip this plan returns names a reason today.)
1428
+ if ("skip" in outcome) {
1429
+ return { reason: outcome.reason ?? "agent_status_not_federated" };
1430
+ }
1431
+ try {
1432
+ noteFederationMergedMemory(record.table, mergedData, local ?? null);
1433
+ }
1434
+ catch (err) {
1435
+ console.warn(`[Federation] post-commit note failed for ${record.table}/${record.id}: ${String(err)}`);
1436
+ }
1437
+ return { merged: true };
746
1438
  }
747
1439
  catch (err) {
748
1440
  const msg = err instanceof Error ? err.message : String(err);
749
- recordSkip("merge_error");
750
1441
  // Cap the captured-error list so a hostile/buggy peer can't blow up
751
1442
  // the SyncLog row, but ALWAYS log to console so operators don't lose
752
1443
  // the per-record signal — the silent-swallow is the bug we're fixing.
@@ -754,7 +1445,27 @@ export class FederationSync extends Resource {
754
1445
  mergeErrors.push(`${record.table}/${record.id}: ${msg}`);
755
1446
  }
756
1447
  console.warn(`[Federation] merge error for ${record.table}/${record.id} from ${instanceId}: ${msg}`);
1448
+ return writeBackStarted ? { indeterminate: true } : { reason: "merge_error" };
1449
+ }
1450
+ };
1451
+ for (const record of records) {
1452
+ let timer;
1453
+ const deadline = new Promise((resolve) => {
1454
+ timer = setTimeout(() => resolve({ indeterminate: true }), RECORD_MERGE_DEADLINE_MS);
1455
+ });
1456
+ let outcome;
1457
+ try {
1458
+ outcome = await Promise.race([mergeOne(record), deadline]);
1459
+ }
1460
+ finally {
1461
+ clearTimeout(timer);
757
1462
  }
1463
+ if ("reason" in outcome)
1464
+ recordSkip(outcome.reason, record);
1465
+ else if ("merged" in outcome)
1466
+ merged++;
1467
+ else
1468
+ indeterminate.push({ table: record.table, id: record.id });
758
1469
  }
759
1470
  // Peer cursor update — distinguish liveness from progress:
760
1471
  // lastSyncAt → "we heard from this peer just now" (always update)
@@ -775,8 +1486,13 @@ export class FederationSync extends Resource {
775
1486
  }
776
1487
  await databases.flair.Peer.put(peerUpdate);
777
1488
  // Log sync operation with skip-reason breakdown so the partial state
778
- // is debuggable instead of a black box.
1489
+ // is debuggable instead of a black box. The response reports what the put
1490
+ // did: true when it returned; false when it threw, so the row's state is
1491
+ // unconfirmed (there is no confirmation read).
1492
+ let syncLogWritten = false;
779
1493
  try {
1494
+ if (txnFault("federation-synclog"))
1495
+ throw new Error("injected SyncLog write failure");
780
1496
  const errorParts = [];
781
1497
  if (Object.keys(skippedReasons).length > 0) {
782
1498
  errorParts.push("skipped: " +
@@ -790,7 +1506,7 @@ export class FederationSync extends Resource {
790
1506
  const errorSummary = errorParts.length > 0 ? errorParts.join(" | ") : undefined;
791
1507
  const status = mergeErrors.length > 0
792
1508
  ? "partial"
793
- : skipped > 0 ? "partial" : "success";
1509
+ : skipped > 0 || indeterminate.length > 0 ? "partial" : "success";
794
1510
  await databases.flair.SyncLog.put({
795
1511
  id: `sync_${Date.now()}_${randomBytes(4).toString("hex")}`,
796
1512
  peerId: instanceId,
@@ -803,14 +1519,20 @@ export class FederationSync extends Resource {
803
1519
  durationMs: Date.now() - startTime,
804
1520
  createdAt: nowIso,
805
1521
  });
1522
+ syncLogWritten = true;
1523
+ }
1524
+ catch (err) {
1525
+ console.warn(`[Federation] SyncLog write failed for ${instanceId}: ${String(err)}`);
806
1526
  }
807
- catch { /* non-fatal */ }
808
1527
  return {
809
1528
  merged,
810
1529
  skipped,
811
1530
  skippedReasons,
1531
+ refused,
1532
+ indeterminate,
812
1533
  total: records.length,
813
1534
  durationMs: Date.now() - startTime,
1535
+ syncLogWritten,
814
1536
  };
815
1537
  }
816
1538
  }
@@ -838,6 +1560,7 @@ export class FederationPeers extends Resource {
838
1560
  endpoint: p.endpoint,
839
1561
  lastSyncAt: p.lastSyncAt,
840
1562
  lastMergeAt: p.lastMergeAt,
1563
+ presenceLastSyncAt: p.presenceLastSyncAt,
841
1564
  relayOnly: p.relayOnly,
842
1565
  pairedAt: p.pairedAt,
843
1566
  });
@@ -847,6 +1570,53 @@ export class FederationPeers extends Resource {
847
1570
  return { peers };
848
1571
  }
849
1572
  }
1573
+ /**
1574
+ * GET /FederationRetries — the rows of the sender's FederationRetry table
1575
+ * (flair#2455), admin view, split into `pending`, `terminal` and `malformed`.
1576
+ * The generic-Memory sender (`runFederationSyncOnce`) creates a pending row on
1577
+ * a retryable refusal or a first indeterminate outcome, and updates it on
1578
+ * later attempts, outcomes and source changes; rows an admin writes are
1579
+ * readable too.
1580
+ *
1581
+ * A row that breaks a sender convention (retryRowProblem: an id that is not its
1582
+ * tuple's key, an unknown state, reason or outcome) is listed under
1583
+ * `malformed` with the problem's name, and never as pending or terminal.
1584
+ *
1585
+ * allowRead()=allowAdmin, the same gate as FederationPeers above. Read-only:
1586
+ * it never writes a row, and a read failure propagates instead of being
1587
+ * reported as an empty set. `flair federation status` renders it.
1588
+ */
1589
+ export class FederationRetries extends Resource {
1590
+ async allowRead() {
1591
+ return allowAdmin(this.getContext?.());
1592
+ }
1593
+ async get() {
1594
+ const pending = [];
1595
+ const terminal = [];
1596
+ const malformed = [];
1597
+ for await (const r of databases.flair.FederationRetry.search()) {
1598
+ const problem = retryRowProblem(r);
1599
+ if (problem) {
1600
+ malformed.push({ key: r.id, peerId: r.peerId, table: r.table, id: r.recordId, state: r.state, problem });
1601
+ continue;
1602
+ }
1603
+ const row = {
1604
+ peerId: r.peerId,
1605
+ table: r.table,
1606
+ id: r.recordId,
1607
+ reason: r.lastReason,
1608
+ attempts: r.attempts,
1609
+ bound: r.bound,
1610
+ resolution: r.resolution,
1611
+ state: r.state,
1612
+ firstRefusedAt: r.firstRefusedAt,
1613
+ completedAt: r.completedAt,
1614
+ };
1615
+ (r.state === "pending" ? pending : terminal).push(row);
1616
+ }
1617
+ return { pending, terminal, malformed };
1618
+ }
1619
+ }
850
1620
  // ── Module initialisation ────────────────────────────────────────────────────
851
1621
  // Deferred: the cleanup sweep (PR-5) starts after the module graph resolves.
852
1622
  // In unit test environments (no Harper runtime), setTimeout never fires