@tpsdev-ai/flair 0.59.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 (259) hide show
  1. package/README.md +4 -4
  2. package/SECURITY.md +36 -0
  3. package/config.yaml +12 -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 +991 -248
  10. package/dist/commands/agent.js +224 -43
  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 +592 -146
  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 +97 -35
  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 +41 -10
  59. package/dist/lib/doctor-run.js +75 -37
  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 +4 -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 +24 -0
  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 +1168 -326
  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 +76 -12
  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 +321 -1
  105. package/dist/resources/AgentKeyRegister.js +214 -0
  106. package/dist/resources/AgentKeyRegistration.js +28 -0
  107. package/dist/resources/AgentSeed.js +10 -4
  108. package/dist/resources/AutoPromoteCandidates.js +7 -1
  109. package/dist/resources/Credential.js +177 -2
  110. package/dist/resources/Federation.js +751 -143
  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 +110 -39
  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/Presence.js +144 -49
  129. package/dist/resources/PromoteMemoryCandidate.js +18 -7
  130. package/dist/resources/Relationship.js +23 -0
  131. package/dist/resources/SemanticSearch.js +63 -32
  132. package/dist/resources/Soul.js +189 -76
  133. package/dist/resources/TeamDirectory.js +35 -0
  134. package/dist/resources/WorkspaceState.js +21 -1
  135. package/dist/resources/XAA.js +181 -63
  136. package/dist/resources/agent-auth.js +40 -15
  137. package/dist/resources/auth-middleware.js +400 -161
  138. package/dist/resources/ed25519-auth.js +1 -1
  139. package/dist/resources/embedding-space-guard.js +366 -72
  140. package/dist/resources/engine-version-stamp-boot.js +53 -0
  141. package/dist/resources/federation-classify.js +72 -0
  142. package/dist/resources/federation-crypto.js +5 -5
  143. package/dist/resources/federation-retry-lib.js +135 -0
  144. package/dist/resources/grant-visibility.js +135 -0
  145. package/dist/resources/harper-routing.js +83 -0
  146. package/dist/resources/health.js +120 -18
  147. package/dist/resources/host-source-citation.js +49 -0
  148. package/dist/resources/host-source-visibility.js +7 -6
  149. package/dist/resources/instance-create-lock.js +17 -0
  150. package/dist/resources/instance-identity.js +23 -0
  151. package/dist/resources/instruction-version-record.js +343 -0
  152. package/dist/resources/key-lock.js +3 -3
  153. package/dist/resources/mcp-handler.js +36 -8
  154. package/dist/resources/mcp-oauth-env-guard.js +36 -0
  155. package/dist/resources/mcp-oauth.js +23 -6
  156. package/dist/resources/mcp-tool-arguments.js +4 -6
  157. package/dist/resources/mcp-tools.js +128 -19
  158. package/dist/resources/memory-bootstrap-lib.js +5 -15
  159. package/dist/resources/memory-declared-attributes.js +3 -1
  160. package/dist/resources/memory-deletion-history.js +55 -0
  161. package/dist/resources/memory-durability.js +54 -0
  162. package/dist/resources/memory-embed-hash.js +88 -0
  163. package/dist/resources/memory-embedding-value.js +8 -0
  164. package/dist/resources/memory-host-source.js +27 -5
  165. package/dist/resources/memory-id-guard.js +75 -0
  166. package/dist/resources/memory-redaction.js +236 -0
  167. package/dist/resources/memory-supplied-vector.js +72 -0
  168. package/dist/resources/memory-write-lock.js +310 -0
  169. package/dist/resources/memory-write-response.js +139 -0
  170. package/dist/resources/migrations/data-dir.js +74 -16
  171. package/dist/resources/migrations/dir-safety.js +1 -1
  172. package/dist/resources/migrations/embedding-stamp.js +193 -79
  173. package/dist/resources/migrations/export.js +1 -0
  174. package/dist/resources/migrations/graph-heal.js +18 -25
  175. package/dist/resources/migrations/lock.js +7 -1
  176. package/dist/resources/migrations/snapshot.js +1 -0
  177. package/dist/resources/migrations/source-fields.js +5 -5
  178. package/dist/resources/migrations/synthetic-test-migration.js +14 -11
  179. package/dist/resources/migrations/visibility-backfill.js +29 -29
  180. package/dist/resources/object-body-guard.js +33 -0
  181. package/dist/resources/org-event-created-at.js +133 -0
  182. package/dist/resources/originator-instance.js +39 -7
  183. package/dist/resources/owner-delete-recheck.js +78 -0
  184. package/dist/resources/owner-field-guard.js +39 -5
  185. package/dist/resources/owner-scoped-write-policy.js +212 -0
  186. package/dist/resources/owner-scoped-writes.js +58 -0
  187. package/dist/resources/presence-receipt.js +236 -0
  188. package/dist/resources/promotion-stamp.js +47 -12
  189. package/dist/resources/record-owner-guard.js +74 -26
  190. package/dist/resources/record-types.js +1 -1
  191. package/dist/resources/relay-ops.js +78 -6
  192. package/dist/resources/replay-store.js +96 -19
  193. package/dist/resources/request-target.js +136 -0
  194. package/dist/resources/request-transaction.js +35 -0
  195. package/dist/resources/search-readiness.js +4 -1
  196. package/dist/resources/seed-ids.js +9 -0
  197. package/dist/resources/seed-reservation.js +117 -0
  198. package/dist/resources/semantic-retrieval-core.js +20 -9
  199. package/dist/resources/skill-manifest.js +20 -11
  200. package/dist/resources/skill-subject.js +53 -0
  201. package/dist/resources/skill-version-write.js +432 -0
  202. package/dist/resources/skill-write-fault.js +17 -0
  203. package/dist/resources/skill-write-policy.js +67 -0
  204. package/dist/resources/skill-write.js +67 -7
  205. package/dist/resources/table-helpers.js +10 -7
  206. package/dist/resources/team-directory.js +248 -0
  207. package/dist/resources/tool-descriptors/index.js +69 -8
  208. package/dist/resources/txn-pause-point.js +118 -0
  209. package/dist/resources/usage-recording.js +171 -63
  210. package/dist/resources/write-back.js +218 -0
  211. package/dist/src/engine-version-contract.js +1 -0
  212. package/dist/src/keystore.js +72 -0
  213. package/dist/src/lib/agent-home-fields.js +132 -0
  214. package/dist/src/lib/agent-id-rule.js +46 -0
  215. package/dist/src/lib/agent-key-register.js +80 -0
  216. package/dist/src/lib/atomic-write.js +256 -0
  217. package/dist/src/lib/credential-status-rule.js +78 -0
  218. package/dist/src/lib/expired-by-agent.js +37 -0
  219. package/dist/src/lib/flair-agent-role.js +4 -0
  220. package/dist/src/lib/idp-mapping-rule.js +81 -0
  221. package/dist/src/lib/instance-identity-row.js +20 -0
  222. package/dist/src/lib/mcp-oauth-env-core.js +133 -0
  223. package/dist/src/lib/memory-attributes.js +2 -0
  224. package/dist/src/lib/memory-id-policy.js +46 -0
  225. package/dist/src/lib/principal-status.js +29 -0
  226. package/dist/src/lib/proto-safe-record.js +42 -0
  227. package/dist/src/lib/reembed-server-support.js +66 -0
  228. package/dist/src/lib/scheduler-platform.js +10 -6
  229. package/dist/src/lib/systemd-agent-id.js +38 -0
  230. package/docs/access-control.md +146 -45
  231. package/docs/api-reference.md +46 -11
  232. package/docs/auth.md +6 -12
  233. package/docs/bridges.md +11 -0
  234. package/docs/claude-code.md +34 -4
  235. package/docs/deploying-on-fabric.md +70 -0
  236. package/docs/deployment.md +2 -0
  237. package/docs/embedding-in-a-harper-app.md +1 -1
  238. package/docs/federation.md +33 -2
  239. package/docs/hosted-on-fabric.md +43 -36
  240. package/docs/integrations.md +5 -5
  241. package/docs/mcp-clients.md +5 -2
  242. package/docs/n8n.md +17 -11
  243. package/docs/notes/mcp-agent-auth-consumer.md +12 -4
  244. package/docs/notes/mcp-oauth-model2.md +34 -5
  245. package/docs/quickstart-fabric.md +2 -2
  246. package/docs/quickstart.md +9 -1
  247. package/docs/releasing.md +12 -6
  248. package/docs/rem.md +8 -0
  249. package/docs/secrets-and-keys.md +19 -2
  250. package/docs/standalone-local.md +1 -0
  251. package/docs/supply-chain-policy.md +13 -3
  252. package/docs/upgrade.md +32 -6
  253. package/package.json +10 -5
  254. package/schemas/agent-key-registration.graphql +22 -0
  255. package/schemas/agent.graphql +3 -0
  256. package/schemas/federation.graphql +38 -1
  257. package/schemas/memory.graphql +84 -5
  258. package/schemas/oauth.graphql +19 -0
  259. package/schemas/schema.graphql +2 -0
