@tpsdev-ai/flair 0.59.0 → 0.63.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (359) hide show
  1. package/README.md +10 -10
  2. package/SECURITY.md +49 -5
  3. package/config.yaml +23 -12
  4. package/dist/bridges/builtins/mem0.js +63 -28
  5. package/dist/bridges/runtime/execute.js +1 -0
  6. package/dist/bridges/runtime/import-runner.js +12 -0
  7. package/dist/bridges/runtime/load-plugin.js +42 -13
  8. package/dist/bridges/runtime/yaml-loader.js +4 -2
  9. package/dist/bridges/types.js +1 -0
  10. package/dist/build-info.json +3 -3
  11. package/dist/cli.js +1054 -367
  12. package/dist/commands/agent.js +233 -90
  13. package/dist/commands/attention.js +4 -3
  14. package/dist/commands/backup-approval.js +218 -0
  15. package/dist/commands/backup.js +211 -39
  16. package/dist/commands/bootstrap.js +3 -1
  17. package/dist/commands/bridge.js +172 -119
  18. package/dist/commands/deploy.js +71 -8
  19. package/dist/commands/doctor.js +711 -146
  20. package/dist/commands/export.js +57 -23
  21. package/dist/commands/federation.js +787 -82
  22. package/dist/commands/grant.js +5 -6
  23. package/dist/commands/help.js +25 -0
  24. package/dist/commands/hook.js +155 -2
  25. package/dist/commands/idp.js +27 -19
  26. package/dist/commands/import.js +136 -20
  27. package/dist/commands/init.js +469 -200
  28. package/dist/commands/integrity.js +387 -0
  29. package/dist/commands/keys.js +247 -58
  30. package/dist/commands/mcp.js +108 -52
  31. package/dist/commands/memory.js +203 -35
  32. package/dist/commands/migrate-harness-memory.js +3 -2
  33. package/dist/commands/orgevent.js +51 -47
  34. package/dist/commands/presence.js +4 -3
  35. package/dist/commands/principal.js +428 -62
  36. package/dist/commands/quality.js +13 -1
  37. package/dist/commands/reembed.js +141 -17
  38. package/dist/commands/relationship.js +2 -1
  39. package/dist/commands/rem.js +537 -80
  40. package/dist/commands/restore.js +413 -65
  41. package/dist/commands/search.js +6 -4
  42. package/dist/commands/service.js +235 -40
  43. package/dist/commands/soul.js +4 -9
  44. package/dist/commands/status.js +94 -38
  45. package/dist/commands/test.js +7 -3
  46. package/dist/commands/upgrade.js +77 -23
  47. package/dist/commands/workspace.js +13 -11
  48. package/dist/component-env.js +31 -41
  49. package/dist/deploy.js +136 -4
  50. package/dist/doctor-client.js +534 -92
  51. package/dist/engine-version-contract.js +1 -0
  52. package/dist/engine-version.js +23 -3
  53. package/dist/fabric-upgrade.js +12 -2
  54. package/dist/federation/presence-send.js +139 -0
  55. package/dist/federation-verify.js +273 -180
  56. package/dist/hook-install.js +670 -6
  57. package/dist/install/clients.js +171 -35
  58. package/dist/keystore.js +72 -0
  59. package/dist/lib/action-recall-runtime.js +328 -0
  60. package/dist/lib/agent-home-fields.js +132 -0
  61. package/dist/lib/agent-home.js +427 -0
  62. package/dist/lib/agent-id-rule.js +88 -0
  63. package/dist/lib/agent-roster.js +33 -0
  64. package/dist/lib/atomic-write.js +1 -1
  65. package/dist/lib/auth-resolve.js +1069 -60
  66. package/dist/lib/backup-approval-store.js +612 -0
  67. package/dist/lib/backup-artifact.js +343 -0
  68. package/dist/lib/capture-runtime.js +124 -0
  69. package/dist/lib/config-critical-section.js +212 -25
  70. package/dist/lib/connect-phase.js +33 -0
  71. package/dist/lib/credential-status-rule.js +78 -0
  72. package/dist/lib/daemon-liveness.js +43 -11
  73. package/dist/lib/doctor-run.js +75 -37
  74. package/dist/lib/durability-copy.js +10 -0
  75. package/dist/lib/embedding-space-doctor.js +75 -0
  76. package/dist/lib/federation-pair-access.js +4 -0
  77. package/dist/lib/federation-retry-queue.js +283 -0
  78. package/dist/lib/federation-retry-row.js +101 -0
  79. package/dist/lib/flair-agent-role.js +4 -0
  80. package/dist/lib/hub-url.js +12 -0
  81. package/dist/lib/init-admin-pass.js +88 -12
  82. package/dist/lib/init-listener-environ.js +1 -2
  83. package/dist/lib/init-occupied-listener.js +15 -111
  84. package/dist/lib/init-spawn-attribution.js +73 -0
  85. package/dist/lib/init-tcp-probe.js +33 -0
  86. package/dist/lib/instance-identity-row.js +20 -0
  87. package/dist/lib/instruction-event-contract.js +17 -0
  88. package/dist/lib/instruction-event-doctor.js +102 -0
  89. package/dist/lib/launchd-management.js +38 -3
  90. package/dist/lib/listener-table.js +268 -0
  91. package/dist/lib/local-delete-instance.js +27 -0
  92. package/dist/lib/local-instance-pair.js +256 -0
  93. package/dist/lib/mcp-enable.js +1182 -341
  94. package/dist/lib/mcp-oauth-env-core.js +133 -0
  95. package/dist/lib/mcp-oauth-env.js +125 -0
  96. package/dist/lib/mcp-spec.js +17 -1
  97. package/dist/lib/memory-attributes.js +4 -0
  98. package/dist/lib/memory-id-policy.js +46 -0
  99. package/dist/lib/memory-integrity.js +309 -0
  100. package/dist/lib/memory-provider-timeout.js +33 -0
  101. package/dist/lib/memory-purge-response.js +20 -0
  102. package/dist/lib/mqtt-config.js +132 -0
  103. package/dist/lib/mqtt-listener-doctor.js +104 -0
  104. package/dist/lib/open-live-row.js +20 -0
  105. package/dist/lib/ops-table-count.js +25 -0
  106. package/dist/lib/ops-url.js +52 -0
  107. package/dist/lib/owned-pins.js +67 -10
  108. package/dist/lib/peer-status.js +27 -0
  109. package/dist/lib/principal-status.js +29 -0
  110. package/dist/lib/process-start-time.js +76 -12
  111. package/dist/lib/promotion-content-hash.js +20 -0
  112. package/dist/lib/proto-safe-record.js +42 -0
  113. package/dist/lib/record-id-path.js +25 -0
  114. package/dist/lib/reembed-server-support.js +66 -0
  115. package/dist/lib/restore-archive.js +760 -0
  116. package/dist/lib/restore-verify.js +104 -0
  117. package/dist/lib/scheduler-platform.js +10 -6
  118. package/dist/lib/secret-keys.js +25 -0
  119. package/dist/lib/secrets-push.js +50 -22
  120. package/dist/lib/skill-assignment-preflight.js +159 -0
  121. package/dist/lib/skill-seed-pending.js +24 -0
  122. package/dist/lib/skill-seed.js +448 -0
  123. package/dist/lib/skill-tombstone-doctor.js +133 -0
  124. package/dist/lib/soul-scope-fields.js +26 -0
  125. package/dist/lib/stop-start-recovery.js +54 -0
  126. package/dist/lib/uninstall-purge.js +266 -11
  127. package/dist/lib/upgrade-prior-liveness.js +2 -1
  128. package/dist/lib/using-flair-skill.js +87 -0
  129. package/dist/mcp-client-assertion.js +114 -14
  130. package/dist/memory-id-checkpoint.js +347 -0
  131. package/dist/memory-node-compare.js +207 -0
  132. package/dist/mqtt-off-deploy.js +550 -0
  133. package/dist/packages/flair-mcp/src/secret-redaction.js +113 -0
  134. package/dist/rem/promote-policy.js +3 -3
  135. package/dist/rem/restore.js +303 -26
  136. package/dist/rem/runner.js +317 -96
  137. package/dist/rem/scheduler.js +21 -4
  138. package/dist/resources/A2AAdapter.js +131 -178
  139. package/dist/resources/AdminMemory.js +2 -0
  140. package/dist/resources/AdminMemoryCandidates.js +116 -0
  141. package/dist/resources/Agent.js +463 -33
  142. package/dist/resources/AgentCard.js +4 -0
  143. package/dist/resources/AgentKeyRegister.js +248 -0
  144. package/dist/resources/AgentKeyRegistration.js +28 -0
  145. package/dist/resources/AgentReadPosition.js +7 -0
  146. package/dist/resources/AgentSeed.js +238 -107
  147. package/dist/resources/AutoPromoteCandidates.js +413 -78
  148. package/dist/resources/Credential.js +183 -10
  149. package/dist/resources/Federation.js +915 -145
  150. package/dist/resources/FederationRetry.js +140 -0
  151. package/dist/resources/InstructionVersion.js +220 -0
  152. package/dist/resources/Integration.js +300 -25
  153. package/dist/resources/MCPClientMetadata.js +6 -3
  154. package/dist/resources/Memory.js +3300 -758
  155. package/dist/resources/MemoryArchive.js +171 -53
  156. package/dist/resources/MemoryBootstrap.js +122 -61
  157. package/dist/resources/MemoryCandidate.js +37 -3
  158. package/dist/resources/MemoryConsolidate.js +2 -2
  159. package/dist/resources/MemoryDedupStats.js +30 -1
  160. package/dist/resources/MemoryFeed.js +545 -50
  161. package/dist/resources/MemoryGrant.js +21 -1
  162. package/dist/resources/MemoryMaintenance.js +368 -46
  163. package/dist/resources/MemoryPurge.js +348 -0
  164. package/dist/resources/MemoryReflect.js +71 -12
  165. package/dist/resources/MemoryReindex.js +111 -17
  166. package/dist/resources/Message.js +16 -5
  167. package/dist/resources/OAuth.js +342 -48
  168. package/dist/resources/OAuthClient.js +1 -1
  169. package/dist/resources/OrgEvent.js +405 -19
  170. package/dist/resources/OrgEventCatchup.js +7 -0
  171. package/dist/resources/OrgEventMaintenance.js +48 -10
  172. package/dist/resources/PairingToken.js +1 -1
  173. package/dist/resources/Presence.js +166 -51
  174. package/dist/resources/PromoteMemoryCandidate.js +24 -7
  175. package/dist/resources/RecordUsage.js +2 -4
  176. package/dist/resources/Relationship.js +23 -0
  177. package/dist/resources/SemanticSearch.js +63 -32
  178. package/dist/resources/Soul.js +191 -76
  179. package/dist/resources/SoulFeed.js +2 -1
  180. package/dist/resources/TeamDirectory.js +35 -0
  181. package/dist/resources/WorkspaceLatest.js +4 -0
  182. package/dist/resources/WorkspaceState.js +21 -1
  183. package/dist/resources/XAA.js +207 -63
  184. package/dist/resources/a2a-stream.js +313 -0
  185. package/dist/resources/a2a-url.js +4 -5
  186. package/dist/resources/agent-admin.js +10 -1
  187. package/dist/resources/agent-auth.js +138 -83
  188. package/dist/resources/agent-read-position-lib.js +4 -1
  189. package/dist/resources/agent-status-guard.js +9 -7
  190. package/dist/resources/auth-middleware.js +534 -171
  191. package/dist/resources/authority-field-guard.js +9 -11
  192. package/dist/resources/auto-promote-lib.js +8 -5
  193. package/dist/resources/basic-auth-header.js +21 -0
  194. package/dist/resources/bm25-index-service.js +4 -5
  195. package/dist/resources/dedup-cluster.js +6 -1
  196. package/dist/resources/ed25519-auth.js +1 -1
  197. package/dist/resources/embedding-space-guard.js +366 -72
  198. package/dist/resources/embeddings-provider.js +25 -0
  199. package/dist/resources/engine-version-stamp-boot.js +53 -0
  200. package/dist/resources/federation-classify.js +161 -0
  201. package/dist/resources/federation-crypto.js +5 -5
  202. package/dist/resources/federation-retry-lib.js +60 -0
  203. package/dist/resources/grant-visibility.js +135 -0
  204. package/dist/resources/harper-routing.js +83 -0
  205. package/dist/resources/health.js +163 -22
  206. package/dist/resources/host-pointer/registry.js +29 -0
  207. package/dist/resources/host-pointer-adapter.js +1 -0
  208. package/dist/resources/host-source-citation.js +49 -0
  209. package/dist/resources/host-source-visibility.js +7 -6
  210. package/dist/resources/in-process.js +24 -22
  211. package/dist/resources/instance-create-lock.js +17 -0
  212. package/dist/resources/instance-identity.js +23 -0
  213. package/dist/resources/instruction-version-record.js +587 -0
  214. package/dist/resources/internal-authority.js +13 -0
  215. package/dist/resources/key-lock.js +3 -3
  216. package/dist/resources/mcp-handler.js +141 -19
  217. package/dist/resources/mcp-oauth-env-guard.js +36 -0
  218. package/dist/resources/mcp-oauth-flag.js +12 -14
  219. package/dist/resources/mcp-oauth.js +450 -56
  220. package/dist/resources/mcp-tool-arguments.js +4 -6
  221. package/dist/resources/mcp-tools.js +187 -40
  222. package/dist/resources/memory-bootstrap-lib.js +5 -15
  223. package/dist/resources/memory-declared-attributes.js +4 -1
  224. package/dist/resources/memory-deletion-history.js +55 -0
  225. package/dist/resources/memory-durability.js +54 -0
  226. package/dist/resources/memory-embed-hash.js +144 -0
  227. package/dist/resources/memory-embedding-value.js +8 -0
  228. package/dist/resources/memory-host-source.js +32 -7
  229. package/dist/resources/memory-id-guard.js +75 -0
  230. package/dist/resources/memory-redaction.js +236 -0
  231. package/dist/resources/memory-reflect-lib.js +1 -1
  232. package/dist/resources/memory-supplied-vector.js +72 -0
  233. package/dist/resources/memory-write-lock.js +489 -0
  234. package/dist/resources/memory-write-response.js +139 -0
  235. package/dist/resources/memory-write-transaction.js +243 -0
  236. package/dist/resources/migration-boot.js +17 -12
  237. package/dist/resources/migrations/boot-progress.js +25 -0
  238. package/dist/resources/migrations/data-dir.js +90 -19
  239. package/dist/resources/migrations/dir-safety.js +61 -3
  240. package/dist/resources/migrations/embedding-stamp.js +462 -82
  241. package/dist/resources/migrations/export.js +1 -0
  242. package/dist/resources/migrations/graph-heal.js +27 -27
  243. package/dist/resources/migrations/ledger.js +5 -2
  244. package/dist/resources/migrations/lock.js +870 -77
  245. package/dist/resources/migrations/progress.js +71 -10
  246. package/dist/resources/migrations/runner.js +212 -18
  247. package/dist/resources/migrations/snapshot.js +1 -0
  248. package/dist/resources/migrations/source-fields.js +5 -5
  249. package/dist/resources/migrations/state.js +36 -1
  250. package/dist/resources/migrations/status.js +2 -13
  251. package/dist/resources/migrations/synthetic-test-migration.js +81 -12
  252. package/dist/resources/migrations/types.js +26 -1
  253. package/dist/resources/migrations/visibility-backfill.js +113 -72
  254. package/dist/resources/oauth-discovery.js +0 -5
  255. package/dist/resources/object-body-guard.js +40 -0
  256. package/dist/resources/org-event-created-at.js +133 -0
  257. package/dist/resources/org-event-reserved.js +92 -0
  258. package/dist/resources/org-event-write-fault.js +19 -0
  259. package/dist/resources/originator-instance.js +39 -7
  260. package/dist/resources/owner-delete-recheck.js +78 -0
  261. package/dist/resources/owner-field-guard.js +39 -5
  262. package/dist/resources/owner-scoped-write-policy.js +256 -0
  263. package/dist/resources/owner-scoped-writes.js +89 -0
  264. package/dist/resources/path-id-rewrite.js +76 -0
  265. package/dist/resources/presence-internal.js +5 -5
  266. package/dist/resources/presence-receipt.js +236 -0
  267. package/dist/resources/promotion-binding.js +43 -0
  268. package/dist/resources/promotion-stamp.js +143 -17
  269. package/dist/resources/protocol-context.js +189 -0
  270. package/dist/resources/record-owner-guard.js +74 -26
  271. package/dist/resources/record-type-kit.js +2 -4
  272. package/dist/resources/record-types.js +1 -1
  273. package/dist/resources/relay-ops.js +78 -6
  274. package/dist/resources/replay-store.js +96 -19
  275. package/dist/resources/request-target.js +163 -0
  276. package/dist/resources/request-transaction.js +46 -1
  277. package/dist/resources/search-readiness.js +4 -1
  278. package/dist/resources/seed-ids.js +9 -0
  279. package/dist/resources/seed-reservation.js +116 -0
  280. package/dist/resources/semantic-retrieval-core.js +27 -15
  281. package/dist/resources/server-row-validation.js +71 -0
  282. package/dist/resources/skill-manifest.js +24 -14
  283. package/dist/resources/skill-subject.js +53 -0
  284. package/dist/resources/skill-version-write.js +789 -0
  285. package/dist/resources/skill-write-fault.js +20 -0
  286. package/dist/resources/skill-write-policy.js +68 -0
  287. package/dist/resources/skill-write.js +67 -7
  288. package/dist/resources/soul-write-policy.js +26 -7
  289. package/dist/resources/table-helpers.js +10 -7
  290. package/dist/resources/table-subscription-policy.js +518 -85
  291. package/dist/resources/table-subscriptions.js +20 -7
  292. package/dist/resources/team-directory.js +248 -0
  293. package/dist/resources/tool-descriptors/index.js +69 -8
  294. package/dist/resources/txn-pause-point.js +235 -0
  295. package/dist/resources/usage-recording.js +186 -70
  296. package/dist/resources/write-back.js +383 -0
  297. package/dist/resources/write-journal-context.js +5 -0
  298. package/dist/resources/write-journal.js +289 -0
  299. package/dist/src/engine-version-contract.js +1 -0
  300. package/dist/src/keystore.js +72 -0
  301. package/dist/src/lib/agent-home-fields.js +132 -0
  302. package/dist/src/lib/agent-id-rule.js +88 -0
  303. package/dist/src/lib/agent-key-register.js +80 -0
  304. package/dist/src/lib/atomic-write.js +256 -0
  305. package/dist/src/lib/credential-status-rule.js +78 -0
  306. package/dist/src/lib/expired-by-agent.js +37 -0
  307. package/dist/src/lib/federation-retry-row.js +101 -0
  308. package/dist/src/lib/flair-agent-role.js +4 -0
  309. package/dist/src/lib/idp-mapping-rule.js +81 -0
  310. package/dist/src/lib/instance-identity-row.js +20 -0
  311. package/dist/src/lib/instruction-event-contract.js +17 -0
  312. package/dist/src/lib/mcp-oauth-env-core.js +133 -0
  313. package/dist/src/lib/memory-attributes.js +4 -0
  314. package/dist/src/lib/memory-id-policy.js +46 -0
  315. package/dist/src/lib/open-live-row.js +20 -0
  316. package/dist/src/lib/principal-status.js +29 -0
  317. package/dist/src/lib/proto-safe-record.js +42 -0
  318. package/dist/src/lib/reembed-server-support.js +66 -0
  319. package/dist/src/lib/scheduler-platform.js +10 -6
  320. package/dist/src/lib/soul-scope-fields.js +26 -0
  321. package/dist/src/lib/systemd-agent-id.js +38 -0
  322. package/dist/src/rem/promote-policy.js +3 -3
  323. package/dist/src/rem/scheduler.js +21 -4
  324. package/docs/access-control.md +164 -54
  325. package/docs/api-reference.md +165 -32
  326. package/docs/auth.md +46 -30
  327. package/docs/bridges.md +11 -0
  328. package/docs/claude-code.md +37 -7
  329. package/docs/deploying-on-fabric.md +178 -0
  330. package/docs/deployment.md +19 -0
  331. package/docs/embedding-in-a-harper-app.md +17 -15
  332. package/docs/entity-vocabulary.md +3 -6
  333. package/docs/federation.md +61 -3
  334. package/docs/hosted-on-fabric.md +43 -36
  335. package/docs/integrations.md +14 -14
  336. package/docs/mcp-clients.md +12 -7
  337. package/docs/n8n.md +17 -11
  338. package/docs/notes/mcp-agent-auth-consumer.md +16 -13
  339. package/docs/notes/mcp-oauth-model2.md +40 -11
  340. package/docs/openclaw.md +1 -1
  341. package/docs/quickstart-fabric.md +4 -4
  342. package/docs/quickstart.md +12 -4
  343. package/docs/releasing.md +25 -19
  344. package/docs/rem.md +32 -3
  345. package/docs/secrets-and-keys.md +21 -4
  346. package/docs/standalone-local.md +30 -2
  347. package/docs/supply-chain-policy.md +34 -16
  348. package/docs/the-team.md +2 -2
  349. package/docs/upgrade.md +46 -6
  350. package/package.json +24 -12
  351. package/schemas/agent-key-registration.graphql +22 -0
  352. package/schemas/agent.graphql +6 -3
  353. package/schemas/federation.graphql +41 -1
  354. package/schemas/memory.graphql +91 -7
  355. package/schemas/oauth.graphql +19 -0
  356. package/schemas/schema.graphql +2 -0
  357. package/templates/bin/flair-rem-nightly.sh.tmpl +7 -1
  358. package/templates/launchd/start-flair-with-admin-pass.sh +188 -10
  359. package/dist/resources/soul-adk-guard.js +0 -68
