@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
@@ -1,40 +1,191 @@
1
1
  /**
2
- * lock.ts — single-flight guard (Kern verdict, 2026-07-12):
3
- * "Single-flight v1 = in-process mutex + stale-tolerant file lock (flock on
4
- * well-known path; dead-holder → break and proceed). Fabric-wide ordering =
5
- * follow-on with its own review, NOT this slice."
2
+ * lock.ts — single-flight guard for migration cycles.
6
3
  *
7
4
  * Two layers:
8
- * 1. An in-process mutex (module-scope flag) — cheapest guard against two
9
- * concurrent async callers inside the SAME Node process (e.g. a
10
- * duplicate boot-trigger firing twice).
5
+ * 1. An in-process flag — cheapest guard against two concurrent async
6
+ * callers inside the SAME process.
11
7
  * 2. A file lock at a well-known path under the data dir. Node has no
12
- * portable flock() binding, so this uses exclusive file CREATE
13
- * (O_CREAT|O_EXCL — atomic at the OS level, the same primitive flock
14
- * ultimately reduces to for a single-host guard) instead. The lock file
15
- * holds `{pid, hostname, startedAt}`. A lock is considered STALE (and
16
- * is broken/removed before the new attempt) when either: the recorded
17
- * pid is no longer alive on this host, OR the file is older than
18
- * `staleMs` (covers a cross-host holder this process can't liveness-
19
- * check by pid — Fabric-wide coordination is explicitly out of scope
20
- * for this slice, so age is the only signal available for that case).
8
+ * portable flock() binding, so a contender publishes a complete holder
9
+ * record to a unique temporary file in the same directory, flushes it,
10
+ * and hard-links it to the lock path (`link(2)`, which fails with EEXIST
11
+ * when a lock exists). A reader sees no lock file, a complete record, or
12
+ * a record this module refuses as unreadable; it never treats a partial
13
+ * or unknown record as stale.
14
+ *
15
+ * Every ownership transition on the migration lock is serialized by a sibling directory mutex
16
+ * (`<lock>.guard`). A process publishes that mutex by renaming an
17
+ * already-populated directory over the guard path: replacing an empty
18
+ * directory succeeds; replacing a non-empty one fails, and either EEXIST or
19
+ * ENOTEMPTY from that rename is treated as contention. The
20
+ * mutex is released by unlinking only the owner entry of the generation it
21
+ * published, leaving the directory empty when the unlink succeeds. A dead
22
+ * owner is recovered by
23
+ * unlinking that same generation-specific entry; the recovering process must
24
+ * then win publication of its own directory, so recovery never grants
25
+ * ownership by itself.
26
+ *
27
+ * The lock file holds `{pid, hostname, startedAt}`. Another live local pid
28
+ * is held regardless of age. After abandoned-record cleanup, this process's
29
+ * own pid is judged by heartbeat age unless this module holds it, because the pid probe cannot
30
+ * distinguish an earlier process with that pid from this one. A holder on
31
+ * another host is also judged by age (`staleMs`). Same host compares the
32
+ * hostname string: the discriminator is a name, not an identity, so two
33
+ * hosts sharing a hostname and a data dir can misclassify a remote holder as
34
+ * local. A holder record that cannot be read or parsed is not treated as stale:
35
+ * acquisition refuses with a named error.
21
36
  *
22
37
  * This is a SINGLE-HOST guard, not a Fabric-wide one — multiple Flair
23
- * instances in a Fabric cluster each have their OWN data dir today, so this
24
- * is sufficient for v1. Fabric-wide ordering (one lock across a cluster
25
- * sharing storage) is explicitly deferred, per the verdict above.
38
+ * instances in a Fabric cluster each have their OWN data dir today. Fabric-
39
+ * wide ordering (one lock across a cluster sharing storage) is deferred.
40
+ *
41
+ * Known windows: a holder recorded on another host is still judged by age,
42
+ * for the mutex as well as the migration record, so a remote holder that
43
+ * resumes after takeover is not fenced. A same-pid holder that stops
44
+ * heartbeating for longer than staleMs while alive is treated as stale unless
45
+ * this module holds it. A process killed while preparing a
46
+ * record leaves an unpublished staging directory or temporary file; one
47
+ * killed after publication and before that record is cleaned up leaves a
48
+ * complete owner record that another process may recover.
26
49
  */
27
- import { existsSync, mkdirSync, openSync, closeSync, writeSync, readFileSync, unlinkSync, statSync, utimesSync, constants as fsConstants } from "node:fs";
28
- import { dirname } from "node:path";
50
+ import { closeSync, constants as fsConstants, fstatSync, fsyncSync, futimesSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmSync, unlinkSync, writeFileSync, } from "node:fs";
51
+ import { randomBytes } from "node:crypto";
52
+ import { basename, dirname, join } from "node:path";
29
53
  import { hostname as osHostname } from "node:os";
54
+ import { ensureSecureDir } from "./dir-safety.js";
55
+ import { txnPausePointSync } from "../txn-pause-point.js";
30
56
  export const DEFAULT_STALE_MS = 5 * 60 * 1000; // 5 minutes with no heartbeat touch = stale
