@tpsdev-ai/flair 0.54.2 → 0.55.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/dist/build-info.json +3 -3
  2. package/dist/cli.js +774 -176
  3. package/dist/commands/doctor.js +86 -1
  4. package/dist/commands/federation.js +131 -36
  5. package/dist/commands/hook.js +20 -10
  6. package/dist/commands/init.js +193 -67
  7. package/dist/commands/service.js +16 -12
  8. package/dist/commands/soul.js +10 -5
  9. package/dist/commands/status.js +62 -7
  10. package/dist/commands/upgrade.js +6 -0
  11. package/dist/doctor-client.js +118 -32
  12. package/dist/hook-install.js +170 -16
  13. package/dist/lib/doctor-run.js +49 -3
  14. package/dist/lib/embed-gpu-doctor.js +63 -0
  15. package/dist/lib/federation-pair-access.js +118 -0
  16. package/dist/lib/harper-port-value.js +43 -0
  17. package/dist/lib/http-bind.js +227 -0
  18. package/dist/lib/init-admin-pass.js +316 -0
  19. package/dist/lib/launchd-management.js +16 -0
  20. package/dist/lib/launchd-repair.js +122 -1
  21. package/dist/lib/owned-pins.js +54 -1
  22. package/dist/lib/process-start-time.js +82 -0
  23. package/dist/lib/scratch-owner.js +124 -10
  24. package/dist/lib/stale-client-pin.js +26 -0
  25. package/dist/lib/upgrade-plain-tree.js +293 -48
  26. package/dist/rem/runner.js +10 -1
  27. package/dist/resources/AdminInstance.js +8 -2
  28. package/dist/resources/Memory.js +36 -1
  29. package/dist/resources/MemoryBootstrap.js +23 -32
  30. package/dist/resources/MemoryFeed.js +4 -1
  31. package/dist/resources/MemoryReflect.js +121 -93
  32. package/dist/resources/SkillScan.js +13 -11
  33. package/dist/resources/Soul.js +15 -1
  34. package/dist/resources/XAA.js +16 -1
  35. package/dist/resources/a2a-url.js +5 -2
  36. package/dist/resources/client-version-gate.js +144 -0
  37. package/dist/resources/embed-gpu.js +241 -0
  38. package/dist/resources/embeddings-boot.js +34 -42
  39. package/dist/resources/federation-peer-liveness.js +7 -1
  40. package/dist/resources/health.js +12 -3
  41. package/dist/resources/memory-reflect-lib.js +66 -0
  42. package/dist/resources/memory-reflect-models.js +9 -0
  43. package/dist/resources/migrations/embedding-stamp.js +32 -4
  44. package/dist/resources/oauth-discovery.js +3 -1
  45. package/dist/resources/record-type-kit.js +59 -0
  46. package/dist/resources/scan/skill-markdown.js +166 -0
  47. package/dist/resources/scan/skill-scanner.js +89 -68
  48. package/dist/resources/skill-provenance.js +273 -0
  49. package/dist/resources/skill-write.js +26 -7
  50. package/dist/src/lib/harper-port-value.js +43 -0
  51. package/docs/api-reference.md +35 -2
  52. package/docs/deployment.md +39 -6
  53. package/docs/federation.md +18 -7
  54. package/docs/mcp-clients.md +19 -6
  55. package/docs/releasing.md +79 -13
  56. package/docs/rem.md +1 -1
  57. package/docs/secrets-and-keys.md +1 -0
  58. package/docs/standalone-local.md +8 -5
  59. package/docs/troubleshooting.md +17 -0
  60. package/package.json +1 -1
