@tpsdev-ai/flair 0.58.0 → 0.62.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (268) hide show
  1. package/README.md +7 -6
  2. package/SECURITY.md +36 -0
  3. package/config.yaml +15 -1
  4. package/dist/bridges/builtins/mem0.js +63 -28
  5. package/dist/bridges/runtime/import-runner.js +12 -0
  6. package/dist/bridges/runtime/load-plugin.js +42 -13
  7. package/dist/bridges/runtime/yaml-loader.js +4 -2
  8. package/dist/build-info.json +3 -3
  9. package/dist/cli.js +1030 -343
  10. package/dist/commands/agent.js +384 -45
  11. package/dist/commands/attention.js +4 -3
  12. package/dist/commands/backup.js +202 -34
  13. package/dist/commands/bridge.js +172 -119
  14. package/dist/commands/deploy.js +37 -4
  15. package/dist/commands/doctor.js +601 -163
  16. package/dist/commands/export.js +54 -19
  17. package/dist/commands/federation.js +141 -21
  18. package/dist/commands/hook.js +155 -2
  19. package/dist/commands/idp.js +14 -1
  20. package/dist/commands/import.js +7 -3
  21. package/dist/commands/init.js +462 -193
  22. package/dist/commands/integrity.js +388 -0
  23. package/dist/commands/keys.js +247 -58
  24. package/dist/commands/mcp.js +146 -53
  25. package/dist/commands/memory.js +171 -21
  26. package/dist/commands/migrate-harness-memory.js +3 -2
  27. package/dist/commands/orgevent.js +46 -37
  28. package/dist/commands/presence.js +4 -3
  29. package/dist/commands/principal.js +426 -48
  30. package/dist/commands/quality.js +10 -1
  31. package/dist/commands/reembed.js +141 -17
  32. package/dist/commands/relationship.js +2 -1
  33. package/dist/commands/rem.js +56 -18
  34. package/dist/commands/restore.js +101 -61
  35. package/dist/commands/search.js +6 -4
  36. package/dist/commands/service.js +151 -38
  37. package/dist/commands/soul.js +4 -3
  38. package/dist/commands/status.js +43 -5
  39. package/dist/commands/test.js +3 -2
  40. package/dist/commands/upgrade.js +24 -1
  41. package/dist/commands/workspace.js +6 -3
  42. package/dist/component-env.js +31 -41
  43. package/dist/deploy.js +77 -1
  44. package/dist/doctor-client.js +529 -92
  45. package/dist/engine-version-contract.js +1 -0
  46. package/dist/engine-version.js +23 -3
  47. package/dist/federation-verify.js +4 -3
  48. package/dist/hook-install.js +670 -6
  49. package/dist/keystore.js +72 -0
  50. package/dist/lib/action-recall-runtime.js +328 -0
  51. package/dist/lib/agent-home-fields.js +132 -0
  52. package/dist/lib/agent-home.js +427 -0
  53. package/dist/lib/agent-id-rule.js +46 -0
  54. package/dist/lib/agent-roster.js +33 -0
  55. package/dist/lib/auth-resolve.js +49 -16
  56. package/dist/lib/capture-runtime.js +124 -0
  57. package/dist/lib/credential-status-rule.js +78 -0
  58. package/dist/lib/daemon-liveness.js +81 -8
  59. package/dist/lib/doctor-run.js +140 -35
  60. package/dist/lib/durability-copy.js +10 -0
  61. package/dist/lib/embedding-space-doctor.js +75 -0
  62. package/dist/lib/flair-agent-role.js +120 -0
  63. package/dist/lib/hub-url.js +12 -0
  64. package/dist/lib/init-admin-pass.js +88 -12
  65. package/dist/lib/init-listener-environ.js +1 -2
  66. package/dist/lib/init-occupied-listener.js +15 -111
  67. package/dist/lib/init-spawn-attribution.js +73 -0
  68. package/dist/lib/init-tcp-probe.js +33 -0
  69. package/dist/lib/instance-identity-row.js +20 -0
  70. package/dist/lib/launchd-management.js +27 -2
  71. package/dist/lib/listener-table.js +268 -0
  72. package/dist/lib/local-delete-instance.js +27 -0
  73. package/dist/lib/local-instance-pair.js +256 -0
  74. package/dist/lib/mcp-enable.js +1775 -338
  75. package/dist/lib/mcp-oauth-env-core.js +133 -0
  76. package/dist/lib/mcp-oauth-env.js +125 -0
  77. package/dist/lib/mcp-spec.js +17 -1
  78. package/dist/lib/memory-attributes.js +2 -0
  79. package/dist/lib/memory-id-policy.js +46 -0
  80. package/dist/lib/memory-integrity.js +309 -0
  81. package/dist/lib/memory-purge-response.js +20 -0
  82. package/dist/lib/ops-table-count.js +25 -0
  83. package/dist/lib/owned-pins.js +67 -10
  84. package/dist/lib/peer-status.js +27 -0
  85. package/dist/lib/principal-status.js +29 -0
  86. package/dist/lib/process-start-time.js +103 -7
  87. package/dist/lib/proto-safe-record.js +42 -0
  88. package/dist/lib/record-id-path.js +25 -0
  89. package/dist/lib/reembed-server-support.js +66 -0
  90. package/dist/lib/restore-verify.js +104 -0
  91. package/dist/lib/scheduler-platform.js +10 -6
  92. package/dist/lib/secret-keys.js +25 -0
  93. package/dist/lib/secrets-push.js +50 -22
  94. package/dist/lib/skill-seed-pending.js +24 -0
  95. package/dist/lib/skill-seed.js +365 -0
  96. package/dist/lib/stop-start-recovery.js +54 -0
  97. package/dist/lib/using-flair-skill.js +87 -0
  98. package/dist/mcp-client-assertion.js +112 -4
  99. package/dist/memory-id-checkpoint.js +326 -0
  100. package/dist/memory-node-compare.js +207 -0
  101. package/dist/packages/flair-mcp/src/secret-redaction.js +113 -0
  102. package/dist/rem/restore.js +6 -5
  103. package/dist/rem/runner.js +103 -44
  104. package/dist/resources/Agent.js +348 -8
  105. package/dist/resources/AgentKeyRegister.js +214 -0
  106. package/dist/resources/AgentKeyRegistration.js +28 -0
  107. package/dist/resources/AgentSeed.js +19 -4
  108. package/dist/resources/AutoPromoteCandidates.js +7 -1
  109. package/dist/resources/Credential.js +177 -2
  110. package/dist/resources/Federation.js +752 -132
  111. package/dist/resources/FederationRetry.js +140 -0
  112. package/dist/resources/InstructionVersion.js +220 -0
  113. package/dist/resources/Integration.js +300 -25
  114. package/dist/resources/Memory.js +2113 -604
  115. package/dist/resources/MemoryArchive.js +75 -42
  116. package/dist/resources/MemoryBootstrap.js +227 -64
  117. package/dist/resources/MemoryCandidate.js +21 -1
  118. package/dist/resources/MemoryDedupStats.js +30 -1
  119. package/dist/resources/MemoryFeed.js +327 -45
  120. package/dist/resources/MemoryGrant.js +21 -1
  121. package/dist/resources/MemoryMaintenance.js +129 -25
  122. package/dist/resources/MemoryPurge.js +232 -0
  123. package/dist/resources/MemoryReflect.js +7 -2
  124. package/dist/resources/MemoryReindex.js +24 -8
  125. package/dist/resources/Message.js +5 -3
  126. package/dist/resources/OAuth.js +186 -9
  127. package/dist/resources/OrgEvent.js +126 -3
  128. package/dist/resources/OrgSkillAssignment.js +209 -0
  129. package/dist/resources/Presence.js +144 -49
  130. package/dist/resources/PromoteMemoryCandidate.js +18 -7
  131. package/dist/resources/Relationship.js +23 -0
  132. package/dist/resources/SemanticSearch.js +63 -32
  133. package/dist/resources/Soul.js +189 -76
  134. package/dist/resources/TeamDirectory.js +35 -0
  135. package/dist/resources/WorkspaceState.js +21 -1
  136. package/dist/resources/XAA.js +212 -65
  137. package/dist/resources/agent-auth.js +40 -15
  138. package/dist/resources/agent-status-guard.js +63 -0
  139. package/dist/resources/auth-middleware.js +402 -162
  140. package/dist/resources/ed25519-auth.js +1 -1
  141. package/dist/resources/embedding-space-guard.js +366 -72
  142. package/dist/resources/engine-version-stamp-boot.js +53 -0
  143. package/dist/resources/federation-classify.js +94 -0
  144. package/dist/resources/federation-crypto.js +5 -5
  145. package/dist/resources/federation-retry-lib.js +135 -0
  146. package/dist/resources/flair-agent-role-boot.js +26 -0
  147. package/dist/resources/grant-visibility.js +135 -0
  148. package/dist/resources/harper-routing.js +83 -0
  149. package/dist/resources/health.js +130 -20
  150. package/dist/resources/host-source-citation.js +49 -0
  151. package/dist/resources/host-source-visibility.js +7 -6
  152. package/dist/resources/instance-create-lock.js +17 -0
  153. package/dist/resources/instance-identity.js +23 -0
  154. package/dist/resources/instruction-version-record.js +343 -0
  155. package/dist/resources/key-lock.js +31 -0
  156. package/dist/resources/mcp-handler.js +36 -8
  157. package/dist/resources/mcp-oauth-env-guard.js +36 -0
  158. package/dist/resources/mcp-oauth.js +26 -12
  159. package/dist/resources/mcp-tool-arguments.js +4 -6
  160. package/dist/resources/mcp-tools.js +150 -23
  161. package/dist/resources/memory-bootstrap-lib.js +5 -15
  162. package/dist/resources/memory-declared-attributes.js +3 -1
  163. package/dist/resources/memory-deletion-history.js +55 -0
  164. package/dist/resources/memory-durability.js +54 -0
  165. package/dist/resources/memory-embed-hash.js +88 -0
  166. package/dist/resources/memory-embedding-value.js +8 -0
  167. package/dist/resources/memory-host-source.js +27 -5
  168. package/dist/resources/memory-id-guard.js +75 -0
  169. package/dist/resources/memory-redaction.js +236 -0
  170. package/dist/resources/memory-supplied-vector.js +72 -0
  171. package/dist/resources/memory-write-lock.js +310 -0
  172. package/dist/resources/memory-write-response.js +139 -0
  173. package/dist/resources/migrations/data-dir.js +74 -16
  174. package/dist/resources/migrations/dir-safety.js +1 -1
  175. package/dist/resources/migrations/embedding-stamp.js +193 -79
  176. package/dist/resources/migrations/export.js +1 -0
  177. package/dist/resources/migrations/graph-heal.js +18 -25
  178. package/dist/resources/migrations/lock.js +7 -1
  179. package/dist/resources/migrations/snapshot.js +1 -0
  180. package/dist/resources/migrations/source-fields.js +5 -5
  181. package/dist/resources/migrations/synthetic-test-migration.js +14 -11
  182. package/dist/resources/migrations/visibility-backfill.js +29 -29
  183. package/dist/resources/multi-worker-guard.js +121 -0
  184. package/dist/resources/oauth-discovery.js +1 -0
  185. package/dist/resources/oauth-wellknown.js +8 -4
  186. package/dist/resources/object-body-guard.js +33 -0
  187. package/dist/resources/org-event-created-at.js +133 -0
  188. package/dist/resources/originator-instance.js +39 -7
  189. package/dist/resources/owner-delete-recheck.js +78 -0
  190. package/dist/resources/owner-field-guard.js +39 -5
  191. package/dist/resources/owner-scoped-write-policy.js +212 -0
  192. package/dist/resources/owner-scoped-writes.js +58 -0
  193. package/dist/resources/presence-receipt.js +236 -0
  194. package/dist/resources/promotion-stamp.js +47 -12
  195. package/dist/resources/record-owner-guard.js +74 -26
  196. package/dist/resources/record-types.js +17 -1
  197. package/dist/resources/relay-ops.js +78 -6
  198. package/dist/resources/replay-store.js +145 -21
  199. package/dist/resources/request-target.js +136 -0
  200. package/dist/resources/request-transaction.js +35 -0
  201. package/dist/resources/search-readiness.js +4 -1
  202. package/dist/resources/seed-ids.js +9 -0
  203. package/dist/resources/seed-reservation.js +117 -0
  204. package/dist/resources/semantic-retrieval-core.js +20 -9
  205. package/dist/resources/skill-manifest.js +190 -0
  206. package/dist/resources/skill-provenance.js +15 -10
  207. package/dist/resources/skill-subject.js +53 -0
  208. package/dist/resources/skill-version-write.js +432 -0
  209. package/dist/resources/skill-write-fault.js +17 -0
  210. package/dist/resources/skill-write-policy.js +67 -0
  211. package/dist/resources/skill-write.js +67 -7
  212. package/dist/resources/table-helpers.js +10 -7
  213. package/dist/resources/team-directory.js +248 -0
  214. package/dist/resources/tool-descriptors/index.js +69 -8
  215. package/dist/resources/txn-pause-point.js +118 -0
  216. package/dist/resources/usage-recording.js +171 -63
  217. package/dist/resources/write-back.js +218 -0
  218. package/dist/src/engine-version-contract.js +1 -0
  219. package/dist/src/keystore.js +72 -0
  220. package/dist/src/lib/agent-home-fields.js +132 -0
  221. package/dist/src/lib/agent-id-rule.js +46 -0
  222. package/dist/src/lib/agent-key-register.js +80 -0
  223. package/dist/src/lib/atomic-write.js +256 -0
  224. package/dist/src/lib/credential-status-rule.js +78 -0
  225. package/dist/src/lib/expired-by-agent.js +37 -0
  226. package/dist/src/lib/flair-agent-role.js +120 -0
  227. package/dist/src/lib/idp-mapping-rule.js +81 -0
  228. package/dist/src/lib/instance-identity-row.js +20 -0
  229. package/dist/src/lib/mcp-oauth-env-core.js +133 -0
  230. package/dist/src/lib/memory-attributes.js +2 -0
  231. package/dist/src/lib/memory-id-policy.js +46 -0
  232. package/dist/src/lib/principal-status.js +29 -0
  233. package/dist/src/lib/proto-safe-record.js +42 -0
  234. package/dist/src/lib/reembed-server-support.js +66 -0
  235. package/dist/src/lib/scheduler-platform.js +10 -6
  236. package/dist/src/lib/systemd-agent-id.js +38 -0
  237. package/docs/access-control.md +768 -0
  238. package/docs/api-reference.md +52 -13
  239. package/docs/auth.md +10 -12
  240. package/docs/bridges.md +11 -0
  241. package/docs/claude-code.md +34 -4
  242. package/docs/deepseek-harness.md +1 -1
  243. package/docs/deploying-on-fabric.md +70 -0
  244. package/docs/deployment.md +2 -0
  245. package/docs/embedding-in-a-harper-app.md +1 -1
  246. package/docs/federation.md +33 -2
  247. package/docs/hosted-on-fabric.md +43 -36
  248. package/docs/integrations.md +6 -6
  249. package/docs/mcp-clients.md +10 -5
  250. package/docs/n8n.md +17 -11
  251. package/docs/notes/mcp-agent-auth-consumer.md +12 -4
  252. package/docs/notes/mcp-oauth-model2.md +34 -5
  253. package/docs/quickstart-fabric.md +2 -2
  254. package/docs/quickstart.md +9 -1
  255. package/docs/releasing.md +34 -28
  256. package/docs/rem.md +8 -0
  257. package/docs/secrets-and-keys.md +19 -2
  258. package/docs/standalone-local.md +1 -0
  259. package/docs/supply-chain-policy.md +13 -3
  260. package/docs/upgrade.md +32 -6
  261. package/package.json +12 -6
  262. package/schemas/agent-key-registration.graphql +22 -0
  263. package/schemas/agent.graphql +3 -0
  264. package/schemas/federation.graphql +38 -1
  265. package/schemas/memory.graphql +115 -5
  266. package/schemas/oauth.graphql +27 -4
  267. package/schemas/schema.graphql +2 -0
  268. package/templates/launchd/start-flair-with-admin-pass.sh +89 -16
