@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,343 @@
1
+ /**
2
+ * backup-artifact.ts — a `flair backup` archive and its detached SHA-256
3
+ * digest, published and read as one artifact (flair#2664 slice 1b).
4
+ *
5
+ * The artifact is two files: the archive at the output path, and a sidecar at
6
+ * `<archive>.sha256` that records the SHA-256 of the archive's exact bytes in
7
+ * the `sha256sum` line format, `<64 lowercase hex> <archive file name>\n`.
8
+ * From the archive's directory, `shasum -a 256 -c` and GNU `sha256sum -c`
9
+ * check it. A file name holding a backslash, line feed or carriage return is
10
+ * escaped the way GNU coreutils 9 escapes it: the line starts with `\` and
11
+ * those characters are written as `\\`, `\n` and `\r`. Perl `shasum` reads the
12
+ * backslash and line-feed escapes but not `\r`; the BSD `sha256sum` that ships
13
+ * with macOS reads only unescaped lines. Restore checks the digest, the line
14
+ * framing, the escaping and that the name is UTF-8 (as the formatter writes
15
+ * it), and does not compare the name with the archive's file name, so a pair
16
+ * renamed together still verifies.
17
+ *
18
+ * The sidecar detects a damaged, truncated or substituted archive and an
19
+ * archive paired with another backup's digest. It is not an authenticity
20
+ * check: anyone who can write both files can write a matching pair.
21
+ *
22
+ * PUBLICATION (publishBackupArtifact). Both files are staged in a new
23
+ * directory beside the output path (the same filesystem, so each rename is
24
+ * atomic), then published in this order:
25
+ *
26
+ * 1. stage-archive write the serialized archive to the staging directory
27
+ * 2. sync-archive fsync it
28
+ * 3. verify-archive read it back once; the caller's checks run on that
29
+ * text, the bytes must equal the serialized bytes, and
30
+ * the digest is the SHA-256 of those bytes
31
+ * 4. stage-digest write and fsync the sidecar in the staging directory
32
+ * 5. remove-old-digest remove any sidecar already at `<output>.sha256`
33
+ * 6. publish-archive rename the staged archive over the output path
34
+ * 7. publish-digest rename the staged sidecar to `<output>.sha256`
35
+ *
36
+ * The directory is fsynced after steps 5, 6 and 7. Steps 1–4 touch only the
37
+ * staging directory. Step 5 removes the old digest before the archive can
38
+ * change, and step 7 publishes the new digest only after the new archive is in
39
+ * place. With one backup writing the output path, and starting from no files,
40
+ * a consistent pair, an archive with no sidecar, or a sidecar with no archive,
41
+ * a crash at any point leaves one of: the starting state (steps 1–5), the
42
+ * previous archive with no sidecar or no files (step 6), the new archive with
43
+ * no sidecar (step 7), or the new pair. Only the fourth starting state is
44
+ * inconsistent, and step 5 removes its sidecar before anything is published.
45
+ * A sidecar this backup writes never sits beside bytes it does not describe,
46
+ * and restore refuses an archive with no sidecar unless this host holds a
47
+ * valid approval for those exact bytes. A process crash needs no
48
+ * fsync for this, because each step is one rename or unlink applied in order.
49
+ * Surviving power loss in this order relies on the directory fsync, which is
50
+ * best-effort (atomic-write.ts fsyncDir): on a filesystem that cannot fsync a
51
+ * directory, the order is not guaranteed to survive power loss.
52
+ *
53
+ * Two backups writing the same output path at once are not serialized. They
54
+ * can leave an archive beside the other backup's sidecar (one publishes its
55
+ * pair, then the other replaces the archive and stops before publishing its
56
+ * digest); restore refuses such a pair as a digest mismatch.
57
+ *
58
+ * The staging directory is removed after publication and after a failure.
59
+ * That removal is an attempt that can fail: a failure is reported (as
60
+ * `stagingLeft` on success, appended to the error on failure) and does not
61
+ * change what the result says about the published names.
62
+ *
63
+ * READING (readBackupArtifact). The archive is read once. parseRestoreArchive
64
+ * (restore-archive.ts) hashes that buffer and parses the same buffer. The
65
+ * sidecar is read once and its digest must equal that hash; only then is the
66
+ * parse result considered. Nothing here writes anything. Every refusal names
67
+ * the file and what did not hold and gives a remedy that does not assume
68
+ * which file is at fault. By default it also says restore stopped before any
69
+ * write; a caller that is not restore (`flair backup-approval approve`)
70
+ * passes its own clause. A missing sidecar is one whose path does not exist
71
+ * at all: a symbolic link at the sidecar path whose target is missing is
72
+ * refused as unreadable, never treated as missing.
73
+ */
74
+ import { createHash } from "node:crypto";
75
+ import { lstatSync, mkdirSync, mkdtempSync, openSync, closeSync, fsyncSync, readFileSync, renameSync, rmSync, unlinkSync, writeFileSync } from "node:fs";
76
+ import { basename, dirname, join } from "node:path";
77
+ import { fsyncDir } from "./atomic-write.js";
78
+ import { parseRestoreArchive } from "./restore-archive.js";
79
+ /** The sidecar's file name is the archive's file name plus this suffix. */
80
+ export const BACKUP_DIGEST_SUFFIX = ".sha256";
81
+ /** Where the digest sidecar for `archivePath` lives. */
82
+ export function backupDigestPath(archivePath) {
83
+ return `${archivePath}${BACKUP_DIGEST_SUFFIX}`;
84
+ }
85
+ // ─── Sidecar format ──────────────────────────────────────────────────────────
86
+ const SHA256_HEX = /^[0-9a-f]{64}$/;
87
+ const DIGEST_LINE = /^(\\?)([0-9a-f]{64}) {2}([^\n\r]+)\n$/;
88
+ /** An escaped name: only `\\`, `\n` and `\r` escapes, and at least one of them. */
89
+ const ESCAPED_NAME = /^(?:[^\\]|\\[\\nr])+$/;
90
+ const ESCAPE_SEQUENCE = /\\[\\nr]/;
91
+ /** The sidecar text for an archive named `archiveName` whose bytes hash to `sha256`. */
92
+ export function formatBackupDigest(sha256, archiveName) {
93
+ if (!SHA256_HEX.test(sha256))
94
+ throw new TypeError("formatBackupDigest: expected a lowercase hex SHA-256 digest");
95
+ if (archiveName.length === 0)
96
+ throw new TypeError("formatBackupDigest: expected a non-empty archive file name");
97
+ if (!/[\\\n\r]/.test(archiveName))
98
+ return `${sha256} ${archiveName}\n`;
99
+ const escaped = archiveName.replace(/\\/g, "\\\\").replace(/\n/g, "\\n").replace(/\r/g, "\\r");
100
+ return `\\${sha256} ${escaped}\n`;
101
+ }
102
+ /**
103
+ * Read a sidecar's digest. Accepts exactly one line in the format
104
+ * formatBackupDigest writes: 64 lowercase hex characters, two spaces, a
105
+ * non-empty name in UTF-8, and one trailing line feed. A name written without
106
+ * escapes holds no backslash; a name written with escapes follows a leading
107
+ * `\`, uses only `\\`, `\n` and `\r`, and holds at least one of them. Anything
108
+ * else is refused with a reason. The name is not compared with any file name.
109
+ */
110
+ export function parseBackupDigest(bytes) {
111
+ // latin1 maps each byte to one character, so the check is over the bytes
112
+ // themselves whatever encoding the name is in. No byte of a multi-byte
113
+ // UTF-8 sequence is 0x5c, so a backslash here is a backslash in the name.
114
+ const text = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString("latin1");
115
+ const match = DIGEST_LINE.exec(text);
116
+ if (match) {
117
+ const [, marker, sha256, name] = match;
118
+ try {
119
+ new TextDecoder("utf-8", { fatal: true }).decode(Buffer.from(name, "latin1"));
120
+ }
121
+ catch {
122
+ return { ok: false, reason: "the file name is not UTF-8" };
123
+ }
124
+ if (marker === "") {
125
+ if (name.includes("\\")) {
126
+ return { ok: false, reason: "the file name holds a backslash, but the line does not start with the escape marker \\" };
127
+ }
128
+ return { ok: true, sha256: sha256 };
129
+ }
130
+ if (!ESCAPED_NAME.test(name) || !ESCAPE_SEQUENCE.test(name)) {
131
+ return { ok: false, reason: "the line starts with the escape marker \\, but the file name is not escaped as \\\\, \\n and \\r" };
132
+ }
133
+ return { ok: true, sha256: sha256 };
134
+ }
135
+ if (text.length === 0)
136
+ return { ok: false, reason: "the file is empty" };
137
+ if (!text.endsWith("\n"))
138
+ return { ok: false, reason: "the line does not end with a line feed" };
139
+ if (text.indexOf("\n") !== text.length - 1)
140
+ return { ok: false, reason: "the file holds more than one line" };
141
+ return { ok: false, reason: "expected 64 lowercase hex characters, two spaces and the archive file name" };
142
+ }
143
+ // ─── Publication ─────────────────────────────────────────────────────────────
144
+ /** The publication steps, in order (see the module comment). */
145
+ export const BACKUP_PUBLISH_STEPS = Object.freeze([
146
+ "stage-archive",
147
+ "sync-archive",
148
+ "verify-archive",
149
+ "stage-digest",
150
+ "remove-old-digest",
151
+ "publish-archive",
152
+ "publish-digest",
153
+ ]);
154
+ /** fsync a regular file through its own descriptor. */
155
+ function fsyncFile(path) {
156
+ const fd = openSync(path, "r+");
157
+ try {
158
+ fsyncSync(fd);
159
+ }
160
+ finally {
161
+ closeSync(fd);
162
+ }
163
+ }
164
+ function errorMessage(error) {
165
+ return error instanceof Error ? error.message : String(error);
166
+ }
167
+ /** Try to remove the staging directory; the reason it could not be removed, or undefined. */
168
+ function removeStagingDir(path, removeDir) {
169
+ if (path === undefined)
170
+ return undefined;
171
+ try {
172
+ removeDir(path);
173
+ return undefined;
174
+ }
175
+ catch (error) {
176
+ return error?.code ?? errorMessage(error);
177
+ }
178
+ }
179
+ /**
180
+ * Publish `serialized` at `outputPath` together with its digest sidecar, in
181
+ * the order the module comment gives. Throws when publication does not
182
+ * complete; the message says what the published names hold. Then, on success
183
+ * and on failure, it tries to remove the staging directory and reports a
184
+ * removal that fails (see the module comment).
185
+ */
186
+ export function publishBackupArtifact(options, hooks = {}) {
187
+ const { outputPath, serialized } = options;
188
+ const step = hooks.beforeStep ?? (() => { });
189
+ const removeDir = hooks.removeDir ?? ((path) => rmSync(path, { recursive: true, force: true }));
190
+ const dir = dirname(outputPath);
191
+ const digestPath = backupDigestPath(outputPath);
192
+ const expected = Buffer.from(serialized, "utf-8");
193
+ let stagingDir;
194
+ let removedOldDigest = false;
195
+ let publishedArchive = false;
196
+ let published;
197
+ try {
198
+ step("stage-archive");
199
+ mkdirSync(dir, { recursive: true });
200
+ stagingDir = mkdtempSync(join(dir, ".flair-backup-"));
201
+ const stagedArchive = join(stagingDir, "archive.json");
202
+ writeFileSync(stagedArchive, serialized, { encoding: "utf-8", flag: "wx", mode: 0o600 });
203
+ step("sync-archive");
204
+ fsyncFile(stagedArchive);
205
+ step("verify-archive");
206
+ const written = readFileSync(stagedArchive);
207
+ options.verify?.(written.toString("utf-8"));
208
+ if (!Buffer.isBuffer(written) || !written.equals(expected)) {
209
+ throw new Error("archive bytes on disk do not match the serialized archive");
210
+ }
211
+ const sha256 = createHash("sha256").update(written).digest("hex");
212
+ step("stage-digest");
213
+ const stagedDigest = join(stagingDir, `archive.json${BACKUP_DIGEST_SUFFIX}`);
214
+ writeFileSync(stagedDigest, formatBackupDigest(sha256, basename(outputPath)), { encoding: "utf-8", flag: "wx", mode: 0o600 });
215
+ fsyncFile(stagedDigest);
216
+ step("remove-old-digest");
217
+ try {
218
+ unlinkSync(digestPath);
219
+ removedOldDigest = true;
220
+ }
221
+ catch (error) {
222
+ if (error?.code !== "ENOENT")
223
+ throw error;
224
+ }
225
+ fsyncDir(dir);
226
+ step("publish-archive");
227
+ renameSync(stagedArchive, outputPath);
228
+ publishedArchive = true;
229
+ fsyncDir(dir);
230
+ step("publish-digest");
231
+ renameSync(stagedDigest, digestPath);
232
+ fsyncDir(dir);
233
+ published = { sha256, digestPath };
234
+ }
235
+ catch (error) {
236
+ const cause = errorMessage(error);
237
+ const state = publishedArchive
238
+ ? `${outputPath} holds the new archive but its digest sidecar ${digestPath} was not written, ` +
239
+ "and restore refuses the archive without it unless this host holds a valid approval for these exact bytes; run the backup again"
240
+ : removedOldDigest
241
+ ? `the previous digest sidecar ${digestPath} was removed and ${outputPath} was not replaced, ` +
242
+ "so a previous archive there no longer has a sidecar"
243
+ : "nothing was published";
244
+ const left = removeStagingDir(stagingDir, removeDir);
245
+ const cleanup = left === undefined ? "" : `; the staging directory ${stagingDir} could not be removed (${left}): remove it by hand`;
246
+ throw new Error(`${cause}; ${state}${cleanup}`, { cause: error });
247
+ }
248
+ const left = removeStagingDir(stagingDir, removeDir);
249
+ return left === undefined ? published : { ...published, stagingLeft: { path: stagingDir, reason: left } };
250
+ }
251
+ /** Whether anything, a dangling symbolic link included, exists at `path`. */
252
+ function lstatExists(path) {
253
+ try {
254
+ lstatSync(path);
255
+ return true;
256
+ }
257
+ catch {
258
+ return false;
259
+ }
260
+ }
261
+ function errnoCode(error) {
262
+ const code = error?.code;
263
+ return typeof code === "string" ? code : "read failed";
264
+ }
265
+ /**
266
+ * Verify a backup artifact before restore uses it. In order:
267
+ * 1. read the archive's bytes once;
268
+ * 2. hash and parse that one buffer (parseRestoreArchive);
269
+ * 3. read the sidecar once and parse its digest line;
270
+ * 4. require the sidecar's digest to equal the hash from step 2;
271
+ * 5. require the parse from step 2 to have admitted the archive.
272
+ * The first step that does not hold is returned as a named refusal.
273
+ */
274
+ export function readBackupArtifact(archivePath, hooks = {}) {
275
+ const readFile = hooks.readFile ?? ((path) => readFileSync(path));
276
+ const digestPath = backupDigestPath(archivePath);
277
+ const stopped = hooks.stopped ?? "restore stopped before any write";
278
+ const putSidecar = "put the .sha256 file written with this archive beside it";
279
+ let bytes;
280
+ try {
281
+ bytes = readFile(archivePath);
282
+ }
283
+ catch (error) {
284
+ return {
285
+ ok: false, code: "archive-unreadable",
286
+ reason: `cannot read archive ${archivePath} (${errnoCode(error)}); ${stopped}. Check the path and that this user can read the file.`,
287
+ };
288
+ }
289
+ const parsed = parseRestoreArchive(bytes);
290
+ const sha256 = parsed.sha256;
291
+ let sidecar;
292
+ try {
293
+ sidecar = readFile(digestPath);
294
+ }
295
+ catch (error) {
296
+ if (errnoCode(error) === "ENOENT" && lstatExists(digestPath)) {
297
+ return {
298
+ ok: false, code: "digest-unreadable", sha256,
299
+ reason: `archive digest sidecar ${digestPath} is a symbolic link whose target does not exist; ${stopped}. ` +
300
+ `Replace it with the .sha256 file written with this archive.`,
301
+ };
302
+ }
303
+ if (errnoCode(error) === "ENOENT") {
304
+ return {
305
+ ok: false, code: "digest-missing", sha256,
306
+ reason: `archive digest sidecar ${digestPath} not found; ${stopped}. ` +
307
+ `flair backup writes the archive's SHA-256 to that file beside the archive: ${putSidecar}, or take a new ` +
308
+ "backup. An archive written before flair backup published digests has no sidecar: restore admits it only " +
309
+ `after the operator approves it on this host with flair backup-approval legacy-admit ${archivePath}.`,
310
+ };
311
+ }
312
+ return {
313
+ ok: false, code: "digest-unreadable", sha256,
314
+ reason: `cannot read archive digest sidecar ${digestPath} (${errnoCode(error)}); ${stopped}. ` +
315
+ `Check that the sidecar is a file this user can read, or ${putSidecar}.`,
316
+ };
317
+ }
318
+ const recorded = parseBackupDigest(sidecar);
319
+ if (recorded.ok === false) {
320
+ return {
321
+ ok: false, code: "digest-invalid", sha256,
322
+ reason: `archive digest sidecar ${digestPath} is not a SHA-256 digest line (${recorded.reason}); ${stopped}. ` +
323
+ `${putSidecar[0].toUpperCase()}${putSidecar.slice(1)}, or take a new backup.`,
324
+ };
325
+ }
326
+ if (recorded.sha256 !== sha256) {
327
+ return {
328
+ ok: false, code: "digest-mismatch", sha256,
329
+ reason: `archive ${archivePath} does not match its digest sidecar: its bytes hash to SHA-256 ${sha256}, ` +
330
+ `and ${digestPath} records ${recorded.sha256}; ${stopped}. Use a copy of the archive and sidecar that ` +
331
+ "match each other (from the archive's directory, shasum -a 256 -c checks a pair; for a file name containing a carriage return use GNU sha256sum -c), or take a new backup.",
332
+ };
333
+ }
334
+ if (parsed.ok === false) {
335
+ const location = parsed.location === "" ? "/" : parsed.location;
336
+ return {
337
+ ok: false, code: "archive-refused", sha256, archiveRefusal: parsed,
338
+ reason: `archive ${archivePath} matches its digest sidecar but is not a restorable archive: ${parsed.reason} ` +
339
+ `(${parsed.code} at ${location}); ${stopped}. Restore from another backup, or take a new one.`,
340
+ };
341
+ }
342
+ return { ok: true, archive: parsed.archive, sha256, digestPath };
343
+ }
@@ -18,11 +18,11 @@
18
18
  * the configured entry does not exist AND the parent resolves. A dangling
