@tpsdev-ai/flair 0.56.0 → 0.58.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 (153) hide show
  1. package/README.md +19 -20
  2. package/SECURITY.md +4 -1
  3. package/dist/build-info.json +3 -3
  4. package/dist/cli.js +1800 -293
  5. package/dist/commands/agent.js +22 -15
  6. package/dist/commands/bridge.js +40 -3
  7. package/dist/commands/doctor.js +214 -4
  8. package/dist/commands/federation.js +265 -38
  9. package/dist/commands/hook.js +10 -2
  10. package/dist/commands/init.js +179 -48
  11. package/dist/commands/memory.js +24 -2
  12. package/dist/commands/quality.js +26 -18
  13. package/dist/commands/service.js +137 -22
  14. package/dist/commands/status.js +114 -3
  15. package/dist/commands/upgrade.js +204 -84
  16. package/dist/doctor-client.js +50 -4
  17. package/dist/federation/scheduler.js +253 -4
  18. package/dist/install/clients.js +89 -23
  19. package/dist/install/global-bin-path.js +26 -6
  20. package/dist/lib/atomic-write.js +256 -0
  21. package/dist/lib/auth-resolve.js +46 -0
  22. package/dist/lib/daemon-liveness.js +61 -0
  23. package/dist/lib/doctor-run.js +5 -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/init-admin-pass.js +4 -2
  27. package/dist/lib/init-listener-environ.js +38 -0
  28. package/dist/lib/init-occupied-listener.js +165 -0
  29. package/dist/lib/instance-identity-row.js +580 -0
  30. package/dist/lib/launchd-domain-preflight.js +448 -0
  31. package/dist/lib/launchd-management.js +176 -6
  32. package/dist/lib/launchd-repair.js +95 -0
  33. package/dist/lib/memory-attributes.js +77 -0
  34. package/dist/lib/node-alias-path.js +95 -0
  35. package/dist/lib/npm-registry.js +119 -6
  36. package/dist/lib/owned-pins.js +20 -6
  37. package/dist/lib/redact-token-id.js +197 -0
  38. package/dist/lib/service-repoint-apply.js +267 -0
  39. package/dist/lib/service-repoint.js +575 -0
  40. package/dist/lib/toml-string-array.js +104 -0
  41. package/dist/lib/tree-divergence.js +716 -0
  42. package/dist/lib/upgrade-plain-tree.js +18 -8
  43. package/dist/lib/upgrade-prior-liveness.js +69 -0
  44. package/dist/lib/upgrade-rollback.js +116 -0
  45. package/dist/rem/runner.js +11 -0
  46. package/dist/resources/Agent.js +27 -14
  47. package/dist/resources/AgentSeed.js +39 -2
  48. package/dist/resources/Asset.js +3 -11
  49. package/dist/resources/Credential.js +4 -10
  50. package/dist/resources/Federation.js +299 -127
  51. package/dist/resources/Integration.js +8 -32
  52. package/dist/resources/Memory.js +623 -86
  53. package/dist/resources/MemoryArchive.js +9 -0
  54. package/dist/resources/MemoryBootstrap.js +23 -12
  55. package/dist/resources/MemoryCandidate.js +3 -11
  56. package/dist/resources/MemoryDedupStats.js +1 -1
  57. package/dist/resources/MemoryFeed.js +214 -5
  58. package/dist/resources/MemoryGrant.js +19 -40
  59. package/dist/resources/MemoryHostSource.js +90 -0
  60. package/dist/resources/MemoryMaintenance.js +121 -32
  61. package/dist/resources/MemoryReflect.js +4 -1
  62. package/dist/resources/MemoryReindex.js +7 -4
  63. package/dist/resources/MemoryUsage.js +55 -18
  64. package/dist/resources/Presence.js +18 -10
  65. package/dist/resources/RecordUsage.js +30 -40
  66. package/dist/resources/Relationship.js +170 -89
  67. package/dist/resources/SemanticSearch.js +44 -19
  68. package/dist/resources/Soul.js +31 -19
  69. package/dist/resources/XAA.js +7 -3
  70. package/dist/resources/agent-auth.js +16 -10
  71. package/dist/resources/auth-middleware.js +164 -50
  72. package/dist/resources/auto-promote-lib.js +4 -4
  73. package/dist/resources/bm25-index-service.js +246 -32
  74. package/dist/resources/bm25-status.js +132 -0
  75. package/dist/resources/bm25.js +13 -14
  76. package/dist/resources/ed25519-auth.js +11 -54
  77. package/dist/resources/embed-gpu.js +262 -47
  78. package/dist/resources/embeddings-boot.js +52 -17
  79. package/dist/resources/federation-classify.js +12 -0
  80. package/dist/resources/federation-cleanup.js +289 -51
  81. package/dist/resources/federation-crypto.js +65 -19
  82. package/dist/resources/health.js +105 -22
  83. package/dist/resources/host-pointer/registry.js +35 -0
  84. package/dist/resources/host-pointer-adapter.js +15 -0
  85. package/dist/resources/host-source-visibility.js +167 -0
  86. package/dist/resources/host-source.js +151 -0
  87. package/dist/resources/in-process-api.js +2 -1
  88. package/dist/resources/instance-create-lock.js +363 -0
  89. package/dist/resources/instance-identity-rows.js +43 -0
  90. package/dist/resources/instance-identity.js +97 -12
  91. package/dist/resources/mcp-handler.js +155 -51
  92. package/dist/resources/mcp-tool-arguments.js +83 -0
  93. package/dist/resources/mcp-tools.js +28 -25
  94. package/dist/resources/memory-consolidate-lib.js +3 -1
  95. package/dist/resources/memory-declared-attributes.js +103 -0
  96. package/dist/resources/memory-feed-lib.js +5 -1
  97. package/dist/resources/memory-host-source.js +163 -0
  98. package/dist/resources/memory-visibility.js +10 -7
  99. package/dist/resources/migrations/synthetic-test-migration.js +4 -1
  100. package/dist/resources/migrations/visibility-backfill.js +4 -1
  101. package/dist/resources/originator-instance.js +235 -0
  102. package/dist/resources/promotion-stamp.js +2 -0
  103. package/dist/resources/provenance.js +111 -11
  104. package/dist/resources/rate-limit.js +6 -4
  105. package/dist/resources/record-owner-guard.js +19 -0
  106. package/dist/resources/record-type-kit.js +44 -23
  107. package/dist/resources/record-types.js +6 -6
  108. package/dist/resources/relay-ops.js +28 -3
  109. package/dist/resources/replay-store.js +289 -0
  110. package/dist/resources/request-transaction.js +78 -0
  111. package/dist/resources/search-readiness.js +26 -22
  112. package/dist/resources/semantic-retrieval-core.js +103 -4
  113. package/dist/resources/table-helpers.js +33 -0
  114. package/dist/resources/table-patch-policy.js +109 -0
  115. package/dist/resources/table-patches.js +17 -0
  116. package/dist/resources/table-post-policy.js +138 -0
  117. package/dist/resources/table-posts.js +22 -0
  118. package/dist/resources/table-subscription-policy.js +135 -0
  119. package/dist/resources/table-subscriptions.js +19 -0
  120. package/dist/resources/tool-descriptors/index.js +15 -15
  121. package/dist/resources/trust-block.js +10 -3
  122. package/dist/resources/usage-recording.js +169 -41
  123. package/dist/src/lib/instance-identity-row.js +580 -0
  124. package/dist/src/lib/memory-attributes.js +77 -0
  125. package/dist/src/lib/redact-token-id.js +197 -0
  126. package/docs/api-reference.md +80 -16
  127. package/docs/auth.md +5 -5
  128. package/docs/claude-code.md +137 -6
  129. package/docs/deploying-on-fabric.md +6 -3
  130. package/docs/deployment.md +1 -1
  131. package/docs/embedding-in-a-harper-app.md +3 -3
  132. package/docs/federation.md +17 -10
  133. package/docs/hosted-on-fabric.md +4 -3
  134. package/docs/integrations.md +28 -19
  135. package/docs/mcp-clients.md +26 -32
  136. package/docs/n8n.md +8 -8
  137. package/docs/notes/mcp-oauth-model2.md +27 -18
  138. package/docs/openclaw.md +29 -28
  139. package/docs/quickstart.md +5 -0
  140. package/docs/releasing.md +134 -2
  141. package/docs/spoke-bringup.md +14 -11
  142. package/docs/standalone-local.md +2 -2
  143. package/docs/supply-chain-policy.md +28 -10
  144. package/docs/system-requirements.md +1 -1
  145. package/docs/troubleshooting.md +11 -0
  146. package/docs/upgrade.md +189 -63
  147. package/package.json +9 -5
  148. package/schemas/agent.graphql +9 -6
  149. package/schemas/federation.graphql +2 -11
  150. package/schemas/memory.graphql +106 -17
  151. package/schemas/replay.graphql +18 -0
  152. package/templates/launchd/start-flair-with-admin-pass.sh +22 -0
  153. 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
  }
