@tpsdev-ai/flair 0.62.0 → 0.63.1

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 (257) hide show
  1. package/README.md +14 -13
  2. package/SECURITY.md +73 -43
  3. package/config.yaml +11 -11
  4. package/dist/bridges/runtime/execute.js +1 -0
  5. package/dist/bridges/runtime/import-runner.js +4 -0
  6. package/dist/bridges/types.js +1 -0
  7. package/dist/build-info.json +3 -3
  8. package/dist/cli.js +309 -205
  9. package/dist/commands/agent.js +325 -137
  10. package/dist/commands/attention.js +2 -0
  11. package/dist/commands/backup-approval.js +218 -0
  12. package/dist/commands/backup.js +37 -33
  13. package/dist/commands/bootstrap.js +5 -1
  14. package/dist/commands/bridge.js +10 -0
  15. package/dist/commands/deploy.js +37 -7
  16. package/dist/commands/doctor.js +206 -42
  17. package/dist/commands/export.js +144 -15
  18. package/dist/commands/federation.js +653 -68
  19. package/dist/commands/grant.js +5 -6
  20. package/dist/commands/help.js +25 -0
  21. package/dist/commands/idp.js +14 -19
  22. package/dist/commands/import.js +167 -34
  23. package/dist/commands/init.js +380 -164
  24. package/dist/commands/integrity.js +5 -6
  25. package/dist/commands/keys.js +12 -8
  26. package/dist/commands/mcp.js +157 -79
  27. package/dist/commands/memory.js +38 -17
  28. package/dist/commands/migrate-harness-memory.js +9 -3
  29. package/dist/commands/orgevent.js +5 -10
  30. package/dist/commands/principal.js +32 -39
  31. package/dist/commands/quality.js +26 -3
  32. package/dist/commands/reembed.js +468 -111
  33. package/dist/commands/rem.js +484 -65
  34. package/dist/commands/restore.js +352 -44
  35. package/dist/commands/search.js +2 -0
  36. package/dist/commands/service.js +109 -2
  37. package/dist/commands/soul.js +0 -6
  38. package/dist/commands/status.js +165 -124
  39. package/dist/commands/test.js +4 -1
  40. package/dist/commands/upgrade.js +53 -22
  41. package/dist/commands/workspace.js +7 -8
  42. package/dist/deploy.js +59 -3
  43. package/dist/doctor-client.js +9 -25
  44. package/dist/fabric-upgrade.js +12 -2
  45. package/dist/federation/presence-send.js +139 -0
  46. package/dist/federation/scheduler.js +148 -12
  47. package/dist/federation-verify.js +269 -177
  48. package/dist/install/clients.js +171 -35
  49. package/dist/keystore.js +77 -10
  50. package/dist/lib/agent-id-rule.js +44 -2
  51. package/dist/lib/agent-key-file.js +509 -0
  52. package/dist/lib/agent-rotation-lock.js +249 -0
  53. package/dist/lib/atomic-write.js +3 -3
  54. package/dist/lib/auth-resolve.js +1040 -64
  55. package/dist/lib/backup-approval-store.js +612 -0
  56. package/dist/lib/backup-artifact.js +343 -0
  57. package/dist/lib/config-critical-section.js +212 -25
  58. package/dist/lib/connect-phase.js +33 -0
  59. package/dist/lib/daemon-liveness.js +2 -1
  60. package/dist/lib/federation-pair-access.js +4 -0
  61. package/dist/lib/federation-retry-queue.js +283 -0
  62. package/dist/lib/federation-retry-row.js +101 -0
  63. package/dist/lib/instruction-event-contract.js +17 -0
  64. package/dist/lib/instruction-event-doctor.js +102 -0
  65. package/dist/lib/key-dir.js +203 -0
  66. package/dist/lib/launchd-management.js +21 -6
  67. package/dist/lib/local-instance-pair.js +8 -1
  68. package/dist/lib/mcp-enable.js +14 -15
  69. package/dist/lib/memory-attributes.js +2 -0
  70. package/dist/lib/memory-provider-timeout.js +33 -0
  71. package/dist/lib/mqtt-config.js +132 -0
  72. package/dist/lib/mqtt-listener-doctor.js +104 -0
  73. package/dist/lib/node-alias-path.js +50 -2
  74. package/dist/lib/open-live-row.js +20 -0
  75. package/dist/lib/ops-url.js +52 -0
  76. package/dist/lib/promotion-content-hash.js +20 -0
  77. package/dist/lib/remote-admin-pass.js +157 -0
  78. package/dist/lib/restore-archive.js +760 -0
  79. package/dist/lib/restore-verify.js +1 -1
  80. package/dist/lib/scheduler-platform.js +13 -0
  81. package/dist/lib/service-repoint.js +13 -4
  82. package/dist/lib/skill-assignment-preflight.js +159 -0
  83. package/dist/lib/skill-seed.js +125 -10
  84. package/dist/lib/skill-tombstone-doctor.js +133 -0
  85. package/dist/lib/soul-scope-fields.js +26 -0
  86. package/dist/lib/terminal-text.js +32 -0
  87. package/dist/lib/uninstall-purge.js +266 -11
  88. package/dist/lib/upgrade-prior-liveness.js +2 -1
  89. package/dist/mcp-client-assertion.js +7 -14
  90. package/dist/memory-id-checkpoint.js +28 -7
  91. package/dist/mqtt-off-deploy.js +550 -0
  92. package/dist/rem/promote-policy.js +3 -3
  93. package/dist/rem/restore.js +302 -26
  94. package/dist/rem/runner.js +220 -58
  95. package/dist/rem/scheduler.js +21 -4
  96. package/dist/resources/A2AAdapter.js +131 -178
  97. package/dist/resources/AdminMemory.js +2 -0
  98. package/dist/resources/AdminMemoryCandidates.js +116 -0
  99. package/dist/resources/Agent.js +155 -45
  100. package/dist/resources/AgentCard.js +4 -0
  101. package/dist/resources/AgentKeyRegister.js +56 -22
  102. package/dist/resources/AgentReadPosition.js +7 -0
  103. package/dist/resources/AgentSeed.js +232 -107
  104. package/dist/resources/AutoPromoteCandidates.js +413 -84
  105. package/dist/resources/Credential.js +6 -8
  106. package/dist/resources/Federation.js +219 -57
  107. package/dist/resources/FederationRetry.js +4 -4
  108. package/dist/resources/InstructionVersion.js +1 -1
  109. package/dist/resources/MCPClientMetadata.js +6 -3
  110. package/dist/resources/Memory.js +1348 -271
  111. package/dist/resources/MemoryArchive.js +149 -64
  112. package/dist/resources/MemoryBootstrap.js +12 -22
  113. package/dist/resources/MemoryCandidate.js +16 -2
  114. package/dist/resources/MemoryConsolidate.js +2 -2
  115. package/dist/resources/MemoryFeed.js +360 -147
  116. package/dist/resources/MemoryMaintenance.js +290 -72
  117. package/dist/resources/MemoryPurge.js +138 -22
  118. package/dist/resources/MemoryReflect.js +68 -14
  119. package/dist/resources/MemoryReindex.js +91 -13
  120. package/dist/resources/Message.js +11 -2
  121. package/dist/resources/OAuth.js +156 -39
  122. package/dist/resources/OAuthClient.js +1 -1
  123. package/dist/resources/OrgEvent.js +292 -29
  124. package/dist/resources/OrgEventCatchup.js +7 -0
  125. package/dist/resources/OrgEventMaintenance.js +48 -10
  126. package/dist/resources/PairingToken.js +1 -1
  127. package/dist/resources/Presence.js +31 -11
  128. package/dist/resources/PromoteMemoryCandidate.js +8 -2
  129. package/dist/resources/RecordUsage.js +2 -4
  130. package/dist/resources/Soul.js +2 -0
  131. package/dist/resources/SoulFeed.js +2 -1
  132. package/dist/resources/WorkspaceLatest.js +4 -0
  133. package/dist/resources/XAA.js +36 -10
  134. package/dist/resources/a2a-stream.js +313 -0
  135. package/dist/resources/a2a-url.js +4 -5
  136. package/dist/resources/agent-admin.js +10 -1
  137. package/dist/resources/agent-auth.js +98 -68
  138. package/dist/resources/agent-read-position-lib.js +4 -1
  139. package/dist/resources/agent-status-guard.js +9 -7
  140. package/dist/resources/auth-middleware.js +166 -42
  141. package/dist/resources/authority-field-guard.js +9 -11
  142. package/dist/resources/auto-promote-lib.js +8 -5
  143. package/dist/resources/basic-auth-header.js +21 -0
  144. package/dist/resources/bm25-index-service.js +4 -5
  145. package/dist/resources/dedup-cluster.js +6 -1
  146. package/dist/resources/embeddings-provider.js +25 -0
  147. package/dist/resources/federation-classify.js +89 -0
  148. package/dist/resources/federation-retry-lib.js +6 -81
  149. package/dist/resources/health.js +75 -19
  150. package/dist/resources/host-pointer/registry.js +29 -0
  151. package/dist/resources/host-pointer-adapter.js +1 -0
  152. package/dist/resources/in-process-api.js +74 -11
  153. package/dist/resources/in-process.js +24 -22
  154. package/dist/resources/instruction-version-record.js +251 -7
  155. package/dist/resources/internal-authority.js +13 -0
  156. package/dist/resources/mcp-client-metadata-fields.js +4 -0
  157. package/dist/resources/mcp-handler.js +146 -13
  158. package/dist/resources/mcp-oauth-flag.js +12 -14
  159. package/dist/resources/mcp-oauth.js +446 -53
  160. package/dist/resources/mcp-tool-scopes.js +69 -0
  161. package/dist/resources/mcp-tools.js +70 -22
  162. package/dist/resources/memory-declared-attributes.js +1 -0
  163. package/dist/resources/memory-embed-hash.js +56 -0
  164. package/dist/resources/memory-host-source.js +5 -2
  165. package/dist/resources/memory-reflect-lib.js +1 -1
  166. package/dist/resources/memory-write-lock.js +202 -23
  167. package/dist/resources/memory-write-response.js +1 -1
  168. package/dist/resources/memory-write-transaction.js +243 -0
  169. package/dist/resources/migration-boot.js +17 -12
  170. package/dist/resources/migrations/boot-progress.js +25 -0
  171. package/dist/resources/migrations/data-dir.js +16 -3
  172. package/dist/resources/migrations/dir-safety.js +60 -2
  173. package/dist/resources/migrations/embedding-stamp.js +315 -49
  174. package/dist/resources/migrations/graph-heal.js +9 -2
  175. package/dist/resources/migrations/ledger.js +5 -2
  176. package/dist/resources/migrations/lock.js +867 -80
  177. package/dist/resources/migrations/progress.js +71 -10
  178. package/dist/resources/migrations/runner.js +212 -18
  179. package/dist/resources/migrations/state.js +36 -1
  180. package/dist/resources/migrations/status.js +2 -13
  181. package/dist/resources/migrations/synthetic-test-migration.js +78 -12
  182. package/dist/resources/migrations/types.js +26 -1
  183. package/dist/resources/migrations/visibility-backfill.js +111 -70
  184. package/dist/resources/oauth-discovery.js +0 -5
  185. package/dist/resources/object-body-guard.js +12 -5
  186. package/dist/resources/org-event-reserved.js +92 -0
  187. package/dist/resources/org-event-write-fault.js +19 -0
  188. package/dist/resources/owner-field-guard.js +1 -1
  189. package/dist/resources/owner-scoped-write-policy.js +65 -21
  190. package/dist/resources/owner-scoped-writes.js +37 -6
  191. package/dist/resources/path-id-rewrite.js +76 -0
  192. package/dist/resources/presence-internal.js +5 -5
  193. package/dist/resources/promotion-binding.js +43 -0
  194. package/dist/resources/promotion-stamp.js +124 -33
  195. package/dist/resources/protocol-context.js +189 -0
  196. package/dist/resources/record-type-kit.js +2 -4
  197. package/dist/resources/request-target.js +28 -1
  198. package/dist/resources/request-transaction.js +11 -1
  199. package/dist/resources/seed-reservation.js +1 -2
  200. package/dist/resources/semantic-retrieval-core.js +7 -6
  201. package/dist/resources/server-row-validation.js +71 -0
  202. package/dist/resources/skill-manifest.js +4 -3
  203. package/dist/resources/skill-version-write.js +400 -27
  204. package/dist/resources/skill-write-fault.js +6 -3
  205. package/dist/resources/skill-write-policy.js +2 -1
  206. package/dist/resources/soul-write-policy.js +26 -7
  207. package/dist/resources/table-helpers.js +1 -1
  208. package/dist/resources/table-subscription-policy.js +518 -85
  209. package/dist/resources/table-subscriptions.js +20 -7
  210. package/dist/resources/txn-pause-point.js +122 -5
  211. package/dist/resources/usage-recording.js +54 -46
  212. package/dist/resources/write-back.js +176 -11
  213. package/dist/resources/write-journal-context.js +5 -0
  214. package/dist/resources/write-journal.js +289 -0
  215. package/dist/src/keystore.js +77 -10
  216. package/dist/src/lib/agent-id-rule.js +44 -2
  217. package/dist/src/lib/atomic-write.js +3 -3
  218. package/dist/src/lib/federation-retry-row.js +101 -0
  219. package/dist/src/lib/instruction-event-contract.js +17 -0
  220. package/dist/src/lib/key-dir.js +203 -0
  221. package/dist/src/lib/memory-attributes.js +2 -0
  222. package/dist/src/lib/open-live-row.js +20 -0
  223. package/dist/src/lib/scheduler-platform.js +13 -0
  224. package/dist/src/lib/soul-scope-fields.js +26 -0
  225. package/dist/src/rem/promote-policy.js +3 -3
  226. package/dist/src/rem/scheduler.js +21 -4
  227. package/docs/access-control.md +39 -21
  228. package/docs/api-reference.md +161 -52
  229. package/docs/auth.md +69 -38
  230. package/docs/claude-code.md +3 -3
  231. package/docs/deploying-on-fabric.md +118 -2
  232. package/docs/deployment.md +17 -0
  233. package/docs/embedding-in-a-harper-app.md +23 -21
  234. package/docs/entity-vocabulary.md +7 -11
  235. package/docs/federation.md +29 -2
  236. package/docs/hosted-on-fabric.md +1 -1
  237. package/docs/integrations.md +11 -11
  238. package/docs/mcp-clients.md +7 -5
  239. package/docs/notes/mcp-agent-auth-consumer.md +4 -9
  240. package/docs/notes/mcp-oauth-model2.md +6 -6
  241. package/docs/openclaw.md +1 -1
  242. package/docs/quickstart-fabric.md +2 -2
  243. package/docs/quickstart.md +3 -3
  244. package/docs/releasing.md +13 -13
  245. package/docs/rem.md +24 -3
  246. package/docs/secrets-and-keys.md +9 -14
  247. package/docs/standalone-local.md +29 -2
  248. package/docs/supply-chain-policy.md +28 -20
  249. package/docs/the-team.md +2 -2
  250. package/docs/upgrade.md +29 -5
  251. package/package.json +18 -11
  252. package/schemas/agent.graphql +3 -3
  253. package/schemas/federation.graphql +10 -7
  254. package/schemas/memory.graphql +7 -2
  255. package/templates/bin/flair-rem-nightly.sh.tmpl +7 -1
  256. package/templates/launchd/start-flair-with-admin-pass.sh +188 -10
  257. package/dist/resources/soul-adk-guard.js +0 -68
