@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
@@ -19,8 +19,10 @@
19
19
  import { databases } from "harper";
20
20
  import { WINDOW_MS, importEd25519Key, b64ToArrayBuffer, parseTpsEd25519Header } from "./ed25519-auth.js";
21
21
  import { isKnownAgentReplay, claimAgentNonce } from "./replay-store.js";
22
- import { ADMIN_ROLE, agentRecordIsAdmin } from "./agent-admin.js";
22
+ import { agentRecordIsAdmin, configuredAdminAgentIds } from "./agent-admin.js";
23
23
  import { isPrincipalDeactivated } from "../src/lib/principal-status.js";
24
+ import { isProtocolLayerContext } from "./protocol-context.js";
25
+ import { isDeliberateInternalVerdict } from "./internal-authority.js";
24
26
  /**
25
27
  * Shared Harper user that verified Ed25519 agents resolve to (least-privilege
26
28
  * `flair_agent` role), replacing the old admin super_user elevation. Single
@@ -72,58 +74,73 @@ export async function readCredentialedPrincipal(agentId) {
72
74
  // any one of the three call sites, on any worker thread, is refused by all of
73
75
  // them, and the crypto/decoder logic can't drift.
74
76
  // ─── Admin resolution ─────────────────────────────────────────────────────────
75
- // Admin agents come from FLAIR_ADMIN_AGENTS (comma-separated) OR Agent records
76
- // whose `role` is the admin sentinel. OR-combined, cached 60s. Distinct from
77
- // Harper's super_user — admin here gates flair-policy decisions (promotions,
78
- // raw ops).
77
+ // An agent is a flair administrator when its id is named in FLAIR_ADMIN_AGENTS
78
+ // (comma-separated) or its stored Agent row's `role` is the admin sentinel.
79
+ // Distinct from Harper's super_user — admin here gates flair-policy decisions
80
+ // (promotions, raw ops).
79
81
  //
80
- // The record half of that union is the ONE place the Agent table is consulted
81
- // for an authorization decision, and it resolves through
82
- // resources/agent-admin.ts's shared predicate so it cannot drift from the
83
- // reporters or from the MCP surface (flair#941 — they had drifted).
84
- let adminCacheExpiry = 0;
85
- let adminCache = new Set();
86
- async function getAdminAgents() {
87
- const now = Date.now();
88
- if (now < adminCacheExpiry)
89
- return adminCache;
90
- const fromEnv = (process.env.FLAIR_ADMIN_AGENTS ?? "").split(",").map((s) => s.trim()).filter(Boolean);
91
- const fromDb = [];
82
+ // The decision is taken from an Agent ROW, never from a remembered set of ids.
83
+ // The Ed25519 verifiers (doVerify below and resources/auth-middleware.ts) pass
84
+ // the row they have just checked the request's signature against, so the key
85
+ // check and the admin decision describe the same stored record, on every
86
+ // request and on every worker thread. Nothing about admin status is kept
87
+ // between requests, so a change to the Agent table (a role change, a removed
88
+ // row, a new row under the same id) applies to the next request.
89
+ //
90
+ // The record half resolves through resources/agent-admin.ts's shared predicate
91
+ // so it cannot drift from the reporters or from the MCP surface (flair#941).
92
+ /**
93
+ * THE admin decision for an agent: its id is in the configured
94
+ * FLAIR_ADMIN_AGENTS set, or `row` (that agent's stored Agent row) carries the
95
+ * admin role. Pure: it reads no table. A verifier passes the row it checked the
96
+ * request's key against; a null or absent row leaves only the configured ids.
97
+ */
98
+ export function agentIsAdmin(agentId, row) {
99
+ return configuredAdminAgentIds().has(agentId) || agentRecordIsAdmin(row);
100
+ }
101
+ /**
102
+ * The admin decision for an agent id when no row is in hand: reads the agent's
103
+ * Agent row now and applies {@link agentIsAdmin}. Nothing is kept between
104
+ * calls. A read that fails counts as no row, so only the configured ids can
105
+ * then admit.
106
+ */
107
+ export async function isAdmin(agentId) {
108
+ let row = null;
92
109
  try {
93
- const results = await databases.flair.Agent.search([{ attribute: "role", value: ADMIN_ROLE, condition: "equals" }]);
94
- for await (const row of results)
95
- if (row?.id && agentRecordIsAdmin(row))
96
- fromDb.push(row.id);
110
+ row = await databases.flair.Agent.get(agentId);
111
+ }
112
+ catch {
113
+ row = null;
97
114
  }
98
- catch { /* Agent table may be empty */ }
99
- adminCache = new Set([...fromEnv, ...fromDb]);
100
- adminCacheExpiry = now + 60_000;
101
- return adminCache;
115
+ return agentIsAdmin(agentId, row);
102
116
  }
