@tpsdev-ai/flair 0.57.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 (122) hide show
  1. package/README.md +4 -4
  2. package/SECURITY.md +4 -1
  3. package/dist/build-info.json +3 -3
  4. package/dist/cli.js +1685 -279
  5. package/dist/commands/doctor.js +162 -4
  6. package/dist/commands/federation.js +2 -1
  7. package/dist/commands/hook.js +10 -2
  8. package/dist/commands/init.js +150 -44
  9. package/dist/commands/memory.js +24 -2
  10. package/dist/commands/quality.js +26 -18
  11. package/dist/commands/service.js +137 -22
  12. package/dist/commands/status.js +114 -3
  13. package/dist/commands/upgrade.js +204 -84
  14. package/dist/doctor-client.js +50 -4
  15. package/dist/federation/scheduler.js +253 -4
  16. package/dist/install/clients.js +89 -23
  17. package/dist/install/global-bin-path.js +26 -6
  18. package/dist/lib/atomic-write.js +256 -0
  19. package/dist/lib/daemon-liveness.js +61 -0
  20. package/dist/lib/doctor-run.js +5 -0
  21. package/dist/lib/embed-gpu-doctor.js +49 -26
  22. package/dist/lib/federation-memory-attributes.js +15 -0
  23. package/dist/lib/init-admin-pass.js +4 -2
  24. package/dist/lib/init-listener-environ.js +38 -0
  25. package/dist/lib/init-occupied-listener.js +165 -0
  26. package/dist/lib/launchd-domain-preflight.js +448 -0
  27. package/dist/lib/launchd-management.js +176 -6
  28. package/dist/lib/launchd-repair.js +95 -0
  29. package/dist/lib/memory-attributes.js +77 -0
  30. package/dist/lib/node-alias-path.js +95 -0
  31. package/dist/lib/npm-registry.js +119 -6
  32. package/dist/lib/owned-pins.js +20 -6
  33. package/dist/lib/service-repoint-apply.js +267 -0
  34. package/dist/lib/service-repoint.js +575 -0
  35. package/dist/lib/toml-string-array.js +104 -0
  36. package/dist/lib/tree-divergence.js +716 -0
  37. package/dist/lib/upgrade-plain-tree.js +18 -8
  38. package/dist/lib/upgrade-prior-liveness.js +69 -0
  39. package/dist/lib/upgrade-rollback.js +116 -0
  40. package/dist/rem/runner.js +11 -0
  41. package/dist/resources/Agent.js +27 -14
  42. package/dist/resources/AgentSeed.js +35 -1
  43. package/dist/resources/Federation.js +70 -52
  44. package/dist/resources/Memory.js +567 -72
  45. package/dist/resources/MemoryArchive.js +9 -0
  46. package/dist/resources/MemoryBootstrap.js +4 -0
  47. package/dist/resources/MemoryFeed.js +204 -3
  48. package/dist/resources/MemoryHostSource.js +90 -0
  49. package/dist/resources/MemoryMaintenance.js +121 -32
  50. package/dist/resources/MemoryReflect.js +4 -1
  51. package/dist/resources/MemoryReindex.js +7 -4
  52. package/dist/resources/MemoryUsage.js +53 -3
  53. package/dist/resources/Presence.js +18 -10
  54. package/dist/resources/RecordUsage.js +30 -40
  55. package/dist/resources/Relationship.js +167 -78
  56. package/dist/resources/SemanticSearch.js +19 -6
  57. package/dist/resources/Soul.js +31 -19
  58. package/dist/resources/XAA.js +7 -3
  59. package/dist/resources/agent-auth.js +16 -10
  60. package/dist/resources/auth-middleware.js +135 -48
  61. package/dist/resources/auto-promote-lib.js +4 -4
  62. package/dist/resources/bm25-index-service.js +246 -32
  63. package/dist/resources/bm25-status.js +132 -0
  64. package/dist/resources/ed25519-auth.js +11 -54
  65. package/dist/resources/embed-gpu.js +262 -47
  66. package/dist/resources/embeddings-boot.js +52 -17
  67. package/dist/resources/federation-classify.js +12 -0
  68. package/dist/resources/federation-crypto.js +65 -19
  69. package/dist/resources/health.js +57 -14
  70. package/dist/resources/host-pointer/registry.js +35 -0
  71. package/dist/resources/host-pointer-adapter.js +15 -0
  72. package/dist/resources/host-source-visibility.js +167 -0
  73. package/dist/resources/host-source.js +151 -0
  74. package/dist/resources/instance-identity.js +3 -2
  75. package/dist/resources/mcp-handler.js +147 -51
  76. package/dist/resources/mcp-tools.js +25 -21
  77. package/dist/resources/memory-consolidate-lib.js +3 -1
  78. package/dist/resources/memory-declared-attributes.js +103 -0
  79. package/dist/resources/memory-feed-lib.js +5 -1
  80. package/dist/resources/memory-host-source.js +163 -0
  81. package/dist/resources/migrations/synthetic-test-migration.js +4 -1
  82. package/dist/resources/migrations/visibility-backfill.js +4 -1
  83. package/dist/resources/originator-instance.js +235 -0
  84. package/dist/resources/promotion-stamp.js +2 -0
  85. package/dist/resources/provenance.js +111 -11
  86. package/dist/resources/record-owner-guard.js +19 -0
  87. package/dist/resources/record-type-kit.js +9 -12
  88. package/dist/resources/record-types.js +6 -6
  89. package/dist/resources/relay-ops.js +28 -3
  90. package/dist/resources/replay-store.js +289 -0
  91. package/dist/resources/request-transaction.js +78 -0
  92. package/dist/resources/search-readiness.js +19 -21
  93. package/dist/resources/semantic-retrieval-core.js +5 -1
  94. package/dist/resources/table-patch-policy.js +109 -0
  95. package/dist/resources/table-patches.js +17 -0
  96. package/dist/resources/table-post-policy.js +138 -0
  97. package/dist/resources/table-posts.js +22 -0
  98. package/dist/resources/table-subscription-policy.js +135 -0
  99. package/dist/resources/table-subscriptions.js +19 -0
  100. package/dist/resources/tool-descriptors/index.js +15 -15
  101. package/dist/resources/trust-block.js +10 -3
  102. package/dist/resources/usage-recording.js +169 -41
  103. package/dist/src/lib/memory-attributes.js +77 -0
  104. package/docs/api-reference.md +79 -15
  105. package/docs/claude-code.md +132 -0
  106. package/docs/deployment.md +1 -1
  107. package/docs/federation.md +1 -1
  108. package/docs/integrations.md +5 -5
  109. package/docs/mcp-clients.md +11 -21
  110. package/docs/notes/mcp-oauth-model2.md +15 -1
  111. package/docs/quickstart.md +5 -0
  112. package/docs/releasing.md +134 -2
  113. package/docs/supply-chain-policy.md +10 -5
  114. package/docs/troubleshooting.md +11 -0
  115. package/docs/upgrade.md +187 -61
  116. package/package.json +9 -5
  117. package/schemas/agent.graphql +9 -6
  118. package/schemas/federation.graphql +2 -11
  119. package/schemas/memory.graphql +106 -17
  120. package/schemas/replay.graphql +18 -0
  121. package/templates/launchd/start-flair-with-admin-pass.sh +22 -0
  122. package/dist/resources/federation-nonce-store.js +0 -195
