@tpsdev-ai/flair 0.59.0 → 0.63.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (359) hide show
  1. package/README.md +10 -10
  2. package/SECURITY.md +49 -5
  3. package/config.yaml +23 -12
  4. package/dist/bridges/builtins/mem0.js +63 -28
  5. package/dist/bridges/runtime/execute.js +1 -0
  6. package/dist/bridges/runtime/import-runner.js +12 -0
  7. package/dist/bridges/runtime/load-plugin.js +42 -13
  8. package/dist/bridges/runtime/yaml-loader.js +4 -2
  9. package/dist/bridges/types.js +1 -0
  10. package/dist/build-info.json +3 -3
  11. package/dist/cli.js +1054 -367
  12. package/dist/commands/agent.js +233 -90
  13. package/dist/commands/attention.js +4 -3
  14. package/dist/commands/backup-approval.js +218 -0
  15. package/dist/commands/backup.js +211 -39
  16. package/dist/commands/bootstrap.js +3 -1
  17. package/dist/commands/bridge.js +172 -119
  18. package/dist/commands/deploy.js +71 -8
  19. package/dist/commands/doctor.js +711 -146
  20. package/dist/commands/export.js +57 -23
  21. package/dist/commands/federation.js +787 -82
  22. package/dist/commands/grant.js +5 -6
  23. package/dist/commands/help.js +25 -0
  24. package/dist/commands/hook.js +155 -2
  25. package/dist/commands/idp.js +27 -19
  26. package/dist/commands/import.js +136 -20
  27. package/dist/commands/init.js +469 -200
  28. package/dist/commands/integrity.js +387 -0
  29. package/dist/commands/keys.js +247 -58
  30. package/dist/commands/mcp.js +108 -52
  31. package/dist/commands/memory.js +203 -35
  32. package/dist/commands/migrate-harness-memory.js +3 -2
  33. package/dist/commands/orgevent.js +51 -47
  34. package/dist/commands/presence.js +4 -3
  35. package/dist/commands/principal.js +428 -62
  36. package/dist/commands/quality.js +13 -1
  37. package/dist/commands/reembed.js +141 -17
  38. package/dist/commands/relationship.js +2 -1
  39. package/dist/commands/rem.js +537 -80
  40. package/dist/commands/restore.js +413 -65
  41. package/dist/commands/search.js +6 -4
  42. package/dist/commands/service.js +235 -40
  43. package/dist/commands/soul.js +4 -9
  44. package/dist/commands/status.js +94 -38
  45. package/dist/commands/test.js +7 -3
  46. package/dist/commands/upgrade.js +77 -23
  47. package/dist/commands/workspace.js +13 -11
  48. package/dist/component-env.js +31 -41
  49. package/dist/deploy.js +136 -4
  50. package/dist/doctor-client.js +534 -92
  51. package/dist/engine-version-contract.js +1 -0
  52. package/dist/engine-version.js +23 -3
  53. package/dist/fabric-upgrade.js +12 -2
  54. package/dist/federation/presence-send.js +139 -0
  55. package/dist/federation-verify.js +273 -180
  56. package/dist/hook-install.js +670 -6
  57. package/dist/install/clients.js +171 -35
  58. package/dist/keystore.js +72 -0
  59. package/dist/lib/action-recall-runtime.js +328 -0
  60. package/dist/lib/agent-home-fields.js +132 -0
  61. package/dist/lib/agent-home.js +427 -0
  62. package/dist/lib/agent-id-rule.js +88 -0
  63. package/dist/lib/agent-roster.js +33 -0
  64. package/dist/lib/atomic-write.js +1 -1
  65. package/dist/lib/auth-resolve.js +1069 -60
  66. package/dist/lib/backup-approval-store.js +612 -0
  67. package/dist/lib/backup-artifact.js +343 -0
  68. package/dist/lib/capture-runtime.js +124 -0
  69. package/dist/lib/config-critical-section.js +212 -25
  70. package/dist/lib/connect-phase.js +33 -0
  71. package/dist/lib/credential-status-rule.js +78 -0
  72. package/dist/lib/daemon-liveness.js +43 -11
  73. package/dist/lib/doctor-run.js +75 -37
  74. package/dist/lib/durability-copy.js +10 -0
  75. package/dist/lib/embedding-space-doctor.js +75 -0
  76. package/dist/lib/federation-pair-access.js +4 -0
  77. package/dist/lib/federation-retry-queue.js +283 -0
  78. package/dist/lib/federation-retry-row.js +101 -0
  79. package/dist/lib/flair-agent-role.js +4 -0
  80. package/dist/lib/hub-url.js +12 -0
  81. package/dist/lib/init-admin-pass.js +88 -12
  82. package/dist/lib/init-listener-environ.js +1 -2
  83. package/dist/lib/init-occupied-listener.js +15 -111
  84. package/dist/lib/init-spawn-attribution.js +73 -0
  85. package/dist/lib/init-tcp-probe.js +33 -0
  86. package/dist/lib/instance-identity-row.js +20 -0
  87. package/dist/lib/instruction-event-contract.js +17 -0
  88. package/dist/lib/instruction-event-doctor.js +102 -0
  89. package/dist/lib/launchd-management.js +38 -3
  90. package/dist/lib/listener-table.js +268 -0
  91. package/dist/lib/local-delete-instance.js +27 -0
  92. package/dist/lib/local-instance-pair.js +256 -0
  93. package/dist/lib/mcp-enable.js +1182 -341
  94. package/dist/lib/mcp-oauth-env-core.js +133 -0
  95. package/dist/lib/mcp-oauth-env.js +125 -0
  96. package/dist/lib/mcp-spec.js +17 -1
  97. package/dist/lib/memory-attributes.js +4 -0
  98. package/dist/lib/memory-id-policy.js +46 -0
  99. package/dist/lib/memory-integrity.js +309 -0
  100. package/dist/lib/memory-provider-timeout.js +33 -0
  101. package/dist/lib/memory-purge-response.js +20 -0
  102. package/dist/lib/mqtt-config.js +132 -0
  103. package/dist/lib/mqtt-listener-doctor.js +104 -0
  104. package/dist/lib/open-live-row.js +20 -0
  105. package/dist/lib/ops-table-count.js +25 -0
  106. package/dist/lib/ops-url.js +52 -0
  107. package/dist/lib/owned-pins.js +67 -10
  108. package/dist/lib/peer-status.js +27 -0
  109. package/dist/lib/principal-status.js +29 -0
  110. package/dist/lib/process-start-time.js +76 -12
  111. package/dist/lib/promotion-content-hash.js +20 -0
  112. package/dist/lib/proto-safe-record.js +42 -0
  113. package/dist/lib/record-id-path.js +25 -0
  114. package/dist/lib/reembed-server-support.js +66 -0
  115. package/dist/lib/restore-archive.js +760 -0
  116. package/dist/lib/restore-verify.js +104 -0
  117. package/dist/lib/scheduler-platform.js +10 -6
  118. package/dist/lib/secret-keys.js +25 -0
  119. package/dist/lib/secrets-push.js +50 -22
  120. package/dist/lib/skill-assignment-preflight.js +159 -0
  121. package/dist/lib/skill-seed-pending.js +24 -0
  122. package/dist/lib/skill-seed.js +448 -0
  123. package/dist/lib/skill-tombstone-doctor.js +133 -0
  124. package/dist/lib/soul-scope-fields.js +26 -0
  125. package/dist/lib/stop-start-recovery.js +54 -0
  126. package/dist/lib/uninstall-purge.js +266 -11
  127. package/dist/lib/upgrade-prior-liveness.js +2 -1
  128. package/dist/lib/using-flair-skill.js +87 -0
  129. package/dist/mcp-client-assertion.js +114 -14
  130. package/dist/memory-id-checkpoint.js +347 -0
  131. package/dist/memory-node-compare.js +207 -0
  132. package/dist/mqtt-off-deploy.js +550 -0
  133. package/dist/packages/flair-mcp/src/secret-redaction.js +113 -0
  134. package/dist/rem/promote-policy.js +3 -3
  135. package/dist/rem/restore.js +303 -26
  136. package/dist/rem/runner.js +317 -96
  137. package/dist/rem/scheduler.js +21 -4
  138. package/dist/resources/A2AAdapter.js +131 -178
  139. package/dist/resources/AdminMemory.js +2 -0
  140. package/dist/resources/AdminMemoryCandidates.js +116 -0
  141. package/dist/resources/Agent.js +463 -33
  142. package/dist/resources/AgentCard.js +4 -0
  143. package/dist/resources/AgentKeyRegister.js +248 -0
  144. package/dist/resources/AgentKeyRegistration.js +28 -0
  145. package/dist/resources/AgentReadPosition.js +7 -0
  146. package/dist/resources/AgentSeed.js +238 -107
  147. package/dist/resources/AutoPromoteCandidates.js +413 -78
  148. package/dist/resources/Credential.js +183 -10
  149. package/dist/resources/Federation.js +915 -145
  150. package/dist/resources/FederationRetry.js +140 -0
  151. package/dist/resources/InstructionVersion.js +220 -0
  152. package/dist/resources/Integration.js +300 -25
  153. package/dist/resources/MCPClientMetadata.js +6 -3
  154. package/dist/resources/Memory.js +3300 -758
  155. package/dist/resources/MemoryArchive.js +171 -53
  156. package/dist/resources/MemoryBootstrap.js +122 -61
  157. package/dist/resources/MemoryCandidate.js +37 -3
  158. package/dist/resources/MemoryConsolidate.js +2 -2
  159. package/dist/resources/MemoryDedupStats.js +30 -1
  160. package/dist/resources/MemoryFeed.js +545 -50
  161. package/dist/resources/MemoryGrant.js +21 -1
  162. package/dist/resources/MemoryMaintenance.js +368 -46
  163. package/dist/resources/MemoryPurge.js +348 -0
  164. package/dist/resources/MemoryReflect.js +71 -12
  165. package/dist/resources/MemoryReindex.js +111 -17
  166. package/dist/resources/Message.js +16 -5
  167. package/dist/resources/OAuth.js +342 -48
  168. package/dist/resources/OAuthClient.js +1 -1
  169. package/dist/resources/OrgEvent.js +405 -19
  170. package/dist/resources/OrgEventCatchup.js +7 -0
  171. package/dist/resources/OrgEventMaintenance.js +48 -10
  172. package/dist/resources/PairingToken.js +1 -1
  173. package/dist/resources/Presence.js +166 -51
  174. package/dist/resources/PromoteMemoryCandidate.js +24 -7
  175. package/dist/resources/RecordUsage.js +2 -4
  176. package/dist/resources/Relationship.js +23 -0
  177. package/dist/resources/SemanticSearch.js +63 -32
  178. package/dist/resources/Soul.js +191 -76
  179. package/dist/resources/SoulFeed.js +2 -1
  180. package/dist/resources/TeamDirectory.js +35 -0
  181. package/dist/resources/WorkspaceLatest.js +4 -0
  182. package/dist/resources/WorkspaceState.js +21 -1
  183. package/dist/resources/XAA.js +207 -63
  184. package/dist/resources/a2a-stream.js +313 -0
  185. package/dist/resources/a2a-url.js +4 -5
  186. package/dist/resources/agent-admin.js +10 -1
  187. package/dist/resources/agent-auth.js +138 -83
  188. package/dist/resources/agent-read-position-lib.js +4 -1
  189. package/dist/resources/agent-status-guard.js +9 -7
  190. package/dist/resources/auth-middleware.js +534 -171
  191. package/dist/resources/authority-field-guard.js +9 -11
  192. package/dist/resources/auto-promote-lib.js +8 -5
  193. package/dist/resources/basic-auth-header.js +21 -0
  194. package/dist/resources/bm25-index-service.js +4 -5
  195. package/dist/resources/dedup-cluster.js +6 -1
  196. package/dist/resources/ed25519-auth.js +1 -1
  197. package/dist/resources/embedding-space-guard.js +366 -72
  198. package/dist/resources/embeddings-provider.js +25 -0
  199. package/dist/resources/engine-version-stamp-boot.js +53 -0
  200. package/dist/resources/federation-classify.js +161 -0
  201. package/dist/resources/federation-crypto.js +5 -5
  202. package/dist/resources/federation-retry-lib.js +60 -0
  203. package/dist/resources/grant-visibility.js +135 -0
  204. package/dist/resources/harper-routing.js +83 -0
  205. package/dist/resources/health.js +163 -22
  206. package/dist/resources/host-pointer/registry.js +29 -0
  207. package/dist/resources/host-pointer-adapter.js +1 -0
  208. package/dist/resources/host-source-citation.js +49 -0
  209. package/dist/resources/host-source-visibility.js +7 -6
  210. package/dist/resources/in-process.js +24 -22
  211. package/dist/resources/instance-create-lock.js +17 -0
  212. package/dist/resources/instance-identity.js +23 -0
  213. package/dist/resources/instruction-version-record.js +587 -0
  214. package/dist/resources/internal-authority.js +13 -0
  215. package/dist/resources/key-lock.js +3 -3
  216. package/dist/resources/mcp-handler.js +141 -19
  217. package/dist/resources/mcp-oauth-env-guard.js +36 -0
  218. package/dist/resources/mcp-oauth-flag.js +12 -14
  219. package/dist/resources/mcp-oauth.js +450 -56
  220. package/dist/resources/mcp-tool-arguments.js +4 -6
  221. package/dist/resources/mcp-tools.js +187 -40
  222. package/dist/resources/memory-bootstrap-lib.js +5 -15
  223. package/dist/resources/memory-declared-attributes.js +4 -1
  224. package/dist/resources/memory-deletion-history.js +55 -0
  225. package/dist/resources/memory-durability.js +54 -0
  226. package/dist/resources/memory-embed-hash.js +144 -0
  227. package/dist/resources/memory-embedding-value.js +8 -0
  228. package/dist/resources/memory-host-source.js +32 -7
  229. package/dist/resources/memory-id-guard.js +75 -0
  230. package/dist/resources/memory-redaction.js +236 -0
  231. package/dist/resources/memory-reflect-lib.js +1 -1
  232. package/dist/resources/memory-supplied-vector.js +72 -0
  233. package/dist/resources/memory-write-lock.js +489 -0
  234. package/dist/resources/memory-write-response.js +139 -0
  235. package/dist/resources/memory-write-transaction.js +243 -0
  236. package/dist/resources/migration-boot.js +17 -12
  237. package/dist/resources/migrations/boot-progress.js +25 -0
  238. package/dist/resources/migrations/data-dir.js +90 -19
  239. package/dist/resources/migrations/dir-safety.js +61 -3
  240. package/dist/resources/migrations/embedding-stamp.js +462 -82
  241. package/dist/resources/migrations/export.js +1 -0
  242. package/dist/resources/migrations/graph-heal.js +27 -27
  243. package/dist/resources/migrations/ledger.js +5 -2
  244. package/dist/resources/migrations/lock.js +870 -77
  245. package/dist/resources/migrations/progress.js +71 -10
  246. package/dist/resources/migrations/runner.js +212 -18
  247. package/dist/resources/migrations/snapshot.js +1 -0
  248. package/dist/resources/migrations/source-fields.js +5 -5
  249. package/dist/resources/migrations/state.js +36 -1
  250. package/dist/resources/migrations/status.js +2 -13
  251. package/dist/resources/migrations/synthetic-test-migration.js +81 -12
  252. package/dist/resources/migrations/types.js +26 -1
  253. package/dist/resources/migrations/visibility-backfill.js +113 -72
  254. package/dist/resources/oauth-discovery.js +0 -5
  255. package/dist/resources/object-body-guard.js +40 -0
  256. package/dist/resources/org-event-created-at.js +133 -0
  257. package/dist/resources/org-event-reserved.js +92 -0
  258. package/dist/resources/org-event-write-fault.js +19 -0
  259. package/dist/resources/originator-instance.js +39 -7
  260. package/dist/resources/owner-delete-recheck.js +78 -0
  261. package/dist/resources/owner-field-guard.js +39 -5
  262. package/dist/resources/owner-scoped-write-policy.js +256 -0
  263. package/dist/resources/owner-scoped-writes.js +89 -0
  264. package/dist/resources/path-id-rewrite.js +76 -0
  265. package/dist/resources/presence-internal.js +5 -5
  266. package/dist/resources/presence-receipt.js +236 -0
  267. package/dist/resources/promotion-binding.js +43 -0
  268. package/dist/resources/promotion-stamp.js +143 -17
  269. package/dist/resources/protocol-context.js +189 -0
  270. package/dist/resources/record-owner-guard.js +74 -26
  271. package/dist/resources/record-type-kit.js +2 -4
  272. package/dist/resources/record-types.js +1 -1
  273. package/dist/resources/relay-ops.js +78 -6
  274. package/dist/resources/replay-store.js +96 -19
  275. package/dist/resources/request-target.js +163 -0
  276. package/dist/resources/request-transaction.js +46 -1
  277. package/dist/resources/search-readiness.js +4 -1
  278. package/dist/resources/seed-ids.js +9 -0
  279. package/dist/resources/seed-reservation.js +116 -0
  280. package/dist/resources/semantic-retrieval-core.js +27 -15
  281. package/dist/resources/server-row-validation.js +71 -0
  282. package/dist/resources/skill-manifest.js +24 -14
  283. package/dist/resources/skill-subject.js +53 -0
  284. package/dist/resources/skill-version-write.js +789 -0
  285. package/dist/resources/skill-write-fault.js +20 -0
  286. package/dist/resources/skill-write-policy.js +68 -0
  287. package/dist/resources/skill-write.js +67 -7
  288. package/dist/resources/soul-write-policy.js +26 -7
  289. package/dist/resources/table-helpers.js +10 -7
  290. package/dist/resources/table-subscription-policy.js +518 -85
  291. package/dist/resources/table-subscriptions.js +20 -7
  292. package/dist/resources/team-directory.js +248 -0
  293. package/dist/resources/tool-descriptors/index.js +69 -8
  294. package/dist/resources/txn-pause-point.js +235 -0
  295. package/dist/resources/usage-recording.js +186 -70
  296. package/dist/resources/write-back.js +383 -0
  297. package/dist/resources/write-journal-context.js +5 -0
  298. package/dist/resources/write-journal.js +289 -0
  299. package/dist/src/engine-version-contract.js +1 -0
  300. package/dist/src/keystore.js +72 -0
  301. package/dist/src/lib/agent-home-fields.js +132 -0
  302. package/dist/src/lib/agent-id-rule.js +88 -0
  303. package/dist/src/lib/agent-key-register.js +80 -0
  304. package/dist/src/lib/atomic-write.js +256 -0
  305. package/dist/src/lib/credential-status-rule.js +78 -0
  306. package/dist/src/lib/expired-by-agent.js +37 -0
  307. package/dist/src/lib/federation-retry-row.js +101 -0
  308. package/dist/src/lib/flair-agent-role.js +4 -0
  309. package/dist/src/lib/idp-mapping-rule.js +81 -0
  310. package/dist/src/lib/instance-identity-row.js +20 -0
  311. package/dist/src/lib/instruction-event-contract.js +17 -0
  312. package/dist/src/lib/mcp-oauth-env-core.js +133 -0
  313. package/dist/src/lib/memory-attributes.js +4 -0
  314. package/dist/src/lib/memory-id-policy.js +46 -0
  315. package/dist/src/lib/open-live-row.js +20 -0
  316. package/dist/src/lib/principal-status.js +29 -0
  317. package/dist/src/lib/proto-safe-record.js +42 -0
  318. package/dist/src/lib/reembed-server-support.js +66 -0
  319. package/dist/src/lib/scheduler-platform.js +10 -6
  320. package/dist/src/lib/soul-scope-fields.js +26 -0
  321. package/dist/src/lib/systemd-agent-id.js +38 -0
  322. package/dist/src/rem/promote-policy.js +3 -3
  323. package/dist/src/rem/scheduler.js +21 -4
  324. package/docs/access-control.md +164 -54
  325. package/docs/api-reference.md +165 -32
  326. package/docs/auth.md +46 -30
  327. package/docs/bridges.md +11 -0
  328. package/docs/claude-code.md +37 -7
  329. package/docs/deploying-on-fabric.md +178 -0
  330. package/docs/deployment.md +19 -0
  331. package/docs/embedding-in-a-harper-app.md +17 -15
  332. package/docs/entity-vocabulary.md +3 -6
  333. package/docs/federation.md +61 -3
  334. package/docs/hosted-on-fabric.md +43 -36
  335. package/docs/integrations.md +14 -14
  336. package/docs/mcp-clients.md +12 -7
  337. package/docs/n8n.md +17 -11
  338. package/docs/notes/mcp-agent-auth-consumer.md +16 -13
  339. package/docs/notes/mcp-oauth-model2.md +40 -11
  340. package/docs/openclaw.md +1 -1
  341. package/docs/quickstart-fabric.md +4 -4
  342. package/docs/quickstart.md +12 -4
  343. package/docs/releasing.md +25 -19
  344. package/docs/rem.md +32 -3
  345. package/docs/secrets-and-keys.md +21 -4
  346. package/docs/standalone-local.md +30 -2
  347. package/docs/supply-chain-policy.md +34 -16
  348. package/docs/the-team.md +2 -2
  349. package/docs/upgrade.md +46 -6
  350. package/package.json +24 -12
  351. package/schemas/agent-key-registration.graphql +22 -0
  352. package/schemas/agent.graphql +6 -3
  353. package/schemas/federation.graphql +41 -1
  354. package/schemas/memory.graphql +91 -7
  355. package/schemas/oauth.graphql +19 -0
  356. package/schemas/schema.graphql +2 -0
  357. package/templates/bin/flair-rem-nightly.sh.tmpl +7 -1
  358. package/templates/launchd/start-flair-with-admin-pass.sh +188 -10
  359. package/dist/resources/soul-adk-guard.js +0 -68
