@tpsdev-ai/flair 0.58.0 → 0.62.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 (268) hide show
  1. package/README.md +7 -6
  2. package/SECURITY.md +36 -0
  3. package/config.yaml +15 -1
  4. package/dist/bridges/builtins/mem0.js +63 -28
  5. package/dist/bridges/runtime/import-runner.js +12 -0
  6. package/dist/bridges/runtime/load-plugin.js +42 -13
  7. package/dist/bridges/runtime/yaml-loader.js +4 -2
  8. package/dist/build-info.json +3 -3
  9. package/dist/cli.js +1030 -343
  10. package/dist/commands/agent.js +384 -45
  11. package/dist/commands/attention.js +4 -3
  12. package/dist/commands/backup.js +202 -34
  13. package/dist/commands/bridge.js +172 -119
  14. package/dist/commands/deploy.js +37 -4
  15. package/dist/commands/doctor.js +601 -163
  16. package/dist/commands/export.js +54 -19
  17. package/dist/commands/federation.js +141 -21
  18. package/dist/commands/hook.js +155 -2
  19. package/dist/commands/idp.js +14 -1
  20. package/dist/commands/import.js +7 -3
  21. package/dist/commands/init.js +462 -193
  22. package/dist/commands/integrity.js +388 -0
  23. package/dist/commands/keys.js +247 -58
  24. package/dist/commands/mcp.js +146 -53
  25. package/dist/commands/memory.js +171 -21
  26. package/dist/commands/migrate-harness-memory.js +3 -2
  27. package/dist/commands/orgevent.js +46 -37
  28. package/dist/commands/presence.js +4 -3
  29. package/dist/commands/principal.js +426 -48
  30. package/dist/commands/quality.js +10 -1
  31. package/dist/commands/reembed.js +141 -17
  32. package/dist/commands/relationship.js +2 -1
  33. package/dist/commands/rem.js +56 -18
  34. package/dist/commands/restore.js +101 -61
  35. package/dist/commands/search.js +6 -4
  36. package/dist/commands/service.js +151 -38
  37. package/dist/commands/soul.js +4 -3
  38. package/dist/commands/status.js +43 -5
  39. package/dist/commands/test.js +3 -2
  40. package/dist/commands/upgrade.js +24 -1
  41. package/dist/commands/workspace.js +6 -3
  42. package/dist/component-env.js +31 -41
  43. package/dist/deploy.js +77 -1
  44. package/dist/doctor-client.js +529 -92
  45. package/dist/engine-version-contract.js +1 -0
  46. package/dist/engine-version.js +23 -3
  47. package/dist/federation-verify.js +4 -3
  48. package/dist/hook-install.js +670 -6
  49. package/dist/keystore.js +72 -0
  50. package/dist/lib/action-recall-runtime.js +328 -0
  51. package/dist/lib/agent-home-fields.js +132 -0
  52. package/dist/lib/agent-home.js +427 -0
  53. package/dist/lib/agent-id-rule.js +46 -0
  54. package/dist/lib/agent-roster.js +33 -0
  55. package/dist/lib/auth-resolve.js +49 -16
  56. package/dist/lib/capture-runtime.js +124 -0
  57. package/dist/lib/credential-status-rule.js +78 -0
  58. package/dist/lib/daemon-liveness.js +81 -8
  59. package/dist/lib/doctor-run.js +140 -35
  60. package/dist/lib/durability-copy.js +10 -0
  61. package/dist/lib/embedding-space-doctor.js +75 -0
  62. package/dist/lib/flair-agent-role.js +120 -0
  63. package/dist/lib/hub-url.js +12 -0
  64. package/dist/lib/init-admin-pass.js +88 -12
  65. package/dist/lib/init-listener-environ.js +1 -2
  66. package/dist/lib/init-occupied-listener.js +15 -111
  67. package/dist/lib/init-spawn-attribution.js +73 -0
  68. package/dist/lib/init-tcp-probe.js +33 -0
  69. package/dist/lib/instance-identity-row.js +20 -0
  70. package/dist/lib/launchd-management.js +27 -2
  71. package/dist/lib/listener-table.js +268 -0
  72. package/dist/lib/local-delete-instance.js +27 -0
  73. package/dist/lib/local-instance-pair.js +256 -0
  74. package/dist/lib/mcp-enable.js +1775 -338
  75. package/dist/lib/mcp-oauth-env-core.js +133 -0
  76. package/dist/lib/mcp-oauth-env.js +125 -0
  77. package/dist/lib/mcp-spec.js +17 -1
  78. package/dist/lib/memory-attributes.js +2 -0
  79. package/dist/lib/memory-id-policy.js +46 -0
  80. package/dist/lib/memory-integrity.js +309 -0
  81. package/dist/lib/memory-purge-response.js +20 -0
  82. package/dist/lib/ops-table-count.js +25 -0
  83. package/dist/lib/owned-pins.js +67 -10
  84. package/dist/lib/peer-status.js +27 -0
  85. package/dist/lib/principal-status.js +29 -0
  86. package/dist/lib/process-start-time.js +103 -7
  87. package/dist/lib/proto-safe-record.js +42 -0
  88. package/dist/lib/record-id-path.js +25 -0
  89. package/dist/lib/reembed-server-support.js +66 -0
  90. package/dist/lib/restore-verify.js +104 -0
  91. package/dist/lib/scheduler-platform.js +10 -6
  92. package/dist/lib/secret-keys.js +25 -0
  93. package/dist/lib/secrets-push.js +50 -22
  94. package/dist/lib/skill-seed-pending.js +24 -0
  95. package/dist/lib/skill-seed.js +365 -0
  96. package/dist/lib/stop-start-recovery.js +54 -0
  97. package/dist/lib/using-flair-skill.js +87 -0
  98. package/dist/mcp-client-assertion.js +112 -4
  99. package/dist/memory-id-checkpoint.js +326 -0
  100. package/dist/memory-node-compare.js +207 -0
  101. package/dist/packages/flair-mcp/src/secret-redaction.js +113 -0
  102. package/dist/rem/restore.js +6 -5
  103. package/dist/rem/runner.js +103 -44
  104. package/dist/resources/Agent.js +348 -8
  105. package/dist/resources/AgentKeyRegister.js +214 -0
  106. package/dist/resources/AgentKeyRegistration.js +28 -0
  107. package/dist/resources/AgentSeed.js +19 -4
  108. package/dist/resources/AutoPromoteCandidates.js +7 -1
  109. package/dist/resources/Credential.js +177 -2
  110. package/dist/resources/Federation.js +752 -132
  111. package/dist/resources/FederationRetry.js +140 -0
  112. package/dist/resources/InstructionVersion.js +220 -0
  113. package/dist/resources/Integration.js +300 -25
  114. package/dist/resources/Memory.js +2113 -604
  115. package/dist/resources/MemoryArchive.js +75 -42
  116. package/dist/resources/MemoryBootstrap.js +227 -64
  117. package/dist/resources/MemoryCandidate.js +21 -1
  118. package/dist/resources/MemoryDedupStats.js +30 -1
  119. package/dist/resources/MemoryFeed.js +327 -45
  120. package/dist/resources/MemoryGrant.js +21 -1
  121. package/dist/resources/MemoryMaintenance.js +129 -25
  122. package/dist/resources/MemoryPurge.js +232 -0
  123. package/dist/resources/MemoryReflect.js +7 -2
  124. package/dist/resources/MemoryReindex.js +24 -8
  125. package/dist/resources/Message.js +5 -3
  126. package/dist/resources/OAuth.js +186 -9
  127. package/dist/resources/OrgEvent.js +126 -3
  128. package/dist/resources/OrgSkillAssignment.js +209 -0
  129. package/dist/resources/Presence.js +144 -49
  130. package/dist/resources/PromoteMemoryCandidate.js +18 -7
  131. package/dist/resources/Relationship.js +23 -0
  132. package/dist/resources/SemanticSearch.js +63 -32
  133. package/dist/resources/Soul.js +189 -76
  134. package/dist/resources/TeamDirectory.js +35 -0
  135. package/dist/resources/WorkspaceState.js +21 -1
  136. package/dist/resources/XAA.js +212 -65
  137. package/dist/resources/agent-auth.js +40 -15
  138. package/dist/resources/agent-status-guard.js +63 -0
  139. package/dist/resources/auth-middleware.js +402 -162
  140. package/dist/resources/ed25519-auth.js +1 -1
  141. package/dist/resources/embedding-space-guard.js +366 -72
  142. package/dist/resources/engine-version-stamp-boot.js +53 -0
  143. package/dist/resources/federation-classify.js +94 -0
  144. package/dist/resources/federation-crypto.js +5 -5
  145. package/dist/resources/federation-retry-lib.js +135 -0
  146. package/dist/resources/flair-agent-role-boot.js +26 -0
  147. package/dist/resources/grant-visibility.js +135 -0
  148. package/dist/resources/harper-routing.js +83 -0
  149. package/dist/resources/health.js +130 -20
  150. package/dist/resources/host-source-citation.js +49 -0
  151. package/dist/resources/host-source-visibility.js +7 -6
  152. package/dist/resources/instance-create-lock.js +17 -0
  153. package/dist/resources/instance-identity.js +23 -0
  154. package/dist/resources/instruction-version-record.js +343 -0
  155. package/dist/resources/key-lock.js +31 -0
  156. package/dist/resources/mcp-handler.js +36 -8
  157. package/dist/resources/mcp-oauth-env-guard.js +36 -0
  158. package/dist/resources/mcp-oauth.js +26 -12
  159. package/dist/resources/mcp-tool-arguments.js +4 -6
  160. package/dist/resources/mcp-tools.js +150 -23
  161. package/dist/resources/memory-bootstrap-lib.js +5 -15
  162. package/dist/resources/memory-declared-attributes.js +3 -1
  163. package/dist/resources/memory-deletion-history.js +55 -0
  164. package/dist/resources/memory-durability.js +54 -0
  165. package/dist/resources/memory-embed-hash.js +88 -0
  166. package/dist/resources/memory-embedding-value.js +8 -0
  167. package/dist/resources/memory-host-source.js +27 -5
  168. package/dist/resources/memory-id-guard.js +75 -0
  169. package/dist/resources/memory-redaction.js +236 -0
  170. package/dist/resources/memory-supplied-vector.js +72 -0
  171. package/dist/resources/memory-write-lock.js +310 -0
  172. package/dist/resources/memory-write-response.js +139 -0
  173. package/dist/resources/migrations/data-dir.js +74 -16
  174. package/dist/resources/migrations/dir-safety.js +1 -1
  175. package/dist/resources/migrations/embedding-stamp.js +193 -79
  176. package/dist/resources/migrations/export.js +1 -0
  177. package/dist/resources/migrations/graph-heal.js +18 -25
  178. package/dist/resources/migrations/lock.js +7 -1
  179. package/dist/resources/migrations/snapshot.js +1 -0
  180. package/dist/resources/migrations/source-fields.js +5 -5
  181. package/dist/resources/migrations/synthetic-test-migration.js +14 -11
  182. package/dist/resources/migrations/visibility-backfill.js +29 -29
  183. package/dist/resources/multi-worker-guard.js +121 -0
  184. package/dist/resources/oauth-discovery.js +1 -0
  185. package/dist/resources/oauth-wellknown.js +8 -4
  186. package/dist/resources/object-body-guard.js +33 -0
  187. package/dist/resources/org-event-created-at.js +133 -0
  188. package/dist/resources/originator-instance.js +39 -7
  189. package/dist/resources/owner-delete-recheck.js +78 -0
  190. package/dist/resources/owner-field-guard.js +39 -5
  191. package/dist/resources/owner-scoped-write-policy.js +212 -0
  192. package/dist/resources/owner-scoped-writes.js +58 -0
  193. package/dist/resources/presence-receipt.js +236 -0
  194. package/dist/resources/promotion-stamp.js +47 -12
  195. package/dist/resources/record-owner-guard.js +74 -26
  196. package/dist/resources/record-types.js +17 -1
  197. package/dist/resources/relay-ops.js +78 -6
  198. package/dist/resources/replay-store.js +145 -21
  199. package/dist/resources/request-target.js +136 -0
  200. package/dist/resources/request-transaction.js +35 -0
  201. package/dist/resources/search-readiness.js +4 -1
  202. package/dist/resources/seed-ids.js +9 -0
  203. package/dist/resources/seed-reservation.js +117 -0
  204. package/dist/resources/semantic-retrieval-core.js +20 -9
  205. package/dist/resources/skill-manifest.js +190 -0
  206. package/dist/resources/skill-provenance.js +15 -10
  207. package/dist/resources/skill-subject.js +53 -0
  208. package/dist/resources/skill-version-write.js +432 -0
  209. package/dist/resources/skill-write-fault.js +17 -0
  210. package/dist/resources/skill-write-policy.js +67 -0
  211. package/dist/resources/skill-write.js +67 -7
  212. package/dist/resources/table-helpers.js +10 -7
  213. package/dist/resources/team-directory.js +248 -0
  214. package/dist/resources/tool-descriptors/index.js +69 -8
  215. package/dist/resources/txn-pause-point.js +118 -0
  216. package/dist/resources/usage-recording.js +171 -63
  217. package/dist/resources/write-back.js +218 -0
  218. package/dist/src/engine-version-contract.js +1 -0
  219. package/dist/src/keystore.js +72 -0
  220. package/dist/src/lib/agent-home-fields.js +132 -0
  221. package/dist/src/lib/agent-id-rule.js +46 -0
  222. package/dist/src/lib/agent-key-register.js +80 -0
  223. package/dist/src/lib/atomic-write.js +256 -0
  224. package/dist/src/lib/credential-status-rule.js +78 -0
  225. package/dist/src/lib/expired-by-agent.js +37 -0
  226. package/dist/src/lib/flair-agent-role.js +120 -0
  227. package/dist/src/lib/idp-mapping-rule.js +81 -0
  228. package/dist/src/lib/instance-identity-row.js +20 -0
  229. package/dist/src/lib/mcp-oauth-env-core.js +133 -0
  230. package/dist/src/lib/memory-attributes.js +2 -0
  231. package/dist/src/lib/memory-id-policy.js +46 -0
  232. package/dist/src/lib/principal-status.js +29 -0
  233. package/dist/src/lib/proto-safe-record.js +42 -0
  234. package/dist/src/lib/reembed-server-support.js +66 -0
  235. package/dist/src/lib/scheduler-platform.js +10 -6
  236. package/dist/src/lib/systemd-agent-id.js +38 -0
  237. package/docs/access-control.md +768 -0
  238. package/docs/api-reference.md +52 -13
  239. package/docs/auth.md +10 -12
  240. package/docs/bridges.md +11 -0
  241. package/docs/claude-code.md +34 -4
  242. package/docs/deepseek-harness.md +1 -1
  243. package/docs/deploying-on-fabric.md +70 -0
  244. package/docs/deployment.md +2 -0
  245. package/docs/embedding-in-a-harper-app.md +1 -1
  246. package/docs/federation.md +33 -2
  247. package/docs/hosted-on-fabric.md +43 -36
  248. package/docs/integrations.md +6 -6
  249. package/docs/mcp-clients.md +10 -5
  250. package/docs/n8n.md +17 -11
  251. package/docs/notes/mcp-agent-auth-consumer.md +12 -4
  252. package/docs/notes/mcp-oauth-model2.md +34 -5
  253. package/docs/quickstart-fabric.md +2 -2
  254. package/docs/quickstart.md +9 -1
  255. package/docs/releasing.md +34 -28
  256. package/docs/rem.md +8 -0
  257. package/docs/secrets-and-keys.md +19 -2
  258. package/docs/standalone-local.md +1 -0
  259. package/docs/supply-chain-policy.md +13 -3
  260. package/docs/upgrade.md +32 -6
  261. package/package.json +12 -6
  262. package/schemas/agent-key-registration.graphql +22 -0
  263. package/schemas/agent.graphql +3 -0
  264. package/schemas/federation.graphql +38 -1
  265. package/schemas/memory.graphql +115 -5
  266. package/schemas/oauth.graphql +27 -4
  267. package/schemas/schema.graphql +2 -0
  268. package/templates/launchd/start-flair-with-admin-pass.sh +89 -16
