@tpsdev-ai/flair 0.58.0 → 0.59.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 (46) hide show
  1. package/README.md +3 -2
  2. package/config.yaml +3 -0
  3. package/dist/build-info.json +3 -3
  4. package/dist/cli.js +42 -98
  5. package/dist/commands/agent.js +160 -2
  6. package/dist/commands/doctor.js +15 -23
  7. package/dist/commands/mcp.js +53 -22
  8. package/dist/lib/daemon-liveness.js +42 -0
  9. package/dist/lib/doctor-run.js +67 -0
  10. package/dist/lib/flair-agent-role.js +116 -0
  11. package/dist/lib/launchd-management.js +3 -2
  12. package/dist/lib/mcp-enable.js +667 -72
  13. package/dist/lib/process-start-time.js +32 -0
  14. package/dist/resources/Agent.js +27 -7
  15. package/dist/resources/AgentSeed.js +9 -0
  16. package/dist/resources/Federation.js +14 -2
  17. package/dist/resources/MemoryBootstrap.js +121 -29
  18. package/dist/resources/OrgSkillAssignment.js +209 -0
  19. package/dist/resources/XAA.js +40 -11
  20. package/dist/resources/agent-status-guard.js +63 -0
  21. package/dist/resources/auth-middleware.js +2 -1
  22. package/dist/resources/federation-classify.js +22 -0
  23. package/dist/resources/flair-agent-role-boot.js +26 -0
  24. package/dist/resources/health.js +10 -2
  25. package/dist/resources/key-lock.js +31 -0
  26. package/dist/resources/mcp-oauth.js +3 -6
  27. package/dist/resources/mcp-tools.js +22 -4
  28. package/dist/resources/multi-worker-guard.js +121 -0
  29. package/dist/resources/oauth-discovery.js +1 -0
  30. package/dist/resources/oauth-wellknown.js +8 -4
  31. package/dist/resources/record-types.js +16 -0
  32. package/dist/resources/replay-store.js +56 -9
  33. package/dist/resources/skill-manifest.js +181 -0
  34. package/dist/resources/skill-provenance.js +15 -10
  35. package/dist/src/lib/flair-agent-role.js +116 -0
  36. package/docs/access-control.md +667 -0
  37. package/docs/api-reference.md +6 -2
  38. package/docs/auth.md +4 -0
  39. package/docs/deepseek-harness.md +1 -1
  40. package/docs/integrations.md +1 -1
  41. package/docs/mcp-clients.md +5 -3
  42. package/docs/releasing.md +24 -24
  43. package/package.json +4 -3
  44. package/schemas/memory.graphql +31 -0
  45. package/schemas/oauth.graphql +8 -4
  46. package/templates/launchd/start-flair-with-admin-pass.sh +89 -16
package/README.md CHANGED
@@ -180,8 +180,8 @@ See **[DESIGN.md](DESIGN.md)** for the invariants behind the three primitives
180
180
  | **Auto entity detection** | Entities extracted from memory content on write. No tagging required. |
181
181
  | **Predictive bootstrap** | Cold-start context selected from active project, recent activity and agent role — not just recency. |
182
182
  | **Multi-agent** | One instance, any number of agents, each with its own keys, memories and soul. |
183
- | **Federation** | Hub-and-spoke sync between instances using signed requests and pairing tokens. Originator enforcement blocks cross-node replay. [docs/federation.md](docs/federation.md) |
184
- | **Memory hygiene (REM)** | On-demand (`flair rem rapid`) and scheduled nightly distillation. Candidates are staged and promoted one at a time with a required rationale — never auto-applied. [docs/rem.md](docs/rem.md) |
183
+ | **Federation** | Hub-and-spoke sync between instances using signed requests and pairing tokens. Non-hub peers sync only rows treated as self-originated; the nonce store rejects replayed signed requests. [docs/federation.md](docs/federation.md) |
184
+ | **Memory hygiene (REM)** | On-demand (`flair rem rapid`) and scheduled nightly distillation. `flair rem promote` requires a rationale; nightly REM auto-promotes eligible ADK and continuity candidates. [docs/rem.md](docs/rem.md) |
185
185
  | **Memory bridges** | Import/export to foreign memory systems via a YAML descriptor or a code plugin. [docs/bridges.md](docs/bridges.md) |
186
186
  | **Real-time feeds** | Administrators subscribe to table changes over WebSocket/SSE; verified agents subscribe to changes to the memories they can read through `/FeedMemories`, and to soul changes through `/FeedSouls`. |
187
187
  | **OAuth 2.1 server** | PKCE, dynamic client registration, standards-compliant token endpoint. Delegate auth to Flair without a separate IdP. [docs/auth.md](docs/auth.md) |