@@ -1,20 +1,42 @@
1
1
  /**
2
2
  * embed-gpu.ts — stated gpuLayers default for in-process embedding (flair#1437).
3
3
  *
4
- * Harper-free so the detect → derive → override → fail-loud decision is
4
+ * Harper-free so the detect → derive → override → readback decision is
5
5
  * unit-testable without a live engine. embeddings-boot.ts is the only
6
6
  * production caller that talks to HFE; Health/HealthDetail read the stated
7
7
  * snapshot.
8
8
  *
9
- * HFE's EngineOptions.gpuLayers is input-only — it cannot confirm Metal
10
- * engaged. The confirmation signal is the same ggml_metal_init +
11
- * compute-buffer pair the ingest-throughput bench already greps (#1597).
12
- * A first-class HFE readback is a follow-up, not this change.
9
+ * Engagement is read from the engine after warmup (flair#2031). node-llama-cpp
10
+ * reports the loaded GPU backend as `Llama.gpu` / binding `getGpuType()`
11
+ * (`"metal" | "cuda" | "vulkan" | false`) and the offloaded layer count as
12
+ * `LlamaModel.gpuLayers` (the `n_gpu_layers` the model was constructed with;
13
+ * 0 when GPU support is disabled). HFE's `EmbeddingEngine` does not re-export
14
+ * those getters; it forwards `config.gpuLayers` unchanged into `AddonModel`
15
+ * and dlopens one native binding during warmup. Readback calls `getGpuType()`
16
+ * on that binding object. It does not search `bins/` or dlopen a second
17
+ * module — a different binary can report CPU while the warmed addon is on
18
+ * Metal. An empty stdout/stderr capture is not
19
+ * evidence of CPU — ggml writes `ggml_metal_init` to fd 2 via libc, which
20
+ * under launchd never reaches Node's streams. The launchd stderr log is not
21
+ * consulted either (host-specific, stale across restarts).
22
+ *
23
+ * `parseMetalEngaged` remains the ingest-throughput bench's log gate (#1597).
24
+ * It is not the product engagement decision.
13
25
  */
14
26
  import { createRequire } from "node:module";
15
27
  export const METAL_PREBUILT = "@node-llama-cpp/mac-arm64-metal";
16
- /** Fail-loud sentence. Never report GPU while this is the live statement. */
28
+ /**
29
+ * Fail-loud sentence. Only when the engine itself reports no GPU.
30
+ * Never report GPU while this is the live statement.
31
+ */
17
32
  export const EMBED_GPU_FALLBACK_MSG = "requested GPU offload; Metal did not engage; running CPU";
