@tpsdev-ai/flair 0.55.2 → 0.56.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 (60) hide show
  1. package/README.md +3 -3
  2. package/dist/bridges/builtins/markdown.js +2 -2
  3. package/dist/bridges/discover.js +2 -2
  4. package/dist/bridges/runtime/allow-list.js +2 -2
  5. package/dist/build-info.json +3 -3
  6. package/dist/cli.js +10 -12
  7. package/dist/commands/attention.js +2 -2
  8. package/dist/commands/backup.js +2 -2
  9. package/dist/commands/doctor.js +39 -28
  10. package/dist/commands/export.js +2 -2
  11. package/dist/commands/federation.js +185 -38
  12. package/dist/commands/hook.js +4 -4
  13. package/dist/commands/init.js +30 -8
  14. package/dist/commands/mcp.js +2 -2
  15. package/dist/commands/migrate-harness-memory.js +8 -8
  16. package/dist/commands/rem.js +2 -2
  17. package/dist/commands/service.js +25 -1
  18. package/dist/commands/session.js +2 -2
  19. package/dist/commands/uninstall.js +2 -2
  20. package/dist/commands/upgrade.js +3 -3
  21. package/dist/doctor-client.js +5 -23
  22. package/dist/engine-version.js +2 -2
  23. package/dist/federation/scheduler.js +5 -5
  24. package/dist/install/clients.js +5 -10
  25. package/dist/keystore.js +10 -2
  26. package/dist/lib/auth-resolve.js +5 -5
  27. package/dist/lib/doctor-config-path.js +2 -2
  28. package/dist/lib/flair-paths.js +29 -0
  29. package/dist/lib/home.js +60 -0
  30. package/dist/lib/launchd-repair.js +6 -0
  31. package/dist/lib/mcp-enable.js +4 -4
  32. package/dist/lib/owned-pins.js +1 -13
  33. package/dist/lib/socket-path-limit.js +120 -0
  34. package/dist/lib/uninstall-purge.js +2 -18
  35. package/dist/lib/upgrade-plain-tree.js +2 -2
  36. package/dist/mcp-client-assertion.js +3 -3
  37. package/dist/rem/runner.js +3 -3
  38. package/dist/rem/scheduler.js +5 -5
  39. package/dist/rem/snapshot.js +2 -2
  40. package/dist/resources/OAuth.js +62 -11
  41. package/dist/resources/Presence.js +135 -47
  42. package/dist/resources/admin-layout.js +7 -2
  43. package/dist/resources/memory-reflect-lib.js +17 -1
  44. package/dist/src/keystore.js +10 -2
  45. package/dist/src/lib/home.js +60 -0
  46. package/dist/src/rem/scheduler.js +5 -5
  47. package/dist/version-check.js +2 -2
  48. package/dist/version-handshake.js +2 -2
  49. package/docs/api-reference.md +31 -6
  50. package/docs/auth.md +14 -2
  51. package/docs/deploying-on-fabric.md +5 -4
  52. package/docs/deployment.md +26 -37
  53. package/docs/embedding-in-a-harper-app.md +4 -2
  54. package/docs/entity-vocabulary.md +5 -5
  55. package/docs/federation.md +39 -19
  56. package/docs/hosted-on-fabric.md +7 -5
  57. package/docs/mcp-clients.md +29 -12
  58. package/docs/spoke-bringup.md +41 -22
  59. package/docs/standalone-local.md +12 -16
  60. package/package.json +1 -1
@@ -109,17 +109,79 @@ const FEDERATION_PRIVATE_VISIBILITY = "private";
109
109
  function isFederationPrivateVisibility(visibility) {
110
110
  return visibility === FEDERATION_PRIVATE_VISIBILITY;
111
111
  }
