@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,22 +1,57 @@
1
- import { applyOrReportClaudeMdBootstrap, applyOrReportSessionStartHook } from "../doctor-client.js";
1
+ import { applyOrReportClaudeMdBootstrap } from "../doctor-client.js";
2
+ import { applyOrRepinSessionStartHook } from "../lib/owned-pins.js";
2
3
  import { hookSettingsPath } from "../hook-install.js";
3
4
  import { claudeCodeMcpEntry, detectClients, renderWiringSummary, wireAntigravity, wireClaudeCodeJson, wireCodex, wireCursor, wireGemini, wirePi } from "../install/clients.js";
4
5
  import { DEFAULT_ADMIN_USER, authFetch, defaultAdminPassPath, defaultKeysDir, readAdminPassFileSecure, resolveAdminUser } from "../lib/auth-resolve.js";
5
- import { detectPersistedAdminUser, executeAdminPasswordRotate, initAdminPassRefusalMessage, resolveInitAdminPasswordRefuseReason, resolveInitAdminPasswordSource, } from "../lib/init-admin-pass.js";
6
+ import { INIT_RESET_ADMIN_PASS_COMMAND, detectPersistedAdminUser, executeAdminPasswordRotate, initAdminPassRefusalMessage, resolveInitAdminPasswordRefuseReason, resolveInitAdminPasswordSource, } from "../lib/init-admin-pass.js";
7
+ import { canonicalLexicalPath } from "../lib/daemon-liveness.js";
8
+ import { encodeRecordId } from "../lib/record-id-path.js";
6
9
  import { mcpServerSpec, unpinnedSpecWarning } from "../lib/mcp-spec.js";
10
+ import { planRedirectMigration, renderRedirectMigration } from "../lib/mcp-oauth-env.js";
11
+ import { seedUsingFlairSkill } from "../lib/skill-seed.js";
12
+ import { clearSkillSeedPending, markSkillSeedPending } from "../lib/skill-seed-pending.js";
7
13
  import { opsSocketPathRefusal } from "../lib/socket-path-limit.js";
8
14
  import * as render from "../render.js";
9
15
  import { rewriteFederationSchedulerRuntime } from "../federation/scheduler.js";
10
16
  import { preferVersionManagerAlias } from "../lib/node-alias-path.js";
11
17
  import { spawn } from "node:child_process";
12
18
  import { randomBytes, randomUUID } from "node:crypto";
13
- import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
19
+ import { chmodSync, closeSync, constants, existsSync, fstatSync, lstatSync, mkdirSync, openSync, readFileSync, writeFileSync } from "node:fs";
14
20
  import { join, resolve } from "node:path";
21
+ import { localPortState } from "../lib/init-tcp-probe.js";
22
+ import { trackInitChild } from "../lib/init-spawn-attribution.js";
15
23
  import nacl from "tweetnacl";
16
24
  import { httpCorsAccessList } from "../lib/http-bind.js";
17
25
  import { resolveHome } from "../lib/home.js";
18
- import { foreignOccupiedListenerDetail, staleHarperBeforeAuthNotice, } from "../lib/init-occupied-listener.js";
26
+ import { foreignOccupiedListenerDetail, } from "../lib/init-occupied-listener.js";
19
27
  let cli;
