@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
@@ -1,44 +1,17 @@
1
- /**
2
- * init-occupied-listener.ts — flair#1749
3
- *
4
- * `flair init` used to treat "something already answered /health" as "our
5
- * Harper is up", skip its own start, and then explain an operations-API 401
6
- * as a wrong `--admin-pass`. Two claims that message must not make:
7
- *
8
- * - A different data directory does not prove the admin passwords differ.
9
- * - The process holding the HTTP port is not necessarily the one that
10
- * rejected an operations-port request. Those ports are resolved separately
11
- * and can have different owners.
12
- *
13
- * Init can name a different data directory only when that one read could
14
- * read one. An unreadable ROOTPATH is not proof of a foreign instance.
15
- * On macOS the directory is unavailable, so init does not refuse before
16
- * auth from a parsed ROOTPATH.
17
- *
18
- * That pre-auth observation is a single read. It is not the operations-port
19
- * 401 check. A 401 names a pid only when the read before the insert and the
20
- * read after the 401 are the same sole PID. Several holders, or a holder
21
- * that changed during the request, stay "a Harper instance this init did
22
- * not start".
23
- *
24
- * These messages do not offer `flair stop`. `flair stop` cannot be promised
25
- * to act on this listener. The remedy is `kill <pid>` when one process is
26
- * named. Init never signals a process it did not start.
27
- */
28
- import { canonicalLexicalPath } from "./daemon-liveness.js";
29
1
  /**
30
2
  * One observation of who is listening. An unreadable ROOTPATH is omitted,
31
3
  * so it cannot become a pre-auth refusal. Does not decide `flair stop`.
32
4
  */
33
5
  export function listenerFromLookup(port, lookup) {
34
- const pids = lookup.pids(port) ?? [];
6
+ const read = lookup.pids(port);
7
+ const pids = read ?? [];
35
8
  const dataDirs = [];
36
9
  for (const pid of pids) {
37
- const read = lookup.rootPath(pid);
38
- if (read.environReadable && read.rootPath && !dataDirs.includes(read.rootPath))
39
- dataDirs.push(read.rootPath);
10
+ const root = lookup.rootPath(pid);
11
+ if (root.environReadable && root.rootPath && !dataDirs.includes(root.rootPath))
12
+ dataDirs.push(root.rootPath);
40
13
  }
41
- return { port, pids, dataDirs };
14
+ return { port, pids, dataDirs, pidsKnown: read !== null };
42
15
  }
