@tpsdev-ai/flair 0.57.0 → 0.59.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 (143) hide show
  1. package/README.md +7 -6
  2. package/SECURITY.md +4 -1
  3. package/config.yaml +3 -0
  4. package/dist/build-info.json +3 -3
  5. package/dist/cli.js +1726 -376
  6. package/dist/commands/agent.js +160 -2
  7. package/dist/commands/doctor.js +177 -27
  8. package/dist/commands/federation.js +2 -1
  9. package/dist/commands/hook.js +10 -2
  10. package/dist/commands/init.js +150 -44
  11. package/dist/commands/mcp.js +53 -22
  12. package/dist/commands/memory.js +24 -2
  13. package/dist/commands/quality.js +26 -18
  14. package/dist/commands/service.js +137 -22
  15. package/dist/commands/status.js +114 -3
  16. package/dist/commands/upgrade.js +204 -84
  17. package/dist/doctor-client.js +50 -4
  18. package/dist/federation/scheduler.js +253 -4
  19. package/dist/install/clients.js +89 -23
  20. package/dist/install/global-bin-path.js +26 -6
  21. package/dist/lib/atomic-write.js +256 -0
  22. package/dist/lib/daemon-liveness.js +103 -0
  23. package/dist/lib/doctor-run.js +72 -0
  24. package/dist/lib/embed-gpu-doctor.js +49 -26
  25. package/dist/lib/federation-memory-attributes.js +15 -0
  26. package/dist/lib/flair-agent-role.js +116 -0
  27. package/dist/lib/init-admin-pass.js +4 -2
  28. package/dist/lib/init-listener-environ.js +38 -0
  29. package/dist/lib/init-occupied-listener.js +165 -0
  30. package/dist/lib/launchd-domain-preflight.js +448 -0
  31. package/dist/lib/launchd-management.js +179 -8
  32. package/dist/lib/launchd-repair.js +95 -0
  33. package/dist/lib/mcp-enable.js +667 -72
  34. package/dist/lib/memory-attributes.js +77 -0
  35. package/dist/lib/node-alias-path.js +95 -0
  36. package/dist/lib/npm-registry.js +119 -6
  37. package/dist/lib/owned-pins.js +20 -6
  38. package/dist/lib/process-start-time.js +32 -0
  39. package/dist/lib/service-repoint-apply.js +267 -0
  40. package/dist/lib/service-repoint.js +575 -0
  41. package/dist/lib/toml-string-array.js +104 -0
  42. package/dist/lib/tree-divergence.js +716 -0
  43. package/dist/lib/upgrade-plain-tree.js +18 -8
  44. package/dist/lib/upgrade-prior-liveness.js +69 -0
  45. package/dist/lib/upgrade-rollback.js +116 -0
  46. package/dist/rem/runner.js +11 -0
  47. package/dist/resources/Agent.js +54 -21
  48. package/dist/resources/AgentSeed.js +44 -1
  49. package/dist/resources/Federation.js +84 -54
  50. package/dist/resources/Memory.js +567 -72
  51. package/dist/resources/MemoryArchive.js +9 -0
  52. package/dist/resources/MemoryBootstrap.js +125 -29
  53. package/dist/resources/MemoryFeed.js +204 -3
  54. package/dist/resources/MemoryHostSource.js +90 -0
  55. package/dist/resources/MemoryMaintenance.js +121 -32
  56. package/dist/resources/MemoryReflect.js +4 -1
  57. package/dist/resources/MemoryReindex.js +7 -4
  58. package/dist/resources/MemoryUsage.js +53 -3
  59. package/dist/resources/OrgSkillAssignment.js +209 -0
  60. package/dist/resources/Presence.js +18 -10
  61. package/dist/resources/RecordUsage.js +30 -40
  62. package/dist/resources/Relationship.js +167 -78
  63. package/dist/resources/SemanticSearch.js +19 -6
  64. package/dist/resources/Soul.js +31 -19
  65. package/dist/resources/XAA.js +47 -14
  66. package/dist/resources/agent-auth.js +16 -10
  67. package/dist/resources/agent-status-guard.js +63 -0
  68. package/dist/resources/auth-middleware.js +137 -49
  69. package/dist/resources/auto-promote-lib.js +4 -4
  70. package/dist/resources/bm25-index-service.js +246 -32
  71. package/dist/resources/bm25-status.js +132 -0
  72. package/dist/resources/ed25519-auth.js +11 -54
  73. package/dist/resources/embed-gpu.js +262 -47
  74. package/dist/resources/embeddings-boot.js +52 -17
  75. package/dist/resources/federation-classify.js +34 -0
  76. package/dist/resources/federation-crypto.js +65 -19
  77. package/dist/resources/flair-agent-role-boot.js +26 -0
  78. package/dist/resources/health.js +67 -16
  79. package/dist/resources/host-pointer/registry.js +35 -0
  80. package/dist/resources/host-pointer-adapter.js +15 -0
  81. package/dist/resources/host-source-visibility.js +167 -0
  82. package/dist/resources/host-source.js +151 -0
  83. package/dist/resources/instance-identity.js +3 -2
  84. package/dist/resources/key-lock.js +31 -0
  85. package/dist/resources/mcp-handler.js +147 -51
  86. package/dist/resources/mcp-oauth.js +3 -6
  87. package/dist/resources/mcp-tools.js +47 -25
  88. package/dist/resources/memory-consolidate-lib.js +3 -1
  89. package/dist/resources/memory-declared-attributes.js +103 -0
  90. package/dist/resources/memory-feed-lib.js +5 -1
  91. package/dist/resources/memory-host-source.js +163 -0
  92. package/dist/resources/migrations/synthetic-test-migration.js +4 -1
  93. package/dist/resources/migrations/visibility-backfill.js +4 -1
  94. package/dist/resources/multi-worker-guard.js +121 -0
  95. package/dist/resources/oauth-discovery.js +1 -0
  96. package/dist/resources/oauth-wellknown.js +8 -4
  97. package/dist/resources/originator-instance.js +235 -0
  98. package/dist/resources/promotion-stamp.js +2 -0
  99. package/dist/resources/provenance.js +111 -11
  100. package/dist/resources/record-owner-guard.js +19 -0
  101. package/dist/resources/record-type-kit.js +9 -12
  102. package/dist/resources/record-types.js +22 -6
  103. package/dist/resources/relay-ops.js +28 -3
  104. package/dist/resources/replay-store.js +336 -0
  105. package/dist/resources/request-transaction.js +78 -0
  106. package/dist/resources/search-readiness.js +19 -21
  107. package/dist/resources/semantic-retrieval-core.js +5 -1
  108. package/dist/resources/skill-manifest.js +181 -0
  109. package/dist/resources/skill-provenance.js +15 -10
  110. package/dist/resources/table-patch-policy.js +109 -0
  111. package/dist/resources/table-patches.js +17 -0
  112. package/dist/resources/table-post-policy.js +138 -0
  113. package/dist/resources/table-posts.js +22 -0
  114. package/dist/resources/table-subscription-policy.js +135 -0
  115. package/dist/resources/table-subscriptions.js +19 -0
  116. package/dist/resources/tool-descriptors/index.js +15 -15
  117. package/dist/resources/trust-block.js +10 -3
  118. package/dist/resources/usage-recording.js +169 -41
  119. package/dist/src/lib/flair-agent-role.js +116 -0
  120. package/dist/src/lib/memory-attributes.js +77 -0
  121. package/docs/access-control.md +667 -0
  122. package/docs/api-reference.md +85 -17
  123. package/docs/auth.md +4 -0
  124. package/docs/claude-code.md +132 -0
  125. package/docs/deepseek-harness.md +1 -1
  126. package/docs/deployment.md +1 -1
  127. package/docs/federation.md +1 -1
  128. package/docs/integrations.md +6 -6
  129. package/docs/mcp-clients.md +16 -24
  130. package/docs/notes/mcp-oauth-model2.md +15 -1
  131. package/docs/quickstart.md +5 -0
  132. package/docs/releasing.md +152 -20
  133. package/docs/supply-chain-policy.md +10 -5
  134. package/docs/troubleshooting.md +11 -0
  135. package/docs/upgrade.md +187 -61
  136. package/package.json +10 -5
  137. package/schemas/agent.graphql +9 -6
  138. package/schemas/federation.graphql +2 -11
  139. package/schemas/memory.graphql +137 -17
  140. package/schemas/oauth.graphql +8 -4
  141. package/schemas/replay.graphql +18 -0
  142. package/templates/launchd/start-flair-with-admin-pass.sh +95 -0
  143. package/dist/resources/federation-nonce-store.js +0 -195
