@tpsdev-ai/flair 0.58.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 (268) hide show
  1. package/README.md +7 -6
  2. package/SECURITY.md +36 -0
  3. package/config.yaml +15 -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 +1030 -343
  10. package/dist/commands/agent.js +384 -45
  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 +601 -163
  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 +146 -53
  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 +81 -8
  59. package/dist/lib/doctor-run.js +140 -35
  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 +120 -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 +27 -2
  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 +1775 -338
  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 +103 -7
  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 +348 -8
  105. package/dist/resources/AgentKeyRegister.js +214 -0
  106. package/dist/resources/AgentKeyRegistration.js +28 -0
  107. package/dist/resources/AgentSeed.js +19 -4
  108. package/dist/resources/AutoPromoteCandidates.js +7 -1
  109. package/dist/resources/Credential.js +177 -2
  110. package/dist/resources/Federation.js +752 -132
  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 +227 -64
  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/OrgSkillAssignment.js +209 -0
  129. package/dist/resources/Presence.js +144 -49
  130. package/dist/resources/PromoteMemoryCandidate.js +18 -7
  131. package/dist/resources/Relationship.js +23 -0
  132. package/dist/resources/SemanticSearch.js +63 -32
  133. package/dist/resources/Soul.js +189 -76
  134. package/dist/resources/TeamDirectory.js +35 -0
  135. package/dist/resources/WorkspaceState.js +21 -1
  136. package/dist/resources/XAA.js +212 -65
  137. package/dist/resources/agent-auth.js +40 -15
  138. package/dist/resources/agent-status-guard.js +63 -0
  139. package/dist/resources/auth-middleware.js +402 -162
  140. package/dist/resources/ed25519-auth.js +1 -1
  141. package/dist/resources/embedding-space-guard.js +366 -72
  142. package/dist/resources/engine-version-stamp-boot.js +53 -0
  143. package/dist/resources/federation-classify.js +94 -0
  144. package/dist/resources/federation-crypto.js +5 -5
  145. package/dist/resources/federation-retry-lib.js +135 -0
  146. package/dist/resources/flair-agent-role-boot.js +26 -0
  147. package/dist/resources/grant-visibility.js +135 -0
  148. package/dist/resources/harper-routing.js +83 -0
  149. package/dist/resources/health.js +130 -20
  150. package/dist/resources/host-source-citation.js +49 -0
  151. package/dist/resources/host-source-visibility.js +7 -6
  152. package/dist/resources/instance-create-lock.js +17 -0
  153. package/dist/resources/instance-identity.js +23 -0
  154. package/dist/resources/instruction-version-record.js +343 -0
  155. package/dist/resources/key-lock.js +31 -0
  156. package/dist/resources/mcp-handler.js +36 -8
  157. package/dist/resources/mcp-oauth-env-guard.js +36 -0
  158. package/dist/resources/mcp-oauth.js +26 -12
  159. package/dist/resources/mcp-tool-arguments.js +4 -6
  160. package/dist/resources/mcp-tools.js +150 -23
  161. package/dist/resources/memory-bootstrap-lib.js +5 -15
  162. package/dist/resources/memory-declared-attributes.js +3 -1
  163. package/dist/resources/memory-deletion-history.js +55 -0
  164. package/dist/resources/memory-durability.js +54 -0
  165. package/dist/resources/memory-embed-hash.js +88 -0
  166. package/dist/resources/memory-embedding-value.js +8 -0
  167. package/dist/resources/memory-host-source.js +27 -5
  168. package/dist/resources/memory-id-guard.js +75 -0
  169. package/dist/resources/memory-redaction.js +236 -0
  170. package/dist/resources/memory-supplied-vector.js +72 -0
  171. package/dist/resources/memory-write-lock.js +310 -0
  172. package/dist/resources/memory-write-response.js +139 -0
  173. package/dist/resources/migrations/data-dir.js +74 -16
  174. package/dist/resources/migrations/dir-safety.js +1 -1
  175. package/dist/resources/migrations/embedding-stamp.js +193 -79
  176. package/dist/resources/migrations/export.js +1 -0
  177. package/dist/resources/migrations/graph-heal.js +18 -25
  178. package/dist/resources/migrations/lock.js +7 -1
  179. package/dist/resources/migrations/snapshot.js +1 -0
  180. package/dist/resources/migrations/source-fields.js +5 -5
  181. package/dist/resources/migrations/synthetic-test-migration.js +14 -11
  182. package/dist/resources/migrations/visibility-backfill.js +29 -29
  183. package/dist/resources/multi-worker-guard.js +121 -0
  184. package/dist/resources/oauth-discovery.js +1 -0
  185. package/dist/resources/oauth-wellknown.js +8 -4
  186. package/dist/resources/object-body-guard.js +33 -0
  187. package/dist/resources/org-event-created-at.js +133 -0
  188. package/dist/resources/originator-instance.js +39 -7
  189. package/dist/resources/owner-delete-recheck.js +78 -0
  190. package/dist/resources/owner-field-guard.js +39 -5
  191. package/dist/resources/owner-scoped-write-policy.js +212 -0
  192. package/dist/resources/owner-scoped-writes.js +58 -0
  193. package/dist/resources/presence-receipt.js +236 -0
  194. package/dist/resources/promotion-stamp.js +47 -12
  195. package/dist/resources/record-owner-guard.js +74 -26
  196. package/dist/resources/record-types.js +17 -1
  197. package/dist/resources/relay-ops.js +78 -6
  198. package/dist/resources/replay-store.js +145 -21
  199. package/dist/resources/request-target.js +136 -0
  200. package/dist/resources/request-transaction.js +35 -0
  201. package/dist/resources/search-readiness.js +4 -1
  202. package/dist/resources/seed-ids.js +9 -0
  203. package/dist/resources/seed-reservation.js +117 -0
  204. package/dist/resources/semantic-retrieval-core.js +20 -9
  205. package/dist/resources/skill-manifest.js +190 -0
  206. package/dist/resources/skill-provenance.js +15 -10
  207. package/dist/resources/skill-subject.js +53 -0
  208. package/dist/resources/skill-version-write.js +432 -0
  209. package/dist/resources/skill-write-fault.js +17 -0
  210. package/dist/resources/skill-write-policy.js +67 -0
  211. package/dist/resources/skill-write.js +67 -7
  212. package/dist/resources/table-helpers.js +10 -7
  213. package/dist/resources/team-directory.js +248 -0
  214. package/dist/resources/tool-descriptors/index.js +69 -8
  215. package/dist/resources/txn-pause-point.js +118 -0
  216. package/dist/resources/usage-recording.js +171 -63
  217. package/dist/resources/write-back.js +218 -0
  218. package/dist/src/engine-version-contract.js +1 -0
  219. package/dist/src/keystore.js +72 -0
  220. package/dist/src/lib/agent-home-fields.js +132 -0
  221. package/dist/src/lib/agent-id-rule.js +46 -0
  222. package/dist/src/lib/agent-key-register.js +80 -0
  223. package/dist/src/lib/atomic-write.js +256 -0
  224. package/dist/src/lib/credential-status-rule.js +78 -0
  225. package/dist/src/lib/expired-by-agent.js +37 -0
  226. package/dist/src/lib/flair-agent-role.js +120 -0
  227. package/dist/src/lib/idp-mapping-rule.js +81 -0
  228. package/dist/src/lib/instance-identity-row.js +20 -0
  229. package/dist/src/lib/mcp-oauth-env-core.js +133 -0
  230. package/dist/src/lib/memory-attributes.js +2 -0
  231. package/dist/src/lib/memory-id-policy.js +46 -0
  232. package/dist/src/lib/principal-status.js +29 -0
  233. package/dist/src/lib/proto-safe-record.js +42 -0
  234. package/dist/src/lib/reembed-server-support.js +66 -0
  235. package/dist/src/lib/scheduler-platform.js +10 -6
  236. package/dist/src/lib/systemd-agent-id.js +38 -0
  237. package/docs/access-control.md +768 -0
  238. package/docs/api-reference.md +52 -13
  239. package/docs/auth.md +10 -12
  240. package/docs/bridges.md +11 -0
  241. package/docs/claude-code.md +34 -4
  242. package/docs/deepseek-harness.md +1 -1
  243. package/docs/deploying-on-fabric.md +70 -0
  244. package/docs/deployment.md +2 -0
  245. package/docs/embedding-in-a-harper-app.md +1 -1
  246. package/docs/federation.md +33 -2
  247. package/docs/hosted-on-fabric.md +43 -36
  248. package/docs/integrations.md +6 -6
  249. package/docs/mcp-clients.md +10 -5
  250. package/docs/n8n.md +17 -11
  251. package/docs/notes/mcp-agent-auth-consumer.md +12 -4
  252. package/docs/notes/mcp-oauth-model2.md +34 -5
  253. package/docs/quickstart-fabric.md +2 -2
  254. package/docs/quickstart.md +9 -1
  255. package/docs/releasing.md +34 -28
  256. package/docs/rem.md +8 -0
  257. package/docs/secrets-and-keys.md +19 -2
  258. package/docs/standalone-local.md +1 -0
  259. package/docs/supply-chain-policy.md +13 -3
  260. package/docs/upgrade.md +32 -6
  261. package/package.json +12 -6
  262. package/schemas/agent-key-registration.graphql +22 -0
  263. package/schemas/agent.graphql +3 -0
  264. package/schemas/federation.graphql +38 -1
  265. package/schemas/memory.graphql +115 -5
  266. package/schemas/oauth.graphql +27 -4
  267. package/schemas/schema.graphql +2 -0
  268. package/templates/launchd/start-flair-with-admin-pass.sh +89 -16