@@ -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, cimdAllowedHostsFromFlag, claudeAiExcludedNote, } 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) {
@@ -312,6 +312,18 @@ function printEnableSteps(result) {
312
312
  }
313
313
  console.log("");
314
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
+ }
315
327
  export function register(program) {
316
328
  const mcp = program.command("mcp").description("MCP client-credentials agent-auth (RFC 7523 private_key_jwt)");
317
329
  mcp
@@ -322,8 +334,13 @@ export function register(program) {
322
334
  .requiredOption("--agent-id <id>", "Agent id — becomes the client_id (iss/sub claims)")
323
335
  .option("--client-id <url>", "Client ID Metadata Document URL for this agent (defaults to this instance's " +
324
336
  "MCPClientMetadata URL, derived from FLAIR_MCP_ISSUER/FLAIR_PUBLIC_URL)")
325
- .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 " +
326
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)')
327
344
  .option("--resource <url>", "RFC 8707 resource indicator for the token request (defaults to this instance's canonical /mcp URI)")
328
345
  .option("--keys-dir <dir>", "Directory to look for <agentId>.key (else FLAIR_KEY_DIR, ~/.flair/keys, ~/.tps/secrets/flair)")
329
346
  .option("--expires-in <seconds>", `Assertion exp - iat window, seconds (default + hard cap: ${MAX_ASSERTION_LIFETIME_SECONDS})`)
@@ -352,6 +369,27 @@ export function register(program) {
352
369
  }
353
370
  const resource = opts.resource ?? defaultMcpResource();
354
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
+ }
355
393
  let privateKey;
