@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,11 +1,15 @@
1
- import { DEFAULT_ADMIN_USER } from "../lib/auth-resolve.js";
1
+ import { DEFAULT_ADMIN_USER, defaultAdminPassPath, readAdminPassFileSecure } from "../lib/auth-resolve.js";
2
+ import { seedUsingFlairSkill } from "../lib/skill-seed.js";
3
+ import { reconcilePendingSkillSeed, skillSeedPendingPath } from "../lib/skill-seed-pending.js";
2
4
  import { classifyDaemonState } from "../lib/daemon-liveness.js";
3
- import { diagnoseLaunchdPlistPaths, isDetached, renderDetachedWarning, verifyLaunchdManagement } from "../lib/launchd-management.js";
5
+ import { decideStartOnUnknown, probePortListening } from "../lib/stop-start-recovery.js";
6
+ import { diagnoseLaunchdPlistPaths, isDetached, renderDetachedWarning, renderManagedStartUnconfirmed } from "../lib/launchd-management.js";
4
7
  import { LaunchdValidationRefusal, loadabilityAllowsAttempt, renderDirectRunNotice, renderStartLaunchdUnavailable, } from "../lib/launchd-domain-preflight.js";
8
+ import { mapRepairThrow } from "../lib/launchd-repair.js";
5
9
  import { opsSocketPathRefusal } from "../lib/socket-path-limit.js";
6
10
  import { formatServingTreeLine, formatTreeAssessmentLines } from "../lib/tree-divergence.js";
7
11
  import { spawn } from "node:child_process";
8
- import { existsSync } from "node:fs";
12
+ import { existsSync, readFileSync } from "node:fs";
9
13
  import { join } from "node:path";
10
14
  let cli;
11
15
  /** Bind the cli-locals this module depends on. */
@@ -40,6 +44,21 @@ export function restartTreeReport(a) {
40
44
  }
41
45
  return { ok: true, lines: [` ${formatServingTreeLine(a)}`] };
42
46
  }
47
+ /**
48
+ * flair#2422: the warning lines `flair start` prints for an unconfirmed
49
+ * launchd-managed start. Forwards the sidecar outcome's confirmation and
50
+ * detail, and the launchd observer's detail and remedy, to the renderer.
51
+ */
52
+ export function managedStartUnconfirmedLines(input) {
53
+ return renderManagedStartUnconfirmed({
54
+ port: input.port,
55
+ confirmation: input.recorded.confirmation,
56
+ detail: input.recorded.detail,
57
+ moved: input.moved,
58
+ launchdDetail: input.managed.detail,
59
+ remedy: input.managed.remedy,
60
+ });
61
+ }
43
62
  function closedDirectSpawnEnv(...args) {
44
63
  return cli.closedDirectSpawnEnv(...args);
45
64
  }
