@tpsdev-ai/flair 0.59.0 → 0.62.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (259) hide show
  1. package/README.md +4 -4
  2. package/SECURITY.md +36 -0
  3. package/config.yaml +12 -1
  4. package/dist/bridges/builtins/mem0.js +63 -28
  5. package/dist/bridges/runtime/import-runner.js +12 -0
  6. package/dist/bridges/runtime/load-plugin.js +42 -13
  7. package/dist/bridges/runtime/yaml-loader.js +4 -2
  8. package/dist/build-info.json +3 -3
  9. package/dist/cli.js +991 -248
  10. package/dist/commands/agent.js +224 -43
  11. package/dist/commands/attention.js +4 -3
  12. package/dist/commands/backup.js +202 -34
  13. package/dist/commands/bridge.js +172 -119
  14. package/dist/commands/deploy.js +37 -4
  15. package/dist/commands/doctor.js +592 -146
  16. package/dist/commands/export.js +54 -19
  17. package/dist/commands/federation.js +141 -21
  18. package/dist/commands/hook.js +155 -2
  19. package/dist/commands/idp.js +14 -1
  20. package/dist/commands/import.js +7 -3
  21. package/dist/commands/init.js +462 -193
  22. package/dist/commands/integrity.js +388 -0
  23. package/dist/commands/keys.js +247 -58
  24. package/dist/commands/mcp.js +97 -35
  25. package/dist/commands/memory.js +171 -21
  26. package/dist/commands/migrate-harness-memory.js +3 -2
  27. package/dist/commands/orgevent.js +46 -37
  28. package/dist/commands/presence.js +4 -3
  29. package/dist/commands/principal.js +426 -48
  30. package/dist/commands/quality.js +10 -1
  31. package/dist/commands/reembed.js +141 -17
  32. package/dist/commands/relationship.js +2 -1
  33. package/dist/commands/rem.js +56 -18
  34. package/dist/commands/restore.js +101 -61
  35. package/dist/commands/search.js +6 -4
  36. package/dist/commands/service.js +151 -38
  37. package/dist/commands/soul.js +4 -3
  38. package/dist/commands/status.js +43 -5
  39. package/dist/commands/test.js +3 -2
  40. package/dist/commands/upgrade.js +24 -1
  41. package/dist/commands/workspace.js +6 -3
  42. package/dist/component-env.js +31 -41
  43. package/dist/deploy.js +77 -1
  44. package/dist/doctor-client.js +529 -92
  45. package/dist/engine-version-contract.js +1 -0
  46. package/dist/engine-version.js +23 -3
  47. package/dist/federation-verify.js +4 -3
  48. package/dist/hook-install.js +670 -6
  49. package/dist/keystore.js +72 -0
  50. package/dist/lib/action-recall-runtime.js +328 -0
  51. package/dist/lib/agent-home-fields.js +132 -0
  52. package/dist/lib/agent-home.js +427 -0
  53. package/dist/lib/agent-id-rule.js +46 -0
  54. package/dist/lib/agent-roster.js +33 -0
  55. package/dist/lib/auth-resolve.js +49 -16
  56. package/dist/lib/capture-runtime.js +124 -0
  57. package/dist/lib/credential-status-rule.js +78 -0
  58. package/dist/lib/daemon-liveness.js +41 -10
  59. package/dist/lib/doctor-run.js +75 -37
  60. package/dist/lib/durability-copy.js +10 -0
  61. package/dist/lib/embedding-space-doctor.js +75 -0
  62. package/dist/lib/flair-agent-role.js +4 -0
  63. package/dist/lib/hub-url.js +12 -0
  64. package/dist/lib/init-admin-pass.js +88 -12
  65. package/dist/lib/init-listener-environ.js +1 -2
  66. package/dist/lib/init-occupied-listener.js +15 -111
  67. package/dist/lib/init-spawn-attribution.js +73 -0
  68. package/dist/lib/init-tcp-probe.js +33 -0
  69. package/dist/lib/instance-identity-row.js +20 -0
  70. package/dist/lib/launchd-management.js +24 -0
  71. package/dist/lib/listener-table.js +268 -0
  72. package/dist/lib/local-delete-instance.js +27 -0
  73. package/dist/lib/local-instance-pair.js +256 -0
  74. package/dist/lib/mcp-enable.js +1168 -326
  75. package/dist/lib/mcp-oauth-env-core.js +133 -0
  76. package/dist/lib/mcp-oauth-env.js +125 -0
  77. package/dist/lib/mcp-spec.js +17 -1
  78. package/dist/lib/memory-attributes.js +2 -0
  79. package/dist/lib/memory-id-policy.js +46 -0
  80. package/dist/lib/memory-integrity.js +309 -0
  81. package/dist/lib/memory-purge-response.js +20 -0
  82. package/dist/lib/ops-table-count.js +25 -0
  83. package/dist/lib/owned-pins.js +67 -10
  84. package/dist/lib/peer-status.js +27 -0
  85. package/dist/lib/principal-status.js +29 -0
  86. package/dist/lib/process-start-time.js +76 -12
  87. package/dist/lib/proto-safe-record.js +42 -0
  88. package/dist/lib/record-id-path.js +25 -0
  89. package/dist/lib/reembed-server-support.js +66 -0
  90. package/dist/lib/restore-verify.js +104 -0
  91. package/dist/lib/scheduler-platform.js +10 -6
  92. package/dist/lib/secret-keys.js +25 -0
  93. package/dist/lib/secrets-push.js +50 -22
  94. package/dist/lib/skill-seed-pending.js +24 -0
  95. package/dist/lib/skill-seed.js +365 -0
  96. package/dist/lib/stop-start-recovery.js +54 -0
  97. package/dist/lib/using-flair-skill.js +87 -0
  98. package/dist/mcp-client-assertion.js +112 -4
  99. package/dist/memory-id-checkpoint.js +326 -0
  100. package/dist/memory-node-compare.js +207 -0
  101. package/dist/packages/flair-mcp/src/secret-redaction.js +113 -0
  102. package/dist/rem/restore.js +6 -5
  103. package/dist/rem/runner.js +103 -44
  104. package/dist/resources/Agent.js +321 -1
  105. package/dist/resources/AgentKeyRegister.js +214 -0
  106. package/dist/resources/AgentKeyRegistration.js +28 -0
  107. package/dist/resources/AgentSeed.js +10 -4
  108. package/dist/resources/AutoPromoteCandidates.js +7 -1
  109. package/dist/resources/Credential.js +177 -2
  110. package/dist/resources/Federation.js +751 -143
  111. package/dist/resources/FederationRetry.js +140 -0
  112. package/dist/resources/InstructionVersion.js +220 -0
  113. package/dist/resources/Integration.js +300 -25
  114. package/dist/resources/Memory.js +2113 -604
  115. package/dist/resources/MemoryArchive.js +75 -42
  116. package/dist/resources/MemoryBootstrap.js +110 -39
  117. package/dist/resources/MemoryCandidate.js +21 -1
  118. package/dist/resources/MemoryDedupStats.js +30 -1
  119. package/dist/resources/MemoryFeed.js +327 -45
  120. package/dist/resources/MemoryGrant.js +21 -1
  121. package/dist/resources/MemoryMaintenance.js +129 -25
  122. package/dist/resources/MemoryPurge.js +232 -0
  123. package/dist/resources/MemoryReflect.js +7 -2
  124. package/dist/resources/MemoryReindex.js +24 -8
  125. package/dist/resources/Message.js +5 -3
  126. package/dist/resources/OAuth.js +186 -9
  127. package/dist/resources/OrgEvent.js +126 -3
  128. package/dist/resources/Presence.js +144 -49
  129. package/dist/resources/PromoteMemoryCandidate.js +18 -7
  130. package/dist/resources/Relationship.js +23 -0
  131. package/dist/resources/SemanticSearch.js +63 -32
  132. package/dist/resources/Soul.js +189 -76
  133. package/dist/resources/TeamDirectory.js +35 -0
  134. package/dist/resources/WorkspaceState.js +21 -1
  135. package/dist/resources/XAA.js +181 -63
  136. package/dist/resources/agent-auth.js +40 -15
  137. package/dist/resources/auth-middleware.js +400 -161
  138. package/dist/resources/ed25519-auth.js +1 -1
  139. package/dist/resources/embedding-space-guard.js +366 -72
  140. package/dist/resources/engine-version-stamp-boot.js +53 -0
  141. package/dist/resources/federation-classify.js +72 -0
  142. package/dist/resources/federation-crypto.js +5 -5
  143. package/dist/resources/federation-retry-lib.js +135 -0
  144. package/dist/resources/grant-visibility.js +135 -0
  145. package/dist/resources/harper-routing.js +83 -0
  146. package/dist/resources/health.js +120 -18
  147. package/dist/resources/host-source-citation.js +49 -0
  148. package/dist/resources/host-source-visibility.js +7 -6
  149. package/dist/resources/instance-create-lock.js +17 -0
  150. package/dist/resources/instance-identity.js +23 -0
  151. package/dist/resources/instruction-version-record.js +343 -0
  152. package/dist/resources/key-lock.js +3 -3
  153. package/dist/resources/mcp-handler.js +36 -8
  154. package/dist/resources/mcp-oauth-env-guard.js +36 -0
  155. package/dist/resources/mcp-oauth.js +23 -6
  156. package/dist/resources/mcp-tool-arguments.js +4 -6
  157. package/dist/resources/mcp-tools.js +128 -19
  158. package/dist/resources/memory-bootstrap-lib.js +5 -15
  159. package/dist/resources/memory-declared-attributes.js +3 -1
  160. package/dist/resources/memory-deletion-history.js +55 -0
  161. package/dist/resources/memory-durability.js +54 -0
  162. package/dist/resources/memory-embed-hash.js +88 -0
  163. package/dist/resources/memory-embedding-value.js +8 -0
  164. package/dist/resources/memory-host-source.js +27 -5
  165. package/dist/resources/memory-id-guard.js +75 -0
  166. package/dist/resources/memory-redaction.js +236 -0
  167. package/dist/resources/memory-supplied-vector.js +72 -0
  168. package/dist/resources/memory-write-lock.js +310 -0
  169. package/dist/resources/memory-write-response.js +139 -0
  170. package/dist/resources/migrations/data-dir.js +74 -16
  171. package/dist/resources/migrations/dir-safety.js +1 -1
  172. package/dist/resources/migrations/embedding-stamp.js +193 -79
  173. package/dist/resources/migrations/export.js +1 -0
  174. package/dist/resources/migrations/graph-heal.js +18 -25
  175. package/dist/resources/migrations/lock.js +7 -1
  176. package/dist/resources/migrations/snapshot.js +1 -0
  177. package/dist/resources/migrations/source-fields.js +5 -5
  178. package/dist/resources/migrations/synthetic-test-migration.js +14 -11
  179. package/dist/resources/migrations/visibility-backfill.js +29 -29
  180. package/dist/resources/object-body-guard.js +33 -0
  181. package/dist/resources/org-event-created-at.js +133 -0
  182. package/dist/resources/originator-instance.js +39 -7
  183. package/dist/resources/owner-delete-recheck.js +78 -0
  184. package/dist/resources/owner-field-guard.js +39 -5
  185. package/dist/resources/owner-scoped-write-policy.js +212 -0
  186. package/dist/resources/owner-scoped-writes.js +58 -0
  187. package/dist/resources/presence-receipt.js +236 -0
  188. package/dist/resources/promotion-stamp.js +47 -12
  189. package/dist/resources/record-owner-guard.js +74 -26
  190. package/dist/resources/record-types.js +1 -1
  191. package/dist/resources/relay-ops.js +78 -6
  192. package/dist/resources/replay-store.js +96 -19
  193. package/dist/resources/request-target.js +136 -0
  194. package/dist/resources/request-transaction.js +35 -0
  195. package/dist/resources/search-readiness.js +4 -1
  196. package/dist/resources/seed-ids.js +9 -0
  197. package/dist/resources/seed-reservation.js +117 -0
  198. package/dist/resources/semantic-retrieval-core.js +20 -9
  199. package/dist/resources/skill-manifest.js +20 -11
  200. package/dist/resources/skill-subject.js +53 -0
  201. package/dist/resources/skill-version-write.js +432 -0
  202. package/dist/resources/skill-write-fault.js +17 -0
  203. package/dist/resources/skill-write-policy.js +67 -0
  204. package/dist/resources/skill-write.js +67 -7
  205. package/dist/resources/table-helpers.js +10 -7
  206. package/dist/resources/team-directory.js +248 -0
  207. package/dist/resources/tool-descriptors/index.js +69 -8
  208. package/dist/resources/txn-pause-point.js +118 -0
  209. package/dist/resources/usage-recording.js +171 -63
  210. package/dist/resources/write-back.js +218 -0
  211. package/dist/src/engine-version-contract.js +1 -0
  212. package/dist/src/keystore.js +72 -0
  213. package/dist/src/lib/agent-home-fields.js +132 -0
  214. package/dist/src/lib/agent-id-rule.js +46 -0
  215. package/dist/src/lib/agent-key-register.js +80 -0
  216. package/dist/src/lib/atomic-write.js +256 -0
  217. package/dist/src/lib/credential-status-rule.js +78 -0
  218. package/dist/src/lib/expired-by-agent.js +37 -0
  219. package/dist/src/lib/flair-agent-role.js +4 -0
  220. package/dist/src/lib/idp-mapping-rule.js +81 -0
  221. package/dist/src/lib/instance-identity-row.js +20 -0
  222. package/dist/src/lib/mcp-oauth-env-core.js +133 -0
  223. package/dist/src/lib/memory-attributes.js +2 -0
  224. package/dist/src/lib/memory-id-policy.js +46 -0
  225. package/dist/src/lib/principal-status.js +29 -0
  226. package/dist/src/lib/proto-safe-record.js +42 -0
  227. package/dist/src/lib/reembed-server-support.js +66 -0
  228. package/dist/src/lib/scheduler-platform.js +10 -6
  229. package/dist/src/lib/systemd-agent-id.js +38 -0
  230. package/docs/access-control.md +146 -45
  231. package/docs/api-reference.md +46 -11
  232. package/docs/auth.md +6 -12
  233. package/docs/bridges.md +11 -0
  234. package/docs/claude-code.md +34 -4
  235. package/docs/deploying-on-fabric.md +70 -0
  236. package/docs/deployment.md +2 -0
  237. package/docs/embedding-in-a-harper-app.md +1 -1
  238. package/docs/federation.md +33 -2
  239. package/docs/hosted-on-fabric.md +43 -36
  240. package/docs/integrations.md +5 -5
  241. package/docs/mcp-clients.md +5 -2
  242. package/docs/n8n.md +17 -11
  243. package/docs/notes/mcp-agent-auth-consumer.md +12 -4
  244. package/docs/notes/mcp-oauth-model2.md +34 -5
  245. package/docs/quickstart-fabric.md +2 -2
  246. package/docs/quickstart.md +9 -1
  247. package/docs/releasing.md +12 -6
  248. package/docs/rem.md +8 -0
  249. package/docs/secrets-and-keys.md +19 -2
  250. package/docs/standalone-local.md +1 -0
  251. package/docs/supply-chain-policy.md +13 -3
  252. package/docs/upgrade.md +32 -6
  253. package/package.json +10 -5
  254. package/schemas/agent-key-registration.graphql +22 -0
  255. package/schemas/agent.graphql +3 -0
  256. package/schemas/federation.graphql +38 -1
  257. package/schemas/memory.graphql +84 -5
  258. package/schemas/oauth.graphql +19 -0
  259. package/schemas/schema.graphql +2 -0