@@ -20,9 +20,13 @@
20
20
  // "not present", never a thrown error — doctor must never crash or hang on a
21
21
  // broken client config.
22
22
  import { spawnSync } from "node:child_process";
23
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
23
+ import { closeSync, existsSync, mkdirSync, mkdtempSync, openSync, readFileSync, readSync, rmSync, writeFileSync } from "node:fs";
24
+ import { tmpdir } from "node:os";
24
25
  import { dirname, join } from "node:path";
25
26
  import { withHome } from "./lib/home.js";
27
+ import { AGENT_ID_RULE, isValidAgentId } from "./lib/agent-id-rule.js";
28
+ import { AGENT_HOME_STAMP_REMEDY, planAgentHomeStamps } from "./lib/agent-home.js";
29
+ import { INSTANCE_ROW_PRUNE_REMEDY } from "./lib/instance-identity-row.js";
26
30
  import { ALL_CLIENTS, clientConfigPath, piSettingsPath, resolvePiExtensionPath, scanPiSettings, } from "./install/clients.js";
27
31
  import { FLAIR_MCP_PACKAGE, flairCliVersion, mcpServerSpec } from "./lib/mcp-spec.js";
28
32
  import { decidePinWrite } from "./lib/pin-write-guard.js";
@@ -120,6 +124,8 @@ export function buildSessionStartHookCommand(agentId, flairUrl, opts) {
120
124
  }
121
125
  const harness = opts?.harness ?? "claude-code";
122
126
  const envParts = harness === "codex" ? [`FLAIR_HOOK_HARNESS=${harness}`] : [];
127
+ if (opts?.actionRecall)
128
+ envParts.push("FLAIR_ACTION_RECALL=1");
123
129
  envParts.push(`FLAIR_AGENT_ID=${agentId}`);
124
130
  if (flairUrl)
125
131
  envParts.push(`FLAIR_URL=${flairUrl}`);
@@ -151,6 +157,46 @@ export const SESSION_START_HOOK_INVOCATION_RE = /npx -y -p @tpsdev-ai\/flair-mcp
151
157
  export function isSessionStartHookInvocation(command) {
152
158
  return typeof command === "string" && SESSION_START_HOOK_INVOCATION_RE.test(command);
153
159
  }