@@ -207,9 +207,9 @@ export function validateHumanReviewerId(reviewerId) {
207
207
  // lives server-side in resources/auto-promote-lib.ts (decideAutoPromote — the
208
208
  // UNATTENDED path), which IMPORTS these from here. The direction is deliberate
209
209
  // and established in this repo: a server file may import a PURE helper from src/
210
- // (resources/PromoteMemoryCandidate.ts and resources/soul-adk-guard.ts already
211
- // import this very module); it is a CLI file importing FROM resources/ that does
212
- // not survive npm packaging. Defining it here lets the CLI side
210
+ // (resources/PromoteMemoryCandidate.ts already imports this very module); it is
211
+ // a CLI file importing FROM resources/ that does not survive npm packaging.
212
+ // Defining it here lets the CLI side
213
213
  // (src/commands/rem.ts, `flair rem candidates`) and the server gate share ONE
214
214
  // implementation rather than a hand-kept pair.
215
215
  //
@@ -22,10 +22,38 @@
22
22
  * scope here; the operator's agent can only restore its own memories.
23
23
  * Cross-agent restore is a 1.1+ feature.
24
24
  */
25
+ import { encodeRecordId } from "../lib/record-id-path.js";
26
+ import { suppliesSoulScopeFields } from "../lib/soul-scope-fields.js";
27
+ import { ApiHttpError, ApiRequestOutcomeUnknown } from "../lib/auth-resolve.js";
28
+ import { MEMORY_PROVIDER_RETRY_DELAY_MS, apiErrorCode, isProviderTimeoutRefusal, } from "../lib/memory-provider-timeout.js";
25
29
  import { readFileSync, existsSync, rmSync, mkdtempSync } from "node:fs";
26
30
  import { resolve } from "node:path";
27
31
  import { tmpdir } from "node:os";
28
32
  import { extractSnapshot, createSnapshot } from "./snapshot.js";
33
+ function delay(ms) {
34
+ return new Promise((resolve) => setTimeout(resolve, ms));
35
+ }
36
+ /**
37
+ * One line about an unknown-outcome id, from the post-restore read. Present
38
+ * does NOT mean restored: comparing ids alone cannot tell a row this restore
39
+ * wrote from a pre-existing row that already had the id.
40
+ */
41
+ export function formatUnknownState(state) {
42
+ return state.present
43
+ ? `${state.entity} ${state.id}: present in the verification read; an id-only check cannot tell whether this restore wrote the row or it was already present, so its state is unverified`
44
+ : `${state.entity} ${state.id}: absent from the verification read; the deadline fired before a complete response, so whether the write landed is unresolved and its state is unverified`;
45
+ }
46
+ /**
47
+ * The server release that first serves `GET /AdminMemoryCandidates/{agentId}`. This is a server-capability
48
+ * minimum, not a package version, so its name does not end in "version": in the files it scans,
49
+ * check-version-sync treats a declaration whose identifier ends in "version" and holds the target release as
50
+ * a version site the release must bump.
51
+ */
52
+ export const CANDIDATE_LIST_FIRST_SERVER_RELEASE = "0.63.0";
53
+ /** The page size restore asks the admin-only candidate route for. */
54
+ export const CANDIDATE_LIST_LIMIT = 500;
55
+ /** The most candidate-listing pages one restore requests before it refuses. */
56
+ export const CANDIDATE_LIST_MAX_PAGES = 2_000;
29
57
  function asArray(raw) {
30
58
  if (Array.isArray(raw))
31
59
  return raw;
@@ -38,15 +66,136 @@ function asArray(raw) {
38
66
  }
39
67
  return [];
40
68
  }
69
+ /**
70
+ * A live table listing for the pre-restore snapshot. Unlike `asArray`, which
71
+ * reads an unrecognised shape as an empty table, this refuses: an unreadable
72
+ * listing would look empty, so the pre-restore snapshot would miss the live
73
+ * rows, the scope preflight would see no live Souls, and the DELETE and PUT
74
+ * loops would run over a table this run never read (flair#2931).
75
+ */
76
+ export function requireLiveListing(raw, table, agentId) {
77
+ if (Array.isArray(raw))
78
+ return raw;
79
+ if (raw && typeof raw === "object") {
80
+ const obj = raw;
81
+ if (Array.isArray(obj.results))
82
+ return obj.results;
83
+ if (Array.isArray(obj.items))
84
+ return obj.items;
85
+ }
86
+ throw new Error(`live-listing-unreadable: GET /${table}?agentId=${agentId} returned a response that is not a list `
87
+ + `(expected a JSON array, or an object with a "results" or "items" array); `
88
+ + "refusing to restore until the live listing can be read — check the API response and that the agent id is correct.");
89
+ }
41
90
  function soulWrite(opts) {
42
91
  return opts.soulApiCall ?? opts.apiCall;
43
92
  }
44
- async function listAgentCandidates(opsSearch, agentId) {
45
- if (!opsSearch)
46
- return [];
47
- return asArray(await opsSearch("MemoryCandidate", [
48
- { search_attribute: "agentId", search_type: "equals", search_value: agentId },
49
- ], ["id", "claim"]));
93
+ /**
94
+ * Ids of Soul rows a whole-row replay would send that supply a non-empty
95
+ * `scopeTag` or `tags` array. The server refuses each such write (flair#1540),
96
+ * so a restore that deletes before writing one can leave a live row absent and
97
+ * a rollback to the pre-restore snapshot refused (flair#2931). Rows the DELETE
98
+ * and PUT loops skip (no usable id) are not written or deleted, so they are not
99
+ * checked here.
100
+ */
101
+ function refusedSoulReplayIds(rows) {
102
+ const ids = [];
103
+ for (const row of rows) {
104
+ if (!row || typeof row !== "object" || Array.isArray(row) || !row.id)
105
+ continue;
106
+ if (suppliesSoulScopeFields(row))
107
+ ids.push(String(row.id));
108
+ }
109
+ return [...new Set(ids)];
110
+ }
111
+ function isCandidateRoute404(err) {
112
+ return err instanceof ApiHttpError && err.status === 404;
113
+ }
114
+ /** The refusal for a candidate listing restore could not read completely. */
115
+ function incompleteListing(agentId, state, remedy = "") {
116
+ return new Error(`the target's MemoryCandidate listing for agent ${agentId} could not be read completely: ${state}. `
117
+ + `No target rows were deleted or written.${remedy ? ` ${remedy}` : ""}`);
118
+ }
119
+ /**
120
+ * One agent's leftover candidates, read through the `apiCall` restore uses
121
+ * for its Memory reads, deletes and writes, its Soul reads and its
122
+ * MemoryCandidate deletes. Soul deletes and writes use `soulApiCall` when one
123
+ * is given; the CLI binds both calls to the same target. Each candidate object
124
+ * carries only an id; each reply also carries `hasMore`.
125
+ *
126
+ * Pages through the route with `after` set to the last id of the page before,
127
+ * until a page answers `hasMore: false`, and returns only that complete
128
+ * listing. A `hasMore: true` page with no candidates (the cursor cannot move),
129
+ * an id listed twice, or more than {@link CANDIDATE_LIST_MAX_PAGES} pages is
130
+ * refused.
131
+ *
132
+ * Exported for `flair restore --replace`, which lists the agent of each
133
+ * archived Soul row it will write a non-empty value for before any delete, so
134
+ * it can compare that agent's live candidate claims with the values it is
135
+ * about to write.
136
+ */
137
+ export async function listAgentCandidates(apiCall, agentId) {
138
+ const listed = [];
139
+ const seen = new Set();
140
+ let after;
141
+ for (let page = 1; page <= CANDIDATE_LIST_MAX_PAGES; page++) {
142
+ const query = `?limit=${CANDIDATE_LIST_LIMIT}${after === undefined ? "" : `&after=${encodeURIComponent(after)}`}`;
143
+ let body;
144
+ try {
145
+ body = await apiCall("GET", `/AdminMemoryCandidates/${encodeURIComponent(agentId)}${query}`);
146
+ }
147
+ catch (err) {
148
+ // Only this GET's 404 gets the candidate-route 404 guidance.
149
+ if (isCandidateRoute404(err))
150
+ throw new Error(candidateRoute404Guidance(err));
151
+ if (err instanceof ApiHttpError && apiErrorCode(err) === "candidate_id_unusable") {
152
+ throw incompleteListing(agentId, "GET /AdminMemoryCandidates answered candidate_id_unusable (a row has no usable id)", "Remove or repair that agent's MemoryCandidate row without a usable id on the target, then retry.");
153
+ }
154
+ throw incompleteListing(agentId, `GET /AdminMemoryCandidates failed: ${err?.message ?? String(err)}`);
155
+ }
156
+ const defect = candidateListDefect(body);
157
+ if (defect) {
158
+ throw incompleteListing(agentId, `GET /AdminMemoryCandidates returned an unexpected response shape: ${defect}`);
159
+ }
160
+ for (const entry of body.candidates) {
161
+ if (seen.has(entry.id)) {
162
+ throw incompleteListing(agentId, `GET /AdminMemoryCandidates listed candidate id ${entry.id} twice (candidate_id_repeated)`);
163
+ }
164
+ seen.add(entry.id);
165
+ listed.push({ id: entry.id });
166
+ }
167
+ if (body.hasMore === false)
168
+ return listed;
169
+ // A page that repeats the cursor's own id is refused above as a repeated id.
170
+ const last = body.candidates.at(-1)?.id;
171
+ if (last === undefined) {
172
+ throw incompleteListing(agentId, `page ${page} of GET /AdminMemoryCandidates answered hasMore: true with no candidates, so the cursor cannot move past ${after === undefined ? "the start" : after} (candidate_cursor_not_advancing)`);
173
+ }
174
+ after = last;
175
+ }
176
+ throw incompleteListing(agentId, `GET /AdminMemoryCandidates still answered hasMore: true after ${CANDIDATE_LIST_MAX_PAGES} pages of ${CANDIDATE_LIST_LIMIT}, the most restore requests (candidate_listing_page_limit)`);
177
+ }
178
+ /** The first required field a candidate-route body lacks or mistypes, or null when `candidates` and `hasMore` check out. */
179
+ function candidateListDefect(body) {
180
+ if (!body || typeof body !== "object" || Array.isArray(body))
181
+ return "the body is not an object";
182
+ if (!Array.isArray(body.candidates))
183
+ return "candidates is not an array";
184
+ for (const [i, entry] of body.candidates.entries()) {
185
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
186
+ return `candidates[${i}] is not an object`;
187
+ if (typeof entry.id !== "string" || entry.id.length === 0)
188
+ return `candidates[${i}].id is not a non-empty string`;
189
+ }
190
+ if (typeof body.hasMore !== "boolean")
191
+ return "hasMore is missing or not a boolean";
192
+ return null;
193
+ }
194
+ /** The candidate-route 404 guidance: the operator message when GET /AdminMemoryCandidates answers 404. */
195
+ function candidateRoute404Guidance(err) {
196
+ return `restore lists leftover MemoryCandidate rows through GET /AdminMemoryCandidates on the restore target, and the target answered HTTP ${err.status}. `
197
+ + `That route is part of Flair server ${CANDIDATE_LIST_FIRST_SERVER_RELEASE}; if the target runs an older server, upgrade it to ${CANDIDATE_LIST_FIRST_SERVER_RELEASE} or newer, then retry. `
198
+ + "No target rows were deleted or written.";
50
199
  }
51
200
  function parseJsonlSafe(text) {
52
201
  if (!text.trim())
@@ -65,12 +214,15 @@ function parseJsonlSafe(text) {
65
214
  * 3. Verify metadata.agentId matches opts.agentId (prevents accidental
66
215
  * cross-agent restore — the file might have been hand-copied).
67
216
  * 4. Create a pre-restore snapshot of current state (skip in dry-run).
217
+ * 4b. Refuse before any delete when a snapshot Soul row or a live Soul row
218
+ * captured in the pre-restore snapshot supplies scope fields (flair#2931).
68
219
  * 5. Fetch + delete current memories/souls/candidates for the agent (skip in dry-run).
69
220
  * 6. PUT snapshot souls, then memories (skip in dry-run).
70
221
  * 7. Return counts.
71
222
  *
72
223
  * On any error after step 4: the result reports `status: "failed"` with
73
- * the pre-restore snapshot path included so the operator can roll back.
224
+ * the pre-restore snapshot path included so the operator can roll back. If any
225
+ * write's outcome is unknown, the status is `unresolved` instead.
74
226
  */
75
227
  export async function applySnapshot(opts) {
76
228
  const errors = [];
@@ -80,8 +232,17 @@ export async function applySnapshot(opts) {
80
232
  snapshotPath: opts.snapshotPath,
81
233
  deleted: { memories: 0, souls: 0, candidates: 0 },
82
234
  restored: { memories: 0, souls: 0 },
235
+ retried: { memories: [] },
236
+ unknown: { memories: [], souls: [], candidates: [] },
237
+ skippedAfterUnknownDelete: { memories: [], souls: [] },
83
238
  errors,
84
239
  };
240
+ if (!opts.dryRun && opts.listCandidates === false) {
241
+ errors.push("listCandidates: false is accepted only with dryRun: a live restore lists leftover MemoryCandidate rows before any delete. "
242
+ + "No request was sent to the target.");
243
+ result.status = "failed";
244
+ return result;
245
+ }
85
246
  if (!existsSync(opts.snapshotPath)) {
86
247
  errors.push(`snapshot does not exist: ${opts.snapshotPath}`);
87
248
  result.status = "failed";
@@ -140,7 +301,9 @@ export async function applySnapshot(opts) {
140
301
  try {
141
302
  const currentMem = asArray(await opts.apiCall("GET", `/Memory?agentId=${encodeURIComponent(opts.agentId)}`));
142
303
  const currentSouls = asArray(await opts.apiCall("GET", `/Soul?agentId=${encodeURIComponent(opts.agentId)}`));
143
- const currentCandidates = await listAgentCandidates(opts.opsSearch, opts.agentId);
304
+ const currentCandidates = opts.listCandidates === false
305
+ ? []
306
+ : await listAgentCandidates(opts.apiCall, opts.agentId);
144
307
  result.deleted.memories = currentMem.length;
145
308
  result.deleted.souls = currentSouls.length;
146
309
  result.deleted.candidates = currentCandidates.length;
@@ -159,14 +322,14 @@ export async function applySnapshot(opts) {
159
322
  let currentMem;
160
323
  let currentSouls;
161
324
  try {
162
- currentMem = asArray(await opts.apiCall("GET", `/Memory?agentId=${encodeURIComponent(opts.agentId)}`));
163
- currentSouls = asArray(await opts.apiCall("GET", `/Soul?agentId=${encodeURIComponent(opts.agentId)}`));
325
+ currentMem = requireLiveListing(await opts.apiCall("GET", `/Memory?agentId=${encodeURIComponent(opts.agentId)}`), "Memory", opts.agentId);
326
+ currentSouls = requireLiveListing(await opts.apiCall("GET", `/Soul?agentId=${encodeURIComponent(opts.agentId)}`), "Soul", opts.agentId);
164
327
  const preRestore = await createSnapshot({
165
328
  agentId: opts.agentId,
166
329
  flairVersion: opts.flairVersion,
167
330
  memories: currentMem,
168
331
  soul: currentSouls.length === 1 ? currentSouls[0] : currentSouls.length > 1 ? currentSouls : null,
169
- pendingCandidateCount: 0, // not load-bearing at restore time
332
+ pendingCandidateCount: null, // not counted at restore time (flair#2680)
170
333
  rootOverride: opts.preRestoreSnapshotRoot,
171
334
  runId: `rem-restore-pre-${(opts.nowOverride ?? new Date()).toISOString().replace(/[:.]/g, "-")}`,
172
335
  nowOverride: opts.nowOverride,
@@ -179,46 +342,112 @@ export async function applySnapshot(opts) {
179
342
  rmSync(tmp, { recursive: true, force: true });
180
343
  return result;
181
344
  }
345
+ // 4b. Scope-field preflight (flair#2931), before any DELETE: refuse when a
346
+ // snapshot Soul row this run would PUT, or a live Soul row captured in the
347
+ // pre-restore snapshot, supplies a non-empty `scopeTag` or `tags` array.
348
+ // The server refuses that write, so the replay cannot restore the row. When
349
+ // the row is live, deleting it first also makes the pre-restore rollback
350
+ // refuse it. Merge mode does not exist here; this restore always replaces
351
+ // the agent's rows.
352
+ const snapshotRefusedSouls = new Set(refusedSoulReplayIds(souls));
353
+ const liveRefusedSouls = new Set(refusedSoulReplayIds(currentSouls));
354
+ const refusedSouls = [...new Set([...snapshotRefusedSouls, ...liveRefusedSouls])];
355
+ if (refusedSouls.length > 0) {
356
+ for (const id of refusedSouls) {
357
+ const inSnapshot = snapshotRefusedSouls.has(id);
358
+ const inLive = liveRefusedSouls.has(id);
359
+ const source = inSnapshot && inLive
360
+ ? "in the snapshot row and the live row"
361
+ : inSnapshot ? "in the snapshot row" : "in the live row";
362
+ const remedies = [];
363
+ if (inSnapshot)
364
+ remedies.push("Restore from a different snapshot, or edit that row in the snapshot file, then re-run.");
365
+ if (inLive) {
366
+ remedies.push(inSnapshot
367
+ ? "Clear tags/scopeTag on the live row (PATCH) or delete it, then re-run."
368
+ : "Clear tags/scopeTag on that row (PATCH) or delete it, then re-run.");
369
+ }
370
+ errors.push(`soul-scope-preflight: Soul ${id} supplies a non-empty scopeTag or tags array ${source}, `
371
+ + `which the Soul scope-field rule refuses; no target rows were deleted or written. ${remedies.join(" ")}`);
372
+ }
373
+ result.status = "failed";
374
+ rmSync(tmp, { recursive: true, force: true });
375
+ return result;
376
+ }
182
377
  // 5. Delete current memories, souls, and leftover candidates. Candidates
183
378
  // are not in the snapshot, but refuseLearnedSoulWrite matches claim text,
184
- // so a leftover row 403s Soul PUT after operator auth succeeds.
185
- let currentCandidates = [];
379
+ // so a leftover row 403s Soul PUT after operator auth succeeds. A failed
380
+ // candidate listing stops the restore before any delete.
381
+ let currentCandidates;
186
382
  try {
187
- currentCandidates = await listAgentCandidates(opts.opsSearch, opts.agentId);
383
+ currentCandidates = await listAgentCandidates(opts.apiCall, opts.agentId);
188
384
  }
189
385
  catch (err) {
190
386
  errors.push(`fetch-candidates: ${err?.message ?? String(err)}`);
387
+ result.status = "failed";
388
+ rmSync(tmp, { recursive: true, force: true });
389
+ return result;
191
390
  }
391
+ // Ids whose write outcome is unknown, per table. Once a table and record id
392
+ // appears here, no later write to that same table and record id in this run
393
+ // is sent: a late write could land after the restored row.
394
+ const unknownMemoryWrites = new Set();
395
+ const unknownSoulWrites = new Set();
396
+ const unknownCandidateWrites = new Set();
192
397
  for (const m of currentMem) {
193
398
  if (!m?.id)
194
399
  continue;
400
+ const id = String(m.id);
401
+ if (unknownMemoryWrites.has(id))
402
+ continue;
195
403
  try {
196
- await opts.apiCall("DELETE", `/Memory/${encodeURIComponent(String(m.id))}`);
404
+ await opts.apiCall("DELETE", `/Memory/${encodeRecordId(id)}`);
197
405
  result.deleted.memories++;
198
406
  }
199
407
  catch (err) {
408
+ if (err instanceof ApiRequestOutcomeUnknown) {
409
+ result.unknown.memories.push(id);
410
+ unknownMemoryWrites.add(id);
411
+ continue;
412
+ }
200
413
  errors.push(`delete-memory ${m.id}: ${err?.message ?? String(err)}`);
201
414
  }
202
415
  }
203
416
  for (const s of currentSouls) {
204
417
  if (!s?.id)
205
418
  continue;
419
+ const id = String(s.id);
420
+ if (unknownSoulWrites.has(id))
421
+ continue;
206
422
  try {
207
- await soulWrite(opts)("DELETE", `/Soul/${encodeURIComponent(String(s.id))}`);
423
+ await soulWrite(opts)("DELETE", `/Soul/${encodeRecordId(id)}`);
208
424
  result.deleted.souls++;
209
425
  }
210
426
  catch (err) {
427
+ if (err instanceof ApiRequestOutcomeUnknown) {
428
+ result.unknown.souls.push(id);
429
+ unknownSoulWrites.add(id);
430
+ continue;
431
+ }
211
432
  errors.push(`delete-soul ${s.id}: ${err?.message ?? String(err)}`);
212
433
  }
213
434
  }
214
435
  for (const c of currentCandidates) {
215
436
  if (!c?.id)
216
437
  continue;
438
+ const id = String(c.id);
439
+ if (unknownCandidateWrites.has(id))
440
+ continue;
217
441
  try {
218
- await opts.apiCall("DELETE", `/MemoryCandidate/${encodeURIComponent(String(c.id))}`);
442
+ await opts.apiCall("DELETE", `/MemoryCandidate/${encodeRecordId(id)}`);
219
443
  result.deleted.candidates++;
220
444
  }
221
445
  catch (err) {
446
+ if (err instanceof ApiRequestOutcomeUnknown) {
447
+ result.unknown.candidates.push(id);
448
+ unknownCandidateWrites.add(id);
449
+ continue;
450
+ }
222
451
  errors.push(`delete-candidate ${c.id}: ${err?.message ?? String(err)}`);
223
452
  }
224
453
  }
@@ -228,30 +457,70 @@ export async function applySnapshot(opts) {
228
457
  for (const s of souls) {
229
458
  if (!s?.id)
230
459
  continue;
460
+ const id = String(s.id);
461
+ if (unknownSoulWrites.has(id)) {
462
+ result.skippedAfterUnknownDelete.souls.push(id);
463
+ continue;
464
+ }
231
465
  try {
232
- await soulWrite(opts)("PUT", `/Soul/${encodeURIComponent(String(s.id))}`, s);
466
+ await soulWrite(opts)("PUT", `/Soul/${encodeRecordId(id)}`, s);
233
467
  result.restored.souls++;
234
468
  }
235
469
  catch (err) {
470
+ if (err instanceof ApiRequestOutcomeUnknown) {
471
+ result.unknown.souls.push(id);
472
+ unknownSoulWrites.add(id);
473
+ continue;
474
+ }
236
475
  errors.push(`put-soul ${s.id}: ${err?.message ?? String(err)}`);
237
476
  }
238
477
  }
239
478
  for (const m of memories) {
240
479
  if (!m?.id)
241
480
  continue;
481
+ const id = String(m.id);
482
+ if (unknownMemoryWrites.has(id)) {
483
+ result.skippedAfterUnknownDelete.memories.push(id);
484
+ continue;
485
+ }
242
486
  try {
243
- await opts.apiCall("PUT", `/Memory/${encodeURIComponent(String(m.id))}`, m);
487
+ try {
488
+ await opts.apiCall("PUT", `/Memory/${encodeRecordId(id)}`, m);
489
+ }
490
+ catch (err) {
491
+ // A write whose outcome is unknown may have committed, so it is
492
+ // recorded as unknown by the outer catch and never replayed.
493
+ if (err instanceof ApiRequestOutcomeUnknown)
494
+ throw err;
495
+ // The write-lock contract states a provider-bound refusal wrote
496
+ // nothing, so replaying this one PUT cannot double-write the row.
497
+ if (!isProviderTimeoutRefusal(err))
498
+ throw err;
499
+ result.retried.memories.push(id);
500
+ await delay(MEMORY_PROVIDER_RETRY_DELAY_MS);
501
+ // No client-side timer here: a request abandoned at a client deadline
502
+ // could still commit after this row was recorded failed. The whole
503
+ // request now carries the shared deadline, and its expiry is an
504
+ // ApiRequestOutcomeUnknown recorded as unknown by the outer catch.
505
+ await opts.apiCall("PUT", `/Memory/${encodeRecordId(id)}`, m);
506
+ }
244
507
  result.restored.memories++;
245
508
  }
246
509
  catch (err) {
247
- errors.push(`put-memory ${m.id}: ${err?.message ?? String(err)}`);
510
+ if (err instanceof ApiRequestOutcomeUnknown) {
511
+ result.unknown.memories.push(id);
512
+ unknownMemoryWrites.add(id);
513
+ continue;
514
+ }
515
+ errors.push(`put-memory ${id}: ${err?.message ?? String(err)}`);
248
516
  }
249
517
  }
250
518
  // 7. Verify post-restore state (default on; opt-out via verifyPostRestore=false).
251
- // Catches silent failures: Harper schema coercion, 4xx responses the
252
- // apiCall layer masked as ok, partial-DELETE leftovers. Per-ID diff,
253
- // not just counts — count parity can hide simultaneous PUT+DELETE
254
- // failures that wash out numerically.
519
+ // Compares Memory and Soul ids only; candidates are not read back. When
520
+ // both reads succeed, it reports snapshot ids missing from the agent's rows
521
+ // and ids present that the snapshot does not hold; row content is not
522
+ // compared. Per-ID diff, not just counts — count parity can hide
523
+ // simultaneous PUT+DELETE failures that wash out numerically.
255
524
  if (opts.verifyPostRestore !== false) {
256
525
  try {
257
526
  const verifyMem = asArray(await opts.apiCall("GET", `/Memory?agentId=${encodeURIComponent(opts.agentId)}`));
@@ -264,10 +533,14 @@ export async function applySnapshot(opts) {
264
533
  const expSoul = new Set(expectedSoulIds);
265
534
  const actMem = new Set(actualMemoryIds);
266
535
  const actSoul = new Set(actualSoulIds);
267
- const missingMemoryIds = [...expMem].filter((id) => !actMem.has(id));
268
- const missingSoulIds = [...expSoul].filter((id) => !actSoul.has(id));
536
+ const missingMemoryIds = [...expMem].filter((id) => !actMem.has(id) && !result.unknown.memories.includes(id));
537
+ const missingSoulIds = [...expSoul].filter((id) => !actSoul.has(id) && !result.unknown.souls.includes(id));
269
538
  const extraMemoryIds = [...actMem].filter((id) => !expMem.has(id));
270
539
  const extraSoulIds = [...actSoul].filter((id) => !expSoul.has(id));
540
+ const unknownStates = [
541
+ ...result.unknown.memories.map((id) => ({ entity: "memory", id, present: actMem.has(id) })),
542
+ ...result.unknown.souls.map((id) => ({ entity: "soul", id, present: actSoul.has(id) })),
543
+ ];
271
544
  result.verified = {
272
545
  expectedMemoryIds,
273
546
  expectedSoulIds,
@@ -277,6 +550,7 @@ export async function applySnapshot(opts) {
277
550
  missingSoulIds,
278
551
  extraMemoryIds,
279
552
  extraSoulIds,
553
+ unknownStates,
280
554
  };
281
555
  if (missingMemoryIds.length > 0) {
282
556
  errors.push(`post-restore-verify: ${missingMemoryIds.length} memory rows missing (e.g. ${missingMemoryIds.slice(0, 3).join(", ")})`);
@@ -299,5 +573,8 @@ export async function applySnapshot(opts) {
299
573
  if (errors.length > 0) {
300
574
  result.status = "failed";
301
575
  }
576
+ if (result.unknown.memories.length > 0 || result.unknown.souls.length > 0 || result.unknown.candidates.length > 0) {
577
+ result.status = "unresolved";
578
+ }
302
579
  return result;
303
580
  }