@@ -3,9 +3,11 @@ import { dirname, join } from "node:path";
3
3
  import nacl from "tweetnacl";
4
4
  import * as render from "../render.js";
5
5
  import { defaultKeysDir, resolveAdminUser, resolveLocalAdminPass } from "../lib/auth-resolve.js";
6
- import { resolveAgentKeyPath, loadEd25519PrivateKeyFromFile, signClientAssertion, buildTokenRequestForm, getMcpAccessToken, McpTokenRequestError, defaultMcpClientId, defaultMcpTokenEndpoint, defaultMcpResource, defaultMcpIssuer, MAX_ASSERTION_LIFETIME_SECONDS, } from "../mcp-client-assertion.js";
7
- import { enableMcp, disableMcp, mcpStatus, checkLocalOriginRefusal, selfVerifyMcpMetadata, } from "../lib/mcp-enable.js";
6
+ import { resolveAgentKeyPath, loadEd25519PrivateKeyFromFile, signClientAssertion, buildTokenRequestForm, getMcpAccessToken, McpTokenRequestError, defaultMcpClientId, defaultMcpTokenEndpoint, defaultMcpResource, defaultMcpIssuer, MAX_ASSERTION_LIFETIME_SECONDS, clientAssertionAudienceForm, resolveClientAssertionAudience, oauthMetadataUrl, } from "../mcp-client-assertion.js";
7
+ import { enableMcp, refreshMcpOAuthFlag, disableMcp, mcpStatus, checkLocalOriginRefusal, fabricLoopbackRefusal, targetOriginRefusal, selfVerifyMcpMetadata, cimdAllowedHostsFromFlag, claudeAiExcludedNote, } from "../lib/mcp-enable.js";
8
8
  import { resolveHome } from "../lib/home.js";
