@tpsdev-ai/flair 0.62.0 → 0.63.1

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 (257) hide show
  1. package/README.md +14 -13
  2. package/SECURITY.md +73 -43
  3. package/config.yaml +11 -11
  4. package/dist/bridges/runtime/execute.js +1 -0
  5. package/dist/bridges/runtime/import-runner.js +4 -0
  6. package/dist/bridges/types.js +1 -0
  7. package/dist/build-info.json +3 -3
  8. package/dist/cli.js +309 -205
  9. package/dist/commands/agent.js +325 -137
  10. package/dist/commands/attention.js +2 -0
  11. package/dist/commands/backup-approval.js +218 -0
  12. package/dist/commands/backup.js +37 -33
  13. package/dist/commands/bootstrap.js +5 -1
  14. package/dist/commands/bridge.js +10 -0
  15. package/dist/commands/deploy.js +37 -7
  16. package/dist/commands/doctor.js +206 -42
  17. package/dist/commands/export.js +144 -15
  18. package/dist/commands/federation.js +653 -68
  19. package/dist/commands/grant.js +5 -6
  20. package/dist/commands/help.js +25 -0
  21. package/dist/commands/idp.js +14 -19
  22. package/dist/commands/import.js +167 -34
  23. package/dist/commands/init.js +380 -164
  24. package/dist/commands/integrity.js +5 -6
  25. package/dist/commands/keys.js +12 -8
  26. package/dist/commands/mcp.js +157 -79
  27. package/dist/commands/memory.js +38 -17
  28. package/dist/commands/migrate-harness-memory.js +9 -3
  29. package/dist/commands/orgevent.js +5 -10
  30. package/dist/commands/principal.js +32 -39
  31. package/dist/commands/quality.js +26 -3
  32. package/dist/commands/reembed.js +468 -111
  33. package/dist/commands/rem.js +484 -65
  34. package/dist/commands/restore.js +352 -44
  35. package/dist/commands/search.js +2 -0
  36. package/dist/commands/service.js +109 -2
  37. package/dist/commands/soul.js +0 -6
  38. package/dist/commands/status.js +165 -124
  39. package/dist/commands/test.js +4 -1
  40. package/dist/commands/upgrade.js +53 -22
  41. package/dist/commands/workspace.js +7 -8
  42. package/dist/deploy.js +59 -3
  43. package/dist/doctor-client.js +9 -25
  44. package/dist/fabric-upgrade.js +12 -2
  45. package/dist/federation/presence-send.js +139 -0
  46. package/dist/federation/scheduler.js +148 -12
  47. package/dist/federation-verify.js +269 -177
  48. package/dist/install/clients.js +171 -35
  49. package/dist/keystore.js +77 -10
  50. package/dist/lib/agent-id-rule.js +44 -2
  51. package/dist/lib/agent-key-file.js +509 -0
  52. package/dist/lib/agent-rotation-lock.js +249 -0
  53. package/dist/lib/atomic-write.js +3 -3
  54. package/dist/lib/auth-resolve.js +1040 -64
  55. package/dist/lib/backup-approval-store.js +612 -0
  56. package/dist/lib/backup-artifact.js +343 -0
  57. package/dist/lib/config-critical-section.js +212 -25
  58. package/dist/lib/connect-phase.js +33 -0
  59. package/dist/lib/daemon-liveness.js +2 -1
  60. package/dist/lib/federation-pair-access.js +4 -0
  61. package/dist/lib/federation-retry-queue.js +283 -0
  62. package/dist/lib/federation-retry-row.js +101 -0
  63. package/dist/lib/instruction-event-contract.js +17 -0
  64. package/dist/lib/instruction-event-doctor.js +102 -0
  65. package/dist/lib/key-dir.js +203 -0
  66. package/dist/lib/launchd-management.js +21 -6
  67. package/dist/lib/local-instance-pair.js +8 -1
  68. package/dist/lib/mcp-enable.js +14 -15
  69. package/dist/lib/memory-attributes.js +2 -0
  70. package/dist/lib/memory-provider-timeout.js +33 -0
  71. package/dist/lib/mqtt-config.js +132 -0
  72. package/dist/lib/mqtt-listener-doctor.js +104 -0
  73. package/dist/lib/node-alias-path.js +50 -2
  74. package/dist/lib/open-live-row.js +20 -0
  75. package/dist/lib/ops-url.js +52 -0
  76. package/dist/lib/promotion-content-hash.js +20 -0
  77. package/dist/lib/remote-admin-pass.js +157 -0
  78. package/dist/lib/restore-archive.js +760 -0
  79. package/dist/lib/restore-verify.js +1 -1
  80. package/dist/lib/scheduler-platform.js +13 -0
  81. package/dist/lib/service-repoint.js +13 -4
  82. package/dist/lib/skill-assignment-preflight.js +159 -0
  83. package/dist/lib/skill-seed.js +125 -10
  84. package/dist/lib/skill-tombstone-doctor.js +133 -0
  85. package/dist/lib/soul-scope-fields.js +26 -0
  86. package/dist/lib/terminal-text.js +32 -0
  87. package/dist/lib/uninstall-purge.js +266 -11
  88. package/dist/lib/upgrade-prior-liveness.js +2 -1
  89. package/dist/mcp-client-assertion.js +7 -14
  90. package/dist/memory-id-checkpoint.js +28 -7
  91. package/dist/mqtt-off-deploy.js +550 -0
  92. package/dist/rem/promote-policy.js +3 -3
  93. package/dist/rem/restore.js +302 -26
  94. package/dist/rem/runner.js +220 -58
  95. package/dist/rem/scheduler.js +21 -4
  96. package/dist/resources/A2AAdapter.js +131 -178
  97. package/dist/resources/AdminMemory.js +2 -0
  98. package/dist/resources/AdminMemoryCandidates.js +116 -0
  99. package/dist/resources/Agent.js +155 -45
  100. package/dist/resources/AgentCard.js +4 -0
  101. package/dist/resources/AgentKeyRegister.js +56 -22
  102. package/dist/resources/AgentReadPosition.js +7 -0
  103. package/dist/resources/AgentSeed.js +232 -107
  104. package/dist/resources/AutoPromoteCandidates.js +413 -84
  105. package/dist/resources/Credential.js +6 -8
  106. package/dist/resources/Federation.js +219 -57
  107. package/dist/resources/FederationRetry.js +4 -4
  108. package/dist/resources/InstructionVersion.js +1 -1
  109. package/dist/resources/MCPClientMetadata.js +6 -3
  110. package/dist/resources/Memory.js +1348 -271
  111. package/dist/resources/MemoryArchive.js +149 -64
  112. package/dist/resources/MemoryBootstrap.js +12 -22
  113. package/dist/resources/MemoryCandidate.js +16 -2
  114. package/dist/resources/MemoryConsolidate.js +2 -2
  115. package/dist/resources/MemoryFeed.js +360 -147
  116. package/dist/resources/MemoryMaintenance.js +290 -72
  117. package/dist/resources/MemoryPurge.js +138 -22
  118. package/dist/resources/MemoryReflect.js +68 -14
  119. package/dist/resources/MemoryReindex.js +91 -13
  120. package/dist/resources/Message.js +11 -2
  121. package/dist/resources/OAuth.js +156 -39
  122. package/dist/resources/OAuthClient.js +1 -1
  123. package/dist/resources/OrgEvent.js +292 -29
  124. package/dist/resources/OrgEventCatchup.js +7 -0
  125. package/dist/resources/OrgEventMaintenance.js +48 -10
  126. package/dist/resources/PairingToken.js +1 -1
  127. package/dist/resources/Presence.js +31 -11
  128. package/dist/resources/PromoteMemoryCandidate.js +8 -2
  129. package/dist/resources/RecordUsage.js +2 -4
  130. package/dist/resources/Soul.js +2 -0
  131. package/dist/resources/SoulFeed.js +2 -1
  132. package/dist/resources/WorkspaceLatest.js +4 -0
  133. package/dist/resources/XAA.js +36 -10
  134. package/dist/resources/a2a-stream.js +313 -0
  135. package/dist/resources/a2a-url.js +4 -5
  136. package/dist/resources/agent-admin.js +10 -1
  137. package/dist/resources/agent-auth.js +98 -68
  138. package/dist/resources/agent-read-position-lib.js +4 -1
  139. package/dist/resources/agent-status-guard.js +9 -7
  140. package/dist/resources/auth-middleware.js +166 -42
  141. package/dist/resources/authority-field-guard.js +9 -11
  142. package/dist/resources/auto-promote-lib.js +8 -5
  143. package/dist/resources/basic-auth-header.js +21 -0
  144. package/dist/resources/bm25-index-service.js +4 -5
  145. package/dist/resources/dedup-cluster.js +6 -1
  146. package/dist/resources/embeddings-provider.js +25 -0
  147. package/dist/resources/federation-classify.js +89 -0
  148. package/dist/resources/federation-retry-lib.js +6 -81
  149. package/dist/resources/health.js +75 -19
  150. package/dist/resources/host-pointer/registry.js +29 -0
  151. package/dist/resources/host-pointer-adapter.js +1 -0
  152. package/dist/resources/in-process-api.js +74 -11
  153. package/dist/resources/in-process.js +24 -22
  154. package/dist/resources/instruction-version-record.js +251 -7
  155. package/dist/resources/internal-authority.js +13 -0
  156. package/dist/resources/mcp-client-metadata-fields.js +4 -0
  157. package/dist/resources/mcp-handler.js +146 -13
  158. package/dist/resources/mcp-oauth-flag.js +12 -14
  159. package/dist/resources/mcp-oauth.js +446 -53
  160. package/dist/resources/mcp-tool-scopes.js +69 -0
  161. package/dist/resources/mcp-tools.js +70 -22
  162. package/dist/resources/memory-declared-attributes.js +1 -0
  163. package/dist/resources/memory-embed-hash.js +56 -0
  164. package/dist/resources/memory-host-source.js +5 -2
  165. package/dist/resources/memory-reflect-lib.js +1 -1
  166. package/dist/resources/memory-write-lock.js +202 -23
  167. package/dist/resources/memory-write-response.js +1 -1
  168. package/dist/resources/memory-write-transaction.js +243 -0
  169. package/dist/resources/migration-boot.js +17 -12
  170. package/dist/resources/migrations/boot-progress.js +25 -0
  171. package/dist/resources/migrations/data-dir.js +16 -3
  172. package/dist/resources/migrations/dir-safety.js +60 -2
  173. package/dist/resources/migrations/embedding-stamp.js +315 -49
  174. package/dist/resources/migrations/graph-heal.js +9 -2
  175. package/dist/resources/migrations/ledger.js +5 -2
  176. package/dist/resources/migrations/lock.js +867 -80
  177. package/dist/resources/migrations/progress.js +71 -10
  178. package/dist/resources/migrations/runner.js +212 -18
  179. package/dist/resources/migrations/state.js +36 -1
  180. package/dist/resources/migrations/status.js +2 -13
  181. package/dist/resources/migrations/synthetic-test-migration.js +78 -12
  182. package/dist/resources/migrations/types.js +26 -1
  183. package/dist/resources/migrations/visibility-backfill.js +111 -70
  184. package/dist/resources/oauth-discovery.js +0 -5
  185. package/dist/resources/object-body-guard.js +12 -5
  186. package/dist/resources/org-event-reserved.js +92 -0
  187. package/dist/resources/org-event-write-fault.js +19 -0
  188. package/dist/resources/owner-field-guard.js +1 -1
  189. package/dist/resources/owner-scoped-write-policy.js +65 -21
  190. package/dist/resources/owner-scoped-writes.js +37 -6
  191. package/dist/resources/path-id-rewrite.js +76 -0
  192. package/dist/resources/presence-internal.js +5 -5
  193. package/dist/resources/promotion-binding.js +43 -0
  194. package/dist/resources/promotion-stamp.js +124 -33
  195. package/dist/resources/protocol-context.js +189 -0
  196. package/dist/resources/record-type-kit.js +2 -4
  197. package/dist/resources/request-target.js +28 -1
  198. package/dist/resources/request-transaction.js +11 -1
  199. package/dist/resources/seed-reservation.js +1 -2
  200. package/dist/resources/semantic-retrieval-core.js +7 -6
  201. package/dist/resources/server-row-validation.js +71 -0
  202. package/dist/resources/skill-manifest.js +4 -3
  203. package/dist/resources/skill-version-write.js +400 -27
  204. package/dist/resources/skill-write-fault.js +6 -3
  205. package/dist/resources/skill-write-policy.js +2 -1
  206. package/dist/resources/soul-write-policy.js +26 -7
  207. package/dist/resources/table-helpers.js +1 -1
  208. package/dist/resources/table-subscription-policy.js +518 -85
  209. package/dist/resources/table-subscriptions.js +20 -7
  210. package/dist/resources/txn-pause-point.js +122 -5
  211. package/dist/resources/usage-recording.js +54 -46
  212. package/dist/resources/write-back.js +176 -11
  213. package/dist/resources/write-journal-context.js +5 -0
  214. package/dist/resources/write-journal.js +289 -0
  215. package/dist/src/keystore.js +77 -10
  216. package/dist/src/lib/agent-id-rule.js +44 -2
  217. package/dist/src/lib/atomic-write.js +3 -3
  218. package/dist/src/lib/federation-retry-row.js +101 -0
  219. package/dist/src/lib/instruction-event-contract.js +17 -0
  220. package/dist/src/lib/key-dir.js +203 -0
  221. package/dist/src/lib/memory-attributes.js +2 -0
  222. package/dist/src/lib/open-live-row.js +20 -0
  223. package/dist/src/lib/scheduler-platform.js +13 -0
  224. package/dist/src/lib/soul-scope-fields.js +26 -0
  225. package/dist/src/rem/promote-policy.js +3 -3
  226. package/dist/src/rem/scheduler.js +21 -4
  227. package/docs/access-control.md +39 -21
  228. package/docs/api-reference.md +161 -52
  229. package/docs/auth.md +69 -38
  230. package/docs/claude-code.md +3 -3
  231. package/docs/deploying-on-fabric.md +118 -2
  232. package/docs/deployment.md +17 -0
  233. package/docs/embedding-in-a-harper-app.md +23 -21
  234. package/docs/entity-vocabulary.md +7 -11
  235. package/docs/federation.md +29 -2
  236. package/docs/hosted-on-fabric.md +1 -1
  237. package/docs/integrations.md +11 -11
  238. package/docs/mcp-clients.md +7 -5
  239. package/docs/notes/mcp-agent-auth-consumer.md +4 -9
  240. package/docs/notes/mcp-oauth-model2.md +6 -6
  241. package/docs/openclaw.md +1 -1
  242. package/docs/quickstart-fabric.md +2 -2
  243. package/docs/quickstart.md +3 -3
  244. package/docs/releasing.md +13 -13
  245. package/docs/rem.md +24 -3
  246. package/docs/secrets-and-keys.md +9 -14
  247. package/docs/standalone-local.md +29 -2
  248. package/docs/supply-chain-policy.md +28 -20
  249. package/docs/the-team.md +2 -2
  250. package/docs/upgrade.md +29 -5
  251. package/package.json +18 -11
  252. package/schemas/agent.graphql +3 -3
  253. package/schemas/federation.graphql +10 -7
  254. package/schemas/memory.graphql +7 -2
  255. package/templates/bin/flair-rem-nightly.sh.tmpl +7 -1
  256. package/templates/launchd/start-flair-with-admin-pass.sh +188 -10
  257. package/dist/resources/soul-adk-guard.js +0 -68