19
19
  * symlink is not absence; EACCES / ELOOP / ENOTDIR are resolution ERRORS
20
20
  * and HOLD, never "absent".
21
- * 2. LOCK: an `O_EXCL` create of `<resolvedTarget>.lock`, beside the
22
- * RESOLVED target so stable symlink aliases share one lock, computed once
23
- * per attempt. Content is diagnostic only (`<pid> <iso> <hostname>`),
24
- * never an authorization input. Bounded retry then a NAMED refusal. No
25
- * reclaim, no age-out, no pid-liveness shortcut.
21
+ * 2. LOCK: an `O_EXCL` create of `<resolvedTarget>.lock` unless the caller
22
+ * supplies `lockPath`, computed once per attempt. Content is
23
+ * diagnostic only (`<pid> <iso> <hostname>`), never an authorization
24
+ * input. Bounded retry then a NAMED refusal. No reclaim, no age-out, no
25
+ * pid-liveness shortcut.
26
26
  * 3. RE-OBSERVE INSIDE the lock and compare. Any change of entry type,
27
27
  * entry identity, resolved path, target identity, parent identity or
28
28
  * absence state HELDS the write (fixture 11/12), naming which
@@ -83,14 +83,152 @@
83
83
  * (every wired client re-reads at startup). ACL, xattr and hard-link