160
+ /** Does this SessionStart command enable the action-recall refresh? */
161
+ export function sessionStartEnablesActionRecall(command) {
162
+ return typeof command === "string" && command.includes("FLAIR_ACTION_RECALL=1");
163
+ }
164
+ // ── the action-recall PreToolUse hook (flair#2067 slice 2) ──────────────────
165
+ //
166
+ // Runs the absolute runtime and artifact paths selected at installation.
167
+ /** The exact substring identifying a Flair action-recall hook command. */
168
+ export const ACTION_RECALL_HOOK_MARKER = "action-recall-hook.js";
169
+ /** The Claude-only PreToolUse matcher written alongside our hook entry. */
170
+ export const ACTION_RECALL_PRE_TOOL_USE_MATCHER = "Bash";
171
+ /**
172
+ * Build the exact `command` string registered for the PreToolUse action-recall
173
+ * hook. Throws rather than emitting a quoted approximation when a value is
174
+ * unsafe. Artefact paths also allow `@`.
175
+ */
176
+ export function buildActionRecallHookCommand(bunPath, artifactPath, agentId, flairUrl) {
177
+ for (const [label, value] of [
178
+ ["agent id", agentId],
179
+ ["bun path", bunPath],
180
+ ["artefact path", artifactPath],
181
+ ]) {
182
+ if (!(label === "artefact path" ? /^[A-Za-z0-9._:@/-]+$/.test(value) : isHookCommandValueSafe(value))) {
183
+ throw new Error(`${label} '${value}' contains characters that cannot be safely written into a shell hook command (allowed: letters, digits, . _ : / -; artefact paths also allow @)`);
184
+ }
185
+ }
186
+ if (flairUrl != null && flairUrl !== "" && !isHookCommandValueSafe(flairUrl)) {
187
+ throw new Error(`Flair URL '${flairUrl}' contains characters that cannot be safely written into a shell hook command (allowed: letters, digits, . _ : / -)`);
188
+ }
189
+ const env = flairUrl ? `FLAIR_AGENT_ID=${agentId} FLAIR_URL=${flairUrl}` : `FLAIR_AGENT_ID=${agentId}`;
190
+ const invocation = `${env} ${bunPath} ${artifactPath}`;
191
+ return String.raw `sh -c 'out=$(${invocation} 2>/dev/null) && [ -n "$out" ] && [ "${"$"}{#out}" -le 4096 ] && printf %s "$out" || true'`;
192
+ }
193
+ const recognizeActionRecallCommand = installerCommandRecognizer(buildActionRecallHookCommand, ACTION_RECALL_HOOK_MARKER);
194
+ export function isFlairActionRecallCommand(command) {
195
+ return recognizeActionRecallCommand(command) !== null;
196
+ }
197
+ export function parseActionRecallCommand(command) {
198
+ return recognizeActionRecallCommand(command);
199
+ }
154
200
  /**
155
201
  * Does this command absorb a failure so the harness session still starts?
156
202
  * flair#1734: "silenced" means `|| true` (won't brick the session), not
@@ -278,6 +324,124 @@ export function isFlairContinuityCommand(command) {
278
324
  command.includes("@tpsdev-ai/flair-mcp") &&
279
325
  command.includes(CONTINUITY_CAPTURE_HOOK_MARKER));
280
326
  }
327
+ // ── the capture PostToolUseFailure/PostToolUse/Stop hook (flair#2068) ──────
328
+ //
329
+ // Runs the provisioned absolute runtime + artifact paths (same Flair-owned
330
+ // provisioning as the action-recall hook). One binary serves all three events; the
331
+ // payload's hook_event_name tells it which fired.
332
+ /** Matches this substring unless npx is bounded by whitespace or string edges; a match does not prove ownership. */
333
+ export const CAPTURE_HOOK_MARKER = "capture-hook.js";
334
+ /** Tools considered for a possible matching follow-up. */
335
+ export const CAPTURE_POST_TOOL_USE_MATCHER = "Write|Edit|NotebookEdit|Bash";
336
+ export const CAPTURE_POST_TOOL_USE_FAILURE_MATCHER = "Bash";
337
+ /** The hook events the capture hook registers under. */
338
+ export const CAPTURE_HOOK_EVENTS = ["PostToolUseFailure", "PostToolUse", "Stop"];
339
+ /** The matcher each capture event's group carries (Stop has none). */
340
+ export const CAPTURE_HOOK_MATCHERS = {
341
+ PostToolUseFailure: CAPTURE_POST_TOOL_USE_FAILURE_MATCHER,
342
+ PostToolUse: CAPTURE_POST_TOOL_USE_MATCHER,
343
+ Stop: null,
344
+ };
345
+ /** The pinned spec the background flush resolves through npx, so the flush
346
+ * runs the published package and its flair-client dependency rather than the
347
+ * dependency-free hot-path copy. */
348
+ export function captureFlushSpec() {
349
+ return `${FLAIR_MCP_PACKAGE}@${flairCliVersion()}`;
350
+ }
351
+ /**
352
+ * Build the exact `command` string registered for every capture hook event.
353
+ */
354
+ export function buildCaptureHookCommand(bunPath, artifactPath, agentId, flairUrl, flushSpec) {
355
+ for (const [label, value] of [
356
+ ["agent id", agentId],
357
+ ["bun path", bunPath],
358
+ ["artefact path", artifactPath],
359
+ ]) {
360
+ if (!(label === "artefact path" ? /^[A-Za-z0-9._:@/-]+$/.test(value) : isHookCommandValueSafe(value))) {
361
+ throw new Error(`${label} '${value}' contains characters that cannot be safely written into a shell hook command (allowed: letters, digits, . _ : / -; artefact paths also allow @)`);
362
+ }
363
+ }
364
+ if (flairUrl != null && flairUrl !== "" && !isHookCommandValueSafe(flairUrl)) {
365
+ throw new Error(`Flair URL '${flairUrl}' contains characters that cannot be safely written into a shell hook command (allowed: letters, digits, . _ : / -)`);
366
+ }
367
+ if (flushSpec != null && flushSpec !== "" && !/^@[A-Za-z0-9._/-]+@[A-Za-z0-9._-]+$/.test(flushSpec)) {
368
+ throw new Error(`flush spec '${flushSpec}' is not a safe pinned package spec`);
369
+ }
370
+ const parts = [`FLAIR_AGENT_ID=${agentId}`];
371
+ if (flairUrl)
372
+ parts.push(`FLAIR_URL=${flairUrl}`);
373
+ if (flushSpec)
374
+ parts.push(`FLAIR_CAPTURE_FLUSH_SPEC=${flushSpec}`);
375
+ return `sh -c '${parts.join(" ")} ${bunPath} ${artifactPath} >/dev/null || true'`;
376
+ }
377
+ const recognizeCurrentCaptureCommand = installerCommandRecognizer(buildCaptureHookCommand, CAPTURE_HOOK_MARKER, true);
378
+ const recognizeLegacyCaptureCommand = installerCommandRecognizer((...args) => buildCaptureHookCommand(...args).replace(" >/dev/null || true'", " >/dev/null 2>/dev/null || true'"), CAPTURE_HOOK_MARKER, true);
379
+ const recognizeCaptureCommand = (command) => recognizeCurrentCaptureCommand(command) ?? recognizeLegacyCaptureCommand(command);
380
+ export function isFlairCaptureCommand(command) {
381
+ return recognizeCaptureCommand(command) !== null;
382
+ }
383
+ export function parseCaptureCommand(command) {
384
+ return recognizeCaptureCommand(command);
385
+ }
386
+ function installerCommandRecognizer(builder, marker, withFlushSpec = false) {
387
+ const tokens = {
388
+ bunPath: "MATCH_BUN_PATH",
389
+ artifactPath: "MATCH_ARTIFACT_PATH",
390
+ agentId: "MATCH_AGENT_ID",
391
+ flairUrl: "MATCH_FLAIR_URL",
392
+ flushSpec: "@MATCH_FLUSH_PACKAGE@MATCH_FLUSH_VERSION",
393
+ };
394
+ const forms = [];
395
+ for (const url of [undefined, tokens.flairUrl]) {
396
+ for (const spec of withFlushSpec ? [undefined, tokens.flushSpec] : [undefined]) {
397
+ forms.push(builder(tokens.bunPath, tokens.artifactPath, tokens.agentId, url, spec).split(" ").map((part) => {
398
+ for (const name of Object.keys(tokens)) {
399
+ const token = tokens[name];
400
+ const offset = part.indexOf(token);
401
+ if (offset !== -1)
402
+ return { name, prefix: part.slice(0, offset), suffix: part.slice(offset + token.length) };
403
+ }
404
+ return { literal: part };
405
+ }));
406
+ }
407
+ }
408
+ return (command) => {
409
+ if (typeof command !== "string")
410
+ return null;
411
+ const commandTokens = command.split(" ");
412
+ for (const form of forms) {
413
+ if (commandTokens.length !== form.length)
414
+ continue;
415
+ const parts = {};
416
+ const matches = form.every((part, index) => {
417
+ const value = commandTokens[index];
418
+ if ("literal" in part)
419
+ return value === part.literal;
420
+ if (!value.startsWith(part.prefix) || !value.endsWith(part.suffix))
421
+ return false;
422
+ const captured = value.slice(part.prefix.length, value.length - part.suffix.length);
423
+ if (!captured)
424
+ return false;
425
+ parts[part.name] = captured;
426
+ return true;
427
+ });
428
+ if (!matches || parts.artifactPath?.split("/").at(-1) !== marker)
429
+ continue;
430
+ const { bunPath, artifactPath, agentId, flairUrl, flushSpec } = parts;
431
+ if (!bunPath || !artifactPath || !agentId)
432
+ continue;
433
+ try {
434
+ if (command === builder(bunPath, artifactPath, agentId, flairUrl, flushSpec)) {
435
+ return { bunPath, artifactPath, agentId, ...(flairUrl ? { flairUrl } : {}), ...(flushSpec ? { flushSpec } : {}) };
436
+ }
437
+ }
438
+ catch {
439
+ continue;
440
+ }
441
+ }
442
+ return null;
443
+ };
444
+ }
281
445
  /** The two hook events continuity registers under. */