@@ -379,6 +379,7 @@ Full model, threat analysis and recommendations in [SECURITY.md](SECURITY.md).
379
379
  - `Memory.post()` and `Memory.put()` are the calls behind `flair memory add`, MCP `memory_store` and the SDK writes. A new memory they write without a visibility takes a default from durability: `permanent`/`persistent` default to `shared`, `standard`/`ephemeral` to `private`. A write that names neither lands `private`, and an update through `Memory.put()` that names no visibility keeps the stored one. Their write response names the visibility the record landed on whenever the record has one; the admin-only `_reindex` re-PUT, which rebuilds indexes for an existing row, does not return that response. `POST /FeedMemories` does not apply this default: a new `ephemeral` feed record without `visibility` lands `private`, any other new feed record without `visibility` has no visibility field and reads as non-private, an update that names no visibility keeps a stored `private`/`shared` value, and the response (the stored record) names `visibility` only when the record has one. Say what you mean with `--visibility shared|private` (CLI) or `visibility` (MCP / SDK / feed).
380
380
  - The admin password is generated by `flair init` and written to `~/.flair/admin-pass` (mode 0600). The CLI prints the path, never the value. Prefer `--admin-pass-file` over `--admin-pass` so it stays out of `ps` and shell history.
381
381
  - Key rotation via `flair agent rotate-key`.
382
+ - Who can connect to a hosted Flair's native `/mcp` (which people, which apps, what they can reach) and how to revoke access: [docs/access-control.md](docs/access-control.md).
382
383
 
383
384
  ## Architecture
384
385
 
package/config.yaml CHANGED
@@ -56,6 +56,9 @@ authentication:
56
56
  dynamicClientRegistration:
57
57
  enabled: false
58
58
  clientIdMetadataDocuments:
59
+ # A LITERAL list, not a ${VAR} reference: @harperfast/oauth 2.5.0 does
60
+ # not split a variable's value into hosts, and an unset one would replace
61
+ # this default (flair#2113).
59
62
  allowedHosts:
60
63
  - claude.ai
61
64
  - claude.com
@@ -1,6 +1,6 @@
1
1
  {
2
- "version": "0.58.0",
3
- "commit": "2bec5cd8af1762763a438cfec9bde01bad69c034",
4
- "builtAt": "2026-09-30T22:58:01.388Z",
2
+ "version": "0.59.0",
3
+ "commit": "e6b92b12a835799d4c55b93619653fa01db79357",
4
+ "builtAt": "2026-10-02T08:18:27.351Z",
5
5
  "builder": "tsc"
6
6
  }
package/dist/cli.js CHANGED
@@ -42,8 +42,8 @@ import { stabilizeMqttNetworkKeyOrder } from "./lib/stabilize-mqtt-network.js";
42
42
  import { detectOpsApiAllInterfacesBind } from "./lib/ops-api-bind.js";
43
43
  import { applyUpgradeHookConsent, runDoctorChecks, } from "./lib/doctor-run.js";
44
44
  import { classifyInstalledVersion, shouldPrintUpgradeLine, upgradeStatusSuffix } from "./lib/upgrade-status.js";
45
- import { classifyDaemonState, verifyIdentity, parseSidecarJson, classifyHealthProbe, classifyPortOwner, classifyInstanceMatch, shouldAdoptMissingSidecar, classifySidecarStaleness, shouldRemoveSidecarAfterStop, livenessFromKillError, parseNullSeparatedEnviron, extractRootPath, } from "./lib/daemon-liveness.js";
46
- import { readProcessStartTimeMs } from "./lib/process-start-time.js";
45
+ import { classifyDaemonState, verifyIdentity, isHarperProcessCommandLine, sidecarStartAgrees, parseSidecarJson, classifyHealthProbe, classifyPortOwner, classifyInstanceMatch, shouldAdoptMissingSidecar, classifySidecarStaleness, shouldRemoveSidecarAfterStop, livenessFromKillError, parseNullSeparatedEnviron, extractRootPath, } from "./lib/daemon-liveness.js";
46
+ import { readProcessStartSecondMs, readProcessStartTimeMs } from "./lib/process-start-time.js";
47
47
  import { readInitListenerRootPath } from "./lib/init-listener-environ.js";
48
48
  import { listenerFromLookup, occupiedListenerAuthFailure, stableAnsweredHolder, } from "./lib/init-occupied-listener.js";
