@tpsdev-ai/flair 0.57.0 → 0.59.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 (143) hide show
  1. package/README.md +7 -6
  2. package/SECURITY.md +4 -1
  3. package/config.yaml +3 -0
  4. package/dist/build-info.json +3 -3
  5. package/dist/cli.js +1726 -376
  6. package/dist/commands/agent.js +160 -2
  7. package/dist/commands/doctor.js +177 -27
  8. package/dist/commands/federation.js +2 -1
  9. package/dist/commands/hook.js +10 -2
  10. package/dist/commands/init.js +150 -44
  11. package/dist/commands/mcp.js +53 -22
  12. package/dist/commands/memory.js +24 -2
  13. package/dist/commands/quality.js +26 -18
  14. package/dist/commands/service.js +137 -22
  15. package/dist/commands/status.js +114 -3
  16. package/dist/commands/upgrade.js +204 -84
  17. package/dist/doctor-client.js +50 -4
  18. package/dist/federation/scheduler.js +253 -4
  19. package/dist/install/clients.js +89 -23
  20. package/dist/install/global-bin-path.js +26 -6
  21. package/dist/lib/atomic-write.js +256 -0
  22. package/dist/lib/daemon-liveness.js +103 -0
  23. package/dist/lib/doctor-run.js +72 -0
  24. package/dist/lib/embed-gpu-doctor.js +49 -26
  25. package/dist/lib/federation-memory-attributes.js +15 -0
  26. package/dist/lib/flair-agent-role.js +116 -0
  27. package/dist/lib/init-admin-pass.js +4 -2
  28. package/dist/lib/init-listener-environ.js +38 -0
  29. package/dist/lib/init-occupied-listener.js +165 -0
  30. package/dist/lib/launchd-domain-preflight.js +448 -0
  31. package/dist/lib/launchd-management.js +179 -8
  32. package/dist/lib/launchd-repair.js +95 -0
  33. package/dist/lib/mcp-enable.js +667 -72
  34. package/dist/lib/memory-attributes.js +77 -0
  35. package/dist/lib/node-alias-path.js +95 -0
  36. package/dist/lib/npm-registry.js +119 -6
  37. package/dist/lib/owned-pins.js +20 -6
  38. package/dist/lib/process-start-time.js +32 -0
  39. package/dist/lib/service-repoint-apply.js +267 -0
  40. package/dist/lib/service-repoint.js +575 -0
  41. package/dist/lib/toml-string-array.js +104 -0
  42. package/dist/lib/tree-divergence.js +716 -0
  43. package/dist/lib/upgrade-plain-tree.js +18 -8
  44. package/dist/lib/upgrade-prior-liveness.js +69 -0
  45. package/dist/lib/upgrade-rollback.js +116 -0
  46. package/dist/rem/runner.js +11 -0
  47. package/dist/resources/Agent.js +54 -21
  48. package/dist/resources/AgentSeed.js +44 -1
  49. package/dist/resources/Federation.js +84 -54
  50. package/dist/resources/Memory.js +567 -72
  51. package/dist/resources/MemoryArchive.js +9 -0
  52. package/dist/resources/MemoryBootstrap.js +125 -29
  53. package/dist/resources/MemoryFeed.js +204 -3
  54. package/dist/resources/MemoryHostSource.js +90 -0
  55. package/dist/resources/MemoryMaintenance.js +121 -32
  56. package/dist/resources/MemoryReflect.js +4 -1
  57. package/dist/resources/MemoryReindex.js +7 -4
  58. package/dist/resources/MemoryUsage.js +53 -3
  59. package/dist/resources/OrgSkillAssignment.js +209 -0
  60. package/dist/resources/Presence.js +18 -10
  61. package/dist/resources/RecordUsage.js +30 -40
  62. package/dist/resources/Relationship.js +167 -78
  63. package/dist/resources/SemanticSearch.js +19 -6
  64. package/dist/resources/Soul.js +31 -19
  65. package/dist/resources/XAA.js +47 -14
  66. package/dist/resources/agent-auth.js +16 -10
  67. package/dist/resources/agent-status-guard.js +63 -0
  68. package/dist/resources/auth-middleware.js +137 -49
  69. package/dist/resources/auto-promote-lib.js +4 -4
  70. package/dist/resources/bm25-index-service.js +246 -32
  71. package/dist/resources/bm25-status.js +132 -0
  72. package/dist/resources/ed25519-auth.js +11 -54
  73. package/dist/resources/embed-gpu.js +262 -47
  74. package/dist/resources/embeddings-boot.js +52 -17
  75. package/dist/resources/federation-classify.js +34 -0
  76. package/dist/resources/federation-crypto.js +65 -19
  77. package/dist/resources/flair-agent-role-boot.js +26 -0
  78. package/dist/resources/health.js +67 -16
  79. package/dist/resources/host-pointer/registry.js +35 -0
  80. package/dist/resources/host-pointer-adapter.js +15 -0
  81. package/dist/resources/host-source-visibility.js +167 -0
  82. package/dist/resources/host-source.js +151 -0
  83. package/dist/resources/instance-identity.js +3 -2
  84. package/dist/resources/key-lock.js +31 -0
  85. package/dist/resources/mcp-handler.js +147 -51
  86. package/dist/resources/mcp-oauth.js +3 -6
  87. package/dist/resources/mcp-tools.js +47 -25
  88. package/dist/resources/memory-consolidate-lib.js +3 -1
  89. package/dist/resources/memory-declared-attributes.js +103 -0
  90. package/dist/resources/memory-feed-lib.js +5 -1
  91. package/dist/resources/memory-host-source.js +163 -0
  92. package/dist/resources/migrations/synthetic-test-migration.js +4 -1
  93. package/dist/resources/migrations/visibility-backfill.js +4 -1
  94. package/dist/resources/multi-worker-guard.js +121 -0
  95. package/dist/resources/oauth-discovery.js +1 -0
  96. package/dist/resources/oauth-wellknown.js +8 -4
  97. package/dist/resources/originator-instance.js +235 -0
  98. package/dist/resources/promotion-stamp.js +2 -0
  99. package/dist/resources/provenance.js +111 -11
  100. package/dist/resources/record-owner-guard.js +19 -0
  101. package/dist/resources/record-type-kit.js +9 -12
  102. package/dist/resources/record-types.js +22 -6
  103. package/dist/resources/relay-ops.js +28 -3
  104. package/dist/resources/replay-store.js +336 -0
  105. package/dist/resources/request-transaction.js +78 -0
  106. package/dist/resources/search-readiness.js +19 -21
  107. package/dist/resources/semantic-retrieval-core.js +5 -1
  108. package/dist/resources/skill-manifest.js +181 -0
  109. package/dist/resources/skill-provenance.js +15 -10
  110. package/dist/resources/table-patch-policy.js +109 -0
  111. package/dist/resources/table-patches.js +17 -0
  112. package/dist/resources/table-post-policy.js +138 -0
  113. package/dist/resources/table-posts.js +22 -0
  114. package/dist/resources/table-subscription-policy.js +135 -0
  115. package/dist/resources/table-subscriptions.js +19 -0
  116. package/dist/resources/tool-descriptors/index.js +15 -15
  117. package/dist/resources/trust-block.js +10 -3
  118. package/dist/resources/usage-recording.js +169 -41
  119. package/dist/src/lib/flair-agent-role.js +116 -0
  120. package/dist/src/lib/memory-attributes.js +77 -0
  121. package/docs/access-control.md +667 -0
  122. package/docs/api-reference.md +85 -17
  123. package/docs/auth.md +4 -0
  124. package/docs/claude-code.md +132 -0
  125. package/docs/deepseek-harness.md +1 -1
  126. package/docs/deployment.md +1 -1
  127. package/docs/federation.md +1 -1
  128. package/docs/integrations.md +6 -6
  129. package/docs/mcp-clients.md +16 -24
  130. package/docs/notes/mcp-oauth-model2.md +15 -1
  131. package/docs/quickstart.md +5 -0
  132. package/docs/releasing.md +152 -20
  133. package/docs/supply-chain-policy.md +10 -5
  134. package/docs/troubleshooting.md +11 -0
  135. package/docs/upgrade.md +187 -61
  136. package/package.json +10 -5
  137. package/schemas/agent.graphql +9 -6
  138. package/schemas/federation.graphql +2 -11
  139. package/schemas/memory.graphql +137 -17
  140. package/schemas/oauth.graphql +8 -4
  141. package/schemas/replay.graphql +18 -0
  142. package/templates/launchd/start-flair-with-admin-pass.sh +95 -0
  143. package/dist/resources/federation-nonce-store.js +0 -195
