@tpsdev-ai/flair 0.62.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 (232) hide show
  1. package/README.md +6 -6
  2. package/SECURITY.md +18 -10
  3. package/config.yaml +11 -11
  4. package/dist/bridges/runtime/execute.js +1 -0
  5. package/dist/bridges/types.js +1 -0
  6. package/dist/build-info.json +3 -3
  7. package/dist/cli.js +66 -122
  8. package/dist/commands/agent.js +27 -65
  9. package/dist/commands/backup-approval.js +218 -0
  10. package/dist/commands/backup.js +37 -33
  11. package/dist/commands/bootstrap.js +3 -1
  12. package/dist/commands/deploy.js +37 -7
  13. package/dist/commands/doctor.js +119 -0
  14. package/dist/commands/export.js +3 -4
  15. package/dist/commands/federation.js +653 -68
  16. package/dist/commands/grant.js +5 -6
  17. package/dist/commands/help.js +25 -0
  18. package/dist/commands/idp.js +14 -19
  19. package/dist/commands/import.js +131 -19
  20. package/dist/commands/init.js +7 -7
  21. package/dist/commands/integrity.js +5 -6
  22. package/dist/commands/mcp.js +11 -17
  23. package/dist/commands/memory.js +33 -15
  24. package/dist/commands/orgevent.js +5 -10
  25. package/dist/commands/principal.js +13 -25
  26. package/dist/commands/quality.js +3 -0
  27. package/dist/commands/rem.js +484 -65
  28. package/dist/commands/restore.js +352 -44
  29. package/dist/commands/service.js +84 -2
  30. package/dist/commands/soul.js +0 -6
  31. package/dist/commands/status.js +51 -33
  32. package/dist/commands/test.js +4 -1
  33. package/dist/commands/upgrade.js +53 -22
  34. package/dist/commands/workspace.js +7 -8
  35. package/dist/deploy.js +59 -3
  36. package/dist/doctor-client.js +7 -2
  37. package/dist/fabric-upgrade.js +12 -2
  38. package/dist/federation/presence-send.js +139 -0
  39. package/dist/federation-verify.js +269 -177
  40. package/dist/install/clients.js +171 -35
  41. package/dist/lib/agent-id-rule.js +44 -2
  42. package/dist/lib/atomic-write.js +1 -1
  43. package/dist/lib/auth-resolve.js +1028 -52
  44. package/dist/lib/backup-approval-store.js +612 -0
  45. package/dist/lib/backup-artifact.js +343 -0
  46. package/dist/lib/config-critical-section.js +212 -25
  47. package/dist/lib/connect-phase.js +33 -0
  48. package/dist/lib/daemon-liveness.js +2 -1
  49. package/dist/lib/federation-pair-access.js +4 -0
  50. package/dist/lib/federation-retry-queue.js +283 -0
  51. package/dist/lib/federation-retry-row.js +101 -0
  52. package/dist/lib/instruction-event-contract.js +17 -0
  53. package/dist/lib/instruction-event-doctor.js +102 -0
  54. package/dist/lib/launchd-management.js +14 -3
  55. package/dist/lib/mcp-enable.js +14 -15
  56. package/dist/lib/memory-attributes.js +2 -0
  57. package/dist/lib/memory-provider-timeout.js +33 -0
  58. package/dist/lib/mqtt-config.js +132 -0
  59. package/dist/lib/mqtt-listener-doctor.js +104 -0
  60. package/dist/lib/open-live-row.js +20 -0
  61. package/dist/lib/ops-url.js +52 -0
  62. package/dist/lib/promotion-content-hash.js +20 -0
  63. package/dist/lib/restore-archive.js +760 -0
  64. package/dist/lib/restore-verify.js +1 -1
  65. package/dist/lib/skill-assignment-preflight.js +159 -0
  66. package/dist/lib/skill-seed.js +91 -8
  67. package/dist/lib/skill-tombstone-doctor.js +133 -0
  68. package/dist/lib/soul-scope-fields.js +26 -0
  69. package/dist/lib/uninstall-purge.js +266 -11
  70. package/dist/lib/upgrade-prior-liveness.js +2 -1
  71. package/dist/mcp-client-assertion.js +2 -10
  72. package/dist/memory-id-checkpoint.js +28 -7
  73. package/dist/mqtt-off-deploy.js +550 -0
  74. package/dist/rem/promote-policy.js +3 -3
  75. package/dist/rem/restore.js +302 -26
  76. package/dist/rem/runner.js +220 -58
  77. package/dist/rem/scheduler.js +21 -4
  78. package/dist/resources/A2AAdapter.js +131 -178
  79. package/dist/resources/AdminMemory.js +2 -0
  80. package/dist/resources/AdminMemoryCandidates.js +116 -0
  81. package/dist/resources/Agent.js +155 -45
  82. package/dist/resources/AgentCard.js +4 -0
  83. package/dist/resources/AgentKeyRegister.js +56 -22
  84. package/dist/resources/AgentReadPosition.js +7 -0
  85. package/dist/resources/AgentSeed.js +232 -107
  86. package/dist/resources/AutoPromoteCandidates.js +413 -84
  87. package/dist/resources/Credential.js +6 -8
  88. package/dist/resources/Federation.js +219 -57
  89. package/dist/resources/FederationRetry.js +4 -4
  90. package/dist/resources/InstructionVersion.js +1 -1
  91. package/dist/resources/MCPClientMetadata.js +6 -3
  92. package/dist/resources/Memory.js +1303 -270
  93. package/dist/resources/MemoryArchive.js +149 -64
  94. package/dist/resources/MemoryBootstrap.js +12 -22
  95. package/dist/resources/MemoryCandidate.js +16 -2
  96. package/dist/resources/MemoryConsolidate.js +2 -2
  97. package/dist/resources/MemoryFeed.js +360 -147
  98. package/dist/resources/MemoryMaintenance.js +290 -72
  99. package/dist/resources/MemoryPurge.js +138 -22
  100. package/dist/resources/MemoryReflect.js +68 -14
  101. package/dist/resources/MemoryReindex.js +91 -13
  102. package/dist/resources/Message.js +11 -2
  103. package/dist/resources/OAuth.js +156 -39
  104. package/dist/resources/OAuthClient.js +1 -1
  105. package/dist/resources/OrgEvent.js +292 -29
  106. package/dist/resources/OrgEventCatchup.js +7 -0
  107. package/dist/resources/OrgEventMaintenance.js +48 -10
  108. package/dist/resources/PairingToken.js +1 -1
  109. package/dist/resources/Presence.js +31 -11
  110. package/dist/resources/PromoteMemoryCandidate.js +8 -2
  111. package/dist/resources/RecordUsage.js +2 -4
  112. package/dist/resources/Soul.js +2 -0
  113. package/dist/resources/SoulFeed.js +2 -1
  114. package/dist/resources/WorkspaceLatest.js +4 -0
  115. package/dist/resources/XAA.js +36 -10
  116. package/dist/resources/a2a-stream.js +313 -0
  117. package/dist/resources/a2a-url.js +4 -5
  118. package/dist/resources/agent-admin.js +10 -1
  119. package/dist/resources/agent-auth.js +98 -68
  120. package/dist/resources/agent-read-position-lib.js +4 -1
  121. package/dist/resources/agent-status-guard.js +9 -7
  122. package/dist/resources/auth-middleware.js +166 -42
  123. package/dist/resources/authority-field-guard.js +9 -11
  124. package/dist/resources/auto-promote-lib.js +8 -5
  125. package/dist/resources/basic-auth-header.js +21 -0
  126. package/dist/resources/bm25-index-service.js +4 -5
  127. package/dist/resources/dedup-cluster.js +6 -1
  128. package/dist/resources/embeddings-provider.js +25 -0
  129. package/dist/resources/federation-classify.js +89 -0
  130. package/dist/resources/federation-retry-lib.js +6 -81
  131. package/dist/resources/health.js +43 -4
  132. package/dist/resources/host-pointer/registry.js +29 -0
  133. package/dist/resources/host-pointer-adapter.js +1 -0
  134. package/dist/resources/in-process.js +24 -22
  135. package/dist/resources/instruction-version-record.js +251 -7
  136. package/dist/resources/internal-authority.js +13 -0
  137. package/dist/resources/mcp-handler.js +106 -12
  138. package/dist/resources/mcp-oauth-flag.js +12 -14
  139. package/dist/resources/mcp-oauth.js +430 -53
  140. package/dist/resources/mcp-tools.js +60 -22
  141. package/dist/resources/memory-declared-attributes.js +1 -0
  142. package/dist/resources/memory-embed-hash.js +56 -0
  143. package/dist/resources/memory-host-source.js +5 -2
  144. package/dist/resources/memory-reflect-lib.js +1 -1
  145. package/dist/resources/memory-write-lock.js +202 -23
  146. package/dist/resources/memory-write-response.js +1 -1
  147. package/dist/resources/memory-write-transaction.js +243 -0
  148. package/dist/resources/migration-boot.js +17 -12
  149. package/dist/resources/migrations/boot-progress.js +25 -0
  150. package/dist/resources/migrations/data-dir.js +16 -3
  151. package/dist/resources/migrations/dir-safety.js +60 -2
  152. package/dist/resources/migrations/embedding-stamp.js +315 -49
  153. package/dist/resources/migrations/graph-heal.js +9 -2
  154. package/dist/resources/migrations/ledger.js +5 -2
  155. package/dist/resources/migrations/lock.js +867 -80
  156. package/dist/resources/migrations/progress.js +71 -10
  157. package/dist/resources/migrations/runner.js +212 -18
  158. package/dist/resources/migrations/state.js +36 -1
  159. package/dist/resources/migrations/status.js +2 -13
  160. package/dist/resources/migrations/synthetic-test-migration.js +78 -12
  161. package/dist/resources/migrations/types.js +26 -1
  162. package/dist/resources/migrations/visibility-backfill.js +111 -70
  163. package/dist/resources/oauth-discovery.js +0 -5
  164. package/dist/resources/object-body-guard.js +12 -5
  165. package/dist/resources/org-event-reserved.js +92 -0
  166. package/dist/resources/org-event-write-fault.js +19 -0
  167. package/dist/resources/owner-field-guard.js +1 -1
  168. package/dist/resources/owner-scoped-write-policy.js +65 -21
  169. package/dist/resources/owner-scoped-writes.js +37 -6
  170. package/dist/resources/path-id-rewrite.js +76 -0
  171. package/dist/resources/presence-internal.js +5 -5
  172. package/dist/resources/promotion-binding.js +43 -0
  173. package/dist/resources/promotion-stamp.js +124 -33
  174. package/dist/resources/protocol-context.js +189 -0
  175. package/dist/resources/record-type-kit.js +2 -4
  176. package/dist/resources/request-target.js +28 -1
  177. package/dist/resources/request-transaction.js +11 -1
  178. package/dist/resources/seed-reservation.js +1 -2
  179. package/dist/resources/semantic-retrieval-core.js +7 -6
  180. package/dist/resources/server-row-validation.js +71 -0
  181. package/dist/resources/skill-manifest.js +4 -3
  182. package/dist/resources/skill-version-write.js +384 -27
  183. package/dist/resources/skill-write-fault.js +6 -3
  184. package/dist/resources/skill-write-policy.js +2 -1
  185. package/dist/resources/soul-write-policy.js +26 -7
  186. package/dist/resources/table-helpers.js +1 -1
  187. package/dist/resources/table-subscription-policy.js +518 -85
  188. package/dist/resources/table-subscriptions.js +20 -7
  189. package/dist/resources/txn-pause-point.js +122 -5
  190. package/dist/resources/usage-recording.js +54 -46
  191. package/dist/resources/write-back.js +176 -11
  192. package/dist/resources/write-journal-context.js +5 -0
  193. package/dist/resources/write-journal.js +289 -0
  194. package/dist/src/lib/agent-id-rule.js +44 -2
  195. package/dist/src/lib/atomic-write.js +1 -1
  196. package/dist/src/lib/federation-retry-row.js +101 -0
  197. package/dist/src/lib/instruction-event-contract.js +17 -0
  198. package/dist/src/lib/memory-attributes.js +2 -0
  199. package/dist/src/lib/open-live-row.js +20 -0
  200. package/dist/src/lib/soul-scope-fields.js +26 -0
  201. package/dist/src/rem/promote-policy.js +3 -3
  202. package/dist/src/rem/scheduler.js +21 -4
  203. package/docs/access-control.md +18 -9
  204. package/docs/api-reference.md +126 -28
  205. package/docs/auth.md +40 -18
  206. package/docs/claude-code.md +3 -3
  207. package/docs/deploying-on-fabric.md +108 -0
  208. package/docs/deployment.md +17 -0
  209. package/docs/embedding-in-a-harper-app.md +16 -14
  210. package/docs/entity-vocabulary.md +3 -6
  211. package/docs/federation.md +29 -2
  212. package/docs/integrations.md +11 -11
  213. package/docs/mcp-clients.md +7 -5
  214. package/docs/notes/mcp-agent-auth-consumer.md +4 -9
  215. package/docs/notes/mcp-oauth-model2.md +6 -6
  216. package/docs/openclaw.md +1 -1
  217. package/docs/quickstart-fabric.md +2 -2
  218. package/docs/quickstart.md +3 -3
  219. package/docs/releasing.md +13 -13
  220. package/docs/rem.md +24 -3
  221. package/docs/secrets-and-keys.md +2 -2
  222. package/docs/standalone-local.md +29 -2
  223. package/docs/supply-chain-policy.md +28 -20
  224. package/docs/the-team.md +2 -2
  225. package/docs/upgrade.md +14 -0
  226. package/package.json +18 -11
  227. package/schemas/agent.graphql +3 -3
  228. package/schemas/federation.graphql +10 -7
  229. package/schemas/memory.graphql +7 -2
  230. package/templates/bin/flair-rem-nightly.sh.tmpl +7 -1
  231. package/templates/launchd/start-flair-with-admin-pass.sh +188 -10
  232. package/dist/resources/soul-adk-guard.js +0 -68