49
49
  import { bindCli as bindFederationCli, register as registerFederation, signRequestBody, parseTokenFromFile, runFederationSyncOnce, persistLocalPeerLastSyncAt, runFederationWatch, federationStatusUrlSetting, describeFederationStatusFetchFailed, isFederationStatusConnectFailure, rewriteFederationStatusFetchFailed, isFederationStatusAuthFailure, isFederationStatusAuthRemedy, } from "./commands/federation.js";
@@ -89,6 +89,7 @@ import { bindCli as bindDoctorCli, register as registerDoctor, } from "./command
89
89
  import { bindCli as bindQualityCli, register as registerQuality, } from "./commands/quality.js";
90
90
  import { bindCli as bindGrantCli, register as registerGrant, } from "./commands/grant.js";
91
91
  import { resolveHome } from "./lib/home.js";
92
+ import { FLAIR_AGENT_PERMISSION } from "./lib/flair-agent-role.js";
92
93
  // Federation crypto helpers + private-visibility filter live with the
93
94
  // federation command group (src/commands/federation.ts, flair#1620). Inlined
94
95
  // there for the same packaging reason: src/ must not import resources/.
@@ -3034,6 +3035,18 @@ const PAIR_INITIATOR_PERMISSION = {
3034
3035
  super_user: false,
3035
3036
  structure_user: false,
3036
3037
  };
