@tpsdev-ai/flair 0.62.0 → 0.63.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (257) hide show
  1. package/README.md +14 -13
  2. package/SECURITY.md +73 -43
  3. package/config.yaml +11 -11
  4. package/dist/bridges/runtime/execute.js +1 -0
  5. package/dist/bridges/runtime/import-runner.js +4 -0
  6. package/dist/bridges/types.js +1 -0
  7. package/dist/build-info.json +3 -3
  8. package/dist/cli.js +309 -205
  9. package/dist/commands/agent.js +325 -137
  10. package/dist/commands/attention.js +2 -0
  11. package/dist/commands/backup-approval.js +218 -0
  12. package/dist/commands/backup.js +37 -33
  13. package/dist/commands/bootstrap.js +5 -1
  14. package/dist/commands/bridge.js +10 -0
  15. package/dist/commands/deploy.js +37 -7
  16. package/dist/commands/doctor.js +206 -42
  17. package/dist/commands/export.js +144 -15
  18. package/dist/commands/federation.js +653 -68
  19. package/dist/commands/grant.js +5 -6
  20. package/dist/commands/help.js +25 -0
  21. package/dist/commands/idp.js +14 -19
  22. package/dist/commands/import.js +167 -34
  23. package/dist/commands/init.js +380 -164
  24. package/dist/commands/integrity.js +5 -6
  25. package/dist/commands/keys.js +12 -8
  26. package/dist/commands/mcp.js +157 -79
  27. package/dist/commands/memory.js +38 -17
  28. package/dist/commands/migrate-harness-memory.js +9 -3
  29. package/dist/commands/orgevent.js +5 -10
  30. package/dist/commands/principal.js +32 -39
  31. package/dist/commands/quality.js +26 -3
  32. package/dist/commands/reembed.js +468 -111
  33. package/dist/commands/rem.js +484 -65
  34. package/dist/commands/restore.js +352 -44
  35. package/dist/commands/search.js +2 -0
  36. package/dist/commands/service.js +109 -2
  37. package/dist/commands/soul.js +0 -6
  38. package/dist/commands/status.js +165 -124
  39. package/dist/commands/test.js +4 -1
  40. package/dist/commands/upgrade.js +53 -22
  41. package/dist/commands/workspace.js +7 -8
  42. package/dist/deploy.js +59 -3
  43. package/dist/doctor-client.js +9 -25
  44. package/dist/fabric-upgrade.js +12 -2
  45. package/dist/federation/presence-send.js +139 -0
  46. package/dist/federation/scheduler.js +148 -12
  47. package/dist/federation-verify.js +269 -177
  48. package/dist/install/clients.js +171 -35
  49. package/dist/keystore.js +77 -10
  50. package/dist/lib/agent-id-rule.js +44 -2
  51. package/dist/lib/agent-key-file.js +509 -0
  52. package/dist/lib/agent-rotation-lock.js +249 -0
  53. package/dist/lib/atomic-write.js +3 -3
  54. package/dist/lib/auth-resolve.js +1040 -64
  55. package/dist/lib/backup-approval-store.js +612 -0
  56. package/dist/lib/backup-artifact.js +343 -0
  57. package/dist/lib/config-critical-section.js +212 -25
  58. package/dist/lib/connect-phase.js +33 -0
  59. package/dist/lib/daemon-liveness.js +2 -1
  60. package/dist/lib/federation-pair-access.js +4 -0
  61. package/dist/lib/federation-retry-queue.js +283 -0
  62. package/dist/lib/federation-retry-row.js +101 -0
  63. package/dist/lib/instruction-event-contract.js +17 -0
  64. package/dist/lib/instruction-event-doctor.js +102 -0
  65. package/dist/lib/key-dir.js +203 -0
  66. package/dist/lib/launchd-management.js +21 -6
  67. package/dist/lib/local-instance-pair.js +8 -1
  68. package/dist/lib/mcp-enable.js +14 -15
  69. package/dist/lib/memory-attributes.js +2 -0
  70. package/dist/lib/memory-provider-timeout.js +33 -0
  71. package/dist/lib/mqtt-config.js +132 -0
  72. package/dist/lib/mqtt-listener-doctor.js +104 -0
  73. package/dist/lib/node-alias-path.js +50 -2
  74. package/dist/lib/open-live-row.js +20 -0
  75. package/dist/lib/ops-url.js +52 -0
  76. package/dist/lib/promotion-content-hash.js +20 -0
  77. package/dist/lib/remote-admin-pass.js +157 -0
  78. package/dist/lib/restore-archive.js +760 -0
  79. package/dist/lib/restore-verify.js +1 -1
  80. package/dist/lib/scheduler-platform.js +13 -0
  81. package/dist/lib/service-repoint.js +13 -4
  82. package/dist/lib/skill-assignment-preflight.js +159 -0
  83. package/dist/lib/skill-seed.js +125 -10
  84. package/dist/lib/skill-tombstone-doctor.js +133 -0
  85. package/dist/lib/soul-scope-fields.js +26 -0
  86. package/dist/lib/terminal-text.js +32 -0
  87. package/dist/lib/uninstall-purge.js +266 -11
  88. package/dist/lib/upgrade-prior-liveness.js +2 -1
  89. package/dist/mcp-client-assertion.js +7 -14
  90. package/dist/memory-id-checkpoint.js +28 -7
  91. package/dist/mqtt-off-deploy.js +550 -0
  92. package/dist/rem/promote-policy.js +3 -3
  93. package/dist/rem/restore.js +302 -26
  94. package/dist/rem/runner.js +220 -58
  95. package/dist/rem/scheduler.js +21 -4
  96. package/dist/resources/A2AAdapter.js +131 -178
  97. package/dist/resources/AdminMemory.js +2 -0
  98. package/dist/resources/AdminMemoryCandidates.js +116 -0
  99. package/dist/resources/Agent.js +155 -45
  100. package/dist/resources/AgentCard.js +4 -0
  101. package/dist/resources/AgentKeyRegister.js +56 -22
  102. package/dist/resources/AgentReadPosition.js +7 -0
  103. package/dist/resources/AgentSeed.js +232 -107
  104. package/dist/resources/AutoPromoteCandidates.js +413 -84
  105. package/dist/resources/Credential.js +6 -8
  106. package/dist/resources/Federation.js +219 -57
  107. package/dist/resources/FederationRetry.js +4 -4
  108. package/dist/resources/InstructionVersion.js +1 -1
  109. package/dist/resources/MCPClientMetadata.js +6 -3
  110. package/dist/resources/Memory.js +1348 -271
  111. package/dist/resources/MemoryArchive.js +149 -64
  112. package/dist/resources/MemoryBootstrap.js +12 -22
  113. package/dist/resources/MemoryCandidate.js +16 -2
  114. package/dist/resources/MemoryConsolidate.js +2 -2
  115. package/dist/resources/MemoryFeed.js +360 -147
  116. package/dist/resources/MemoryMaintenance.js +290 -72
  117. package/dist/resources/MemoryPurge.js +138 -22
  118. package/dist/resources/MemoryReflect.js +68 -14
  119. package/dist/resources/MemoryReindex.js +91 -13
  120. package/dist/resources/Message.js +11 -2
  121. package/dist/resources/OAuth.js +156 -39
  122. package/dist/resources/OAuthClient.js +1 -1
  123. package/dist/resources/OrgEvent.js +292 -29
  124. package/dist/resources/OrgEventCatchup.js +7 -0
  125. package/dist/resources/OrgEventMaintenance.js +48 -10
  126. package/dist/resources/PairingToken.js +1 -1
  127. package/dist/resources/Presence.js +31 -11
  128. package/dist/resources/PromoteMemoryCandidate.js +8 -2
  129. package/dist/resources/RecordUsage.js +2 -4
  130. package/dist/resources/Soul.js +2 -0
  131. package/dist/resources/SoulFeed.js +2 -1
  132. package/dist/resources/WorkspaceLatest.js +4 -0
  133. package/dist/resources/XAA.js +36 -10
  134. package/dist/resources/a2a-stream.js +313 -0
  135. package/dist/resources/a2a-url.js +4 -5
  136. package/dist/resources/agent-admin.js +10 -1
  137. package/dist/resources/agent-auth.js +98 -68
  138. package/dist/resources/agent-read-position-lib.js +4 -1
  139. package/dist/resources/agent-status-guard.js +9 -7
  140. package/dist/resources/auth-middleware.js +166 -42
  141. package/dist/resources/authority-field-guard.js +9 -11
  142. package/dist/resources/auto-promote-lib.js +8 -5
  143. package/dist/resources/basic-auth-header.js +21 -0
  144. package/dist/resources/bm25-index-service.js +4 -5
  145. package/dist/resources/dedup-cluster.js +6 -1
  146. package/dist/resources/embeddings-provider.js +25 -0
  147. package/dist/resources/federation-classify.js +89 -0
  148. package/dist/resources/federation-retry-lib.js +6 -81
  149. package/dist/resources/health.js +75 -19
  150. package/dist/resources/host-pointer/registry.js +29 -0
  151. package/dist/resources/host-pointer-adapter.js +1 -0
  152. package/dist/resources/in-process-api.js +74 -11
  153. package/dist/resources/in-process.js +24 -22
  154. package/dist/resources/instruction-version-record.js +251 -7
  155. package/dist/resources/internal-authority.js +13 -0
  156. package/dist/resources/mcp-client-metadata-fields.js +4 -0
  157. package/dist/resources/mcp-handler.js +146 -13
  158. package/dist/resources/mcp-oauth-flag.js +12 -14
  159. package/dist/resources/mcp-oauth.js +446 -53
  160. package/dist/resources/mcp-tool-scopes.js +69 -0
  161. package/dist/resources/mcp-tools.js +70 -22
  162. package/dist/resources/memory-declared-attributes.js +1 -0
  163. package/dist/resources/memory-embed-hash.js +56 -0
  164. package/dist/resources/memory-host-source.js +5 -2
  165. package/dist/resources/memory-reflect-lib.js +1 -1
  166. package/dist/resources/memory-write-lock.js +202 -23
  167. package/dist/resources/memory-write-response.js +1 -1
  168. package/dist/resources/memory-write-transaction.js +243 -0
  169. package/dist/resources/migration-boot.js +17 -12
  170. package/dist/resources/migrations/boot-progress.js +25 -0
  171. package/dist/resources/migrations/data-dir.js +16 -3
  172. package/dist/resources/migrations/dir-safety.js +60 -2
  173. package/dist/resources/migrations/embedding-stamp.js +315 -49
  174. package/dist/resources/migrations/graph-heal.js +9 -2
  175. package/dist/resources/migrations/ledger.js +5 -2
  176. package/dist/resources/migrations/lock.js +867 -80
  177. package/dist/resources/migrations/progress.js +71 -10
  178. package/dist/resources/migrations/runner.js +212 -18
  179. package/dist/resources/migrations/state.js +36 -1
  180. package/dist/resources/migrations/status.js +2 -13
  181. package/dist/resources/migrations/synthetic-test-migration.js +78 -12
  182. package/dist/resources/migrations/types.js +26 -1
  183. package/dist/resources/migrations/visibility-backfill.js +111 -70
  184. package/dist/resources/oauth-discovery.js +0 -5
  185. package/dist/resources/object-body-guard.js +12 -5
  186. package/dist/resources/org-event-reserved.js +92 -0
  187. package/dist/resources/org-event-write-fault.js +19 -0
  188. package/dist/resources/owner-field-guard.js +1 -1
  189. package/dist/resources/owner-scoped-write-policy.js +65 -21
  190. package/dist/resources/owner-scoped-writes.js +37 -6
  191. package/dist/resources/path-id-rewrite.js +76 -0
  192. package/dist/resources/presence-internal.js +5 -5
  193. package/dist/resources/promotion-binding.js +43 -0
  194. package/dist/resources/promotion-stamp.js +124 -33
  195. package/dist/resources/protocol-context.js +189 -0
  196. package/dist/resources/record-type-kit.js +2 -4
  197. package/dist/resources/request-target.js +28 -1
  198. package/dist/resources/request-transaction.js +11 -1
  199. package/dist/resources/seed-reservation.js +1 -2
  200. package/dist/resources/semantic-retrieval-core.js +7 -6
  201. package/dist/resources/server-row-validation.js +71 -0
  202. package/dist/resources/skill-manifest.js +4 -3
  203. package/dist/resources/skill-version-write.js +400 -27
  204. package/dist/resources/skill-write-fault.js +6 -3
  205. package/dist/resources/skill-write-policy.js +2 -1
  206. package/dist/resources/soul-write-policy.js +26 -7
  207. package/dist/resources/table-helpers.js +1 -1
  208. package/dist/resources/table-subscription-policy.js +518 -85
  209. package/dist/resources/table-subscriptions.js +20 -7
  210. package/dist/resources/txn-pause-point.js +122 -5
  211. package/dist/resources/usage-recording.js +54 -46
  212. package/dist/resources/write-back.js +176 -11
  213. package/dist/resources/write-journal-context.js +5 -0
  214. package/dist/resources/write-journal.js +289 -0
  215. package/dist/src/keystore.js +77 -10
  216. package/dist/src/lib/agent-id-rule.js +44 -2
  217. package/dist/src/lib/atomic-write.js +3 -3
  218. package/dist/src/lib/federation-retry-row.js +101 -0
  219. package/dist/src/lib/instruction-event-contract.js +17 -0
  220. package/dist/src/lib/key-dir.js +203 -0
  221. package/dist/src/lib/memory-attributes.js +2 -0
  222. package/dist/src/lib/open-live-row.js +20 -0
  223. package/dist/src/lib/scheduler-platform.js +13 -0
  224. package/dist/src/lib/soul-scope-fields.js +26 -0
  225. package/dist/src/rem/promote-policy.js +3 -3
  226. package/dist/src/rem/scheduler.js +21 -4
  227. package/docs/access-control.md +39 -21
  228. package/docs/api-reference.md +161 -52
  229. package/docs/auth.md +69 -38
  230. package/docs/claude-code.md +3 -3
  231. package/docs/deploying-on-fabric.md +118 -2
  232. package/docs/deployment.md +17 -0
  233. package/docs/embedding-in-a-harper-app.md +23 -21
  234. package/docs/entity-vocabulary.md +7 -11
  235. package/docs/federation.md +29 -2
  236. package/docs/hosted-on-fabric.md +1 -1
  237. package/docs/integrations.md +11 -11
  238. package/docs/mcp-clients.md +7 -5
  239. package/docs/notes/mcp-agent-auth-consumer.md +4 -9
  240. package/docs/notes/mcp-oauth-model2.md +6 -6
  241. package/docs/openclaw.md +1 -1
  242. package/docs/quickstart-fabric.md +2 -2
  243. package/docs/quickstart.md +3 -3
  244. package/docs/releasing.md +13 -13
  245. package/docs/rem.md +24 -3
  246. package/docs/secrets-and-keys.md +9 -14
  247. package/docs/standalone-local.md +29 -2
  248. package/docs/supply-chain-policy.md +28 -20
  249. package/docs/the-team.md +2 -2
  250. package/docs/upgrade.md +29 -5
  251. package/package.json +18 -11
  252. package/schemas/agent.graphql +3 -3
  253. package/schemas/federation.graphql +10 -7
  254. package/schemas/memory.graphql +7 -2
  255. package/templates/bin/flair-rem-nightly.sh.tmpl +7 -1
  256. package/templates/launchd/start-flair-with-admin-pass.sh +188 -10
  257. package/dist/resources/soul-adk-guard.js +0 -68
