@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
@@ -14,10 +14,10 @@
14
14
  * uninstall itself. The report always names leftovers instead of claiming
15
15
  * "fully purged" when anything remains.
16
16
  */
17
- import { existsSync, rmSync } from "node:fs";
18
- import { join } from "node:path";
17
+ import { existsSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
18
+ import { basename, join } from "node:path";
19
19
  import { resolveHome, withHome } from "./home.js";
20
- import { ALL_CLIENTS } from "../install/clients.js";
20
+ import { ALL_CLIENTS, clientConfigBackupPath, clientConfigHasFlairEntry, } from "../install/clients.js";
21
21
  import { uninstallContinuityHooks, uninstallHook, harnessSupportsContinuity, hookBackupPath, hookSettingsPath, SUPPORTED_HARNESSES, } from "../hook-install.js";
22
22
  import { disableScheduler as disableRemScheduler, LAUNCHD_LABEL as REM_LAUNCHD_LABEL, SYSTEMD_SERVICE_UNIT as REM_SYSTEMD_SERVICE, SYSTEMD_TIMER_UNIT as REM_SYSTEMD_TIMER, } from "../rem/scheduler.js";
23
23
  import { disableScheduler as disableFederationScheduler, LAUNCHD_LABEL as FED_LAUNCHD_LABEL, SYSTEMD_SERVICE_UNIT as FED_SYSTEMD_SERVICE, SYSTEMD_TIMER_UNIT as FED_SYSTEMD_TIMER, } from "../federation/scheduler.js";
@@ -103,18 +103,248 @@ function sweepHookBackup(settingsPath, reportedBackup, homeDir, removed, leftove
103
103
  rmPath(bak, removed, leftovers, displayUnderHome(homeDir, bak));
104
104
  }
105
105
  }
