@tpsdev-ai/flair 0.58.0 → 0.62.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 (268) hide show
  1. package/README.md +7 -6
  2. package/SECURITY.md +36 -0
  3. package/config.yaml +15 -1
  4. package/dist/bridges/builtins/mem0.js +63 -28
  5. package/dist/bridges/runtime/import-runner.js +12 -0
  6. package/dist/bridges/runtime/load-plugin.js +42 -13
  7. package/dist/bridges/runtime/yaml-loader.js +4 -2
  8. package/dist/build-info.json +3 -3
  9. package/dist/cli.js +1030 -343
  10. package/dist/commands/agent.js +384 -45
  11. package/dist/commands/attention.js +4 -3
  12. package/dist/commands/backup.js +202 -34
  13. package/dist/commands/bridge.js +172 -119
  14. package/dist/commands/deploy.js +37 -4
  15. package/dist/commands/doctor.js +601 -163
  16. package/dist/commands/export.js +54 -19
  17. package/dist/commands/federation.js +141 -21
  18. package/dist/commands/hook.js +155 -2
  19. package/dist/commands/idp.js +14 -1
  20. package/dist/commands/import.js +7 -3
  21. package/dist/commands/init.js +462 -193
  22. package/dist/commands/integrity.js +388 -0
  23. package/dist/commands/keys.js +247 -58
  24. package/dist/commands/mcp.js +146 -53
  25. package/dist/commands/memory.js +171 -21
  26. package/dist/commands/migrate-harness-memory.js +3 -2
  27. package/dist/commands/orgevent.js +46 -37
  28. package/dist/commands/presence.js +4 -3
  29. package/dist/commands/principal.js +426 -48
  30. package/dist/commands/quality.js +10 -1
  31. package/dist/commands/reembed.js +141 -17
  32. package/dist/commands/relationship.js +2 -1
  33. package/dist/commands/rem.js +56 -18
  34. package/dist/commands/restore.js +101 -61
  35. package/dist/commands/search.js +6 -4
  36. package/dist/commands/service.js +151 -38
  37. package/dist/commands/soul.js +4 -3
  38. package/dist/commands/status.js +43 -5
  39. package/dist/commands/test.js +3 -2
  40. package/dist/commands/upgrade.js +24 -1
  41. package/dist/commands/workspace.js +6 -3
  42. package/dist/component-env.js +31 -41
  43. package/dist/deploy.js +77 -1
  44. package/dist/doctor-client.js +529 -92
  45. package/dist/engine-version-contract.js +1 -0
  46. package/dist/engine-version.js +23 -3
  47. package/dist/federation-verify.js +4 -3
  48. package/dist/hook-install.js +670 -6
  49. package/dist/keystore.js +72 -0
  50. package/dist/lib/action-recall-runtime.js +328 -0
  51. package/dist/lib/agent-home-fields.js +132 -0
  52. package/dist/lib/agent-home.js +427 -0
  53. package/dist/lib/agent-id-rule.js +46 -0
  54. package/dist/lib/agent-roster.js +33 -0
  55. package/dist/lib/auth-resolve.js +49 -16
  56. package/dist/lib/capture-runtime.js +124 -0
  57. package/dist/lib/credential-status-rule.js +78 -0
  58. package/dist/lib/daemon-liveness.js +81 -8
  59. package/dist/lib/doctor-run.js +140 -35
  60. package/dist/lib/durability-copy.js +10 -0
  61. package/dist/lib/embedding-space-doctor.js +75 -0
  62. package/dist/lib/flair-agent-role.js +120 -0
  63. package/dist/lib/hub-url.js +12 -0
  64. package/dist/lib/init-admin-pass.js +88 -12
  65. package/dist/lib/init-listener-environ.js +1 -2
  66. package/dist/lib/init-occupied-listener.js +15 -111
  67. package/dist/lib/init-spawn-attribution.js +73 -0
  68. package/dist/lib/init-tcp-probe.js +33 -0
  69. package/dist/lib/instance-identity-row.js +20 -0
  70. package/dist/lib/launchd-management.js +27 -2
  71. package/dist/lib/listener-table.js +268 -0
  72. package/dist/lib/local-delete-instance.js +27 -0
  73. package/dist/lib/local-instance-pair.js +256 -0
  74. package/dist/lib/mcp-enable.js +1775 -338
  75. package/dist/lib/mcp-oauth-env-core.js +133 -0
  76. package/dist/lib/mcp-oauth-env.js +125 -0
  77. package/dist/lib/mcp-spec.js +17 -1
  78. package/dist/lib/memory-attributes.js +2 -0
  79. package/dist/lib/memory-id-policy.js +46 -0
  80. package/dist/lib/memory-integrity.js +309 -0
  81. package/dist/lib/memory-purge-response.js +20 -0
  82. package/dist/lib/ops-table-count.js +25 -0
  83. package/dist/lib/owned-pins.js +67 -10
  84. package/dist/lib/peer-status.js +27 -0
  85. package/dist/lib/principal-status.js +29 -0
  86. package/dist/lib/process-start-time.js +103 -7
  87. package/dist/lib/proto-safe-record.js +42 -0
  88. package/dist/lib/record-id-path.js +25 -0
  89. package/dist/lib/reembed-server-support.js +66 -0
  90. package/dist/lib/restore-verify.js +104 -0
  91. package/dist/lib/scheduler-platform.js +10 -6
  92. package/dist/lib/secret-keys.js +25 -0
  93. package/dist/lib/secrets-push.js +50 -22
  94. package/dist/lib/skill-seed-pending.js +24 -0
  95. package/dist/lib/skill-seed.js +365 -0
  96. package/dist/lib/stop-start-recovery.js +54 -0
  97. package/dist/lib/using-flair-skill.js +87 -0
  98. package/dist/mcp-client-assertion.js +112 -4
  99. package/dist/memory-id-checkpoint.js +326 -0
  100. package/dist/memory-node-compare.js +207 -0
  101. package/dist/packages/flair-mcp/src/secret-redaction.js +113 -0
  102. package/dist/rem/restore.js +6 -5
  103. package/dist/rem/runner.js +103 -44
  104. package/dist/resources/Agent.js +348 -8
  105. package/dist/resources/AgentKeyRegister.js +214 -0
  106. package/dist/resources/AgentKeyRegistration.js +28 -0
  107. package/dist/resources/AgentSeed.js +19 -4
  108. package/dist/resources/AutoPromoteCandidates.js +7 -1
  109. package/dist/resources/Credential.js +177 -2
  110. package/dist/resources/Federation.js +752 -132
  111. package/dist/resources/FederationRetry.js +140 -0
  112. package/dist/resources/InstructionVersion.js +220 -0
  113. package/dist/resources/Integration.js +300 -25
  114. package/dist/resources/Memory.js +2113 -604
  115. package/dist/resources/MemoryArchive.js +75 -42
  116. package/dist/resources/MemoryBootstrap.js +227 -64
  117. package/dist/resources/MemoryCandidate.js +21 -1
  118. package/dist/resources/MemoryDedupStats.js +30 -1
  119. package/dist/resources/MemoryFeed.js +327 -45
  120. package/dist/resources/MemoryGrant.js +21 -1
  121. package/dist/resources/MemoryMaintenance.js +129 -25
  122. package/dist/resources/MemoryPurge.js +232 -0
  123. package/dist/resources/MemoryReflect.js +7 -2
  124. package/dist/resources/MemoryReindex.js +24 -8
  125. package/dist/resources/Message.js +5 -3
  126. package/dist/resources/OAuth.js +186 -9
  127. package/dist/resources/OrgEvent.js +126 -3
  128. package/dist/resources/OrgSkillAssignment.js +209 -0
  129. package/dist/resources/Presence.js +144 -49
  130. package/dist/resources/PromoteMemoryCandidate.js +18 -7
  131. package/dist/resources/Relationship.js +23 -0
  132. package/dist/resources/SemanticSearch.js +63 -32
  133. package/dist/resources/Soul.js +189 -76
  134. package/dist/resources/TeamDirectory.js +35 -0
  135. package/dist/resources/WorkspaceState.js +21 -1
  136. package/dist/resources/XAA.js +212 -65
  137. package/dist/resources/agent-auth.js +40 -15
  138. package/dist/resources/agent-status-guard.js +63 -0
  139. package/dist/resources/auth-middleware.js +402 -162
  140. package/dist/resources/ed25519-auth.js +1 -1
  141. package/dist/resources/embedding-space-guard.js +366 -72
  142. package/dist/resources/engine-version-stamp-boot.js +53 -0
  143. package/dist/resources/federation-classify.js +94 -0
  144. package/dist/resources/federation-crypto.js +5 -5
  145. package/dist/resources/federation-retry-lib.js +135 -0
  146. package/dist/resources/flair-agent-role-boot.js +26 -0
  147. package/dist/resources/grant-visibility.js +135 -0
  148. package/dist/resources/harper-routing.js +83 -0
  149. package/dist/resources/health.js +130 -20
  150. package/dist/resources/host-source-citation.js +49 -0
  151. package/dist/resources/host-source-visibility.js +7 -6
  152. package/dist/resources/instance-create-lock.js +17 -0
  153. package/dist/resources/instance-identity.js +23 -0
  154. package/dist/resources/instruction-version-record.js +343 -0
  155. package/dist/resources/key-lock.js +31 -0
  156. package/dist/resources/mcp-handler.js +36 -8
  157. package/dist/resources/mcp-oauth-env-guard.js +36 -0
  158. package/dist/resources/mcp-oauth.js +26 -12
  159. package/dist/resources/mcp-tool-arguments.js +4 -6
  160. package/dist/resources/mcp-tools.js +150 -23
  161. package/dist/resources/memory-bootstrap-lib.js +5 -15
  162. package/dist/resources/memory-declared-attributes.js +3 -1
  163. package/dist/resources/memory-deletion-history.js +55 -0
  164. package/dist/resources/memory-durability.js +54 -0
  165. package/dist/resources/memory-embed-hash.js +88 -0
  166. package/dist/resources/memory-embedding-value.js +8 -0
  167. package/dist/resources/memory-host-source.js +27 -5
  168. package/dist/resources/memory-id-guard.js +75 -0
  169. package/dist/resources/memory-redaction.js +236 -0
  170. package/dist/resources/memory-supplied-vector.js +72 -0
  171. package/dist/resources/memory-write-lock.js +310 -0
  172. package/dist/resources/memory-write-response.js +139 -0
  173. package/dist/resources/migrations/data-dir.js +74 -16
  174. package/dist/resources/migrations/dir-safety.js +1 -1
  175. package/dist/resources/migrations/embedding-stamp.js +193 -79
  176. package/dist/resources/migrations/export.js +1 -0
  177. package/dist/resources/migrations/graph-heal.js +18 -25
  178. package/dist/resources/migrations/lock.js +7 -1
  179. package/dist/resources/migrations/snapshot.js +1 -0
  180. package/dist/resources/migrations/source-fields.js +5 -5
  181. package/dist/resources/migrations/synthetic-test-migration.js +14 -11
  182. package/dist/resources/migrations/visibility-backfill.js +29 -29
  183. package/dist/resources/multi-worker-guard.js +121 -0
  184. package/dist/resources/oauth-discovery.js +1 -0
  185. package/dist/resources/oauth-wellknown.js +8 -4
  186. package/dist/resources/object-body-guard.js +33 -0
  187. package/dist/resources/org-event-created-at.js +133 -0
  188. package/dist/resources/originator-instance.js +39 -7
  189. package/dist/resources/owner-delete-recheck.js +78 -0
  190. package/dist/resources/owner-field-guard.js +39 -5
  191. package/dist/resources/owner-scoped-write-policy.js +212 -0
  192. package/dist/resources/owner-scoped-writes.js +58 -0
  193. package/dist/resources/presence-receipt.js +236 -0
  194. package/dist/resources/promotion-stamp.js +47 -12
  195. package/dist/resources/record-owner-guard.js +74 -26
  196. package/dist/resources/record-types.js +17 -1
  197. package/dist/resources/relay-ops.js +78 -6
  198. package/dist/resources/replay-store.js +145 -21
  199. package/dist/resources/request-target.js +136 -0
  200. package/dist/resources/request-transaction.js +35 -0
  201. package/dist/resources/search-readiness.js +4 -1
  202. package/dist/resources/seed-ids.js +9 -0
  203. package/dist/resources/seed-reservation.js +117 -0
  204. package/dist/resources/semantic-retrieval-core.js +20 -9
  205. package/dist/resources/skill-manifest.js +190 -0
  206. package/dist/resources/skill-provenance.js +15 -10
  207. package/dist/resources/skill-subject.js +53 -0
  208. package/dist/resources/skill-version-write.js +432 -0
  209. package/dist/resources/skill-write-fault.js +17 -0
  210. package/dist/resources/skill-write-policy.js +67 -0
  211. package/dist/resources/skill-write.js +67 -7
  212. package/dist/resources/table-helpers.js +10 -7
  213. package/dist/resources/team-directory.js +248 -0
  214. package/dist/resources/tool-descriptors/index.js +69 -8
  215. package/dist/resources/txn-pause-point.js +118 -0
  216. package/dist/resources/usage-recording.js +171 -63
  217. package/dist/resources/write-back.js +218 -0
  218. package/dist/src/engine-version-contract.js +1 -0
  219. package/dist/src/keystore.js +72 -0
  220. package/dist/src/lib/agent-home-fields.js +132 -0
  221. package/dist/src/lib/agent-id-rule.js +46 -0
  222. package/dist/src/lib/agent-key-register.js +80 -0
  223. package/dist/src/lib/atomic-write.js +256 -0
  224. package/dist/src/lib/credential-status-rule.js +78 -0
  225. package/dist/src/lib/expired-by-agent.js +37 -0
  226. package/dist/src/lib/flair-agent-role.js +120 -0
  227. package/dist/src/lib/idp-mapping-rule.js +81 -0
  228. package/dist/src/lib/instance-identity-row.js +20 -0
  229. package/dist/src/lib/mcp-oauth-env-core.js +133 -0
  230. package/dist/src/lib/memory-attributes.js +2 -0
  231. package/dist/src/lib/memory-id-policy.js +46 -0
  232. package/dist/src/lib/principal-status.js +29 -0
  233. package/dist/src/lib/proto-safe-record.js +42 -0
  234. package/dist/src/lib/reembed-server-support.js +66 -0
  235. package/dist/src/lib/scheduler-platform.js +10 -6
  236. package/dist/src/lib/systemd-agent-id.js +38 -0
  237. package/docs/access-control.md +768 -0
  238. package/docs/api-reference.md +52 -13
  239. package/docs/auth.md +10 -12
  240. package/docs/bridges.md +11 -0
  241. package/docs/claude-code.md +34 -4
  242. package/docs/deepseek-harness.md +1 -1
  243. package/docs/deploying-on-fabric.md +70 -0
  244. package/docs/deployment.md +2 -0
  245. package/docs/embedding-in-a-harper-app.md +1 -1
  246. package/docs/federation.md +33 -2
  247. package/docs/hosted-on-fabric.md +43 -36
  248. package/docs/integrations.md +6 -6
  249. package/docs/mcp-clients.md +10 -5
  250. package/docs/n8n.md +17 -11
  251. package/docs/notes/mcp-agent-auth-consumer.md +12 -4
  252. package/docs/notes/mcp-oauth-model2.md +34 -5
  253. package/docs/quickstart-fabric.md +2 -2
  254. package/docs/quickstart.md +9 -1
  255. package/docs/releasing.md +34 -28
  256. package/docs/rem.md +8 -0
  257. package/docs/secrets-and-keys.md +19 -2
  258. package/docs/standalone-local.md +1 -0
  259. package/docs/supply-chain-policy.md +13 -3
  260. package/docs/upgrade.md +32 -6
  261. package/package.json +12 -6
  262. package/schemas/agent-key-registration.graphql +22 -0
  263. package/schemas/agent.graphql +3 -0
  264. package/schemas/federation.graphql +38 -1
  265. package/schemas/memory.graphql +115 -5
  266. package/schemas/oauth.graphql +27 -4
  267. package/schemas/schema.graphql +2 -0
  268. package/templates/launchd/start-flair-with-admin-pass.sh +89 -16
