@tpsdev-ai/flair 0.59.0 → 0.62.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (259) hide show
  1. package/README.md +4 -4
  2. package/SECURITY.md +36 -0
  3. package/config.yaml +12 -1
  4. package/dist/bridges/builtins/mem0.js +63 -28
  5. package/dist/bridges/runtime/import-runner.js +12 -0
  6. package/dist/bridges/runtime/load-plugin.js +42 -13
  7. package/dist/bridges/runtime/yaml-loader.js +4 -2
  8. package/dist/build-info.json +3 -3
  9. package/dist/cli.js +991 -248
  10. package/dist/commands/agent.js +224 -43
  11. package/dist/commands/attention.js +4 -3
  12. package/dist/commands/backup.js +202 -34
  13. package/dist/commands/bridge.js +172 -119
  14. package/dist/commands/deploy.js +37 -4
  15. package/dist/commands/doctor.js +592 -146
  16. package/dist/commands/export.js +54 -19
  17. package/dist/commands/federation.js +141 -21
  18. package/dist/commands/hook.js +155 -2
  19. package/dist/commands/idp.js +14 -1
  20. package/dist/commands/import.js +7 -3
  21. package/dist/commands/init.js +462 -193
  22. package/dist/commands/integrity.js +388 -0
  23. package/dist/commands/keys.js +247 -58
  24. package/dist/commands/mcp.js +97 -35
  25. package/dist/commands/memory.js +171 -21
  26. package/dist/commands/migrate-harness-memory.js +3 -2
  27. package/dist/commands/orgevent.js +46 -37
  28. package/dist/commands/presence.js +4 -3
  29. package/dist/commands/principal.js +426 -48
  30. package/dist/commands/quality.js +10 -1
  31. package/dist/commands/reembed.js +141 -17
  32. package/dist/commands/relationship.js +2 -1
  33. package/dist/commands/rem.js +56 -18
  34. package/dist/commands/restore.js +101 -61
  35. package/dist/commands/search.js +6 -4
  36. package/dist/commands/service.js +151 -38
  37. package/dist/commands/soul.js +4 -3
  38. package/dist/commands/status.js +43 -5
  39. package/dist/commands/test.js +3 -2
  40. package/dist/commands/upgrade.js +24 -1
  41. package/dist/commands/workspace.js +6 -3
  42. package/dist/component-env.js +31 -41
  43. package/dist/deploy.js +77 -1
  44. package/dist/doctor-client.js +529 -92
  45. package/dist/engine-version-contract.js +1 -0
  46. package/dist/engine-version.js +23 -3
  47. package/dist/federation-verify.js +4 -3
  48. package/dist/hook-install.js +670 -6
  49. package/dist/keystore.js +72 -0
  50. package/dist/lib/action-recall-runtime.js +328 -0
  51. package/dist/lib/agent-home-fields.js +132 -0
  52. package/dist/lib/agent-home.js +427 -0
  53. package/dist/lib/agent-id-rule.js +46 -0
  54. package/dist/lib/agent-roster.js +33 -0
  55. package/dist/lib/auth-resolve.js +49 -16
  56. package/dist/lib/capture-runtime.js +124 -0
  57. package/dist/lib/credential-status-rule.js +78 -0
  58. package/dist/lib/daemon-liveness.js +41 -10
  59. package/dist/lib/doctor-run.js +75 -37
  60. package/dist/lib/durability-copy.js +10 -0
  61. package/dist/lib/embedding-space-doctor.js +75 -0
  62. package/dist/lib/flair-agent-role.js +4 -0
  63. package/dist/lib/hub-url.js +12 -0
  64. package/dist/lib/init-admin-pass.js +88 -12
  65. package/dist/lib/init-listener-environ.js +1 -2
  66. package/dist/lib/init-occupied-listener.js +15 -111
  67. package/dist/lib/init-spawn-attribution.js +73 -0
  68. package/dist/lib/init-tcp-probe.js +33 -0
  69. package/dist/lib/instance-identity-row.js +20 -0
  70. package/dist/lib/launchd-management.js +24 -0
  71. package/dist/lib/listener-table.js +268 -0
  72. package/dist/lib/local-delete-instance.js +27 -0
  73. package/dist/lib/local-instance-pair.js +256 -0
  74. package/dist/lib/mcp-enable.js +1168 -326
  75. package/dist/lib/mcp-oauth-env-core.js +133 -0
  76. package/dist/lib/mcp-oauth-env.js +125 -0
  77. package/dist/lib/mcp-spec.js +17 -1
  78. package/dist/lib/memory-attributes.js +2 -0
  79. package/dist/lib/memory-id-policy.js +46 -0
  80. package/dist/lib/memory-integrity.js +309 -0
  81. package/dist/lib/memory-purge-response.js +20 -0
  82. package/dist/lib/ops-table-count.js +25 -0
  83. package/dist/lib/owned-pins.js +67 -10
  84. package/dist/lib/peer-status.js +27 -0
  85. package/dist/lib/principal-status.js +29 -0
  86. package/dist/lib/process-start-time.js +76 -12
  87. package/dist/lib/proto-safe-record.js +42 -0
  88. package/dist/lib/record-id-path.js +25 -0
  89. package/dist/lib/reembed-server-support.js +66 -0
  90. package/dist/lib/restore-verify.js +104 -0
  91. package/dist/lib/scheduler-platform.js +10 -6
  92. package/dist/lib/secret-keys.js +25 -0
  93. package/dist/lib/secrets-push.js +50 -22
  94. package/dist/lib/skill-seed-pending.js +24 -0
  95. package/dist/lib/skill-seed.js +365 -0
  96. package/dist/lib/stop-start-recovery.js +54 -0
  97. package/dist/lib/using-flair-skill.js +87 -0
  98. package/dist/mcp-client-assertion.js +112 -4
  99. package/dist/memory-id-checkpoint.js +326 -0
  100. package/dist/memory-node-compare.js +207 -0
  101. package/dist/packages/flair-mcp/src/secret-redaction.js +113 -0
  102. package/dist/rem/restore.js +6 -5
  103. package/dist/rem/runner.js +103 -44
  104. package/dist/resources/Agent.js +321 -1
  105. package/dist/resources/AgentKeyRegister.js +214 -0
  106. package/dist/resources/AgentKeyRegistration.js +28 -0
  107. package/dist/resources/AgentSeed.js +10 -4
  108. package/dist/resources/AutoPromoteCandidates.js +7 -1
  109. package/dist/resources/Credential.js +177 -2
  110. package/dist/resources/Federation.js +751 -143
  111. package/dist/resources/FederationRetry.js +140 -0
  112. package/dist/resources/InstructionVersion.js +220 -0
  113. package/dist/resources/Integration.js +300 -25
  114. package/dist/resources/Memory.js +2113 -604
  115. package/dist/resources/MemoryArchive.js +75 -42
  116. package/dist/resources/MemoryBootstrap.js +110 -39
  117. package/dist/resources/MemoryCandidate.js +21 -1
  118. package/dist/resources/MemoryDedupStats.js +30 -1
  119. package/dist/resources/MemoryFeed.js +327 -45
  120. package/dist/resources/MemoryGrant.js +21 -1
  121. package/dist/resources/MemoryMaintenance.js +129 -25
  122. package/dist/resources/MemoryPurge.js +232 -0
  123. package/dist/resources/MemoryReflect.js +7 -2
  124. package/dist/resources/MemoryReindex.js +24 -8
  125. package/dist/resources/Message.js +5 -3
  126. package/dist/resources/OAuth.js +186 -9
  127. package/dist/resources/OrgEvent.js +126 -3
  128. package/dist/resources/Presence.js +144 -49
  129. package/dist/resources/PromoteMemoryCandidate.js +18 -7
  130. package/dist/resources/Relationship.js +23 -0
  131. package/dist/resources/SemanticSearch.js +63 -32
  132. package/dist/resources/Soul.js +189 -76
  133. package/dist/resources/TeamDirectory.js +35 -0
  134. package/dist/resources/WorkspaceState.js +21 -1
  135. package/dist/resources/XAA.js +181 -63
  136. package/dist/resources/agent-auth.js +40 -15
  137. package/dist/resources/auth-middleware.js +400 -161
  138. package/dist/resources/ed25519-auth.js +1 -1
  139. package/dist/resources/embedding-space-guard.js +366 -72
  140. package/dist/resources/engine-version-stamp-boot.js +53 -0
  141. package/dist/resources/federation-classify.js +72 -0
  142. package/dist/resources/federation-crypto.js +5 -5
  143. package/dist/resources/federation-retry-lib.js +135 -0
  144. package/dist/resources/grant-visibility.js +135 -0
  145. package/dist/resources/harper-routing.js +83 -0
  146. package/dist/resources/health.js +120 -18
  147. package/dist/resources/host-source-citation.js +49 -0
  148. package/dist/resources/host-source-visibility.js +7 -6
  149. package/dist/resources/instance-create-lock.js +17 -0
  150. package/dist/resources/instance-identity.js +23 -0
  151. package/dist/resources/instruction-version-record.js +343 -0
  152. package/dist/resources/key-lock.js +3 -3
  153. package/dist/resources/mcp-handler.js +36 -8
  154. package/dist/resources/mcp-oauth-env-guard.js +36 -0
  155. package/dist/resources/mcp-oauth.js +23 -6
  156. package/dist/resources/mcp-tool-arguments.js +4 -6
  157. package/dist/resources/mcp-tools.js +128 -19
  158. package/dist/resources/memory-bootstrap-lib.js +5 -15
  159. package/dist/resources/memory-declared-attributes.js +3 -1
  160. package/dist/resources/memory-deletion-history.js +55 -0
  161. package/dist/resources/memory-durability.js +54 -0
  162. package/dist/resources/memory-embed-hash.js +88 -0
  163. package/dist/resources/memory-embedding-value.js +8 -0
  164. package/dist/resources/memory-host-source.js +27 -5
  165. package/dist/resources/memory-id-guard.js +75 -0
  166. package/dist/resources/memory-redaction.js +236 -0
  167. package/dist/resources/memory-supplied-vector.js +72 -0
  168. package/dist/resources/memory-write-lock.js +310 -0
  169. package/dist/resources/memory-write-response.js +139 -0
  170. package/dist/resources/migrations/data-dir.js +74 -16
  171. package/dist/resources/migrations/dir-safety.js +1 -1
  172. package/dist/resources/migrations/embedding-stamp.js +193 -79
  173. package/dist/resources/migrations/export.js +1 -0
  174. package/dist/resources/migrations/graph-heal.js +18 -25
  175. package/dist/resources/migrations/lock.js +7 -1
  176. package/dist/resources/migrations/snapshot.js +1 -0
  177. package/dist/resources/migrations/source-fields.js +5 -5
  178. package/dist/resources/migrations/synthetic-test-migration.js +14 -11
  179. package/dist/resources/migrations/visibility-backfill.js +29 -29
  180. package/dist/resources/object-body-guard.js +33 -0
  181. package/dist/resources/org-event-created-at.js +133 -0
  182. package/dist/resources/originator-instance.js +39 -7
  183. package/dist/resources/owner-delete-recheck.js +78 -0
  184. package/dist/resources/owner-field-guard.js +39 -5
  185. package/dist/resources/owner-scoped-write-policy.js +212 -0
  186. package/dist/resources/owner-scoped-writes.js +58 -0
  187. package/dist/resources/presence-receipt.js +236 -0
  188. package/dist/resources/promotion-stamp.js +47 -12
  189. package/dist/resources/record-owner-guard.js +74 -26
  190. package/dist/resources/record-types.js +1 -1
  191. package/dist/resources/relay-ops.js +78 -6
  192. package/dist/resources/replay-store.js +96 -19
  193. package/dist/resources/request-target.js +136 -0
  194. package/dist/resources/request-transaction.js +35 -0
  195. package/dist/resources/search-readiness.js +4 -1
  196. package/dist/resources/seed-ids.js +9 -0
  197. package/dist/resources/seed-reservation.js +117 -0
  198. package/dist/resources/semantic-retrieval-core.js +20 -9
  199. package/dist/resources/skill-manifest.js +20 -11
  200. package/dist/resources/skill-subject.js +53 -0
  201. package/dist/resources/skill-version-write.js +432 -0
  202. package/dist/resources/skill-write-fault.js +17 -0
  203. package/dist/resources/skill-write-policy.js +67 -0
  204. package/dist/resources/skill-write.js +67 -7
  205. package/dist/resources/table-helpers.js +10 -7
  206. package/dist/resources/team-directory.js +248 -0
  207. package/dist/resources/tool-descriptors/index.js +69 -8
  208. package/dist/resources/txn-pause-point.js +118 -0
  209. package/dist/resources/usage-recording.js +171 -63
  210. package/dist/resources/write-back.js +218 -0
  211. package/dist/src/engine-version-contract.js +1 -0
  212. package/dist/src/keystore.js +72 -0
  213. package/dist/src/lib/agent-home-fields.js +132 -0
  214. package/dist/src/lib/agent-id-rule.js +46 -0
  215. package/dist/src/lib/agent-key-register.js +80 -0
  216. package/dist/src/lib/atomic-write.js +256 -0
  217. package/dist/src/lib/credential-status-rule.js +78 -0
  218. package/dist/src/lib/expired-by-agent.js +37 -0
  219. package/dist/src/lib/flair-agent-role.js +4 -0
  220. package/dist/src/lib/idp-mapping-rule.js +81 -0
  221. package/dist/src/lib/instance-identity-row.js +20 -0
  222. package/dist/src/lib/mcp-oauth-env-core.js +133 -0
  223. package/dist/src/lib/memory-attributes.js +2 -0
  224. package/dist/src/lib/memory-id-policy.js +46 -0
  225. package/dist/src/lib/principal-status.js +29 -0
  226. package/dist/src/lib/proto-safe-record.js +42 -0
  227. package/dist/src/lib/reembed-server-support.js +66 -0
  228. package/dist/src/lib/scheduler-platform.js +10 -6
  229. package/dist/src/lib/systemd-agent-id.js +38 -0
  230. package/docs/access-control.md +146 -45
  231. package/docs/api-reference.md +46 -11
  232. package/docs/auth.md +6 -12
  233. package/docs/bridges.md +11 -0
  234. package/docs/claude-code.md +34 -4
  235. package/docs/deploying-on-fabric.md +70 -0
  236. package/docs/deployment.md +2 -0
  237. package/docs/embedding-in-a-harper-app.md +1 -1
  238. package/docs/federation.md +33 -2
  239. package/docs/hosted-on-fabric.md +43 -36
  240. package/docs/integrations.md +5 -5
  241. package/docs/mcp-clients.md +5 -2
  242. package/docs/n8n.md +17 -11
  243. package/docs/notes/mcp-agent-auth-consumer.md +12 -4
  244. package/docs/notes/mcp-oauth-model2.md +34 -5
  245. package/docs/quickstart-fabric.md +2 -2
  246. package/docs/quickstart.md +9 -1
  247. package/docs/releasing.md +12 -6
  248. package/docs/rem.md +8 -0
  249. package/docs/secrets-and-keys.md +19 -2
  250. package/docs/standalone-local.md +1 -0
  251. package/docs/supply-chain-policy.md +13 -3
  252. package/docs/upgrade.md +32 -6
  253. package/package.json +10 -5
  254. package/schemas/agent-key-registration.graphql +22 -0
  255. package/schemas/agent.graphql +3 -0
  256. package/schemas/federation.graphql +38 -1
  257. package/schemas/memory.graphql +84 -5
  258. package/schemas/oauth.graphql +19 -0
  259. package/schemas/schema.graphql +2 -0
