@tpsdev-ai/flair 0.54.2 → 0.55.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 (58) hide show
  1. package/dist/build-info.json +3 -3
  2. package/dist/cli.js +774 -176
  3. package/dist/commands/doctor.js +61 -1
  4. package/dist/commands/federation.js +131 -36
  5. package/dist/commands/hook.js +20 -10
  6. package/dist/commands/init.js +193 -67
  7. package/dist/commands/service.js +16 -12
  8. package/dist/commands/soul.js +10 -5
  9. package/dist/commands/status.js +62 -7
  10. package/dist/doctor-client.js +118 -32
  11. package/dist/hook-install.js +170 -16
  12. package/dist/lib/doctor-run.js +49 -3
  13. package/dist/lib/embed-gpu-doctor.js +30 -0
  14. package/dist/lib/federation-pair-access.js +118 -0
  15. package/dist/lib/harper-port-value.js +43 -0
  16. package/dist/lib/http-bind.js +227 -0
  17. package/dist/lib/init-admin-pass.js +316 -0
  18. package/dist/lib/launchd-management.js +16 -0
  19. package/dist/lib/launchd-repair.js +122 -1
  20. package/dist/lib/owned-pins.js +54 -1
  21. package/dist/lib/process-start-time.js +82 -0
  22. package/dist/lib/scratch-owner.js +124 -10
  23. package/dist/lib/stale-client-pin.js +26 -0
  24. package/dist/rem/runner.js +10 -1
  25. package/dist/resources/AdminInstance.js +8 -2
  26. package/dist/resources/Memory.js +36 -1
  27. package/dist/resources/MemoryBootstrap.js +23 -32
  28. package/dist/resources/MemoryFeed.js +4 -1
  29. package/dist/resources/MemoryReflect.js +121 -93
  30. package/dist/resources/SkillScan.js +13 -11
  31. package/dist/resources/Soul.js +15 -1
  32. package/dist/resources/XAA.js +16 -1
  33. package/dist/resources/a2a-url.js +5 -2
  34. package/dist/resources/client-version-gate.js +144 -0
  35. package/dist/resources/embed-gpu.js +241 -0
  36. package/dist/resources/embeddings-boot.js +34 -42
  37. package/dist/resources/federation-peer-liveness.js +7 -1
  38. package/dist/resources/health.js +12 -3
  39. package/dist/resources/memory-reflect-lib.js +66 -0
  40. package/dist/resources/memory-reflect-models.js +9 -0
  41. package/dist/resources/migrations/embedding-stamp.js +32 -4
  42. package/dist/resources/oauth-discovery.js +3 -1
  43. package/dist/resources/record-type-kit.js +59 -0
  44. package/dist/resources/scan/skill-markdown.js +166 -0
  45. package/dist/resources/scan/skill-scanner.js +89 -68
  46. package/dist/resources/skill-provenance.js +273 -0
  47. package/dist/resources/skill-write.js +26 -7
  48. package/dist/src/lib/harper-port-value.js +43 -0
  49. package/docs/api-reference.md +35 -2
  50. package/docs/deployment.md +1 -1
  51. package/docs/federation.md +18 -7
  52. package/docs/mcp-clients.md +19 -6
  53. package/docs/releasing.md +79 -13
  54. package/docs/rem.md +1 -1
  55. package/docs/secrets-and-keys.md +1 -0
  56. package/docs/standalone-local.md +1 -1
  57. package/docs/troubleshooting.md +17 -0
  58. package/package.json +1 -1
@@ -1,15 +1,17 @@
1
1
  import { applyOrReportClaudeMdBootstrap, applyOrReportSessionStartHook } from "../doctor-client.js";
2
2
  import { hookSettingsPath } from "../hook-install.js";
3
3
  import { detectClients, renderWiringSummary, wireAntigravity, wireCodex, wireCursor, wireGemini, wirePi } from "../install/clients.js";
4
- import { DEFAULT_ADMIN_USER, authFetch, defaultKeysDir, readAdminPassFileSecure, resolveAdminUser } from "../lib/auth-resolve.js";
4
+ import { DEFAULT_ADMIN_USER, authFetch, defaultAdminPassPath, defaultKeysDir, readAdminPassFileSecure, resolveAdminUser } from "../lib/auth-resolve.js";
5
+ import { detectPersistedAdminUser, executeAdminPasswordRotate, initAdminPassRefusalMessage, resolveInitAdminPasswordRefuseReason, resolveInitAdminPasswordSource, } from "../lib/init-admin-pass.js";
5
6
  import { mcpServerSpec, unpinnedSpecWarning } from "../lib/mcp-spec.js";
6
7
  import * as render from "../render.js";
7
8
  import { execSync, spawn } from "node:child_process";
8
9
  import { randomBytes, randomUUID } from "node:crypto";
9
- import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
10
+ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
10
11
  import { homedir } from "node:os";
11
12
  import { join } from "node:path";
12
13
  import nacl from "tweetnacl";
14
+ import { httpCorsAccessList } from "../lib/http-bind.js";
13
15
  let cli;