@@ -0,0 +1,75 @@
1
+ /**
2
+ * A bounded, printable reason for a failed scan. The guard's own
3
+ * reason strings are short and content-free, but /Health is unauthenticated, so
4
+ * bound the length and reject control characters before printing the string.
5
+ */
6
+ export function boundedScanFailureReason(reason) {
7
+ if (typeof reason !== "string")
8
+ return "unspecified";
9
+ const s = reason.trim();
10
+ if (s.length === 0 || s.length > 120 || /[\u0000-\u001f\u007f]/.test(s))
11
+ return "unspecified";
12
+ return s;
13
+ }
14
+ /**
15
+ * The guard's `excluded` count as a printable whole number, or null when it is
16
+ * absent or malformed (an older or foreign server, or no scan has published a
17
+ * count). Never rendered as zero on unknown evidence.
18
+ */
19
+ function excludedCount(value) {
20
+ return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : null;
21
+ }
22
+ /** The clause naming the excluded count, or "" when it is unknown. */
23
+ function excludedClause(value) {
24
+ const n = excludedCount(value);
25
+ if (n === null)
26
+ return "";
27
+ return `; excluded from the vector leg: ${n} row(s) with no trusted model stamp`;
28
+ }
29
+ /**
30
+ * Doctor finding, or null when there is nothing to say. The five states map to
31
+ * a distinct line: `uniform` an OK line; `mixed` and `excluded` blocking
32
+ * findings with a remedy; `unverified` and `scan-failed` advisories naming the
33
+ * state.
34
+ */
35
+ export function describeEmbeddingSpaceDoctorFinding(field) {
36
+ if (field == null || typeof field !== "object" || Array.isArray(field))
37
+ return null;
38
+ const rec = field;
39
+ switch (rec.state) {
40
+ case "uniform":
41
+ return { isIssue: false, icon: "ok", message: "embedding model stamps verified uniform" };
42
+ case "mixed":
43
+ return {
44
+ isIssue: true,
45
+ icon: "error",
46
+ message: "a non-current embedding model stamp was observed — the embedding leg is refused" +
47
+ // A known foreign stamp outranks a scan error; name the error too.
48
+ (rec.reason == null ? "" : `; last scan failed (${boundedScanFailureReason(rec.reason)})`),
49
+ fixHint: "Reconcile to one space with: flair reembed --stale-only",
50
+ };
51
+ case "excluded":
52
+ return {
53
+ isIssue: true,
54
+ icon: "error",
55
+ message: "the last scan found a stored vector with no trusted current-space stamp — the embedding leg is refused" +
56
+ excludedClause(rec.excluded),
57
+ fixHint: "Re-embed or remove the stored vector; a later embedding query must trigger and complete a rescan before flair doctor can confirm the repair",
58
+ };
59
+ case "unverified":
60
+ return {
61
+ isIssue: false,
62
+ icon: "warn",
63
+ message: "embedding space not yet verified — the embedding leg is refused until a scan verifies the stamps",
64
+ };
65
+ case "scan-failed":
66
+ return {
67
+ isIssue: false,
68
+ icon: "warn",
69
+ message: `embedding space unverified: last scan failed (${boundedScanFailureReason(rec.reason)}) — ` +
70
+ `the embedding leg is refused`,
71
+ };
72
+ default:
73
+ return null;
74
+ }
75
+ }
@@ -79,6 +79,10 @@ export const FLAIR_AGENT_PERMISSION = {
79
79
  // no write grant. The history table has no direct REST route.
80
80
  OrgSkillAssignment: grant(true, false, false, false),
81
81
  OrgSkillAssignmentHistory: grant(false, false, false, false),
82
+ // flair#2139 S1: instruction-version history. Read only — the resource
83
+ // itself denies every mutation verb to every principal, and the only
84
+ // application writer is the in-process append helper. See resources/InstructionVersion.ts.
85
+ InstructionVersion: grant(true, false, false, false),
82
86
  // Federation / OAuth / IdP / internal — system + admin only; agents get none.
83
87
  Peer: grant(false, false, false, false),
84
88
  PairingToken: grant(false, false, false, false),
@@ -0,0 +1,12 @@
1
+ /**
2
+ * hub-url.ts — normalize a federation hub URL.
3
+ *
4
+ * New pairings store the normalized hub URL; sync normalizes previously stored
5
+ * endpoints when sending. This strips trailing slashes only; it does not
6
+ * otherwise validate the hub URL's path.
7
+ */
8
+ export function normalizeHubUrl(hubUrl) {
9
+ // A non-string (a peer row without an endpoint or id) is passed through
10
+ // unchanged, exactly as it was used before.
11
+ return typeof hubUrl === "string" ? hubUrl.replace(/\/+$/, "") : hubUrl;
12
+ }
@@ -26,7 +26,8 @@
26
26
  */
27
27
  import { request as httpRequest } from "node:http";
28
28
  import { createConnection } from "node:net";
29
- import { existsSync, statSync } from "node:fs";
29
+ import { createRequire } from "node:module";
30
+ import { closeSync, lstatSync, openSync, statSync } from "node:fs";
30
31
  import { dirname, join } from "node:path";
31
32
  /** Copy-pasteable recovery commands. Tests assert these strings verbatim. */
32
33
  export const INIT_RESET_ADMIN_PASS_COMMAND = "flair init --reset-admin-pass";
@@ -54,12 +55,12 @@ export function resolveInitAdminPasswordSource(adminPassFileExists, ctx = {}) {
54
55
  if (adminPassFileExists && !reset) {
55
56
  return "reuse-existing";
56
57
  }
58
+ if (explicit && !reset) {
59
+ return "re-persist";
60
+ }
57
61
  if (!adminPassFileExists && !persisted && !reset) {
58
62
  return "generate-new";
59
63
  }
60
- if (persisted && explicit && !reset) {
61
- return "re-persist";
62
- }
63
64
  // Rotate is production credential rotation. The ONLY way in is the
64
65
  // explicit `--reset-admin-pass` flag — never a missing-file guess.
65
66
  if (reset) {
@@ -83,20 +84,95 @@ export function resolveInitAdminPasswordRefuseReason(adminPassFileExists, ctx =
83
84
  return "persisted-missing-file";
84
85
  }
85
86
  /**
86
- * Harper's own install-validator signal that a rootPath already has a user
87
- * record (`system/hdb_user/data.mdb` or the legacy `system/hdb_user.mdb`).
88
- * Config presence alone is not enough — an interrupted install can write
89
- * harper-config.yaml before the user hash lands.
87
+ * Where each storage engine keeps the system schema (and so the admin user).
88
+ *
89
+ * Older data directories use LMDB: one file per table, at
90
+ * `system/hdb_user/data.mdb`, or the legacy single `system/hdb_user.mdb`.
91
+ *
92
+ * Harper 5 uses RocksDB: the whole `system` database is ONE column-family
93
+ * database at `database/system`, and each table's primary store is a column
94
+ * family named `<table>/` (Harper names a table's primary store with a
95
+ * trailing slash).
96
+ */
97
+ export const HARPER_SYSTEM_DB_REL = join("database", "system");
98
+ export const HDB_USER_PRIMARY_CF = "hdb_user/";
99
+ /**
100
+ * Match `hdb_user/` or the `hdb_user/@` prefix.
101
+ */
102
+ export function isHdbUserPrimaryColumn(column) {
103
+ return column === HDB_USER_PRIMARY_CF || column.startsWith(`${HDB_USER_PRIMARY_CF}@`);
104
+ }
105
+ /**
106
+ * Count the rows in the `hdb_user` primary store of a Harper 5 system
107
+ * database, opened READ-ONLY (RocksDB read-only needs no lock, so this works
108
+ * while the instance is running, and writes nothing).
109
+ *
110
+ * Both physical layouts are accepted (see `isHdbUserPrimaryColumn`); every
111
+ * matching family is counted.
112
+ *
113
+ * `@harperfast/rocksdb-js` is resolved through the installed `harper`
114
+ * package: flair does not depend on it directly, and the reader must be the
115
+ * same engine Harper wrote the store with.
90
116
  */
117
+ export function countRocksAdminUsers(systemDbDir) {
118
+ const requireFromHere = createRequire(import.meta.url);
119
+ const rocksPath = createRequire(requireFromHere.resolve("harper")).resolve("@harperfast/rocksdb-js");
120
+ const { RocksDatabase } = requireFromHere(rocksPath);
121
+ const probe = RocksDatabase.open(systemDbDir, { readOnly: true });
122
+ let userStores;
123
+ try {
124
+ if (!Array.isArray(probe.columns) || !probe.columns.every(column => typeof column === "string")) {
125
+ throw new Error(`Invalid RocksDB columns metadata at ${systemDbDir}`);
126
+ }
127
+ userStores = probe.columns.filter(isHdbUserPrimaryColumn);
128
+ }
129
+ finally {
130
+ probe.close?.();
131
+ }
132
+ if (userStores.length === 0) {
133
+ throw new Error(`MISSING_HDB_USER_COLUMN: existing system store at ${systemDbDir} lacks ${HDB_USER_PRIMARY_CF}. Repair the system store or select the correct --data-dir.`);
134
+ }
135
+ let total = 0;
136
+ for (const name of userStores) {
137
+ const users = RocksDatabase.open(systemDbDir, { name, readOnly: true });
138
+ try {
139
+ total += users.getKeysCount();
140
+ }
141
+ finally {
142
+ users.close?.();
143
+ }
144
+ }
145
+ return total;
146
+ }
147
+ /** A populated user store is evidence that the install is not fresh. */
91
148
  export function detectPersistedAdminUser(dataDir) {
92
- const dir = dataDir;
93
- return (existsSync(join(dir, "system", "hdb_user", "data.mdb")) ||
94
- existsSync(join(dir, "system", "hdb_user.mdb")));
149
+ for (const path of [join(dataDir, "system", "hdb_user", "data.mdb"), join(dataDir, "system", "hdb_user.mdb")]) {
150
+ try {
151
+ const fd = openSync(path, "r");
152
+ closeSync(fd);
153
+ return true;
154
+ }
155
+ catch (err) {
156
+ if (err.code !== "ENOENT")
157
+ throw err;
158
+ }
159
+ }
160
+ const systemDbDir = join(dataDir, HARPER_SYSTEM_DB_REL);
161
+ try {
162
+ lstatSync(systemDbDir);
163
+ }
164
+ catch (err) {
165
+ if (err.code === "ENOENT")
166
+ return false;
167
+ throw err;
168
+ }
169
+ return countRocksAdminUsers(systemDbDir) > 0;
95
170
  }
96
171
  export function initAdminPassRefusalMessage(reason, opts = {}) {
97
172
  if (reason === "foreign-instance") {
98
173
  const port = opts.httpPort ?? 19926;
99
- const head = `A Harper instance is already answering on port ${port} and this data directory has no persisted admin user.`;
174
+ const pid = opts.pid === undefined ? "" : `, pid ${opts.pid}`;
175
+ const head = `Refusing init: port ${port}${pid}: persisted admin user was not detected in this data directory.`;
100
176
  if (opts.offerFlairStop === false)
101
177
  return head;
102
178
  return (`${head} Stop that process before initializing a new instance:\n ${INIT_STOP_FOREIGN_COMMAND}`);
@@ -4,8 +4,7 @@
4
4
  * Linux reads `/proc/<pid>/environ` (NUL-separated, so a space in the path
5
5
  * stays part of the value). macOS `ps -E` output does not separate arguments
6
6
  * from the environment, so it cannot establish ROOTPATH. On macOS, and on
7
- * any failed read, the directory is unavailable. Init must not refuse
8
- * before auth from a directory it cannot read, and must not invent one.
7
+ * any failed read, the directory is unavailable.
9
8
  *
10
9
  * Daemon sidecar recovery keeps its own reader. This module is init's.
11
10
  */
@@ -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
  *
@@ -487,6 +487,30 @@ export function renderDetachedWarning(m, headline) {
487
487
  lines.push(` Fix: ${m.remedy.join(" && ")}`);
488
488
  return lines;
489
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
+ }
490
514
  // renderVerifiedSummary used to live here and qualify ✅ from version +
491
515
  // LaunchdManagement alone (flair#1022). That signature was the ceiling on
492
516
  // what it could notice — a blacklist of one known-unhealthy form. The