@@ -109,12 +128,51 @@ function stampEngineVersionIfRunning(...args) {
109
128
  function waitForHealth(...args) {
110
129
  return cli.waitForHealth(...args);
111
130
  }
131
+ function recordManagedStartSidecar(...args) {
132
+ return cli.recordManagedStartSidecar(...args);
133
+ }
112
134
  function waitForProcessExit(...args) {
113
135
  return cli.waitForProcessExit(...args);
114
136
  }
115
137
  function writeDaemonSidecar(...args) {
116
138
  return cli.writeDaemonSidecar(...args);
117
139
  }
140
+ /**
141
+ * Finish a local --skip-start init's deferred seed after this command has
142
+ * started its instance (flair#2141 S2). A seed it cannot complete is a
143
+ * WARNING, not a failure: the server started, so `flair start` exits 0 and the
144
+ * pending marker stays for the next `flair start`. The credential case names
145
+ * the remedy.
146
+ */
147
+ async function seedAfterStart(dataDir, port) {
148
+ try {
149
+ const outcome = await reconcilePendingSkillSeed(dataDir, async () => {
150
+ const passPath = defaultAdminPassPath();
151
+ const pass = process.env.FLAIR_ADMIN_PASS || process.env.HDB_ADMIN_PASSWORD ||
152
+ (existsSync(passPath) ? readAdminPassFileSecure(passPath) : "");
153
+ if (!pass) {
154
+ throw new Error(`admin credentials are needed to seed it — set FLAIR_ADMIN_PASS or restore ${passPath}, ` +
155
+ "then run 'flair start' again");
156
+ }
157
+ return seedUsingFlairSkill({
158
+ baseUrl: `http://127.0.0.1:${port}`,
159
+ user: DEFAULT_ADMIN_USER,
160
+ pass,
161
+ notify: (line) => console.log(line),
162
+ });
163
+ });
164
+ if (!outcome)
165
+ return;
166
+ if (outcome.kind === "refused") {
167
+ console.error(`⚠️ Flair started, but the using-flair skill seed is still pending: ${outcome.message}`);
168
+ return;
169
+ }
170
+ console.log(`using-flair skill: ${outcome.message}`);
171
+ }
172
+ catch (err) {
173
+ console.error(`⚠️ Flair started, but the using-flair skill seed is still pending: ${err?.message ?? err}`);
174
+ }
175
+ }
118
176
  export function register(program) {
119
177
  const LEGACY_LAUNCHD_LABEL = cli.LEGACY_LAUNCHD_LABEL;
120
178
  const STARTUP_TIMEOUT_MS = cli.STARTUP_TIMEOUT_MS;
@@ -132,14 +190,29 @@ export function register(program) {
132
190
  // the new instance-scoped one, or a pre-flair#693 legacy install.
133
191
  const { plistPath } = resolveLaunchdLabel(defaultDataDir());
134
192
  if (existsSync(plistPath)) {
193
+ const dataDir = defaultDataDir();
194
+ let pid = null;
135
195
  try {
196
+ const n = Number(readFileSync(join(dataDir, "hdb.pid"), "utf-8").trim());
197
+ if (!Number.isSafeInteger(n) || n <= 0)
198
+ throw new Error("recorded pid is invalid");
199
+ pid = n;
136
200
  const { execSync } = await import("node:child_process");
137
201
  execSync(`launchctl unload "${plistPath}"`, { stdio: "pipe" });
202
+ // Verify the captured pid exited before attempting confirmed-dead cleanup.
203
+ await waitForProcessExit(pid, STARTUP_TIMEOUT_MS);
204
+ removeStaleSidecarIfConfirmedDead(dataDir, pid);
138
205
  console.log("✅ Flair stopped (launchd service unloaded)");
139
206
  return;
140
207
  }
141
- catch {
142
- // launchd unload failed, try PID fallback
208
+ catch (err) {
209
+ const failure = mapRepairThrow(err);
210
+ console.error(`❌ flair stop: launchd stop failed for ${dataDir} (pid ${pid ?? "unknown"}): ${failure.detail}`);
211
+ if (failure.kind === "failed") {
212
+ for (const remedy of failure.remedy ?? [])
213
+ console.error(` Fix: ${remedy}`);
214
+ }
215
+ process.exit(1);
143
216
  }
144
217
  }
145
218
  }
@@ -169,12 +242,8 @@ export function register(program) {
169
242
  }
170
243
  }
171
244
  await waitForProcessExit(pid, STARTUP_TIMEOUT_MS);
172
- // flair#2055: once the process is CONFIRMED gone, drop the identity
173
- // sidecar — a leftover naming the stopped pid is what makes a later
174
- // instance under another supervisor refuse. Gated on a fresh
175
- // O_NOFOLLOW read that still names the pid it named before; unknown
176
- // liveness removes nothing.
177
- removeStaleSidecarIfConfirmedDead(dataDir);
245
+ // Use the PID the exit probe observed gone for best-effort cleanup.
246
+ removeStaleSidecarIfConfirmedDead(dataDir, pid);
178
247
  const after = await probeHealth(port);
179
248
  if (after.kind === "refused") {
180
249
  console.log(`✅ Flair stopped (${label}, pid ${pid})`);
@@ -185,9 +254,6 @@ export function register(program) {
185
254
  return;
186
255
  }
187
256
  case "NOT_RUNNING":
188
- // A sidecar left naming a pid that is CONFIRMED gone is a leftover too
189
- // (flair#2055); clearing it here keeps a repeat stop from carrying the
190
- // refusal forward.
191
257
  removeStaleSidecarIfConfirmedDead(dataDir);
192
258
  console.log("Flair is not running.");
193
259
  return;
@@ -224,11 +290,9 @@ export function register(program) {
224
290
  process.exit(1);
225
291
  }
226
292
  // Already-running check via the five-state liveness machine (flair#1454).
227
- // The old check was a bare `fetch /Health` that treated "got a response"
228
- // as "already running" and exited 0 — half of #1454. Now the machine
229
- // classifies, and every non-NOT_RUNNING state refuses with a non-zero exit.
230
293
  const evidence = await gatherDaemonEvidence(port, dataDir);
231
294
  const state = classifyDaemonState(evidence, { port, dataDir });
295
+ let recoveryPid;
232
296
  switch (state.state) {
233
297
  case "NOT_RUNNING":
234
298
  break; // proceed to boot
@@ -246,11 +310,36 @@ export function register(program) {
246
310
  console.error(` port: ${port}`);
247
311
  console.error(` To inspect: flair doctor`);
248
312
  process.exit(1);
249
- case "UNKNOWN":
250
- console.error(`⚠️ ${state.detail}`);
251
- console.error(` Refusing to start — could not determine whether Flair is running.`);
313
+ case "UNKNOWN": {
314
+ const probe = await probePortListening(port);
315
+ const decision = decideStartOnUnknown({ evidence, detail: state.detail, port, probe });
316
+ for (const line of decision.lines)
317
+ console.error(line);
318
+ if (decision.proceed) {
319
+ recoveryPid = evidence.pidfile.kind === "present" ? evidence.pidfile.pid : evidence.lastKnownPid;
320
+ break;
321
+ }
252
322
  process.exit(1);
323
+ }
253
324
  }
325
+ const recheckRecovery = async () => {
326
+ if (recoveryPid === undefined)
327
+ return;
328
+ const observed = await gatherDaemonEvidence(port, dataDir);
329
+ const probe = await probePortListening(port);
330
+ const fresh = { ...observed, ...cli.gatherDaemonOwnerEvidence(dataDir) };
331
+ const pid = fresh.pidfile.kind === "present" ? fresh.pidfile.pid : fresh.lastKnownPid;
332
+ const decision = decideStartOnUnknown({
333
+ evidence: pid === recoveryPid ? fresh : { ...fresh, pidLiveness: { kind: "unknown", reason: "recorded owner changed" } },
334
+ detail: "Rechecking the recorded owner before start.", port,
335
+ probe,
336
+ });
337
+ if (pid !== recoveryPid || !decision.proceed) {
338
+ for (const line of decision.lines)
339
+ console.error(line);
340
+ process.exit(1);
341
+ }
342
+ };
254
343
  if (!existsSync(dataDir)) {
255
344
  console.error("❌ No Flair data directory found. Run 'flair init' first.");
256
345
  process.exit(1);
@@ -301,31 +390,46 @@ export function register(program) {
301
390
  }
302
391
  const { execSync } = await import("node:child_process");
303
392
  // Targeted at gui/<uid> — the domain the preflight probed (flair#2040).
393
+ await recheckRecovery();
304
394
  const { label, migrated } = ensureLaunchdServiceLoaded(dataDir, (cmd) => execSync(cmd, { stdio: "pipe" }));
305
- await waitForHealth(port, DEFAULT_ADMIN_USER, process.env.HDB_ADMIN_PASSWORD ?? "", STARTUP_TIMEOUT_MS);
395
+ // flair#2411: wait for health and record the identity sidecar naming
396
+ // the pid launchd reports, only once that pid is confirmed to be the
397
+ // one serving this instance. An unconfirmed pid writes nothing and
398
+ // names the check that failed.
399
+ const recorded = await recordManagedStartSidecar(dataDir, port, label, {
400
+ adminPass: process.env.HDB_ADMIN_PASSWORD ?? "",
401
+ });
306
402
  readyOpsSocketPosture(dataDir); // flair#763: re-assert socket posture on the freshly-created socket
307
403
  stampEngineVersionIfRunning(dataDir); // flair#1047: stamp the store with the engine version
308
- // flair#2040: the launchd check mark only after VERIFYING that
309
- // launchd's pid IS the identified serving pid — a healthy port is
310
- // not proof that launchd started what answers it, and an
311
- // unidentified serving process is not proof either.
312
- const managed = observeLaunchdManagement(dataDir, port);
313
- const verdict = verifyLaunchdManagement(managed);
314
- if (verdict.verified) {
315
- // The migration's check mark too only after the strict verifier
316
- // passed: moving a plist is not launchd running this instance.
404
+ if (recorded.recorded) {
405
+ await seedAfterStart(dataDir, port);
406
+ // The migration's check mark too only after the identity was confirmed:
407
+ // moving a plist is not launchd running this instance.
317
408
  if (migrated)
318
409
  console.log(`Migrated launchd service off the legacy label (${LEGACY_LAUNCHD_LABEL}) → ${label} ✓`);
319
- console.log(`✅ Flair started (launchd-managed: ${verdict.detail})`);
410
+ console.log(`✅ Flair started (launchd-managed: ${recorded.detail})`);
320
411
  return;
321
412
  }
322
- // Healthy, but not proven to be launchd's process: no launchd check
323
- // mark, and no claim about what happens at the next reboot either.
324
- console.error(`⚠️ Flair is running on port ${port}, but it is NOT verified as launchd-managed: ${managed.detail}`);
325
- if (migrated)
326
- console.error(` The launchd service was moved off the legacy label (${LEGACY_LAUNCHD_LABEL}) → ${label}.`);
327
- if (managed.remedy?.length)
328
- console.error(` Fix: ${managed.remedy.join(" && ")}`);
413
+ // flair#2040/#2422: the managed process was not confirmed. No launchd
414
+ // check mark, and no claim about what happens at the next reboot. The
415
+ // warning reports what the confirmation probe saw on the port; it says
416
+ // Flair is running for the Flair-shaped answer, and names the probe's
417
+ // other results instead.
418
+ const managed = observeLaunchdManagement(dataDir, port);
419
+ for (const line of managedStartUnconfirmedLines({
420
+ port,
421
+ recorded,
422
+ managed,
423
+ moved: migrated
424
+ ? `The launchd service was moved off the legacy label (${LEGACY_LAUNCHD_LABEL}) → ${label}.`
425
+ : undefined,
426
+ })) {
427
+ console.error(line);
428
+ }
429
+ if (existsSync(skillSeedPendingPath(dataDir))) {
430
+ console.error("❌ Flair started, but its identity is unverified; the using-flair skill seed remains pending. Run 'flair doctor' before retrying.");
431
+ process.exit(1);
432
+ }
329
433
  return;
330
434
  }
331
435
  catch (err) {
@@ -367,6 +471,7 @@ export function register(program) {
367
471
  adminUser: DEFAULT_ADMIN_USER,
368
472
  adminPass,
369
473
  }));
474
+ await recheckRecovery();
370
475
  const proc = spawn(process.execPath, [bin, "run", "."], {
371
476
  cwd: flairPackageDir(), env, detached: true, stdio: "ignore",
372
477
  });
@@ -381,6 +486,14 @@ export function register(program) {
381
486
  await waitForHealth(port, DEFAULT_ADMIN_USER, adminPass, STARTUP_TIMEOUT_MS);
382
487
  readyOpsSocketPosture(dataDir); // flair#763: re-assert socket posture on the freshly-created socket
383
488
  stampEngineVersionIfRunning(dataDir); // flair#1047: stamp the store with the engine version
489
+ if (existsSync(skillSeedPendingPath(dataDir))) {
490
+ const observed = classifyDaemonState(await gatherDaemonEvidence(port, dataDir), { port, dataDir });
491
+ if (observed.state !== "RUNNING" || observed.pid !== proc.pid) {
492
+ console.error("❌ Flair answered health, but this start did not prove the serving process; the using-flair skill seed remains pending.");
493
+ process.exit(1);
494
+ }
495
+ await seedAfterStart(dataDir, port);
496
+ }
384
497
  if (launchdFellBack) {
385
498
  // flair#2040: a direct start that took launchd's place says so.
386
499
  const [headline, ...rest] = renderDirectRunNotice(port, proc.pid ?? null);
@@ -1,4 +1,5 @@
1
1
  import * as render from "../render.js";
2
+ import { encodeRecordId } from "../lib/record-id-path.js";
2
3
  let cli;
3
4
  /** Bind shared CLI helpers. cli.ts calls this immediately before register(program). */
4
5
  export function bindCli(fns) {
@@ -23,7 +24,7 @@ export function register(program) {
23
24
  .requiredOption("--agent <id>")
24
25
  .requiredOption("--key <key>")
25
26
  .requiredOption("--value <value>")
26
- .option("--durability <d>", "permanent|persistent|standard|ephemeral (default permanent — soul entries are identity, not working memory)")
27
+ .option("--durability <d>", "Stored Soul label (permanent/persistent/standard/ephemeral). Soul has no expiresAt/validTo and is not scanned by MemoryMaintenance. PUT supplies no default; omitted durability is unset.")
27
28
  .option("--url <url>", "Flair base URL (overrides the URL resolved from config; env: FLAIR_URL)")
28
29
  .option("--json", "Emit raw JSON response (also: pipe + FLAIR_OUTPUT=json)")
29
30
  .action(async (opts) => {
@@ -39,7 +40,7 @@ export function register(program) {
39
40
  // wrote a record owned by X while signing as Y (the soul family's stale rung).
40
41
  const { agentId, source } = resolveSigningAgentId(opts, "soul set");
41
42
  const id = `${opts.agent}:${opts.key}`;
42
- const out = await api("PUT", `/Soul/${encodeURIComponent(id)}`, {
43
+ const out = await api("PUT", `/Soul/${encodeRecordId(id)}`, {
43
44
  id,
44
45
  agentId: opts.agent,
45
46
  key: opts.key,
@@ -71,7 +72,7 @@ export function register(program) {
71
72
  // signer through the canonical seam so soul get honors the SAME precedence
72
73
  // as every other family; a null result lets api() fall to admin-pass/floor.
73
74
  const { agentId, source } = resolveSigningAgentId(opts, "soul get");
74
- const out = await api("GET", `/Soul/${id}`, undefined, { agentId, agentIdSource: source, explicitAdminPass: opts.adminPass, adminUser: opts.adminUser, baseUrl: opts.url });
75
+ const out = await api("GET", `/Soul/${encodeRecordId(id)}`, undefined, { agentId, agentIdSource: source, explicitAdminPass: opts.adminPass, adminUser: opts.adminUser, baseUrl: opts.url });
75
76
  const mode = render.resolveOutputMode(opts);
76
77
  if (mode === "json") {
77
78
  console.log(render.asJSON(out));
@@ -96,12 +96,16 @@ export function statusVersionAdvice(input) {
96
96
  * The ops-API bind is read from the same harper-config.yaml doctor reads.
97
97
  * Only judged for a loopback target: the LOCAL install's config says nothing
98
98
  * about a remote instance, and warning about the wrong machine is its own lie.
99
+ *
100
+ * `dataDir` defaults to `defaultDataDir()`, so both call sites (plain `status`
101
+ * and `status deep`) behave as before. It is injectable so a test can drive the
102
+ * decision against a temp data dir, without touching process.env.
99
103
  */
100
- function localOpsApiWarnings(baseUrl) {
104
+ export function localOpsApiWarnings(baseUrl, dataDir = defaultDataDir()) {
101
105
  const out = [];
102
106
  if (!isLocalhostUrl(baseUrl))
103
107
  return out;
104
- const finding = opsApiBindFinding(readHarperConfig(defaultDataDir()));
108
+ const finding = opsApiBindFinding(readHarperConfig(dataDir));
105
109
  if (finding?.allInterfaces) {
106
110
  // Name where the full explanation + fix live, matching the status warning
107
111
  // convention (docs/quickstart.md: a warning names the command to run).
@@ -269,6 +273,25 @@ export async function discoverLocalFlairPort(originalUrl) {
269
273
  }
270
274
  return null;
271
275
  }
276
+ /** Freshness of the newest distillation from a completed cycle with no errors or skips, observed in the server-local log tail. */
277
+ export const DISTILL_STALE_AFTER_MS = 2 * 24 * 3600 * 1000;
278
+ export function distillationStaleness(rem, now = Date.now()) {
279
+ const last = typeof rem.lastDistilledAt === "string" && rem.lastDistilledAt.length > 0
280
+ ? rem.lastDistilledAt
281
+ : null;
282
+ const pending = typeof rem.pendingCandidates === "number" ? rem.pendingCandidates : null;
283
+ const age = last ? now - new Date(last).getTime() : null;
284
+ const stale = pending === 0
285
+ && rem.nightlyEnabled !== false
286
+ && (rem.lastDistillationIncomplete === true || age === null || !Number.isFinite(age) || age > DISTILL_STALE_AFTER_MS);
287
+ return { lastDistilledAt: last, stale };
288
+ }
289
+ /** Observed server-local log-tail time and freshness. */
290
+ export function distillStalenessLine(ds, relative) {
291
+ const base = (ds.lastDistilledAt ? relative(ds.lastDistilledAt) : "not observed") + " (server-local log tail)";
292
+ return ds.stale ? base + DISTILL_STALE_HINT : base;
293
+ }
294
+ const DISTILL_STALE_HINT = " — no recent complete distillation observed";
272
295
  export function register(program) {
273
296
  const __pkgVersion = cli.__pkgVersion;
274
297
  // Renders OAuth status lines from non-secret metadata. /HealthDetail never
@@ -570,8 +593,13 @@ export function register(program) {
570
593
  console.log(render.kv("Nightly", nightlyTxt));
571
594
  if (r.nightlyEnabled && r.lastNightlyAt)
572
595
  console.log(render.kv("Last nightly", render.relativeTime(r.lastNightlyAt)));
573
- if (typeof r.pendingCandidates === "number" && r.pendingCandidates > 0) {
574
- console.log(render.kv("Pending candidates", render.wrap(render.c.yellow, String(r.pendingCandidates))));
596
+ const ds = distillationStaleness(r);
597
+ if (typeof r.pendingCandidates === "number") {
598
+ console.log(render.kv("Pending candidates", render.wrap(ds.stale || r.pendingCandidates > 0 ? render.c.yellow : render.c.dim, String(r.pendingCandidates))));
599
+ }
600
+ if (typeof r.pendingCandidates === "number" || ds.lastDistilledAt || ds.stale) {
601
+ const text = distillStalenessLine(ds, render.relativeTime);
602
+ console.log(render.kv("Last distilled", ds.stale ? render.wrap(render.c.yellow, text) : render.wrap(render.c.dim, text)));
575
603
  }
576
604
  }
577
605
  if (healthData?.federation) {
@@ -663,13 +691,18 @@ export function register(program) {
663
691
  if (r.lastNightlyAt) {
664
692
  console.log(render.kv("Last nightly", `${render.relativeTime(r.lastNightlyAt)} ${render.wrap(render.c.dim, `(${r.lastNightlyAt})`)}`, 18));
665
693
  }
694
+ const ds = distillationStaleness(r);
666
695
  if (typeof r.pendingCandidates === "number") {
667
- const pendingColor = r.pendingCandidates > 0 ? render.c.yellow : render.c.dim;
696
+ const pendingColor = ds.stale || r.pendingCandidates > 0 ? render.c.yellow : render.c.dim;
668
697
  console.log(render.kv("Pending candidates", render.wrap(pendingColor, String(r.pendingCandidates)), 18));
669
698
  }
670
699
  else {
671
700
  console.log(render.kv("Pending candidates", render.wrap(render.c.dim, "— (schema not available)"), 18));
672
701
  }
702
+ if (typeof r.pendingCandidates === "number" || ds.lastDistilledAt || ds.stale) {
703
+ const text = distillStalenessLine(ds, render.relativeTime);
704
+ console.log(render.kv("Last distilled", ds.stale ? render.wrap(render.c.yellow, text) : render.wrap(render.c.dim, text), 18));
705
+ }
673
706
  });
674
707
  statusCmd
675
708
  .command("federation")
@@ -1026,6 +1059,11 @@ export function register(program) {
1026
1059
  console.log(`Last nightly: ${relativeTime(r.lastNightlyAt)} (${r.lastNightlyAt})`);
1027
1060
  if (typeof r.pendingCandidates === "number")
1028
1061
  console.log(`Pending candidates: ${r.pendingCandidates}`);
1062
+ const ds = distillationStaleness(r);
1063
+ if (typeof r.pendingCandidates === "number" || ds.lastDistilledAt || ds.stale) {
1064
+ const base = ds.lastDistilledAt ? `${relativeTime(ds.lastDistilledAt)} (${ds.lastDistilledAt})` : "not observed";
1065
+ console.log(`Last distilled: ${base} (server-local log tail)${ds.stale ? DISTILL_STALE_HINT : ""}`);
1066
+ }
1029
1067
  }
1030
1068
  if (healthData?.federation) {
1031
1069
  const f = healthData.federation;
@@ -1,4 +1,5 @@
1
1
  import * as render from "../render.js";
2
+ import { encodeRecordId } from "../lib/record-id-path.js";
2
3
  let cli;
3
4
  /** Bind the cli-locals this module depends on. */
4
5
  export function bindCli(fns) {
@@ -61,7 +62,7 @@ export function register(program) {
61
62
  };
62
63
  if (agentId)
63
64
  body.agentId = agentId;
64
- await api("PUT", `/Memory/${id}`, body, { baseUrl });
65
+ await api("PUT", `/Memory/${encodeRecordId(id)}`, body, { baseUrl });
65
66
  memoryId = id;
66
67
  return true;
67
68
  });
@@ -81,7 +82,7 @@ export function register(program) {
81
82
  console.log(` (skipped — no id returned from write step)`);
82
83
  return true;
83
84
  }
84
- await api("DELETE", `/Memory/${memoryId}`, agentId ? { agentId } : undefined, { baseUrl });
85
+ await api("DELETE", `/Memory/${encodeRecordId(memoryId)}`, agentId ? { agentId } : undefined, { baseUrl });
85
86
  return true;
86
87
  });
87
88
  const passColor = passed > 0 ? render.c.green : render.c.dim;
@@ -8,6 +8,7 @@ import { classifyDaemonState } from "../lib/daemon-liveness.js";
8
8
  import { renderVerifiedSummary } from "../lib/doctor-run.js";
9
9
  import { isDetached, renderDetachedWarning } from "../lib/launchd-management.js";
10
10
  import { FLAIR_MCP_PACKAGE, clearFlairCliVersionCache } from "../lib/mcp-spec.js";
11
+ import { planRedirectMigration, renderRedirectMigration } from "../lib/mcp-oauth-env.js";
11
12
  import { createRegistryNoticePrinter, fetchLatestVersion, fetchVersionDeprecation, isStrictSemver } from "../lib/npm-registry.js";
12
13
  import { classifyUpgradePriorLiveness } from "../lib/upgrade-prior-liveness.js";
13
14
  import { decideAfterRestartFailure, decideDeprecatedRollback, formatKnownBrokenRollbackRestart } from "../lib/upgrade-rollback.js";
@@ -48,6 +49,21 @@ function doctorRunAfterUpgrade(...args) {
48
49
  function flairPackageDir(...args) {
49
50
  return cli.flairPackageDir(...args);
50
51
  }
52
+ function stageMcpRedirect(packageRoot) {
53
+ try {
54
+ const migration = planRedirectMigration({
55
+ configPath: join(packageRoot, "config.yaml"),
56
+ env: process.env,
57
+ });
58
+ const line = renderRedirectMigration(migration);
59
+ if (line)
60
+ console.log(` ${line}`);
61
+ }
62
+ catch (err) {
63
+ const reason = err instanceof Error ? err.code ?? err.message : "unknown error";
64
+ console.error(`warning: MCP OAuth redirect migration failed (${reason}). Set OAUTH_GITHUB_REDIRECT_URI to your MCP issuer origin + /oauth in ${join(packageRoot, ".env")}, then run: flair restart.`);
65
+ }
66
+ }
51
67
  function fleetSweepCallerExitMessage(...args) {
52
68
  return cli.fleetSweepCallerExitMessage(...args);
53
69
  }
@@ -772,6 +788,8 @@ export function register(program) {
772
788
  .action(async (opts) => {
773
789
  // ── Fabric-upgrade branch ───────────────────────────────────────────────
774
790
  if (opts.target) {
791
+ if (!opts.check)
792
+ console.log("OAuth redirect migration is local-only; --target requires target-side OAuth environment configuration.");
775
793
  await runFabricUpgrade(opts);
776
794
  return;
777
795
  }
@@ -1090,6 +1108,8 @@ export function register(program) {
1090
1108
  "(see above), so that is not a statement about what is running.");
1091
1109
  return;
1092
1110
  }
1111
+ if (!checkOnly)
1112
+ stageMcpRedirect(treeLane?.dir ?? flairPackageDir());
1093
1113
  console.log(anyAhead || unknownFindings.length > 0 ? "\nNo upgrades available." : "\n✅ Everything is up to date.");
1094
1114
  return;
1095
1115
  }
@@ -1125,6 +1145,8 @@ export function register(program) {
1125
1145
  // run will do. `npm install -g` remains wrong for flair-mcp either way
1126
1146
  // (#1168/#1208).
1127
1147
  if (totalUpgrades === 0) {
1148
+ if (!checkOnly)
1149
+ stageMcpRedirect(treeLane?.dir ?? flairPackageDir());
1128
1150
  if (missing.length > 0) {
1129
1151
  const npmMissing = missing.filter((f) => f.name !== FLAIR_MCP_PACKAGE);
1130
1152
  const mcpMissing = missing.some((f) => f.name === FLAIR_MCP_PACKAGE);
@@ -1389,6 +1411,8 @@ export function register(program) {
1389
1411
  if (deprecatedRestartFlagUsed) {
1390
1412
  console.error("warning: --restart is deprecated and is now a no-op — flair upgrade restarts by default. Use --no-restart to skip it.");
1391
1413
  }
1414
+ const swappedPackageRoot = treePlan?.treeDir ?? flairPackageDir();
1415
+ stageMcpRedirect(swappedPackageRoot);
1392
1416
  if (!shouldRestart) {
1393
1417
  console.log("\nRun: flair restart to use the new version");
1394
1418
  if (treePlan) {
@@ -1615,7 +1639,6 @@ export function register(program) {
1615
1639
  // from disk AFTER the swap. `null` (flair itself wasn't swapped, or the new
1616
1640
  // tree can't be verified) falls back to an in-process restart, announced.
1617
1641
  const flairWasSwapped = flairIsUpgrading && !flairInstallFailed;
1618
- const swappedPackageRoot = treePlan?.treeDir ?? flairPackageDir();
1619
1642
  let newCli = null;
1620
1643
  if (flairWasSwapped) {
1621
1644
  const resolved = resolveInstalledFlairCli(swappedPackageRoot, expectedFlairVersion);
@@ -1,4 +1,5 @@
1
- import { resolveKeyPath, buildEd25519Auth } from "../lib/auth-resolve.js";
1
+ import { resolveKeyPath, buildEd25519Auth, requestTarget, requestUrl } from "../lib/auth-resolve.js";
2
+ import { encodeRecordId } from "../lib/record-id-path.js";
2
3
  let cli;
3
4
  /** Bind shared CLI helpers. cli.ts calls this immediately before register(program). */
4
5
  export function bindCli(fns) {
@@ -75,7 +76,9 @@ export function register(program) {
75
76
  // ref overwrites the same record, which is intentional (one row per
76
77
  // agent+ref, not an append log).
77
78
  const id = `${agentId}:${opts.ref}`;
78
- const auth = buildEd25519Auth(agentId, "PUT", `/WorkspaceState/${id}`, keyPath);
79
+ const path = `/WorkspaceState/${encodeRecordId(id)}`;
80
+ const url = requestUrl(baseUrl, path);
81
+ const auth = buildEd25519Auth(agentId, "PUT", requestTarget(url), keyPath);
79
82
  // agentId IS included in the body now — WorkspaceState.put() (unlike
80
83
  // post()) does not auto-attribute from the signature, it 403s any
81
84
  // mismatch. This is a self-declaration the server verifies against the
@@ -99,7 +102,7 @@ export function register(program) {
99
102
  body.summary = opts.summary;
100
103
  if (entities && entities.length > 0)
101
104
  body.entities = entities;
102
- const res = await fetch(`${baseUrl}/WorkspaceState/${id}`, {
105
+ const res = await fetch(url, {
103
106
  method: "PUT",
104
107
  headers: { "Content-Type": "application/json", Authorization: auth },
105
108
  body: JSON.stringify(body),