@@ -24,9 +24,12 @@ import { runFederationVerify } from "../federation-verify.js";
24
24
  import { resolveHubPeerIdentity } from "../lib/federation-pair-identity.js";
25
25
  import { redactTokenMessage } from "../lib/redact-token-id.js";
26
26
  import { rewriteFederationPairHubAccessError, rewriteFederationPairLocalAccessError, } from "../lib/federation-pair-access.js";
27
- import { defaultAdminPassPath, isLocalBase, resolveAdminPassFromSources, resolveAdminUser, ADMIN_PASS_FILE_FLAG, ADMIN_PASS_FILE_HELP, ADMIN_PASS_HELP, } from "../lib/auth-resolve.js";
27
+ import { ApiHttpError, apiErrorRawBody, defaultAdminPassPath, isLocalBase, resolveAdminUser, addAdminPassOptions, applyAdminPassFile, ApiRequestOutcomeUnknown, } from "../lib/auth-resolve.js";
28
28
  import { DEFAULT_INTERVAL_SECONDS as FEDERATION_SYNC_DEFAULT_INTERVAL } from "../federation/scheduler.js";
29
29
  import { FEDERATION_MEMORY_SELECT } from "../lib/federation-memory-attributes.js";
30
+ import { retryEntryKey } from "../lib/federation-retry-row.js";
31
+ import { MEMORY_RETRY_REASONS, dueRetryRows, retryOfferProblem, retryRowConfirmation, retryRowForAttempt, retryRowForRefusal, retryRowMalformedness, terminalRetryRow, } from "../lib/federation-retry-queue.js";
32
+ import { presenceCursorMs, presenceSendEnabled, presenceWatermarkMs, presenceWireRecord, PRESENCE_SEND_FUTURE_ALLOWANCE_MS, PRESENCE_SEND_OVERLAP_MS, PRESENCE_SEND_RECEIVE_DISABLED_SKIP_REASON, PRESENCE_SEND_RETRYABLE_SKIP_REASONS, selectPresenceRowsToSend, } from "../federation/presence-send.js";
30
33
  import { decideInstancePrune, formatInstanceRow, INSTANCE_ROW_PRUNE_REMEDY, prunePeerWarningLines, readInstanceRows, pruneInstanceRows, writeConfirmed, } from "../lib/instance-identity-row.js";