@@ -0,0 +1,249 @@
1
+ /**
2
+ * agent-rotation-lock.ts — a rotation lock for one agent in one keys directory,
3
+ * for `flair agent rotate-key` (flair#3151).
4
+ *
5
+ * Two rotations of one agent that use the same keys directory used to
6
+ * interleave: each read the current key, staged its own, sent the ops `update`,
7
+ * then renamed its staged key over the current one. The stored public key could
8
+ * end up matching neither private key on disk. The lock serializes rotations of
9
+ * one agent that use the same keys directory on a filesystem with reliable
10
+ * exclusive create; it is taken BEFORE the current key is read and held
11
+ * through the read-back check, the rename and the
12
+ * public-key write. Rotations that use different keys directories do not share
13
+ * it, and a server-side compare-and-set for the Agent row is out of scope.
14
+ *
15
+ * Conventions follow src/lib/config-critical-section.ts:
16
+ * - the lock is an `O_EXCL` create of a file in the keys dir named for the
17
+ * agent; its content is `<pid> <iso> <hostname>` for diagnosis only and is
18
+ * never an authorization input (a blank or partial record refuses).
19
+ * - acquisition retries a bounded number of times, then refuses, if the lock
20
+ * still exists after the retries, with a NAMED message that names the lock
21
+ * file and says to remove it only once no rotation of that agent is running.
22
+ * - a lock path that is not a regular file (a FIFO, a directory, a symlink)
23
+ * is refused at once, before it is read.
24
+ * - there is no reclaim, no age-out and no pid-liveness shortcut: a lock left
25
+ * by a killed run keeps refusing until an operator removes it.
26
+ * - release attempts to remove the lock file when that path still has the
27
+ * device and inode recorded at create. That is an lstat then unlink, not an
28
+ * atomic remove. A leaked lock refuses the next rotation; it never corrupts
29
+ * a key file.
30
+ *
31
+ * Release runs from an explicit `release()` and from a `process.once("exit")`
32
+ * listener registered with the lock. `flair agent rotate-key` exits with
33
+ * `process.exit(1)` on many failure paths, and `finally` does not run on
34
+ * `process.exit`.
35
+ *
36
+ * On filesystems where `O_EXCL` is unreliable (NFS/SMB) the lock may not
37
+ * serialize at all; that is the same residual config-critical-section.ts names.
38
+ */
39
+ import { closeSync, constants, existsSync, fstatSync, lstatSync, openSync, readFileSync, unlinkSync, writeFileSync, writeSync, } from "node:fs";
40
+ import { hostname } from "node:os";
41
+ import { join } from "node:path";
42
+ /** Lock acquisition: bounded retry (default 40 × 50 ms). */
43
+ export const AGENT_ROTATION_LOCK_RETRY = { attempts: 40, delayMs: 50 };
44
+ /**
45
+ * Test hook; production leaves it unset. It may return the open flags for the
46
+ * diagnostic holder read, so a test can present a platform that defines
47
+ * neither `O_NOFOLLOW` nor `O_NONBLOCK`.
48
+ */
49
+ let beforeHolderOpen;
50
+ export function setAgentRotationLockTestHook(hook) {
51
+ beforeHolderOpen = hook;
52
+ }
53
+ /** The lock path for one agent in one keys directory. */
54
+ export function agentRotationLockPath(keysDir, id) {
55
+ return join(keysDir, `${id}.rotate-key.lock`);
56
+ }
57
+ /** Synchronous backoff without a sleep primitive that differs between bun and node. */
58
+ function sleepSync(ms) {
59
+ if (ms <= 0)
60
+ return;
61
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
62
+ }
63
+ function message(err) {
64
+ return err instanceof Error ? err.message : String(err);
65
+ }
66
+ function parseLockHolder(raw) {
67
+ if (!raw)
68
+ return null;
69
+ const m = raw.trim().match(/^(\d+)\s+(\S+)\s+(\S+)$/);
70
+ if (!m)
71
+ return null;
72
+ return { pid: m[1], timestamp: m[2], host: m[3] };
73
+ }
74
+ /** What an existing entry at the lock path is, by lstat alone (never a read). */
75
+ function lockPathKind(lockPath) {
76
+ try {
77
+ const st = lstatSync(lockPath);
78
+ if (st.isFile())
79
+ return "regular";
80
+ if (st.isDirectory())
81
+ return "a directory";
82
+ if (st.isSymbolicLink())
83
+ return "a symlink";
84
+ if (st.isFIFO())
85
+ return "a FIFO";
86
+ if (st.isSocket())
87
+ return "a socket";
88
+ if (st.isCharacterDevice())
89
+ return "a character device";
90
+ if (st.isBlockDevice())
91
+ return "a block device";
92
+ return "a non-regular file";
93
+ }
94
+ catch (err) {
95
+ if (err.code === "ENOENT")
96
+ return "missing";
97
+ return `could not check the lock path (${err.code ?? "unknown"})`;
98
+ }
99
+ }
100
+ function nonRegularLockRefusal(lockPath, id, kind) {
101
+ return (`refusing to rotate agent '${id}': ${kind.startsWith("could not check") ? `${kind}: ${lockPath}` : `the rotation lock path ${lockPath} is not a regular file (lstat reports ${kind})`}. ` +
102
+ `Remove ${lockPath} only once no rotation of that agent is running.`);
103
+ }
104
+ /**
105
+ * Read the diagnostic holder record from a regular lock file only. Without
106
+ * `O_NOFOLLOW` the open could follow a symlink swapped in after the lstat;
107
+ * without `O_NONBLOCK` it could block on a FIFO swapped in the same way. When
108
+ * `O_RDONLY`, `O_NOFOLLOW` or `O_NONBLOCK` is not defined, there is no holder
109
+ * diagnostic.
110
+ */
111
+ function readLockHolder(lockPath, flags = constants) {
112
+ if (typeof flags.O_RDONLY !== "number" ||
113
+ typeof flags.O_NOFOLLOW !== "number" ||
114
+ typeof flags.O_NONBLOCK !== "number") {
115
+ return null;
116
+ }
117
+ let fd;
118
+ try {
119
+ fd = openSync(lockPath, flags.O_RDONLY | flags.O_NOFOLLOW | flags.O_NONBLOCK);
120
+ }
121
+ catch {
122
+ return null;
123
+ }
124
+ try {
125
+ if (!fstatSync(fd).isFile())
126
+ return null;
127
+ return readFileSync(fd, "utf-8");
128
+ }
129
+ catch {
130
+ return null;
131
+ }
132
+ finally {
133
+ try {
134
+ closeSync(fd);
135
+ }
136
+ catch {
137
+ // already closed
138
+ }
139
+ }
140
+ }
141
+ function refusalLine(lockPath, id, holder) {
142
+ const parsed = parseLockHolder(holder);
143
+ const who = parsed
144
+ ? `recorded holder pid ${parsed.pid} since ${parsed.timestamp} on host ${parsed.host}`
145
+ : "an unreadable or malformed lock record";
146
+ return (`an existing lock at ${lockPath} (${who}); refusing to rotate agent '${id}' without the lock. ` +
147
+ `Remove ${lockPath} only once no rotation of that agent is running.`);
148
+ }
149
+ function makeHandle(lockPath, identity) {
150
+ let released = false;
151
+ const release = () => {
152
+ if (released)
153
+ return;
154
+ released = true;
155
+ process.removeListener("exit", release);
156
+ try {
157
+ const st = lstatSync(lockPath, { bigint: true });
158
+ if (st.dev !== identity.dev || st.ino !== identity.ino)
159
+ return;
160
+ unlinkSync(lockPath);
161
+ }
162
+ catch {
163
+ // ENOENT: the lock is already gone. Any other failure leaves a lock that
164
+ // refuses the next rotation; it never touches a key file.
165
+ }
166
+ };
167
+ process.once("exit", release);
168
+ return { path: lockPath, release };
169
+ }
170
+ /**
171
+ * Take the per-agent rotation lock, or refuse by name. An existing lock
172
+ * is retried within the bound and then refused; the caller must exit without
173
+ * reading or writing any key file.
174
+ */
175
+ export function acquireAgentRotationLock(opts) {
176
+ const lockPath = opts.lockPath ?? agentRotationLockPath(opts.keysDir, opts.id);
177
+ const retry = { ...AGENT_ROTATION_LOCK_RETRY, ...opts.retry };
178
+ for (let i = 0; i < retry.attempts; i++) {
179
+ let fd;
180
+ try {
181
+ fd = openSync(lockPath, "wx", 0o600);
182
+ }
183
+ catch (err) {
184
+ if (err.code !== "EEXIST") {
185
+ return {
186
+ ok: false,
187
+ message: `could not create the rotation lock ${lockPath} (${message(err)}); no key file was changed`,
188
+ };
189
+ }
190
+ const kind = lockPathKind(lockPath);
191
+ if (kind !== "regular" && kind !== "missing") {
192
+ return { ok: false, message: nonRegularLockRefusal(lockPath, opts.id, kind) };
193
+ }
194
+ if (i < retry.attempts - 1)
195
+ sleepSync(retry.delayMs);
196
+ continue;
197
+ }
198
+ try {
199
+ const st = fstatSync(fd, { bigint: true });
200
+ const identity = { dev: st.dev, ino: st.ino };
201
+ try {
202
+ // Diagnostic only: never an authorization input.
203
+ writeSync(fd, `${process.pid} ${new Date().toISOString()} ${hostname()}\n`);
204
+ }
205
+ catch {
206
+ // The lock exists (that is what protects us); a failed diagnostic
207
+ // write is not fatal.
208
+ }
209
+ return { ok: true, lock: makeHandle(lockPath, identity) };
210
+ }
211
+ finally {
212
+ try {
213
+ closeSync(fd);
214
+ }
215
+ catch {
216
+ // already closed
217
+ }
218
+ }
219
+ }
220
+ const kind = lockPathKind(lockPath);
221
+ if (kind !== "regular" && kind !== "missing") {
222
+ return { ok: false, message: nonRegularLockRefusal(lockPath, opts.id, kind) };
223
+ }
224
+ const hookResult = kind === "regular" ? beforeHolderOpen?.(lockPath) : undefined;
225
+ const hookFlags = typeof hookResult === "object" ? hookResult : undefined;
226
+ const holder = kind === "regular" ? readLockHolder(lockPath, hookFlags ?? constants) : null;
227
+ return { ok: false, message: refusalLine(lockPath, opts.id, holder) };
228
+ }
229
+ /**
230
+ * ENV-GATED test barrier for the real-server interleave test: after marking its
231
+ * own `.ready` file, a rotation waits (bounded) for the `.go` file the test
232
+ * drops. Inert unless `FLAIR_TEST_ROTATE_KEY_PAUSE` names a base path.
233
+ *
234
+ * TRUSTED-ENV ASSUMPTION: this path is only as privileged as the environment
235
+ * that starts the CLI; a caller who can set it can already set `FLAIR_*` and
236
+ * run the command itself. The polling loop is bounded.
237
+ */
238
+ export async function agentRotationTestPause() {
239
+ const base = process.env.FLAIR_TEST_ROTATE_KEY_PAUSE;
240
+ if (!base)
241
+ return;
242
+ writeFileSync(`${base}.ready`, `${process.pid}\n`);
243
+ for (let i = 0; i < 1200; i++) {
244
+ if (existsSync(`${base}.go`))
245
+ return;
246
+ await new Promise((resolve) => setTimeout(resolve, 25));
247
+ }
248
+ throw new Error(`rotation test pause at ${base} timed out waiting for ${base}.go`);
249
+ }
@@ -47,7 +47,7 @@ function resolveHooks(h) {
47
47
  return {
48
48
  open: h.open ?? ((p, flags, mode) => openSync(p, flags, mode)),
49
49
  write: h.write ?? ((fd, data) => {
50
- const buf = Buffer.from(data, "utf-8");
50
+ const buf = typeof data === "string" ? Buffer.from(data, "utf-8") : Buffer.from(data);
51
51
  let off = 0;
52
52
  while (off < buf.length)
53
53
  off += writeSync(fd, buf, off, buf.length - off);
@@ -148,7 +148,7 @@ function stage(fs, target, content, mode) {
148
148
  return tmp;
149
149
  }
150
150
  /** Best-effort directory fsync so the renames themselves are durable. */
151
- function fsyncDir(dir) {
151
+ export function fsyncDir(dir) {
152
152
  try {
153
153
  const fd = openSync(dir, "r");
154
154
  try {
@@ -184,7 +184,7 @@ export function writeFilesAtomically(entries, hooks = {}) {
184
184
  if (!fs.exists(e.path))
185
185
  return { path: e.path, existed: false };
186
186
  // A planned-from target is restored from the bytes it was re-checked to hold.
187
- const content = e.expect ? e.expect.content : fs.read(e.path);
187
+ const content = e.expect ? Buffer.from(e.expect.content, "utf-8") : fs.readBytes(e.path);
188
188
  return { path: e.path, existed: true, content, mode: fs.modeOf(e.path) };
189
189
  });
190
190
  // 2. Stage every new file. Nothing visible has changed yet.