@@ -86,6 +86,15 @@ export class MemoryArchive extends Resource {
86
86
  delete merged.archivedAt;
87
87
  delete merged.archivedBy;
88
88
  }
89
+ // flair#1940 A3 (item 9): the record we read was PROJECTED — for the author
90
+ // it carries the canonical pointer with the URL query/fragment STRIPPED,
91
+ // and for a non-author it may read "withheld". Writing any of that back
92
+ // would replace the stored pointer (losing the full URL) or store a bogus
93
+ // value, and would re-derive the scope. Omit every pointer field from the
94
+ // write-back so the stored pointer row, its full URL and its scope stand.
95
+ delete merged.hostSource;
96
+ delete merged.hostSourceScope;
97
+ delete merged.hostSourceVisibility;
89
98
  // Write back — Memory.put()'s ownership gate applies (stampAttribution), so
90
99
  // a non-admin caller cannot flip another agent's memory (403).
91
100
  const result = await Memory.put(merged, ctx);
@@ -5,7 +5,7 @@ import { wrapUntrusted } from "./content-safety.js";
5
5
  import { isTeammate, formatTeamLine, isZeroRowNoOpEvent } from "./memory-bootstrap-lib.js";
6
6
  import { resolveReadScope } from "./memory-read-scope.js";
7
7
  import { isValidEntity } from "./entity-vocab.js";
8
- import { withDetachedTxn } from "./table-helpers.js";
8
+ import { withDetachedTxn, withDetachedTxnAsync } from "./table-helpers.js";
9
9
  import { getPresenceRoster } from "./presence-internal.js";
10
10
  import { buildCollisionEntries, buildEntityMatchCondition, freshPresenceByAgent, } from "./collision-lib.js";
11
11
  // The bounded HNSW candidate-pool retrieval for the task-relevant/teammate/