@@ -105,12 +105,29 @@ function resolveTarget(...args) {
105
105
  function runSoulWizard(...args) {
106
106
  return cli.runSoulWizard(...args);
107
107
  }
108
+ function reconcileFederationInstanceViaOpsApi(...args) {
109
+ return cli.reconcileFederationInstanceViaOpsApi(...args);
110
+ }
108
111
  function seedAgentViaOpsApi(...args) {
109
112
  return cli.seedAgentViaOpsApi(...args);
110
113
  }
111
114
  function seedFederationInstanceViaOpsApi(...args) {
112
115
  return cli.seedFederationInstanceViaOpsApi(...args);
113
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
+ }
114
131
  function shouldShowInlineSecretWarning(...args) {
115
132
  return cli.shouldShowInlineSecretWarning(...args);
116
133
  }
@@ -126,8 +143,11 @@ function waitForHealth(...args) {
126
143
  function writeDaemonSidecar(...args) {
127
144
  return cli.writeDaemonSidecar(...args);
128
145
  }
129
- function writeInitLaunchdPlist(...args) {
130
- return cli.writeInitLaunchdPlist(...args);
146
+ function registerInitLaunchdService(...args) {
147
+ return cli.registerInitLaunchdService(...args);
148
+ }
149
+ function repointMainServiceUnit(...args) {
150
+ return cli.repointMainServiceUnit(...args);
131
151
  }
132
152
  export function register(program) {
133
153
  const MQTT_DISABLED_CONFIG = cli.MQTT_DISABLED_CONFIG;
@@ -287,16 +307,38 @@ export function register(program) {
287
307
  else {
288
308
  console.log("No --agent-id provided -- skipping agent registration");
289
309
  }
290
- // Write FederationInstance row if --remote (hub role)
310
+ // Reconcile the federation Instance identity row if --remote (hub role).
311
+ // flair#1883: this used to INSERT a row with a fresh random id on every
312
+ // run, so a hub that had already answered a `GET /FederationInstance`
313
+ // (which find-or-creates a `spoke` row) ended up with TWO rows and no
314
+ // canonical identity. Reconciling keeps the row peers already know.
291
315
  if (role) {
292
316
  if (!pubKeyB64url) {
293
317
  const kp = nacl.sign.keyPair();
294
318
  pubKeyB64url = b64url(kp.publicKey);
295
319
  }
296
320
  instanceId = randomUUID();
297
- console.log(`Writing federation Instance (role=${role}) via ops API...`);
298
- await seedFederationInstanceViaOpsApi(opsUrl, instanceId, pubKeyB64url, role, adminUser, flairAdminPass);
299
- console.log(`Federation Instance created: ${instanceId} (${role}) ✓`);
321
+ console.log(`Reconciling federation Instance (role=${role}) via ops API...`);
322
+ let reconciled;
323
+ try {
324
+ reconciled = await reconcileFederationInstanceViaOpsApi(opsUrl, { instanceId, publicKey: pubKeyB64url }, adminUser, flairAdminPass);
325
+ }
326
+ catch (err) {
327
+ // A refusal (two rows) or an unreachable ops API — both are this
328
+ // command failing, and both already name what to do.
329
+ console.error(`Error: ${err?.message ?? err}`);
330
+ process.exit(1);
331
+ }
332
+ instanceId = reconciled.id;
333
+ if (reconciled.action === "created") {
334
+ console.log(`Federation Instance created: ${reconciled.id} (role=${role}) ✓`);
335
+ }
336
+ else if (reconciled.action === "updated") {
337
+ console.log(`Federation Instance reconciled: ${reconciled.id} is now role=${role} (id and key kept) ✓`);
338
+ }
339
+ else {
340
+ console.log(`Federation Instance already role=${role}: ${reconciled.id} — no change ✓`);
341
+ }
300
342
  }
301
343
  // Verify connectivity
302
344
  if (didProvision) {
@@ -452,11 +494,30 @@ export function register(program) {
452
494
  const reason = resolveInitAdminPasswordRefuseReason(fileExists, passwordCtx);
453
495
  if (!reason)
454
496
  return;
455
- console.error(initAdminPassRefusalMessage(reason, {
497
+ const message = initAdminPassRefusalMessage(reason, {
456
498
  dataDir,
457
499
  httpPort,
458
500
  adminPassPath,
459
- }));
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
+ }
460
521
  process.exit(1);
461
522
  };
462
523
  // Read from file if provided
@@ -576,9 +637,30 @@ export function register(program) {
576
637
  // The socket doesn't exist yet, so only the parent-dir mode is applied here.
577
638
  mkdirSync(dataDir, { recursive: true });
578
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;
579
647
  if (!opts.skipStart) {
580
648
  if (alreadyRunning) {
581
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;
582
664
  }
583
665
  if (!alreadyRunning) {
584
666
  const bin = harperBin();
@@ -733,8 +815,9 @@ export function register(program) {
733
815
  pendingAdminPassRotate = false;
734
816
  console.log(`Admin password saved to: ${adminPassPath}`);
735
817
  }
736
- // Register launchd service on macOS so Harper survives reboots
737
- // 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).
738
821
  if (process.platform === "darwin") {
739
822
  const harperBinPath = harperBin();
740
823
  if (harperBinPath) {
@@ -742,19 +825,6 @@ export function register(program) {
742
825
  const plistDir = defaultLaunchAgentsDir();
743
826
  mkdirSync(plistDir, { recursive: true });
744
827
  const plistPath = launchdPlistPath(label, plistDir);
745
- // flair#693 + flair#966: a pre-flair#693 install registered under
746
- // the bare LEGACY_LAUNCHD_LABEL. init always writes fresh plist
747
- // content below (it has the current ports/creds in hand), so
748
- // migration here is just "clean up the old registration" —
749
- // unload + remove it BEFORE writing the new one, so re-running
750
- // init never leaves two services behind for this data dir.
751
- //
752
- // flair#966: the legacy plist is NOT scoped to this data dir —
753
- // it is a single global label. cleanupLegacyLaunchdPlist reads
754
- // ROOTPATH to establish ownership before touching it.
755
- cleanupLegacyLaunchdPlist(dataDir, plistDir, (cmd) => {
756
- execSync(cmd, { stdio: "pipe" });
757
- });
758
828
  const opsSocket = join(dataDir, "operations-server");
759
829
  // authorizeLocal: false (flair#654) — same posture as the initial spawn
760
830
  // above; the launchd-managed process must not diverge from it.
@@ -779,32 +849,86 @@ export function register(program) {
779
849
  // emits the pass-file launcher and never HDB_ADMIN_PASSWORD. It reuses
780
850
  // an existing valid ~/.flair/admin-pass, or proves the credential in
781
851
  // hand against this (now-healthy) instance and writes it 0600, or
782
- // refuses without writing a plist. An already-adopted instance is left
783
- // byte-for-byte unchanged rather than downgraded to the inline shape.
784
- 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({
785
872
  dataDir,
786
- plistPath,
787
- label,
788
- adminPass,
789
- adminUser,
790
- modelsDir,
791
- execPath: process.execPath,
792
- harperBinPath,
793
- workingDirectory: flairPackageDir(),
794
- httpPort: httpBind.bindValue,
795
- opsNetworkPort: opsNetworkPortValue(opsBindHost, opsPort),
796
- setConfig,
797
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
+ },
798
890
  });
799
- if (outcome.kind === "refused") {
800
- 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") {
801
895
  process.exit(1);
802
896
  }
803
- console.log(outcome.kind === "unchanged"
804
- ? "Launchd service already managed — plist unchanged ✓"
805
- : "Launchd service registered ✓");
806
897
  }
807
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
+ }
808
932
  }
809
933
  if (pendingAdminPassRotate) {
810
934
  // Same gate as the post-health path: readiness is the operations
@@ -874,9 +998,16 @@ export function register(program) {
874
998
  pubKeyB64url = b64url(kp.publicKey);
875
999
  console.log(`Keypair written: ${privPath} ✓`);
876
1000
  }
877
- // 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.
878
1008
  console.log(`Seeding agent '${agentId}' via operations API...`);
879
- await seedAgentViaOpsApi(opsPort, agentId, pubKeyB64url, adminUser, adminPass);
1009
+ const opsListener = skippedOwnStart ? operationsPortAttribution(opsPort) : undefined;
1010
+ await seedAgentViaOpsApi(opsPort, agentId, pubKeyB64url, adminUser, adminPass, opsListener);
880
1011
  console.log(`Agent '${agentId}' registered ✓`);
881
1012
  // Verify Ed25519 auth
882
1013
  console.log("Verifying Ed25519 auth...");
@@ -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