3038
+ /**
3039
+ * The `id` that `alter_role` addresses a role by. `list_roles` answers with each
3040
+ * role's `id`, and Harper 5.2.8 rejects an `alter_role` that omits it ("Id can't
3041
+ * be blank").
3042
+ */
3043
+ function alterRoleId(roleName, existing) {
3044
+ const id = existing?.id;
3045
+ if (typeof id !== "string" || id.length === 0) {
3046
+ throw new Error(`alter_role for '${roleName}': list_roles returned no id for the role`);
3047
+ }
3048
+ return id;
3049
+ }
3037
3050
  /**
3038
3051
  * Idempotently ensures the `flair_pair_initiator` role exists on the Harper
3039
3052
  * instance at `opsUrl` with the canonical permission spec.
@@ -3078,6 +3091,7 @@ export async function ensureFlairPairInitiatorRole(opsUrl, adminUser, adminPass)
3078
3091
  console.log(`Role '${ROLE_NAME}' exists but permissions differ — updating...`);
3079
3092
  await callOpsApi(opsUrl, {
3080
3093
  operation: "alter_role",
3094
+ id: alterRoleId(ROLE_NAME, existing),
3081
3095
  role: ROLE_NAME,
3082
3096
  permission: PAIR_INITIATOR_PERMISSION,
3083
3097
  }, adminUser, adminPass);
@@ -3085,102 +3099,8 @@ export async function ensureFlairPairInitiatorRole(opsUrl, adminUser, adminPass)
3085
3099
  }
3086
3100
  // ─── flair_agent role ────────────────────────────────────────────────────────
3087
3101
  //
3088
- // The auth reshape replaces the global gate's "verified agent borrows admin
3089
- // super_user" elevation with a real, least-privilege Harper role. After an
3090
- // agent's Ed25519 signature verifies, resources resolve the request to the
3091
- // shared `flair_agent`-roled user instead of admin — so agents get exactly the
3092
- // table CRUD below and nothing more. Critically: with no `super_user` and no
3093
- // operations grants, /sql and /graphql become NATIVELY 403 for agents (the
3094
- // raw-query block the gate hand-rolled is now enforced by Harper itself).
3095
- //
3096
- // Row-level ownership (an agent touches only its OWN memories/soul/events) is
3097
- // NOT expressible in Harper's role model — it stays in each resource's allow*,
3098
- // keyed on the Ed25519-verified agentId. So these per-table grants are the
3099
- // coarse CRUD envelope; allow* is the ownership boundary inside it.
3100
- //
3101
- // VALIDATION GATES (must confirm against a live Harper before this role goes
3102
- // live — flagged for Sherlock + the PR, not assumed):
3103
- // 1. HNSW/vector search (SemanticSearch over Memory) works with table `read`
3104
- // alone — the old elevation comment claimed admin perms were needed for
3105
- // "HNSW-capable" access; confirm `read` suffices or widen precisely.
3106
- // 2. Role table keys must EXACTLY match the @table names (Memory, OrgEvent,
3107
- // WorkspaceState, OAuthClient — NOT the logical Memory/Event/Workspace/OAuth
3108
- // shorthand the flair_pair_initiator spec used, which was harmless only
3109
- // because every grant there is false).
3110
- // Harper 5.0.21 add_role requires an `attribute_permissions` array on EVERY table
3111
- // grant (empty = no attribute-level restriction, so the table-level CRUD applies);
3112
- // omitting it makes add_role reject the whole spec ("Missing 'attribute_permissions'
3113
- // array"). Validated live against a spawned Harper. This helper guarantees the
3114
- // array is never forgotten. Also: `cluster_user` is NOT a valid top-level key —
3115
- // Harper reads unrecognized top-level keys as database names ("database
3116
- // 'cluster_user' does not exist"); only super_user / structure_user are recognized.
3117
- const grant = (read, insert, update, del) => ({ read, insert, update, delete: del, attribute_permissions: [] });
3118
- /** Canonical permission spec for flair_agent (least-privilege; real @table names). */
3119
- const FLAIR_AGENT_PERMISSION = {
3120
- super_user: false,
3121
- structure_user: false,
3122
- flair: {
3123
- tables: {
3124
- // Core agent-owned data — CRUD envelope; ownership enforced in allow*.
3125
- Memory: grant(true, true, true, true),
3126
- MemoryCandidate: grant(true, true, true, true),
3127
- MemoryGrant: grant(true, true, true, true),
3128
- // Asset (images-in-Flair slice 1). Harper authorizes BEFORE Asset.post
3129
- // runs, so a de-elevated flair_agent needs the table grant or signed
3130
- // POST /Asset 403s as AccessViolation (Kern P0). CRUD envelope;
3131
- // owner-only + write-time size/MIME gates live in resources/Asset.ts.
3132
- Asset: grant(true, true, true, true),
3133
- Soul: grant(true, true, true, false),
3134
- OrgEvent: grant(true, true, true, true),
3135
- WorkspaceState: grant(true, true, true, true),
3136
- Relationship: grant(true, true, true, true),
3137
- // Flair Relay S1 (flair#1521). Harper authorizes BEFORE the resource
3138
- // methods run, so a de-elevated flair_agent needs the table grant OR it
3139
- // 403s on POST /Message before relaySend is reached (Kern P0-2). read =
3140
- // the party-scoped collection (Message.search); insert = send via post().
3141
- // update = FALSE (least privilege, Kern P0 blocker): the ack's write goes
3142
- // through the IN-PROCESS static accessor (relayConsume → deps.messages.put),
3143
- // which bypasses role gates entirely — the same raw-put seam Federation.ts
3144
- // relies on — so update:true is NOT needed for any legitimate path. Leaving
3145
- // it granted let PATCH /Message/<id> reach Table's update verb, whose
3146
- // authorize step consults update:true and PASSES for any de-elevated agent,
3147
- // bypassing Message.put()'s FORBIDDEN guard AND relayConsume's recipient-only
3148
- // check (Message has no patch() at the platform level → TableResource.patch
3149
- // runs update()+save() directly). delete = false: direct deletes are
3150
- // admin/internal only. Message.patch() also guards the verb in-resource.
3151
- Message: grant(true, true, false, false),
3152
- Integration: grant(true, true, true, true),
3153
- Credential: grant(true, true, true, true),
3154
- Presence: grant(true, true, true, false),
3155
- // MemoryUsage (flair#683): the usage-feedback dedup ledger. Read (own
3156
- // contributions, scoped in resources/MemoryUsage.ts) + insert (a fresh
3157
- // contribution row) only — NO update/delete. This is load-bearing, not
3158
- // just least-privilege tidiness: the dedup rule ("(agent, memory)
3159
- // contributes ≤ 1") is enforced by requiring a NEW ledger row before
3160
- // any usageCount bump; if an agent could delete its own row, it could
3161
- // re-trigger the /RecordUsage endpoint for the same memory indefinitely
3162
- // (create → count → delete → count again → repeat), defeating the cap
3163
- // entirely. See resources/MemoryUsage.ts's module doc.
3164
- MemoryUsage: grant(true, true, false, false),
3165
- // MemoryHitStat (flair#1528): internal search-hit ledger. No agent REST
3166
- // surface (@table without @export). Counts overlay onto Memory reads.
3167
- MemoryHitStat: grant(false, false, false, false),
3168
- // Agent: read for discovery, update own card; creation/removal is admin.
3169
- Agent: grant(true, false, true, false),
3170
- // Read-only reference data.
3171
- Instance: grant(true, false, false, false),
3172
- // Federation / OAuth / IdP / internal — system + admin only; agents get none.
3173
- Peer: grant(false, false, false, false),
3174
- PairingToken: grant(false, false, false, false),
3175
- SyncLog: grant(false, false, false, false),
3176
- OAuthClient: grant(false, false, false, false),
3177
- OAuthToken: grant(false, false, false, false),
3178
- OAuthAuthCode: grant(false, false, false, false),
3179
- IdpConfig: grant(false, false, false, false),
3180
- IdJagReplay: grant(false, false, false, false),
3181
- },
3182
- },
3183
- };
3102
+ // The grant spec (FLAIR_AGENT_PERMISSION) lives in src/lib/flair-agent-role.ts,
3103
+ // shared with the server's startup check (resources/flair-agent-role-boot.ts).
3184
3104
  /**
3185
3105
  * Idempotently ensures the `flair_agent` role exists on the Harper instance at
3186
3106
  * `opsUrl` with the canonical least-privilege spec. Same list/add/alter shape as
@@ -3222,6 +3142,7 @@ export async function ensureFlairAgentRole(opsUrl, adminUser, adminPass) {
3222
3142
  console.log(`Role '${ROLE_NAME}' exists but permissions differ — updating...`);
3223
3143
  await callOpsApi(opsUrl, {
3224
3144
  operation: "alter_role",
3145
+ id: alterRoleId(ROLE_NAME, existing),
3225
3146
  role: ROLE_NAME,
3226
3147
  permission: FLAIR_AGENT_PERMISSION,
3227
3148
  }, adminUser, adminPass);
@@ -4661,10 +4582,33 @@ function resolveInstanceServingPid(dataDir, port) {
4661
4582
  listeningPids = listeningPidsOnPort(port, (cmd) => execSync(cmd, { encoding: "utf-8" }));
4662
4583
  }
4663
4584
  catch { /* lsof unavailable — the PID file may still answer */ }