57
+ /** Bounds every acquisition loop; each failed attempt settles briefly, and the loop can end while contention continues. */
58
+ const GUARD_ACQUISITION_ATTEMPTS = 24;
59
+ const LOCK_ACQUISITION_ROUNDS = 8;
60
+ const CONTENTION_SETTLE_MS = 2;
61
+ const liveHandles = new WeakSet();
62
+ const revokedHandles = new WeakSet();
63
+ /** Module-private identity: never read from a property a caller can shadow. */
64
+ const identities = new WeakMap();
65
+ const HANDLE_KEY = Symbol("migration-lock-handle");
66
+ /** Holder identities this process currently has a live handle for, per lock path. */
67
+ const liveHolderKeys = new Set();
68
+ const ownedGuardGenerations = new Map();
69
+ /**
70
+ * A later acquisition may finish abandoned-record cleanup after taking the mutex, finding
71
+ * this exact identity still at the lock path, and finding no live handle for it
72
+ * (flair#2866).
73
+ */
74
+ const abandonedOwnRecords = new Map();
75
+ const abandonedGuardGenerations = new Map();
76
+ function holderKey(lockPath, holder) {
77
+ return `${lockPath}\u0000${holder.pid}\u0000${holder.hostname}\u0000${holder.startedAt}`;
78
+ }
79
+ /**
80
+ * An acquired migration lock. Only {@link acquireMigrationLock} constructs a
81
+ * live one; {@link MigrationLockHandle.release} revokes it. The lock path and
82
+ * holder record live in module-private storage keyed by this object. The
83
+ * `lockPath` and `holder` getters return a snapshot for diagnostics; neither
84
+ * `state.ts` nor `release()` consults them (flair#2866).
85
+ */
86
+ export class MigrationLockHandle {
87
+ acquired = true;
88
+ constructor(key, identity) {
89
+ if (key !== HANDLE_KEY) {
90
+ throw new TypeError("MigrationLockHandle is created only by acquireMigrationLock");
91
+ }
92
+ identities.set(this, identity);
93
+ liveHandles.add(this);
94
+ }
95
+ get lockPath() {
96
+ return identityFor(this).lockPath;
97
+ }
98
+ get holder() {
99
+ return identityFor(this).holder;
100
+ }
101
+ release() {
102
+ const identity = identities.get(this);
103
+ if (!liveHandles.has(this) || identity === undefined)
104
+ return;
105
+ liveHandles.delete(this);
106
+ revokedHandles.add(this);
107
+ liveHolderKeys.delete(holderKey(identity.lockPath, identity.holder));
108
+ identity.release();
109
+ }
110
+ touch() {
111
+ if (!liveHandles.has(this))
112
+ return;
113
+ identities.get(this)?.touch();
114
+ }
115
+ }
116
+ function identityFor(handle) {
117
+ const identity = identities.get(handle);
118
+ if (identity === undefined)
119
+ throw new TypeError("not a migration lock handle");
120
+ return identity;
121
+ }
122
+ /**
123
+ * The lock path and holder a handle was issued for, or null for any other
124
+ * value. This is the only way `state.ts` reads a handle's identity.
125
+ */
126
+ export function migrationLockIdentity(value) {
127
+ if (typeof value !== "object" || value === null)
128
+ return null;
129
+ const identity = identities.get(value);
130
+ if (identity === undefined)
131
+ return null;
132
+ return Object.freeze({ lockPath: identity.lockPath, holder: identity.holder });
133
+ }
134
+ /** Classify a value without exposing whether a forged object imitates a handle. */
135
+ export function migrationLockHandleStatus(value) {
136
+ if (typeof value === "object" && value !== null) {
137
+ if (liveHandles.has(value))
138
+ return "live";
139
+ if (revokedHandles.has(value))
140
+ return "released";
141
+ }
142
+ return "unknown";
143
+ }
144
+ export function isLiveMigrationLockHandle(value) {
145
+ return migrationLockHandleStatus(value) === "live";
146
+ }
147
+ /** The named refusal when a pid probe fails for a reason other than ESRCH/EPERM. */
148
+ export class MigrationLockProbeError extends Error {
149
+ constructor(pid, code) {
150
+ super(`refusing to treat holder pid ${pid} as dead: the liveness probe failed with ` +
151
+ `${code ?? "an unknown error"}. Inspect pid ${pid} on this host (for example, ` +
152
+ `ps -p ${pid}); only when it is gone, and no other writer is running, remove the lock file by hand`);
153
+ this.name = "MigrationLockProbeError";
154
+ }
155
+ }
156
+ /** The named refusal when a lock file's holder record cannot be trusted. */
157
+ export class MigrationLockUnreadableError extends Error {
158
+ constructor(lockPath, detail) {
159
+ super(`refusing to break ${lockPath}: ${detail}. Inspect ${lockPath}; if no process on ` +
160
+ `this host still holds it, stop every writer and remove that file by hand, then retry`);
161
+ this.name = "MigrationLockUnreadableError";
162
+ }
163
+ }
164
+ /** The named refusal when the directory mutex cannot be trusted. */
165
+ export class MigrationLockMutexError extends Error {
166
+ constructor(guardPath, detail) {
167
+ super(`refusing to change the migration lock at ${guardPath}: ${detail}. Inspect ${guardPath}; ` +
168
+ `if no process on this host still holds the mutex, stop every writer and remove it by hand, then retry`);
169
+ this.name = "MigrationLockMutexError";
170
+ }
171
+ }
172
+ /**
173
+ * True when the pid is alive. ESRCH means dead; EPERM means alive (the process
174
+ * exists but is not ours to signal); every other probe error refuses
175
+ * acquisition by name rather than guessing (flair#2866).
176
+ */
31
177
  export function defaultIsProcessAlive(pid) {
32
178
  try {
33
179
  process.kill(pid, 0);
34
180
  return true;
35
181
  }
36
- catch {
37
- return false;
182
+ catch (err) {
183
+ const code = err?.code;
184
+ if (code === "ESRCH")
185
+ return false;
186
+ if (code === "EPERM")
187
+ return true;
188
+ throw new MigrationLockProbeError(pid, code);
38
189
  }
39
190
  }
40
191
  export function defaultLockDeps(lockPath) {
@@ -53,102 +204,744 @@ let inProcessHeld = false;
53
204
  export function _resetInProcessLockForTests() {
54
205
  inProcessHeld = false;
55
206
  }
56
- function readHolder(lockPath) {
207
+ /**
208
+ * True only when this module issued the handle and the file it opens at the
209
+ * lock pathname records that handle's holder at the device and inode recorded
210
+ * when the lock was published. The inspection describes the file opened, not
211
+ * the pathname afterwards: a replacement during that descriptor read can
212
+ * occur before this returns. Any read or parse failure answers false: an
213
+ * unknown lock state never licenses a write (flair#2866).
214
+ */
215
+ export function migrationLockStillHeld(lock) {
216
+ if (!liveHandles.has(lock))
217
+ return false;
218
+ const identity = identities.get(lock);
219
+ if (identity === undefined)
220
+ return false;
221
+ const current = inspectLock(identity.lockPath);
222
+ return (current.state === "held" &&
223
+ current.dev === identity.dev &&
224
+ current.ino === identity.ino &&
225
+ sameHolder(current.holder, identity.holder));
226
+ }
227
+ function sameHolder(a, b) {
228
+ return a.pid === b.pid && a.hostname === b.hostname && a.startedAt === b.startedAt;
229
+ }
230
+ function parseHolder(raw) {
231
+ if (typeof raw === "object" &&
232
+ raw !== null &&
233
+ Number.isInteger(raw.pid) &&
234
+ raw.pid > 0 &&
235
+ typeof raw.hostname === "string" &&
236
+ raw.hostname.length > 0 &&
237
+ typeof raw.startedAt === "string" &&
238
+ raw.startedAt.length > 0) {
239
+ return {
240
+ pid: raw.pid,
241
+ hostname: raw.hostname,
242
+ startedAt: raw.startedAt,
243
+ };
244
+ }
245
+ return null;
246
+ }
247
+ /**
248
+ * Read the lock's holder, device and inode from one open file descriptor, so
249
+ * the three facts describe the same file even if the name is replaced while
250
+ * the read runs. A missing file is absent; anything else that prevents a
251
+ * complete regular-file record is unreadable and never breakable.
252
+ */
253
+ function inspectLock(lockPath) {
254
+ let fd;
57
255
  try {
58
- const raw = JSON.parse(readFileSync(lockPath, "utf-8"));
59
- if (typeof raw?.pid === "number" && typeof raw?.hostname === "string" && typeof raw?.startedAt === "string") {
60
- return raw;
256
+ fd = openSync(lockPath, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);
257
+ }
258
+ catch (err) {
259
+ if (err?.code === "ENOENT")
260
+ return { state: "absent" };
261
+ return { state: "unreadable", detail: `the lock file cannot be opened (${err?.code ?? String(err)})` };
262
+ }
263
+ try {
264
+ const st = fstatSync(fd);
265
+ if (!st.isFile())
266
+ return { state: "unreadable", detail: "it is not a regular file" };
267
+ const text = readFileSync(fd, "utf-8");
268
+ let raw;
269
+ try {
270
+ raw = JSON.parse(text);
61
271
  }
62
- return null;
272
+ catch {
273
+ return { state: "unreadable", detail: "its holder record is not valid JSON" };
274
+ }
275
+ const holder = parseHolder(raw);
276
+ if (holder === null) {
277
+ return { state: "unreadable", detail: "its holder record lacks a positive integer pid, a hostname or a startedAt" };
278
+ }
279
+ return { state: "held", holder, dev: st.dev, ino: st.ino, mtimeMs: st.mtimeMs };
63
280
  }
64
- catch {
65
- return null;
281
+ catch (err) {
282
+ return { state: "unreadable", detail: `the lock file cannot be read (${err?.code ?? String(err)})` };
283
+ }
284
+ finally {
285
+ closeSync(fd);
66
286
  }
67
287
  }
68
288
  /**
69
- * Attempts to acquire the migration lock. On success, returns `release()`
70
- * (removes the lock file + clears the in-process flag) and `touch()`
71
- * (updates the lock file's mtime — the runner calls this periodically
72
- * during a long-running migration so ANOTHER process's staleness check
73
- * doesn't mistake a genuinely-still-running holder for dead).
289
+ * Write the complete holder record to a unique temporary file in the lock's
290
+ * directory, flush it, then hard-link it to the lock path. `link` is atomic
291
+ * and fails with EEXIST when a lock already exists, so a reader never sees a
292
+ * partial record. The temporary name is removed best-effort; a cleanup
293
+ * failure leaves an extra temporary file and does not affect a published lock.
74
294
  */
75
- export function acquireMigrationLock(deps) {
76
- const resolved = { ...defaultLockDeps(deps.lockPath), ...deps };
77
- const { lockPath, staleMs, isProcessAlive, now } = resolved;
78
- if (inProcessHeld) {
79
- return { acquired: false, reason: "already held in-process (another async caller in this process holds it)" };
80
- }
81
- mkdirSync(dirname(lockPath), { recursive: true, mode: 0o700 });
82
- if (existsSync(lockPath)) {
83
- const holder = readHolder(lockPath);
84
- let ageMs = Infinity;
295
+ function publishLock(lockPath, holder) {
296
+ const temp = join(dirname(lockPath), `.${basename(lockPath)}.${process.pid}.${randomBytes(8).toString("hex")}.tmp`);
297
+ let fd;
298
+ let created = false;
299
+ let dev = 0;
300
+ let ino = 0;
301
+ try {
302
+ fd = openSync(temp, "wx", 0o600);
303
+ created = true;
304
+ writeFileSync(fd, JSON.stringify(holder));
305
+ fsyncSync(fd);
306
+ const st = fstatSync(fd);
307
+ dev = st.dev;
308
+ ino = st.ino;
309
+ closeSync(fd);
310
+ fd = undefined;
311
+ // Test-only pause between the complete temporary record and the link that
312
+ // publishes it, so a test can put a second contender into that window
313
+ // deterministically (flair#2866).
314
+ txnPausePointSync("migration-lock-publish", process.env, undefined, { lockPath, temp });
85
315
  try {
86
- ageMs = now() - statSync(lockPath).mtimeMs;
316
+ linkSync(temp, lockPath);
87
317
  }
88
- catch {
89
- /* vanished between existsSync and stat — fall through to acquire */
318
+ catch (err) {
319
+ if (err?.code === "EEXIST")
320
+ return { published: false };
321
+ throw err;
90
322
  }
91
- const dead = !holder || !isProcessAlive(holder.pid) || ageMs > staleMs;
92
- if (dead) {
323
+ txnPausePointSync("migration-lock-published", process.env, undefined, { lockPath });
324
+ return { published: true, dev, ino };
325
+ }
326
+ finally {
327
+ if (fd !== undefined) {
93
328
  try {
94
- unlinkSync(lockPath);
329
+ closeSync(fd);
95
330
  }
96
331
  catch {
97
- /* another racer already broke it — fine, continue to the exclusive create below */
332
+ /* the original error is the one to surface */
98
333
  }
99
334
  }
100
- else {
335
+ try {
336
+ if (created)
337
+ unlinkSync(temp);
338
+ }
339
+ catch {
340
+ /* best-effort cleanup: an extra temporary name does not affect the lock */
341
+ }
342
+ }
343
+ }
344
+ function prepareLockRecord(lockPath, holder) {
345
+ const temp = join(dirname(lockPath), `.${basename(lockPath)}.${process.pid}.${randomBytes(8).toString("hex")}.reclaim.tmp`);
346
+ const fd = openSync(temp, "wx", 0o600);
347
+ try {
348
+ writeFileSync(fd, JSON.stringify(holder));
349
+ fsyncSync(fd);
350
+ const st = fstatSync(fd);
351
+ return { temp, dev: st.dev, ino: st.ino };
352
+ }
353
+ catch (err) {
354
+ try {
355
+ unlinkSync(temp);
356
+ }
357
+ catch {
358
+ /* best-effort cleanup of our own unpublished record */
359
+ }
360
+ throw err;
361
+ }
362
+ finally {
363
+ closeSync(fd);
364
+ }
365
+ }
366
+ // ─── directory mutex ────────────────────────────────────────────────────────
367
+ function guardPathFor(lockPath) {
368
+ return `${lockPath}.guard`;
369
+ }
370
+ function ownerEntryName(generation) {
371
+ return `owner-${generation}.json`;
372
+ }
373
+ const GENERATION_PATTERN = /^[0-9a-f]{16}$/;
374
+ const OWNER_ENTRY_PATTERN = /^owner-([0-9a-f]{16})\.json$/;
375
+ function parseGuardHolder(raw, nameGeneration) {
376
+ if (typeof raw === "object" &&
377
+ raw !== null &&
378
+ Number.isInteger(raw.pid) &&
379
+ raw.pid > 0 &&
380
+ typeof raw.hostname === "string" &&
381
+ raw.hostname.length > 0 &&
382
+ typeof raw.startedAt === "string" &&
383
+ raw.startedAt.length > 0 &&
384
+ typeof raw.generation === "string" &&
385
+ raw.generation === nameGeneration) {
386
+ return {
387
+ pid: raw.pid,
388
+ hostname: raw.hostname,
389
+ startedAt: raw.startedAt,
390
+ generation: raw.generation,
391
+ };
392
+ }
393
+ return null;
394
+ }
395
+ /**
396
+ * Inspect the mutex directory without accepting a symlink or unexpected type.
397
+ * It is either absent, empty, or holds exactly one owner entry whose record
398
+ * and filename name the same generation. Everything else refuses.
399
+ */
400
+ function inspectGuard(guardPath) {
401
+ let st;
402
+ try {
403
+ st = lstatSync(guardPath);
404
+ }
405
+ catch (err) {
406
+ if (err?.code === "ENOENT")
407
+ return { state: "absent" };
408
+ return { state: "unreadable", detail: `the mutex cannot be inspected (${err?.code ?? String(err)})` };
409
+ }
410
+ if (!st.isDirectory())
411
+ return { state: "unreadable", detail: "it is not a directory" };
412
+ let entries;
413
+ try {
414
+ entries = readdirSync(guardPath);
415
+ }
416
+ catch (err) {
417
+ return { state: "unreadable", detail: `its entries cannot be listed (${err?.code ?? String(err)})` };
418
+ }
419
+ if (entries.length === 0)
420
+ return { state: "empty" };
421
+ if (entries.length !== 1) {
422
+ return { state: "unreadable", detail: `it contains ${entries.length} entries instead of none or one` };
423
+ }
424
+ const name = entries[0];
425
+ const match = OWNER_ENTRY_PATTERN.exec(name);
426
+ if (match === null)
427
+ return { state: "unreadable", detail: `it contains an unexpected entry ${name}` };
428
+ let fd;
429
+ try {
430
+ fd = openSync(join(guardPath, name), fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);
431
+ }
432
+ catch (err) {
433
+ return { state: "unreadable", detail: `its owner entry cannot be opened (${err?.code ?? String(err)})` };
434
+ }
435
+ try {
436
+ const entryStat = fstatSync(fd);
437
+ if (!entryStat.isFile())
438
+ return { state: "unreadable", detail: "its owner entry is not a regular file" };
439
+ const text = readFileSync(fd, "utf-8");
440
+ let raw;
441
+ try {
442
+ raw = JSON.parse(text);
443
+ }
444
+ catch {
445
+ return { state: "unreadable", detail: "its owner entry is not valid JSON" };
446
+ }
447
+ const holder = parseGuardHolder(raw, match[1]);
448
+ if (holder === null) {
449
+ return { state: "unreadable", detail: "its owner entry does not name the generation in its filename or lacks a holder field" };
450
+ }
451
+ return { state: "occupied", holder, name, mtimeMs: entryStat.mtimeMs };
452
+ }
453
+ catch (err) {
454
+ return { state: "unreadable", detail: `its owner entry cannot be read (${err?.code ?? String(err)})` };
455
+ }
456
+ finally {
457
+ closeSync(fd);
458
+ }
459
+ }
460
+ function publishGuard(guardPath, holder) {
461
+ const staging = join(dirname(guardPath), `.${basename(guardPath)}.${process.pid}.${randomBytes(8).toString("hex")}.stage`);
462
+ try {
463
+ mkdirSync(staging, { mode: 0o700 });
464
+ const fd = openSync(join(staging, ownerEntryName(holder.generation)), "wx", 0o600);
465
+ try {
466
+ writeFileSync(fd, JSON.stringify(holder));
467
+ fsyncSync(fd);
468
+ }
469
+ finally {
470
+ closeSync(fd);
471
+ }
472
+ // Test-only pause after the populated staging directory is complete and
473
+ // before the rename that publishes it (flair#2866).
474
+ txnPausePointSync("migration-lock-guard-publish", process.env, undefined, {
475
+ guardPath,
476
+ generation: holder.generation,
477
+ });
478
+ try {
479
+ renameSync(staging, guardPath);
480
+ return { published: true };
481
+ }
482
+ catch (err) {
483
+ const code = err?.code;
484
+ if (code === "EEXIST" || code === "ENOTEMPTY")
485
+ return { published: false, contention: true };
486
+ return { published: false, contention: false, code };
487
+ }
488
+ }
489
+ catch (err) {
490
+ return { published: false, contention: false, code: err?.code };
491
+ }
492
+ finally {
493
+ try {
494
+ rmSync(staging, { recursive: true, force: true });
495
+ }
496
+ catch {
497
+ /* best-effort cleanup of our own staging directory */
498
+ }
499
+ }
500
+ }
501
+ function releaseGuard(guardPath, generation) {
502
+ try {
503
+ unlinkSync(join(guardPath, ownerEntryName(generation)));
504
+ return { ok: true };
505
+ }
506
+ catch (err) {
507
+ if (err?.code === "ENOENT")
508
+ return { ok: true };
509
+ abandonedGuardGenerations.set(guardPath, generation);
510
+ return {
511
+ ok: false,
512
+ reason: `its owner entry ${ownerEntryName(generation)} cannot be removed (${err?.code ?? String(err)})`,
513
+ };
514
+ }
515
+ finally {
516
+ if (ownedGuardGenerations.get(guardPath) === generation)
517
+ ownedGuardGenerations.delete(guardPath);
518
+ }
519
+ }
520
+ function settleContention() {
521
+ const sleeper = new Int32Array(new SharedArrayBuffer(4));
522
+ Atomics.wait(sleeper, 0, 0, CONTENTION_SETTLE_MS);
523
+ }
524
+ function makeGuardHolder(now) {
525
+ return {
526
+ pid: process.pid,
527
+ hostname: osHostname(),
528
+ startedAt: new Date(now()).toISOString(),
529
+ generation: randomBytes(8).toString("hex"),
530
+ };
531
+ }
532
+ /**
533
+ * Acquire the directory mutex, recovering a generation at most as often
534
+ * as the bounded loop allows.
535
+ */
536
+ function acquireGuard(guardPath, deps) {
537
+ for (let attempt = 0; attempt < GUARD_ACQUISITION_ATTEMPTS; attempt++) {
538
+ const holder = makeGuardHolder(deps.now);
539
+ const published = publishGuard(guardPath, holder);
540
+ if (published.published) {
541
+ ownedGuardGenerations.set(guardPath, holder.generation);
542
+ txnPausePointSync("migration-lock-guard-published", process.env, undefined, {
543
+ guardPath,
544
+ generation: holder.generation,
545
+ });
546
+ return { generation: holder.generation };
547
+ }
548
+ if (!published.contention) {
101
549
  return {
102
550
  acquired: false,
103
- reason: `held by pid ${holder.pid} on ${holder.hostname} since ${holder.startedAt}`,
104
- holder,
551
+ kind: "error",
552
+ reason: `${MigrationLockMutexError.name}: the mutex at ${guardPath} cannot be published (${published.code ?? "unknown error"})`,
105
553
  };
106
554
  }
555
+ const inspected = inspectGuard(guardPath);
556
+ if (inspected.state === "unreadable") {
557
+ return { acquired: false, kind: "error", reason: `${MigrationLockMutexError.name}: ${inspected.detail}` };
558
+ }
559
+ if (inspected.state !== "occupied") {
560
+ settleContention();
561
+ continue;
562
+ }
563
+ let breakable;
564
+ try {
565
+ breakable = guardHolderIsBreakable(guardPath, inspected.holder, inspected.mtimeMs, deps);
566
+ }
567
+ catch (err) {
568
+ if (err instanceof MigrationLockProbeError) {
569
+ return { acquired: false, kind: "error", reason: `${err.name}: ${err.message}` };
570
+ }
571
+ throw err;
572
+ }
573
+ if (!breakable) {
574
+ return {
575
+ acquired: false,
576
+ kind: "held",
577
+ reason: `the migration-lock mutex is held by pid ${inspected.holder.pid} on ${inspected.holder.hostname} ` +
578
+ `since ${inspected.holder.startedAt} (${guardPath})`,
579
+ };
580
+ }
581
+ // Test-only pause after the breakable generation is inspected and before its
582
+ // owner entry is unlinked, so a test can let a successor recover and
583
+ // publish before this process resumes its old cleanup (flair#2866).
584
+ txnPausePointSync("migration-lock-guard-reclaim", process.env, undefined, {
585
+ guardPath,
586
+ generation: inspected.holder.generation,
587
+ });
588
+ try {
589
+ // Unlink only the entry this inspection named; never a fresh listing.
590
+ unlinkSync(join(guardPath, inspected.name));
591
+ }
592
+ catch (err) {
593
+ if (err?.code !== "ENOENT") {
594
+ return {
595
+ acquired: false,
596
+ kind: "error",
597
+ reason: `${MigrationLockMutexError.name}: ${inspected.name} cannot be removed (${err?.code ?? String(err)})`,
598
+ };
599
+ }
600
+ settleContention();
601
+ continue;
602
+ }
603
+ if (abandonedGuardGenerations.get(guardPath) === inspected.holder.generation) {
604
+ abandonedGuardGenerations.delete(guardPath);
605
+ }
606
+ txnPausePointSync("migration-lock-guard-reclaimed", process.env, undefined, {
607
+ guardPath,
608
+ generation: inspected.holder.generation,
609
+ });
610
+ settleContention();
107
611
  }
108
- let fd;
612
+ return { acquired: false, kind: "held", reason: `lost the race to acquire the migration-lock mutex (${guardPath})` };
613
+ }
614
+ function guardHolderIsBreakable(guardPath, holder, mtimeMs, deps) {
615
+ if (holder.hostname === osHostname()) {
616
+ if (holder.pid === process.pid) {
617
+ if (abandonedGuardGenerations.get(guardPath) === holder.generation)
618
+ return true;
619
+ return ownedGuardGenerations.get(guardPath) !== holder.generation && deps.now() - mtimeMs > deps.staleMs;
620
+ }
621
+ return !deps.isProcessAlive(holder.pid);
622
+ }
623
+ return deps.now() - mtimeMs > deps.staleMs;
624
+ }
625
+ /**
626
+ * True only for the exact record this process wrote, with
627
+ * no live handle for it. The path and the full identity must match: a pid
628
+ * alone never authorizes deleting a record (flair#2866).
629
+ */
630
+ function isAbandonedOwnRecord(lockPath, holder) {
631
+ const remembered = abandonedOwnRecords.get(lockPath);
632
+ return (remembered !== undefined &&
633
+ sameHolder(remembered, holder) &&
634
+ !liveHolderKeys.has(holderKey(lockPath, holder)));
635
+ }
636
+ function rememberAbandonedRecord(lockPath, holder) {
637
+ abandonedOwnRecords.set(lockPath, holder);
638
+ }
639
+ /**
640
+ * One inspection-and-transition inside the mutex. The lock is inspected
641
+ * afresh here: an inspection made before the mutex was acquired never
642
+ * authorizes replacement.
643
+ */
644
+ function transitionUnderGuard(lockPath, deps, staleMs, now) {
645
+ const inspected = inspectLock(lockPath);
646
+ if (inspected.state === "absent") {
647
+ abandonedOwnRecords.delete(lockPath);
648
+ const holder = makeHolder(now);
649
+ const published = publishLock(lockPath, holder);
650
+ if (!published.published)
651
+ return { kind: "retry" };
652
+ return { kind: "handle", holder, dev: published.dev, ino: published.ino };
653
+ }
654
+ if (inspected.state === "unreadable") {
655
+ const err = new MigrationLockUnreadableError(lockPath, inspected.detail);
656
+ return { kind: "refused", reason: `${err.name}: ${err.message}` };
657
+ }
658
+ const holder = inspected.holder;
659
+ if (isAbandonedOwnRecord(lockPath, holder)) {
660
+ try {
661
+ unlinkSync(lockPath);
662
+ }
663
+ catch (err) {
664
+ if (err?.code !== "ENOENT") {
665
+ return {
666
+ kind: "refused",
667
+ reason: `refusing to reclaim ${lockPath}: this process's abandoned lock record cannot be removed ` +
668
+ `(${err?.code ?? String(err)})`,
669
+ };
670
+ }
671
+ }
672
+ abandonedOwnRecords.delete(lockPath);
673
+ const fresh = makeHolder(now);
674
+ const published = publishLock(lockPath, fresh);
675
+ if (!published.published)
676
+ return { kind: "retry" };
677
+ return { kind: "handle", holder: fresh, dev: published.dev, ino: published.ino };
678
+ }
679
+ // A different (or live) record means the abandoned one is gone.
680
+ abandonedOwnRecords.delete(lockPath);
681
+ let breakable;
109
682
  try {
110
- // O_EXCL: atomic exclusive create — fails with EEXIST if another
111
- // process/racer won the create between our stale-check above and here.
112
- fd = openSync(lockPath, fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_WRONLY, 0o600);
683
+ if (holder.hostname === osHostname()) {
684
+ breakable = holder.pid === process.pid
685
+ ? !liveHolderKeys.has(holderKey(lockPath, holder)) && now() - inspected.mtimeMs > staleMs
686
+ : !deps.isProcessAlive(holder.pid);
687
+ }
688
+ else {
689
+ breakable = now() - inspected.mtimeMs > staleMs;
690
+ }
113
691
  }
114
692
  catch (err) {
115
- const code = err?.code;
116
- if (code === "EEXIST") {
117
- return { acquired: false, reason: "lost the race to acquire the lock file" };
693
+ if (err instanceof MigrationLockProbeError) {
694
+ return { kind: "refused", reason: `${err.name}: ${err.message}` };
118
695
  }
119
696
  throw err;
120
697
  }
698
+ if (!breakable)
699
+ return { kind: "held", holder };
700
+ // Test-only pause between the holder inspection and the rename-over
701
+ // replacement, so a test can put a second contender into that window
702
+ // deterministically (flair#2866).
703
+ txnPausePointSync("migration-lock-reclaim", process.env, undefined, { lockPath });
704
+ const fresh = makeHolder(now);
705
+ let prepared;
121
706
  try {
122
- const info = { pid: process.pid, hostname: osHostname(), startedAt: new Date(now()).toISOString() };
123
- writeSync(fd, JSON.stringify(info));
707
+ prepared = prepareLockRecord(lockPath, fresh);
124
708
  }
125
- finally {
126
- closeSync(fd);
709
+ catch (err) {
710
+ return {
711
+ kind: "refused",
712
+ reason: `refusing to reclaim ${lockPath}: a new holder record cannot be prepared (${err?.code ?? String(err)})`,
713
+ };
714
+ }
715
+ try {
716
+ // Atomic replacement: the old record occupies the name before, the new
717
+ // one after. There is no unlink-first window and no restore step.
718
+ renameSync(prepared.temp, lockPath);
719
+ }
720
+ catch (err) {
721
+ try {
722
+ unlinkSync(prepared.temp);
723
+ }
724
+ catch {
725
+ /* best-effort cleanup of our own unpublished record */
726
+ }
727
+ return {
728
+ kind: "refused",
729
+ reason: `refusing to reclaim ${lockPath}: the new holder record cannot be renamed over it (${err?.code ?? String(err)})`,
730
+ };
731
+ }
732
+ txnPausePointSync("migration-lock-reclaimed", process.env, undefined, { lockPath });
733
+ return { kind: "handle", holder: fresh, dev: prepared.dev, ino: prepared.ino };
734
+ }
735
+ /**
736
+ * Attempts to acquire the migration lock. On success, returns a handle whose
737
+ * `release()` removes the lock file only when it still holds this handle's
738
+ * record, for cooperating holders under the mutex. The cross-host takeover is
739
+ * unfenced, so a replacement between that inspection and the pathname unlink
740
+ * is outside the guarantee. `touch()` updates the mtime of the verified
741
+ * descriptor.
742
+ */
743
+ export function acquireMigrationLock(deps) {
744
+ const defaults = defaultLockDeps(deps.lockPath);
745
+ const resolved = {
746
+ lockPath: deps.lockPath,
747
+ staleMs: deps.staleMs ?? defaults.staleMs,
748
+ isProcessAlive: deps.isProcessAlive ?? defaults.isProcessAlive,
749
+ now: deps.now ?? defaults.now,
750
+ };
751
+ const { lockPath, staleMs, now } = resolved;
752
+ const guardPath = guardPathFor(lockPath);
753
+ if (inProcessHeld) {
754
+ return {
755
+ acquired: false,
756
+ kind: "held",
757
+ reason: "already held in-process (another async caller in this process holds it)",
758
+ };
127
759
  }
128
760
  inProcessHeld = true;
129
- let released = false;
130
- return {
131
- acquired: true,
132
- release: () => {
133
- if (released)
134
- return;
135
- released = true;
761
+ const abortHeld = (reason, holder) => {
762
+ inProcessHeld = false;
763
+ return holder === undefined
764
+ ? { acquired: false, kind: "held", reason }
765
+ : { acquired: false, kind: "held", reason, holder };
766
+ };
767
+ const abortError = (reason) => {
768
+ inProcessHeld = false;
769
+ return { acquired: false, kind: "error", reason };
770
+ };
771
+ try {
772
+ ensureSecureDir(dirname(lockPath));
773
+ }
774
+ catch (err) {
775
+ inProcessHeld = false;
776
+ throw err;
777
+ }
778
+ for (let round = 0; round < LOCK_ACQUISITION_ROUNDS; round++) {
779
+ const guard = acquireGuard(guardPath, resolved);
780
+ if (!("generation" in guard))
781
+ return guard.kind === "held" ? abortHeld(guard.reason) : abortError(guard.reason);
782
+ let outcome;
783
+ try {
784
+ outcome = transitionUnderGuard(lockPath, resolved, staleMs, now);
785
+ }
786
+ catch (err) {
787
+ const released = releaseGuard(guardPath, guard.generation);
788
+ if (!released.ok) {
789
+ return abortError(`${String(err)}; the mutex at ${guardPath} could not be released (${released.reason})`);
790
+ }
136
791
  inProcessHeld = false;
792
+ throw err;
793
+ }
794
+ const released = releaseGuard(guardPath, guard.generation);
795
+ if (!released.ok) {
796
+ if (outcome.kind === "handle")
797
+ rememberAbandonedRecord(lockPath, outcome.holder);
798
+ return abortError(`refusing to return the migration lock at ${lockPath}: the mutex could not be released ` +
799
+ `(${released.reason})`);
800
+ }
801
+ if (outcome.kind === "retry") {
802
+ settleContention();
803
+ continue;
804
+ }
805
+ if (outcome.kind === "refused")
806
+ return abortError(outcome.reason);
807
+ if (outcome.kind === "held") {
808
+ return abortHeld(`held by pid ${outcome.holder.pid} on ${outcome.holder.hostname} since ${outcome.holder.startedAt} (lock ${lockPath})`, outcome.holder);
809
+ }
810
+ return issueHandle(lockPath, outcome.holder, outcome.dev, outcome.ino, now);
811
+ }
812
+ return abortHeld(`lost the race to acquire the lock file (${lockPath})`);
813
+ }
814
+ function makeHolder(now) {
815
+ return { pid: process.pid, hostname: osHostname(), startedAt: new Date(now()).toISOString() };
816
+ }
817
+ function issueHandle(lockPath, holder, dev, ino, now) {
818
+ Object.freeze(holder);
819
+ const guardPath = guardPathFor(lockPath);
820
+ const identity = {
821
+ lockPath,
822
+ holder,
823
+ dev,
824
+ ino,
825
+ release: () => {
826
+ // The public handle was revoked before this runs. End protected work
827
+ // first, then serialize the identity-checked unlink with the mutex.
828
+ txnPausePointSync("migration-lock-release-revoked", process.env, undefined, { lockPath });
829
+ let cleanupFailure = null;
830
+ // What this release established about the record, so a later failure
831
+ // does not claim more than the release observed.
832
+ let recordOutcome = "unknown";
833
+ let recordNotInspected = false;
137
834
  try {
138
- unlinkSync(lockPath);
835
+ const guard = acquireGuard(guardPath, defaultLockDeps(lockPath));
836
+ if (!("generation" in guard)) {
837
+ rememberAbandonedRecord(lockPath, holder);
838
+ recordNotInspected = true;
839
+ cleanupFailure = `the mutex could not be acquired: ${guard.reason}`;
840
+ }
841
+ else {
842
+ txnPausePointSync("migration-lock-release-guard", process.env, undefined, { lockPath, guardPath });
843
+ try {
844
+ const inspected = inspectLock(lockPath);
845
+ if (inspected.state === "unreadable") {
846
+ cleanupFailure = `the lock file cannot be inspected: ${inspected.detail}`;
847
+ }
848
+ else if (inspected.state === "held" &&
849
+ inspected.dev === dev &&
850
+ inspected.ino === ino &&
851
+ sameHolder(inspected.holder, holder)) {
852
+ txnPausePointSync("migration-lock-release-verified", process.env, undefined, { lockPath });
853
+ try {
854
+ unlinkSync(lockPath);
855
+ recordOutcome = "removed";
856
+ txnPausePointSync("migration-lock-release-unlinked", process.env, undefined, { lockPath });
857
+ }
858
+ catch (err) {
859
+ if (err?.code === "ENOENT") {
860
+ recordOutcome = "absent";
861
+ }
862
+ else {
863
+ recordOutcome = "unknown";
864
+ cleanupFailure = `the lock file cannot be removed (${err?.code ?? String(err)})`;
865
+ }
866
+ }
867
+ }
868
+ else if (inspected.state === "absent") {
869
+ recordOutcome = "absent";
870
+ }
871
+ else {
872
+ recordOutcome = "present";
873
+ }
874
+ // A different record belongs to someone else and an absent record
875
+ // belongs to nobody: leave both.
876
+ }
877
+ catch (err) {
878
+ cleanupFailure = `the lock file cannot be inspected (${err?.code ?? String(err)})`;
879
+ }
880
+ const released = releaseGuard(guardPath, guard.generation);
881
+ if (!released.ok && cleanupFailure === null)
882
+ cleanupFailure = released.reason;
883
+ }
139
884
  }
140
- catch {
141
- /* already gone — fine */
885
+ catch (err) {
886
+ cleanupFailure = `the mutex could not be used (${err?.code ?? String(err)})`;
887
+ }
888
+ finally {
889
+ inProcessHeld = false;
890
+ }
891
+ if (cleanupFailure !== null) {
892
+ // Release runs in the runner's finally: it must not throw, but an
893
+ // uncertain cleanup is reported rather than silently ignored.
894
+ const recordState = recordOutcome === "removed"
895
+ ? "The lock record was removed by this release"
896
+ : recordOutcome === "absent"
897
+ ? "No lock record was present"
898
+ : recordOutcome === "present"
899
+ ? "The lock record is left in place"
900
+ : recordNotInspected
901
+ ? "The lock record was not inspected because the mutex could not be taken, so its state is unknown; a later acquisition by this process removes it only after taking the mutex and finding this exact record with no live handle"
902
+ : "The lock record's state is unknown";
903
+ console.warn(`[flair-migrations] migration lock cleanup failed for ${lockPath}: ${cleanupFailure}. ` +
904
+ `${recordState}; inspect the lock and its mutex before the next migration cycle`);
142
905
  }
143
906
  },
144
907
  touch: () => {
145
908
  const t = new Date(now());
909
+ let fd;
146
910
  try {
147
- utimesSync(lockPath, t, t);
911
+ fd = openSync(lockPath, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);
912
+ const st = fstatSync(fd);
913
+ if (!st.isFile() || st.dev !== dev || st.ino !== ino)
914
+ return;
915
+ let raw;
916
+ try {
917
+ raw = JSON.parse(readFileSync(fd, "utf-8"));
918
+ }
919
+ catch {
920
+ return;
921
+ }
922
+ const record = parseHolder(raw);
923
+ if (record === null || !sameHolder(record, holder))
924
+ return;
925
+ txnPausePointSync("migration-lock-touch-verified", process.env, undefined, { lockPath });
926
+ // Same still-open descriptor: a later pathname replacement cannot
927
+ // redirect this update to a successor's file.
928
+ futimesSync(fd, t, t);
148
929
  }
149
930
  catch {
150
931
  /* best-effort heartbeat — a failed touch must never break the migration */
151
932
  }
933
+ finally {
934
+ if (fd !== undefined) {
935
+ try {
936
+ closeSync(fd);
937
+ }
938
+ catch {
939
+ /* best-effort close */
940
+ }
941
+ }
942
+ }
152
943
  },
153
944
  };
945
+ liveHolderKeys.add(holderKey(lockPath, holder));
946
+ return new MigrationLockHandle(HANDLE_KEY, identity);
154
947
  }