@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
@@ -12,7 +12,7 @@ import { invalidEntitiesResponse } from "./entity-vocab.js";
12
12
  import { checkRateLimit, rateLimitResponse } from "./rate-limiter.js";
13
13
  import { assertValidVisibility, assertVisibilityAllowedForDurability } from "./memory-visibility.js";
14
14
  import { assertValidDurability } from "./memory-durability.js";
15
- import { enforceSkillDurability, rejectSkillWritePath, skillEmbedText, skillScanGate } from "./skill-write.js";
15
+ import { enforceSkillDurability, rejectSkillWritePath, refuseSkillWriteSource, skillEmbedText, skillScanGate } from "./skill-write.js";
16
16
  import { DEDUP_COSINE_THRESHOLD_DEFAULT, DEDUP_LEXICAL_THRESHOLD_DEFAULT, DEDUP_MIN_CONTENT_LENGTH, computeMatchConfidence, cosineSimilarity, isConservativeMatch, } from "./dedup.js";
17
17
  import { buildProvenance, makeAuthGate, makeReadScope, makeByIdReadGate, makeScopedSearch, resolveAuthGate, stampAttribution, FORBIDDEN, UNAUTH, } from "./record-type-kit.js";
18
18
  import { RECORD_TYPES } from "./record-types.js";
@@ -20,6 +20,7 @@ import { attachTrust } from "./trust-block.js";
20
20
  import { recordCitations } from "./usage-recording.js";
21
21
  import { noteMemoryUpsert, noteMemoryDelete } from "./bm25-index-service.js";
22
22
  import { applyHitStats, clearHitStats, overlayHitStatsResult } from "./hit-tracking.js";
