@tpsdev-ai/flair 0.62.0 → 0.63.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 (232) hide show
  1. package/README.md +6 -6
  2. package/SECURITY.md +18 -10
  3. package/config.yaml +11 -11
  4. package/dist/bridges/runtime/execute.js +1 -0
  5. package/dist/bridges/types.js +1 -0
  6. package/dist/build-info.json +3 -3
  7. package/dist/cli.js +66 -122
  8. package/dist/commands/agent.js +27 -65
  9. package/dist/commands/backup-approval.js +218 -0
  10. package/dist/commands/backup.js +37 -33
  11. package/dist/commands/bootstrap.js +3 -1
  12. package/dist/commands/deploy.js +37 -7
  13. package/dist/commands/doctor.js +119 -0
  14. package/dist/commands/export.js +3 -4
  15. package/dist/commands/federation.js +653 -68
  16. package/dist/commands/grant.js +5 -6
  17. package/dist/commands/help.js +25 -0
  18. package/dist/commands/idp.js +14 -19
  19. package/dist/commands/import.js +131 -19
  20. package/dist/commands/init.js +7 -7
  21. package/dist/commands/integrity.js +5 -6
  22. package/dist/commands/mcp.js +11 -17
  23. package/dist/commands/memory.js +33 -15
  24. package/dist/commands/orgevent.js +5 -10
  25. package/dist/commands/principal.js +13 -25
  26. package/dist/commands/quality.js +3 -0
  27. package/dist/commands/rem.js +484 -65
  28. package/dist/commands/restore.js +352 -44
  29. package/dist/commands/service.js +84 -2
  30. package/dist/commands/soul.js +0 -6
  31. package/dist/commands/status.js +51 -33
  32. package/dist/commands/test.js +4 -1
  33. package/dist/commands/upgrade.js +53 -22
  34. package/dist/commands/workspace.js +7 -8
  35. package/dist/deploy.js +59 -3
  36. package/dist/doctor-client.js +7 -2
  37. package/dist/fabric-upgrade.js +12 -2
  38. package/dist/federation/presence-send.js +139 -0
  39. package/dist/federation-verify.js +269 -177
  40. package/dist/install/clients.js +171 -35
  41. package/dist/lib/agent-id-rule.js +44 -2
  42. package/dist/lib/atomic-write.js +1 -1
  43. package/dist/lib/auth-resolve.js +1028 -52
  44. package/dist/lib/backup-approval-store.js +612 -0
  45. package/dist/lib/backup-artifact.js +343 -0
  46. package/dist/lib/config-critical-section.js +212 -25
  47. package/dist/lib/connect-phase.js +33 -0
  48. package/dist/lib/daemon-liveness.js +2 -1
  49. package/dist/lib/federation-pair-access.js +4 -0
  50. package/dist/lib/federation-retry-queue.js +283 -0
  51. package/dist/lib/federation-retry-row.js +101 -0
  52. package/dist/lib/instruction-event-contract.js +17 -0
  53. package/dist/lib/instruction-event-doctor.js +102 -0
  54. package/dist/lib/launchd-management.js +14 -3
  55. package/dist/lib/mcp-enable.js +14 -15
  56. package/dist/lib/memory-attributes.js +2 -0
  57. package/dist/lib/memory-provider-timeout.js +33 -0
  58. package/dist/lib/mqtt-config.js +132 -0
  59. package/dist/lib/mqtt-listener-doctor.js +104 -0
  60. package/dist/lib/open-live-row.js +20 -0
  61. package/dist/lib/ops-url.js +52 -0
  62. package/dist/lib/promotion-content-hash.js +20 -0
  63. package/dist/lib/restore-archive.js +760 -0
  64. package/dist/lib/restore-verify.js +1 -1
  65. package/dist/lib/skill-assignment-preflight.js +159 -0
  66. package/dist/lib/skill-seed.js +91 -8
  67. package/dist/lib/skill-tombstone-doctor.js +133 -0
  68. package/dist/lib/soul-scope-fields.js +26 -0
  69. package/dist/lib/uninstall-purge.js +266 -11
  70. package/dist/lib/upgrade-prior-liveness.js +2 -1
  71. package/dist/mcp-client-assertion.js +2 -10
  72. package/dist/memory-id-checkpoint.js +28 -7
  73. package/dist/mqtt-off-deploy.js +550 -0
  74. package/dist/rem/promote-policy.js +3 -3
  75. package/dist/rem/restore.js +302 -26
  76. package/dist/rem/runner.js +220 -58
  77. package/dist/rem/scheduler.js +21 -4
  78. package/dist/resources/A2AAdapter.js +131 -178
  79. package/dist/resources/AdminMemory.js +2 -0
  80. package/dist/resources/AdminMemoryCandidates.js +116 -0
  81. package/dist/resources/Agent.js +155 -45
  82. package/dist/resources/AgentCard.js +4 -0
  83. package/dist/resources/AgentKeyRegister.js +56 -22
  84. package/dist/resources/AgentReadPosition.js +7 -0
  85. package/dist/resources/AgentSeed.js +232 -107
  86. package/dist/resources/AutoPromoteCandidates.js +413 -84
  87. package/dist/resources/Credential.js +6 -8
  88. package/dist/resources/Federation.js +219 -57
  89. package/dist/resources/FederationRetry.js +4 -4
  90. package/dist/resources/InstructionVersion.js +1 -1
  91. package/dist/resources/MCPClientMetadata.js +6 -3
  92. package/dist/resources/Memory.js +1303 -270
  93. package/dist/resources/MemoryArchive.js +149 -64
  94. package/dist/resources/MemoryBootstrap.js +12 -22
  95. package/dist/resources/MemoryCandidate.js +16 -2
  96. package/dist/resources/MemoryConsolidate.js +2 -2
  97. package/dist/resources/MemoryFeed.js +360 -147
  98. package/dist/resources/MemoryMaintenance.js +290 -72
  99. package/dist/resources/MemoryPurge.js +138 -22
  100. package/dist/resources/MemoryReflect.js +68 -14
  101. package/dist/resources/MemoryReindex.js +91 -13
  102. package/dist/resources/Message.js +11 -2
  103. package/dist/resources/OAuth.js +156 -39
  104. package/dist/resources/OAuthClient.js +1 -1
  105. package/dist/resources/OrgEvent.js +292 -29
  106. package/dist/resources/OrgEventCatchup.js +7 -0
  107. package/dist/resources/OrgEventMaintenance.js +48 -10
  108. package/dist/resources/PairingToken.js +1 -1
  109. package/dist/resources/Presence.js +31 -11
  110. package/dist/resources/PromoteMemoryCandidate.js +8 -2
  111. package/dist/resources/RecordUsage.js +2 -4
  112. package/dist/resources/Soul.js +2 -0
  113. package/dist/resources/SoulFeed.js +2 -1
  114. package/dist/resources/WorkspaceLatest.js +4 -0
  115. package/dist/resources/XAA.js +36 -10
  116. package/dist/resources/a2a-stream.js +313 -0
  117. package/dist/resources/a2a-url.js +4 -5
  118. package/dist/resources/agent-admin.js +10 -1
  119. package/dist/resources/agent-auth.js +98 -68
  120. package/dist/resources/agent-read-position-lib.js +4 -1
  121. package/dist/resources/agent-status-guard.js +9 -7
  122. package/dist/resources/auth-middleware.js +166 -42
  123. package/dist/resources/authority-field-guard.js +9 -11
  124. package/dist/resources/auto-promote-lib.js +8 -5
  125. package/dist/resources/basic-auth-header.js +21 -0
  126. package/dist/resources/bm25-index-service.js +4 -5
  127. package/dist/resources/dedup-cluster.js +6 -1
  128. package/dist/resources/embeddings-provider.js +25 -0
  129. package/dist/resources/federation-classify.js +89 -0
  130. package/dist/resources/federation-retry-lib.js +6 -81
  131. package/dist/resources/health.js +43 -4
  132. package/dist/resources/host-pointer/registry.js +29 -0
  133. package/dist/resources/host-pointer-adapter.js +1 -0
  134. package/dist/resources/in-process.js +24 -22
  135. package/dist/resources/instruction-version-record.js +251 -7
  136. package/dist/resources/internal-authority.js +13 -0
  137. package/dist/resources/mcp-handler.js +106 -12
  138. package/dist/resources/mcp-oauth-flag.js +12 -14
  139. package/dist/resources/mcp-oauth.js +430 -53
  140. package/dist/resources/mcp-tools.js +60 -22
  141. package/dist/resources/memory-declared-attributes.js +1 -0
  142. package/dist/resources/memory-embed-hash.js +56 -0
  143. package/dist/resources/memory-host-source.js +5 -2
  144. package/dist/resources/memory-reflect-lib.js +1 -1
  145. package/dist/resources/memory-write-lock.js +202 -23
  146. package/dist/resources/memory-write-response.js +1 -1
  147. package/dist/resources/memory-write-transaction.js +243 -0
  148. package/dist/resources/migration-boot.js +17 -12
  149. package/dist/resources/migrations/boot-progress.js +25 -0
  150. package/dist/resources/migrations/data-dir.js +16 -3
  151. package/dist/resources/migrations/dir-safety.js +60 -2
  152. package/dist/resources/migrations/embedding-stamp.js +315 -49
  153. package/dist/resources/migrations/graph-heal.js +9 -2
  154. package/dist/resources/migrations/ledger.js +5 -2
  155. package/dist/resources/migrations/lock.js +867 -80
  156. package/dist/resources/migrations/progress.js +71 -10
  157. package/dist/resources/migrations/runner.js +212 -18
  158. package/dist/resources/migrations/state.js +36 -1
  159. package/dist/resources/migrations/status.js +2 -13
  160. package/dist/resources/migrations/synthetic-test-migration.js +78 -12
  161. package/dist/resources/migrations/types.js +26 -1
  162. package/dist/resources/migrations/visibility-backfill.js +111 -70
  163. package/dist/resources/oauth-discovery.js +0 -5
  164. package/dist/resources/object-body-guard.js +12 -5
  165. package/dist/resources/org-event-reserved.js +92 -0
  166. package/dist/resources/org-event-write-fault.js +19 -0
  167. package/dist/resources/owner-field-guard.js +1 -1
  168. package/dist/resources/owner-scoped-write-policy.js +65 -21
  169. package/dist/resources/owner-scoped-writes.js +37 -6
  170. package/dist/resources/path-id-rewrite.js +76 -0
  171. package/dist/resources/presence-internal.js +5 -5
  172. package/dist/resources/promotion-binding.js +43 -0
  173. package/dist/resources/promotion-stamp.js +124 -33
  174. package/dist/resources/protocol-context.js +189 -0
  175. package/dist/resources/record-type-kit.js +2 -4
  176. package/dist/resources/request-target.js +28 -1
  177. package/dist/resources/request-transaction.js +11 -1
  178. package/dist/resources/seed-reservation.js +1 -2
  179. package/dist/resources/semantic-retrieval-core.js +7 -6
  180. package/dist/resources/server-row-validation.js +71 -0
  181. package/dist/resources/skill-manifest.js +4 -3
  182. package/dist/resources/skill-version-write.js +384 -27
  183. package/dist/resources/skill-write-fault.js +6 -3
  184. package/dist/resources/skill-write-policy.js +2 -1
  185. package/dist/resources/soul-write-policy.js +26 -7
  186. package/dist/resources/table-helpers.js +1 -1
  187. package/dist/resources/table-subscription-policy.js +518 -85
  188. package/dist/resources/table-subscriptions.js +20 -7
  189. package/dist/resources/txn-pause-point.js +122 -5
  190. package/dist/resources/usage-recording.js +54 -46
  191. package/dist/resources/write-back.js +176 -11
  192. package/dist/resources/write-journal-context.js +5 -0
  193. package/dist/resources/write-journal.js +289 -0
  194. package/dist/src/lib/agent-id-rule.js +44 -2
  195. package/dist/src/lib/atomic-write.js +1 -1
  196. package/dist/src/lib/federation-retry-row.js +101 -0
  197. package/dist/src/lib/instruction-event-contract.js +17 -0
  198. package/dist/src/lib/memory-attributes.js +2 -0
  199. package/dist/src/lib/open-live-row.js +20 -0
  200. package/dist/src/lib/soul-scope-fields.js +26 -0
  201. package/dist/src/rem/promote-policy.js +3 -3
  202. package/dist/src/rem/scheduler.js +21 -4
  203. package/docs/access-control.md +18 -9
  204. package/docs/api-reference.md +126 -28
  205. package/docs/auth.md +40 -18
  206. package/docs/claude-code.md +3 -3
  207. package/docs/deploying-on-fabric.md +108 -0
  208. package/docs/deployment.md +17 -0
  209. package/docs/embedding-in-a-harper-app.md +16 -14
  210. package/docs/entity-vocabulary.md +3 -6
  211. package/docs/federation.md +29 -2
  212. package/docs/integrations.md +11 -11
  213. package/docs/mcp-clients.md +7 -5
  214. package/docs/notes/mcp-agent-auth-consumer.md +4 -9
  215. package/docs/notes/mcp-oauth-model2.md +6 -6
  216. package/docs/openclaw.md +1 -1
  217. package/docs/quickstart-fabric.md +2 -2
  218. package/docs/quickstart.md +3 -3
  219. package/docs/releasing.md +13 -13
  220. package/docs/rem.md +24 -3
  221. package/docs/secrets-and-keys.md +2 -2
  222. package/docs/standalone-local.md +29 -2
  223. package/docs/supply-chain-policy.md +28 -20
  224. package/docs/the-team.md +2 -2
  225. package/docs/upgrade.md +14 -0
  226. package/package.json +18 -11
  227. package/schemas/agent.graphql +3 -3
  228. package/schemas/federation.graphql +10 -7
  229. package/schemas/memory.graphql +7 -2
  230. package/templates/bin/flair-rem-nightly.sh.tmpl +7 -1
  231. package/templates/launchd/start-flair-with-admin-pass.sh +188 -10
  232. package/dist/resources/soul-adk-guard.js +0 -68