@@ -1,3 +1,4 @@
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";
@@ -6,15 +7,25 @@ import { canonicalize, signBody, verifyBodySignature, signBodyFresh, verifyBodyS
6
7
  import { reconcileState } from "./relay-lib.js";
7
8
  import { decideInstanceAnswer, INSTANCE_ROW_PRUNE_REMEDY, multipleInstanceRowsMessage, } from "../src/lib/instance-identity-row.js";
8
9
  import { readAllInstanceRows } from "./instance-identity-rows.js";
9
- import { findOrCreateInstance } from "./instance-create-lock.js";
10
+ import { findOrCreateInstance, storeInstanceSeed } from "./instance-create-lock.js";
10
11
  import { withDetachedTxnAsync } from "./table-helpers.js";
11
12
  import { isSkillWrite } from "./skill-write.js";
13
+ import { stampEphemeralExpiry } from "./memory-durability.js";
14
+ import { isReservedSeedId } from "./seed-reservation.js";
15
+ import { AGENT_ID_ERROR, isValidAgentId } from "../src/lib/agent-id-rule.js";
16
+ import { endsWithContentSelectorSuffix } from "../src/lib/memory-id-policy.js";
12
17
  import { stripInboundMemoryRow, stripServerStampedFields } from "./memory-declared-attributes.js";
13
18
  import { noteWriteStamp } from "./embedding-space-guard.js";
14
19
  import { initFederationCleanup } from "./federation-cleanup.js";
15
20
  import { verifyFederationRequestBody } from "./replay-store.js";
16
- import { classifyRecord, reconstructRecordVerifyBody, checkPrincipalEntitlement, } from "./federation-classify.js";
17
- export { classifyRecord, reconstructRecordVerifyBody, checkPrincipalEntitlement, recordSignatureVersion, PRINCIPAL_OWNING_TABLES, FEDERATION_TABLE_POLICY, FEDERATION_SYNC_TABLES, } from "./federation-classify.js";
21
+ import { CommittedRowChanged, confirmCommittedRow, writeBackCommittedRow, WriteBackConflictError } from "./write-back.js";
22
+ import { withKeyLock } from "./key-lock.js";
23
+ import { withOwnedTransaction } from "./request-transaction.js";
24
+ import { txnPausePoint } from "./txn-pause-point.js";
25
+ import { retryRowProblem } from "./federation-retry-lib.js";
26
+ import { classifyRecord, reconstructRecordVerifyBody, checkPrincipalEntitlement, inboundChangesExistingPrincipalStatus, inboundChangesExistingPendingKey, } from "./federation-classify.js";
27
+ import { mergePresenceReceipt, presenceHomeBindingReason, presenceReceiveEnabled, validatePresenceReceipt, } from "./presence-receipt.js";
28
+ 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
29
  // Federation anti-replay: FederationPair and FederationSync both verify through
19
30
  // verifyFederationRequestBody (resources/replay-store.ts), which claims each
20
31
  // body nonce ONCE in the instance-wide `ReplayNonce` table after the signature
@@ -105,18 +116,18 @@ export function mergeRecord(local, remote) {
105
116
  * cosine that foreign vector = mixed-space garbage — exactly the failure the
106
117
  * guard exists to kill. Trip the latch here.
107
118
  *
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
119
+ * Kept as a note-ONLY helper — the
120
+ * merge's row write stays INLINE at the call site (every synced table's merge
121
+ * through the shared write-back helper, write-back.ts, flair#2441/flair#2450),
122
+ * so the raw-writer coverage gates
123
+ * (authority-field-guard.test.ts / memory-embedding-writer-coverage.test.ts)
124
+ * still enumerate the writer — while the trip decision itself is
125
+ * unit-testable without standing up the full signed sync-in path (see
115
126
  * test/unit-isolated/embedding-space-guard-federation.test.ts).
116
127
  */
117
- export function noteFederationMergedMemory(recordTable, mergedData) {
128
+ export function noteFederationMergedMemory(recordTable, mergedData, previous) {
118
129
  if (recordTable === "Memory") {
119
- noteWriteStamp(mergedData.embeddingModel);
130
+ noteWriteStamp(mergedData.embeddingModel, previous);
120
131
  }
121
132
  }
122
133
  // ─── Instance identity ───────────────────────────────────────────────────────
@@ -240,10 +251,7 @@ export class FederationInstance extends Resource {
240
251
  // the request (the lock cannot serialise a write that commits after the
241
252
  // method returns — the earlier BLOCKED finding, flair#1897 slice 1).
242
253
  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
- }),
254
+ setSeed: (createdId, seed) => withDetachedTxnAsync(this.getContext?.(), () => storeInstanceSeed(createdId, seed)),
247
255
  seedPresent: async (rowId) => {
248
256
  try {
249
257
  const { keystore } = await import("../src/keystore.js");
@@ -325,7 +333,34 @@ export class FederationInstance extends Resource {
325
333
  /**
326
334
  * POST /FederationPair — one-shot pairing handshake.
327
335
  * 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`.
336
+ * A FIRST-time pair requires a one-time pairing token generated by
337
+ * `flair federation token`. An otherwise valid, non-revoked RE-pair of an
338
+ * existing peer (same instance id, and a signed request whose key equals the
339
+ * pinned public key) requires NO token — the protocol requires none for an
340
+ * existing peer — though it validates and consumes a supplied one. A re-pair of
341
+ * a revoked peer is refused.
342
+ *
343
+ * Before writing, a re-pair rechecks the pinned key and status inside its owned
344
+ * transaction; a supplied token must pass validation before that Peer re-read.
345
+ * A key that differs is refused (409); otherwise a revoked
346
+ * row is refused (403 peer_revoked). Either refusal writes no Peer row and
347
+ * consumes no token. A row deleted before that re-read is no longer an existing
348
+ * peer: with a valid token the request is paired as a first-time pair with that
349
+ * token; without one it is refused (401, a pairing token is required). On the
350
+ * token path the owned transaction's first read is its token read, so these
351
+ * re-read checks cover a change committed before that read, not after it.
352
+ *
353
+ * A first-time pair (no Peer row at the pre-transaction read) stages its token
354
+ * consume and its Peer write in one owned transaction, then confirms against
355
+ * committed state that the Peer row is still absent before that transaction
356
+ * commits. If that confirm read finds a row for the instance in committed state
357
+ * although the pre-transaction read returned none, the pair is refused (409
358
+ * peer_row_appeared): the transaction aborts, so this request writes no Peer row
359
+ * and the token stays unconsumed. The confirm reports only a row present when it
360
+ * runs, not when that row was committed; it also detects a row committed after
361
+ * the transaction's token read, if that row is still present. Harper has no
362
+ * compare-and-set on a table write, so a row committed after the confirm read
363
+ * and before the commit is not seen by it.
329
364
  */
330
365
  export class FederationPair extends Resource {
331
366
  // Pairing is a public endpoint by design — spokes have no Harper credentials
@@ -405,87 +440,216 @@ export class FederationPair extends Resource {
405
440
  INSTANCE_ROW_PRUNE_REMEDY,
406
441
  }), { status: 409, headers: { "content-type": "application/json" } });
407
442
  }
408
- // Check if already paired (re-pairing doesn't need a token)
443
+ // Check for an existing peer; an otherwise valid, non-revoked re-pair needs no token.
409
444
  const existing = await databases.flair.Peer.get(instanceId);
410
445
  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,
446
+ // Re-pairing: verify public key matches (prevents impersonation). Both
447
+ // owned-transaction writes below repeat this comparison on their re-read.
448
+ if (existing.publicKey !== publicKey)
449
+ return publicKeyMismatchRefusal();
450
+ // A revoked peer does not re-pair (flair#2333): a revoke is a local
451
+ // decision, and a re-pair does not restore it. This runs BEFORE any token
452
+ // is consumed, so this refusal changes neither the Peer row nor a token.
453
+ if (existing.status === "revoked")
454
+ return peerRevokedRefusal();
455
+ // An otherwise valid, non-revoked re-pair validates and consumes a supplied
456
+ // token as the first-pair path does (flair#2333), under this node's token
457
+ // lock; a consumed token cannot pair a later new peer. Such a re-pair with
458
+ // NO token still proceeds — the protocol requires none (docs/federation.md,
459
+ // "Pairing tokens"). The supplied token is not the request's credential;
460
+ // the request still has to prove key ownership above (`verifyResult`).
461
+ //
462
+ // With a supplied token, the consume AND this peer write run in a FRESH
463
+ // OWNED transaction committed BEFORE the lock releases (withOwnedTransaction).
464
+ // Harper commits the request's own transaction only after this handler
465
+ // returns, so a consume that joined it would still be invisible when the lock
466
+ // frees and a pairing taking the lock right after would read the token
467
+ // unconsumed. The consume and the peer write commit together or neither does:
468
+ // a Peer write that REJECTS inside this transaction callback aborts the owned
469
+ // transaction, so the token is left unconsumed and this re-pair is refused by
470
+ // name (a commit-time error propagates unnamed).
471
+ //
472
+ // Both paths build an existing peer's updated row from their transactional
473
+ // re-read, never from the pre-transaction read above.
474
+ const rePairedRow = (base) => ({
475
+ ...base,
476
+ endpoint: endpoint ?? base.endpoint,
421
477
  status: "paired",
422
478
  updatedAt: new Date().toISOString(),
423
479
  });
480
+ const writePeerRow = (owned, row) => databases.flair.Peer.put(row, owned);
481
+ if (pairingToken) {
482
+ const ctx = this.getContext?.() ?? {};
483
+ // Test-only: inert unless the fault-injection env opt-in is set and armed.
484
+ // Pause AFTER the pre-transaction read of the Peer row and BEFORE the owned
485
+ // transaction, so a competing revoke, key change or delete can commit in
486
+ // between (flair#2333).
487
+ const tokenRepairPause = txnPausePoint("federation-pair-repair-token-pre");
488
+ if (tokenRepairPause)
489
+ await tokenRepairPause;
490
+ let refusal;
491
+ let pairedAsFirst = false;
492
+ try {
493
+ refusal = await withPairingTokenClaim(pairingToken, () => withOwnedTransaction(ctx, async (owned) => {
494
+ const claim = await consumePairingToken(pairingToken, instanceId, owned);
495
+ if (claim.kind !== "consumed")
496
+ return claim;
497
+ // The Peer re-read sees a change committed before the owned
498
+ // transaction's first read (its token read); a change committed
499
+ // after that read is not covered by this re-read. A pinned key that
500
+ // differs from the signed request's key is refused 409, a revoked row
501
+ // 403 peer_revoked; throwing aborts the transaction, so the staged
502
+ // consume rolls back and no Peer row is written.
503
+ const current = await databases.flair.Peer.get(instanceId, owned);
504
+ if (current && current.publicKey !== publicKey)
505
+ throw new PeerKeyChangedDuringRepairError();
506
+ if (current?.status === "revoked")
507
+ throw new PeerRevokedDuringRepairError();
508
+ // A row deleted before the re-read: this is no longer a re-pair, and
509
+ // the valid token just consumed makes it a first-time pair. Write the
510
+ // row the first-pair path writes, built from the verified request —
511
+ // no field of the deleted row survives.
512
+ pairedAsFirst = !current;
513
+ try {
514
+ await writePeerRow(owned, current ? rePairedRow(current) : firstPairPeerRow(instanceId, publicKey, role, endpoint));
515
+ }
516
+ catch (err) {
517
+ // Rethrow so the owned transaction ABORTS: the consume rolls back
518
+ // with the peer write (both commit or neither does). Tagged so the
519
+ // caller answers a named refusal, not a bare 500.
520
+ throw new PeerWriteFailedError(err);
521
+ }
522
+ return claim;
523
+ }));
524
+ }
525
+ catch (err) {
526
+ if (err instanceof PeerWriteFailedError) {
527
+ const cause = err.cause;
528
+ 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). ` +
529
+ `${cause?.constructor?.name ?? "Error"}: ${cause?.message ?? cause}`);
530
+ return peerWriteFailedRefusal();
531
+ }
532
+ if (err instanceof PeerRevokedDuringRepairError) {
533
+ 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.");
534
+ return peerRevokedRefusal();
535
+ }
536
+ if (err instanceof PeerKeyChangedDuringRepairError) {
537
+ 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.");
538
+ return publicKeyMismatchRefusal();
539
+ }
540
+ throw err;
541
+ }
542
+ if (refusal)
543
+ return refusal;
544
+ // Paired as a first-time pair: attempt bootstrap-user cleanup.
545
+ if (pairedAsFirst)
546
+ await dropPairBootstrapUser(pairingToken, ctx);
547
+ }
548
+ // The NO-token re-pair's peer write: the token path wrote the row inside the
549
+ // owned transaction above, so its consume and write committed together before
550
+ // the lock released. This path spends no token, but the same shape applies: the
551
+ // write runs in a FRESH OWNED transaction (withOwnedTransaction) that RE-READS
552
+ // the Peer row the pre-transaction read above decided on. A row whose pinned
553
+ // key now differs from the signed request's key is refused 409 (the key
554
+ // mismatch above); a row that is now revoked is refused with the token path's
555
+ // 403 peer_revoked; a row that is now gone means this is no longer a re-pair,
556
+ // and with no token it is refused like a first-time pair without one (401, a
557
+ // pairing token is required). None of these writes a row. The pause below
558
+ // still sits BEFORE that owned transaction, so a competing change commits in
559
+ // between (the guard tests).
560
+ const repairPause = txnPausePoint("federation-pair-repair-pre");
561
+ if (repairPause)
562
+ await repairPause;
563
+ if (!pairingToken) {
564
+ const ctx = this.getContext?.() ?? {};
565
+ const refusal = await withOwnedTransaction(ctx, async (owned) => {
566
+ const current = await databases.flair.Peer.get(instanceId, owned);
567
+ if (!current)
568
+ return pairingTokenRequiredRefusal();
569
+ if (current.publicKey !== publicKey)
570
+ return publicKeyMismatchRefusal();
571
+ if (current.status === "revoked")
572
+ return peerRevokedRefusal();
573
+ await writePeerRow(owned, rePairedRow(current));
574
+ return undefined;
575
+ });
576
+ if (refusal)
577
+ return refusal;
578
+ }
424
579
  }
425
580
  else {
426
581
  // New peer — require a valid pairing token in the request body.
427
582
  // The handler self-validates because the endpoint is public at the
428
583
  // Harper-auth and middleware layers (Bearer is not usable on Harper —
429
584
  // 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
585
+ if (!pairingToken)
586
+ return pairingTokenRequiredRefusal();
587
+ // Consume the token under its per-key lock (flair#2333): the claim is
588
+ // check-then-consume, so two pairings on this node using the same token
589
+ // cannot both commit a successful claim. The lock is this ONE Flair node's
590
+ // PairingToken store lock, so it excludes concurrent pairings on this node; it
591
+ // is not shared across the nodes of a Fabric instance (see the PR body).
592
+ // A contender exhausting lock attempts while the lock is held gets 409;
593
+ // one acquiring it after a successful claim commits sees the consumed
594
+ // token and gets 401.
595
+ //
596
+ // The consume AND the Peer write run in a FRESH OWNED transaction that is
597
+ // COMMITTED before the lock releases (withOwnedTransaction). Harper wraps
598
+ // POST /FederationPair in a REQUEST transaction that commits only after the
599
+ // handler returns, so writes that joined it would still be invisible when
600
+ // the lock frees: a pairing that takes the lock right after release could
601
+ // re-read the token unconsumed and pair a second peer. Detaching the request
602
+ // transaction re-reads the token from committed state and commits the
603
+ // consume and the Peer write while the lock is held.
452
604
  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.
605
+ // Test-only: inert unless the fault-injection env opt-in is set and armed.
606
+ // Pause AFTER the pre-transaction read of the Peer row and BEFORE the owned
607
+ // transaction, so a competing pair or revoke for this instance commits in
608
+ // between (flair#2512).
609
+ const firstPairPause = txnPausePoint("federation-pair-first-pre");
610
+ if (firstPairPause)
611
+ await firstPairPause;
612
+ let refusal;
482
613
  try {
483
- const bootstrapUsername = `pair-bootstrap-${pairingToken.slice(0, 8)}`;
484
- await server.operation({ operation: "drop_user", username: bootstrapUsername }, ctx, false);
614
+ refusal = await withPairingTokenClaim(pairingToken, () => withOwnedTransaction(ctx, async (owned) => {
615
+ const claim = await consumePairingToken(pairingToken, instanceId, owned);
616
+ if (claim.kind !== "consumed")
617
+ return claim;
618
+ await databases.flair.Peer.put(firstPairPeerRow(instanceId, publicKey, role, endpoint), owned);
619
+ // The pre-transaction read above returned no Peer row, and this first
620
+ // pair has now staged one. Confirm against COMMITTED state that the row
621
+ // is still absent (confirmCommittedRow, resources/write-back.ts): its
622
+ // read is an explicit fresh context, so it sees the Peer row present in
623
+ // committed state when it runs, including one committed after this
624
+ // transaction's token read (which pins this transaction's own read
625
+ // snapshot). It reports presence, not when the row was committed, and a
626
+ // row deleted again before it runs is not seen. A row there is not the
627
+ // one this request staged, so the request must not answer `paired` for
628
+ // it: the throw aborts the owned transaction, the staged consume and
629
+ // Peer write are discarded, and the caller answers a named refusal with
630
+ // the token left unconsumed. A change committed after this confirm read
631
+ // and before the commit is not seen by it: Harper has no compare-and-set
632
+ // on a table write.
633
+ await confirmCommittedRow(databases.flair.Peer, instanceId, (committed) => committed == null);
634
+ return claim;
635
+ }));
485
636
  }
486
637
  catch (err) {
487
- console.warn(`[federation] drop_user failed: ${err?.message} — cleanup sweep will retry`);
638
+ if (err instanceof CommittedRowChanged)
639
+ return firstPairRowAppearedRefusal();
640
+ throw err;
488
641
  }
642
+ if (refusal)
643
+ return refusal;
644
+ // Test-only: inert unless the fault-injection env opt-in is set and armed.
645
+ // Pause AFTER the token lock released (and the consume is committed) but
646
+ // BEFORE this request's own transaction commits (Harper commits it when the
647
+ // handler returns). A pairing that takes the now-free lock here must read
648
+ // the token consumed; a request-transaction write would not (flair#2333).
649
+ const claimed = txnPausePoint("federation-pair-claim-done");
650
+ if (claimed)
651
+ await claimed;
652
+ await dropPairBootstrapUser(pairingToken, ctx);
489
653
  }
490
654
  // Return our own identity for the peer to record — `{ id, publicKey, role }`,
491
655
  // decided BEFORE the token was consumed (above; flair#1883 round 3). An
@@ -502,7 +666,211 @@ export class FederationPair extends Resource {
502
666
  };
503
667
  }
504
668
  }
505
- // ─── Sync endpoint ───────────────────────────────────────────────────────────
669
+ /** The per-token lock namespace (resources/key-lock.ts); a token's lock key is its own. */
670
+ const PAIRING_TOKEN_LOCK_NAMESPACE = "flair-pairing-token";
671
+ /**
672
+ * The token lock gets up to `PAIR_LOCK_ATTEMPTS` acquisition attempts, with
673
+ * at most one fewer waits of `PAIR_LOCK_WAIT_MS` nominally between attempts.
674
+ * Exhaustion refuses the pairing; timer spacing does not bound elapsed time.
675
+ */
676
+ const PAIR_LOCK_ATTEMPTS = 200;
677
+ const PAIR_LOCK_WAIT_MS = 10;
678
+ /** 401 for a pair with no pairing token: a first-time pair, and a re-pair whose Peer row was deleted, both require one. */
679
+ function pairingTokenRequiredRefusal() {
680
+ return new Response(JSON.stringify({
681
+ error: "pairingToken required in body for first-time pair",
682
+ }), { status: 401, headers: { "content-type": "application/json" } });
683
+ }
684
+ /** 409 for a re-pair whose signed request's key is not the peer row's pinned public key. */
685
+ function publicKeyMismatchRefusal() {
686
+ return new Response(JSON.stringify({
687
+ error: "public key mismatch — peer already paired with different key",
688
+ }), { status: 409, headers: { "content-type": "application/json" } });
689
+ }
690
+ /** The Peer row a first-time pair builds without an earlier Peer row. */
691
+ function firstPairPeerRow(instanceId, publicKey, role, endpoint) {
692
+ const at = new Date().toISOString();
693
+ return {
694
+ id: instanceId,
695
+ publicKey,
696
+ role: role ?? "spoke",
697
+ endpoint: endpoint ?? null,
698
+ status: "paired",
699
+ relayOnly: false,
700
+ pairedAt: at,
701
+ createdAt: at,
702
+ updatedAt: at,
703
+ };
704
+ }
705
+ /**
706
+ * Drop the bootstrap user that was created alongside this pairing token, after a
707
+ * first-time pair consumed it. Failure here is logged and non-fatal.
708
+ */
709
+ async function dropPairBootstrapUser(pairingToken, ctx) {
710
+ try {
711
+ const bootstrapUsername = `pair-bootstrap-${pairingToken.slice(0, 8)}`;
712
+ await server.operation({ operation: "drop_user", username: bootstrapUsername }, ctx, false);
713
+ }
714
+ catch (err) {
715
+ console.warn(`[federation] drop_user failed: ${err?.message} — cleanup sweep will retry`);
716
+ }
717
+ }
718
+ /** 403 for a re-pair of a revoked peer: a revoke is a local decision, and a re-pair does not restore it. */
719
+ function peerRevokedRefusal() {
720
+ return new Response(JSON.stringify({
721
+ error: "peer_revoked",
722
+ message: "this Peer row is revoked; it stays revoked",
723
+ }), { status: 403, headers: { "content-type": "application/json" } });
724
+ }
725
+ /**
726
+ * 409 for a first-time pair whose committed-state confirm found a Peer row for
727
+ * the instance although its pre-transaction read returned none. The owned
728
+ * transaction aborted: this request wrote no Peer row and did not consume the
729
+ * pairing token.
730
+ * Signature verification recorded the request's replay nonce before pairing
731
+ * began; that record stays.
732
+ */
733
+ function firstPairRowAppearedRefusal() {
734
+ return new Response(JSON.stringify({
735
+ error: "peer_row_appeared",
736
+ message: "a Peer row for this instance is present in committed state although this pairing's earlier read found none; this request wrote no Peer row and did not consume the pairing token",
737
+ }), { status: 409, headers: { "content-type": "application/json" } });
738
+ }
739
+ /**
740
+ * Tag a token-supplying re-pair's Peer.put rejection inside the owned transaction
741
+ * callback (flair#2333), so it aborts before the caller returns peer_write_failed.
742
+ */
743
+ class PeerWriteFailedError extends Error {
744
+ cause;
745
+ constructor(cause) {
746
+ super("re-pair Peer write failed");
747
+ this.cause = cause;
748
+ this.name = "PeerWriteFailedError";
749
+ }
750
+ }
751
+ /**
752
+ * A token-supplying re-pair's Peer re-read found a revoked row (flair#2333).
753
+ * The transaction aborts, so the token claim that ran with it
754
+ * rolls back and the token is left unconsumed; the caller answers the revoked
755
+ * refusal, not a bare 500.
756
+ */
757
+ class PeerRevokedDuringRepairError extends Error {
758
+ constructor() {
759
+ super("re-pair Peer row revoked inside the owned transaction");
760
+ this.name = "PeerRevokedDuringRepairError";
761
+ }
762
+ }
763
+ /**
764
+ * A token-supplying re-pair's Peer re-read found a pinned key unlike the request's
765
+ * key (flair#2333). The transaction aborts, so the token claim that ran with it
766
+ * rolls back and the token is left unconsumed; the caller answers the key-mismatch
767
+ * refusal, not a bare 500.
768
+ */
769
+ class PeerKeyChangedDuringRepairError extends Error {
770
+ constructor() {
771
+ super("re-pair Peer row's pinned key differs from the signed request's key on the owned transaction's re-read");
772
+ this.name = "PeerKeyChangedDuringRepairError";
773
+ }
774
+ }
775
+ /**
776
+ * 503 for a token-supplying re-pair whose Peer.put rejected inside the owned
777
+ * transaction callback. The token consume and Peer write rolled back; the
778
+ * replay nonce remains recorded. The token is retryable while valid.
779
+ */
780
+ function peerWriteFailedRefusal() {
781
+ return new Response(JSON.stringify({
782
+ error: "peer_write_failed",
783
+ 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",
784
+ }), { status: 503, headers: { "content-type": "application/json" } });
785
+ }
786
+ /**
787
+ * Run one pairing token's check-and-consume under that token's per-key lock
788
+ * (flair#2333), and map the outcome to the refusal the caller returns. `fn`
789
+ * runs only when the lock is held and the store has a lock; `undefined` means
790
+ * `fn` ran and its claim consumed the token (any other claim maps to its refusal
791
+ * through `pairingTokenRefusal`).
792
+ *
793
+ * The lock is the PairingToken store's per-key lock (resources/key-lock.ts): it
794
+ * is shared by this ONE Harper node's threads, so it excludes concurrent
795
+ * pairings of the same token WITHIN one Flair node. Harper can run several
796
+ * nodes for one instance; the lock is not shared across them (see the PR body).
797
+ */
798
+ async function withPairingTokenClaim(pairingToken, fn) {
799
+ const outcome = await withKeyLock(databases.flair.PairingToken?.primaryStore, [PAIRING_TOKEN_LOCK_NAMESPACE, pairingToken], fn, PAIR_LOCK_ATTEMPTS, PAIR_LOCK_WAIT_MS);
800
+ if (outcome.kind === "busy") {
801
+ return new Response(JSON.stringify({
802
+ error: "pairing_in_progress",
803
+ message: "another pairing of this token is still in progress; retry",
804
+ }), { status: 409, headers: { "content-type": "application/json" } });
805
+ }
806
+ if (outcome.kind === "unavailable") {
807
+ return new Response(JSON.stringify({
808
+ error: "pairing_lock_unavailable",
809
+ message: "this instance's PairingToken store has no per-key lock, so the pairing was refused",
810
+ }), { status: 503, headers: { "content-type": "application/json" } });
811
+ }
812
+ return pairingTokenRefusal(outcome.value);
813
+ }
814
+ /** The refusal a finished pairing-token claim maps to, or `undefined` when it consumed the token. */
815
+ function pairingTokenRefusal(claim) {
816
+ if (claim.kind === "consumed")
817
+ return undefined;
818
+ if (claim.kind === "bootstrap_mismatch") {
819
+ return new Response(JSON.stringify({
820
+ error: "bootstrap_user_token_mismatch",
821
+ }), { status: 401, headers: { "content-type": "application/json" } });
822
+ }
823
+ return new Response(JSON.stringify({ error: "invalid_or_expired_pairing_token" }), {
824
+ status: 401, headers: { "content-type": "application/json" },
825
+ });
826
+ }
827
+ /**
828
+ * The check-then-consume of one pairing token, run while holding that token's
829
+ * per-key lock (FederationPair.post). The token is re-read on entry: a pairing
830
+ * that consumed it first makes this one refuse. On success the token records
831
+ * `consumerInstanceId` and is consumed.
832
+ */
833
+ async function consumePairingToken(pairingToken, consumerInstanceId, ctx) {
834
+ // Fetch the token record for consumption IN the caller's transaction — the
835
+ // fresh OWNED one the claim runs in (withOwnedTransaction), never the request's
836
+ // earlier read snapshot. Harper's transaction() set `ctx.transaction`, so the
837
+ // read sees committed state and the write below commits with it.
838
+ let tokenRecord = null;
839
+ try {
840
+ tokenRecord = await databases.flair.PairingToken.get(pairingToken, ctx);
841
+ }
842
+ catch { /* table may not exist */ }
843
+ const pause = txnPausePoint("federation-pair-token");
844
+ if (pause)
845
+ await pause;
846
+ if (!tokenRecord || tokenRecord.consumedBy) {
847
+ return { kind: "refused" };
848
+ }
849
+ if (tokenRecord.expiresAt && new Date(tokenRecord.expiresAt) < new Date()) {
850
+ return { kind: "refused" };
851
+ }
852
+ // PR-4: bind authenticated bootstrap user to specific pairing token.
853
+ // The middleware annotates the REQUEST (request.tpsAgent); getContext() IS
854
+ // that request (resources/Resource.js getResource), not a wrapper with a
855
+ // `.request` field — the same read A2AAdapter uses (`ctx.request ?? ctx`).
856
+ const ctxRequest = ctx?.request ?? ctx ?? {};
857
+ const authedUser = ctxRequest.tpsAgent;
858
+ const isAdmin = ctxRequest.tpsAgentIsAdmin === true;
859
+ if (!isAdmin && authedUser) {
860
+ const expectedBootstrap = `pair-bootstrap-${pairingToken.slice(0, 8)}`;
861
+ if (authedUser !== expectedBootstrap) {
862
+ return { kind: "bootstrap_mismatch" };
863
+ }
864
+ }
865
+ // Consume the token
866
+ await databases.flair.PairingToken.put({
867
+ ...tokenRecord,
868
+ consumedBy: consumerInstanceId,
869
+ consumedAt: new Date().toISOString(),
870
+ }, ctx);
871
+ return { kind: "consumed" };
872
+ }
873
+ const RECORD_MERGE_DEADLINE_MS = 5_000;
506
874
  /**
507
875
  * POST /FederationSync — push sync records from a peer.
508
876
  * In 1.0, this is a simple HTTP push (not WebSocket).
@@ -540,14 +908,34 @@ export class FederationSync extends Resource {
540
908
  const verifyResult = await verifyFederationRequestBody(data, peer.publicKey);
541
909
  if (!verifyResult.ok)
542
910
  return federationVerifyRefusal(verifyResult.reason);
911
+ const offeredKeys = new Set();
912
+ for (const record of records) {
913
+ if (typeof record?.table !== "string" || record.table.length === 0 ||
914
+ typeof record?.id !== "string" || record.id.length === 0 ||
915
+ record?.data?.id !== record.id) {
916
+ return new Response(JSON.stringify({ error: "invalid_sync_batch_key" }), {
917
+ status: 400, headers: { "content-type": "application/json" },
918
+ });
919
+ }
920
+ const key = JSON.stringify([record.table, record.id]);
921
+ if (offeredKeys.has(key)) {
922
+ return new Response(JSON.stringify({ error: "duplicate_sync_batch_key" }), {
923
+ status: 400, headers: { "content-type": "application/json" },
924
+ });
925
+ }
926
+ offeredKeys.add(key);
927
+ }
543
928
  const startTime = Date.now();
544
929
  let merged = 0;
545
930
  let skipped = 0;
546
931
  const skippedReasons = {};
932
+ const refused = [];
933
+ const indeterminate = [];
547
934
  const mergeErrors = [];
548
- function recordSkip(reason) {
935
+ function recordSkip(reason, record) {
549
936
  skipped++;
550
937
  skippedReasons[reason] = (skippedReasons[reason] ?? 0) + 1;
938
+ refused.push({ table: record.table, id: record.id, reason });
551
939
  }
552
940
  // Table name → Harper database table mapping.
553
941
  // Typed against FEDERATION_TABLE_POLICY so adding a federated table
@@ -573,13 +961,82 @@ export class FederationSync extends Resource {
573
961
  // trust delegation to the originator's send-time check) alongside adding
574
962
  // Message to the push list — do not inherit this as a silent gap.
575
963
  Message: databases.flair.Message,
964
+ // flair#2578 slice 1: Presence is REGISTERED so the receive path can carry
965
+ // it (the receiver writes it through the write-back helper). The sender
966
+ // ships in a later slice — this is the RECEIVE side only.
967
+ Presence: databases.flair.Presence,
576
968
  };
577
969
  const knownTables = new Set(Object.keys(tableMap));
578
- for (const record of records) {
970
+ /** Read the local Agent row for an id, or null when there is none.
971
+ * Read failures throw: before write-back starts they become retryable
972
+ * `merge_error`; after it starts they are indeterminate. */
973
+ const readAgentRow = async (agentId) => {
974
+ const row = await databases.flair.Agent.get(agentId);
975
+ return row ?? null;
976
+ };
977
+ // ── flair#2578 slice 1: Presence receipt (P1, P4, P5) ──
978
+ // The batch-verified sender (`sender`) is the home authority. Write-back
979
+ // rechecks the home fresh and reads the Presence row in its owned transaction.
980
+ const mergePresence = async (record, sender, local, table, markWriteStarted) => {
981
+ const receivedAt = Date.now();
982
+ // P5: strip to the declared Presence fields and validate. The wire record
983
+ // id IS the primary key (agentId).
984
+ const validated = validatePresenceReceipt(record.id, record.data, receivedAt, sender);
985
+ if (!validated.ok)
986
+ return { reason: validated.reason };
987
+ const agentId = validated.row.agentId;
988
+ // P1: the Agent row must be homed on the batch-verified sender.
989
+ const homeReason = presenceHomeBindingReason(await readAgentRow(agentId), sender);
990
+ if (homeReason)
991
+ return { reason: homeReason };
992
+ // P4: Presence-specific merge (heartbeat, then activity stamp).
993
+ const planned = mergePresenceReceipt(local, validated.row, receivedAt);
994
+ if (planned.action === "skip")
995
+ return { reason: planned.reason };
996
+ // Same failure path as the generic merge: the started flag is set BEFORE
997
+ // the write, so a post-write exception is INDETERMINATE (not retryable),
998
+ // and a changed row is the SAME named conflict the generic merge reports.
999
+ let outcome;
1000
+ markWriteStarted();
1001
+ try {
1002
+ outcome = await writeBackCommittedRow(table, record.id, async (row) => {
1003
+ // Fresh home recheck during write-back; `row` is the transaction-scoped
1004
+ // Presence read.
1005
+ const currentHome = presenceHomeBindingReason(await readAgentRow(agentId), sender);
1006
+ if (currentHome)
1007
+ return { skip: true, reason: currentHome };
1008
+ const current = mergePresenceReceipt(row, validated.row, receivedAt);
1009
+ if (current.action === "skip")
1010
+ return { skip: true, reason: current.reason };
1011
+ return { write: current.row };
1012
+ }, {
1013
+ label: "FederationSync",
1014
+ expectedRow: local,
1015
+ attempts: 1,
1016
+ wholeRow: true,
1017
+ pausePre: () => txnPausePoint("presence-merge-pre"),
1018
+ pausePoint: () => txnPausePoint("presence-merge"),
1019
+ });
1020
+ }
1021
+ catch (err) {
1022
+ // The helper's named refusal for a row that changed: the owned
1023
+ // transaction aborted, so nothing was written — refuse the key, not
1024
+ // indeterminate. Matches the generic merge's handler below.
1025
+ if (err instanceof WriteBackConflictError) {
1026
+ return { reason: "merge_target_changed" };
1027
+ }
1028
+ throw err;
1029
+ }
1030
+ if ("skip" in outcome) {
1031
+ return { reason: outcome.reason ?? "presence_invalid_shape" };
1032
+ }
1033
+ return { merged: true };
1034
+ };
1035
+ const mergeOne = async (record) => {
1036
+ let writeBackStarted = false;
579
1037
  try {
580
1038
  if (payloadIdMismatch(record)) {
581
- recordSkip("id_mismatch");
582
- continue;
1039
+ return { reason: "id_mismatch" };
583
1040
  }
584
1041
  const table = (record.table in tableMap)
585
1042
  ? tableMap[record.table]
@@ -587,8 +1044,12 @@ export class FederationSync extends Resource {
587
1044
  const local = table ? await table.get(record.id) : null;
588
1045
  const decision = classifyRecord(record, peer.role, instanceId, local, knownTables);
589
1046
  if (decision.action === "skip") {
590
- recordSkip(decision.reason);
591
- continue;
1047
+ return { reason: decision.reason };
1048
+ }
1049
+ // With the flag OFF, an eligible Presence record reaching receipt skips
1050
+ // as presence_receive_disabled; earlier key/classifier refusals answer first.
1051
+ if (record.table === "Presence" && !presenceReceiveEnabled()) {
1052
+ return { reason: "presence_receive_disabled" };
592
1053
  }
593
1054
  // ── Per-record signature verification (federation-edge-hardening slice 3b) ──
594
1055
  // classifyRecord's "merge" verdict above only proves the record is
@@ -614,8 +1075,7 @@ export class FederationSync extends Resource {
614
1075
  ? peer.publicKey
615
1076
  : (await databases.flair.Peer.get(originator))?.publicKey;
616
1077
  if (!originatorPublicKey) {
617
- recordSkip("unknown_originator_key");
618
- continue;
1078
+ return { reason: "unknown_originator_key" };
619
1079
  }
620
1080
  // CONTRACT — reconstruct from the record (v defaults to 1 when
621
1081
  // absent — v is NOT on the wire today). Must match
@@ -627,16 +1087,14 @@ export class FederationSync extends Resource {
627
1087
  // records. See flair#1416.
628
1088
  const signatureValid = verifyBodySignature(reconstructRecordVerifyBody(record, originator), originatorPublicKey);
629
1089
  if (!signatureValid) {
630
- recordSkip("invalid_signature");
631
- continue;
1090
+ return { reason: "invalid_signature" };
632
1091
  }
633
1092
  }
634
1093
  else if (requireRecordSignatures()) {
635
1094
  // require-mode: unsigned records are no longer trusted on
636
1095
  // batch-level auth alone. Default mode (verify-if-present) falls
637
1096
  // through here and merges — see requireRecordSignatures() above.
638
- recordSkip("missing_signature");
639
- continue;
1097
+ return { reason: "missing_signature" };
640
1098
  }
641
1099
  // ── Per-record principal entitlement (flair#1416 / slice 3a) ──
642
1100
  // After signature verification, before table.put. Scoped by the
@@ -648,10 +1106,30 @@ export class FederationSync extends Resource {
648
1106
  enforceV1Principal: requireRecordPrincipal(),
649
1107
  });
650
1108
  if (principalSkip) {
651
- recordSkip(principalSkip);
652
- continue;
1109
+ return { reason: principalSkip };
1110
+ }
1111
+ // ── flair#2578 slice 1: Presence receipt ──
1112
+ if (record.table === "Presence") {
1113
+ return await mergePresence(record, instanceId, local, table, () => { writeBackStarted = true; });
1114
+ }
1115
+ const incoming = { ...record.data };
1116
+ if (record.table === "Memory") {
1117
+ // Ephemeral peer expiry must be a valid UTC ISO date from the Unix
1118
+ // epoch through receiver time + 365 days. Missing expiry uses the receiver's
1119
+ // clock and configured TTL when the incoming row wins last-write-wins.
1120
+ // Malformed or out-of-bound ephemeral expiry skips the record before merging.
1121
+ const expiryError = stampEphemeralExpiry(incoming, local, { incoming: true });
1122
+ if (expiryError) {
1123
+ return { reason: "invalid_expiry" };
1124
+ }
1125
+ }
1126
+ const mergedData = mergeRecord(local, { ...record, data: incoming });
1127
+ // ── flair#2359: an inbound Agent row must satisfy the same agent-ID
1128
+ // rule as a locally-created one. This raw merge is the receiver's write
1129
+ // path, so a peer pushing a malformed id must not land a row here.
1130
+ if (record.table === "Agent" && !isValidAgentId(record.id)) {
1131
+ return { reason: AGENT_ID_ERROR };
653
1132
  }
654
- const mergedData = mergeRecord(local, record);
655
1133
  // ── flair#1940 A1'' item 8: the SAME declared-attribute whitelist the
656
1134
  // writers apply. A dirty pushed row (a legacy direct-insert, or a raw
657
1135
  // writer that slipped a pointer field past the writers) must not carry
@@ -667,32 +1145,20 @@ export class FederationSync extends Resource {
667
1145
  // would land an unscanned, possibly non-persistent skill — bypassing the
668
1146
  // gate. Skip it: skills are written locally via skill_store, never synced.
669
1147
  if (record.table === "Memory" && isSkillWrite(mergedData)) {
670
- recordSkip("skill_not_federated");
671
- continue;
1148
+ return { reason: "skill_not_federated" };
672
1149
  }
673
- // Absorbing-state guard for the Message table (flair#1521 §12 P0-3).
674
- // Generic newer-wins LWW would let a deadline-sweep `failed` (or any
675
- // other state) written on a peer overwrite a locally-CONSUMED message,
676
- // telling the sender "failed" about a message the recipient actually
677
- // consumed — the exact inversion Relay exists to kill. `consumed` is
678
- // absorbing: reconcileState pins it regardless of updatedAt. The guard
679
- // lives HERE, in the raw-put apply path, because sync-in bypasses the
680
- // Message resource's methods (Federation.ts uses table.put directly).
681
- if (record.table === "Message") {
682
- const reconciled = reconcileState(local?.state, mergedData.state);
683
- mergedData.state = reconciled;
684
- // P1-3 (flair#1521): reconcile the SATELLITE lifecycle fields too, not
685
- // just `state`. Generic LWW keeps the incoming (newer) record's
686
- // failureReason/consumedAt, so a locally-CONSUMED row could end up
687
- // `consumed` while carrying a remote `failureReason: "deadline"` — the
688
- // sender-visible "failed" about a message the recipient actually
689
- // consumed, the exact inversion the absorbing rule exists to kill. A
690
- // consumed row NEVER has a failureReason; keep the consumed row's own
691
- // consumedAt (local's when local was the consumer).
692
- if (reconciled === "consumed") {
693
- mergedData.failureReason = null;
694
- mergedData.consumedAt = local?.consumedAt ?? mergedData.consumedAt ?? null;
695
- }
1150
+ // flair#2141 S2: the merge skips a row on the seed's fixed id
1151
+ // (resources/seed-reservation.ts), whatever its tags.
1152
+ if (isReservedSeedId(record.table, record.id)) {
1153
+ return { reason: "seed_id_not_federated" };
1154
+ }
1155
+ // flair#2307: Harper's REST by-id path reads a trailing `.content` as a
1156
+ // property selector, and the Memory write paths refuse such an id, so a
1157
+ // federated Memory row whose id ends in `.content` is skipped, as the
1158
+ // seed reservation does just above. A legacy row with such an id that
1159
+ // already exists on the sending peer is therefore not federated.
1160
+ if (record.table === "Memory" && endsWithContentSelectorSuffix(mergedData.id)) {
1161
+ return { reason: "content_suffix_id_not_federated" };
696
1162
  }
697
1163
  mergedData._originatorInstanceId = decision.originator;
698
1164
  mergedData._syncedFrom = instanceId;
@@ -724,17 +1190,104 @@ export class FederationSync extends Resource {
724
1190
  ? local.instanceToken
725
1191
  : randomUUID();
726
1192
  }
727
- await table.put(mergedData);
728
- // embedding-space-guard slice 1: a federation-merged Memory can carry a
729
- // FOREIGN embeddingModel (LWW remote-win) — trip the guard's latch so
730
- // recall/dedup degrade instead of cosining a foreign vector. See
731
- // noteFederationMergedMemory's doc.
732
- noteFederationMergedMemory(record.table, mergedData);
733
- merged++;
1193
+ // flair#2441 / flair#2450 / flair#2475: every synced table uses the
1194
+ // write-back helper (one attempt, no retry). The plan reads the
1195
+ // in-transaction row. The Agent status guard can skip as
1196
+ // agent_status_not_federated before row comparison. For planned writes,
1197
+ // every table compares the WHOLE stored row against `local` (the row the
1198
+ // merge read and built from): a change to any field committed between that
1199
+ // read and the helper's in-transaction read skips the record as
1200
+ // merge_target_changed. The committed row is checked again before commit.
1201
+ // A change committed after that final read is not seen: Harper has no
1202
+ // compare-and-set (write-back.ts).
1203
+ //
1204
+ // flair#2450 set `wholeRow` for Soul, Agent, Relationship and Message;
1205
+ // flair#2475 extends it to Memory: Memory's identity fields
1206
+ // (instanceToken, contentHash, createdAt, agentId) do not move on a
1207
+ // field-only update, and the merge writes the whole row, so an
1208
+ // identity-only check let it put back the changed field's pre-change
1209
+ // value.
1210
+ let outcome;
1211
+ writeBackStarted = true;
1212
+ try {
1213
+ outcome = await writeBackCommittedRow(table, record.id, (row) => {
1214
+ // flair#2108: an inbound Agent record whose `status` differs from
1215
+ // the in-transaction local principal's stored value is skipped WHOLE,
1216
+ // whether or not it would win the last-write-wins merge — the
1217
+ // federation path carries no verified administrator authority for
1218
+ // that principal (the batch is signed, and a record signature may
1219
+ // also be present; neither is an admin claim), so a second field
1220
+ // in the record does not land either.
1221
+ if (record.table === "Agent" && inboundChangesExistingPrincipalStatus(record, row)) {
1222
+ return { skip: true, reason: "agent_status_not_federated" };
1223
+ }
1224
+ // flair#2266: skip an inbound Agent record carrying a publicKey
1225
+ // different from stored `pending`, regardless of timestamps.
1226
+ if (record.table === "Agent" && inboundChangesExistingPendingKey(record, row)) {
1227
+ return { skip: true, reason: "agent_pending_key_not_federated" };
1228
+ }
1229
+ // Absorbing-state guard for the Message table (flair#1521 §12
1230
+ // P0-3). Generic newer-wins LWW would let a deadline-sweep `failed`
1231
+ // (or any other state) written on a peer overwrite a locally-
1232
+ // CONSUMED message, telling the sender "failed" about a message the
1233
+ // recipient actually consumed — the exact inversion Relay exists to
1234
+ // kill. `consumed` is absorbing: reconcileState pins it regardless
1235
+ // of updatedAt, against the in-transaction row's state. For consumed
1236
+ // state, clear failureReason and prefer the in-transaction row's
1237
+ // consumedAt when non-null.
1238
+ if (record.table === "Message") {
1239
+ const reconciled = reconcileState(row?.state, mergedData.state);
1240
+ mergedData.state = reconciled;
1241
+ if (reconciled === "consumed") {
1242
+ mergedData.failureReason = null;
1243
+ mergedData.consumedAt = row?.consumedAt ?? mergedData.consumedAt ?? null;
1244
+ }
1245
+ }
1246
+ if (record.table === "Memory")
1247
+ normalizeEmptyEmbedding(mergedData);
1248
+ return { write: mergedData };
1249
+ }, {
1250
+ label: "FederationSync",
1251
+ expectedRow: local,
1252
+ attempts: 1,
1253
+ // Planned writes compare the whole stored row, not just
1254
+ // sameStoredRow's identity fields: Memory's identity fields do not
1255
+ // move on a field-only update (flair#2475), and the other tables'
1256
+ // identity fields do not move on one either (flair#2450 — see
1257
+ // above).
1258
+ wholeRow: true,
1259
+ pausePre: () => txnPausePoint("federation-merge-pre"),
1260
+ pausePoint: () => txnPausePoint("federation-merge"),
1261
+ });
1262
+ }
1263
+ catch (err) {
1264
+ // A merge refusal returned by the write path itself: the helper
1265
+ // names a changed row with WriteBackConflictError only after its
1266
+ // owned transaction aborted, whether the change was seen at the
1267
+ // in-transaction comparison or at the committed-row confirmation
1268
+ // after staging. Nothing was written, so the key is refused, not
1269
+ // indeterminate.
1270
+ if (err instanceof WriteBackConflictError) {
1271
+ return { reason: "merge_target_changed" };
1272
+ }
1273
+ throw err;
1274
+ }
1275
+ // Each skip above carries its OWN name on the plan's `reason`; the
1276
+ // fallback is the status rule's name for any future skip that does not.
1277
+ // (Every skip this plan returns names a reason today.)
1278
+ if ("skip" in outcome) {
1279
+ return { reason: outcome.reason ?? "agent_status_not_federated" };
1280
+ }
1281
+ try {
1282
+ noteFederationMergedMemory(record.table, mergedData, local ?? null);
1283
+ }
1284
+ catch (err) {
1285
+ console.warn(`[Federation] post-commit note failed for ${record.table}/${record.id}: ${String(err)}`);
1286
+ }
1287
+ return { merged: true };
734
1288
  }
735
1289
  catch (err) {
736
1290
  const msg = err instanceof Error ? err.message : String(err);
737
- recordSkip("merge_error");
738
1291
  // Cap the captured-error list so a hostile/buggy peer can't blow up
739
1292
  // the SyncLog row, but ALWAYS log to console so operators don't lose
740
1293
  // the per-record signal — the silent-swallow is the bug we're fixing.
@@ -742,7 +1295,27 @@ export class FederationSync extends Resource {
742
1295
  mergeErrors.push(`${record.table}/${record.id}: ${msg}`);
743
1296
  }
744
1297
  console.warn(`[Federation] merge error for ${record.table}/${record.id} from ${instanceId}: ${msg}`);
1298
+ return writeBackStarted ? { indeterminate: true } : { reason: "merge_error" };
745
1299
  }
1300
+ };
1301
+ for (const record of records) {
1302
+ let timer;
1303
+ const deadline = new Promise((resolve) => {
1304
+ timer = setTimeout(() => resolve({ indeterminate: true }), RECORD_MERGE_DEADLINE_MS);
1305
+ });
1306
+ let outcome;
1307
+ try {
1308
+ outcome = await Promise.race([mergeOne(record), deadline]);
1309
+ }
1310
+ finally {
1311
+ clearTimeout(timer);
1312
+ }
1313
+ if ("reason" in outcome)
1314
+ recordSkip(outcome.reason, record);
1315
+ else if ("merged" in outcome)
1316
+ merged++;
1317
+ else
1318
+ indeterminate.push({ table: record.table, id: record.id });
746
1319
  }
747
1320
  // Peer cursor update — distinguish liveness from progress:
748
1321
  // lastSyncAt → "we heard from this peer just now" (always update)
@@ -778,7 +1351,7 @@ export class FederationSync extends Resource {
778
1351
  const errorSummary = errorParts.length > 0 ? errorParts.join(" | ") : undefined;
779
1352
  const status = mergeErrors.length > 0
780
1353
  ? "partial"
781
- : skipped > 0 ? "partial" : "success";
1354
+ : skipped > 0 || indeterminate.length > 0 ? "partial" : "success";
782
1355
  await databases.flair.SyncLog.put({
783
1356
  id: `sync_${Date.now()}_${randomBytes(4).toString("hex")}`,
784
1357
  peerId: instanceId,
@@ -797,6 +1370,8 @@ export class FederationSync extends Resource {
797
1370
  merged,
798
1371
  skipped,
799
1372
  skippedReasons,
1373
+ refused,
1374
+ indeterminate,
800
1375
  total: records.length,
801
1376
  durationMs: Date.now() - startTime,
802
1377
  };
@@ -835,6 +1410,51 @@ export class FederationPeers extends Resource {
835
1410
  return { peers };
836
1411
  }
837
1412
  }
1413
+ /**
1414
+ * GET /FederationRetries — the rows of the sender's FederationRetry table
1415
+ * (flair#2455), admin view, split into `pending`, `terminal` and `malformed`.
1416
+ * No production sender path creates rows yet (a later slice activates the
1417
+ * sender); rows an admin writes are readable now.
1418
+ *
1419
+ * A row that breaks a sender convention (retryRowProblem: an id that is not its
1420
+ * tuple's key, an unknown state, reason or outcome) is listed under
1421
+ * `malformed` with the problem's name, and never as pending or terminal.
1422
+ *
1423
+ * allowRead()=allowAdmin, the same gate as FederationPeers above. Read-only:
1424
+ * it never writes a row, and a read failure propagates instead of being
1425
+ * reported as an empty set. `flair federation status` renders it.
1426
+ */
1427
+ export class FederationRetries extends Resource {
1428
+ async allowRead() {
1429
+ return allowAdmin(this.getContext?.());
1430
+ }
1431
+ async get() {
1432
+ const pending = [];
1433
+ const terminal = [];
1434
+ const malformed = [];
1435
+ for await (const r of databases.flair.FederationRetry.search()) {
1436
+ const problem = retryRowProblem(r);
1437
+ if (problem) {
1438
+ malformed.push({ key: r.id, peerId: r.peerId, table: r.table, id: r.recordId, state: r.state, problem });
1439
+ continue;
1440
+ }
1441
+ const row = {
1442
+ peerId: r.peerId,
1443
+ table: r.table,
1444
+ id: r.recordId,
1445
+ reason: r.lastReason,
1446
+ attempts: r.attempts,
1447
+ bound: r.bound,
1448
+ resolution: r.resolution,
1449
+ state: r.state,
1450
+ firstRefusedAt: r.firstRefusedAt,
1451
+ completedAt: r.completedAt,
1452
+ };
1453
+ (r.state === "pending" ? pending : terminal).push(row);
1454
+ }
1455
+ return { pending, terminal, malformed };
1456
+ }
1457
+ }
838
1458
  // ── Module initialisation ────────────────────────────────────────────────────
839
1459
  // Deferred: the cleanup sweep (PR-5) starts after the module graph resolves.
840
1460
  // In unit test environments (no Harper runtime), setTimeout never fires