@@ -3,6 +3,7 @@ import { Resource, databases, server } from "harper";
3
3
  import { randomBytes, randomUUID } from "node:crypto";
4
4
  import nacl from "tweetnacl";
5
5
  import { allowAdmin } from "./agent-auth.js";
6
+ import { configuredAdminAgentIds } from "./agent-admin.js";
6
7
  import { canonicalize, signBody, verifyBodySignature, signBodyFresh, verifyBodySignatureFresh, generateNonce, } from "./federation-crypto.js";
7
8
  import { reconcileState } from "./relay-lib.js";
8
9
  import { decideInstanceAnswer, INSTANCE_ROW_PRUNE_REMEDY, multipleInstanceRowsMessage, } from "../src/lib/instance-identity-row.js";
@@ -18,12 +19,14 @@ import { stripInboundMemoryRow, stripServerStampedFields } from "./memory-declar
18
19
  import { noteWriteStamp } from "./embedding-space-guard.js";
19
20
  import { initFederationCleanup } from "./federation-cleanup.js";
20
21
  import { verifyFederationRequestBody } from "./replay-store.js";
21
- import { CommittedRowChanged, confirmCommittedRow, writeBackCommittedRow, WriteBackConflictError } from "./write-back.js";
22
+ import { CommittedRowChanged, confirmCommittedRow, verifyCommittedFields, withoutHarperManagedFields, writeBackCommittedRow, WriteBackConflictError } from "./write-back.js";
22
23
  import { withKeyLock } from "./key-lock.js";