@@ -1,3 +1,4 @@
1
+ import { addAdminPassOptions } from "../lib/auth-resolve.js";
1
2
  import { readExactCountSince, readExactTableCount } from "../lib/ops-table-count.js";
2
3
  import { InconsistentReadError, readTableByIdPaged } from "../memory-id-checkpoint.js";
3
4
  import { writeConfirmed } from "../lib/instance-identity-row.js";
@@ -272,14 +273,13 @@ export function register(program) {
272
273
  const integrity = program
273
274
  .command("integrity")
274
275
  .description("Detect missing checkpointed durable Memory IDs or changed or missing previously nonempty tokens");
275
- integrity
276
+ addAdminPassOptions(integrity
276
277
  .command("check")
277
278
  .description("Report missing checkpointed durable IDs or changed or missing previously nonempty tokens; rows created and lost entirely between scans are not observed")
278
279
  .option("--json", "Print the verdict as JSON")
279
280
  .option("--accept", "On an alert, advance the whole checkpoint only if no reported replacement lacks a token; otherwise write no checkpoint, even with other losses")
280
281
  .option("--checkpoint <path>", "Checkpoint file path (default: ~/.flair/integrity-checkpoint.json)")
281
- .option("--ops-port <port>", "Harper operations API port")
282
- .option("--admin-pass <pass>", "Admin password (or set FLAIR_ADMIN_PASS env)")
282
+ .option("--ops-port <port>", "Harper operations API port"), "Admin password (or set FLAIR_ADMIN_PASS env)")
283
283
  .option("--admin-user <name>", "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)")
284
284
  .action(async (opts) => {
285
285
  const opsPort = cli.resolveOpsPort(opts);
@@ -344,15 +344,14 @@ export function register(program) {
344
344
  // bounded one-shot process, and the next run simply omits --apply. It prunes
345
345
  // nothing — with a named reason — when a checkpoint is missing or a watermark
346
346
  // is unreadable.
347
- integrity
347
+ addAdminPassOptions(integrity
348
348
  .command("prune-history")
349
349
  .description("Prune MemoryDeletionHistory rows older than the oldest named checkpoint watermark minus a margin; dry-run unless --apply")
350
350
  .option("--checkpoint <path...>", "Checkpoint file whose watermark bounds the prune; repeat for several (default: ~/.flair/integrity-checkpoint.json)")
351
351
  .option("--apply", "Delete the eligible rows; without it nothing is deleted")
352
352
  .option("--max <n>", "Hard cap on rows pruned in one run (default: 500)")
353
353
  .option("--json", "Print the plan as JSON")
354
- .option("--ops-port <port>", "Harper operations API port")
355
- .option("--admin-pass <pass>", "Admin password (or set FLAIR_ADMIN_PASS env)")
354
+ .option("--ops-port <port>", "Harper operations API port"), "Admin password (or set FLAIR_ADMIN_PASS env)")
356
355
  .option("--admin-user <name>", "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)")
357
356
  .action(async (opts) => {
358
357
  const opsPort = cli.resolveOpsPort(opts);
@@ -1,6 +1,7 @@
1
1
  import { existsSync, lstatSync, mkdirSync, renameSync, readdirSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import * as render from "../render.js";
4
+ import { scanKeyDir } from "../lib/key-dir.js";
4
5
  import { loadEd25519PrivateKeyFromFile } from "../mcp-client-assertion.js";
5
6
  import { defaultAdminPassPath, defaultKeysDir, isLocalBase, resolveAdminUser, resolveLocalAdminPass } from "../lib/auth-resolve.js";
6
7
  import { probeInstanceIds } from "../lib/instance-identity-row.js";
@@ -35,23 +36,26 @@ function isValidPrivateKeySeedFile(keyPath) {
35
36
  export async function classifyKeysDir(keysDir, baseUrl, readInstanceIds) {
36
37
  if (!existsSync(keysDir))
37
38
  return { aborted: false, entries: [], orphanRead: null };
38
- const dirents = readdirSync(keysDir, { withFileTypes: true });
39
+ // One walk, shared with doctor and status (flair#3077).
40
+ const scan = scanKeyDir(keysDir);
41
+ if (scan.state === "unreadable")
42
+ throw scan.error;
39
43
  const entries = [];
40
44
  const candidates = [];
41
- for (const d of dirents) {
42
- if (d.isDirectory()) {
45
+ for (const e of scan.entries) {
46
+ if (e.kind === "dir") {
43
47
  entries.push({
44
- name: d.name,
48
+ name: e.name,
45
49
  class: "ignored",
46
- reason: d.name === PRUNED_DIR_NAME ? "prune archive directory" : "directory (not a key file)",
50
+ reason: e.name === PRUNED_DIR_NAME ? "prune archive directory" : "directory (not a key file)",
47
51
  });
48
52
  continue;
49
53
  }
50
- if (!d.name.endsWith(".key")) {
51
- entries.push({ name: d.name, class: "ignored", reason: "not a .key file" });
54
+ if (e.kind === "other") {
55
+ entries.push({ name: e.name, class: "ignored", reason: "not a .key file" });
52
56
  continue;
53
57
  }
54
- candidates.push({ name: d.name, agentId: d.name.slice(0, -".key".length) });
58
+ candidates.push({ name: e.name, agentId: e.name.slice(0, -".key".length) });
55
59
  }
56
60
  const { nodeKeyIds } = partitionKeyIds(candidates.map((c) => c.agentId), keysDir);
57
61
  const orphanRead = nodeKeyIds.length > 0 ? await readInstanceIds() : null;
@@ -1,13 +1,15 @@
1
- import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
1
+ import { chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
2
2
  import { dirname, join } from "node:path";
3
3
  import nacl from "tweetnacl";
4
4
  import * as render from "../render.js";
5
- import { defaultKeysDir, resolveAdminUser, resolveLocalAdminPass } from "../lib/auth-resolve.js";
5
+ import { defaultKeysDir, resolveAdminUser, resolveLocalAdminPass, addAdminPassOptions } from "../lib/auth-resolve.js";
6
6
  import { resolveAgentKeyPath, loadEd25519PrivateKeyFromFile, signClientAssertion, buildTokenRequestForm, getMcpAccessToken, McpTokenRequestError, defaultMcpClientId, defaultMcpTokenEndpoint, defaultMcpResource, defaultMcpIssuer, MAX_ASSERTION_LIFETIME_SECONDS, clientAssertionAudienceForm, resolveClientAssertionAudience, oauthMetadataUrl, } from "../mcp-client-assertion.js";
7
7
  import { enableMcp, refreshMcpOAuthFlag, disableMcp, mcpStatus, checkLocalOriginRefusal, fabricLoopbackRefusal, targetOriginRefusal, selfVerifyMcpMetadata, cimdAllowedHostsFromFlag, claudeAiExcludedNote, } from "../lib/mcp-enable.js";
8
8
  import { resolveHome } from "../lib/home.js";
9
9
  import { invalidAgentIdMessage, isValidAgentId } from "../lib/agent-id-rule.js";
10
+ import { AgentKeyPathRefusal } from "../lib/key-dir.js";
10
11
  import { agentHomeEndpoint, resolveTargetInstanceId } from "../lib/agent-home.js";
12
+ import { createAgentKeyFile, ensureAgentKeysDir } from "../lib/agent-key-file.js";
11
13
  let cli;
12
14
  /** Bind shared CLI helpers. cli.ts calls this immediately before register(program). */
13
15
  export function bindCli(fns) {
@@ -103,6 +105,30 @@ export class McpClientNotFoundError extends Error {
103
105
  this.name = "McpClientNotFoundError";
104
106
  }
105
107
  }
108
+ function preflightMcpGrantKeyPaths(name, keysDir) {
109
+ if (!isValidAgentId(name) || !/^[a-zA-Z0-9]/.test(name)) {
110
+ throw new Error(`Invalid machine client name '${name}' — ${invalidAgentIdMessage(name)}; must start with a letter or digit.`);
111
+ }
112
+ const privPath = privKeyPath(name, keysDir);
113
+ const pubPath = pubKeyPath(name, keysDir);
114
+ // An occupied path may retain an existing mode and contents; refuse it
115
+ // before key generation or network requests.
116
+ const existingKeyPaths = [];
117
+ for (const path of [privPath, pubPath]) {
118
+ try {
119
+ lstatSync(path);
120
+ existingKeyPaths.push(path);
121
+ }
122
+ catch (error) {
123
+ if (error.code !== "ENOENT")
124
+ throw error;
125
+ }
126
+ }
127
+ if (existingKeyPaths.length > 0) {
128
+ throw new Error(`Key file ${existingKeyPaths.join(", ")} already exists — remove it, or grant under another name.`);
129
+ }
130
+ return { privPath, pubPath };
131
+ }
106
132
  /**
107
133
  * Core, testable `flair mcp grant` orchestration — no process.exit, no
108
134
  * console output, so it's directly unit-testable with a mocked fetch and a
@@ -125,6 +151,7 @@ export async function grantMcpClient(params, deps = {}) {
125
151
  if (manifest.some((e) => e.name === name)) {
126
152
  throw new McpClientNameExistsError(name);
127
153
  }
154
+ const { privPath, pubPath } = preflightMcpGrantKeyPaths(name, keysDir);
128
155
  // Defense-in-depth: refuse to silently reuse/clobber an unrelated
129
156
  // pre-existing Agent id (e.g. a human-run principal sharing this name).
130
157
  const opsUrl = typeof opsPortOrUrl === "number" ? `http://127.0.0.1:${opsPortOrUrl}/` : `${opsPortOrUrl.replace(/\/$/, "")}/`;
@@ -147,71 +174,111 @@ export async function grantMcpClient(params, deps = {}) {
147
174
  throw new McpClientAgentIdCollisionError(name);
148
175
  }
149
176
  }
150
- mkdirSync(keysDir, { recursive: true });
151
- const privPath = privKeyPath(name, keysDir);
152
- const pubPath = pubKeyPath(name, keysDir);
177
+ ensureAgentKeysDir(keysDir);
153
178
  const kp = generateKeyPair();
154
179
  const seed = kp.secretKey.slice(0, 32);
155
180
  const pubKeyB64url = b64url(kp.publicKey);
156
- writeFileSync(privPath, Buffer.from(seed), { mode: 0o600 });
157
- chmodSync(privPath, 0o600);
158
- writeFileSync(pubPath, Buffer.from(kp.publicKey));
159
- const nowIso = now();
160
- // flair#2433 — the new Agent row's home is THIS instance's federation id,
161
- // resolved through the one shared rule; a create stamps it.
162
- const home = await resolveTargetInstanceId(agentHomeEndpoint(opsUrl, adminUser, adminPass, fetchImpl));
163
- const insertRes = await fetchImpl(opsUrl, {
164
- method: "POST",
165
- headers: { "Content-Type": "application/json", Authorization: authHeader },
166
- body: JSON.stringify({
167
- operation: "insert",
168
- database: "flair",
169
- table: "Agent",
170
- records: [{
171
- id: name,
172
- name,
173
- type: "agent",
174
- kind: "agent",
175
- status: "active",
176
- displayName: name,
177
- admin: false,
178
- defaultTrustTier: "unverified",
179
- runtime: "headless",
180
- publicKey: pubKeyB64url,
181
- originatorInstanceId: home,
182
- createdAt: nowIso,
183
- updatedAt: nowIso,
184
- }],
185
- }),
186
- });
187
- if (!insertRes.ok) {
188
- // Roll back the key files we just wrote — nothing left behind locally
189
- // on a failed grant.
190
- for (const p of [privPath, pubPath]) {
191
- try {
192
- const { unlinkSync } = await import("node:fs");
193
- unlinkSync(p);
181
+ const createdKeyFiles = [];
182
+ const trackKeyFile = (path, identity) => {
183
+ createdKeyFiles.push({ path, dev: identity.dev, ino: identity.ino });
184
+ };
185
+ try {
186
+ createAgentKeyFile(privPath, Buffer.from(seed), trackKeyFile);
187
+ createAgentKeyFile(pubPath, Buffer.from(kp.publicKey), trackKeyFile);
188
+ const nowIso = now();
189
+ // flair#2433 — the new Agent row's home is THIS instance's federation id,
190
+ // resolved through the one shared rule; a create stamps it.
191
+ const home = await resolveTargetInstanceId(agentHomeEndpoint(opsUrl, adminUser, adminPass, fetchImpl));
192
+ const insertRes = await fetchImpl(opsUrl, {
193
+ method: "POST",
194
+ headers: { "Content-Type": "application/json", Authorization: authHeader },
195
+ body: JSON.stringify({
196
+ operation: "insert",
197
+ database: "flair",
198
+ table: "Agent",
199
+ records: [{
200
+ id: name,
201
+ name,
202
+ type: "agent",
203
+ kind: "agent",
204
+ status: "active",
205
+ displayName: name,
206
+ admin: false,
207
+ defaultTrustTier: "unverified",
208
+ runtime: "headless",
209
+ publicKey: pubKeyB64url,
210
+ originatorInstanceId: home,
211
+ createdAt: nowIso,
212
+ updatedAt: nowIso,
213
+ }],
214
+ }),
215
+ });
216
+ if (!insertRes.ok) {
217
+ const text = await insertRes.text().catch(() => "");
218
+ throw new Error(`Failed to create Agent '${name}' via operations API (${insertRes.status}): ${text}`);
219
+ }
220
+ const clientId = `${issuer.replace(/\/+$/, "")}/MCPClientMetadata/${name}`;
221
+ const entry = {
222
+ name,
223
+ agentId: name,
224
+ clientId,
225
+ keyFile: privPath,
226
+ pubKeyFile: pubPath,
227
+ issuer,
228
+ createdAt: nowIso,
229
+ status: "active",
230
+ };
231
+ writeMcpClientManifest(manifestPath, [...manifest, entry]);
232
+ const resource = `${issuer.replace(/\/+$/, "")}/mcp`;
233
+ const config = buildMcpGrantConfig({ name, resource, keyFile: privPath });
234
+ return { entry, config };
235
+ }
236
+ catch (error) {
237
+ // On failure, try to remove the key files this call created. File identity decides
238
+ // eligibility at the check: a path is removed (by path) only if, when
239
+ // checked, it still names the file this grant created. A path replaced
240
+ // between that check and the unlink can still be removed; a POSIX unlink by
241
+ // name cannot close that window. On POSIX the keys directory has no group or
242
+ // world permissions: a new directory requests 0700, and an existing narrower
243
+ // one keeps its mode. A path that no longer names the
244
+ // created file, or whose check or unlink fails with an error other than
245
+ // ENOENT, is named in the error; a created file moved to another name is
246
+ // not tracked.
247
+ if (createdKeyFiles.length > 0) {
248
+ const leftBehind = [];
249
+ for (const created of createdKeyFiles) {
250
+ let current;
251
+ try {
252
+ current = (deps.lstatKeyFile ?? lstatSync)(created.path);
253
+ }
254
+ catch (statError) {
255
+ const code = statError.code;
256
+ if (code !== "ENOENT") {
257
+ leftBehind.push(`${created.path} (not removed: could not check it (${code ?? "lstat failed"}))`);
258
+ }
259
+ continue;
260
+ }
261
+ if (!current.isFile() || current.dev !== created.dev || current.ino !== created.ino) {
262
+ leftBehind.push(`${created.path} (not removed: the path no longer names the file this grant created)`);
263
+ continue;
264
+ }
265
+ try {
266
+ (deps.unlinkKeyFile ?? unlinkSync)(created.path);
267
+ }
268
+ catch (cleanupError) {
269
+ const code = cleanupError.code;
270
+ if (code !== "ENOENT")
271
+ leftBehind.push(`${created.path} (not removed: ${code ?? "unlink failed"})`);
272
+ }
194
273
  }
195
- catch { /* best effort */ }
274
+ const message = error instanceof Error ? error.message : String(error);
275
+ const cleanup = leftBehind.length === 0
276
+ ? "removed the key paths that still named this call's files when checked"
277
+ : `could not remove key file(s): ${leftBehind.join("; ")}`;
278
+ throw new Error(`${message}; ${cleanup}`, { cause: error });
196
279
  }
197
- const text = await insertRes.text().catch(() => "");
198
- throw new Error(`Failed to create Agent '${name}' via operations API (${insertRes.status}): ${text}`);
280
+ throw error;
199
281
  }
200
- const clientId = `${issuer.replace(/\/+$/, "")}/MCPClientMetadata/${name}`;
201
- const entry = {
202
- name,
203
- agentId: name,
204
- clientId,
205
- keyFile: privPath,
206
- pubKeyFile: pubPath,
207
- issuer,
208
- createdAt: nowIso,
209
- status: "active",
210
- };
211
- writeMcpClientManifest(manifestPath, [...manifest, entry]);
212
- const resource = `${issuer.replace(/\/+$/, "")}/mcp`;
213
- const config = buildMcpGrantConfig({ name, resource, keyFile: privPath });
214
- return { entry, config };
215
282
  }
216
283
  /**
217
284
  * Core, testable `flair mcp revoke` orchestration. SERVER-SIDE ack is
@@ -349,7 +416,17 @@ export function register(program) {
349
416
  .option("--json", "Print machine-readable JSON instead of a human summary")
350
417
  .action(async (opts) => {
351
418
  const agentId = opts.agentId;
352
- const keyPath = resolveAgentKeyPath(agentId, opts.keysDir);
419
+ let keyPath;
420
+ try {
421
+ keyPath = resolveAgentKeyPath(agentId, opts.keysDir);
422
+ }
423
+ catch (err) {
424
+ if (err instanceof AgentKeyPathRefusal) {
425
+ console.error(`Error: ${err.message}`);
426
+ process.exit(1);
427
+ }
428
+ throw err;
429
+ }
353
430
  if (!keyPath) {
354
431
  console.error(`Error: no private key found for agent '${agentId}'. Checked --keys-dir, FLAIR_KEY_DIR, ` +
355
432
  `~/.flair/keys, and ~/.tps/secrets/flair.`);
@@ -445,14 +522,13 @@ export function register(program) {
445
522
  process.exit(1);
446
523
  }
447
524
  });
448
- mcp
525
+ addAdminPassOptions(mcp
449
526
  .command("grant <name>")
450
527
  .description("Provision a named, individually-revocable machine client for the /mcp OAuth surface " +
451
528
  "(flair Agent + Ed25519 keypair; the existing CIMD path — see `flair mcp token` — makes it usable).")
452
529
  .option("--issuer <url>", "Public origin for the CIMD client_id (defaults to FLAIR_MCP_ISSUER/FLAIR_PUBLIC_URL)")
453
530
  .option("--keys-dir <dir>", "Directory to write the new key pair into (else FLAIR_KEY_DIR, ~/.flair/keys)")
454
- .option("--manifest <path>", "Path to the local machine-client manifest (else ~/.flair/mcp-clients.json)")
455
- .option("--admin-pass <pass>", "Admin password (or set FLAIR_ADMIN_PASS)")
531
+ .option("--manifest <path>", "Path to the local machine-client manifest (else ~/.flair/mcp-clients.json)"), "Admin password (or set FLAIR_ADMIN_PASS)")
456
532
  .option("--admin-user <name>", "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)")
457
533
  .option("--port <port>", "Harper HTTP port")
458
534
  .option("--ops-port <port>", "Harper operations API port")
@@ -464,6 +540,14 @@ export function register(program) {
464
540
  "must be a stable, publicly-resolvable URL.");
465
541
  process.exit(1);
466
542
  }
543
+ const keysDir = opts.keysDir ?? defaultKeysDir();
544
+ try {
545
+ preflightMcpGrantKeyPaths(name, keysDir);
546
+ }
547
+ catch (err) {
548
+ console.error(`Error: ${err.message}`);
549
+ process.exit(1);
550
+ }
467
551
  // Workflow gate: proof `flair mcp enable` has actually run against this
468
552
  // instance — a live probe of the OAuth metadata endpoint (flair#756;
469
553
  // replaces the old DCR-gate-token presence check, which a CIMD-only
@@ -479,7 +563,6 @@ export function register(program) {
479
563
  "Set FLAIR_ADMIN_PASS, or make sure ~/.flair/admin-pass exists (created by `flair init`).");
480
564
  process.exit(1);
481
565
  }
482
- const keysDir = opts.keysDir ?? defaultKeysDir();
483
566
  const manifestPath = opts.manifest ?? defaultMcpClientManifestPath();
484
567
  const opsPort = resolveOpsPort(opts);
485
568
  try {
@@ -509,11 +592,10 @@ export function register(program) {
509
592
  process.exit(1);
510
593
  }
511
594
  });
512
- mcp
595
+ addAdminPassOptions(mcp
513
596
  .command("revoke <name>")
514
597
  .description("Server-side revoke a granted machine client (deletes its backing Agent record), then clean up locally.")
515
- .option("--manifest <path>", "Path to the local machine-client manifest (else ~/.flair/mcp-clients.json)")
516
- .option("--admin-pass <pass>", "Admin password (or set FLAIR_ADMIN_PASS)")
598
+ .option("--manifest <path>", "Path to the local machine-client manifest (else ~/.flair/mcp-clients.json)"), "Admin password (or set FLAIR_ADMIN_PASS)")
517
599
  .option("--admin-user <name>", "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)")
518
600
  .option("--issuer <url>", "Public origin of the /mcp OAuth surface — used only for the enable-gate probe (defaults to FLAIR_MCP_ISSUER/FLAIR_PUBLIC_URL)")
519
601
  .option("--ops-port <port>", "Harper operations API port")
@@ -580,7 +662,7 @@ export function register(program) {
580
662
  ];
581
663
  console.log(render.table(cols, entries));
582
664
  });
583
- mcp
665
+ addAdminPassOptions(mcp
584
666
  .command("enable")
585
667
  .description("Enable the OAuth /mcp surface for claude.ai. " +
586
668
  "Rejects invalid issuer URLs, localhost/.localhost/.local hosts, " +
@@ -602,8 +684,7 @@ export function register(program) {
602
684
  "Without --dry-run, refused unless a preflight match links the host and pid the target reports, a readable " +
603
685
  "process on this machine, and that file (by realpath); --dry-run skips the match and writes nothing. " +
604
686
  "Always refused with --fabric or a *.harperfabric.com instance. " +
605
- "Without it the list is not changed (shipped: claude.ai,claude.com)")
606
- .option("--admin-pass <pass>", "Admin password for the TARGET instance. Required explicitly for a remote target — FLAIR_ADMIN_PASS and ~/.flair/admin-pass are this machine's local credentials and are never sent to a remote instance")
687
+ "Without it the list is not changed (shipped: claude.ai,claude.com)"), "Admin password for the TARGET instance. Required explicitly for a remote target — FLAIR_ADMIN_PASS and ~/.flair/admin-pass are this machine's local credentials and are never sent to a remote instance")
607
688
  .option("--admin-user <name>", "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)")
608
689
  .option("--confirm-secrets-applied", "Confirm the staged secrets are already live on the target instance's environment (skips the interactive confirm)")
609
690
  .option("--fabric", "Use the Fabric branch and default to Fabric secrets staging; refused for a localhost, *.localhost, 127/8, ::1, ::ffff:127/8, 0.0.0.0 or :: target host")
@@ -637,7 +718,7 @@ export function register(program) {
637
718
  const dryRun = Boolean(opts.dryRun);
638
719
  const adminPass = dryRun ? (opts.adminPass ?? process.env.FLAIR_ADMIN_PASS ?? "") : resolveLocalAdminPass(opts.adminPass, /* isRemoteTarget */ true);
639
720
  if (!dryRun && !adminPass) {
640
- console.error("Error: --admin-pass <pass> is required for a REMOTE target " +
721
+ console.error("Error: --admin-pass <pass> or --admin-pass-file <path> is required for a target instance " +
641
722
  "(the command authenticates to the target instance's operations API with it).\n" +
642
723
  " FLAIR_ADMIN_PASS and ~/.flair/admin-pass are deliberately NOT used here: they are THIS machine's " +
643
724
  "local admin credentials, and sending them to another instance is how a local secret ends up on someone " +
@@ -736,11 +817,10 @@ export function register(program) {
736
817
  for (const line of enableSuccessLines(result))
737
818
  console.log(line);
738
819
  });
739
- mcp
820
+ addAdminPassOptions(mcp
740
821
  .command("disable")
741
822
  .description("Flag off + restart = byte-identical boot (Model-2 contract) — removes the /mcp OAuth surface.")
742
- .option("--instance <url>", "Remote flair instance to disable against (else FLAIR_URL)")
743
- .option("--admin-pass <pass>", "Admin password for the remote target instance; pass it explicitly with --admin-pass")
823
+ .option("--instance <url>", "Flair instance to disable against (else FLAIR_URL)"), "Admin password for the target instance; use --admin-pass or --admin-pass-file", { adminPassFileHelp: "Read the target instance's admin password from an owner-only file (group and world permission bits are refused; an owner-only mode such as 0600 or 0400 is accepted)" })
744
824
  .option("--admin-user <name>", "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)")
745
825
  .option("--confirm-flag-off", "Confirm FLAIR_MCP_OAUTH is already unset on the target instance's environment (skips the interactive confirm)")
746
826
  .option("--json", "Print machine-readable JSON instead of a human summary")
@@ -750,11 +830,9 @@ export function register(program) {
750
830
  console.error("Error: --instance is required (or set FLAIR_URL).");
751
831
  process.exit(1);
752
832
  }
753
- // --instance is always remote for this command — see the matching
754
- // comment in `mcp enable` above.
755
833
  const adminPass = resolveLocalAdminPass(opts.adminPass, /* isRemoteTarget */ true);
756
834
  if (!adminPass) {
757
- console.error("Error: --admin-pass <pass> is required for a REMOTE target. Pass the target instance's admin password explicitly.");
835
+ console.error("Error: --admin-pass <pass> or --admin-pass-file <path> is required for a target instance. Pass the target instance's admin password explicitly.");
758
836
  process.exit(1);
759
837
  }
760
838
  const result = await disableMcp({ instance, adminUser: resolveAdminUser(opts.adminUser), adminPass, confirmFlagOff: Boolean(opts.confirmFlagOff) }, { confirmPrompt: confirmYesNo });
@@ -11,15 +11,17 @@
11
11
  * Do not import src/cli.ts from here — that would cycle and pull the
12
12
  * non-strict entry into the strict check.
13
13
  */
14
+ import { randomUUID } from "node:crypto";
14
15
  import { Option } from "commander";
15
16
  import * as render from "../render.js";
16
- import { resolveAdminUser } from "../lib/auth-resolve.js";
17
+ import { resolveAdminUser, addAdminPassOptions } from "../lib/auth-resolve.js";
17
18
  import { encodeRecordId } from "../lib/record-id-path.js";
18
19
  import { DURABILITY_TIERS_HELP } from "../lib/durability-copy.js";
19
20
  import { resolveLocalDeleteInstance } from "../lib/local-delete-instance.js";
20
21
  import { confirmedPurgeIds } from "../lib/memory-purge-response.js";
21
22
  import { resolveHome } from "../lib/home.js";
22
23
  import { ALL_TIERS } from "../lib/memory-integrity.js";
24
+ import { MEMORY_PROVIDER_RETRY_DELAY_MS, isProviderTimeoutRefusal, } from "../lib/memory-provider-timeout.js";
23
25
  import { normalizeOrigin, buildCheckpoint, buildOpsPost, readMemoryRowCount, readMemoryRowsPaged, readCheckpointFile, writeCheckpointFile, checkpointPath, unknownVerify, verifyCheckpoint, renderVerifyHuman, VERIFY_EXIT_CODES, } from "../memory-id-checkpoint.js";
24
26
  import { classifyNodeSets, readNode, renderCompareNodesHuman, COMPARE_EXIT_CODES, } from "../memory-node-compare.js";
25
27
  let cli;
@@ -36,9 +38,6 @@ function resolveBaseUrl(opts) {
36
38
  function resolveSigningAgentId(opts, command) {
37
39
  return cli.resolveSigningAgentId(opts, command);
38
40
  }
39
- function applyAdminPassFile(opts) {
40
- cli.applyAdminPassFile(opts);
41
- }
42
41
  function addSharedCredentialOptions(cmd) {
43
42
  return cli.addSharedCredentialOptions(cmd);
44
43
  }
@@ -80,6 +79,11 @@ export function categorizeForHygiene(row, opts) {
80
79
  export function register(program) {
81
80
  // ─── flair memory ──────────────────────────────────────────────────────────
82
81
  const ENTITIES_OPTION_DESCRIPTION = cli.ENTITIES_OPTION_DESCRIPTION;
82
+ // A write refused with 503 memory_provider_timeout wrote nothing (the
83
+ // write-lock contract), so `memory add` replays it with the same id. The
84
+ // bounded attempt count keeps a slow provider from turning one command into
85
+ // an unbounded wait.
86
+ const MEMORY_ADD_MAX_ATTEMPTS = 3;
83
87
  const memory = program.command("memory").description("Manage agent memories");
84
88
  addSharedCredentialOptions(addSharedIdentityOption(memory.command("add [content]")
85
89
  .description("Write a new memory row for an agent (content via positional arg or --content)")))
@@ -96,13 +100,14 @@ export function register(program) {
96
100
  console.error("error: content required (positional arg or --content)");
97
101
  process.exit(1);
98
102
  }
99
- applyAdminPassFile(opts);
100
103
  const { agentId, source } = resolveSigningAgentId(opts, "memory add");
101
104
  if (!agentId) {
102
105
  console.error("error: --agent <id> required (or set FLAIR_AGENT_ID)");
103
106
  process.exit(2);
104
107
  }
105
- const memId = `${agentId}-${Date.now()}`;
108
+ // flair#3107: one id per command, random so same-millisecond adds do not
109
+ // collide; computed once so the retry loop below replays it.
110
+ const memId = `${agentId}-${randomUUID()}`;
106
111
  const body = {
107
112
  id: memId, agentId, content, durability: opts.durability || "standard",
108
113
  tags: opts.tags ? String(opts.tags).split(",").map((x) => x.trim()).filter(Boolean) : undefined,
@@ -137,12 +142,27 @@ export function register(program) {
137
142
  if (entities.length > 0)
138
143
  body.entities = entities;
139
144
  }
140
- const out = await api("PUT", `/Memory/${encodeRecordId(memId)}`, body, {
141
- agentId,
142
- agentIdSource: source,
143
- explicitAdminPass: opts.adminPass,
144
- adminUser: opts.adminUser,
145
- });
145
+ let out;
146
+ for (let attempt = 1;; attempt++) {
147
+ try {
148
+ out = await api("PUT", `/Memory/${encodeRecordId(memId)}`, body, {
149
+ agentId,
150
+ agentIdSource: source,
151
+ explicitAdminPass: opts.adminPass,
152
+ adminUser: opts.adminUser,
153
+ });
154
+ break;
155
+ }
156
+ catch (err) {
157
+ if (!isProviderTimeoutRefusal(err))
158
+ throw err;
159
+ if (attempt >= MEMORY_ADD_MAX_ATTEMPTS) {
160
+ console.error(`error: memory add: the embedding provider timed out (503 memory_provider_timeout) on all ${attempt} attempts; nothing was written — retry when the provider is responsive`);
161
+ process.exit(1);
162
+ }
163
+ await new Promise((resolve) => setTimeout(resolve, MEMORY_PROVIDER_RETRY_DELAY_MS * attempt));
164
+ }
165
+ }
146
166
  console.log(JSON.stringify(out, null, 2));
147
167
  });
148
168
  // ─── flair memory write-task-summary ────────────────────────────────────────
@@ -200,7 +220,7 @@ export function register(program) {
200
220
  }
201
221
  const content = lines.join("\n");
202
222
  const { agentId, source } = resolveSigningAgentId(opts, "memory write-task-summary");
203
- const memId = `${opts.agent}-task-${opts.beads}-${Date.now()}`;
223
+ const memId = `${opts.agent}-task-${opts.beads}-${randomUUID()}`;
204
224
  const body = {
205
225
  id: memId,
206
226
  agentId: opts.agent,
@@ -225,10 +245,11 @@ export function register(program) {
225
245
  // without parsing a JSON blob.
226
246
  console.log(memId);
227
247
  });
228
- memory.command("search [query]")
248
+ addAdminPassOptions(memory
249
+ .command("search [query]")
229
250
  .description("Semantic search over an agent's memories (query via positional arg or --q)")
230
- .option("--agent <id>", "Agent ID (or set FLAIR_AGENT_ID env)")
231
- .option("--admin-pass <pass>", "Admin password — sign as admin while --agent names whose memories to search (flair#1500: a flag-pinned agent with no key no longer falls back to FLAIR_ADMIN_PASS)")
251
+ .option("--agent <id>", "Agent ID (or set FLAIR_AGENT_ID env)"), "Admin password — sign as admin while --agent names whose memories to search (flair#1500: a flag-pinned agent with no key no longer falls back to FLAIR_ADMIN_PASS)")
252
+ .option("--admin-user <name>", "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)")
232
253
  .option("--q <query>", "search query (alias for positional arg)")
233
254
  .option("--json", "Output raw JSON array")
234
255
  .option("--limit <n>", "Max results", "5")
@@ -254,7 +275,7 @@ export function register(program) {
254
275
  if (opts.includeArchived)
255
276
  body.includeArchived = true;
256
277
  const baseUrl = resolveBaseUrl(opts);
257
- const res = await api("POST", "/SemanticSearch", body, { baseUrl, agentId, agentIdSource: source, explicitAdminPass: opts.adminPass });
278
+ const res = await api("POST", "/SemanticSearch", body, { baseUrl, agentId, agentIdSource: source, explicitAdminPass: opts.adminPass, adminUser: opts.adminUser });
258
279
  if (opts.json) {
259
280
  const results = res.results || res || [];
260
281
  console.log(render.asJSON(Array.isArray(results) ? results : []));
@@ -4,6 +4,7 @@ import { randomUUID } from "node:crypto";
4
4
  import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync } from "node:fs";
5
5
  import { join, resolve, sep } from "node:path";
6
6
  import { resolveHome } from "../lib/home.js";
7
+ import { agentKeyPath } from "../lib/key-dir.js";
7
8
  import { encodeRecordId } from "../lib/record-id-path.js";
8
9
  let cli;
9
10
  /** Bind the cli-locals this module depends on. */
@@ -111,6 +112,14 @@ export function register(program) {
111
112
  const target = opts.target;
112
113
  const agentId = opts.agent;
113
114
  const dryRun = !!opts.dryRun;
115
+ let keyPath;
116
+ try {
117
+ keyPath = agentKeyPath(join(resolveHome(), ".flair", "keys"), agentId);
118
+ }
119
+ catch (err) {
120
+ console.error(`Error: ${err instanceof Error ? err.message : String(err)}`);
121
+ process.exit(1);
122
+ }
114
123
  let memoryDir;
115
124
  try {
116
125
  memoryDir = resolveMemoryDir(target, agentId);
@@ -187,9 +196,6 @@ export function register(program) {
187
196
  console.log(` Writing to Flair...`);
188
197
  try {
189
198
  const httpUrl = `http://127.0.0.1:${resolveHttpPort({})}`;
190
- const agentKeyId = `${agentId}.key`;
191
- const keysDir = join(resolveHome(), ".flair", "keys");
192
- const keyPath = join(keysDir, agentKeyId);
193
199
  let authSuccess = false;
194
200
  if (existsSync(keyPath)) {
195
201
  const memoryId = `${agentId}-${randomUUID()}`;
@@ -91,16 +91,11 @@ export function register(program) {
91
91
  // another agent's events — the difference from post() is that put() checks-
92
92
  // and-rejects a mismatch rather than silently overwriting it.
93
93
  //
94
- // (flair#679, measured against a real spawned Harper): table-backed resources
95
- // only accept writes via PUT /<Table>/<id> — a bare POST /OrgEvent 405s
96
- // ("does not have a post method implemented to handle HTTP method POST"),
97
- // same restriction documented in resources/Memory.ts and already fixed for
98
- // `soul set` (#498). OrgEvent.ts DOES define a post() method that
99
- // auto-generates id/createdAt, but Harper's REST layer never routes a real
100
- // HTTP POST to it — post() is only reachable via in-process resource
101
- // instantiation, never the wire. put() does NOT default id/createdAt, so the
102
- // CLI generates and supplies them itself (id convention mirrors flair-client's
103
- // Memory.write(): `${agentId}-${randomUUID()}`).
94
+ // (flair#679): the CLI writes with PUT /OrgEvent/{id}, as `flair workspace set`
95
+ // and `soul set` (#498) do, rather than a bare POST /OrgEvent, and generates the
96
+ // id itself (`${agentId}-${randomUUID()}`, the convention of flair-client's
97
+ // Memory.write()). A bare POST /OrgEvent is also accepted (the sanity test in
98
+ // test/integration/workspace-orgevent-cli-e2e.test.ts asserts it does not 405).
104
99
  program
105
100
  .command("orgevent")
106
101
  .description("Publish an org-wide coordination event attributed to your agent (PUT /OrgEvent/{id})")