103
117
  /**
104
- * Drop the memoised admin set so the NEXT isAdmin() re-reads the Agent table.
118
+ * The admin decision for a handler that identifies its caller by the request's
119
+ * `tpsAgent` annotation.
105
120
  *
106
- * The 60s TTL is a load optimisation, but on its own it makes a privilege
107
- * change take up to a minute to appear — which reads as "the change didn't
108
- * work", and is exactly the confusion flair#941 is about: an operator grants
109
- * admin, tests it, sees a denial, and starts changing other things. The write
110
- * path knows precisely when a principal's admin status changed, so it says so
111
- * and the grant is effective on the caller's very next request.
121
+ * - A request the Ed25519 gate verified carries `tpsAgentAdminFromVerifiedRow`
122
+ * (resources/auth-middleware.ts). Its `tpsAgentIsAdmin` is the decision the
123
+ * gate took from the Agent row it verified the signature against, and that
124
+ * decision is returned unchanged: no second read.
125
+ * - Any other annotated caller (a Basic credential the gate annotated, an
126
+ * in-process agentContext()/adminContext(), an MCP tool context built from
127
+ * them) is decided by {@link isAdmin}: its Agent row read now, plus the
128
+ * configured ids. Its `tpsAgentIsAdmin` is not consulted here.
129
+ * - A request with no `tpsAgent` is not an admin here.
112
130
  *
113
- * Deliberately NOT a distributed invalidation: Harper runs N worker threads,
114
- * each with its own module instance and its own cache, so a promotion applied
115
- * on thread A still takes up to the TTL to be seen by thread B. Making that
116
- * exact would mean a shared invalidation channel, which is a much larger change
117
- * than the confusion warrants — the bound stays 60s, unchanged, and the common
118
- * single-threaded/dev case becomes immediate. Called by resources/Agent.ts's
119
- * write paths.
131
+ * All three are properties of the request object, never headers. On an HTTP
132
+ * request the gate sets `tpsAgent` and `tpsAgentIsAdmin`, and only its Ed25519
133
+ * branch sets `tpsAgentAdminFromVerifiedRow`. An in-process caller builds its
134
+ * own context with `tpsAgent` and `tpsAgentIsAdmin` (resources/in-process.ts),
135
+ * without the marker.
120
136
  */