33
+ /**
34
+ * Offload was requested and the engine exposed no GPU type / layer count.
35
+ * This is not a CPU claim — Health must not pair it with `backend: "cpu"`
36
+ * or `gpuLayers: 0`.
37
+ */
38
+ export const EMBED_GPU_UNCONFIRMED_MSG = "requested GPU offload; Metal engagement unconfirmed";
39
+ export const EMBED_GPU_PENDING_MSG = "requested GPU offload; Metal engagement pending (warmup in progress)";
18
40
  const METAL_INIT_RE = /ggml_metal_init/i;
19
41
  const METAL_BUFFER_RE = /compute[- ]buffer/i;
20
42
  let stated = null;
@@ -81,7 +103,10 @@ function parseNonNegativeInt(raw) {
81
103
  return undefined;
82
104
  return n;
83
105
  }
84
- /** Prove GPU engagement from the engine / boot log. Requested ≠ used. */
106
+ /**
107
+ * Bench log gate (#1597 / #1436). Not the product engagement decision —
108
+ * a missing capture is not evidence the engine is on CPU (flair#2031).
109
+ */
85
110
  export function parseMetalEngaged(log) {
86
111
  const lines = (log ?? "").split(/\r?\n/);
87
112
  const evidence = lines.filter((l) => METAL_INIT_RE.test(l) || METAL_BUFFER_RE.test(l));
@@ -94,18 +119,196 @@ export function parseMetalEngaged(log) {
94
119
  evidence: evidence.slice(0, 12),
95
120
  };
96
121
  }
