@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
@@ -22,6 +22,7 @@
22
22
  import { spawnSync } from "node:child_process";
23
23
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
24
24
  import { dirname, join } from "node:path";
25
+ import { withHome } from "./lib/home.js";
25
26
  import { ALL_CLIENTS, clientConfigPath, piSettingsPath, resolvePiExtensionPath, scanPiSettings, } from "./install/clients.js";
26
27
  import { FLAIR_MCP_PACKAGE, flairCliVersion, mcpServerSpec } from "./lib/mcp-spec.js";
27
28
  import { decidePinWrite } from "./lib/pin-write-guard.js";
@@ -579,29 +580,10 @@ export function removeContinuityCaptureHooks(homeDir) {
579
580
  }
580
581
  }
581
582
  // ── shared helpers ──────────────────────────────────────────────────────────
582
- /**
583
- * Run `fn` with process.env.HOME temporarily pointed at `homeDir`, then
584
- * restore it. clientConfigPath() (src/install/clients.ts) resolves the home
585
- * dir via HOME/USERPROFILE at call time (not cached), so this lets us reuse
586
- * that single source of truth for per-client config paths while keeping
587
- * doctor-client's own functions parameterized by an explicit homeDir for
588
- * tests — no test ever touches the real ~/.claude.json etc. The override is
589
- * synchronous and restored before this function returns, so it's safe even
590
- * though process.env is process-global.
591
- */
592
- function withHome(homeDir, fn) {
593
- const prev = process.env.HOME;
594
- process.env.HOME = homeDir;
595
- try {
596
- return fn();
597
- }
598
- finally {
599
- if (prev === undefined)
600
- delete process.env.HOME;
601
- else
602
- process.env.HOME = prev;
603
- }
604
- }
583
+ // `withHome()` (src/lib/home.ts) points HOME and USERPROFILE at an explicit
584
+ // homeDir for a synchronous callback; clientConfigPath() (src/install/clients.ts)
585
+ // resolves the home at call time, so doctor-client's explicit-homeDir functions
586
+ // reuse that single source of truth and no test touches the real ~/.claude.json.
605
587
  function readTextFile(path) {
606
588
  try {
607
589
  if (!existsSync(path))
@@ -18,12 +18,12 @@
18
18
  // the engine cannot boot, we still need to read it.
19
19
  import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
20
20
  import { join, resolve } from "node:path";
21
- import { homedir } from "node:os";
22
21
  import { fetchDeclaredDependencies } from "./lib/npm-registry.js";
22
+ import { resolveHome } from "./lib/home.js";
23
23
  /** Filename of the engine-version stamp inside the data directory. */
24
24
  export const ENGINE_VERSION_STAMP = "engine-version.txt";
25
25
  /** Root directory for pre-upgrade snapshots (~/.flair/upgrade-snapshots). */
26
- export const UPGRADE_SNAPSHOT_ROOT = resolve(homedir(), ".flair", "upgrade-snapshots");
26
+ export const UPGRADE_SNAPSHOT_ROOT = resolve(resolveHome(), ".flair", "upgrade-snapshots");
27
27
  /** Read the Harper version installed alongside this flair package. */
28
28
  export function readInstalledHarperVersion(packageRoot) {
29
29
  for (const name of ["harper", "@harperfast/harper"]) {
@@ -59,16 +59,16 @@
59
59
  */
60
60
  import { existsSync, chmodSync, rmSync, readFileSync, mkdirSync } from "node:fs";
61
61
  import { resolve, dirname } from "node:path";
62
- import { homedir } from "node:os";
63
62
  import { fileURLToPath } from "node:url";
64
63
  import { escapeXml } from "../lib/xml-escape.js";
65
64
  import { detectPlatform as detectPlatformFor, spawnReport, readTemplate, renderTemplateWith, writeFileWithDir, interpretActiveResult, describeLoadFailure as describeLoadFailureFor, describeExitCode, resolveNodeBin, resolveFlairBin, formatFlairBinWarning, verifyFirstRun, probeUserLingerEnabled, STATUS_CHECK_TIMEOUT_MS, } from "../lib/scheduler-platform.js";
65
+ import { resolveHome } from "../lib/home.js";
66
66
  export const LAUNCHD_LABEL = "dev.flair.federation.sync";
67
67
  export const SYSTEMD_TIMER_UNIT = "flair-federation-sync.timer";
68
68
  export const SYSTEMD_SERVICE_UNIT = "flair-federation-sync.service";
69
- export const SHIM_PATH_DEFAULT = resolve(homedir(), ".flair", "bin", "flair-federation-sync");
70
- export const LAUNCHD_PLIST_PATH = resolve(homedir(), "Library", "LaunchAgents", `${LAUNCHD_LABEL}.plist`);
71
- export const SYSTEMD_USER_DIR = resolve(homedir(), ".config", "systemd", "user");
69
+ export const SHIM_PATH_DEFAULT = resolve(resolveHome(), ".flair", "bin", "flair-federation-sync");
70
+ export const LAUNCHD_PLIST_PATH = resolve(resolveHome(), "Library", "LaunchAgents", `${LAUNCHD_LABEL}.plist`);
71
+ export const SYSTEMD_USER_DIR = resolve(resolveHome(), ".config", "systemd", "user");
72
72
  export const SYSTEMD_TIMER_PATH = resolve(SYSTEMD_USER_DIR, SYSTEMD_TIMER_UNIT);
73
73
  export const SYSTEMD_SERVICE_PATH = resolve(SYSTEMD_USER_DIR, SYSTEMD_SERVICE_UNIT);
74
74
  /** Default seconds between one-shot syncs. See the module header for why 300. */
@@ -143,7 +143,7 @@ function buildSubstitutions(opts, shimPath, flairBin, nodeBin) {
143
143
  FLAIR_BIN: flairBin,
144
144
  NODE_BIN: nodeBin,
145
145
  SHIM_PATH: shimPath,
146
- HOME: opts.homeOverride ?? homedir(),
146
+ HOME: opts.homeOverride ?? resolveHome(),
147
147
  INTERVAL_SECONDS: String(opts.intervalSeconds),
148
148
  ADMIN_PASS_FILE: adminPassFile,
149
149
  FLAIR_TARGET: opts.target ?? "",
@@ -20,8 +20,8 @@
20
20
  // per-client locations under $HOME / $XDG_CONFIG_HOME.
21
21
  // ---- Detection helpers ----------------------------------------------------------
22
22
  import { accessSync, constants, existsSync, mkdirSync } from "node:fs";
23
- import { homedir } from "node:os";
24
23
  import { dirname, join } from "node:path";
24
+ import { resolveHome } from "../lib/home.js";
25
25
  import { FLAIR_MCP_PACKAGE, flairCliVersion, isResolvedVersion, mcpServerSpec } from "../lib/mcp-spec.js";
26
26
  import { decodeWiringSpec, wiringPinString } from "../lib/wiring-spec.js";
27
27
  import { decidePinWrite } from "../lib/pin-write-guard.js";
@@ -44,15 +44,10 @@ function manualWireMessage(label, display, reason, env) {
44
44
  return (`${label}: manual wiring needed (could not write ${display}: ${reason}).\n` +
45
45
  ` Add this to ${display}:\n${indent(jsonSnippet(env))}`);
46
46
  }
47
- /**
48
- * Resolve the user's home dir. Prefer the live HOME/USERPROFILE env over
49
- * os.homedir(), which caches the value at process start and so ignores a
50
- * runtime HOME override — same convention as src/cli.ts ("so tests can
51
- * override"). Production behavior is unchanged (HOME is set on every OS).
52
- */
53
- export function resolveHome() {
54
- return process.env.HOME || process.env.USERPROFILE || homedir();
55
- }
47
+ // The shared home resolver (src/lib/home.ts, flair#1853 round 3): resolved at
48
+ // call time, with the platform rule (Windows -> USERPROFILE, elsewhere -> HOME).
49
+ // Re-exported so importers of this module keep their existing entry point.
50
+ export { resolveHome };
56
51
  /**
57
52
  * Check if a command exists in PATH (cross-platform alternative to `which`).
58
53
  * Does not spawn a child process — pure filesystem check.
package/dist/keystore.js CHANGED
@@ -10,11 +10,19 @@
10
10
  */
11
11
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
12
12
  import { join } from "node:path";
13
- import { homedir } from "node:os";
13
+ import { resolveHome } from "./lib/home.js";
14
14
  import { randomBytes, createCipheriv, createDecipheriv, hkdfSync, } from "node:crypto";
15
15
  // ─── Helpers ────────────────────────────────────────────────────────────────
16
+ /**
17
+ * The keystore's home comes from the ONE shared resolver (src/lib/home.ts,
18
+ * flair#1853 round 3): resolved at CALL time, with the platform rule (Windows
19
+ * uses USERPROFILE, everywhere else HOME). The runtime caches `os.homedir()` at
20
+ * process start, so a HOME set after start — the test harness in
21
+ * test/helpers/sandbox-home.ts — would otherwise be invisible and the keystore
22
+ * would reach the REAL ~/.flair/keys.
23
+ */
16
24
  function keysDir() {
17
- return join(homedir(), ".flair", "keys");
25
+ return join(resolveHome(), ".flair", "keys");
18
26
  }
19
27
  function keyPath(instanceId) {
20
28
  // Sanitize instanceId to prevent directory traversal
@@ -63,9 +63,9 @@
63
63
  * conflict (`--admin-pass` + `--agent`) is never quiet either.
64
64
  */
65
65
  import { existsSync, readFileSync, readdirSync, statSync, } from "node:fs";
66
- import { homedir } from "node:os";
67
66
  import { join } from "node:path";
68
67
  import { createPrivateKey, randomUUID, sign as nodeCryptoSign } from "node:crypto";
68
+ import { resolveHome } from "./home.js";
69
69
  // ─── Failure classification ─────────────────────────────────────────────────
70
70
  /**
71
71
  * Thrown by `sendJsonRequest` for an HTTP-level failure (as opposed to a
@@ -129,7 +129,7 @@ export function readAdminPassFileSecure(path) {
129
129
  return readSecretFileSecure(path, "--admin-pass-file");
130
130
  }
131
131
  export function defaultAdminPassPath() {
132
- return join(homedir(), ".flair", "admin-pass");
132
+ return join(resolveHome(), ".flair", "admin-pass");
133
133
  }
134
134
  /** The admin username Harper's bootstrap creates and every Basic-auth path
135
135
  * historically hardcoded. Kept as the default; overridable per call via
@@ -160,7 +160,7 @@ export function resolveAdminUser(explicit) {
160
160
  return explicit || process.env.FLAIR_ADMIN_USER || DEFAULT_ADMIN_USER;
161
161
  }
162
162
  export function defaultKeysDir() {
163
- return join(homedir(), ".flair", "keys");
163
+ return join(resolveHome(), ".flair", "keys");
164
164
  }
165
165
  /**
166
166
  * Resolve an admin password for LOCAL-only CLI convenience (`agent add`,
@@ -219,8 +219,8 @@ export function resolveLocalAdminPass(explicit, isRemoteTarget = false, adminPas
219
219
  export function resolveKeyPath(agentId) {
220
220
  const candidates = [
221
221
  process.env.FLAIR_KEY_DIR ? join(process.env.FLAIR_KEY_DIR, `${agentId}.key`) : null,
222
- join(homedir(), ".flair", "keys", `${agentId}.key`),
223
- join(homedir(), ".tps", "secrets", "flair", `${agentId}-priv.key`),
222
+ join(resolveHome(), ".flair", "keys", `${agentId}.key`),
223
+ join(resolveHome(), ".tps", "secrets", "flair", `${agentId}-priv.key`),
224
224
  ].filter(Boolean);
225
225
  return candidates.find((p) => existsSync(p)) ?? null;
226
226
  }
@@ -14,8 +14,8 @@
14
14
  * as "no peers" and the driver check would be silenced — the #1514 hazard).
15
15
  */
16
16
  import { existsSync, readFileSync } from "node:fs";
17
- import { homedir } from "node:os";
18
17
  import { join, resolve } from "node:path";
18
+ import { resolveHome } from "./home.js";
19
19
  const CONFIG_BASENAMES = ["config.yaml", "config.yml"];
20
20
  function configFilesIn(dir) {
21
21
  return CONFIG_BASENAMES.map((name) => join(dir, name));
@@ -27,7 +27,7 @@ function configFilesIn(dir) {
27
27
  */
28
28
  export function flairConfigYamlCandidates(opts = {}) {
29
29
  const cwd = resolve(opts.cwd ?? process.cwd());
30
- const homeDir = opts.homeDir ?? homedir();
30
+ const homeDir = opts.homeDir ?? resolveHome();
31
31
  const out = [...configFilesIn(cwd)];
32
32
  if (opts.componentDir) {
33
33
  const componentDir = resolve(opts.componentDir);
@@ -0,0 +1,29 @@
1
+ /**
2
+ * flair-paths.ts — the home-derived paths every subsystem must agree on (flair#1858).
3
+ *
4
+ * Each of these used to compute `~` itself (`os.homedir()` in cli.ts and
5
+ * backup.ts). `os.homedir()` is cached at process START, so a `HOME` set later in
6
+ * the process — which the keystore and the client writers now honour — was
7
+ * invisible to them, and doctor could inspect a different home from the one the
8
+ * writers used. They all resolve through `resolveHome()` now, with an explicit
9
+ * `home` argument available to tests and callers that already resolved one.
10
+ */
11
+ import { existsSync } from "node:fs";
12
+ import { join } from "node:path";
13
+ import { resolveHome } from "./home.js";
14
+ /** `~/.flair/data` — the instance data dir. */
15
+ export function flairDataDir(home = resolveHome()) {
16
+ return join(home, ".flair", "data");
17
+ }
18
+ /** `~/.flair/config.yaml`, or `config.yml` when only that exists. */
19
+ export function flairConfigPath(home = resolveHome()) {
20
+ const yamlPath = join(home, ".flair", "config.yaml");
21
+ const ymlPath = join(home, ".flair", "config.yml");
22
+ if (existsSync(ymlPath) && !existsSync(yamlPath))
23
+ return ymlPath;
24
+ return yamlPath;
25
+ }
26
+ /** Default `flair backup` output: `~/.flair/backups/flair-backup-<timestamp>.json`. */
27
+ export function flairBackupOutputPath(timestamp, home = resolveHome()) {
28
+ return join(home, ".flair", "backups", `flair-backup-${timestamp}.json`);
29
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * The user's home directory, resolved at CALL time (flair#1853).
3
+ *
4
+ * `os.homedir()` is cached at process start, so a HOME set later in the same
5
+ * process is invisible to it. Every Flair surface that resolves `~` — the
6
+ * keystore and the client config writers — must land on the SAME home, and it
7
+ * must be the one the calling shell actually uses.
8
+ *
9
+ * Which environment variable names that home differs by platform:
10
+ *
11
+ * - **Windows** — `USERPROFILE` is authoritative. Node's `os.homedir()` reads
12
+ * it, but a POSIX-style shell (Git Bash, MSYS, Cygwin) may set `HOME` to a
13
+ * different path. Preferring `HOME` there would move `~/.flair/keys` away
14
+ * from where the keys actually live, so an existing key would read as
15
+ * missing (and a new one would be written somewhere nothing looks).
16
+ * - **Everywhere else** — `HOME` is authoritative (and is how the test harness
17
+ * redirects a process), with `os.homedir()` as the fallback.
18
+ */
19
+ import { homedir } from "node:os";
20
+ /** The home directory for this invocation, resolved at call time. */
21
+ export function resolveHome() {
22
+ return process.platform === "win32"
23
+ ? process.env.USERPROFILE || homedir()
24
+ : process.env.HOME || homedir();
25
+ }
26
+ /**
27
+ * Run `fn` with BOTH `HOME` and `USERPROFILE` pointed at `homeDir`, then restore
28
+ * both to exactly what they were — including the previously-UNSET case, and even
29
+ * when `fn` throws. Returns `fn`'s value.
30
+ *
31
+ * `resolveHome()` reads `USERPROFILE` on win32 and `HOME` elsewhere, so setting
32
+ * only `HOME` silently ignored the override on Windows: doctor, the pin refresh
33
+ * and uninstall's `unwire()` then acted on the real profile instead of the
34
+ * directory the caller named. Both are set here, so the override holds on every
35
+ * platform.
36
+ *
37
+ * `fn` MUST be synchronous. The parameter type REJECTS a Promise-returning
38
+ * callback at compile time (a Promise is not assignable to the `never` branch),
39
+ * because a sync save/restore around async work would restore the environment
40
+ * before the work runs.
41
+ */
42
+ export function withHome(homeDir, fn) {
43
+ const prevHome = process.env.HOME;
44
+ const prevProfile = process.env.USERPROFILE;
45
+ process.env.HOME = homeDir;
46
+ process.env.USERPROFILE = homeDir;
47
+ try {
48
+ return fn();
49
+ }
50
+ finally {
51
+ if (prevHome === undefined)
52
+ delete process.env.HOME;
53
+ else
54
+ process.env.HOME = prevHome;
55
+ if (prevProfile === undefined)
56
+ delete process.env.USERPROFILE;
57
+ else
58
+ process.env.USERPROFILE = prevProfile;
59
+ }
60
+ }
@@ -240,6 +240,12 @@ export function verifyAdoptServing(input) {
240
240
  detail: `the serving process is still pid ${servingPid}, the pre-adopt process — adoption did not bounce the live instance`,
241
241
  };
242
242
  }
243
+ if (managedPid === null) {
244
+ return {
245
+ detail: "the launchd job reports no pid after load - the adopted job's identity cannot be confirmed, " +
246
+ "so the listener cannot be attributed to it",
247
+ };
248
+ }
243
249
  if (managedPid !== null && servingPid !== managedPid) {
244
250
  return {
245
251
  detail: `the instance is served by pid ${servingPid}, but launchd reports pid ${managedPid} for the adopted ` +
@@ -141,10 +141,10 @@
141
141
  */
142
142
  import { probeSecretsCapability, pushSecrets, PROCESS_ENV_TIER } from "./secrets-push.js";
143
143
  import { existsSync, mkdirSync, writeFileSync, chmodSync, readFileSync } from "node:fs";
144
- import { homedir } from "node:os";
145
144
  import { join, dirname } from "node:path";
146
145
  import { generateKeyPairSync, randomBytes } from "node:crypto";
147
146
  import yaml from "js-yaml";
147
+ import { resolveHome } from "./home.js";
148
148
  // ─── CIMD constants ──────────────────────────────────────────────────────────
149
149
  /** Default `clientIdMetadataDocuments.allowedHosts` allowlist — see the
150
150
  * module header's "claude.ai CIMD/redirect-URI allowlist hosts" note for
@@ -262,7 +262,7 @@ export function generateRsaSigningKeyPair() {
262
262
  return { publicKey, privateKey };
263
263
  }
264
264
  export function defaultSigningKeyFilePath() {
265
- return join(homedir(), ".flair", "mcp-signing-key.pem");
265
+ return join(resolveHome(), ".flair", "mcp-signing-key.pem");
266
266
  }
267
267
  /** Write the RS256 private key PEM to a 0600 file (idempotent — reuses an
268
268
  * existing file rather than silently rotating the signing key). */
@@ -377,7 +377,7 @@ export const MCP_ENABLED_ENV_REFERENCE = "${FLAIR_MCP_OAUTH}";
377
377
  export function updateLocalConfigMcpEnabled(enabled, explicitPath) {
378
378
  const candidates = explicitPath
379
379
  ? [explicitPath]
380
- : ["config.yaml", join(homedir(), ".flair", "config.yaml")];
380
+ : ["config.yaml", join(resolveHome(), ".flair", "config.yaml")];
381
381
  let configPath = null;
382
382
  for (const p of candidates) {
383
383
  if (existsSync(p)) {
@@ -481,7 +481,7 @@ export function defaultSecretsStagingPath(issuer) {
481
481
  /* fall through to the generic name */
482
482
  }
483
483
  const safe = host.replace(/[^a-zA-Z0-9.-]/g, "_");
484
- return join(homedir(), ".flair", `mcp-enable-secrets-${safe}.env`);
484
+ return join(resolveHome(), ".flair", `mcp-enable-secrets-${safe}.env`);
485
485
  }
486
486
  /** Write the secrets bundle to a 0600 staging file, `KEY=VALUE` per line.
487
487
  * This file legitimately carries secret material (like `grant`'s 0600 key
@@ -15,6 +15,7 @@
15
15
  */
16
16
  import { existsSync, lstatSync, readFileSync, statSync } from "node:fs";
17
17
  import { dirname, join } from "node:path";
18
+ import { withHome } from "./home.js";
18
19
  import { ALL_CLIENTS, clientConfigPath, repinCodexPin, repinJsonMcpPin, } from "../install/clients.js";
19
20
  import { checkSessionStartHook, isFlairHookCommand, readClientMcpBlock, } from "../doctor-client.js";
20
21
  import { decodeWiringSpec, decodeWiringSpecs, isComparableWiringPin, wiringPinString, } from "./wiring-spec.js";
@@ -22,19 +23,6 @@ import { isUnsafeAdapterPin } from "./stale-client-pin.js";
22
23
  import { hookInstallHint, hookSettingsPath, repinSessionStartHook, SUPPORTED_HARNESSES, } from "../hook-install.js";
23
24
  import { flairCliVersion, isResolvedVersion, FLAIR_MCP_PACKAGE } from "./mcp-spec.js";
24
25
  import { comparePinVersions, pinWriteWouldLowerOrIsUnknown } from "./upgrade-status.js";
25
- function withHome(homeDir, fn) {
26
- const prev = process.env.HOME;
27
- process.env.HOME = homeDir;
28
- try {
29
- return fn();
30
- }
31
- finally {
32
- if (prev === undefined)
33
- delete process.env.HOME;
34
- else
35
- process.env.HOME = prev;
36
- }
37
- }
38
26
  function displayHomePath(homeDir, path) {
39
27
  if (path.startsWith(homeDir))
40
28
  return "~" + path.slice(homeDir.length);
@@ -0,0 +1,120 @@
1
+ import { join, resolve } from "node:path";
2
+ /**
3
+ * socket-path-limit.ts — the OS cap on a Unix domain socket's path.
4
+ *
5
+ * A Unix domain socket (the Harper operations API's `operations-server` socket)
6
+ * is bind()ed at a filesystem path, and that path is stored in a
7
+ * `struct sockaddr_un` whose `sun_path` field is a fixed-size buffer. The
8
+ * kernel counts the trailing NUL terminator, so the USABLE path length is one
9
+ * byte shorter than the field size:
10
+ *
11
+ * - macOS (darwin): `sun_path` is 104 bytes -> 103 usable
12
+ * - Linux: `sun_path` is 108 bytes -> 107 usable
13
+ *
14
+ * (darwin and freebsd: <sys/un.h>'s `SUNPATH_MAX`; linux: un(7) / the 108-byte
15
+ * `sa_data` minus the NUL. See also the macOS `listen() EINVAL` behaviour
16
+ * for a path that overflows the buffer.)
17
+ *
18
+ * Harper's operations API socket lives at `<data-dir>/operations-server`, so a
19
+ * long `flair init --data-dir <dir>` can push it past the cap, and `listen`
20
+ * dies with a bare `EINVAL` that names neither the socket nor the limit
21
+ * (flair#916). These pure predicates let callers refuse a too-long data dir
22
+ * BEFORE anything is written to disk, and say exactly what is wrong and how to
23
+ * fix it.
24
+ */
25
+ /**
26
+ * The suffix appended to a data dir to form the operations-socket path,
27
+ * INCLUDING the leading separator. A single 18-byte constant — the part of the
28
+ * socket path that no amount of shortening the data dir can remove.
29
+ */
30
+ export const OPS_SOCKET_SUFFIX = "/operations-server";
31
+ /**
32
+ * The usable (NUL-excluded) maximum length of a Unix socket path, in BYTES,
33
+ * for a platform. macOS (darwin) and FreeBSD both have a 104-byte sun_path,
34
+ * so 103 usable; Linux has a 108-byte sun_path, so 107 usable. Any unknown
35
+ * platform takes the Linux limit of 107.
36
+ * Unknown platforms fall back to 107 because no real platform is looser than
37
+ * Linux's — falling back lower would refuse a path that is actually legal.
38
+ */
39
+ export function socketPathLimit(platform) {
40
+ return platform === "darwin" || platform === "freebsd" ? 103 : 107;
41
+ }
42
+ /**
43
+ * Measure a socket path in BYTES (not characters — a multibyte path counts each
44
+ * byte of its UTF-8 encoding) against its platform's `sun_path`-derived limit.
45
+ * Returns OK when `bytes <= limit`; otherwise a refusal.
46
+ */
47
+ export function checkSocketPathLength(path, platform) {
48
+ const limit = socketPathLimit(platform);
49
+ const bytes = Buffer.byteLength(path, "utf8");
50
+ if (bytes <= limit)
51
+ return { ok: true, bytes, limit };
52
+ return { ok: false, bytes, limit, over: bytes - limit };
53
+ }
54
+ /**
55
+ * Type guard: true when a socket-path check is a refusal (the path overflowed
56
+ * its platform's limit). An explicit type predicate — not control-flow
57
+ * narrowing — so it narrows the refusal branch even under `strict: false`
58
+ * (tsconfig.cli.json turns off strictNullChecks, which disables discriminated
59
+ * union narrowing).
60
+ */
61
+ export function isSocketPathRefusal(check) {
62
+ return !check.ok;
63
+ }
64
+ /**
65
+ * An actionable refusal message for a socket path that exceeds its platform's
66
+ * `sun_path` limit. Names the actual constraint — the socket path itself, its
67
+ * byte length, the platform limit — and the remedy: how many bytes shorter the
68
+ * `--data-dir` must be (the `/operations-server` suffix is fixed, so the data
69
+ * dir is the only part that can move).
70
+ *
71
+ * Pure: it only formats. The caller decides whether to print and exit.
72
+ */
73
+ export function socketPathTooLongMessage(socketPath, dataDir, check) {
74
+ const [head, ...tail] = [
75
+ "Error: the Harper operations socket path is too long for this OS — Harper",
76
+ "would die with a bare `listen EINVAL` instead. Refusing before touching disk.",
77
+ "",
78
+ ` Operations socket: ${JSON.stringify(socketPath)}`,
79
+ ` Path length: ${check.bytes} bytes`,
80
+ ` OS limit: ${check.limit} bytes (Unix-domain-socket sun_path, counting the trailing NUL)`,
81
+ ` Data directory: ${JSON.stringify(dataDir)}`,
82
+ "",
83
+ "The socket is always <data-dir>/operations-server, so that suffix is fixed.",
84
+ "Choose a --data-dir that is at least " +
85
+ `${check.over} byte${check.over === 1 ? "" : "s"} shorter, so the socket path` +
86
+ " fits within " +
87
+ `${check.limit} bytes.`,
88
+ ];
89
+ return head + "\n" + tail.join("\n");
90
+ }
91
+ /**
92
+ * CLI preflight for the operations socket. Builds the socket path from a data
93
+ * directory exactly as Harper binds it (`<data-dir>/operations-server`) and,
94
+ * unless it fits the platform's `sun_path` limit, returns the actionable refusal
95
+ * message. Returns `null` when the path fits.
96
+ *
97
+ * The data dir is resolved to an ABSOLUTE path BEFORE measuring, because Harper
98
+ * binds the socket relative to its own cwd (the flair package directory), not
99
+ * ours — a relative `--data-dir r` would otherwise be measured as the short
100
+ * `r/operations-server` while Harper binds a much longer path. The refusal
101
+ * message prints the RESOLVED path and the resolved data dir.
102
+ *
103
+ * Callers that run it: `flair init` (which accepts `--data-dir`) and
104
+ * `flair start` / `flair restart` (defensive — the default data dir is short).
105
+ * NOT covered here: `flair snapshot create` and the launchd repair path, which
106
+ * hand Harper a socket path without this check; an over-long data dir cannot
107
+ * boot in either case, so it is not a live bug.
108
+ *
109
+ * Pure — it only builds and formats; the caller decides whether to print and
110
+ * exit, so it is unit-testable without `process.exit`.
111
+ */
112
+ export function opsSocketPathRefusal(dataDir, platform) {
113
+ const resolvedDataDir = resolve(dataDir);
114
+ const socketPath = join(resolvedDataDir, OPS_SOCKET_SUFFIX);
115
+ const check = checkSocketPathLength(socketPath, platform);
116
+ if (isSocketPathRefusal(check)) {
117
+ return socketPathTooLongMessage(socketPath, resolvedDataDir, check);
118
+ }
119
+ return null;
120
+ }
@@ -15,8 +15,8 @@
15
15
  * "fully purged" when anything remains.
16
16
  */
17
17
  import { existsSync, rmSync } from "node:fs";
18
- import { homedir } from "node:os";
19
18
  import { join } from "node:path";
19
+ import { resolveHome, withHome } from "./home.js";
20
20
  import { ALL_CLIENTS } from "../install/clients.js";
21
21
  import { uninstallContinuityHooks, uninstallHook, harnessSupportsContinuity, hookBackupPath, hookSettingsPath, SUPPORTED_HARNESSES, } from "../hook-install.js";
22
22
  import { disableScheduler as disableRemScheduler, LAUNCHD_LABEL as REM_LAUNCHD_LABEL, SYSTEMD_SERVICE_UNIT as REM_SYSTEMD_SERVICE, SYSTEMD_TIMER_UNIT as REM_SYSTEMD_TIMER, } from "../rem/scheduler.js";
@@ -24,22 +24,6 @@ import { disableScheduler as disableFederationScheduler, LAUNCHD_LABEL as FED_LA
24
24
  /** The published CLI package. Named here so the leftover line cannot drift
25
25
  * from the remedy command. */
26
26
  export const FLAIR_NPM_PACKAGE = "@tpsdev-ai/flair";
27
- function resolveHome(homeDir) {
28
- return homeDir ?? process.env.HOME ?? process.env.USERPROFILE ?? homedir();
29
- }
30
- function withHome(homeDir, fn) {
31
- const prev = process.env.HOME;
32
- process.env.HOME = homeDir;
33
- try {
34
- return fn();
35
- }
36
- finally {
37
- if (prev === undefined)
38
- delete process.env.HOME;
39
- else
40
- process.env.HOME = prev;
41
- }
42
- }
43
27
  function displayUnderHome(homeDir, absPath) {
44
28
  if (absPath.startsWith(homeDir))
45
29
  return "~" + absPath.slice(homeDir.length);
@@ -127,7 +111,7 @@ function sweepHookBackup(settingsPath, reportedBackup, homeDir, removed, leftove
127
111
  * unless `omitNpmLeftover` is set.
128
112
  */
129
113
  export function purgeFlairInstall(opts = {}) {
130
- const homeDir = resolveHome(opts.homeDir);
114
+ const homeDir = opts.homeDir ?? resolveHome();
131
115
  const skipUnload = !!opts.skipSchedulerUnload;
132
116
  const removed = [];
133
117
  const leftovers = [];
@@ -19,10 +19,10 @@
19
19
  */
20
20
  import { existsSync, mkdirSync, renameSync, rmSync, cpSync, readdirSync, readFileSync, statSync, lstatSync, realpathSync, } from "node:fs";
21
21
  import { basename, dirname, join, resolve } from "node:path";
22
- import { homedir } from "node:os";
23
22
  import { execFileSync } from "node:child_process";
24
23
  import { extract as tarExtract } from "tar";
25
24
  import { canonicalPath, findFlairPackageDir, readFlairPackageAt, sameInstallPath, } from "./upgrade-exec-path.js";
25
+ import { resolveHome } from "./home.js";
26
26
  export const FLAIR_PACKAGE = "@tpsdev-ai/flair";
27
27
  /** Sibling suffix for the staged new tree (same filesystem as the live tree). */
28
28
  export const UPGRADE_NEXT_SUFFIX = "upgrade-next";
@@ -525,7 +525,7 @@ export function unitTextMentionsTree(unitText, treeDir) {
525
525
  return false;
526
526
  }
527
527
  const SYSTEM_UNIT_DIRS = ["/etc/systemd/system"];
528
- export function userSystemdDir(home = homedir()) {
528
+ export function userSystemdDir(home = resolveHome()) {
529
529
  return join(home, ".config", "systemd", "user");
530
530
  }
531
531
  /**
@@ -54,8 +54,8 @@
54
54
  */
55
55
  import { createPrivateKey, createPublicKey, randomUUID, sign } from "node:crypto";
56
56
  import { existsSync, readFileSync } from "node:fs";
57
- import { homedir } from "node:os";
58
57
  import { join } from "node:path";
58
+ import { resolveHome } from "./lib/home.js";
59
59
  // ─── RFC 7523 constants ─────────────────────────────────────────────────────
60
60
  /** RFC 7523 §2.2 value for `client_assertion_type`. */
61
61
  export const CLIENT_ASSERTION_TYPE_JWT_BEARER = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer";
@@ -76,8 +76,8 @@ export function resolveAgentKeyPath(agentId, keysDirOverride) {
76
76
  const candidates = [
77
77
  keysDirOverride ? join(keysDirOverride, `${agentId}.key`) : null,
78
78
  process.env.FLAIR_KEY_DIR ? join(process.env.FLAIR_KEY_DIR, `${agentId}.key`) : null,
79
- join(homedir(), ".flair", "keys", `${agentId}.key`),
80
- join(homedir(), ".tps", "secrets", "flair", `${agentId}-priv.key`),
79
+ join(resolveHome(), ".flair", "keys", `${agentId}.key`),
80
+ join(resolveHome(), ".tps", "secrets", "flair", `${agentId}-priv.key`),
81
81
  ].filter((p) => Boolean(p));
82
82
  return candidates.find((p) => existsSync(p)) ?? null;
83
83
  }
@@ -56,11 +56,11 @@
56
56
  */
57
57
  import { appendFileSync, existsSync, mkdirSync, readFileSync } from "node:fs";
58
58
  import { dirname, resolve } from "node:path";
59
- import { homedir } from "node:os";
60
59
  import { setImmediate as yieldToEventLoop } from "node:timers/promises";
61
60
  import { createSnapshot } from "./snapshot.js";
62
- export const REM_PAUSE_FLAG = resolve(homedir(), ".flair", "rem.paused");
63
- export const REM_NIGHTLY_LOG = resolve(homedir(), ".flair", "logs", "rem-nightly.jsonl");
61
+ import { resolveHome } from "../lib/home.js";
62
+ export const REM_PAUSE_FLAG = resolve(resolveHome(), ".flair", "rem.paused");
63
+ export const REM_NIGHTLY_LOG = resolve(resolveHome(), ".flair", "logs", "rem-nightly.jsonl");
64
64
  // ─── ADK per-tag distillation (#1205b-1) ─────────────────────────────────────
65
65
  // adk-flair collapses (app_name, user_id) → ONE Flair agentId, distinguishing
66
66
  // users ONLY by a per-user tag `adk:<app>:<user>` (see the adk-flair
@@ -15,25 +15,25 @@
15
15
  */
16
16
  import { existsSync, mkdirSync, chmodSync, rmSync } from "node:fs";
17
17
  import { resolve, dirname } from "node:path";
18
- import { homedir } from "node:os";
19
18
  import { spawn } from "node:child_process";
20
19
  import { fileURLToPath } from "node:url";
21
20
  import { escapeXml } from "../lib/xml-escape.js";
22
21
  import { detectPlatform as detectPlatformFor, spawnReport, readTemplate as readTemplateFrom, renderTemplateWith, writeFileWithDir, interpretActiveResult, describeLoadFailure as describeLoadFailureFor, describeExitCode, resolveNodeBin, resolveFlairBin, formatFlairBinWarning, verifyFirstRun, probeUserLingerEnabled, STATUS_CHECK_TIMEOUT_MS, } from "../lib/scheduler-platform.js";
22
+ import { resolveHome } from "../lib/home.js";
23
23
  // Re-exported so this module's public surface is unchanged by the extraction
24
24
  // into src/lib/scheduler-platform.ts (a second scheduler — `flair federation
25
25
  // sync enable` — needs the identical launchctl/systemctl interpretation, and
26
26
  // flair#850's lesson must have exactly one implementation).
27
27
  export { interpretActiveResult };
28
- export const SHIM_PATH_DEFAULT = resolve(homedir(), ".flair", "bin", "flair-rem-nightly");
28
+ export const SHIM_PATH_DEFAULT = resolve(resolveHome(), ".flair", "bin", "flair-rem-nightly");
29
29
  // Unit names, exported (flair#1278) so `flair doctor`'s scheduled-drivers
30
30
  // section addresses the same job this module installs — same single-source
31
31
  // rule as the federation scheduler's LAUNCHD_LABEL/SYSTEMD_*_UNIT constants.
32
32
  export const LAUNCHD_LABEL = "dev.flair.rem.nightly";
33
33
  export const SYSTEMD_TIMER_UNIT = "flair-rem-nightly.timer";
34
34
  export const SYSTEMD_SERVICE_UNIT = "flair-rem-nightly.service";
35
- export const LAUNCHD_PLIST_PATH = resolve(homedir(), "Library", "LaunchAgents", `${LAUNCHD_LABEL}.plist`);
36
- export const SYSTEMD_USER_DIR = resolve(homedir(), ".config", "systemd", "user");
35
+ export const LAUNCHD_PLIST_PATH = resolve(resolveHome(), "Library", "LaunchAgents", `${LAUNCHD_LABEL}.plist`);
36
+ export const SYSTEMD_USER_DIR = resolve(resolveHome(), ".config", "systemd", "user");
37
37
  export const SYSTEMD_TIMER_PATH = resolve(SYSTEMD_USER_DIR, SYSTEMD_TIMER_UNIT);
38
38
  export const SYSTEMD_SERVICE_PATH = resolve(SYSTEMD_USER_DIR, SYSTEMD_SERVICE_UNIT);
39
39
  function detectPlatform(override) {
@@ -102,7 +102,7 @@ function buildSubstitutions(opts, shimPath, flairBin, nodeBin) {
102
102
  FLAIR_BIN: flairBin,
103
103
  NODE_BIN: nodeBin,
104
104
  SHIM_PATH: shimPath,
105
- HOME: opts.homeOverride ?? homedir(),
105
+ HOME: opts.homeOverride ?? resolveHome(),
106
106
  AGENT_ID: opts.agentId,
107
107
  FLAIR_URL: opts.flairUrl,
108
108
  HOUR: String(opts.hour),