106
+ /**
107
+ * After a failed read: is the path genuinely absent? A dangling symlink also
108
+ * reads as ENOENT but is an entry purge could not check — not a missing one.
109
+ */
110
+ function backupEntryAbsent(path) {
111
+ try {
112
+ lstatSync(path);
113
+ return false;
114
+ }
115
+ catch (err) {
116
+ return err.code === "ENOENT";
117
+ }
118
+ }
119
+ /**
120
+ * Client configs get the same sibling snapshot as hook settings: an unwire
121
+ * that writes an existing config copies its pre-write bytes to `<config>.bak`
122
+ * when that copy write succeeds. Purge removes a copy that
123
+ * `clientConfigHasFlairEntry()` identifies as carrying a Flair entry and
124
+ * reports the path like a hook backup. A copy with no Flair entry may be the
125
+ * user's own file and stays — as does one whose wiring could not be decided,
126
+ * which is reported as not checked (flair#2886).
127
+ *
128
+ * Call inside `withHome(homeDir, ...)`: `clientConfigBackupPath()` resolves `~`
129
+ * at call time, so the sweep must run with the target home in the environment,
130
+ * not the caller's (flair#2886).
131
+ */
132
+ function sweepClientConfigBackup(clientId, homeDir, removed, leftovers) {
133
+ const backup = clientConfigBackupPath(clientId);
134
+ const display = displayUnderHome(homeDir, backup);
135
+ let bytes;
136
+ try {
137
+ bytes = readFileSync(backup);
138
+ }
139
+ catch (err) {
140
+ const code = err.code;
141
+ if (code === "ENOENT" && backupEntryAbsent(backup))
142
+ return;
143
+ leftovers.push({
144
+ path: display,
145
+ kind: "unverified",
146
+ reason: `could not check for Flair wiring: could not read the file${code ? ` (${code})` : ""}`,
147
+ });
148
+ return;
149
+ }
150
+ const scan = clientConfigHasFlairEntry(clientId, bytes, display);
151
+ if (scan.status === "unknown") {
152
+ leftovers.push({
153
+ path: display,
154
+ kind: "unverified",
155
+ reason: `could not check for Flair wiring: ${scan.reason}`,
156
+ });
157
+ return;
158
+ }
159
+ if (scan.status === "present")
160
+ rmPath(backup, removed, leftovers, display);
161
+ }
162
+ /**
163
+ * TEST-ONLY pause between choosing a hold directory name and creating it, so
164
+ * a fixture can occupy the name. Inert unless
165
+ * `FLAIR_TEST_PURGE_HOLD_BARRIER` names a directory; self-releases after 15 s.
166
+ */
167
+ function holdSelectionBarrier(candidate) {
168
+ const barrierDir = process.env.FLAIR_TEST_PURGE_HOLD_BARRIER;
169
+ if (!barrierDir)
170
+ return;
171
+ try {
172
+ writeFileSync(join(barrierDir, `${process.pid}.hold-select`), candidate);
173
+ }
174
+ catch { /* inert */ }
175
+ const release = join(barrierDir, `${process.pid}.go`);
176
+ const deadline = Date.now() + 15_000;
177
+ while (!existsSync(release) && Date.now() < deadline) {
178
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 5);
179
+ }
180
+ }
181
+ /**
182
+ * Select a hold directory name and create it exclusively. `mkdir` without
183
+ * `recursive` fails with `EEXIST` when any entry already occupies the name,
184
+ * so a user file or directory there is never adopted or overwritten. The name
185
+ * carries this process's pid and a per-client sequence; the directory is
186
+ * created with requested mode 0700.
187
+ */
188
+ function reserveHoldPath(backup, seq) {
189
+ for (let attempt = 0; attempt < 16; attempt++) {
190
+ const candidate = `${backup}.purge-hold-${process.pid}-${seq}${attempt === 0 ? "" : `-${attempt}`}`;
191
+ holdSelectionBarrier(candidate);
192
+ try {
193
+ mkdirSync(candidate, { mode: 0o700 });
194
+ return { dir: candidate, path: join(candidate, basename(backup)) };
195
+ }
196
+ catch (err) {
197
+ if (err.code === "EEXIST")
198
+ continue;
199
+ throw err;
200
+ }
201
+ }
202
+ throw new Error("no free hold path name after 16 attempts");
203
+ }
204
+ /**
205
+ * A pre-existing `<config>.bak` is the user's copy until this purge decides
206
+ * otherwise, but the unwire's snapshot write renames over it. Move it aside
207
+ * first and put it back before the sweep, so its bytes — or, for a symlink,
208
+ * the link itself — survive the unwire. This covers a copy that cannot be
209
+ * read or parsed too: a failed read must never license its replacement. The
210
+ * hold directory is created exclusively, so a file or directory already at
211
+ * its name is never overwritten; when no free name can be reserved, or the
212
+ * rename fails, the client is reported and its unwire and sweep are skipped.
213
+ * Call inside `withHome(homeDir, ...)`.
214
+ */
215
+ function holdClientConfigBackups(homeDir, leftovers) {
216
+ const held = [];
217
+ const skipped = new Set();
218
+ for (const client of ALL_CLIENTS) {
219
+ const backup = clientConfigBackupPath(client.id);
220
+ try {
221
+ lstatSync(backup);
222
+ }
223
+ catch (err) {
224
+ if (err.code === "ENOENT")
225
+ continue;
226
+ const reason = err instanceof Error ? err.message : String(err);
227
+ leftovers.push({
228
+ path: displayUnderHome(homeDir, backup),
229
+ kind: "failed",
230
+ reason: `could not hold the backup across unwiring: ${reason}; skipped unwiring this client`,
231
+ });
232
+ skipped.add(client.id);
233
+ continue;
234
+ }
235
+ let hold;
236
+ try {
237
+ hold = reserveHoldPath(backup, held.length);
238
+ }
239
+ catch (err) {
240
+ const reason = err instanceof Error ? err.message : String(err);
241
+ leftovers.push({
242
+ path: displayUnderHome(homeDir, backup),
243
+ kind: "failed",
244
+ reason: `could not reserve a hold path: ${reason}; skipped unwiring this client`,
245
+ });
246
+ skipped.add(client.id);
247
+ continue;
248
+ }
249
+ try {
250
+ renameSync(backup, hold.path);
251
+ held.push({ clientId: client.id, path: backup, heldPath: hold.path, heldDir: hold.dir, display: displayUnderHome(homeDir, backup) });
252
+ }
253
+ catch (err) {
254
+ rmSync(hold.dir, { recursive: true, force: true });
255
+ const reason = err instanceof Error ? err.message : String(err);
256
+ leftovers.push({
257
+ path: displayUnderHome(homeDir, backup),
258
+ kind: "failed",
259
+ reason: `could not hold the backup across unwiring: ${reason}; skipped unwiring this client`,
260
+ });
261
+ skipped.add(client.id);
262
+ }
263
+ }
264
+ return { held, skipped };
265
+ }
266
+ /** Put a held entry back over the snapshot this purge's unwire attempts to
267
+ * write, then let the sweep decide it. A client whose restore fails is
268
+ * returned so its sweep is skipped; the REASON names the held copy, and
269
+ * after a failed restore that copy may remain only at the hold path. Call
270
+ * inside `withHome(homeDir, ...)`. */
271
+ export function restoreHeldClientConfigBackups(homeDir, held, leftovers) {
272
+ const unrestored = new Set();
273
+ for (const item of held) {
274
+ try {
275
+ rmSync(item.path, { force: true });
276
+ renameSync(item.heldPath, item.path);
277
+ }
278
+ catch (err) {
279
+ unrestored.add(item.clientId);
280
+ const reason = err instanceof Error ? err.message : String(err);
281
+ leftovers.push({
282
+ path: item.display,
283
+ kind: "failed",
284
+ reason: `could not restore the backup held across unwiring: ${reason}; skipped this backup's sweep; ` +
285
+ `the held copy remains at ${displayUnderHome(homeDir, item.heldPath)}`,
286
+ });
287
+ continue;
288
+ }
289
+ // Empty now; remove only the directory this purge created. Its loss is
290
+ // not a restore failure — the copy is already back at the config path.
291
+ try {
292
+ rmSync(item.heldDir, { recursive: true, force: true });
293
+ }
294
+ catch { /* empty hold dir left */ }
295
+ }
296
+ return unrestored;
297
+ }
298
+ /** Restore held snapshots, then sweep eligible clients. A failed hold skips
299
+ * unwiring and leaves the original backup in place. A failed restore skips
300
+ * the sweep and reports the held path; the original backup path may be absent.
301
+ * An absent backup is not held, and its client proceeds (flair#2886). */
302
+ export function restoreAndSweepClientConfigBackups(homeDir, hold, removed, leftovers) {
303
+ const unrestored = restoreHeldClientConfigBackups(homeDir, hold.held, leftovers);
304
+ for (const client of ALL_CLIENTS) {
305
+ if (hold.skipped.has(client.id) || unrestored.has(client.id))
306
+ continue;
307
+ sweepClientConfigBackup(client.id, homeDir, removed, leftovers);
308
+ }
309
+ }
310
+ /** Run client-config work with `HOME` set to the home being purged, and —
311
+ * when that home is not the caller's — with `PI_CODING_AGENT_DIR` ignored, so
312
+ * pi resolves under the target home instead of the caller's pi directory. */
313
+ function withClientConfigHome(homeDir, ignorePiDirOverride, fn) {
314
+ if (!ignorePiDirOverride) {
315
+ withHome(homeDir, fn);
316
+ return;
317
+ }
318
+ const prevPiDir = process.env.PI_CODING_AGENT_DIR;
319
+ withHome(homeDir, () => {
320
+ delete process.env.PI_CODING_AGENT_DIR;
321
+ try {
322
+ fn();
323
+ }
324
+ finally {
325
+ if (prevPiDir !== undefined)
326
+ process.env.PI_CODING_AGENT_DIR = prevPiDir;
327
+ }
328
+ });
329
+ }
106
330
  /**
107
331
  * Remove Flair-owned state under `homeDir`: the `~/.flair` tree (data, keys,
108
332
  * admin-pass, backups, logs, snapshots, shims), REM + federation scheduler
109
- * units on both platforms, SessionStart/continuity hooks, and MCP/native
110
- * client wiring. The npm package is listed as an intentional leftover
111
- * unless `omitNpmLeftover` is set.
333
+ * units on both platforms, SessionStart/continuity hooks, MCP/native
334
+ * client wiring, and the client-config snapshots left by unwiring. The npm
335
+ * package is listed as an intentional leftover unless `omitNpmLeftover` is set.
112
336
  */
