@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,8 +1,13 @@
1
1
  import nacl from "tweetnacl";
2
- import { existsSync, mkdirSync, writeFileSync, readFileSync, chmodSync } from "node:fs";
2
+ import { existsSync, mkdirSync, writeFileSync, readFileSync, chmodSync, unlinkSync, realpathSync } from "node:fs";
3
3
  import { join } from "node:path";
4
4
  import * as render from "../render.js";
5
5
  import { resolveAdminPassFromSources, defaultKeysDir, resolveLocalAdminPass, resolveAdminUser, resolveKeyPath, authFetch, } from "../lib/auth-resolve.js";
6
+ import { encodeRecordId } from "../lib/record-id-path.js";
7
+ import { resolveLocalDeleteInstance } from "../lib/local-delete-instance.js";
8
+ import { invalidAgentIdMessage, isValidAgentId } from "../lib/agent-id-rule.js";
9
+ import { agentHomeEndpoint, resolveTargetInstanceId, runAgentHomeStamp, stampLeftoverLines, } from "../lib/agent-home.js";
10
+ import { confirmedPurgeIds } from "../lib/memory-purge-response.js";
6
11
  let cli;
7
12
  /** Bind shared CLI helpers. cli.ts calls this immediately before register(program). */
8
13
  export function bindCli(fns) {
@@ -12,12 +17,48 @@ const api = (method, path, body, options) => cli.api(method, path, body, options
12
17
  const b64url = (bytes) => cli.b64url(bytes);
13
18
  const privKeyPath = (agentId, keysDir) => cli.privKeyPath(agentId, keysDir);
14
19
  const pubKeyPath = (agentId, keysDir) => cli.pubKeyPath(agentId, keysDir);
20
+ /**
21
+ * flair#2479 — check each key's canonical target before unlinking.
22
+ * Return successful unlinks; invalid ids require manual cleanup.
23
+ */
24
+ export function removeAgentKeyFiles(agentId, keysDir) {
25
+ if (!isValidAgentId(agentId))
26
+ return { removed: [], manual: true };
27
+ let root;
28
+ try {
29
+ root = realpathSync(keysDir);
30
+ }
31
+ catch {
32
+ return { removed: [], manual: false }; // directory resolution failed
33
+ }
34
+ const removed = [];
35
+ for (const name of [`${agentId}.key`, `${agentId}.pub`, `${agentId}.key.bak`]) {
36
+ let real;
37
+ try {
38
+ real = realpathSync(join(keysDir, name));
39
+ }
40
+ catch {
41
+ continue; // candidate resolution failed
42
+ }
43
+ if (real !== join(root, name))
44
+ continue; // unexpected canonical target; skip
45
+ try {
46
+ unlinkSync(real);
47
+ removed.push(real);
48
+ }
49
+ catch { /* best effort */ }
50
+ }
51
+ return { removed, manual: false };
52
+ }
15
53
  const shouldShowInlineSecretWarning = (optValue, fromEnv, secretFlagNames, flagName) => cli.shouldShowInlineSecretWarning(optValue, fromEnv, secretFlagNames, flagName);
16
54
  const resolveHttpPort = (opts, mode) => cli.resolveHttpPort(opts, mode);
17
55
  const resolveOpsPort = (opts) => cli.resolveOpsPort(opts);
56
+ const resolveAgentHomeTarget = (opts) => cli.resolveAgentHomeTarget(opts);
18
57
  const resolveEffectiveOpsUrl = (opts) => cli.resolveEffectiveOpsUrl(opts);
19
- const seedAgentViaOpsApi = (opsPortOrUrl, agentId, pubKeyB64url, adminUser, adminPass) => cli.seedAgentViaOpsApi(opsPortOrUrl, agentId, pubKeyB64url, adminUser, adminPass);
58
+ const seedAgentWithLocalHome = (opsPortOrUrl, agentId, pubKeyB64url, adminUser, adminPass) => cli.seedAgentWithLocalHome(opsPortOrUrl, agentId, pubKeyB64url, adminUser, adminPass);
20
59
  const agentRecordIsAdmin = (record) => cli.agentRecordIsAdmin(record);
60
+ const INLINE_ADMIN_PASS_WARNING = "warning: --admin-pass passed inline. Use FLAIR_ADMIN_PASS without typing its value into a recorded " +
61
+ "shell line (for example, read it from the admin-pass file).";
21
62
  /** Operations API URL, same shape as `seedAgentViaOpsApi` (trailing slash). */
22
63
  function opsApiUrl(opsPortOrUrl) {
23
64
  return typeof opsPortOrUrl === "number"
@@ -175,9 +216,15 @@ export function register(program) {
175
216
  .option("--admin-user <name>", "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)")
176
217
  .option("--keys-dir <dir>", "Directory for Ed25519 keys")
177
218
  .option("--ops-port <port>", "Harper operations API port")
178
- .option("--target <url>", "Remote Flair REST URL; derives the ops API URL (port-1) to seed the Agent there (env: FLAIR_TARGET)")
219
+ .option("--target <url>", "Remote Flair REST URL; derives ops URL (HTTPS no port/:443 → Fabric ops :9925; HTTP no port/:80 → :19925; other ports 2–65535 → port-1; port 1 refused; env: FLAIR_TARGET)")
179
220
  .option("--ops-target <url>", "Explicit ops API URL to seed the Agent on (env: FLAIR_OPS_TARGET; bypasses port derivation)")
180
221
  .action(async (id, opts) => {
222
+ // flair#2359 — the ONE agent-ID rule, before any key file is written or
223
+ // any insert is attempted. Refuse a non-matching id by name.
224
+ if (!isValidAgentId(id)) {
225
+ console.error(`Error: ${invalidAgentIdMessage(id)}`);
226
+ process.exit(1);
227
+ }
181
228
  const httpPort = resolveHttpPort(opts);
182
229
  const opsPort = resolveOpsPort(opts);
183
230
  const keysDir = opts.keysDir ?? defaultKeysDir();
@@ -264,7 +311,7 @@ export function register(program) {
264
311
  pubKeyB64url = b64url(kp.publicKey);
265
312
  console.log(`Keypair written: ${privPath}`);
266
313
  }
267
- await seedAgentViaOpsApi(seedOpsTarget, id, pubKeyB64url, adminUser, adminPass);
314
+ await seedAgentWithLocalHome(seedOpsTarget, id, pubKeyB64url, adminUser, adminPass);
268
315
  const stored = await readStoredAgent(seedOpsTarget, id, adminUser, adminPass);
269
316
  if (!stored || stored.publicKey !== pubKeyB64url) {
270
317
  console.error(agentKeyNotStoredMessage(id, stored));
@@ -297,8 +344,7 @@ export function register(program) {
297
344
  // fromEnv is true ONLY when the resolved value came from env (no inline override).
298
345
  const adminPassFromEnv = !opts.adminPass && (!!process.env.FLAIR_ADMIN_PASS || !!process.env.HDB_ADMIN_PASSWORD);
299
346
  if (shouldShowInlineSecretWarning(opts.adminPass, adminPassFromEnv, new Set(["--admin-pass"]), "--admin-pass")) {
300
- console.error("warning: --admin-pass passed inline. Consider --admin-pass-from <file> or FLAIR_ADMIN_PASS env " +
301
- "to keep secrets out of shell history.");
347
+ console.error(INLINE_ADMIN_PASS_WARNING);
302
348
  }
303
349
  const adminPass = opts.adminPass ?? process.env.FLAIR_ADMIN_PASS ?? process.env.HDB_ADMIN_PASSWORD ?? "";
304
350
  const mode = render.resolveOutputMode(opts);
@@ -385,7 +431,7 @@ export function register(program) {
385
431
  .description("Show agent details")
386
432
  .option("--json", "Emit raw JSON response (also: pipe + FLAIR_OUTPUT=json)")
387
433
  .action(async (id, opts) => {
388
- const out = await api("GET", `/Agent/${id}`);
434
+ const out = await api("GET", `/Agent/${encodeRecordId(id)}`);
389
435
  const mode = render.resolveOutputMode(opts);
390
436
  if (mode === "json") {
391
437
  console.log(render.asJSON(out));
@@ -433,8 +479,7 @@ export function register(program) {
433
479
  // fromEnv is true ONLY when the resolved value came from env (no inline override).
434
480
  const adminPassFromEnv = !opts.adminPass && !!process.env.FLAIR_ADMIN_PASS;
435
481
  if (shouldShowInlineSecretWarning(opts.adminPass, adminPassFromEnv, new Set(["--admin-pass"]), "--admin-pass")) {
436
- console.error("warning: --admin-pass passed inline. Consider --admin-pass-from <file> or FLAIR_ADMIN_PASS env " +
437
- "to keep secrets out of shell history.");
482
+ console.error(INLINE_ADMIN_PASS_WARNING);
438
483
  }
439
484
  const adminPass = opts.adminPass ?? process.env.FLAIR_ADMIN_PASS ?? "";
440
485
  const adminUser = resolveAdminUser(opts.adminUser);
@@ -491,7 +536,7 @@ export function register(program) {
491
536
  // Verify new key works
492
537
  console.log(`Verifying new Ed25519 auth...`);
493
538
  const httpUrl = `http://127.0.0.1:${httpPort}`;
494
- const verifyRes = await authFetch(httpUrl, id, currentPrivPath, "GET", `/Agent/${id}`);
539
+ const verifyRes = await authFetch(httpUrl, id, currentPrivPath, "GET", `/Agent/${encodeRecordId(id)}`);
495
540
  if (!verifyRes.ok) {
496
541
  console.error(`⚠️ Auth verification failed (${verifyRes.status}). Old key is backed up at: ${backupPrivPath}`);
497
542
  process.exit(1);
@@ -514,7 +559,6 @@ export function register(program) {
514
559
  .option("--keys-dir <dir>", "Directory for Ed25519 keys")
515
560
  .option("--force", "Skip interactive confirmation (required when stdin is not a TTY)")
516
561
  .action(async (id, opts) => {
517
- const opsPort = resolveOpsPort(opts);
518
562
  const adminPass = opts.adminPass ?? process.env.FLAIR_ADMIN_PASS ?? "";
519
563
  const adminUser = resolveAdminUser(opts.adminUser);
520
564
  const keysDir = opts.keysDir ?? defaultKeysDir();
@@ -523,9 +567,11 @@ export function register(program) {
523
567
  process.exit(1);
524
568
  }
525
569
  const auth = `Basic ${Buffer.from(`${adminUser}:${adminPass}`).toString("base64")}`;
570
+ const instance = await resolveLocalDeleteInstance(opts, resolveOpsPort, auth);
526
571
  async function opsPost(body) {
527
- return fetch(`http://127.0.0.1:${opsPort}/`, {
572
+ return fetch(instance.opsUrl, {
528
573
  method: "POST",
574
+ redirect: "error",
529
575
  headers: { "Content-Type": "application/json", Authorization: auth },
530
576
  body: JSON.stringify(body),
531
577
  signal: AbortSignal.timeout(10_000),
@@ -535,9 +581,41 @@ export function register(program) {
535
581
  const agentRes = await opsPost({ operation: "search_by_value", database: "flair", table: "Agent", search_attribute: "id", search_value: id, get_attributes: ["id", "name"] });
536
582
  const agentData = agentRes.ok ? await agentRes.json().catch(() => null) : null;
537
583
  const agentName = agentData?.[0]?.name ?? id;
538
- const memRes = await opsPost({ operation: "search_by_value", database: "flair", table: "Memory", search_attribute: "agentId", search_value: id, get_attributes: ["id"] });
539
- const memories = memRes.ok ? await memRes.json().catch(() => []) : [];
540
- const memoryCount = Array.isArray(memories) ? memories.length : 0;
584
+ async function scanOwnedIds(table) {
585
+ const res = await opsPost({
586
+ operation: "search_by_conditions", database: "flair", table, operator: "and",
587
+ conditions: [{ search_attribute: "agentId", search_type: "equals", search_value: id }],
588
+ get_attributes: ["id", "agentId"],
589
+ });
590
+ if (!res.ok)
591
+ throw new Error(`operations API returned ${res.status}`);
592
+ const rows = await res.json();
593
+ if (!Array.isArray(rows) || !rows.every((row) => typeof row?.id === "string" && row.id.length > 0)) {
594
+ throw new Error("returned an unexpected response");
595
+ }
596
+ for (const row of rows) {
597
+ if (row.agentId !== id) {
598
+ const error = new Error(`${table} row '${row.id}' does not belong to agent '${id}'`);
599
+ error.name = "AgentRemoveOwnerMismatchError";
600
+ throw error;
601
+ }
602
+ }
603
+ return rows.map((row) => row.id);
604
+ }
605
+ async function initialScan(table) {
606
+ try {
607
+ return await scanOwnedIds(table);
608
+ }
609
+ catch (error) {
610
+ const failure = new Error(`The ${table} scan for agent '${id}' failed: ${error instanceof Error ? error.message : String(error)}; nothing was removed.`, { cause: error });
611
+ if (error instanceof Error)
612
+ failure.name = error.name;
613
+ throw failure;
614
+ }
615
+ }
616
+ const memoryIds = await initialScan("Memory");
617
+ const memoryCount = memoryIds.length;
618
+ const soulIds = await initialScan("Soul");
541
619
  // Confirmation
542
620
  const isInteractive = process.stdin.isTTY;
543
621
  if (!opts.force) {
@@ -568,25 +646,48 @@ export function register(program) {
568
646
  else {
569
647
  console.log(`Removing agent '${agentName}' (${id}) with ${memoryCount} memories...`);
570
648
  }
571
- // Delete all memories
649
+ // Delete the scanned memories through the server's physical-removal
650
+ // path. A skill-tagged row expands to its whole lineage there, so
651
+ // superseded version rows go too. An accepted DELETE of a non-reserved
652
+ // skill closes its head; the reserved `using-flair` seed is physically
653
+ // deleted. A response that does not list every scanned id as
654
+ // removed stops the command before the Agent record is deleted.
572
655
  if (memoryCount > 0) {
573
656
  console.log(`Deleting ${memoryCount} memories...`);
574
- for (const mem of (Array.isArray(memories) ? memories : [])) {
575
- if (!mem?.id)
576
- continue;
577
- await opsPost({ operation: "delete", database: "flair", table: "Memory", ids: [mem.id] }).catch(() => { });
657
+ const purge = await api("POST", "/MemoryPurge", { ids: memoryIds }, {
658
+ baseUrl: instance.baseUrl,
659
+ explicitAdminPass: adminPass, adminUser, agentId: null,
660
+ });
661
+ confirmedPurgeIds(purge, memoryIds);
662
+ }
663
+ if (soulIds.length > 0) {
664
+ console.log(`Deleting ${soulIds.length} soul entries...`);
665
+ for (const soulId of soulIds) {
666
+ try {
667
+ const soulDel = await opsPost({ operation: "delete", database: "flair", table: "Soul", ids: [soulId] });
668
+ if (!soulDel.ok) {
669
+ const text = await soulDel.text().catch(() => "");
670
+ throw new Error(`operations API returned ${soulDel.status}: ${text}`);
671
+ }
672
+ }
673
+ catch (error) {
674
+ throw new Error(`Failed to delete Soul '${soulId}': ${error instanceof Error ? error.message : String(error)}`, { cause: error });
675
+ }
578
676
  }
579
677
  }
580
- // Delete all souls
581
- const soulRes = await opsPost({ operation: "search_by_value", database: "flair", table: "Soul", search_attribute: "agentId", search_value: id, get_attributes: ["id"] });
582
- const souls = soulRes.ok ? await soulRes.json().catch(() => []) : [];
583
- if (Array.isArray(souls) && souls.length > 0) {
584
- console.log(`Deleting ${souls.length} soul entries...`);
585
- for (const soul of souls) {
586
- if (!soul?.id)
587
- continue;
588
- await opsPost({ operation: "delete", database: "flair", table: "Soul", ids: [soul.id] }).catch(() => { });
589
- }
678
+ let remainingIds;
679
+ try {
680
+ remainingIds = await scanOwnedIds("Soul");
681
+ }
682
+ catch (error) {
683
+ const failure = new Error(`The Soul deletion for agent '${id}' could not be confirmed: ${error instanceof Error ? error.message : String(error)}; ` +
684
+ `these scanned Soul rows may remain and the Agent record was not deleted: ${soulIds.join(", ") || "(none scanned)"}.`, { cause: error });
685
+ if (error instanceof Error)
686
+ failure.name = error.name;
687
+ throw failure;
688
+ }
689
+ if (remainingIds.length > 0) {
690
+ throw new Error(`The Soul deletion for agent '${id}' was not confirmed; these Soul rows remain and the Agent record was not deleted: ${remainingIds.join(", ")}.`);
590
691
  }
591
692
  // Delete agent record
592
693
  const delRes = await opsPost({ operation: "delete", database: "flair", table: "Agent", ids: [id] });
@@ -596,23 +697,103 @@ export function register(program) {
596
697
  }
597
698
  // Delete key files (unless --keep-keys)
598
699
  if (!opts.keepKeys) {
599
- const privPath = privKeyPath(id, keysDir);
600
- const pubPath = pubKeyPath(id, keysDir);
601
- const backupPath = privPath + ".bak";
602
- for (const p of [privPath, pubPath, backupPath]) {
603
- if (existsSync(p)) {
604
- try {
605
- const { unlinkSync: ul } = await import("node:fs");
606
- ul(p);
607
- }
608
- catch { /* best effort */ }
609
- }
610
- }
611
- console.log("Key files deleted.");
700
+ const keys = removeAgentKeyFiles(id, keysDir);
701
+ console.log(keys.manual
702
+ ? `Key files for '${id}' are not deleted by this command (the id is outside the agent-ID rule); clean them up manually.`
703
+ : `Removed ${keys.removed.length} key file(s).`);
612
704
  }
613
705
  else {
614
706
  console.log("Key files preserved (--keep-keys).");
615
707
  }
616
708
  console.log(`\n✅ Agent '${id}' removed successfully`);
617
709
  });
710
+ agent
711
+ .command("stamp-home")
712
+ .description("Back-fill the home instance (originatorInstanceId) on home-less Agent rows with no federation-sync provenance")
713
+ .option("--port <port>", "Harper HTTP port")
714
+ .option("--ops-port <port>", "Harper operations API port")
715
+ .option("--admin-pass <pass>", "Admin password (or set FLAIR_ADMIN_PASS)")
716
+ .option("--admin-pass-file <path>", "Read the admin password from a file (chmod 600 enforced)")
717
+ .option("--admin-user <name>", "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)")
718
+ .option("--apply", "Write the home; without it the command is a dry run and writes nothing")
719
+ .action(async (opts) => {
720
+ let target;
721
+ try {
722
+ // flair#2474 — pair the ops port (the roster read) with the HTTP port (the
723
+ // guarded PATCH). A target the configured pair contradicts, or one with a
724
+ // single port named and no complete configured pair, is refused by name
725
+ // (see resolveAgentHomeTarget).
726
+ target = resolveAgentHomeTarget(opts);
727
+ }
728
+ catch (err) {
729
+ console.error(`Error: ${err.message}`);
730
+ process.exit(1);
731
+ }
732
+ const opsPort = target.opsPort;
733
+ const adminUser = resolveAdminUser(opts.adminUser);
734
+ let explicitPass;
735
+ try {
736
+ explicitPass =
737
+ resolveAdminPassFromSources({
738
+ adminPassFile: opts.adminPassFile,
739
+ adminPass: opts.adminPass,
740
+ envPass: undefined,
741
+ }) || undefined;
742
+ }
743
+ catch (err) {
744
+ console.error(`Error: ${err.message}`);
745
+ process.exit(1);
746
+ }
747
+ let adminPass;
748
+ try {
749
+ adminPass = resolveLocalAdminPass(explicitPass);
750
+ }
751
+ catch (err) {
752
+ console.error(`Error: ${err.message}`);
753
+ process.exit(1);
754
+ }
755
+ if (!adminPass) {
756
+ console.error("Error: --admin-pass or FLAIR_ADMIN_PASS required (or ensure ~/.flair/admin-pass exists, created by `flair init`)");
757
+ process.exit(1);
758
+ }
759
+ const opsUrl = `http://127.0.0.1:${opsPort}/`;
760
+ const httpUrl = `http://127.0.0.1:${target.httpPort}/`;
761
+ const auth = `Basic ${Buffer.from(`${adminUser}:${adminPass}`).toString("base64")}`;
762
+ const localInstanceId = await resolveTargetInstanceId(agentHomeEndpoint(opsUrl, adminUser, adminPass));
763
+ const result = await runAgentHomeStamp({
764
+ opsUrl,
765
+ httpUrl,
766
+ authHeader: auth,
767
+ localInstanceId,
768
+ apply: Boolean(opts.apply),
769
+ });
770
+ if (result.reason === "roster-unreadable") {
771
+ console.error("Error: could not read the stored Agent roster; nothing was changed.");
772
+ process.exit(1);
773
+ }
774
+ const plan = result.plan;
775
+ if (plan.homeLess.length === 0) {
776
+ console.log(`${render.icons.ok} Every stored agent row names a home instance.`);
777
+ return;
778
+ }
779
+ console.log(`${plan.homeLess.length} agent row(s) have no home instance` +
780
+ (localInstanceId ? ` (this instance is ${localInstanceId})` : ""));
781
+ for (const id of plan.homeLess) {
782
+ const inSync = plan.sync.includes(id);
783
+ console.log(` ${inSync ? "list only (sync-originated):" : "stamp:"} ${id}`);
784
+ }
785
+ if (result.reason === "no-canonical-id") {
786
+ console.error("Error: could not confirm a single canonical Instance row to stamp as the home; nothing was written.");
787
+ process.exitCode = 1;
788
+ return;
789
+ }
790
+ if (!opts.apply) {
791
+ console.log(`Dry run — nothing written. Re-run with --apply to stamp ${plan.stampable.length} row(s); ` +
792
+ `${plan.sync.length} sync-originated row(s) are never stamped.`);
793
+ return;
794
+ }
795
+ for (const line of stampLeftoverLines(result))
796
+ console.log(line);
797
+ console.log(`${render.icons.ok} Stamped the home instance on ${result.stamped.length} row(s).`);
798
+ });
618
799
  }
@@ -1,4 +1,4 @@
1
- import { buildEd25519Auth, resolveKeyPath } from "../lib/auth-resolve.js";
1
+ import { buildEd25519Auth, requestTarget, requestUrl, resolveKeyPath } from "../lib/auth-resolve.js";
2
2
  import * as render from "../render.js";
3
3
  let cli;
4
4
  /** Bind the cli-locals this module depends on. */
@@ -67,12 +67,13 @@ export function register(program) {
67
67
  payload.days = n;
68
68
  }
69
69
  const baseUrl = resolveBaseUrl(opts);
70
+ const url = requestUrl(baseUrl, "/AttentionQuery");
70
71
  const headers = { "content-type": "application/json" };
71
72
  const keyPath = opts.key || resolveKeyPath(agentId);
72
73
  if (keyPath) {
73
- headers["authorization"] = buildEd25519Auth(agentId, "POST", "/AttentionQuery", keyPath);
74
+ headers["authorization"] = buildEd25519Auth(agentId, "POST", requestTarget(url), keyPath);
74
75
  }
75
- const res = await fetch(`${baseUrl}/AttentionQuery`, {
76
+ const res = await fetch(url, {
76
77
  method: "POST",
77
78
  headers,
78
79
  body: JSON.stringify(payload),