121
- export function invalidateAdminCache() {
122
- adminCacheExpiry = 0;
123
- adminCache = new Set();
124
- }
125
- export async function isAdmin(agentId) {
126
- return (await getAdminAgents()).has(agentId);
137
+ export async function annotatedCallerIsAdmin(request) {
138
+ const agentId = request?.tpsAgent;
139
+ if (!agentId)
140
+ return false;
141
+ if (request.tpsAgentAdminFromVerifiedRow === true)
142
+ return request.tpsAgentIsAdmin === true;
143
+ return isAdmin(String(agentId));
127
144
  }
128
145
  async function doVerify(request) {
129
146
  const header = request?.headers?.get?.("authorization") ??
@@ -165,7 +182,8 @@ async function doVerify(request) {
165
182
  // before the request has any effect. A replay or an unusable store refuses.
166
183
  if (!(await claimAgentNonce(agentId, nonce)).ok)
167
184
  return null;
168
- return { agentId, isAdmin: await isAdmin(agentId) };
185
+ // The admin decision uses the row the signature was just verified against.
186
+ return { agentId, isAdmin: agentIsAdmin(agentId, agent) };
169
187
  }
170
188
  /**
171
189
  * Verify a TPS-Ed25519 signed request → the authenticated agent, or null.
@@ -266,27 +284,26 @@ export async function allowVerified(context) {
266
284
  return (await resolveAgentAuth(context)).kind !== "anonymous";
267
285
  }
268
286
  /**
269
- * allow* for ADMIN-ONLY resources: permit admin agents + super_user + trusted
270
- * internal calls; deny non-admin agents and anonymous.
287
+ * allow* for ADMIN-ONLY resources: permit admin agents + super_user, and the
288
+ * `internal` verdict only when isDeliberateInternalVerdict
289
+ * (resources/internal-authority.ts) holds: the context carries the
290
+ * `__flairInternal` marker and no request headers (flair#2837). Deny non-admin
291
+ * agents and anonymous.
271
292
  */
272
293
  export async function allowAdmin(context) {
273
294
  const a = await resolveAgentAuth(context);
274
- return a.kind === "internal" || (a.kind === "agent" && a.isAdmin);
295
+ if (a.kind === "internal")
296
+ return isDeliberateInternalVerdict(context, a);
297
+ return a.kind === "agent" && a.isAdmin;
275
298
  }
276
299
  /**
277
- * flair#936 — the `internal` verdict is TRUSTED and UNFILTERED, and it is also
278
- * what a caller gets for supplying no context at all. Nothing distinguishes
279
- * "I am flair's own maintenance code" from "I am an application developer who
280
- * did not know a context was required": both spell it `new Memory()`, both
281
- * succeed, and both return plausible data. It surfaces months later as memories
282
- * that were never scoped.
300
+ * flair#936 — the `internal` verdict is TRUSTED and UNFILTERED.
283
301
  *
284
- * This does not change the verdict — every authorization outcome is byte-
285
- * identical — it ends the SILENCE. A deliberate elevated call says so with
286
- * `internalContext()` (resources/in-process.ts), whose `__flairInternal` marker
287
- * is read here and nowhere else; anything else that lands on `internal` gets one
288
- * warning per process, with the stack, so the condition is observable where it
289
- * was previously invisible.
302
+ * This does not change the verdict. noteInternalVerdict skips a context that
303
+ * carries the `__flairInternal` marker, which `internalContext()`
304
+ * (resources/in-process.ts) sets; for an `internal` verdict without the marker
305
+ * it logs the warning with the stack, and the module-level latch below stops
306
+ * later warnings.
290
307
  *
291
308
  * MEASURED, and the reason this is worth having: flair itself has NO in-process
292
309
  * caller that relies on the omission — every maintenance, migration, federation
@@ -302,8 +319,8 @@ export async function allowAdmin(context) {
302
319
  */
303
320
  let warnedInternalByOmission = false;
304
321
  /**
305
- * Was this elevated call DELIBERATE — i.e. did the caller name the authority
306
- * with `internalContext()` rather than land on it by leaving a context off?
322
+ * Does this context carry the `__flairInternal` marker (which
323
+ * `internalContext()` sets)?
307
324
  *
308
325
  * Exported because it is the whole decision, and a decision worth testing is
309
326
  * worth testing directly: the warning itself is latched once per process, which
@@ -312,16 +329,19 @@ let warnedInternalByOmission = false;
312
329
  * first consumes the latch and every later assertion silently passes). Pinning
313
330
  * the predicate instead is deterministic.
314
331
  *
315
- * Grants nothing and is never consulted for an authorization decision — the
316
- * verdict is identical either way.
332
+ * This function feeds the warning, and the verdict is identical either way.
333
+ * The admin-only gate reads the same marker: `allowAdmin` admits
334
+ * the `internal` verdict only for a call that carries it and no request
335
+ * headers (isDeliberateInternalVerdict in resources/internal-authority.ts,
336
+ * shared with the Soul and skill write-source rules).
317
337
  */
318
338
  export function isDeliberateInternalCall(context) {
319
339
  return context?.__flairInternal === true;
320
340
  }
321
341
  /** The advisory text, exported so its content is pinned without tripping the latch. */
322
- export const INTERNAL_BY_OMISSION_WARNING = "[flair-auth] a resource was invoked with NO caller context and resolved to the trusted " +
323
- "`internal` verdict: reads are UNFILTERED across every agent, writes are unattributed, and " +
324
- "the admin-only gate passes. If this is your application's code, pass agentContext(<id>) from " +
342
+ export const INTERNAL_BY_OMISSION_WARNING = "[flair-auth] a resource resolved a call to the trusted `internal` verdict without the " +
343
+ "deliberate-call marker: reads are UNFILTERED across every agent, writes are unattributed, and " +
344
+ "the admin-only gate (allowAdmin) refuses it. If this is your application's code, pass agentContext(<id>) from " +
325
345
  "@tpsdev-ai/flair's in-process seam so the call is scoped and attributed. If the elevated " +
326
346
  "authority is genuinely intended, say so with internalContext() and this warning will stop. " +
327
347
  "Fires once per process.";
@@ -393,6 +413,16 @@ export async function resolveAgentAuth(context) {
393
413
  return { kind: "agent", agentId: auth.agentId, isAdmin: auth.isAdmin };
394
414
  return { kind: "anonymous" };
395
415
  }
416
+ // A context a protocol layer built (an MQTT session's action — on Harper's
417
+ // TCP or TLS listener it carries no HTTP request — one still carrying
418
+ // Harper's `authorize: true`, or a requestless one carrying Harper's
419
+ // `checkPermission` marker, as Harper's native MCP application tools build)
420
+ // is a remote caller with no credential flair can verify: anonymous, never
421
+ // internal (resources/protocol-context.ts). flair has no verified bridge from
422
+ // the Harper user of a native MCP call to a flair caller, so that caller is
423
+ // anonymous too, in the resource's authorization hooks and in its handlers.
424
+ if (isProtocolLayerContext(context))
425
+ return { kind: "anonymous" };
396
426
  noteInternalVerdict(context);
397
427
  return { kind: "internal" };
398
428
  }
@@ -28,7 +28,10 @@ export function readPositionId(agentId, stream) {
28
28
  export function recordPosition(record) {
29
29
  return `${record.createdAt ?? ""}${POSITION_SEP}${record.id ?? ""}`;
30
30
  }
31
- /** Exclusive cursor just after every record at-or-before this ISO timestamp. */
31
+ /**
32
+ * Exclusive cursor after every record created before this ISO timestamp. A
33
+ * record created at exactly this timestamp (non-empty id) sorts after it.
34
+ */
32
35
  export function positionAfterTimestamp(iso) {
33
36
  return `${iso}${POSITION_SEP}`;
34
37
  }
@@ -7,13 +7,15 @@
7
7
  * may write its own `status` can deactivate itself. Liveness belongs on the
8
8
  * Presence beacon, not on this column.
9
9
  *
10
- * resources/Agent.ts's PUT and PATCH admit a trusted internal call and an
11
- * administrator, and refuse anonymous and any verdict kind the auth resolver
12
- * does not define. A non-admin agent's PUT or PATCH whose body carries the
13
- * `status` key is refused whole, on any row including its own, so the other
14
- * fields in that request are not written either; without `status`, it goes on
15
- * to Agent.ts's other per-record rules. A non-admin agent's POST (create) is
16
- * refused earlier, at allowCreate(). (A federation peer's record is merged
10
+ * resources/Agent.ts's PUT is an administrator operation: it admits a trusted
11
+ * internal call and an administrator and refuses every other caller, whatever
12
+ * its body. Its PATCH admits a trusted internal call and an administrator,
13
+ * refuses anonymous and any verdict kind the auth resolver does not define,
14
+ * and admits a non-admin agent to the rules below. A non-admin agent's PATCH
15
+ * whose body carries the `status` key is refused whole, on any row including
16
+ * its own, so the other fields in that request are not written either; without
17
+ * `status`, it goes on to Agent.ts's other per-record rules. A non-admin
18
+ * agent's POST (create) is refused earlier, at allowCreate(). (A federation peer's record is merged
17
19
  * through the raw table, not this resource; resources/Federation.ts skips an
18
20
  * inbound Agent record whose `status` differs from an existing local
19
21
  * principal's stored value.)
@@ -1,12 +1,14 @@
1
1
  import { WRITE_BACK_ATTEMPTS, WriteBackConflictError, writeBackCommittedRow } from "./write-back.js";
2
2
  import { txnPausePoint } from "./txn-pause-point.js";
3
+ import { withMemoryWriteLockOnce } from "./memory-write-lock.js";
3
4
  import { server, databases } from "harper";
4
5
  import { getEmbedding, getModelId } from "./embeddings-provider.js";
5
6
  import { noteWriteStamp } from "./embedding-space-guard.js";
6
- import { hashEmbeddedText } from "./memory-embed-hash.js";
7
+ import { hashEmbeddedText, holdsOwnStaleVector } from "./memory-embed-hash.js";
7
8
  import { MEMORY_EMBEDDING_INPUT_FIELDS, skillEmbedText } from "./skill-write.js";
8
- import { isAdmin, isPrincipalDeactivated, FLAIR_AGENT_USERNAME, readCredentialedPrincipal, AGENT_LOOKUP_FAILED } from "./agent-auth.js";
9
+ import { agentIsAdmin, isPrincipalDeactivated, FLAIR_AGENT_USERNAME, readCredentialedPrincipal, AGENT_LOOKUP_FAILED } from "./agent-auth.js";
9
10
  import { WINDOW_MS, importEd25519Key, b64ToArrayBuffer, parseTpsEd25519Header } from "./ed25519-auth.js";
11
+ import { BASIC_AUTH_HEADER_RE, parseBasicAuthHeader } from "./basic-auth-header.js";
10
12
  import { isKnownAgentReplay, claimAgentNonce } from "./replay-store.js";
11
13
  import { isForbiddenOwnerMutation, ownerMutationRefusal, resolveGuardedRecord, resolveGuardedRecordById } from "./record-owner-guard.js";
12
14
  import { routeWithHarper } from "./harper-routing.js";
@@ -15,7 +17,7 @@ import { FLAIR_AUTH_MIDDLEWARE_HTTP_NAME } from "./multi-worker-guard.js";
15
17
  import { DECLARED_MEMORY_ATTRIBUTES } from "./memory-declared-attributes.js";
16
18
  import { idSegmentHasEncodedSlash, decodeMemoryIdSegment, MEMORY_CONTENT_SELECTOR_SUFFIX } from "../src/lib/memory-id-policy.js";
17
19
  import { contentSuffixIdDenial } from "./memory-id-guard.js";
18
- import { isCanonicalRequestTarget, nonCanonicalRequestTargetRefusal, requestPath, lastRawPathSegment, routedRecordId, routedResourceAndRemainder, routedIdAfterPropertyRule, routedResourcePath, } from "./request-target.js";
20
+ import { isCanonicalRequestTarget, nonCanonicalRequestTargetRefusal, requestPath, lastRawPathSegment, routedRecordId, routedResourceAndRemainder, routedIdAfterPropertyRule, routedResourcePath, whatwgUrlMatchesRawTarget, } from "./request-target.js";
19
21
  // --- Non-admin Memory read: ignore the caller's selection --------------------
20
22
  //
21
23
  // flair#1940 round 17. A non-admin HTTP Memory read returns the authorized,
@@ -151,10 +153,10 @@ function getAdminPass() {
151
153
  return null;
152
154
  }
153
155
  // ─── Admin resolution ─────────────────────────────────────────────────────────
154
- // `isAdmin` (FLAIR_ADMIN_AGENTS env + Agent role==="admin", 60s-cached) now lives
155
- // in agent-auth.ts as the single source of truth, imported above. During the
156
- // auth reshape this gate and the per-resource allow* helpers must agree on who's
157
- // an admin — one implementation guarantees they can't diverge.
156
+ // `agentIsAdmin` (FLAIR_ADMIN_AGENTS env + the Agent row's role === "admin")
157
+ // lives in agent-auth.ts as the single source of truth, imported above. This
158
+ // gate passes it the Agent row it verifies the signature against, exactly as
159
+ // agent-auth.ts's own verifier does, so the two cannot diverge.
158
160
  // ─── Crypto + replay-guard helpers ────────────────────────────────────────────
159
161
  // WINDOW_MS and importEd25519Key live in ./ed25519-auth.ts, and the replay
160
162
  // guard (isKnownAgentReplay / claimAgentNonce) in ./replay-store.ts — shared by
@@ -162,6 +164,11 @@ function getAdminPass() {
162
164
  // any one of the three call sites, on any worker thread, is refused by all of
163
165
  // them, and the crypto/decoder logic can't drift.
164
166
  async function backfillEmbedding(memoryId) {
167
+ let unconfirmed = false;
168
+ // Whether the attempt that just ended saw its write confirmed on the committed
169
+ // row, so a failure after the commit is not reported as the outcome of an
170
+ // earlier attempt.
171
+ let lastAttemptConfirmed = false;
165
172
  try {
166
173
  const table = databases.flair.Memory;
167
174
  // flair#2484: compute the vector before the owned write transaction opens.
@@ -171,55 +178,161 @@ async function backfillEmbedding(memoryId) {
171
178
  // entries skip before the text comparison. For eligible rows, `matchFields`
172
179
  // compares every field that selects the text (`content`, `trigger`, `tags`)
173
180
  // before staging; the helper confirms the committed row afterward. Drift
174
- // observed by either check aborts the attempt; remaining outer attempts
175
- // re-read and may recompute. Changes after confirmation and before commit
176
- // are not detected by these checks.
181
+ // observed before commit aborts the attempt; remaining outer attempts
182
+ // re-read and may recompute.
177
183
  //
178
184
  // flair#2573: the vector is stamped with the current model id, the space it
179
185
  // was computed in, and the embedding-space guard is notified after the write
180
186
  // commits with that stamp and the row it replaced, as for any other notified
181
187
  // vector write.
188
+ //
189
+ // flair#2478 slice 3: the write runs under the id's per-id Memory write lock
190
+ // shared with the owner verbs (resources/memory-write-lock.ts): one
191
+ // non-waiting acquisition per attempt of the loop below, taken after that
192
+ // attempt's vector is computed, so no provider call runs while the id is
193
+ // locked; a retry acquires it again.
194
+ // A held id, an id with an unresolved write outcome, or a store with no lock
195
+ // is skipped and logged, and that attempt writes nothing. After an earlier
196
+ // attempt of this call committed unconfirmed, every exit that ends the call
197
+ // without a verified write (a lock miss, a row now gone or already embedded,
198
+ // a provider that returned no vector, a thrown error, which is logged and not
199
+ // rethrown) logs the outcome as unconfirmed instead; a later verified write
200
+ // is logged as written, or, when its write-stamp notification then fails,
201
+ // as confirmed with that failure named. A skipped backfill is not
202
+ // retried by this call. The backfill starts only from the post-response hook
203
+ // at the end of this middleware (the "Embedding backfill" block below),
204
+ // which a successful HTTP Memory POST, PUT or PATCH reaches when a verified
205
+ // Ed25519 agent signed it; a valid Basic-admin request returns earlier
206
+ // (the super_user and Basic branches call nextLayer directly) and starts
207
+ // none, and neither does a raw or direct table write. So the id's next such
208
+ // signed write starts another, and a row with a stale or missing stamp is
209
+ // re-embedded by the embedding-stamp migration.
210
+ //
211
+ // Holding the lock, the helper's first read is the committed row: a row
212
+ // whose text changed, or that has a vector of more than 100 entries, is not
213
+ // written (a changed text ends this attempt; the next attempt of the loop
214
+ // below re-reads and re-embeds after the lock is released). The helper
215
+ // stages the update and confirms the committed row: a change visible at
216
+ // that confirmation aborts the transaction, writes nothing, and the helper
217
+ // retries from a fresh read under the same lock. Then it commits and reads
218
+ // the committed row back (identity, the written fields, and the text the
219
+ // vector was computed for) before the lock is released. A readable
220
+ // read-back that does not show them retries from a fresh read: within the
221
+ // helper's own bound (WRITE_BACK_ATTEMPTS, 3) under the same lock, and,
222
+ // when that retry finds the text changed, through the next attempt of the
223
+ // loop below (at most WRITE_BACK_ATTEMPTS attempts, each with its own
224
+ // acquisition). An unreadable read-back stops without a retry. The
225
+ // read-back checks only the final committed state of those fields, so a
226
+ // lock-bypassing write committed and then overwritten inside this write's
227
+ // window is not detected. An outcome the read-back did not confirm
228
+ // (unreadable, or the attempts exhausted) is logged as unconfirmed; it does
229
+ // not mark the id outcome-unknown.
230
+ //
231
+ // The backfill writes a row whose vector is missing or has at most 100
232
+ // entries, whatever stored it. A row holding a longer vector counts as
233
+ // already embedded and is skipped, except one whose stored vector matches,
234
+ // within a relative tolerance that accepts a float32 copy of an in-range
235
+ // component (a non-finite component never matches), the
236
+ // vector an earlier unconfirmed attempt of this call staged, while its text
237
+ // is no longer the text that vector was computed from (holdsOwnStaleVector):
238
+ // the row holds a vector equal to this call's computation for a text it no
239
+ // longer has, whoever stored it. That row is re-read and re-embedded by the
240
+ // next attempt of the loop below while one remains, which needs the
241
+ // read-back that found the mismatch to have been readable. The check
242
+ // compares vectors, not the stored text hash: a row with an empty
243
+ // owner stores a null hash, which would match any text. A longer stored
244
+ // vector that does not match the staged one is skipped like any other
245
+ // already-embedded row; a non-match says nothing about who stored it.
246
+ let ownUnconfirmed;
247
+ const alreadyEmbedded = (row) => row.embedding?.length > 100 && !holdsOwnStaleVector(row, ownUnconfirmed);
248
+ // After an earlier attempt of this call committed and its read-back did not
249
+ // confirm it, every exit that ends the call without a verified write logs
250
+ // the outcome as unconfirmed; an exit that wrote nothing says so for its own
251
+ // attempt only (flair#2478).
252
+ const endAfterUnconfirmed = (ended) => {
253
+ if (unconfirmed)
254
+ console.warn("[auto-embed] %s: %s; an earlier attempt's vector was not confirmed on the committed row; outcome: unconfirmed", memoryId, ended, { outcome: "unconfirmed" });
255
+ };
182
256
  for (let attempt = 1; attempt <= WRITE_BACK_ATTEMPTS; attempt++) {
257
+ lastAttemptConfirmed = false;
183
258
  const record = await table.get(memoryId, {});
184
259
  const text = record ? skillEmbedText(record) : undefined;
185
- if (typeof text !== "string" || text.length === 0)
260
+ if (typeof text !== "string" || text.length === 0) {
261
+ endAfterUnconfirmed("the row is gone or has no text, so this attempt wrote nothing");
186
262
  return;
187
- if (record.embedding?.length > 100)
263
+ }
264
+ if (alreadyEmbedded(record)) {
265
+ endAfterUnconfirmed("the row now counts as already embedded, so this attempt wrote nothing");
188
266
  return;
267
+ }
189
268
  const embedding = await getEmbedding(text, "document");
190
- if (!Array.isArray(embedding) || embedding.length === 0)
269
+ if (!Array.isArray(embedding) || embedding.length === 0) {
270
+ endAfterUnconfirmed("the provider returned no vector, so this attempt wrote nothing");
191
271
  return;
272
+ }
192
273
  const model = getModelId();
274
+ // Test-only: inert unless the fault-injection opt-in is armed. The vector
275
+ // is computed and the id's lock is not yet taken.
276
+ const entry = txnPausePoint("backfill-embedding-entry");
277
+ if (entry)
278
+ await entry;
193
279
  // The vector fields of the committed row the update replaces, for the
194
280
  // guard notification.
195
281
  let replaced = null;
196
282
  try {
197
- const outcome = await writeBackCommittedRow(table, memoryId, (row) => {
198
- const rowText = row ? skillEmbedText(row) : undefined;
199
- if (typeof rowText !== "string" || rowText.length === 0)
200
- return { skip: true };
201
- if (row.embedding?.length > 100)
202
- return { skip: true };
203
- replaced = { embedding: row.embedding, embeddingModel: row.embeddingModel };
204
- // Only `embedding`, its model stamp and its text hash: an incremental
205
- // update, never a full-row put of the row read above (flair#2470,
206
- // flair#2465). The newly computed hash is of `text`, the text this
207
- // vector was computed from (null for an empty owner).
208
- return { update: { embedding, embeddingModel: model, embeddedContentHash: hashEmbeddedText(row.agentId, text) ?? null } };
209
- }, {
210
- label: "backfillEmbedding",
211
- expectedRow: record,
212
- // Compare the text-selecting fields before staging, after the plan's skip checks.
213
- matchFields: [...MEMORY_EMBEDDING_INPUT_FIELDS, "tags"],
214
- pausePre: () => txnPausePoint("backfill-embedding-pre"),
215
- pausePoint: () => txnPausePoint("backfill-embedding"),
216
- });
283
+ const locked = await withMemoryWriteLockOnce(table.primaryStore, [memoryId], async () => {
284
+ const written = await writeBackCommittedRow(table, memoryId, (row) => {
285
+ const rowText = row ? skillEmbedText(row) : undefined;
286
+ if (typeof rowText !== "string" || rowText.length === 0)
287
+ return { skip: true };
288
+ if (alreadyEmbedded(row))
289
+ return { skip: true };
290
+ replaced = { embedding: row.embedding, embeddingModel: row.embeddingModel };
291
+ // Only `embedding`, its model stamp and its text hash: an incremental
292
+ // update, never a full-row put of the row read above (flair#2470,
293
+ // flair#2465). The newly computed hash is of `text`, the text this
294
+ // vector was computed from (null for an empty owner).
295
+ return { idempotent: true, update: { embedding, embeddingModel: model, embeddedContentHash: hashEmbeddedText(row.agentId, text) ?? null } };
296
+ }, {
297
+ label: "backfillEmbedding",
298
+ onUnconfirmed: () => { unconfirmed = true; ownUnconfirmed = { embedding, text }; },
299
+ expectedRow: record,
300
+ // Compare the text-selecting fields before staging, after the plan's skip checks.
301
+ matchFields: [...MEMORY_EMBEDDING_INPUT_FIELDS, "tags"],
302
+ // After the commit, the committed row must still carry the text this
303
+ // vector was computed from.
304
+ verifyAlso: (committed) => skillEmbedText(committed) === text,
305
+ pausePre: () => txnPausePoint("backfill-embedding-pre"),
306
+ pausePoint: () => txnPausePoint("backfill-embedding"),
307
+ pauseAfterStage: () => txnPausePoint("backfill-embedding-staged"),
308
+ pauseBeforeCommit: () => txnPausePoint("backfill-embedding-commit"),
309
+ });
310
+ // Test-only: the update has committed and been read back; the lock is
311
+ // still held. A plan that skipped wrote nothing, so it does not reach
312
+ // this point.
313
+ if (!("skip" in written)) {
314
+ const committed = txnPausePoint("backfill-embedding-committed");
315
+ if (committed)
316
+ await committed;
317
+ }
318
+ return written;
319
+ }, { phase: "auto-embed" });
320
+ if (locked.kind !== "done") {
321
+ if (unconfirmed)
322
+ endAfterUnconfirmed(`skipped; the per-id write lock answered ${locked.kind}, so this attempt wrote nothing`);
323
+ else
324
+ console.warn("[auto-embed] %s: skipped; the per-id write lock answered %s, so nothing was written", memoryId, locked.kind);
325
+ return;
326
+ }
327
+ const outcome = locked.value;
217
328
  if ("update" in outcome) {
218
- // After the commit: the stamp the update stored (an absent one reads as
219
- // untrusted and closes the guard) and the row it replaced.
329
+ lastAttemptConfirmed = true;
220
330
  noteWriteStamp(outcome.update.embeddingModel, replaced);
221
331
  console.log(`[auto-embed] ${memoryId}: ${outcome.update.embedding.length}d`);
222
332
  }
333
+ else if (unconfirmed) {
334
+ console.warn("[auto-embed] %s: an earlier attempt's vector was not confirmed on the committed row, and the row is now skipped; outcome: unconfirmed", memoryId, { outcome: "unconfirmed" });
335
+ }
223
336
  return;
224
337
  }
225
338
  catch (err) {
@@ -230,7 +343,11 @@ async function backfillEmbedding(memoryId) {
230
343
  }
231
344
  }
232
345
  catch (err) {
233
- console.error(`[auto-embed] Failed for ${memoryId}: ${err.message}`);
346
+ if (lastAttemptConfirmed) {
347
+ console.error("[auto-embed] %s for %s: the vector is confirmed on the committed row; the embedding-space write-stamp notification failed: %s", "Outcome confirmed", memoryId, err.message, { outcome: "stamp_notification_failed" });
348
+ return;
349
+ }
350
+ console.error("[auto-embed] %s for %s: %s", unconfirmed ? "Outcome unconfirmed" : "Failed", memoryId, err.message, ...(unconfirmed ? [{ outcome: "unconfirmed" }] : err instanceof WriteBackConflictError ? [{ outcome: err.outcome }] : []));
234
351
  }
235
352
  }
236
353
  // ─── HTTP middleware ──────────────────────────────────────────────────────────
@@ -422,7 +539,7 @@ server.http(async (request, nextLayer) => {
422
539
  // Scheme names are case-insensitive (RFC 9110): "basic"/"BASIC"/"Basic" all
423
540
  // select the Basic branch below, exactly as "Basic" does. Used for both the
424
541
  // /FederationPair public-bypass test and the Basic branch itself.
425
- const isBasic = /^Basic /i.test(header);
542
+ const isBasic = BASIC_AUTH_HEADER_RE.test(header);
426
543
  const isA2APath = routedDecisionPath === "/a2a" || routedDecisionPath === "/A2AAdapter" || routedDecisionPath.startsWith("/A2AAdapter/");
427
544
  if (!isTpsEd25519 && (routedDecisionPath === "/health" ||
428
545
  routedDecisionPath === "/Health" ||
@@ -505,10 +622,7 @@ server.http(async (request, nextLayer) => {
505
622
  // Checked BEFORE Ed25519 so admin tools can use simple auth.
506
623
  if (isBasic) {
507
624
  try {
508
- const decoded = Buffer.from(header.slice(6), "base64").toString("utf-8");
509
- const colonIdx = decoded.indexOf(":");
510
- const user = colonIdx >= 0 ? decoded.slice(0, colonIdx) : decoded;
511
- const pass = colonIdx >= 0 ? decoded.slice(colonIdx + 1) : "";
625
+ const { user, pass } = parseBasicAuthHeader(header);
512
626
  // Path 1: Env-var fast-path (back-compat). Only matches user==="admin"
513
627
  // with exact HDB_ADMIN_PASSWORD. Non-match falls through to Path 2.
514
628
  const adminPass = getAdminPass();
@@ -633,6 +747,11 @@ server.http(async (request, nextLayer) => {
633
747
  return nextLayer(request);
634
748
  }
635
749
  const { agentId, tsRaw, nonce, signatureB64 } = parsed;
750
+ // Refuse a signed request whose raw target WHATWG URL parsing would rewrite
751
+ // before verification, so the signature covers the target exactly as received.
752
+ if (!whatwgUrlMatchesRawTarget(rawTarget)) {
753
+ return nonCanonicalRequestTargetRefusal(String(request.method ?? ""));
754
+ }
636
755
  const ts = Number(tsRaw);
637
756
  const now = Date.now();
638
757
  if (!Number.isFinite(ts) || Math.abs(now - ts) > WINDOW_MS)
@@ -669,7 +788,12 @@ server.http(async (request, nextLayer) => {
669
788
  return new Response(JSON.stringify({ error: claim.error }), { status: claim.status });
670
789
  request.tpsAgent = agentId;
671
790
  request._tpsAuthVerified = true;
672
- request.tpsAgentIsAdmin = await isAdmin(agentId);
791
+ // The admin decision uses the Agent row the signature was just verified
792
+ // against, plus the configured admin ids. The marker tells a handler that
793
+ // tpsAgentIsAdmin already is that decision (agent-auth.ts
794
+ // annotatedCallerIsAdmin), so no handler re-decides it from another read.
795
+ request.tpsAgentIsAdmin = agentIsAdmin(agentId, agent);
796
+ request.tpsAgentAdminFromVerifiedRow = true;
673
797
  // RESHAPE (auth-rbac) — THE FLIP: per-agent DE-ELEVATION. A cryptographically-
674
798
  // verified NON-admin agent resolves to the least-privilege `flair-agent` user,
675
799
  // NOT admin super_user. The flair_agent role grants exactly the table CRUD agents