282
446
  export const CONTINUITY_HOOK_EVENTS = ["PostToolUse", "Stop"];
283
447
  function findContinuityEntry(config, event) {
@@ -935,17 +1099,20 @@ export function checkSessionStartHook(homeDir, settingsPath) {
935
1099
  const groups = config?.hooks?.SessionStart;
936
1100
  if (!Array.isArray(groups))
937
1101
  return { present: false, path };
1102
+ let command;
1103
+ let matches = 0;
938
1104
  for (const group of groups) {
939
1105
  const hooks = group?.hooks;
940
1106
  if (!Array.isArray(hooks))
941
1107
  continue;
942
1108
  for (const hook of hooks) {
943
1109
  if (typeof hook?.command === "string" && hook.command.includes(SESSION_START_HOOK_MARKER)) {
944
- return { present: true, path, command: hook.command };
1110
+ matches++;
1111
+ command ??= hook.command;
945
1112
  }
946
1113
  }
947
1114
  }
948
- return { present: false, path };
1115
+ return command === undefined ? { present: false, path } : { present: true, path, command, matches };
949
1116
  }
950
1117
  catch {
951
1118
  return { present: false, path };
@@ -1180,34 +1347,191 @@ export function evidenceLine(s, max = 200) {
1180
1347
  const line = lines.find((l) => !NOISE_LINE_RE.test(l)) ?? lines[0] ?? "";
1181
1348
  return line.length > max ? `${line.slice(0, max - 1)}…` : line;
1182
1349
  }
1183
- const defaultProbeRunner = (command, timeoutMs) => {
1184
- // `/bin/sh -c` is not a guess: it is exactly how Claude Code runs a
1185
- // `type: "command"` hook (spawn with `shell: true`, $SHELL never consulted).
1186
- // Probing through any other shell would answer a question the user never
1187
- // asked.
1188
- const res = spawnSync("/bin/sh", ["-c", command], {
1189
- input: "",
1190
- encoding: "utf-8",
1350
+ const PROBE_GROUP_TERM_GRACE_MS = 200;
1351
+ const PROBE_GROUP_KILL_GRACE_MS = 2_000;
1352
+ const PROBE_PIN_MARGIN_S = 60;
1353
+ export const HOOK_PROBE_MAX_OUTPUT_BYTES = 1024 * 1024;
1354
+ function sleepMs(ms) {
1355
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, Math.max(0, ms));
1356
+ }
1357
+ function sleepUntil(deadline) {
1358
+ for (let now = performance.now(); now < deadline; now = performance.now())
1359
+ sleepMs(Math.min(5, deadline - now));
1360
+ }
1361
+ const sendSignal = (pid, signal) => {
1362
+ process.kill(pid, signal);
1363
+ };
1364
+ function signalTargetPresent(target, kill) {
1365
+ try {
1366
+ kill(target, 0);
1367
+ return true;
1368
+ }
1369
+ catch (err) {
1370
+ return err.code !== "ESRCH";
1371
+ }
1372
+ }
1373
+ export function endProbeProcessGroup(pgid, pinPid, kill = sendSignal) {
1374
+ const groupGone = () => !signalTargetPresent(-pgid, kill);
1375
+ const pinned = () => pinPid !== null && signalTargetPresent(pinPid, kill);
1376
+ const unconfirmed = (reason) => (groupGone() ? null : reason);
1377
+ let signalError = "";
1378
+ const signalGroup = (signal) => {
1379
+ try {
1380
+ kill(-pgid, signal);
1381
+ }
1382
+ catch (err) {
1383
+ signalError = `; ${signal} failed: ${err.code ?? String(err)}`;
1384
+ }
1385
+ };
1386
+ if (!pinned())
1387
+ return unconfirmed("its pin process was not present, so the group was not signalled");
1388
+ signalGroup("SIGTERM");
1389
+ sleepUntil(performance.now() + PROBE_GROUP_TERM_GRACE_MS);
1390
+ if (!pinned())
1391
+ return unconfirmed(`its pin process exited before SIGKILL, so SIGKILL was not sent${signalError}`);
1392
+ signalGroup("SIGKILL");
1393
+ const deadline = performance.now() + PROBE_GROUP_KILL_GRACE_MS;
1394
+ while (!groupGone() && performance.now() < deadline)
1395
+ sleepMs(5);
1396
+ return unconfirmed(`the group was still present ${PROBE_GROUP_KILL_GRACE_MS} ms after SIGKILL${signalError}`);
1397
+ }
1398
+ function readPinPid(path) {
1399
+ let fd = -1;
1400
+ try {
1401
+ fd = openSync(path, "r");
1402
+ const buf = Buffer.alloc(32);
1403
+ const text = buf.toString("utf-8", 0, readSync(fd, buf, 0, buf.length, 0));
1404
+ if (!/^[1-9][0-9]{0,9}$/.test(text))
1405
+ return null;
1406
+ const pid = Number(text);
1407
+ return pid > 1 && pid <= 0x7fffffff ? pid : null;
1408
+ }
1409
+ catch {
1410
+ return null;
1411
+ }
1412
+ finally {
1413
+ if (fd >= 0)
1414
+ closeSync(fd);
1415
+ }
1416
+ }
1417
+ function readCappedOutput(fd) {
1418
+ const buf = Buffer.alloc(HOOK_PROBE_MAX_OUTPUT_BYTES + 1);
1419
+ let total = 0;
1420
+ while (total < buf.length) {
1421
+ const n = readSync(fd, buf, total, buf.length - total, total);
1422
+ if (n === 0)
1423
+ break;
1424
+ total += n;
1425
+ }
1426
+ return {
1427
+ text: buf.toString("utf-8", 0, Math.min(total, HOOK_PROBE_MAX_OUTPUT_BYTES)),
1428
+ overflow: total > HOOK_PROBE_MAX_OUTPUT_BYTES,
1429
+ };
1430
+ }
1431
+ const bunRuntime = globalThis.Bun;
1432
+ // The pin must never sit at SIGTERM's default disposition: cleanup sends SIGKILL
1433
+ // only while the pin answers signal 0, so a pin killed by the probe's own
1434
+ // SIGTERM skips that SIGKILL. Ignoring the signals here, before the fork, lets
1435
+ // the pin inherit them across fork and exec instead of racing to run its own
1436
+ // `trap`; the command's shell gets the defaults back via `trap -` before its exec.
1437
+ const PROBE_WRAPPER = `trap '' HUP INT QUIT TERM; ` +
1438
+ `( ( PATH="$PATH:/bin:/usr/bin"; exec sleep "$2" ) </dev/null >/dev/null 2>&1 & ` +
1439
+ `printf '%s' "$!" >"$1" ); ` +
1440
+ `trap - HUP INT QUIT TERM; exec /bin/sh -c "$3"`;
1441
+ function spawnProbeBounded(command, timeoutMs, input, env, outFd, errFd, pinPath) {
1442
+ const pinSeconds = String(Math.ceil(timeoutMs / 1000) + PROBE_PIN_MARGIN_S);
1443
+ const wrapperPath = join(dirname(pinPath), "wrapper.sh");
1444
+ writeFileSync(wrapperPath, PROBE_WRAPPER, { mode: 0o600 });
1445
+ const args = [wrapperPath, pinPath, pinSeconds, command];
1446
+ if (bunRuntime) {
1447
+ try {
1448
+ const r = bunRuntime.spawnSync(["/bin/sh", ...args], {
1449
+ detached: true,
1450
+ stdin: Buffer.from(input),
1451
+ stdout: outFd,
1452
+ stderr: errFd,
1453
+ timeout: timeoutMs,
1454
+ killSignal: "SIGTERM",
1455
+ env,
1456
+ });
1457
+ return { pid: r.pid, exitCode: r.exitCode, timedOut: r.exitedDueToTimeout === true, spawnError: null };
1458
+ }
1459
+ catch (err) {
1460
+ return { pid: null, exitCode: null, timedOut: false, spawnError: err instanceof Error ? err.message : String(err) };
1461
+ }
1462
+ }
1463
+ const res = spawnSync("/bin/sh", args, {
1464
+ detached: true,
1465
+ stdio: ["pipe", outFd, errFd],
1466
+ input,
1191
1467
  timeout: timeoutMs,
1192
- env: {
1193
- ...process.env,
1194
- // Tell a #1007-or-later adapter to answer without side effects.
1195
- FLAIR_HOOK_PROBE: "1",
1196
- // Bound an OLDER adapter, which will do a real bootstrap + presence
1197
- // heartbeat because it has never heard of FLAIR_HOOK_PROBE.
1198
- FLAIR_HOOK_TIMEOUT_MS: "1500",
1199
- FLAIR_PRESENCE_TIMEOUT_MS: "500",
1200
- },
1468
+ env,
1201
1469
  });
1202
1470
  const timedOut = res.signal === "SIGTERM" && res.status === null;
1203
1471
  return {
1472
+ pid: typeof res.pid === "number" && res.pid > 1 ? res.pid : null,
1204
1473
  exitCode: res.status,
1205
- stdout: res.stdout ?? "",
1206
- stderr: res.stderr ?? "",
1207
1474
  timedOut,
1208
1475
  spawnError: res.error && !timedOut ? res.error.message : null,
1209
1476
  };
1210
- };
1477
+ }
1478
+ export function runProbeInOwnGroup(command, timeoutMs, opts) {
1479
+ const { input, env } = opts;
1480
+ if (process.platform === "win32") {
1481
+ const res = spawnSync("/bin/sh", ["-c", command], { input, encoding: "utf-8", timeout: timeoutMs, env });
1482
+ const timedOut = res.signal === "SIGTERM" && res.status === null;
1483
+ return { exitCode: res.status, stdout: res.stdout ?? "", stderr: res.stderr ?? "", timedOut, spawnError: res.error && !timedOut ? res.error.message : null };
1484
+ }
1485
+ const openOutput = opts.openOutput ?? ((path) => openSync(path, "w+"));
1486
+ const dir = mkdtempSync(join(opts.tmpRoot ?? tmpdir(), "flair-hook-probe-"));
1487
+ const fds = [];
1488
+ try {
1489
+ const outFd = openOutput(join(dir, "stdout"));
1490
+ fds.push(outFd);
1491
+ const errFd = openOutput(join(dir, "stderr"));
1492
+ fds.push(errFd);
1493
+ const pinPath = join(dir, "pin");
1494
+ const spawned = spawnProbeBounded(command, timeoutMs, input, env, outFd, errFd, pinPath);
1495
+ const cleanupError = spawned.pid === null ? null : endProbeProcessGroup(spawned.pid, readPinPid(pinPath), opts.kill);
1496
+ const out = readCappedOutput(outFd);
1497
+ const err = readCappedOutput(errFd);
1498
+ return {
1499
+ exitCode: spawned.exitCode,
1500
+ stdout: out.text,
1501
+ stderr: err.text,
1502
+ timedOut: spawned.timedOut,
1503
+ spawnError: spawned.spawnError,
1504
+ cleanupError,
1505
+ outputOverflow: out.overflow || err.overflow,
1506
+ };
1507
+ }
1508
+ finally {
1509
+ for (const fd of fds) {
1510
+ try {
1511
+ closeSync(fd);
1512
+ }
1513
+ catch {
1514
+ }
1515
+ }
1516
+ try {
1517
+ rmSync(dir, { recursive: true, force: true });
1518
+ }
1519
+ catch {
1520
+ }
1521
+ }
1522
+ }
1523
+ const defaultProbeRunner = (command, timeoutMs) => runProbeInOwnGroup(command, timeoutMs, {
1524
+ input: "",
1525
+ env: {
1526
+ ...process.env,
1527
+ // Tell a #1007-or-later adapter to answer without side effects.
1528
+ FLAIR_HOOK_PROBE: "1",
1529
+ // Bound an OLDER adapter, which will do a real bootstrap + presence
1530
+ // heartbeat because it has never heard of FLAIR_HOOK_PROBE.
1531
+ FLAIR_HOOK_TIMEOUT_MS: "1500",
1532
+ FLAIR_PRESENCE_TIMEOUT_MS: "500",
1533
+ },
1534
+ });
1211
1535
  /**
1212
1536
  * Delivery probe (flair#1734): run the registered command so we can classify
1213
1537
  * SessionStart additionalContext. Must NOT set FLAIR_HOOK_PROBE — that path
@@ -1215,28 +1539,16 @@ const defaultProbeRunner = (command, timeoutMs) => {
1215
1539
  */
1216
1540
  export function probeSessionStartHookDelivery(command, opts = {}) {
1217
1541
  const timeoutMs = opts.timeoutMs ?? 8_000;
1218
- const runner = opts.runner ?? ((cmd, ms) => {
1219
- const res = spawnSync("/bin/sh", ["-c", cmd], {
1220
- input: "{}",
1221
- encoding: "utf-8",
1222
- timeout: ms,
1223
- env: {
1224
- ...process.env,
1225
- FLAIR_HOOK_PROBE: "0",
1226
- FLAIR_HOOK_DELIVERY_PROBE: "1",
1227
- FLAIR_HOOK_TIMEOUT_MS: "4000",
1228
- FLAIR_PRESENCE_TIMEOUT_MS: "1",
1229
- },
1230
- });
1231
- const timedOut = res.signal === "SIGTERM" && res.status === null;
1232
- return {
1233
- exitCode: res.status,
1234
- stdout: res.stdout ?? "",
1235
- stderr: res.stderr ?? "",
1236
- timedOut,
1237
- spawnError: res.error && !timedOut ? res.error.message : null,
1238
- };
1239
- });
1542
+ const runner = opts.runner ?? ((cmd, ms) => runProbeInOwnGroup(cmd, ms, {
1543
+ input: "{}",
1544
+ env: {
1545
+ ...process.env,
1546
+ FLAIR_HOOK_PROBE: "0",
1547
+ FLAIR_HOOK_DELIVERY_PROBE: "1",
1548
+ FLAIR_HOOK_TIMEOUT_MS: "4000",
1549
+ FLAIR_PRESENCE_TIMEOUT_MS: "1",
1550
+ },
1551
+ }));
1240
1552
  try {
1241
1553
  return runner(command, timeoutMs);
1242
1554
  }
@@ -1264,6 +1576,12 @@ export function probeSessionStartHookCommand(command, opts = {}) {
1264
1576
  /** Pure: probe outcome -> verdict. See the section doc for why "exit 0, no
1265
1577
  * output" is a definite failure rather than an ambiguous one. */
1266
1578
  export function classifyHookProbe(outcome) {
1579
+ if (outcome.cleanupError) {
1580
+ return { execution: "unknown", detail: `could not confirm the command's process group ended (${outcome.cleanupError})` };
1581
+ }
1582
+ if (outcome.outputOverflow) {
1583
+ return { execution: "unknown", detail: `the command's output exceeded the probe's ${HOOK_PROBE_MAX_OUTPUT_BYTES}-byte limit` };
1584
+ }
1267
1585
  if (outcome.timedOut) {
1268
1586
  return { execution: "unknown", detail: "the command did not answer in time" };
1269
1587
  }
@@ -1440,7 +1758,7 @@ export function applyOrReportClaudeMdBootstrap(cwd, homeDir, skip) {
1440
1758
  const fix = fixClaudeMdBootstrap(cwd);
1441
1759
  return { applied: fix.ok, ok: fix.ok, message: fix.message, hint: fix.ok ? undefined : hint };
1442
1760
  }
1443
- function sessionStartHookHint(agentId, path) {
1761
+ export function sessionStartHookHint(agentId, path) {
1444
1762
  const snippet = {
1445
1763
  hooks: {
1446
1764
  SessionStart: [
@@ -1681,6 +1999,9 @@ export function resolveCollisionSafeName(existingNames, filename) {
1681
1999
  n++;
1682
2000
  return `${filename}.${n}`;
1683
2001
  }
2002
+ /** An unparseable keystore blob may be a live federation key (flair#1026). */
2003
+ const UNIDENTIFIED_SEED_REASON = "not a parseable Ed25519 private key seed — may be a keystore blob or another format; " +
2004
+ "left in place, inspect it before removing anything (flair#1026)";
1684
2005
  /**
1685
2006
  * Classify one `.key` file given whether its seed parsed (`seedValid`) and,
1686
2007
  * if it did, the registration-gate result checkAgentRegistered (src/cli.ts)
@@ -1700,19 +2021,8 @@ export function resolveCollisionSafeName(existingNames, filename) {
1700
2021
  */
1701
2022
  export function classifyKeyFile(agentId, seedValid, registration, baseUrl) {
1702
2023
  if (!seedValid) {
1703
- // NOT "invalid", and therefore NOT prunable. "I could not parse this" and
1704
- // "this is a stale agent key" are different findings, and only the second
1705
- // is safe to act on. `~/.flair/keys/<id>.key` is a namespace shared by two
1706
- // writers: plaintext Ed25519 seeds, and AES-256-GCM keystore blobs written
1707
- // by FileKeyStore (flair#1026). A keystore blob is unparseable AS A SEED
1708
- // while being a LIVE federation key — classifying it "invalid" moved a key
1709
- // that was in use. An unidentified file is reported for a human and left
1710
- // exactly where it is.
1711
- return {
1712
- class: "unidentified",
1713
- reason: "not a parseable Ed25519 private key seed — may be a keystore blob or another format; " +
1714
- "left in place, inspect it before removing anything (flair#1026)",
1715
- };
2024
+ // NOT "invalid", and therefore NOT prunable — see UNIDENTIFIED_SEED_REASON.
2025
+ return { class: "unidentified", reason: UNIDENTIFIED_SEED_REASON };
1716
2026
  }
1717
2027
  if (registration?.state === "registered") {
1718
2028
  return { class: "keep", reason: `agent '${agentId}' is registered on ${baseUrl} — never pruned` };
@@ -1728,40 +2038,93 @@ export function classifyKeyFile(agentId, seedValid, registration, baseUrl) {
1728
2038
  reason: `agent '${agentId}' is not registered on ${baseUrl}${registration?.detail ? ` (${registration.detail})` : ""}`,
1729
2039
  };
1730
2040
  }
1731
- // ── Node-scoped federation keys vs agent signing keys (flair#1193) ─────────
1732
- //
1733
- // `~/.flair/keys/` is a namespace shared by two writers with two file shapes:
1734
- //
1735
- // • agent Ed25519 signing keys — a 32-byte raw seed at `<name>.key`, ALWAYS
1736
- // written together with a sibling `<name>.pub` (see the keypair write in
1737
- // src/cli.ts: the seed and the public key are emitted in the same block).
1738
- // • node-scoped federation keys — `flair_<hex8>.key`, an AES-256-GCM
1739
- // keystore blob written by FileKeyStore during Fabric provisioning
1740
- // (flair#1026). The id is minted as `flair_${randomBytes(4).toString("hex")}`
1741
- // in resources/Federation.ts, and NO `.pub` is ever written for it.
1742
- //
1743
- // Nothing used to tell them apart, so doctor tried to Ed25519-parse the node
1744
- // blob — a "DECODER routines::unsupported" warning that reads as agent-auth
1745
- // breakage when agent auth is fine — and `doctor --fix` could infer the node
1746
- // id as the sole "agent" and wire it as a connector identity, authenticating
1747
- // as a phantom, unregistered node whose key cannot sign (flair#1193).
1748
- //
1749
- // The guard is STRUCTURAL, not a parse attempt: a node id matches
1750
- // `flair_<hex8>` AND has no sibling `.pub`. We deliberately do NOT classify by
1751
- // parsing the file and treating a decode failure as "must be a node key" —
1752
- // that is the exact fails-open move flair#1026 warns against (a genuinely
1753
- // corrupt agent key would be misread as a node key and silently skipped).
1754
- // A real agent always has a `.pub`; a node key never does, so `.pub` presence
1755
- // is the primary, falsifiable signal and classification never depends on the
1756
- // parse-failure of the thing being classified.
1757
- /** The shape a Fabric node id always has: `flair_` + 8 lowercase hex chars. */
2041
+ /** Report node-shaped seeds using rows bound by HTTP/ops Instance id; never authorize removal. */
2042
+ export function classifyNodeKeySeed(id, instanceIds, baseUrl, agentIds = null, unreadableReason) {
2043
+ if (instanceIds === null || agentIds === null) {
2044
+ return {
2045
+ class: "unidentified",
2046
+ reason: `${instanceIds === null ? "Instance" : "Agent"} reference check unavailable${unreadableReason ? ` (${unreadableReason})` : ""}; node-shaped seed left in place`,
2047
+ };
2048
+ }
2049
+ if (agentIds.includes(id)) {
2050
+ return { class: "unidentified", reason: `id '${id}' is registered in the Agent table on ${baseUrl} (HTTP/ops Instance id matched); left in place` };
2051
+ }
2052
+ if (instanceIds.includes(id)) {
2053
+ return { class: "keep", reason: `id '${id}' is named by the Instance row on ${baseUrl} (HTTP/ops Instance id matched); kept` };
2054
+ }
2055
+ return {
2056
+ class: "orphan-candidate",
2057
+ reason: `id '${id}' is absent from the Instance and Agent tables on ${baseUrl} (HTTP/ops Instance id matched); ownership cannot be proven; not removed (see #2200)`,
2058
+ };
2059
+ }
2060
+ /** Sidecars are unauthenticated metadata; node-shaped candidates stay unidentified. */
2061
+ export function classifyOwnedNodeSeed(id, instanceIds, baseUrl, agentIds, proof, unreadableReason) {
2062
+ const decision = classifyNodeKeySeed(id, instanceIds, baseUrl, agentIds, unreadableReason);
2063
+ if (decision.class !== "orphan-candidate")
2064
+ return decision;
2065
+ const { owner, keyPath, ownerPath, targetDataDir } = proof;
2066
+ const base = `id '${id}' is absent from the Instance and Agent tables on ${baseUrl} (HTTP/ops Instance id matched)`;
2067
+ const leftInPlace = `${keyPath} is left in place`;
2068
+ if (owner.state === "absent") {
2069
+ return {
2070
+ class: "unidentified",
2071
+ reason: `${base}; no owner record at ${ownerPath} — ownership cannot be proven; ${leftInPlace}. `
2072
+ + `Remedy: if no instance uses it, remove the seed manually.`,
2073
+ };
2074
+ }
2075
+ if (owner.state === "unreadable") {
2076
+ return {
2077
+ class: "unidentified",
2078
+ reason: `${base}; the owner record at ${ownerPath} could not be read (${owner.reason}) — ownership cannot be proven; ${leftInPlace}. `
2079
+ + `Remedy: check all instances before manual cleanup.`,
2080
+ };
2081
+ }
2082
+ if (owner.state === "malformed") {
2083
+ return {
2084
+ class: "unidentified",
2085
+ reason: `${base}; the owner record at ${ownerPath} is malformed (${owner.reason}) — ownership cannot be proven; ${leftInPlace}. `
2086
+ + `Remedy: check all instances before manual cleanup.`,
2087
+ };
2088
+ }
2089
+ if (owner.instanceId !== id) {
2090
+ return {
2091
+ class: "unidentified",
2092
+ reason: `${base}; the owner record at ${ownerPath} names instance '${owner.instanceId}', not the seed '${id}' — the record does not belong to this seed; ${leftInPlace}.`,
2093
+ };
2094
+ }
2095
+ if (targetDataDir === null) {
2096
+ return {
2097
+ class: "unidentified",
2098
+ reason: `${base}; the owner record at ${ownerPath} names instance '${owner.instanceId}' (data directory ${owner.dataDir}), but the targeted instance's data directory could not be established, so ownership cannot be proven; ${leftInPlace}. `
2099
+ + `Remedy: check all instances before manual cleanup.`,
2100
+ };
2101
+ }
2102
+ if (owner.dataDir !== targetDataDir) {
2103
+ return {
2104
+ class: "unidentified",
2105
+ reason: `${base}; the owner record at ${ownerPath} names instance '${owner.instanceId}' (data directory ${owner.dataDir}), not the targeted instance (data directory ${targetDataDir}); ${leftInPlace}.`,
2106
+ };
2107
+ }
2108
+ return {
2109
+ class: "unidentified",
2110
+ reason: `${base}; the owner record at ${ownerPath} is unauthenticated; file type and ownership cannot be proven; ${leftInPlace}.`,
2111
+ };
2112
+ }
2113
+ export function orphanInstanceSeedAdvisory(input) {
2114
+ const { nodeKeyIds, instanceIds, agentIds, keysDir, baseUrl } = input;
2115
+ if (nodeKeyIds.length === 0)
2116
+ return null;
2117
+ if (instanceIds === null || agentIds == null) {
2118
+ return `${instanceIds === null ? "Instance" : "Agent"} reference check unavailable (${input.unreadableReason ?? "read unavailable"}); node-shaped seeds in ${keysDir} remain unidentified`;
2119
+ }
2120
+ const candidates = nodeKeyIds.filter((id) => classifyNodeKeySeed(id, instanceIds, baseUrl, agentIds).class === "orphan-candidate").length;
2121
+ if (candidates === 0)
2122
+ return null;
2123
+ return `${candidates} orphan candidate(s) in ${keysDir}, absent from the Instance and Agent tables on ${baseUrl} (HTTP/ops Instance id matched); ownership cannot be proven; not removed (see #2200)`;
2124
+ }
2125
+ /** Node-shaped file ids. */
1758
2126
  const NODE_KEY_ID_RE = /^flair_[0-9a-f]{8}$/;
1759
- /**
1760
- * True iff `id` names a node-scoped federation key rather than an agent
1761
- * signing key: it is shaped like a node id AND has no sibling `<id>.pub` in
1762
- * `keysDir`. Both conditions are required — an agent that happened to be named
1763
- * `flair_deadbeef` would still have a `.pub`, so it is never misclassified.
1764
- */
2127
+ /** Match node-shaped ids without a sibling .pub; file type is unproven. */
1765
2128
  export function isNodeKeyId(id, keysDir) {
1766
2129
  if (!NODE_KEY_ID_RE.test(id))
1767
2130
  return false;
@@ -1803,3 +2166,77 @@ export function resolveFixAgentId(args) {
1803
2166
  return undefined;
1804
2167
  return candidate;
1805
2168
  }
2169
+ /**
2170
+ * Report a stored Agent id that is outside the shared agent-ID rule
2171
+ * (flair#2359). `rows` is the Agent roster read from the instance. Returns null
2172
+ * when the roster's ids conform. PURE — it reports; nothing is rewritten.
2173
+ */
2174
+ export function describeAgentIdRuleFinding(rows) {
2175
+ const invalidIds = (Array.isArray(rows) ? rows : [])
2176
+ .filter((row) => row == null || !isValidAgentId(row.id))
2177
+ .map((row) => String(row?.id))
2178
+ .sort();
2179
+ if (invalidIds.length === 0)
2180
+ return null;
2181
+ return {
2182
+ invalidIds,
2183
+ message: `${invalidIds.length} stored agent id(s) are outside the agent-ID rule (${AGENT_ID_RULE}): ` +
2184
+ invalidIds.join(", "),
2185
+ fixHint: "after any needed data migration and registration with `flair agent add <new-id>`, " +
2186
+ "remove the old row with `flair agent remove <id>`, or remove it alone if stale; " +
2187
+ "`flair agent remove` also deletes the agent's Memory and Soul data, but not the key files of an id outside the rule — clean those up manually",
2188
+ };
2189
+ }
2190
+ /**
2191
+ * Report every stored Agent row with no home (flair#2433). `rows` is the Agent
2192
+ * roster read from the instance (each row's full record).
2193
+ *
2194
+ * The split is the remedy's contract: a row that carries sync provenance
2195
+ * (`_syncedFrom`/`_originatorInstanceId`, resources/Federation.ts's receiver
2196
+ * stamps) arrived through federation and is LISTED ONLY — stamping it would
2197
+ * forge its origin. `flair agent stamp-home --apply` stamps the local id on a
2198
+ * home-less row that carries no federation-sync provenance.
2199
+ *
2200
+ * PURE — it reports; nothing is rewritten.
2201
+ */
2202
+ export function describeAgentHomeFinding(rows, identity) {
2203
+ const plan = planAgentHomeStamps(rows, identity.kind === "one" ? identity.id : null);
2204
+ if (plan.homeLess.length === 0)
2205
+ return null;
2206
+ const base = {
2207
+ homeLessIds: plan.homeLess,
2208
+ stampableIds: plan.stampable,
2209
+ syncIds: plan.sync,
2210
+ };
2211
+ const listed = `${plan.homeLess.length} stored agent row(s) have no home instance (originatorInstanceId): ${plan.homeLess.join(", ")}`;
2212
+ if (identity.kind === "one") {
2213
+ return {
2214
+ ...base,
2215
+ severity: "advisory",
2216
+ isIssue: false,
2217
+ message: `${listed}; ${plan.stampable.length} can be stamped with this instance's id (${identity.id})` +
2218
+ (plan.sync.length > 0 ? `, ${plan.sync.length} arrived through federation and are listed only` : ""),
2219
+ fixHint: AGENT_HOME_STAMP_REMEDY,
2220
+ };
2221
+ }
2222
+ if (identity.kind === "multiple") {
2223
+ return {
2224
+ ...base,
2225
+ severity: "info",
2226
+ isIssue: false,
2227
+ message: `${listed}; this instance has ${identity.count} Instance rows, so no single canonical id; ` +
2228
+ "homes stay unset (the local-origin state) until it has one",
2229
+ fixHint: `keep one Instance row and delete the rest with: ${INSTANCE_ROW_PRUNE_REMEDY}`,
2230
+ };
2231
+ }
2232
+ return {
2233
+ ...base,
2234
+ severity: "info",
2235
+ isIssue: false,
2236
+ message: `${listed}; ` +
2237
+ (identity.kind === "none"
2238
+ ? "this instance has no Instance row yet, so homes stay unset (the local-origin state) until it has an identity"
2239
+ : "the Instance row could not be read, so no id was resolved"),
2240
+ fixHint: null,
2241
+ };
2242
+ }