84
84
  * preservation are NOT handled and are documented, not silently dropped.
85
85
  *
86
- * Leaf module: imports only node:fs, node:crypto, node:os and node:path.
87
- * NEVER import src/cli.ts here — its `writeFileAtomic` lacks exclusive temp
88
- * creation, fsync, locking and identity checks (flair#1778 2c-i-b ruling).
86
+ * Leaf module: imports only node:fs, node:child_process, node:crypto, node:os
87
+ * and node:path. NEVER import src/cli.ts here.
89
88
  */
90
- import { closeSync, existsSync, fchmodSync, fchownSync, fstatSync, fsyncSync, lstatSync, openSync, readFileSync, realpathSync, renameSync, statSync, unlinkSync, writeFileSync, writeSync, } from "node:fs";
89
+ import { closeSync, existsSync, fchmodSync, fchownSync, fstatSync, fsyncSync, lstatSync, openSync, readFileSync, realpathSync, renameSync, statfsSync, statSync, unlinkSync, writeFileSync, writeSync, } from "node:fs";
90
+ import { execFileSync } from "node:child_process";
91
91
  import { randomBytes } from "node:crypto";
92
92
  import { hostname } from "node:os";
93
- import { basename, dirname, join } from "node:path";
93
+ import { basename, dirname, join, resolve } from "node:path";
94
+ // ── filesystem support ──────────────────────────────────────────────────────
95
+ /** Linux custody allowlist, keyed by `statfs` magic. Overlayfs crash durability
96
+ * depends on the upper layer's backing, which this check does not verify.
97
+ * macOS is classified by mount-table name. */
98
+ const LOCAL_FILESYSTEM_TYPES = {
99
+ 0xef53: "ext2/ext3/ext4",
100
+ 0x58465342: "xfs",
101
+ 0x9123683e: "btrfs",
102
+ 0x2fc12fc1: "zfs",
103
+ 0x794c7630: "overlayfs",
104
+ 0x3153464a: "jfs",
105
+ 0xf2f52010: "f2fs",
106
+ };
107
+ /** macOS filesystem names accepted for custody, as named in the mount table. */
108
+ const LOCAL_FILESYSTEM_NAMES = new Set(["apfs", "hfs"]);
109
+ /** Whether a Linux statfs magic is allowlisted. */
110
+ export function isSupportedLocalFilesystemType(type) {
111
+ return Object.hasOwn(LOCAL_FILESYSTEM_TYPES, type);
112
+ }
113
+ /** Whether a filesystem NAME reported by the platform is accepted. */
114
+ export function isSupportedLocalFilesystemName(name) {
115
+ return LOCAL_FILESYSTEM_NAMES.has(name.toLowerCase());
116
+ }
117
+ /** `<device> on <mount point> (<type>, <option>, ...)`. Mount points can
118
+ * contain spaces, so nothing here splits on whitespace. */
119
+ const MOUNT_LINE = /^(.+) on (.+) \(([^,()]+)((?:, [^()]*)?)\)$/;
120
+ /** Parse one `mount` output line. Returns null for anything that does not
121
+ * match the documented shape. */
122
+ export function parseMountLine(line) {
123
+ const match = MOUNT_LINE.exec(line);
124
+ if (!match)
125
+ return null;
126
+ const device = match[1];
127
+ const mountPoint = match[2];
128
+ const type = match[3].trim();
129
+ const rawOptions = match[4];
130
+ const options = rawOptions
131
+ ? rawOptions.split(",").map((option) => option.trim()).filter((option) => option !== "")
132
+ : [];
133
+ return { device, mountPoint, type, options };
134
+ }
135
+ /** Select exactly one entry at the covering mount point reported by df. */
136
+ export function selectMountEntry(entries, mountPoint) {
137
+ const matches = entries.filter((entry) => entry.mountPoint === mountPoint);
138
+ return matches.length === 1 ? matches[0] : null;
139
+ }
140
+ /** One `df -P` data row: device, blocks, used, available, capacity, mount. */
141
+ const DF_DATA_LINE = /^(.+?)\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+%)\s+(.+)$/;
142
+ /** The one non-data line `df -P` prefixes: its column header. */
143
+ const DF_HEADER_LINE = /^Filesystem\s+(?:512|1024)-blocks\s+Used\s+Available\s+Capacity\s+Mounted\s+on$/;
144
+ /** Parse `df -P` output. The output must be the header (optional) plus exactly
145
+ * one data row; any other nonempty line is a refusal, never skipped. */
146
+ export function parseDfMountPoint(output) {
147
+ const lines = output.split("\n").map((line) => line.trim()).filter((line) => line !== "");
148
+ if (lines.length === 0)
149
+ return null;
150
+ const rows = DF_HEADER_LINE.test(lines[0]) ? lines.slice(1) : lines;
151
+ if (rows.length !== 1)
152
+ return null;
153
+ const match = DF_DATA_LINE.exec(rows[0]);
154
+ return match !== null && match[6].startsWith("/") ? match[6] : null;
155
+ }
156
+ function readDarwinDf(path) {
157
+ return execFileSync("/bin/df", ["-P", path], {
158
+ encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 5000, killSignal: "SIGKILL",
159
+ });
160
+ }
161
+ /** Classify the covering mount reported by df. */
162
+ export function classifyDarwinFilesystem(realPath, mountOutput, readDf = readDarwinDf) {
163
+ const entries = [];
164
+ for (const line of mountOutput.split("\n")) {
165
+ if (line.trim() === "")
166
+ continue;
167
+ const entry = parseMountLine(line);
168
+ if (entry === null)
169
+ return { ok: false, reason: "unparseable mount entry" };
170
+ entries.push(entry);
171
+ }
172
+ let mountPoint;
173
+ try {
174
+ mountPoint = parseDfMountPoint(readDf(realPath));
175
+ }
176
+ catch (err) {
177
+ return { ok: false, reason: `cannot read the covering mount for ${realPath}: ${msg(err)}` };
178
+ }
179
+ if (mountPoint === null)
180
+ return { ok: false, reason: "unparseable df output" };
181
+ const entry = selectMountEntry(entries, mountPoint);
182
+ if (entry === null)
183
+ return { ok: false, reason: `no unique mount entry for ${mountPoint}` };
184
+ if (!isSupportedLocalFilesystemName(entry.type) || !entry.options.includes("local")) {
185
+ return { ok: false, reason: `mount at ${mountPoint} is not a recognized local filesystem` };
186
+ }
187
+ return { ok: true, type: entry.type.toLowerCase() };
188
+ }
189
+ export function assertSupportedLocalFilesystem(targetPath) {
190
+ let probe = resolve(targetPath);
191
+ // Try at most 256 paths, stopping early at root; refuse if the cap is exhausted.
192
+ for (let i = 0; i < 256; i++) {
193
+ if (existsSync(probe))
194
+ break;
195
+ const parent = dirname(probe);
196
+ if (parent === probe)
197
+ return { ok: false, reason: `cannot find an existing ancestor of ${targetPath}` };
198
+ if (i === 255)
199
+ return { ok: false, reason: `ancestor walk reached its iteration cap for ${targetPath}` };
200
+ probe = parent;
201
+ }
202
+ if (process.platform === "darwin") {
203
+ let realProbe;
204
+ try {
205
+ realProbe = realpathSync(probe);
206
+ }
207
+ catch (err) {
208
+ return { ok: false, reason: `cannot resolve ${probe}: ${msg(err)}` };
209
+ }
210
+ let table;
211
+ try {
212
+ table = execFileSync("/sbin/mount", [], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 5000, killSignal: "SIGKILL" });
213
+ }
214
+ catch (err) {
215
+ return { ok: false, reason: `cannot read the mount table for ${realProbe}: ${msg(err)}` };
216
+ }
217
+ return classifyDarwinFilesystem(realProbe, table);
218
+ }
219
+ let st;
220
+ try {
221
+ st = statfsSync(probe);
222
+ }
223
+ catch (err) {
224
+ return { ok: false, reason: `cannot inspect the filesystem for ${probe}: ${msg(err)}` };
225
+ }
226
+ const name = isSupportedLocalFilesystemType(st.type) ? LOCAL_FILESYSTEM_TYPES[st.type] : undefined;
227
+ if (!name) {
228
+ return { ok: false, reason: `filesystem type 0x${st.type.toString(16)} at ${probe} is not allowlisted for custody` };
229
+ }
230
+ return { ok: true, type: name };
231
+ }
94
232
  // ── helpers ─────────────────────────────────────────────────────────────────
