@tpsdev-ai/flair 0.59.0 → 0.63.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 (359) hide show
  1. package/README.md +10 -10
  2. package/SECURITY.md +49 -5
  3. package/config.yaml +23 -12
  4. package/dist/bridges/builtins/mem0.js +63 -28
  5. package/dist/bridges/runtime/execute.js +1 -0
  6. package/dist/bridges/runtime/import-runner.js +12 -0
  7. package/dist/bridges/runtime/load-plugin.js +42 -13
  8. package/dist/bridges/runtime/yaml-loader.js +4 -2
  9. package/dist/bridges/types.js +1 -0
  10. package/dist/build-info.json +3 -3
  11. package/dist/cli.js +1054 -367
  12. package/dist/commands/agent.js +233 -90
  13. package/dist/commands/attention.js +4 -3
  14. package/dist/commands/backup-approval.js +218 -0
  15. package/dist/commands/backup.js +211 -39
  16. package/dist/commands/bootstrap.js +3 -1
  17. package/dist/commands/bridge.js +172 -119
  18. package/dist/commands/deploy.js +71 -8
  19. package/dist/commands/doctor.js +711 -146
  20. package/dist/commands/export.js +57 -23
  21. package/dist/commands/federation.js +787 -82
  22. package/dist/commands/grant.js +5 -6
  23. package/dist/commands/help.js +25 -0
  24. package/dist/commands/hook.js +155 -2
  25. package/dist/commands/idp.js +27 -19
  26. package/dist/commands/import.js +136 -20
  27. package/dist/commands/init.js +469 -200
  28. package/dist/commands/integrity.js +387 -0
  29. package/dist/commands/keys.js +247 -58
  30. package/dist/commands/mcp.js +108 -52
  31. package/dist/commands/memory.js +203 -35
  32. package/dist/commands/migrate-harness-memory.js +3 -2
  33. package/dist/commands/orgevent.js +51 -47
  34. package/dist/commands/presence.js +4 -3
  35. package/dist/commands/principal.js +428 -62
  36. package/dist/commands/quality.js +13 -1
  37. package/dist/commands/reembed.js +141 -17
  38. package/dist/commands/relationship.js +2 -1
  39. package/dist/commands/rem.js +537 -80
  40. package/dist/commands/restore.js +413 -65
  41. package/dist/commands/search.js +6 -4
  42. package/dist/commands/service.js +235 -40
  43. package/dist/commands/soul.js +4 -9
  44. package/dist/commands/status.js +94 -38
  45. package/dist/commands/test.js +7 -3
  46. package/dist/commands/upgrade.js +77 -23
  47. package/dist/commands/workspace.js +13 -11
  48. package/dist/component-env.js +31 -41
  49. package/dist/deploy.js +136 -4
  50. package/dist/doctor-client.js +534 -92
  51. package/dist/engine-version-contract.js +1 -0
  52. package/dist/engine-version.js +23 -3
  53. package/dist/fabric-upgrade.js +12 -2
  54. package/dist/federation/presence-send.js +139 -0
  55. package/dist/federation-verify.js +273 -180
  56. package/dist/hook-install.js +670 -6
  57. package/dist/install/clients.js +171 -35
  58. package/dist/keystore.js +72 -0
  59. package/dist/lib/action-recall-runtime.js +328 -0
  60. package/dist/lib/agent-home-fields.js +132 -0
  61. package/dist/lib/agent-home.js +427 -0
  62. package/dist/lib/agent-id-rule.js +88 -0
  63. package/dist/lib/agent-roster.js +33 -0
  64. package/dist/lib/atomic-write.js +1 -1
  65. package/dist/lib/auth-resolve.js +1069 -60
  66. package/dist/lib/backup-approval-store.js +612 -0
  67. package/dist/lib/backup-artifact.js +343 -0
  68. package/dist/lib/capture-runtime.js +124 -0
  69. package/dist/lib/config-critical-section.js +212 -25
  70. package/dist/lib/connect-phase.js +33 -0
  71. package/dist/lib/credential-status-rule.js +78 -0
  72. package/dist/lib/daemon-liveness.js +43 -11
  73. package/dist/lib/doctor-run.js +75 -37
  74. package/dist/lib/durability-copy.js +10 -0
  75. package/dist/lib/embedding-space-doctor.js +75 -0
  76. package/dist/lib/federation-pair-access.js +4 -0
  77. package/dist/lib/federation-retry-queue.js +283 -0
  78. package/dist/lib/federation-retry-row.js +101 -0
  79. package/dist/lib/flair-agent-role.js +4 -0
  80. package/dist/lib/hub-url.js +12 -0
  81. package/dist/lib/init-admin-pass.js +88 -12
  82. package/dist/lib/init-listener-environ.js +1 -2
  83. package/dist/lib/init-occupied-listener.js +15 -111
  84. package/dist/lib/init-spawn-attribution.js +73 -0
  85. package/dist/lib/init-tcp-probe.js +33 -0
  86. package/dist/lib/instance-identity-row.js +20 -0
  87. package/dist/lib/instruction-event-contract.js +17 -0
  88. package/dist/lib/instruction-event-doctor.js +102 -0
  89. package/dist/lib/launchd-management.js +38 -3
  90. package/dist/lib/listener-table.js +268 -0
  91. package/dist/lib/local-delete-instance.js +27 -0
  92. package/dist/lib/local-instance-pair.js +256 -0
  93. package/dist/lib/mcp-enable.js +1182 -341
  94. package/dist/lib/mcp-oauth-env-core.js +133 -0
  95. package/dist/lib/mcp-oauth-env.js +125 -0
  96. package/dist/lib/mcp-spec.js +17 -1
  97. package/dist/lib/memory-attributes.js +4 -0
  98. package/dist/lib/memory-id-policy.js +46 -0
  99. package/dist/lib/memory-integrity.js +309 -0
  100. package/dist/lib/memory-provider-timeout.js +33 -0
  101. package/dist/lib/memory-purge-response.js +20 -0
  102. package/dist/lib/mqtt-config.js +132 -0
  103. package/dist/lib/mqtt-listener-doctor.js +104 -0
  104. package/dist/lib/open-live-row.js +20 -0
  105. package/dist/lib/ops-table-count.js +25 -0
  106. package/dist/lib/ops-url.js +52 -0
  107. package/dist/lib/owned-pins.js +67 -10
  108. package/dist/lib/peer-status.js +27 -0
  109. package/dist/lib/principal-status.js +29 -0
  110. package/dist/lib/process-start-time.js +76 -12
  111. package/dist/lib/promotion-content-hash.js +20 -0
  112. package/dist/lib/proto-safe-record.js +42 -0
  113. package/dist/lib/record-id-path.js +25 -0
  114. package/dist/lib/reembed-server-support.js +66 -0
  115. package/dist/lib/restore-archive.js +760 -0
  116. package/dist/lib/restore-verify.js +104 -0
  117. package/dist/lib/scheduler-platform.js +10 -6
  118. package/dist/lib/secret-keys.js +25 -0
  119. package/dist/lib/secrets-push.js +50 -22
  120. package/dist/lib/skill-assignment-preflight.js +159 -0
  121. package/dist/lib/skill-seed-pending.js +24 -0
  122. package/dist/lib/skill-seed.js +448 -0
  123. package/dist/lib/skill-tombstone-doctor.js +133 -0
  124. package/dist/lib/soul-scope-fields.js +26 -0
  125. package/dist/lib/stop-start-recovery.js +54 -0
  126. package/dist/lib/uninstall-purge.js +266 -11
  127. package/dist/lib/upgrade-prior-liveness.js +2 -1
  128. package/dist/lib/using-flair-skill.js +87 -0
  129. package/dist/mcp-client-assertion.js +114 -14
  130. package/dist/memory-id-checkpoint.js +347 -0
  131. package/dist/memory-node-compare.js +207 -0
  132. package/dist/mqtt-off-deploy.js +550 -0
  133. package/dist/packages/flair-mcp/src/secret-redaction.js +113 -0
  134. package/dist/rem/promote-policy.js +3 -3
  135. package/dist/rem/restore.js +303 -26
  136. package/dist/rem/runner.js +317 -96
  137. package/dist/rem/scheduler.js +21 -4
  138. package/dist/resources/A2AAdapter.js +131 -178
  139. package/dist/resources/AdminMemory.js +2 -0
  140. package/dist/resources/AdminMemoryCandidates.js +116 -0
  141. package/dist/resources/Agent.js +463 -33
  142. package/dist/resources/AgentCard.js +4 -0
  143. package/dist/resources/AgentKeyRegister.js +248 -0
  144. package/dist/resources/AgentKeyRegistration.js +28 -0
  145. package/dist/resources/AgentReadPosition.js +7 -0
  146. package/dist/resources/AgentSeed.js +238 -107
  147. package/dist/resources/AutoPromoteCandidates.js +413 -78
  148. package/dist/resources/Credential.js +183 -10
  149. package/dist/resources/Federation.js +915 -145
  150. package/dist/resources/FederationRetry.js +140 -0
  151. package/dist/resources/InstructionVersion.js +220 -0
  152. package/dist/resources/Integration.js +300 -25
  153. package/dist/resources/MCPClientMetadata.js +6 -3
  154. package/dist/resources/Memory.js +3300 -758
  155. package/dist/resources/MemoryArchive.js +171 -53
  156. package/dist/resources/MemoryBootstrap.js +122 -61
  157. package/dist/resources/MemoryCandidate.js +37 -3
  158. package/dist/resources/MemoryConsolidate.js +2 -2
  159. package/dist/resources/MemoryDedupStats.js +30 -1
  160. package/dist/resources/MemoryFeed.js +545 -50
  161. package/dist/resources/MemoryGrant.js +21 -1
  162. package/dist/resources/MemoryMaintenance.js +368 -46
  163. package/dist/resources/MemoryPurge.js +348 -0
  164. package/dist/resources/MemoryReflect.js +71 -12
  165. package/dist/resources/MemoryReindex.js +111 -17
  166. package/dist/resources/Message.js +16 -5
  167. package/dist/resources/OAuth.js +342 -48
  168. package/dist/resources/OAuthClient.js +1 -1
  169. package/dist/resources/OrgEvent.js +405 -19
  170. package/dist/resources/OrgEventCatchup.js +7 -0
  171. package/dist/resources/OrgEventMaintenance.js +48 -10
  172. package/dist/resources/PairingToken.js +1 -1
  173. package/dist/resources/Presence.js +166 -51
  174. package/dist/resources/PromoteMemoryCandidate.js +24 -7
  175. package/dist/resources/RecordUsage.js +2 -4
  176. package/dist/resources/Relationship.js +23 -0
  177. package/dist/resources/SemanticSearch.js +63 -32
  178. package/dist/resources/Soul.js +191 -76
  179. package/dist/resources/SoulFeed.js +2 -1
  180. package/dist/resources/TeamDirectory.js +35 -0
  181. package/dist/resources/WorkspaceLatest.js +4 -0
  182. package/dist/resources/WorkspaceState.js +21 -1
  183. package/dist/resources/XAA.js +207 -63
  184. package/dist/resources/a2a-stream.js +313 -0
  185. package/dist/resources/a2a-url.js +4 -5
  186. package/dist/resources/agent-admin.js +10 -1
  187. package/dist/resources/agent-auth.js +138 -83
  188. package/dist/resources/agent-read-position-lib.js +4 -1
  189. package/dist/resources/agent-status-guard.js +9 -7
  190. package/dist/resources/auth-middleware.js +534 -171
  191. package/dist/resources/authority-field-guard.js +9 -11
  192. package/dist/resources/auto-promote-lib.js +8 -5
  193. package/dist/resources/basic-auth-header.js +21 -0
  194. package/dist/resources/bm25-index-service.js +4 -5
  195. package/dist/resources/dedup-cluster.js +6 -1
  196. package/dist/resources/ed25519-auth.js +1 -1
  197. package/dist/resources/embedding-space-guard.js +366 -72
  198. package/dist/resources/embeddings-provider.js +25 -0
  199. package/dist/resources/engine-version-stamp-boot.js +53 -0
  200. package/dist/resources/federation-classify.js +161 -0
  201. package/dist/resources/federation-crypto.js +5 -5
  202. package/dist/resources/federation-retry-lib.js +60 -0
  203. package/dist/resources/grant-visibility.js +135 -0
  204. package/dist/resources/harper-routing.js +83 -0
  205. package/dist/resources/health.js +163 -22
  206. package/dist/resources/host-pointer/registry.js +29 -0
  207. package/dist/resources/host-pointer-adapter.js +1 -0
  208. package/dist/resources/host-source-citation.js +49 -0
  209. package/dist/resources/host-source-visibility.js +7 -6
  210. package/dist/resources/in-process.js +24 -22
  211. package/dist/resources/instance-create-lock.js +17 -0
  212. package/dist/resources/instance-identity.js +23 -0
  213. package/dist/resources/instruction-version-record.js +587 -0
  214. package/dist/resources/internal-authority.js +13 -0
  215. package/dist/resources/key-lock.js +3 -3
  216. package/dist/resources/mcp-handler.js +141 -19
  217. package/dist/resources/mcp-oauth-env-guard.js +36 -0
  218. package/dist/resources/mcp-oauth-flag.js +12 -14
  219. package/dist/resources/mcp-oauth.js +450 -56
  220. package/dist/resources/mcp-tool-arguments.js +4 -6
  221. package/dist/resources/mcp-tools.js +187 -40
  222. package/dist/resources/memory-bootstrap-lib.js +5 -15
  223. package/dist/resources/memory-declared-attributes.js +4 -1
  224. package/dist/resources/memory-deletion-history.js +55 -0
  225. package/dist/resources/memory-durability.js +54 -0
  226. package/dist/resources/memory-embed-hash.js +144 -0
  227. package/dist/resources/memory-embedding-value.js +8 -0
  228. package/dist/resources/memory-host-source.js +32 -7
  229. package/dist/resources/memory-id-guard.js +75 -0
  230. package/dist/resources/memory-redaction.js +236 -0
  231. package/dist/resources/memory-reflect-lib.js +1 -1
  232. package/dist/resources/memory-supplied-vector.js +72 -0
  233. package/dist/resources/memory-write-lock.js +489 -0
  234. package/dist/resources/memory-write-response.js +139 -0
  235. package/dist/resources/memory-write-transaction.js +243 -0
  236. package/dist/resources/migration-boot.js +17 -12
  237. package/dist/resources/migrations/boot-progress.js +25 -0
  238. package/dist/resources/migrations/data-dir.js +90 -19
  239. package/dist/resources/migrations/dir-safety.js +61 -3
  240. package/dist/resources/migrations/embedding-stamp.js +462 -82
  241. package/dist/resources/migrations/export.js +1 -0
  242. package/dist/resources/migrations/graph-heal.js +27 -27
  243. package/dist/resources/migrations/ledger.js +5 -2
  244. package/dist/resources/migrations/lock.js +870 -77
  245. package/dist/resources/migrations/progress.js +71 -10
  246. package/dist/resources/migrations/runner.js +212 -18
  247. package/dist/resources/migrations/snapshot.js +1 -0
  248. package/dist/resources/migrations/source-fields.js +5 -5
  249. package/dist/resources/migrations/state.js +36 -1
  250. package/dist/resources/migrations/status.js +2 -13
  251. package/dist/resources/migrations/synthetic-test-migration.js +81 -12
  252. package/dist/resources/migrations/types.js +26 -1
  253. package/dist/resources/migrations/visibility-backfill.js +113 -72
  254. package/dist/resources/oauth-discovery.js +0 -5
  255. package/dist/resources/object-body-guard.js +40 -0
  256. package/dist/resources/org-event-created-at.js +133 -0
  257. package/dist/resources/org-event-reserved.js +92 -0
  258. package/dist/resources/org-event-write-fault.js +19 -0
  259. package/dist/resources/originator-instance.js +39 -7
  260. package/dist/resources/owner-delete-recheck.js +78 -0
  261. package/dist/resources/owner-field-guard.js +39 -5
  262. package/dist/resources/owner-scoped-write-policy.js +256 -0
  263. package/dist/resources/owner-scoped-writes.js +89 -0
  264. package/dist/resources/path-id-rewrite.js +76 -0
  265. package/dist/resources/presence-internal.js +5 -5
  266. package/dist/resources/presence-receipt.js +236 -0
  267. package/dist/resources/promotion-binding.js +43 -0
  268. package/dist/resources/promotion-stamp.js +143 -17
  269. package/dist/resources/protocol-context.js +189 -0
  270. package/dist/resources/record-owner-guard.js +74 -26
  271. package/dist/resources/record-type-kit.js +2 -4
  272. package/dist/resources/record-types.js +1 -1
  273. package/dist/resources/relay-ops.js +78 -6
  274. package/dist/resources/replay-store.js +96 -19
  275. package/dist/resources/request-target.js +163 -0
  276. package/dist/resources/request-transaction.js +46 -1
  277. package/dist/resources/search-readiness.js +4 -1
  278. package/dist/resources/seed-ids.js +9 -0
  279. package/dist/resources/seed-reservation.js +116 -0
  280. package/dist/resources/semantic-retrieval-core.js +27 -15
  281. package/dist/resources/server-row-validation.js +71 -0
  282. package/dist/resources/skill-manifest.js +24 -14
  283. package/dist/resources/skill-subject.js +53 -0
  284. package/dist/resources/skill-version-write.js +789 -0
  285. package/dist/resources/skill-write-fault.js +20 -0
  286. package/dist/resources/skill-write-policy.js +68 -0
  287. package/dist/resources/skill-write.js +67 -7
  288. package/dist/resources/soul-write-policy.js +26 -7
  289. package/dist/resources/table-helpers.js +10 -7
  290. package/dist/resources/table-subscription-policy.js +518 -85
  291. package/dist/resources/table-subscriptions.js +20 -7
  292. package/dist/resources/team-directory.js +248 -0
  293. package/dist/resources/tool-descriptors/index.js +69 -8
  294. package/dist/resources/txn-pause-point.js +235 -0
  295. package/dist/resources/usage-recording.js +186 -70
  296. package/dist/resources/write-back.js +383 -0
  297. package/dist/resources/write-journal-context.js +5 -0
  298. package/dist/resources/write-journal.js +289 -0
  299. package/dist/src/engine-version-contract.js +1 -0
  300. package/dist/src/keystore.js +72 -0
  301. package/dist/src/lib/agent-home-fields.js +132 -0
  302. package/dist/src/lib/agent-id-rule.js +88 -0
  303. package/dist/src/lib/agent-key-register.js +80 -0
  304. package/dist/src/lib/atomic-write.js +256 -0
  305. package/dist/src/lib/credential-status-rule.js +78 -0
  306. package/dist/src/lib/expired-by-agent.js +37 -0
  307. package/dist/src/lib/federation-retry-row.js +101 -0
  308. package/dist/src/lib/flair-agent-role.js +4 -0
  309. package/dist/src/lib/idp-mapping-rule.js +81 -0
  310. package/dist/src/lib/instance-identity-row.js +20 -0
  311. package/dist/src/lib/instruction-event-contract.js +17 -0
  312. package/dist/src/lib/mcp-oauth-env-core.js +133 -0
  313. package/dist/src/lib/memory-attributes.js +4 -0
  314. package/dist/src/lib/memory-id-policy.js +46 -0
  315. package/dist/src/lib/open-live-row.js +20 -0
  316. package/dist/src/lib/principal-status.js +29 -0
  317. package/dist/src/lib/proto-safe-record.js +42 -0
  318. package/dist/src/lib/reembed-server-support.js +66 -0
  319. package/dist/src/lib/scheduler-platform.js +10 -6
  320. package/dist/src/lib/soul-scope-fields.js +26 -0
  321. package/dist/src/lib/systemd-agent-id.js +38 -0
  322. package/dist/src/rem/promote-policy.js +3 -3
  323. package/dist/src/rem/scheduler.js +21 -4
  324. package/docs/access-control.md +164 -54
  325. package/docs/api-reference.md +165 -32
  326. package/docs/auth.md +46 -30
  327. package/docs/bridges.md +11 -0
  328. package/docs/claude-code.md +37 -7
  329. package/docs/deploying-on-fabric.md +178 -0
  330. package/docs/deployment.md +19 -0
  331. package/docs/embedding-in-a-harper-app.md +17 -15
  332. package/docs/entity-vocabulary.md +3 -6
  333. package/docs/federation.md +61 -3
  334. package/docs/hosted-on-fabric.md +43 -36
  335. package/docs/integrations.md +14 -14
  336. package/docs/mcp-clients.md +12 -7
  337. package/docs/n8n.md +17 -11
  338. package/docs/notes/mcp-agent-auth-consumer.md +16 -13
  339. package/docs/notes/mcp-oauth-model2.md +40 -11
  340. package/docs/openclaw.md +1 -1
  341. package/docs/quickstart-fabric.md +4 -4
  342. package/docs/quickstart.md +12 -4
  343. package/docs/releasing.md +25 -19
  344. package/docs/rem.md +32 -3
  345. package/docs/secrets-and-keys.md +21 -4
  346. package/docs/standalone-local.md +30 -2
  347. package/docs/supply-chain-policy.md +34 -16
  348. package/docs/the-team.md +2 -2
  349. package/docs/upgrade.md +46 -6
  350. package/package.json +24 -12
  351. package/schemas/agent-key-registration.graphql +22 -0
  352. package/schemas/agent.graphql +6 -3
  353. package/schemas/federation.graphql +41 -1
  354. package/schemas/memory.graphql +91 -7
  355. package/schemas/oauth.graphql +19 -0
  356. package/schemas/schema.graphql +2 -0
  357. package/templates/bin/flair-rem-nightly.sh.tmpl +7 -1
  358. package/templates/launchd/start-flair-with-admin-pass.sh +188 -10
  359. package/dist/resources/soul-adk-guard.js +0 -68