113
337
  export function purgeFlairInstall(opts = {}) {
114
- const homeDir = opts.homeDir ?? resolveHome();
338
+ const callerHome = resolveHome();
339
+ const homeDir = opts.homeDir ?? callerHome;
340
+ const ignorePiDirOverride = homeDir !== callerHome && process.env.PI_CODING_AGENT_DIR !== undefined;
115
341
  const skipUnload = !!opts.skipSchedulerUnload;
116
342
  const removed = [];
117
343
  const leftovers = [];
344
+ const notes = [];
345
+ if (ignorePiDirOverride) {
346
+ notes.push(`ignored PI_CODING_AGENT_DIR while purging a different home: pi settings resolved under ${displayUnderHome(homeDir, join(homeDir, ".pi", "agent"))}`);
347
+ }
118
348
  disableAndSweepScheduler(homeDir, skipUnload, "rem", removed, leftovers);
119
349
  disableAndSweepScheduler(homeDir, skipUnload, "federation", removed, leftovers);
120
350
  for (const harness of SUPPORTED_HARNESSES) {
@@ -141,7 +371,17 @@ export function purgeFlairInstall(opts = {}) {
141
371
  for (const harness of SUPPORTED_HARNESSES) {
142
372
  sweepHookBackup(hookSettingsPath(homeDir, harness), null, homeDir, removed, leftovers);
143
373
  }
144
- const unwireResults = withHome(homeDir, () => ALL_CLIENTS.map((c) => c.unwire()));
374
+ const hold = { held: [], skipped: new Set() };
375
+ withClientConfigHome(homeDir, ignorePiDirOverride, () => {
376
+ const found = holdClientConfigBackups(homeDir, leftovers);
377
+ hold.held.push(...found.held);
378
+ for (const id of found.skipped)
379
+ hold.skipped.add(id);
380
+ });
381
+ const unwireResults = [];
382
+ withClientConfigHome(homeDir, ignorePiDirOverride, () => {
383
+ unwireResults.push(...ALL_CLIENTS.filter((c) => !hold.skipped.has(c.id)).map((c) => c.unwire()));
384
+ });
145
385
  for (const u of unwireResults) {
146
386
  if (!u.ok) {
147
387
  leftovers.push({ path: u.message, kind: "failed", reason: u.message });
@@ -150,6 +390,12 @@ export function purgeFlairInstall(opts = {}) {
150
390
  removed.push(u.message);
151
391
  }
152
392
  }
393
+ // Restore and sweep under the target home. A failed hold skipped unwiring
394
+ // and left the original backup in place; a failed restore skips the sweep,
395
+ // reports the held path, and may leave the original backup path absent.
396
+ withClientConfigHome(homeDir, ignorePiDirOverride, () => {
397
+ restoreAndSweepClientConfigBackups(homeDir, hold, removed, leftovers);
398
+ });
153
399
  const flairDir = join(homeDir, ".flair");
154
400
  rmPath(flairDir, removed, leftovers, "~/.flair");
155
401
  if (existsSync(flairDir)) {
@@ -167,19 +413,26 @@ export function purgeFlairInstall(opts = {}) {
167
413
  remedy: `npm uninstall -g ${FLAIR_NPM_PACKAGE}`,
168
414
  });
169
415
  }
170
- return { removed, leftovers };
416
+ return { removed, leftovers, notes };
171
417
  }
172
418
  export function formatPurgeReport(result) {
173
419
  const lines = [];
420
+ for (const note of result.notes ?? []) {
421
+ lines.push(`ℹ️ ${note}`);
422
+ }
174
423
  for (const item of result.removed) {
175
424
  lines.push(`✅ Removed: ${item}`);
176
425
  }
177
426
  const failed = result.leftovers.filter((l) => l.kind === "failed");
427
+ const unverified = result.leftovers.filter((l) => l.kind === "unverified");
178
428
  const intentional = result.leftovers.filter((l) => l.kind === "intentional");
179
429
  for (const item of failed) {
180
430
  lines.push(`⚠️ Left (failed): ${item.path} — ${item.reason}`);
181
431
  }
182
- if (failed.length === 0 && intentional.length === 0) {
432
+ for (const item of unverified) {
433
+ lines.push(`❓ Not checked: ${item.path} — ${item.reason}`);
434
+ }
435
+ if (failed.length === 0 && unverified.length === 0 && intentional.length === 0) {
183
436
  lines.push("");
184
437
  lines.push("🗑️ Flair fully purged");
185
438
  return { lines, claimedFullyPurged: true };
@@ -198,5 +451,7 @@ export function formatPurgeReport(result) {
198
451
  return { lines, claimedFullyPurged: false };
199
452
  }
200
453
  export function purgeHadFailures(result) {
201
- return result.leftovers.some((l) => l.kind === "failed");
454
+ // An unverified path means purge could not prove it was clean, so the run is
455
+ // not a success either (flair#2886).
456
+ return result.leftovers.some((l) => l.kind === "failed" || l.kind === "unverified");
202
457
  }
@@ -1,6 +1,7 @@
1
1
  /** Classify the pre-install /Health attempt for the restart-failure decision. */
2
+ import { REFUSED_CODES } from "./connect-phase.js";
2
3
  const DEFAULT_TIMEOUT_MS = 3000;
3
- const REFUSED_TOKENS = ["ECONNREFUSED", "ConnectionRefused"];
4
+ const REFUSED_TOKENS = REFUSED_CODES;
4
5
  function namesRefusal(text) {
5
6
  return REFUSED_TOKENS.some((token) => text.includes(token));
6
7
  }
@@ -45,10 +45,7 @@
45
45
  * `sub`).
46
46
  * - RFC 8707 `resource` parameter: accepted, exact-match, fail-closed,
47
47
  * defaulting to the configured canonical resource — `buildTokenRequestForm`
48
- * already carries an optional `resource` pass-through (see below), and
49
- * `defaultMcpResource()` supplies the configured canonical default
50
- * (mirrors `resources/mcp-oauth-flag.ts`'s `mcpResource()` — the same
51
- * `<issuer>/mcp` value the AS will exact-match against).
48
+ * already carries an optional `resource` pass-through (see below).
52
49
  * - Issued token `sub` = `client_id`; access-token TTL default 300s
53
50
  * (`mcp.clientCredentials.accessTokenTtl`); no `refresh_token` — agents
54
51
  * re-mint on 401/near-expiry instead (see `getMcpAccessToken` below).
@@ -67,6 +64,7 @@ import { createPrivateKey, createPublicKey, randomUUID, sign } from "node:crypto
67
64
  import { existsSync, readFileSync } from "node:fs";
68
65
  import { join } from "node:path";
69
66
  import { resolveHome } from "./lib/home.js";
67
+ import { agentKeyPath, legacyAgentKeyPath } from "./lib/key-dir.js";
70
68
  // ─── RFC 7523 constants ─────────────────────────────────────────────────────
71
69
  /** RFC 7523 §2.2 value for `client_assertion_type`. */
72
70
  export const CLIENT_ASSERTION_TYPE_JWT_BEARER = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";
@@ -178,10 +176,10 @@ export async function resolveClientAssertionAudience(params) {
178
176
  */
179
177
  export function resolveAgentKeyPath(agentId, keysDirOverride) {
180
178
  const candidates = [
181
- keysDirOverride ? join(keysDirOverride, `${agentId}.key`) : null,
182
- process.env.FLAIR_KEY_DIR ? join(process.env.FLAIR_KEY_DIR, `${agentId}.key`) : null,
183
- join(resolveHome(), ".flair", "keys", `${agentId}.key`),
184
- join(resolveHome(), ".tps", "secrets", "flair", `${agentId}-priv.key`),
179
+ keysDirOverride ? agentKeyPath(keysDirOverride, agentId) : null,
180
+ process.env.FLAIR_KEY_DIR ? agentKeyPath(process.env.FLAIR_KEY_DIR, agentId) : null,
181
+ agentKeyPath(join(resolveHome(), ".flair", "keys"), agentId),
182
+ legacyAgentKeyPath(agentId),
185
183
  ].filter((p) => Boolean(p));
186
184
  return candidates.find((p) => existsSync(p)) ?? null;
187
185
  }
@@ -441,12 +439,7 @@ export async function getMcpAccessToken(params) {
441
439
  }
442
440
  // ─── Convenience defaults (this Flair instance's own /mcp + oauth surface) ──
443
441
  //
444
- // Mirrors resources/mcp-oauth-flag.ts's mcpIssuer()/mcpResource() env-driven
445
- // defaults. Duplicated here (rather than imported) because src/ (this CLI's
446
- // build root, tsconfig.cli.json) and resources/ (tsconfig.json) are separate
447
- // TypeScript compilation roots with no existing cross-import in this repo —
448
- // keep both in sync if either changes. These are only DEFAULTS: every value
449
- // is overridable via CLI flags, since an agent may authenticate to a
442
+ // Each default is overridable via CLI flags, since an agent may authenticate to a
450
443
  // DIFFERENT Harper MCP server than the one running this CLI (identity is
451
444
  // portable — the whole point of the design, see
452
445
  // ~/ops/FLAIR-AGENT-AUTH-CONSUMER-SPEC.md "Wiring / usage").
@@ -9,7 +9,7 @@ export const CHECKPOINT_MODE = 0o600;
9
9
  export const CHECKPOINT_FILENAME = "memory-id-checkpoint.json";
10
10
  /** Rows requested per operations-API page. */
11
11
  export const MEMORY_PAGE_SIZE = 10_000;
12
- /** A full final page at this cap is refused. */
12
+ /** Hard page-walk bound. */
13
13
  export const MAX_MEMORY_PAGES = 100;
14
14
  /** Per-request timeout for the admin read. Every operation is bounded. */
15
15
  export const OPS_READ_TIMEOUT_MS = 30_000;
@@ -53,9 +53,14 @@ function asTime(value) {
53
53
  /**
54
54
  * Walk `flair.<table>` by primary key: `SELECT <select> ... [WHERE <filter> AND] id > cursor
55
55
  * ORDER BY id LIMIT <pageSize>`, resuming strictly after the last id read. A duplicate id
56
- * across pages, a full final page at the page cap, or a read that differs in size from
57
- * `expected` refuses. Duplicates raise InconsistentReadError; size mismatches do too by
58
- * default, but `mismatch` can return any Error. Errors from `opsPost` propagate unchanged.
56
+ * across pages, or a read that differs in size from `expected`, refuses. A full final page at
57
+ * the cap is accepted when a read after its last id returns no row and the rows read equal
58
+ * `expected`, the same evidence an uncapped walk ends on. The page allowance is
59
+ * `ceil(expected / pageSize) + 1`, capped by `maxPages`
60
+ * (default MAX_MEMORY_PAGES). Duplicates raise InconsistentReadError. Outside the cap branch a
61
+ * size mismatch raises InconsistentReadError by default, but `mismatch` can return any Error;
62
+ * a mismatch on a full final page at the cap raises the page-cap error. Errors from `opsPost`
63
+ * propagate unchanged.
59
64
  */
60
65
  export async function readTableByIdPaged(opsPost, opts) {
61
66
  const pageSize = opts.pageSize ?? MEMORY_PAGE_SIZE;
@@ -63,11 +68,15 @@ export async function readTableByIdPaged(opsPost, opts) {
63
68
  if (!Number.isSafeInteger(pageSize) || pageSize < 1 || !Number.isSafeInteger(maxPages) || maxPages < 1) {
64
69
  throw new Error("invalid keyset paging bounds");
65
70
  }
71
+ // The allowance is the pages the expected count needs plus one, or the caller's hard cap
72
+ // when that is smaller; the request count never follows a server-reported value without
73
+ // a bound.
74
+ const pageAllowance = Math.min(maxPages, Math.ceil(opts.expected / pageSize) + 1);
66
75
  const mismatch = opts.mismatch ?? ((expected, read) => new InconsistentReadError(`${opts.table}: server reports ${expected} rows, integrity read ${read}`));
67
76
  const rows = [];
68
77
  let lastId;
69
78
  const seen = new Set();
70
- for (let page = 0; page < maxPages; page++) {
79
+ for (let page = 0; page < pageAllowance; page++) {
71
80
  if (lastId?.includes("\\"))
72
81
  throw new Error(`${opts.table} cursor contains an unsupported backslash`);
73
82
  const where = [];
@@ -95,8 +104,17 @@ export async function readTableByIdPaged(opsPost, opts) {
95
104
  }
96
105
  if (batch.length < pageSize)
97
106
  break;
98
- if (page === maxPages - 1) {
99
- throw new Error(`${opts.table} read reached the ${maxPages}-page cap`);
107
+ if (page === pageAllowance - 1) {
108
+ if (lastId?.includes("\\"))
109
+ throw new Error(`${opts.table} cursor contains an unsupported backslash`);
110
+ const probeWhere = opts.filter ? `(${opts.filter}) AND ` : "";
111
+ const probe = asRows(await opsPost({
112
+ operation: "sql",
113
+ sql: `SELECT id FROM flair.${opts.table} WHERE ${probeWhere}id > '${lastId.replace(/'/g, "''")}' ORDER BY id LIMIT 1`,
114
+ }));
115
+ if (probe?.length === 0 && rows.length === opts.expected)
116
+ break;
117
+ throw new Error(`${opts.table} read reached the ${pageAllowance}-page cap`);
100
118
  }
101
119
  }
102
120
  if (rows.length !== opts.expected)
@@ -283,6 +301,9 @@ export function writeCheckpointFile(path, checkpoint) {
283
301
  /**
284
302
  * Read the live instance and compare it against the checkpoint. Any read
285
303
  * failure (unreachable instance, a page, or a short read) is UNKNOWN.
304
+ * The walk shares the reader's no-snapshot limit (see integrityReader in
305
+ * src/commands/integrity.ts), so a balanced concurrent write can leave a `verified`
306
+ * result that no single instant matched; #2679 tracks a consistent read.
286
307
  */
287
308
  export async function verifyCheckpoint(opts) {
288
309
  try {