@@ -2,6 +2,14 @@ import nacl from "tweetnacl";
2
2
  import { existsSync, mkdirSync, writeFileSync, readFileSync, chmodSync } from "node:fs";
3
3
  import * as render from "../render.js";
4
4
  import { defaultKeysDir, resolveLocalAdminPass, resolveAdminUser, } 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,172 @@ 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
+ command
184
+ .option("--admin-pass <pass>", "Admin password; required explicitly for a remote --instance")
185
+ .option("--admin-user <name>", "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)")
186
+ .option("--ops-port <port>", "Harper operations API port (local target)")
187
+ .option("--instance <url>", "Remote Flair instance (else FLAIR_URL); its ops API is derived as in mcp enable")
188
+ .action(async (id, opts) => setPrincipalStatus(id, status, opts));
189
+ }
16
190
  // ─── flair principal ─────────────────────────────────────────────────────────
17
191
  // 1.0 identity management. The Principal model extends Agent — this is the
18
192
  // preferred CLI surface for managing identities going forward.
@@ -50,7 +224,33 @@ export function register(program) {
50
224
  .option("--keys-dir <dir>", "Directory for Ed25519 keys")
51
225
  .option("--ops-port <port>", "Harper operations API port")
52
226
  .action(async (id, opts) => {
53
- const opsPort = resolveOpsPort(opts);
227
+ // flair#2359 — the ONE shared agent-ID rule, before any key file is
228
+ // written or any insert is attempted. The upsert below writes the row
229
+ // through the operations API, so the Agent resource's own guard never
230
+ // runs on it.
231
+ if (!isValidAgentId(id)) {
232
+ console.error(`Error: ${invalidAgentIdMessage(id)}`);
233
+ process.exit(1);
234
+ }
235
+ // flair#2474 — pair the ops port and the HTTP port. `principal add` reads
236
+ // the stored home through the ops API and sends its guarded write-back to
237
+ // the Agent RESOURCE on the HTTP port; resolving the two INDEPENDENTLY
238
+ // would let `--ops-port` name one instance and `--port` another, so the
239
+ // home is read from the first and written to the second. A target the
240
+ // configured pair contradicts, or one with a single port named and no
241
+ // complete configured pair, is refused by name (`ambiguous_instance_target`)
242
+ // BEFORE any key file is written or any insert attempted. Two named ports
243
+ // that match neither side of the configured pair are used as given, without
244
+ // verification (see resolveAgentHomeTarget).
245
+ let target;
246
+ try {
247
+ target = resolveAgentHomeTarget(opts);
248
+ }
249
+ catch (err) {
250
+ console.error(`Error: ${err.message}`);
251
+ process.exit(1);
252
+ }
253
+ const opsPort = target.opsPort;
54
254
  const keysDir = opts.keysDir ?? defaultKeysDir();
55
255
  const adminUser = resolveAdminUser(opts.adminUser);
56
256
  const kind = opts.kind ?? "agent";
@@ -96,6 +296,30 @@ export function register(program) {
96
296
  }
97
297
  // Insert via operations API with Principal fields
98
298
  const auth = `Basic ${Buffer.from(`${adminUser}:${adminPass}`).toString("base64")}`;
299
+ // flair#2433 / flair#2473 — the HOME ASSIGNMENT on a create is THIS
300
+ // instance's federation id, resolved through the one shared rule, and it
301
+ // rides on the `insert` itself — so a row created at write time carries it,
302
+ // even one deleted since this read. That assignment is CREATE-ONLY: an
303
+ // insert over a row that already exists is SKIPPED by Harper, so this insert
304
+ // does not replace a stored home (other fields of an existing row may still
305
+ // be updated by the write-back below). A row with a home that DIFFERS from
306
+ // this instance's is refused with `originator_instance_immutable` when this
307
+ // command's reads or the resource's reads see it; an insert the operations
308
+ // API reports neither inserted nor skipped is a failure, not a success. A
309
+ // failed read is UNREADABLE, not "no home", and refused.
310
+ const opsUrl = `http://127.0.0.1:${opsPort}/`;
311
+ // The instance's HTTP port, where the Agent RESOURCE lives. The write-back
312
+ // goes to the resource (a guarded REST PATCH), not the raw ops API, so it
313
+ // runs in an owned transaction (flair#2473). `target` pairs this with the
314
+ // ops port above (flair#2474).
315
+ const httpUrl = `http://127.0.0.1:${target.httpPort}/`;
316
+ const home = await resolveTargetInstanceId(agentHomeEndpoint(opsPort, adminUser, adminPass));
317
+ const existingHome = await readStoredAgentHome({ opsUrl, authHeader: auth, id });
318
+ const homePlan = planAgentHomeWrite(existingHome, home, id);
319
+ if (homePlan.refuse) {
320
+ console.error(`Error: ${homePlan.message}`);
321
+ process.exit(1);
322
+ }
99
323
  const record = {
100
324
  id,
101
325
  name,
@@ -115,16 +339,71 @@ export function register(program) {
115
339
  createdAt: new Date().toISOString(),
116
340
  updatedAt: new Date().toISOString(),
117
341
  };
118
- const res = await fetch(`http://127.0.0.1:${opsPort}/`, {
342
+ // 1) Create-only. The home rides on THIS insert (so a row the insert
343
+ // creates at write time carries it); over an existing row the insert is
344
+ // skipped and the stored home stands.
345
+ const createRecord = { ...record, originatorInstanceId: home };
346
+ const createRes = await fetch(opsUrl, {
119
347
  method: "POST",
120
348
  headers: { "Content-Type": "application/json", Authorization: auth },
121
- body: JSON.stringify({ operation: "upsert", database: "flair", table: "Agent", records: [record] }),
349
+ body: JSON.stringify({ operation: "insert", database: "flair", table: "Agent", records: [createRecord] }),
122
350
  });
123
- if (!res.ok) {
124
- const text = await res.text().catch(() => "");
125
- console.error(`Error: ${res.status} ${text}`);
351
+ if (!createRes.ok) {
352
+ const text = await createRes.text().catch(() => "");
353
+ console.error(`Error: ${createRes.status} ${text}`);
126
354
  process.exit(1);
127
355
  }
356
+ const createBody = (await createRes.json().catch(() => null));
357
+ const inserted = Array.isArray(createBody?.inserted_hashes) && createBody.inserted_hashes.map(String).includes(id);
358
+ const createSkipped = Array.isArray(createBody?.skipped_hashes) && createBody.skipped_hashes.map(String).includes(id);
359
+ if (!inserted) {
360
+ if (!createSkipped) {
361
+ 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.`);
362
+ process.exit(1);
363
+ }
364
+ // The row already exists — the one this read found, or one that APPEARED
365
+ // since. Its stored home STANDS. Re-read it now: a row this re-read sees
366
+ // with a home that differs from this instance's is refused here, before
367
+ // any write-back; an unreadable re-read is refused too.
368
+ const liveHome = await readStoredAgentHome({ opsUrl, authHeader: auth, id });
369
+ const livePlan = planAgentHomeWrite(liveHome, home, id);
370
+ if (livePlan.refuse) {
371
+ console.error(`Error: ${livePlan.message}`);
372
+ process.exit(1);
373
+ }
374
+ // Write back WITHOUT the home field, so THIS write does not change a
375
+ // stored home; other fields are written when the write-back is admitted
376
+ // and succeeds. The write goes to the Agent RESOURCE (a REST PATCH, never the
377
+ // raw ops API): the resource runs it in a fresh owned transaction (the
378
+ // request's transaction is detached), writes ONLY an allow-list of fields
379
+ // (a home or a federation stamp in the body is never carried), STAGES it,
380
+ // then re-reads the COMMITTED row and ABORTS — with
381
+ // `originator_instance_immutable` if a non-empty string stored home differs from
382
+ // the resolved local ID, or `agent_principal_write_back_no_row` if no row
383
+ // is returned — so a differing stored home seen by those reads is not changed,
384
+ // and a row they find deleted is not re-created (flair#2473). This write uses no
385
+ // compare-and-set, so a change committed after that confirmation read and
386
+ // before the commit is not seen: this narrows the race rather than closing
387
+ // it (per-id serialization: flair#2478).
388
+ const writeBackRes = await fetch(`${httpUrl}Agent/${encodeURIComponent(id)}`, {
389
+ method: "PATCH",
390
+ headers: { "Content-Type": "application/json", Authorization: auth },
391
+ body: JSON.stringify({ ...record, [AGENT_PRINCIPAL_WRITE_BACK_FIELD]: true }),
392
+ });
393
+ if (!writeBackRes.ok) {
394
+ const body = (await writeBackRes.json().catch(() => null));
395
+ if (body?.error === AGENT_HOME_IMMUTABLE_ERROR) {
396
+ console.error(`Error: ${typeof body.message === "string" && body.message.length > 0 ? body.message : AGENT_HOME_IMMUTABLE_ERROR}`);
397
+ }
398
+ else if (body?.error === AGENT_PRINCIPAL_WRITE_BACK_NO_ROW_ERROR) {
399
+ 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.`);
400
+ }
401
+ else {
402
+ 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}'.`);
403
+ }
404
+ process.exit(1);
405
+ }
406
+ }
128
407
  console.log(`✅ Principal '${id}' created`);
129
408
  console.log(` Kind: ${kind}`);
130
409
  console.log(` Trust: ${trustTier}`);
@@ -163,10 +442,12 @@ export function register(program) {
163
442
  table: "Agent",
164
443
  operator: "and",
165
444
  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"],
445
+ // Read rows as stored. A `get_attributes` projection materialises an
446
+ // absent column as an explicit `null` (Harper), which the `status`
447
+ // column would then read as deactivated; the raw row omits the key, so
448
+ // the absent-versus-null distinction the auth gate makes survives
449
+ // here (flair#2378). `role` — the authority behind admin, flair#941 —
450
+ // is read from the same unprojected row.
170
451
  }),
171
452
  });
172
453
  if (!res.ok) {
@@ -212,8 +493,10 @@ export function register(program) {
212
493
  {
213
494
  label: "status",
214
495
  key: "status",
215
- format: (v) => {
216
- const s = String(v ?? "active");
496
+ // Report what the gate applies (isPrincipalDeactivated, flair#2378):
497
+ // an explicit null status is deactivated, an absent status is active.
498
+ format: (_v, row) => {
499
+ const s = isPrincipalDeactivated(row) ? String(row.status ?? "deactivated") : "active";
217
500
  const color = s === "active" ? render.c.green : s === "disabled" ? render.c.red : render.c.yellow;
218
501
  return render.wrap(color, s);
219
502
  },
@@ -228,7 +511,7 @@ export function register(program) {
228
511
  .description("Show principal details")
229
512
  .option("--json", "Emit raw JSON response (also: pipe + FLAIR_OUTPUT=json)")
230
513
  .action(async (id, opts) => {
231
- const result = await api("GET", `/Agent/${id}`);
514
+ const result = await api("GET", `/Agent/${encodeRecordId(id)}`);
232
515
  const mode = render.resolveOutputMode(opts);
233
516
  if (mode === "json") {
234
517
  console.log(render.asJSON(result));
@@ -243,10 +526,11 @@ export function register(program) {
243
526
  console.log(render.kv("name", String(result.name)));
244
527
  if (result.kind)
245
528
  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
- }
529
+ // Report what the gate applies (isPrincipalDeactivated, flair#2378): an
530
+ // explicit null `status` is deactivated; an absent one is active.
531
+ const shownStatus = isPrincipalDeactivated(result) ? String(result.status ?? "deactivated") : "active";
532
+ const statusColor = shownStatus === "active" ? render.c.green : shownStatus === "disabled" ? render.c.red : render.c.yellow;
533
+ console.log(render.kv("status", render.wrap(statusColor, shownStatus)));
250
534
  if (result.defaultTrustTier)
251
535
  console.log(render.kv("trust tier", String(result.defaultTrustTier)));
252
536
  // flair#941 — read the authority, not the mirror, and say so when the two
@@ -268,37 +552,8 @@ export function register(program) {
268
552
  console.log(render.kv("updated", `${render.relativeTime(result.updatedAt)} ${render.wrap(render.c.dim, `(${result.updatedAt})`)}`));
269
553
  }
270
554
  });
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
- });
555
+ registerPrincipalStatusCommand(principal.command("disable <id>").description("Deactivate a principal (revokes access, preserves data)"), "deactivated");
556
+ registerPrincipalStatusCommand(principal.command("enable <id>").description("Reactivate a principal"), "active");
302
557
  principal
303
558
  .command("promote <id> <tier>")
304
559
  .description("Change a principal's trust tier (endorsed, corroborated, unverified)")
@@ -335,4 +590,127 @@ export function register(program) {
335
590
  }
336
591
  console.log(`✅ Principal '${id}' trust tier set to '${tier}'`);
337
592
  });
593
+ // ── flair principal link / unlink / links (flair#2115) ─────────────────────
594
+ //
595
+ // link maps one IdP login to an existing principal; unlink revokes a mapping;
596
+ // links lists the principal's current mappings.
597
+ /**
598
+ * The instance and admin credential these commands need: `--instance` (else
599
+ * FLAIR_URL) names the target, and a REMOTE target gets no local-credential
600
+ * fallback (`flair mcp enable`'s `--admin-pass` rule). The target policy is
601
+ * enforced in src/lib/mcp-enable.ts before the first request; every refusal
602
+ * here happens before any ops call too.
603
+ */
604
+ function mappingTarget(opts, command) {
605
+ const instance = opts.instance ?? process.env.FLAIR_URL;
606
+ if (!instance) {
607
+ console.error(`Error: --instance is required (or set FLAIR_URL) — \`${command}\` operates on one specific instance.`);
608
+ process.exit(1);
609
+ }
610
+ const adminPass = resolveLocalAdminPass(opts.adminPass, /* isRemoteTarget */ true);
611
+ if (!adminPass) {
612
+ console.error("Error: --admin-pass <pass> is required for a REMOTE target " +
613
+ "(the command authenticates to the target instance's operations API with it).\n" +
614
+ " FLAIR_ADMIN_PASS and ~/.flair/admin-pass are deliberately NOT used here: they are THIS machine's " +
615
+ "local admin credentials, and sending them to another instance is how a local secret ends up on " +
616
+ "someone else's Harper. Pass the target's own admin password explicitly.");
617
+ process.exit(1);
618
+ }
619
+ return { instance, adminUser: resolveAdminUser(opts.adminUser), adminPass };
620
+ }
621
+ const MAPPING_INSTANCE_OPTION = "--instance <url>";
622
+ const MAPPING_INSTANCE_HELP = "Remote flair instance holding the mapping (else FLAIR_URL)";
623
+ const MAPPING_TARGET_HELP = "Targets a REMOTE instance: --instance must be HTTPS, and an unparseable URL, localhost, a .local name, or a " +
624
+ "loopback, unspecified, RFC1918, link-local or IPv6 unique-local address literal is refused before any request.";
625
+ const MAPPING_ADMIN_PASS_HELP = "Admin password for the TARGET instance (required — FLAIR_ADMIN_PASS and ~/.flair/admin-pass are this " +
626
+ "machine's local credentials and are never sent to a remote instance)";
627
+ const MAPPING_ADMIN_USER_HELP = "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)";
628
+ principal
629
+ .command("link <principal>")
630
+ .description("Map one IdP login to an existing principal on an already-enabled instance — the identity-mapping step " +
631
+ "`flair mcp enable` runs, and nothing else. " + MAPPING_TARGET_HELP)
632
+ .option("--idp-subject <login>", "The login the identity provider reports for this person (GitHub: the username)")
633
+ .option("--idp-provider <name>", "Upstream IdP provider", "github")
634
+ .option(MAPPING_INSTANCE_OPTION, MAPPING_INSTANCE_HELP)
635
+ .option("--replace", "Move a subject that is already mapped to a different principal")
636
+ .option("--admin-pass <pass>", MAPPING_ADMIN_PASS_HELP)
637
+ .option("--admin-user <name>", MAPPING_ADMIN_USER_HELP)
638
+ .action(async (principalId, opts) => {
639
+ if (!opts.idpSubject) {
640
+ console.error("Error: --idp-subject <login> is required — it is the login the identity provider reports for this person.");
641
+ process.exit(1);
642
+ }
643
+ const target = mappingTarget(opts, "flair principal link");
644
+ try {
645
+ const result = await linkPrincipalMapping({
646
+ hostedOrigin: target.instance,
647
+ adminUser: target.adminUser,
648
+ adminPass: target.adminPass,
649
+ principal: principalId,
650
+ idpProvider: opts.idpProvider,
651
+ idpSubject: opts.idpSubject,
652
+ replace: Boolean(opts.replace),
653
+ });
654
+ for (const line of result.lines)
655
+ console.log(line);
656
+ }
657
+ catch (err) {
658
+ console.error(`Error: ${err?.message ?? err}`);
659
+ process.exit(1);
660
+ }
661
+ });
662
+ principal
663
+ .command("unlink <principal>")
664
+ .description("Revoke one IdP login's mapping; success requires confirmed updates and no resolvable subject mapping on readback. " + MAPPING_TARGET_HELP)
665
+ .option("--idp-subject <login>", "The login the identity provider reports for this person (GitHub: the username)")
666
+ .option("--idp-provider <name>", "Upstream IdP provider the mapping carries", "github")
667
+ .option(MAPPING_INSTANCE_OPTION, MAPPING_INSTANCE_HELP)
668
+ .option("--admin-pass <pass>", MAPPING_ADMIN_PASS_HELP)
669
+ .option("--admin-user <name>", MAPPING_ADMIN_USER_HELP)
670
+ .action(async (principalId, opts) => {
671
+ if (!opts.idpSubject) {
672
+ console.error("Error: --idp-subject <login> is required — it is the login the identity provider reports for this person.");
673
+ process.exit(1);
674
+ }
675
+ const target = mappingTarget(opts, "flair principal unlink");
676
+ try {
677
+ const result = await unlinkPrincipalMapping({
678
+ hostedOrigin: target.instance,
679
+ adminUser: target.adminUser,
680
+ adminPass: target.adminPass,
681
+ principal: principalId,
682
+ idpProvider: opts.idpProvider,
683
+ idpSubject: opts.idpSubject,
684
+ });
685
+ for (const line of result.lines)
686
+ console.log(line);
687
+ }
688
+ catch (err) {
689
+ console.error(`Error: ${err?.message ?? err}`);
690
+ process.exit(1);
691
+ }
692
+ });
693
+ principal
694
+ .command("links <principal>")
695
+ .description("List a principal's current IdP mappings on an already-enabled instance. " + MAPPING_TARGET_HELP)
696
+ .option(MAPPING_INSTANCE_OPTION, MAPPING_INSTANCE_HELP)
697
+ .option("--admin-pass <pass>", MAPPING_ADMIN_PASS_HELP)
698
+ .option("--admin-user <name>", MAPPING_ADMIN_USER_HELP)
699
+ .action(async (principalId, opts) => {
700
+ const target = mappingTarget(opts, "flair principal links");
701
+ try {
702
+ const result = await listPrincipalMappings({
703
+ hostedOrigin: target.instance,
704
+ adminUser: target.adminUser,
705
+ adminPass: target.adminPass,
706
+ principal: principalId,
707
+ });
708
+ for (const line of result.lines)
709
+ console.log(line);
710
+ }
711
+ catch (err) {
712
+ console.error(`Error: ${err?.message ?? err}`);
713
+ process.exit(1);
714
+ }
715
+ });
338
716
  }
@@ -1,3 +1,12 @@
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";
1
10
  import * as render from "../render.js";
2
11
  import { EMBEDDING_STAMP_ID, describeStampOutstanding, resolveCurrentModelId } from "../stamp-outstanding.js";
3
12
  let cli;
@@ -811,7 +820,7 @@ async function storeQualitySnapshot(agentId, agentIdSource, baseUrl, subject, sn
811
820
  type: "quality-snapshot",
812
821
  createdAt: new Date().toISOString(),
813
822
  };
814
- const out = await api("PUT", `/Memory/${encodeURIComponent(memId)}`, body, { baseUrl, agentId, agentIdSource });
823
+ const out = await api("PUT", `/Memory/${encodeRecordId(memId)}`, body, { baseUrl, agentId, agentIdSource });
815
824
  if (out?.error)
816
825
  throw new Error(String(out.error));
817
826
  return memId;