@@ -1,7 +1,15 @@
1
1
  import nacl from "tweetnacl";
2
2
  import { existsSync, mkdirSync, writeFileSync, readFileSync, chmodSync } from "node:fs";
3
3
  import * as render from "../render.js";
4
- import { defaultKeysDir, resolveLocalAdminPass, resolveAdminUser, } from "../lib/auth-resolve.js";
4
+ import { defaultKeysDir, resolveLocalAdminPass, resolveAdminUser, addAdminPassOptions, } from "../lib/auth-resolve.js";
5
+ import { resolveOpsUrl } from "../lib/mcp-enable.js";
6
+ import { writeConfirmed } from "../lib/instance-identity-row.js";
7
+ import { agentHomeEndpoint, planAgentHomeWrite, readStoredAgentHome, resolveTargetInstanceId, AGENT_HOME_IMMUTABLE_ERROR, AGENT_PRINCIPAL_WRITE_BACK_FIELD, AGENT_PRINCIPAL_WRITE_BACK_NO_ROW_ERROR } from "../lib/agent-home.js";
8
+ import { fetchErrorLabel, redactUrl } from "./federation.js";
9
+ import { encodeRecordId } from "../lib/record-id-path.js";
10
+ import { invalidAgentIdMessage, isValidAgentId } from "../lib/agent-id-rule.js";
11
+ import { isPrincipalDeactivated } from "../lib/principal-status.js";
12
+ import { linkPrincipalMapping, unlinkPrincipalMapping, listPrincipalMappings, } from "../lib/mcp-enable.js";
5
13
  let cli;