@@ -1,23 +1,24 @@
1
1
  /** Workflow verdicts can only be stamped by their trusted raw-table paths.
2
2
  * Keep unchanged echoes compatible with full-row clients, and preserve omitted
3
- * stamps on PUT; omission must not erase a verdict. A content change drops the
4
- * stamp: the verdict is bound to the reviewed text. No admin/body bypass. */
3
+ * stamps on PUT; omission must not erase a verdict. A Memory content change
4
+ * drops Memory's stamps; other tables keep theirs. No admin/body bypass. */
5
5
  export const AUTHORITY_FIELDS = {
6
- Memory: ["promotionStatus", "promotedAt", "promotedBy"],
6
+ Memory: ["promotionStatus", "promotedAt", "promotedBy", "promotionContentHash", "writeBackWriteId"],
7
+ MemoryCandidate: ["promotedRowId", "promotedRowInstanceToken"],
7
8
  };
8
9
  export async function guardAuthorityFields(getExisting, content, table) {
9
10
  const existing = await getExisting();
10
11
  for (const field of AUTHORITY_FIELDS[table]) {
11
12
  if (Object.hasOwn(content, field) && content[field] !== existing?.[field]) {
12
- return new Response(JSON.stringify({ error: `forbidden: ${field} is set by the promotion workflow` }), {
13
+ return new Response(JSON.stringify({ error: `forbidden: ${field} is set by ${field === "writeBackWriteId" ? "write-back" : "the promotion workflow"}` }), {
13
14
  status: 403, headers: { "content-type": "application/json" },
14
15
  });
15
16
  }
16
17
  }
17
- // The stamp means this specific content was reviewed. Echo-tolerance and
18
- // omitted-field restore apply only when the body does not change `content`.
19
- // Null the columns (do not merely delete) so PATCH and PUT both drop them.
20
- if (existing && Object.hasOwn(content, "content") && content.content !== existing.content) {
18
+ // Memory's verdict and content binding attest to its content, so a Memory
19
+ // content change drops them. Null the columns (do not merely delete) so PATCH
20
+ // and PUT both drop them. Other tables' fields are preserved below.
21
+ if (table === "Memory" && existing && Object.hasOwn(content, "content") && content.content !== existing.content) {
21
22
  for (const field of AUTHORITY_FIELDS[table])
22
23
  content[field] = null;
23
24
  return null;
@@ -28,9 +29,6 @@ export async function guardAuthorityFields(getExisting, content, table) {
28
29
  }
29
30
  return null;
30
31
  }
31
- /** Drop workflow stamps from a request-origin raw write. Unconditional: even
32
- * stamps the guard would restore onto an omitted-field update must not land
33
- * through ingest paths that are not a promotion-stamp site. */
34
32
  export function stripAuthorityFields(record, table) {
35
33
  for (const field of AUTHORITY_FIELDS[table])
36
34
  delete record[field];
@@ -69,7 +69,10 @@ export const AUTO_PROMOTE_RATIONALE = "auto-promoted from ADK session distillati
69
69
  * runs once per nightly cycle, not on every write, and each promotion is a
70
70
  * bounded DB write (plus at most one embedding compute on the Memory.put path),
71
71
  * so this caps the blast radius of a single cycle rather than throttling a hot
72
- * path. Overflow stays `pending` and is swept on subsequent cycles.
72
+ * path. AutoPromoteCandidates counts every eligible candidate it attempts a
73
+ * Memory write for, whatever the outcome (a rejected or thrown attempt
74
+ * included), plus those it takes a recorded row for (flair#2714). Overflow
75
+ * stays `pending` and is swept on subsequent cycles.
73
76
  */
74
77
  export const DEFAULT_MAX_AUTO_PROMOTE_PER_CYCLE = 200;
75
78
  // ─── Structural-truncation signal (flair#1756 slice 2) ───────────────────────
@@ -77,10 +80,10 @@ export const DEFAULT_MAX_AUTO_PROMOTE_PER_CYCLE = 200;
77
80
  // src/rem/promote-policy.ts. This gate imports structuralImbalance from it; the
78
81
  // CLI flag path (src/commands/rem.ts) uses hasTerminalPunctuation from the same
79
82
  // module. A server file importing a PURE helper from src/ is established practice
80
- // in this repo (resources/PromoteMemoryCandidate.ts and resources/soul-adk-guard.ts
81
- // both import that module); what does not survive npm packaging is a CLI file
82
- // importing FROM resources/. One definition lets the CLI and this gate share a
83
- // single implementation rather than a hand-kept pair.
83
+ // in this repo (resources/PromoteMemoryCandidate.ts imports that module); what
84
+ // does not survive npm packaging is a CLI file importing FROM resources/. One
85
+ // definition lets the CLI and this gate share a single implementation rather
86
+ // than a hand-kept pair.
84
87
  //
85
88
  // Slice 1 handled a generation the backend LABELLED incomplete (finishReason
86
89
  // `length` / `content_filter`). This handles the other case: a claim reaches
@@ -0,0 +1,21 @@
1
+ /**
2
+ * The Basic `Authorization` header check the auth middleware uses
3
+ * (flair#2764), in one place so the CLI's copy in src/lib/auth-resolve.ts can
4
+ * be tested against it. It is a prefix test only: `Basic` in any case (scheme
5
+ * names are case-insensitive, RFC 9110) followed by a space. Nothing after
6
+ * that space is validated: parseBasicAuthHeader decodes all of it with
7
+ * `Buffer.from(..., "base64")`, which does not reject characters outside the
8
+ * base64 alphabet, so further spaces or any other text pass the check.
9
+ */
10
+ export const BASIC_AUTH_HEADER_RE = /^Basic /i;
11
+ /** The user and password a Basic header carries, or null for any other header. */
12
+ export function parseBasicAuthHeader(header) {
13
+ if (!BASIC_AUTH_HEADER_RE.test(header))
14
+ return null;
15
+ const decoded = Buffer.from(header.slice(6), "base64").toString("utf-8");
16
+ const colonIdx = decoded.indexOf(":");
17
+ return {
18
+ user: colonIdx >= 0 ? decoded.slice(0, colonIdx) : decoded,
19
+ pass: colonIdx >= 0 ? decoded.slice(colonIdx + 1) : "",
20
+ };
21
+ }
@@ -53,10 +53,8 @@
53
53
  //
54
54
  // 2. SYNCHRONOUS HOOKS at flair's own write surface (`noteMemoryUpsert` /
55
55
  // `noteMemoryDelete`) give READ-YOUR-WRITE after owned transactions commit.
56
- // A request-owned Memory delete cannot use this hook before its request
57
- // commits, so it reaches the index through the committed feed. The feed is
58
- // asynchronous; other hooked writes avoid that delay. Both mechanisms are
59
- // idempotent by id, so seeing a committed write twice is a no-op.
56
+ // Both mechanisms are idempotent by id, so seeing a committed write twice
57
+ // is a no-op.
60
58
  //
61
59
  // If the feed cannot be established, or delivers an event shape we do not
62
60
  // understand (Harper emits a bare `reload` marker when a base copy / resync is
@@ -83,6 +81,7 @@
83
81
  import { threadId } from "node:worker_threads";
84
82
  import { databases } from "harper";
85
83
  import { withDetachedTxn } from "./table-helpers.js";
84
+ import { subscribeInProcess } from "./table-subscription-policy.js";
86
85
  import { Bm25Index, INDEX_SELECT } from "./bm25-index.js";
87
86
  import { BM25_BOOT_WARM_SKIPPED_PREFIX, formatBm25IndexSummary, readThreadsCount } from "./bm25-status.js";
88
87
  import { retrievalMode } from "./bm25.js";
@@ -258,7 +257,7 @@ async function startFeed(ctx) {
258
257
  if (feedStarted)
259
258
  return;
260
259
  feedStarted = true;
261
- const subscription = await withDetachedTxn(ctx, () => databases.flair.Memory.subscribe({ omitCurrent: true }));
260
+ const subscription = await withDetachedTxn(ctx, () => subscribeInProcess(databases.flair.Memory, { omitCurrent: true }));
262
261
  // Deliberately not awaited: the consumer runs for the life of the process.
263
262
  (async () => {
264
263
  try {
@@ -41,7 +41,12 @@ export const DEDUP_CLUSTER_ANN_K_DEFAULT = 10;
41
41
  * foreseeable future, and the brief explicitly asked to prefer the full ANN
42
42
  * sweep over sampling. When the instance exceeds this, the sweep covers the
43
43
  * most-recently-created N memories (deterministic, documented) rather than
44
- * a random sample. */
44
+ * a random sample. The CLI's `POST /MemoryDedupStats` shares the REM work
45
+ * deadline (1,800 s by default, `REM_WORK_REQUEST_DEADLINE_MS` in
46
+ * `src/commands/rem.ts`) which is a sizing estimate
47
+ * from one observation, not a throughput claim: 20,000 x ~57 ms = ~1,140 s.
48
+ * The route also scans every Memory row before it selects the capped ANN
49
+ * set. */
45
50
  export const DEDUP_CLUSTER_MAX_MEMORIES_DEFAULT = 20_000;
46
51
  /** Server-side stat artifact home (Slice 1c Part 2 — smallest-surface
47
52
  * storage choice). A single small JSON file under the SERVER's own
@@ -107,6 +107,28 @@
107
107
  * still a separate, deliberate step from shipping this code — see the PR
108
108
  * description for that distinction.
109
109
  */
110
+ import { TEST_FAULT_INJECTION_ENV } from "./txn-pause-point.js";
111
+ /**
112
+ * Test-only provider delay: the first call in this process whose text contains
113
+ * `FLAIR_TEST_EMBED_PROVIDER_DELAY_MATCH` waits
114
+ * `FLAIR_TEST_EMBED_PROVIDER_DELAY_MS` before reaching the backend. The delay
115
+ * happens only when `FLAIR_ENABLE_TEST_FAULT_INJECTION=1` and both settings are set.
116
+ */
117
+ const TEST_EMBED_DELAY_MS_ENV = "FLAIR_TEST_EMBED_PROVIDER_DELAY_MS";
118
+ const TEST_EMBED_DELAY_MATCH_ENV = "FLAIR_TEST_EMBED_PROVIDER_DELAY_MATCH";
119
+ let testProviderDelayUsed = false;
120
+ function testProviderDelayMs(text) {
121
+ if (testProviderDelayUsed)
122
+ return undefined;
123
+ if (process.env[TEST_FAULT_INJECTION_ENV] !== "1")
124
+ return undefined;
125
+ const match = process.env[TEST_EMBED_DELAY_MATCH_ENV];
126
+ const ms = Number(process.env[TEST_EMBED_DELAY_MS_ENV]);
127
+ if (!match || !text.includes(match) || !Number.isFinite(ms) || ms <= 0)
128
+ return undefined;
129
+ testProviderDelayUsed = true;
130
+ return ms;
131
+ }
110
132
  const VALID_INPUT_TYPES = new Set(["document", "query"]);
111
133
  /**
112
134
  * THE GATE (flair#504 Phase 2 — flipped ON). A module-level constant, not an
@@ -320,6 +342,9 @@ function ensureProbeStarted() {
320
342
  export async function getEmbedding(text, inputType) {
321
343
  ensureProbeStarted();
322
344
  try {
345
+ const providerDelay = testProviderDelayMs(text);
346
+ if (providerDelay !== undefined)
347
+ await new Promise((resolve) => setTimeout(resolve, providerDelay));
323
348
  const models = await getModelsApi();
324
349
  const [vec] = await models.embed(text, buildEmbedOptions(inputType));
325
350
  if (!vec)
@@ -6,6 +6,7 @@
6
6
  * in SyncLog.skippedReasons so operators can grep for them.
7
7
  */
8
8
  import { effectiveAgentStatus } from "./agent-status-guard.js";
9
+ import { ADMIN_ROLE } from "./agent-admin.js";
9
10
  /**
10
11
  * Every SkipReason's retry class (flair#2455 design rev 2, K1/S3).
11
12
  *
@@ -32,9 +33,12 @@ export const SKIP_REASON_CLASS = {
32
33
  pointer_not_federated: "non_retryable",
33
34
  agent_status_not_federated: "non_retryable",
34
35
  agent_pending_key_not_federated: "non_retryable",
36
+ agent_identity_not_from_home: "non_retryable",
37
+ agent_admin_id_not_federated: "non_retryable",
35
38
  id_mismatch: "non_retryable",
36
39
  invalid_expiry: "non_retryable",
37
40
  merge_target_changed: "retryable",
41
+ merge_target_busy: "retryable",
38
42
  merge_error: "retryable",
39
43
  invalid_agent_id: "non_retryable",
40
44
  skill_not_federated: "non_retryable",
@@ -245,3 +249,88 @@ export function inboundChangesExistingPendingKey(record, local) {
245
249
  return false;
246
250
  return Object.prototype.hasOwnProperty.call(data, "publicKey") && data.publicKey !== local.publicKey;
247
251
  }
252
+ const hasOwn = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
253
+ /** A missing, null or empty home all mean "no recorded home". */
254
+ function sameAgentHome(a, b) {
255
+ const none = (v) => v === null || v === undefined || v === "";
256
+ return (none(a) && none(b)) || a === b;
257
+ }
258
+ /**
259
+ * flair#2665: whether `senderInstanceId` (the batch-verified sender, not a
260
+ * field of the record) is the stored Agent row's home (`originatorInstanceId`).
261
+ * A row with no recorded home has no sender that matches.
262
+ */
263
+ export function senderIsAgentHome(local, senderInstanceId) {
264
+ const home = local?.originatorInstanceId;
265
+ return typeof home === "string" && home.length > 0 && home === senderInstanceId;
266
+ }
267
+ /**
268
+ * flair#2665: true for an inbound Agent record that would change an existing
269
+ * local row's `publicKey` or home (`originatorInstanceId`), regardless of
270
+ * timestamps.
271
+ */
272
+ export function inboundChangesAgentIdentity(record, local) {
273
+ if (record.table !== "Agent" || local == null)
274
+ return false;
275
+ const data = record.data;
276
+ if (!data || typeof data !== "object")
277
+ return false;
278
+ if (hasOwn(data, "publicKey") && data.publicKey !== local.publicKey)
279
+ return true;
280
+ return hasOwn(data, "originatorInstanceId") && !sameAgentHome(data.originatorInstanceId, local.originatorInstanceId);
281
+ }
282
+ /**
283
+ * flair#2665: the refusal for an inbound Agent record that would change an
284
+ * existing row's `publicKey` or home when the batch-verified sender is not that
285
+ * row's stored home, else null.
286
+ */
287
+ export function agentIdentityRefusal(record, local, senderInstanceId) {
288
+ if (!inboundChangesAgentIdentity(record, local))
289
+ return null;
290
+ return senderIsAgentHome(local, senderInstanceId) ? null : "agent_identity_not_from_home";
291
+ }
292
+ /**
293
+ * flair#2665: the refusal for an inbound Agent record that would create a row
294
+ * (`local` is null) whose id is in `configuredAdminIds`, else null. The caller
295
+ * passes resources/agent-admin.ts's configuredAdminAgentIds(), the set
296
+ * resources/agent-auth.ts's agentIsAdmin() admits by id.
297
+ */
298
+ export function agentAdminIdCreateRefusal(record, local, configuredAdminIds) {
299
+ if (record.table !== "Agent" || local != null)
300
+ return null;
301
+ return configuredAdminIds.has(record.id) ? "agent_admin_id_not_federated" : null;
302
+ }
303
+ /**
304
+ * flair#2665: admin state (`role` equal to ADMIN_ROLE, `admin: true`) is the
305
+ * receiving instance's own. Applied to the row a federation merge is
306
+ * about to write for an Agent record (mutates and returns `merged`):
307
+ * - a NEW row (`stored` is null) is written without admin state: a `role` equal to
308
+ * ADMIN_ROLE is removed and an `admin: true` mirror becomes false;
309
+ * - an EXISTING row keeps its stored `role` when the merged one would change
310
+ * whether the row is an administrator, and keeps its stored `admin` mirror
311
+ * when the merged one's `admin: true` state differs from the stored one's.
312
+ * A `role` label follows the merge when the stored and incoming roles are both
313
+ * non-admin.
314
+ */
315
+ export function keepReceiverAgentAuthority(merged, stored) {
316
+ if (stored == null) {
317
+ if (merged.role === ADMIN_ROLE)
318
+ delete merged.role;
319
+ if (merged.admin === true)
320
+ merged.admin = false;
321
+ return merged;
322
+ }
323
+ if ((merged.role === ADMIN_ROLE) !== (stored.role === ADMIN_ROLE)) {
324
+ if (hasOwn(stored, "role"))
325
+ merged.role = stored.role;
326
+ else
327
+ delete merged.role;
328
+ }
329
+ if ((merged.admin === true) !== (stored.admin === true)) {
330
+ if (hasOwn(stored, "admin"))
331
+ merged.admin = stored.admin;
332
+ else
333
+ delete merged.admin;
334
+ }
335
+ return merged;
336
+ }
@@ -8,26 +8,14 @@
8
8
  * in resources/FederationRetry.ts.
9
9
  */
10
10
  import { isSkipReason } from "./federation-classify.js";
11
- export const RETRY_RESOLUTIONS = new Set([
12
- "merged",
13
- "refused_terminal",
14
- "source_deleted",
15
- "source_ineligible",
16
- "peer_unavailable",
17
- "retry_exhausted",
18
- ]);
19
- export const RETRY_BOUNDS = new Set(["attempts", "age", "both"]);
11
+ import { RETRY_BOUNDS, RETRY_RESOLUTIONS, isRetryBound, isRetryResolution, parseRetryEntryKey, retryEntryKey, retryRowProblem as retryRowProblemShared, } from "../src/lib/federation-retry-row.js";
12
+ export { parseRetryEntryKey, retryEntryKey };
13
+ export { RETRY_BOUNDS, RETRY_RESOLUTIONS, isRetryBound, isRetryResolution };
20
14
  export const LOCAL_RETRY_REASONS = new Set([
21
15
  "transport_failure",
22
16
  "invalid_response",
23
17
  "retry_unknown",
24
18
  ]);
25
- export function isRetryResolution(value) {
26
- return typeof value === "string" && RETRY_RESOLUTIONS.has(value);
27
- }
28
- export function isRetryBound(value) {
29
- return typeof value === "string" && RETRY_BOUNDS.has(value);
30
- }
31
19
  /**
32
20
  * Every field the `FederationRetry` schema declares (schemas/federation.graphql),
33
21
  * in schema order. The table is `@sealed`, so Harper refuses a write that
@@ -64,72 +52,9 @@ export function pickRetryRowFields(row) {
64
52
  return out;
65
53
  }
66
54
  /**
67
- * Encode the (peerId, table, recordId) tuple as the row's primary key.
68
- *
69
- * A JSON array join, never a bare concatenation: a naive `${peerId}${table}
70
- * ${recordId}` collides (peer `a` + table `bc` is peer `ab` + table `c`), and
71
- * peer and record ids are arbitrary strings off the wire, including legacy
72
- * `.content`-suffixed ids. JSON quotes and escapes each component, so distinct
73
- * tuples encode to distinct strings and the components round-trip exactly.
74
- *
75
- * Every component must be a non-empty string; a missing component is a caller
76
- * bug, not a row to write, so this THROWS rather than mint a malformed key.
55
+ * See {@link retryRowProblemShared}: the shared convention check, with the
56
+ * receiver's full reason vocabulary.
77
57
  */
78
- export function retryEntryKey(peerId, table, recordId) {
79
- for (const [name, value] of [
80
- ["peerId", peerId],
81
- ["table", table],
82
- ["recordId", recordId],
83
- ]) {
84
- if (typeof value !== "string" || value.length === 0) {
85
- throw new Error(`federation retry: ${name} must be a non-empty string`);
86
- }
87
- }
88
- return JSON.stringify([peerId, table, recordId]);
89
- }
90
- /** Decode {@link retryEntryKey}'s output, or null when `id` is not a retry key. */
91
- export function parseRetryEntryKey(id) {
92
- let parsed;
93
- try {
94
- parsed = JSON.parse(id);
95
- }
96
- catch {
97
- return null;
98
- }
99
- if (!Array.isArray(parsed) || parsed.length !== 3)
100
- return null;
101
- const [peerId, table, recordId] = parsed;
102
- if (typeof peerId !== "string" || typeof table !== "string" || typeof recordId !== "string")
103
- return null;
104
- if (peerId.length === 0 || table.length === 0 || recordId.length === 0)
105
- return null;
106
- return { peerId, table, recordId };
107
- }
108
58
  export function retryRowProblem(row) {
109
- let expectedId = null;
110
- try {
111
- expectedId = retryEntryKey(row.peerId, row.table, row.recordId);
112
- }
113
- catch {
114
- expectedId = null;
115
- }
116
- if (expectedId === null || row.id !== expectedId)
117
- return "id_mismatch";
118
- if (row.state !== "pending" && row.state !== "terminal")
119
- return "unknown_state";
120
- if (row.lastReason != null && !isSkipReason(row.lastReason) && !LOCAL_RETRY_REASONS.has(row.lastReason)) {
121
- return "unknown_reason";
122
- }
123
- if (row.state === "pending") {
124
- if (row.resolution != null || row.bound != null)
125
- return "outcome_mismatch";
126
- }
127
- else {
128
- if (!isRetryResolution(row.resolution))
129
- return "outcome_mismatch";
130
- const exhausted = row.resolution === "retry_exhausted";
131
- if (exhausted ? !isRetryBound(row.bound) : row.bound != null)
132
- return "outcome_mismatch";
133
- }
134
- return null;
59
+ return retryRowProblemShared(row, (value) => isSkipReason(value) || LOCAL_RETRY_REASONS.has(value));
135
60
  }
@@ -203,6 +203,10 @@ export class HealthDetail extends Resource {
203
203
  // corpus is one space and still outstanding against getModelId().
204
204
  let mixedEmbeddingSpaces = false;
205
205
  let memoryScanOk = false;
206
+ // Set only when the Memory scan finished without throwing. A failed or
207
+ // partial scan leaves it false, and the unregistered-author list is then
208
+ // reported unavailable (null); no other field reads this flag.
209
+ let memoryScanComplete = false;
206
210
  let memoryModelCounts = {};
207
211
  // flair#1326: same search-ready signal as public /Health. HealthDetail
208
212
  // stays HTTP 200 (it is a stats dump, not a traffic gate); the field
@@ -335,6 +339,7 @@ export class HealthDetail extends Resource {
335
339
  memoryModelCounts = modelCounts;
336
340
  if (distinctSpaces.size > 1)
337
341
  mixedEmbeddingSpaces = true;
342
+ memoryScanComplete = true;
338
343
  }
339
344
  catch {
340
345
  stats.memories = null;
@@ -347,16 +352,24 @@ export class HealthDetail extends Resource {
347
352
  const blank = (id) => ({
348
353
  id, memoryCount: 0, hashFallback: 0, writes24h: 0, lastWriteAt: null, usageCount: 0,
349
354
  });
355
+ // The count, the names and the table all come from one map keyed by
356
+ // Agent id, so the admin total, names and row set describe the same
357
+ // agents. A Memory row whose author has no Agent record — the
358
+ // operator's `skill:using-flair` seed when the operator id was never
359
+ // registered — is kept in a separate list, never added to `perAgent`
360
+ // as if it were an agent (flair#3051).
350
361
  const perAgentMap = new Map();
351
362
  for (const a of agents) {
352
363
  if (a.id)
353
364
  perAgentMap.set(a.id, blank(a.id));
354
365
  }
366
+ const unregisteredMap = new Map();
355
367
  const cutoff24h = nowMs - 24 * 3600 * 1000;
356
368
  for (const m of memoriesList) {
357
369
  if (!m.agentId)
358
370
  continue;
359
- const row = perAgentMap.get(m.agentId) ?? blank(m.agentId);
371
+ const known = perAgentMap.get(m.agentId);
372
+ const row = known ?? unregisteredMap.get(m.agentId) ?? blank(m.agentId);
360
373
  row.memoryCount++;
361
374
  row.usageCount += (m.usageCount ?? 0);
362
375
  if (!m.embeddingModel || m.embeddingModel === "hash-512d")
@@ -369,16 +382,33 @@ export class HealthDetail extends Resource {
369
382
  row.lastWriteAt = m.createdAt;
370
383
  }
371
384
  }
372
- perAgentMap.set(m.agentId, row);
385
+ if (known)
386
+ perAgentMap.set(m.agentId, row);
387
+ else
388
+ unregisteredMap.set(m.agentId, row);
373
389
  }
390
+ const agentIds = Array.from(perAgentMap.keys());
374
391
  const perAgentFull = Array.from(perAgentMap.values()).sort((a, b) => b.memoryCount - a.memoryCount);
375
392
  const perAgent = isAdmin
376
393
  ? perAgentFull
377
394
  : perAgentFull.filter((r) => r.id === callerAgent || r.memoryCount > 0);
395
+ const unregisteredMemoryAuthors = Array.from(unregisteredMap.values())
396
+ .sort((a, b) => b.memoryCount - a.memoryCount)
397
+ .map((r) => ({ id: r.id, memoryCount: r.memoryCount }));
378
398
  stats.agents = {
379
- count: agents.length,
380
- names: isAdmin ? agents.map((a) => a.id).filter(Boolean) : undefined,
399
+ count: perAgentMap.size,
400
+ names: isAdmin ? agentIds : undefined,
381
401
  perAgent,
402
+ // A non-admin gets the de-duplicated Agent count — one per distinct
403
+ // truthy Agent id, so a duplicate collapses and an id-less row is
404
+ // not counted — and only the perAgent rows it may see: its own row
405
+ // and rows with memories. unregisteredMemoryAuthors is undefined for
406
+ // a non-admin. An admin gets that list only after a complete Memory
407
+ // scan; null means the scan did not finish, so the answer is unknown
408
+ // rather than empty or partial.
409
+ unregisteredMemoryAuthors: isAdmin
410
+ ? (memoryScanComplete ? unregisteredMemoryAuthors : null)
411
+ : undefined,
382
412
  };
383
413
  }
384
414
  catch {
@@ -847,6 +877,9 @@ export class HealthDetail extends Resource {
847
877
  lastCycleError: redactReason(rawSnapshot.lastCycleError),
848
878
  migrations: rawSnapshot.migrations.map((m) => ({
849
879
  ...m,
880
+ // Row ids are operator detail, like the state-file path below:
881
+ // verified non-admin callers get the count only (flair#2840).
882
+ unconfirmedIds: undefined,
850
883
  reason: m.state === "completed" && m.reason
851
884
  ? "recorded complete; not re-verified this boot"
852
885
  : redactReason(m.reason),
@@ -888,6 +921,12 @@ export class HealthDetail extends Resource {
888
921
  if (m.state === "halted" || m.state === "failed") {
889
922
  warnings.push({ level: "warn", message: `migration '${m.id}' ${m.state}${m.reason ? `: ${m.reason}` : ""} — see \`flair doctor\`` });
890
923
  }
924
+ else if (m.state === "completed" && (m.rowsUnconfirmed ?? 0) > 0) {
925
+ warnings.push({
926
+ level: "warn",
927
+ message: `migration '${m.id}' completed with ${m.rowsUnconfirmed} row(s) it could not confirm`,
928
+ });
929
+ }
891
930
  }
892
931
  // The boot trigger sets `scheduled` synchronously at module load, so
893
932
  // `idle` here means resources/migration-boot.js never loaded — the
@@ -33,3 +33,32 @@ export const productionHostPointerAdapter = {
33
33
  export function currentHostPointerAdapter() {
34
34
  return productionHostPointerAdapter;
35
35
  }
36
+ export class PointerAlreadyStoredError extends Error {
37
+ pointer;
38
+ constructor(pointer) {
39
+ super("MemoryHostSource replacement already stored");
40
+ this.pointer = pointer;
41
+ }
42
+ }
43
+ /** Guard the table put with Harper's commit-time entry and conflict retry. */
44
+ export async function restorePointerRowIfAbsent(row, ctx) {
45
+ const store = pointerTable()?.primaryStore;
46
+ if (!store || typeof ctx?.transaction?.addWrite !== "function") {
47
+ throw new Error("MemoryHostSource conditional restore unavailable");
48
+ }
49
+ const guard = {
50
+ key: row.memoryId,
51
+ store,
52
+ reloadCommitBase: true,
53
+ entry: undefined,
54
+ commit(_time, entry) {
55
+ if (entry?.value)
56
+ throw new PointerAlreadyStoredError(entry.value);
57
+ },
58
+ };
59
+ ctx.transaction.addWrite(guard);
60
+ // Distinguish a read absence from an entry Harper's save() has not read yet.
61
+ if (guard.entry === undefined)
62
+ guard.entry = null;
63
+ await currentHostPointerAdapter().putPointerRow(row, ctx);
64
+ }
@@ -7,6 +7,7 @@
7
7
  * Production behaviour is the real table.
8
8
  */
9
9
  import { currentHostPointerAdapter } from "./host-pointer/registry.js";
10
+ export { PointerAlreadyStoredError, restorePointerRowIfAbsent } from "./host-pointer/registry.js";
10
11
  export function putPointerRow(row, ctx) {
11
12
  return currentHostPointerAdapter().putPointerRow(row, ctx);
12
13
  }
@@ -44,15 +44,17 @@
44
44
  *
45
45
  * resolveAgentAuth({ request: { tpsAgent: undefined } }) -> { kind: "internal" }
46
46
  * resolveAgentAuth({ request: { tpsAgent: "" } }) -> { kind: "internal" }
47
- * allowAdmin({ request: { tpsAgent: undefined } }) -> true
47
+ * allowAdmin({ request: { tpsAgent: undefined } }) -> false
48
48
  *
49
49
  * `resolveAgentAuth` tests `tpsAgent` for TRUTHINESS, so a missing or empty id
50
50
  * is indistinguishable from "no identity was supplied at all" — and that is the
51
51
  * trusted verdict. The consequence is that the most ordinary application bug
52
52
  * there is — `agentContext(session.agentId)` where the field is undefined, a
53
- * typo'd property, a lookup that found nothing — would not fail closed. It
54
- * would silently grant unfiltered cross-agent reads and writes, and pass the
55
- * admin-only gate on admin-only resources. No error, no 403, no log line.
53
+ * typo'd property, a lookup that found nothing — would not fail closed: the
54
+ * agent-facing gate (`allowVerified`) admits the `internal` verdict, and a
55
+ * `Memory` read with it is unfiltered. The admin-only gate refuses it:
56
+ * `allowAdmin` admits the `internal` verdict only for a call that carries
57
+ * `internalContext()`'s marker and no request headers.
56
58
  *
57
59
  * That is the same defect class as a check that cannot fail: **the failure mode
58
60
  * of "I forgot the id" must never be "you are now an administrator."** So:
@@ -73,7 +75,7 @@
73
75
  *
74
76
  * These guards are runtime, not types, on purpose: an embedding application may
75
77
  * be plain JavaScript, where a `string` parameter annotation buys exactly
76
- * nothing. test/integration/in-process-agents.test.ts pins both the guards and
78
+ * nothing. test/integration-heavy/in-process-agents.test.ts pins both the guards and
77
79
  * the hazard they exist for, against a real Harper.
78
80
  *
79
81
  * ── Deliberately dependency-free ─────────────────────────────────────────────
@@ -103,9 +105,8 @@ function requireAgentId(agentId, fnName) {
103
105
  : "a blank string";
104
106
  throw new InProcessContextError(`${fnName}() requires a non-empty agent id, but received ${got}. ` +
105
107
  "This is refused rather than defaulted because flair resolves a missing or empty " +
106
- "tpsAgent to its trusted `internal` verdict, which reads and writes UNFILTERED across " +
107
- "every agent and passes the admin-only gate — so returning a context here would have " +
108
- "turned a missing id into silent administrator access. Resolve the agent id from your " +
108
+ "tpsAgent to its trusted `internal` verdict, which can keep UNFILTERED access on " +
109
+ "agent-facing paths. Resolve the agent id from your " +
109
110
  "own server-side state before calling, and never from request data.");
110
111
  }
111
112
  return agentId;
@@ -175,15 +176,14 @@ export function adminContext(agentId) {
175
176
  *
176
177
  * This exists for work that is genuinely infrastructure rather than an agent's:
177
178
  * provisioning a principal, a migration, a maintenance sweep. It is the same
178
- * verdict a context-less call used to fall into by accident; naming it means an
179
- * application can no longer reach it by forgetting an argument, and means
180
- * `git grep internalContext` enumerates every place flair or an embedder took
181
- * that authority deliberately.
179
+ * `internal` verdict that `resolveAgentAuth(undefined)` returns, and
180
+ * `git grep internalContext` finds textual references to this helper's name in
181
+ * tracked files.
182
182
  *
183
183
  * There is no id to validate: the verdict comes precisely from the ABSENCE of
184
- * an identity annotation, so the returned object carries none. The marker field
185
- * is inert — it documents intent at a debugger breakpoint and is read by
186
- * nothing.
184
+ * an identity annotation, so the returned object carries none. The admin-only
185
+ * gate reads its marker: `allowAdmin` admits the `internal` verdict only for a
186
+ * call that carries it and no request headers.
187
187
  *
188
188
  * ```ts
189
189
  * // Registering a principal — infrastructure, not an agent's own write.
@@ -210,13 +210,15 @@ export function internalContext() {
210
210
  * start their own transaction.
211
211
  *
212
212
  * **They do still need the CONTEXT.** Only the collection binding is
213
- * unnecessary for a read, not the identity. `Cls.search(query)` with the second
214
- * argument left off does not read "as nobody" — outside a Harper request scope
215
- * (a boot hook, a timer, a queue worker, a detached promise) it resolves to the
216
- * same trusted `internal` verdict this module exists to keep out of reach, and
217
- * returns every agent's private records unfiltered. On that path the resource's
218
- * own `allow*` gate is not consulted at all, so nothing else stands in the way.
219
- * Pass the context to every call, read or write (flair#936).
213
+ * unnecessary for a read, not the identity. `Cls.search(query)` with no explicit
214
+ * or ambient context resolves to the trusted `internal` verdict. The query's
215
+ * conditions still narrow the rows, but no agent scope applies: every agent's
216
+ * matching records, `private` included, are returned. With the resulting `{}`
217
+ * context and no `query.checkPermission`, no permission check is requested
218
+ * (no `context.authorize`), so `allowRead` is never consulted. Memory's
219
+ * `allowRead` -> `memoryAuthGate` -> `allowVerified` would admit this `internal`
220
+ * call even if consulted. Pass the context to every call, read or write
221
+ * (flair#936).
220
222
  */
221
223
  export async function collectionResource(Cls, context) {
222
224
  if (context == null || typeof context !== "object") {