122
+ function isLayerCount(value) {
123
+ return typeof value === "number" && Number.isInteger(value) && value >= 0;
124
+ }
125
+ function isCpuGpuType(value) {
126
+ return value === false || value === "cpu";
127
+ }
128
+ function asNodeLlamaGpu(value) {
129
+ if (value === false || value === "metal" || value === "cuda" || value === "vulkan") {
130
+ return value;
131
+ }
132
+ return undefined;
133
+ }
134
+ /**
135
+ * Read GPU type and offloaded layer count from an engine object.
136
+ *
137
+ * Recognized shapes (the node-llama-cpp / native binding API, not logs):
138
+ * - `LlamaModel`: numeric `gpuLayers` and `llama.gpu`
139
+ * - the same pair flattened (`gpu` + `gpuLayers`)
140
+ * - binding `getGpuType()` plus numeric `gpuLayers` on the same object
141
+ *
142
+ * `gpu === false` (or `"cpu"`) is the engine saying no GPU device; offloaded
143
+ * layers are then 0, matching `LlamaModel.gpuLayers` when GPU support is
144
+ * disabled. A GPU type without a layer count, or a layer count without a
145
+ * type, is unavailable.
146
+ */
147
+ export function readEngineGpuEngagement(engine) {
148
+ try {
149
+ return readEngineGpuEngagementUnchecked(engine);
150
+ }
151
+ catch {
152
+ return { available: false };
153
+ }
154
+ }
155
+ function readEngineGpuEngagementUnchecked(engine) {
156
+ if (engine == null || typeof engine !== "object")
157
+ return { available: false };
158
+ const obj = engine;
159
+ const gpu = readGpuTypeProperty(obj);
160
+ if (isCpuGpuType(gpu)) {
161
+ return { available: true, gpu: false, gpuLayers: 0 };
162
+ }
163
+ const named = asNodeLlamaGpu(gpu);
164
+ if (named === undefined)
165
+ return { available: false };
166
+ if (named === "metal" && isLayerCount(obj.gpuLayers) && obj.gpuLayers > 0) {
167
+ return { available: true, gpu: "metal", gpuLayers: obj.gpuLayers };
168
+ }
169
+ // cuda/vulkan, metal with 0 layers, or metal without a layer count:
170
+ // not a Metal engagement, and not an engine-stated CPU.
171
+ return { available: false };
172
+ }
173
+ function readGpuTypeProperty(obj) {
174
+ const llama = obj.llama;
175
+ if (llama != null && typeof llama === "object" && "gpu" in llama) {
176
+ return llama.gpu;
177
+ }
178
+ if ("gpu" in obj)
179
+ return obj.gpu;
180
+ if (typeof obj.getGpuType === "function") {
181
+ return obj.getGpuType();
182
+ }
183
+ return undefined;
184
+ }
185
+ /**
186
+ * Binding-level readback used when the engine object does not expose
187
+ * `gpu` / `gpuLayers` (HFE's `EmbeddingEngine`).
188
+ *
189
+ * `gpuType` is `getGpuType()` on the binding warmup already opened — not a
190
+ * second addon. `loadedGpuLayers` is the requested
191
+ * `gpuLayers` value passed into `AddonModel` (llama.cpp caps it at the
192
+ * model's layer count, so `99` means all layers). It is
193
+ * reported only after the binding says Metal. A CPU binding forces 0.
194
+ * `undefined` (no device enumerated) is unavailable, not CPU.
195
+ */
196
+ export function readBindingGpuEngagement(gpuType, loadedGpuLayers) {
197
+ if (isCpuGpuType(gpuType)) {
198
+ return { available: true, gpu: false, gpuLayers: 0 };
199
+ }
200
+ const named = asNodeLlamaGpu(gpuType);
201
+ if (named === "metal" && isLayerCount(loadedGpuLayers) && loadedGpuLayers > 0) {
202
+ return { available: true, gpu: "metal", gpuLayers: loadedGpuLayers };
203
+ }
204
+ return { available: false };
205
+ }
206
+ /** Exports object from the addon HFE dlopened during this warmup. */
207
+ let capturedBinding;
208
+ export function _resetCapturedAddonBindingForTests() {
209
+ capturedBinding = undefined;
210
+ }
211
+ /**
212
+ * While the hook is installed, remember the native binding each
213
+ * `process.dlopen` produces when that module exports `getGpuType`. That is
214
+ * HFE's `loadAddon` during `ensureReady`. The hook forwards to the previous
215
+ * `dlopen`; it does not choose a path, does not load a second addon, and
216
+ * does not call `init` or `loadBackends`.
217
+ *
218
+ * The restore function puts `process.dlopen` back. The captured exports
219
+ * object stays readable so `readCapturedAddonGpuType` can run after restore.
220
+ */
221
+ export function beginAddonBindingCapture() {
222
+ capturedBinding = undefined;
223
+ const orig = process.dlopen;
224
+ const wrapped = (module, filename, flags) => {
225
+ const loaded = module;
226
+ const result = flags === undefined
227
+ ? orig.call(process, loaded, filename)
228
+ : orig.call(process, loaded, filename, flags);
229
+ const exports = loaded.exports;
230
+ if (exports && typeof exports.getGpuType === "function") {
231
+ capturedBinding = exports;
232
+ }
233
+ return result;
234
+ };
235
+ process.dlopen = wrapped;
236
+ return () => {
237
+ if (process.dlopen === wrapped)
238
+ process.dlopen = orig;
239
+ };
240
+ }
241
+ /**
242
+ * `getGpuType()` on the binding captured during warmup. Does not dlopen.
243
+ * Missing capture or a throw is `undefined` (unconfirmed), not CPU.
244
+ */
245
+ export function readCapturedAddonGpuType() {
246
+ const binding = capturedBinding;
247
+ if (!binding || typeof binding.getGpuType !== "function")
248
+ return undefined;
249
+ try {
250
+ return binding.getGpuType();
251
+ }
252
+ catch {
253
+ return undefined;
254
+ }
255
+ }
256
+ /**
257
+ * Run warmup (HFE `register` + `ensureReady`) and read GPU type from the
258
+ * binding that warmup opened. No second `dlopen`.
259
+ */
260
+ export async function readGpuTypeFromWarmup(warmup) {
261
+ const end = beginAddonBindingCapture();
262
+ try {
263
+ const value = await warmup();
264
+ return { value, gpuType: readCapturedAddonGpuType() };
265
+ }
266
+ finally {
267
+ end();
268
+ }
269
+ }
270
+ function safeProbe(probe) {
271
+ try {
272
+ return probe();
273
+ }
274
+ catch {
275
+ return undefined;
276
+ }
277
+ }
97
278
  /**
98
- * Fail-loud confirmation. Offload requested + Metal not usable, or offload
99
- * requested + usable but the ggml_metal_init / compute-buffer pair is
100
- * missing → CPU + fallback sentence. Never returns backend="metal" without
101
- * the log proof.
279
+ * Engagement from the engine, not from captured stdio.
280
+ *
281
+ * `warmupLog` / `capturedLog` are accepted and ignored so a launchd capture
282
+ * (empty, or full of markers that never reached Node) cannot decide the
283
+ * statement. `metalUsable` is platform detection, not engagement evidence.
284
+ *
285
+ * When `engine` exposes `gpu` + `gpuLayers` (or `getGpuType()` + `gpuLayers`),
286
+ * that pair wins. Otherwise `probeGpuType` — boot passes a reader of the
287
+ * binding captured during warmup — is combined with `requestedGpuLayers`,
288
+ * the count HFE passed to `AddonModel`. No probe and no engine fields is
289
+ * unconfirmed. `probeGpuType` must not open a second native addon.
102
290
  */
