@tpsdev-ai/flair 0.54.2 → 0.55.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/dist/build-info.json +3 -3
  2. package/dist/cli.js +774 -176
  3. package/dist/commands/doctor.js +61 -1
  4. package/dist/commands/federation.js +131 -36
  5. package/dist/commands/hook.js +20 -10
  6. package/dist/commands/init.js +193 -67
  7. package/dist/commands/service.js +16 -12
  8. package/dist/commands/soul.js +10 -5
  9. package/dist/commands/status.js +62 -7
  10. package/dist/doctor-client.js +118 -32
  11. package/dist/hook-install.js +170 -16
  12. package/dist/lib/doctor-run.js +49 -3
  13. package/dist/lib/embed-gpu-doctor.js +30 -0
  14. package/dist/lib/federation-pair-access.js +118 -0
  15. package/dist/lib/harper-port-value.js +43 -0
  16. package/dist/lib/http-bind.js +227 -0
  17. package/dist/lib/init-admin-pass.js +316 -0
  18. package/dist/lib/launchd-management.js +16 -0
  19. package/dist/lib/launchd-repair.js +122 -1
  20. package/dist/lib/owned-pins.js +54 -1
  21. package/dist/lib/process-start-time.js +82 -0
  22. package/dist/lib/scratch-owner.js +124 -10
  23. package/dist/lib/stale-client-pin.js +26 -0
  24. package/dist/rem/runner.js +10 -1
  25. package/dist/resources/AdminInstance.js +8 -2
  26. package/dist/resources/Memory.js +36 -1
  27. package/dist/resources/MemoryBootstrap.js +23 -32
  28. package/dist/resources/MemoryFeed.js +4 -1
  29. package/dist/resources/MemoryReflect.js +121 -93
  30. package/dist/resources/SkillScan.js +13 -11
  31. package/dist/resources/Soul.js +15 -1
  32. package/dist/resources/XAA.js +16 -1
  33. package/dist/resources/a2a-url.js +5 -2
  34. package/dist/resources/client-version-gate.js +144 -0
  35. package/dist/resources/embed-gpu.js +241 -0
  36. package/dist/resources/embeddings-boot.js +34 -42
  37. package/dist/resources/federation-peer-liveness.js +7 -1
  38. package/dist/resources/health.js +12 -3
  39. package/dist/resources/memory-reflect-lib.js +66 -0
  40. package/dist/resources/memory-reflect-models.js +9 -0
  41. package/dist/resources/migrations/embedding-stamp.js +32 -4
  42. package/dist/resources/oauth-discovery.js +3 -1
  43. package/dist/resources/record-type-kit.js +59 -0
  44. package/dist/resources/scan/skill-markdown.js +166 -0
  45. package/dist/resources/scan/skill-scanner.js +89 -68
  46. package/dist/resources/skill-provenance.js +273 -0
  47. package/dist/resources/skill-write.js +26 -7
  48. package/dist/src/lib/harper-port-value.js +43 -0
  49. package/docs/api-reference.md +35 -2
  50. package/docs/deployment.md +1 -1
  51. package/docs/federation.md +18 -7
  52. package/docs/mcp-clients.md +19 -6
  53. package/docs/releasing.md +79 -13
  54. package/docs/rem.md +1 -1
  55. package/docs/secrets-and-keys.md +1 -0
  56. package/docs/standalone-local.md +1 -1
  57. package/docs/troubleshooting.md +17 -0
  58. package/package.json +1 -1
@@ -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);
@@ -135,6 +135,8 @@
135
135
  */
136
136
  import { databases } from "harper";
137
137
  import { getModelId } from "../embeddings-provider.js";
138
+ import { harperPortValue } from "../../src/lib/harper-port-value.js";
139
+ import { DEFAULT_HTTP_PORT } from "../a2a-url.js";
138
140
  import { currentSpaceRawForms, isCurrentSpaceStamp } from "../embedding-space-guard.js";
139
141
  import { EMBEDDING_STAMP_ID } from "./stamp-outstanding.js";
140
142
  export { EMBEDDING_STAMP_ID };
@@ -149,10 +151,36 @@ function resolveAdminAuthHeader() {
149
151
  return null;
150
152
  return "Basic " + Buffer.from(`admin:${pass}`).toString("base64");
151
153
  }