14
16
  /** Bind the cli-locals this module depends on. */
15
17
  export function bindCli(fns) {
@@ -21,9 +23,6 @@ function api(...args) {
21
23
  function b64url(...args) {
22
24
  return cli.b64url(...args);
23
25
  }
24
- function buildLaunchdPlist(...args) {
25
- return cli.buildLaunchdPlist(...args);
26
- }
27
26
  function buildOperationsApiConfig(...args) {
28
27
  return cli.buildOperationsApiConfig(...args);
29
28
  }
@@ -81,12 +80,15 @@ function readyOpsSocketPosture(...args) {
81
80
  function resolveHttpPort(...args) {
82
81
  return cli.resolveHttpPort(...args);
83
82
  }
84
- function resolveInitAdminPasswordSource(...args) {
85
- return cli.resolveInitAdminPasswordSource(...args);
83
+ function writeAdminPassFile(...args) {
84
+ return cli.writeAdminPassFile(...args);
86
85
  }
87
86
  function resolveOpsBindHost(...args) {
88
87
  return cli.resolveOpsBindHost(...args);
89
88
  }
89
+ function resolveHttpBindFor(...args) {
90
+ return cli.resolveHttpBindFor(...args);
91
+ }
90
92
  function resolveOpsPort(...args) {
91
93
  return cli.resolveOpsPort(...args);
92
94
  }
@@ -123,6 +125,9 @@ function waitForHealth(...args) {
123
125
  function writeDaemonSidecar(...args) {
124
126
  return cli.writeDaemonSidecar(...args);
125
127
  }
128
+ function writeInitLaunchdPlist(...args) {
129
+ return cli.writeInitLaunchdPlist(...args);
130
+ }
126
131
  export function register(program) {
127
132
  const MQTT_DISABLED_CONFIG = cli.MQTT_DISABLED_CONFIG;
128
133
  const STARTUP_TIMEOUT_MS = cli.STARTUP_TIMEOUT_MS;
@@ -140,8 +145,10 @@ export function register(program) {
140
145
  .option("--port <port>", "Harper HTTP port (default: this instance's current port, or 19926 for a new one)")
141
146
  .option("--ops-port <port>", "Harper operations API port")
142
147
  .option("--ops-bind <addr>", "Harper ops API bind address (env: FLAIR_OPS_BIND; default: 127.0.0.1 loopback-only for single-host — pass e.g. 0.0.0.0 for multi-host/Fabric remote admin)")
148
+ .option("--http-bind <addr>", "Harper HTTP bind address (env: FLAIR_HTTP_BIND; default: 127.0.0.1 loopback-only). The listener MUST include IPv4 loopback (Flair's self-calls hardcode 127.0.0.1), so only 127.0.0.1 or a wildcard (0.0.0.0 / ::) is accepted; a specific non-loopback host is refused.")
143
149
  .option("--admin-pass <pass>", "Admin password (generated if omitted)")
144
150
  .option("--admin-pass-file <path>", "Read admin password from file (chmod 600 recommended)")
151
+ .option("--reset-admin-pass", "Rotate Harper's persisted admin hash via the operations socket, then write ~/.flair/admin-pass")
145
152
  .option("--admin-user <name>", "Admin username when authenticating to an already-running instance via --target/--ops-target (env: FLAIR_ADMIN_USER; default: admin — local bootstrap and Fabric provisioning always create 'admin')")
146
153
  .option("--keys-dir <dir>", "Directory for Ed25519 keys")
147
154
  .option("--data-dir <dir>", "Harper data directory")
@@ -361,6 +368,19 @@ export function register(program) {
361
368
  // which would ask the same question again in "address" mode.
362
369
  const opsPort = resolveOpsPort({ ...opts, port: httpPort });
363
370
  const opsBindHost = resolveOpsBindHost(opts);
371
+ // HTTP bind (ops-nv9d slice 2): the same escape-hatch shape as the ops API
372
+ // (--http-bind > FLAIR_HTTP_BIND > persisted httpBind > loopback), but
373
+ // VALIDATED — the constructor refuses any host that does not guarantee
374
+ // IPv4-loopback reachability. Resolved before any write so a bad host is
375
+ // refused without touching the instance.
376
+ let httpBind;
377
+ try {
378
+ httpBind = resolveHttpBindFor(httpPort, opts);
379
+ }
380
+ catch (err) {
381
+ console.error(`Error: ${err instanceof Error ? err.message : String(err)}`);
382
+ process.exit(1);
383
+ }
364
384
  // Resolve MCP client selection (union of init's auto-wire + the multi-client
365
385
  // detection/wiring that the front-door command provides). `--no-mcp` sets
366
386
  // opts.mcp === false (commander negates the flag). Validate an explicit
@@ -376,16 +396,47 @@ export function register(program) {
376
396
  }
377
397
  selectedClients.push(clientOpt);
378
398
  }
379
- // Admin password: determine from opts, env, or generate
380
- // Priority: 1) --admin-pass-file, 2) env vars, 3) reuse existing file, 4) generate new
399
+ // Admin password: determine from opts, env, reuse, rotate, or generate.
400
+ // Priority: 1) --admin-pass-file, 2) env vars, 3) --admin-pass, 4) reuse
401
+ // existing file (#827), 5) refuse / rotate when Harper already has a
402
+ // persisted user and the file is gone (#837), 6) generate new (fresh).
381
403
  let adminPass;
382
404
  let passwordSource = "generated";
383
405
  let reusedExistingAdminPass = false;
406
+ let pendingAdminPassRotate = false;
407
+ const adminPassPath = defaultAdminPassPath();
408
+ const persistedAdminUser = detectPersistedAdminUser(dataDir);
409
+ let alreadyRunning = false;
410
+ try {
411
+ const res = await fetch(`http://127.0.0.1:${httpPort}/health`, { signal: AbortSignal.timeout(1000) });
412
+ if (res.status > 0)
413
+ alreadyRunning = true;
414
+ }
415
+ catch { /* not running */ }
416
+ const explicitCredential = !!(opts.adminPassFile || process.env.FLAIR_ADMIN_PASS || process.env.HDB_ADMIN_PASSWORD || opts.adminPass);
417
+ const passwordCtx = {
418
+ persistedAdminUser,
419
+ foreignInstanceOnPort: alreadyRunning && !persistedAdminUser,
420
+ explicitCredential,
421
+ resetRequested: !!opts.resetAdminPass,
422
+ opsSocketAvailable: alreadyRunning || !opts.skipStart,
423
+ };
384
424
  // Warn if --admin-pass is passed inline (not from env)
385
425
  if (shouldShowInlineSecretWarning(opts.adminPass, false, new Set(["--admin-pass"]), "--admin-pass")) {
386
426
  console.error("warning: --admin-pass passed inline. Consider --admin-pass-file <path> or FLAIR_ADMIN_PASS env " +
387
427
  "to keep secrets out of shell history.");
388
428
  }
429
+ const refuseIfNeeded = (fileExists) => {
430
+ const reason = resolveInitAdminPasswordRefuseReason(fileExists, passwordCtx);
431
+ if (!reason)
432
+ return;
433
+ console.error(initAdminPassRefusalMessage(reason, {
434
+ dataDir,
435
+ httpPort,
436
+ adminPassPath,
437
+ }));
438
+ process.exit(1);
439
+ };
389
440
  // Read from file if provided
390
441
  if (opts.adminPassFile) {
391
442
  try {
@@ -396,40 +447,55 @@ export function register(program) {
396
447
  process.exit(1);
397
448
  }
398
449
  passwordSource = "file";
450
+ if (opts.resetAdminPass) {
451
+ refuseIfNeeded(false);
452
+ pendingAdminPassRotate = resolveInitAdminPasswordSource(false, passwordCtx) === "rotate";
453
+ }
454
+ else if (resolveInitAdminPasswordSource(false, passwordCtx) === "re-persist") {
455
+ writeAdminPassFile(adminPassPath, adminPass + "\n");
456
+ }
399
457
  }
400
458
  else if (process.env.FLAIR_ADMIN_PASS) {
401
459
  adminPass = process.env.FLAIR_ADMIN_PASS;
402
460
  passwordSource = "env";
461
+ if (opts.resetAdminPass) {
462
+ refuseIfNeeded(false);
463
+ pendingAdminPassRotate = resolveInitAdminPasswordSource(false, passwordCtx) === "rotate";
464
+ }
465
+ else if (resolveInitAdminPasswordSource(false, passwordCtx) === "re-persist") {
466
+ writeAdminPassFile(adminPassPath, adminPass + "\n");
467
+ }
403
468
  }
404
469
  else if (process.env.HDB_ADMIN_PASSWORD) {
405
470
  adminPass = process.env.HDB_ADMIN_PASSWORD;
406
471
  passwordSource = "env";
472
+ if (opts.resetAdminPass) {
473
+ refuseIfNeeded(false);
474
+ pendingAdminPassRotate = resolveInitAdminPasswordSource(false, passwordCtx) === "rotate";
475
+ }
476
+ else if (resolveInitAdminPasswordSource(false, passwordCtx) === "re-persist") {
477
+ writeAdminPassFile(adminPassPath, adminPass + "\n");
478
+ }
407
479
  }
408
480
  else if (opts.adminPass) {
409
481
  // Inline admin pass (deprecated)
410
482
  adminPass = opts.adminPass;
411
- // Don't generate - don't write to file
412
483
  passwordSource = "env"; // Treat same as env for display purposes
484
+ if (opts.resetAdminPass) {
485
+ refuseIfNeeded(false);
486
+ pendingAdminPassRotate = resolveInitAdminPasswordSource(false, passwordCtx) === "rotate";
487
+ }
488
+ else if (resolveInitAdminPasswordSource(false, passwordCtx) === "re-persist") {
489
+ writeAdminPassFile(adminPassPath, adminPass + "\n");
490
+ }
413
491
  }
414
492
  else {
415
- const flairDir = join(homedir(), ".flair");
416
- const adminPassPath = join(flairDir, "admin-pass");
417
493
  passwordSource = "generated";
418
- if (resolveInitAdminPasswordSource(existsSync(adminPassPath)) === "reuse-existing") {
494
+ const fileExists = existsSync(adminPassPath);
495
+ const decision = resolveInitAdminPasswordSource(fileExists, passwordCtx);
496
+ if (decision === "reuse-existing") {
419
497
  // flair#827: an admin-pass file already on disk means a PRIOR `flair
420
498
  // init` already bootstrapped Harper's admin user with this password.
421
- // HDB_ADMIN_PASSWORD only seeds a brand-new install — Harper does
422
- // NOT rotate an existing user's stored password hash from env on
423
- // every boot. Generating and overwriting the file here would desync
424
- // it from what Harper actually has persisted, breaking ops-API auth
425
- // (401 "Login failed") on THIS SAME init run (the agent-seeding call
426
- // below) without fixing whatever the re-run was meant to fix — e.g.
427
- // `flair doctor`'s ops-bind finding, whose only prescribed remedy is
428
- // re-running `flair init`. Re-init must be idempotent here: reuse
429
- // the existing password so it's always safe to re-run against a
430
- // working install. Rotating the admin password on purpose is a
431
- // separate, deliberate operation (see the ops runbook), not a side
432
- // effect of re-init.
433
499
  try {
434
500
  adminPass = readAdminPassFileSecure(adminPassPath);
435
501
  }
@@ -439,35 +505,34 @@ export function register(program) {
439
505
  }
440
506
  reusedExistingAdminPass = true;
441
507
  }
442
- else {
443
- // Generate new password and write to file atomically
508
+ else if (decision === "generate-new") {
444
509
  adminPass = Buffer.from(nacl.randomBytes(18)).toString("base64url");
445
- // Atomic write: create temp file in same dir, then rename
446
- mkdirSync(flairDir, { recursive: true });
447
- const tempPath = mkdtempSync(join(flairDir, ".admin-pass.tmp-"));
448
- const finalTempPath = join(tempPath, "admin-pass");
449
- try {
450
- writeFileSync(finalTempPath, adminPass + "\n", { mode: 0o600 });
451
- renameSync(finalTempPath, adminPassPath);
452
- rmSync(tempPath, { recursive: true, force: true });
453
- }
454
- catch (err) {
455
- // Clean up temp dir on failure
456
- try {
457
- rmSync(tempPath, { recursive: true, force: true });
458
- }
459
- catch { }
460
- throw err;
510
+ writeAdminPassFile(adminPassPath, adminPass + "\n");
511
+ }
512
+ else if (decision === "rotate") {
513
+ if (!opts.resetAdminPass) {
514
+ throw new Error("unreachable: rotate without --reset-admin-pass");
461
515
  }
516
+ adminPass = Buffer.from(nacl.randomBytes(18)).toString("base64url");
517
+ pendingAdminPassRotate = true;
518
+ }
519
+ else {
520
+ refuseIfNeeded(fileExists);
521
+ // refuseIfNeeded always exits on refuse; keep a throw so TS knows
522
+ // adminPass is assigned on every path.
523
+ throw new Error("unreachable: init admin-pass refuse");
462
524
  }
463
525
  }
464
526
  const adminUser = DEFAULT_ADMIN_USER;
465
- // If we generated (or reused) the password, report where it lives
527
+ // If we generated (or reused) the password, report where it lives.
528
+ // A pending rotate writes the file only AFTER alter_user succeeds.
466
529
  if (passwordSource === "generated") {
467
- const adminPassPath = join(homedir(), ".flair", "admin-pass");
468
530
  if (reusedExistingAdminPass) {
469
531
  console.log(`Reusing existing admin password from: ${adminPassPath} (flair#827: re-init never rotates it — see the ops runbook to change it deliberately)`);
470
532
  }
533
+ else if (pendingAdminPassRotate) {
534
+ console.log(`Will rotate the persisted admin password and write: ${adminPassPath}`);
535
+ }
471
536
  else {
472
537
  console.log(`Admin password saved to: ${adminPassPath}`);
473
538
  }
@@ -476,7 +541,6 @@ export function register(program) {
476
541
  const major = parseInt(process.version.slice(1), 10);
477
542
  if (major < 18)
478
543
  throw new Error(`Node.js >= 18 required (found ${process.version})`);
479
- let alreadyRunning = false;
480
544
  // <ROOTPATH>/models — resources/embeddings-provider.ts's resolveModelsDir()
481
545
  // tier 2 default; an operator override already in the environment wins
482
546
  // (tier 1). Scoped above the alreadyRunning branch below (not just inside
@@ -491,15 +555,9 @@ export function register(program) {
491
555
  mkdirSync(dataDir, { recursive: true });
492
556
  readyOpsSocketPosture(dataDir);
493
557
  if (!opts.skipStart) {
494
- // Check if already running
495
- try {
496
- const res = await fetch(`http://127.0.0.1:${httpPort}/health`, { signal: AbortSignal.timeout(1000) });
497
- if (res.status > 0) {
498
- alreadyRunning = true;
499
- console.log(`Harper already running on port ${httpPort} — skipping start`);
500
- }
558
+ if (alreadyRunning) {
559
+ console.log(`Harper already running on port ${httpPort} — skipping start`);
501
560
  }
502
- catch { /* not running */ }
503
561
  if (!alreadyRunning) {
504
562
  const bin = harperBin();
505
563
  if (!bin) {
@@ -529,7 +587,7 @@ export function register(program) {
529
587
  // domainSocket schema path), escape hatch via --ops-bind/FLAIR_OPS_BIND.
530
588
  const harperSetConfig = JSON.stringify({
531
589
  rootPath: dataDir,
532
- http: { port: httpPort, cors: true, corsAccessList: [`http://127.0.0.1:${httpPort}`, `http://localhost:${httpPort}`] },
590
+ http: { port: httpBind.bindValue, cors: true, corsAccessList: httpCorsAccessList(httpPort) },
533
591
  operationsApi: buildOperationsApiConfig(opsPort, opsSocket, opsBindHost),
534
592
  mqtt: MQTT_DISABLED_CONFIG,
535
593
  localStudio: { enabled: false },
@@ -545,7 +603,7 @@ export function register(program) {
545
603
  HDB_ADMIN_PASSWORD: adminPass,
546
604
  THREADS_COUNT: "1",
547
605
  NODE_HOSTNAME: "localhost",
548
- HTTP_PORT: String(httpPort),
606
+ HTTP_PORT: httpBind.bindValue,
549
607
  // flair#863: host-qualified, NOT a bare port. A bare value here is
550
608
  // what Harper latches as `originalValues["operationsApi.network.port"]`
551
609
  // when HARPER_SET_CONFIG force-sets the same key — and restores on the
@@ -630,6 +688,29 @@ export function register(program) {
630
688
  // flair#763: the socket now exists — apply its file mode (+ chgrp for the
631
689
  // FLAIR_SOCKET_GROUP opt-in). The dir gate above is re-asserted idempotently.
632
690
  readyOpsSocketPosture(dataDir);
691
+ if (pendingAdminPassRotate) {
692
+ // HTTP /Health is not rotate-ready: Harper can answer it before
693
+ // operations-server accepts. Wait for a live socket, then alter_user,
694
+ // then write. A dead leftover inode is not-ready — refuse, no write.
695
+ const opsSocket = join(dataDir, "operations-server");
696
+ try {
697
+ await executeAdminPasswordRotate({
698
+ resetRequested: !!opts.resetAdminPass,
699
+ username: adminUser,
700
+ password: adminPass,
701
+ socketPath: opsSocket,
702
+ adminPassPath,
703
+ writeAdminPassFile,
704
+ onPreflight: (line) => console.log(line),
705
+ });
706
+ }
707
+ catch (err) {
708
+ console.error(err?.message ?? err);
709
+ process.exit(1);
710
+ }
711
+ pendingAdminPassRotate = false;
712
+ console.log(`Admin password saved to: ${adminPassPath}`);
713
+ }
633
714
  // Register launchd service on macOS so Harper survives reboots
634
715
  // and `flair restart` / `flair stop` work via launchctl.
635
716
  if (process.platform === "darwin") {
@@ -659,7 +740,7 @@ export function register(program) {
659
740
  // initial spawn above — the launchd-managed process must not diverge.
660
741
  const setConfig = JSON.stringify({
661
742
  rootPath: dataDir,
662
- http: { port: httpPort, cors: true, corsAccessList: [`http://127.0.0.1:${httpPort}`, `http://localhost:${httpPort}`] },
743
+ http: { port: httpBind.bindValue, cors: true, corsAccessList: httpCorsAccessList(httpPort) },
663
744
  operationsApi: buildOperationsApiConfig(opsPort, opsSocket, opsBindHost),
664
745
  mqtt: MQTT_DISABLED_CONFIG,
665
746
  localStudio: { enabled: false },
@@ -671,24 +752,61 @@ export function register(program) {
671
752
  // backend on every KeepAlive restart in-process. See that file's
672
753
  // header (flair#694) for why this replaced the old HARPER_CONFIG
673
754
  // plist line.
674
- const plist = buildLaunchdPlist({
755
+ //
756
+ // Credential before plist, ONE shape (flair#1693): the writer always
757
+ // emits the pass-file launcher and never HDB_ADMIN_PASSWORD. It reuses
758
+ // an existing valid ~/.flair/admin-pass, or proves the credential in
759
+ // hand against this (now-healthy) instance and writes it 0600, or
760
+ // refuses without writing a plist. An already-adopted instance is left
761
+ // byte-for-byte unchanged rather than downgraded to the inline shape.
762
+ const outcome = await writeInitLaunchdPlist({
763
+ dataDir,
764
+ plistPath,
675
765
  label,
766
+ adminPass,
767
+ adminUser,
768
+ modelsDir,
676
769
  execPath: process.execPath,
677
770
  harperBinPath,
678
771
  workingDirectory: flairPackageDir(),
679
- dataDir,
680
- modelsDir,
681
- setConfig,
682
- adminUser,
683
- adminPass,
684
- httpPort,
772
+ httpPort: httpBind.bindValue,
685
773
  opsNetworkPort: opsNetworkPortValue(opsBindHost, opsPort),
774
+ setConfig,
775
+ port: httpPort,
686
776
  });
687
- writeFileSync(plistPath, plist);
688
- console.log("Launchd service registered ✓");
777
+ if (outcome.kind === "refused") {
778
+ console.error(`Error: ${outcome.detail}`);
779
+ process.exit(1);
780
+ }
781
+ console.log(outcome.kind === "unchanged"
782
+ ? "Launchd service already managed — plist unchanged ✓"
783
+ : "Launchd service registered ✓");
689
784
  }
690
785
  }
691
786
  }
787
+ if (pendingAdminPassRotate) {
788
+ // Same gate as the post-health path: readiness is the operations
789
+ // socket accepting a connection, not HTTP. Never fall through to
790
+ // the HTTP ops path; never write the pass file if rotate did not land.
791
+ const opsSocket = join(dataDir, "operations-server");
792
+ try {
793
+ await executeAdminPasswordRotate({
794
+ resetRequested: !!opts.resetAdminPass,
795
+ username: adminUser,
796
+ password: adminPass,
797
+ socketPath: opsSocket,
798
+ adminPassPath,
799
+ writeAdminPassFile,
800
+ onPreflight: (line) => console.log(line),
801
+ });
802
+ }
803
+ catch (err) {
804
+ console.error(err?.message ?? err);
805
+ process.exit(1);
806
+ }
807
+ pendingAdminPassRotate = false;
808
+ console.log(`Admin password saved to: ${adminPassPath}`);
809
+ }
692
810
  // Persist the instance coordinates so other commands can find AND
693
811
  // re-assert this instance. flair#863: `opsBind` in particular has to be
694
812
  // persisted here, not just handed to this run's spawn — `flair start` /
@@ -702,7 +820,15 @@ export function register(program) {
702
820
  // instance's own port needs no write here — Harper has just recorded it in
703
821
  // <dataDir>/harper-config.yaml, which is what resolveHttpPort reads (see
704
822
  // persistDefaultInstallCoordinates).
705
- persistDefaultInstallCoordinates(dataDir, httpPort, opsPort, opsBindHost);
823
+ //
824
+ // `httpBind` is persisted with THIS run's resolved host, always — not only
825
+ // when it differs from the loopback default. `undefined` would mean both
826
+ // "no preference" and "read from disk", so persisting it only for a
827
+ // non-default host made the hatch a ONE-WAY DOOR: a later `--http-bind
828
+ // 127.0.0.1` narrowed only that run's spawn, and the next restart re-widened
829
+ // from the still-persisted wildcard. Writing the resolved host on every init
830
+ // means an explicit loopback also persists, so a widening can be reversed.
831
+ persistDefaultInstallCoordinates(dataDir, httpPort, opsPort, opsBindHost, httpBind.host);
706
832
  if (agentId) {
707
833
  // Generate or reuse keypair
708
834
  mkdirSync(keysDir, { recursive: true });
@@ -12,6 +12,9 @@ export function bindCli(fns) {
12
12
  function buildDirectSpawnEnv(...args) {
13
13
  return cli.buildDirectSpawnEnv(...args);
14
14
  }
15
+ function closedDirectSpawnEnv(...args) {
16
+ return cli.closedDirectSpawnEnv(...args);
17
+ }
15
18
  function defaultDataDir(...args) {
16
19
  return cli.defaultDataDir(...args);
17
20
  }
@@ -45,6 +48,9 @@ function readyOpsSocketPosture(...args) {
45
48
  function resolveHarperBin(...args) {
46
49
  return cli.resolveHarperBin(...args);
47
50
  }
51
+ function resolveHttpBindHost(...args) {
52
+ return cli.resolveHttpBindHost(...args);
53
+ }
48
54
  function resolveHttpPort(...args) {
49
55
  return cli.resolveHttpPort(...args);
50
56
  }
@@ -248,18 +254,16 @@ export function register(program) {
248
254
  // every spawn — see buildDirectSpawnEnv. The escape hatch on this path is
249
255
  // FLAIR_OPS_BIND or the `opsBind` that `flair init --ops-bind` persisted to
250
256
  // ~/.flair/config.yaml; there is no --ops-bind flag on `start`.
251
- const env = {
252
- ...process.env,
253
- ...buildDirectSpawnEnv({
254
- dataDir,
255
- modelsDir: process.env.FLAIR_MODELS_DIR ?? join(dataDir, "models"),
256
- httpPort: port,
257
- opsPort: resolveOpsPort(opts),
258
- opsBindHost: resolveOpsBindHost({}),
259
- adminUser: DEFAULT_ADMIN_USER,
260
- adminPass,
261
- }),
262
- };
257
+ const env = closedDirectSpawnEnv(process.env, buildDirectSpawnEnv({
258
+ dataDir,
259
+ modelsDir: process.env.FLAIR_MODELS_DIR ?? join(dataDir, "models"),
260
+ httpPort: port,
261
+ httpBindHost: resolveHttpBindHost({}),
262
+ opsPort: resolveOpsPort(opts),
263
+ opsBindHost: resolveOpsBindHost({}),
264
+ adminUser: DEFAULT_ADMIN_USER,
265
+ adminPass,
266
+ }));
263
267
  const proc = spawn(process.execPath, [bin, "run", "."], {
264
268
  cwd: flairPackageDir(), env, detached: true, stdio: "ignore",
265
269
  });
@@ -24,6 +24,7 @@ export function register(program) {
24
24
  .requiredOption("--key <key>")
25
25
  .requiredOption("--value <value>")
26
26
  .option("--durability <d>", "permanent|persistent|standard|ephemeral (default permanent — soul entries are identity, not working memory)")
27
+ .option("--url <url>", "Flair base URL (overrides the URL resolved from config; env: FLAIR_URL)")
27
28
  .option("--json", "Emit raw JSON response (also: pipe + FLAIR_OUTPUT=json)")
28
29
  .action(async (opts) => {
29
30
  applyAdminPassFile(opts);
@@ -45,7 +46,7 @@ export function register(program) {
45
46
  value: opts.value,
46
47
  durability: opts.durability,
47
48
  createdAt: new Date().toISOString(),
48
- }, { agentId, agentIdSource: source, explicitAdminPass: opts.adminPass, adminUser: opts.adminUser });
49
+ }, { agentId, agentIdSource: source, explicitAdminPass: opts.adminPass, adminUser: opts.adminUser, baseUrl: opts.url });
49
50
  const mode = render.resolveOutputMode(opts);
50
51
  if (mode === "json") {
51
52
  console.log(render.asJSON(out));
@@ -58,17 +59,19 @@ export function register(program) {
58
59
  if (opts.durability)
59
60
  console.log(render.kv("durability", render.wrap(render.c.magenta, opts.durability)));
60
61
  });
61
- soul.command("get")
62
+ addSharedCredentialOptions(soul.command("get"))
62
63
  .description("Fetch a single soul entry by id (agent:key)")
63
64
  .argument("<id>")
64
65
  .option("--agent <id>", "Agent ID to sign the read as (or set FLAIR_AGENT_ID); falls back to the config-profile agent")
66
+ .option("--url <url>", "Flair base URL (overrides the URL resolved from config; env: FLAIR_URL)")
65
67
  .option("--json", "Emit raw JSON response (also: pipe + FLAIR_OUTPUT=json)")
66
68
  .action(async (id, opts) => {
69
+ applyAdminPassFile(opts);
67
70
  // flair#1183: /Soul reads are verified (any registered agent). Resolve the
68
71
  // signer through the canonical seam so soul get honors the SAME precedence
69
72
  // as every other family; a null result lets api() fall to admin-pass/floor.
70
73
  const { agentId, source } = resolveSigningAgentId(opts, "soul get");
71
- const out = await api("GET", `/Soul/${id}`, undefined, { agentId, agentIdSource: source });
74
+ const out = await api("GET", `/Soul/${id}`, undefined, { agentId, agentIdSource: source, explicitAdminPass: opts.adminPass, adminUser: opts.adminUser, baseUrl: opts.url });
72
75
  const mode = render.resolveOutputMode(opts);
73
76
  if (mode === "json") {
74
77
  console.log(render.asJSON(out));
@@ -95,17 +98,19 @@ export function register(program) {
95
98
  console.log(render.kv("updated", `${render.relativeTime(out.updatedAt)} ${render.wrap(render.c.dim, `(${out.updatedAt})`)}`));
96
99
  }
97
100
  });
98
- soul.command("list")
101
+ addSharedCredentialOptions(soul.command("list"))
99
102
  .description("List all soul entries for an agent")
100
103
  .option("--agent <id>", "Agent ID (or set FLAIR_AGENT_ID env)")
104
+ .option("--url <url>", "Flair base URL (overrides the URL resolved from config; env: FLAIR_URL)")
101
105
  .option("--json", "Emit raw JSON array (also: pipe + FLAIR_OUTPUT=json)")
102
106
  .action(async (opts) => {
107
+ applyAdminPassFile(opts);
103
108
  const { agentId, source } = resolveSigningAgentId(opts, "soul list");
104
109
  if (!agentId) {
105
110
  console.error(`${render.icons.error} --agent <id> required (or set FLAIR_AGENT_ID)`);
106
111
  process.exit(2);
107
112
  }
108
- const out = await api("GET", `/Soul?agentId=${encodeURIComponent(agentId)}`, undefined, { agentId, agentIdSource: source });
113
+ const out = await api("GET", `/Soul?agentId=${encodeURIComponent(agentId)}`, undefined, { agentId, agentIdSource: source, explicitAdminPass: opts.adminPass, adminUser: opts.adminUser, baseUrl: opts.url });
109
114
  const mode = render.resolveOutputMode(opts);
110
115
  if (mode === "json") {
111
116
  console.log(render.asJSON(out));
@@ -29,6 +29,9 @@ function defaultDataDir(...args) {
29
29
  function readHarperConfig(...args) {
30
30
  return cli.readHarperConfig(...args);
31
31
  }
32
+ function readPortFromConfig() {
33
+ return cli.readPortFromConfig();
34
+ }
32
35
  /**
33
36
  * Local install-health warnings that `flair doctor` also checks (flair#852).
34
37
  *
@@ -111,6 +114,51 @@ function oauthDetailLines(o) {
111
114
  // 19926: current default (DEFAULT_PORT)
112
115
  // 19925: ops-anvil VM secondary
113
116
  const LOCAL_FLAIR_PROBE_PORTS = [9926, 19926, 19925];
117
+ /**
118
+ * The unreachable-path guidance for a localhost target, as printable lines.
119
+ *
120
+ * flair#1719: the old message asserted "Your config points at <resolved URL>"
121
+ * without ever reading the config, and then told the user to "set port: N" in
122
+ * a file that may already say exactly that — a remedy that cannot work. This
123
+ * reads the per-user config and only names it when it actually disagrees with
124
+ * the running daemon; when the config is already correct it points at the
125
+ * command that reconciles the instance record instead of the file.
126
+ *
127
+ * Pure so the wording is pinned by a unit test (the daemon is not required).
128
+ */
129
+ export function formatPortDriftGuidance(args) {
130
+ const lines = [];
131
+ if (args.discoveredPort == null) {
132
+ if (args.configuredPort != null) {
133
+ lines.push(`\n ~/.flair/config.yaml records port ${args.configuredPort}, but nothing answered there.`);
134
+ }
135
+ lines.push(`\n Run: flair start or flair doctor`);
136
+ return lines;
137
+ }
138
+ const altUrl = `http://127.0.0.1:${args.discoveredPort}`;
139
+ lines.push(`\n ⚠ Found a Flair daemon listening on port ${args.discoveredPort} (URL: ${altUrl}).`);
140
+ if (args.configuredPort === args.discoveredPort) {
141
+ // The config already names the running port. The divergence is in the
142
+ // instance's own record, not the operator's config — do not send them to
143
+ // edit a file that is already right.
144
+ lines.push(` ~/.flair/config.yaml already records port ${args.configuredPort}; the resolved URL (${args.baseUrl}) is not that port.`);
145
+ lines.push(`\n Quick fix: FLAIR_URL=${altUrl} flair status`);
146
+ lines.push(` Permanent fix: flair doctor (reconcile the instance's recorded port with the running daemon)`);
147
+ }
148
+ else if (args.configuredPort != null) {
149
+ lines.push(` ~/.flair/config.yaml records port ${args.configuredPort}; the daemon is on ${args.discoveredPort}.`);
150
+ lines.push(`\n Quick fix: FLAIR_URL=${altUrl} flair status`);
151
+ lines.push(` Permanent fix: edit ~/.flair/config.yaml to set port: ${args.discoveredPort}`);
152
+ lines.push(` Or: flair doctor`);
153
+ }
154
+ else {
155
+ lines.push(` No port is recorded in ~/.flair/config.yaml.`);
156
+ lines.push(`\n Quick fix: FLAIR_URL=${altUrl} flair status`);
157
+ lines.push(` Permanent fix: edit ~/.flair/config.yaml to set port: ${args.discoveredPort}`);
158
+ lines.push(` Or: flair doctor`);
159
+ }
160
+ return lines;
161
+ }
114
162
  export function isLocalhostUrl(url) {
115
163
  try {
116
164
  const u = new URL(url);
@@ -227,15 +275,22 @@ export function register(program) {
227
275
  if (registryNotice.error)
228
276
  console.log(` ⚠ ${registryNotice.error}`);
229
277
  if (discoveredPort != null) {
230
- const altUrl = `http://127.0.0.1:${discoveredPort}`;
231
- console.log(`\n ⚠ Found a Flair daemon listening on port ${discoveredPort} (URL: ${altUrl}).`);
232
- console.log(` Your config points at ${baseUrl} — drift detected.`);
233
- console.log(`\n Quick fix: FLAIR_URL=${altUrl} flair status`);
234
- console.log(` Permanent fix: edit ~/.flair/config.yaml to set port: ${discoveredPort}`);
235
- console.log(` Or: flair doctor (when port-drift detection lands there)`);
278
+ for (const line of formatPortDriftGuidance({
279
+ baseUrl,
280
+ discoveredPort,
281
+ configuredPort: readPortFromConfig(),
282
+ })) {
283
+ console.log(line);
284
+ }
236
285
  }
237
286
  else {
238
- console.log(`\n Run: flair start or flair doctor`);
287
+ for (const line of formatPortDriftGuidance({
288
+ baseUrl,
289
+ discoveredPort: null,
290
+ configuredPort: readPortFromConfig(),
291
+ })) {
292
+ console.log(line);
293
+ }
239
294
  }
240
295
  if (versionNudge) {
241
296
  const color = versionNudge.severity === "red" ? render.c.red : render.c.yellow;