@@ -6,13 +6,16 @@ import { detectPersistedAdminUser, executeAdminPasswordRotate, initAdminPassRefu
6
6
  import { mcpServerSpec, unpinnedSpecWarning } from "../lib/mcp-spec.js";
7
7
  import { opsSocketPathRefusal } from "../lib/socket-path-limit.js";
8
8
  import * as render from "../render.js";
9
- import { execSync, spawn } from "node:child_process";
9
+ import { rewriteFederationSchedulerRuntime } from "../federation/scheduler.js";
10
+ import { preferVersionManagerAlias } from "../lib/node-alias-path.js";
11
+ import { spawn } from "node:child_process";
10
12
  import { randomBytes, randomUUID } from "node:crypto";
11
13
  import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
12
14
  import { join, resolve } from "node:path";
13
15
  import nacl from "tweetnacl";
14
16
  import { httpCorsAccessList } from "../lib/http-bind.js";
15
17
  import { resolveHome } from "../lib/home.js";
18
+ import { foreignOccupiedListenerDetail, staleHarperBeforeAuthNotice, } from "../lib/init-occupied-listener.js";
16
19
  let cli;
17
20
  /** Bind the cli-locals this module depends on. */
18
21
  export function bindCli(fns) {
@@ -27,9 +30,6 @@ function b64url(...args) {
27
30
  function buildOperationsApiConfig(...args) {
28
31
  return cli.buildOperationsApiConfig(...args);
29
32
  }
30
- function cleanupLegacyLaunchdPlist(...args) {
31
- return cli.cleanupLegacyLaunchdPlist(...args);
32
- }
33
33
  function defaultDataDir(...args) {
34
34
  return cli.defaultDataDir(...args);
35
35
  }
@@ -114,6 +114,20 @@ function seedAgentViaOpsApi(...args) {
114
114
  function seedFederationInstanceViaOpsApi(...args) {
115
115
  return cli.seedFederationInstanceViaOpsApi(...args);
116
116
  }
117
+ function readOccupiedListener(port) {
118
+ return cli.readOccupiedListener(port);
119
+ }
120
+ /**
121
+ * Operations-port attribution for a later 401. `before` is taken now;
122
+ * `reread` runs only if the insert is rejected, so a holder that changed
123
+ * during the request is not named. The HTTP port's pids are not an input.
124
+ */
125
+ function operationsPortAttribution(port) {
126
+ return {
127
+ before: readOccupiedListener(port),
128
+ reread: () => readOccupiedListener(port),
129
+ };
130
+ }
117
131
  function shouldShowInlineSecretWarning(...args) {
118
132
  return cli.shouldShowInlineSecretWarning(...args);
119
133
  }
@@ -129,8 +143,11 @@ function waitForHealth(...args) {
129
143
  function writeDaemonSidecar(...args) {
130
144
  return cli.writeDaemonSidecar(...args);
131
145
  }
132
- function writeInitLaunchdPlist(...args) {
133
- return cli.writeInitLaunchdPlist(...args);
146
+ function registerInitLaunchdService(...args) {
147
+ return cli.registerInitLaunchdService(...args);
148
+ }
149
+ function repointMainServiceUnit(...args) {
150
+ return cli.repointMainServiceUnit(...args);
134
151
  }
135
152
  export function register(program) {
136
153
  const MQTT_DISABLED_CONFIG = cli.MQTT_DISABLED_CONFIG;
@@ -477,11 +494,30 @@ export function register(program) {
477
494
  const reason = resolveInitAdminPasswordRefuseReason(fileExists, passwordCtx);
478
495
  if (!reason)
479
496
  return;
480
- console.error(initAdminPassRefusalMessage(reason, {
497
+ const message = initAdminPassRefusalMessage(reason, {
481
498
  dataDir,
482
499
  httpPort,
483
500
  adminPassPath,
484
- }));
501
+ });
502
+ // The port is already taken and this data dir has no admin user.
503
+ // The unauthenticated /health probe already ran. This is one read of
504
+ // that port's listener — not the before-and-after 401 attribution.
505
+ // Name it and exit before any Authorization header is sent. Do not
506
+ // signal it. `flair stop` cannot be promised to act on this listener
507
+ // (flair#1749).
508
+ if (reason === "foreign-instance") {
509
+ const listener = readOccupiedListener(httpPort);
510
+ const head = initAdminPassRefusalMessage(reason, {
511
+ dataDir,
512
+ httpPort,
513
+ adminPassPath,
514
+ offerFlairStop: false,
515
+ });
516
+ console.error(`${head}\n${foreignOccupiedListenerDetail(listener, dataDir)}`);
517
+ }
518
+ else {
519
+ console.error(message);
520
+ }
485
521
  process.exit(1);
486
522
  };
487
523
  // Read from file if provided
@@ -601,9 +637,30 @@ export function register(program) {
601
637
  // The socket doesn't exist yet, so only the parent-dir mode is applied here.
602
638
  mkdirSync(dataDir, { recursive: true });
603
639
  readyOpsSocketPosture(dataDir);
640
+ // True only when the port was already answering and the single pre-auth
641
+ // read did not include a different data directory (that case exits
642
+ // below, before any authenticated request). An unreadable directory,
643
+ // including every macOS lookup, does not count as different. A later
644
+ // ops 401 is a separate before-and-after read of the operations port,
645
+ // not this HTTP observation (flair#1749).
646
+ let skippedOwnStart = false;
604
647
  if (!opts.skipStart) {
605
648
  if (alreadyRunning) {
606
649
  console.log(`Harper already running on port ${httpPort} — skipping start`);
650
+ // One read of the HTTP port that answered /health. When that read
651
+ // includes a ROOTPATH other than this init's, stop before
652
+ // waitForHealth, which would send Authorization. An unreadable
653
+ // directory is not treated as foreign. This is not the
654
+ // before-and-after check used for an operations-port 401. A
655
+ // different directory does not prove the passwords differ, and
656
+ // this init does not signal the process.
657
+ const httpListener = readOccupiedListener(httpPort);
658
+ const notice = staleHarperBeforeAuthNotice(dataDir, httpListener);
659
+ if (notice) {
660
+ console.error(notice);
661
+ process.exit(1);
662
+ }
663
+ skippedOwnStart = true;
607
664
  }
608
665
  if (!alreadyRunning) {
609
666
  const bin = harperBin();
@@ -758,8 +815,9 @@ export function register(program) {
758
815
  pendingAdminPassRotate = false;
759
816
  console.log(`Admin password saved to: ${adminPassPath}`);
760
817
  }
761
- // Register launchd service on macOS so Harper survives reboots
762
- // and `flair restart` / `flair stop` work via launchctl.
818
+ // Write this instance's launchd plist on macOS so launchd can own it
819
+ // (survive reboots; `flair restart` / `flair stop` via launchctl) — and
820
+ // report whether launchd ACTUALLY manages it (flair#2040).
763
821
  if (process.platform === "darwin") {
764
822
  const harperBinPath = harperBin();
765
823
  if (harperBinPath) {
@@ -767,19 +825,6 @@ export function register(program) {
767
825
  const plistDir = defaultLaunchAgentsDir();
768
826
  mkdirSync(plistDir, { recursive: true });
769
827
  const plistPath = launchdPlistPath(label, plistDir);
770
- // flair#693 + flair#966: a pre-flair#693 install registered under
771
- // the bare LEGACY_LAUNCHD_LABEL. init always writes fresh plist
772
- // content below (it has the current ports/creds in hand), so
773
- // migration here is just "clean up the old registration" —
774
- // unload + remove it BEFORE writing the new one, so re-running
775
- // init never leaves two services behind for this data dir.
776
- //
777
- // flair#966: the legacy plist is NOT scoped to this data dir —
778
- // it is a single global label. cleanupLegacyLaunchdPlist reads
779
- // ROOTPATH to establish ownership before touching it.
780
- cleanupLegacyLaunchdPlist(dataDir, plistDir, (cmd) => {
781
- execSync(cmd, { stdio: "pipe" });
782
- });
783
828
  const opsSocket = join(dataDir, "operations-server");
784
829
  // authorizeLocal: false (flair#654) — same posture as the initial spawn
785
830
  // above; the launchd-managed process must not diverge from it.
@@ -804,32 +849,86 @@ export function register(program) {
804
849
  // emits the pass-file launcher and never HDB_ADMIN_PASSWORD. It reuses
805
850
  // an existing valid ~/.flair/admin-pass, or proves the credential in
806
851
  // hand against this (now-healthy) instance and writes it 0600, or
807
- // refuses without writing a plist. An already-adopted instance is left
808
- // byte-for-byte unchanged rather than downgraded to the inline shape.
809
- const outcome = await writeInitLaunchdPlist({
852
+ // refuses without writing a plist. An already-adopted instance is never
853
+ // regenerated or downgraded to the inline shape; only its runtime paths
854
+ // are re-pointed, when it is provably this instance's plist serving
855
+ // another npm-global tree (flair#2034 — see src/lib/service-repoint.ts).
856
+ //
857
+ // flair#693 + flair#966 + flair#2040: a pre-flair#693 install
858
+ // registered under the bare LEGACY_LAUNCHD_LABEL is retired here, but
859
+ // only when ROOTPATH proves it is this data dir's — and when its job
860
+ // is the process SERVING this instance, retiring it stops Flair, so
861
+ // registerInitLaunchdService preflights the launchd domain and
862
+ // validates the replacement BEFORE unloading anything, loads and
863
+ // verifies the replacement, and restores the legacy job on failure.
864
+ //
865
+ // flair#2040: NEVER a check mark for a load that did not happen. The
866
+ // step reports "launchd-managed ✓" only when launchd is verified to
867
+ // run the process serving this instance; otherwise it says the plist
868
+ // is on disk and Flair runs directly, with the reason. The plist
869
+ // writer's own outcome (written / unchanged / re-pointed / not
870
+ // re-pointed, flair#2034) is reported in the same lines.
871
+ const launchdStep = await registerInitLaunchdService({
810
872
  dataDir,
811
- plistPath,
812
- label,
813
- adminPass,
814
- adminUser,
815
- modelsDir,
816
- execPath: process.execPath,
817
- harperBinPath,
818
- workingDirectory: flairPackageDir(),
819
- httpPort: httpBind.bindValue,
820
- opsNetworkPort: opsNetworkPortValue(opsBindHost, opsPort),
821
- setConfig,
822
873
  port: httpPort,
874
+ plistDir,
875
+ write: {
876
+ dataDir,
877
+ plistPath,
878
+ label,
879
+ adminPass,
880
+ adminUser,
881
+ modelsDir,
882
+ execPath: preferVersionManagerAlias(process.execPath),
883
+ harperBinPath,
884
+ workingDirectory: flairPackageDir(),
885
+ httpPort: httpBind.bindValue,
886
+ opsNetworkPort: opsNetworkPortValue(opsBindHost, opsPort),
887
+ setConfig,
888
+ port: httpPort,
889
+ },
823
890
  });
824
- if (outcome.kind === "refused") {
825
- console.error(`Error: ${outcome.detail}`);
891
+ for (const line of launchdStep.lines) {
892
+ (line.stream === "err" ? console.error : console.log)(line.text);
893
+ }
894
+ if (launchdStep.kind === "refused" || launchdStep.kind === "down" || launchdStep.kind === "uncertain") {
826
895
  process.exit(1);
827
896
  }
828
- console.log(outcome.kind === "unchanged"
829
- ? "Launchd service already managed — plist unchanged ✓"
830
- : "Launchd service registered ✓");
831
897
  }
832
898
  }
899
+ // flair#2034 §2: on Linux the instance's own service is the systemd
900
+ // USER unit proven to own the serving process (flair writes none). A
901
+ // unit that serves another npm-global tree is re-pointed — runtime paths
902
+ // only — and systemd is reloaded; anything else is left alone.
903
+ if (process.platform === "linux") {
904
+ const r = repointMainServiceUnit(dataDir, httpPort);
905
+ if (r.kind === "repointed") {
906
+ console.log(`Systemd user unit re-pointed at this CLI's install tree ✓ — ${r.detail}`);
907
+ console.log(" It takes effect when systemd next starts the unit: flair restart");
908
+ }
909
+ else if (r.kind === "refused") {
910
+ console.warn(`Systemd user unit left unchanged — ${r.detail}`);
911
+ }
912
+ else if (r.kind === "pinned-node") {
913
+ console.log(`Systemd user unit left as it is — ${r.detail}`);
914
+ }
915
+ }
916
+ // flair#2034 §2: the federation-sync shim bakes the node + flair paths
917
+ // of the runtime that enabled it. When it runs another npm-global tree,
918
+ // re-point its exec line (only that line; the scheduler unit is never
919
+ // rewritten). A machine that never enabled federation sync is left alone.
920
+ try {
921
+ const fed = rewriteFederationSchedulerRuntime();
922
+ if (fed.status === "rewritten") {
923
+ console.log(`Federation sync shim re-pointed at this CLI's install tree ✓ — ${fed.detail}`);
924
+ }
925
+ else if (fed.status === "refused") {
926
+ console.warn(`Federation sync shim left unchanged — ${fed.detail}`);
927
+ }
928
+ }
929
+ catch (err) {
930
+ console.warn(`Could not check the federation sync shim: ${err?.message ?? err}`);
931
+ }
833
932
  }
834
933
  if (pendingAdminPassRotate) {
835
934
  // Same gate as the post-health path: readiness is the operations
@@ -899,9 +998,16 @@ export function register(program) {
899
998
  pubKeyB64url = b64url(kp.publicKey);
900
999
  console.log(`Keypair written: ${privPath} ✓`);
901
1000
  }
902
- // Seed agent via operations API
1001
+ // Seed agent via operations API. Unlike the pre-auth observation,
1002
+ // which is one read, a 401 names a pid only when the read before the
1003
+ // insert and the read after the rejection are the same sole PID. The
1004
+ // HTTP port's holder is not an input and is not assumed to have caused
1005
+ // the rejection. Several holders, or a holder that changed during the
1006
+ // request, stay unattributed. Init started Harper itself → no listener,
1007
+ // and that 401 keeps the credential hint.
903
1008
  console.log(`Seeding agent '${agentId}' via operations API...`);
904
- await seedAgentViaOpsApi(opsPort, agentId, pubKeyB64url, adminUser, adminPass);
1009
+ const opsListener = skippedOwnStart ? operationsPortAttribution(opsPort) : undefined;
1010
+ await seedAgentViaOpsApi(opsPort, agentId, pubKeyB64url, adminUser, adminPass, opsListener);
905
1011
  console.log(`Agent '${agentId}' registered ✓`);
906
1012
  // Verify Ed25519 auth
907
1013
  console.log("Verifying Ed25519 auth...");
@@ -4,7 +4,7 @@ import nacl from "tweetnacl";
4
4
  import * as render from "../render.js";
5
5
  import { defaultKeysDir, resolveAdminUser, resolveLocalAdminPass } from "../lib/auth-resolve.js";
6
6
  import { resolveAgentKeyPath, loadEd25519PrivateKeyFromFile, signClientAssertion, buildTokenRequestForm, getMcpAccessToken, McpTokenRequestError, defaultMcpClientId, defaultMcpTokenEndpoint, defaultMcpResource, defaultMcpIssuer, MAX_ASSERTION_LIFETIME_SECONDS, } from "../mcp-client-assertion.js";
7
- import { enableMcp, disableMcp, mcpStatus, checkLocalOriginRefusal, selfVerifyMcpMetadata, } from "../lib/mcp-enable.js";
7
+ import { enableMcp, disableMcp, mcpStatus, checkLocalOriginRefusal, selfVerifyMcpMetadata, cimdAllowedHostsFromFlag, claudeAiExcludedNote, } from "../lib/mcp-enable.js";
8
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). */
@@ -285,6 +285,25 @@ async function promptText(question) {
285
285
  const answer = await new Promise((res) => rl.question(question, (a) => { rl.close(); res(a); }));
286
286
  return answer.trim();
287
287
  }
288
+ /**
289
+ * flair#2113 review: the closing lines of a successful `flair mcp enable`.
290
+ * They claim only what the run checked: the self-verify step's OAuth metadata
291
+ * check (the /mcp route itself is not probed), and, when this run confirmed a
292
+ * --cimd-allowed-hosts list (ensured it in config.yaml, writing the list only
293
+ * if the file did not already hold that exact list, and read it back), whether
294
+ * that list includes claude.ai. With no flag the command does not inspect
295
+ * allowedHosts, so it says nothing about claude.ai.
296
+ */
297
+ export function enableSuccessLines(result) {
298
+ const lines = [
299
+ `${render.icons.ok} ${render.wrap(render.c.bold, "The OAuth metadata check passed.")} The /mcp route itself was not probed.`,
300
+ ];
301
+ const claudeAiNote = claudeAiExcludedNote(result.cimdAllowedHosts);
302
+ if (claudeAiNote)
303
+ lines.push(`${render.icons.info} ${claudeAiNote}`);
304
+ lines.push("", result.pasteBlock ?? "", "");
305
+ return lines;
306
+ }
288
307
  function printEnableSteps(result) {
289
308
  console.log(`\n${render.wrap(render.c.bold, "flair mcp enable")}${result.dryRun ? render.wrap(render.c.dim, " (dry run)") : ""}\n`);
290
309
  for (const s of result.steps) {
@@ -536,12 +555,18 @@ export function register(program) {
536
555
  .option("--principal-kind <human|agent>", "Kind for a newly-created principal", "human")
537
556
  .option("--secrets-mechanism <fabric-env-secrets|env-file>", "Override the shape-aware secrets mechanism (else auto-detected from --instance)")
538
557
  .option("--secrets-path <path>", "Override the secrets staging file path")
539
- .option("--cimd-allowed-hosts <hosts>", "Comma-separated clientIdMetadataDocuments.allowedHosts override (else claude.ai,claude.com)")
558
+ .option("--cimd-allowed-hosts <hosts>", "Comma-separated lowercase hostnames to ensure as mcp.clientIdMetadataDocuments.allowedHosts in the config.yaml " +
559
+ "this command edits on this machine (./config.yaml, else ~/.flair/config.yaml), written unless that file already holds " +
560
+ "that exact list, then read back, before the restart. " +
561
+ "Without --dry-run, refused unless a preflight match links the host and pid the target reports, a readable " +
562
+ "process on this machine, and that file (by realpath); --dry-run skips the match and writes nothing. " +
563
+ "Always refused for a *.harperfabric.com instance. " +
564
+ "Without it the list is not changed (shipped: claude.ai,claude.com)")
540
565
  .option("--signing-key-file <path>", "RS256 signing key PEM file (else ~/.flair/mcp-signing-key.pem)")
541
566
  .option("--admin-pass <pass>", "Admin password for the TARGET instance. Required explicitly for a remote target — FLAIR_ADMIN_PASS and ~/.flair/admin-pass are this machine's local credentials and are never sent to a remote instance")
542
567
  .option("--admin-user <name>", "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)")
543
568
  .option("--confirm-secrets-applied", "Confirm the staged secrets are already live on the target instance's environment (skips the interactive confirm)")
544
- .option("--dry-run", "Generate keys/tokens/config and validate inputs; skip every remote call")
569
+ .option("--dry-run", "Validate inputs and report the signing key a real run would reuse or generate; write no file and make no remote call")
545
570
  .option("--json", "Print machine-readable JSON instead of a human summary")
546
571
  .action(async (opts) => {
547
572
  const instance = opts.instance ?? process.env.FLAIR_URL;
@@ -557,6 +582,14 @@ export function register(program) {
557
582
  console.error(`${render.icons.error} ${localCheck.message}`);
558
583
  process.exit(1);
559
584
  }
585
+ // flair#2113: an invalid --cimd-allowed-hosts, or one for a Fabric
586
+ // instance, is refused here, before anything is asked for. An explicit empty
587
+ // value is refused too: it used to be dropped as if the flag were absent.
588
+ const cimdFlag = cimdAllowedHostsFromFlag(opts.cimdAllowedHosts, instance);
589
+ if (cimdFlag.error) {
590
+ console.error(`${render.icons.error} ${cimdFlag.error}`);
591
+ process.exit(1);
592
+ }
560
593
  const dryRun = Boolean(opts.dryRun);
561
594
  // --instance is ALWAYS remote for this command (local is refused above)
562
595
  // — isRemoteTarget=true so a missing --admin-pass/FLAIR_ADMIN_PASS never
@@ -564,8 +597,8 @@ export function register(program) {
564
597
  // against someone else's instance (see resolveLocalAdminPass's doc comment).
565
598
  const adminPass = dryRun ? (opts.adminPass ?? process.env.FLAIR_ADMIN_PASS ?? "") : resolveLocalAdminPass(opts.adminPass, /* isRemoteTarget */ true);
566
599
  if (!dryRun && !adminPass) {
567
- console.error("Error: --admin-pass <pass> or --admin-pass-file <path> is required for a REMOTE target " +
568
- "(the operations API on the target instance needs it for identity mapping + restart).\n" +
600
+ console.error("Error: --admin-pass <pass> is required for a REMOTE target " +
601
+ "(the command authenticates to the target instance's operations API with it).\n" +
569
602
  " FLAIR_ADMIN_PASS and ~/.flair/admin-pass are deliberately NOT used here: they are THIS machine's " +
570
603
  "local admin credentials, and sending them to another instance is how a local secret ends up on someone " +
571
604
  "else's Harper. Pass the target's own admin password explicitly.");
@@ -587,9 +620,6 @@ export function register(program) {
587
620
  console.error(`Error: --secrets-mechanism must be "fabric-env-secrets" or "env-file", got "${secretsMechanism}"`);
588
621
  process.exit(1);
589
622
  }
590
- const cimdAllowedHosts = opts.cimdAllowedHosts
591
- ? String(opts.cimdAllowedHosts).split(",").map((h) => h.trim()).filter(Boolean)
592
- : undefined;
593
623
  const result = await enableMcp({
594
624
  instance,
595
625
  issuer: opts.issuer,
@@ -604,7 +634,7 @@ export function register(program) {
604
634
  signingKeyFilePath: opts.signingKeyFile,
605
635
  secretsMechanism,
606
636
  secretsStagingPath: opts.secretsPath,
607
- cimdAllowedHosts,
637
+ cimdAllowedHosts: cimdFlag.hosts,
608
638
  dryRun,
609
639
  confirmSecretsApplied: Boolean(opts.confirmSecretsApplied),
610
640
  }, { confirmPrompt: dryRun ? undefined : confirmYesNo });
@@ -620,15 +650,17 @@ export function register(program) {
620
650
  }
621
651
  if (!result.ok) {
622
652
  if (result.failedStep === "fabric-operator-deploy") {
623
- // flair#1136: Fabric deployments require the operator to deploy the
624
- // config change — we can't write to harperdb-config.yaml (Fabric
625
- // regenerates it on every container restart).
653
+ // flair#1136/#1152: on Fabric, `enable` never restarts the instance and
654
+ // needs no config edit (config.yaml ships mcp.enabled as an env
655
+ // reference). The operator addresses the cause the step reports (applying
656
+ // the environment and restarting when it says so); a re-run then passes
657
+ // this step once self-verify does (flair#2116).
658
+ // The step's own detail above carries the specifics.
626
659
  console.error(`\n${render.icons.info} ${render.wrap(render.c.bold, "Fabric deployment detected.")}`);
627
- console.error(` The @harperfast/oauth block ships in your component config.yaml with mcp.enabled: false.`);
628
- console.error(` To activate: set mcp.enabled: true (literal boolean) in your deployed component`);
629
- console.error(` config.yaml, ensure the staged secrets are live in the instance's process`);
630
- console.error(` environment, and redeploy. Then re-run \`flair mcp enable\` — earlier steps`);
631
- console.error(` are idempotent and will be reused.\n`);
660
+ console.error(` The /mcp OAuth surface did not pass self-verify on the public origin yet; the step above says why`);
661
+ console.error(` and what to do. Address that cause (restart the instance if its environment changed), then re-run`);
662
+ console.error(` \`flair mcp enable\` with the same options plus --confirm-secrets-applied: that step checks again`);
663
+ console.error(` and passes once self-verify does.\n`);
632
664
  }
633
665
  else {
634
666
  console.error(`${render.icons.error} enable failed at step "${result.failedStep}" — see detail above for the exact fix, then re-run \`flair mcp enable\` (earlier steps are idempotent and will be reused).`);
@@ -639,15 +671,14 @@ export function register(program) {
639
671
  console.log(`${render.icons.info} ${render.wrap(render.c.dim, "dry-run: no remote calls were made.")}`);
640
672
  return;
641
673
  }
642
- console.log(`${render.icons.ok} ${render.wrap(render.c.bold, "claude.ai can now connect.")}\n`);
643
- console.log(result.pasteBlock ?? "");
644
- console.log("");
674
+ for (const line of enableSuccessLines(result))
675
+ console.log(line);
645
676
  });
646
677
  mcp
647
678
  .command("disable")
648
679
  .description("Flag off + restart = byte-identical boot (Model-2 contract) — removes the /mcp OAuth surface.")
649
680
  .option("--instance <url>", "Remote flair instance to disable against (else FLAIR_URL)")
650
- .option("--admin-pass <pass>", "Admin password for the target instance (or FLAIR_ADMIN_PASS)")
681
+ .option("--admin-pass <pass>", "Admin password for the remote target instance; pass it explicitly with --admin-pass")
651
682
  .option("--admin-user <name>", "Admin username for Basic auth (env: FLAIR_ADMIN_USER; default: admin)")
652
683
  .option("--confirm-flag-off", "Confirm FLAIR_MCP_OAUTH is already unset on the target instance's environment (skips the interactive confirm)")
653
684
  .option("--json", "Print machine-readable JSON instead of a human summary")
@@ -661,7 +692,7 @@ export function register(program) {
661
692
  // comment in `mcp enable` above.
662
693
  const adminPass = resolveLocalAdminPass(opts.adminPass, /* isRemoteTarget */ true);
663
694
  if (!adminPass) {
664
- console.error("Error: --admin-pass or FLAIR_ADMIN_PASS required.");
695
+ console.error("Error: --admin-pass <pass> is required for a REMOTE target. Pass the target instance's admin password explicitly.");
665
696
  process.exit(1);
666
697
  }
667
698
  const result = await disableMcp({ instance, adminUser: resolveAdminUser(opts.adminUser), adminPass, confirmFlagOff: Boolean(opts.confirmFlagOff) }, { confirmPrompt: confirmYesNo });
@@ -1,3 +1,17 @@
1
+ /**
2
+ * memory.ts — `flair memory` command group (flair#1621 / epic #1618).
3
+ *
4
+ * Extracted from src/cli.ts with ZERO behavior change. This file owns the
5
+ * group's commander registration, action handlers, and group-specific
6
+ * inline helpers (hygiene predicates). Shared CLI helpers (api,
7
+ * resolveSigningAgentId, credential flags, --entities parse, …) stay in
8
+ * cli.ts and are bound before register().
9
+ *
10
+ * Compiled with the rest of src/ under tsconfig.check.src.json (strict).
11
+ * Do not import src/cli.ts from here — that would cycle and pull the
12
+ * non-strict entry into the strict check.
13
+ */
14
+ import { Option } from "commander";
1
15
  import * as render from "../render.js";
2
16
  import { resolveAdminUser } from "../lib/auth-resolve.js";
3
17
  let cli;
@@ -127,7 +141,7 @@ export function register(program) {
127
141
  // before resetting the session.
128
142
  //
129
143
  // The shape of this row matters: tags=['task-summary','auto-on-reset'] +
130
- // subject='task:<beads-id>' + summary populated. Slice 3+4 (harness
144
+ // subject='task:<reference>' + summary when supplied. Slice 3+4 (harness
131
145
  // integrations) will call this as part of the reset pipeline; slice 5+6
132
146
  // (operator surfaces) will surface promote/restore controls. Today, this
133
147
  // command is independently useful — operator can capture a manual summary
@@ -138,13 +152,15 @@ export function register(program) {
138
152
  memory.command("write-task-summary")
139
153
  .description("Capture a structured task summary as a persistent Memory row (used by session-reset harness; standalone-callable by operators)")
140
154
  .requiredOption("--agent <id>", "Agent the summary belongs to")
141
- .requiredOption("--beads <ops-id>", "Bead/PR/task identifier this summary is about")
155
+ .option("--ref <ref>", "Task reference (optional)")
156
+ .addOption(new Option("--beads <ops-id>", "Deprecated alias for --ref").hideHelp())
142
157
  .requiredOption("--outcome <s>", "Outcome of the task: merged | rejected | abandoned")
143
158
  .option("--summary <text>", "Multi-sentence dense compression (populates Memory.summary; will be the agent's read-time view)")
144
159
  .option("--files-touched <csv>", "Comma-separated list of files touched during the task (becomes part of content)")
145
160
  .option("--lessons <text>", "Lessons learned during the task (becomes part of content)")
146
161
  .option("--derived-from <csv>", "Comma-separated list of source Memory IDs this summary was distilled from")
147
162
  .action(async (opts) => {
163
+ opts.beads = opts.ref ?? opts.beads ?? "unreferenced";
148
164
  const validOutcomes = new Set(["merged", "rejected", "abandoned"]);
149
165
  if (!validOutcomes.has(opts.outcome)) {
150
166
  console.error(`Error: --outcome must be one of: merged, rejected, abandoned (got: ${opts.outcome})`);
@@ -203,6 +219,7 @@ export function register(program) {
203
219
  .option("--agent <id>", "Agent ID (or set FLAIR_AGENT_ID env)")
204
220
  .option("--admin-pass <pass>", "Admin password — sign as admin while --agent names whose memories to search (flair#1500: a flag-pinned agent with no key no longer falls back to FLAIR_ADMIN_PASS)")
205
221
  .option("--q <query>", "search query (alias for positional arg)")
222
+ .option("--json", "Output raw JSON array")
206
223
  .option("--limit <n>", "Max results", "5")
207
224
  .option("--tag <tag>")
208
225
  .option("--include-archived", "Include basemented (archived) memories in results (default: excluded)")
@@ -227,6 +244,11 @@ export function register(program) {
227
244
  body.includeArchived = true;
228
245
  const baseUrl = resolveBaseUrl(opts);
229
246
  const res = await api("POST", "/SemanticSearch", body, { baseUrl, agentId, agentIdSource: source, explicitAdminPass: opts.adminPass });
247
+ if (opts.json) {
248
+ const results = res.results || res || [];
249
+ console.log(render.asJSON(Array.isArray(results) ? results : []));
250
+ return;
251
+ }
230
252
  console.log(JSON.stringify(res, null, 2));
231
253
  });
232
254
  // ─── flair memory basement / restore ────────────────────────────────────────
@@ -32,17 +32,20 @@ export const QUALITY_HASH_FALLBACK_DEGRADED_PCT = 10;
32
32
  export const QUALITY_RECALL_SAMPLE_SIZE = 10;
33
33
  export const QUALITY_RECALL_K = 5;
34
34
  /**
35
- * Fields the recall spot-check and the quality-snapshot lookup actually
36
- * read. Harper REST `select(...)` (same syntax adk-flair-js's listMemories
37
- * already uses) projects these server-side so the nightly sweep never
38
- * pulls embedding vectors inline — the defect in flair#1360 was an
39
- * unfiltered `GET /Memory?agentId=…` that returned every row's 768-d
40
- * vector (~66 MB × 2 per `--emit` run on a 3k-row store) just to sample
41
- * 10 memories. `archived` is projected so the planner can drop basemented
42
- * rows before sampling (flair#857 — SemanticSearch excludes them, so an
43
- * archived row in the sample is a guaranteed miss). `type` is intentionally
44
- * omitted: it is not a declared Memory column (see schemas/memory.graphql);
45
- * snapshot exclusion keys off `subject` (`quality-snapshot/…`).
35
+ * Fields the recall spot-check and the quality-snapshot lookup READ from the
36
+ * list response. The request still carries a Harper REST `select(...)` (the same
37
+ * syntax adk-flair-js's listMemories uses), but a non-admin Memory read IGNORES
38
+ * the caller's selection (flair#1940): the response is the FULL stored row,
39
+ * which can include the 768-d embedding vector (the inline cost flair#1360
40
+ * measured on an unfiltered `GET /Memory?agentId=…` — ~66 MB × 2 per `--emit`
41
+ * run on a 3k-row store). The select is retained because a reader that does
42
+ * honour it (an admin) gets the projection, and it documents the fields the
43
+ * planner maps; the planner must not assume the response is reduced to them.
44
+ * `archived` is named so the planner can drop basemented rows before sampling
45
+ * (flair#857 — SemanticSearch excludes them, so an archived row in the sample
46
+ * is a guaranteed miss). `type` is intentionally omitted: it is not a declared
47
+ * Memory column (see schemas/memory.graphql); snapshot exclusion keys off
48
+ * `subject` (`quality-snapshot/…`).
46
49
  */
47
50
  export const QUALITY_MEMORY_LIST_SELECT = ["id", "subject", "content", "createdAt", "archived"];
48
51
  /**
@@ -56,7 +59,9 @@ export const QUALITY_MEMORY_LIST_SELECT = ["id", "subject", "content", "createdA
56
59
  export const QUALITY_RECALL_SNAPSHOT_OVERFETCH = 16;
57
60
  /**
58
61
  * Harper REST collection path for the recall spot-check's sample fetch:
59
- * agent-scoped, projected (never `embedding`), recency-sorted, bounded.
62
+ * agent-scoped, recency-sorted, bounded. The server returns the FULL stored
63
+ * row — a non-admin Memory read ignores the selection (see the field-list
64
+ * note above) — so `limit` is what bounds the fetch, not the `select`.
60
65
  * `limit(start,end)` is Harper's offset window — same as
61
66
  * packages/adk-flair-js/src/memory_service.ts.
62
67
  */
@@ -67,7 +72,8 @@ export function qualityRecallSamplePath(agentId, sampleSize = QUALITY_RECALL_SAM
67
72
  }
68
73
  /**
69
74
  * Harper REST collection path for the previous quality-snapshot lookup:
70
- * same projection as the sample fetch (never `embedding`). Subject is
75
+ * the same field list as the sample fetch (the server returns the full
76
+ * stored row; a non-admin read ignores the selection). Subject is
71
77
  * passed as a query equals (indexed) plus a client-side re-filter —
72
78
  * Memory.search() historically did not turn bare query params into
73
79
  * conditions beyond the signed agent scope, so the client-side filter
@@ -470,9 +476,10 @@ export function computeQualityReport(healthy, healthData, opts = {}) {
470
476
  * The I/O half of the recall spot-check (Slice 1d): fetch a sample of
471
477
  * `agentId`'s own memories and, for each, search for a cue derived from it.
472
478
  * Reuses the EXACT read path `flair memory search` / `flair memory list`
473
- * use — `api()` (→ authedRequest's 5-tier resolver) for both the
474
- * projected, bounded `GET /Memory?…&select(…)&limit(…)` sample fetch
475
- * (flair#1360 — never the unfiltered collection with embeddings inline)
479
+ * use — `api()` (→ authedRequest's 5-tier resolver) for the
480
+ * bounded `GET /Memory?…&select(…)&limit(…)` sample fetch (flair#1360;
481
+ * the server returns the full stored row because a non-admin read ignores
482
+ * the selection, so `limit` bounds the fetch, not the `select`)
476
483
  * and the `POST /SemanticSearch` queries — so this has zero new endpoint
477
484
  * and zero new auth mechanism; it is scoped to `agentId`'s own memories
478
485
  * exactly as those commands already are. Never throws: every failure mode
@@ -884,8 +891,9 @@ export function register(program) {
884
891
  // from /HealthDetail at all — it's the one metric in this file that requires
885
892
  // live QUERIES, because it's checking whether querying itself still works.
886
893
  // For a sample of the querying agent's OWN memories (fetchRecallSpotCheckData
887
- // below, a projected+bounded GET /Memory — flair#1360: never the unfiltered
888
- // collection with embeddings inline), a CUE is derived from each memory
894
+ // below, a bounded GET /Memory — flair#1360; the server returns the full stored
895
+ // row because a non-admin read ignores the selection, so `limit` bounds the
896
+ // fetch), a CUE is derived from each memory
889
897
  // (deriveRecallCue — its `subject` if present, else the leading ~8 words /
890
898
  // first sentence of `content`; a PARTIAL cue, never the full content) and
891
899
  // searched for through the EXACT SAME authenticated read path `flair memory