95
233
  function msg(err) {
96
234
  return err instanceof Error ? err.message : String(err);
@@ -343,7 +481,7 @@ export function atomicReplace(targetPath, bytes, original, onTempCreate,
343
481
  // TEST-ONLY: fires AFTER the staging file is fsynced and BEFORE the rename
344
482
  // (flair#1778 2c-i-d2 crash window, T1c). A SIGKILL here leaves the target
345
483
  // byte-identical and orphans the temp + lock (cleanup bypassed).
346
- onAfterFsync) {
484
+ onAfterFsync, onAfterRename, onBeforeRename, onPublished) {
347
485
  if (original && !isRegularMode(original.mode)) {
348
486
  return { ok: false, reason: `the destination ${targetPath} is not a regular file (mode ${original.mode.toString(8)}); refusing to replace it` };
349
487
  }
@@ -423,6 +561,12 @@ onAfterFsync) {
423
561
  // byte-identical and orphans the staging temp + the lock (the crash window).
424
562
  envBarrier("fsync");
425
563
  onAfterFsync?.(tempPath);
564
+ try {
565
+ onBeforeRename?.();
566
+ }
567
+ catch (err) {
568
+ return fail(`pre-rename check failed: ${msg(err)}`);
569
+ }
426
570
  try {
427
571
  renameSync(tempPath, targetPath);
428
572
  }
@@ -432,19 +576,28 @@ onAfterFsync) {
432
576
  }
433
577
  let cleanupWarning = null;
434
578
  try {
435
- const dfd = openSync(dir, "r");
579
+ onAfterRename?.(targetPath);
580
+ onPublished?.();
581
+ }
582
+ catch (err) {
583
+ cleanupWarning = `the replacement is committed but the post-rename step failed: ${msg(err)}`;
584
+ }
585
+ if (cleanupWarning === null) {
436
586
  try {
437
- fsyncSync(dfd);
438
- }
439
- finally {
587
+ const dfd = openSync(dir, "r");
440
588
  try {
441
- closeSync(dfd);
589
+ fsyncSync(dfd);
590
+ }
591
+ finally {
592
+ try {
593
+ closeSync(dfd);
594
+ }
595
+ catch { /* */ }
442
596
  }
443
- catch { /* */ }
444
597
  }
445
- }
446
- catch (err) {
447
- cleanupWarning = `the replacement is committed but the directory fsync failed: ${msg(err)}`;
598
+ catch (err) {
599
+ cleanupWarning = `the replacement is committed but the directory fsync failed: ${msg(err)}`;
600
+ }
448
601
  }
449
602
  return { ok: true, cleanupWarning };
450
603
  }