9
+ import { invalidAgentIdMessage, isValidAgentId } from "../lib/agent-id-rule.js";
10
+ import { agentHomeEndpoint, resolveTargetInstanceId } from "../lib/agent-home.js";
9
11
  let cli;
10
12
  /** Bind shared CLI helpers. cli.ts calls this immediately before register(program). */
11
13
  export function bindCli(fns) {
@@ -101,7 +103,6 @@ export class McpClientNotFoundError extends Error {
101
103
  this.name = "McpClientNotFoundError";
102
104
  }
103
105
  }
104
- const MCP_CLIENT_NAME_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/;
105
106
  /**
106
107
  * Core, testable `flair mcp grant` orchestration — no process.exit, no
107
108
  * console output, so it's directly unit-testable with a mocked fetch and a
@@ -113,9 +114,12 @@ export async function grantMcpClient(params, deps = {}) {
113
114
  const fetchImpl = deps.fetchImpl ?? fetch;
114
115
  const now = deps.now ?? (() => new Date().toISOString());
115
116
  const generateKeyPair = deps.generateKeyPair ?? (() => nacl.sign.keyPair());
116
- if (!MCP_CLIENT_NAME_PATTERN.test(name)) {
117
- throw new Error(`Invalid machine client name '${name}' — must be 1-64 chars, start alphanumeric, ` +
118
- `and contain only letters, digits, '_', '-' (it becomes an Agent id, a key filename, and a URL path segment).`);
117
+ if (!isValidAgentId(name)) {
118
+ throw new Error(`Invalid machine client name '${name}' — ${invalidAgentIdMessage(name)}.`);
119
+ }
120
+ // MCP client naming policy also requires a leading letter or digit.
121
+ if (!/^[a-zA-Z0-9]/.test(name)) {
122
+ throw new Error(`Invalid machine client name '${name}' — MCP client naming policy: must start with a letter or digit.`);
119
123
  }
120
124
  const manifest = readMcpClientManifest(manifestPath);
121
125
  if (manifest.some((e) => e.name === name)) {
@@ -153,6 +157,9 @@ export async function grantMcpClient(params, deps = {}) {
153
157
  chmodSync(privPath, 0o600);
154
158
  writeFileSync(pubPath, Buffer.from(kp.publicKey));
155
159
  const nowIso = now();
160
+ // flair#2433 — the new Agent row's home is THIS instance's federation id,
161
+ // resolved through the one shared rule; a create stamps it.
162
+ const home = await resolveTargetInstanceId(agentHomeEndpoint(opsUrl, adminUser, adminPass, fetchImpl));
156
163
  const insertRes = await fetchImpl(opsUrl, {
157
164
  method: "POST",
158
165
  headers: { "Content-Type": "application/json", Authorization: authHeader },
@@ -171,6 +178,7 @@ export async function grantMcpClient(params, deps = {}) {
171
178
  defaultTrustTier: "unverified",
172
179
  runtime: "headless",
173
180
  publicKey: pubKeyB64url,
181
+ originatorInstanceId: home,
174
182
  createdAt: nowIso,
175
183
  updatedAt: nowIso,
176
184
  }],
@@ -258,14 +266,6 @@ export async function revokeMcpClient(params, deps = {}) {
258
266
  return entry;
259
267
  }
260
268
  // ─── flair mcp enable / disable / status ────────────────────────────────────
261
- // flair#719 — the last piece of the paved-paths command family. Automates
262
- // docs/notes/mcp-oauth-model2.md's 8-step operator checklist into one
263
- // command, per the design record + K&S verdicts on #719's thread (see
264
- // src/lib/mcp-enable.ts's module header for the full binding design record,
265
- // including the scenario addendum: `enable` targets the HOSTED shape only —
266
- // it runs on the OPERATOR's machine, against a REMOTE instance, and refuses
267
- // honestly against a local-origin instance rather than walking eight steps
268
- // toward a connector that can never connect).
269
269
  /** Simple y/N confirmation over readline — TTY-only, mirrors the existing
270
270
  * restore-confirmation pattern (`flair snapshot restore`) above. */