@@ -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
- 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";
5
+ import { DEFAULT_ADMIN_USER, ApiRequestOutcomeUnknown, addAdminPassOptions, authFetch, defaultAdminPassPath, defaultKeysDir, readAdminPassFileSecure, resolveAdminUser } from "../lib/auth-resolve.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
  }
@@ -153,7 +217,7 @@ export function register(program) {
153
217
  const MQTT_DISABLED_CONFIG = cli.MQTT_DISABLED_CONFIG;
154
218
  const STARTUP_TIMEOUT_MS = cli.STARTUP_TIMEOUT_MS;
155
219
  // ─── flair init ──────────────────────────────────────────────────────────────
156
- program
220
+ addAdminPassOptions(program
157
221
  .command("init")
158
222
  .description("One-command Flair setup — bootstrap the instance, register an agent, and wire MCP clients")
159
223
  .option("--agent-id <id>", "Agent ID to register (omit to bootstrap instance without agent)")
@@ -166,14 +230,12 @@ export function register(program) {
166
230
  .option("--port <port>", "Harper HTTP port (default: this instance's current port, or 19926 for a new one)")
167
231
  .option("--ops-port <port>", "Harper operations API port")
168
232
  .option("--ops-bind <addr>", "Harper ops API bind address (env: FLAIR_OPS_BIND; default: 127.0.0.1 loopback-only for single-host — pass e.g. 0.0.0.0 for multi-host/Fabric remote admin)")
169
- .option("--http-bind <addr>", "Harper HTTP bind address (env: FLAIR_HTTP_BIND; default: 127.0.0.1 loopback-only). The listener MUST include IPv4 loopback (Flair's self-calls hardcode 127.0.0.1), so only 127.0.0.1 or a wildcard (0.0.0.0 / ::) is accepted; a specific non-loopback host is refused.")
170
- .option("--admin-pass <pass>", "Admin password (generated if omitted)")
171
- .option("--admin-pass-file <path>", "Read admin password from file (chmod 600 recommended)")
233
+ .option("--http-bind <addr>", "Harper HTTP bind address (env: FLAIR_HTTP_BIND; default: 127.0.0.1 loopback-only). The listener MUST include IPv4 loopback (Flair's self-calls hardcode 127.0.0.1), so only 127.0.0.1 or a wildcard (0.0.0.0 / ::) is accepted; a specific non-loopback host is refused."), "Admin password (generated if omitted)", { adminPassFileHelp: "Read admin password from file (chmod 600 recommended)" })
172
234
  .option("--reset-admin-pass", "Rotate Harper's persisted admin hash via the operations socket, then write ~/.flair/admin-pass")
173
235
  .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
236
  .option("--keys-dir <dir>", "Directory for Ed25519 keys")
175
237
  .option("--data-dir <dir>", "Harper data directory")
176
- .option("--skip-start", "Skip Harper startup (assume already running)")
238
+ .option("--skip-start", "Do not start Harper; with --agent, defer registration (ignored with --target/--ops-target)")
177
239
  .option("--skip-soul", "Skip interactive personality setup")
178
240
  .option("--client <client>", "Client(s) to wire: claude-code, codex, gemini, cursor, antigravity, pi (native extension), all, or none")
179
241
  .option("--no-mcp", "Skip MCP client wiring (instance + agent only)")
@@ -270,6 +332,36 @@ export function register(program) {
270
332
  let pubKeyB64url;
271
333
  let privPath;
272
334
  let instanceId;
335
+ // Reconcile the federation Instance identity row if --remote (hub role).
336
+ // flair#1883: this used to INSERT a row with a fresh random id on every
337
+ // run, so a hub that had already answered a `GET /FederationInstance`
338
+ // (which find-or-creates a `spoke` row) ended up with TWO rows and no
339
+ // canonical identity. Reconciling keeps the row peers already know.
340
+ // It runs before the agent seed so the agent's home is the hub's id.
341
+ const reconcileHubInstance = async (publicKey) => {
342
+ instanceId = randomUUID();
343
+ console.log(`Reconciling federation Instance (role=${role}) via ops API...`);
344
+ let reconciled;
345
+ try {
346
+ reconciled = await reconcileFederationInstanceViaOpsApi(opsUrl, { instanceId, publicKey }, adminUser, flairAdminPass);
347
+ }
348
+ catch (err) {
349
+ // A refusal (two rows) or an unreachable ops API — both are this
350
+ // command failing, and both already name what to do.
351
+ console.error(`Error: ${err?.message ?? err}`);
352
+ process.exit(1);
353
+ }
354
+ instanceId = reconciled.id;
355
+ if (reconciled.action === "created") {
356
+ console.log(`Federation Instance created: ${reconciled.id} (role=${role}) ✓`);
357
+ }
358
+ else if (reconciled.action === "updated") {
359
+ console.log(`Federation Instance reconciled: ${reconciled.id} is now role=${role} (id and key kept) ✓`);
360
+ }
361
+ else {
362
+ console.log(`Federation Instance already role=${role}: ${reconciled.id} — no change ✓`);
363
+ }
364
+ };
273
365
  if (agentId || role) {
274
366
  const keysDir = opts.keysDir ?? defaultKeysDir();
275
367
  mkdirSync(keysDir, { recursive: true });
@@ -292,9 +384,11 @@ export function register(program) {
292
384
  pubKeyB64url = b64url(kp.publicKey);
293
385
  console.log(`Keypair written: ${privPath} ✓`);
294
386
  }
387
+ if (role)
388
+ await reconcileHubInstance(pubKeyB64url);
295
389
  // Seed agent via remote ops API
296
390
  console.log(`Seeding agent '${agentId}' on ${baseUrl}...`);
297
- await seedAgentViaOpsApi(opsUrl, agentId, pubKeyB64url, adminUser, flairAdminPass);
391
+ await seedAgentWithLocalHome(opsUrl, agentId, pubKeyB64url, adminUser, flairAdminPass);
298
392
  console.log(`Agent '${agentId}' registered on remote instance ✓`);
299
393
  }
300
394
  else {
@@ -302,44 +396,16 @@ export function register(program) {
302
396
  console.log("Generating federation instance keypair...");
303
397
  const kp = nacl.sign.keyPair();
304
398
  pubKeyB64url = b64url(kp.publicKey);
399
+ if (role)
400
+ await reconcileHubInstance(pubKeyB64url);
305
401
  }
306
402
  }
307
403
  else {
308
404
  console.log("No --agent-id provided -- skipping agent registration");
309
405
  }
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
- }
406
+ // flair#2141 S2 — seed the org-wide using-flair skill on the remote
407
+ // instance, as the operator. Idempotent; a refusal fails this run.
408
+ await seedUsingFlairSkillViaRest(baseUrl, adminUser, flairAdminPass);
343
409
  // Verify connectivity
344
410
  if (didProvision) {
345
411
  // Use /FederationInstance with Basic auth (not /Health which false-401s on Fabric)
@@ -399,6 +465,18 @@ export function register(program) {
399
465
  // preflight measured. Every downstream use (preflight, config/plist,
400
466
  // ROOTPATH / HARPER_SET_CONFIG, messages) takes this resolved value.
401
467
  const dataDir = opts.dataDir ? resolve(opts.dataDir) : defaultDataDir();
468
+ try {
469
+ const migration = planRedirectMigration({
470
+ env: process.env,
471
+ configPath: join(flairPackageDir(), "config.yaml"),
472
+ });
473
+ const migrationLine = renderRedirectMigration(migration);
474
+ if (migrationLine)
475
+ console.log(` ${migrationLine}`);
476
+ }
477
+ catch (err) {
478
+ console.error(`warning: MCP OAuth redirect migration could not run (${err?.message ?? String(err)}).`);
479
+ }
402
480
  // flair#916: the Harper operations API is a Unix domain socket at
403
481
  // `<data-dir>/operations-server`, and Unix socket paths are capped by
404
482
  // `sun_path` (darwin 104 / linux 108, counting the trailing NUL, so the
@@ -469,14 +547,152 @@ export function register(program) {
469
547
  let reusedExistingAdminPass = false;
470
548
  let pendingAdminPassRotate = false;
471
549
  const adminPassPath = defaultAdminPassPath();
472
- const persistedAdminUser = detectPersistedAdminUser(dataDir);
473
- let alreadyRunning = false;
550
+ let persistedAdminUser;
474
551
  try {
475
- const res = await fetch(`http://127.0.0.1:${httpPort}/health`, { signal: AbortSignal.timeout(1000) });
476
- if (res.status > 0)
552
+ persistedAdminUser = detectPersistedAdminUser(dataDir);
553
+ }
554
+ catch (err) {
555
+ const detail = err instanceof Error ? err.message : String(err);
556
+ console.error(`❌ Refusing to initialize: the Harper system database under ${dataDir} could not be read, ` +
557
+ `so I cannot tell whether an admin user is already persisted (${detail}). ` +
558
+ `Repair that data directory (or point --data-dir at the right one) and re-run.`);
559
+ process.exit(1);
560
+ }
561
+ let alreadyRunning = false;
562
+ let ownChild;
563
+ const freeBeforeSpawn = new Set();
564
+ const refuseUnattributedListener = (listener) => {
565
+ const installedAttributed = harperConfigPath(dataDir) !== null &&
566
+ listener.pids.length === 1 &&
567
+ ownedInitPidfilePid(dataDir) === listener.pids[0] &&
568
+ listener.dataDirs.every(dir => canonicalLexicalPath(dir) === canonicalLexicalPath(dataDir)) &&
569
+ cli.resolveInstanceServingPid(dataDir, listener.port, { findListeningPids: () => [] }) === listener.pids[0];
570
+ const attributed = ownChild ? ownChild.attributes(listener, dataDir, freeBeforeSpawn) : installedAttributed;
571
+ if (attributed)
572
+ return;
573
+ const pid = listener.pids.length === 1 ? `, pid ${listener.pids[0]}` : "";
574
+ console.error(`Refusing init: port ${listener.port}${pid}: attribution to this data directory was not confirmed.`);
575
+ console.error(foreignOccupiedListenerDetail(listener));
576
+ process.exit(1);
577
+ };
578
+ // `detail` is the credential-gate diagnostic (attributeBeforeCredential);
579
+ // the pre-start refusals pass none.
580
+ const refuseFreePort = (listener, detail) => {
581
+ const pid = listener.pids.length === 1 ? `, pid ${listener.pids[0]}` : "";
582
+ console.error(`Refusing init: port ${listener.port}${pid}: TCP readiness check failed${detail ? `: ${detail}` : ""}.`);
583
+ console.error("Remedy: start the instance, then rerun init.");
584
+ process.exit(1);
585
+ };
586
+ // The readiness budget here is `cli.STARTUP_TIMEOUT_MS`, the same duration
587
+ // as the test-harness readiness poll's `HARPER_STARTUP_BUDGET_MS`
588
+ // (test/helpers/harper-lifecycle.ts); test/unit/harper-lifecycle-budgets
589
+ // .test.ts keeps the two durations equal. The probes (a TCP connect here, an
590
+ // HTTP request there) and the points the timers start from differ.
591
+ const attributeBeforeCredential = async (port, host) => {
592
+ const startedAt = Date.now();
593
+ const deadline = startedAt + STARTUP_TIMEOUT_MS;
594
+ let listener = readOccupiedListener(port);
595
+ let state = await localPortState(port, host);
596
+ while (ownChild && state === "free" && Date.now() < deadline) {
597
+ await new Promise(resolve => setTimeout(resolve, 100));
598
+ listener = readOccupiedListener(port);
599
+ state = await localPortState(port, host);
600
+ }
601
+ // Only a child this init spawned is waited for. Without one (init found
602
+ // an instance already running and did not spawn) the port is checked
603
+ // once, so the diagnostic must not claim a wait or a spawned instance.
604
+ if (state === "free") {
605
+ refuseFreePort(listener, ownChild
606
+ ? `still free after ${Date.now() - startedAt}ms (phase: waiting for the spawned instance to listen)`
607
+ : "no listener (phase: TCP readiness check of an instance this init did not spawn; checked once, no wait)");
608
+ }
609
+ if (state === "listening")
610
+ listener = readOccupiedListener(port);
611
+ if (state === "unknown")
612
+ refuseUnknownListener(listener);
613
+ refuseUnattributedListener(listener);
614
+ };
615
+ const refuseUnknownListener = (listener) => {
616
+ const pid = listener.pids.length === 1 ? `, pid ${listener.pids[0]}` : "";
617
+ console.error(`Refusing init: port ${listener.port}${pid}: TCP probe was inconclusive.`);
618
+ console.error("Remedy: check TCP connectivity, then rerun init.");
619
+ process.exit(1);
620
+ };
621
+ if (opts.skipStart && !agentId) {
622
+ try {
623
+ const res = await fetch(`http://127.0.0.1:${httpPort}/health`, { signal: AbortSignal.timeout(1000) });
624
+ if (res.status > 0) {
625
+ alreadyRunning = true;
626
+ }
627
+ }
628
+ catch { }
629
+ const httpListener = readOccupiedListener(httpPort);
630
+ const httpState = await localPortState(httpPort, httpBind.host);
631
+ alreadyRunning ||= httpListener.pids.length > 0 || httpState === "listening";
632
+ if (alreadyRunning) {
633
+ if (httpState === "free")
634
+ refuseFreePort(httpListener);
635
+ refuseUnattributedListener(httpListener);
636
+ console.log(`Harper already running on port ${httpPort} — skipping start`);
637
+ }
638
+ else if (httpState === "unknown") {
639
+ refuseUnknownListener(httpListener);
640
+ }
641
+ const opsListener = readOccupiedListener(opsPort);
642
+ let opsAnswer;
643
+ try {
644
+ const res = await fetch(`http://127.0.0.1:${opsPort}/`, { signal: AbortSignal.timeout(1000) });
645
+ if (res.status > 0)
646
+ opsAnswer = res.status;
647
+ }
648
+ catch { }
649
+ const opsState = await localPortState(opsPort, opsBindHost);
650
+ if (opsAnswer !== undefined || opsListener.pids.length > 0 || opsState === "listening") {
651
+ if (opsState === "free")
652
+ refuseFreePort(opsListener);
653
+ refuseUnattributedListener(opsListener);
654
+ }
655
+ else if (opsState === "unknown") {
656
+ refuseUnknownListener(opsListener);
657
+ }
658
+ }
659
+ else if (!opts.skipStart) {
660
+ try {
661
+ const res = await fetch(`http://127.0.0.1:${httpPort}/health`, { signal: AbortSignal.timeout(1000) });
662
+ if (res.status > 0) {
663
+ alreadyRunning = true;
664
+ }
665
+ }
666
+ catch { }
667
+ const httpListener = readOccupiedListener(httpPort);
668
+ const httpState = await localPortState(httpPort, httpBind.host);
669
+ if (alreadyRunning || httpListener.pids.length > 0 || httpState === "listening") {
670
+ if (httpState === "free")
671
+ refuseFreePort(httpListener);
672
+ refuseUnattributedListener(httpListener);
477
673
  alreadyRunning = true;
674
+ }
675
+ else if (httpState === "unknown") {
676
+ refuseUnknownListener(httpListener);
677
+ }
678
+ const opsListener = readOccupiedListener(opsPort);
679
+ let opsAnswer;
680
+ try {
681
+ const res = await fetch(`http://127.0.0.1:${opsPort}/`, { signal: AbortSignal.timeout(1000) });
682
+ if (res.status > 0)
683
+ opsAnswer = res.status;
684
+ }
685
+ catch { }
686
+ const opsState = await localPortState(opsPort, opsBindHost);
687
+ if (opsAnswer !== undefined || opsListener.pids.length > 0 || opsState === "listening") {
688
+ if (opsState === "free")
689
+ refuseFreePort(opsListener);
690
+ refuseUnattributedListener(opsListener);
691
+ }
692
+ else if (opsState === "unknown") {
693
+ refuseUnknownListener(opsListener);
694
+ }
478
695
  }
479
- catch { /* not running */ }
480
696
  const explicitCredential = !!(opts.adminPassFile || process.env.FLAIR_ADMIN_PASS || process.env.HDB_ADMIN_PASSWORD || opts.adminPass);
481
697
  const passwordCtx = {
482
698
  persistedAdminUser,
@@ -485,8 +701,8 @@ export function register(program) {
485
701
  resetRequested: !!opts.resetAdminPass,
486
702
  opsSocketAvailable: alreadyRunning || !opts.skipStart,
487
703
  };
488
- // Warn if --admin-pass is passed inline (not from env)
489
- if (shouldShowInlineSecretWarning(opts.adminPass, false, new Set(["--admin-pass"]), "--admin-pass")) {
704
+ // Warn if --admin-pass is passed inline (not from env or a file)
705
+ if (shouldShowInlineSecretWarning(opts.inlineAdminPass, false, new Set(["--admin-pass"]), "--admin-pass")) {
490
706
  console.error("warning: --admin-pass passed inline. Consider --admin-pass-file <path> or FLAIR_ADMIN_PASS env " +
491
707
  "to keep secrets out of shell history.");
492
708
  }
@@ -499,12 +715,6 @@ export function register(program) {
499
715
  httpPort,
500
716
  adminPassPath,
501
717
  });
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
718
  if (reason === "foreign-instance") {
509
719
  const listener = readOccupiedListener(httpPort);
510
720
  const head = initAdminPassRefusalMessage(reason, {
@@ -512,14 +722,54 @@ export function register(program) {
512
722
  httpPort,
513
723
  adminPassPath,
514
724
  offerFlairStop: false,
725
+ pid: listener.pids.length === 1 ? listener.pids[0] : undefined,
515
726
  });
516
- console.error(`${head}\n${foreignOccupiedListenerDetail(listener, dataDir)}`);
727
+ console.error(`${head}\n${foreignOccupiedListenerDetail(listener)}`);
517
728
  }
518
729
  else {
519
730
  console.error(message);
520
731
  }
521
732
  process.exit(1);
522
733
  };
734
+ const persistSuppliedAdminPass = async () => {
735
+ if (resolveInitAdminPasswordSource(false, passwordCtx) !== "re-persist")
736
+ return;
737
+ if (opts.skipStart && !alreadyRunning && existsSync(adminPassPath)) {
738
+ try {
739
+ const saved = lstatSync(adminPassPath);
740
+ if (saved.isFile() && (typeof process.getuid !== "function" || saved.uid === process.getuid()) &&
741
+ readAdminPassFileSecure(adminPassPath) === adminPass)
742
+ return;
743
+ }
744
+ catch (err) {
745
+ console.error(`Error: ${err instanceof Error ? err.message : String(err)}`);
746
+ process.exit(1);
747
+ }
748
+ }
749
+ if (!alreadyRunning && (existsSync(adminPassPath) || persistedAdminUser)) {
750
+ const verificationDeferred = opts.skipStart && !!agentId;
751
+ console.error(`Refusing to write ${adminPassPath}: ` +
752
+ (verificationDeferred
753
+ ? `credential verification is deferred by --skip-start. `
754
+ : `no running instance; a saved admin-pass file or persisted admin user exists. `) +
755
+ `No pass file was written; any existing file is unchanged. ` +
756
+ (verificationDeferred
757
+ ? `Re-run init without --skip-start to verify a different supplied credential.`
758
+ : harperConfigPath(dataDir) !== null
759
+ ? `Start the instance and re-run init with the supplied credential, or run:\n ${INIT_RESET_ADMIN_PASS_COMMAND}`
760
+ : `Run:\n ${INIT_RESET_ADMIN_PASS_COMMAND}`));
761
+ process.exit(1);
762
+ }
763
+ if (alreadyRunning) {
764
+ const failure = await proveAdminPassAgainstInstance(httpPort, adminPass);
765
+ if (failure) {
766
+ console.error(`Refusing to write ${adminPassPath}: ${failure} on port ${httpPort}. No pass file was written; any existing file is unchanged. ` +
767
+ `To rotate the instance's admin password instead, run:\n ${INIT_RESET_ADMIN_PASS_COMMAND}`);
768
+ process.exit(1);
769
+ }
770
+ }
771
+ writeAdminPassFile(adminPassPath, adminPass + "\n");
772
+ };
523
773
  // Read from file if provided
524
774
  if (opts.adminPassFile) {
525
775
  try {
@@ -534,8 +784,8 @@ export function register(program) {
534
784
  refuseIfNeeded(false);
535
785
  pendingAdminPassRotate = resolveInitAdminPasswordSource(false, passwordCtx) === "rotate";
536
786
  }
537
- else if (resolveInitAdminPasswordSource(false, passwordCtx) === "re-persist") {
538
- writeAdminPassFile(adminPassPath, adminPass + "\n");
787
+ else {
788
+ await persistSuppliedAdminPass();
539
789
  }
540
790
  }
541
791
  else if (process.env.FLAIR_ADMIN_PASS) {
@@ -545,8 +795,8 @@ export function register(program) {
545
795
  refuseIfNeeded(false);
546
796
  pendingAdminPassRotate = resolveInitAdminPasswordSource(false, passwordCtx) === "rotate";
547
797
  }
548
- else if (resolveInitAdminPasswordSource(false, passwordCtx) === "re-persist") {
549
- writeAdminPassFile(adminPassPath, adminPass + "\n");
798
+ else {
799
+ await persistSuppliedAdminPass();
550
800
  }
551
801
  }
552
802
  else if (process.env.HDB_ADMIN_PASSWORD) {
@@ -556,8 +806,8 @@ export function register(program) {
556
806
  refuseIfNeeded(false);
557
807
  pendingAdminPassRotate = resolveInitAdminPasswordSource(false, passwordCtx) === "rotate";
558
808
  }
559
- else if (resolveInitAdminPasswordSource(false, passwordCtx) === "re-persist") {
560
- writeAdminPassFile(adminPassPath, adminPass + "\n");
809
+ else {
810
+ await persistSuppliedAdminPass();
561
811
  }
562
812
  }
563
813
  else if (opts.adminPass) {
@@ -568,8 +818,8 @@ export function register(program) {
568
818
  refuseIfNeeded(false);
569
819
  pendingAdminPassRotate = resolveInitAdminPasswordSource(false, passwordCtx) === "rotate";
570
820
  }
571
- else if (resolveInitAdminPasswordSource(false, passwordCtx) === "re-persist") {
572
- writeAdminPassFile(adminPassPath, adminPass + "\n");
821
+ else {
822
+ await persistSuppliedAdminPass();
573
823
  }
574
824
  }
575
825
  else {
@@ -577,8 +827,6 @@ export function register(program) {
577
827
  const fileExists = existsSync(adminPassPath);
578
828
  const decision = resolveInitAdminPasswordSource(fileExists, passwordCtx);
579
829
  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
830
  try {
583
831
  adminPass = readAdminPassFileSecure(adminPassPath);
584
832
  }
@@ -637,32 +885,25 @@ export function register(program) {
637
885
  // The socket doesn't exist yet, so only the parent-dir mode is applied here.
638
886
  mkdirSync(dataDir, { recursive: true });
639
887
  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
888
  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) {
889
+ if (!opts.skipStart && alreadyRunning) {
890
+ console.log(`Harper already running on port ${httpPort} — skipping start`);
891
+ skippedOwnStart = true;
892
+ }
893
+ if (!alreadyRunning) {
894
+ // Detect whether Harper has already been installed in this data dir.
895
+ // Harper's config is created during install — its presence means
896
+ // install already ran. Re-running install against an existing data dir
897
+ // crashes in Harper v5 beta.6+ (checkForExistingInstall queries the
898
+ // database before the env is initialized). Goes through
899
+ // harperConfigPath so an install predating Harper's config-file rename
900
+ // (harperdb-config.yaml) is still recognised as installed rather than
901
+ // re-installed over.
902
+ const alreadyInstalled = harperConfigPath(dataDir) !== null;
903
+ const willStart = !opts.skipStart;
904
+ // An already-installed instance with --skip-start is not installed
905
+ // over or started.
906
+ if (!alreadyInstalled || willStart) {
666
907
  const bin = harperBin();
667
908
  if (!bin) {
668
909
  throw new Error("Harper CLI not found: no dist/bin/harper.js under node_modules/harper " +
@@ -672,15 +913,6 @@ export function register(program) {
672
913
  "or interrupted install.\nFix: reinstall flair — npm install -g @tpsdev-ai/flair");
673
914
  }
674
915
  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
916
  const opsSocket = join(dataDir, "operations-server");
685
917
  // authorizeLocal: false (flair#654) — a credential-less loopback ops-API
686
918
  // request is no longer auto-authorized as super_user. Every ops-API
@@ -777,17 +1009,35 @@ export function register(program) {
777
1009
  // Start Harper with flair loaded as a component (the "." arg).
778
1010
  // ROOTPATH in env points to the data dir; authorizeLocal and thread
779
1011
  // 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);
1012
+ if (willStart) {
1013
+ console.log(`Starting Harper on port ${httpPort}...`);
1014
+ for (const [port, host] of [[httpPort, httpBind.host], [opsPort, opsBindHost]]) {
1015
+ const listener = readOccupiedListener(port);
1016
+ const state = await localPortState(port, host);
1017
+ if (state === "unknown")
1018
+ refuseUnknownListener(listener);
1019
+ if (listener.pids.length > 0 || state !== "free") {
1020
+ const pid = listener.pids.length === 1 ? `, pid ${listener.pids[0]}` : "";
1021
+ console.error(`Refusing init: port ${port}${pid}: pre-start port check failed.`);
1022
+ console.error(foreignOccupiedListenerDetail(listener));
1023
+ process.exit(1);
1024
+ }
1025
+ freeBeforeSpawn.add(port);
1026
+ }
1027
+ const proc = spawn(process.execPath, [bin, "run", "."], { cwd: flairPackageDir(), env, detached: true, stdio: "ignore" });
1028
+ ownChild = trackInitChild(proc);
1029
+ proc.unref();
1030
+ // flair#1454: write the identity sidecar immediately after spawn so
1031
+ // `flair stop` and `flair status` can classify this daemon's state
1032
+ // without lsof. Same call as startFlairProcess() uses.
1033
+ if (proc.pid)
1034
+ writeDaemonSidecar(dataDir, proc.pid, httpPort);
1035
+ }
788
1036
  }
1037
+ }
1038
+ if (!opts.skipStart) {
789
1039
  console.log("Waiting for Harper health check...");
790
- await waitForHealth(httpPort, adminUser, adminPass, STARTUP_TIMEOUT_MS);
1040
+ await waitForHealth(httpPort, adminUser, adminPass, STARTUP_TIMEOUT_MS, () => attributeBeforeCredential(httpPort, httpBind.host));
791
1041
  console.log("Harper is healthy ✓");
792
1042
  // flair#763: the socket now exists — apply its file mode (+ chgrp for the
793
1043
  // FLAIR_SOCKET_GROUP opt-in). The dir gate above is re-asserted idempotently.
@@ -891,9 +1141,9 @@ export function register(program) {
891
1141
  for (const line of launchdStep.lines) {
892
1142
  (line.stream === "err" ? console.error : console.log)(line.text);
893
1143
  }
894
- if (launchdStep.kind === "refused" || launchdStep.kind === "down" || launchdStep.kind === "uncertain") {
895
- process.exit(1);
896
- }
1144
+ const launchdExit = initLaunchdExitCode(launchdStep.kind);
1145
+ if (launchdExit !== 0)
1146
+ process.exit(launchdExit);
897
1147
  }
898
1148
  }
899
1149
  // flair#2034 §2: on Linux the instance's own service is the systemd
@@ -975,6 +1225,29 @@ export function register(program) {
975
1225
  // from the still-persisted wildcard. Writing the resolved host on every init
976
1226
  // means an explicit loopback also persists, so a widening can be reversed.
977
1227
  persistDefaultInstallCoordinates(dataDir, httpPort, opsPort, opsBindHost, httpBind.host);
1228
+ // flair#2141 S2 — seed the org-wide using-flair skill on this instance, as
1229
+ // the operator. Re-initializing an already-installed default local instance
1230
+ // with `flair init --skip-start` defers seeding to a later `flair start`
1231
+ // with the admin credential; that command has no `--data-dir` flag.
1232
+ // (Remote init, `--target`, seeds with or
1233
+ // without `--skip-start`.) A refusal fails this run rather than reporting a
1234
+ // successful init without the skill, so both local paths call it before
1235
+ // they print their success summary.
1236
+ const seedUsingFlairSkillOnInstall = async () => {
1237
+ if (opts.skipStart) {
1238
+ if (dataDir === defaultDataDir()) {
1239
+ markSkillSeedPending(dataDir);
1240
+ console.log("using-flair skill: pending");
1241
+ }
1242
+ else {
1243
+ console.log("using-flair skill: not seeded");
1244
+ }
1245
+ return;
1246
+ }
1247
+ await attributeBeforeCredential(httpPort, httpBind.host);
1248
+ await seedUsingFlairSkillViaRest(`http://127.0.0.1:${httpPort}`, adminUser, adminPass);
1249
+ clearSkillSeedPending(dataDir);
1250
+ };
978
1251
  if (agentId) {
979
1252
  // Generate or reuse keypair
980
1253
  mkdirSync(keysDir, { recursive: true });
@@ -998,85 +1271,85 @@ export function register(program) {
998
1271
  pubKeyB64url = b64url(kp.publicKey);
999
1272
  console.log(`Keypair written: ${privPath} ✓`);
1000
1273
  }
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
1274
  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.")}`);
1275
+ if (!opts.skipStart) {
1276
+ console.log(`Seeding agent '${agentId}' via operations API...`);
1277
+ const opsListener = skippedOwnStart ? operationsPortAttribution(opsPort) : undefined;
1278
+ await attributeBeforeCredential(opsPort, opsBindHost);
1279
+ await seedAgentWithLocalHome(opsPort, agentId, pubKeyB64url, adminUser, adminPass, opsListener);
1280
+ console.log(`Agent '${agentId}' registered ✓`);
1281
+ // Verify Ed25519 auth
1282
+ console.log("Verifying Ed25519 auth...");
1283
+ const verifyRes = await authFetch(httpUrl, agentId, privPath, "GET", `/Agent/${encodeRecordId(agentId)}`);
1284
+ if (!verifyRes.ok)
1285
+ throw new Error(`Ed25519 auth verification failed: ${verifyRes.status}`);
1286
+ console.log("Ed25519 auth verified ✓");
1287
+ // Verify semantic search ACTUALLY works (real embed→paraphrase-search
1288
+ // round-trip). A clean-VM dogfood found semantic search dead out of the box
1289
+ // (sudo/root-owned install can't write the embeddings models symlink →
1290
+ // EACCES) while init reported success. Never report a clean init when
1291
+ // recall-by-meaning is broken. Skipped paths (no key yet) are non-fatal.
1292
+ console.log("Verifying semantic search...");
1293
+ const embedCheck = await verifySemanticSearch(httpUrl, agentId, keysDir);
1294
+ if (embedCheck.state === "ok") {
1295
+ console.log(`Semantic search operational ✓ ${render.wrap(render.c.dim, `(paraphrase recall verified, score ${embedCheck.score.toFixed(2)})`)}`);
1296
+ }
1297
+ else if (embedCheck.state === "degraded") {
1298
+ // LOUD — embeddings not loaded. Same message class as `flair doctor`.
1299
+ console.log(`\n${render.icons.error} ${render.wrap(render.c.red, "Semantic search DEGRADED")} — embeddings not loaded; recall-by-meaning will NOT work.`);
1300
+ console.log(` ${render.wrap(render.c.dim, `(${embedCheck.detail})`)}`);
1301
+ console.log(` ${render.wrap(render.c.dim, "Common cause: the embeddings component lacks write access (sudo/root global installs).")}`);
1302
+ console.log(` ${render.wrap(render.c.dim, "Fix: install without sudo (see README Quick Start), then:")} flair restart && flair doctor`);
1303
+ }
1304
+ else if (embedCheck.state === "failed") {
1305
+ // flair#1501: the instance rejected the probe's signature. init just
1306
+ // registered this agent, so this is a genuine auth defect, not a
1307
+ // missing identity — surface it loudly with the signer named.
1308
+ console.log(`\n${render.icons.error} ${render.wrap(render.c.red, "Semantic search probe rejected")} — ${embedCheck.detail}.`);
1309
+ 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
1310
  }
1062
1311
  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.")}`);
1312
+ console.log(`${render.icons.warn} Semantic search not verified ${render.wrap(render.c.dim, `(${embedCheck.detail})`)}`);
1313
+ }
1314
+ // Verify the audit log ACTUALLY records (flair#970) — a positive
1315
+ // control, not a flag read: `describe_table` reports `audit: true` on
1316
+ // nodes whose audit trail is empty (base-copy elision, harper#2212).
1317
+ // Same surface as the semantic-search check above.
1318
+ console.log("Verifying audit log...");
1319
+ const auditCheck = await verifyAuditLog(httpUrl, agentId, keysDir, `http://127.0.0.1:${opsPort}`, adminUser, adminPass);
1320
+ if (auditCheck.state === "ok") {
1321
+ // Present tense ONLY: the probe proves current recording, never
1322
+ // historical completeness — see AuditVerifyResult's doc comment.
1323
+ 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)")}`);
1324
+ }
1325
+ else if (auditCheck.state === "degraded") {
1326
+ if (auditCheck.cause === "disabled") {
1327
+ console.log(`\n${render.icons.error} ${render.wrap(render.c.red, "Audit log DISABLED")} — ${auditCheck.detail}.`);
1328
+ 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.")}`);
1329
+ }
1330
+ else {
1331
+ console.log(`\n${render.icons.error} ${render.wrap(render.c.red, "Audit log NOT RECORDING")} — ${auditCheck.detail}.`);
1332
+ 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.")}`);
1333
+ 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\".")}`);
1334
+ 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.")}`);
1335
+ }
1336
+ }
1337
+ else if (auditCheck.state === "failed") {
1338
+ // Same loud discipline as the semantic-search probe above (flair#1501).
1339
+ console.log(`\n${render.icons.error} ${render.wrap(render.c.red, "Audit log probe rejected")} — ${auditCheck.detail}.`);
1340
+ 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>.")}`);
1341
+ }
1342
+ else {
1343
+ // An unrun check must not look like a pass.
1344
+ console.log(`${render.icons.warn} Audit log: UNVERIFIED (could not probe — ${auditCheck.detail})`);
1067
1345
  }
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
1346
  }
1074
1347
  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})`);
1348
+ console.log(`Agent registration deferred. After flair start, run flair init --agent ${JSON.stringify(agentId)} (keep your instance flags).`);
1077
1349
  }
1078
- // Output — admin password printed once, never written to disk
1079
- console.log("\n✅ Flair initialized successfully");
1350
+ // flair#2141 S2 — seed the using-flair skill before init reports success.
1351
+ await seedUsingFlairSkillOnInstall();
1352
+ console.log(opts.skipStart ? "\n✅ Flair configured locally (no agent registered)" : "\n✅ Flair initialized successfully");
1080
1353
  console.log(` Agent ID: ${agentId}`);
1081
1354
  console.log(` Flair URL: ${httpUrl}`);
1082
1355
  console.log(` Private key: ${privPath}`);
@@ -1104,16 +1377,18 @@ export function register(program) {
1104
1377
  // "AI assistant [default]" — it leaked into bootstrap output and
1105
1378
  // confused users. Now those paths leave the soul empty and nudge the
1106
1379
  // user toward `flair soul set` / `flair doctor` instead.
1107
- if (!opts.skipSoul && process.stdin.isTTY) {
1380
+ if (!opts.skipStart && !opts.skipSoul && process.stdin.isTTY) {
1108
1381
  const soulEntries = await runSoulWizard(agentId);
1109
1382
  if (soulEntries.length > 0) {
1110
1383
  console.log("");
1111
1384
  for (const [key, value] of soulEntries) {
1112
1385
  try {
1113
- await api("PUT", `/Soul/${agentId}:${key}`, { id: `${agentId}:${key}`, agentId, key, value, createdAt: new Date().toISOString() }, { baseUrl: httpUrl, explicitAdminPass: adminPass, adminUser });
1386
+ await api("PUT", `/Soul/${encodeRecordId(`${agentId}:${key}`)}`, { id: `${agentId}:${key}`, agentId, key, value, createdAt: new Date().toISOString() }, { baseUrl: httpUrl, explicitAdminPass: adminPass, adminUser });
1114
1387
  console.log(` ✓ soul:${key} set`);
1115
1388
  }
1116
1389
  catch (err) {
1390
+ if (err instanceof ApiRequestOutcomeUnknown)
1391
+ throw err;
1117
1392
  const message = err instanceof Error ? err.message : String(err);
1118
1393
  console.warn(` ⚠ soul:${key} failed: ${message}`);
1119
1394
  }
@@ -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
  });