23
24
  import { withOwnedTransaction } from "./request-transaction.js";
24
- import { txnPausePoint } from "./txn-pause-point.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";
25
28
  import { retryRowProblem } from "./federation-retry-lib.js";
26
- import { classifyRecord, reconstructRecordVerifyBody, checkPrincipalEntitlement, inboundChangesExistingPrincipalStatus, inboundChangesExistingPendingKey, } from "./federation-classify.js";
29
+ import { classifyRecord, reconstructRecordVerifyBody, checkPrincipalEntitlement, inboundChangesExistingPrincipalStatus, inboundChangesExistingPendingKey, agentAdminIdCreateRefusal, agentIdentityRefusal, keepReceiverAgentAuthority, } from "./federation-classify.js";
27
30
  import { mergePresenceReceipt, presenceHomeBindingReason, presenceReceiveEnabled, validatePresenceReceipt, } from "./presence-receipt.js";
28
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";
29
32
  // Federation anti-replay: FederationPair and FederationSync both verify through
@@ -488,12 +491,15 @@ export class FederationPair extends Resource {
488
491
  if (tokenRepairPause)
489
492
  await tokenRepairPause;
490
493
  let refusal;
491
- let pairedAsFirst = false;
494
+ let stagedFirstPeer;
495
+ let stagedPeer;
496
+ let stagedToken;
492
497
  try {
493
498
  refusal = await withPairingTokenClaim(pairingToken, () => withOwnedTransaction(ctx, async (owned) => {
494
499
  const claim = await consumePairingToken(pairingToken, instanceId, owned);
495
500
  if (claim.kind !== "consumed")
496
501
  return claim;
502
+ stagedToken = claim;
497
503
  // The Peer re-read sees a change committed before the owned
498
504
  // transaction's first read (its token read); a change committed
499
505
  // after that read is not covered by this re-read. A pinned key that
@@ -509,9 +515,14 @@ export class FederationPair extends Resource {
509
515
  // the valid token just consumed makes it a first-time pair. Write the
510
516
  // row the first-pair path writes, built from the verified request —
511
517
  // no field of the deleted row survives.
512
- pairedAsFirst = !current;
518
+ if (!current)
519
+ stagedFirstPeer = { ...firstPairPeerRow(instanceId, publicKey, role, endpoint), pairAttemptWriteId: claim.pairAttemptWriteId };
513
520
  try {
514
- await writePeerRow(owned, current ? rePairedRow(current) : firstPairPeerRow(instanceId, publicKey, role, endpoint));
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);
515
526
  }
516
527
  catch (err) {
517
528
  // Rethrow so the owned transaction ABORTS: the consume rolls back
@@ -519,10 +530,21 @@ export class FederationPair extends Resource {
519
530
  // caller answers a named refusal, not a bare 500.
520
531
  throw new PeerWriteFailedError(err);
521
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;
522
542
  return claim;
523
543
  }));
524
544
  }
525
545
  catch (err) {
546
+ if (err instanceof CommittedRowChanged)
547
+ return firstPairRowAppearedRefusal();
526
548
  if (err instanceof PeerWriteFailedError) {
527
549
  const cause = err.cause;
528
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). ` +
@@ -541,8 +563,15 @@ export class FederationPair extends Resource {
541
563
  }
542
564
  if (refusal)
543
565
  return refusal;
544
- // Paired as a first-time pair: attempt bootstrap-user cleanup.
545
- if (pairedAsFirst)
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)
546
575
  await dropPairBootstrapUser(pairingToken, ctx);
547
576
  }
548
577
  // The NO-token re-pair's peer write: the token path wrote the row inside the
@@ -562,6 +591,7 @@ export class FederationPair extends Resource {
562
591
  await repairPause;
563
592
  if (!pairingToken) {
564
593
  const ctx = this.getContext?.() ?? {};
594
+ let stagedPeer;
565
595
  const refusal = await withOwnedTransaction(ctx, async (owned) => {
566
596
  const current = await databases.flair.Peer.get(instanceId, owned);
567
597
  if (!current)
@@ -570,11 +600,27 @@ export class FederationPair extends Resource {
570
600
  return publicKeyMismatchRefusal();
571
601
  if (current.status === "revoked")
572
602
  return peerRevokedRefusal();
573
- await writePeerRow(owned, rePairedRow(current));
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;
574
613
  return undefined;
575
614
  });
576
615
  if (refusal)
577
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();
578
624
  }
579
625
  }
580
626
  else {
@@ -610,27 +656,17 @@ export class FederationPair extends Resource {
610
656
  if (firstPairPause)
611
657
  await firstPairPause;
612
658
  let refusal;
659
+ let stagedFirstPeer;
660
+ let stagedToken;
613
661
  try {
614
662
  refusal = await withPairingTokenClaim(pairingToken, () => withOwnedTransaction(ctx, async (owned) => {
615
663
  const claim = await consumePairingToken(pairingToken, instanceId, owned);
616
664
  if (claim.kind !== "consumed")
617
665
  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);
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);
634
670
  return claim;
635
671
  }));
636
672
  }
@@ -641,6 +677,11 @@ export class FederationPair extends Resource {
641
677
  }
642
678
  if (refusal)
643
679
  return refusal;
680
+ if (!stagedFirstPeer || !stagedToken)
681
+ return firstPairReadBackUnconfirmedRefusal();
682
+ const unconfirmed = await confirmTokenPairAfterCommit(pairingToken, stagedFirstPeer, stagedToken);
683
+ if (unconfirmed)
684
+ return unconfirmed;
644
685
  // Test-only: inert unless the fault-injection env opt-in is set and armed.
645
686
  // Pause AFTER the token lock released (and the consume is committed) but
646
687
  // BEFORE this request's own transaction commits (Harper commits it when the
@@ -702,6 +743,38 @@ function firstPairPeerRow(instanceId, publicKey, role, endpoint) {
702
743
  updatedAt: at,
703
744
  };
704
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
+ }
705
778
  /**
706
779
  * Drop the bootstrap user that was created alongside this pairing token, after a
707
780
  * first-time pair consumed it. Failure here is logged and non-fatal.
@@ -724,7 +797,7 @@ function peerRevokedRefusal() {
724
797
  }
725
798
  /**
726
799
  * 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
800
+ * the instance although its earlier read returned none. The owned
728
801
  * transaction aborted: this request wrote no Peer row and did not consume the
729
802
  * pairing token.
730
803
  * Signature verification recorded the request's replay nonce before pairing
@@ -733,9 +806,32 @@ function peerRevokedRefusal() {
733
806
  function firstPairRowAppearedRefusal() {
734
807
  return new Response(JSON.stringify({
735
808
  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",
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",
737
811
  }), { status: 409, headers: { "content-type": "application/json" } });
738
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
+ }
739
835
  /**
740
836
  * Tag a token-supplying re-pair's Peer.put rejection inside the owned transaction
741
837
  * callback (flair#2333), so it aborts before the caller returns peer_write_failed.
@@ -862,13 +958,19 @@ async function consumePairingToken(pairingToken, consumerInstanceId, ctx) {
862
958
  return { kind: "bootstrap_mismatch" };
863
959
  }
864
960
  }
865
- // Consume the token
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();
866
967
  await databases.flair.PairingToken.put({
867
968
  ...tokenRecord,
868
969
  consumedBy: consumerInstanceId,
869
- consumedAt: new Date().toISOString(),
970
+ consumedAt,
971
+ pairAttemptWriteId,
870
972
  }, ctx);
871
- return { kind: "consumed" };
973
+ return { kind: "consumed", consumedBy: consumerInstanceId, consumedAt, pairAttemptWriteId };
872
974
  }
873
975
  const RECORD_MERGE_DEADLINE_MS = 5_000;
874
976
  /**
@@ -967,6 +1069,8 @@ export class FederationSync extends Resource {
967
1069
  Presence: databases.flair.Presence,
968
1070
  };
969
1071
  const knownTables = new Set(Object.keys(tableMap));
1072
+ /** The per-id Memory write lock store (flair#2478 slice 3c). */
1073
+ const memoryLockStore = () => databases?.flair?.Memory?.primaryStore;
970
1074
  /** Read the local Agent row for an id, or null when there is none.
971
1075
  * Read failures throw: before write-back starts they become retryable
972
1076
  * `merge_error`; after it starts they are indeterminate. */
@@ -993,9 +1097,8 @@ export class FederationSync extends Resource {
993
1097
  const planned = mergePresenceReceipt(local, validated.row, receivedAt);
994
1098
  if (planned.action === "skip")
995
1099
  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.
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.
999
1102
  let outcome;
1000
1103
  markWriteStarted();
1001
1104
  try {
@@ -1008,7 +1111,7 @@ export class FederationSync extends Resource {
1008
1111
  const current = mergePresenceReceipt(row, validated.row, receivedAt);
1009
1112
  if (current.action === "skip")
1010
1113
  return { skip: true, reason: current.reason };
1011
- return { write: current.row };
1114
+ return { idempotent: true, write: current.row };
1012
1115
  }, {
1013
1116
  label: "FederationSync",
1014
1117
  expectedRow: local,
@@ -1019,11 +1122,8 @@ export class FederationSync extends Resource {
1019
1122
  });
1020
1123
  }
1021
1124
  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
1125
  if (err instanceof WriteBackConflictError) {
1026
- return { reason: "merge_target_changed" };
1126
+ return err.outcome === "conflict" ? { reason: "merge_target_changed" } : { indeterminate: true };
1027
1127
  }
1028
1128
  throw err;
1029
1129
  }
@@ -1198,19 +1298,19 @@ export class FederationSync extends Resource {
1198
1298
  // merge read and built from): a change to any field committed between that
1199
1299
  // read and the helper's in-transaction read skips the record as
1200
1300
  // 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
1301
  //
1204
1302
  // flair#2450 set `wholeRow` for Soul, Agent, Relationship and Message;
1205
1303
  // flair#2475 extends it to Memory: Memory's identity fields
1206
1304
  // (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.
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.
1210
1310
  let outcome;
1211
1311
  writeBackStarted = true;
1212
1312
  try {
1213
- outcome = await writeBackCommittedRow(table, record.id, (row) => {
1313
+ const writeMerge = async () => await writeBackCommittedRow(table, record.id, (row) => {
1214
1314
  // flair#2108: an inbound Agent record whose `status` differs from
1215
1315
  // the in-transaction local principal's stored value is skipped WHOLE,
1216
1316
  // whether or not it would win the last-write-wins merge — the
@@ -1226,6 +1326,20 @@ export class FederationSync extends Resource {
1226
1326
  if (record.table === "Agent" && inboundChangesExistingPendingKey(record, row)) {
1227
1327
  return { skip: true, reason: "agent_pending_key_not_federated" };
1228
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
+ }
1229
1343
  // Absorbing-state guard for the Message table (flair#1521 §12
1230
1344
  // P0-3). Generic newer-wins LWW would let a deadline-sweep `failed`
1231
1345
  // (or any other state) written on a peer overwrite a locally-
@@ -1243,9 +1357,31 @@ export class FederationSync extends Resource {
1243
1357
  mergedData.consumedAt = row?.consumedAt ?? mergedData.consumedAt ?? null;
1244
1358
  }
1245
1359
  }
1246
- if (record.table === "Memory")
1360
+ if (record.table === "Memory") {
1247
1361
  normalizeEmptyEmbedding(mergedData);
1248
- return { write: 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 };
1249
1385
  }, {
1250
1386
  label: "FederationSync",
1251
1387
  expectedRow: local,
@@ -1258,17 +1394,31 @@ export class FederationSync extends Resource {
1258
1394
  wholeRow: true,
1259
1395
  pausePre: () => txnPausePoint("federation-merge-pre"),
1260
1396
  pausePoint: () => txnPausePoint("federation-merge"),
1397
+ pauseAfterStage: () => txnPausePoint("federation-merge-staged"),
1398
+ pauseBeforeCommit: () => txnPausePoint("federation-merge-commit"),
1261
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
+ }
1262
1418
  }
1263
1419
  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
1420
  if (err instanceof WriteBackConflictError) {
1271
- return { reason: "merge_target_changed" };
1421
+ return err.outcome === "conflict" ? { reason: "merge_target_changed" } : { indeterminate: true };
1272
1422
  }
1273
1423
  throw err;
1274
1424
  }
@@ -1336,8 +1486,13 @@ export class FederationSync extends Resource {
1336
1486
  }
1337
1487
  await databases.flair.Peer.put(peerUpdate);
1338
1488
  // Log sync operation with skip-reason breakdown so the partial state
1339
- // 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;
1340
1493
  try {
1494
+ if (txnFault("federation-synclog"))
1495
+ throw new Error("injected SyncLog write failure");
1341
1496
  const errorParts = [];
1342
1497
  if (Object.keys(skippedReasons).length > 0) {
1343
1498
  errorParts.push("skipped: " +
@@ -1364,8 +1519,11 @@ export class FederationSync extends Resource {
1364
1519
  durationMs: Date.now() - startTime,
1365
1520
  createdAt: nowIso,
1366
1521
  });
1522
+ syncLogWritten = true;
1523
+ }
1524
+ catch (err) {
1525
+ console.warn(`[Federation] SyncLog write failed for ${instanceId}: ${String(err)}`);
1367
1526
  }
1368
- catch { /* non-fatal */ }
1369
1527
  return {
1370
1528
  merged,
1371
1529
  skipped,
@@ -1374,6 +1532,7 @@ export class FederationSync extends Resource {
1374
1532
  indeterminate,
1375
1533
  total: records.length,
1376
1534
  durationMs: Date.now() - startTime,
1535
+ syncLogWritten,
1377
1536
  };
1378
1537
  }
1379
1538
  }
@@ -1401,6 +1560,7 @@ export class FederationPeers extends Resource {
1401
1560
  endpoint: p.endpoint,
1402
1561
  lastSyncAt: p.lastSyncAt,
1403
1562
  lastMergeAt: p.lastMergeAt,
1563
+ presenceLastSyncAt: p.presenceLastSyncAt,
1404
1564
  relayOnly: p.relayOnly,
1405
1565
  pairedAt: p.pairedAt,
1406
1566
  });
@@ -1413,8 +1573,10 @@ export class FederationPeers extends Resource {
1413
1573
  /**
1414
1574
  * GET /FederationRetries — the rows of the sender's FederationRetry table
1415
1575
  * (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.
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.
1418
1580
  *
1419
1581
  * A row that breaks a sender convention (retryRowProblem: an id that is not its
1420
1582
  * tuple's key, an unknown state, reason or outcome) is listed under
@@ -4,8 +4,8 @@
4
4
  *
5
5
  * The table is shaped for one row per (peerId, table, recordId) the receiver
6
6
  * refused for a reason a later re-offer could clear, plus locally observed
7
- * unconfirmed sends. No production sender path creates rows yet (a later slice
8
- * activates the sender); rows an admin writes are readable now. See
7
+ * unconfirmed sends. The sync sender writes these rows; an admin can also
8
+ * write them directly. See
9
9
  * resources/federation-retry-lib.ts for the key/state/outcome vocabulary and
10
10
  * schemas/federation.graphql for the table.
11
11
  *
@@ -21,8 +21,8 @@
21
21
  * FederationSync's receive `tableMap` (resources/Federation.ts), so no inbound
22
22
  * sync record can write the table, even though receive `allowCreate` is public
23
23
  * (a record that passes the receiver's earlier payload-id check skips as
24
- * `unknown_table`). It is also not a sending table. Nothing in
25
- * this slice sends a retry; the sender is activated in a later slice.
24
+ * `unknown_table`). It is also not a sending table: the sync sender reads and
25
+ * writes retry rows through its local operations endpoint.
26
26
  *
27
27
  * ACCESS (design rev 2.1). Admin-only on read, create,
28
28
  * update AND delete — the FederationPeers/Peer pattern (resources/Peer.ts,
@@ -29,7 +29,7 @@ import { makeAuthGate, makeScopedSearch, NOT_FOUND, UNAUTH } from "./record-type
29
29
  import { SKILL_SUBJECT_TYPE, readHead, skillRefReadable, subjectTypeReadable } from "./instruction-version-record.js";
30
30
  const MUTATION_DENIED = () => new Response(JSON.stringify({
31
31
  error: "instruction_version_immutable",
32
- message: "InstructionVersion is append-only within the application; REST writes are refused",
32
+ message: "InstructionVersion: resource REST clients cannot write or delete version records; the server appends them, and when a request's close fails it attempts to remove the version that request appended only while that version is still the head, reporting a compensation failure when the removal cannot be confirmed",
33
33
  }), { status: 403, headers: { "Content-Type": "application/json" } });
34
34
  // See makeAuthGate's doc (record-type-kit.ts): must be a genuine prototype
35
35
  // method, never a class-field assignment — Harper's relationship-traversal
@@ -1,6 +1,6 @@
1
1
  import { Resource, databases } from "harper";
2
- import { mcpIssuer } from "./mcp-oauth-flag.js";
3
2
  import { agentPublicKeyToJwk, buildCimdDocument } from "./mcp-client-metadata-fields.js";
3
+ import { refuseRewrittenAgentId } from "./path-id-rewrite.js";
4
4
  /**
5
5
  * MCPClientMetadata — serves a Client ID Metadata Document (CIMD) for a
6
6
  * Flair agent at `GET /MCPClientMetadata/{agentId}`.
@@ -34,7 +34,7 @@ import { agentPublicKeyToJwk, buildCimdDocument } from "./mcp-client-metadata-fi
34
34
  *
35
35
  * Deployment coordination: the AS's `clientIdMetadataDocuments.allowedHosts`
36
36
  * config MUST include this route's host (derived from `FLAIR_MCP_ISSUER` /
37
- * `FLAIR_PUBLIC_URL`, same env vars as `mcpIssuer()` below) — merely being
37
+ * `FLAIR_PUBLIC_URL`) — merely being
38
38
  * reachable is not enough; the allowlist gate is AS-side config and
39
39
  * fail-closed. See docs/notes/mcp-agent-auth-consumer.md.
40
40
  */
@@ -49,7 +49,10 @@ export class MCPClientMetadata extends Resource {
49
49
  if (!agentId) {
50
50
  return new Response(JSON.stringify({ error: "agentId required in path: GET /MCPClientMetadata/{agentId}" }), { status: 400, headers: { "Content-Type": "application/json" } });
51
51
  }
52
- const issuer = mcpIssuer();
52
+ const rewritten = refuseRewrittenAgentId(this.getContext?.(), agentId);
53
+ if (rewritten)
54
+ return rewritten;
55
+ const issuer = (process.env.FLAIR_MCP_ISSUER ?? process.env.FLAIR_PUBLIC_URL ?? "").trim();
53
56
  if (!issuer) {
54
57
  // Fail closed rather than guess a client_id URL — CIMD requires the
55
58
  // document's client_id to equal the URL it was fetched from, byte for