31
34
  let cli;
32
35
  /** Bind shared CLI helpers. cli.ts calls this immediately before register(program). */
@@ -48,36 +51,20 @@ function resolveEffectiveOpsUrl(opts) {
48
51
  function resolveOpsPort(opts) {
49
52
  return cli.resolveOpsPort(opts);
50
53
  }
51
- function applyAdminPassFile(opts) {
52
- cli.applyAdminPassFile(opts);
53
- }
54
54
  /** `federation token` / `federation pair` credential flags (flair#1873).
55
55
  * The flag/help strings live in auth-resolve.ts next to the resolver, shared
56
56
  * with every sibling command's credential options (flair#1910). */
57
57
  /**
58
- * Resolve `federation token`/`pair`'s admin password through the SAME reader
59
- * `flair backup` uses (`readAdminPassFileSecure`), with the precedence the
60
- * usage text states: an explicit `--admin-pass-file` or `--admin-pass` over
61
- * `FLAIR_ADMIN_PASS`; combining the file and the flag is a usage error. The resolved value is written back to
62
- * `opts.adminPass`, the slot the ops preflight and `loadInstanceSecretKey`
63
- * read — mirroring `applyAdminPassFile` for the sibling commands. Never prints
64
- * the value.
58
+ * `federation token`/`pair`'s admin password: an explicit `--admin-pass-file`
59
+ * or `--admin-pass` was already applied to `opts.adminPass` by
60
+ * addAdminPassOptions' preAction hook (which also refuses both at once); the
61
+ * environment is the fallback. Never prints the value.
65
62
  */
66
63
  function resolveFederationAdminPass(opts, envPass) {
67
- try {
68
- const pass = resolveAdminPassFromSources({
69
- adminPassFile: opts.adminPassFile,
70
- adminPass: opts.adminPass,
71
- envPass,
72
- });
73
- if (pass)
74
- opts.adminPass = pass;
75
- return pass;
76
- }
77
- catch (err) {
78
- console.error(`Error: ${err.message}`);
79
- process.exit(1);
80
- }
64
+ const pass = opts.adminPass ?? envPass ?? "";
65
+ if (pass)
66
+ opts.adminPass = pass;
67
+ return pass;
81
68
  }
82
69
  function addSharedCredentialOptions(cmd) {
83
70
  return cli.addSharedCredentialOptions(cmd);
@@ -88,6 +75,25 @@ function addSharedIdentityOption(cmd) {
88
75
  function shouldShowInlineSecretWarning(optValue, fromEnv, secretFlagNames, flagName) {
89
76
  return cli.shouldShowInlineSecretWarning(optValue, fromEnv, secretFlagNames, flagName);
90
77
  }
78
+ /**
79
+ * Apply the admin-password pair inherited by `federation sync status` and
80
+ * `federation sync disable`. The parent (`flair federation sync`) declares the
81
+ * pair, so commander stores the values there.
82
+ * Resolve an explicitly supplied pair before the action body runs and store the
83
+ * password on the leaf, where `status` reads it for its request. `enable`
84
+ * stores the path only and does not call this.
85
+ */
86
+ function applyInheritedAdminPass(actionCommand) {
87
+ const inherited = actionCommand.parent?.opts();
88
+ if (!inherited)
89
+ return;
90
+ if (inherited.adminPass === undefined && inherited.adminPassFile === undefined)
91
+ return;
92
+ const opts = { adminPass: inherited.adminPass, adminPassFile: inherited.adminPassFile };
93
+ applyAdminPassFile(opts);
94
+ actionCommand.setOptionValue("adminPass", opts.adminPass);
95
+ actionCommand.setOptionValue("adminPassFile", opts.adminPassFile);
96
+ }
91
97
  // Federation crypto helpers — inlined to avoid cross-boundary imports from
92
98
  // src/ into resources/, which don't survive npm packaging (see also
93
99
  // resources/federation-crypto.ts; the two must stay in sync).
@@ -389,6 +395,48 @@ export async function persistLocalPeerLastSyncAt(args) {
389
395
  }
390
396
  return { ok: true, status: updateRes.status };
391
397
  }
398
+ /**
399
+ * Attempt the Presence watermark update after contact. Presence has no `updatedAt`, so
400
+ * the row cursor over `lastHeartbeatAt` / `activityUpdatedAt` is compared against
401
+ * this field instead of `lastSyncAt`.
402
+ *
403
+ * Same shape and same result contract as {@link persistLocalPeerLastSyncAt}: a
404
+ * field-only `update` carrying `{id, presenceLastSyncAt, updatedAt}`, so it
405
+ * cannot revert `publicKey`/`status` or re-create a deleted row, and HTTP 200 is
406
+ * not success — the id must appear in `update_hashes`; otherwise the update is
407
+ * unconfirmed (a committed update with an unreadable response also reads as
408
+ * unconfirmed), unless Harper explicitly reports a miss.
409
+ * Callers invoke it only after contact — a confirmed batch, or a successful
410
+ * liveness ping on a no-change pass.
411
+ */
412
+ export async function persistLocalPeerPresenceSyncAt(args) {
413
+ const headers = { "Content-Type": "application/json", Authorization: args.auth };
414
+ const updateRes = await fetch(`${args.opsEndpoint}/`, {
415
+ method: "POST",
416
+ headers,
417
+ body: JSON.stringify({
418
+ operation: "update",
419
+ database: "flair",
420
+ table: "Peer",
421
+ records: [{ id: args.peerId, presenceLastSyncAt: args.presenceLastSyncAt, updatedAt: args.presenceLastSyncAt }],
422
+ }),
423
+ signal: AbortSignal.timeout(10_000),
424
+ });
425
+ if (!updateRes.ok) {
426
+ const txt = await updateRes.text().catch(() => "");
427
+ return { ok: false, status: updateRes.status, error: txt.slice(0, 200) };
428
+ }
429
+ const parsed = (await updateRes.json().catch(() => null));
430
+ const matched = !!parsed && Array.isArray(parsed.update_hashes) && parsed.update_hashes.includes(args.peerId);
431
+ if (!matched) {
432
+ return {
433
+ ok: false,
434
+ status: updateRes.status,
435
+ error: `Presence watermark update for Peer ${args.peerId} was not confirmed.`,
436
+ };
437
+ }
438
+ return { ok: true, status: updateRes.status };
439
+ }
392
440
  /**
393
441
  * The most recent CONTACT with any peer (max of peer.lastSyncAt), or null.
394
442
  *
@@ -405,7 +453,14 @@ async function latestPeerContact(opts) {
405
453
  try {
406
454
  const target = resolveTarget(opts);
407
455
  const baseUrl = target ? target.replace(/\/$/, "") : undefined;
408
- const { peers } = await api("GET", "/FederationPeers", undefined, baseUrl ? { baseUrl } : undefined);
456
+ const requestOptions = {};
457
+ if (baseUrl)
458
+ requestOptions.baseUrl = baseUrl;
459
+ if (opts.adminPass)
460
+ requestOptions.explicitAdminPass = opts.adminPass;
461
+ if (opts.adminUser)
462
+ requestOptions.adminUser = opts.adminUser;
463
+ const { peers } = await api("GET", "/FederationPeers", undefined, Object.keys(requestOptions).length ? requestOptions : undefined);
409
464
  let best = null;
410
465
  for (const p of peers ?? []) {
411
466
  if (!p?.lastSyncAt)
@@ -457,6 +512,11 @@ export function describeFederationStatusFetchFailed(url, setting) {
457
512
  * `TypeError: fetch failed`, Bun's `Unable to connect…`, or a cause
458
513
  * carrying a connect/DNS errno. Auth and HTTP errors stay out. */
459
514
  export function isFederationStatusConnectFailure(err) {
515
+ // Every ApiHttpError is excluded: the ones sendJsonRequest raises are built
516
+ // only after a response arrived, so that connection did not fail, whatever
517
+ // the body says (flair#2764).
518
+ if (err instanceof ApiHttpError)
519
+ return false;
460
520
  const msg = err instanceof Error ? err.message : String(err);
461
521
  if (/\bfetch failed\b/i.test(msg))
462
522
  return true;
@@ -494,11 +554,11 @@ export function isFederationStatusAuthFailure(err) {
494
554
  if (status === 401 || status === 403)
495
555
  return true;
496
556
  }
497
- const m = err instanceof Error
557
+ const m = apiErrorRawBody(err) || (err instanceof Error
498
558
  ? err.message
499
559
  : String(typeof err === "object" && err && "message" in err
500
560
  ? err.message ?? err
501
- : err);
561
+ : err));
502
562
  return m.includes("missing_or_invalid_authorization") || /(?:^|\D)401(?:\D|$)/.test(m);
503
563
  }
504
564
  /**
@@ -514,11 +574,11 @@ export function isFederationStatusAuthRemedy(err) {
514
574
  if (typeof err === "object" && "status" in err && err.status === 401) {
515
575
  return true;
516
576
  }
517
- const m = err instanceof Error
577
+ const m = apiErrorRawBody(err) || (err instanceof Error
518
578
  ? err.message
519
579
  : String(typeof err === "object" && err && "message" in err
520
580
  ? err.message ?? err
521
- : err);
581
+ : err));
522
582
  return m.includes("missing_or_invalid_authorization") || /(?:^|\D)401(?:\D|$)/.test(m);
523
583
  }
524
584
  /** Parse a JSON triple file for --token-from.
@@ -583,18 +643,77 @@ export function parseTokenFromFile(filePath) {
583
643
  * sender's success log and the watch loop's line, so each must be an integer
584
644
  * from 0 to the number of records in the batch it answers; anything else
585
645
  * (text, a fraction, a negative, a count larger than the batch, a missing
586
- * field) makes the whole response invalid. The caller reports that in local
587
- * text, never the received value.
646
+ * field) makes the whole response invalid. Their sum must also be at most the
647
+ * batch size: a receiver cannot report more outcomes than records it was
648
+ * offered. The bound is "at most", not "equal", because older receivers send
649
+ * counts without refusal lists and indeterminate rows fall in neither count.
650
+ * The caller reports a rejection in local text, never a received value that is
651
+ * not an in-range count.
588
652
  */
589
653
  export function parseSyncBatchCounts(body, batchSize) {
590
654
  if (body === null || typeof body !== "object" || Array.isArray(body))
591
655
  return null;
592
- const isCount = (v) => typeof v === "number" && Number.isSafeInteger(v) && v >= 0 && v <= batchSize;
593
656
  const { merged, skipped } = body;
594
- if (!isCount(merged) || !isCount(skipped))
657
+ if (!isSyncBatchCount(merged, batchSize) || !isSyncBatchCount(skipped, batchSize))
658
+ return null;
659
+ if (merged + skipped > batchSize)
595
660
  return null;
596
661
  return { merged, skipped };
597
662
  }
663
+ function isSyncBatchCount(v, batchSize) {
664
+ return typeof v === "number" && Number.isSafeInteger(v) && v >= 0 && v <= batchSize;
665
+ }
666
+ /** Local text naming why a batch response's counts were rejected: the table
667
+ * and, when both counts are in range individually, their values. Other
668
+ * receiver-authored values stay out of the message. */
669
+ export function describeSyncBatchCountsRejection(body, batchSize, table) {
670
+ const counts = body !== null && typeof body === "object" && !Array.isArray(body)
671
+ ? body
672
+ : {};
673
+ if (isSyncBatchCount(counts.merged, batchSize) && isSyncBatchCount(counts.skipped, batchSize)) {
674
+ return `${table}: merged ${counts.merged} + skipped ${counts.skipped} exceeds ${batchSize} records offered`;
675
+ }
676
+ return `${table}: merged/skipped are not counts from 0 to ${batchSize}`;
677
+ }
678
+ /** One receiver-authored refusal from a FederationSync batch: which record the
679
+ * receiver refused and under which name. Only well-formed entries are kept; a
680
+ * refused field that is absent or not an array of {table,id,reason} strings is
681
+ * ignored (the sender acts on a retryable name, never on a shape it invented). */
682
+ export function parseSyncBatchRefused(body) {
683
+ if (body === null || typeof body !== "object" || Array.isArray(body))
684
+ return [];
685
+ const refused = body.refused;
686
+ if (!Array.isArray(refused))
687
+ return [];
688
+ const out = [];
689
+ for (const entry of refused) {
690
+ if (entry === null || typeof entry !== "object")
691
+ continue;
692
+ const { table, id, reason } = entry;
693
+ if (typeof table !== "string" || typeof id !== "string" || typeof reason !== "string")
694
+ continue;
695
+ out.push({ table, id, reason });
696
+ }
697
+ return out;
698
+ }
699
+ /** Keep well-formed indeterminate entries from a FederationSync batch. */
700
+ export function parseSyncBatchIndeterminate(body) {
701
+ if (body === null || typeof body !== "object" || Array.isArray(body))
702
+ return [];
703
+ const indeterminate = body.indeterminate;
704
+ if (!Array.isArray(indeterminate))
705
+ return [];
706
+ const out = [];
707
+ for (const entry of indeterminate) {
708
+ if (entry === null || typeof entry !== "object")
709
+ continue;
710
+ const { table, id } = entry;
711
+ if (typeof table !== "string" || typeof id !== "string")
712
+ continue;
713
+ out.push({ table, id });
714
+ }
715
+ return out;
716
+ }
598
717
  export async function runFederationSyncOnce(opts) {
599
718
  const target = resolveTarget(opts);
600
719
  const baseUrl = target ? target.replace(/\/$/, "") : undefined;
@@ -630,6 +749,222 @@ export async function runFederationSyncOnce(opts) {
630
749
  const auth = `Basic ${Buffer.from(`${resolveAdminUser(opts.adminUser)}:${adminPass}`).toString("base64")}`;
631
750
  const tables = ["Memory", "Soul", "Agent", "Relationship"];
632
751
  const instance = await api("GET", "/FederationInstance", undefined, apiOpts);
752
+ // ── federation retry bookkeeping (flair#2797) ─────────────────────────
753
+ // An eligible generic Memory row the hub refused for a retryable reason is
754
+ // kept in FederationRetry and offered again on a later cycle while its
755
+ // pending row is valid, its backoff is due and the source row is still
756
+ // eligible, independent of the since cursor. A source the cursor selects
757
+ // that also has a pending row gets the same treatment: a valid row's
758
+ // attempt is reserved before the send and the outcome updates or resolves
759
+ // it; a malformed row is reported and left as stored. A non-retryable
760
+ // refusal ends the obligation; the retry path in one sender run does not
761
+ // select a terminal row again, and concurrent sender runs for one peer are
762
+ // not serialized (a separate issue).
763
+ const retryHeaders = { "Content-Type": "application/json", Authorization: auth };
764
+ // One projection for every Memory read: the cursor query and the retry
765
+ // re-read must not differ in what a row exposes to the signed batch.
766
+ const memorySelect = [...FEDERATION_MEMORY_SELECT];
767
+ const pendingRetries = new Map();
768
+ /** Pending rows whose attempt this run reserved before sending. */
769
+ const reservedOffers = new Set();
770
+ /** Pending retry rows to reserve when their batch is reached. */
771
+ const reservationTargets = new Map();
772
+ /** Retry row ids already reported malformed in this run. */
773
+ const reportedMalformedRetries = new Set();
774
+ function reportMalformedRetryRow(id, malformed) {
775
+ if (reportedMalformedRetries.has(id))
776
+ return;
777
+ reportedMalformedRetries.add(id);
778
+ console.warn(`⚠️ FederationRetry row ${id} is malformed (${malformed.problem}: ${malformed.field}); left as stored.`);
779
+ }
780
+ async function loadPendingRetries() {
781
+ const res = await fetch(`${opsEndpoint}/`, {
782
+ method: "POST",
783
+ headers: retryHeaders,
784
+ body: JSON.stringify({
785
+ operation: "search_by_conditions",
786
+ schema: "flair",
787
+ table: "FederationRetry",
788
+ operator: "and",
789
+ conditions: [
790
+ { search_attribute: "peerId", search_type: "equals", search_value: hub.id },
791
+ { search_attribute: "table", search_type: "equals", search_value: "Memory" },
792
+ { search_attribute: "state", search_type: "equals", search_value: "pending" },
793
+ ],
794
+ get_attributes: ["*"],
795
+ }),
796
+ signal: AbortSignal.timeout(15_000),
797
+ });
798
+ if (!res.ok)
799
+ throw new Error(`FederationRetry read failed (${res.status})`);
800
+ const list = await res.json();
801
+ if (!Array.isArray(list))
802
+ throw new Error("FederationRetry read failed: body is not a row list");
803
+ for (const row of list)
804
+ pendingRetries.set(row.id, row);
805
+ }
806
+ /** Read the stored retry rows for `keys`, whatever their state. */
807
+ async function readStoredRetryRows(keys) {
808
+ const out = new Map();
809
+ if (keys.length === 0)
810
+ return out;
811
+ const res = await fetch(`${opsEndpoint}/`, {
812
+ method: "POST",
813
+ headers: retryHeaders,
814
+ body: JSON.stringify({ operation: "search_by_hash", database: "flair", table: "FederationRetry", hash_values: keys, get_attributes: ["*"] }),
815
+ signal: AbortSignal.timeout(15_000),
816
+ });
817
+ if (!res.ok)
818
+ throw new Error(`FederationRetry read failed (${res.status})`);
819
+ const rows = await res.json();
820
+ if (!Array.isArray(rows))
821
+ throw new Error("FederationRetry read failed: body is not a row list");
822
+ for (const row of rows) {
823
+ if (typeof row.id === "string")
824
+ out.set(row.id, row);
825
+ }
826
+ return out;
827
+ }
828
+ /** Read one retry row back and check it with retryRowConfirmation. */
829
+ async function confirmRetryRow(operation, record) {
830
+ const read = await fetch(`${opsEndpoint}/`, {
831
+ method: "POST",
832
+ headers: retryHeaders,
833
+ body: JSON.stringify({ operation: "search_by_hash", database: "flair", table: "FederationRetry", hash_values: [record.id], get_attributes: ["*"] }),
834
+ signal: AbortSignal.timeout(15_000),
835
+ });
836
+ if (!read.ok)
837
+ throw new Error(`FederationRetry read-back failed (${read.status})`);
838
+ const rows = await read.json();
839
+ if (!Array.isArray(rows))
840
+ throw new Error("FederationRetry read-back failed: body is not a row list");
841
+ const stored = rows.find((r) => r.id === record.id) ?? null;
842
+ const mismatch = retryRowConfirmation(record, stored);
843
+ if (mismatch !== null) {
844
+ throw new Error(`FederationRetry ${operation} was not confirmed for ${String(record.id)} (${mismatch})`);
845
+ }
846
+ }
847
+ /** Write one retry row; an unconfirmed write is an error, never a silent success. */
848
+ async function writeRetryRow(operation, record) {
849
+ const res = await fetch(`${opsEndpoint}/`, {
850
+ method: "POST",
851
+ headers: retryHeaders,
852
+ body: JSON.stringify({ operation, database: "flair", table: "FederationRetry", records: [record] }),
853
+ signal: AbortSignal.timeout(15_000),
854
+ });
855
+ if (!res.ok)
856
+ throw new Error(`FederationRetry ${operation} failed (${res.status})`);
857
+ if (operation === "update") {
858
+ const body = await res.json().catch(() => null);
859
+ if (!Array.isArray(body?.update_hashes) || !body.update_hashes.map(String).includes(String(record.id))) {
860
+ throw new Error(`FederationRetry update was not confirmed for ${String(record.id)}`);
861
+ }
862
+ }
863
+ // The upsert answer does not name the row and an update's hash only says
864
+ // it matched one. Read the row back: a write the sender cannot see is not
865
+ // a recorded obligation.
866
+ await confirmRetryRow(operation, record);
867
+ }
868
+ async function retireRetry(row, resolution, nowIso = new Date().toISOString()) {
869
+ await writeRetryRow("update", terminalRetryRow(row, resolution, nowIso));
870
+ pendingRetries.delete(row.id);
871
+ }
872
+ async function loadMemoryRow(id) {
873
+ const res = await fetch(`${opsEndpoint}/`, {
874
+ method: "POST",
875
+ headers: retryHeaders,
876
+ body: JSON.stringify({
877
+ operation: "search_by_conditions",
878
+ schema: "flair",
879
+ table: "Memory",
880
+ operator: "and",
881
+ conditions: [{ search_attribute: "id", search_type: "equals", search_value: id }],
882
+ get_attributes: memorySelect,
883
+ }),
884
+ signal: AbortSignal.timeout(15_000),
885
+ });
886
+ if (!res.ok)
887
+ throw new Error(`Memory read failed (${res.status})`);
888
+ const rows = await res.json();
889
+ if (!Array.isArray(rows))
890
+ throw new Error("Memory read failed: body is not a row list");
891
+ return rows[0] ?? null;
892
+ }
893
+ async function applyMemoryOutcomes(batch, result) {
894
+ const keyOf = (table, id) => JSON.stringify([table, id]);
895
+ const refused = new Map(result.refused.map((r) => [keyOf(r.table, r.id), r.reason]));
896
+ const undecided = new Set(result.indeterminate.map((r) => keyOf(r.table, r.id)));
897
+ const nowIso = new Date().toISOString();
898
+ // Read what is stored for this batch whatever each row's state: a
899
+ // malformed row is left as stored and its outcome write is skipped.
900
+ const storedRows = await readStoredRetryRows(batch.filter((record) => record.table === "Memory").map((record) => retryEntryKey(hub.id, "Memory", record.id)));
901
+ for (const record of batch) {
902
+ if (record.table !== "Memory")
903
+ continue;
904
+ const key = retryEntryKey(hub.id, "Memory", record.id);
905
+ const attemptReserved = reservedOffers.delete(key);
906
+ const prior = pendingRetries.get(key) ?? null;
907
+ const stored = storedRows.get(key) ?? null;
908
+ if (stored !== null) {
909
+ const malformed = retryRowMalformedness(stored);
910
+ if (malformed !== null) {
911
+ reportMalformedRetryRow(key, malformed);
912
+ continue;
913
+ }
914
+ }
915
+ // A row the shared validator names malformed is reported before the
916
+ // offer and left as stored: the outcome does not transition it.
917
+ if (prior !== null && retryOfferProblem(prior) !== null)
918
+ continue;
919
+ if (undecided.has(keyOf(record.table, record.id))) {
920
+ // The receiver did not decide this record. Offering it again is safe
921
+ // (the merge is idempotent); `retry_unknown` is the sender's own name.
922
+ // A first offer records the obligation too, or the cursor advance
923
+ // would lose it.
924
+ const row = retryRowForRefusal({ peerId: hub.id, recordId: record.id, reason: "retry_unknown", nowIso, existing: prior, attemptReserved });
925
+ await writeRetryRow("upsert", row);
926
+ pendingRetries.set(String(row.id), row);
927
+ continue;
928
+ }
929
+ const reason = refused.get(keyOf(record.table, record.id));
930
+ if (reason !== undefined) {
931
+ if (MEMORY_RETRY_REASONS.has(reason)) {
932
+ const row = retryRowForRefusal({ peerId: hub.id, recordId: record.id, reason, nowIso, existing: prior, attemptReserved });
933
+ await writeRetryRow("upsert", row);
934
+ pendingRetries.set(String(row.id), row);
935
+ }
936
+ else if (prior) {
937
+ await retireRetry(prior, "refused_terminal", nowIso);
938
+ }
939
+ continue;
940
+ }
941
+ if (prior)
942
+ await retireRetry(prior, "merged", nowIso);
943
+ }
944
+ }
945
+ /**
946
+ * Reserve one attempt for each Memory record in `batch` that selection recorded
947
+ * in `reservationTargets` (a record with a valid pending retry row).
948
+ * Called immediately before that batch is sent, so a
949
+ * batch the run never reaches leaves its rows' attempts and lastAttemptAt
950
+ * as stored. A reservation write that fails throws here, before the send.
951
+ */
952
+ async function reserveBatchAttempts(batch) {
953
+ const nowIso = new Date().toISOString();
954
+ for (const record of batch) {
955
+ if (record.table !== "Memory")
956
+ continue;
957
+ const pending = reservationTargets.get(String(record.id));
958
+ if (!pending)
959
+ continue;
960
+ reservationTargets.delete(String(record.id));
961
+ const reserved = retryRowForAttempt(pending, nowIso);
962
+ await writeRetryRow("upsert", reserved);
963
+ pendingRetries.set(String(reserved.id), reserved);
964
+ reservedOffers.add(String(reserved.id));
965
+ }
966
+ }
967
+ await loadPendingRetries();
633
968
  // A stored endpoint with a trailing slash still yields `<hub>/FederationSync`.
634
969
  const hubUrl = normalizeHubUrl(hub.endpoint ?? hub.id);
635
970
  // ── Batching constants ──────────────────────────────────────────────
@@ -658,7 +993,7 @@ export async function runFederationSyncOnce(opts) {
658
993
  // a healthy 50-record batch merges in <2s — so a trip means a real stall,
659
994
  // and we split-and-retry rather than wait it out.
660
995
  const BATCH_TIMEOUT_MS = 45_000;
661
- async function sendBatch(batch) {
996
+ async function sendBatch(batch, validatePresence = false) {
662
997
  if (!secretKey)
663
998
  secretKey = await loadInstanceSecretKey(instance.id, opts);
664
999
  const syncBody = { instanceId: instance.id, records: batch, lamportClock: Date.now() };
@@ -669,9 +1004,14 @@ export async function runFederationSyncOnce(opts) {
669
1004
  const splittable = (status) => batch.length > 1 && (status === null || TIMEOUT_STATUSES.has(status));
670
1005
  const split = async () => {
671
1006
  const mid = Math.floor(batch.length / 2);
672
- const left = await sendBatch(batch.slice(0, mid));
673
- const right = await sendBatch(batch.slice(mid));
674
- return { merged: left.merged + right.merged, skipped: left.skipped + right.skipped };
1007
+ const left = await sendBatch(batch.slice(0, mid), validatePresence);
1008
+ const right = await sendBatch(batch.slice(mid), validatePresence);
1009
+ return {
1010
+ merged: left.merged + right.merged,
1011
+ skipped: left.skipped + right.skipped,
1012
+ refused: [...left.refused, ...right.refused],
1013
+ indeterminate: [...left.indeterminate, ...right.indeterminate],
1014
+ };
675
1015
  };
676
1016
  let syncRes;
677
1017
  try {
@@ -707,9 +1047,31 @@ export async function runFederationSyncOnce(opts) {
707
1047
  }
708
1048
  const counts = parseSyncBatchCounts(body, batch.length);
709
1049
  if (!counts) {
710
- throw new Error(`Sync batch failed: invalid response (HTTP ${syncRes.status}, merged/skipped are not counts from 0 to ${batch.length})`);
1050
+ const table = typeof batch[0]?.table === "string" ? batch[0].table : "batch";
1051
+ throw new Error(`Sync batch failed: invalid response (HTTP ${syncRes.status}, ${describeSyncBatchCountsRejection(body, batch.length, table)})`);
1052
+ }
1053
+ const refused = parseSyncBatchRefused(body);
1054
+ const indeterminate = parseSyncBatchIndeterminate(body);
1055
+ // A Memory batch changes the sender's retry state and advances its
1056
+ // cursor, so its response must account for every offered record. Presence
1057
+ // already requires the same. Other generic tables are checked on their
1058
+ // counts.
1059
+ if (validatePresence || batch[0]?.table === "Memory") {
1060
+ const outcomeBody = body;
1061
+ const validList = (raw, parsed) => raw === undefined || (Array.isArray(raw) && raw.length === parsed.length);
1062
+ const key = (row) => JSON.stringify([row.table, row.id]);
1063
+ const offered = new Set(batch.map(key));
1064
+ const unresolved = [...refused, ...indeterminate].map(key);
1065
+ if (!validList(outcomeBody.refused, refused) ||
1066
+ !validList(outcomeBody.indeterminate, indeterminate) ||
1067
+ unresolved.some((entry) => !offered.has(entry)) ||
1068
+ new Set(unresolved).size !== unresolved.length ||
1069
+ counts.skipped !== refused.length ||
1070
+ counts.merged + refused.length + indeterminate.length !== batch.length) {
1071
+ throw new Error(`Sync batch failed: invalid response (HTTP ${syncRes.status}, outcomes do not account for ${batch.length} offered records)`);
1072
+ }
711
1073
  }
712
- return counts;
1074
+ return { ...counts, refused, indeterminate };
713
1075
  }
714
1076
  let totalBatches = 0;
715
1077
  // Memory rows that passed the since-cursor filter but were excluded as
@@ -731,7 +1093,7 @@ export async function runFederationSyncOnce(opts) {
731
1093
  res = await fetch(`${opsEndpoint}/`, {
732
1094
  method: "POST",
733
1095
  headers: { "Content-Type": "application/json", Authorization: auth },
734
- body: JSON.stringify({ operation: "search_by_conditions", schema: "flair", table, operator: "and", conditions: [query], get_attributes: table === "Memory" ? [...FEDERATION_MEMORY_SELECT] : ["*"] }),
1096
+ body: JSON.stringify({ operation: "search_by_conditions", schema: "flair", table, operator: "and", conditions: [query], get_attributes: table === "Memory" ? memorySelect : ["*"] }),
735
1097
  signal: AbortSignal.timeout(15_000),
736
1098
  });
737
1099
  }
@@ -756,6 +1118,46 @@ export async function runFederationSyncOnce(opts) {
756
1118
  privateHeldBack += sinceCursor.length - federable.length;
757
1119
  rows = rows.concat(federable);
758
1120
  }
1121
+ if (table === "Memory" && pendingRetries.size > 0) {
1122
+ // Re-offer the pending rows whose backoff has elapsed. A row still
1123
+ // selected by the since cursor is offered once (the set below). A row
1124
+ // that is gone or has become private ends its obligation here.
1125
+ const seen = new Set(rows.map((r) => r.id));
1126
+ for (const pending of pendingRetries.values()) {
1127
+ const malformed = retryRowMalformedness(pending);
1128
+ if (malformed !== null)
1129
+ reportMalformedRetryRow(pending.id, malformed);
1130
+ }
1131
+ // A source the cursor selects that also has a valid pending row is
1132
+ // offered now — a new change is not a retry, so the backoff does not
1133
+ // hold it back. Its attempt is reserved immediately before the batch
1134
+ // carrying it is sent, as on the re-offer path. A malformed row
1135
+ // reserves nothing.
1136
+ for (const row of rows) {
1137
+ const pending = pendingRetries.get(retryEntryKey(hub.id, "Memory", row.id));
1138
+ if (!pending || retryOfferProblem(pending) !== null)
1139
+ continue;
1140
+ reservationTargets.set(String(row.id), pending);
1141
+ }
1142
+ for (const pending of dueRetryRows([...pendingRetries.values()], Date.now())) {
1143
+ if (seen.has(pending.recordId))
1144
+ continue;
1145
+ const row = await loadMemoryRow(pending.recordId);
1146
+ if (!row) {
1147
+ await retireRetry(pending, "source_deleted");
1148
+ continue;
1149
+ }
1150
+ if (isFederationPrivateVisibility(row.visibility)) {
1151
+ await retireRetry(pending, "source_ineligible");
1152
+ continue;
1153
+ }
1154
+ // An unconfirmed send keeps the reservation; retry backoff applies
1155
+ // while the row remains behind the cursor.
1156
+ reservationTargets.set(String(row.id), pending);
1157
+ rows.push(row);
1158
+ seen.add(pending.recordId);
1159
+ }
1160
+ }
759
1161
  if (rows.length === 0)
760
1162
  continue;
761
1163
  // Records are signed (below) before they're batched, so the secret key
@@ -814,7 +1216,11 @@ export async function runFederationSyncOnce(opts) {
814
1216
  sr.principalId = principalId;
815
1217
  const srBytes = JSON.stringify(sr).length;
816
1218
  if (batch.length >= BUDGET_RECORDS || (batch.length > 0 && batchBytes + srBytes > BUDGET_BYTES)) {
1219
+ if (table === "Memory")
1220
+ await reserveBatchAttempts(batch);
817
1221
  const result = await sendBatch(batch);
1222
+ if (table === "Memory")
1223
+ await applyMemoryOutcomes(batch, result);
818
1224
  totalMerged += result.merged;
819
1225
  totalSkipped += result.skipped;
820
1226
  totalBatches++;
@@ -826,7 +1232,11 @@ export async function runFederationSyncOnce(opts) {
826
1232
  }
827
1233
  // Send final partial batch for this table
828
1234
  if (batch.length > 0) {
1235
+ if (table === "Memory")
1236
+ await reserveBatchAttempts(batch);
829
1237
  const result = await sendBatch(batch);
1238
+ if (table === "Memory")
1239
+ await applyMemoryOutcomes(batch, result);
830
1240
  totalMerged += result.merged;
831
1241
  totalSkipped += result.skipped;
832
1242
  totalBatches++;
@@ -852,6 +1262,137 @@ export async function runFederationSyncOnce(opts) {
852
1262
  console.warn(`⚠️ Local hub.lastSyncAt advance error: ${advErr?.message ?? advErr}. Next poll will re-send memories.`);
853
1263
  }
854
1264
  };
1265
+ const genericBatches = totalBatches;
1266
+ const failPresence = async (err) => {
1267
+ if (genericBatches > 0)
1268
+ await stampLocalContact();
1269
+ return { pushed: totalMerged, skipped: totalSkipped, error: err instanceof Error ? err : new Error(String(err)) };
1270
+ };
1271
+ // ── flair#2578 slice 2: Presence push (P6) ──────────────────────────────
1272
+ // Presence has no updatedAt/createdAt, so the generic cursor above cannot
1273
+ // select it. Home rows travel by their OWN per-table watermark on
1274
+ // lastHeartbeatAt / activityUpdatedAt, sent AFTER the generic tables so the
1275
+ // receiver can bind Presence to an accepted Agent row.
1276
+ // A scan, send or response failure returns before watermark persistence.
1277
+ let presenceAdvanceMs = null;
1278
+ let presenceCapMs = Number.POSITIVE_INFINITY;
1279
+ try {
1280
+ if (presenceSendEnabled()) {
1281
+ const presenceScanAtMs = Date.now();
1282
+ const presenceRes = await fetch(`${opsEndpoint}/`, {
1283
+ method: "POST",
1284
+ headers: { "Content-Type": "application/json", Authorization: auth },
1285
+ body: JSON.stringify({ operation: "sql", sql: "SELECT * FROM flair.Presence" }),
1286
+ signal: AbortSignal.timeout(15_000),
1287
+ });
1288
+ if (!presenceRes.ok) {
1289
+ const text = await presenceRes.text().catch(() => "");
1290
+ throw new Error(`Presence scan failed (${presenceRes.status}): ${text.slice(0, 200)}`);
1291
+ }
1292
+ const parsed = await presenceRes.json();
1293
+ const list = Array.isArray(parsed) ? parsed : Array.isArray(parsed?.results) ? parsed.results : null;
1294
+ if (!list) {
1295
+ throw new Error("Presence scan failed: body is not a row list");
1296
+ }
1297
+ const presenceRows = list;
1298
+ const watermarkMs = presenceWatermarkMs(hub.presenceLastSyncAt);
1299
+ // Clamp selection to scan time.
1300
+ const effectiveWatermarkMs = Math.min(watermarkMs, presenceScanAtMs);
1301
+ // Re-scan from the effective watermark minus the overlap.
1302
+ const scanFloorMs = Math.max(0, effectiveWatermarkMs - PRESENCE_SEND_OVERLAP_MS);
1303
+ const toSend = selectPresenceRowsToSend(presenceRows, instance.id, scanFloorMs);
1304
+ if (toSend.length === 0 && watermarkMs > effectiveWatermarkMs) {
1305
+ presenceAdvanceMs = effectiveWatermarkMs;
1306
+ }
1307
+ if (toSend.length > 0) {
1308
+ if (!secretKey)
1309
+ secretKey = await loadInstanceSecretKey(instance.id, opts);
1310
+ let presenceBatch = [];
1311
+ let presenceBatchBytes = 0;
1312
+ // Overlap resends retain the effective watermark unless capped below.
1313
+ let advanceMs = effectiveWatermarkMs;
1314
+ const flushPresence = async () => {
1315
+ const result = await sendBatch(presenceBatch, true);
1316
+ totalMerged += result.merged;
1317
+ totalSkipped += result.skipped;
1318
+ totalBatches++;
1319
+ // Cap the candidate below retryable refusals, and below a row
1320
+ // refused because the hub's Presence receipt is off: enabling it
1321
+ // later must not need a new heartbeat to re-offer that row.
1322
+ for (const refusal of result.refused) {
1323
+ if (refusal.table !== "Presence")
1324
+ continue;
1325
+ if (!PRESENCE_SEND_RETRYABLE_SKIP_REASONS.has(refusal.reason) &&
1326
+ refusal.reason !== PRESENCE_SEND_RECEIVE_DISABLED_SKIP_REASON)
1327
+ continue;
1328
+ const sent = presenceBatch.find((r) => r.id === refusal.id);
1329
+ if (!sent)
1330
+ continue;
1331
+ const refusedCursor = Date.parse(sent.updatedAt);
1332
+ if (Number.isFinite(refusedCursor))
1333
+ presenceCapMs = Math.min(presenceCapMs, refusedCursor - 1);
1334
+ }
1335
+ // Apply the same cap to indeterminate outcomes.
1336
+ for (const undecided of result.indeterminate) {
1337
+ if (undecided.table !== "Presence")
1338
+ continue;
1339
+ const sent = presenceBatch.find((r) => r.id === undecided.id);
1340
+ if (!sent)
1341
+ continue;
1342
+ const undecidedCursor = Date.parse(sent.updatedAt);
1343
+ if (Number.isFinite(undecidedCursor))
1344
+ presenceCapMs = Math.min(presenceCapMs, undecidedCursor - 1);
1345
+ }
1346
+ presenceBatch = [];
1347
+ presenceBatchBytes = 0;
1348
+ };
1349
+ for (const row of toSend) {
1350
+ const cursor = presenceCursorMs(row);
1351
+ // A row dated more than the receiver's future allowance past this
1352
+ // scan is left out of the batch: the receiver may refuse it, and
1353
+ // its cursor must not count toward the watermark.
1354
+ if (cursor != null && cursor > presenceScanAtMs + PRESENCE_SEND_FUTURE_ALLOWANCE_MS)
1355
+ continue;
1356
+ const payload = presenceWireRecord(row, instance.id);
1357
+ if (!payload)
1358
+ continue;
1359
+ const sr = { ...payload, signature: signBody(payload, secretKey) };
1360
+ const srBytes = JSON.stringify(sr).length;
1361
+ if (presenceBatch.length >= BUDGET_RECORDS || (presenceBatch.length > 0 && presenceBatchBytes + srBytes > BUDGET_BYTES)) {
1362
+ await flushPresence();
1363
+ }
1364
+ presenceBatch.push(sr);
1365
+ presenceBatchBytes += srBytes;
1366
+ // Clamp the candidate to scan time.
1367
+ if (cursor != null && Math.min(cursor, presenceScanAtMs) > advanceMs)
1368
+ advanceMs = Math.min(cursor, presenceScanAtMs);
1369
+ }
1370
+ if (presenceBatch.length > 0)
1371
+ await flushPresence();
1372
+ presenceAdvanceMs = Math.min(advanceMs, presenceCapMs);
1373
+ }
1374
+ }
1375
+ }
1376
+ catch (err) {
1377
+ return await failPresence(err);
1378
+ }
1379
+ // Attempt the watermark update after contact.
1380
+ const persistPresence = async (presenceMs) => {
1381
+ try {
1382
+ const advanced = await persistLocalPeerPresenceSyncAt({
1383
+ opsEndpoint,
1384
+ auth,
1385
+ peerId: hub.id,
1386
+ presenceLastSyncAt: new Date(presenceMs).toISOString(),
1387
+ });
1388
+ if (!advanced.ok) {
1389
+ console.warn(`⚠️ Local hub.presenceLastSyncAt advance failed (${advanced.status}): ${advanced.error ?? ""}.`);
1390
+ }
1391
+ }
1392
+ catch (advErr) {
1393
+ console.warn(`⚠️ Local hub.presenceLastSyncAt advance error: ${advErr?.message ?? advErr}.`);
1394
+ }
1395
+ };
855
1396
  if (totalBatches === 0) {
856
1397
  // No-change syncs must still ping the hub so it updates the
857
1398
  // spoke's lastSyncAt (liveness). Without this, idle-but-alive spokes
@@ -884,6 +1425,8 @@ export async function runFederationSyncOnce(opts) {
884
1425
  }
885
1426
  if (pingOk)
886
1427
  await stampLocalContact();
1428
+ if (pingOk && presenceAdvanceMs != null)
1429
+ await persistPresence(presenceAdvanceMs);
887
1430
  // flair#1232: "No changes" is true only when nothing was found since
888
1431
  // the cursor. If rows were found and every one was withheld as private,
889
1432
  // say so — count and reason only, never content. A zero withheld count
@@ -894,6 +1437,8 @@ export async function runFederationSyncOnce(opts) {
894
1437
  return { pushed: 0, skipped: 0 };
895
1438
  }
896
1439
  await stampLocalContact();
1440
+ if (presenceAdvanceMs != null)
1441
+ await persistPresence(presenceAdvanceMs);
897
1442
  console.log(`✅ Synced ${totalMerged} records (${totalSkipped} skipped) across ${totalBatches} batches`);
898
1443
  return { pushed: totalMerged, skipped: totalSkipped };
899
1444
  }
@@ -1369,12 +1914,10 @@ export function register(program) {
1369
1914
  if (failures > 0)
1370
1915
  process.exit(1);
1371
1916
  });
1372
- federation
1917
+ addAdminPassOptions(federation
1373
1918
  .command("pair <hub-url>")
1374
1919
  .description("Pair this spoke with a hub instance")
1375
- .option("--port <port>", "Harper HTTP port")
1376
- .option(ADMIN_PASS_FILE_FLAG, ADMIN_PASS_FILE_HELP)
1377
- .option("--admin-pass <pass>", ADMIN_PASS_HELP)
1920
+ .option("--port <port>", "Harper HTTP port"))
1378
1921
  .option("--admin-user <name>", "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)")
1379
1922
  .option("--ops-port <port>", "Harper operations API port")
1380
1923
  .option("--token <token>", "One-time pairing token from hub admin (env: FLAIR_PAIRING_TOKEN) [deprecated: use --token-from]")
@@ -1621,12 +2164,10 @@ export function register(program) {
1621
2164
  process.exit(1);
1622
2165
  }
1623
2166
  });
1624
- federation
2167
+ addAdminPassOptions(federation
1625
2168
  .command("token")
1626
2169
  .description("Generate a one-time pairing token (run on the hub)")
1627
- .option("--port <port>", "Harper HTTP port")
1628
- .option(ADMIN_PASS_FILE_FLAG, ADMIN_PASS_FILE_HELP)
1629
- .option("--admin-pass <pass>", ADMIN_PASS_HELP)
2170
+ .option("--port <port>", "Harper HTTP port"))
1630
2171
  .option("--admin-user <name>", "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)")
1631
2172
  .option("--ops-port <port>", "Harper operations API port")
1632
2173
  .option("--ttl <minutes>", "Token TTL in minutes (default: 60)", "60")
@@ -1724,7 +2265,6 @@ export function register(program) {
1724
2265
  .option("--ops-target <url>", "Explicit ops API URL (env: FLAIR_OPS_TARGET; bypasses port derivation)")).action(async (opts) => {
1725
2266
  // --admin-pass-file resolves into the same `adminPass` slot the inline
1726
2267
  // flag uses, so the scheduler never has to embed a secret in a unit file.
1727
- applyAdminPassFile(opts);
1728
2268
  const r = await runFederationSyncOnce(opts);
1729
2269
  if (r.error) {
1730
2270
  console.error(`Error: ${r.error.message}`);
@@ -1808,6 +2348,7 @@ export function register(program) {
1808
2348
  .command("disable")
1809
2349
  .description("Remove the sync driver (peers and sync history are preserved)")
1810
2350
  .option("--remove-shim", "Also delete the ~/.flair/bin/flair-federation-sync shim")
2351
+ .hook("preAction", (_thisCommand, actionCommand) => applyInheritedAdminPass(actionCommand))
1811
2352
  .action(async (opts) => {
1812
2353
  const { disableScheduler } = await import("../federation/scheduler.js");
1813
2354
  try {
@@ -1840,6 +2381,7 @@ export function register(program) {
1840
2381
  // `flair federation sync` owns them and commander binds them there. They
1841
2382
  // still work on this command, via optsWithGlobals() below.
1842
2383
  .option("--json", "Emit JSON")
2384
+ .hook("preAction", (_thisCommand, actionCommand) => applyInheritedAdminPass(actionCommand))
1843
2385
  .action(async (_opts, cmd) => {
1844
2386
  // See the comment on `enable` above: `--target`/`--port` live on the
1845
2387
  // parent, so commander binds them there and only optsWithGlobals() sees
@@ -1869,12 +2411,11 @@ export function register(program) {
1869
2411
  process.exit(1);
1870
2412
  }
1871
2413
  });
1872
- federation
2414
+ addAdminPassOptions(federation
1873
2415
  .command("watch")
1874
2416
  .description("Run federation sync in a loop (foreground daemon)")
1875
2417
  .option("--interval <seconds>", "Seconds between syncs", "30")
1876
- .option("--port <port>", "Harper HTTP port")
1877
- .option("--admin-pass <pass>", "Admin password")
2418
+ .option("--port <port>", "Harper HTTP port"), "Admin password")
1878
2419
  .option("--admin-user <name>", "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)")
1879
2420
  .option("--ops-port <port>", "Harper operations API port")
1880
2421
  .option("--target <url>", "Remote Flair URL")
@@ -1942,31 +2483,77 @@ export function register(program) {
1942
2483
  console.log(`Run with --apply to actually delete.`);
1943
2484
  return;
1944
2485
  }
1945
- // Apply path. Delete each peer via the Harper ops API. We use the
1946
- // domain-socket form when local; otherwise we fall back to the resource
1947
- // DELETE which requires admin auth.
2486
+ // Apply path: delete each peer's `flair.Peer` row through the admin-only
2487
+ // `/Peer/{id}` REST resource and read it back to confirm it is gone.
1948
2488
  let deleted = 0;
1949
2489
  let errors = 0;
2490
+ let unknown = 0;
2491
+ const requestOptions = baseUrl ? { baseUrl } : undefined;
2492
+ // The DELETE's own body is not evidence, so a 2xx whose body is empty or
2493
+ // not JSON must not throw: the server may already have deleted the row.
2494
+ const deleteOptions = { ...(requestOptions ?? {}), tolerateUnparsedSuccessBody: true };
1950
2495
  for (const p of candidates) {
2496
+ let refusal;
1951
2497
  try {
1952
- const res = await api("DELETE", `/FederationPeers/${encodeRecordId(p.id)}`, undefined, baseUrl ? { baseUrl } : undefined);
1953
- const ok = res?.ok ?? res?.deleted ?? true;
1954
- if (ok) {
1955
- deleted++;
1956
- const ts = p.lastSyncAt ?? p.pairedAt ?? "never";
1957
- console.log(`Deleted ${p.id} (last seen ${ts}).`);
2498
+ await api("DELETE", `/Peer/${encodeRecordId(p.id)}`, undefined, deleteOptions);
2499
+ }
2500
+ catch (e) {
2501
+ if (e instanceof ApiRequestOutcomeUnknown) {
2502
+ // An expired request is reported as an unknown outcome, like every
2503
+ // other non-GET/HEAD request through the shared REST sender: the client cannot tell
2504
+ // whether the server acted. Count it apart from a definite failure
2505
+ // and exit 3 for it (unknown outranks a known failure, as rem's
2506
+ // `unresolved` does).
2507
+ unknown++;
2508
+ console.log(`Unknown outcome for ${p.id}: ${e.message}`);
2509
+ continue;
1958
2510
  }
2511
+ if (e instanceof ApiHttpError)
2512
+ refusal = e;
1959
2513
  else {
1960
2514
  errors++;
1961
- console.log(`Failed to delete ${p.id}: ${JSON.stringify(res)}`);
2515
+ console.log(`Failed to delete ${p.id}: ${e.message}`);
2516
+ continue;
1962
2517
  }
1963
2518
  }
2519
+ // 404 or a null body means absent; a row means it is still there. A
2520
+ // read failure after a successful DELETE is an unknown outcome.
2521
+ let present;
2522
+ try {
2523
+ const row = await api("GET", `/Peer/${encodeRecordId(p.id)}`, undefined, requestOptions);
2524
+ present = row != null;
2525
+ }
1964
2526
  catch (e) {
2527
+ if (e instanceof ApiHttpError && e.status === 404)
2528
+ present = false;
2529
+ else if (refusal) {
2530
+ errors++;
2531
+ console.log(`Failed to delete ${p.id}: ${refusal.message}`);
2532
+ continue;
2533
+ }
2534
+ else {
2535
+ unknown++;
2536
+ console.log(`Unknown outcome for ${p.id}: the delete returned, but reading the row back failed: ${e.message}`);
2537
+ continue;
2538
+ }
2539
+ }
2540
+ if (refusal) {
2541
+ errors++;
2542
+ console.log(`Failed to delete ${p.id}: ${refusal.message}`);
2543
+ }
2544
+ else if (!present) {
2545
+ deleted++;
2546
+ const ts = p.lastSyncAt ?? p.pairedAt ?? "never";
2547
+ console.log(`Deleted ${p.id} (last seen ${ts}).`);
2548
+ }
2549
+ else {
1965
2550
  errors++;
1966
- console.log(`Failed to delete ${p.id}: ${e.message}`);
2551
+ console.log(`Failed to delete ${p.id}: the row is still present after the DELETE.`);
1967
2552
  }
1968
2553
  }
1969
- console.log(`${deleted} peer(s) deleted; ${errors} error(s).`);
2554
+ console.log(`${deleted} peer(s) deleted; ${errors} error(s); ${unknown} unknown outcome(s).`);
2555
+ if (unknown > 0)
2556
+ process.exit(3);
1970
2557
  if (errors > 0)
1971
2558
  process.exit(1);
1972
2559
  });
@@ -1984,7 +2571,6 @@ export function register(program) {
1984
2571
  const instanceOpsEndpoint = (opts) => {
1985
2572
  // --admin-pass-file resolves into the same `adminPass` slot the inline flag
1986
2573
  // uses (the shared idiom: the secret stays out of ps and shell history).
1987
- applyAdminPassFile(opts);
1988
2574
  const opsUrl = resolveEffectiveOpsUrl(opts) ?? `http://127.0.0.1:${resolveOpsPort(opts)}`;
1989
2575
  const adminPass = opts.adminPass ?? process.env.FLAIR_ADMIN_PASS ?? "";
1990
2576
  return { opsUrl, credentials: { user: resolveAdminUser(opts.adminUser), pass: adminPass } };
@@ -2114,7 +2700,6 @@ export function register(program) {
2114
2700
  .option("--ops-port <port>", "Harper operations API port")
2115
2701
  .option("--target <url>", "Remote Flair URL (env: FLAIR_TARGET)")
2116
2702
  .option("--ops-target <url>", "Explicit ops API URL (env: FLAIR_OPS_TARGET; bypasses port derivation)"))).action(async (opts) => {
2117
- applyAdminPassFile(opts);
2118
2703
  const target = resolveTarget(opts);
2119
2704
  const baseUrl = target ? target.replace(/\/$/, "") : undefined;
2120
2705
  const waitSeconds = Number(opts.wait) || 60;
@@ -2132,7 +2717,7 @@ export function register(program) {
2132
2717
  peerId: opts.peer,
2133
2718
  baseUrl,
2134
2719
  syncOpts: opts,
2135
- // GET /FederationPeers is allowAdmin. applyAdminPassFile already
2720
+ // GET /FederationPeers is allowAdmin. The preAction hook already
2136
2721
  // folded --admin-pass-file into opts.adminPass; without this the
2137
2722
  // injected api only sees { baseUrl } and flag-only creds never
2138
2723
  // reach the listing (UNVERIFIABLE, check never runs).