@@ -1,26 +1,118 @@
1
1
  import * as render from "../render.js";
2
- import { resolveKeyPath, buildEd25519Auth } from "../lib/auth-resolve.js";
2
+ import { resolveKeyPath, buildEd25519Auth, readSecretFileSecure, requestTarget, requestUrl } from "../lib/auth-resolve.js";
3
+ import { encodeRecordId } from "../lib/record-id-path.js";
4
+ import { protoSafeRecord } from "../lib/proto-safe-record.js";
3
5
  let cli;
4
- /**
5
- * Percent-encode a Memory id so it addresses exactly that record as ONE path
6
- * segment (flair#1970). REFUSES an id that is exactly `.` or `..`: percent-
7
- * encoding leaves those unchanged and URL normalization collapses `/Memory/.`
8
- * to `/Memory/` and `/Memory/..` to `/`, so the sent path would not be the id
9
- * (nor the signed path). Such an id cannot address its record.
10
- */
11
- function encodeRecordId(id) {
12
- if (id === "." || id === "..") {
13
- throw new Error(`record id ${JSON.stringify(id)} is a URL path dot-segment ("." or ".."); ` +
14
- `it cannot be addressed as one path segment of /Memory/<id>. Use a different id.`);
15
- }
16
- return encodeURIComponent(id);
17
- }
18
6
  /** Bind shared CLI helpers. cli.ts calls this immediately before register(program). */