6
14
  /** Bind shared CLI helpers. cli.ts calls this immediately before register(program). */
7
15
  export function bindCli(fns) {
@@ -13,6 +21,171 @@ const privKeyPath = (agentId, keysDir) => cli.privKeyPath(agentId, keysDir);
13
21
  const pubKeyPath = (agentId, keysDir) => cli.pubKeyPath(agentId, keysDir);
14
22
  const relativeTime = (iso) => cli.relativeTime(iso);
15
23
  const resolveOpsPort = (opts) => cli.resolveOpsPort(opts);
24
+ const resolveAgentHomeTarget = (opts) => cli.resolveAgentHomeTarget(opts);
25
+ const PRINCIPAL_OPS_TIMEOUT_MS = 10_000;
26
+ /** Only a principal that exists, a confirmed update for it, and a read-back of the requested status are success. */
27
+ async function setPrincipalStatus(id, status, opts) {
28
+ // Match `mcp enable`: --instance wins, then FLAIR_URL. Neither of the older
29
+ // FLAIR_TARGET / FLAIR_OPS_TARGET variables selects this admin destination.
30
+ const instance = opts.instance ?? process.env.FLAIR_URL;
31
+ if (opts.instance !== undefined && !opts.instance.trim()) {
32
+ console.error("Error: --instance is empty. Pass the target instance URL or omit the flag for a local operation.");
33
+ process.exit(1);
34
+ }
35
+ const remote = Boolean(instance);
36
+ const targetText = instance && !instance.includes("://") ? `https://${instance}` : (instance ?? "");
37
+ let opsUrl;
38
+ try {
39
+ if (remote) {
40
+ const target = new URL(targetText);
41
+ if (!(["http:", "https:"].includes(target.protocol) && target.hostname && !target.username && !target.password)) {
42
+ throw new Error("invalid target");
43
+ }
44
+ // mcp enable resolves the served instance to the ops API on its host.
45
+ // Parse the result too: resolveOpsUrl preserves a malformed input as a
46
+ // string for its own caller's error path.
47
+ opsUrl = resolveOpsUrl(instance);
48
+ const ops = new URL(opsUrl);
49
+ if (!["http:", "https:"].includes(ops.protocol) || !ops.hostname)
50
+ throw new Error("invalid ops URL");
51
+ }
52
+ else {
53
+ opsUrl = resolveOpsUrl(resolveOpsPort(opts));
54
+ }
55
+ }
56
+ catch {
57
+ // Show only a redacted http(s) URL: other schemes can keep credential-looking text in an opaque path.
58
+ let shown = "<unparseable URL>";
59
+ try {
60
+ if (["http:", "https:"].includes(new URL(targetText).protocol))
61
+ shown = redactUrl(targetText);
62
+ }
63
+ catch { /* placeholder */ }
64
+ console.error(`Error: invalid --instance target ${shown}. Pass a valid http(s) Flair instance URL and check its operations API address.`);
65
+ process.exit(1);
66
+ }
67
+ let adminPass;
68
+ if (remote) {
69
+ // A local env/file credential must never silently cross to another host.
70
+ adminPass = resolveLocalAdminPass(opts.adminPass, true);
71
+ if (!adminPass) {
72
+ console.error("Error: --admin-pass <pass> is required for a remote --instance. Pass that instance's own admin password explicitly; FLAIR_ADMIN_PASS and ~/.flair/admin-pass are local credentials.");
73
+ process.exit(1);
74
+ }
75
+ }
76
+ else {
77
+ adminPass = opts.adminPass ?? process.env.FLAIR_ADMIN_PASS;
78
+ if (!adminPass) {
79
+ console.error("Error: --admin-pass or FLAIR_ADMIN_PASS required for a local principal update.");
80
+ process.exit(1);
81
+ }
82
+ }
83
+ const auth = `Basic ${Buffer.from(`${resolveAdminUser(opts.adminUser)}:${adminPass}`).toString("base64")}`;
84
+ const safeUrl = redactUrl(opsUrl);
85
+ const action = status === "active" ? "enable" : "disable";
86
+ const remedy = `Check --instance, the target's operations API, and --admin-pass/--admin-user; then check the principal's status on that instance before retrying.`;
87
+ const post = async (body, stage) => {
88
+ try {
89
+ return await fetch(opsUrl, {
90
+ method: "POST",
91
+ headers: { "Content-Type": "application/json", Authorization: auth },
92
+ body: JSON.stringify(body),
93
+ redirect: "manual",
94
+ signal: AbortSignal.timeout(PRINCIPAL_OPS_TIMEOUT_MS),
95
+ });
96
+ }
97
+ catch (err) {
98
+ console.error(`Error: could not ${stage} principal at ${safeUrl} (${fetchErrorLabel(err)}). ${remedy}`);
99
+ process.exit(1);
100
+ }
101
+ };
102
+ const checkResponse = (res, stage) => {
103
+ if (res.status >= 300 && res.status < 400) {
104
+ console.error(`Error: ${safeUrl} redirected the ${stage}; refused to forward the admin credential. ${remedy}`);
105
+ process.exit(1);
106
+ }
107
+ if (!res.ok) {
108
+ console.error(`Error: ${safeUrl} refused the ${stage} (HTTP ${res.status}). ${remedy}`);
109
+ process.exit(1);
110
+ }
111
+ };
112
+ // Transport/HTTP failures exit in post/checkResponse; invalid successful
113
+ // responses are "unreadable".
114
+ const readPrincipal = async (stage) => {
115
+ const res = await post({
116
+ operation: "search_by_value", database: "flair", table: "Agent",
117
+ search_attribute: "id", search_type: "equals", search_value: id,
118
+ get_attributes: ["id", "status"],
119
+ }, stage);
120
+ checkResponse(res, stage);
121
+ let rows;
122
+ try {
123
+ rows = await res.json();
124
+ }
125
+ catch {
126
+ return { kind: "unreadable" };
127
+ }
128
+ if (!Array.isArray(rows))
129
+ return { kind: "unreadable" };
130
+ if (rows.length === 0)
131
+ return { kind: "absent" };
132
+ if (rows.length !== 1)
133
+ return { kind: "unreadable" };
134
+ const row = rows[0];
135
+ if (row?.id !== id)
136
+ return { kind: "unreadable" };
137
+ const rawStatus = row.status;
138
+ if (rawStatus === "active" || rawStatus === "deactivated") {
139
+ return { kind: "found", status: rawStatus };
140
+ }
141
+ if (rawStatus === undefined || rawStatus === null)
142
+ return { kind: "found", status: null };
143
+ return { kind: "unreadable" };
144
+ };
145
+ // Read the principal BEFORE the update. Harper answers an update for an id
146
+ // with no row, so existence has to come from a read, not from the update's
147
+ // status. An unreadable read is refused separately — never treated as absent.
148
+ const before = await readPrincipal(`${action} lookup`);
149
+ if (before.kind === "absent") {
150
+ console.error(`Error: no principal ${id} at ${safeUrl} — nothing to ${action}. Check the id and the target, then create it with \`flair principal add\` or name an existing principal.`);
151
+ process.exit(1);
152
+ }
153
+ if (before.kind === "unreadable") {
154
+ console.error(`Error: ${safeUrl} could not read principal ${id} before the ${action}; the read did not return the single requested record, so no change was made. ${remedy}`);
155
+ process.exit(1);
156
+ }
157
+ const updated = await post({
158
+ operation: "update", database: "flair", table: "Agent",
159
+ records: [{ id, status, updatedAt: new Date().toISOString() }],
160
+ }, `${action} update`);
161
+ checkResponse(updated, "update");
162
+ let updateBody;
163
+ try {
164
+ updateBody = await updated.json();
165
+ }
166
+ catch {
167
+ updateBody = null;
168
+ }
169
+ if (!writeConfirmed(updateBody, "update_hashes", id)) {
170
+ console.error(`Error: ${safeUrl} did not confirm the update for principal '${id}'. Check that the principal exists on the target and verify its status before retrying.`);
171
+ process.exit(1);
172
+ }
173
+ const after = await readPrincipal(`${action} read-back`);
174
+ const storedStatus = after.kind === "found" ? after.status : "no single record";
175
+ if (storedStatus !== status) {
176
+ console.error(`Error: ${safeUrl} did not confirm principal '${id}' is ${status}; the stored status is not ${status}. Check the principal's status on that instance.`);
177
+ process.exit(1);
178
+ }
179
+ console.log(`✅ Principal '${id}' ${status === "active" ? "activated" : "deactivated"} (stored status: ${storedStatus})`);
180
+ }
181
+ /** Both state verbs accept the same target and admin credentials. */
182
+ function registerPrincipalStatusCommand(command, status) {
183
+ addAdminPassOptions(command, "Admin password; required explicitly for a remote --instance")
184
+ .option("--admin-user <name>", "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)")
185
+ .option("--ops-port <port>", "Harper operations API port (local target)")
186
+ .option("--instance <url>", "Remote Flair instance (else FLAIR_URL); its ops API is derived as in mcp enable")
187
+ .action(async (id, opts) => setPrincipalStatus(id, status, opts));
188
+ }
16
189
  // ─── flair principal ─────────────────────────────────────────────────────────
17
190
  // 1.0 identity management. The Principal model extends Agent — this is the
18
191
  // preferred CLI surface for managing identities going forward.
@@ -36,7 +209,7 @@ export function agentRecordIsAdmin(record) {
36
209
  /** Register the `flair principal` command group (flair#1632). */
37
210
  export function register(program) {
38
211
  const principal = program.command("principal").description("Manage principals (humans and agents)");
39
- principal
212
+ addAdminPassOptions(principal
40
213
  .command("add <id>")
41
214
  .description("Create a new principal")
42
215
  .option("--kind <kind>", "Principal kind: human or agent", "agent")
@@ -44,13 +217,38 @@ export function register(program) {
44
217
  .option("--admin", "Grant admin privileges")
45
218
  .option("--trust <tier>", "Default trust tier: endorsed, corroborated, or unverified")
46
219
  .option("--runtime <runtime>", "Runtime: openclaw, claude-code, headless, external")
47
- .option("--port <port>", "Harper HTTP port")
48
- .option("--admin-pass <pass>", "Admin password for registration")
220
+ .option("--port <port>", "Harper HTTP port"), "Admin password for registration")
49
221
  .option("--admin-user <name>", "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)")
50
222
  .option("--keys-dir <dir>", "Directory for Ed25519 keys")
51
223
  .option("--ops-port <port>", "Harper operations API port")
52
224
  .action(async (id, opts) => {
53
- const opsPort = resolveOpsPort(opts);
225
+ // flair#2359 — the ONE shared agent-ID rule, before any key file is
226
+ // written or any insert is attempted. The upsert below writes the row
227
+ // through the operations API, so the Agent resource's own guard never
228
+ // runs on it.
229
+ if (!isValidAgentId(id)) {
230
+ console.error(`Error: ${invalidAgentIdMessage(id)}`);
231
+ process.exit(1);
232
+ }
233
+ // flair#2474 — pair the ops port and the HTTP port. `principal add` reads
234
+ // the stored home through the ops API and sends its guarded write-back to
235
+ // the Agent RESOURCE on the HTTP port; resolving the two INDEPENDENTLY
236
+ // would let `--ops-port` name one instance and `--port` another, so the
237
+ // home is read from the first and written to the second. A target the
238
+ // configured pair contradicts, or one with a single port named and no
239
+ // complete configured pair, is refused by name (`ambiguous_instance_target`)
240
+ // BEFORE any key file is written or any insert attempted. Two named ports
241
+ // that match neither side of the configured pair are used as given, without
242
+ // verification (see resolveAgentHomeTarget).
243
+ let target;
244
+ try {
245
+ target = resolveAgentHomeTarget(opts);
246
+ }
247
+ catch (err) {
248
+ console.error(`Error: ${err.message}`);
249
+ process.exit(1);
250
+ }
251
+ const opsPort = target.opsPort;
54
252
  const keysDir = opts.keysDir ?? defaultKeysDir();
55
253
  const adminUser = resolveAdminUser(opts.adminUser);
56
254
  const kind = opts.kind ?? "agent";
@@ -58,9 +256,6 @@ export function register(program) {
58
256
  const isAdmin = opts.admin ?? false;
59
257
  const trustTier = opts.trust ?? (isAdmin ? "endorsed" : "unverified");
60
258
  const runtime = opts.runtime;
61
- // #590 — same local-only fallback as `agent add`: FLAIR_ADMIN_PASS env, then
62
- // the secure ~/.flair/admin-pass file (mode 0600). `principal add` has no
63
- // --target/--ops-target (always localhost), so the fallback always applies.
64
259
  let adminPass;
65
260
  try {
66
261
  adminPass = resolveLocalAdminPass(opts.adminPass);
@@ -96,6 +291,30 @@ export function register(program) {
96
291
  }
97
292
  // Insert via operations API with Principal fields
98
293
  const auth = `Basic ${Buffer.from(`${adminUser}:${adminPass}`).toString("base64")}`;
294
+ // flair#2433 / flair#2473 — the HOME ASSIGNMENT on a create is THIS
295
+ // instance's federation id, resolved through the one shared rule, and it
296
+ // rides on the `insert` itself — so a row created at write time carries it,
297
+ // even one deleted since this read. That assignment is CREATE-ONLY: an
298
+ // insert over a row that already exists is SKIPPED by Harper, so this insert
299
+ // does not replace a stored home (other fields of an existing row may still
300
+ // be updated by the write-back below). A row with a home that DIFFERS from
301
+ // this instance's is refused with `originator_instance_immutable` when this
302
+ // command's reads or the resource's reads see it; an insert the operations
303
+ // API reports neither inserted nor skipped is a failure, not a success. A
304
+ // failed read is UNREADABLE, not "no home", and refused.
305
+ const opsUrl = `http://127.0.0.1:${opsPort}/`;
306
+ // The instance's HTTP port, where the Agent RESOURCE lives. The write-back
307
+ // goes to the resource (a guarded REST PATCH), not the raw ops API, so it
308
+ // runs in an owned transaction (flair#2473). `target` pairs this with the
309
+ // ops port above (flair#2474).
310
+ const httpUrl = `http://127.0.0.1:${target.httpPort}/`;
311
+ const home = await resolveTargetInstanceId(agentHomeEndpoint(opsPort, adminUser, adminPass));
312
+ const existingHome = await readStoredAgentHome({ opsUrl, authHeader: auth, id });
313
+ const homePlan = planAgentHomeWrite(existingHome, home, id);
314
+ if (homePlan.refuse) {
315
+ console.error(`Error: ${homePlan.message}`);
316
+ process.exit(1);
317
+ }
99
318
  const record = {
100
319
  id,
101
320
  name,
@@ -115,16 +334,71 @@ export function register(program) {
115
334
  createdAt: new Date().toISOString(),
116
335
  updatedAt: new Date().toISOString(),
117
336
  };
118
- const res = await fetch(`http://127.0.0.1:${opsPort}/`, {
337
+ // 1) Create-only. The home rides on THIS insert (so a row the insert
338
+ // creates at write time carries it); over an existing row the insert is
339
+ // skipped and the stored home stands.
340
+ const createRecord = { ...record, originatorInstanceId: home };
341
+ const createRes = await fetch(opsUrl, {
119
342
  method: "POST",
120
343
  headers: { "Content-Type": "application/json", Authorization: auth },
121
- body: JSON.stringify({ operation: "upsert", database: "flair", table: "Agent", records: [record] }),
344
+ body: JSON.stringify({ operation: "insert", database: "flair", table: "Agent", records: [createRecord] }),
122
345
  });
123
- if (!res.ok) {
124
- const text = await res.text().catch(() => "");
125
- console.error(`Error: ${res.status} ${text}`);
346
+ if (!createRes.ok) {
347
+ const text = await createRes.text().catch(() => "");
348
+ console.error(`Error: ${createRes.status} ${text}`);
126
349
  process.exit(1);
127
350
  }
351
+ const createBody = (await createRes.json().catch(() => null));
352
+ const inserted = Array.isArray(createBody?.inserted_hashes) && createBody.inserted_hashes.map(String).includes(id);
353
+ const createSkipped = Array.isArray(createBody?.skipped_hashes) && createBody.skipped_hashes.map(String).includes(id);
354
+ if (!inserted) {
355
+ if (!createSkipped) {
356
+ console.error(`Error: the create for principal '${id}' was not confirmed by the operations API (${JSON.stringify(createBody)}); no row is known to have been written.`);
357
+ process.exit(1);
358
+ }
359
+ // The row already exists — the one this read found, or one that APPEARED
360
+ // since. Its stored home STANDS. Re-read it now: a row this re-read sees
361
+ // with a home that differs from this instance's is refused here, before
362
+ // any write-back; an unreadable re-read is refused too.
363
+ const liveHome = await readStoredAgentHome({ opsUrl, authHeader: auth, id });
364
+ const livePlan = planAgentHomeWrite(liveHome, home, id);
365
+ if (livePlan.refuse) {
366
+ console.error(`Error: ${livePlan.message}`);
367
+ process.exit(1);
368
+ }
369
+ // Write back WITHOUT the home field, so THIS write does not change a
370
+ // stored home; other fields are written when the write-back is admitted
371
+ // and succeeds. The write goes to the Agent RESOURCE (a REST PATCH, never the
372
+ // raw ops API): the resource runs it in a fresh owned transaction (the
373
+ // request's transaction is detached), writes ONLY an allow-list of fields
374
+ // (a home or a federation stamp in the body is never carried), STAGES it,
375
+ // then re-reads the COMMITTED row and ABORTS — with
376
+ // `originator_instance_immutable` if a non-empty string stored home differs from
377
+ // the resolved local ID, or `agent_principal_write_back_no_row` if no row
378
+ // is returned — so a differing stored home seen by those reads is not changed,
379
+ // and a row they find deleted is not re-created (flair#2473). This write uses no
380
+ // compare-and-set, so a change committed after that confirmation read and
381
+ // before the commit is not seen: this narrows the race rather than closing
382
+ // it (per-id serialization: flair#2478).
383
+ const writeBackRes = await fetch(`${httpUrl}Agent/${encodeURIComponent(id)}`, {
384
+ method: "PATCH",
385
+ headers: { "Content-Type": "application/json", Authorization: auth },
386
+ body: JSON.stringify({ ...record, [AGENT_PRINCIPAL_WRITE_BACK_FIELD]: true }),
387
+ });
388
+ if (!writeBackRes.ok) {
389
+ const body = (await writeBackRes.json().catch(() => null));
390
+ if (body?.error === AGENT_HOME_IMMUTABLE_ERROR) {
391
+ console.error(`Error: ${typeof body.message === "string" && body.message.length > 0 ? body.message : AGENT_HOME_IMMUTABLE_ERROR}`);
392
+ }
393
+ else if (body?.error === AGENT_PRINCIPAL_WRITE_BACK_NO_ROW_ERROR) {
394
+ console.error(`Error: the write-back for principal '${id}' was refused: could not confirm a stored agent row, so it was not changed and not re-created. Re-run 'flair principal add ${id}' to create it afresh.`);
395
+ }
396
+ else {
397
+ console.error(`Error: the write-back for principal '${id}' failed (${writeBackRes.status}${body?.message ? `: ${String(body.message)}` : ""}); no row is known to have been changed. Re-run 'flair principal add ${id}'.`);
398
+ }
399
+ process.exit(1);
400
+ }
401
+ }
128
402
  console.log(`✅ Principal '${id}' created`);
129
403
  console.log(` Kind: ${kind}`);
130
404
  console.log(` Trust: ${trustTier}`);
@@ -134,11 +408,10 @@ export function register(program) {
134
408
  console.log(` Public key: ${pubKeyB64url}`);
135
409
  console.log(` Private key: ${privPath}`);
136
410
  });
137
- principal
411
+ addAdminPassOptions(principal
138
412
  .command("list")
139
413
  .description("List all principals")
140
- .option("--kind <kind>", "Filter by kind: human or agent")
141
- .option("--admin-pass <pass>", "Admin password (or set FLAIR_ADMIN_PASS)")
414
+ .option("--kind <kind>", "Filter by kind: human or agent"), "Admin password (or set FLAIR_ADMIN_PASS)")
142
415
  .option("--admin-user <name>", "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)")
143
416
  .option("--port <port>", "Harper HTTP port")
144
417
  .option("--ops-port <port>", "Harper operations API port")
@@ -163,10 +436,12 @@ export function register(program) {
163
436
  table: "Agent",
164
437
  operator: "and",
165
438
  conditions,
166
- // `role` is the authority behind admin status (flair#941); the
167
- // projection used to omit it, so this listing could only ever report
168
- // the mirror.
169
- get_attributes: ["id", "name", "kind", "status", "defaultTrustTier", "role", "admin", "runtime", "createdAt"],
439
+ // Read rows as stored. A `get_attributes` projection materialises an
440
+ // absent column as an explicit `null` (Harper), which the `status`
441
+ // column would then read as deactivated; the raw row omits the key, so
442
+ // the absent-versus-null distinction the auth gate makes survives
443
+ // here (flair#2378). `role` — the authority behind admin, flair#941 —
444
+ // is read from the same unprojected row.
170
445
  }),
171
446
  });
172
447
  if (!res.ok) {
@@ -212,8 +487,10 @@ export function register(program) {
212
487
  {
213
488
  label: "status",
214
489
  key: "status",
215
- format: (v) => {
216
- const s = String(v ?? "active");
490
+ // Report what the gate applies (isPrincipalDeactivated, flair#2378):
491
+ // an explicit null status is deactivated, an absent status is active.
492
+ format: (_v, row) => {
493
+ const s = isPrincipalDeactivated(row) ? String(row.status ?? "deactivated") : "active";
217
494
  const color = s === "active" ? render.c.green : s === "disabled" ? render.c.red : render.c.yellow;
218
495
  return render.wrap(color, s);
219
496
  },
@@ -228,7 +505,7 @@ export function register(program) {
228
505
  .description("Show principal details")
229
506
  .option("--json", "Emit raw JSON response (also: pipe + FLAIR_OUTPUT=json)")
230
507
  .action(async (id, opts) => {
231
- const result = await api("GET", `/Agent/${id}`);
508
+ const result = await api("GET", `/Agent/${encodeRecordId(id)}`);
232
509
  const mode = render.resolveOutputMode(opts);
233
510
  if (mode === "json") {
234
511
  console.log(render.asJSON(result));
@@ -243,10 +520,11 @@ export function register(program) {
243
520
  console.log(render.kv("name", String(result.name)));
244
521
  if (result.kind)
245
522
  console.log(render.kv("kind", render.wrap(result.kind === "human" ? render.c.cyan : render.c.magenta, String(result.kind))));
246
- if (result.status) {
247
- const statusColor = result.status === "active" ? render.c.green : result.status === "disabled" ? render.c.red : render.c.yellow;
248
- console.log(render.kv("status", render.wrap(statusColor, String(result.status))));
249
- }
523
+ // Report what the gate applies (isPrincipalDeactivated, flair#2378): an
524
+ // explicit null `status` is deactivated; an absent one is active.
525
+ const shownStatus = isPrincipalDeactivated(result) ? String(result.status ?? "deactivated") : "active";
526
+ const statusColor = shownStatus === "active" ? render.c.green : shownStatus === "disabled" ? render.c.red : render.c.yellow;
527
+ console.log(render.kv("status", render.wrap(statusColor, shownStatus)));
250
528
  if (result.defaultTrustTier)
251
529
  console.log(render.kv("trust tier", String(result.defaultTrustTier)));
252
530
  // flair#941 — read the authority, not the mirror, and say so when the two
@@ -268,41 +546,9 @@ export function register(program) {
268
546
  console.log(render.kv("updated", `${render.relativeTime(result.updatedAt)} ${render.wrap(render.c.dim, `(${result.updatedAt})`)}`));
269
547
  }
270
548
  });
271
- principal
272
- .command("disable <id>")
273
- .description("Deactivate a principal (revokes access, preserves data)")
274
- .option("--admin-pass <pass>", "Admin password")
275
- .option("--admin-user <name>", "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)")
276
- .option("--ops-port <port>", "Harper operations API port")
277
- .action(async (id, opts) => {
278
- const opsPort = resolveOpsPort(opts);
279
- const adminPass = opts.adminPass ?? process.env.FLAIR_ADMIN_PASS ?? "";
280
- if (!adminPass) {
281
- console.error("Error: --admin-pass or FLAIR_ADMIN_PASS required");
282
- process.exit(1);
283
- }
284
- const auth = `Basic ${Buffer.from(`${resolveAdminUser(opts.adminUser)}:${adminPass}`).toString("base64")}`;
285
- const res = await fetch(`http://127.0.0.1:${opsPort}/`, {
286
- method: "POST",
287
- headers: { "Content-Type": "application/json", Authorization: auth },
288
- body: JSON.stringify({
289
- operation: "update",
290
- database: "flair",
291
- table: "Agent",
292
- records: [{ id, status: "deactivated", updatedAt: new Date().toISOString() }],
293
- }),
294
- });
295
- if (!res.ok) {
296
- const text = await res.text().catch(() => "");
297
- console.error(`Error: ${res.status} ${text}`);
298
- process.exit(1);
299
- }
300
- console.log(`✅ Principal '${id}' deactivated`);
301
- });
302
- principal
303
- .command("promote <id> <tier>")
304
- .description("Change a principal's trust tier (endorsed, corroborated, unverified)")
305
- .option("--admin-pass <pass>", "Admin password")
549
+ registerPrincipalStatusCommand(principal.command("disable <id>").description("Deactivate a principal (revokes access, preserves data)"), "deactivated");
550
+ registerPrincipalStatusCommand(principal.command("enable <id>").description("Reactivate a principal"), "active");
551
+ addAdminPassOptions(principal.command("promote <id> <tier>").description("Change a principal's trust tier (endorsed, corroborated, unverified)"), "Admin password")
306
552
  .option("--admin-user <name>", "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)")
307
553
  .option("--ops-port <port>", "Harper operations API port")
308
554
  .action(async (id, tier, opts) => {
@@ -335,4 +581,124 @@ export function register(program) {
335
581
  }
336
582
  console.log(`✅ Principal '${id}' trust tier set to '${tier}'`);
337
583
  });
584
+ // ── flair principal link / unlink / links (flair#2115) ─────────────────────
585
+ //
586
+ // link maps one IdP login to an existing principal; unlink revokes a mapping;
587
+ // links lists the principal's current mappings.
588
+ /**
589
+ * The instance and admin credential these commands need: `--instance` (else
590
+ * FLAIR_URL) names the target, and a REMOTE target gets no local-credential
591
+ * fallback (`flair mcp enable`'s `--admin-pass` rule). The target policy is
592
+ * enforced in src/lib/mcp-enable.ts before the first request; every refusal
593
+ * here happens before any ops call too.
594
+ */
595
+ function mappingTarget(opts, command) {
596
+ const instance = opts.instance ?? process.env.FLAIR_URL;
597
+ if (!instance) {
598
+ console.error(`Error: --instance is required (or set FLAIR_URL) — \`${command}\` operates on one specific instance.`);
599
+ process.exit(1);
600
+ }
601
+ const adminPass = resolveLocalAdminPass(opts.adminPass, /* isRemoteTarget */ true);
602
+ if (!adminPass) {
603
+ console.error("Error: --admin-pass <pass> is required for a REMOTE target " +
604
+ "(the command authenticates to the target instance's operations API with it).\n" +
605
+ " FLAIR_ADMIN_PASS and ~/.flair/admin-pass are deliberately NOT used here: they are THIS machine's " +
606
+ "local admin credentials, and sending them to another instance is how a local secret ends up on " +
607
+ "someone else's Harper. Pass the target's own admin password explicitly.");
608
+ process.exit(1);
609
+ }
610
+ return { instance, adminUser: resolveAdminUser(opts.adminUser), adminPass };
611
+ }
612
+ const MAPPING_INSTANCE_OPTION = "--instance <url>";
613
+ const MAPPING_INSTANCE_HELP = "Remote flair instance holding the mapping (else FLAIR_URL)";
614
+ const MAPPING_TARGET_HELP = "Targets a REMOTE instance: --instance must be HTTPS, and an unparseable URL, localhost, a .local name, or a " +
615
+ "loopback, unspecified, RFC1918, link-local or IPv6 unique-local address literal is refused before any request.";
616
+ const MAPPING_ADMIN_PASS_HELP = "Admin password for the TARGET instance (required — FLAIR_ADMIN_PASS and ~/.flair/admin-pass are this " +
617
+ "machine's local credentials and are never sent to a remote instance)";
618
+ const MAPPING_ADMIN_USER_HELP = "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)";
619
+ addAdminPassOptions(principal
620
+ .command("link <principal>")
621
+ .description("Map one IdP login to an existing principal on an already-enabled instance — the identity-mapping step " +
622
+ "`flair mcp enable` runs, and nothing else. " + MAPPING_TARGET_HELP)
623
+ .option("--idp-subject <login>", "The login the identity provider reports for this person (GitHub: the username)")
624
+ .option("--idp-provider <name>", "Upstream IdP provider", "github")
625
+ .option(MAPPING_INSTANCE_OPTION, MAPPING_INSTANCE_HELP)
626
+ .option("--replace", "Move a subject that is already mapped to a different principal"), MAPPING_ADMIN_PASS_HELP)
627
+ .option("--admin-user <name>", MAPPING_ADMIN_USER_HELP)
628
+ .action(async (principalId, opts) => {
629
+ if (!opts.idpSubject) {
630
+ console.error("Error: --idp-subject <login> is required — it is the login the identity provider reports for this person.");
631
+ process.exit(1);
632
+ }
633
+ const target = mappingTarget(opts, "flair principal link");
634
+ try {
635
+ const result = await linkPrincipalMapping({
636
+ hostedOrigin: target.instance,
637
+ adminUser: target.adminUser,
638
+ adminPass: target.adminPass,
639
+ principal: principalId,
640
+ idpProvider: opts.idpProvider,
641
+ idpSubject: opts.idpSubject,
642
+ replace: Boolean(opts.replace),
643
+ });
644
+ for (const line of result.lines)
645
+ console.log(line);
646
+ }
647
+ catch (err) {
648
+ console.error(`Error: ${err?.message ?? err}`);
649
+ process.exit(1);
650
+ }
651
+ });
652
+ addAdminPassOptions(principal
653
+ .command("unlink <principal>")
654
+ .description("Revoke one IdP login's mapping; success requires confirmed updates and no resolvable subject mapping on readback. " + MAPPING_TARGET_HELP)
655
+ .option("--idp-subject <login>", "The login the identity provider reports for this person (GitHub: the username)")
656
+ .option("--idp-provider <name>", "Upstream IdP provider the mapping carries", "github")
657
+ .option(MAPPING_INSTANCE_OPTION, MAPPING_INSTANCE_HELP), MAPPING_ADMIN_PASS_HELP)
658
+ .option("--admin-user <name>", MAPPING_ADMIN_USER_HELP)
659
+ .action(async (principalId, opts) => {
660
+ if (!opts.idpSubject) {
661
+ console.error("Error: --idp-subject <login> is required — it is the login the identity provider reports for this person.");
662
+ process.exit(1);
663
+ }
664
+ const target = mappingTarget(opts, "flair principal unlink");
665
+ try {
666
+ const result = await unlinkPrincipalMapping({
667
+ hostedOrigin: target.instance,
668
+ adminUser: target.adminUser,
669
+ adminPass: target.adminPass,
670
+ principal: principalId,
671
+ idpProvider: opts.idpProvider,
672
+ idpSubject: opts.idpSubject,
673
+ });
674
+ for (const line of result.lines)
675
+ console.log(line);
676
+ }
677
+ catch (err) {
678
+ console.error(`Error: ${err?.message ?? err}`);
679
+ process.exit(1);
680
+ }
681
+ });
682
+ addAdminPassOptions(principal
683
+ .command("links <principal>")
684
+ .description("List a principal's current IdP mappings on an already-enabled instance. " + MAPPING_TARGET_HELP)
685
+ .option(MAPPING_INSTANCE_OPTION, MAPPING_INSTANCE_HELP), MAPPING_ADMIN_PASS_HELP)
686
+ .option("--admin-user <name>", MAPPING_ADMIN_USER_HELP)
687
+ .action(async (principalId, opts) => {
688
+ const target = mappingTarget(opts, "flair principal links");
689
+ try {
690
+ const result = await listPrincipalMappings({
691
+ hostedOrigin: target.instance,
692
+ adminUser: target.adminUser,
693
+ adminPass: target.adminPass,
694
+ principal: principalId,
695
+ });
696
+ for (const line of result.lines)
697
+ console.log(line);
698
+ }
699
+ catch (err) {
700
+ console.error(`Error: ${err?.message ?? err}`);
701
+ process.exit(1);
702
+ }
703
+ });
338
704
  }
@@ -1,3 +1,13 @@
1
+ /**
2
+ * quality.ts — extracted from src/cli.ts (flair#1636, epic #1618).
3
+ *
4
+ * Pure move, ZERO behavior change: `flair quality` and `flair quality --emit` plus the pure metric-computation helpers (memory-quality-observability arc).
5
+ * Shared cli-locals stay in cli.ts and are injected via bindCli() before
6
+ * register(); this module never imports src/cli.ts. Top-level imports only
7
+ * (no require(), #1653). Compiled strictly via tsconfig.check.src.json.
8
+ */
9
+ import { encodeRecordId } from "../lib/record-id-path.js";
10
+ import { ApiRequestOutcomeUnknown } from "../lib/auth-resolve.js";
1
11
  import * as render from "../render.js";
2
12
  import { EMBEDDING_STAMP_ID, describeStampOutstanding, resolveCurrentModelId } from "../stamp-outstanding.js";
3
13
  let cli;
@@ -811,7 +821,7 @@ async function storeQualitySnapshot(agentId, agentIdSource, baseUrl, subject, sn
811
821
  type: "quality-snapshot",
812
822
  createdAt: new Date().toISOString(),
813
823
  };
814
- const out = await api("PUT", `/Memory/${encodeURIComponent(memId)}`, body, { baseUrl, agentId, agentIdSource });
824
+ const out = await api("PUT", `/Memory/${encodeRecordId(memId)}`, body, { baseUrl, agentId, agentIdSource });
815
825
  if (out?.error)
816
826
  throw new Error(String(out.error));
817
827
  return memId;
@@ -1002,6 +1012,8 @@ export function register(program) {
1002
1012
  emitResult.snapshotId = await storeQualitySnapshot(agentId, source, baseUrl, subject, current);
1003
1013
  }
1004
1014
  catch (err) {
1015
+ if (err instanceof ApiRequestOutcomeUnknown)
1016
+ throw err;
1005
1017
  emitResult.errors.push(`snapshot store failed: ${err?.message ?? String(err)}`);
1006
1018
  }
1007
1019
  }