4585
+ // flair#2056: the `hdb.pid` pid is used as PID-file evidence only when it is
4586
+ // alive, its command line passes isHarperProcessCommandLine (node or bun
4587
+ // followed by a Harper entry path; see there for what a `ps` line cannot
4588
+ // establish), and no flair#1454 sidecar disagrees. A sidecar is not
4589
+ // required: an instance started by a pre-sidecar flair, or the one the
4590
+ // launchd launcher execs, has none. A sidecar disagrees when it names a
4591
+ // different pid, or a startTimeMs more than 2000 ms from the pid's start
4592
+ // second (readProcessStartSecondMs). When the pid is not used,
4593
+ // pickInstancePid returns the first process listening on `port`, if any,
4594
+ // which can be the same pid.
4595
+ const sidecar = readSidecar(dataDir);
4596
+ const isPidFileEvidence = (pid) => {
4597
+ if (sidecar.kind === "present") {
4598
+ if (sidecar.pid !== pid)
4599
+ return false;
4600
+ const startSecondMs = readProcessStartSecondMs(pid);
4601
+ if (startSecondMs === null || !sidecarStartAgrees(startSecondMs, sidecar.startTimeMs))
4602
+ return false;
4603
+ }
4604
+ const cmdline = defaultReadProcessCmdline(pid);
4605
+ return cmdline !== null && isHarperProcessCommandLine(cmdline);
4606
+ };
4664
4607
  return pickInstancePid({
4665
4608
  pidFilePid: readHarperPid(dataDir),
4666
4609
  isAlive: isProcessAlive,
4667
4610
  listeningPids,
4611
+ isPidFileEvidence,
4668
4612
  });
4669
4613
  }
4670
4614
  // ─── which install tree serves this instance (flair#2034 §2) ────────────────
@@ -18,13 +18,156 @@ const resolveOpsPort = (opts) => cli.resolveOpsPort(opts);
18
18
  const resolveEffectiveOpsUrl = (opts) => cli.resolveEffectiveOpsUrl(opts);
19
19
  const seedAgentViaOpsApi = (opsPortOrUrl, agentId, pubKeyB64url, adminUser, adminPass) => cli.seedAgentViaOpsApi(opsPortOrUrl, agentId, pubKeyB64url, adminUser, adminPass);
20
20
  const agentRecordIsAdmin = (record) => cli.agentRecordIsAdmin(record);