356
394
  try {
357
395
  privateKey = loadEd25519PrivateKeyFromFile(keyPath);
@@ -366,6 +404,7 @@ export function register(program) {
366
404
  tokenEndpoint,
367
405
  privateKey,
368
406
  expiresInSeconds: expiresIn,
407
+ audience,
369
408
  });
370
409
  const form = buildTokenRequestForm({ clientId, assertion, resource });
371
410
  if (opts.json) {
@@ -385,6 +424,7 @@ export function register(program) {
385
424
  privateKey,
386
425
  resource,
387
426
  expiresInSeconds: expiresIn,
427
+ audience,
388
428
  forceRefresh: Boolean(opts.forceRefresh),
389
429
  });
390
430
  if (opts.json) {
@@ -542,10 +582,11 @@ export function register(program) {
542
582
  });
543
583
  mcp
544
584
  .command("enable")
545
- .description("One-command hosted-shape enablement of the OAuth /mcp surface for claude.ai — automates the " +
546
- "docs/notes/mcp-oauth-model2.md checklist. Targets a REMOTE instance with a public HTTPS origin; " +
547
- "refuses honestly against a local-origin instance.")
548
- .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)")
549
590
  .option("--issuer <url>", "Public origin claude.ai will use (else --instance)")
550
591
  .option("--idp-provider <name>", "Upstream IdP provider", "github")
551
592
  .option("--idp-client-id <id>", "IdP OAuth app client id (else prompted interactively)")
@@ -553,31 +594,34 @@ export function register(program) {
553
594
  .option("--idp-subject <value>", "Your expected `sub`/login at the IdP (GitHub: your username; else prompted interactively)")
554
595
  .option("--principal <id>", "Principal (Agent) to map your IdP identity to — personal-shape default", "self")
555
596
  .option("--principal-kind <human|agent>", "Kind for a newly-created principal", "human")
556
- .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)")
557
598
  .option("--secrets-path <path>", "Override the secrets staging file path")
558
599
  .option("--cimd-allowed-hosts <hosts>", "Comma-separated lowercase hostnames to ensure as mcp.clientIdMetadataDocuments.allowedHosts in the config.yaml " +
559
600
  "this command edits on this machine (./config.yaml, else ~/.flair/config.yaml), written unless that file already holds " +
560
601
  "that exact list, then read back, before the restart. " +
561
602
  "Without --dry-run, refused unless a preflight match links the host and pid the target reports, a readable " +
562
603
  "process on this machine, and that file (by realpath); --dry-run skips the match and writes nothing. " +
563
- "Always refused for a *.harperfabric.com instance. " +
604
+ "Always refused with --fabric or a *.harperfabric.com instance. " +
564
605
  "Without it the list is not changed (shipped: claude.ai,claude.com)")
565
- .option("--signing-key-file <path>", "RS256 signing key PEM file (else ~/.flair/mcp-signing-key.pem)")
566
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")
567
607
  .option("--admin-user <name>", "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)")
568
608
  .option("--confirm-secrets-applied", "Confirm the staged secrets are already live on the target instance's environment (skips the interactive confirm)")
569
- .option("--dry-run", "Validate inputs and report the signing key a real run would reuse or generate; write no file and make no 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")
570
612
  .option("--json", "Print machine-readable JSON instead of a human summary")
