@tpsdev-ai/flair 0.59.0 → 0.63.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (359) hide show
  1. package/README.md +10 -10
  2. package/SECURITY.md +49 -5
  3. package/config.yaml +23 -12
  4. package/dist/bridges/builtins/mem0.js +63 -28
  5. package/dist/bridges/runtime/execute.js +1 -0
  6. package/dist/bridges/runtime/import-runner.js +12 -0
  7. package/dist/bridges/runtime/load-plugin.js +42 -13
  8. package/dist/bridges/runtime/yaml-loader.js +4 -2
  9. package/dist/bridges/types.js +1 -0
  10. package/dist/build-info.json +3 -3
  11. package/dist/cli.js +1054 -367
  12. package/dist/commands/agent.js +233 -90
  13. package/dist/commands/attention.js +4 -3
  14. package/dist/commands/backup-approval.js +218 -0
  15. package/dist/commands/backup.js +211 -39
  16. package/dist/commands/bootstrap.js +3 -1
  17. package/dist/commands/bridge.js +172 -119
  18. package/dist/commands/deploy.js +71 -8
  19. package/dist/commands/doctor.js +711 -146
  20. package/dist/commands/export.js +57 -23
  21. package/dist/commands/federation.js +787 -82
  22. package/dist/commands/grant.js +5 -6
  23. package/dist/commands/help.js +25 -0
  24. package/dist/commands/hook.js +155 -2
  25. package/dist/commands/idp.js +27 -19
  26. package/dist/commands/import.js +136 -20
  27. package/dist/commands/init.js +469 -200
  28. package/dist/commands/integrity.js +387 -0
  29. package/dist/commands/keys.js +247 -58
  30. package/dist/commands/mcp.js +108 -52
  31. package/dist/commands/memory.js +203 -35
  32. package/dist/commands/migrate-harness-memory.js +3 -2
  33. package/dist/commands/orgevent.js +51 -47
  34. package/dist/commands/presence.js +4 -3
  35. package/dist/commands/principal.js +428 -62
  36. package/dist/commands/quality.js +13 -1
  37. package/dist/commands/reembed.js +141 -17
  38. package/dist/commands/relationship.js +2 -1
  39. package/dist/commands/rem.js +537 -80
  40. package/dist/commands/restore.js +413 -65
  41. package/dist/commands/search.js +6 -4
  42. package/dist/commands/service.js +235 -40
  43. package/dist/commands/soul.js +4 -9
  44. package/dist/commands/status.js +94 -38
  45. package/dist/commands/test.js +7 -3
  46. package/dist/commands/upgrade.js +77 -23
  47. package/dist/commands/workspace.js +13 -11
  48. package/dist/component-env.js +31 -41
  49. package/dist/deploy.js +136 -4
  50. package/dist/doctor-client.js +534 -92
  51. package/dist/engine-version-contract.js +1 -0
  52. package/dist/engine-version.js +23 -3
  53. package/dist/fabric-upgrade.js +12 -2
  54. package/dist/federation/presence-send.js +139 -0
  55. package/dist/federation-verify.js +273 -180
  56. package/dist/hook-install.js +670 -6
  57. package/dist/install/clients.js +171 -35
  58. package/dist/keystore.js +72 -0
  59. package/dist/lib/action-recall-runtime.js +328 -0
  60. package/dist/lib/agent-home-fields.js +132 -0
  61. package/dist/lib/agent-home.js +427 -0
  62. package/dist/lib/agent-id-rule.js +88 -0
  63. package/dist/lib/agent-roster.js +33 -0
  64. package/dist/lib/atomic-write.js +1 -1
  65. package/dist/lib/auth-resolve.js +1069 -60
  66. package/dist/lib/backup-approval-store.js +612 -0
  67. package/dist/lib/backup-artifact.js +343 -0
  68. package/dist/lib/capture-runtime.js +124 -0
  69. package/dist/lib/config-critical-section.js +212 -25
  70. package/dist/lib/connect-phase.js +33 -0
  71. package/dist/lib/credential-status-rule.js +78 -0
  72. package/dist/lib/daemon-liveness.js +43 -11
  73. package/dist/lib/doctor-run.js +75 -37
  74. package/dist/lib/durability-copy.js +10 -0
  75. package/dist/lib/embedding-space-doctor.js +75 -0
  76. package/dist/lib/federation-pair-access.js +4 -0
  77. package/dist/lib/federation-retry-queue.js +283 -0
  78. package/dist/lib/federation-retry-row.js +101 -0
  79. package/dist/lib/flair-agent-role.js +4 -0
  80. package/dist/lib/hub-url.js +12 -0
  81. package/dist/lib/init-admin-pass.js +88 -12
  82. package/dist/lib/init-listener-environ.js +1 -2
  83. package/dist/lib/init-occupied-listener.js +15 -111
  84. package/dist/lib/init-spawn-attribution.js +73 -0
  85. package/dist/lib/init-tcp-probe.js +33 -0
  86. package/dist/lib/instance-identity-row.js +20 -0
  87. package/dist/lib/instruction-event-contract.js +17 -0
  88. package/dist/lib/instruction-event-doctor.js +102 -0
  89. package/dist/lib/launchd-management.js +38 -3
  90. package/dist/lib/listener-table.js +268 -0
  91. package/dist/lib/local-delete-instance.js +27 -0
  92. package/dist/lib/local-instance-pair.js +256 -0
  93. package/dist/lib/mcp-enable.js +1182 -341
  94. package/dist/lib/mcp-oauth-env-core.js +133 -0
  95. package/dist/lib/mcp-oauth-env.js +125 -0
  96. package/dist/lib/mcp-spec.js +17 -1
  97. package/dist/lib/memory-attributes.js +4 -0
  98. package/dist/lib/memory-id-policy.js +46 -0
  99. package/dist/lib/memory-integrity.js +309 -0
  100. package/dist/lib/memory-provider-timeout.js +33 -0
  101. package/dist/lib/memory-purge-response.js +20 -0
  102. package/dist/lib/mqtt-config.js +132 -0
  103. package/dist/lib/mqtt-listener-doctor.js +104 -0
  104. package/dist/lib/open-live-row.js +20 -0
  105. package/dist/lib/ops-table-count.js +25 -0
  106. package/dist/lib/ops-url.js +52 -0
  107. package/dist/lib/owned-pins.js +67 -10
  108. package/dist/lib/peer-status.js +27 -0
  109. package/dist/lib/principal-status.js +29 -0
  110. package/dist/lib/process-start-time.js +76 -12
  111. package/dist/lib/promotion-content-hash.js +20 -0
  112. package/dist/lib/proto-safe-record.js +42 -0
  113. package/dist/lib/record-id-path.js +25 -0
  114. package/dist/lib/reembed-server-support.js +66 -0
  115. package/dist/lib/restore-archive.js +760 -0
  116. package/dist/lib/restore-verify.js +104 -0
  117. package/dist/lib/scheduler-platform.js +10 -6
  118. package/dist/lib/secret-keys.js +25 -0
  119. package/dist/lib/secrets-push.js +50 -22
  120. package/dist/lib/skill-assignment-preflight.js +159 -0
  121. package/dist/lib/skill-seed-pending.js +24 -0
  122. package/dist/lib/skill-seed.js +448 -0
  123. package/dist/lib/skill-tombstone-doctor.js +133 -0
  124. package/dist/lib/soul-scope-fields.js +26 -0
  125. package/dist/lib/stop-start-recovery.js +54 -0
  126. package/dist/lib/uninstall-purge.js +266 -11
  127. package/dist/lib/upgrade-prior-liveness.js +2 -1
  128. package/dist/lib/using-flair-skill.js +87 -0
  129. package/dist/mcp-client-assertion.js +114 -14
  130. package/dist/memory-id-checkpoint.js +347 -0
  131. package/dist/memory-node-compare.js +207 -0
  132. package/dist/mqtt-off-deploy.js +550 -0
  133. package/dist/packages/flair-mcp/src/secret-redaction.js +113 -0
  134. package/dist/rem/promote-policy.js +3 -3
  135. package/dist/rem/restore.js +303 -26
  136. package/dist/rem/runner.js +317 -96
  137. package/dist/rem/scheduler.js +21 -4
  138. package/dist/resources/A2AAdapter.js +131 -178
  139. package/dist/resources/AdminMemory.js +2 -0
  140. package/dist/resources/AdminMemoryCandidates.js +116 -0
  141. package/dist/resources/Agent.js +463 -33
  142. package/dist/resources/AgentCard.js +4 -0
  143. package/dist/resources/AgentKeyRegister.js +248 -0
  144. package/dist/resources/AgentKeyRegistration.js +28 -0
  145. package/dist/resources/AgentReadPosition.js +7 -0
  146. package/dist/resources/AgentSeed.js +238 -107
  147. package/dist/resources/AutoPromoteCandidates.js +413 -78
  148. package/dist/resources/Credential.js +183 -10
  149. package/dist/resources/Federation.js +915 -145
  150. package/dist/resources/FederationRetry.js +140 -0
  151. package/dist/resources/InstructionVersion.js +220 -0
  152. package/dist/resources/Integration.js +300 -25
  153. package/dist/resources/MCPClientMetadata.js +6 -3
  154. package/dist/resources/Memory.js +3300 -758
  155. package/dist/resources/MemoryArchive.js +171 -53
  156. package/dist/resources/MemoryBootstrap.js +122 -61
  157. package/dist/resources/MemoryCandidate.js +37 -3
  158. package/dist/resources/MemoryConsolidate.js +2 -2
  159. package/dist/resources/MemoryDedupStats.js +30 -1
  160. package/dist/resources/MemoryFeed.js +545 -50
  161. package/dist/resources/MemoryGrant.js +21 -1
  162. package/dist/resources/MemoryMaintenance.js +368 -46
  163. package/dist/resources/MemoryPurge.js +348 -0
  164. package/dist/resources/MemoryReflect.js +71 -12
  165. package/dist/resources/MemoryReindex.js +111 -17
  166. package/dist/resources/Message.js +16 -5
  167. package/dist/resources/OAuth.js +342 -48
  168. package/dist/resources/OAuthClient.js +1 -1
  169. package/dist/resources/OrgEvent.js +405 -19
  170. package/dist/resources/OrgEventCatchup.js +7 -0
  171. package/dist/resources/OrgEventMaintenance.js +48 -10
  172. package/dist/resources/PairingToken.js +1 -1
  173. package/dist/resources/Presence.js +166 -51
  174. package/dist/resources/PromoteMemoryCandidate.js +24 -7
  175. package/dist/resources/RecordUsage.js +2 -4
  176. package/dist/resources/Relationship.js +23 -0
  177. package/dist/resources/SemanticSearch.js +63 -32
  178. package/dist/resources/Soul.js +191 -76
  179. package/dist/resources/SoulFeed.js +2 -1
  180. package/dist/resources/TeamDirectory.js +35 -0
  181. package/dist/resources/WorkspaceLatest.js +4 -0
  182. package/dist/resources/WorkspaceState.js +21 -1
  183. package/dist/resources/XAA.js +207 -63
  184. package/dist/resources/a2a-stream.js +313 -0
  185. package/dist/resources/a2a-url.js +4 -5
  186. package/dist/resources/agent-admin.js +10 -1
  187. package/dist/resources/agent-auth.js +138 -83
  188. package/dist/resources/agent-read-position-lib.js +4 -1
  189. package/dist/resources/agent-status-guard.js +9 -7
  190. package/dist/resources/auth-middleware.js +534 -171
  191. package/dist/resources/authority-field-guard.js +9 -11
  192. package/dist/resources/auto-promote-lib.js +8 -5
  193. package/dist/resources/basic-auth-header.js +21 -0
  194. package/dist/resources/bm25-index-service.js +4 -5
  195. package/dist/resources/dedup-cluster.js +6 -1
  196. package/dist/resources/ed25519-auth.js +1 -1
  197. package/dist/resources/embedding-space-guard.js +366 -72
  198. package/dist/resources/embeddings-provider.js +25 -0
  199. package/dist/resources/engine-version-stamp-boot.js +53 -0
  200. package/dist/resources/federation-classify.js +161 -0
  201. package/dist/resources/federation-crypto.js +5 -5
  202. package/dist/resources/federation-retry-lib.js +60 -0
  203. package/dist/resources/grant-visibility.js +135 -0
  204. package/dist/resources/harper-routing.js +83 -0
  205. package/dist/resources/health.js +163 -22
  206. package/dist/resources/host-pointer/registry.js +29 -0
  207. package/dist/resources/host-pointer-adapter.js +1 -0
  208. package/dist/resources/host-source-citation.js +49 -0
  209. package/dist/resources/host-source-visibility.js +7 -6
  210. package/dist/resources/in-process.js +24 -22
  211. package/dist/resources/instance-create-lock.js +17 -0
  212. package/dist/resources/instance-identity.js +23 -0
  213. package/dist/resources/instruction-version-record.js +587 -0
  214. package/dist/resources/internal-authority.js +13 -0
  215. package/dist/resources/key-lock.js +3 -3
  216. package/dist/resources/mcp-handler.js +141 -19
  217. package/dist/resources/mcp-oauth-env-guard.js +36 -0
  218. package/dist/resources/mcp-oauth-flag.js +12 -14
  219. package/dist/resources/mcp-oauth.js +450 -56
  220. package/dist/resources/mcp-tool-arguments.js +4 -6
  221. package/dist/resources/mcp-tools.js +187 -40
  222. package/dist/resources/memory-bootstrap-lib.js +5 -15
  223. package/dist/resources/memory-declared-attributes.js +4 -1
  224. package/dist/resources/memory-deletion-history.js +55 -0
  225. package/dist/resources/memory-durability.js +54 -0
  226. package/dist/resources/memory-embed-hash.js +144 -0
  227. package/dist/resources/memory-embedding-value.js +8 -0
  228. package/dist/resources/memory-host-source.js +32 -7
  229. package/dist/resources/memory-id-guard.js +75 -0
  230. package/dist/resources/memory-redaction.js +236 -0
  231. package/dist/resources/memory-reflect-lib.js +1 -1
  232. package/dist/resources/memory-supplied-vector.js +72 -0
  233. package/dist/resources/memory-write-lock.js +489 -0
  234. package/dist/resources/memory-write-response.js +139 -0
  235. package/dist/resources/memory-write-transaction.js +243 -0
  236. package/dist/resources/migration-boot.js +17 -12
  237. package/dist/resources/migrations/boot-progress.js +25 -0
  238. package/dist/resources/migrations/data-dir.js +90 -19
  239. package/dist/resources/migrations/dir-safety.js +61 -3
  240. package/dist/resources/migrations/embedding-stamp.js +462 -82
  241. package/dist/resources/migrations/export.js +1 -0
  242. package/dist/resources/migrations/graph-heal.js +27 -27
  243. package/dist/resources/migrations/ledger.js +5 -2
  244. package/dist/resources/migrations/lock.js +870 -77
  245. package/dist/resources/migrations/progress.js +71 -10
  246. package/dist/resources/migrations/runner.js +212 -18
  247. package/dist/resources/migrations/snapshot.js +1 -0
  248. package/dist/resources/migrations/source-fields.js +5 -5
  249. package/dist/resources/migrations/state.js +36 -1
  250. package/dist/resources/migrations/status.js +2 -13
  251. package/dist/resources/migrations/synthetic-test-migration.js +81 -12
  252. package/dist/resources/migrations/types.js +26 -1
  253. package/dist/resources/migrations/visibility-backfill.js +113 -72
  254. package/dist/resources/oauth-discovery.js +0 -5
  255. package/dist/resources/object-body-guard.js +40 -0
  256. package/dist/resources/org-event-created-at.js +133 -0
  257. package/dist/resources/org-event-reserved.js +92 -0
  258. package/dist/resources/org-event-write-fault.js +19 -0
  259. package/dist/resources/originator-instance.js +39 -7
  260. package/dist/resources/owner-delete-recheck.js +78 -0
  261. package/dist/resources/owner-field-guard.js +39 -5
  262. package/dist/resources/owner-scoped-write-policy.js +256 -0
  263. package/dist/resources/owner-scoped-writes.js +89 -0
  264. package/dist/resources/path-id-rewrite.js +76 -0
  265. package/dist/resources/presence-internal.js +5 -5
  266. package/dist/resources/presence-receipt.js +236 -0
  267. package/dist/resources/promotion-binding.js +43 -0
  268. package/dist/resources/promotion-stamp.js +143 -17
  269. package/dist/resources/protocol-context.js +189 -0
  270. package/dist/resources/record-owner-guard.js +74 -26
  271. package/dist/resources/record-type-kit.js +2 -4
  272. package/dist/resources/record-types.js +1 -1
  273. package/dist/resources/relay-ops.js +78 -6
  274. package/dist/resources/replay-store.js +96 -19
  275. package/dist/resources/request-target.js +163 -0
  276. package/dist/resources/request-transaction.js +46 -1
  277. package/dist/resources/search-readiness.js +4 -1
  278. package/dist/resources/seed-ids.js +9 -0
  279. package/dist/resources/seed-reservation.js +116 -0
  280. package/dist/resources/semantic-retrieval-core.js +27 -15
  281. package/dist/resources/server-row-validation.js +71 -0
  282. package/dist/resources/skill-manifest.js +24 -14
  283. package/dist/resources/skill-subject.js +53 -0
  284. package/dist/resources/skill-version-write.js +789 -0
  285. package/dist/resources/skill-write-fault.js +20 -0
  286. package/dist/resources/skill-write-policy.js +68 -0
  287. package/dist/resources/skill-write.js +67 -7
  288. package/dist/resources/soul-write-policy.js +26 -7
  289. package/dist/resources/table-helpers.js +10 -7
  290. package/dist/resources/table-subscription-policy.js +518 -85
  291. package/dist/resources/table-subscriptions.js +20 -7
  292. package/dist/resources/team-directory.js +248 -0
  293. package/dist/resources/tool-descriptors/index.js +69 -8
  294. package/dist/resources/txn-pause-point.js +235 -0
  295. package/dist/resources/usage-recording.js +186 -70
  296. package/dist/resources/write-back.js +383 -0
  297. package/dist/resources/write-journal-context.js +5 -0
  298. package/dist/resources/write-journal.js +289 -0
  299. package/dist/src/engine-version-contract.js +1 -0
  300. package/dist/src/keystore.js +72 -0
  301. package/dist/src/lib/agent-home-fields.js +132 -0
  302. package/dist/src/lib/agent-id-rule.js +88 -0
  303. package/dist/src/lib/agent-key-register.js +80 -0
  304. package/dist/src/lib/atomic-write.js +256 -0
  305. package/dist/src/lib/credential-status-rule.js +78 -0
  306. package/dist/src/lib/expired-by-agent.js +37 -0
  307. package/dist/src/lib/federation-retry-row.js +101 -0
  308. package/dist/src/lib/flair-agent-role.js +4 -0
  309. package/dist/src/lib/idp-mapping-rule.js +81 -0
  310. package/dist/src/lib/instance-identity-row.js +20 -0
  311. package/dist/src/lib/instruction-event-contract.js +17 -0
  312. package/dist/src/lib/mcp-oauth-env-core.js +133 -0
  313. package/dist/src/lib/memory-attributes.js +4 -0
  314. package/dist/src/lib/memory-id-policy.js +46 -0
  315. package/dist/src/lib/open-live-row.js +20 -0
  316. package/dist/src/lib/principal-status.js +29 -0
  317. package/dist/src/lib/proto-safe-record.js +42 -0
  318. package/dist/src/lib/reembed-server-support.js +66 -0
  319. package/dist/src/lib/scheduler-platform.js +10 -6
  320. package/dist/src/lib/soul-scope-fields.js +26 -0
  321. package/dist/src/lib/systemd-agent-id.js +38 -0
  322. package/dist/src/rem/promote-policy.js +3 -3
  323. package/dist/src/rem/scheduler.js +21 -4
  324. package/docs/access-control.md +164 -54
  325. package/docs/api-reference.md +165 -32
  326. package/docs/auth.md +46 -30
  327. package/docs/bridges.md +11 -0
  328. package/docs/claude-code.md +37 -7
  329. package/docs/deploying-on-fabric.md +178 -0
  330. package/docs/deployment.md +19 -0
  331. package/docs/embedding-in-a-harper-app.md +17 -15
  332. package/docs/entity-vocabulary.md +3 -6
  333. package/docs/federation.md +61 -3
  334. package/docs/hosted-on-fabric.md +43 -36
  335. package/docs/integrations.md +14 -14
  336. package/docs/mcp-clients.md +12 -7
  337. package/docs/n8n.md +17 -11
  338. package/docs/notes/mcp-agent-auth-consumer.md +16 -13
  339. package/docs/notes/mcp-oauth-model2.md +40 -11
  340. package/docs/openclaw.md +1 -1
  341. package/docs/quickstart-fabric.md +4 -4
  342. package/docs/quickstart.md +12 -4
  343. package/docs/releasing.md +25 -19
  344. package/docs/rem.md +32 -3
  345. package/docs/secrets-and-keys.md +21 -4
  346. package/docs/standalone-local.md +30 -2
  347. package/docs/supply-chain-policy.md +34 -16
  348. package/docs/the-team.md +2 -2
  349. package/docs/upgrade.md +46 -6
  350. package/package.json +24 -12
  351. package/schemas/agent-key-registration.graphql +22 -0
  352. package/schemas/agent.graphql +6 -3
  353. package/schemas/federation.graphql +41 -1
  354. package/schemas/memory.graphql +91 -7
  355. package/schemas/oauth.graphql +19 -0
  356. package/schemas/schema.graphql +2 -0
  357. package/templates/bin/flair-rem-nightly.sh.tmpl +7 -1
  358. package/templates/launchd/start-flair-with-admin-pass.sh +188 -10
  359. package/dist/resources/soul-adk-guard.js +0 -68