21
+ /** Operations API URL, same shape as `seedAgentViaOpsApi` (trailing slash). */
22
+ function opsApiUrl(opsPortOrUrl) {
23
+ return typeof opsPortOrUrl === "number"
24
+ ? `http://127.0.0.1:${opsPortOrUrl}/`
25
+ : `${opsPortOrUrl.replace(/\/$/, "")}/`;
26
+ }
27
+ /**
28
+ * Parse an operations `search_by_value` body for one id.
29
+ * `[]` is the only absence. One row with this id and a string `name` is that
30
+ * agent even when `publicKey` is missing or empty: a missing public key is
31
+ * still an existing row and fails the later success check. It is not a
32
+ * missing row. Unreadable, and never treated as absence: a non-array, more
33
+ * than one row, a non-object element, a missing or empty id, a different id,
34
+ * a non-string `publicKey`, or a missing or non-string `name`.
35
+ */
36
+ function parseAgentRows(body, id) {
37
+ if (!Array.isArray(body)) {
38
+ return { ok: false, reason: "operations API returned an unexpected body." };
39
+ }
40
+ if (body.length === 0)
41
+ return { ok: true, row: null };
42
+ if (body.length !== 1) {
43
+ return { ok: false, reason: `operations API returned ${body.length} rows for Agent '${id}'.` };
44
+ }
45
+ const row = body[0];
46
+ if (!row || typeof row !== "object" || Array.isArray(row)) {
47
+ return { ok: false, reason: "operations API returned a malformed Agent row." };
48
+ }
49
+ const rec = row;
50
+ if (typeof rec.id !== "string" || rec.id.length === 0) {
51
+ return { ok: false, reason: "operations API returned a malformed Agent row." };
52
+ }
53
+ if (rec.id !== id) {
54
+ return {
55
+ ok: false,
56
+ reason: `operations API returned Agent '${rec.id}' while looking up '${id}'.`,
57
+ };
58
+ }
59
+ if (rec.publicKey !== undefined && typeof rec.publicKey !== "string") {
60
+ return { ok: false, reason: "operations API returned a malformed Agent row." };
61
+ }
62
+ if (typeof rec.name !== "string") {
63
+ return { ok: false, reason: "operations API returned an Agent row whose name is missing or not a string." };
64
+ }
65
+ const publicKey = typeof rec.publicKey === "string" && rec.publicKey.length > 0 ? rec.publicKey : undefined;
66
+ return {
67
+ ok: true,
68
+ row: {
69
+ id: rec.id,
70
+ name: rec.name,
71
+ ...(publicKey !== undefined ? { publicKey } : {}),
72
+ },
73
+ };
74
+ }
75
+ function agentAlreadyExistsMessage(id) {
76
+ return (`Error: Agent '${id}' already exists; its stored public key was left unchanged. ` +
77
+ `Run \`flair agent rotate-key ${id}\` on the Flair host to replace the key, ` +
78
+ `or \`flair agent remove ${id}\` first and then \`flair agent add ${id}\`. ` +
79
+ `\`flair agent remove\` tries to delete that agent's Memory and Soul rows.`);
80
+ }
81
+ function agentKeyNotStoredMessage(id, stored) {
82
+ let found;
83
+ if (!stored) {
84
+ found = `Reading the record back found no Agent row for '${id}'.`;
85
+ }
86
+ else if (typeof stored.publicKey !== "string" || stored.publicKey.length === 0) {
87
+ found = `An Agent row for '${id}' was found, but it has no usable public key.`;
88
+ }
89
+ else {
90
+ found = `The stored public key is '${stored.publicKey}', which is not the key generated or reused by this command.`;
91
+ }
92
+ return (`Error: Agent '${id}' was not stored with the public key generated or reused by this command. ${found} ` +
93
+ `Run \`flair agent rotate-key ${id}\` on the Flair host to replace the key, ` +
94
+ `or \`flair agent remove ${id}\` first and then \`flair agent add ${id}\`. ` +
95
+ `\`flair agent remove\` tries to delete that agent's Memory and Soul rows.`);
96
+ }
97
+ /**
98
+ * Read one Agent row by id through the operations API.
99
+ * Exits on a failed body read, an empty body, non-JSON, a row whose id is
100
+ * not the one searched, or a row that is unreadable: non-object, missing or
101
+ * empty id, non-string `publicKey`, or missing or non-string `name`.
102
+ * Those results are not "no such agent". A row with this id and a string
103
+ * `name` is returned even when `publicKey` is missing or empty; that is an
104
+ * existing row, and the add success check refuses it. Returns null only
105
+ * when the body is a JSON `[]`.
106
+ */
107
+ async function readStoredAgent(opsPortOrUrl, id, adminUser, adminPass) {
108
+ const auth = Buffer.from(`${adminUser}:${adminPass}`).toString("base64");
109
+ let res;
110
+ try {
111
+ res = await fetch(opsApiUrl(opsPortOrUrl), {
112
+ method: "POST",
113
+ headers: { "Content-Type": "application/json", Authorization: `Basic ${auth}` },
114
+ body: JSON.stringify({
115
+ operation: "search_by_value",
116
+ database: "flair",
117
+ table: "Agent",
118
+ search_attribute: "id",
119
+ search_value: id,
120
+ get_attributes: ["id", "name", "publicKey"],
121
+ }),
122
+ signal: AbortSignal.timeout(10_000),
123
+ });
124
+ }
125
+ catch (err) {
126
+ const message = err instanceof Error ? err.message : String(err);
127
+ console.error(`Error: could not read Agent '${id}': ${message}`);
128
+ process.exit(1);
129
+ }
130
+ let text;
131
+ try {
132
+ text = await res.text();
133
+ }
134
+ catch (err) {
135
+ const message = err instanceof Error ? err.message : String(err);
136
+ console.error(`Error: could not read Agent '${id}': ${message}`);
137
+ process.exit(1);
138
+ }
139
+ if (!res.ok) {
140
+ console.error(`Error: could not read Agent '${id}' (${res.status}): ${text}`);
141
+ process.exit(1);
142
+ }
143
+ if (text.trim().length === 0) {
144
+ console.error(`Error: could not read Agent '${id}': operations API returned an empty body.`);
145
+ process.exit(1);
146
+ }
147
+ let body;
148
+ try {
149
+ body = JSON.parse(text);
150
+ }
151
+ catch {
152
+ console.error(`Error: could not read Agent '${id}': operations API returned a body that is not JSON.`);
153
+ process.exit(1);
154
+ }
155
+ const parsed = parseAgentRows(body, id);
156
+ // `=== false`, not `!parsed.ok`: tsconfig.cli.json is not strict, and `!`
157
+ // does not narrow this union there.
158
+ if (parsed.ok === false) {
159
+ console.error(`Error: could not read Agent '${id}': ${parsed.reason}`);
160
+ process.exit(1);
161
+ }
162
+ return parsed.row;
163
+ }
21
164
  /** Register the `flair agent` command group (flair#1630). */