@@ -0,0 +1,144 @@
1
+ /**
2
+ * client-version-gate.ts — flair#1383
3
+ *
4
+ * Pre-0.18.0 `@tpsdev-ai/flair-client` (and the adapters that shipped it)
5
+ * runs a cosine-only write preflight and, on a hit, returns the existing
6
+ * record WITHOUT issuing the PUT. The match can be another agent's
7
+ * `shared` memory. The server never sees that write, so its cosine-AND-
8
+ * Jaccard gate and `written: true` contract cannot run.
9
+ *
10
+ * A server upgrade does not fix a silent client. This module is the
11
+ * server-side half: when a request *identifies* as a pre-0.18.0 client
12
+ * on a Memory write path, refuse it loudly (426) and name the remedy
13
+ * (upgrade the adapter, not the server).
14
+ *
15
+ * Honest limit: v0.17.0 does not send a library version (nor does any
16
+ * published client before this change). Missing version is therefore
17
+ * NOT treated as old — current published clients, raw HTTP, and
18
+ * in-process `/mcp` would all false-positive. Identification is:
19
+ * - `X-Flair-Client: flair-client/<semver>` (or `flair-mcp/<semver>`)
20
+ * - optional write-body `flairClientVersion` (stripped, never stored)
21
+ *
22
+ * Harper-free so the compare/parse/denial shape is unit-testable
23
+ * without a live table.
24
+ */
25
+ export const MIN_SAFE_FLAIR_CLIENT = "0.18.0";
26
+ export const FLAIR_CLIENT_VERSION_HEADER = "x-flair-client";
27
+ export const FLAIR_CLIENT_VERSION_BODY = "flairClientVersion";
28
+ export const STALE_CLIENT_ERROR = "stale_flair_client";
29
+ const STALE_CLIENT_REMEDY = "Upgrade the adapter, not the server: `flair upgrade`, or pin " +
30
+ `@tpsdev-ai/flair-mcp / @tpsdev-ai/flair-client >= ${MIN_SAFE_FLAIR_CLIENT}.`;
31
+ export function parseSemverCore(v) {
32
+ if (!v)
33
+ return null;
34
+ const core = v.trim().replace(/^v/, "").split("-")[0].split("+")[0];
35
+ const parts = core.split(".");
36
+ if (parts.length < 3)
37
+ return null;
38
+ const nums = parts.slice(0, 3).map((p) => Number(p));
39
+ if (nums.some((n) => !Number.isFinite(n)))
40
+ return null;
41
+ return [nums[0], nums[1], nums[2]];
42
+ }
43
+ export function semverLessThan(a, b) {
44
+ const pa = parseSemverCore(a);
45
+ const pb = parseSemverCore(b);
46
+ if (!pa || !pb)
47
+ return false;
48
+ for (let i = 0; i < 3; i++) {
49
+ if (pa[i] < pb[i])
50
+ return true;
51
+ if (pa[i] > pb[i])
52
+ return false;
53
+ }
54
+ return false;
55
+ }
56
+ /** True when `version` is parseable and strictly older than 0.18.0. */
57
+ export function isUnsafeClientVersion(version) {
58
+ if (!version)
59
+ return false;
60
+ return semverLessThan(version, MIN_SAFE_FLAIR_CLIENT);
61
+ }
62
+ /**
63
+ * Parse `flair-client/0.17.0`, `flair-mcp/0.17.0`, or a bare `0.17.0`.
64
+ * Unknown package prefixes still yield the version so a future adapter
65
+ * name does not silently evade the gate.
66
+ */
67
+ export function parseClientVersionToken(raw) {
68
+ if (typeof raw !== "string")
69
+ return null;
70
+ const token = raw.trim();
71
+ if (!token)
72
+ return null;
73
+ const slash = token.lastIndexOf("/");
74
+ const version = slash === -1 ? token : token.slice(slash + 1);
75
+ return parseSemverCore(version) ? version : null;
76
+ }
77
+ function headerGet(request, name) {
78
+ const headers = request?.headers;
79
+ if (!headers)
80
+ return null;
81
+ const lower = name.toLowerCase();
82
+ const fromGet = headers.get?.(lower) ?? headers.get?.(name);
83
+ if (typeof fromGet === "string" && fromGet)
84
+ return fromGet;
85
+ const obj = headers.asObject ?? headers;
86
+ const fromObj = obj?.[lower] ?? obj?.[name];
87
+ return typeof fromObj === "string" && fromObj ? fromObj : null;
88
+ }
89
+ /**
90
+ * Library version the caller declared, or null when absent/unparseable.
91
+ * Header wins over the write-body passthrough. Never invents a version.
92
+ */
93
+ export function readDeclaredClientVersion(request, content) {
94
+ const fromHeader = parseClientVersionToken(headerGet(request, FLAIR_CLIENT_VERSION_HEADER));
95
+ if (fromHeader)
96
+ return fromHeader;
97
+ return parseClientVersionToken(content?.[FLAIR_CLIENT_VERSION_BODY]);
98
+ }
99
+ /** Strip the write-body-only passthrough so it is never persisted. */
100
+ export function stripClientVersionPassthrough(content) {
101
+ if (content && typeof content === "object")
102
+ delete content[FLAIR_CLIENT_VERSION_BODY];
103
+ }
104
+ export function staleClientDenialMessage(version) {
105
+ return (`This flair-client (${version}) silently drops writes — including against ` +
106
+ `another agent's shared memories. ${STALE_CLIENT_REMEDY}`);
107
+ }
108
+ export function staleClientDenialBody(version) {
109
+ return {
110
+ error: STALE_CLIENT_ERROR,
111
+ message: staleClientDenialMessage(version),
112
+ clientVersion: version,
113
+ minimumClientVersion: MIN_SAFE_FLAIR_CLIENT,
114
+ };
115
+ }
116
+ export function staleClientWriteDenial(version) {
117
+ return new Response(JSON.stringify(staleClientDenialBody(version)), {
118
+ status: 426,
119
+ headers: { "Content-Type": "application/json" },
120
+ });
121
+ }
122
+ /**
123
+ * Refuse an identified pre-0.18.0 client on a Memory write path.
124
+ * Missing version → null (serve). Internal/no-request → null (serve).
125
+ */
126
+ export function refuseStaleClientWrite(request, content) {
127
+ const version = readDeclaredClientVersion(request, content);
128
+ if (!isUnsafeClientVersion(version))
129
+ return null;
130
+ return staleClientWriteDenial(version);
131
+ }
132
+ /**
133
+ * The v0.17.0 write() preflight shape: `POST /SemanticSearch` with
134
+ * `limit: 1` and `scoring: "raw"`. Current write() never searches.
135
+ * Exposed for fixtures and for a future search-path flag; not a refuse
136
+ * trigger on its own (unversioned limit:1 raw searches are legitimate).
137
+ */
138
+ export function isOldClientWritePreflight(data) {
139
+ if (!data || typeof data !== "object")
140
+ return false;
141
+ const limit = data.limit;
142
+ const scoring = data.scoring;
143
+ return limit === 1 && (scoring === "raw" || scoring === undefined);
144
+ }
@@ -0,0 +1,241 @@
1
+ /**
2
+ * embed-gpu.ts — stated gpuLayers default for in-process embedding (flair#1437).
3
+ *
4
+ * Harper-free so the detect → derive → override → fail-loud decision is
5
+ * unit-testable without a live engine. embeddings-boot.ts is the only
6
+ * production caller that talks to HFE; Health/HealthDetail read the stated
7
+ * snapshot.
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.
13
+ */
14
+ import { createRequire } from "node:module";
15
+ export const METAL_PREBUILT = "@node-llama-cpp/mac-arm64-metal";
16
+ /** Fail-loud sentence. Never report GPU while this is the live statement. */
17
+ export const EMBED_GPU_FALLBACK_MSG = "requested GPU offload; Metal did not engage; running CPU";
18
+ const METAL_INIT_RE = /ggml_metal_init/i;
19
+ const METAL_BUFFER_RE = /compute[- ]buffer/i;
20
+ let stated = null;
21
+ /**
22
+ * A *usable* Metal backend is darwin+arm64 AND a resolvable
23
+ * `@node-llama-cpp/mac-arm64-metal` prebuilt. Platform alone is not proof
24
+ * (headless / VM / stripped install).
25
+ */
26
+ export function detectUsableMetalBackend(input = {}) {
27
+ if (typeof input.usable === "boolean")
28
+ return input.usable;
29
+ const platform = input.platform ?? process.platform;
30
+ const arch = input.arch ?? process.arch;
31
+ if (platform !== "darwin" || arch !== "arm64")
32
+ return false;
33
+ const resolve = input.resolve ?? defaultResolveMetal;
34
+ try {
35
+ resolve(METAL_PREBUILT);
36
+ return true;
37
+ }
38
+ catch {
39
+ return false;
40
+ }
41
+ }
42
+ function defaultResolveMetal(specifier) {
43
+ const fromHere = createRequire(import.meta.url);
44
+ try {
45
+ return fromHere.resolve(specifier);
46
+ }
47
+ catch {
48
+ // Optional dep lives on harper-fabric-embeddings; try from its graph.
49
+ const hfe = fromHere.resolve("harper-fabric-embeddings");
50
+ return createRequire(hfe).resolve(specifier);
51
+ }
52
+ }
53
+ /**
54
+ * Derived default: usable Metal → 99, else 0. `FLAIR_EMBED_GPU_LAYERS`
55
+ * (non-negative integer) wins. Invalid / empty values fall through to the
56
+ * derived default — they do not omit the field (HFE would then silently
57
+ * keep its own 0, which is exactly the unstated default this issue removes).
58
+ */
59
+ export function resolveEmbedGpuChoice(env = process.env, detect = {}) {
60
+ const metalUsable = detectUsableMetalBackend(detect);
61
+ const parsed = parseNonNegativeInt(env.FLAIR_EMBED_GPU_LAYERS);
62
+ if (parsed !== undefined) {
63
+ return { gpuLayers: parsed, source: "env", metalUsable };
64
+ }
65
+ if (metalUsable) {
66
+ return { gpuLayers: 99, source: "detected", metalUsable: true };
67
+ }
68
+ return { gpuLayers: 0, source: "default", metalUsable: false };
69
+ }
70
+ export function resolveEmbedGpuLayers(env = process.env, detect = {}) {
71
+ return resolveEmbedGpuChoice(env, detect).gpuLayers;
72
+ }
73
+ function parseNonNegativeInt(raw) {
74
+ if (raw == null)
75
+ return undefined;
76
+ const trimmed = raw.trim();
77
+ if (trimmed === "")
78
+ return undefined;
79
+ const n = Number(trimmed);
80
+ if (!Number.isInteger(n) || n < 0)
81
+ return undefined;
82
+ return n;
83
+ }
84
+ /** Prove GPU engagement from the engine / boot log. Requested ≠ used. */
85
+ export function parseMetalEngaged(log) {
86
+ const lines = (log ?? "").split(/\r?\n/);
87
+ const evidence = lines.filter((l) => METAL_INIT_RE.test(l) || METAL_BUFFER_RE.test(l));
88
+ const hasInit = evidence.some((l) => METAL_INIT_RE.test(l));
89
+ const hasComputeBuffer = evidence.some((l) => METAL_BUFFER_RE.test(l));
90
+ return {
91
+ engaged: hasInit && hasComputeBuffer,
92
+ hasInit,
93
+ hasComputeBuffer,
94
+ evidence: evidence.slice(0, 12),
95
+ };
96
+ }
97
+ /**
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.
102
+ */
103
+ export function confirmMetalEngagement(opts) {
104
+ const { requestedGpuLayers, metalUsable, warmupLog, source } = opts;
105
+ if (requestedGpuLayers <= 0) {
106
+ return { engaged: false, statement: { backend: "cpu", gpuLayers: 0, source } };
107
+ }
108
+ if (!metalUsable) {
109
+ return {
110
+ engaged: false,
111
+ statement: {
112
+ backend: "cpu",
113
+ gpuLayers: 0,
114
+ source,
115
+ fallback: EMBED_GPU_FALLBACK_MSG,
116
+ },
117
+ };
118
+ }
119
+ const readback = parseMetalEngaged(warmupLog);
120
+ if (readback.engaged) {
121
+ return {
122
+ engaged: true,
123
+ statement: { backend: "metal", gpuLayers: requestedGpuLayers, source },
124
+ };
125
+ }
126
+ return {
127
+ engaged: false,
128
+ statement: {
129
+ backend: "cpu",
130
+ gpuLayers: 0,
131
+ source,
132
+ fallback: EMBED_GPU_FALLBACK_MSG,
133
+ },
134
+ };
135
+ }
136
+ /**
137
+ * Pre-confirmation view of a choice. A Metal-derived 99 does not claim
138
+ * `backend: "metal"` until confirmMetalEngagement sees the log markers.
139
+ */
140
+ export function previewEmbedGpuStatement(choice) {
141
+ if (choice.gpuLayers <= 0) {
142
+ return { backend: "cpu", gpuLayers: 0, source: choice.source };
143
+ }
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 };
153
+ }
154
+ export function applyEmbedGpuChoice(choice, warmupLog) {
155
+ const { statement } = confirmMetalEngagement({
156
+ requestedGpuLayers: choice.gpuLayers,
157
+ metalUsable: choice.metalUsable,
158
+ warmupLog,
159
+ source: choice.source,
160
+ });
161
+ stated = statement;
162
+ return statement;
163
+ }
164
+ export function setEmbedGpuStatement(next) {
165
+ stated = next;
166
+ }
167
+ export function getEmbedGpuStatement(detect = {}) {
168
+ if (stated)
169
+ return stated;
170
+ return previewEmbedGpuStatement(resolveEmbedGpuChoice(process.env, detect));
171
+ }
172
+ export function _resetEmbedGpuStatementForTests() {
173
+ stated = null;
174
+ }
175
+ export function formatEmbedGpuLogLine(statement) {
176
+ if (statement.fallback) {
177
+ return `[embeddings] ${statement.fallback} (source=${statement.source})`;
178
+ }
179
+ if (statement.backend === "metal") {
180
+ return `[embeddings] embedding: GPU (Metal), ${statement.gpuLayers} layers (source=${statement.source})`;
181
+ }
182
+ if (statement.gpuLayers > 0) {
183
+ return (`[embeddings] embedding: GPU (Metal) requested, ${statement.gpuLayers} layers ` +
184
+ `(source=${statement.source}) — confirming engagement`);
185
+ }
186
+ if (statement.source === "env") {
187
+ return `[embeddings] embedding: CPU, 0 layers (source=env)`;
188
+ }
189
+ return `[embeddings] embedding: CPU (no GPU backend detected)`;
190
+ }
191
+ /** Attach the stated embedding field to a /Health or /HealthDetail body. */
192
+ export function withEmbedGpuHealth(body) {
193
+ return { ...body, embedding: getEmbedGpuStatement() };
194
+ }
195
+ /**
196
+ * Capture stdout/stderr (and console.*) for the duration of `fn`.
197
+ * 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.
201
+ */
202
+ export async function captureIoDuring(fn) {
203
+ const chunks = [];
204
+ const tapChunk = (chunk) => {
205
+ if (typeof chunk === "string")
206
+ chunks.push(chunk);
207
+ else if (Buffer.isBuffer(chunk))
208
+ chunks.push(chunk.toString("utf8"));
209
+ else
210
+ chunks.push(String(chunk));
211
+ };
212
+ const wrapWrite = (orig) => function (chunk, encoding, cb) {
213
+ tapChunk(chunk);
214
+ return orig.call(this, chunk, encoding, cb);
215
+ };
216
+ const origErr = process.stderr.write;
217
+ const origOut = process.stdout.write;
218
+ const origLog = console.log;
219
+ const origWarn = console.warn;
220
+ const origError = console.error;
221
+ const tapConsole = (orig) => (...args) => {
222
+ chunks.push(args.map((a) => (typeof a === "string" ? a : String(a))).join(" ") + "\n");
223
+ return orig.apply(console, args);
224
+ };
225
+ process.stderr.write = wrapWrite(origErr);
226
+ process.stdout.write = wrapWrite(origOut);
227
+ console.log = tapConsole(origLog);
228
+ console.warn = tapConsole(origWarn);
229
+ console.error = tapConsole(origError);
230
+ try {
231
+ const value = await fn();
232
+ return { value, log: chunks.join("") };
233
+ }
234
+ finally {
235
+ process.stderr.write = origErr;
236
+ process.stdout.write = origOut;
237
+ console.log = origLog;
238
+ console.warn = origWarn;
239
+ console.error = origError;
240
+ }
241
+ }
@@ -86,6 +86,8 @@
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";
90
+ export { resolveEmbedGpuLayers } from "./embed-gpu.js";
89
91
  const LOGICAL_NAME = "default";