571
613
  .action(async (opts) => {
572
614
  const instance = opts.instance ?? process.env.FLAIR_URL;
573
615
  if (!instance) {
574
- 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.");
617
+ process.exit(1);
618
+ }
619
+ const targetRefusal = targetOriginRefusal(instance) ?? fabricLoopbackRefusal(instance, Boolean(opts.fabric));
620
+ if (targetRefusal) {
621
+ console.error(`${render.icons.error} ${targetRefusal}`);
575
622
  process.exit(1);
576
623
  }
577
- // Local-origin refusal short-circuits before we ask for anything else —
578
- // never walk the operator through IdP app creation for a connector that
579
- // can never connect.
580
- const localCheck = checkLocalOriginRefusal(instance);
624
+ const localCheck = checkLocalOriginRefusal(opts.issuer ?? instance);
581
625
  if (localCheck.refused) {
582
626
  console.error(`${render.icons.error} ${localCheck.message}`);
583
627
  process.exit(1);
@@ -585,16 +629,12 @@ export function register(program) {
585
629
  // flair#2113: an invalid --cimd-allowed-hosts, or one for a Fabric
586
630
  // instance, is refused here, before anything is asked for. An explicit empty
587
631
  // value is refused too: it used to be dropped as if the flag were absent.
588
- const cimdFlag = cimdAllowedHostsFromFlag(opts.cimdAllowedHosts, instance);
632
+ const cimdFlag = cimdAllowedHostsFromFlag(opts.cimdAllowedHosts, instance, Boolean(opts.fabric));
589
633
  if (cimdFlag.error) {
590
634
  console.error(`${render.icons.error} ${cimdFlag.error}`);
591
635
  process.exit(1);
592
636
  }
593
637
  const dryRun = Boolean(opts.dryRun);
594
- // --instance is ALWAYS remote for this command (local is refused above)
595
- // — isRemoteTarget=true so a missing --admin-pass/FLAIR_ADMIN_PASS never
596
- // silently falls back to THIS machine's local ~/.flair/admin-pass file
597
- // against someone else's instance (see resolveLocalAdminPass's doc comment).
598
638
  const adminPass = dryRun ? (opts.adminPass ?? process.env.FLAIR_ADMIN_PASS ?? "") : resolveLocalAdminPass(opts.adminPass, /* isRemoteTarget */ true);
599
639
  if (!dryRun && !adminPass) {
600
640
  console.error("Error: --admin-pass <pass> is required for a REMOTE target " +
@@ -604,6 +644,28 @@ export function register(program) {
604
644
  "else's Harper. Pass the target's own admin password explicitly.");
605
645
  process.exit(1);
606
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
+ }
607
669
  let idpClientId = opts.idpClientId;
608
670
  let idpClientSecret = opts.idpClientSecret;
609
671
  let idpSubject = opts.idpSubject;
@@ -631,12 +693,12 @@ export function register(program) {
631
693
  principalKind: opts.principalKind,
632
694
  adminUser: resolveAdminUser(opts.adminUser),
633
695
  adminPass,
634
- signingKeyFilePath: opts.signingKeyFile,
635
696
  secretsMechanism,
636
697
  secretsStagingPath: opts.secretsPath,
637
698
  cimdAllowedHosts: cimdFlag.hosts,
638
699
  dryRun,
639
700
  confirmSecretsApplied: Boolean(opts.confirmSecretsApplied),
701
+ fabric: Boolean(opts.fabric),
640
702
  }, { confirmPrompt: dryRun ? undefined : confirmYesNo });
641
703
  if (opts.json) {
642
704
  console.log(render.asJSON(result));
@@ -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
  }
@@ -4,6 +4,7 @@ import { randomUUID } from "node:crypto";
4
4
  import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync } from "node:fs";
5
5
  import { join, resolve, sep } from "node:path";
6
6
  import { resolveHome } from "../lib/home.js";
7
+ import { encodeRecordId } from "../lib/record-id-path.js";
7
8
  let cli;
8
9
  /** Bind the cli-locals this module depends on. */
9
10
  export function bindCli(fns) {
@@ -201,7 +202,7 @@ export function register(program) {
201
202
  tags: tags,
202
203
  createdAt: new Date().toISOString(),
203
204
  };
204
- const memoryPath = `/Memory/${memoryId}`;
205
+ const memoryPath = `/Memory/${encodeRecordId(memoryId)}`;
205
206
  const res = await authFetch(httpUrl, agentId, keyPath, "PUT", memoryPath, body);
206
207
  if (res.ok) {
207
208
  authSuccess = true;
@@ -221,7 +222,7 @@ export function register(program) {
221
222
  tags: tags,
222
223
  createdAt: new Date().toISOString(),
223
224
  };
224
- const memoryPath = `/Memory/${memoryId}`;
225
+ const memoryPath = `/Memory/${encodeRecordId(memoryId)}`;
225
226
  const auth = `Basic ${Buffer.from(`${resolveAdminUser(undefined)}:${adminPass}`).toString("base64")}`;
226
227
  const res = await fetch(`${httpUrl}${memoryPath}`, {
227
228
  method: "PUT",