28
+ function ownedInitPidfilePid(dataDir) {
29
+ let fd;
30
+ try {
31
+ const uid = process.getuid?.();
32
+ if (uid === undefined)
33
+ return null;
34
+ const dir = lstatSync(dataDir);
35
+ if (!dir.isDirectory() || dir.uid !== uid || (dir.mode & 0o022))
36
+ return null;
37
+ fd = openSync(join(dataDir, "hdb.pid"), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
38
+ const file = fstatSync(fd);
39
+ if (!file.isFile() || file.nlink !== 1 || file.size > 32 || file.uid !== uid || (file.mode & 0o022))
40
+ return null;
41
+ const value = readFileSync(fd, "utf8").trim();
42
+ if (!/^[1-9]\d*$/.test(value))
43
+ return null;
44
+ const pid = Number(value);
45
+ return Number.isSafeInteger(pid) ? pid : null;
46
+ }
47
+ catch {
48
+ return null;
49
+ }
50
+ finally {
51
+ if (fd !== undefined)
52
+ closeSync(fd);
53
+ }
54
+ }
20
55
  /** Bind the cli-locals this module depends on. */
21
56
  export function bindCli(fns) {
22
57
  cli = fns;
@@ -84,6 +119,9 @@ function resolveHttpPort(...args) {
84
119
  function writeAdminPassFile(...args) {
85
120
  return cli.writeAdminPassFile(...args);
86
121
  }
122
+ function proveAdminPassAgainstInstance(port, adminPass) {
123
+ return cli.proveAdminPassAgainstInstance(port, adminPass);
124
+ }
87
125
  function resolveOpsBindHost(...args) {
88
126
  return cli.resolveOpsBindHost(...args);
89
127
  }
@@ -111,9 +149,31 @@ function reconcileFederationInstanceViaOpsApi(...args) {
111
149
  function seedAgentViaOpsApi(...args) {
112
150
  return cli.seedAgentViaOpsApi(...args);
113
151
  }
152
+ function seedAgentWithLocalHome(...args) {
153
+ return cli.seedAgentWithLocalHome(...args);
154
+ }
114
155
  function seedFederationInstanceViaOpsApi(...args) {
115
156
  return cli.seedFederationInstanceViaOpsApi(...args);
116
157
  }
158
+ /**
159
+ * flair#2141 S2 — seed the org-wide `using-flair` skill on an instance, as the
160
+ * operator. Idempotent (fixed row ids, read by primary key). A refusal names
161
+ * what failed and how to fix it, and FAILS this run: init never reports success
162
+ * after a seed it could not complete.
163
+ */
164
+ async function seedUsingFlairSkillViaRest(baseUrl, adminUser, adminPass) {
165
+ const outcome = await seedUsingFlairSkill({
166
+ baseUrl,
167
+ user: adminUser,
168
+ pass: adminPass,
169
+ notify: (line) => console.log(line),
170
+ });
171
+ if (outcome.kind === "refused") {
172
+ console.error(`Error: the using-flair skill seed was refused — ${outcome.message}`);
173
+ process.exit(1);
174
+ }
175
+ console.log(`using-flair skill: ${outcome.message}`);
176
+ }
117
177
  function readOccupiedListener(port) {
118
178
  return cli.readOccupiedListener(port);
119
179
  }
@@ -146,6 +206,10 @@ function writeDaemonSidecar(...args) {
146
206
  function registerInitLaunchdService(...args) {
147
207
  return cli.registerInitLaunchdService(...args);
148
208
  }
209
+ /** `flair init`'s launchd-step exit code (flair#2040, flair#2085): 1 for a refused, down or uncertain outcome, else 0. */
210
+ function initLaunchdExitCode(kind) {
211
+ return cli.initLaunchdExitCode(kind);
212
+ }
149
213
  function repointMainServiceUnit(...args) {
150
214
  return cli.repointMainServiceUnit(...args);
151
215
  }
@@ -173,7 +237,7 @@ export function register(program) {
173
237
  .option("--admin-user <name>", "Admin username when authenticating to an already-running instance via --target/--ops-target (env: FLAIR_ADMIN_USER; default: admin — local bootstrap and Fabric provisioning always create 'admin')")
174
238
  .option("--keys-dir <dir>", "Directory for Ed25519 keys")
175
239
  .option("--data-dir <dir>", "Harper data directory")
176
- .option("--skip-start", "Skip Harper startup (assume already running)")
240
+ .option("--skip-start", "Do not start Harper; with --agent, defer registration (ignored with --target/--ops-target)")
177
241
  .option("--skip-soul", "Skip interactive personality setup")
178
242
  .option("--client <client>", "Client(s) to wire: claude-code, codex, gemini, cursor, antigravity, pi (native extension), all, or none")
179
243
  .option("--no-mcp", "Skip MCP client wiring (instance + agent only)")
@@ -270,6 +334,36 @@ export function register(program) {
270
334
  let pubKeyB64url;
271
335
  let privPath;
272
336
  let instanceId;
337
+ // Reconcile the federation Instance identity row if --remote (hub role).
338
+ // flair#1883: this used to INSERT a row with a fresh random id on every
339
+ // run, so a hub that had already answered a `GET /FederationInstance`
340
+ // (which find-or-creates a `spoke` row) ended up with TWO rows and no
341
+ // canonical identity. Reconciling keeps the row peers already know.
342
+ // It runs before the agent seed so the agent's home is the hub's id.
343
+ const reconcileHubInstance = async (publicKey) => {
344
+ instanceId = randomUUID();
345
+ console.log(`Reconciling federation Instance (role=${role}) via ops API...`);
346
+ let reconciled;
347
+ try {
348
+ reconciled = await reconcileFederationInstanceViaOpsApi(opsUrl, { instanceId, publicKey }, adminUser, flairAdminPass);
349
+ }
350
+ catch (err) {
351
+ // A refusal (two rows) or an unreachable ops API — both are this
352
+ // command failing, and both already name what to do.
353
+ console.error(`Error: ${err?.message ?? err}`);
354
+ process.exit(1);
355
+ }
356
+ instanceId = reconciled.id;
357
+ if (reconciled.action === "created") {
358
+ console.log(`Federation Instance created: ${reconciled.id} (role=${role}) ✓`);
359
+ }
360
+ else if (reconciled.action === "updated") {
361
+ console.log(`Federation Instance reconciled: ${reconciled.id} is now role=${role} (id and key kept) ✓`);
362
+ }
363
+ else {
364
+ console.log(`Federation Instance already role=${role}: ${reconciled.id} — no change ✓`);
365
+ }
366
+ };
273
367
  if (agentId || role) {
274
368
  const keysDir = opts.keysDir ?? defaultKeysDir();
275
369
  mkdirSync(keysDir, { recursive: true });
@@ -292,9 +386,11 @@ export function register(program) {
292
386
  pubKeyB64url = b64url(kp.publicKey);
293
387
  console.log(`Keypair written: ${privPath} ✓`);
294
388
  }
389
+ if (role)
390
+ await reconcileHubInstance(pubKeyB64url);
295
391
  // Seed agent via remote ops API
296
392
  console.log(`Seeding agent '${agentId}' on ${baseUrl}...`);
297
- await seedAgentViaOpsApi(opsUrl, agentId, pubKeyB64url, adminUser, flairAdminPass);
393
+ await seedAgentWithLocalHome(opsUrl, agentId, pubKeyB64url, adminUser, flairAdminPass);
298
394
  console.log(`Agent '${agentId}' registered on remote instance ✓`);
299
395
  }
300
396
  else {
@@ -302,44 +398,16 @@ export function register(program) {
302
398
  console.log("Generating federation instance keypair...");
303
399
  const kp = nacl.sign.keyPair();
304
400
  pubKeyB64url = b64url(kp.publicKey);
401
+ if (role)
402
+ await reconcileHubInstance(pubKeyB64url);
305
403
  }
306
404
  }
307
405
  else {
308
406
  console.log("No --agent-id provided -- skipping agent registration");
309
407
  }
310
- // Reconcile the federation Instance identity row if --remote (hub role).
311
- // flair#1883: this used to INSERT a row with a fresh random id on every
312
- // run, so a hub that had already answered a `GET /FederationInstance`
313
- // (which find-or-creates a `spoke` row) ended up with TWO rows and no
314
- // canonical identity. Reconciling keeps the row peers already know.
315
- if (role) {
316
- if (!pubKeyB64url) {
317
- const kp = nacl.sign.keyPair();
318
- pubKeyB64url = b64url(kp.publicKey);
319
- }
320
- instanceId = randomUUID();
321
- console.log(`Reconciling federation Instance (role=${role}) via ops API...`);
322
- let reconciled;
323
- try {
324
- reconciled = await reconcileFederationInstanceViaOpsApi(opsUrl, { instanceId, publicKey: pubKeyB64url }, adminUser, flairAdminPass);
325
- }
326
- catch (err) {
327
- // A refusal (two rows) or an unreachable ops API — both are this
328
- // command failing, and both already name what to do.
329
- console.error(`Error: ${err?.message ?? err}`);
330
- process.exit(1);
331
- }
332
- instanceId = reconciled.id;
333
- if (reconciled.action === "created") {
334
- console.log(`Federation Instance created: ${reconciled.id} (role=${role}) ✓`);
335
- }
336
- else if (reconciled.action === "updated") {
337
- console.log(`Federation Instance reconciled: ${reconciled.id} is now role=${role} (id and key kept) ✓`);
338
- }
339
- else {
340
- console.log(`Federation Instance already role=${role}: ${reconciled.id} — no change ✓`);
341
- }
342
- }
408
+ // flair#2141 S2 — seed the org-wide using-flair skill on the remote
409
+ // instance, as the operator. Idempotent; a refusal fails this run.
410
+ await seedUsingFlairSkillViaRest(baseUrl, adminUser, flairAdminPass);
343
411
  // Verify connectivity
344
412
  if (didProvision) {
345
413
  // Use /FederationInstance with Basic auth (not /Health which false-401s on Fabric)
@@ -399,6 +467,18 @@ export function register(program) {
399
467
  // preflight measured. Every downstream use (preflight, config/plist,
400
468
  // ROOTPATH / HARPER_SET_CONFIG, messages) takes this resolved value.
401
469
  const dataDir = opts.dataDir ? resolve(opts.dataDir) : defaultDataDir();
470
+ try {
471
+ const migration = planRedirectMigration({
472
+ env: process.env,
473
+ configPath: join(flairPackageDir(), "config.yaml"),
474
+ });
475
+ const migrationLine = renderRedirectMigration(migration);
476
+ if (migrationLine)
477
+ console.log(` ${migrationLine}`);
478
+ }
479
+ catch (err) {
480
+ console.error(`warning: MCP OAuth redirect migration could not run (${err?.message ?? String(err)}).`);
481
+ }
402
482
  // flair#916: the Harper operations API is a Unix domain socket at
403
483
  // `<data-dir>/operations-server`, and Unix socket paths are capped by
404
484
  // `sun_path` (darwin 104 / linux 108, counting the trailing NUL, so the
@@ -469,14 +549,152 @@ export function register(program) {
469
549
  let reusedExistingAdminPass = false;
470
550
  let pendingAdminPassRotate = false;
471
551
  const adminPassPath = defaultAdminPassPath();
472
- const persistedAdminUser = detectPersistedAdminUser(dataDir);
473
- let alreadyRunning = false;
552
+ let persistedAdminUser;
474
553
  try {
475
- const res = await fetch(`http://127.0.0.1:${httpPort}/health`, { signal: AbortSignal.timeout(1000) });
476
- if (res.status > 0)
554
+ persistedAdminUser = detectPersistedAdminUser(dataDir);
555
+ }
556
+ catch (err) {
557
+ const detail = err instanceof Error ? err.message : String(err);
558
+ console.error(`❌ Refusing to initialize: the Harper system database under ${dataDir} could not be read, ` +
559
+ `so I cannot tell whether an admin user is already persisted (${detail}). ` +
560
+ `Repair that data directory (or point --data-dir at the right one) and re-run.`);
561
+ process.exit(1);
562
+ }
563
+ let alreadyRunning = false;
564
+ let ownChild;
565
+ const freeBeforeSpawn = new Set();
566
+ const refuseUnattributedListener = (listener) => {
567
+ const installedAttributed = harperConfigPath(dataDir) !== null &&
568
+ listener.pids.length === 1 &&
569
+ ownedInitPidfilePid(dataDir) === listener.pids[0] &&
570
+ listener.dataDirs.every(dir => canonicalLexicalPath(dir) === canonicalLexicalPath(dataDir)) &&
571
+ cli.resolveInstanceServingPid(dataDir, listener.port, { findListeningPids: () => [] }) === listener.pids[0];
572
+ const attributed = ownChild ? ownChild.attributes(listener, dataDir, freeBeforeSpawn) : installedAttributed;
573
+ if (attributed)
574
+ return;
575
+ const pid = listener.pids.length === 1 ? `, pid ${listener.pids[0]}` : "";
576
+ console.error(`Refusing init: port ${listener.port}${pid}: attribution to this data directory was not confirmed.`);
577
+ console.error(foreignOccupiedListenerDetail(listener));
578
+ process.exit(1);
579
+ };
580
+ // `detail` is the credential-gate diagnostic (attributeBeforeCredential);
581
+ // the pre-start refusals pass none.
582
+ const refuseFreePort = (listener, detail) => {
583
+ const pid = listener.pids.length === 1 ? `, pid ${listener.pids[0]}` : "";
584
+ console.error(`Refusing init: port ${listener.port}${pid}: TCP readiness check failed${detail ? `: ${detail}` : ""}.`);
585
+ console.error("Remedy: start the instance, then rerun init.");
586
+ process.exit(1);
587
+ };
588
+ // The readiness budget here is `cli.STARTUP_TIMEOUT_MS`, the same duration
589
+ // as the test-harness readiness poll's `HARPER_STARTUP_BUDGET_MS`
590
+ // (test/helpers/harper-lifecycle.ts); test/unit/harper-lifecycle-budgets
591
+ // .test.ts keeps the two durations equal. The probes (a TCP connect here, an
592
+ // HTTP request there) and the points the timers start from differ.
593
+ const attributeBeforeCredential = async (port, host) => {
594
+ const startedAt = Date.now();
595
+ const deadline = startedAt + STARTUP_TIMEOUT_MS;
596
+ let listener = readOccupiedListener(port);
597
+ let state = await localPortState(port, host);
598
+ while (ownChild && state === "free" && Date.now() < deadline) {
599
+ await new Promise(resolve => setTimeout(resolve, 100));
600
+ listener = readOccupiedListener(port);
601
+ state = await localPortState(port, host);
602
+ }
603
+ // Only a child this init spawned is waited for. Without one (init found
604
+ // an instance already running and did not spawn) the port is checked
605
+ // once, so the diagnostic must not claim a wait or a spawned instance.
606
+ if (state === "free") {
607
+ refuseFreePort(listener, ownChild
608
+ ? `still free after ${Date.now() - startedAt}ms (phase: waiting for the spawned instance to listen)`
609
+ : "no listener (phase: TCP readiness check of an instance this init did not spawn; checked once, no wait)");
610
+ }
611
+ if (state === "listening")
612
+ listener = readOccupiedListener(port);
613
+ if (state === "unknown")
614
+ refuseUnknownListener(listener);
615
+ refuseUnattributedListener(listener);
616
+ };
617
+ const refuseUnknownListener = (listener) => {
618
+ const pid = listener.pids.length === 1 ? `, pid ${listener.pids[0]}` : "";
619
+ console.error(`Refusing init: port ${listener.port}${pid}: TCP probe was inconclusive.`);
620
+ console.error("Remedy: check TCP connectivity, then rerun init.");
621
+ process.exit(1);
622
+ };
623
+ if (opts.skipStart && !agentId) {
624
+ try {
625
+ const res = await fetch(`http://127.0.0.1:${httpPort}/health`, { signal: AbortSignal.timeout(1000) });
626
+ if (res.status > 0) {
627
+ alreadyRunning = true;
628
+ }
629
+ }
630
+ catch { }
631
+ const httpListener = readOccupiedListener(httpPort);
632
+ const httpState = await localPortState(httpPort, httpBind.host);
633
+ alreadyRunning ||= httpListener.pids.length > 0 || httpState === "listening";
634
+ if (alreadyRunning) {
635
+ if (httpState === "free")
636
+ refuseFreePort(httpListener);
637
+ refuseUnattributedListener(httpListener);
638
+ console.log(`Harper already running on port ${httpPort} — skipping start`);
639
+ }
640
+ else if (httpState === "unknown") {
641
+ refuseUnknownListener(httpListener);
642
+ }
643
+ const opsListener = readOccupiedListener(opsPort);
644
+ let opsAnswer;
645
+ try {
646
+ const res = await fetch(`http://127.0.0.1:${opsPort}/`, { signal: AbortSignal.timeout(1000) });
647
+ if (res.status > 0)
648
+ opsAnswer = res.status;
649
+ }
650
+ catch { }
651
+ const opsState = await localPortState(opsPort, opsBindHost);
652
+ if (opsAnswer !== undefined || opsListener.pids.length > 0 || opsState === "listening") {
653
+ if (opsState === "free")
654
+ refuseFreePort(opsListener);
655
+ refuseUnattributedListener(opsListener);
656
+ }
657
+ else if (opsState === "unknown") {
658
+ refuseUnknownListener(opsListener);
659
+ }
660
+ }
661
+ else if (!opts.skipStart) {
662
+ try {
663
+ const res = await fetch(`http://127.0.0.1:${httpPort}/health`, { signal: AbortSignal.timeout(1000) });
664
+ if (res.status > 0) {
665
+ alreadyRunning = true;
666
+ }
667
+ }
668
+ catch { }
669
+ const httpListener = readOccupiedListener(httpPort);
670
+ const httpState = await localPortState(httpPort, httpBind.host);
671
+ if (alreadyRunning || httpListener.pids.length > 0 || httpState === "listening") {
672
+ if (httpState === "free")
673
+ refuseFreePort(httpListener);
674
+ refuseUnattributedListener(httpListener);
477
675
  alreadyRunning = true;
676
+ }
677
+ else if (httpState === "unknown") {
678
+ refuseUnknownListener(httpListener);
679
+ }
680
+ const opsListener = readOccupiedListener(opsPort);
681
+ let opsAnswer;
682
+ try {
683
+ const res = await fetch(`http://127.0.0.1:${opsPort}/`, { signal: AbortSignal.timeout(1000) });
684
+ if (res.status > 0)
685
+ opsAnswer = res.status;
686
+ }
687
+ catch { }
688
+ const opsState = await localPortState(opsPort, opsBindHost);
689
+ if (opsAnswer !== undefined || opsListener.pids.length > 0 || opsState === "listening") {
690
+ if (opsState === "free")
691
+ refuseFreePort(opsListener);
692
+ refuseUnattributedListener(opsListener);
693
+ }
694
+ else if (opsState === "unknown") {
695
+ refuseUnknownListener(opsListener);
696
+ }
478
697
  }
479
- catch { /* not running */ }
480
698
  const explicitCredential = !!(opts.adminPassFile || process.env.FLAIR_ADMIN_PASS || process.env.HDB_ADMIN_PASSWORD || opts.adminPass);
481
699
  const passwordCtx = {
482
700
  persistedAdminUser,
@@ -499,12 +717,6 @@ export function register(program) {
499
717
  httpPort,
500
718
  adminPassPath,
501
719
  });
502
- // The port is already taken and this data dir has no admin user.
503
- // The unauthenticated /health probe already ran. This is one read of
504
- // that port's listener — not the before-and-after 401 attribution.
505
- // Name it and exit before any Authorization header is sent. Do not
506
- // signal it. `flair stop` cannot be promised to act on this listener
507
- // (flair#1749).
508
720
  if (reason === "foreign-instance") {
509
721
  const listener = readOccupiedListener(httpPort);
510
722
  const head = initAdminPassRefusalMessage(reason, {
@@ -512,14 +724,54 @@ export function register(program) {
512
724
  httpPort,
513
725
  adminPassPath,
514
726
  offerFlairStop: false,
727
+ pid: listener.pids.length === 1 ? listener.pids[0] : undefined,
515
728
  });
516
- console.error(`${head}\n${foreignOccupiedListenerDetail(listener, dataDir)}`);
729
+ console.error(`${head}\n${foreignOccupiedListenerDetail(listener)}`);
517
730
  }
518
731
  else {
519
732
  console.error(message);
520
733
  }
521
734
  process.exit(1);
522
735
  };
736
+ const persistSuppliedAdminPass = async () => {
737
+ if (resolveInitAdminPasswordSource(false, passwordCtx) !== "re-persist")
738
+ return;
739
+ if (opts.skipStart && !alreadyRunning && existsSync(adminPassPath)) {
740
+ try {
741
+ const saved = lstatSync(adminPassPath);
742
+ if (saved.isFile() && (typeof process.getuid !== "function" || saved.uid === process.getuid()) &&
743
+ readAdminPassFileSecure(adminPassPath) === adminPass)
744
+ return;
745
+ }
746
+ catch (err) {
747
+ console.error(`Error: ${err instanceof Error ? err.message : String(err)}`);
748
+ process.exit(1);
749
+ }
750
+ }
751
+ if (!alreadyRunning && (existsSync(adminPassPath) || persistedAdminUser)) {
752
+ const verificationDeferred = opts.skipStart && !!agentId;
753
+ console.error(`Refusing to write ${adminPassPath}: ` +
754
+ (verificationDeferred
755
+ ? `credential verification is deferred by --skip-start. `
756
+ : `no running instance; a saved admin-pass file or persisted admin user exists. `) +
757
+ `No pass file was written; any existing file is unchanged. ` +
758
+ (verificationDeferred
759
+ ? `Re-run init without --skip-start to verify a different supplied credential.`
760
+ : harperConfigPath(dataDir) !== null
761
+ ? `Start the instance and re-run init with the supplied credential, or run:\n ${INIT_RESET_ADMIN_PASS_COMMAND}`
762
+ : `Run:\n ${INIT_RESET_ADMIN_PASS_COMMAND}`));
763
+ process.exit(1);
764
+ }
765
+ if (alreadyRunning) {
766
+ const failure = await proveAdminPassAgainstInstance(httpPort, adminPass);
767
+ if (failure) {
768
+ console.error(`Refusing to write ${adminPassPath}: ${failure} on port ${httpPort}. No pass file was written; any existing file is unchanged. ` +
769
+ `To rotate the instance's admin password instead, run:\n ${INIT_RESET_ADMIN_PASS_COMMAND}`);
770
+ process.exit(1);
771
+ }
772
+ }
773
+ writeAdminPassFile(adminPassPath, adminPass + "\n");
774
+ };
523
775
  // Read from file if provided
524
776
  if (opts.adminPassFile) {
525
777
  try {
@@ -534,8 +786,8 @@ export function register(program) {
534
786
  refuseIfNeeded(false);
535
787
  pendingAdminPassRotate = resolveInitAdminPasswordSource(false, passwordCtx) === "rotate";
536
788
  }
537
- else if (resolveInitAdminPasswordSource(false, passwordCtx) === "re-persist") {
538
- writeAdminPassFile(adminPassPath, adminPass + "\n");
789
+ else {
790
+ await persistSuppliedAdminPass();
539
791
  }
540
792
  }
541
793
  else if (process.env.FLAIR_ADMIN_PASS) {
@@ -545,8 +797,8 @@ export function register(program) {
545
797
  refuseIfNeeded(false);
546
798
  pendingAdminPassRotate = resolveInitAdminPasswordSource(false, passwordCtx) === "rotate";
547
799
  }
548
- else if (resolveInitAdminPasswordSource(false, passwordCtx) === "re-persist") {
549
- writeAdminPassFile(adminPassPath, adminPass + "\n");
800
+ else {
801
+ await persistSuppliedAdminPass();
550
802
  }
551
803
  }
552
804
  else if (process.env.HDB_ADMIN_PASSWORD) {
@@ -556,8 +808,8 @@ export function register(program) {
556
808
  refuseIfNeeded(false);
557
809
  pendingAdminPassRotate = resolveInitAdminPasswordSource(false, passwordCtx) === "rotate";
558
810
  }
559
- else if (resolveInitAdminPasswordSource(false, passwordCtx) === "re-persist") {
560
- writeAdminPassFile(adminPassPath, adminPass + "\n");
811
+ else {
812
+ await persistSuppliedAdminPass();
561
813
  }
562
814
  }
563
815
  else if (opts.adminPass) {
@@ -568,8 +820,8 @@ export function register(program) {
568
820
  refuseIfNeeded(false);
569
821
  pendingAdminPassRotate = resolveInitAdminPasswordSource(false, passwordCtx) === "rotate";
570
822
  }
571
- else if (resolveInitAdminPasswordSource(false, passwordCtx) === "re-persist") {
572
- writeAdminPassFile(adminPassPath, adminPass + "\n");
823
+ else {
824
+ await persistSuppliedAdminPass();
573
825
  }
574
826
  }
575
827
  else {
@@ -577,8 +829,6 @@ export function register(program) {
577
829
  const fileExists = existsSync(adminPassPath);
578
830
  const decision = resolveInitAdminPasswordSource(fileExists, passwordCtx);
579
831
  if (decision === "reuse-existing") {
580
- // flair#827: an admin-pass file already on disk means a PRIOR `flair
581
- // init` already bootstrapped Harper's admin user with this password.
582
832
  try {
583
833
  adminPass = readAdminPassFileSecure(adminPassPath);
584
834
  }
@@ -637,32 +887,25 @@ export function register(program) {
637
887
  // The socket doesn't exist yet, so only the parent-dir mode is applied here.
638
888
  mkdirSync(dataDir, { recursive: true });
639
889
  readyOpsSocketPosture(dataDir);
640
- // True only when the port was already answering and the single pre-auth
641
- // read did not include a different data directory (that case exits
642
- // below, before any authenticated request). An unreadable directory,
643
- // including every macOS lookup, does not count as different. A later
644
- // ops 401 is a separate before-and-after read of the operations port,
645
- // not this HTTP observation (flair#1749).
646
890
  let skippedOwnStart = false;
647
- if (!opts.skipStart) {
648
- if (alreadyRunning) {
649
- console.log(`Harper already running on port ${httpPort} — skipping start`);
650
- // One read of the HTTP port that answered /health. When that read
651
- // includes a ROOTPATH other than this init's, stop before
652
- // waitForHealth, which would send Authorization. An unreadable
653
- // directory is not treated as foreign. This is not the
654
- // before-and-after check used for an operations-port 401. A
655
- // different directory does not prove the passwords differ, and
656
- // this init does not signal the process.
657
- const httpListener = readOccupiedListener(httpPort);
658
- const notice = staleHarperBeforeAuthNotice(dataDir, httpListener);
659
- if (notice) {
660
- console.error(notice);
661
- process.exit(1);
662
- }
663
- skippedOwnStart = true;
664
- }
665
- if (!alreadyRunning) {
891
+ if (!opts.skipStart && alreadyRunning) {
892
+ console.log(`Harper already running on port ${httpPort} — skipping start`);
893
+ skippedOwnStart = true;
894
+ }
895
+ if (!alreadyRunning) {
896
+ // Detect whether Harper has already been installed in this data dir.
897
+ // Harper's config is created during install — its presence means
898
+ // install already ran. Re-running install against an existing data dir
899
+ // crashes in Harper v5 beta.6+ (checkForExistingInstall queries the
900
+ // database before the env is initialized). Goes through
901
+ // harperConfigPath so an install predating Harper's config-file rename
902
+ // (harperdb-config.yaml) is still recognised as installed rather than
903
+ // re-installed over.
904
+ const alreadyInstalled = harperConfigPath(dataDir) !== null;
905
+ const willStart = !opts.skipStart;
906
+ // An already-installed instance with --skip-start is not installed
907
+ // over or started.
908
+ if (!alreadyInstalled || willStart) {
666
909
  const bin = harperBin();
667
910
  if (!bin) {
668
911
  throw new Error("Harper CLI not found: no dist/bin/harper.js under node_modules/harper " +
@@ -672,15 +915,6 @@ export function register(program) {
672
915
  "or interrupted install.\nFix: reinstall flair — npm install -g @tpsdev-ai/flair");
673
916
  }
674
917
  mkdirSync(dataDir, { recursive: true });
675
- // Detect whether Harper has already been installed in this data dir.
676
- // Harper's config is created during install — its presence means
677
- // install already ran. Re-running install against an existing data dir
678
- // crashes in Harper v5 beta.6+ (checkForExistingInstall queries the
679
- // database before the env is initialized). Goes through
680
- // harperConfigPath so an install predating Harper's config-file rename
681
- // (harperdb-config.yaml) is still recognised as installed rather than
682
- // re-installed over.
683
- const alreadyInstalled = harperConfigPath(dataDir) !== null;
684
918
  const opsSocket = join(dataDir, "operations-server");
685
919
  // authorizeLocal: false (flair#654) — a credential-less loopback ops-API
686
920
  // request is no longer auto-authorized as super_user. Every ops-API
@@ -777,17 +1011,35 @@ export function register(program) {
777
1011
  // Start Harper with flair loaded as a component (the "." arg).
778
1012
  // ROOTPATH in env points to the data dir; authorizeLocal and thread
779
1013
  // count are set via HARPER_SET_CONFIG — no need for dev mode.
780
- console.log(`Starting Harper on port ${httpPort}...`);
781
- const proc = spawn(process.execPath, [bin, "run", "."], { cwd: flairPackageDir(), env, detached: true, stdio: "ignore" });
782
- proc.unref();
783
- // flair#1454: write the identity sidecar immediately after spawn so
784
- // `flair stop` and `flair status` can classify this daemon's state
785
- // without lsof. Same call as startFlairProcess() uses.
786
- if (proc.pid)
787
- writeDaemonSidecar(dataDir, proc.pid, httpPort);
1014
+ if (willStart) {
1015
+ console.log(`Starting Harper on port ${httpPort}...`);
1016
+ for (const [port, host] of [[httpPort, httpBind.host], [opsPort, opsBindHost]]) {
1017
+ const listener = readOccupiedListener(port);
1018
+ const state = await localPortState(port, host);
1019
+ if (state === "unknown")
1020
+ refuseUnknownListener(listener);
1021
+ if (listener.pids.length > 0 || state !== "free") {
1022
+ const pid = listener.pids.length === 1 ? `, pid ${listener.pids[0]}` : "";
1023
+ console.error(`Refusing init: port ${port}${pid}: pre-start port check failed.`);
1024
+ console.error(foreignOccupiedListenerDetail(listener));
1025
+ process.exit(1);
1026
+ }
1027
+ freeBeforeSpawn.add(port);
1028
+ }
1029
+ const proc = spawn(process.execPath, [bin, "run", "."], { cwd: flairPackageDir(), env, detached: true, stdio: "ignore" });
1030
+ ownChild = trackInitChild(proc);
1031
+ proc.unref();
1032
+ // flair#1454: write the identity sidecar immediately after spawn so
1033
+ // `flair stop` and `flair status` can classify this daemon's state
1034
+ // without lsof. Same call as startFlairProcess() uses.
1035
+ if (proc.pid)
1036
+ writeDaemonSidecar(dataDir, proc.pid, httpPort);
1037
+ }
788
1038
  }
1039
+ }
1040
+ if (!opts.skipStart) {
789
1041
  console.log("Waiting for Harper health check...");
790
- await waitForHealth(httpPort, adminUser, adminPass, STARTUP_TIMEOUT_MS);
1042
+ await waitForHealth(httpPort, adminUser, adminPass, STARTUP_TIMEOUT_MS, () => attributeBeforeCredential(httpPort, httpBind.host));
791
1043
  console.log("Harper is healthy ✓");
792
1044
  // flair#763: the socket now exists — apply its file mode (+ chgrp for the
793
1045
  // FLAIR_SOCKET_GROUP opt-in). The dir gate above is re-asserted idempotently.
@@ -891,9 +1143,9 @@ export function register(program) {
891
1143
  for (const line of launchdStep.lines) {
892
1144
  (line.stream === "err" ? console.error : console.log)(line.text);
893
1145
  }
894
- if (launchdStep.kind === "refused" || launchdStep.kind === "down" || launchdStep.kind === "uncertain") {
895
- process.exit(1);
896
- }
1146
+ const launchdExit = initLaunchdExitCode(launchdStep.kind);
1147
+ if (launchdExit !== 0)
1148
+ process.exit(launchdExit);
897
1149
  }
898
1150
  }
899
1151
  // flair#2034 §2: on Linux the instance's own service is the systemd
@@ -975,6 +1227,29 @@ export function register(program) {
975
1227
  // from the still-persisted wildcard. Writing the resolved host on every init
976
1228
  // means an explicit loopback also persists, so a widening can be reversed.
977
1229
  persistDefaultInstallCoordinates(dataDir, httpPort, opsPort, opsBindHost, httpBind.host);
1230
+ // flair#2141 S2 — seed the org-wide using-flair skill on this instance, as
1231
+ // the operator. Re-initializing an already-installed default local instance
1232
+ // with `flair init --skip-start` defers seeding to a later `flair start`
1233
+ // with the admin credential; that command has no `--data-dir` flag.
1234
+ // (Remote init, `--target`, seeds with or
1235
+ // without `--skip-start`.) A refusal fails this run rather than reporting a
1236
+ // successful init without the skill, so both local paths call it before
1237
+ // they print their success summary.
1238
+ const seedUsingFlairSkillOnInstall = async () => {
1239
+ if (opts.skipStart) {
1240
+ if (dataDir === defaultDataDir()) {
1241
+ markSkillSeedPending(dataDir);
1242
+ console.log("using-flair skill: pending");
1243
+ }
1244
+ else {
1245
+ console.log("using-flair skill: not seeded");
1246
+ }
1247
+ return;
1248
+ }
1249
+ await attributeBeforeCredential(httpPort, httpBind.host);
1250
+ await seedUsingFlairSkillViaRest(`http://127.0.0.1:${httpPort}`, adminUser, adminPass);
1251
+ clearSkillSeedPending(dataDir);
1252
+ };
978
1253
  if (agentId) {
979
1254
  // Generate or reuse keypair
980
1255
  mkdirSync(keysDir, { recursive: true });
@@ -998,85 +1273,85 @@ export function register(program) {
998
1273
  pubKeyB64url = b64url(kp.publicKey);
999
1274
  console.log(`Keypair written: ${privPath} ✓`);
1000
1275
  }
1001
- // Seed agent via operations API. Unlike the pre-auth observation,
1002
- // which is one read, a 401 names a pid only when the read before the
1003
- // insert and the read after the rejection are the same sole PID. The
1004
- // HTTP port's holder is not an input and is not assumed to have caused
1005
- // the rejection. Several holders, or a holder that changed during the
1006
- // request, stay unattributed. Init started Harper itself → no listener,
1007
- // and that 401 keeps the credential hint.
1008
- console.log(`Seeding agent '${agentId}' via operations API...`);
1009
- const opsListener = skippedOwnStart ? operationsPortAttribution(opsPort) : undefined;
1010
- await seedAgentViaOpsApi(opsPort, agentId, pubKeyB64url, adminUser, adminPass, opsListener);
1011
- console.log(`Agent '${agentId}' registered ✓`);
1012
- // Verify Ed25519 auth
1013
- console.log("Verifying Ed25519 auth...");
1014
1276
  const httpUrl = `http://127.0.0.1:${httpPort}`;
1015
- const verifyRes = await authFetch(httpUrl, agentId, privPath, "GET", `/Agent/${agentId}`);
1016
- if (!verifyRes.ok)
1017
- throw new Error(`Ed25519 auth verification failed: ${verifyRes.status}`);
1018
- console.log("Ed25519 auth verified ✓");
1019
- // Verify semantic search ACTUALLY works (real embed→paraphrase-search
1020
- // round-trip). A clean-VM dogfood found semantic search dead out of the box
1021
- // (sudo/root-owned install can't write the embeddings models symlink →
1022
- // EACCES) while init reported success. Never report a clean init when
1023
- // recall-by-meaning is broken. Skipped paths (no key yet) are non-fatal.
1024
- console.log("Verifying semantic search...");
1025
- const embedCheck = await verifySemanticSearch(httpUrl, agentId, keysDir);
1026
- if (embedCheck.state === "ok") {
1027
- console.log(`Semantic search operational ✓ ${render.wrap(render.c.dim, `(paraphrase recall verified, score ${embedCheck.score.toFixed(2)})`)}`);
1028
- }
1029
- else if (embedCheck.state === "degraded") {
1030
- // LOUD — embeddings not loaded. Same message class as `flair doctor`.
1031
- console.log(`\n${render.icons.error} ${render.wrap(render.c.red, "Semantic search DEGRADED")} — embeddings not loaded; recall-by-meaning will NOT work.`);
1032
- console.log(` ${render.wrap(render.c.dim, `(${embedCheck.detail})`)}`);
1033
- console.log(` ${render.wrap(render.c.dim, "Common cause: the embeddings component lacks write access (sudo/root global installs).")}`);
1034
- console.log(` ${render.wrap(render.c.dim, "Fix: install without sudo (see README Quick Start), then:")} flair restart && flair doctor`);
1035
- }
1036
- else if (embedCheck.state === "failed") {
1037
- // flair#1501: the instance rejected the probe's signature. init just
1038
- // registered this agent, so this is a genuine auth defect, not a
1039
- // missing identity — surface it loudly with the signer named.
1040
- console.log(`\n${render.icons.error} ${render.wrap(render.c.red, "Semantic search probe rejected")} — ${embedCheck.detail}.`);
1041
- console.log(` ${render.wrap(render.c.dim, "Fix: register this key on the instance (`flair agent add <id>`) or pass --agent <a registered agent id>.")}`);
1042
- }
1043
- else {
1044
- console.log(`${render.icons.warn} Semantic search not verified ${render.wrap(render.c.dim, `(${embedCheck.detail})`)}`);
1045
- }
1046
- // Verify the audit log ACTUALLY records (flair#970) — a positive
1047
- // control, not a flag read: `describe_table` reports `audit: true` on
1048
- // nodes whose audit trail is empty (base-copy elision, harper#2212).
1049
- // Same surface as the semantic-search check above.
1050
- console.log("Verifying audit log...");
1051
- const auditCheck = await verifyAuditLog(httpUrl, agentId, keysDir, `http://127.0.0.1:${opsPort}`, adminUser, adminPass);
1052
- if (auditCheck.state === "ok") {
1053
- // Present tense ONLY: the probe proves current recording, never
1054
- // historical completeness — see AuditVerifyResult's doc comment.
1055
- console.log(`Audit log: recording (verified now) ✓ ${render.wrap(render.c.dim, "(verifies current recording, not history — a resynced node's audit has a hard start boundary at its copy time)")}`);
1056
- }
1057
- else if (auditCheck.state === "degraded") {
1058
- if (auditCheck.cause === "disabled") {
1059
- console.log(`\n${render.icons.error} ${render.wrap(render.c.red, "Audit log DISABLED")} — ${auditCheck.detail}.`);
1060
- console.log(` ${render.wrap(render.c.dim, "Fix: enable logging.auditLog in the ROOT harperdb-config.yaml (the Harper instance config, NOT flair's component config.yaml), then restart Harper.")}`);
1277
+ if (!opts.skipStart) {
1278
+ console.log(`Seeding agent '${agentId}' via operations API...`);
1279
+ const opsListener = skippedOwnStart ? operationsPortAttribution(opsPort) : undefined;
1280
+ await attributeBeforeCredential(opsPort, opsBindHost);
1281
+ await seedAgentWithLocalHome(opsPort, agentId, pubKeyB64url, adminUser, adminPass, opsListener);
1282
+ console.log(`Agent '${agentId}' registered ✓`);
1283
+ // Verify Ed25519 auth
1284
+ console.log("Verifying Ed25519 auth...");
1285
+ const verifyRes = await authFetch(httpUrl, agentId, privPath, "GET", `/Agent/${encodeRecordId(agentId)}`);
1286
+ if (!verifyRes.ok)
1287
+ throw new Error(`Ed25519 auth verification failed: ${verifyRes.status}`);
1288
+ console.log("Ed25519 auth verified ✓");
1289
+ // Verify semantic search ACTUALLY works (real embed→paraphrase-search
1290
+ // round-trip). A clean-VM dogfood found semantic search dead out of the box
1291
+ // (sudo/root-owned install can't write the embeddings models symlink →
1292
+ // EACCES) while init reported success. Never report a clean init when
1293
+ // recall-by-meaning is broken. Skipped paths (no key yet) are non-fatal.
1294
+ console.log("Verifying semantic search...");
1295
+ const embedCheck = await verifySemanticSearch(httpUrl, agentId, keysDir);
1296
+ if (embedCheck.state === "ok") {
1297
+ console.log(`Semantic search operational ✓ ${render.wrap(render.c.dim, `(paraphrase recall verified, score ${embedCheck.score.toFixed(2)})`)}`);
1298
+ }
1299
+ else if (embedCheck.state === "degraded") {
1300
+ // LOUD — embeddings not loaded. Same message class as `flair doctor`.
1301
+ console.log(`\n${render.icons.error} ${render.wrap(render.c.red, "Semantic search DEGRADED")} — embeddings not loaded; recall-by-meaning will NOT work.`);
1302
+ console.log(` ${render.wrap(render.c.dim, `(${embedCheck.detail})`)}`);
1303
+ console.log(` ${render.wrap(render.c.dim, "Common cause: the embeddings component lacks write access (sudo/root global installs).")}`);
1304
+ console.log(` ${render.wrap(render.c.dim, "Fix: install without sudo (see README Quick Start), then:")} flair restart && flair doctor`);
1305
+ }
1306
+ else if (embedCheck.state === "failed") {
1307
+ // flair#1501: the instance rejected the probe's signature. init just
1308
+ // registered this agent, so this is a genuine auth defect, not a
1309
+ // missing identity — surface it loudly with the signer named.
1310
+ console.log(`\n${render.icons.error} ${render.wrap(render.c.red, "Semantic search probe rejected")} — ${embedCheck.detail}.`);
1311
+ console.log(` ${render.wrap(render.c.dim, "Fix: register this key on the instance (`flair agent add <id>`) or pass --agent <a registered agent id>.")}`);
1061
1312
  }
1062
1313
  else {
1063
- console.log(`\n${render.icons.error} ${render.wrap(render.c.red, "Audit log NOT RECORDING")} — ${auditCheck.detail}.`);
1064
- console.log(` ${render.wrap(render.c.red, "Audit reports as enabled, but fresh writes produced no audit entries — do not treat the audit log as a record of what happened.")}`);
1065
- console.log(` ${render.wrap(render.c.dim, "On a node that joined or resynced via cluster base copy, audit history has a hard start boundary at copy time (harper#2212) — \"no history\" does not mean \"nothing happened\".")}`);
1066
- console.log(` ${render.wrap(render.c.dim, "Check logging.auditLog in the ROOT harperdb-config.yaml (not flair's component config.yaml), then restart Harper.")}`);
1314
+ console.log(`${render.icons.warn} Semantic search not verified ${render.wrap(render.c.dim, `(${embedCheck.detail})`)}`);
1315
+ }
1316
+ // Verify the audit log ACTUALLY records (flair#970) — a positive
1317
+ // control, not a flag read: `describe_table` reports `audit: true` on
1318
+ // nodes whose audit trail is empty (base-copy elision, harper#2212).
1319
+ // Same surface as the semantic-search check above.
1320
+ console.log("Verifying audit log...");
1321
+ const auditCheck = await verifyAuditLog(httpUrl, agentId, keysDir, `http://127.0.0.1:${opsPort}`, adminUser, adminPass);
1322
+ if (auditCheck.state === "ok") {
1323
+ // Present tense ONLY: the probe proves current recording, never
1324
+ // historical completeness — see AuditVerifyResult's doc comment.
1325
+ console.log(`Audit log: recording (verified now) ✓ ${render.wrap(render.c.dim, "(verifies current recording, not history — a resynced node's audit has a hard start boundary at its copy time)")}`);
1326
+ }
1327
+ else if (auditCheck.state === "degraded") {
1328
+ if (auditCheck.cause === "disabled") {
1329
+ console.log(`\n${render.icons.error} ${render.wrap(render.c.red, "Audit log DISABLED")} — ${auditCheck.detail}.`);
1330
+ console.log(` ${render.wrap(render.c.dim, "Fix: enable logging.auditLog in the ROOT harperdb-config.yaml (the Harper instance config, NOT flair's component config.yaml), then restart Harper.")}`);
1331
+ }
1332
+ else {
1333
+ console.log(`\n${render.icons.error} ${render.wrap(render.c.red, "Audit log NOT RECORDING")} — ${auditCheck.detail}.`);
1334
+ console.log(` ${render.wrap(render.c.red, "Audit reports as enabled, but fresh writes produced no audit entries — do not treat the audit log as a record of what happened.")}`);
1335
+ console.log(` ${render.wrap(render.c.dim, "On a node that joined or resynced via cluster base copy, audit history has a hard start boundary at copy time (harper#2212) — \"no history\" does not mean \"nothing happened\".")}`);
1336
+ console.log(` ${render.wrap(render.c.dim, "Check logging.auditLog in the ROOT harperdb-config.yaml (not flair's component config.yaml), then restart Harper.")}`);
1337
+ }
1338
+ }
1339
+ else if (auditCheck.state === "failed") {
1340
+ // Same loud discipline as the semantic-search probe above (flair#1501).
1341
+ console.log(`\n${render.icons.error} ${render.wrap(render.c.red, "Audit log probe rejected")} — ${auditCheck.detail}.`);
1342
+ console.log(` ${render.wrap(render.c.dim, "Fix: register this key on the instance (`flair agent add <id>`) or pass --agent <a registered agent id>.")}`);
1343
+ }
1344
+ else {
1345
+ // An unrun check must not look like a pass.
1346
+ console.log(`${render.icons.warn} Audit log: UNVERIFIED (could not probe — ${auditCheck.detail})`);
1067
1347
  }
1068
- }
1069
- else if (auditCheck.state === "failed") {
1070
- // Same loud discipline as the semantic-search probe above (flair#1501).
1071
- console.log(`\n${render.icons.error} ${render.wrap(render.c.red, "Audit log probe rejected")} — ${auditCheck.detail}.`);
1072
- console.log(` ${render.wrap(render.c.dim, "Fix: register this key on the instance (`flair agent add <id>`) or pass --agent <a registered agent id>.")}`);
1073
1348
  }
1074
1349
  else {
1075
- // An unrun check must not look like a pass.
1076
- console.log(`${render.icons.warn} Audit log: UNVERIFIED (could not probe — ${auditCheck.detail})`);
1350
+ console.log(`Agent registration deferred. After flair start, run flair init --agent ${JSON.stringify(agentId)} (keep your instance flags).`);
1077
1351
  }
1078
- // Output — admin password printed once, never written to disk
1079
- console.log("\n✅ Flair initialized successfully");
1352
+ // flair#2141 S2 — seed the using-flair skill before init reports success.
1353
+ await seedUsingFlairSkillOnInstall();
1354
+ console.log(opts.skipStart ? "\n✅ Flair configured locally (no agent registered)" : "\n✅ Flair initialized successfully");
1080
1355
  console.log(` Agent ID: ${agentId}`);
1081
1356
  console.log(` Flair URL: ${httpUrl}`);
1082
1357
  console.log(` Private key: ${privPath}`);
@@ -1104,13 +1379,13 @@ export function register(program) {
1104
1379
  // "AI assistant [default]" — it leaked into bootstrap output and
1105
1380
  // confused users. Now those paths leave the soul empty and nudge the
1106
1381
  // user toward `flair soul set` / `flair doctor` instead.
1107
- if (!opts.skipSoul && process.stdin.isTTY) {
1382
+ if (!opts.skipStart && !opts.skipSoul && process.stdin.isTTY) {
1108
1383
  const soulEntries = await runSoulWizard(agentId);
1109
1384
  if (soulEntries.length > 0) {
1110
1385
  console.log("");
1111
1386
  for (const [key, value] of soulEntries) {
1112
1387
  try {
1113
- await api("PUT", `/Soul/${agentId}:${key}`, { id: `${agentId}:${key}`, agentId, key, value, createdAt: new Date().toISOString() }, { baseUrl: httpUrl, explicitAdminPass: adminPass, adminUser });
1388
+ await api("PUT", `/Soul/${encodeRecordId(`${agentId}:${key}`)}`, { id: `${agentId}:${key}`, agentId, key, value, createdAt: new Date().toISOString() }, { baseUrl: httpUrl, explicitAdminPass: adminPass, adminUser });
1114
1389
  console.log(` ✓ soul:${key} set`);
1115
1390
  }
1116
1391
  catch (err) {
@@ -1128,7 +1403,7 @@ export function register(program) {
1128
1403
  }
1129
1404
  }
1130
1405
  else {
1131
- const reason = opts.skipSoul ? "--skip-soul" : "non-interactive";
1406
+ const reason = opts.skipStart ? "--skip-start" : opts.skipSoul ? "--skip-soul" : "non-interactive";
1132
1407
  console.log(`\n Soul prompts skipped (${reason}). Add entries with:`);
1133
1408
  console.log(` flair soul set --agent ${agentId} --key role --value "..."`);
1134
1409
  }
@@ -1277,7 +1552,7 @@ export function register(program) {
1277
1552
  // ~/.claude/settings.json — without it, mcp__flair__bootstrap only
1278
1553
  // ever runs if the agent remembers to call it itself.
1279
1554
  // --skip-hook opts out and prints the exact JSON to add by hand.
1280
- const hookResult = applyOrReportSessionStartHook(resolveHome(), agentId, !!opts.skipHook);
1555
+ const hookResult = applyOrRepinSessionStartHook(resolveHome(), agentId, !!opts.skipHook);
1281
1556
  console.log(` ${hookResult.ok ? "✓" : "•"} ${hookResult.message}`);
1282
1557
  if (hookResult.hint) {
1283
1558
  for (const line of hookResult.hint.split("\n"))
@@ -1318,7 +1593,7 @@ export function register(program) {
1318
1593
  // consent to set up the client, same as the Claude Code hook
1319
1594
  // applied above. --skip-hook opts out and prints the JSON.
1320
1595
  if (clientId === "codex" && result.ok) {
1321
- const hookResult = applyOrReportSessionStartHook(resolveHome(), agentId, !!opts.skipHook, hookSettingsPath(resolveHome(), "codex"));
1596
+ const hookResult = applyOrRepinSessionStartHook(resolveHome(), agentId, !!opts.skipHook, hookSettingsPath(resolveHome(), "codex"));
1322
1597
  console.log(` ${hookResult.ok ? "✓" : "•"} ${hookResult.message}`);
1323
1598
  if (hookResult.hint) {
1324
1599
  for (const line of hookResult.hint.split("\n"))
@@ -1337,7 +1612,7 @@ export function register(program) {
1337
1612
  // would render a green "MCP server responded" for a setup that never
1338
1613
  // starts an MCP server.
1339
1614
  const wiredAnyMcpClient = wiringResults.some((r) => r.client !== "pi");
1340
- if (!opts.skipSmoke && !noMcp && clientOpt !== "none" && wiringResults.length > 0 && wiredAnyMcpClient) {
1615
+ if (!opts.skipStart && !opts.skipSmoke && !noMcp && clientOpt !== "none" && wiringResults.length > 0 && wiredAnyMcpClient) {
1341
1616
  console.log("\n Smoke-testing MCP server...");
1342
1617
  try {
1343
1618
  // The RUNNING CLI's own server: mcpServerSpec() pins to THIS
@@ -1440,6 +1715,8 @@ export function register(program) {
1440
1715
  }
1441
1716
  else {
1442
1717
  const httpUrl = `http://127.0.0.1:${httpPort}`;
1718
+ // flair#2141 S2 — seed the using-flair skill before init reports success.
1719
+ await seedUsingFlairSkillOnInstall();
1443
1720
  console.log("\n✅ Flair initialized (no agent registered)");
1444
1721
  console.log(` Flair URL: ${httpUrl}`);
1445
1722
  // Display admin credentials when password was generated or from a file
@@ -1470,14 +1747,6 @@ export function register(program) {
1470
1747
  console.log(` Complete setup with: flair init --agent <id> --client all`);
1471
1748
  }
1472
1749
  }
1473
- // All init work is genuinely done at this point: Harper is installed +
1474
- // running (detached, unref'd — survives this process exiting), the agent is
1475
- // registered, semantic search is verified, MCP clients are wired, and the
1476
- // smoke test ran. The MCP smoke subprocess can leave a lingering npx handle
1477
- // that pins Node's event loop for ~60s after success ("rc=0 but doesn't
1478
- // return"). We've cleared/unref'd the known timers above; exit explicitly so
1479
- // the prompt returns in a couple seconds regardless of any stray handle. The
1480
- // running Harper instance is unaffected.
1481
1750
  await new Promise((r) => process.stdout.write("", () => r()));
1482
1751
  process.exit(0);
1483
1752
  });