271
271
  async function confirmYesNo(question) {
@@ -276,7 +276,7 @@ async function confirmYesNo(question) {
276
276
  const answer = await new Promise((res) => rl.question(`${question} [y/N] `, (a) => { rl.close(); res(a); }));
277
277
  return /^y(es)?$/i.test(answer.trim());
278
278
  }
279
- /** Plain-text readline prompt (tests never exercise this — CLI-only). Used
279
+ /** Plain-text readline prompt. Used
280
280
  * for --idp-client-id/--idp-client-secret/--idp-subject when a flag is
281
281
  * omitted and stdin is a TTY. */
282
282
  async function promptText(question) {
@@ -285,6 +285,25 @@ async function promptText(question) {
285
285
  const answer = await new Promise((res) => rl.question(question, (a) => { rl.close(); res(a); }));
286
286
  return answer.trim();
287
287
  }
288
+ /**
289
+ * flair#2113 review: the closing lines of a successful `flair mcp enable`.
290
+ * They claim only what the run checked: the self-verify step's OAuth metadata
291
+ * check (the /mcp route itself is not probed), and, when this run confirmed a
292
+ * --cimd-allowed-hosts list (ensured it in config.yaml, writing the list only
293
+ * if the file did not already hold that exact list, and read it back), whether
294
+ * that list includes claude.ai. With no flag the command does not inspect
295
+ * allowedHosts, so it says nothing about claude.ai.
296
+ */
297
+ export function enableSuccessLines(result) {
298
+ const lines = [
299
+ `${render.icons.ok} ${render.wrap(render.c.bold, "The OAuth metadata check passed.")} The /mcp route itself was not probed.`,
300
+ ];
301
+ const claudeAiNote = claudeAiExcludedNote(result.cimdAllowedHosts);
302
+ if (claudeAiNote)
303
+ lines.push(`${render.icons.info} ${claudeAiNote}`);
304
+ lines.push("", result.pasteBlock ?? "", "");
305
+ return lines;
306
+ }
288
307
  function printEnableSteps(result) {
289
308
  console.log(`\n${render.wrap(render.c.bold, "flair mcp enable")}${result.dryRun ? render.wrap(render.c.dim, " (dry run)") : ""}\n`);
290
309
  for (const s of result.steps) {
@@ -293,6 +312,18 @@ function printEnableSteps(result) {
293
312
  }
294
313
  console.log("");
295
314
  }
315
+ function printRefreshFlagSteps(result) {
316
+ console.log(`\n${render.wrap(render.c.bold, "flair mcp enable --refresh-flag")}${result.dryRun ? render.wrap(render.c.dim, " (dry run)") : ""}\n`);
317
+ for (const s of result.steps) {
318
+ console.log(` ${s.ok ? render.icons.ok : render.icons.error} ${render.wrap(render.c.dim, s.step)}`);
319
+ console.log(` ${s.detail}`);
320
+ }
321
+ console.log("");
322
+ if (result.ok && !result.dryRun) {
323
+ console.log(`${render.icons.ok} ${render.wrap(render.c.bold, "Encrypted FLAIR_MCP_OAUTH=true update accepted; secret processEnv marker, restart and discovery metadata checks passed.")} Confirm with \`flair mcp status\`.`);
324
+ console.log("");
325
+ }
326
+ }
296
327
  export function register(program) {
297
328
  const mcp = program.command("mcp").description("MCP client-credentials agent-auth (RFC 7523 private_key_jwt)");
298
329
  mcp
@@ -303,8 +334,13 @@ export function register(program) {
303
334
  .requiredOption("--agent-id <id>", "Agent id — becomes the client_id (iss/sub claims)")
304
335
  .option("--client-id <url>", "Client ID Metadata Document URL for this agent (defaults to this instance's " +
305
336
  "MCPClientMetadata URL, derived from FLAIR_MCP_ISSUER/FLAIR_PUBLIC_URL)")
306
- .option("--token-endpoint <url>", "Token-endpoint URL — becomes the `aud` claim (defaults to this instance's " +
337
+ .option("--token-endpoint <url>", "Token-endpoint URL — becomes the `aud` claim in token-endpoint mode (defaults to this instance's " +
307
338
  "own oauth token endpoint, same env vars)")
339
+ .option("--assertion-audience <form>", 'Audience form: "token-endpoint" (default — aud is the token-endpoint URL, header typ "JWT") ' +
340
+ 'or "issuer" (aud is the authorization server metadata document\'s issuer, header typ ' +
341
+ '"client-authentication+jwt"). Uses FLAIR_MCP_CLIENT_ASSERTION_AUDIENCE when set; otherwise token-endpoint.')
342
+ .option("--issuer <url>", "Authorization server origin whose metadata document supplies the `aud` for the " +
343
+ '"issuer" audience form (defaults to this instance\'s issuer, same env vars)')
308
344
  .option("--resource <url>", "RFC 8707 resource indicator for the token request (defaults to this instance's canonical /mcp URI)")
309
345
  .option("--keys-dir <dir>", "Directory to look for <agentId>.key (else FLAIR_KEY_DIR, ~/.flair/keys, ~/.tps/secrets/flair)")
310
346
  .option("--expires-in <seconds>", `Assertion exp - iat window, seconds (default + hard cap: ${MAX_ASSERTION_LIFETIME_SECONDS})`)
@@ -333,6 +369,27 @@ export function register(program) {
333
369
  }
334
370
  const resource = opts.resource ?? defaultMcpResource();
335
371
  const expiresIn = opts.expiresIn ? Number(opts.expiresIn) : undefined;
372
+ let audienceForm;
373
+ try {
374
+ audienceForm = clientAssertionAudienceForm(opts.assertionAudience);
375
+ }
376
+ catch (err) {
377
+ console.error(`Error: ${err?.message ?? err}`);
378
+ process.exit(1);
379
+ }
380
+ const issuerOrigin = opts.issuer ?? defaultMcpIssuer();
381
+ let audience;
382
+ try {
383
+ audience = await resolveClientAssertionAudience({
384
+ form: audienceForm,
385
+ tokenEndpoint,
386
+ metadataUrl: issuerOrigin ? oauthMetadataUrl(issuerOrigin) : undefined,
387
+ });
388
+ }
389
+ catch (err) {
390
+ console.error(`Error: ${err?.message ?? err}`);
391
+ process.exit(1);
392
+ }
336
393
  let privateKey;
337
394
  try {
338
395
  privateKey = loadEd25519PrivateKeyFromFile(keyPath);
@@ -347,6 +404,7 @@ export function register(program) {
347
404
  tokenEndpoint,
348
405
  privateKey,
349
406
  expiresInSeconds: expiresIn,
407
+ audience,
350
408
  });
351
409
  const form = buildTokenRequestForm({ clientId, assertion, resource });
352
410
  if (opts.json) {
@@ -366,6 +424,7 @@ export function register(program) {
366
424
  privateKey,
367
425
  resource,
368
426
  expiresInSeconds: expiresIn,
427
+ audience,
369
428
  forceRefresh: Boolean(opts.forceRefresh),
370
429
  });
371
430
  if (opts.json) {
@@ -523,10 +582,11 @@ export function register(program) {
523
582
  });
524
583
  mcp
525
584
  .command("enable")
526
- .description("One-command hosted-shape enablement of the OAuth /mcp surface for claude.ai — automates the " +
527
- "docs/notes/mcp-oauth-model2.md checklist. Targets a REMOTE instance with a public HTTPS origin; " +
528
- "refuses honestly against a local-origin instance.")
529
- .option("--instance <url>", "Remote flair instance to enable against (else FLAIR_URL)")
585
+ .description("Enable the OAuth /mcp surface for claude.ai. " +
586
+ "Rejects invalid issuer URLs, localhost/.localhost/.local hosts, " +
587
+ "IPv4 0/8, 10/8, 127/8, 169.254/16, 172.16/12, 192.168/16 (also IPv4-mapped IPv6), " +
588
+ "and IPv6 ::, ::1, fc00::/7, fe80::/10; no DNS lookup.")
589
+ .option("--instance <url>", "Canonical http(s) target origin, optionally followed by / (else FLAIR_URL)")
530
590
  .option("--issuer <url>", "Public origin claude.ai will use (else --instance)")
531
591
  .option("--idp-provider <name>", "Upstream IdP provider", "github")
532
592
  .option("--idp-client-id <id>", "IdP OAuth app client id (else prompted interactively)")
@@ -534,43 +594,78 @@ export function register(program) {
534
594
  .option("--idp-subject <value>", "Your expected `sub`/login at the IdP (GitHub: your username; else prompted interactively)")
535
595
  .option("--principal <id>", "Principal (Agent) to map your IdP identity to — personal-shape default", "self")
536
596
  .option("--principal-kind <human|agent>", "Kind for a newly-created principal", "human")
537
- .option("--secrets-mechanism <fabric-env-secrets|env-file>", "Override the shape-aware secrets mechanism (else auto-detected from --instance)")
597
+ .option("--secrets-mechanism <fabric-env-secrets|env-file>", "Override the shape-aware secrets mechanism (else selected from --instance and --fabric)")
538
598
  .option("--secrets-path <path>", "Override the secrets staging file path")
539
- .option("--cimd-allowed-hosts <hosts>", "Comma-separated clientIdMetadataDocuments.allowedHosts override (else claude.ai,claude.com)")
540
- .option("--signing-key-file <path>", "RS256 signing key PEM file (else ~/.flair/mcp-signing-key.pem)")
599
+ .option("--cimd-allowed-hosts <hosts>", "Comma-separated lowercase hostnames to ensure as mcp.clientIdMetadataDocuments.allowedHosts in the config.yaml " +
600
+ "this command edits on this machine (./config.yaml, else ~/.flair/config.yaml), written unless that file already holds " +
601
+ "that exact list, then read back, before the restart. " +
602
+ "Without --dry-run, refused unless a preflight match links the host and pid the target reports, a readable " +
603
+ "process on this machine, and that file (by realpath); --dry-run skips the match and writes nothing. " +
604
+ "Always refused with --fabric or a *.harperfabric.com instance. " +
605
+ "Without it the list is not changed (shipped: claude.ai,claude.com)")
541
606
  .option("--admin-pass <pass>", "Admin password for the TARGET instance. Required explicitly for a remote target — FLAIR_ADMIN_PASS and ~/.flair/admin-pass are this machine's local credentials and are never sent to a remote instance")
542
607
  .option("--admin-user <name>", "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)")
543
608
  .option("--confirm-secrets-applied", "Confirm the staged secrets are already live on the target instance's environment (skips the interactive confirm)")
544
- .option("--dry-run", "Generate keys/tokens/config and validate inputs; skip every remote call")
609
+ .option("--fabric", "Use the Fabric branch and default to Fabric secrets staging; refused for a localhost, *.localhost, 127/8, ::1, ::ffff:127/8, 0.0.0.0 or :: target host")
610
+ .option("--dry-run", "Preview enable or refresh without writing files or making remote calls. Skip live checks; refresh refuses an occupied explicit --secrets-path")
611
+ .option("--refresh-flag", "One-shot migration (flair#2283): attempt the encrypted FLAIR_MCP_OAUTH=true push, check the secret row's processEnv marker, restart and check discovery metadata; when the update could not be pushed or confirmed, attempt a 0600 fallback file and exit non-zero. An occupied explicit path is refused before probing, including in dry run; an occupied default path is refused when fallback is needed. Uses a separate default filename; --secrets-path can select mcp enable's path. Does not re-run IdP intake or apply identity mapping or CIMD changes. Use it to correct FLAIR_MCP_OAUTH=1, which does not enable the component's MCP AS")
545
612
  .option("--json", "Print machine-readable JSON instead of a human summary")
546
613
  .action(async (opts) => {
547
614
  const instance = opts.instance ?? process.env.FLAIR_URL;
548
615
  if (!instance) {
549
- console.error("Error: --instance is required (or set FLAIR_URL) — `flair mcp enable` targets a specific remote instance.");
616
+ console.error("Error: --instance is required (or set FLAIR_URL) — `flair mcp enable` targets a specific instance.");
550
617
  process.exit(1);
551
618
  }
552
- // Local-origin refusal short-circuits before we ask for anything else —
553
- // never walk the operator through IdP app creation for a connector that
554
- // can never connect.
555
- const localCheck = checkLocalOriginRefusal(instance);
619
+ const targetRefusal = targetOriginRefusal(instance) ?? fabricLoopbackRefusal(instance, Boolean(opts.fabric));
620
+ if (targetRefusal) {
621
+ console.error(`${render.icons.error} ${targetRefusal}`);
622
+ process.exit(1);
623
+ }
624
+ const localCheck = checkLocalOriginRefusal(opts.issuer ?? instance);
556
625
  if (localCheck.refused) {
557
626
  console.error(`${render.icons.error} ${localCheck.message}`);
558
627
  process.exit(1);
559
628
  }
629
+ // flair#2113: an invalid --cimd-allowed-hosts, or one for a Fabric
630
+ // instance, is refused here, before anything is asked for. An explicit empty
631
+ // value is refused too: it used to be dropped as if the flag were absent.
632
+ const cimdFlag = cimdAllowedHostsFromFlag(opts.cimdAllowedHosts, instance, Boolean(opts.fabric));
633
+ if (cimdFlag.error) {
634
+ console.error(`${render.icons.error} ${cimdFlag.error}`);
635
+ process.exit(1);
636
+ }
560
637
  const dryRun = Boolean(opts.dryRun);
561
- // --instance is ALWAYS remote for this command (local is refused above)
562
- // — isRemoteTarget=true so a missing --admin-pass/FLAIR_ADMIN_PASS never
563
- // silently falls back to THIS machine's local ~/.flair/admin-pass file
564
- // against someone else's instance (see resolveLocalAdminPass's doc comment).
565
638
  const adminPass = dryRun ? (opts.adminPass ?? process.env.FLAIR_ADMIN_PASS ?? "") : resolveLocalAdminPass(opts.adminPass, /* isRemoteTarget */ true);
566
639
  if (!dryRun && !adminPass) {
567
- console.error("Error: --admin-pass <pass> or --admin-pass-file <path> is required for a REMOTE target " +
568
- "(the operations API on the target instance needs it for identity mapping + restart).\n" +
640
+ console.error("Error: --admin-pass <pass> is required for a REMOTE target " +
641
+ "(the command authenticates to the target instance's operations API with it).\n" +
569
642
  " FLAIR_ADMIN_PASS and ~/.flair/admin-pass are deliberately NOT used here: they are THIS machine's " +
570
643
  "local admin credentials, and sending them to another instance is how a local secret ends up on someone " +
571
644
  "else's Harper. Pass the target's own admin password explicitly.");
572
645
  process.exit(1);
573
646
  }
647
+ // flair#2283: refresh failures exit non-zero in both output modes.
648
+ if (opts.refreshFlag) {
649
+ const refreshed = await refreshMcpOAuthFlag({
650
+ instance,
651
+ issuer: opts.issuer,
652
+ adminUser: resolveAdminUser(opts.adminUser),
653
+ adminPass,
654
+ fabric: Boolean(opts.fabric),
655
+ dryRun,
656
+ secretsStagingPath: opts.secretsPath,
657
+ }, {});
658
+ if (opts.json) {
659
+ console.log(render.asJSON(refreshed));
660
+ if (!refreshed.ok)
661
+ process.exit(1);
662
+ return;
663
+ }
664
+ printRefreshFlagSteps(refreshed);
665
+ if (!refreshed.ok)
666
+ process.exit(1);
667
+ return;
668
+ }
574
669
  let idpClientId = opts.idpClientId;
575
670
  let idpClientSecret = opts.idpClientSecret;
576
671
  let idpSubject = opts.idpSubject;
@@ -587,9 +682,6 @@ export function register(program) {
587
682
  console.error(`Error: --secrets-mechanism must be "fabric-env-secrets" or "env-file", got "${secretsMechanism}"`);
588
683
  process.exit(1);
589
684
  }
590
- const cimdAllowedHosts = opts.cimdAllowedHosts
591
- ? String(opts.cimdAllowedHosts).split(",").map((h) => h.trim()).filter(Boolean)
592
- : undefined;
593
685
  const result = await enableMcp({
594
686
  instance,
595
687
  issuer: opts.issuer,
@@ -601,12 +693,12 @@ export function register(program) {
601
693
  principalKind: opts.principalKind,
602
694
  adminUser: resolveAdminUser(opts.adminUser),
603
695
  adminPass,
604
- signingKeyFilePath: opts.signingKeyFile,
605
696
  secretsMechanism,
606
697
  secretsStagingPath: opts.secretsPath,
607
- cimdAllowedHosts,
698
+ cimdAllowedHosts: cimdFlag.hosts,
608
699
  dryRun,
609
700
  confirmSecretsApplied: Boolean(opts.confirmSecretsApplied),
701
+ fabric: Boolean(opts.fabric),
610
702
  }, { confirmPrompt: dryRun ? undefined : confirmYesNo });
611
703
  if (opts.json) {
612
704
  console.log(render.asJSON(result));
@@ -620,15 +712,17 @@ export function register(program) {
620
712
  }
621
713
  if (!result.ok) {
622
714
  if (result.failedStep === "fabric-operator-deploy") {
623
- // flair#1136: Fabric deployments require the operator to deploy the
624
- // config change — we can't write to harperdb-config.yaml (Fabric
625
- // regenerates it on every container restart).
715
+ // flair#1136/#1152: on Fabric, `enable` never restarts the instance and
716
+ // needs no config edit (config.yaml ships mcp.enabled as an env
717
+ // reference). The operator addresses the cause the step reports (applying
718
+ // the environment and restarting when it says so); a re-run then passes
719
+ // this step once self-verify does (flair#2116).
720
+ // The step's own detail above carries the specifics.
626
721
  console.error(`\n${render.icons.info} ${render.wrap(render.c.bold, "Fabric deployment detected.")}`);
627
- console.error(` The @harperfast/oauth block ships in your component config.yaml with mcp.enabled: false.`);
628
- console.error(` To activate: set mcp.enabled: true (literal boolean) in your deployed component`);
629
- console.error(` config.yaml, ensure the staged secrets are live in the instance's process`);
630
- console.error(` environment, and redeploy. Then re-run \`flair mcp enable\` — earlier steps`);
631
- console.error(` are idempotent and will be reused.\n`);
722
+ console.error(` The /mcp OAuth surface did not pass self-verify on the public origin yet; the step above says why`);
723
+ console.error(` and what to do. Address that cause (restart the instance if its environment changed), then re-run`);
724
+ console.error(` \`flair mcp enable\` with the same options plus --confirm-secrets-applied: that step checks again`);
725
+ console.error(` and passes once self-verify does.\n`);
632
726
  }
633
727
  else {
634
728
  console.error(`${render.icons.error} enable failed at step "${result.failedStep}" — see detail above for the exact fix, then re-run \`flair mcp enable\` (earlier steps are idempotent and will be reused).`);
@@ -639,15 +733,14 @@ export function register(program) {
639
733
  console.log(`${render.icons.info} ${render.wrap(render.c.dim, "dry-run: no remote calls were made.")}`);
640
734
  return;
641
735
  }
642
- console.log(`${render.icons.ok} ${render.wrap(render.c.bold, "claude.ai can now connect.")}\n`);
643
- console.log(result.pasteBlock ?? "");
644
- console.log("");
736
+ for (const line of enableSuccessLines(result))
737
+ console.log(line);
645
738
  });
646
739
  mcp
647
740
  .command("disable")
648
741
  .description("Flag off + restart = byte-identical boot (Model-2 contract) — removes the /mcp OAuth surface.")
649
742
  .option("--instance <url>", "Remote flair instance to disable against (else FLAIR_URL)")
650
- .option("--admin-pass <pass>", "Admin password for the target instance (or FLAIR_ADMIN_PASS)")
743
+ .option("--admin-pass <pass>", "Admin password for the remote target instance; pass it explicitly with --admin-pass")
651
744
  .option("--admin-user <name>", "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)")
652
745
  .option("--confirm-flag-off", "Confirm FLAIR_MCP_OAUTH is already unset on the target instance's environment (skips the interactive confirm)")
653
746
  .option("--json", "Print machine-readable JSON instead of a human summary")
@@ -661,7 +754,7 @@ export function register(program) {
661
754
  // comment in `mcp enable` above.
662
755
  const adminPass = resolveLocalAdminPass(opts.adminPass, /* isRemoteTarget */ true);
663
756
  if (!adminPass) {
664
- console.error("Error: --admin-pass or FLAIR_ADMIN_PASS required.");
757
+ console.error("Error: --admin-pass <pass> is required for a REMOTE target. Pass the target instance's admin password explicitly.");
665
758
  process.exit(1);
666
759
  }
667
760
  const result = await disableMcp({ instance, adminUser: resolveAdminUser(opts.adminUser), adminPass, confirmFlagOff: Boolean(opts.confirmFlagOff) }, { confirmPrompt: confirmYesNo });
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * memory.ts — `flair memory` command group (flair#1621 / epic #1618).
3
3
  *
4
- * Extracted from src/cli.ts with ZERO behavior change. This file owns the
4
+ * This file owns the
5
5
  * group's commander registration, action handlers, and group-specific
6
6
  * inline helpers (hygiene predicates). Shared CLI helpers (api,
7
7
  * resolveSigningAgentId, credential flags, --entities parse, …) stay in
@@ -14,6 +14,14 @@
14
14
  import { Option } from "commander";
15
15
  import * as render from "../render.js";
16
16
  import { resolveAdminUser } from "../lib/auth-resolve.js";
17
+ import { encodeRecordId } from "../lib/record-id-path.js";
18
+ import { DURABILITY_TIERS_HELP } from "../lib/durability-copy.js";
19
+ import { resolveLocalDeleteInstance } from "../lib/local-delete-instance.js";
20
+ import { confirmedPurgeIds } from "../lib/memory-purge-response.js";
21
+ import { resolveHome } from "../lib/home.js";
22
+ import { ALL_TIERS } from "../lib/memory-integrity.js";
23
+ import { normalizeOrigin, buildCheckpoint, buildOpsPost, readMemoryRowCount, readMemoryRowsPaged, readCheckpointFile, writeCheckpointFile, checkpointPath, unknownVerify, verifyCheckpoint, renderVerifyHuman, VERIFY_EXIT_CODES, } from "../memory-id-checkpoint.js";
24
+ import { classifyNodeSets, readNode, renderCompareNodesHuman, COMPARE_EXIT_CODES, } from "../memory-node-compare.js";
17
25
  let cli;
18
26
  /** Bind shared CLI helpers. cli.ts calls this immediately before register(program). */
19
27
  export function bindCli(fns) {
@@ -43,6 +51,9 @@ function resolveOpsPort(opts) {
43
51
  function parseEntitiesOptionOrExit(csv) {
44
52
  return cli.parseEntitiesOptionOrExit(csv);
45
53
  }
54
+ function resolveFabricCredentials(opts) {
55
+ return cli.resolveFabricCredentials(opts);
56
+ }
46
57
  // Exported for unit testing — keeps the predicate logic separable from
47
58
  // the CLI plumbing, ops-API fetching, and confirmation flow.
48
59
  export const HYGIENE_TEST_CONTENT_PATTERNS = [
@@ -73,7 +84,7 @@ export function register(program) {
73
84
  addSharedCredentialOptions(addSharedIdentityOption(memory.command("add [content]")
74
85
  .description("Write a new memory row for an agent (content via positional arg or --content)")))
75
86
  .option("--content <text>", "memory content (alias for positional arg)")
76
- .option("--durability <d>", "permanent|persistent|standard|ephemeral (default standard). Also decides the default visibility when --visibility is omitted: permanent/persistent -> shared, standard/ephemeral -> private").option("--tags <csv>")
87
+ .option("--durability <d>", `${DURABILITY_TIERS_HELP} (default standard). Also decides the default visibility when --visibility is omitted: permanent/persistent -> shared, standard/ephemeral -> private`).option("--tags <csv>")
77
88
  .option("--summary <text>", "agent-set multi-sentence dense compression (3-tier chain: subject → summary → content)")
78
89
  .option("--subject <text>", "one-line title / entity this memory is about")
79
90
  .option("--derived-from <csv>", "Comma-separated source Memory IDs this memory was distilled/reflected from (sets Memory.derivedFrom; used by the `rem rapid` reflection loop)")
@@ -126,7 +137,7 @@ export function register(program) {
126
137
  if (entities.length > 0)
127
138
  body.entities = entities;
128
139
  }
129
- const out = await api("PUT", `/Memory/${memId}`, body, {
140
+ const out = await api("PUT", `/Memory/${encodeRecordId(memId)}`, body, {
130
141
  agentId,
131
142
  agentIdSource: source,
132
143
  explicitAdminPass: opts.adminPass,
@@ -205,7 +216,7 @@ export function register(program) {
205
216
  if (opts.derivedFrom) {
206
217
  body.derivedFrom = String(opts.derivedFrom).split(",").map((x) => x.trim()).filter(Boolean);
207
218
  }
208
- const out = await api("PUT", `/Memory/${encodeURIComponent(memId)}`, body, { agentId, agentIdSource: source });
219
+ const out = await api("PUT", `/Memory/${encodeRecordId(memId)}`, body, { agentId, agentIdSource: source });
209
220
  if (out?.error) {
210
221
  console.error(`Error writing task summary: ${out.error}`);
211
222
  process.exit(1);
@@ -430,7 +441,6 @@ export function register(program) {
430
441
  .option("--port <port>", "Harper HTTP port")
431
442
  .option("--ops-port <port>", "Harper ops API port (default: HTTP - 1)")
432
443
  .action(async (opts) => {
433
- const opsPort = resolveOpsPort(opts);
434
444
  const adminPass = process.env.FLAIR_ADMIN_PASS ?? process.env.HDB_ADMIN_PASSWORD;
435
445
  if (!adminPass) {
436
446
  console.error("❌ Admin password required (set FLAIR_ADMIN_PASS or HDB_ADMIN_PASSWORD).");
@@ -440,9 +450,11 @@ export function register(program) {
440
450
  const tinyThreshold = Math.max(0, Number(opts.tinyThreshold) || 25);
441
451
  const apply = !!opts.apply;
442
452
  const opsAuth = `Basic ${Buffer.from(`${resolveAdminUser(undefined)}:${adminPass}`).toString("base64")}`;
453
+ const instance = await resolveLocalDeleteInstance(opts, resolveOpsPort, opsAuth);
443
454
  async function ops(body) {
444
- const res = await fetch(`http://127.0.0.1:${opsPort}/`, {
455
+ const res = await fetch(instance.opsUrl, {
445
456
  method: "POST",
457
+ redirect: "error",
446
458
  headers: { "Content-Type": "application/json", Authorization: opsAuth },
447
459
  body: JSON.stringify(body),
448
460
  signal: AbortSignal.timeout(60_000),
@@ -498,26 +510,164 @@ export function register(program) {
498
510
  console.log("\n(dry-run) — re-run with --apply to delete the matched rows.");
499
511
  return;
500
512
  }
501
- // Delete in chunks (Harper accepts batches of hash_values).
502
513
  const ids = Array.from(allIds);
503
- const chunkSize = 200;
504
- let deleted = 0;
505
- for (let i = 0; i < ids.length; i += chunkSize) {
506
- const batch = ids.slice(i, i + chunkSize);
507
- const result = await ops({
508
- operation: "delete",
509
- database: "flair",
510
- table: "Memory",
511
- hash_values: batch,
512
- });
513
- const m = /(\d+)\s*of\s*\d+\s*records/.exec(result.message ?? "");
514
- deleted += m ? Number(m[1]) : batch.length;
515
- process.stdout.write(`\r Deleting ${deleted}/${ids.length} (${Math.round((deleted / ids.length) * 100)}%)`);
516
- }
514
+ // Remove the matched rows through the server's physical-removal path: a
515
+ // skill-tagged row expands to its whole lineage there. The count printed
516
+ // is the rows the response lists as removed; a response that does not
517
+ // list every matched id fails the command.
518
+ const purge = await api("POST", "/MemoryPurge", { ids }, {
519
+ baseUrl: instance.baseUrl, explicitAdminPass: adminPass,
520
+ adminUser: resolveAdminUser(undefined), agentId: null,
521
+ });
522
+ const deleted = confirmedPurgeIds(purge, ids).length;
517
523
  console.log(`\n\n✅ Deleted ${deleted} rows.`);
518
524
  console.log("");
519
525
  console.log("Note: this is a local-instance delete. Federated peers will keep their copies until");
520
526
  console.log("tombstone-based distributed delete lands. Until then, run `flair memory");
521
527
  console.log("hygiene --apply` on each peer to fan out.");
522
528
  });
529
+ // ── flair memory checkpoint / verify (flair#2218) ─────────────────────────
530
+ const credentialOptions = (cmd, withOpsTarget = true) => {
531
+ if (withOpsTarget)
532
+ cmd.option("--ops-target <url>", "Operations API URL override (env: FLAIR_OPS_TARGET)");
533
+ return cmd
534
+ .option("--fabric-user <user>", "Admin username (env: FABRIC_USER; inline leaks to ps/shell history)")
535
+ .option("--fabric-password <pass>", "Admin password (prefer FABRIC_PASSWORD env or --fabric-password-file)")
536
+ .option("--fabric-password-file <path>", "Read the admin password from a mode-0600 file");
537
+ };
538
+ const requireCredentials = (opts, command) => {
539
+ const { fabricUser, fabricPassword, warnings } = resolveFabricCredentials(opts);
540
+ for (const w of warnings)
541
+ console.error(render.wrap(render.c.dim, w));
542
+ if (!fabricUser || !fabricPassword) {
543
+ console.error(render.wrap(render.c.red, `${command}: admin credentials required`));
544
+ console.error(" set FABRIC_USER + FABRIC_PASSWORD env, or --fabric-password-file, or (discouraged) inline --fabric-user/--fabric-password");
545
+ process.exit(1);
546
+ }
547
+ return { user: fabricUser, pass: fabricPassword };
548
+ };
549
+ const originOf = (target, command) => {
550
+ try {
551
+ return normalizeOrigin(target);
552
+ }
553
+ catch {
554
+ console.error(render.wrap(render.c.red, `${command}: --target must be a URL (the instance's own origin)`));
555
+ process.exit(1);
556
+ }
557
+ };
558
+ credentialOptions(memory
559
+ .command("checkpoint")
560
+ .description("Write this instance's Memory ids and per-tier counts to an operator-held checkpoint (mode 0600) before a planned cluster operation")
561
+ .requiredOption("--target <url>", "Instance served URL; operations API address is derived unless --ops-target or FLAIR_OPS_TARGET is set")
562
+ .option("--checkpoint <path>", "Checkpoint file path (default: ~/.flair/memory-id-checkpoint.json)")).action(async (opts) => {
563
+ const { user, pass } = requireCredentials(opts, "flair memory checkpoint");
564
+ const origin = originOf(opts.target, "flair memory checkpoint");
565
+ const path = opts.checkpoint ?? checkpointPath(resolveHome());
566
+ try {
567
+ const opsOrigin = normalizeOrigin(cli.resolveEffectiveOpsUrl({ ...opts, target: origin }));
568
+ const opsPost = buildOpsPost(opsOrigin, user, pass);
569
+ const expected = await readMemoryRowCount(opsPost);
570
+ const rows = await readMemoryRowsPaged(opsPost, { expected });
571
+ const checkpoint = buildCheckpoint({ node: opsOrigin, at: new Date().toISOString(), rows });
572
+ writeCheckpointFile(path, checkpoint);
573
+ const counts = ALL_TIERS.map((t) => `${t} ${checkpoint.byDurability[t]}`).join(", ");
574
+ console.log(`${render.icons.ok} Checkpoint written: ${path}`);
575
+ console.log(` node: ${checkpoint.host} at ${checkpoint.at}`);
576
+ console.log(` memories: ${checkpoint.ids.length} id(s) — ${counts}`);
577
+ console.log(render.wrap(render.c.dim, " no Memory content was read or written"));
578
+ }
579
+ catch (err) {
580
+ console.error(render.wrap(render.c.red, `${render.icons.error} checkpoint unknown: ${err instanceof Error ? err.message : String(err)}`));
581
+ console.error(render.wrap(render.c.dim, " no checkpoint was written"));
582
+ process.exit(3);
583
+ }
584
+ });
585
+ credentialOptions(memory
586
+ .command("verify")
587
+ .description("Compare this instance's Memory ids with a checkpoint taken before the operation: integrity failure, verified, or unknown")
588
+ .requiredOption("--target <url>", "Instance served URL — must resolve to the same operations origin")
589
+ .option("--checkpoint <path>", "Checkpoint file path (default: ~/.flair/memory-id-checkpoint.json)")
590
+ .addHelpText("after", `
591
+ Exit codes:
592
+ 0 verified — checkpointed ids present and no tier-count drop; new ids are fine
593
+ 1 absent checkpoint — no verification outcome
594
+ 2 integrity failure — a checkpointed Memory id is missing, or a durability tier count dropped
595
+ 3 unknown — comparison could not be completed: e.g. unreadable checkpoint, different operations origin, failed read, or count change
596
+ `)).action(async (opts) => {
597
+ const { user, pass } = requireCredentials(opts, "flair memory verify");
598
+ const origin = originOf(opts.target, "flair memory verify");
599
+ const path = opts.checkpoint ?? checkpointPath(resolveHome());
600
+ const read = readCheckpointFile(path);
601
+ if (read.kind === "absent") {
602
+ console.error(render.wrap(render.c.red, `${render.icons.error} no checkpoint at ${path}`));
603
+ console.error(` run \`flair memory checkpoint\` before the operation to create one`);
604
+ process.exit(1);
605
+ }
606
+ const result = read.kind === "unreadable"
607
+ ? unknownVerify(`checkpoint unreadable: ${read.reason}`)
608
+ : await verifyCheckpoint({ checkpoint: read.checkpoint, target: origin, opsTarget: cli.resolveEffectiveOpsUrl({ ...opts, target: origin }), user, password: pass });
609
+ console.log(renderVerifyHuman(result, path));
610
+ process.exit(VERIFY_EXIT_CODES[result.outcome]);
611
+ });
612
+ // ── flair memory compare-nodes (flair#2216, slice 2 of #971) ──────────────
613
+ credentialOptions(memory
614
+ .command("compare-nodes")
615
+ .description("Compare observed Memory id sets of two or more explicitly named nodes")
616
+ .option("--node <ops-url>", "A node's operations API URL (repeat once per node; at least two)", (value, seen) => [...seen, value], [])
617
+ .option("--json", "Print the comparison as JSON")
618
+ .addHelpText("after", `
619
+ Each --node explicitly names an HTTP(S) operations API URL; its path, query and
620
+ fragment are removed. Peers are never inferred from Flair federation peers.
621
+
622
+ The command compares observed id sets. Count checks cannot detect equal-count
623
+ concurrent updates or replacements. An id absent on every named node is invisible
624
+ without a reference set.
625
+
626
+ Classes use stored timestamps: parseable updatedAt, else createdAt. createdAt can
627
+ be caller-supplied and node clocks can differ; these do not prove write order.
628
+ A missing id uses the maximum timestamp among usable peers holding it.
629
+
630
+ Per-node classes:
631
+ in-sync observed ids equal the union of the other usable readings
632
+ lagging missing ids only, each timestamp greater than this node's maximum
633
+ divergent an extra id, or a missing id timestamp at or below this node's maximum
634
+ unknown failed read, unusable timestamp, no usable peer, or no local timestamp for missing ids
635
+
636
+ The overall result is healthy only when every node is in-sync;
637
+ any unknown makes the overall result unknown.
638
+
639
+ Exit codes:
640
+ 0 healthy — every node has the same observed Memory ids
641
+ 1 usage — fewer than two --node values, a duplicate node, or an invalid HTTP(S) URL
642
+ 2 divergent — at least one divergent node and no unknown node
643
+ 3 unknown — at least one node could not be classified
644
+ 4 lagging — at least one node is lagging, with no divergent or unknown nodes
645
+ `), false).action(async (opts) => {
646
+ const provided = opts.node ?? [];
647
+ if (provided.length < 2) {
648
+ console.error(render.wrap(render.c.red, `${render.icons.error} flair memory compare-nodes: at least two --node values are required`));
649
+ process.exit(1);
650
+ }
651
+ const nodes = [];
652
+ for (const raw of provided) {
653
+ let origin;
654
+ try {
655
+ origin = normalizeOrigin(raw);
656
+ }
657
+ catch {
658
+ console.error(render.wrap(render.c.red, `${render.icons.error} --node must be an HTTP(S) operations API origin without credentials`));
659
+ process.exit(1);
660
+ }
661
+ if (nodes.includes(origin)) {
662
+ console.error(render.wrap(render.c.red, `${render.icons.error} --node ${origin} was given more than once`));
663
+ process.exit(1);
664
+ }
665
+ nodes.push(origin);
666
+ }
667
+ const { user, pass } = requireCredentials(opts, "flair memory compare-nodes");
668
+ const readings = await Promise.all(nodes.map((node) => readNode(node, { user, password: pass })));
669
+ const result = classifyNodeSets(readings);
670
+ console.log(opts.json ? JSON.stringify(result, null, 2) : renderCompareNodesHuman(result));
671
+ process.exit(COMPARE_EXIT_CODES[result.verdict]);
672
+ });
523
673
  }