152
- /** Same HTTP_PORT env resolution src/cli.ts sets on every Harper spawn (see that file's grep for HTTP_PORT). */
153
- function resolveSelfBaseUrl() {
154
- const port = process.env.HTTP_PORT ?? "9926";
155
- return `http://127.0.0.1:${port}`;
154
+ /**
155
+ * Base URL for the loopback self-call that regenerates an embedding.
156
+ *
157
+ * ALWAYS loopback. This is the destination of a credentialed self-call —
158
+ * `regenViaHttpPut` sends `Authorization: Basic` carrying the admin password to
159
+ * it — so it must never leave the box. `FLAIR_PUBLIC_URL` names a remote /
160
+ * reverse-proxied origin and is deliberately ignored here, matching
161
+ * `a2a-url.localBaseUrl` ("never the public/proxy URL"): two self-call
162
+ * resolvers, both pinned to loopback. The public-facing resolvers (e.g.
163
+ * oauth-discovery, AdminInstance, XAA; also a2a-url.resolvePublicBaseUrl and
164
+ * the MCP issuer resolvers) honour `FLAIR_PUBLIC_URL` precisely because their
165
+ * output is meant to be reachable off-box; this one's output is not. That list
166
+ * is illustrative, not exhaustive — the deciding question is whether the URL
167
+ * leaves the box, not a roster of call sites.
168
+ *
169
+ * Pinned by the "loopback self-call target" suite in
170
+ * test/unit/host-qualified-port-consumers.test.ts, which asserts this returns
171
+ * loopback even when `FLAIR_PUBLIC_URL` is set (and not merely that it parses).
172
+ *
173
+ * `HTTP_PORT` is parsed through `harperPortValue` so a host-qualified value
174
+ * (`127.0.0.1:19926`) yields a valid URL rather than a doubled host. Absent
175
+ * (or out-of-range) falls back to `DEFAULT_HTTP_PORT` (19926) — NOT the legacy
176
+ * early-install 9926 this used to reach for. 9926 is Harper's OWN default bind,
177
+ * which is what the one boot shape that reaches this fallback actually uses: a
178
+ * bare `harper run .` that flair did not spawn. On a pre-March data dir that
179
+ * 9926 coincidentally matched the real bind; post-March 19926 does. Both are
180
+ * guesses — `HTTP_PORT` is the only channel carrying the truth.
181
+ */
182
+ export function resolveSelfBaseUrl(env = process.env) {
183
+ return `http://127.0.0.1:${harperPortValue(env.HTTP_PORT) ?? DEFAULT_HTTP_PORT}`;
156
184
  }
157
185
  /**
158
186
  * Triggers Memory.put()'s regen branch via a genuine loopback HTTP PUT —
@@ -28,6 +28,8 @@
28
28
  */
29
29
  import { mcpOAuthEnabled } from "./mcp-oauth-flag.js";
30
30
  import { dcrEnabled } from "./dcr-gate.js";
31
+ import { harperPortValue } from "../src/lib/harper-port-value.js";
32
+ import { DEFAULT_HTTP_PORT } from "./a2a-url.js";
31
33
  /** RFC 9728 §3.1 — Protected Resource Metadata well-known path. */
32
34
  export const PRM_PATH = "/.well-known/oauth-protected-resource";
33
35
  /** RFC 8414 §3 — Authorization Server Metadata well-known path. */
@@ -39,7 +41,7 @@ export const AS_METADATA_PATH = "/.well-known/oauth-authorization-server";
39
41
  * existed — moved, not changed. See the header note on flair#1005.
40
42
  */
41
43
  export function oauthPublicBaseUrl() {
42
- return process.env.FLAIR_PUBLIC_URL || `http://127.0.0.1:${process.env.HTTP_PORT || 19926}`;
44
+ return process.env.FLAIR_PUBLIC_URL || `http://127.0.0.1:${harperPortValue(process.env.HTTP_PORT) ?? DEFAULT_HTTP_PORT}`;
43
45
  }
44
46
  /**
45
47
  * The RFC 8707 resource identifier of flair's MCP surface: `<base>/mcp`.
@@ -292,6 +292,65 @@ export function makeScopedSearch(readScope) {
292
292
  export function stampAttribution(auth, content, field, mode, forbiddenMessage) {
293
293
  if (auth.kind !== "agent")
294
294
  return {}; // internal → always passthrough
295
+ // KNOWN, DATED ASYMMETRY (2026-09-18, tracked as flair#1741 — do not
296
+ // "fix" here; that change wants its own design pass):
297
+ //
298
+ // An admin AGENT KEY (a TPS-Ed25519 signature whose principal is in the
299
+ // admin set) is treated as an OPERATOR on this branch: every kit table's
300
+ // write path honors a body-supplied owner field from it (or defaults it
301
+ // under "stamp-default") rather than stamping the caller's own identity.
302
+ // agent-auth.ts resolves such a key and credentialed Basic super_user
303
+ // ALIKE to `isAdmin: true`, but from different evidence — the key's
304
+ // boolean is the middleware-computed `tpsAgentIsAdmin` annotation, the
305
+ // Basic one a `user.role.permission.super_user` role claim — and the
306
+ // verdict cannot tell which evidence produced it. That predates #1537's
307
+ // source-class model, which adopted the OPPOSITE rule for Soul — "Role
308
+ // is not source: an admin agent key or delegated OAuth identity is still
309
+ // a runtime credential. Only verified Basic admin auth enters the
310
+ // operator path" (resources/soul-write-policy.ts) — and this branch has
311
+ // NOT been re-adjudicated against it. Both controls were deliberate;
312
+ // nobody propagated the newer rule backward. That is policy drift, not
313
+ // code drift.
314
+ //
315
+ // WRITE reach, so this is taken seriously and not read as a Soul-only
316
+ // concern: this branch sits BEFORE the mode switch, so it covers EVERY
317
+ // kit call site in EVERY mode — Memory, MemoryFeed, Credential, OrgEvent,
318
+ // Relationship, WorkspaceState, Asset and MemoryCandidate. Soul is
319
+ // protected only because its source gate (authorizeSoulWrite) lives
320
+ // OUTSIDE the kit and re-reads the raw Authorization header before
321
+ // stampAttribution is ever reached.
322
+ //
323
+ // READ reach — the SAME `isAdmin` boolean is also the READ authorization
324
+ // in this kit, so the exposure is unfiltered reads of owner-scoped data,
325
+ // not just forged provenance on writes: resolveAuthGate returns
326
+ // { kind: "unfiltered" } for admin (the verdict that also dispatches the
327
+ // Asset/MemoryCandidate/OrgEvent delete() paths), makeByIdReadGate
328
+ // returns superGet(target) with no ownership check, Credential.search()/
329
+ // get() branch on the same verdict out-of-kit (Credential.ts), and
330
+ // Message.ts hand-rolls the identical branch inline. With an admin agent
331
+ // key, that reads: MemoryCandidate rows whose contract is "a candidate
332
+ // must not be org-readable before a human/agent reviewer explicitly
333
+ // promotes or rejects it" (record-types.ts); other principals' Credential
334
+ // rows — get() strips tokenHash but returns the metadata, and search()'s
335
+ // admin branch strips NOTHING (the strip lives only in get()); and every
336
+ // Message in the table. Provenance integrity AND confidentiality, one
337
+ // root cause: the verdict conflates a runtime credential with the
338
+ // operator. Same fix — #1741's credential class.
339
+ //
340
+ // PINNING: the behaviour is pinned, but only as behaviour, and every pin
341
+ // passes `isAdmin` as a bare boolean (`agentCtx("agent-admin", true)`)
342
+ // because the code cannot express the credential distinction. Writes —
343
+ // record-type-kit.test.ts's "admin → always passthrough" (validate-
344
+ // truthy and validate-strict), "admin + field absent → default-if-absent
345
+ // (||=)" (stamp-default) and "admin → passthrough, NO default-if-absent"
346
+ // (stamp-strict). Reads — the same file's "admin agent → unfiltered via
347
+ // superGet, no ownership check" and "admin agent → unfiltered", plus
348
+ // memory-candidate-read-gate.test.ts's "admin agent → returns any id
349
+ // unchanged, no ownership check" and "an admin agent sees every
350
+ // candidate, unfiltered". Soul's out-of-kit gate — the TPS-Ed25519-
351
+ // adminAgent-toNull line in soul-adk-refusal.test.ts. Until #1741 lands,
352
+ // "an admin agent key cannot read X" is UNTESTABLE — the read path's
353
+ // credential-class property is pinned by nothing today.
295
354
  if (auth.isAdmin) {
296
355
  if (mode === "stamp-default")
297
356
  content[field] ||= auth.agentId;