@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
@@ -0,0 +1,347 @@
1
+ /** Memory id and tier-count checks around a planned cluster operation. */
2
+ import { chmodSync, mkdirSync, readFileSync, renameSync, rmSync, lstatSync, writeFileSync } from "node:fs";
3
+ import { dirname, join } from "node:path";
4
+ import { randomBytes } from "node:crypto";
5
+ import { ALL_TIERS, normalizeTier, tallyByDurability } from "./lib/memory-integrity.js";
6
+ export const CHECKPOINT_VERSION = 1;
7
+ /** Written 0600 (flair#2218): ids + tier counts are operator-held, not world-readable. */
8
+ export const CHECKPOINT_MODE = 0o600;
9
+ export const CHECKPOINT_FILENAME = "memory-id-checkpoint.json";
10
+ /** Rows requested per operations-API page. */
11
+ export const MEMORY_PAGE_SIZE = 10_000;
12
+ /** Hard page-walk bound. */
13
+ export const MAX_MEMORY_PAGES = 100;
14
+ /** Per-request timeout for the admin read. Every operation is bounded. */
15
+ export const OPS_READ_TIMEOUT_MS = 30_000;
16
+ /** How many missing ids the failure report names. */
17
+ export const MISSING_SAMPLE_LIMIT = 10;
18
+ /** A read inconsistent with the exact count of the same range: a duplicate id or a size that differs. */
19
+ export class InconsistentReadError extends Error {
20
+ }
21
+ /** The default checkpoint file is under ~/.flair/. */
22
+ export function checkpointPath(home) {
23
+ return join(home, ".flair", CHECKPOINT_FILENAME);
24
+ }
25
+ /** Build a Basic-auth operations caller; omit response bodies from errors. */
26
+ export function buildOpsPost(target, user, password, timeoutMs = OPS_READ_TIMEOUT_MS) {
27
+ const base = `${target.replace(/\/+$/, "")}/`;
28
+ const headers = { "Content-Type": "application/json" };
29
+ if (user && password) {
30
+ headers.Authorization = `Basic ${Buffer.from(`${user}:${password}`).toString("base64")}`;
31
+ }
32
+ return async (body) => {
33
+ const res = await fetch(base, {
34
+ method: "POST",
35
+ headers,
36
+ body: JSON.stringify(body),
37
+ signal: AbortSignal.timeout(timeoutMs),
38
+ });
39
+ if (!res.ok)
40
+ throw new Error(`operations API read returned HTTP ${res.status}`);
41
+ return (await res.json());
42
+ };
43
+ }
44
+ function asRows(body) {
45
+ if (Array.isArray(body))
46
+ return body;
47
+ const results = body?.results;
48
+ return Array.isArray(results) ? results : null;
49
+ }
50
+ function asTime(value) {
51
+ return typeof value === "string" && value.length > 0 ? value : null;
52
+ }
53
+ /**
54
+ * Walk `flair.<table>` by primary key: `SELECT <select> ... [WHERE <filter> AND] id > cursor
55
+ * ORDER BY id LIMIT <pageSize>`, resuming strictly after the last id read. A duplicate id
56
+ * across pages, or a read that differs in size from `expected`, refuses. A full final page at
57
+ * the cap is accepted when a read after its last id returns no row and the rows read equal
58
+ * `expected`, the same evidence an uncapped walk ends on. The page allowance is
59
+ * `ceil(expected / pageSize) + 1`, capped by `maxPages`
60
+ * (default MAX_MEMORY_PAGES). Duplicates raise InconsistentReadError. Outside the cap branch a
61
+ * size mismatch raises InconsistentReadError by default, but `mismatch` can return any Error;
62
+ * a mismatch on a full final page at the cap raises the page-cap error. Errors from `opsPost`
63
+ * propagate unchanged.
64
+ */
65
+ export async function readTableByIdPaged(opsPost, opts) {
66
+ const pageSize = opts.pageSize ?? MEMORY_PAGE_SIZE;
67
+ const maxPages = opts.maxPages ?? MAX_MEMORY_PAGES;
68
+ if (!Number.isSafeInteger(pageSize) || pageSize < 1 || !Number.isSafeInteger(maxPages) || maxPages < 1) {
69
+ throw new Error("invalid keyset paging bounds");
70
+ }
71
+ // The allowance is the pages the expected count needs plus one, or the caller's hard cap
72
+ // when that is smaller; the request count never follows a server-reported value without
73
+ // a bound.
74
+ const pageAllowance = Math.min(maxPages, Math.ceil(opts.expected / pageSize) + 1);
75
+ const mismatch = opts.mismatch ?? ((expected, read) => new InconsistentReadError(`${opts.table}: server reports ${expected} rows, integrity read ${read}`));
76
+ const rows = [];
77
+ let lastId;
78
+ const seen = new Set();
79
+ for (let page = 0; page < pageAllowance; page++) {
80
+ if (lastId?.includes("\\"))
81
+ throw new Error(`${opts.table} cursor contains an unsupported backslash`);
82
+ const where = [];
83
+ if (opts.filter)
84
+ where.push(`(${opts.filter})`);
85
+ if (lastId !== undefined)
86
+ where.push(`id > '${lastId.replace(/'/g, "''")}'`);
87
+ const clause = where.length > 0 ? ` WHERE ${where.join(" AND ")}` : "";
88
+ const body = await opsPost({
89
+ operation: "sql",
90
+ sql: `SELECT ${opts.select} FROM flair.${opts.table}${clause} ORDER BY id LIMIT ${pageSize}`,
91
+ });
92
+ const batch = asRows(body);
93
+ if (batch === null)
94
+ throw new Error(`${opts.table} search returned a body that is neither a row array nor { results: [...] }`);
95
+ for (const r of batch) {
96
+ if (!r || typeof r.id !== "string" || r.id.length === 0) {
97
+ throw new Error(`${opts.table} search returned a row without a usable id`);
98
+ }
99
+ if (seen.has(r.id))
100
+ throw new InconsistentReadError(`${opts.table} search returned duplicate id ${r.id} across pages`);
101
+ seen.add(r.id);
102
+ lastId = r.id;
103
+ rows.push(r);
104
+ }
105
+ if (batch.length < pageSize)
106
+ break;
107
+ if (page === pageAllowance - 1) {
108
+ if (lastId?.includes("\\"))
109
+ throw new Error(`${opts.table} cursor contains an unsupported backslash`);
110
+ const probeWhere = opts.filter ? `(${opts.filter}) AND ` : "";
111
+ const probe = asRows(await opsPost({
112
+ operation: "sql",
113
+ sql: `SELECT id FROM flair.${opts.table} WHERE ${probeWhere}id > '${lastId.replace(/'/g, "''")}' ORDER BY id LIMIT 1`,
114
+ }));
115
+ if (probe?.length === 0 && rows.length === opts.expected)
116
+ break;
117
+ throw new Error(`${opts.table} read reached the ${pageAllowance}-page cap`);
118
+ }
119
+ }
120
+ if (rows.length !== opts.expected)
121
+ throw mismatch(opts.expected, rows.length);
122
+ return rows;
123
+ }
124
+ /** Read id and durability (and, when asked, the stored row timestamps) in primary-key order. */
125
+ export async function readMemoryRowsPaged(opsPost, opts = {}) {
126
+ const withWriteTimes = opts.withWriteTimes ?? false;
127
+ const expected = opts.expected ?? await readMemoryRowCount(opsPost);
128
+ const raw = await readTableByIdPaged(opsPost, {
129
+ table: "Memory",
130
+ select: withWriteTimes ? "id, durability, createdAt, updatedAt" : "id, durability",
131
+ expected,
132
+ pageSize: opts.pageSize,
133
+ maxPages: opts.maxPages,
134
+ mismatch: () => new InconsistentReadError("writes during checkpoint"),
135
+ });
136
+ const after = await readMemoryRowCount(opsPost);
137
+ if (after !== expected) {
138
+ throw new InconsistentReadError("writes during checkpoint");
139
+ }
140
+ return raw.map((r) => withWriteTimes
141
+ ? { id: r.id, durability: typeof r.durability === "string" ? r.durability : "standard", createdAt: asTime(r.createdAt), updatedAt: asTime(r.updatedAt) }
142
+ : { id: r.id, durability: typeof r.durability === "string" ? r.durability : "standard" });
143
+ }
144
+ /** The instance's own exact Memory row count (describe_table, exact_count). */
145
+ export async function readMemoryRowCount(opsPost) {
146
+ const body = (await opsPost({ operation: "describe_table", database: "flair", table: "Memory", exact_count: true }));
147
+ const n = body?.record_count;
148
+ if (!Number.isSafeInteger(n) || n < 0) {
149
+ throw new Error("Memory row count via the operations API: response carried no record_count");
150
+ }
151
+ return n;
152
+ }
153
+ // ─── Build / compare ────────────────────────────────────────────────────────
154
+ /** Reduce a row set to a checkpoint (sorted ids, tier counts, origin, time). */
155
+ export function buildCheckpoint(input) {
156
+ const node = normalizeOrigin(input.node);
157
+ const host = new URL(node).host;
158
+ const ids = input.rows.map((r) => r.id).slice().sort();
159
+ return {
160
+ version: CHECKPOINT_VERSION,
161
+ node,
162
+ host,
163
+ at: input.at,
164
+ ids,
165
+ byDurability: tallyByDurability(input.rows),
166
+ };
167
+ }
168
+ export function normalizeOrigin(value) {
169
+ const url = new URL(value);
170
+ if (!["http:", "https:"].includes(url.protocol) || url.username || url.password) {
171
+ throw new Error("node must be an HTTP(S) origin without credentials");
172
+ }
173
+ return url.origin;
174
+ }
175
+ /** Documented exit codes for `flair memory verify --help`. */
176
+ export const VERIFY_EXIT_CODES = {
177
+ verified: 0,
178
+ "integrity-failure": 2,
179
+ unknown: 3,
180
+ };
181
+ /** UNKNOWN — a check that could not be made is never verified. */
182
+ export function unknownVerify(reason) {
183
+ return { outcome: "unknown", reason, totalRows: 0, missing: [], tierDrops: [], detail: `unknown — ${reason}` };
184
+ }
185
+ /**
186
+ * Compare the live rows against the checkpoint.
187
+ *
188
+ * - a checkpointed id that is gone → integrity failure;
189
+ * - a durability-tier count that dropped → integrity failure;
190
+ * - ids present with no tier-count drop → verified (new ids are fine).
191
+ */
192
+ export function compareCheckpoint(checkpoint, rows) {
193
+ const present = new Set(rows.map((r) => r.id));
194
+ const missing = checkpoint.ids.filter((id) => !present.has(id)).sort();
195
+ const counts = tallyByDurability(rows);
196
+ const tierDrops = [];
197
+ for (const tier of ALL_TIERS) {
198
+ const dropped = (checkpoint.byDurability[tier] ?? 0) - counts[tier];
199
+ if (dropped > 0)
200
+ tierDrops.push({ tier, dropped });
201
+ }
202
+ if (missing.length > 0 || tierDrops.length > 0) {
203
+ const parts = [];
204
+ if (missing.length > 0) {
205
+ const sample = missing.slice(0, MISSING_SAMPLE_LIMIT);
206
+ parts.push(`${missing.length} of ${checkpoint.ids.length} checkpointed Memory id(s) missing` +
207
+ ` (sample: ${sample.join(", ")}${missing.length > sample.length ? ", …" : ""})`);
208
+ }
209
+ for (const d of tierDrops)
210
+ parts.push(`${d.tier} tier dropped by ${d.dropped}`);
211
+ return {
212
+ outcome: "integrity-failure",
213
+ totalRows: rows.length,
214
+ missing,
215
+ tierDrops,
216
+ detail: `INTEGRITY FAILURE — ${parts.join("; ")}`,
217
+ };
218
+ }
219
+ return {
220
+ outcome: "verified",
221
+ totalRows: rows.length,
222
+ missing: [],
223
+ tierDrops: [],
224
+ detail: `verified — all ${checkpoint.ids.length} checkpointed Memory id(s) present; no tier-count drop; counts: ${ALL_TIERS.map((t) => `${t} ${counts[t]}`).join(", ")}`,
225
+ };
226
+ }
227
+ /** Normalise a raw row's durability, exposed for callers that build rows themselves. */
228
+ export { normalizeTier };
229
+ /**
230
+ * Read a checkpoint. A missing file is `absent`; a present-but-unreadable or
231
+ * malformed file is `unreadable` — UNKNOWN, never treated as "no checkpoint".
232
+ */
233
+ export function readCheckpointFile(path) {
234
+ try {
235
+ lstatSync(path);
236
+ }
237
+ catch (err) {
238
+ if (err.code === "ENOENT")
239
+ return { kind: "absent" };
240
+ return { kind: "unreadable", reason: err instanceof Error ? err.message : String(err) };
241
+ }
242
+ let raw;
243
+ try {
244
+ raw = readFileSync(path, "utf-8");
245
+ }
246
+ catch (err) {
247
+ return { kind: "unreadable", reason: err instanceof Error ? err.message : String(err) };
248
+ }
249
+ try {
250
+ const parsed = JSON.parse(raw);
251
+ if (!parsed || parsed.version !== CHECKPOINT_VERSION ||
252
+ typeof parsed.node !== "string" || parsed.node.length === 0 ||
253
+ typeof parsed.host !== "string" || parsed.host.length === 0 ||
254
+ typeof parsed.at !== "string" || parsed.at.length === 0 ||
255
+ !Array.isArray(parsed.ids) || !parsed.ids.every((id) => typeof id === "string" && id.length > 0) ||
256
+ !parsed.byDurability || !ALL_TIERS.every((t) => Number.isSafeInteger(parsed.byDurability[t]) && parsed.byDurability[t] >= 0)) {
257
+ return { kind: "unreadable", reason: "checkpoint is not a version-1 memory id checkpoint" };
258
+ }
259
+ const node = normalizeOrigin(parsed.node);
260
+ if (new URL(node).host !== parsed.host) {
261
+ return { kind: "unreadable", reason: "checkpoint host does not match its origin" };
262
+ }
263
+ // Built from the validated fields only: a key the file adds beyond the
264
+ // version-1 shape is not carried into the checkpoint.
265
+ const byDurability = Object.create(null);
266
+ for (const t of ALL_TIERS)
267
+ byDurability[t] = parsed.byDurability[t];
268
+ const checkpoint = Object.create(null);
269
+ checkpoint.version = CHECKPOINT_VERSION;
270
+ checkpoint.node = node;
271
+ checkpoint.host = parsed.host;
272
+ checkpoint.at = parsed.at;
273
+ checkpoint.ids = [...parsed.ids];
274
+ checkpoint.byDurability = byDurability;
275
+ return { kind: "ok", checkpoint };
276
+ }
277
+ catch {
278
+ return { kind: "unreadable", reason: "checkpoint is not valid JSON or has an invalid origin" };
279
+ }
280
+ }
281
+ /**
282
+ * Write the checkpoint atomically: a 0600 temp file beside it, then rename. A
283
+ * failure throws — the caller never claims a checkpoint landed.
284
+ */
285
+ export function writeCheckpointFile(path, checkpoint) {
286
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
287
+ const tmp = `${path}.tmp-${process.pid}-${randomBytes(6).toString("hex")}`;
288
+ try {
289
+ writeFileSync(tmp, `${JSON.stringify(checkpoint)}\n`, { mode: CHECKPOINT_MODE });
290
+ chmodSync(tmp, CHECKPOINT_MODE);
291
+ renameSync(tmp, path);
292
+ }
293
+ catch (err) {
294
+ try {
295
+ rmSync(tmp, { force: true });
296
+ }
297
+ catch { /* best effort */ }
298
+ throw err;
299
+ }
300
+ }
301
+ /**
302
+ * Read the live instance and compare it against the checkpoint. Any read
303
+ * failure (unreachable instance, a page, or a short read) is UNKNOWN.
304
+ * The walk shares the reader's no-snapshot limit (see integrityReader in
305
+ * src/commands/integrity.ts), so a balanced concurrent write can leave a `verified`
306
+ * result that no single instant matched; #2679 tracks a consistent read.
307
+ */
308
+ export async function verifyCheckpoint(opts) {
309
+ try {
310
+ const target = normalizeOrigin(opts.opsTarget ?? opts.target);
311
+ const node = normalizeOrigin(opts.checkpoint.node);
312
+ if (target !== node) {
313
+ return unknownVerify(`checkpoint was taken from node ${node} but this target is ${target} — refusing to compare across origins`);
314
+ }
315
+ const opsPost = opts.opsPost ?? buildOpsPost(target, opts.user, opts.password);
316
+ const expected = await readMemoryRowCount(opsPost);
317
+ const rows = await readMemoryRowsPaged(opsPost, { expected, pageSize: opts.pageSize });
318
+ return compareCheckpoint(opts.checkpoint, rows);
319
+ }
320
+ catch (err) {
321
+ return unknownVerify(err instanceof Error ? err.message : String(err));
322
+ }
323
+ }
324
+ /** Render the comparison report. */
325
+ export function renderVerifyHuman(result, checkpointPathShown) {
326
+ const lines = [];
327
+ lines.push(`Memory id checkpoint verify: ${result.outcome.toUpperCase()}`);
328
+ lines.push(` checkpoint: ${checkpointPathShown}`);
329
+ if (result.outcome === "unknown") {
330
+ lines.push(` ⚠️ UNKNOWN — ${result.reason ?? "the check could not be made"}; NOT verified`);
331
+ return lines.join("\n");
332
+ }
333
+ lines.push(` rows read now: ${result.totalRows}`);
334
+ if (result.outcome === "integrity-failure") {
335
+ if (result.missing.length > 0) {
336
+ lines.push(` ❌ ${result.missing.length} checkpointed Memory id(s) missing; sample (up to ${MISSING_SAMPLE_LIMIT}):`);
337
+ for (const id of result.missing.slice(0, MISSING_SAMPLE_LIMIT))
338
+ lines.push(` - ${id}`);
339
+ }
340
+ for (const d of result.tierDrops)
341
+ lines.push(` ❌ ${d.tier} tier dropped by ${d.dropped}`);
342
+ }
343
+ else {
344
+ lines.push(` ✓ every checkpointed Memory id present; no tier-count drop`);
345
+ }
346
+ return lines.join("\n");
347
+ }
@@ -0,0 +1,207 @@
1
+ /**
2
+ * memory-node-compare.ts — `flair memory compare-nodes` (flair#2216, slice 2 of
3
+ * #971).
4
+ *
5
+ * Compares observed Memory id sets of explicitly named physical nodes.
6
+ * Peers come only from `--node`, never Flair's federation peer table.
7
+ *
8
+ * Reads use the checkpoint's keyset paging and exact-count recheck, with the
9
+ * same admin credentials. Count checks cannot detect equal-count concurrent
10
+ * updates or replacements. An id absent on every named node is invisible
11
+ * without a reference set.
12
+ *
13
+ * Classes use stored timestamps: parseable `updatedAt`, else `createdAt`.
14
+ * `createdAt` can be caller-supplied and nodes can use different clocks;
15
+ * timestamp comparisons do not establish actual write order.
16
+ * - `in-sync` — observed ids equal the union of the other usable readings.
17
+ * - `lagging` — missing ids only, each with a timestamp greater than this
18
+ * node's maximum timestamp.
19
+ * - `divergent` — an extra id, or a missing id whose timestamp is at or below
20
+ * this node's maximum timestamp.
21
+ * - `unknown` — failed read, unusable row timestamp, no usable peer, or
22
+ * missing ids with no local timestamp to compare against.
23
+ * A missing id uses the maximum timestamp among usable peers holding it.
24
+ * The overall result is `healthy` only when every node is `in-sync`;
25
+ * any `unknown` makes the overall result `unknown`.
26
+ */
27
+ import { buildOpsPost, normalizeOrigin, readMemoryRowCount, readMemoryRowsPaged, } from "./memory-id-checkpoint.js";
28
+ /** How many missing/extra ids the report names per node before it just counts. */
29
+ export const NODE_ID_SAMPLE_LIMIT = 10;
30
+ /** Documented exit codes for `flair memory compare-nodes --help`. */
31
+ export const COMPARE_EXIT_CODES = {
32
+ healthy: 0,
33
+ divergent: 2,
34
+ unknown: 3,
35
+ lagging: 4,
36
+ };
37
+ /** Parse a stored timestamp; absent or unparseable values yield null. */
38
+ export function parseWriteTime(value) {
39
+ if (typeof value !== "string" || value.length === 0)
40
+ return null;
41
+ const ms = Date.parse(value);
42
+ return Number.isFinite(ms) ? ms : null;
43
+ }
44
+ /** First parseable timestamp: `updatedAt`, then `createdAt`; null when neither parses. */
45
+ export function rowWriteTime(row) {
46
+ for (const value of [row.updatedAt, row.createdAt]) {
47
+ if (typeof value === "string" && value.length > 0 && Number.isFinite(Date.parse(value)))
48
+ return value;
49
+ }
50
+ return null;
51
+ }
52
+ function sample(ids) {
53
+ const sorted = [...ids].sort();
54
+ return { count: sorted.length, sample: sorted.slice(0, NODE_ID_SAMPLE_LIMIT) };
55
+ }
56
+ function prepare(reading) {
57
+ if (reading.kind === "failed") {
58
+ return { node: reading.node, ok: false, reason: reading.reason, rowCount: "UNAVAILABLE", idSet: new Set(), timeById: new Map(), newestMs: null };
59
+ }
60
+ const idSet = new Set();
61
+ const timeById = new Map();
62
+ let newestMs = null;
63
+ for (const row of reading.rows) {
64
+ idSet.add(row.id);
65
+ const ms = parseWriteTime(row.writeTime);
66
+ if (ms === null) {
67
+ // A row without a usable timestamp makes this reading unknown.
68
+ return { node: reading.node, ok: false, reason: `row ${row.id} has no usable stored timestamp`, rowCount: reading.rows.length, idSet, timeById, newestMs };
69
+ }
70
+ timeById.set(row.id, ms);
71
+ if (newestMs === null || ms > newestMs)
72
+ newestMs = ms;
73
+ }
74
+ return { node: reading.node, ok: true, rowCount: reading.rows.length, idSet, timeById, newestMs };
75
+ }
76
+ /**
77
+ * Classify the readings. Pure and deterministic: the caller supplies each
78
+ * node's rows or a read failure. Fewer than two nodes is a misuse.
79
+ */
80
+ export function classifyNodeSets(readings) {
81
+ if (readings.length < 2)
82
+ throw new Error("compare-nodes needs at least two nodes to compare");
83
+ const prepared = readings.map(prepare);
84
+ const usable = prepared.filter((p) => p.ok);
85
+ const nodes = prepared.map((p) => {
86
+ if (!p.ok) {
87
+ return {
88
+ node: p.node,
89
+ verdict: "unknown",
90
+ reason: p.reason,
91
+ rowCount: p.rowCount,
92
+ newestWrite: "UNAVAILABLE",
93
+ missing: "UNAVAILABLE",
94
+ extra: "UNAVAILABLE",
95
+ };
96
+ }
97
+ // Compare only with other usable readings; no usable peer means unavailable differences.
98
+ const peers = usable.filter((q) => q !== p);
99
+ const base = { node: p.node, rowCount: p.rowCount, newestWrite: p.newestMs === null ? null : new Date(p.newestMs).toISOString() };
100
+ if (peers.length === 0) {
101
+ return {
102
+ ...base,
103
+ verdict: "unknown",
104
+ reason: "no usable peer to compare against",
105
+ missing: "UNAVAILABLE",
106
+ extra: "UNAVAILABLE",
107
+ };
108
+ }
109
+ const others = new Set();
110
+ for (const q of peers)
111
+ for (const id of q.idSet)
112
+ others.add(id);
113
+ const extra = [...p.idSet].filter((id) => !others.has(id));
114
+ const missing = [...others].filter((id) => !p.idSet.has(id));
115
+ if (extra.length > 0) {
116
+ return { ...base, verdict: "divergent", missing: sample(missing), extra: sample(extra) };
117
+ }
118
+ if (missing.length === 0) {
119
+ return { ...base, verdict: "in-sync", missing: sample([]), extra: sample([]) };
120
+ }
121
+ if (p.newestMs === null) {
122
+ // Missing ids with no local timestamp to compare against yield unknown.
123
+ return {
124
+ ...base,
125
+ verdict: "unknown",
126
+ reason: `missing ${missing.length} id(s) but reports no stored timestamp to compare against`,
127
+ missing: sample(missing),
128
+ extra: sample([]),
129
+ };
130
+ }
131
+ // A missing id's maximum peer timestamp at or below the local maximum
132
+ // counts as divergence, including equality.
133
+ const older = missing.filter((id) => {
134
+ let latest = null;
135
+ for (const q of peers) {
136
+ const ms = q.idSet.has(id) ? q.timeById.get(id) ?? null : null;
137
+ if (ms !== null && (latest === null || ms > latest))
138
+ latest = ms;
139
+ }
140
+ return latest !== null && latest <= p.newestMs;
141
+ });
142
+ if (older.length > 0) {
143
+ return { ...base, verdict: "divergent", missing: sample(missing), extra: sample([]) };
144
+ }
145
+ return { ...base, verdict: "lagging", missing: sample(missing), extra: sample([]) };
146
+ });
147
+ const verdict = nodes.some((n) => n.verdict === "unknown")
148
+ ? "unknown"
149
+ : nodes.some((n) => n.verdict === "divergent")
150
+ ? "divergent"
151
+ : nodes.some((n) => n.verdict === "lagging")
152
+ ? "lagging"
153
+ : "healthy";
154
+ const counts = { "in-sync": 0, lagging: 0, divergent: 0, unknown: 0 };
155
+ for (const n of nodes)
156
+ counts[n.verdict]++;
157
+ const detail = verdict === "healthy"
158
+ ? `healthy — all ${nodes.length} node(s) have the same observed Memory ids`
159
+ : `${verdict} — ${["in-sync", "lagging", "divergent", "unknown"]
160
+ .filter((c) => counts[c] > 0)
161
+ .map((c) => `${counts[c]} ${c}`)
162
+ .join(", ")}`;
163
+ return { verdict, nodes, detail };
164
+ }
165
+ /**
166
+ * Read one node's Memory ids and stored timestamps through the admin operations API,
167
+ * using the checkpoint's read (keyset paging + exact-count recheck). A read
168
+ * failure is a `failed` reading, never an empty id set.
169
+ */
170
+ export async function readNode(opsUrl, opts = {}) {
171
+ let node = opsUrl;
172
+ try {
173
+ node = normalizeOrigin(opsUrl);
174
+ const opsPost = opts.opsPost ?? buildOpsPost(node, opts.user, opts.password);
175
+ const expected = await readMemoryRowCount(opsPost);
176
+ const rows = await readMemoryRowsPaged(opsPost, { expected, pageSize: opts.pageSize, withWriteTimes: true });
177
+ return { kind: "read", node, rows: rows.map((row) => ({ id: row.id, writeTime: rowWriteTime(row) })) };
178
+ }
179
+ catch (err) {
180
+ return { kind: "failed", node, reason: err instanceof Error ? err.message : String(err) };
181
+ }
182
+ }
183
+ // ─── Report ─────────────────────────────────────────────────────────────────
184
+ export function renderCompareNodesHuman(result) {
185
+ const lines = [];
186
+ lines.push(`Memory node comparison: ${result.verdict.toUpperCase()}`);
187
+ if (result.verdict !== "healthy")
188
+ lines.push(` ⚠️ ${result.detail}`);
189
+ for (const n of result.nodes) {
190
+ lines.push(` ${n.node} ${n.verdict.toUpperCase()} (${n.rowCount} id(s), maximum timestamp ${n.newestWrite ?? "none"})`);
191
+ if (n.verdict === "unknown")
192
+ lines.push(` ⚠️ ${n.reason ?? "the node could not be classified"}; NOT healthy`);
193
+ if (n.missing === "UNAVAILABLE") {
194
+ lines.push(" missing: UNAVAILABLE");
195
+ }
196
+ else if (n.missing.count > 0) {
197
+ lines.push(` missing ${n.missing.count} id(s): ${n.missing.sample.join(", ")}${n.missing.count > n.missing.sample.length ? ", …" : ""}`);
198
+ }
199
+ if (n.extra === "UNAVAILABLE") {
200
+ lines.push(" extra: UNAVAILABLE");
201
+ }
202
+ else if (n.extra.count > 0) {
203
+ lines.push(` holds ${n.extra.count} id(s) absent from the other usable readings: ${n.extra.sample.join(", ")}${n.extra.count > n.extra.sample.length ? ", …" : ""}`);
204
+ }
205
+ }
206
+ return lines.join("\n");
207
+ }