103
291
  export function confirmMetalEngagement(opts) {
104
- const { requestedGpuLayers, metalUsable, warmupLog, source } = opts;
292
+ const { requestedGpuLayers, source, engine, probeGpuType } = opts;
105
293
  if (requestedGpuLayers <= 0) {
106
294
  return { engaged: false, statement: { backend: "cpu", gpuLayers: 0, source } };
107
295
  }
108
- if (!metalUsable) {
296
+ const direct = readEngineGpuEngagement(engine);
297
+ const readback = direct.available
298
+ ? direct
299
+ : probeGpuType
300
+ ? readBindingGpuEngagement(safeProbe(probeGpuType), requestedGpuLayers)
301
+ : { available: false };
302
+ return statementFromReadback(source, readback);
303
+ }
304
+ function statementFromReadback(source, readback) {
305
+ if (readback.available && readback.gpu === "metal") {
306
+ return {
307
+ engaged: true,
308
+ statement: { backend: "metal", gpuLayers: readback.gpuLayers, source },
309
+ };
310
+ }
311
+ if (readback.available && readback.gpu === false) {
109
312
  return {
110
313
  engaged: false,
111
314
  statement: {
@@ -116,47 +319,28 @@ export function confirmMetalEngagement(opts) {
116
319
  },
117
320
  };
118
321
  }
119
- const readback = parseMetalEngaged(warmupLog);
120
- if (readback.engaged) {
121
- return {
122
- engaged: true,
123
- statement: { backend: "metal", gpuLayers: requestedGpuLayers, source },
124
- };
125
- }
126
322
  return {
127
323
  engaged: false,
128
- statement: {
129
- backend: "cpu",
130
- gpuLayers: 0,
131
- source,
132
- fallback: EMBED_GPU_FALLBACK_MSG,
133
- },
324
+ statement: { backend: "unconfirmed", gpuLayers: null, source },
134
325
  };
135
326
  }
136
327
  /**
137
- * Pre-confirmation view of a choice. A Metal-derived 99 does not claim
138
- * `backend: "metal"` until confirmMetalEngagement sees the log markers.
328
+ * Pre-confirmation view. A requested offload does not claim Metal and does
329
+ * not claim CPU / `gpuLayers: 0` before the engine answers.
139
330
  */
140
331
  export function previewEmbedGpuStatement(choice) {
141
332
  if (choice.gpuLayers <= 0) {
142
333
  return { backend: "cpu", gpuLayers: 0, source: choice.source };
143
334
  }
144
- if (!choice.metalUsable) {
145
- return {
146
- backend: "cpu",
147
- gpuLayers: 0,
148
- source: choice.source,
149
- fallback: EMBED_GPU_FALLBACK_MSG,
150
- };
151
- }
152
- return { backend: "cpu", gpuLayers: choice.gpuLayers, source: choice.source };
335
+ return { backend: "unconfirmed", gpuLayers: null, source: choice.source, pending: true };
153
336
  }
154
- export function applyEmbedGpuChoice(choice, warmupLog) {
337
+ export function applyEmbedGpuChoice(choice, engine, probeGpuType) {
155
338
  const { statement } = confirmMetalEngagement({
156
339
  requestedGpuLayers: choice.gpuLayers,
157
340
  metalUsable: choice.metalUsable,
158
- warmupLog,
159
341
  source: choice.source,
342
+ engine: typeof engine === "string" ? undefined : engine,
343
+ probeGpuType,
160
344
  });
161
345
  stated = statement;
162
346
  return statement;
@@ -167,7 +351,12 @@ export function setEmbedGpuStatement(next) {
167
351
  export function getEmbedGpuStatement(detect = {}) {
168
352
  if (stated)
169
353
  return stated;
170
- return previewEmbedGpuStatement(resolveEmbedGpuChoice(process.env, detect));
354
+ const choice = resolveEmbedGpuChoice(process.env, detect);
355
+ // No warmup preview has been published yet. A missing backend must not
356
+ // announce "warmup in progress" just because Health was read first.
357
+ return choice.gpuLayers > 0
358
+ ? { backend: "unconfirmed", gpuLayers: null, source: choice.source }
359
+ : previewEmbedGpuStatement(choice);
171
360
  }
172
361
  export function _resetEmbedGpuStatementForTests() {
173
362
  stated = null;
@@ -176,18 +365,45 @@ export function formatEmbedGpuLogLine(statement) {
176
365
  if (statement.fallback) {
177
366
  return `[embeddings] ${statement.fallback} (source=${statement.source})`;
178
367
  }
179
- if (statement.backend === "metal") {
368
+ if (statement.backend === "metal" && statement.gpuLayers != null) {
180
369
  return `[embeddings] embedding: GPU (Metal), ${statement.gpuLayers} layers (source=${statement.source})`;
181
370
  }
182
- if (statement.gpuLayers > 0) {
183
- return (`[embeddings] embedding: GPU (Metal) requested, ${statement.gpuLayers} layers ` +
184
- `(source=${statement.source}) — confirming engagement`);
371
+ if (statement.backend === "unconfirmed") {
372
+ return `[embeddings] ${EMBED_GPU_UNCONFIRMED_MSG} (source=${statement.source})`;
185
373
  }
186
374
  if (statement.source === "env") {
187
375
  return `[embeddings] embedding: CPU, 0 layers (source=env)`;
188
376
  }
189
377
  return `[embeddings] embedding: CPU (no GPU backend detected)`;
190
378
  }
379
+ /** Boot line before readback. Names the request; it does not claim a backend. */
380
+ export function formatEmbedGpuRequestLine(choice) {
381
+ return (`[embeddings] embedding: GPU (Metal) requested, ${choice.gpuLayers} layers ` +
382
+ `(source=${choice.source}) — confirming engagement`);
383
+ }
384
+ /**
385
+ * Warning text `flair status` prints from HealthDetail. `null` when there is
386
+ * nothing to warn about (Metal engaged, or a CPU request that was not an
387
+ * offload). Unconfirmed text does not say the engine is on CPU.
388
+ */
389
+ export function embedGpuStatusWarning(statement) {
390
+ if (statement.backend === "metal")
391
+ return null;
392
+ if (statement.fallback)
393
+ return statement.fallback;
394
+ if (statement.backend === "unconfirmed" && statement.pending)
395
+ return EMBED_GPU_PENDING_MSG;
396
+ if (statement.backend === "unconfirmed")
397
+ return EMBED_GPU_UNCONFIRMED_MSG;
398
+ return null;
399
+ }
400
+ /** HealthDetail notice for `flair status`; warmup is informational. */
401
+ export function embedGpuStatusNotice(statement) {
402
+ const message = embedGpuStatusWarning(statement);
403
+ return message
404
+ ? { level: statement.backend === "unconfirmed" && statement.pending ? "info" : "warn", message }
405
+ : null;
406
+ }
191
407
  /** Attach the stated embedding field to a /Health or /HealthDetail body. */
192
408
  export function withEmbedGpuHealth(body) {
193
409
  return { ...body, embedding: getEmbedGpuStatement() };
@@ -195,9 +411,8 @@ export function withEmbedGpuHealth(body) {
195
411
  /**
196
412
  * Capture stdout/stderr (and console.*) for the duration of `fn`.
197
413
  * Native ggml writes that bypass Node's stream (fd 2 via libc) are not
198
- * guaranteed to appear here — that is the HFE-readback follow-up. The
199
- * fail-loud path that does not need a log (offload requested + Metal not
200
- * usable) does not call this.
414
+ * guaranteed to appear here. Product engagement does not read this capture
415
+ * (flair#2031); the ingest-throughput bench still greps its own logs.
201
416
  */
202
417
  export async function captureIoDuring(fn) {
203
418
  const chunks = [];
@@ -86,7 +86,7 @@
86
86
  */
87
87
  import { availableParallelism } from "node:os";
88
88
  import { resolveModelsDir } from "./embeddings-provider.js";
89
- import { applyEmbedGpuChoice, captureIoDuring, formatEmbedGpuLogLine, getEmbedGpuStatement, previewEmbedGpuStatement, resolveEmbedGpuChoice, setEmbedGpuStatement, } from "./embed-gpu.js";
89
+ import { applyEmbedGpuChoice, formatEmbedGpuLogLine, formatEmbedGpuRequestLine, previewEmbedGpuStatement, readGpuTypeFromWarmup, resolveEmbedGpuChoice, setEmbedGpuStatement, } from "./embed-gpu.js";
90
90
  export { resolveEmbedGpuLayers } from "./embed-gpu.js";
91
91
  const LOGICAL_NAME = "default";
92
92
  const MODEL_NAME = "nomic-embed-text";
@@ -212,27 +212,40 @@ export async function registerEmbeddingsBackend() {
212
212
  threads,
213
213
  gpuLayers: choice.gpuLayers,
214
214
  };
215
- const needsMetalConfirm = choice.gpuLayers > 0 && choice.metalUsable;
216
- if (!needsMetalConfirm) {
217
- const statement = applyEmbedGpuChoice(choice, "");
215
+ // gpuLayers 0 is a CPU request — nothing was asked of the GPU.
216
+ // Any positive offload is read back from the engine after warmup.
217
+ // Captured stdio is not the signal (flair#2031).
218
+ if (choice.gpuLayers <= 0) {
219
+ const statement = applyEmbedGpuChoice(choice);
218
220
  console.log(formatEmbedGpuLogLine(statement));
219
221
  await register({ logicalName: LOGICAL_NAME, kind: "embedding", config });
220
222
  }
221
223
  else {
222
224
  setEmbedGpuStatement(previewEmbedGpuStatement(choice));
223
- console.log(formatEmbedGpuLogLine(getEmbedGpuStatement()));
224
- const { log } = await captureIoDuring(async () => {
225
- const engine = await register({
226
- logicalName: LOGICAL_NAME,
227
- kind: "embedding",
228
- config,
225
+ console.log(formatEmbedGpuRequestLine(choice));
226
+ // GPU type comes from the binding this warmup dlopens. Do not open
227
+ // another llama-addon afterwards — a second binary can report CPU
228
+ // while this one is on Metal (flair#2031).
229
+ try {
230
+ const { value: engine, gpuType } = await readGpuTypeFromWarmup(async () => {
231
+ const created = await register({
232
+ logicalName: LOGICAL_NAME,
233
+ kind: "embedding",
234
+ config,
235
+ });
236
+ if (created && typeof created.ensureReady === "function") {
237
+ await created.ensureReady();
238
+ }
239
+ return created;
229
240
  });
230
- if (engine && typeof engine.ensureReady === "function") {
231
- await engine.ensureReady();
232
- }
233
- });
234
- const statement = applyEmbedGpuChoice(choice, log);
235
- console.log(formatEmbedGpuLogLine(statement));
241
+ const statement = applyEmbedGpuChoice(choice, engine, () => gpuType);
242
+ console.log(formatEmbedGpuLogLine(statement));
243
+ }
244
+ catch (err) {
245
+ // A failed warmup has ended; it must not leave Health pending forever.
246
+ applyEmbedGpuChoice(choice);
247
+ throw err;
248
+ }
236
249
  }
237
250
  }
238
251
  catch (err) {
@@ -247,4 +260,26 @@ export async function registerEmbeddingsBackend() {
247
260
  export function _resetEmbeddingsBackendRegistrationForTests() {
248
261
  registered = false;
249
262
  }
250
- void registerEmbeddingsBackend();
263
+ /**
264
+ * Kick the BM25 build after embeddings registration settles.
265
+ *
266
+ * Not a static import: this module is loaded by unit tests that only want
267
+ * `resolveEmbedThreads`, and `bm25-index-service` imports `harper`, which
268
+ * throws outside a real Harper boot. `globalThis.models` is the same "are
269
+ * we inside Harper?" signal the registration path already uses. Boot does
270
+ * not wait on the scan — `scheduleBm25BootWarm` returns on this turn.
271
+ */
272
+ function kickBm25BootWarm() {
273
+ const g = globalThis;
274
+ if (g.models == null)
275
+ return;
276
+ void import("./bm25-index-service.js").then((mod) => {
277
+ mod.scheduleBm25BootWarm();
278
+ }).catch((err) => {
279
+ const message = err instanceof Error ? err.message : String(err);
280
+ console.error(`[bm25] boot warm skipped: ${message}`);
281
+ });
282
+ }
283
+ void registerEmbeddingsBackend().finally(() => {
284
+ kickBm25BootWarm();
285
+ });
@@ -117,10 +117,22 @@ export function checkPrincipalEntitlement(record, opts = {}) {
117
117
  }
118
118
  return null;
119
119
  }
120
+ /** The Memory attributes that would carry a pointer into an inbound federated
121
+ * row (flair#1940 A1' item 5). Local + pure — this module stays DB-free. */
122
+ const FEDERATION_POINTER_FIELDS = ["hostSource", "hostSourceScope", "hostSourceVisibility"];
123
+ function inboundCarriesPointer(data) {
124
+ if (!data || typeof data !== "object")
125
+ return false;
126
+ return FEDERATION_POINTER_FIELDS.some((f) => data[f] !== undefined);
127
+ }
120
128
  export function classifyRecord(record, peerRole, receiverInstanceId, local, knownTables, now = new Date()) {
121
129
  if (!knownTables.has(record.table)) {
122
130
  return { action: "skip", reason: "unknown_table" };
123
131
  }
132
+ // flair#1940 A1' item 5: refuse an inbound row carrying a host pointer.
133
+ if (inboundCarriesPointer(record.data)) {
134
+ return { action: "skip", reason: "pointer_not_federated" };
135
+ }
124
136
  const originator = record.originatorInstanceId ?? receiverInstanceId;
125
137
  if (originator !== receiverInstanceId && peerRole !== "hub") {
126
138
  return { action: "skip", reason: "non_originator" };
@@ -31,9 +31,33 @@ function sortKeys(val) {
31
31
  export function generateNonce() {
32
32
  return Buffer.from(nacl.randomBytes(16)).toString("base64url");
33
33
  }
34
+ /** Freshness window the federation endpoints (FederationPair, FederationSync) use, in ms. */
35
+ export const FEDERATION_WINDOW_MS = 30_000;
36
+ /** Field presence and timestamp checks shared by both verify functions. */
37
+ function precheckFresh(body, windowMs) {
38
+ const { signature, _ts, _nonce, ...rest } = body;
39
+ // ── Field presence ───────────────────────────────────────────────────
40
+ if (!signature)
41
+ return { ok: false, reason: "invalid_signature" };
42
+ if (_ts == null || !Number.isFinite(_ts))
43
+ return { ok: false, reason: "invalid_signature" };
44
+ if (!_nonce || typeof _nonce !== "string")
45
+ return { ok: false, reason: "invalid_signature" };
46
+ // ── Timestamp check ──────────────────────────────────────────────────
47
+ const now = Date.now();
48
+ const delta = now - _ts;
49
+ if (delta > windowMs)
50
+ return { ok: false, reason: "stale" };
51
+ if (delta < -windowMs)
52
+ return { ok: false, reason: "future" };
53
+ // Canonical form includes _ts and _nonce.
54
+ return { ok: true, nonce: _nonce, now, verificationBody: { _ts, _nonce, ...rest, signature } };
55
+ }
34
56
  /**
35
- * Default in-memory nonce store backed by a Map.
36
- * Safe for module-level singleton use (e.g. federationNonceStore).
57
+ * Default in-memory nonce store backed by a Map. It is local to one process
58
+ * (and one Harper thread); the Flair server's federation endpoints record
59
+ * nonces through `verifyBodySignatureFreshOnce` and resources/replay-store.ts
60
+ * instead.
37
61
  */
38
62
  export function createNonceStore() {
39
63
  const store = new Map();
@@ -77,25 +101,16 @@ export function signBodyFresh(body, secretKey, opts) {
77
101
  * 4. Records the nonce on success.
78
102
  *
79
103
  * Returns `{ ok: true }` on success, or `{ ok: false, reason: "..." }`.
104
+ * Replay detection is only as wide as `opts.nonceStore`; the Flair server's
105
+ * endpoints use `verifyBodySignatureFreshOnce` below.
80
106
  */
81
107
  export function verifyBodySignatureFresh(body, publicKeyB64url, opts = {}) {
82
108
  const windowMs = opts.windowMs ?? 30_000;
83
109
  const nonceStore = opts.nonceStore;
84
- const { signature, _ts, _nonce, ...rest } = body;
85
- // ── Field presence ───────────────────────────────────────────────────
86
- if (!signature)
87
- return { ok: false, reason: "invalid_signature" };
88
- if (_ts == null || !Number.isFinite(_ts))
89
- return { ok: false, reason: "invalid_signature" };
90
- if (!_nonce || typeof _nonce !== "string")
91
- return { ok: false, reason: "invalid_signature" };
92
- // ── Timestamp check ──────────────────────────────────────────────────
93
- const now = Date.now();
94
- const delta = now - _ts;
95
- if (delta > windowMs)
96
- return { ok: false, reason: "stale" };
97
- if (delta < -windowMs)
98
- return { ok: false, reason: "future" };
110
+ const pre = precheckFresh(body, windowMs);
111
+ if (!pre.ok)
112
+ return pre;
113
+ const { nonce: _nonce, now } = pre;
99
114
  // ── Nonce replay check ───────────────────────────────────────────────
100
115
  if (nonceStore) {
101
116
  // Evict entries older than 2x window — keeps the store bounded
@@ -104,8 +119,7 @@ export function verifyBodySignatureFresh(body, publicKeyB64url, opts = {}) {
104
119
  return { ok: false, reason: "replay" };
105
120
  }
106
121
  // ── Signature verification — canonical form includes _ts, _nonce ─────
107
- const verificationBody = { _ts, _nonce, ...rest, signature };
108
- if (!verifyBodySignature(verificationBody, publicKeyB64url)) {
122
+ if (!verifyBodySignature(pre.verificationBody, publicKeyB64url)) {
109
123
  return { ok: false, reason: "invalid_signature" };
110
124
  }
111
125
  // ── Record nonce ─────────────────────────────────────────────────────
@@ -114,6 +128,38 @@ export function verifyBodySignatureFresh(body, publicKeyB64url, opts = {}) {
114
128
  }
115
129
  return { ok: true };
116
130
  }
131
+ /**
132
+ * Verify a signed request body and record its nonce ONCE (the federation
133
+ * endpoints' check).
134
+ *
135
+ * Same field, timestamp and signature checks as `verifyBodySignatureFresh`.
136
+ * The nonce is claimed through `opts.replay` only AFTER the signature has
137
+ * verified; a claim that is not "recorded" — a replay, an unusable store, or
138
+ * anything thrown — refuses. `replay.knownReplay` may refuse earlier, on a hit
139
+ * only.
140
+ */
141
+ export async function verifyBodySignatureFreshOnce(body, publicKeyB64url, opts) {
142
+ const pre = precheckFresh(body, opts.windowMs ?? FEDERATION_WINDOW_MS);
143
+ if (!pre.ok)
144
+ return pre;
145
+ if (opts.replay.knownReplay(pre.nonce, pre.now))
146
+ return { ok: false, reason: "replay" };
147
+ if (!verifyBodySignature(pre.verificationBody, publicKeyB64url)) {
148
+ return { ok: false, reason: "invalid_signature" };
149
+ }
150
+ let claimed;
151
+ try {
152
+ claimed = await opts.replay.claim(pre.nonce);
153
+ }
154
+ catch {
155
+ claimed = "unavailable";
156
+ }
157
+ if (claimed === "recorded")
158
+ return { ok: true };
159
+ if (claimed === "replay")
160
+ return { ok: false, reason: "replay" };
161
+ return { ok: false, reason: "replay_store_unavailable" };
162
+ }
117
163
  // ─── Legacy signing (without anti-replay) ────────────────────────────────────
118
164
  // Kept as implementation detail for signBodyFresh / verifyBodySignatureFresh.
119
165
  // Callers should use the fresh variants for replay-safe federation operations.