@@ -469,7 +622,7 @@ export function withConfigCriticalSection(configPath, decide, opts = {}) {
469
622
  const targetPath = resolvedTargetPath(preObs, configPath);
470
623
  barrier(opts.testHooks?.afterPreObserve, "preObserve", attempt);
471
624
  // 2. LOCK (computed once per attempt).
472
- const lockPath = `${targetPath}.lock`;
625
+ const lockPath = opts.lockPath ?? `${targetPath}.lock`;
473
626
  const lock = acquireLock(lockPath, lockRetry);
474
627
  if (!lock.ok) {
475
628
  return { status: "refused", path: targetPath, attempts, message: lockRefusalLine(lockPath, lock.holder) };
@@ -525,13 +678,47 @@ export function withConfigCriticalSection(configPath, decide, opts = {}) {
525
678
  if ("noop" in decision) {
526
679
  return { status: "noop", path: targetPath, attempts, message: decision.noop, backupPath };
527
680
  }
528
- // 5. WRITE.
681
+ // 5. WRITE. Stage under the SAME lock before replacing the target.
682
+ let stageCleanup;
683
+ if (opts.stage) {
684
+ try {
685
+ const staged = opts.stage(decision.write, obs);
686
+ stageCleanup = typeof staged === "function" ? staged : undefined;
687
+ }
688
+ catch (err) {
689
+ return { status: "refused", path: targetPath, attempts, message: `target was not replaced; staged files may remain: staging failed: ${msg(err)}`, backupPath };
690
+ }
691
+ }
529
692
  const original = obs.target.type === "regular"
530
693
  ? { mode: obs.target.mode, uid: obs.target.uid, gid: obs.target.gid }
531
694
  : null;
532
- const wr = atomicReplace(targetPath, decision.write, original, opts.testHooks?.afterTempCreate, opts.testHooks?.afterFsync);
695
+ let wr;
696
+ try {
697
+ wr = atomicReplace(targetPath, decision.write, original, opts.testHooks?.afterTempCreate, opts.testHooks?.afterFsync, opts.testHooks?.afterRename, opts.beforeRename, opts.afterRename);
698
+ }
699
+ catch (err) {
700
+ try {
701
+ stageCleanup?.();
702
+ }
703
+ catch { /* the original failure stands */ }
704
+ throw err;
705
+ }
533
706
  if (!wr.ok) {
534
- return { status: "refused", path: targetPath, attempts, message: `nothing written: ${wr.reason}`, backupPath };
707
+ try {
708
+ stageCleanup?.();
709
+ }
710
+ catch { /* the refusal stands */ }
711
+ const prefix = opts.stage ? "target was not replaced; staged files may remain" : "target was not replaced";
712
+ return { status: "refused", path: targetPath, attempts, message: `${prefix}: ${wr.reason}`, backupPath };
713
+ }
714
+ let cleanupWarning = wr.cleanupWarning;
715
+ if (cleanupWarning === null && opts.onCommitted) {
716
+ try {
717
+ opts.onCommitted();
718
+ }
719
+ catch (err) {
720
+ cleanupWarning = `the replacement is committed but the post-rename step failed: ${msg(err)}`;
721
+ }
535
722
  }
536
723
  return {
537
724
  status: "written",
@@ -540,7 +727,7 @@ export function withConfigCriticalSection(configPath, decide, opts = {}) {
540
727
  message: "",
541
728
  backupPath,
542
729
  committed: true,
543
- cleanupWarning: wr.cleanupWarning,
730
+ cleanupWarning,
544
731
  };
545
732
  }
546
733
  finally {
@@ -0,0 +1,33 @@
1
+ /**
2
+ * A connect-phase code identifies failure of the current connection attempt.
3
+ * Replay on another configured instance requires no earlier redirect.
4
+ *
5
+ * Node's undici wraps the errno in the `fetch failed` TypeError's `cause`; Bun
6
+ * puts `code` on the TypeError itself, and Bun may also name a refusal
7
+ * `ConnectionRefused`. So the chain starts at the error and both refusal
8
+ * spellings are accepted.
9
+ */
10
+ /** The refusal spellings, shared with daemon-liveness and upgrade-prior-liveness. */
11
+ export const REFUSED_CODES = ["ECONNREFUSED", "ConnectionRefused"];
12
+ const CONNECT_PHASE_CODES = new Set([
13
+ ...REFUSED_CODES,
14
+ "ENOTFOUND",
15
+ "EAI_AGAIN",
16
+ "EHOSTUNREACH",
17
+ "ENETUNREACH",
18
+ "EADDRNOTAVAIL",
19
+ "UND_ERR_CONNECT_TIMEOUT",
20
+ ]);
21
+ /** True when `err` or a `cause` in its chain carries a connect-phase code. */
22
+ export function isConnectPhaseFailure(err) {
23
+ let current = err;
24
+ for (let depth = 0; current !== null && current !== undefined && depth < 8; depth++) {
25
+ if (typeof current === "object" && "code" in current) {
26
+ const code = current.code;
27
+ if (typeof code === "string" && CONNECT_PHASE_CODES.has(code))
28
+ return true;
29
+ }
30
+ current = current.cause;
31
+ }
32
+ return false;
33
+ }