@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
@@ -34,14 +34,17 @@
34
34
  * dropped by the stale-intent post-filter
35
35
  *
36
36
  * The pure logic behind execute mode (prompt building, actor resolution,
37
- * generate+validate+retry, dedup) lives in ./memory-reflect-lib.ts — see that
38
- * file's header for why: importing Resource/databases/models here pulls in
39
- * the Harper runtime and can't be unit-tested directly (Harper injects
40
- * `Resource` as a runtime global; bun's ESM linker rejects `import {
41
- * Resource }` outright — see test/unit/resource-allow.test.ts). This
42
- * resource is a thin orchestrator over the lib's tested functions.
37
+ * generate+validate+retry, dedup, #1263 txn boundary) lives in
38
+ * ./memory-reflect-lib.ts — see that file's header for why: importing
39
+ * Resource/databases/models here pulls in the Harper runtime and can't be
40
+ * unit-tested directly (Harper injects `Resource` as a runtime global;
41
+ * bun's ESM linker rejects `import { Resource }` outright — see
42
+ * test/unit/resource-allow.test.ts). This resource is a thin orchestrator
43
+ * over the lib's tested functions. Execute mode releases the request
44
+ * transaction before the generative call so a cold backend cannot trip
45
+ * Harper's 30s open-transaction 422 (flair#1263).
43
46
  */
44
- import { Resource, databases, models, logger } from "harper";
47
+ import { Resource, databases, logger } from "harper";
45
48
  import { randomBytes } from "node:crypto";
46
49
  import { existsSync } from "node:fs";
47
50
  import { resolve } from "node:path";
@@ -49,7 +52,8 @@ import { homedir } from "node:os";
49
52
  import { setImmediate as yieldToRequests } from "node:timers/promises";
50
53
  import { isAdmin, allowVerified } from "./agent-auth.js";
51
54
  import { patchRecordSilent } from "./table-helpers.js";
52
- import { buildReflectionPrompt, buildExecutePrompt, resolveReflectActor, generateCandidates, dedupeCandidates, memoryMatchesReflectScope, buildStagedCandidateRow, isContinuityScopeTag, filterStaleSessionIntentCandidates, resolveCandidateVisibilityRuling, considerForOldestUnreflectedCap, isRemAbortRequested, resolveMaxMemoriesPerRun, shouldStampLastReflected, DEFAULT_STALE_INTENT_HORIZON_MS, REM_GATHER_YIELD_BUDGET_MS, } from "./memory-reflect-lib.js";
55
+ import { buildReflectionPrompt, buildExecutePrompt, resolveReflectActor, generateCandidates, releaseRequestTransaction, runExecuteDistillation, dedupeCandidates, memoryMatchesReflectScope, buildStagedCandidateRow, isContinuityScopeTag, filterStaleSessionIntentCandidates, resolveCandidateVisibilityRuling, considerForOldestUnreflectedCap, isRemAbortRequested, resolveMaxMemoriesPerRun, shouldStampLastReflected, DEFAULT_STALE_INTENT_HORIZON_MS, REM_GATHER_YIELD_BUDGET_MS, } from "./memory-reflect-lib.js";
56
+ import { reflectModelsGenerate } from "./memory-reflect-models.js";
53
57
  /** Same path `flair rem pause` writes. Duplicated across the src/ boundary. */
54
58
  const REM_PAUSE_FLAG = resolve(homedir(), ".flair", "rem.paused");
55
59
  const GATHER_SELECT = [
@@ -194,108 +198,132 @@ export class ReflectMemories extends Resource {
194
198
  });
195
199
  const gatheredMemoryIds = new Set(promptInputs.map((m) => m.id));
196
200
  const configuredModel = process.env.FLAIR_REM_MODEL || undefined;
197
- const outcome = await generateCandidates({
198
- prompt: executePrompt,
199
- model: configuredModel,
200
- gatheredMemoryIds,
201
- generate: (input, opts) => models.generate(input, opts),
201
+ // #1263: Resource dispatch already opened a request transaction around
202
+ // post(). A cold generative call (Ollama model load > 30s) held that
203
+ // write-bearing txn past storage.maxTransactionOpenTime → HTTP 422,
204
+ // not the documented 502/503. Release the request txn before generate
205
+ // (distill outside it); stage inside a fresh short write window.
206
+ // The resource reaches generate only through this helper + binder.
207
+ const distill = await runExecuteDistillation({
208
+ releaseRequestTxn: () => releaseRequestTransaction(ctx),
209
+ generate: () => generateCandidates({
210
+ prompt: executePrompt,
211
+ model: configuredModel,
212
+ gatheredMemoryIds,
213
+ generate: reflectModelsGenerate,
214
+ }),
215
+ write: async (outcome) => {
216
+ if (!outcome.ok)
217
+ return { kind: "failed", outcome };
218
+ if (outcome.usedJsonFallback) {
219
+ logger.warn?.(`MemoryReflect: json-fallback path active for agent ${agentId} (schema-mode output failed validation)`);
220
+ }
221
+ // flair#1257 slice 3 — the stale-intent POST-FILTER (the testable second
222
+ // layer of the two-layer guard; the prompt rule above is the primary).
223
+ // Runs AFTER validation (a drop is a policy skip, never a batch failure)
224
+ // and BEFORE dedup/staging. Only continuity runs are filtered — for every
225
+ // other run this is a straight pass-through.
226
+ const staleIntentResult = isContinuityRun
227
+ ? filterStaleSessionIntentCandidates(outcome.candidates, {
228
+ sessionNewestCreatedAt,
229
+ now: executeNow,
230
+ horizonMs: staleHorizonMs,
231
+ })
232
+ : { kept: outcome.candidates, droppedStaleIntent: [] };
233
+ if (staleIntentResult.droppedStaleIntent.length > 0) {
234
+ logger.warn?.(`MemoryReflect: stale-intent filter dropped ${staleIntentResult.droppedStaleIntent.length} candidate(s) for agent ${agentId} (stale continuity session)`);
235
+ }
236
+ // Dedup against this agent's existing pending candidates (spec §3A item 4).
237
+ const existingPendingClaims = [];
238
+ let writeYieldAt = performance.now() + REM_GATHER_YIELD_BUDGET_MS;
239
+ for await (const c of databases.flair.MemoryCandidate.search({})) {
240
+ if (performance.now() >= writeYieldAt) {
241
+ await yieldToRequests();
242
+ writeYieldAt = performance.now() + REM_GATHER_YIELD_BUDGET_MS;
243
+ }
244
+ if (c.agentId !== agentId)
245
+ continue;
246
+ if (c.status !== "pending")
247
+ continue;
248
+ existingPendingClaims.push(c.claim);
249
+ }
250
+ const toStage = dedupeCandidates(staleIntentResult.kept, existingPendingClaims);
251
+ // generatedBy: GenerateResult in the pinned harper 5.1.17 has
252
+ // no model/backend-id field (content/finishReason/usage/toolCalls/trace
253
+ // only) — the "from the generate result if available" branch is
254
+ // unreachable in this version, so this always falls back to the
255
+ // configured logical name, matching Harper's own default routing name.
256
+ const resolvedModel = configuredModel ?? "default";
257
+ const generatedAt = new Date().toISOString();
258
+ // Write-window atomicity (#1263): generate has already succeeded.
259
+ // Each MemoryCandidate.put is its own short commit. A throw mid-loop
260
+ // leaves earlier puts durable and skips lastReflected (never reached).
261
+ // lastReflected is patchRecordSilent — it cannot fail the request.
262
+ // 502/503 stay generate-only (no_backend / distillation_failed).
263
+ const staged = [];
264
+ for (const c of toStage) {
265
+ // #1205b-1: buildStagedCandidateRow stamps `scopeTag` when this run was
266
+ // scope:"tagged" — the authoritative per-user tag promotion consumes
267
+ // directly (closing the #1205a source-re-read seam). Non-tagged runs
268
+ // leave scopeTag absent, unchanged.
269
+ const row = buildStagedCandidateRow({
270
+ id: `cand_${randomBytes(8).toString("hex")}`,
271
+ agentId,
272
+ claim: c.claim,
273
+ sourceMemoryIds: c.sourceMemoryIds,
274
+ rationalePrompt: executePrompt,
275
+ generatedBy: resolvedModel,
276
+ generatedAt,
277
+ scope,
278
+ tag,
279
+ // flair#1257 slice 3: record an AFFIRMATIVE shared ruling (with its
280
+ // team-relevance justification) on the candidate — continuity runs
281
+ // only. resolveCandidateVisibilityRuling returns null for anything
282
+ // less than shared+justified, and null stamps nothing: the promoted
283
+ // row then defaults private (Sherlock's default-private-unless).
284
+ visibilityRuling: isContinuityRun ? resolveCandidateVisibilityRuling(c) : null,
285
+ });
286
+ await databases.flair.MemoryCandidate.put(row);
287
+ staged.push(row);
288
+ }
289
+ // Stamp after a successful generate on execute runs only. Prompt-only
290
+ // and 502/503/abort leave lastReflected unset so the next night retries
291
+ // the same sources instead of permanently skipping them (#1515 Bugbot).
292
+ if (shouldStampLastReflected({ execute, generateSucceeded: true })) {
293
+ const now = new Date().toISOString();
294
+ for (const memory of memories) {
295
+ patchRecordSilent(databases.flair.Memory, memory.id, { lastReflected: now });
296
+ }
297
+ }
298
+ return {
299
+ kind: "ok",
300
+ staged,
301
+ resolvedModel,
302
+ droppedStaleIntent: staleIntentResult.droppedStaleIntent.length,
303
+ };
304
+ },
202
305
  });
203
- if (!outcome.ok) {
204
- if (outcome.reason === "no_backend") {
306
+ if (distill.kind === "failed") {
307
+ if (distill.outcome.reason === "no_backend") {
205
308
  // Static body (K&S) — never echo Harper version, backend lists, or endpoints.
206
309
  return new Response(JSON.stringify({ error: "No generative backend configured. See the models configuration docs." }), { status: 503 });
207
310
  }
208
311
  return new Response(JSON.stringify({ error: "distillation_failed", detail: "model output did not validate after one retry" }), { status: 502 });
209
312
  }
210
- if (outcome.usedJsonFallback) {
211
- logger.warn?.(`MemoryReflect: json-fallback path active for agent ${agentId} (schema-mode output failed validation)`);
212
- }
213
- // flair#1257 slice 3 — the stale-intent POST-FILTER (the testable second
214
- // layer of the two-layer guard; the prompt rule above is the primary).
215
- // Runs AFTER validation (a drop is a policy skip, never a batch failure)
216
- // and BEFORE dedup/staging. Only continuity runs are filtered — for every
217
- // other run this is a straight pass-through.
218
- const staleIntentResult = isContinuityRun
219
- ? filterStaleSessionIntentCandidates(outcome.candidates, {
220
- sessionNewestCreatedAt,
221
- now: executeNow,
222
- horizonMs: staleHorizonMs,
223
- })
224
- : { kept: outcome.candidates, droppedStaleIntent: [] };
225
- if (staleIntentResult.droppedStaleIntent.length > 0) {
226
- logger.warn?.(`MemoryReflect: stale-intent filter dropped ${staleIntentResult.droppedStaleIntent.length} candidate(s) for agent ${agentId} (stale continuity session)`);
227
- }
228
- // Dedup against this agent's existing pending candidates (spec §3A item 4).
229
- const existingPendingClaims = [];
230
- yieldAt = performance.now() + REM_GATHER_YIELD_BUDGET_MS;
231
- for await (const c of databases.flair.MemoryCandidate.search({})) {
232
- if (performance.now() >= yieldAt) {
233
- await yieldToRequests();
234
- yieldAt = performance.now() + REM_GATHER_YIELD_BUDGET_MS;
235
- }
236
- if (c.agentId !== agentId)
237
- continue;
238
- if (c.status !== "pending")
239
- continue;
240
- existingPendingClaims.push(c.claim);
241
- }
242
- const toStage = dedupeCandidates(staleIntentResult.kept, existingPendingClaims);
243
- // generatedBy: GenerateResult in the pinned harper 5.1.17 has
244
- // no model/backend-id field (content/finishReason/usage/toolCalls/trace
245
- // only) — the "from the generate result if available" branch is
246
- // unreachable in this version, so this always falls back to the
247
- // configured logical name, matching Harper's own default routing name.
248
- const resolvedModel = configuredModel ?? "default";
249
- const generatedAt = new Date().toISOString();
250
- const staged = [];
251
- for (const c of toStage) {
252
- // #1205b-1: buildStagedCandidateRow stamps `scopeTag` when this run was
253
- // scope:"tagged" — the authoritative per-user tag promotion consumes
254
- // directly (closing the #1205a source-re-read seam). Non-tagged runs
255
- // leave scopeTag absent, unchanged.
256
- const row = buildStagedCandidateRow({
257
- id: `cand_${randomBytes(8).toString("hex")}`,
258
- agentId,
259
- claim: c.claim,
260
- sourceMemoryIds: c.sourceMemoryIds,
261
- rationalePrompt: executePrompt,
262
- generatedBy: resolvedModel,
263
- generatedAt,
264
- scope,
265
- tag,
266
- // flair#1257 slice 3: record an AFFIRMATIVE shared ruling (with its
267
- // team-relevance justification) on the candidate — continuity runs
268
- // only. resolveCandidateVisibilityRuling returns null for anything
269
- // less than shared+justified, and null stamps nothing: the promoted
270
- // row then defaults private (Sherlock's default-private-unless).
271
- visibilityRuling: isContinuityRun ? resolveCandidateVisibilityRuling(c) : null,
272
- });
273
- await databases.flair.MemoryCandidate.put(row);
274
- staged.push(row);
275
- }
276
- // Stamp after a successful generate on execute runs only. Prompt-only
277
- // and 502/503/abort leave lastReflected unset so the next night retries
278
- // the same sources instead of permanently skipping them (#1515 Bugbot).
279
- if (shouldStampLastReflected({ execute, generateSucceeded: true })) {
280
- const now = new Date().toISOString();
281
- for (const memory of memories) {
282
- patchRecordSilent(databases.flair.Memory, memory.id, { lastReflected: now });
283
- }
284
- }
285
313
  // Response omits rationalePrompt (spec §3A item 5: "no prompt field") —
286
314
  // it's identical across every row in this batch and already persisted
287
315
  // for audit on the MemoryCandidate row itself; echoing it back per
288
316
  // candidate would just repeat the same large string N times. Matches
289
317
  // `flair rem candidates`' own listing, which doesn't surface it either.
290
- const responseCandidates = staged.map(({ rationalePrompt, ...rest }) => rest);
318
+ const responseCandidates = distill.staged.map(({ rationalePrompt, ...rest }) => rest);
291
319
  return {
292
320
  candidates: responseCandidates,
293
321
  count: responseCandidates.length,
294
- model: resolvedModel,
322
+ model: distill.resolvedModel,
295
323
  ...gatherMeta,
296
324
  // flair#1257 slice 3: continuity-run observability — how many candidates
297
325
  // the stale-intent post-filter dropped (0 for non-continuity runs).
298
- ...(isContinuityRun ? { droppedStaleIntent: staleIntentResult.droppedStaleIntent.length } : {}),
326
+ ...(isContinuityRun ? { droppedStaleIntent: distill.droppedStaleIntent } : {}),
299
327
  };
300
328
  }
301
329
  }
@@ -18,17 +18,19 @@ import { scanSkillContent } from "./scan/skill-scanner.js";
18
18
  * runtime deps) so unit tests can exercise it without instantiating the
19
19
  * Harper database.
20
20
  *
21
- * Markdown awareness:
22
- * - Inline `single-token` backticks (markdown identifier convention) are NOT
23
- * flagged. Only inline backticks whose content actually looks shell-ish
24
- * (whitespace, pipe, semicolon, env-var, $(), &&, ||) fire shell_backtick.
25
- * - Fenced ```code blocks``` with no language hint or a shell-family
26
- * language (sh|bash|shell|zsh) are scanned for shell patterns. Non-shell
27
- * language hints (json, yaml, ts, py, graphql, etc.) skip the shell
28
- * patterns but keep network/fs/encoding/unicode detection active — those
29
- * are language-agnostic attack surfaces.
30
- * - This prevents the documentation-as-skill false-positive class without
31
- * weakening detection on actual shell content.
21
+ * Markdown is parsed before scanning (see `./scan/skill-markdown.ts`):
22
+ * - Well-formed inline code spans and fenced blocks are documentation
23
+ * for `shell_backtick`. Naming `npm create harper@latest` in a bullet
24
+ * is not a substitution the loader would execute.
25
+ * - Executable surfaces are YAML frontmatter, prose, and fail-closed
26
+ * leftovers (unclosed fences, unmatched backtick runs). `$(...)` on
27
+ * those surfaces is a substitution. A backtick pair in frontmatter is
28
+ * YAML legacy substitution, not markdown docs, and also fires
29
+ * `shell_backtick`.
30
+ * - Inline and fenced interiors still run the non-backtick detectors
31
+ * (exec/network/fs/encoding). Wrapping exec() in one backtick is not
32
+ * an exemption. A fence marker is not scanned. Unicode/homoglyph
33
+ * checks always run on the raw line.
32
34
  */
33
35
  export class SkillScan extends Resource {
34
36
  /**
@@ -4,6 +4,7 @@ import { localInstanceId } from "./instance-identity.js";
4
4
  import { makeAuthGate, stampAttribution } from "./record-type-kit.js";
5
5
  import { RECORD_TYPES } from "./record-types.js";
6
6
  import { authorizeSoulWrite, refuseSoulWriteContent, soulProvenance } from "./soul-write-policy.js";
7
+ import { refuseSkillAssignmentWrite } from "./skill-provenance.js";
7
8
  // Source authorization is independent of principal ownership: an admin runtime
8
9
  // may manage records elsewhere, but it cannot author identity-defining Soul.
9
10
  async function enforceWriteAuth(self, data) {
@@ -43,6 +44,9 @@ export class Soul extends databases.flair.Soul {
43
44
  const learnedDenied = await refuseSoulWriteContent(content);
44
45
  if (learnedDenied)
45
46
  return learnedDenied;
47
+ const skillSourceDenied = refuseSkillAssignmentWrite(content);
48
+ if (skillSourceDenied)
49
+ return skillSourceDenied;
46
50
  content.durability ||= "permanent";
47
51
  content.createdAt = new Date().toISOString();
48
52
  content.updatedAt = content.createdAt;
@@ -78,6 +82,9 @@ export class Soul extends databases.flair.Soul {
78
82
  const learnedDenied = await refuseSoulWriteContent({ ...existing, ...content });
79
83
  if (learnedDenied)
80
84
  return learnedDenied;
85
+ const skillSourceDenied = refuseSkillAssignmentWrite(content, existing);
86
+ if (skillSourceDenied)
87
+ return skillSourceDenied;
81
88
  return super.patch(content, query);
82
89
  }
83
90
  async put(content, context) {
@@ -87,7 +94,14 @@ export class Soul extends databases.flair.Soul {
87
94
  const learnedDenied = await refuseSoulWriteContent(content);
88
95
  if (learnedDenied)
89
96
  return learnedDenied;
90
- const ownerDenial = await guardOwnerFieldImmutable(this, () => super.get(), content, "agentId");
97
+ const existing = await super.get();
98
+ const existingRow = existing && typeof existing === "object" && !(existing instanceof Response)
99
+ ? existing
100
+ : undefined;
101
+ const skillSourceDenied = refuseSkillAssignmentWrite(content, existingRow);
102
+ if (skillSourceDenied)
103
+ return skillSourceDenied;
104
+ const ownerDenial = await guardOwnerFieldImmutable(this, () => existing, content, "agentId");
91
105
  if (ownerDenial)
92
106
  return ownerDenial;
93
107
  content.updatedAt = new Date().toISOString();
@@ -1,5 +1,7 @@
1
1
  import { databases } from "harper";
2
2
  import { allowAdmin } from "./agent-auth.js";
3
+ import { harperPortValue } from "../src/lib/harper-port-value.js";
4
+ import { DEFAULT_HTTP_PORT } from "./a2a-url.js";
3
5
  import { createHash, randomBytes } from "node:crypto";
4
6
  import { createRemoteJWKSet, jwtVerify } from "jose";
5
7
  /**
@@ -175,6 +177,19 @@ async function resolveOrCreatePrincipal(payload, idpConfig) {
175
177
  });
176
178
  return principalId;
177
179
  }
180
+ /**
181
+ * Base URL an ID-JAG is validated against: `FLAIR_PUBLIC_URL` when set,
182
+ * otherwise the loopback bind address. `HTTP_PORT` is parsed through
183
+ * `harperPortValue` so a host-qualified value (`127.0.0.1:19926`) yields a
184
+ * valid URL rather than a doubled host; the default is `DEFAULT_HTTP_PORT`
185
+ * (19926).
186
+ *
187
+ * Exported for direct unit testing — the grant handler itself needs a live
188
+ * Harper database (IdpConfig, Credential, Agent tables).
189
+ */
190
+ export function jwtBearerBaseUrl(env = process.env) {
191
+ return env.FLAIR_PUBLIC_URL || `http://127.0.0.1:${harperPortValue(env.HTTP_PORT) ?? DEFAULT_HTTP_PORT}`;
192
+ }
178
193
  /**
179
194
  * Handle the jwt-bearer grant type at the token endpoint.
180
195
  * Called from OAuthToken when grant_type is urn:ietf:params:oauth:grant-type:jwt-bearer.
@@ -187,7 +202,7 @@ export async function handleJwtBearerGrant(data) {
187
202
  error_description: "assertion parameter required for jwt-bearer grant",
188
203
  }), { status: 400, headers: { "content-type": "application/json" } });
189
204
  }
190
- const baseUrl = process.env.FLAIR_PUBLIC_URL || `http://127.0.0.1:${process.env.HTTP_PORT || 19926}`;
205
+ const baseUrl = jwtBearerBaseUrl();
191
206
  try {
192
207
  const { payload, idpConfig } = await validateIdJag(assertion, baseUrl);
193
208
  // Resolve or create principal
@@ -10,14 +10,17 @@
10
10
  // unit-testable without spinning up Harper (mirrors agentcard-fields.ts —
11
11
  // avoids the simulator-pattern drift that let the AdminInstance predicate be
12
12
  // reproduced-not-imported).
13
+ import { harperPortValue } from "../src/lib/harper-port-value.js";
13
14
  // The CLI's DEFAULT_HTTP_PORT (src/cli.ts `DEFAULT_PORT`). Keep in sync.
14
15
  export const DEFAULT_HTTP_PORT = 19926;
15
16
  // Loopback base URL for in-process self-calls (e.g. the streaming catch-up
16
17
  // fetch). Points at the port Flair is ACTUALLY listening on, which Harper
17
18
  // exposes via HTTP_PORT in the runtime env — never the public/proxy URL.
18
- // Falls back to DEFAULT_HTTP_PORT for a default local install.
19
+ // `HTTP_PORT` is parsed through `harperPortValue` so a host-qualified value
20
+ // (`127.0.0.1:19926`, `[::1]:19926`) yields a valid URL rather than a doubled
21
+ // host. Falls back to DEFAULT_HTTP_PORT for a default local install.
19
22
  export function localBaseUrl(env = process.env) {
20
- return `http://127.0.0.1:${env.HTTP_PORT || DEFAULT_HTTP_PORT}`;
23
+ return `http://127.0.0.1:${harperPortValue(env.HTTP_PORT) ?? DEFAULT_HTTP_PORT}`;
21
24
  }
22
25
  // Public base URL advertised in the A2A agent card so remote peers can reach
23
26
  // this Flair. Mirrors AdminInstance.resolvePublicUrl (flair#404):
@@ -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
+ }