@@ -22,7 +22,10 @@ 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
+ import { SKILL_ASSIGNMENT_KEY } from "./skill-provenance.js";
26
+ import { SKILL_TAG } from "./skill-write.js";
27
+ import { SKILL_ROW_SELECT, receivesOrgSkills, resolvableSkillRows, resolveSkillManifest, skillLine, } from "./skill-manifest.js";
28
+ import { localInstanceId } from "./instance-identity.js";
26
29
  /**
27
30
  * POST /MemoryBootstrap
28
31
  *
@@ -82,13 +85,15 @@ import { resolveActiveSkills } from "./skill-provenance.js";
82
85
  * { context, sections, tokenEstimate, maxTokens, memoriesIncluded, memoriesAvailable,
83
86
  * memoriesTruncated, teammateFindingsIncluded, teammateFindingsTruncated,
84
87
  * teammateFindingsMatched, agentId, scope, soul, memories, predicted,
85
- * teammateFindings, events, soulTokens, memoryTokens, trustTokens,
86
- * eventsTokens, scaffoldTokens[, currentTaskHint][, taskRetrievalHint][, predictedHint] }
88
+ * teammateFindings, events, skills, skillDiagnostics, skillsTruncated,
89
+ * skillDiagnosticsTruncated, soulTokens, memoryTokens, trustTokens,
90
+ * eventsTokens, skillsTokens, skillDiagnosticsTokens, scaffoldTokens
91
+ * [, currentTaskHint][, taskRetrievalHint][, predictedHint] }
87
92
  *
88
93
  * TOKEN LEDGER (flair#1270): the counters decompose `tokenEstimate` from the
89
94
  * payload alone —
90
95
  * tokenEstimate ≈ scaffoldTokens + soulTokens + memoryTokens + trustTokens
91
- * + eventsTokens
96
+ * + eventsTokens + skillsTokens + skillDiagnosticsTokens
92
97
  * Each figure is measured from what SHIPS (never derived as a residual), so
93
98
  * a section that ships uncounted content breaks the identity visibly instead
94
99
  * of hiding in an unexplained gap. See the ledger block in the response tail
@@ -263,6 +268,10 @@ const MAX_CANDIDATE_POOL = 100;
263
268
  // `m._source !== agentId` is the "is this a teammate's finding" check; own
264
269
  // memories never carry `_source` at all.
265
270
  function formatMemory(m, agentId) {
271
+ // flair#1940 A1' item 5: bootstrap does NOT render pointers in this slice.
272
+ // The pointer lives in MemoryHostSource and is joined only into Memory.get/
273
+ // search/SemanticSearch results; the bootstrap citation (A6) arrives in slice
274
+ // 4. So this surface leaves the record unchanged.
266
275
  const tag = m.durability === "permanent" ? "🔒" : m.durability === "persistent" ? "📌" : "📝";
267
276
  const date = m.createdAt ? ` (${m.createdAt.slice(0, 10)})` : "";
268
277
  const chain = m.supersedes ? " [supersedes earlier decision]" : "";
@@ -501,23 +510,28 @@ export class BootstrapMemories extends Resource {
501
510
  // Full workspace files — lowest priority (runtime already injects these)
502
511
  soul: 90, "workspace-rules": 91,
503
512
  };
513
+ // flair#2141 — `skill-assignment` rows are read whatever includeSoul says
514
+ // (the skills manifest in 1b is always present); the other soul entries
515
+ // only when includeSoul is on.
504
516
  const skillAssignments = [];
517
+ const soulEntries = [];
518
+ for await (const record of databases.flair.Soul.search()) {
519
+ if (record.agentId !== agentId)
520
+ continue;
521
+ if (record.key === SKILL_ASSIGNMENT_KEY) {
522
+ skillAssignments.push(record);
523
+ continue;
524
+ }
525
+ if (!includeSoul)
526
+ continue;
527
+ const line = `**${record.key}:** ${record.value}`;
528
+ const tokens = estimateTokens(line);
529
+ const priority = SOUL_KEY_PRIORITY[record.key] ?? 50;
530
+ soulEntries.push({ key: record.key, value: record.value, line, tokens, priority });
531
+ }
505
532
  const soulMaxTokens = Math.floor(maxTokens * 0.4); // 40% of budget for soul
506
533
  if (includeSoul) {
507
534
  let soulTokens = 0;
508
- const soulEntries = [];
509
- for await (const record of databases.flair.Soul.search()) {
510
- if (record.agentId !== agentId)
511
- continue;
512
- if (record.key === "skill-assignment") {
513
- skillAssignments.push(record);
514
- continue;
515
- }
516
- const line = `**${record.key}:** ${record.value}`;
517
- const tokens = estimateTokens(line);
518
- const priority = SOUL_KEY_PRIORITY[record.key] ?? 50;
519
- soulEntries.push({ key: record.key, value: record.value, line, tokens, priority });
520
- }
521
535
  // Sort by priority (lower = more important)
522
536
  soulEntries.sort((a, b) => a.priority - b.priority);
523
537
  // flair#1431 — collapse VERBATIM duplicates. The live payload shipped the
@@ -563,13 +577,78 @@ export class BootstrapMemories extends Resource {
563
577
  tokenBudget -= entry.tokens; // #1199 — soul draws from the shared budget
564
578
  }
565
579
  }
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.
570
- if (skillAssignments.length > 0) {
571
- const resolved = resolveActiveSkills(skillAssignments);
572
- sections.skills.push(...resolved.lines);
580
+ // The read scope (see the "Read-scope" block below), resolved here because
581
+ // the skills manifest (1b) re-checks its skill rows against it.
582
+ const scope = await resolveReadScope(agentId);
583
+ // --- 1b. Skills manifest (flair#2141 S1b and S1; conflict rules flair#1433) ---
584
+ // Present whatever includeSoul and includeContext say. resolveSkillManifest
585
+ // (resources/skill-manifest.ts) splits the agent's own and org-scope
586
+ // assignments into winners, each with the skill row `skill_get` reads,
587
+ // and diagnostics. Entries are
588
+ // admitted while they fit the shared budget, right after the soul, at
589
+ // their serialized size; an entry that does not fit is counted in
590
+ // skillsTruncated / skillDiagnosticsTruncated instead.
591
+ const includedSkills = [];
592
+ const includedSkillDiagnostics = [];
593
+ let skillsTruncated = 0;
594
+ let skillDiagnosticsTruncated = 0;
595
+ // flair#2141 S1 — when org rows exist, the target's Agent record is read on
596
+ // this call, and org assignments apply only when it says the target
597
+ // receives org skills.
598
+ const orgRows = [];
599
+ const orgQuery = withDetachedTxn(ctx, () => databases.flair.OrgSkillAssignment.search());
600
+ for await (const row of orgQuery)
601
+ orgRows.push(row);
602
+ const org = { assignments: [], rows: [], instanceId: null };
603
+ if (orgRows.length > 0
604
+ && receivesOrgSkills(await withDetachedTxnAsync(ctx, () => databases.flair.Agent.get(agentId)))) {
605
+ const refRows = [];
606
+ for (const ref of new Set(orgRows.map((row) => row.skillRef).filter((ref) => typeof ref === "string"))) {
607
+ const refQuery = withDetachedTxn(ctx, () => databases.flair.Memory.search({
608
+ conditions: [{ attribute: "id", comparator: "equals", value: ref }],
609
+ select: SKILL_ROW_SELECT,
610
+ }));
611
+ for await (const record of refQuery)
612
+ refRows.push(record);
613
+ }
614
+ org.assignments = orgRows;
615
+ org.rows = resolvableSkillRows(refRows, scope.isAllowed);
616
+ org.instanceId = await localInstanceId();
617
+ }
618
+ if (skillAssignments.length > 0 || org.assignments.length > 0) {
619
+ const skillRows = [];
620
+ if (skillAssignments.length > 0) {
621
+ const skillQuery = withDetachedTxn(ctx, () => databases.flair.Memory.search({
622
+ conditions: [
623
+ { attribute: "agentId", comparator: "equals", value: agentId },
624
+ { attribute: "tags", comparator: "equals", value: SKILL_TAG },
625
+ { attribute: "archived", comparator: "not_equal", value: true },
626
+ ],
627
+ select: SKILL_ROW_SELECT,
628
+ }));
629
+ for await (const record of skillQuery)
630
+ skillRows.push(record);
631
+ }
632
+ const manifest = resolveSkillManifest(skillAssignments, resolvableSkillRows(skillRows, scope.isAllowed), agentId, org);
633
+ for (const entry of manifest.skills) {
634
+ const cost = estimateTokens(JSON.stringify(entry));
635
+ if (cost > tokenBudget) {
636
+ skillsTruncated++;
637
+ continue;
638
+ }
639
+ includedSkills.push(entry);
640
+ sections.skills.push(skillLine(entry));
641
+ tokenBudget -= cost;
642
+ }
643
+ for (const diagnostic of manifest.diagnostics) {
644
+ const cost = estimateTokens(JSON.stringify(diagnostic));
645
+ if (cost > tokenBudget) {
646
+ skillDiagnosticsTruncated++;
647
+ continue;
648
+ }
649
+ includedSkillDiagnostics.push(diagnostic);
650
+ tokenBudget -= cost;
651
+ }
573
652
  }
574
653
  // --- 1c. Team roster + cross-agent search nudge ---
575
654
  // Soul is still caller-own-only (unaffected here). Memory loading below
@@ -630,8 +709,8 @@ export class BootstrapMemories extends Resource {
630
709
  // spans the org. Each bounded query still re-checks `scope.isAllowed()`
631
710
  // on every record even where it's provably a no-op (e.g. an
632
711
  // agentId==self-only query) — uniform defense-in-depth, never skipped
633
- // because "the filter already pushed down."
634
- const scope = await resolveReadScope(agentId);
712
+ // because "the filter already pushed down." (`scope` is resolved above,
713
+ // before the skills manifest.)
635
714
  // `memoriesAvailable`: dropped the org-wide exact count (computing it
636
715
  // exactly WAS the scan being removed — `visibility != private` isn't
637
716
  // index-seekable, so even a bare count would scan). Replaced with the
@@ -1450,7 +1529,9 @@ export class BootstrapMemories extends Resource {
1450
1529
  if (sections.soul.length > 0) {
1451
1530
  parts.push("## Identity\n" + sections.soul.join("\n"));
1452
1531
  }
1453
- if (sections.skills.length > 0) {
1532
+ // flair#2141 — rendered from the admitted `skills` entries, and only with
1533
+ // includeSoul.
1534
+ if (includeSoul && sections.skills.length > 0) {
1454
1535
  parts.push("## Active Skills\n" + sections.skills.join("\n"));
1455
1536
  }
1456
1537
  if (sections.team.length > 0) {
@@ -1509,7 +1590,8 @@ export class BootstrapMemories extends Resource {
1509
1590
  // counter doesn't prevent silent regression, per Kern's #1270 ruling):
1510
1591
  //
1511
1592
  // tokenEstimate ≈ scaffoldTokens + soulTokens + memoryTokens
1512
- // + trustTokens + eventsTokens
1593
+ // + trustTokens + eventsTokens + skillsTokens
1594
+ // + skillDiagnosticsTokens
1513
1595
  //
1514
1596
  // Every token-charged content class has a named counter, so a consumer can
1515
1597
  // decompose `tokenEstimate` FROM THE PAYLOAD ALONE and any future section
@@ -1549,6 +1631,10 @@ export class BootstrapMemories extends Resource {
1549
1631
  // events admission loop charged (#1199). Same reporting hole-class as
1550
1632
  // trust: charged content with no counter would be invisible in the ledger.
1551
1633
  const eventsTokens = includedEvents.reduce((sum, evt) => sum + estimateTokens(JSON.stringify(evt)), 0);
1634
+ // flair#2141 — the skills manifest and its diagnostics: Σ estimateTokens
1635
+ // (JSON) over the shipped entries, the same per-entry cost 1b charged.
1636
+ const skillsTokens = includedSkills.reduce((sum, entry) => sum + estimateTokens(JSON.stringify(entry)), 0);
1637
+ const skillDiagnosticsTokens = includedSkillDiagnostics.reduce((sum, entry) => sum + estimateTokens(JSON.stringify(entry)), 0);
1552
1638
  // flair#744 slice 1 — opt-in per-memory trust block. Bootstrap renders
1553
1639
  // memories as text lines rather than result objects, so the block is
1554
1640
  // surfaced as a `trust` array of self-contained entries (each carries its
@@ -1655,6 +1741,12 @@ export class BootstrapMemories extends Resource {
1655
1741
  ...(taskRetrievalHint ? { taskRetrievalHint } : {}),
1656
1742
  scope: scopeInfo,
1657
1743
  soul: soulMap,
1744
+ // flair#2141 S1b — always present (`[]` when none), whatever includeSoul
1745
+ // and includeContext say; see 1b.
1746
+ skills: includedSkills,
1747
+ skillDiagnostics: includedSkillDiagnostics,
1748
+ skillsTruncated,
1749
+ skillDiagnosticsTruncated,
1658
1750
  memories: includedOwnMemories,
1659
1751
  predicted: includedPredicted,
1660
1752
  // flair#1199 — cross-agent teammate findings as a structured container
@@ -1700,6 +1792,8 @@ export class BootstrapMemories extends Resource {
1700
1792
  // token-charged content class is decomposable from the payload alone.
1701
1793
  trustTokens,
1702
1794
  eventsTokens,
1795
+ skillsTokens,
1796
+ skillDiagnosticsTokens,
1703
1797
  // flair#1199 — the content-selection budget this response was built
1704
1798
  // against (echoed so a connector can relate tokenEstimate to the budget it
1705
1799
  // asked for — and so the conformance tokenEstimate<=maxTokens invariant is
@@ -1765,6 +1859,8 @@ export class BootstrapMemories extends Resource {
1765
1859
  ...responseBody,
1766
1860
  context: "",
1767
1861
  soul: {},
1862
+ skills: [],
1863
+ skillDiagnostics: [],
1768
1864
  memories: [],
1769
1865
  predicted: [],
1770
1866
  teammateFindings: [],
@@ -8,6 +8,11 @@ import { assertValidVisibility, assertVisibilityAllowedForDurability, PRIVATE_VI
8
8
  import { assertValidDurability } from "./memory-durability.js";
9
9
  import { enforceSkillDurability, refuseSkillWriteSource, skillScanGate } from "./skill-write.js";
10
10
  import { noteMemoryUpsert } from "./bm25-index-service.js";
11
+ import { extractPointerInputs } from "./memory-host-source.js";
12
+ import { stripUndeclaredMemoryAttributes, stripServerStampedFields } from "./memory-declared-attributes.js";
13
+ import { buildProvenance } from "./provenance.js";
14
+ import { applyFederationBookkeeping, applyOriginatorInstanceId } from "./originator-instance.js";
15
+ import { resolveReadScope } from "./memory-read-scope.js";
11
16
  export class FeedMemories extends Resource {
12
17
  // Self-authorize via the Ed25519 agent verify (the auth reshape removes the
13
18
  // gate's admin elevation).
@@ -165,19 +170,215 @@ export class FeedMemories extends Resource {
165
170
  if (record.durability === "ephemeral" && (record.visibility === undefined || record.visibility === null)) {
166
171
  record.visibility = PRIVATE_VISIBILITY;
167
172
  }
173
+ // flair#1940 A1' item 1: the feed ingest is a Memory writer too. Drop any
174
+ // pointer inputs (hostSource/hostSourceScope/hostSourceVisibility) and every
175
+ // undeclared attribute here. These paths discard the supplied pointer input
176
+ // and create no pointer row; an existing pointer row stays bound to the
177
+ // updated Memory.
178
+ extractPointerInputs(record);
179
+ stripUndeclaredMemoryAttributes(record);
168
180
  stripAuthorityFields(record, "Memory");
181
+ // A1-iv items 1/3: the feed ingest is a Memory writer too — strip a
182
+ // caller-supplied server-stamped field (instanceToken, provenance), then
183
+ // PRESERVE the existing row's incarnation token, else generate one.
184
+ stripServerStampedFields(record);
185
+ // flair#1940 A1-iv item 1: a failed existing-row lookup must FAIL the write,
186
+ // not fall back to a fresh token — rotating the token would hide a still-
187
+ // stored pointer row that is bound to the stored token (the same fail-closed
188
+ // rule #1956 applies to put()). No `.catch`: the rejection propagates.
189
+ const priorById = await databases.flair.Memory.get(record.id);
190
+ record.instanceToken = priorById?.instanceToken ?? randomUUID();
191
+ // Feed ingest is a full-row write: it REPLACES the stored row, so a
192
+ // re-ingest with new content is a semantic re-authoring. Re-stamp
193
+ // provenance from the resolved (trusted) identity and ONE server clock read
194
+ // (inside buildProvenance) rather than carrying the stored blob forward — a
195
+ // legacy row whose `verified.timestamp` came from a client `createdAt` must
196
+ // not keep presenting that value after a new write (flair#1960 r2). The feed
197
+ // body's own `createdAt` is recorded only as the CLAIM
198
+ // `provenance.claimed.createdAt`, never as a verified timestamp. The
199
+ // incarnation token is still preserved above (a re-ingest is not a
200
+ // reincarnation), so only `provenance` is re-derived.
201
+ record.provenance = buildProvenance(auth, record.createdAt, content);
202
+ // flair#1965 r2: this raw table put REPLACES the row, bypassing the Memory
203
+ // resource's write methods, so the create/update rule is applied here
204
+ // explicitly: a CREATE (no stored row) stamps this instance's own id and
205
+ // ignores any body value; an UPDATE keeps the STORED value (a body value
206
+ // neither replaces nor clears it). The receiver-side federation bookkeeping
207
+ // (`_originatorInstanceId` et al.) is likewise unsettable from a body — it
208
+ // stands as stored, or is dropped on a create. See
209
+ // resources/originator-instance.ts.
210
+ await applyOriginatorInstanceId(record, priorById);
211
+ applyFederationBookkeeping(record, priorById);
169
212
  await databases.flair.Memory.put(record);
170
213
  // flair#1357 — raw-table write: hook it explicitly (see bm25-index-service).
171
214
  noteMemoryUpsert(record);
172
215
  return record;
173
216
  }
217
+ // Subscription admission: verified agents, admins and trusted internal
218
+ // calls; anonymous HTTP is refused (the same gate as FeedSouls). Admission is
219
+ // decided here, by the caller's resolved identity, not by which Harper user
220
+ // the request carries. What a subscriber then RECEIVES is decided per record
221
+ // in connect() below.
222
+ async allowRead() {
223
+ return allowVerified(this.getContext?.());
224
+ }
225
+ /**
226
+ * A non-admin subscriber receives a Memory event only when
227
+ * `resolveReadScope(agentId).isAllowed(record)` allows the record the event
228
+ * is decided from: the predicate Memory.get()/search() use (the reader's own
229
+ * records at any visibility, plus every other agent's non-private records).
230
+ * Admin agents and trusted internal calls are unfiltered, as before. The
231
+ * request for a scoped subscription is built here from an allowlist of the
232
+ * caller's options (see SUBSCRIPTION_OPTIONS: the record id, descendants,
233
+ * and replay), and the server's `rowFilter` is set last; no caller-supplied
234
+ * filter, `rawEvents`, `select` or unknown option reaches it.
235
+ *
236
+ * Two layers decide what a non-admin subscriber receives:
237
+ *
238
+ * 1. Harper's synchronous `SubscriptionRequest.rowFilter`, set to the
239
+ * predicate. In the pinned Harper (5.2.8) the filter is evaluated on the
240
+ * full stored row for the rows replayed when the subscription opens, for
241
+ * every live change (an update is re-read from the primary store and
242
+ * delivered as a full-row `put`) and for reload re-deliveries; a history
243
+ * replay (`startTime`, `previousCount`) is evaluated on each earlier
244
+ * version of the row as it was stored. An event with no stored row (a delete tombstone, a published message,
245
+ * a raw event) is withheld from a filtered subscriber. This layer holds
246
+ * only where the host Harper honours `rowFilter`.
247
+ *
248
+ * 2. The loop below (see readableRowEvent()), which does not rely on
249
+ * `rowFilter`. It delivers only a `put` or `invalidate` event whose value
250
+ * is an object; every other event is withheld. When that object carries a
251
+ * string `agentId` and a defined `visibility`, the predicate decides from
252
+ * those two fields of the event. Otherwise the stored row is re-read by
253
+ * the event id and the predicate decides from the stored row; the event is
254
+ * withheld when it has no id, when the re-read throws, or when the re-read
255
+ * returns anything other than an object with a string `agentId`. When the
256
+ * subscription asked for `startTime` or `previousCount`, every event also
257
+ * needs the record's current stored row, re-read by id, to be readable
258
+ * (see storedRowReadable()).
259
+ */
174
260
  async *connect(target, incomingMessages) {
175
- const subscription = await databases.flair.Memory.subscribe(target);
176
- if (!incomingMessages) {
177
- return subscription;
261
+ const auth = await resolveAgentAuth(this.getContext?.());
262
+ if (auth.kind === "anonymous") {
263
+ // allowRead() refuses anonymous HTTP before connect() runs; this is the
264
+ // in-process backstop.
265
+ throw Object.assign(new Error("authentication required"), { statusCode: 401 });
178
266
  }
267
+ if (auth.kind === "internal" || auth.isAdmin) {
268
+ const subscription = await databases.flair.Memory.subscribe(target);
269
+ if (!incomingMessages) {
270
+ return subscription;
271
+ }
272
+ for await (const event of subscription) {
273
+ yield event;
274
+ }
275
+ return;
276
+ }
277
+ const scope = await resolveReadScope(auth.agentId);
278
+ // The caller's subscription request is connect()'s second argument in
279
+ // instance mode and its first when loadAsInstance is false, the same choice
280
+ // Harper's own Resource.connect() makes.
281
+ const callerRequest = this.constructor.loadAsInstance === false ? target : incomingMessages;
282
+ const request = scopedSubscriptionRequest(callerRequest, (record) => scope.isAllowed(record));
283
+ const subscription = await databases.flair.Memory.subscribe(request);
284
+ const readStored = (id) => databases.flair.Memory.get(id);
285
+ const replaysHistory = request.startTime !== undefined || request.previousCount !== undefined;
179
286
  for await (const event of subscription) {
287
+ if (!(await readableRowEvent(event, scope.isAllowed, readStored)))
288
+ continue;
289
+ if (replaysHistory && !(await storedRowReadable(event?.id, scope.isAllowed, readStored)))
290
+ continue;
180
291
  yield event;
181
292
  }
182
293
  }
183
294
  }