22
165
  export function register(program) {
23
166
  // ─── flair agent ─────────────────────────────────────────────────────────────
24
167
  const agent = program.command("agent").description("Manage Flair agents");
25
168
  agent
26
169
  .command("add <id>")
27
- .description("Register a new agent in a running Flair instance")
170
+ .description("Register a new agent. Refuses an id whose Agent record already exists")
28
171
  .option("--name <name>", "Display name (defaults to id)")
29
172
  .option("--port <port>", "Harper HTTP port")
30
173
  .option("--admin-pass <pass>", "Admin password for registration")
@@ -92,6 +235,16 @@ export function register(program) {
92
235
  }
93
236
  process.exit(1);
94
237
  }
238
+ // flair#2126 — Harper 5.2.8 skips an insert whose id already exists and
239
+ // still returns OK, so the seed helper's 409/"already exists" path never
240
+ // fires and the old public key stays. Look the id up first and refuse
241
+ // before any key file or insert. A later read-back covers a row that
242
+ // appears in the gap, or an insert that does not store this key.
243
+ const existing = await readStoredAgent(seedOpsTarget, id, adminUser, adminPass);
244
+ if (existing) {
245
+ console.error(agentAlreadyExistsMessage(id));
246
+ process.exit(1);
247
+ }
95
248
  mkdirSync(keysDir, { recursive: true });
96
249
  const privPath = privKeyPath(id, keysDir);
97
250
  const pubPath = pubKeyPath(id, keysDir);
@@ -112,11 +265,16 @@ export function register(program) {
112
265
  console.log(`Keypair written: ${privPath}`);
113
266
  }
114
267
  await seedAgentViaOpsApi(seedOpsTarget, id, pubKeyB64url, adminUser, adminPass);
268
+ const stored = await readStoredAgent(seedOpsTarget, id, adminUser, adminPass);
269
+ if (!stored || stored.publicKey !== pubKeyB64url) {
270
+ console.error(agentKeyNotStoredMessage(id, stored));
271
+ process.exit(1);
272
+ }
115
273
  console.log(typeof seedOpsTarget === "string"
116
274
  ? `✅ Agent '${id}' (${name}) registered (ops: ${seedOpsTarget})`
117
275
  : `✅ Agent '${id}' (${name}) registered`);
118
276
  console.log(` Private key: ${privPath}`);
119
- console.log(` Public key: ${pubKeyB64url}`);
277
+ console.log(` Public key: ${stored.publicKey}`);
120
278
  // flair#1280 — connector legibility at provisioning time: an OAuth /mcp
121
279
  // connector resolves its own token subject to an Agent via
122
280
  // Credential(kind:idp), NOT via this key, and the two identities are