112
+ /** The exact refusal sentence when nothing has reached the hub yet. */
113
+ const NOTHING_SENT_TO_HUB = "Nothing was sent to the hub; the pairing token is still valid.";
114
+ /** The post-hub failure sentence: the token is already spent. */
115
+ const PAIR_TOKEN_CONSUMED = "The pairing token has been consumed; mint a new one with 'flair federation token' on the hub and re-run pair.";
116
+ /** A rejected hub fetch may or may not have reached the hub, so be uncertain. */
117
+ const PAIR_TOKEN_MAYBE_CONSUMED = "The request may not have reached the hub; verify the pairing token there before re-minting one with 'flair federation token'.";
118
+ /**
119
+ * Strip any userinfo (user:password) and query string from a URL before printing
120
+ * it. An --ops-target like https://user:pass@host/?token=... must never put the
121
+ * credential or the query token on stderr.
122
+ */
123
+ export function redactUrl(u) {
124
+ try {
125
+ const url = new URL(u);
126
+ url.username = "";
127
+ url.password = "";
128
+ url.search = "";
129
+ return url.toString();
130
+ }
131
+ catch {
132
+ // Not a parseable absolute URL: strip a userinfo-looking prefix and any query.
133
+ return u.replace(/\/\/[^/@]*@/, "//").replace(/\?.*$/, "");
134
+ }
135
+ }
136
+ /**
137
+ * A fetch error's code or name — NEVER its message. Under Node a rejected
138
+ * fetch to a user-supplied URL can carry the full URL (credentials included)
139
+ * in err.message, so the message must never reach an error line.
140
+ */
141
+ function fetchErrorLabel(err) {
142
+ // Node's fetch wraps the OS error: the useful code (ECONNREFUSED, ENOTFOUND,
143
+ // …) is on err.cause.code, so prefer it over the wrapper's code/name.
144
+ const e = err;
145
+ const causeCode = typeof e?.cause?.code === "string" && e.cause.code ? e.cause.code : undefined;
146
+ const code = typeof e?.code === "string" && e.code ? e.code : undefined;
147
+ const name = typeof e?.name === "string" && e.name ? e.name : undefined;
148
+ return causeCode ?? code ?? name ?? "request failed";
149
+ }
150
+ /** Strip any userinfo from URLs embedded in a message before printing it. */
151
+ function redactMessage(text) {
152
+ return text.replace(/\/\/[^/@\s]+@/g, "//");
153
+ }
154
+ /**
155
+ * Whether a Harper permission object can WRITE the Peer table: a super_user, or
156
+ * an explicit flair.Peer insert+update grant. A restrictive `operations`
157
+ * allowlist additionally gates the operation itself, so `upsert` must be
158
+ * permitted for any Peer write to reach the table. A read-only credential can
159
+ * search but not upsert, so the preflight must check this, not readability.
160
+ */
161
+ export function canWritePeerPermission(permission) {
162
+ if (permission?.super_user === true)
163
+ return true;
164
+ const operations = permission?.operations;
165
+ if (Array.isArray(operations) && !operations.includes("upsert") && !operations.includes("standard_user")) {
166
+ return false;
167
+ }
168
+ const peer = permission?.flair?.tables?.Peer;
169
+ return peer?.insert === true && peer?.update === true;
170
+ }
112
171
  async function loadInstanceSecretKey(instanceId, opts) {
113
172
  // Try keystore first
114
173
  const seed = keystore.getPrivateKeySeed(instanceId);
115
174
  if (seed) {
116
175
  return nacl.sign.keyPair.fromSeed(seed).secretKey;
117
176
  }
118
- // Fallback: check DB for legacy _keySeed
119
- const opsPort = resolveOpsPort(opts);
120
- const adminPass = opts.adminPass ?? process.env.FLAIR_ADMIN_PASS ?? "";
177
+ // Fallback: check DB for legacy _keySeed. Use the SAME three-source
178
+ // credential and the SAME resolved ops endpoint as the pair preflight, so a
179
+ // legacy-key spoke cannot pass preflight and then fail here for a different
180
+ // endpoint or a credential the fallback would not send.
181
+ const opsEndpoint = resolveEffectiveOpsUrl(opts) ?? `http://127.0.0.1:${resolveOpsPort(opts)}`;
182
+ const adminPass = opts.adminPass ?? process.env.FLAIR_ADMIN_PASS ?? process.env.HDB_ADMIN_PASSWORD ?? "";
121
183
  const auth = `Basic ${Buffer.from(`${resolveAdminUser(opts.adminUser)}:${adminPass}`).toString("base64")}`;
122
- const res = await fetch(`http://127.0.0.1:${opsPort}/`, {
184
+ const res = await fetch(`${opsEndpoint}/`, {
123
185
  method: "POST",
124
186
  headers: { "Content-Type": "application/json", Authorization: auth },
125
187
  body: JSON.stringify({ operation: "search_by_value", schema: "flair", table: "Instance", search_attribute: "id", search_type: "equals", search_value: instanceId, get_attributes: ["*"] }),
@@ -1118,6 +1180,9 @@ export function register(program) {
1118
1180
  // the GET actually probes (do not cite resolveBaseUrl only in the
1119
1181
  // rewriter while api() falls through to resolveHttpPort({})).
1120
1182
  const identityUrl = resolveBaseUrl(opts).replace(/\/$/, "");
1183
+ // Set immediately before the hub's FederationPair request, so the outer
1184
+ // catch can say whether the one-time token may already be consumed.
1185
+ let hubContacted = false;
1121
1186
  try {
1122
1187
  // flair#820: the identity GET is pair's first step and is allowAdmin.
1123
1188
  // A 403 here is LOCAL (or --target REMOTE), never the hub handshake.
@@ -1128,7 +1193,7 @@ export function register(program) {
1128
1193
  }
1129
1194
  catch (err) {
1130
1195
  throw rewriteFederationPairLocalAccessError(err, {
1131
- url: identityUrl,
1196
+ url: redactUrl(identityUrl),
1132
1197
  side: target ? "REMOTE" : "LOCAL",
1133
1198
  agentId: process.env.FLAIR_AGENT_ID,
1134
1199
  });
@@ -1162,6 +1227,65 @@ export function register(program) {
1162
1227
  console.error("Error: --token or --token-from is required. Ask the hub admin to run 'flair federation token' and provide the token.");
1163
1228
  process.exit(1);
1164
1229
  }
1230
+ // flair#1875: resolve the SPOKE admin credential and preflight it BEFORE
1231
+ // any request that consumes the one-time token. The hub's FederationPair
1232
+ // burns the token, so a missing or refused admin credential must be
1233
+ // caught here — while the token is still valid — not after the hub has
1234
+ // already paired us. Zero hub requests happen on this path.
1235
+ const adminPass = opts.adminPass ?? process.env.FLAIR_ADMIN_PASS ?? process.env.HDB_ADMIN_PASSWORD ?? "";
1236
+ if (!adminPass) {
1237
+ console.error("Error: refusing to contact the hub: the local hub-peer record needs admin auth to write — " +
1238
+ "pass --admin-pass, or set FLAIR_ADMIN_PASS / HDB_ADMIN_PASSWORD (the SPOKE admin password), then re-run pair. " +
1239
+ NOTHING_SENT_TO_HUB);
1240
+ process.exit(1);
1241
+ }
1242
+ const auth = `Basic ${Buffer.from(`${resolveAdminUser(opts.adminUser)}:${adminPass}`).toString("base64")}`;
1243
+ const opsEndpoint = resolveEffectiveOpsUrl(opts) ?? `http://127.0.0.1:${resolveOpsPort(opts)}`;
1244
+ const safeOps = redactUrl(opsEndpoint);
1245
+ // Preflight the credential against the LOCAL ops API before the hub
1246
+ // request. user_info reports the credential's own role/permissions, so
1247
+ // this proves it can WRITE flair.Peer — a read-only credential can search
1248
+ // but is refused by the upsert, and by then the hub has burned the token.
1249
+ let preflightRes;
1250
+ try {
1251
+ preflightRes = await fetch(`${opsEndpoint}/`, {
1252
+ method: "POST",
1253
+ headers: { "Content-Type": "application/json", Authorization: auth },
1254
+ body: JSON.stringify({ operation: "user_info" }),
1255
+ signal: AbortSignal.timeout(10_000),
1256
+ });
1257
+ }
1258
+ catch (err) {
1259
+ // Never print err.message: a rejected fetch to the user-supplied ops
1260
+ // URL can carry the full URL (credentials included) in its message.
1261
+ console.error(`Error: could not reach the local ops API at ${safeOps} to preflight the spoke admin credential ` +
1262
+ `(${fetchErrorLabel(err)}). ${NOTHING_SENT_TO_HUB}`);
1263
+ process.exit(1);
1264
+ }
1265
+ if (preflightRes.status === 401 || preflightRes.status === 403) {
1266
+ console.error(`Error: the spoke admin credential was refused by the local ops API (${preflightRes.status}). ${NOTHING_SENT_TO_HUB}`);
1267
+ process.exit(1);
1268
+ }
1269
+ if (!preflightRes.ok) {
1270
+ console.error(`Error: the local ops API at ${safeOps} answered ${preflightRes.status} to user_info. ${NOTHING_SENT_TO_HUB}`);
1271
+ process.exit(1);
1272
+ }
1273
+ const userInfo = (await preflightRes.json().catch(() => null));
1274
+ const rolePermission = userInfo?.role?.permission;
1275
+ if (rolePermission === undefined || rolePermission === null) {
1276
+ console.error(`Error: user_info returned no role information. ${NOTHING_SENT_TO_HUB}`);
1277
+ process.exit(1);
1278
+ }
1279
+ // super_user is the supported credential. For a non-super_user role this
1280
+ // checks TABLE-level grants only (flair.Peer insert+update) plus the
1281
+ // operations allowlist; it cannot see attribute-level grants, so a role
1282
+ // with table access but restricted attributes still passes here and the
1283
+ // upsert may fail later (reported on the consumed-token path).
1284
+ if (!canWritePeerPermission(rolePermission)) {
1285
+ const roleName = userInfo?.role?.role ?? userInfo?.role?.name ?? "(unknown)";
1286
+ console.error(`Error: the spoke admin credential cannot write the Peer table (role ${roleName}). ${NOTHING_SENT_TO_HUB}`);
1287
+ process.exit(1);
1288
+ }
1165
1289
  // Load secret key and sign the pairing request.
1166
1290
  const secretKey = await loadInstanceSecretKey(instance.id, opts);
1167
1291
  const pairBody = {
@@ -1175,14 +1299,25 @@ export function register(program) {
1175
1299
  if (authHeader) {
1176
1300
  fetchHeaders.Authorization = authHeader;
1177
1301
  }
1178
- const res = await fetch(`${hubUrl}/FederationPair`, {
1179
- method: "POST",
1180
- headers: fetchHeaders,
1181
- body: JSON.stringify(signedBody),
1182
- });
1302
+ let res;
1303
+ try {
1304
+ hubContacted = true;
1305
+ res = await fetch(`${hubUrl}/FederationPair`, {
1306
+ method: "POST",
1307
+ headers: fetchHeaders,
1308
+ body: JSON.stringify(signedBody),
1309
+ });
1310
+ }
1311
+ catch (err) {
1312
+ // A rejected fetch to the user-supplied hub URL: name the error, never
1313
+ // print its message (it can carry the URL). The request was sent, so
1314
+ // the token may already be consumed.
1315
+ console.error(`Error: could not reach the hub at ${redactUrl(hubUrl)} (${fetchErrorLabel(err)}). ${PAIR_TOKEN_MAYBE_CONSUMED}`);
1316
+ process.exit(1);
1317
+ }
1183
1318
  if (!res.ok) {
1184
1319
  const text = await res.text().catch(() => "");
1185
- const hubDenial = rewriteFederationPairHubAccessError(res.status, hubUrl, text);
1320
+ const hubDenial = rewriteFederationPairHubAccessError(res.status, redactUrl(hubUrl), text);
1186
1321
  if (hubDenial) {
1187
1322
  console.error(`Error: ${hubDenial.message}`);
1188
1323
  process.exit(1);
@@ -1209,42 +1344,54 @@ export function register(program) {
1209
1344
  // never runs. Previously this was gated on `if (adminPass)` and the write
1210
1345
  // result was never checked — pairing with only an agent key (or a failed
1211
1346
  // upsert) left no peer behind a misleadingly green "✅ Paired".
1212
- const adminPass = opts.adminPass ?? process.env.FLAIR_ADMIN_PASS ?? process.env.HDB_ADMIN_PASSWORD ?? "";
1213
- if (!adminPass) {
1214
- console.error("Error: paired on the hub, but the local hub-peer record needs admin auth to write — " +
1215
- "pass --admin-pass, or set FLAIR_ADMIN_PASS / HDB_ADMIN_PASSWORD, then re-run pair. " +
1216
- "Without it, 'flair federation sync' will report 'No hub peer configured'.");
1347
+ // flair#1875: the admin credential was resolved and preflighted BEFORE the
1348
+ // hub request, so reaching here means it was accepted. A rejected write
1349
+ // (or a failed upsert) is a genuine post-pair failure: the token is gone.
1350
+ let peerRes;
1351
+ try {
1352
+ peerRes = await fetch(`${opsEndpoint}/`, {
1353
+ method: "POST",
1354
+ headers: { "Content-Type": "application/json", Authorization: auth },
1355
+ body: JSON.stringify({
1356
+ operation: "upsert", database: "flair", table: "Peer",
1357
+ records: [{
1358
+ id: resolvedHub.peer.id,
1359
+ publicKey: resolvedHub.peer.publicKey,
1360
+ role: "hub", endpoint: hubUrl, status: "paired",
1361
+ pairedAt: new Date().toISOString(),
1362
+ createdAt: new Date().toISOString(),
1363
+ updatedAt: new Date().toISOString(),
1364
+ }],
1365
+ }),
1366
+ signal: AbortSignal.timeout(10_000),
1367
+ });
1368
+ }
1369
+ catch (err) {
1370
+ // A THROWN upsert (network error) after the hub returned 200 is the same
1371
+ // post-pair failure as an HTTP error: the token is already consumed.
1372
+ // Name the error, never print its message (the ops URL is user-supplied).
1373
+ console.error(`Error: paired on the hub, but writing the local hub-peer record failed ` +
1374
+ `(${fetchErrorLabel(err)}). ${PAIR_TOKEN_CONSUMED}`);
1217
1375
  process.exit(1);
1218
1376
  }
1219
- const auth = `Basic ${Buffer.from(`${resolveAdminUser(opts.adminUser)}:${adminPass}`).toString("base64")}`;
1220
- const opsEndpoint = resolveEffectiveOpsUrl(opts) ?? `http://127.0.0.1:${resolveOpsPort(opts)}`;
1221
- const peerRes = await fetch(`${opsEndpoint}/`, {
1222
- method: "POST",
1223
- headers: { "Content-Type": "application/json", Authorization: auth },
1224
- body: JSON.stringify({
1225
- operation: "upsert", database: "flair", table: "Peer",
1226
- records: [{
1227
- id: resolvedHub.peer.id,
1228
- publicKey: resolvedHub.peer.publicKey,
1229
- role: "hub", endpoint: hubUrl, status: "paired",
1230
- pairedAt: new Date().toISOString(),
1231
- createdAt: new Date().toISOString(),
1232
- updatedAt: new Date().toISOString(),
1233
- }],
1234
- }),
1235
- signal: AbortSignal.timeout(10_000),
1236
- });
1237
1377
  if (!peerRes.ok) {
1238
1378
  const text = await peerRes.text().catch(() => "");
1239
- console.error(`Error: paired with the hub but failed to write the local hub-peer record ` +
1240
- `(${peerRes.status} ${text.slice(0, 200)}). Ops endpoint: ${opsEndpoint}. ` +
1241
- `'flair federation sync' will not find the hub until this succeeds — check --admin-pass and the ops port.`);
1379
+ console.error(`Error: paired on the hub, but writing the local hub-peer record failed ` +
1380
+ `(${peerRes.status} ${text.slice(0, 200)}). ${PAIR_TOKEN_CONSUMED}`);
1242
1381
  process.exit(1);
1243
1382
  }
1244
1383
  console.log(`✅ Recorded hub as local peer: ${resolvedHub.peer.id} → ${hubUrl}`);
1245
1384
  }
1246
1385
  catch (err) {
1247
- console.error(`Error: ${err.message}`);
1386
+ // A rejected fetch to a user-supplied URL can carry the full URL —
1387
+ // credentials included — in err.message, so for fetch-shaped errors
1388
+ // print the code/name instead. Append whether the hub was contacted: if
1389
+ // the identity GET (or anything before the hub fetch) failed, nothing
1390
+ // reached the hub and the token is untouched.
1391
+ const tail = hubContacted ? PAIR_TOKEN_CONSUMED : NOTHING_SENT_TO_HUB;
1392
+ const name = typeof err?.name === "string" ? err.name : "";
1393
+ const fetchShaped = name === "TypeError" || name === "AbortError" || name === "TimeoutError";
1394
+ console.error(`Error: ${fetchShaped ? fetchErrorLabel(err) : redactMessage(String(err?.message ?? err))}. ${tail}`);
1248
1395
  process.exit(1);
1249
1396
  }
1250
1397
  });
@@ -1,8 +1,8 @@
1
- import { homedir } from "node:os";
2
1
  import * as render from "../render.js";
3
2
  import { unpinnedSpecWarning } from "../lib/mcp-spec.js";
4
3
  import { probeSessionStartHookDelivery, readClientMcpBlock } from "../doctor-client.js";
5
4
  import { installHook, uninstallHook, hookStatus, hookStatusHeadline, hookStatusFailureLine, hookStatusIdentityLines, HOOK_STATUS_UNPARSED, installContinuityHooks, uninstallContinuityHooks, continuityHookStatus, isSupportedHarness, SUPPORTED_HARNESSES, hookInstallHint, harnessSupportsContinuity, resolveHookAgentId, } from "../hook-install.js";
5
+ import { resolveHome } from "../lib/home.js";
6
6
  let cli;
7
7
  /** Bind shared CLI helpers. cli.ts calls this immediately before register(program). */
8
8
  export function bindCli(fns) {
@@ -51,7 +51,7 @@ export function register(program) {
51
51
  .option("--continuity", "Wire the continuity capture hooks instead (PostToolUse + Stop — flair#1257; installing them IS the opt-in)")
52
52
  .action((opts) => {
53
53
  const harness = requireSupportedHarness(opts.harness);
54
- const home = homedir();
54
+ const home = resolveHome();
55
55
  const agentId = resolveHookAgentId(opts, home, harness);
56
56
  if (!agentId) {
57
57
  console.error("No agent id known — pass --agent <id>, set FLAIR_AGENT_ID, or run `flair init` / `flair agent add` first.");
@@ -98,7 +98,7 @@ export function register(program) {
98
98
  .option("--continuity", "Remove the continuity capture hooks instead (PostToolUse + Stop — flair#1257)")
99
99
  .action((opts) => {
100
100
  const harness = requireSupportedHarness(opts.harness);
101
- const home = homedir();
101
+ const home = resolveHome();
102
102
  const dryRun = !!opts.dryRun;
103
103
  if (opts.continuity) {
104
104
  const result = uninstallContinuityHooks({ homeDir: home, harness, dryRun });
@@ -132,7 +132,7 @@ export function register(program) {
132
132
  .option("--harness <name>", `Target harness (${SUPPORTED_HARNESSES.join(", ")})`, "claude-code")
133
133
  .action((opts) => {
134
134
  const harness = requireSupportedHarness(opts.harness);
135
- const home = homedir();
135
+ const home = resolveHome();
136
136
  const status = hookStatus(home, harness, {
137
137
  deliveryProbe: (command) => probeSessionStartHookDelivery(command),
138
138
  });
@@ -4,14 +4,15 @@ import { claudeCodeMcpEntry, detectClients, renderWiringSummary, wireAntigravity
4
4
  import { DEFAULT_ADMIN_USER, authFetch, defaultAdminPassPath, defaultKeysDir, readAdminPassFileSecure, resolveAdminUser } from "../lib/auth-resolve.js";
5
5
  import { detectPersistedAdminUser, executeAdminPasswordRotate, initAdminPassRefusalMessage, resolveInitAdminPasswordRefuseReason, resolveInitAdminPasswordSource, } from "../lib/init-admin-pass.js";
6
6
  import { mcpServerSpec, unpinnedSpecWarning } from "../lib/mcp-spec.js";
7
+ import { opsSocketPathRefusal } from "../lib/socket-path-limit.js";
7
8
  import * as render from "../render.js";
8
9
  import { execSync, spawn } from "node:child_process";
9
10
  import { randomBytes, randomUUID } from "node:crypto";
10
11
  import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
11
- import { homedir } from "node:os";
12
- import { join } from "node:path";
12
+ import { join, resolve } from "node:path";
13
13
  import nacl from "tweetnacl";
14
14
  import { httpCorsAccessList } from "../lib/http-bind.js";
15
+ import { resolveHome } from "../lib/home.js";
15
16
  let cli;
16
17
  /** Bind the cli-locals this module depends on. */
17
18
  export function bindCli(fns) {
@@ -198,7 +199,7 @@ export function register(program) {
198
199
  flairAdminPass = randomBytes(24).toString("base64url");
199
200
  }
200
201
  // Write the flair admin pass to secrets directory
201
- const secretsDir = join(homedir(), ".tps", "secrets");
202
+ const secretsDir = join(resolveHome(), ".tps", "secrets");
202
203
  mkdirSync(secretsDir, { recursive: true });
203
204
  const secretPath = join(secretsDir, "flair-fabric-hdb");
204
205
  writeFileSync(secretPath, flairAdminPass + "\n", { mode: 0o600 });
@@ -329,7 +330,7 @@ export function register(program) {
329
330
  const displayTarget = target || opsTarget;
330
331
  console.log(`\n✓ Flair hub deployed to ${displayTarget}`);
331
332
  console.log(` Component: flair@${flavor}`);
332
- console.log(` Admin user: ${adminUser} (pass written to ${join(homedir(), ".tps", "secrets", "flair-fabric-hdb")})`);
333
+ console.log(` Admin user: ${adminUser} (pass written to ${join(resolveHome(), ".tps", "secrets", "flair-fabric-hdb")})`);
333
334
  if (instanceId)
334
335
  console.log(` Instance: ${instanceId} (role=${role})`);
335
336
  console.log(` Federation: ready — run \`flair federation token\` to mint a pairing token`);
@@ -349,7 +350,28 @@ export function register(program) {
349
350
  }
350
351
  // ── Local init (full one-command setup) ──
351
352
  const keysDir = opts.keysDir ?? defaultKeysDir();
352
- const dataDir = opts.dataDir ?? defaultDataDir();
353
+ // Resolve ONCE, here: the operator means "relative to my shell's cwd", but
354
+ // Harper is spawned with cwd = the flair package directory, so a raw
355
+ // relative `--data-dir r` would make Harper bind
356
+ // <flairPackageDir>/r/operations-server — a different path from the one the
357
+ // preflight measured. Every downstream use (preflight, config/plist,
358
+ // ROOTPATH / HARPER_SET_CONFIG, messages) takes this resolved value.
359
+ const dataDir = opts.dataDir ? resolve(opts.dataDir) : defaultDataDir();
360
+ // flair#916: the Harper operations API is a Unix domain socket at
361
+ // `<data-dir>/operations-server`, and Unix socket paths are capped by
362
+ // `sun_path` (darwin 104 / linux 108, counting the trailing NUL, so the
363
+ // USABLE length is 103 / 107). A long `--data-dir` pushes the socket past
364
+ // the cap, and Harper then dies with a bare `listen EINVAL` that names
365
+ // neither the socket nor the limit — the worst moment (first run, no
366
+ // working install to compare against). Refuse HERE, before any install,
367
+ // config write, keypair, or Harper start: a refusal must leave nothing on
368
+ // disk. The socket path is built exactly as Harper binds it (join with the
369
+ // fixed "operations-server" suffix), so the measured length is the real one.
370
+ const socketRefusal = opsSocketPathRefusal(dataDir, process.platform);
371
+ if (socketRefusal) {
372
+ console.error(socketRefusal);
373
+ process.exit(1);
374
+ }
353
375
  // "create" mode (flair#914): init ESTABLISHES an instance, so a data
354
376
  // directory with no recorded port is a new instance taking the default,
355
377
  // not the hard error every other caller gets — otherwise `flair init
@@ -1113,7 +1135,7 @@ export function register(program) {
1113
1135
  // automatically here (same "just do it" shape as the MCP block
1114
1136
  // above); --skip-claude-md opts out and prints the exact line to
1115
1137
  // add by hand instead.
1116
- const claudeMdResult = applyOrReportClaudeMdBootstrap(process.cwd(), homedir(), !!opts.skipClaudeMd);
1138
+ const claudeMdResult = applyOrReportClaudeMdBootstrap(process.cwd(), resolveHome(), !!opts.skipClaudeMd);
1117
1139
  console.log(` ${claudeMdResult.ok ? "✓" : "•"} ${claudeMdResult.message}`);
1118
1140
  if (claudeMdResult.hint) {
1119
1141
  for (const line of claudeMdResult.hint.split("\n"))
@@ -1124,7 +1146,7 @@ export function register(program) {
1124
1146
  // ~/.claude/settings.json — without it, mcp__flair__bootstrap only
1125
1147
  // ever runs if the agent remembers to call it itself.
1126
1148
  // --skip-hook opts out and prints the exact JSON to add by hand.
1127
- const hookResult = applyOrReportSessionStartHook(homedir(), agentId, !!opts.skipHook);
1149
+ const hookResult = applyOrReportSessionStartHook(resolveHome(), agentId, !!opts.skipHook);
1128
1150
  console.log(` ${hookResult.ok ? "✓" : "•"} ${hookResult.message}`);
1129
1151
  if (hookResult.hint) {
1130
1152
  for (const line of hookResult.hint.split("\n"))
@@ -1165,7 +1187,7 @@ export function register(program) {
1165
1187
  // consent to set up the client, same as the Claude Code hook
1166
1188
  // applied above. --skip-hook opts out and prints the JSON.
1167
1189
  if (clientId === "codex" && result.ok) {
1168
- const hookResult = applyOrReportSessionStartHook(homedir(), agentId, !!opts.skipHook, hookSettingsPath(homedir(), "codex"));
1190
+ const hookResult = applyOrReportSessionStartHook(resolveHome(), agentId, !!opts.skipHook, hookSettingsPath(resolveHome(), "codex"));
1169
1191
  console.log(` ${hookResult.ok ? "✓" : "•"} ${hookResult.message}`);
1170
1192
  if (hookResult.hint) {
1171
1193
  for (const line of hookResult.hint.split("\n"))
@@ -1,11 +1,11 @@
1
1
  import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
- import { homedir } from "node:os";
3
2
  import { dirname, join } from "node:path";
4
3
  import nacl from "tweetnacl";
5
4
  import * as render from "../render.js";
6
5
  import { defaultKeysDir, resolveAdminUser, resolveLocalAdminPass } from "../lib/auth-resolve.js";
7
6
  import { resolveAgentKeyPath, loadEd25519PrivateKeyFromFile, signClientAssertion, buildTokenRequestForm, getMcpAccessToken, McpTokenRequestError, defaultMcpClientId, defaultMcpTokenEndpoint, defaultMcpResource, defaultMcpIssuer, MAX_ASSERTION_LIFETIME_SECONDS, } from "../mcp-client-assertion.js";
8
7
  import { enableMcp, disableMcp, mcpStatus, checkLocalOriginRefusal, selfVerifyMcpMetadata, } from "../lib/mcp-enable.js";
8
+ import { resolveHome } from "../lib/home.js";
9
9
  let cli;
10
10
  /** Bind shared CLI helpers. cli.ts calls this immediately before register(program). */
11
11
  export function bindCli(fns) {
@@ -27,7 +27,7 @@ function b64url(bytes) {
27
27
  * admin-pass/config.yaml — independent of --keys-dir (a custom keys dir
28
28
  * doesn't imply a custom manifest location, and vice versa). */
29
29
  export function defaultMcpClientManifestPath() {
30
- return join(homedir(), ".flair", "mcp-clients.json");
30
+ return join(resolveHome(), ".flair", "mcp-clients.json");
31
31
  }
32
32
  /** Read the manifest; a missing file is "no clients granted yet", not an
33
33
  * error. Malformed JSON is also treated as empty (defensive — a corrupt
@@ -2,8 +2,8 @@ import { authFetch, resolveAdminUser } from "../lib/auth-resolve.js";
2
2
  import { load as parseYaml } from "js-yaml";
3
3
  import { randomUUID } from "node:crypto";
4
4
  import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync } from "node:fs";
5
- import { homedir } from "node:os";
6
5
  import { join, resolve, sep } from "node:path";
6
+ import { resolveHome } from "../lib/home.js";
7
7
  let cli;
8
8
  /** Bind the cli-locals this module depends on. */
9
9
  export function bindCli(fns) {
@@ -17,9 +17,9 @@ function resolveMemoryDir(target, agentId) {
17
17
  case "claude-code": {
18
18
  const cwd = process.cwd();
19
19
  const encodedCwd = encodeURIComponent(cwd).replace(/%2F/g, "/");
20
- const memoryDir = join(homedir(), ".claude", "projects", encodedCwd, "memory");
20
+ const memoryDir = join(resolveHome(), ".claude", "projects", encodedCwd, "memory");
21
21
  const resolved = resolve(memoryDir);
22
- const expectedRoot = join(homedir(), ".claude", "projects");
22
+ const expectedRoot = join(resolveHome(), ".claude", "projects");
23
23
  if (!resolved.startsWith(expectedRoot + sep)) {
24
24
  throw new Error(`Memory dir must be within ${expectedRoot}, got ${resolved}`);
25
25
  }
@@ -28,9 +28,9 @@ function resolveMemoryDir(target, agentId) {
28
28
  case "openclaw": {
29
29
  const cwd = process.cwd();
30
30
  const encodedCwd = encodeURIComponent(cwd).replace(/%2F/g, "/");
31
- const memoryDir = join(homedir(), ".openclaw", "projects", encodedCwd, "memory");
31
+ const memoryDir = join(resolveHome(), ".openclaw", "projects", encodedCwd, "memory");
32
32
  const resolved = resolve(memoryDir);
33
- const expectedRoot = join(homedir(), ".openclaw", "projects");
33
+ const expectedRoot = join(resolveHome(), ".openclaw", "projects");
34
34
  if (!resolved.startsWith(expectedRoot + sep)) {
35
35
  throw new Error(`Memory dir must be within ${expectedRoot}, got ${resolved}`);
36
36
  }
@@ -39,9 +39,9 @@ function resolveMemoryDir(target, agentId) {
39
39
  case "pi": {
40
40
  const cwd = process.cwd();
41
41
  const encodedCwd = encodeURIComponent(cwd).replace(/%2F/g, "/");
42
- const memoryDir = join(homedir(), ".pi", "projects", encodedCwd, "memory");
42
+ const memoryDir = join(resolveHome(), ".pi", "projects", encodedCwd, "memory");
43
43
  const resolved = resolve(memoryDir);
44
- const expectedRoot = join(homedir(), ".pi", "projects");
44
+ const expectedRoot = join(resolveHome(), ".pi", "projects");
45
45
  if (!resolved.startsWith(expectedRoot + sep)) {
46
46
  throw new Error(`Memory dir must be within ${expectedRoot}, got ${resolved}`);
47
47
  }
@@ -187,7 +187,7 @@ export function register(program) {
187
187
  try {
188
188
  const httpUrl = `http://127.0.0.1:${resolveHttpPort({})}`;
189
189
  const agentKeyId = `${agentId}.key`;
190
- const keysDir = join(homedir(), ".flair", "keys");
190
+ const keysDir = join(resolveHome(), ".flair", "keys");
191
191
  const keyPath = join(keysDir, agentKeyId);
192
192
  let authSuccess = false;
193
193
  if (existsSync(keyPath)) {
@@ -1,9 +1,9 @@
1
1
  import { existsSync, mkdirSync, writeFileSync, rmSync } from "node:fs";
2
- import { homedir } from "node:os";
3
2
  import { dirname, resolve } from "node:path";
4
3
  import * as render from "../render.js";
5
4
  import { isLocalBase, resolveAdminUser, resolveLocalAdminPass } from "../lib/auth-resolve.js";
6
5
  import { validatePromoteOpts, validateRejectOpts, decideCandidateAction, derivePromotedTags, validateHumanReviewerId, structuralImbalance, hasTerminalPunctuation, } from "../rem/promote-policy.js";
6
+ import { resolveHome } from "../lib/home.js";
7
7
  export { validatePromoteOpts, validateRejectOpts, decideCandidateAction, derivePromotedTags, derivePromotedVisibility, validateHumanReviewerId, isMachineReviewerId, ADK_SCOPE_TAG_PREFIX, CONTINUITY_SCOPE_TAG_PREFIX, MACHINE_REVIEWER_PREFIX, MACHINE_REVIEWER_ADK_AUTO_PROMOTE, } from "../rem/promote-policy.js";
8
8
  let cli;
9
9
  /** Bind shared CLI helpers. cli.ts calls this immediately before register(program). */
@@ -120,7 +120,7 @@ export function describeReflectError(message) {
120
120
  }
121
121
  return { kind: "other", text: message };
122
122
  }
123
- const REM_PAUSE_FLAG = resolve(homedir(), ".flair", "rem.paused");
123
+ const REM_PAUSE_FLAG = resolve(resolveHome(), ".flair", "rem.paused");
124
124
  function writeRemPauseSentinel() {
125
125
  const dir = dirname(REM_PAUSE_FLAG);
126
126
  if (!existsSync(dir))
@@ -1,6 +1,7 @@
1
1
  import { DEFAULT_ADMIN_USER } from "../lib/auth-resolve.js";
2
2
  import { classifyDaemonState } from "../lib/daemon-liveness.js";
3
3
  import { diagnoseLaunchdPlistPaths, isDetached, renderDetachedWarning } from "../lib/launchd-management.js";
4
+ import { opsSocketPathRefusal } from "../lib/socket-path-limit.js";
4
5
  import { spawn } from "node:child_process";
5
6
  import { existsSync } from "node:fs";
6
7
  import { join } from "node:path";
@@ -165,6 +166,17 @@ export function register(program) {
165
166
  .action(async (opts) => {
166
167
  const port = resolveHttpPort(opts);
167
168
  const dataDir = defaultDataDir();
169
+ // flair#916: the operations socket is a Unix domain socket whose path is
170
+ // capped by sun_path (darwin 103 / linux 107, NUL-excluded); a too-long
171
+ // data dir would make Harper die with a bare `listen EINVAL` on boot.
172
+ // This command uses the hardcoded defaultDataDir() today, so the limit is
173
+ // unreachable here — the preflight is defensive against a future
174
+ // --data-dir or a lengthened default. Refuse before touching disk.
175
+ const socketRefusal = opsSocketPathRefusal(dataDir, process.platform);
176
+ if (socketRefusal) {
177
+ console.error(socketRefusal);
178
+ process.exit(1);
179
+ }
168
180
  // Already-running check via the five-state liveness machine (flair#1454).
169
181
  // The old check was a bare `fetch /Health` that treated "got a response"
170
182
  // as "already running" and exited 0 — half of #1454. Now the machine
@@ -295,8 +307,20 @@ export function register(program) {
295
307
  // Explicit, not defaulted inside restartFlair (flair#902): `flair
296
308
  // restart` has no --data-dir, so the default install IS what it means —
297
309
  // and saying so here is what keeps that true when someone adds one.
310
+ // flair#916: the same defensive preflight `flair start` runs — the
311
+ // operations socket path is capped by sun_path; refuse here, before a
312
+ // restart touches the instance, rather than let Harper die with a bare
313
+ // `listen EINVAL` on boot. `restart` uses the hardcoded defaultDataDir()
314
+ // today, so the limit is unreachable; this is defense against a future
315
+ // --data-dir or a lengthened default.
316
+ const dataDir = defaultDataDir();
317
+ const socketRefusal = opsSocketPathRefusal(dataDir, process.platform);
318
+ if (socketRefusal) {
319
+ console.error(socketRefusal);
320
+ process.exit(1);
321
+ }
298
322
  try {
299
- await restartFlair(port, defaultDataDir());
323
+ await restartFlair(port, dataDir);
300
324
  // flair#1022: a restart that fell back off launchd left the instance
301
325
  // running but unmanaged, and "✅ Flair restarted" was true of both
302
326
  // outcomes. Ask launchd what it is actually running now — an
@@ -1,8 +1,8 @@
1
1
  import { existsSync, mkdirSync, writeFileSync, readFileSync, chmodSync, rmSync, readdirSync, statSync } from "node:fs";
2
- import { homedir } from "node:os";
3
2
  import { resolve } from "node:path";
4
3
  import { create as tarCreate, extract as tarExtract, list as tarList } from "tar";
5
4
  import { validateSnapshotArchive } from "../lib/safe-snapshot-extract.js";
5
+ import { resolveHome } from "../lib/home.js";
6
6
  let cli;
7
7
  /** Bind shared CLI helpers. cli.ts calls this immediately before register(program). */
8
8
  export function bindCli(fns) {
@@ -21,7 +21,7 @@ export function register(program) {
21
21
  //
22
22
  // Standalone-callable today; harness slices 3+4 will wire it into the
23
23
  // session-reset pipeline.
24
- const SNAPSHOT_ROOT = resolve(homedir(), ".flair", "snapshots");
24
+ const SNAPSHOT_ROOT = resolve(resolveHome(), ".flair", "snapshots");
25
25
  function sessionSnapshotDir(agent) {
26
26
  if (!/^[a-zA-Z0-9_-]+$/.test(agent))
27
27
  throw new Error(`invalid agent id: ${agent}`);
@@ -1,6 +1,6 @@
1
1
  import { formatPurgeReport, purgeFlairInstall, purgeHadFailures } from "../lib/uninstall-purge.js";
2
2
  import { existsSync, unlinkSync } from "node:fs";
3
- import { homedir } from "node:os";
3
+ import { resolveHome } from "../lib/home.js";
4
4
  let cli;
5
5
  /** Bind the cli-locals this module depends on. */
6
6
  export function bindCli(fns) {
@@ -127,7 +127,7 @@ export function register(program) {
127
127
  console.log("Stop the process manually, then re-run: flair uninstall --purge");
128
128
  }
129
129
  else {
130
- const home = process.env.HOME ?? homedir();
130
+ const home = resolveHome();
131
131
  const result = purgeFlairInstall({ homeDir: home });
132
132
  const report = formatPurgeReport(result);
133
133
  console.log(report.lines.join("\n"));
@@ -16,10 +16,10 @@ import { probeInstance } from "../probe.js";
16
16
  import * as render from "../render.js";
17
17
  import { FLAIR_PKG_NAME, primeVersionCheckCache } from "../version-check.js";
18
18
  import { chmodSync, existsSync, lstatSync, mkdirSync, readdirSync, realpathSync, rmSync, statSync } from "node:fs";
19
- import { homedir } from "node:os";
20
19
  import { join, resolve, sep } from "node:path";
21
20
  import { create as tarCreate } from "tar";
22
21
  import { classifyInstalledVersion, formatUpgradeStatusLine } from "../lib/upgrade-status.js";
22
+ import { resolveHome } from "../lib/home.js";
23
23
  let cli;
24
24
  /** Bind the cli-locals this module depends on. */
25
25
  export function bindCli(fns) {
@@ -922,7 +922,7 @@ export function register(program) {
922
922
  // the NORMAL state, not "missing". Resolve it from its actual wiring
923
923
  // (the pin in a client MCP config / the SessionStart hook) so the
924
924
  // listing is truthful and the remedy actually works (flair#1208).
925
- const home = process.env.HOME ?? homedir();
925
+ const home = resolveHome();
926
926
  ({ installed, status } = resolveFlairMcpFinding(globalProbe, latest, detectWiredFlairMcp(home)));
927
927
  }
928
928
  else {
@@ -1048,7 +1048,7 @@ export function register(program) {
1048
1048
  // client's env — rewriting each client's FLAIR_AGENT_ID to whichever key
1049
1049
  // happened to sort first. The writer preserves each entry's own identity
1050
1050
  // and changes only the pinned package argument.
1051
- const homeDir = process.env.HOME || process.env.USERPROFILE || homedir();
1051
+ const homeDir = resolveHome();
1052
1052
  const results = refreshOwnedPins({ homeDir });
1053
1053
  const noteworthy = results.filter(ownedPinRefreshShouldReport);
1054
1054
  if (noteworthy.length === 0)