295
+ /**
296
+ * The options a non-admin caller's subscription request may carry into the
297
+ * table subscription, each with the type it must have. These are the options
298
+ * Harper's `Table.subscribe` reads to choose WHICH record ids it follows and
299
+ * WHAT it replays before live events: `id` (one record), `isCollection` and
300
+ * `onlyChildren` (a record's descendants), and `startTime`, `previousCount`
301
+ * and `omitCurrent` (the replay). None of them widens what the read predicate
302
+ * allows. Every other property is dropped, including any filter, `rowFilter`,
303
+ * `eventFilter`, `select`, `rawEvents`, `listener` and any unknown option.
304
+ */
305
+ const SUBSCRIPTION_OPTIONS = Object.freeze({
306
+ id: (value) => typeof value === "string" ||
307
+ (typeof value === "number" && Number.isFinite(value)) ||
308
+ (Array.isArray(value) && value.every((part) => part === null || typeof part === "string" || typeof part === "number")),
309
+ isCollection: (value) => typeof value === "boolean",
310
+ onlyChildren: (value) => typeof value === "boolean",
311
+ startTime: (value) => typeof value === "number" && Number.isFinite(value),
312
+ previousCount: (value) => typeof value === "number" && Number.isFinite(value),
313
+ omitCurrent: (value) => typeof value === "boolean",
314
+ });
315
+ /**
316
+ * Build the scoped subscription request: the allowlisted options the caller
317
+ * supplied with the expected type, then the server-owned `rowFilter`, set last.
318
+ */
319
+ function scopedSubscriptionRequest(callerRequest, rowFilter) {
320
+ const request = {};
321
+ if (callerRequest != null && typeof callerRequest === "object") {
322
+ for (const [option, hasExpectedType] of Object.entries(SUBSCRIPTION_OPTIONS)) {
323
+ const value = callerRequest[option];
324
+ if (value !== undefined && hasExpectedType(value))
325
+ request[option] = value;
326
+ }
327
+ }
328
+ request.rowFilter = rowFilter;
329
+ return request;
330
+ }
331
+ /**
332
+ * The scoped memory feed's second layer: may this event reach the reader?
333
+ *
334
+ * - Only a `put` or `invalidate` event whose value is an object is a
335
+ * candidate; every other event (a delete, a message, a `put` without an
336
+ * object value) is withheld.
337
+ * - The read predicate reads `agentId` and `visibility`. If the event's value
338
+ * carries a string `agentId` and a defined `visibility`, the predicate
339
+ * decides from those two fields.
340
+ * - Otherwise (a partial value, or a row stored without a `visibility` field)
341
+ * the stored row is re-read by the event id, and the predicate decides from
342
+ * the stored row. The event is withheld when it has no id, when the re-read
343
+ * throws, or when the re-read returns anything other than an object with a
344
+ * string `agentId`.
345
+ *
346
+ * The event itself is what is delivered; the stored row is only the input to
347
+ * the decision.
348
+ */
349
+ async function readableRowEvent(event, isAllowed, readStored) {
350
+ if (!event || (event.type !== "put" && event.type !== "invalidate"))
351
+ return false;
352
+ const row = event.value;
353
+ if (row == null || typeof row !== "object")
354
+ return false;
355
+ if (typeof row.agentId === "string" && row.visibility !== undefined)
356
+ return isAllowed(row);
357
+ return storedRowReadable(event.id, isAllowed, readStored);
358
+ }
359
+ /**
360
+ * Re-read the stored row by id and apply the read predicate to it. An absent
361
+ * id, a read that throws, or a result that is not an object with a string
362
+ * `agentId` returns false.
363
+ *
364
+ * Also used for every event of a subscription that asked for `startTime` or
365
+ * `previousCount`: Harper then replays earlier versions of a record, and each
366
+ * version carries its own `agentId` and `visibility`. Such an event reaches a
367
+ * non-admin subscriber only when the record's current stored row is readable
368
+ * too, so a record that is private or deleted now is not replayed from its
369
+ * earlier versions.
370
+ */
371
+ async function storedRowReadable(id, isAllowed, readStored) {
372
+ if (id == null)
373
+ return false;
374
+ let stored;
375
+ try {
376
+ stored = await readStored(id);
377
+ }
378
+ catch {
379
+ return false;
380
+ }
381
+ if (stored == null || typeof stored !== "object" || typeof stored.agentId !== "string")
382
+ return false;
383
+ return isAllowed(stored);
384
+ }
@@ -0,0 +1,90 @@
1
+ /**
2
+ * MemoryHostSource.ts — the resource class for the host-pointer table
3
+ * (flair#1940 slice 1 / A1' item 3). The pointer lives in its own table,
4
+ * keyed by memoryId. Supported writes store host pointers only in `MemoryHostSource`:
5
+ * a pointer reaches a non-admin reader only through the gated join. For non-admin
6
+ * `Memory.get`, `Memory.search`, and `SemanticSearch` results, the gated projection
7
+ * removes inline pointer fields and renders a pointer only from a bound
8
+ * `MemoryHostSource` row.
9
+ *
10
+ * READ — Direct resource reads permit admin agents and trusted in-process callers;
11
+ * non-admin agents cannot read this table directly. Bare `@export`
12
+ * (schemas/memory.graphql) would otherwise
13
+ * reach Harper's default allow-decision (super_user passthrough), reachable by
14
+ * the forged-loopback super_user and, once the global gate is non-rejecting, by
15
+ * a genuinely anonymous remote caller. So allowRead/get/search gate on the
16
+ * authenticated principal: internal calls and admin agents pass; a non-admin by-id
17
+ * get returns 404; search returns 403; neither reveals whether a particular
18
+ * pointer row exists. The author
19
+ * reads their own pointer only through the gated join INTO Memory results
20
+ * (resources/Memory.ts) — never from this table directly.
21
+ *
22
+ * WRITE — there are NO REST write verbs. post/put/patch and delete are refused
23
+ * for EVERY caller (admin included), with a message naming the Memory write
24
+ * path (A1'' item 3) — proved over real HTTP for non-admin AND admin (r4-http).
25
+ * Application pointer writes use `Memory.post` or `Memory.put`; trusted operator
26
+ * table operations remain available. A superuser Harper operation against the
27
+ * table (an operator export, backup
28
+ * or reseed) is the operator path, not gated by this resource.
29
+ */
30
+ import { databases } from "harper";
31
+ import { resolveAgentAuth } from "./agent-auth.js";
32
+ import { resolveAuthGate, FORBIDDEN, UNAUTH, NOT_FOUND } from "./record-type-kit.js";
33
+ /** The admin-only read gate: internal calls and admin agents pass; every
34
+ * non-admin agent is denied. Wired as a genuine prototype method. */
35
+ async function adminOnlyReadGate() {
36
+ const auth = await resolveAgentAuth(this.getContext?.());
37
+ return auth.kind === "internal" || (auth.kind === "agent" && auth.isAdmin);
38
+ }
39
+ export class MemoryHostSource extends databases.flair.MemoryHostSource {
40
+ allowRead() {
41
+ return adminOnlyReadGate.call(this);
42
+ }
43
+ /** A by-id read: admin/internal pass; a non-admin agent gets NOT_FOUND
44
+ * (never a 403 existence oracle for "does this memory have a pointer"). */
45
+ async get(target) {
46
+ if (!target || (typeof target === "object" && target.isCollection)) {
47
+ return this.search(target);
48
+ }
49
+ const gate = await resolveAuthGate(this.getContext?.(), UNAUTH());
50
+ if (gate.kind === "denied")
51
+ return gate.response;
52
+ if (gate.kind === "unfiltered")
53
+ return super.get(target);
54
+ return NOT_FOUND();
55
+ }
56
+ /** A collection read/search: admin/internal pass; a non-admin agent is
57
+ * refused (403). */
58
+ async search(query) {
59
+ const gate = await resolveAuthGate(this.getContext?.(), UNAUTH());
60
+ if (gate.kind === "denied")
61
+ return gate.response;
62
+ if (gate.kind === "unfiltered")
63
+ return super.search(query);
64
+ return FORBIDDEN("forbidden: MemoryHostSource is admin-only");
65
+ }
66
+ /**
67
+ * A1'' item 3 — MemoryHostSource has NO REST write verbs. A pointer row is
68
+ * written ONLY by Memory's own write path (POST/PUT /Memory), through the
69
+ * table object, inside the same request transaction. Every caller is refused
70
+ * here — admin included — with the same message naming that path, so no REST
71
+ * caller can plant a pointer on another agent's memory (which is what item 3
72
+ * replaces: the old resource-side stamp had no business existing).
73
+ */
74
+ async post(_content) {
75
+ return writelessRefusal();
76
+ }
77
+ async put(_content) {
78
+ return writelessRefusal();
79
+ }
80
+ async patch(_content, _query) {
81
+ return writelessRefusal();
82
+ }
83
+ async delete(_id) {
84
+ return writelessRefusal();
85
+ }
86
+ }
87
+ /** The fixed refusal every REST write verb on MemoryHostSource returns. */
88
+ function writelessRefusal() {
89
+ return FORBIDDEN("MemoryHostSource REST writes are disabled; use POST/PUT `/Memory` for application pointer writes");
90
+ }