90
92
  const MODEL_NAME = "nomic-embed-text";
91
93
  /**
@@ -175,23 +177,6 @@ export function resolveEmbedThreads(env = process.env, cores = availableParallel
175
177
  const safeCores = Number.isFinite(cores) && cores >= 1 ? Math.floor(cores) : 1;
176
178
  return Math.max(1, safeCores - 1);
177
179
  }
178
- /**
179
- * llama.cpp GPU-layer offload passed to HFE `register({config:{gpuLayers}})`.
180
- *
181
- * DEFAULT IS UNCHANGED. Unset / empty / non-integer / negative → `undefined`,
182
- * and the register() call OMITS the field so HFE keeps its own default of 0
183
- * (CPU only). This is a measurement pin for the ingest-throughput bench
184
- * (flair#1436 / #1437), not a product default change. #1437 is the decision
185
- * about whether to detect-and-default gpuLayers; this function must not
186
- * pre-empt it.
187
- *
188
- * Override: `FLAIR_EMBED_GPU_LAYERS` — a non-negative integer, env-only
189
- * (same persist-path reason as `FLAIR_EMBED_THREADS`). 0 = CPU only; 99 =
190
- * full offload (the Metal cell). Invalid values fall through to omit.
191
- */
192
- export function resolveEmbedGpuLayers(env = process.env) {
193
- return parseNonNegativeInt(env.FLAIR_EMBED_GPU_LAYERS);
194
- }
195
180
  function parsePositiveInt(raw) {
196
181
  if (raw == null)
197
182
  return undefined;
@@ -203,17 +188,6 @@ function parsePositiveInt(raw) {
203
188
  return undefined;
204
189
  return n;
205
190
  }
206
- function parseNonNegativeInt(raw) {
207
- if (raw == null)
208
- return undefined;
209
- const trimmed = raw.trim();
210
- if (trimmed === "")
211
- return undefined;
212
- const n = Number(trimmed);
213
- if (!Number.isInteger(n) || n < 0)
214
- return undefined;
215
- return n;
216
- }
217
191
  let registered = false;
218
192
  /**
219
193
  * Register the embedding backend. Idempotent within a process (mirrors
@@ -228,20 +202,38 @@ export async function registerEmbeddingsBackend() {
228
202
  const { register } = await import("harper-fabric-embeddings");
229
203
  const modelPath = benchModelPathOverride();
230
204
  const threads = resolveEmbedThreads();
231
- // Omit when unset so HFE's default of 0 is unchanged (flair#1436 measurement
232
- // pin; #1437 is the default-change decision). Never pass a synthesized default.
233
- const gpuLayers = resolveEmbedGpuLayers();
234
- await register({
235
- logicalName: LOGICAL_NAME,
236
- kind: "embedding",
237
- config: {
238
- ...(modelPath
239
- ? { modelPath, pooling: EMBEDDING_POOLING }
240
- : { modelName: MODEL_NAME, modelsDir: resolveModelsDir(), pooling: EMBEDDING_POOLING }),
241
- threads,
242
- ...(gpuLayers !== undefined ? { gpuLayers } : {}),
243
- },
244
- });
205
+ // Always pass a number. Metal-capable host → 99; else 0; env wins.
206
+ // Stated on the boot log and /Health — requested ≠ used (flair#1437).
207
+ const choice = resolveEmbedGpuChoice();
208
+ const config = {
209
+ ...(modelPath
210
+ ? { modelPath, pooling: EMBEDDING_POOLING }
211
+ : { modelName: MODEL_NAME, modelsDir: resolveModelsDir(), pooling: EMBEDDING_POOLING }),
212
+ threads,
213
+ gpuLayers: choice.gpuLayers,
214
+ };
215
+ const needsMetalConfirm = choice.gpuLayers > 0 && choice.metalUsable;
216
+ if (!needsMetalConfirm) {
217
+ const statement = applyEmbedGpuChoice(choice, "");
218
+ console.log(formatEmbedGpuLogLine(statement));
219
+ await register({ logicalName: LOGICAL_NAME, kind: "embedding", config });
220
+ }
221
+ else {
222
+ 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,
229
+ });
230
+ if (engine && typeof engine.ensureReady === "function") {
231
+ await engine.ensureReady();
232
+ }
233
+ });
234
+ const statement = applyEmbedGpuChoice(choice, log);
235
+ console.log(formatEmbedGpuLogLine(statement));
236
+ }
245
237
  }
246
238
  catch (err) {
247
239
  // Not installed, or globalThis.models isn't ready (module loaded outside
@@ -6,7 +6,11 @@
6
6
  * lastSyncAt advance) and then take the oldest lastSyncAt across ALL peers,
7
7
  * including revoked. A healthy hub synced a minute ago plus a revoked row
8
8
  * from June therefore rendered as "0 connected" and fired
9
- * "federation peers all disconnected >24h".
9
+ * "federation peers all disconnected >24h". That pre-#1499 count is the
10
+ * 0.40.0 #1146 symptom (`connected: 0, disconnected: 0`, no `unknown`).
11
+ *
12
+ * flair#1146 names the measure (`PEER_LIVENESS_MEASURED_BY`) so the label
13
+ * cannot be read as a live socket. Do not infer contact from memory lastWrite.
10
14
  *
11
15
  * Three contact states, plus revoked (which never drives the staleness
12
16
  * warning). Same class as #988: missing/unreadable evidence is UNKNOWN,
@@ -18,6 +22,8 @@
18
22
  * revoked stored status → revoked (excluded from the >24h warning)
19
23
  */
20
24
  export const PEER_STALE_MS = 24 * 3600 * 1000;
25
+ /** What `federation.peers.connected` counts. HealthDetail copies this string. */
26
+ export const PEER_LIVENESS_MEASURED_BY = "lastSyncAt";
21
27
  export const FEDERATION_PEERS_ALL_DISCONNECTED_WARNING = "federation peers all disconnected >24h";
22
28
  /** Parse a written last-contact stamp. Missing / unparseable → null, never 0/epoch. */
23
29
  export function parseLastContactMs(lastSyncAt) {
@@ -14,7 +14,8 @@ import { normalizeStamp } from "./embedding-space-guard.js";
14
14
  import { getModelId } from "./embeddings-provider.js";
15
15
  import { describeStampOutstanding, EMBEDDING_STAMP_ID } from "./migrations/stamp-outstanding.js";
16
16
  import { buildPublicHealthBody, resolveSearchReadiness } from "./search-readiness.js";
17
- import { classifyPeerLiveness, federationPeersAllDisconnectedWarning, summarizePeerLiveness, } from "./federation-peer-liveness.js";
17
+ import { withEmbedGpuHealth } from "./embed-gpu.js";
18
+ import { classifyPeerLiveness, federationPeersAllDisconnectedWarning, PEER_LIVENESS_MEASURED_BY, summarizePeerLiveness, } from "./federation-peer-liveness.js";
18
19
  const db = databases;
19
20
  const redactHome = (p) => {
20
21
  const home = homedir();
@@ -111,10 +112,10 @@ export class Health extends Resource {
111
112
  // otherwise (tarball builds) — never omitted, never fabricated (Sherlock).
112
113
  const build = resolveBuildInfo();
113
114
  const readiness = currentSearchReadiness();
114
- const body = buildPublicHealthBody(readiness, {
115
+ const body = withEmbedGpuHealth(buildPublicHealthBody(readiness, {
115
116
  version: build?.version ?? resolveVersion(),
116
117
  buildCommit: build?.commit ?? null,
117
- });
118
+ }));
118
119
  if (readiness.status !== 200) {
119
120
  return new Response(JSON.stringify(body), {
120
121
  status: readiness.status,
@@ -175,6 +176,11 @@ export class HealthDetail extends Resource {
175
176
  // stays HTTP 200 (it is a stats dump, not a traffic gate); the field
176
177
  // and a warning name the lag so `flair status` / operators can see it.
177
178
  const readiness = currentSearchReadiness();
179
+ const embeddingBody = withEmbedGpuHealth({ ok: true });
180
+ stats.embedding = embeddingBody.embedding;
181
+ if (embeddingBody.embedding.fallback) {
182
+ warnings.push({ level: "warn", message: embeddingBody.embedding.fallback });
183
+ }
178
184
  stats.searchReady = readiness.searchReady;
179
185
  // Public/detail shape is unchanged: searchReadyReason stays a lag signal
180
186
  // (present iff !searchReady). Ready-path verification constants stay on
@@ -391,6 +397,8 @@ export class HealthDetail extends Resource {
391
397
  // flair#1499: derive connected/down from lastSyncAt, not stored
392
398
  // status. Pairing writes `paired`; a recent lastSyncAt is connected.
393
399
  // Revoked rows are counted separately and never drive the >24h warning.
400
+ // flair#1146: name the measure so "connected" cannot be read as TCP.
401
+ // Do not substitute memory lastWrite for lastSyncAt.
394
402
  const liveness = summarizePeerLiveness(peers, nowMs);
395
403
  const peersBlock = {
396
404
  total: liveness.total,
@@ -398,6 +406,7 @@ export class HealthDetail extends Resource {
398
406
  disconnected: liveness.disconnected,
399
407
  revoked: liveness.revoked,
400
408
  unknown: liveness.unknown,
409
+ measuredBy: PEER_LIVENESS_MEASURED_BY,
401
410
  };
402
411
  const pendingTokens = tokens.filter((t) => !t.consumedBy && t.expiresAt && new Date(t.expiresAt).getTime() > nowMs).length;
403
412
  stats.federation = {
@@ -417,6 +417,72 @@ export function parseAndValidateCandidates(raw, gatheredMemoryIds) {
417
417
  * matching this file's Harper-free constraint.
418
418
  */
419
419
  export const MODEL_BACKEND_NOT_FOUND_ERROR_NAME = "ModelBackendNotFoundError";
420
+ /**
421
+ * Harper's default `storage.maxTransactionOpenTime` (ms). A write-bearing
422
+ * request transaction that stays open past this ceiling is aborted with
423
+ * HTTP 422 — not the documented 502/503 execute-mode failures. See
424
+ * harper `resources/DatabaseTransaction.ts` `transactionOpenTooLongError`
425
+ * and flair#1263.
426
+ */
427
+ export const HARPER_MAX_TRANSACTION_OPEN_TIME_MS = 30_000;
428
+ /** Harper's status for `transactionOpenTooLongError`. */
429
+ export const TRANSACTION_OPEN_TOO_LONG_STATUS = 422;
430
+ /**
431
+ * Duck-typed release of the Harper request transaction that Resource
432
+ * dispatch opened around `post()`. Must run AFTER gather and BEFORE
433
+ * `models.generate()` so a cold generative backend cannot hold a
434
+ * write-bearing request transaction past `storage.maxTransactionOpenTime`.
435
+ *
436
+ * Harper's `transaction()` wrapper explicitly allows an in-handler
437
+ * `commit({ doneWriting: true })` followed by the wrapper's own final
438
+ * commit (DatabaseTransaction.commit documents this). Clearing
439
+ * `ctx.transaction` afterwards stops `models.generate()` accounting
440
+ * writes from joining the (now closed) request scope via AsyncLocalStorage.
441
+ */
442
+ export async function releaseRequestTransaction(ctx) {
443
+ const txn = ctx?.transaction;
444
+ if (!txn)
445
+ return;
446
+ try {
447
+ const committed = txn.commit?.({ doneWriting: true });
448
+ if (committed && typeof committed.then === "function") {
449
+ await committed;
450
+ }
451
+ }
452
+ catch {
453
+ // Already closed, timed out, or not a Harper transaction — still detach.
454
+ }
455
+ if (ctx)
456
+ ctx.transaction = undefined;
457
+ }
458
+ /**
459
+ * Execute-mode order that keeps the request transaction short: release
460
+ * (and optional warm) first, generate outside any request txn, then write
461
+ * inside a fresh short txn. The helper is Harper-free so the 422 ceiling
462
+ * is unit-testable with an injected delay.
463
+ */
464
+ export async function runExecuteDistillation(opts) {
465
+ await opts.releaseRequestTxn();
466
+ if (opts.warm)
467
+ await opts.warm();
468
+ const generated = await opts.generate();
469
+ return opts.write(generated);
470
+ }
471
+ /**
472
+ * Simulated Harper long-transaction monitor for fails-first tests.
473
+ * A write-bearing transaction that stays open while `generate` runs
474
+ * past `ceilingMs` is the 422 abort operators hit on a cold backend.
475
+ *
476
+ * `generateStartedWhileTxnOpen` is the MAIN interleaving (generate
477
+ * inside Resource.post()'s request txn). After #1263 it must be false.
478
+ */
479
+ export function evaluateTxnCeiling(opts) {
480
+ const ceilingMs = opts.ceilingMs ?? HARPER_MAX_TRANSACTION_OPEN_TIME_MS;
481
+ if (opts.generateStartedWhileTxnOpen && opts.generateDurationMs > ceilingMs) {
482
+ return { status: TRANSACTION_OPEN_TOO_LONG_STATUS };
483
+ }
484
+ return { ok: true };
485
+ }
420
486
  /**
421
487
  * Calls generate(), validates the result, and on malformed/mismatched output
422
488
  * retries exactly once with an explicit `responseFormat: 'json'` (the
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Sole Harper `models.generate` binding for /ReflectMemories execute.
3
+ *
4
+ * MemoryReflect.ts must not call `models.generate()` itself (flair#1263
5
+ * condition 2): the resource reaches generate only by passing this binder
6
+ * into `runExecuteDistillation` → `generateCandidates`.
7
+ */
8
+ import { models } from "harper";
9
+ export const reflectModelsGenerate = (input, opts) => models.generate(input, opts);