@@ -0,0 +1,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
+ }
@@ -0,0 +1,124 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { createHash, randomBytes } from "node:crypto";
3
+ import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { join } from "node:path";
6
+ import { buildCaptureHookCommand, captureFlushSpec } from "../doctor-client.js";
7
+ import { flairCliVersion } from "./mcp-spec.js";
8
+ import { hookArtifactForPackage, hookInstallRoot, isBuiltHookArtifact, plannedHookRuntime, provisionHookRuntime, resolveBunPath, resolveHookRuntime, } from "./action-recall-runtime.js";
9
+ export const CAPTURE_ARTIFACT = {
10
+ key: "capture",
11
+ artifactFile: "capture-hook.js",
12
+ binName: "flair-capture",
13
+ marker: "flair-capture-built",
14
+ runtimeFiles: ["capture-hook.js", "capture-spool.js", "capture.js", "env-guard.js", "secret-redaction.js", "record-id-path.js"],
15
+ envArtifact: "FLAIR_CAPTURE_ARTIFACT",
16
+ };
17
+ export function captureArtifactForPackage(packageDir) {
18
+ return hookArtifactForPackage(packageDir, CAPTURE_ARTIFACT);
19
+ }
20
+ export function captureInstallRoot(homeDir) {
21
+ return hookInstallRoot(homeDir, CAPTURE_ARTIFACT);
22
+ }
23
+ export function plannedCaptureRuntime(runtime, homeDir) {
24
+ return plannedHookRuntime(runtime, homeDir, CAPTURE_ARTIFACT);
25
+ }
26
+ export function provisionCaptureRuntime(runtime, homeDir, agentId, flairUrl) {
27
+ return provisionHookRuntime(runtime, homeDir, agentId, flairUrl, CAPTURE_ARTIFACT, probeCaptureRuntime);
28
+ }
29
+ function isSupportedExecutable(runtime) {
30
+ return resolveBunPath({ FLAIR_BUN_PATH: runtime.bunPath, PATH: "" }) === runtime.bunPath;
31
+ }
32
+ /** The secret shape the probe plants — a GitHub token the redactor recognizes. */
33
+ function probeSecret(nonce) {
34
+ return `ghp_${createHash("sha256").update(nonce).digest("hex").slice(0, 24)}`;
35
+ }
36
+ export function probeCaptureRuntime(runtime, agentId = "flair-probe", flairUrl = "http://localhost:19926", command) {
37
+ const failure = `capture self-test failed (${runtime.bunPath}, ${runtime.artifactPath})`;
38
+ if (!isSupportedExecutable(runtime) || !isBuiltHookArtifact(runtime.artifactPath, CAPTURE_ARTIFACT))
39
+ return failure;
40
+ let home;
41
+ try {
42
+ home = mkdtempSync(join(realpathSync(tmpdir()), "flair-capture-probe-"));
43
+ const nonce = randomBytes(16).toString("hex");
44
+ const secret = probeSecret(nonce);
45
+ const dir = join(home, ".flair", "capture");
46
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
47
+ const installedCommand = command ?? buildCaptureHookCommand(runtime.bunPath, runtime.artifactPath, agentId, flairUrl, captureFlushSpec());
48
+ const commandPath = join(home, "command.sh");
49
+ writeFileSync(commandPath, installedCommand, { mode: 0o600 });
50
+ const payload = JSON.stringify({
51
+ hook_event_name: "Stop",
52
+ session_id: "probe",
53
+ last_assistant_message: `Decision: use probe ${nonce} with token ${secret} for the archive.`,
54
+ });
55
+ const env = {
56
+ HOME: home,
57
+ USERPROFILE: home,
58
+ TMPDIR: home,
59
+ PATH: "/usr/bin:/bin",
60
+ BUN_INSTALL_AUTO: "disable",
61
+ FLAIR_CAPTURE_DIR: dir,
62
+ FLAIR_CAPTURE_NO_FLUSH: "1",
63
+ };
64
+ execFileSync("/bin/sh", [commandPath], { input: payload, encoding: "utf8", timeout: 2000, maxBuffer: 8192, cwd: home, env, stdio: ["pipe", "ignore", "ignore"] });
65
+ const spoolText = readFileSync(join(dir, `${agentId}.spool.json`), "utf-8");
66
+ const parsed = JSON.parse(spoolText);
67
+ const records = Array.isArray(parsed.records) ? parsed.records : [];
68
+ if (records.length !== 1)
69
+ return failure;
70
+ const content = typeof records[0]?.content === "string" ? records[0].content : "";
71
+ if (!content.includes(nonce))
72
+ return failure;
73
+ if (content.includes(secret))
74
+ return failure;
75
+ if (!content.includes("[redacted]"))
76
+ return failure;
77
+ writeFileSync(join(dir, `${agentId}.spool.json`), `${JSON.stringify({ v: 1, agentId, records: [] })}\n`, { mode: 0o600 });
78
+ execFileSync("/bin/sh", [commandPath], {
79
+ input: JSON.stringify({ hook_event_name: "Stop", session_id: "probe", last_assistant_message: "Routine turn; nothing to record." }),
80
+ encoding: "utf8", timeout: 2000, maxBuffer: 8192, cwd: home, env, stdio: ["pipe", "ignore", "ignore"],
81
+ });
82
+ const after = JSON.parse(readFileSync(join(dir, `${agentId}.spool.json`), "utf-8"));
83
+ if ((after.records ?? []).length !== 0)
84
+ return failure;
85
+ // A failed Bash call (PostToolUseFailure) and its later success
86
+ // (PostToolUse) must stage one redacted candidate.
87
+ const toolInput = { command: `probe-${nonce} run` };
88
+ for (const event of [
89
+ { hook_event_name: "PostToolUseFailure", session_id: "probe", tool_name: "Bash", tool_input: toolInput, error: `Error: token ${secret} rejected` },
90
+ { hook_event_name: "PostToolUse", session_id: "probe", tool_name: "Bash", tool_input: toolInput, tool_response: { stdout: "" } },
91
+ ]) {
92
+ execFileSync("/bin/sh", [commandPath], {
93
+ input: JSON.stringify(event), encoding: "utf8", timeout: 2000, maxBuffer: 8192, cwd: home, env, stdio: ["pipe", "ignore", "ignore"],
94
+ });
95
+ }
96
+ const paired = JSON.parse(readFileSync(join(dir, `${agentId}.spool.json`), "utf-8"));
97
+ const pairedRecords = Array.isArray(paired.records) ? paired.records : [];
98
+ if (pairedRecords.length !== 1)
99
+ return failure;
100
+ const pairedContent = typeof pairedRecords[0]?.content === "string" ? pairedRecords[0].content : "";
101
+ if (!pairedContent.includes(nonce) || pairedContent.includes(secret) || !pairedContent.includes("[redacted]"))
102
+ return failure;
103
+ return null;
104
+ }
105
+ catch {
106
+ return failure;
107
+ }
108
+ finally {
109
+ if (home) {
110
+ try {
111
+ rmSync(home, { recursive: true, force: true });
112
+ }
113
+ catch { }
114
+ }
115
+ }
116
+ }
117
+ export function isWorkingCaptureRuntime(runtime) {
118
+ return probeCaptureRuntime(runtime) === null;
119
+ }
120
+ export function resolveCaptureRuntime(opts) {
121
+ return resolveHookRuntime(opts, CAPTURE_ARTIFACT, probeCaptureRuntime);
122
+ }
123
+ /** Re-exported for callers that need the version the descriptor expects. */
124
+ export { flairCliVersion };