@@ -8,7 +8,7 @@ import { buildEd25519Auth, defaultAdminPassPath, defaultKeysDir, resolveAdminUse
8
8
  import { flairConfigYamlCandidates, readPortFromYamlFile, resolveFlairConfigYaml } from "../lib/doctor-config-path.js";
9
9
  import { collectFederationEnv, describeFederationDriverFinding, federationPeersConfigured, loadYamlDoc } from "../lib/doctor-federation-driver.js";
10
10
  import { plistCarriesInlineAdminPassword } from "../lib/launchd-management.js";
11
- import { DOCTOR_CHECK_IDS, catalogIssueDelta, mcpRepinIcon, renderCatalogDoctorLines, runDoctorChecks } from "../lib/doctor-run.js";
11
+ import { DOCTOR_CHECK_IDS, catalogIssueDelta, mcpRepinIcon, probeFlairHealth, renderCatalogDoctorLines, runDoctorChecks } from "../lib/doctor-run.js";
12
12
  import { describeEmbedGpuDoctorFinding } from "../lib/embed-gpu-doctor.js";
13
13
  import { adminPassDesyncFinding, detectPersistedAdminUser } from "../lib/init-admin-pass.js";
14
14
  import { opsApiBindFinding } from "../lib/ops-api-bind.js";
@@ -385,24 +385,12 @@ export function register(program) {
385
385
  console.log(` ${render.icons.ok} npm global bin dir ${render.wrap(render.c.dim, binCheck.binDir)} is on PATH`);
386
386
  }
387
387
  }
388
- // Helper: try to reach Harper on a given port.
389
- // Must return true ONLY when Harper's /Health endpoint returns 200 OK.
390
- // A generic HTTP status > 0 (flair#862) would accept 404 from a Node
391
- // inspector on 9229 or any other service — "present but wrong" beats
392
- // "absent but correct".
388
+ // Probe a port's /Health.
393
389
  async function probePort(p) {
394
- try {
395
- const res = await fetch(`http://127.0.0.1:${p}/Health`, { signal: AbortSignal.timeout(3000) });
396
- return res.ok; // 200-299 only — /Health returns { ok: true } on 200
397
- }
398
- catch {
399
- return false;
400
- }
390
+ const probe = await probeFlairHealth(`http://127.0.0.1:${p}/Health`);
391
+ return probe.reaching;
401
392
  }
402
- // Helper: discover what port a Harper PID is listening on.
403
- // Scans ALL listening ports for this PID and returns the first one that
404
- // responds to /Health with 200 OK. This avoids picking a debug port (9229)
405
- // or any non-Flair listener that happens to share the process (flair#862).
393
+ // Find the PID's port by probing /Health.
406
394
  async function discoverPortFromPid(pid) {
407
395
  // Defense-in-depth: caller already validates, but re-check here
408
396
  if (!/^\d+$/.test(pid))
@@ -414,7 +402,6 @@ export function register(program) {
414
402
  const ports = [...out.matchAll(/n(?:\S+):(\d+)/g)].map(m => Number(m[1]));
415
403
  if (ports.length === 0)
416
404
  return null;
417
- // Try each port until one responds to /Health with 200 OK
418
405
  for (const port of ports) {
419
406
  if (await probePort(port))
420
407
  return port;
@@ -540,13 +527,17 @@ export function register(program) {
540
527
  // picture here instead of a one-liner and `--fix` offers the restart.
541
528
  let runningVersion = null;
542
529
  let embedGpuFromHealth;
530
+ let workerThreads;
543
531
  if (harperResponding) {
544
532
  try {
545
- const healthRes = await fetch(`${baseUrl}/Health`, { signal: AbortSignal.timeout(3000) });
546
- if (healthRes.ok) {
547
- const body = (await healthRes.json());
548
- runningVersion = typeof body?.version === "string" ? body.version : null;
549
- embedGpuFromHealth = body.embedding;
533
+ const probe = await probeFlairHealth(`${baseUrl}/Health`);
534
+ if (probe.reaching) {
535
+ workerThreads = probe.observation ?? undefined;
536
+ if (probe.status >= 200 && probe.status < 300 && probe.body && typeof probe.body === "object") {
537
+ const healthBody = probe.body;
538
+ runningVersion = typeof healthBody.version === "string" ? healthBody.version : null;
539
+ embedGpuFromHealth = healthBody.embedding;
540
+ }
550
541
  }
551
542
  }
552
543
  catch { /* leave runningVersion null — reported below as "unknown" */ }
@@ -1002,6 +993,7 @@ export function register(program) {
1002
993
  keysDir,
1003
994
  keyAgentIds,
1004
995
  agentFlag: typeof opts.agent === "string" ? opts.agent : undefined,
996
+ workerThreads,
1005
997
  };
1006
998
  const catalogBefore = runDoctorChecks(doctorCtx, { catalogIds: doctorCatalogIds });
1007
999
  // flair#1834 PR-H: a hook file on disk IS the wiring — the same rule the