43
16
  /**
44
17
  * The process a 401 can be tied to.
@@ -53,97 +26,27 @@ export function stableAnsweredHolder(before, after) {
53
26
  after.pids.length === 1 &&
54
27
  before.pids[0] === after.pids[0];
55
28
  if (!sameSingle) {
56
- return { port: after.port, pids: [], dataDirs: [] };
29
+ return { port: after.port, pids: [], dataDirs: [], pidsKnown: after.pidsKnown };
57
30
  }
58
31
  return {
59
32
  port: after.port,
60
33
  pids: [after.pids[0]],
61
34
  dataDirs: after.dataDirs,
35
+ pidsKnown: after.pidsKnown,
62
36
  };
63
37
  }
64
- const UNATTRIBUTED = "a Harper instance this init did not start";
65
- /**
66
- * Name the listener for an operator. A pid is included only when exactly one
67
- * was read — several holders are not a kill list. Pid and data directory
68
- * when both were read; whichever was read, plus the fallback phrase, when
69
- * only one was; the fallback phrase alone when neither was.
70
- */
71
- export function describeOccupiedListener(listener) {
72
- const pid = listener.pids.length === 1 ? `pid ${listener.pids[0]}` : null;
73
- const dir = listener.dataDirs.length > 0 ? `data dir ${listener.dataDirs.join(", ")}` : null;
74
- if (pid && dir)
75
- return `${pid}, ${dir}`;
76
- if (pid || dir)
77
- return `${pid ?? dir} (${UNATTRIBUTED})`;
78
- return UNATTRIBUTED;
79
- }
80
- /** Sentence carried wherever a different directory might be misread as a password fact. */
81
- export const DIFFERENT_DIR_DOES_NOT_PROVE_PASSWORD = "A different data directory does not prove the admin passwords differ.";
82
- /** Sentence carried on an operations-port rejection. The HTTP holder is a different fact. */
83
- export const HTTP_HOLDER_DID_NOT_NECESSARILY_REJECT = "The process holding the HTTP port is not necessarily the one that rejected the operations request.";
84
- function foreignDataDirs(expectedDataDir, dataDirs) {
85
- const expected = canonicalLexicalPath(expectedDataDir);
86
- return dataDirs.filter((dir) => canonicalLexicalPath(dir) !== expected);
87
- }
88
- /**
89
- * Printed from the single pre-auth read of the HTTP listener, when that
90
- * read included a ROOTPATH other than this init's data directory. Init
91
- * exits on it — before the authenticated health request and before the
92
- * operations insert. This is not the before-and-after 401 attribution.
93
- * A different directory is not proof the passwords differ. Returns null
94
- * when the directory matches or could not be read: an unreadable lookup
95
- * is not a foreign instance.
96
- */
97
- export function staleHarperBeforeAuthNotice(expectedDataDir, listener) {
98
- const foreign = foreignDataDirs(expectedDataDir, listener.dataDirs);
99
- if (foreign.length === 0)
100
- return null;
101
- const who = describeOccupiedListener({ pids: listener.pids, dataDirs: foreign });
102
- const lines = [
103
- `Harper on port ${listener.port} is ${who}, not this init's data dir ${expectedDataDir}.`,
104
- ` ${DIFFERENT_DIR_DOES_NOT_PROVE_PASSWORD}`,
105
- ` This init will not send its admin password to that process.`,
106
- ` This init will not stop a process it did not start.`,
107
- ];
108
- appendRemedy(lines, listener);
109
- return lines.join("\n");
110
- }
111
- /**
112
- * Appended when init refuses before start because the port is already
113
- * answering and this data directory has no persisted admin user. Names only
114
- * what was read. Does not claim the passwords differ.
115
- */
116
- export function foreignOccupiedListenerDetail(listener, expectedDataDir) {
117
- const lines = [
118
- `The process listening on port ${listener.port} is ${describeOccupiedListener(listener)}.`,
119
- `This init will not send its admin password to a process it did not start.`,
120
- ];
121
- if (expectedDataDir && foreignDataDirs(expectedDataDir, listener.dataDirs).length > 0) {
122
- lines.push(DIFFERENT_DIR_DOES_NOT_PROVE_PASSWORD);
123
- }
124
- lines.push(`This init will not stop a process it did not start.`);
38
+ export function foreignOccupiedListenerDetail(listener) {
39
+ const lines = [];
125
40
  appendRemedy(lines, listener);
126
41
  return lines.join("\n");
127
42
  }
128
- /**
129
- * The operations-API 401 after init skipped its own start. Unlike the
130
- * pre-auth notice, which is one read, `listener` here is the before-and-after
131
- * attribution for the operations port: the same sole PID on both sides,
132
- * or the unattributed fallback. Do not pass the HTTP port's pids through.
133
- * The rejection is not proof the passwords differ, and it is not proof the
134
- * HTTP listener caused it. The message does not offer `flair stop`.
135
- */
136
43
  export function occupiedListenerAuthFailure(input) {
137
- const who = describeOccupiedListener(input.listener);
44
+ const pid = input.listener.pids.length === 1 ? `, pid ${input.listener.pids[0]}` : "";
138
45
  const lines = [
139
46
  `${input.lead}${input.bodyText}`,
140
- ` The operations port ${input.listener.port} rejected this init's admin credentials.`,
141
- ` ${HTTP_HOLDER_DID_NOT_NECESSARILY_REJECT}`,
142
- ` ${DIFFERENT_DIR_DOES_NOT_PROVE_PASSWORD}`,
143
- ` The process holding the operations port is ${who}.`,
144
- ` This init will not stop a process it did not start.`,
47
+ ` Port ${input.listener.port}${pid}: admin authentication failed.`,
145
48
  ];
146
- appendRemedy(lines, input.listener);
49
+ lines.push("Remedy: check the admin password for this data directory, then rerun init.");
147
50
  return lines.join("\n");
148
51
  }
149
52
  /**
@@ -151,6 +54,7 @@ export function occupiedListenerAuthFailure(input) {
151
54
  * promised to act on this listener.
152
55
  */
153
56
  function appendRemedy(lines, listener) {
57
+ lines.push("Remedy: free the port or choose --port and --ops-port, then rerun init.");
154
58
  if (listener.pids.length === 1)
155
59
  lines.push(` kill ${listener.pids[0]}`);
156
60
  for (const dir of listener.dataDirs) {
@@ -158,7 +62,7 @@ function appendRemedy(lines, listener) {
158
62
  }
159
63
  }
160
64
  /** Quote a path that would split on the shell. Numbers and plain paths stay bare. */
161
- function commandArg(value) {
65
+ export function commandArg(value) {
162
66
  if (/^[A-Za-z0-9_./:@+-]+$/.test(value))
163
67
  return value;
164
68
  return `'${value.replace(/'/g, `'\\''`)}'`;
@@ -0,0 +1,73 @@
1
+ import { readFileSync, readdirSync, readlinkSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { canonicalLexicalPath } from "./daemon-liveness.js";
4
+ import { readInitListenerRootPath } from "./init-listener-environ.js";
5
+ export function initChildOwnsProcPort(pid, port, procRoot = "/proc") {
6
+ try {
7
+ const inodes = new Set();
8
+ for (const table of ["tcp", "tcp6"]) {
9
+ const rows = readFileSync(join(procRoot, "net", table), "utf8").trim().split("\n").slice(1);
10
+ for (const row of rows) {
11
+ const fields = row.trim().split(/\s+/);
12
+ if (fields[3] !== "0A" || parseInt(fields[1]?.split(":")[1] ?? "", 16) !== port)
13
+ continue;
14
+ if (!fields[9] || !/^[1-9]\d*$/.test(fields[9]))
15
+ return false;
16
+ inodes.add(fields[9]);
17
+ }
18
+ }
19
+ if (inodes.size === 0)
20
+ return false;
21
+ const owned = new Set();
22
+ const fdDir = join(procRoot, String(pid), "fd");
23
+ for (const fd of readdirSync(fdDir)) {
24
+ try {
25
+ const match = /^socket:\[(\d+)\]$/.exec(readlinkSync(join(fdDir, fd)));
26
+ if (match)
27
+ owned.add(match[1]);
28
+ }
29
+ catch { }
30
+ }
31
+ return [...inodes].every(inode => owned.has(inode));
32
+ }
33
+ catch {
34
+ return false;
35
+ }
36
+ }
37
+ export function trackInitChild(child, options = {}) {
38
+ const pid = child.pid;
39
+ const processGroup = process.platform === "win32" ? undefined : pid;
40
+ let exited = false;
41
+ child.once("exit", () => { exited = true; });
42
+ child.once("error", () => { exited = true; });
43
+ return {
44
+ pid,
45
+ processGroup,
46
+ attributes(listener, dataDir, freePorts) {
47
+ if (!pid || exited || child.exitCode != null || child.signalCode != null || !freePorts.has(listener.port))
48
+ return false;
49
+ if (listener.pids.length > 1)
50
+ return false;
51
+ if (listener.pids.some(holder => holder !== pid))
52
+ return false;
53
+ if ((options.platform ?? process.platform) === "linux") {
54
+ if (!initChildOwnsProcPort(pid, listener.port, options.procRoot))
55
+ return false;
56
+ }
57
+ else if (!listener.pidsKnown || listener.pids.length !== 1)
58
+ return false;
59
+ if (listener.dataDirs.some(dir => canonicalLexicalPath(dir) !== canonicalLexicalPath(dataDir)))
60
+ return false;
61
+ try {
62
+ process.kill(pid, 0);
63
+ if (processGroup)
64
+ process.kill(-processGroup, 0);
65
+ }
66
+ catch {
67
+ return false;
68
+ }
69
+ const root = readInitListenerRootPath(pid);
70
+ return !root.environReadable || (root.rootPath !== null && canonicalLexicalPath(root.rootPath) === canonicalLexicalPath(dataDir));
71
+ },
72
+ };
73
+ }
@@ -0,0 +1,33 @@
1
+ import { createConnection } from "node:net";
2
+ export async function localPortState(port, bindHost, connect = createConnection) {
3
+ const host = ["0.0.0.0", "::", "0:0:0:0:0:0:0:0"].includes(bindHost) ? "127.0.0.1" : bindHost;
4
+ const configured = await tcpPortState(port, host, connect);
5
+ if (host === "127.0.0.1")
6
+ return configured;
7
+ const loopback = await tcpPortState(port, "127.0.0.1", connect);
8
+ if (configured === "listening" || loopback === "listening")
9
+ return "listening";
10
+ if (configured === "unknown" || loopback === "unknown")
11
+ return "unknown";
12
+ return "free";
13
+ }
14
+ function tcpPortState(port, host, connect) {
15
+ return new Promise((resolveState) => {
16
+ let socket;
17
+ try {
18
+ socket = connect({ host, port });
19
+ }
20
+ catch {
21
+ resolveState("unknown");
22
+ return;
23
+ }
24
+ const finish = (state) => {
25
+ socket.destroy();
26
+ resolveState(state);
27
+ };
28
+ socket.setTimeout(1000);
29
+ socket.once("connect", () => finish("listening"));
30
+ socket.once("error", (error) => finish(error.code === "ECONNREFUSED" ? "free" : "unknown"));
31
+ socket.once("timeout", () => finish("unknown"));
32
+ });
33
+ }
@@ -503,6 +503,26 @@ export async function probeInstanceIdentity(endpoint) {
503
503
  const roleNames = await readRoleNames(endpoint);
504
504
  return { rows, roleNames };
505
505
  }
506
+ export async function probeInstanceIds(endpoint) {
507
+ try {
508
+ const rows = await readInstanceRows(endpoint);
509
+ const ids = rows.map((r) => r.id);
510
+ try {
511
+ const parsed = await opsPost(endpoint, { operation: "sql", sql: "SELECT id FROM flair.Agent" }, "Agent read");
512
+ const agents = Array.isArray(parsed) ? parsed : Array.isArray(parsed?.results) ? parsed.results : null;
513
+ if (agents === null || agents.some((row) => typeof row?.id !== "string" || !row.id.trim())) {
514
+ throw new Error("Agent read returned no usable row list");
515
+ }
516
+ return { state: "read", ids, agentIds: agents.map((row) => row.id) };
517
+ }
518
+ catch (err) {
519
+ return { state: "read", ids, agentIds: null, agentReadReason: err instanceof Error ? err.message : String(err) };
520
+ }
521
+ }
522
+ catch (err) {
523
+ return { state: "unreadable", reason: err instanceof Error ? err.message : String(err) };
524
+ }
525
+ }
506
526
  /**
507
527
  * What a prune prints when it is about to delete rows (flair#1883 round 3).
508
528
  *
@@ -332,9 +332,10 @@ export function readLaunchctlJobState(label, list) {
332
332
  * PID is no evidence, so it is discarded and the port listener answers instead.
333
333
  */
334
334
  export function pickInstancePid(input) {
335
- const { pidFilePid, isAlive, listeningPids } = input;
336
- if (pidFilePid !== null && isAlive(pidFilePid))
335
+ const { pidFilePid, isAlive, listeningPids, isPidFileEvidence } = input;
336
+ if (pidFilePid !== null && isAlive(pidFilePid) && (isPidFileEvidence === undefined || isPidFileEvidence(pidFilePid))) {
337
337
  return pidFilePid;
338
+ }
338
339
  return listeningPids.length > 0 ? listeningPids[0] : null;
339
340
  }
340
341
  /** True when the instance is running outside the service manager that is registered to own it. */
@@ -486,6 +487,30 @@ export function renderDetachedWarning(m, headline) {
486
487
  lines.push(` Fix: ${m.remedy.join(" && ")}`);
487
488
  return lines;
488
489
  }
490
+ /**
491
+ * The lines for an unconfirmed managed start (flair#2422). Names what was
492
+ * observed: the reachability wait before the probe passed, and the probe's
493
+ * result by name. "Flair is running" is printed for `flair` — the result whose
494
+ * probe saw Flair shape — and the other results say what they saw instead.
495
+ * Kept here so the wording is assertable without a launchd host.
496
+ */
497
+ export function renderManagedStartUnconfirmed(input) {
498
+ const { port, confirmation, detail, moved, launchdDetail, remedy } = input;
499
+ const headline = {
500
+ flair: `Flair is running on port ${port}, but it is NOT verified as launchd-managed`,
501
+ foreign: `The initial reachability wait on port ${port} passed, but the confirmation probe got a response that was not a Flair health answer (non-2xx or not Flair-shaped), so Flair is NOT verified as launchd-managed`,
502
+ refused: `The initial reachability wait on port ${port} passed, but the confirmation probe's connection was refused (nothing was listening), so Flair is NOT verified as launchd-managed`,
503
+ unreachable: `The initial reachability wait on port ${port} passed, but the confirmation probe could not reach the port (timeout or network error), so Flair is NOT verified as launchd-managed`,
504
+ };
505
+ const lines = [`⚠️ ${headline[confirmation]}`, ` ${detail}`];
506
+ if (moved)
507
+ lines.push(` ${moved}`);
508
+ if (launchdDetail)
509
+ lines.push(` ${launchdDetail}`);
510
+ if (remedy?.length)
511
+ lines.push(` Fix: ${remedy.join(" && ")}`);
512
+ return lines;
513
+ }
489
514
  // renderVerifiedSummary used to live here and qualify ✅ from version +
490
515
  // LaunchdManagement alone (flair#1022). That signature was the ceiling on
491
516
  // what it could notice — a blacklist of one known-unhealthy form. The
@@ -0,0 +1,268 @@
1
+ /**
2
+ * listener-table.ts — the processes the OS lists as LISTENING on a TCP port
3
+ * (flair#2526). The answer comes from the kernel's socket table, never from
4
+ * anything a listener says about itself and never from a PID file.
5
+ *
6
+ * Per platform:
7
+ * - Linux: the LISTEN rows (state `0A`) of `/proc/net/tcp` and
8
+ * `/proc/net/tcp6` whose local port is `port` name socket inodes; the
9
+ * processes holding those inodes are the ones whose `/proc/<pid>/fd/*` link
10
+ * reads `socket:[<inode>]`. No external tool.
11
+ * - every other platform (macOS included): `lsof -nP -iTCP:<port>
12
+ * -sTCP:LISTEN -Fp`, whose `p<pid>` lines name the processes.
13
+ *
14
+ * Its limit: both read only what this CLI can see. Linux `/proc/net` lists
15
+ * this process's network namespace, and `/proc/<pid>/fd` of a process this
16
+ * user may not inspect is unreadable; macOS lsof lists only processes this
17
+ * user may inspect. A listener outside that view (in another network
18
+ * namespace or container, or owned by a user this CLI may not inspect) is
19
+ * absent from the table or has no owner the table can name, and a port
20
+ * reached through a forward is held by the forwarder (docker-proxy, ssh -L).
21
+ * Callers refuse a listener they cannot see, and a forwarder whose observed
22
+ * command line does not match Harper's. A CLI inside the same container, or
23
+ * allowed to inspect that user's processes, sees the listener.
24
+ */
25
+ import { execFileSync } from "node:child_process";
26
+ import { readdirSync, readFileSync, readlinkSync } from "node:fs";
27
+ import { parseProcStatStartTime } from "./daemon-liveness.js";
28
+ /** The lsof command line the non-Linux reader runs for `port`. */
29
+ export function lsofListenerArgs(port) {
30
+ return ["-nP", `-iTCP:${port}`, "-sTCP:LISTEN", "-Fp"];
31
+ }
32
+ /** What to do when the table does not show this CLI the listener, or shows a forwarder. */
33
+ export const LISTENER_VISIBILITY_REMEDY = "Run this command where it can see Harper's own listener: on the host (or inside the container) where Harper "
34
+ + "runs, as a user allowed to inspect Harper's process. A port held by a forwarder whose command line does not "
35
+ + "match Harper's (such as docker-proxy or ssh -L) is refused.";
36
+ /**
37
+ * Parse `lsof -Fp` output into the distinct listening pids, sorted. Only `p`
38
+ * lines carry a pid; lsof's other field lines (`f<fd>` and the like) are
39
+ * ignored. A `p` line that is not a positive integer makes the whole output
40
+ * unusable (null): the caller refuses rather than guessing.
41
+ */
42
+ export function parseLsofListenerPids(output) {
43
+ const pids = new Set();
44
+ for (const raw of output.split("\n")) {
45
+ const line = raw.trim();
46
+ if (!line.startsWith("p"))
47
+ continue;
48
+ const pid = Number(line.slice(1));
49
+ if (!/^p[0-9]+$/.test(line) || !Number.isSafeInteger(pid) || pid <= 0)
50
+ return null;
51
+ pids.add(pid);
52
+ }
53
+ return [...pids].sort((a, b) => a - b);
54
+ }
55
+ /**
56
+ * Parse one `/proc/net/tcp` or `/proc/net/tcp6` table into the socket inodes
57
+ * LISTENING (state `0A`) on `port`. The local address is `<hex addr>:<hex
58
+ * port>`; inode 0 (no owning socket) is skipped. A data row with fewer than 10
59
+ * columns makes the table unusable (null).
60
+ */
61
+ export function parseProcNetTcpListenInodes(table, port) {
62
+ const inodes = [];
63
+ const rows = table.split("\n").slice(1);
64
+ for (const row of rows) {
65
+ const cols = row.trim().split(/\s+/);
66
+ if (cols.length === 1 && cols[0] === "")
67
+ continue;
68
+ if (cols.length < 10)
69
+ return null;
70
+ const local = cols[1];
71
+ const colon = local.lastIndexOf(":");
72
+ if (colon < 0)
73
+ return null;
74
+ const localPort = Number.parseInt(local.slice(colon + 1), 16);
75
+ if (cols[3] !== "0A" || localPort !== port)
76
+ continue;
77
+ if (!/^[0-9]+$/.test(cols[9]))
78
+ return null;
79
+ if (cols[9] !== "0")
80
+ inodes.push(cols[9]);
81
+ }
82
+ return inodes;
83
+ }
84
+ const DEFAULT_IO = {
85
+ platform: process.platform,
86
+ runLsof: (args) => execFileSync("lsof", args, { encoding: "utf-8", timeout: 5_000, killSignal: "SIGKILL", stdio: ["ignore", "pipe", "ignore"] }),
87
+ runPs: (args) => execFileSync("ps", args, {
88
+ encoding: "utf-8",
89
+ timeout: 5_000,
90
+ killSignal: "SIGKILL",
91
+ stdio: ["ignore", "pipe", "ignore"],
92
+ env: { ...process.env, LC_ALL: "C" },
93
+ }),
94
+ readFile: (path) => readFileSync(path, "utf-8"),
95
+ readDir: (path) => readdirSync(path),
96
+ readLink: (path) => readlinkSync(path),
97
+ };
98
+ /** The processes the OS lists as LISTENING on TCP `port` (see the module comment). */
99
+ export function readTcpListenerPids(port, io = {}) {
100
+ const full = { ...DEFAULT_IO, ...io };
101
+ return full.platform === "linux" ? readFromProc(port, full) : readFromLsof(port, full);
102
+ }
103
+ function readFromLsof(port, io) {
104
+ const command = `lsof ${lsofListenerArgs(port).join(" ")}`;
105
+ let output;
106
+ try {
107
+ output = io.runLsof(lsofListenerArgs(port));
108
+ }
109
+ catch (err) {
110
+ if (err?.code === "ENOENT") {
111
+ return {
112
+ kind: "unavailable",
113
+ reason: `lsof is not installed or not on PATH, and this check reads the listener table with \`${command}\``,
114
+ remedy: "Install lsof or put it on PATH (macOS ships it as /usr/sbin/lsof), then re-run this command on the host where Harper runs.",
115
+ };
116
+ }
117
+ // lsof exits 1 with no output when no socket matches.
118
+ if (err?.status === 1 && String(err?.stdout ?? "").trim() === "")
119
+ return { kind: "listeners", pids: [] };
120
+ const how = err?.signal ? `was stopped by ${err.signal}` : `exited ${err?.status ?? err?.code ?? "abnormally"}`;
121
+ return {
122
+ kind: "unavailable",
123
+ reason: `\`${command}\` ${how}`,
124
+ remedy: `Run \`${command}\` yourself to see why it fails, fix that, and re-run this command.`,
125
+ };
126
+ }
127
+ const pids = parseLsofListenerPids(output);
128
+ if (pids === null) {
129
+ return { kind: "unavailable", reason: `\`${command}\` printed a pid line that is not a process id`, remedy: `Run \`${command}\` yourself and check its output.` };
130
+ }
131
+ return { kind: "listeners", pids };
132
+ }
133
+ function readFromProc(port, io) {
134
+ const inodes = new Set();
135
+ for (const table of ["/proc/net/tcp", "/proc/net/tcp6"]) {
136
+ let text;
137
+ try {
138
+ text = io.readFile(table);
139
+ }
140
+ catch (err) {
141
+ // A host with IPv6 disabled has no tcp6 table; the IPv4 table is required.
142
+ if (table === "/proc/net/tcp6" && err?.code === "ENOENT")
143
+ continue;
144
+ return {
145
+ kind: "unavailable",
146
+ reason: `this check reads the listener table from ${table}, which cannot be read (${err?.code ?? err?.message})`,
147
+ remedy: "Run this command on a Linux host with /proc mounted, as the user that runs Harper.",
148
+ };
149
+ }
150
+ const found = parseProcNetTcpListenInodes(text, port);
151
+ if (found === null) {
152
+ return { kind: "unavailable", reason: `${table} has a row this check cannot parse`, remedy: `Check ${table}; this check reads its LISTEN rows.` };
153
+ }
154
+ for (const inode of found)
155
+ inodes.add(inode);
156
+ }
157
+ if (inodes.size === 0)
158
+ return { kind: "listeners", pids: [] };
159
+ const owners = new Map();
160
+ let entries;
161
+ try {
162
+ entries = io.readDir("/proc");
163
+ }
164
+ catch (err) {
165
+ return {
166
+ kind: "unavailable",
167
+ reason: `this check finds socket owners under /proc, which cannot be listed (${err?.code ?? err?.message})`,
168
+ remedy: "Run this command on a Linux host with /proc mounted, as the user that runs Harper.",
169
+ };
170
+ }
171
+ for (const entry of entries) {
172
+ if (!/^[0-9]+$/.test(entry))
173
+ continue;
174
+ let fds;
175
+ try {
176
+ fds = io.readDir(`/proc/${entry}/fd`);
177
+ }
178
+ catch {
179
+ continue; // a process this user may not inspect, or one that exited: its sockets stay unowned below
180
+ }
181
+ for (const fd of fds) {
182
+ let target;
183
+ try {
184
+ target = io.readLink(`/proc/${entry}/fd/${fd}`);
185
+ }
186
+ catch {
187
+ continue;
188
+ }
189
+ const match = /^socket:\[([0-9]+)\]$/.exec(target);
190
+ if (!match || !inodes.has(match[1]))
191
+ continue;
192
+ const set = owners.get(match[1]) ?? new Set();
193
+ set.add(Number(entry));
194
+ owners.set(match[1], set);
195
+ }
196
+ }
197
+ const unowned = [...inodes].filter((inode) => !owners.has(inode));
198
+ if (unowned.length > 0) {
199
+ return {
200
+ kind: "unavailable",
201
+ reason: `TCP port ${port} has a listening socket (inode ${unowned.join(", ")}) whose owner could not be found or inspected in /proc/<pid>/fd (the process may have exited, or this user may not inspect it)`,
202
+ remedy: LISTENER_VISIBILITY_REMEDY,
203
+ };
204
+ }
205
+ const pids = new Set();
206
+ for (const set of owners.values())
207
+ for (const pid of set)
208
+ pids.add(pid);
209
+ return { kind: "listeners", pids: [...pids].sort((a, b) => a - b) };
210
+ }
211
+ /** The ps command line the non-Linux birth reader runs for `pid`. */
212
+ export function psStartArgs(pid) {
213
+ return ["-o", "lstart=", "-p", String(pid)];
214
+ }
215
+ /** `ps -o lstart=` under `LC_ALL=C`: `Tue Oct 13 06:46:06 2026`, with a space-padded day. */
216
+ const LSTART = /^[A-Z][a-z]{2} [A-Z][a-z]{2} [ 0-9][0-9] [0-9]{2}:[0-9]{2}:[0-9]{2} [0-9]{4}$/;
217
+ /** Parse `ps -o lstart=` output into a start time, or null when it is not one. */
218
+ export function parsePsLstart(output) {
219
+ const line = output.trim();
220
+ return LSTART.test(line) ? line : null;
221
+ }
222
+ /** The birth identity of `pid` (see {@link BirthRead}). */
223
+ export function readProcessBirth(pid, io = {}) {
224
+ const full = { ...DEFAULT_IO, ...io };
225
+ if (full.platform === "linux") {
226
+ const path = `/proc/${pid}/stat`;
227
+ let stat;
228
+ try {
229
+ stat = full.readFile(path);
230
+ }
231
+ catch (err) {
232
+ return {
233
+ kind: "unavailable",
234
+ reason: `the start time of process ${pid} cannot be read from ${path} (${err?.code ?? err?.message}); it may have exited`,
235
+ remedy: "Re-run this command once the instance is running and not restarting.",
236
+ };
237
+ }
238
+ const ticks = parseProcStatStartTime(stat);
239
+ if (ticks === null) {
240
+ return { kind: "unavailable", reason: `${path} has no start time this check can read`, remedy: `Check ${path}; this check reads its field 22.` };
241
+ }
242
+ return { kind: "birth", id: `${pid}@${ticks}` };
243
+ }
244
+ const command = `ps ${psStartArgs(pid).join(" ")}`;
245
+ let output;
246
+ try {
247
+ output = full.runPs(psStartArgs(pid));
248
+ }
249
+ catch (err) {
250
+ if (err?.code === "ENOENT") {
251
+ return {
252
+ kind: "unavailable",
253
+ reason: `ps is not installed or not on PATH, and this check reads a process's start time with \`${command}\``,
254
+ remedy: "Put ps on PATH (macOS ships it as /bin/ps), then re-run this command.",
255
+ };
256
+ }
257
+ return {
258
+ kind: "unavailable",
259
+ reason: `\`${command}\` found no start time (exit ${err?.status ?? err?.code ?? "abnormal"}); process ${pid} may have exited`,
260
+ remedy: "Re-run this command once the instance is running and not restarting.",
261
+ };
262
+ }
263
+ const started = parsePsLstart(output);
264
+ if (started === null) {
265
+ return { kind: "unavailable", reason: `\`${command}\` printed a start time this check cannot read`, remedy: `Run \`${command}\` yourself and check its output.` };
266
+ }
267
+ return { kind: "birth", id: `${pid}@${started}` };
268
+ }
@@ -0,0 +1,27 @@
1
+ import { proveLocalInstancePair } from "./local-instance-pair.js";
2
+ export async function resolveLocalDeleteInstance(opts, resolveOpsPort, authorization) {
3
+ const source = opts.opsPort !== undefined ? "--ops-port" : process.env.FLAIR_OPS_PORT ? "FLAIR_OPS_PORT" : "ops endpoint";
4
+ const opsPort = resolveOpsPort(opts);
5
+ const opsUrl = `http://127.0.0.1:${opsPort}/`;
6
+ // The pair check is shared with `flair doctor` (local-instance-pair.ts). It
7
+ // runs before this command sends anything to the HTTP port.
8
+ const pair = await proveLocalInstancePair(opsPort, authorization);
9
+ if (pair.kind !== "proven") {
10
+ throw new Error(`${source} ${opsPort}: the local HTTP/ops pair could not be proven (${pair.detail}); refusing deletion. ` +
11
+ (pair.remedy ?? deleteRemedy(source, opsPort, pair.status)));
12
+ }
13
+ const httpPort = pair.httpPort;
14
+ if (opts.port !== undefined && Number(opts.port) !== httpPort) {
15
+ throw new Error(`--port ${opts.port} does not match ${source} ${opsPort}'s HTTP endpoint ${httpPort}; refusing deletion. ` +
16
+ `Pass --port ${httpPort}, or omit --port, or name the ops port of the instance that serves ${opts.port}.`);
17
+ }
18
+ return { opsUrl, baseUrl: `http://127.0.0.1:${httpPort}` };
19
+ }
20
+ /** The remedy a delete refusal names when the pair check carries none. */
21
+ function deleteRemedy(source, opsPort, status) {
22
+ if (status === 401 || status === 403) {
23
+ return `Check that the admin credential this command uses is the one for the instance on ${source} ${opsPort}.`;
24
+ }
25
+ return "Pass --ops-port with the ops port of the instance to delete from (or set FLAIR_OPS_PORT); if that instance's "
26
+ + "configuration records ports it does not serve, correct it and restart the instance.";
27
+ }