19
7
  export function bindCli(fns) {
20
8
  cli = fns;
21
9
  }
22
10
  const api = (method, path, body, options) => cli.api(method, path, body, options);
23
11
  const resolveHttpPort = (opts, mode) => cli.resolveHttpPort(opts, mode);
12
+ function redactBridgeSecret(value, secret) {
13
+ if (!secret)
14
+ return value;
15
+ const forms = new Set();
16
+ for (let form = secret; form.length <= value.length && !forms.has(form); form = JSON.stringify(form).slice(1, -1)) {
17
+ forms.add(form);
18
+ }
19
+ try {
20
+ forms.add(encodeURIComponent(secret));
21
+ }
22
+ catch { }
23
+ if (!forms.size)
24
+ return value;
25
+ const pattern = [...forms].sort((a, b) => b.length - a.length)
26
+ .map((form) => form.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|");
27
+ return value.replace(new RegExp(pattern, "g"), "[REDACTED]");
28
+ }
29
+ /** Serialize first, then redact so object keys and values share one boundary. */
30
+ export function serializeBridgeLogLine(event, secret) {
31
+ return redactBridgeSecret(JSON.stringify(event), secret);
32
+ }
33
+ function formatTrustErrorLines(detail, secret) {
34
+ const lines = [];
35
+ const write = (line = "") => { lines.push(line); };
36
+ const name = detail.bridge ?? "(unknown)";
37
+ const ctx = detail.context ?? {};
38
+ const reapprove = ` flair bridge allow ${name}`;
39
+ const bar = "─".repeat(60);
40
+ const header = (title) => {
41
+ write();
42
+ write(`⚠ ${title} — ${name}`);
43
+ write(bar);
44
+ };
45
+ const footer = (label) => {
46
+ write();
47
+ write(`${label}:`);
48
+ write(reapprove);
49
+ write();
50
+ };
51
+ switch (detail.got) {
52
+ case "not-allowed":
53
+ header("Approval required");
54
+ write("This bridge is an npm code plugin — it runs arbitrary JavaScript.");
55
+ write("First-use approval is required before Flair will execute it.");
56
+ footer("Approve it with");
57
+ break;
58
+ case "path-mismatch":
59
+ header("Trust check failed: package location changed");
60
+ write("A different package with the same name was discovered. This is how");
61
+ write("local squatting attacks present — a planted `node_modules/flair-bridge-*`");
62
+ write("in an unrelated project tree.");
63
+ write();
64
+ write(` approved: ${ctx.approvedPath ?? "(unknown)"}`);
65
+ write(` version ${ctx.approvedVersion ?? "?"} at ${ctx.approvedAt ?? "?"}`);
66
+ write(` now: ${ctx.observedPath ?? "(unknown)"}`);
67
+ footer("If the new location is intentional, re-approve");
68
+ break;
69
+ case "digest-mismatch":
70
+ header("Trust check failed: package contents changed");
71
+ write("The package.json at the approved location has changed since you");
72
+ write("approved this bridge. This fires on every upgrade — it's a trust");
73
+ write("event, not an error. If the update is intentional, re-approve.");
74
+ write();
75
+ write(` location: ${ctx.packagePath ?? "(unknown)"}`);
76
+ write(` approved version: ${ctx.approvedVersion ?? "?"} (at ${ctx.approvedAt ?? "?"})`);
77
+ write(` approved digest: sha256:${(ctx.approvedDigest ?? "").slice(0, 16)}…`);
78
+ write(` observed digest: sha256:${(ctx.observedDigest ?? "").slice(0, 16)}…`);
79
+ footer("Re-approve");
80
+ break;
81
+ case "entry-incomplete":
82
+ header("Trust check failed: approval record is incomplete");
83
+ write("The allow-list entry for this bridge is missing a location or digest.");
84
+ write("This usually means the record was created by a pre-fix Flair version");
85
+ write("(0.6.0 / 0.6.1) that only stored the name. Re-approve to upgrade.");
86
+ footer("Re-approve");
87
+ break;
88
+ case "package-missing":
89
+ header("Trust check failed: approved package missing on disk");
90
+ write("The package location recorded at allow-time is no longer readable.");
91
+ write();
92
+ write(` approved at: ${ctx.approvedPath ?? "(unknown)"}`);
93
+ write(` discovered: ${ctx.discoveredPath ?? "(unknown)"}`);
94
+ footer("Reinstall the package, then re-approve");
95
+ break;
96
+ default:
97
+ // Unknown trust sub-reason — fall back to the raw structured print.
98
+ write(`Bridge error (trust): ${detail.hint ?? detail.got ?? "unknown"}`);
99
+ write(JSON.stringify(detail, null, 2));
100
+ }
101
+ return lines.map((line) => redactBridgeSecret(line, secret));
102
+ }
103
+ export function formatBridgeErrorLines(err, secret = "") {
104
+ const detail = err?.detail;
105
+ if (detail && typeof detail === "object") {
106
+ if (detail.field === "(trust)") {
107
+ return formatTrustErrorLines(detail, secret);
108
+ }
109
+ return [
110
+ redactBridgeSecret(`Bridge error: ${detail.hint ?? err.message}`, secret),
111
+ redactBridgeSecret(JSON.stringify(detail, null, 2), secret),
112
+ ];
113
+ }
114
+ return [redactBridgeSecret(`Bridge error: ${err.message ?? String(err)}`, secret)];
115
+ }
24
116
  /** Register the `flair bridge` command group. */
25
117
  export function register(program) {
26
118
  // ─── flair bridge ────────────────────────────────────────────────────────────
@@ -118,6 +210,9 @@ export function register(program) {
118
210
  .option("--url <url>", "Flair base URL (overrides --port)")
119
211
  .option("--key <path>", "Ed25519 private key path (default: resolved from agent)")
120
212
  .option("--source <path>", "Source directory (for directory-based imports like markdown)")
213
+ .option("--user <id>", "Foreign-system user id for bridges that import one user (e.g. mem0)")
214
+ .option("--base-url <url>", "Base URL of the foreign API for API bridges (e.g. a self-hosted mem0)")
215
+ .option("--api-key-file <path>", "For API bridges with an apiKey option, read the key from a file that has no group/world permissions (chmod 600 recommended); or, if the bridge declares an environment variable, set that instead (e.g. MEM0_API_KEY).")
121
216
  .action(async (name, srcArg, opts) => {
122
217
  const agentId = opts.agent ?? process.env.FLAIR_AGENT_ID;
123
218
  const cwd = opts.cwd ?? srcArg ?? process.cwd();
@@ -133,12 +228,14 @@ export function register(program) {
133
228
  console.error(`No bridge named "${name}" — run \`flair bridge list\` to see installed bridges.`);
134
229
  process.exit(1);
135
230
  }
231
+ let bridgeApiKey = name === "mem0" ? process.env.MEM0_API_KEY ?? "" : "";
232
+ const safe = (value) => redactBridgeSecret(value, bridgeApiKey);
136
233
  let loaded;
137
234
  try {
138
235
  loaded = await loadBridge(target);
139
236
  }
140
237
  catch (err) {
141
- printBridgeError(err);
238
+ printBridgeError(err, bridgeApiKey);
142
239
  process.exit(1);
143
240
  }
144
241
  const baseUrl = opts.url ?? `http://127.0.0.1:${resolveHttpPort(opts)}`;
@@ -147,16 +244,26 @@ export function register(program) {
147
244
  // for an empty or dry-run import, and including a bare trailing "?" or "#"
148
245
  // (new URL reports those as an empty search/hash, but the join would drop
149
246
  // the base's path). The route's own query string is what gets signed. #1970.
150
- const parsedBase = new URL(baseUrl);
247
+ let parsedBase;
248
+ try {
249
+ parsedBase = new URL(baseUrl);
250
+ }
251
+ catch {
252
+ console.error(safe("Bridge import failed: the Flair base URL must be a valid URL."));
253
+ process.exit(1);
254
+ }
151
255
  if (parsedBase.href.includes("?") || parsedBase.href.includes("#")) {
152
- console.error(`Bridge import failed: refusing base URL "${baseUrl}": a Flair base URL must not carry a query string or fragment.`);
256
+ console.error(safe(`Bridge import failed: refusing base URL "${baseUrl}": a Flair base URL must not carry a query string or fragment.`));
153
257
  process.exit(1);
154
258
  }
155
259
  // Routes join against the PARSED base, which new URL() has normalized (for
156
260
  // example surrounding whitespace removed), so the path sent is the path the
157
261
  // base names.
158
262
  const joinBase = `${parsedBase.href.replace(/\/+$/, "")}/`;
159
- const ctx = makeContext({ bridge: name });
263
+ const ctx = makeContext({
264
+ bridge: name,
265
+ emit: (event) => process.stderr.write(serializeBridgeLogLine(event, bridgeApiKey) + "\n"),
266
+ });
160
267
  // Memory POST: Ed25519-signed when an agent key is available, fall back
161
268
  // to the shared `api()` helper otherwise. Mirrors how `flair memory add`
162
269
  // works (see the `memory.command("add")` handler above).
@@ -181,8 +288,7 @@ export function register(program) {
181
288
  body: JSON.stringify(body),
182
289
  });
183
290
  if (!res.ok) {
184
- const text = await res.text().catch(() => "");
185
- throw new Error(`PUT ${signedPath} → ${res.status}: ${text || res.statusText}`);
291
+ throw new Error(`PUT /Memory → HTTP ${res.status}: Flair rejected the write`);
186
292
  }
187
293
  };
188
294
  let lastReportedAt = Date.now();
@@ -193,10 +299,10 @@ export function register(program) {
193
299
  if (ev.type === "done") {
194
300
  const noun = (n) => `${n} ${n === 1 ? "memory" : "memories"}`;
195
301
  if (opts.dryRun) {
196
- console.log(`\n${target.name}: would import ${noun(ev.total)}. Re-run without --dry-run to write to Flair.`);
302
+ console.log(safe(`\n${target.name}: would import ${noun(ev.total)}. Re-run without --dry-run to write to Flair.`));
197
303
  }
198
304
  else {
199
- console.log(`\n${target.name}: imported ${ev.imported}/${ev.total} memories${ev.skipped > 0 ? ` (${ev.skipped} skipped)` : ""}.`);
305
+ console.log(safe(`\n${target.name}: imported ${ev.imported}/${ev.total} memories${ev.skipped > 0 ? ` (${ev.skipped} skipped)` : ""}.`));
200
306
  }
201
307
  return;
202
308
  }
@@ -206,14 +312,17 @@ export function register(program) {
206
312
  lastReportedAt = now;
207
313
  lastReportedOrdinal = ev.ordinal;
208
314
  if (ev.type === "memory-imported") {
209
- process.stdout.write(`\r ${ev.ordinal} imported (${ev.foreignId ?? ev.flairId})`.padEnd(80));
315
+ process.stdout.write(safe(`\r ${ev.ordinal} imported (${ev.foreignId ?? ev.flairId})`.padEnd(80)));
210
316
  }
211
317
  else if (ev.type === "memory-skipped") {
212
- process.stdout.write(`\r ${ev.ordinal} skipped (${ev.reason})`.padEnd(80));
318
+ process.stdout.write(safe(`\r ${ev.ordinal} skipped (${ev.reason})`.padEnd(80)));
213
319
  }
214
320
  };
215
321
  try {
216
322
  if (loaded.kind === "yaml") {
323
+ if (opts.apiKeyFile !== undefined) {
324
+ throw new Error("--api-key-file requires an API bridge with an apiKey option; YAML imports cannot use it");
325
+ }
217
326
  await runImport({
218
327
  bridgeName: target.name,
219
328
  descriptor: loaded.descriptor,
@@ -229,13 +338,37 @@ export function register(program) {
229
338
  // Code plugin: invoke bridge.import(opts, ctx) directly; the plugin
230
339
  // returns an AsyncIterable of BridgeMemory that runImport processes.
231
340
  if (!loaded.plugin.import) {
232
- console.error(`Bridge "${name}" is a code plugin without an import() function — can only export through it.`);
341
+ console.error(safe(`Bridge "${name}" is a code plugin without an import() function — can only export through it.`));
233
342
  process.exit(1);
234
343
  }
235
- // Code-plugin options: pass through all --X flags as a single object.
236
- // The plugin's declared `options` descriptor validates what it actually cares about.
237
- const pluginOpts = { ...opts };
238
- const source = loaded.plugin.import(pluginOpts, ctx);
344
+ // Code-plugin options: start from the parsed flags, then use only
345
+ // the declared `env` entries as fallbacks. The CLI does not apply
346
+ // descriptor `default` or `required` entries here:
347
+ // - an option no flag set falls back to the env var it names
348
+ // (`BridgeOptionSpec.env`, e.g. MEM0_API_KEY);
349
+ // - `--api-key-file` fills a declared `apiKey` option, read here so
350
+ // the secret never appears in argv (group/world access refused).
351
+ const pluginImportOpts = protoSafeRecord(opts);
352
+ const declaredOptions = loaded.plugin.options ?? {};
353
+ if (opts.apiKeyFile !== undefined) {
354
+ if (!declaredOptions.apiKey) {
355
+ throw new Error("--api-key-file requires an API bridge with an apiKey option");
356
+ }
357
+ if (typeof opts.apiKeyFile !== "string" || opts.apiKeyFile.trim() === "") {
358
+ throw new Error("--api-key-file requires a non-empty path");
359
+ }
360
+ }
361
+ for (const [key, spec] of Object.entries(declaredOptions)) {
362
+ if (pluginImportOpts[key] === undefined && spec.env && process.env[spec.env] !== undefined) {
363
+ pluginImportOpts[key] = process.env[spec.env];
364
+ }
365
+ }
366
+ if (opts.apiKeyFile !== undefined) {
367
+ pluginImportOpts.apiKey = readSecretFileSecure(opts.apiKeyFile, "--api-key-file");
368
+ }
369
+ if (typeof pluginImportOpts.apiKey === "string")
370
+ bridgeApiKey = pluginImportOpts.apiKey;
371
+ const source = loaded.plugin.import(pluginImportOpts, ctx);
239
372
  await runImport({
240
373
  bridgeName: target.name,
241
374
  source,
@@ -250,10 +383,10 @@ export function register(program) {
250
383
  }
251
384
  catch (err) {
252
385
  if (err instanceof BridgeRuntimeError) {
253
- printBridgeError(err);
386
+ printBridgeError(err, bridgeApiKey);
254
387
  process.exit(1);
255
388
  }
256
- console.error(`Bridge import failed: ${err?.message ?? err}`);
389
+ console.error(safe(`Bridge import failed: ${err?.message ?? err}`));
257
390
  process.exit(1);
258
391
  }
259
392
  });
@@ -317,9 +450,10 @@ export function register(program) {
317
450
  const headers = { "content-type": "application/json" };
318
451
  const keyPath = opts.key ?? resolveKeyPath(agentId);
319
452
  const path = `/Memory?${params.toString()}`;
453
+ const url = requestUrl(baseUrl, path);
320
454
  if (keyPath)
321
- headers["authorization"] = buildEd25519Auth(agentId, "GET", path, keyPath);
322
- const res = await fetch(`${baseUrl}${path}`, { headers });
455
+ headers["authorization"] = buildEd25519Auth(agentId, "GET", requestTarget(url), keyPath);
456
+ const res = await fetch(url, { headers });
323
457
  if (!res.ok) {
324
458
  const text = await res.text().catch(() => "");
325
459
  throw new Error(`GET /Memory → ${res.status}: ${text || res.statusText}`);
@@ -555,91 +689,10 @@ export function register(program) {
555
689
  console.log();
556
690
  }
557
691
  });
558
- function printBridgeError(err) {
692
+ function printBridgeError(err, secret = "") {
559
693
  // Pretty-print BridgeRuntimeError as the structured shape from §10 of the
560
- // spec, plus a one-line human summary so the operator gets both.
561
- const detail = err?.detail;
562
- if (detail && typeof detail === "object") {
563
- // Trust-check failures get a dedicated, operator-facing rendering.
564
- // Dumping the full spec-§10 JSON is useful when an operator is
565
- // debugging a broken YAML descriptor; for trust errors it buries the
566
- // one thing that matters — the command to re-approve.
567
- if (detail.field === "(trust)") {
568
- printTrustError(detail);
569
- return;
570
- }
571
- console.error(`Bridge error: ${detail.hint ?? err.message}`);
572
- console.error(JSON.stringify(detail, null, 2));
573
- }
574
- else {
575
- console.error(`Bridge error: ${err.message ?? String(err)}`);
576
- }
577
- }
578
- function printTrustError(detail) {
579
- const name = detail.bridge ?? "(unknown)";
580
- const ctx = detail.context ?? {};
581
- const reapprove = ` flair bridge allow ${name}`;
582
- const bar = "─".repeat(60);
583
- const header = (title) => {
584
- console.error("");
585
- console.error(`⚠ ${title} — ${name}`);
586
- console.error(bar);
587
- };
588
- const footer = (label) => {
589
- console.error("");
590
- console.error(`${label}:`);
591
- console.error(reapprove);
592
- console.error("");
593
- };
594
- switch (detail.got) {
595
- case "not-allowed":
596
- header("Approval required");
597
- console.error("This bridge is an npm code plugin — it runs arbitrary JavaScript.");
598
- console.error("First-use approval is required before Flair will execute it.");
599
- footer("Approve it with");
600
- return;
601
- case "path-mismatch":
602
- header("Trust check failed: package location changed");
603
- console.error("A different package with the same name was discovered. This is how");
604
- console.error("local squatting attacks present — a planted `node_modules/flair-bridge-*`");
605
- console.error("in an unrelated project tree.");
606
- console.error("");
607
- console.error(` approved: ${ctx.approvedPath ?? "(unknown)"}`);
608
- console.error(` version ${ctx.approvedVersion ?? "?"} at ${ctx.approvedAt ?? "?"}`);
609
- console.error(` now: ${ctx.observedPath ?? "(unknown)"}`);
610
- footer("If the new location is intentional, re-approve");
611
- return;
612
- case "digest-mismatch":
613
- header("Trust check failed: package contents changed");
614
- console.error("The package.json at the approved location has changed since you");
615
- console.error("approved this bridge. This fires on every upgrade — it's a trust");
616
- console.error("event, not an error. If the update is intentional, re-approve.");
617
- console.error("");
618
- console.error(` location: ${ctx.packagePath ?? "(unknown)"}`);
619
- console.error(` approved version: ${ctx.approvedVersion ?? "?"} (at ${ctx.approvedAt ?? "?"})`);
620
- console.error(` approved digest: sha256:${(ctx.approvedDigest ?? "").slice(0, 16)}…`);
621
- console.error(` observed digest: sha256:${(ctx.observedDigest ?? "").slice(0, 16)}…`);
622
- footer("Re-approve");
623
- return;
624
- case "entry-incomplete":
625
- header("Trust check failed: approval record is incomplete");
626
- console.error("The allow-list entry for this bridge is missing a location or digest.");
627
- console.error("This usually means the record was created by a pre-fix Flair version");
628
- console.error("(0.6.0 / 0.6.1) that only stored the name. Re-approve to upgrade.");
629
- footer("Re-approve");
630
- return;
631
- case "package-missing":
632
- header("Trust check failed: approved package missing on disk");
633
- console.error("The package location recorded at allow-time is no longer readable.");
634
- console.error("");
635
- console.error(` approved at: ${ctx.approvedPath ?? "(unknown)"}`);
636
- console.error(` discovered: ${ctx.discoveredPath ?? "(unknown)"}`);
637
- footer("Reinstall the package, then re-approve");
638
- return;
639
- default:
640
- // Unknown trust sub-reason — fall back to the raw structured print.
641
- console.error(`Bridge error (trust): ${detail.hint ?? detail.got ?? "unknown"}`);
642
- console.error(JSON.stringify(detail, null, 2));
643
- }
694
+ // spec. Trust failures retain their dedicated operator-facing rendering.
695
+ for (const line of formatBridgeErrorLines(err, secret))
696
+ console.error(line);
644
697
  }
645
698
  }
@@ -1,5 +1,6 @@
1
1
  import { buildTargetUrl as buildDeployUrl, deploy as deployToFabric, validateOptions as validateDeployOptions } from "../deploy.js";
2
2
  import { renderFleetSweepTable, sweepFleet } from "../fleet-verify.js";
3
+ import { readCheckpointFile, verifyCheckpoint } from "../memory-id-checkpoint.js";
3
4
  let cli;
4
5
  /** Bind the cli-locals this module depends on. */
5
6
  export function bindCli(fns) {
@@ -14,6 +15,18 @@ function resolveFabricCredentials(...args) {
14
15
  function shouldRunFleetVerify(...args) {
15
16
  return cli.shouldRunFleetVerify(...args);
16
17
  }
18
+ /** Quote one value for a POSIX shell command operators can copy verbatim. */
19
+ function shellSingleQuote(value) {
20
+ return `'${value.replace(/'/g, `'\\''`)}'`;
21
+ }
22
+ /** Print the same next steps after a successful deploy and in the CLI example test. */
23
+ export function printDeployNextSteps(url) {
24
+ const dim = (s) => `\x1b[2m${s}\x1b[0m`;
25
+ console.log(`\nNext steps:`);
26
+ console.log(dim(` 1. Set an admin password in Fabric Studio (Cluster Settings → Admin)`));
27
+ console.log(dim(` 2. Save that password in an owner-only file (chmod 600), then seed your first agent:`));
28
+ console.log(` flair agent add my-agent --target ${shellSingleQuote(url)} --admin-pass-file /path/to/admin-password`);
29
+ }
17
30
  export function register(program) {
18
31
  // ─── flair deploy ─────────────────────────────────────────────────────────────
19
32
  // NOTE on env-var naming for `flair deploy`: the FABRIC_* env vars below intentionally
@@ -44,6 +57,8 @@ export function register(program) {
44
57
  .option("--no-verify", "Skip post-deploy served-API verification (default: verify — on by design, so the CLI can't report success on an empty/broken deploy)")
45
58
  .option("--verify-timeout <ms>", "Milliseconds to wait for the served API to settle after harper's post-deploy restart before verifying (default: 300000)")
46
59
  .option("--verify-resource <name>", "Resource to verify is serving after deploy (repeatable; default: derived from the deployed package's dist/resources)", (val, prev) => [...prev, val], [])
60
+ .option("--ops-target <url>", "Operations API URL override for the Memory checkpoint report (env: FLAIR_OPS_TARGET)")
61
+ .option("--memory-checkpoint <path>", "After deploy, verify this instance's Memory ids against a `flair memory checkpoint` file and add a Memory id/tier check line to the report")
47
62
  .option("--deploy-retries <n>", "Retry the full harper deploy this many times, ONLY when peer replication is positively observed not to converge (default: 0 — retrying re-runs harper's component install and can escalate a transient replication warning into a hard ENOTEMPTY install failure; see flair#878)", "0")
48
63
  .option("--ignore-replication-errors", "If peer replication still hasn't converged, treat it as a non-fatal warning and succeed with an origin-only deploy (the peer catches up via federation sync or a later deploy)")
49
64
  .option("--no-convergence-check", "Skip the post-replication-error convergence poll and fail on harper's error verbatim (default: poll — Harper replicates asynchronously, so its error is a snapshot, not a verdict; flair#878)")
@@ -123,6 +138,27 @@ export function register(program) {
123
138
  }
124
139
  console.log(`\n URL: ${result.url}`);
125
140
  console.log(` Project: ${result.project}`);
141
+ if (opts.memoryCheckpoint) {
142
+ const read = readCheckpointFile(opts.memoryCheckpoint);
143
+ if (read.kind === "ok") {
144
+ const data = await verifyCheckpoint({
145
+ checkpoint: read.checkpoint,
146
+ target: result.url,
147
+ opsTarget: cli.resolveEffectiveOpsUrl({ target: result.url, opsTarget: opts.opsTarget }),
148
+ user: deployOpts.fabricUser,
149
+ password: deployOpts.fabricPassword,
150
+ });
151
+ const color = data.outcome === "verified" ? green : data.outcome === "integrity-failure" ? red : yellow;
152
+ console.log(` ${color(`Memory id/tier check: ${data.detail}`)}`);
153
+ }
154
+ else {
155
+ const why = read.kind === "absent" ? `no checkpoint at ${opts.memoryCheckpoint}` : `checkpoint unreadable: ${read.reason}`;
156
+ console.log(` ${yellow(`Memory id/tier check: unknown — ${why}`)}`);
157
+ }
158
+ }
159
+ else {
160
+ console.log(dim(" Memory id/tier check: not checked (pass --memory-checkpoint <path>)"));
161
+ }
126
162
  // ── Post-deploy fleet sweep (flair#636) ─────────────────────────────
127
163
  // Harper's own "Successfully deployed" (and the served-API verify
128
164
  // above) only confirm the ORIGIN. This sweeps the origin + every known
@@ -153,10 +189,7 @@ export function register(program) {
153
189
  process.exit(sweep.exitCode);
154
190
  }
155
191
  }
156
- console.log(`\nNext steps:`);
157
- console.log(dim(` 1. Set an admin password in Fabric Studio (Cluster Settings → Admin)`));
158
- console.log(dim(` 2. Seed your first agent:`));
159
- console.log(` flair agent add --remote ${result.url} --name my-agent`);
192
+ printDeployNextSteps(result.url);
160
193
  }
161
194
  catch (err) {
162
195
  console.error(red(`\n✗ deploy failed: ${err.message}`));