23
+ import { refuseStaleClientWrite, stripClientVersionPassthrough } from "./client-version-gate.js";
23
24
  /**
24
25
  * flair#744 slice 1 — read the opt-in `includeTrust` flag for a by-id get.
25
26
  * Two entry shapes: an in-process caller (resources/mcp-tools.ts's memory_get)
@@ -626,6 +627,16 @@ export class Memory extends databases.flair.Memory {
626
627
  if (auth.kind === "anonymous") {
627
628
  return UNAUTH();
628
629
  }
630
+ // flair#1383: an identified pre-0.18.0 flair-client silently drops
631
+ // writes client-side (including against another agent's shared
632
+ // memories). Refuse the write path loudly; missing version is not
633
+ // treated as old (current published clients do not send one yet).
634
+ {
635
+ const stale = refuseStaleClientWrite(ctx?.request, content);
636
+ if (stale)
637
+ return stale;
638
+ }
639
+ stripClientVersionPassthrough(content);
629
640
  // No-forge attribution — mode/field drawn from RECORD_TYPES.Memory
630
641
  // (record-types slice 2, flair#520) rather than a hand-typed literal.
631
642
  // "validate-truthy" (see record-type-kit.ts's stampAttribution doc):
@@ -792,6 +803,11 @@ export class Memory extends databases.flair.Memory {
792
803
  if (skillScanDenial)
793
804
  return skillScanDenial;
794
805
  }
806
+ {
807
+ const skillSourceDenial = refuseSkillWriteSource(content);
808
+ if (skillSourceDenial)
809
+ return skillSourceDenial;
810
+ }
795
811
  // Server-side conservative-duplicate gate (memory-integrity fix). A
796
812
  // supersede write is an intentional version-link, not an ambiguous "is
797
813
  // this a duplicate of something else" situation — bypass the gate for it
@@ -875,6 +891,13 @@ export class Memory extends databases.flair.Memory {
875
891
  const authorityDenial = await guardAuthorityFields(() => super.get(), content, "Memory");
876
892
  if (authorityDenial)
877
893
  return authorityDenial;
894
+ // flair#1383 — patch() routes past put(), so it needs its own refuse.
895
+ {
896
+ const stale = refuseStaleClientWrite(this.getContext?.()?.request, content);
897
+ if (stale)
898
+ return stale;
899
+ }
900
+ stripClientVersionPassthrough(content);
878
901
  const denial = await guardOwnerFieldImmutable(this, () => super.get(), content, "agentId");
879
902
  if (denial)
880
903
  return denial;
@@ -939,6 +962,13 @@ export class Memory extends databases.flair.Memory {
939
962
  if (auth.kind === "anonymous") {
940
963
  return UNAUTH();
941
964
  }
965
+ // flair#1383 — same write-path refuse as post().
966
+ {
967
+ const stale = refuseStaleClientWrite(ctx?.request, content);
968
+ if (stale)
969
+ return stale;
970
+ }
971
+ stripClientVersionPassthrough(content);
942
972
  // No-forge attribution — mode/field drawn from RECORD_TYPES.Memory,
943
973
  // same rule as post(). "validate-truthy" (see record-type-kit.ts's
944
974
  // stampAttribution doc).
@@ -1098,6 +1128,11 @@ export class Memory extends databases.flair.Memory {
1098
1128
  if (skillScanDenial)
1099
1129
  return skillScanDenial;
1100
1130
  }
1131
+ {
1132
+ const skillSourceDenial = refuseSkillWriteSource(content);
1133
+ if (skillSourceDenial)
1134
+ return skillSourceDenial;
1135
+ }
1101
1136
  // Server-side conservative-duplicate gate (memory-integrity fix). PUT is
1102
1137
  // an upsert: only run the gate for a FRESH create (target id does not yet
1103
1138
  // exist) that is NOT a supersede-link write. An update of an EXISTING id
@@ -22,6 +22,7 @@ import { estimateTokens } from "./token-estimate.js";
22
22
  import { initialPosition, ORG_EVENT_STREAM } from "./agent-read-position-lib.js";
23
23
  import { defaultReadPositionTable, ensureReadPosition } from "./agent-read-position.js";
24
24
  import { catchupSeekTimestamp, isCatchupEligible } from "./org-event-catchup-lib.js";
25
+ import { resolveActiveSkills } from "./skill-provenance.js";
25
26
  /**
26
27
  * POST /MemoryBootstrap
27
28
  *
@@ -519,12 +520,27 @@ export class BootstrapMemories extends Resource {
519
520
  }
520
521
  // Sort by priority (lower = more important)
521
522
  soulEntries.sort((a, b) => a.priority - b.priority);
523
+ // flair#1431 — collapse VERBATIM duplicates. The live payload shipped the
524
+ // same IDENTITY.md body three times (`identity`, a second `identity`, and
525
+ // `identity-file`) and `user-context` twice: different soul keys holding
526
+ // byte-identical content. Dedupe by content (not by key) so the
527
+ // higher-priority key wins and the budget is not spent re-saying the same
528
+ // thing. (Roster/template-text cleanup is separate.)
529
+ const seenSoulValues = new Set();
530
+ const admittedSoulEntries = [];
531
+ for (const entry of soulEntries) {
532
+ const valueKey = JSON.stringify(entry.value ?? null);
533
+ if (seenSoulValues.has(valueKey))
534
+ continue;
535
+ seenSoulValues.add(valueKey);
536
+ admittedSoulEntries.push(entry);
537
+ }
522
538
  // flair#1371 — the structured `soul` map follows the admission decision.
523
539
  // Filling it during the scan (flair#1182) shipped every key even when
524
540
  // this loop dropped the entry, so sections.soul / soulTokens / the
525
541
  // context pointer described N while `soul` delivered N+1 (delivered
526
542
  // but not counted or charged — the #1206 mirror).
527
- for (const entry of soulEntries) {
543
+ for (const entry of admittedSoulEntries) {
528
544
  if (soulTokens + entry.tokens > soulMaxTokens) {
529
545
  // Skip large entries that exceed budget — truncate or skip
530
546
  if (entry.priority >= 90)
@@ -547,38 +563,13 @@ export class BootstrapMemories extends Resource {
547
563
  tokenBudget -= entry.tokens; // #1199 — soul draws from the shared budget
548
564
  }
549
565
  }
550
- // --- 1b. Skill assignments (ordered by priority, conflict detection) ---
566
+ // --- 1b. Skill assignments (durable source + stated conflict outcome) ---
567
+ // flair#1433: do not report-and-load-both. resolveActiveSkills decides
568
+ // (unique priority wins; equal-priority same-name tie refuses) and
569
+ // states the decision on the line. Non-durable sources are refused.
551
570
  if (skillAssignments.length > 0) {
552
- const priorityOrder = { critical: 0, high: 1, standard: 2, low: 3 };
553
- skillAssignments.sort((a, b) => {
554
- const pa = priorityOrder[a.priority ?? "standard"] ?? 2;
555
- const pb = priorityOrder[b.priority ?? "standard"] ?? 2;
556
- return pa - pb;
557
- });
558
- // Detect conflicts at same priority level
559
- const byPriority = new Map();
560
- for (const skill of skillAssignments) {
561
- const p = skill.priority ?? "standard";
562
- if (!byPriority.has(p))
563
- byPriority.set(p, []);
564
- byPriority.get(p).push(skill);
565
- }
566
- for (const skill of skillAssignments) {
567
- const p = skill.priority ?? "standard";
568
- let meta = {};
569
- try {
570
- meta = typeof skill.metadata === "string" ? JSON.parse(skill.metadata) : (skill.metadata ?? {});
571
- }
572
- catch { }
573
- const source = meta.source ? `, source: ${meta.source}` : "";
574
- let line = `- ${skill.value} (${p} priority${source})`;
575
- // Flag conflicts at same priority level
576
- const peers = byPriority.get(p) ?? [];
577
- if (peers.length > 1) {
578
- line += " [SKILL_CONFLICT]";
579
- }
580
- sections.skills.push(line);
581
- }
571
+ const resolved = resolveActiveSkills(skillAssignments);
572
+ sections.skills.push(...resolved.lines);
582
573
  }
583
574
  // --- 1c. Team roster + cross-agent search nudge ---
584
575
  // Soul is still caller-own-only (unaffected here). Memory loading below
@@ -5,7 +5,7 @@ import { FORBIDDEN, UNAUTH, stampAttribution } from "./record-type-kit.js";
5
5
  import { guardAuthorityFields, stripAuthorityFields } from "./authority-field-guard.js";
6
6
  import { assertValidVisibility, assertVisibilityAllowedForDurability, PRIVATE_VISIBILITY } from "./memory-visibility.js";
7
7
  import { assertValidDurability } from "./memory-durability.js";
8
- import { enforceSkillDurability, skillScanGate } from "./skill-write.js";
8
+ import { enforceSkillDurability, refuseSkillWriteSource, skillScanGate } from "./skill-write.js";
9
9
  import { noteMemoryUpsert } from "./bm25-index-service.js";
10
10
  export class FeedMemories extends Resource {
11
11
  // Self-authorize via the Ed25519 agent verify (the auth reshape removes the
@@ -68,6 +68,9 @@ export class FeedMemories extends Resource {
68
68
  const skillScanDenial = skillScanGate(content);
69
69
  if (skillScanDenial)
70
70
  return skillScanDenial;
71
+ const skillSourceDenial = refuseSkillWriteSource(content);
72
+ if (skillSourceDenial)
73
+ return skillSourceDenial;
71
74
  const skillDurabilityDenial = enforceSkillDurability(content);
72
75
  if (skillDurabilityDenial)
73
76
  return skillDurabilityDenial;
@@ -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):