@tpsdev-ai/flair 0.62.0 → 0.63.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (257) hide show
  1. package/README.md +14 -13
  2. package/SECURITY.md +73 -43
  3. package/config.yaml +11 -11
  4. package/dist/bridges/runtime/execute.js +1 -0
  5. package/dist/bridges/runtime/import-runner.js +4 -0
  6. package/dist/bridges/types.js +1 -0
  7. package/dist/build-info.json +3 -3
  8. package/dist/cli.js +309 -205
  9. package/dist/commands/agent.js +325 -137
  10. package/dist/commands/attention.js +2 -0
  11. package/dist/commands/backup-approval.js +218 -0
  12. package/dist/commands/backup.js +37 -33
  13. package/dist/commands/bootstrap.js +5 -1
  14. package/dist/commands/bridge.js +10 -0
  15. package/dist/commands/deploy.js +37 -7
  16. package/dist/commands/doctor.js +206 -42
  17. package/dist/commands/export.js +144 -15
  18. package/dist/commands/federation.js +653 -68
  19. package/dist/commands/grant.js +5 -6
  20. package/dist/commands/help.js +25 -0
  21. package/dist/commands/idp.js +14 -19
  22. package/dist/commands/import.js +167 -34
  23. package/dist/commands/init.js +380 -164
  24. package/dist/commands/integrity.js +5 -6
  25. package/dist/commands/keys.js +12 -8
  26. package/dist/commands/mcp.js +157 -79
  27. package/dist/commands/memory.js +38 -17
  28. package/dist/commands/migrate-harness-memory.js +9 -3
  29. package/dist/commands/orgevent.js +5 -10
  30. package/dist/commands/principal.js +32 -39
  31. package/dist/commands/quality.js +26 -3
  32. package/dist/commands/reembed.js +468 -111
  33. package/dist/commands/rem.js +484 -65
  34. package/dist/commands/restore.js +352 -44
  35. package/dist/commands/search.js +2 -0
  36. package/dist/commands/service.js +109 -2
  37. package/dist/commands/soul.js +0 -6
  38. package/dist/commands/status.js +165 -124
  39. package/dist/commands/test.js +4 -1
  40. package/dist/commands/upgrade.js +53 -22
  41. package/dist/commands/workspace.js +7 -8
  42. package/dist/deploy.js +59 -3
  43. package/dist/doctor-client.js +9 -25
  44. package/dist/fabric-upgrade.js +12 -2
  45. package/dist/federation/presence-send.js +139 -0
  46. package/dist/federation/scheduler.js +148 -12
  47. package/dist/federation-verify.js +269 -177
  48. package/dist/install/clients.js +171 -35
  49. package/dist/keystore.js +77 -10
  50. package/dist/lib/agent-id-rule.js +44 -2
  51. package/dist/lib/agent-key-file.js +509 -0
  52. package/dist/lib/agent-rotation-lock.js +249 -0
  53. package/dist/lib/atomic-write.js +3 -3
  54. package/dist/lib/auth-resolve.js +1040 -64
  55. package/dist/lib/backup-approval-store.js +612 -0
  56. package/dist/lib/backup-artifact.js +343 -0
  57. package/dist/lib/config-critical-section.js +212 -25
  58. package/dist/lib/connect-phase.js +33 -0
  59. package/dist/lib/daemon-liveness.js +2 -1
  60. package/dist/lib/federation-pair-access.js +4 -0
  61. package/dist/lib/federation-retry-queue.js +283 -0
  62. package/dist/lib/federation-retry-row.js +101 -0
  63. package/dist/lib/instruction-event-contract.js +17 -0
  64. package/dist/lib/instruction-event-doctor.js +102 -0
  65. package/dist/lib/key-dir.js +203 -0
  66. package/dist/lib/launchd-management.js +21 -6
  67. package/dist/lib/local-instance-pair.js +8 -1
  68. package/dist/lib/mcp-enable.js +14 -15
  69. package/dist/lib/memory-attributes.js +2 -0
  70. package/dist/lib/memory-provider-timeout.js +33 -0
  71. package/dist/lib/mqtt-config.js +132 -0
  72. package/dist/lib/mqtt-listener-doctor.js +104 -0
  73. package/dist/lib/node-alias-path.js +50 -2
  74. package/dist/lib/open-live-row.js +20 -0
  75. package/dist/lib/ops-url.js +52 -0
  76. package/dist/lib/promotion-content-hash.js +20 -0
  77. package/dist/lib/remote-admin-pass.js +157 -0
  78. package/dist/lib/restore-archive.js +760 -0
  79. package/dist/lib/restore-verify.js +1 -1
  80. package/dist/lib/scheduler-platform.js +13 -0
  81. package/dist/lib/service-repoint.js +13 -4
  82. package/dist/lib/skill-assignment-preflight.js +159 -0
  83. package/dist/lib/skill-seed.js +125 -10
  84. package/dist/lib/skill-tombstone-doctor.js +133 -0
  85. package/dist/lib/soul-scope-fields.js +26 -0
  86. package/dist/lib/terminal-text.js +32 -0
  87. package/dist/lib/uninstall-purge.js +266 -11
  88. package/dist/lib/upgrade-prior-liveness.js +2 -1
  89. package/dist/mcp-client-assertion.js +7 -14
  90. package/dist/memory-id-checkpoint.js +28 -7
  91. package/dist/mqtt-off-deploy.js +550 -0
  92. package/dist/rem/promote-policy.js +3 -3
  93. package/dist/rem/restore.js +302 -26
  94. package/dist/rem/runner.js +220 -58
  95. package/dist/rem/scheduler.js +21 -4
  96. package/dist/resources/A2AAdapter.js +131 -178
  97. package/dist/resources/AdminMemory.js +2 -0
  98. package/dist/resources/AdminMemoryCandidates.js +116 -0
  99. package/dist/resources/Agent.js +155 -45
  100. package/dist/resources/AgentCard.js +4 -0
  101. package/dist/resources/AgentKeyRegister.js +56 -22
  102. package/dist/resources/AgentReadPosition.js +7 -0
  103. package/dist/resources/AgentSeed.js +232 -107
  104. package/dist/resources/AutoPromoteCandidates.js +413 -84
  105. package/dist/resources/Credential.js +6 -8
  106. package/dist/resources/Federation.js +219 -57
  107. package/dist/resources/FederationRetry.js +4 -4
  108. package/dist/resources/InstructionVersion.js +1 -1
  109. package/dist/resources/MCPClientMetadata.js +6 -3
  110. package/dist/resources/Memory.js +1348 -271
  111. package/dist/resources/MemoryArchive.js +149 -64
  112. package/dist/resources/MemoryBootstrap.js +12 -22
  113. package/dist/resources/MemoryCandidate.js +16 -2
  114. package/dist/resources/MemoryConsolidate.js +2 -2
  115. package/dist/resources/MemoryFeed.js +360 -147
  116. package/dist/resources/MemoryMaintenance.js +290 -72
  117. package/dist/resources/MemoryPurge.js +138 -22
  118. package/dist/resources/MemoryReflect.js +68 -14
  119. package/dist/resources/MemoryReindex.js +91 -13
  120. package/dist/resources/Message.js +11 -2
  121. package/dist/resources/OAuth.js +156 -39
  122. package/dist/resources/OAuthClient.js +1 -1
  123. package/dist/resources/OrgEvent.js +292 -29
  124. package/dist/resources/OrgEventCatchup.js +7 -0
  125. package/dist/resources/OrgEventMaintenance.js +48 -10
  126. package/dist/resources/PairingToken.js +1 -1
  127. package/dist/resources/Presence.js +31 -11
  128. package/dist/resources/PromoteMemoryCandidate.js +8 -2
  129. package/dist/resources/RecordUsage.js +2 -4
  130. package/dist/resources/Soul.js +2 -0
  131. package/dist/resources/SoulFeed.js +2 -1
  132. package/dist/resources/WorkspaceLatest.js +4 -0
  133. package/dist/resources/XAA.js +36 -10
  134. package/dist/resources/a2a-stream.js +313 -0
  135. package/dist/resources/a2a-url.js +4 -5
  136. package/dist/resources/agent-admin.js +10 -1
  137. package/dist/resources/agent-auth.js +98 -68
  138. package/dist/resources/agent-read-position-lib.js +4 -1
  139. package/dist/resources/agent-status-guard.js +9 -7
  140. package/dist/resources/auth-middleware.js +166 -42
  141. package/dist/resources/authority-field-guard.js +9 -11
  142. package/dist/resources/auto-promote-lib.js +8 -5
  143. package/dist/resources/basic-auth-header.js +21 -0
  144. package/dist/resources/bm25-index-service.js +4 -5
  145. package/dist/resources/dedup-cluster.js +6 -1
  146. package/dist/resources/embeddings-provider.js +25 -0
  147. package/dist/resources/federation-classify.js +89 -0
  148. package/dist/resources/federation-retry-lib.js +6 -81
  149. package/dist/resources/health.js +75 -19
  150. package/dist/resources/host-pointer/registry.js +29 -0
  151. package/dist/resources/host-pointer-adapter.js +1 -0
  152. package/dist/resources/in-process-api.js +74 -11
  153. package/dist/resources/in-process.js +24 -22
  154. package/dist/resources/instruction-version-record.js +251 -7
  155. package/dist/resources/internal-authority.js +13 -0
  156. package/dist/resources/mcp-client-metadata-fields.js +4 -0
  157. package/dist/resources/mcp-handler.js +146 -13
  158. package/dist/resources/mcp-oauth-flag.js +12 -14
  159. package/dist/resources/mcp-oauth.js +446 -53
  160. package/dist/resources/mcp-tool-scopes.js +69 -0
  161. package/dist/resources/mcp-tools.js +70 -22
  162. package/dist/resources/memory-declared-attributes.js +1 -0
  163. package/dist/resources/memory-embed-hash.js +56 -0
  164. package/dist/resources/memory-host-source.js +5 -2
  165. package/dist/resources/memory-reflect-lib.js +1 -1
  166. package/dist/resources/memory-write-lock.js +202 -23
  167. package/dist/resources/memory-write-response.js +1 -1
  168. package/dist/resources/memory-write-transaction.js +243 -0
  169. package/dist/resources/migration-boot.js +17 -12
  170. package/dist/resources/migrations/boot-progress.js +25 -0
  171. package/dist/resources/migrations/data-dir.js +16 -3
  172. package/dist/resources/migrations/dir-safety.js +60 -2
  173. package/dist/resources/migrations/embedding-stamp.js +315 -49
  174. package/dist/resources/migrations/graph-heal.js +9 -2
  175. package/dist/resources/migrations/ledger.js +5 -2
  176. package/dist/resources/migrations/lock.js +867 -80
  177. package/dist/resources/migrations/progress.js +71 -10
  178. package/dist/resources/migrations/runner.js +212 -18
  179. package/dist/resources/migrations/state.js +36 -1
  180. package/dist/resources/migrations/status.js +2 -13
  181. package/dist/resources/migrations/synthetic-test-migration.js +78 -12
  182. package/dist/resources/migrations/types.js +26 -1
  183. package/dist/resources/migrations/visibility-backfill.js +111 -70
  184. package/dist/resources/oauth-discovery.js +0 -5
  185. package/dist/resources/object-body-guard.js +12 -5
  186. package/dist/resources/org-event-reserved.js +92 -0
  187. package/dist/resources/org-event-write-fault.js +19 -0
  188. package/dist/resources/owner-field-guard.js +1 -1
  189. package/dist/resources/owner-scoped-write-policy.js +65 -21
  190. package/dist/resources/owner-scoped-writes.js +37 -6
  191. package/dist/resources/path-id-rewrite.js +76 -0
  192. package/dist/resources/presence-internal.js +5 -5
  193. package/dist/resources/promotion-binding.js +43 -0
  194. package/dist/resources/promotion-stamp.js +124 -33
  195. package/dist/resources/protocol-context.js +189 -0
  196. package/dist/resources/record-type-kit.js +2 -4
  197. package/dist/resources/request-target.js +28 -1
  198. package/dist/resources/request-transaction.js +11 -1
  199. package/dist/resources/seed-reservation.js +1 -2
  200. package/dist/resources/semantic-retrieval-core.js +7 -6
  201. package/dist/resources/server-row-validation.js +71 -0
  202. package/dist/resources/skill-manifest.js +4 -3
  203. package/dist/resources/skill-version-write.js +400 -27
  204. package/dist/resources/skill-write-fault.js +6 -3
  205. package/dist/resources/skill-write-policy.js +2 -1
  206. package/dist/resources/soul-write-policy.js +26 -7
  207. package/dist/resources/table-helpers.js +1 -1
  208. package/dist/resources/table-subscription-policy.js +518 -85
  209. package/dist/resources/table-subscriptions.js +20 -7
  210. package/dist/resources/txn-pause-point.js +122 -5
  211. package/dist/resources/usage-recording.js +54 -46
  212. package/dist/resources/write-back.js +176 -11
  213. package/dist/resources/write-journal-context.js +5 -0
  214. package/dist/resources/write-journal.js +289 -0
  215. package/dist/src/keystore.js +77 -10
  216. package/dist/src/lib/agent-id-rule.js +44 -2
  217. package/dist/src/lib/atomic-write.js +3 -3
  218. package/dist/src/lib/federation-retry-row.js +101 -0
  219. package/dist/src/lib/instruction-event-contract.js +17 -0
  220. package/dist/src/lib/key-dir.js +203 -0
  221. package/dist/src/lib/memory-attributes.js +2 -0
  222. package/dist/src/lib/open-live-row.js +20 -0
  223. package/dist/src/lib/scheduler-platform.js +13 -0
  224. package/dist/src/lib/soul-scope-fields.js +26 -0
  225. package/dist/src/rem/promote-policy.js +3 -3
  226. package/dist/src/rem/scheduler.js +21 -4
  227. package/docs/access-control.md +39 -21
  228. package/docs/api-reference.md +161 -52
  229. package/docs/auth.md +69 -38
  230. package/docs/claude-code.md +3 -3
  231. package/docs/deploying-on-fabric.md +118 -2
  232. package/docs/deployment.md +17 -0
  233. package/docs/embedding-in-a-harper-app.md +23 -21
  234. package/docs/entity-vocabulary.md +7 -11
  235. package/docs/federation.md +29 -2
  236. package/docs/hosted-on-fabric.md +1 -1
  237. package/docs/integrations.md +11 -11
  238. package/docs/mcp-clients.md +7 -5
  239. package/docs/notes/mcp-agent-auth-consumer.md +4 -9
  240. package/docs/notes/mcp-oauth-model2.md +6 -6
  241. package/docs/openclaw.md +1 -1
  242. package/docs/quickstart-fabric.md +2 -2
  243. package/docs/quickstart.md +3 -3
  244. package/docs/releasing.md +13 -13
  245. package/docs/rem.md +24 -3
  246. package/docs/secrets-and-keys.md +9 -14
  247. package/docs/standalone-local.md +29 -2
  248. package/docs/supply-chain-policy.md +28 -20
  249. package/docs/the-team.md +2 -2
  250. package/docs/upgrade.md +29 -5
  251. package/package.json +18 -11
  252. package/schemas/agent.graphql +3 -3
  253. package/schemas/federation.graphql +10 -7
  254. package/schemas/memory.graphql +7 -2
  255. package/templates/bin/flair-rem-nightly.sh.tmpl +7 -1
  256. package/templates/launchd/start-flair-with-admin-pass.sh +188 -10
  257. package/dist/resources/soul-adk-guard.js +0 -68
@@ -1,5 +1,5 @@
1
1
  import { databases } from "harper";
2
- import { resolveAgentAuth, allowVerified, allowAdmin, invalidateAdminCache } from "./agent-auth.js";
2
+ import { resolveAgentAuth, allowVerified, allowAdmin } from "./agent-auth.js";
3
3
  import { agentRecordIsAdmin, reconcileAdminFields } from "./agent-admin.js";
4
4
  import { admitPrincipalWrite, statusWriteRefusal } from "./agent-status-guard.js";
5
5
  import { applyFederationBookkeeping, applyOriginatorInstanceId, dropClientFederationBookkeeping, resolveStoredRow, stampOriginatorOnCreate } from "./originator-instance.js";
@@ -8,6 +8,20 @@ import { AGENT_ID_ERROR, invalidAgentIdMessage, isValidAgentId } from "../src/li
8
8
  import { AGENT_HOME_STAMP_FIELD, AGENT_PRINCIPAL_WRITE_BACK_FIELD, AGENT_PRINCIPAL_WRITE_BACK_NO_ROW_ERROR, isForeignAgentHome, isHomeLessAgentRow, isSyncOriginatedAgentRow, pickPrincipalWriteBackFields } from "../src/lib/agent-home-fields.js";
9
9
  import { withOwnedTransaction } from "./request-transaction.js";
10
10
  import { txnPausePoint } from "./txn-pause-point.js";
11
+ /** The resource's URL-bound target id (`getId()`), or null when it has none
12
+ * (an in-process call on a collection resource) or the id is not a scalar. */
13
+ function urlBoundId(resource) {
14
+ try {
15
+ const getId = resource?.getId;
16
+ const id = typeof getId === "function" ? getId.call(resource) : undefined;
17
+ if (typeof id === "string" || typeof id === "number")
18
+ return id;
19
+ }
20
+ catch {
21
+ /* getId() threw — no URL-bound target */
22
+ }
23
+ return null;
24
+ }
11
25
  /**
12
26
  * The id this write lands on: the URL-bound target (`getId()`) when there is
13
27
  * one, otherwise the body `id` (an in-process call, where the body id IS the
@@ -16,15 +30,9 @@ import { txnPausePoint } from "./txn-pause-point.js";
16
30
  * is absent. A non-scalar target is ignored.
17
31
  */
18
32
  function writeTargetId(resource, content) {
19
- try {
20
- const getId = resource?.getId;
21
- const id = typeof getId === "function" ? getId.call(resource) : undefined;
22
- if (typeof id === "string" || typeof id === "number")
23
- return { present: true, value: id };
24
- }
25
- catch {
26
- /* getId() threw — fall back to the body id below */
27
- }
33
+ const bound = urlBoundId(resource);
34
+ if (bound !== null)
35
+ return { present: true, value: bound };
28
36
  if (content != null && typeof content === "object" && "id" in content && content.id !== undefined) {
29
37
  return { present: true, value: content.id };
30
38
  }
@@ -89,9 +97,11 @@ class PrincipalWriteBackAborted extends Error {
89
97
  */
90
98
  export class Agent extends databases.flair.Agent {
91
99
  // Self-authorize now that the global gate is non-rejecting. Verified agents read
92
- // the principal table for discovery; an agent updates only its OWN record (put
93
- // handler enforces ownership). Creating/deleting principals is admin-only
94
- // (flair_agent grant: insert=false, delete=false). Anonymous denied throughout.
100
+ // the principal table for discovery. An agent that is not an administrator
101
+ // updates only its OWN record, with PATCH (the patch handler enforces
102
+ // ownership); an Agent PUT is an administrator operation (put() refuses any
103
+ // other caller). Creating/deleting principals is admin-only (flair_agent
104
+ // grant: insert=false, delete=false). Anonymous denied throughout.
95
105
  allowRead() { return allowVerified(this.getContext?.()); }
96
106
  allowCreate() { return allowAdmin(this.getContext?.()); }
97
107
  allowUpdate() { return allowVerified(this.getContext?.()); }
@@ -139,6 +149,9 @@ export class Agent extends databases.flair.Agent {
139
149
  * It lives in one place because it previously lived only in put(), and PATCH
140
150
  * does not route through put() — so every rule written here was enforced on
141
151
  * one verb and not the other. Returns a Response to send, or null to proceed.
152
+ * put() refuses a caller that is not an administrator before calling this
153
+ * (an Agent PUT is an administrator operation), so the per-record rules
154
+ * below decide a non-admin PATCH.
142
155
  *
143
156
  * Three rules:
144
157
  * 1. Only an admin principal may modify a principal OTHER than itself.
@@ -188,15 +201,19 @@ export class Agent extends databases.flair.Agent {
188
201
  status: 403, headers: { "content-type": "application/json" },
189
202
  });
190
203
  }
191
- // 2. Only admin principals can change admin status. Compare the RESULTING
192
- // status against the stored one so an ordinary self-update that simply
193
- // doesn't mention either field is unaffected, and a no-op restatement of
194
- // the caller's existing status is not a spurious denial.
204
+ // 2. Only admin principals can change admin status. Both sides of the
205
+ // comparison read the AUTHORITY, `role` (resources/agent-admin.ts), never
206
+ // the `admin` mirror: the role of the row read above, against the role
207
+ // that row would have once the body is merged onto it and reconciled
208
+ // (reconcileAdminFields turns `admin: true` into `role: "admin"`), which is
209
+ // how patch() reconciles. An ordinary self-update that names neither field
210
+ // is unaffected, and a write whose reconciled role keeps the read row's
211
+ // authority is admitted. For a change an administrator commits after this
212
+ // read, see patch().
195
213
  const touchesPrivilegeFields = content != null && typeof content === "object" && ("role" in content || "admin" in content);
196
214
  if (touchesPrivilegeFields) {
197
- const merged = { ...(existing ?? {}), ...content };
198
- const wouldBeAdmin = agentRecordIsAdmin(merged) || merged.admin === true;
199
- const isAdminNow = agentRecordIsAdmin(existing) || (existing?.admin === true);
215
+ const isAdminNow = agentRecordIsAdmin(existing);
216
+ const wouldBeAdmin = agentRecordIsAdmin(reconcileAdminFields({ ...(existing ?? {}), ...content }));
200
217
  if (wouldBeAdmin !== isAdminNow) {
201
218
  return new Response(JSON.stringify({ error: "only admin principals can change a principal's admin status" }), {
202
219
  status: 403, headers: { "content-type": "application/json" },
@@ -207,35 +224,115 @@ export class Agent extends databases.flair.Agent {
207
224
  }
208
225
  async put(content) {
209
226
  // flair#2359 — refuse an id outside the shared rule before any read or
210
- // write. A PUT to a new id is a create (Harper's put is an upsert).
227
+ // write.
211
228
  const idDenial = agentIdDenial(writeTargetId(this, content));
212
229
  if (idDenial)
213
230
  return idDenial;
231
+ // An Agent PUT is an administrator operation (flair#2696). It is a full
232
+ // replacement. The server sets these fields, whatever the body says: the
233
+ // id is the URL's target (a trusted in-process call with no URL target uses
234
+ // its body id); createdAt, publicKey, originatorInstanceId and
235
+ // the receiver federation fields (_originatorInstanceId, _syncedFrom,
236
+ // _syncedAt) are carried from the stored row; updatedAt is set here; and
237
+ // role and admin are reconciled (an admin role or `admin: true` sets both,
238
+ // otherwise admin is false). Every other field comes from the body, so an
239
+ // ordinary field the body omits (`status` and `role` included) is not kept.
240
+ // An agent that is not an administrator updates its own record with PATCH,
241
+ // which merges the body into the stored row. Only an administrator or a
242
+ // trusted internal call goes past this point; anonymous and unrecognized
243
+ // verdicts are refused (by Harper's allowUpdate()/allowCreate() checks or
244
+ // by authorizePrincipalWrite). "Administrator" is the caller verdict
245
+ // authorizePrincipalWrite uses too: for a signed request, the decision the
246
+ // request gate took from the Agent row it verified the signature against
247
+ // (agentIsAdmin in resources/agent-auth.ts: role "admin" on that row, or an
248
+ // id FLAIR_ADMIN_AGENTS names).
249
+ if (admitPrincipalWrite(await resolveAgentAuth(this.getContext?.())) === "non-admin") {
250
+ return new Response(JSON.stringify({
251
+ error: "agent_put_admin_only",
252
+ message: "an Agent PUT is an administrator operation; to update your own agent record, use PATCH",
253
+ }), { status: 403, headers: { "content-type": "application/json" } });
254
+ }
214
255
  const denial = await this.authorizePrincipalWrite(content);
215
256
  if (denial)
216
257
  return denial;
217
- content.updatedAt = new Date().toISOString();
218
- // Protect immutable fields
219
- delete content.createdAt;
220
- delete content.publicKey; // key rotation goes through dedicated endpoint
221
- // Keep the two admin fields agreeing on disk — see resources/agent-admin.ts.
222
- // Only an admin can have reached here with a privilege change (see
223
- // authorizePrincipalWrite), so this normalises an authorized intent; it
224
- // never manufactures one.
225
- reconcileAdminFields(content);
226
- // Write-time originatorInstanceId — see post() above /
227
- // resources/originator-instance.ts. A CREATE stamps the local id; an
228
- // UPDATE keeps the stored value (a body value never replaces or clears it).
229
- // The row is resolved by the URL-BOUND target id, never a body `id` (Harper
230
- // writes to the URL target); a mismatch or a failed read refuses the write.
258
+ // A PUT updates an EXISTING row (flair#2696). Harper's put is an upsert; an
259
+ // Agent PUT does not create one. 404 is the repo's "not found / use the
260
+ // other route" status (resources/table-patch-policy.ts, resources/Memory.ts's
261
+ // reindex_row_not_found), and the message names POST /AgentSeed, a creation
262
+ // path.
263
+ const requiresExisting = () => new Response(JSON.stringify({
264
+ error: "agent_put_requires_existing",
265
+ message: "an Agent PUT updates an existing agent; to create an agent, use POST /AgentSeed",
266
+ }), { status: 404, headers: { "content-type": "application/json" } });
267
+ // The stored row, resolved by the write's target id; a body/URL mismatch or
268
+ // a failed read refuses the write, and a missing row is refused.
231
269
  const resolvedOriginRow = await resolveStoredRow(this, "Agent", content, () => super.get());
232
270
  if (resolvedOriginRow.denial)
233
271
  return resolvedOriginRow.denial;
234
- await applyOriginatorInstanceId(content, resolvedOriginRow.row);
235
- applyFederationBookkeeping(content, resolvedOriginRow.row);
236
- const result = await super.put(content);
237
- invalidateAdminCache();
238
- return result;
272
+ if (!resolvedOriginRow.row)
273
+ return requiresExisting();
274
+ // Test-only: inert unless the fault-injection env opt-in is set and armed.
275
+ // Holds the PUT after the stored-row read above, before the owned
276
+ // transaction below, so a deletion or a key rotation can commit in between
277
+ // (test/integration/agent-put-race-2696.test.ts).
278
+ const prePause = txnPausePoint("agent-put-pre");
279
+ if (prePause)
280
+ await prePause;
281
+ // The replacement is built and written inside a FRESH OWNED transaction
282
+ // (withOwnedTransaction detaches the request's), from a re-read of the row
283
+ // in that transaction, never from the read above, which a deletion or a key
284
+ // rotation may have overtaken. Harper stamps a transaction's writes with one
285
+ // time, taken at its first read (here, the re-read), and applies the writes
286
+ // to a row in the order of those times:
287
+ // - a deletion or rotation committed before the re-read is SEEN by it: a
288
+ // row the re-read finds absent is refused (the PUT never re-creates it),
289
+ // and the immutable fields are taken from the re-read row
290
+ // (test/integration/agent-put-race-2696.test.ts commits both here);
291
+ // - one whose own transaction takes its time after the re-read carries a
292
+ // later time, so Harper applies it after this write (a deletion stays
293
+ // deleted, a rotated key stands).
294
+ // Not covered: a write whose own transaction took its time before the
295
+ // re-read and commits after it. There is no compare-and-set; per-id
296
+ // serialization is tracked in flair#2478.
297
+ const outcome = await withOwnedTransaction(this.getContext?.(), async (c) => {
298
+ const current = await resolveStoredRow(this, "Agent", content, () => super.get(), c);
299
+ if (current.denial)
300
+ return { kind: "denied", denial: current.denial };
301
+ const stored = current.row;
302
+ if (!stored)
303
+ return { kind: "gone" };
304
+ content.updatedAt = new Date().toISOString();
305
+ // Immutable fields: a full replacement carries the STORED values, ignoring
306
+ // any client-supplied value, the way Integration.put carries its stored
307
+ // createdAt forward. A key is rotated by `flair agent rotate-key`, an
308
+ // `update` through Harper's operations API, not by this PUT.
309
+ content.createdAt = stored.createdAt;
310
+ content.publicKey = stored.publicKey;
311
+ // Keep the two admin fields agreeing on disk — see resources/agent-admin.ts.
312
+ // Only an administrator or a trusted internal call reaches here (see the
313
+ // refusal at the top of put()), so this normalises an authorized intent.
314
+ reconcileAdminFields(content);
315
+ // Write-time originatorInstanceId — see post() above /
316
+ // resources/originator-instance.ts. An UPDATE keeps the stored value (a
317
+ // body value never replaces or clears it).
318
+ await applyOriginatorInstanceId(content, stored);
319
+ applyFederationBookkeeping(content, stored);
320
+ // The resource's write joins the owned transaction: Harper resolves an
321
+ // instance write's transaction from its context at write time. A resource
322
+ // bound to a URL target writes to that target. An in-process call on a
323
+ // collection resource has no URL target, so the write names the body id
324
+ // (the id resolveStoredRow read the row by) as its target explicitly.
325
+ const bound = urlBoundId(this);
326
+ const result = bound !== null
327
+ ? await super.put(content)
328
+ : await super.put(writeTargetId(this, content).value, content);
329
+ return { kind: "written", result };
330
+ });
331
+ if (outcome.kind === "denied")
332
+ return outcome.denial;
333
+ if (outcome.kind === "gone")
334
+ return requiresExisting();
335
+ return outcome.result;
239
336
  }
240
337
  /**
241
338
  * PATCH → Harper's partial update (`Resource.patch(data, query)`; see
@@ -290,6 +387,23 @@ export class Agent extends databases.flair.Agent {
290
387
  return this.applyGuardedPrincipalWriteBack(content);
291
388
  }
292
389
  }
390
+ // Test-only: inert unless the fault-injection env opt-in is set and armed.
391
+ // Holds an ordinary PATCH after authorizePrincipalWrite's read and decision,
392
+ // before the merge below, so an administrator's change can commit in
393
+ // between (test/integration/agent-patch-race-2696.test.ts).
394
+ const prePause = txnPausePoint("agent-patch-pre");
395
+ if (prePause)
396
+ await prePause;
397
+ // The ordinary PATCH reads and writes in the request's transaction. Harper
398
+ // stamps a transaction's writes with one time, taken at its first read
399
+ // (before the pause above), and applies the writes to a row in the order of
400
+ // those times. So a change an administrator commits after that read, from a
401
+ // transaction that takes its time after it, is applied after this PATCH: a
402
+ // role the administrator sets stands over the role reconciled here, and
403
+ // `status`, which a non-admin PATCH cannot name, is not written by it at
404
+ // all. Not covered: a write whose transaction took its time before this
405
+ // request's first read and commits after it (per-id serialization is
406
+ // tracked in flair#2478).
293
407
  if (content != null && typeof content === "object") {
294
408
  // A partial update must not be able to leave the record's two admin
295
409
  // fields disagreeing, so reconcile against the MERGED result rather than
@@ -317,9 +431,7 @@ export class Agent extends databases.flair.Agent {
317
431
  applyFederationBookkeeping(content, resolvedOriginRow.row);
318
432
  content.updatedAt = new Date().toISOString();
319
433
  }
320
- const result = await super.patch(content, query);
321
- invalidateAdminCache();
322
- return result;
434
+ return super.patch(content, query);
323
435
  }
324
436
  /**
325
437
  * The guarded home stamp (flair#2472), the ONE write `flair agent stamp-home
@@ -432,7 +544,6 @@ export class Agent extends databases.flair.Agent {
432
544
  }
433
545
  if (outcome.kind === "no-instance")
434
546
  return noInstance();
435
- invalidateAdminCache();
436
547
  if (outcome.kind === "no-row")
437
548
  return noRow();
438
549
  if (outcome.kind === "ineligible")
@@ -518,7 +629,6 @@ export class Agent extends databases.flair.Agent {
518
629
  return err.reason === "no-row" ? noRow() : immutable();
519
630
  throw err;
520
631
  }
521
- invalidateAdminCache();
522
632
  if (outcome.kind === "no-row")
523
633
  return noRow();
524
634
  if (outcome.kind === "unavailable")
@@ -1,5 +1,6 @@
1
1
  import { Resource, databases } from "harper";
2
2
  import { selectPublicDescription, selectPublicSkills } from "./agentcard-fields.js";
3
+ import { refuseRewrittenAgentId } from "./path-id-rewrite.js";
3
4
  export class AgentCard extends Resource {
4
5
  // Public discovery metadata (per A2A spec, agent cards are intentionally
5
6
  // public). Self-gates as public so it survives the global gate's removal — and
@@ -14,6 +15,9 @@ export class AgentCard extends Resource {
14
15
  if (!agentId) {
15
16
  return new Response(JSON.stringify({ error: "agentId required in path: GET /AgentCard/{agentId}" }), { status: 400, headers: { "Content-Type": "application/json" } });
16
17
  }
18
+ const rewritten = refuseRewrittenAgentId(this.getContext?.(), agentId);
19
+ if (rewritten)
20
+ return rewritten;
17
21
  const agent = await databases.flair.Agent.get(agentId).catch(() => null);
18
22
  if (!agent) {
19
23
  return new Response(JSON.stringify({ error: "agent_not_found", agentId }), {
@@ -8,8 +8,9 @@
8
8
  * row (resources/agent-auth.ts), and a pending row's stored value is the literal
9
9
  * string `pending`, which can never verify — so a pending agent cannot
10
10
  * authenticate as itself. The Agent resource's `allowUpdate()` admits a Basic
11
- * admin, but its PUT and PATCH handlers strip `publicKey` from the body
12
- * (resources/Agent.ts), so neither verb writes the key. Here
11
+ * admin, but its PUT handler carries the STORED `publicKey` into the
12
+ * replacement and its PATCH handler strips `publicKey` from the body
13
+ * (resources/Agent.ts), so neither verb writes a key the body supplies. Here
13
14
  * `allowCreate()` returns true and the handler
14
15
  * decides: it admits only an admin and re-reads the row, failing closed on
15
16
  * absent evidence.
@@ -22,7 +23,8 @@
22
23
  * (resources/write-back.ts) before the commit, and the stored key is read back
23
24
  * AFTER the commit. The lock serializes registrations for that agent within one
24
25
  * Harper process; raw operations-API writes and other processes do not take it.
25
- * A change committed after confirmation and before commit is not seen; a commit-time pending check is a follow-up.
26
+ * The post-commit read-back detects surviving differences in compared fields
27
+ * or identity; a commit-time pending check is a follow-up.
26
28
  * The response is returned only when the read-back is equal.
27
29
  *
28
30
  * Accepted credentials: Basic admin or a verified Ed25519 agent with the admin
@@ -34,19 +36,21 @@ import { isDeepStrictEqual } from "node:util";
34
36
  import { resolveAgentAuth } from "./agent-auth.js";
35
37
  import { withKeyLock } from "./key-lock.js";
36
38
  import { withOwnedTransaction } from "./request-transaction.js";
37
- import { CommittedRowChanged, confirmCommittedRow } from "./write-back.js";
39
+ import { CommittedRowChanged, confirmCommittedRow, verifyCommittedFields } from "./write-back.js";
38
40
  import { txnPausePoint } from "./txn-pause-point.js";
39
41
  import { isPrincipalDeactivated } from "../src/lib/principal-status.js";
40
42
  import { isForeignAgentHome, isSyncOriginatedAgentRow } from "../src/lib/agent-home-fields.js";
41
- import { isValidAgentId, invalidAgentIdMessage } from "../src/lib/agent-id-rule.js";
43
+ import { AGENT_ID_STRING_REMEDY, isValidAgentId, invalidAgentIdMessage, isUnsafeAgentIdWireValue } from "../src/lib/agent-id-rule.js";
42
44
  import { localInstanceId } from "./instance-identity.js";
45
+ import { maybeFaultOrgEventRow } from "./org-event-write-fault.js";
46
+ import { validateServerRow } from "./server-row-validation.js";
43
47
  import { AGENT_KEY_REGISTERED_EVENT, AGENT_KEY_NOT_PENDING, AGENT_INACTIVE, AGENT_NOT_FOUND, AGENT_NOT_LOCAL, PENDING_PUBLIC_KEY, REGISTRATION_CONFLICT, REGISTRATION_REQUEST_INVALID, REGISTRATION_UNAVAILABLE, isCanonicalEd25519Base64url, keyFingerprint, } from "../src/lib/agent-key-register.js";
44
48
  /** The lock namespace for one agent's registration. */
45
49
  const LOCK_NAMESPACE = "flair-agent-key-register";
46
50
  /** Attempts and spacing of the per-agent lock, mirroring the pairing claim. */
47
51
  const LOCK_ATTEMPTS = 40;
48
52
  const LOCK_WAIT_MS = 25;
49
- const jsonRefusal = (status, error, message) => new Response(JSON.stringify({ error, message }), { status, headers: { "content-type": "application/json" } });
53
+ const jsonRefusal = (status, error, message, outcome) => new Response(JSON.stringify({ error, message, ...(outcome ? { outcome } : {}) }), { status, headers: { "content-type": "application/json" } });
50
54
  /** Read a header off either header-object shape Harper hands us. */
51
55
  function readHeader(reqLike, name) {
52
56
  return reqLike?.headers?.get?.(name) ?? reqLike?.headers?.asObject?.[name] ?? "";
@@ -83,11 +87,17 @@ export class AgentKeyRegister extends Resource {
83
87
  const actorId = auth.agentId;
84
88
  // Validate the body.
85
89
  const body = data && typeof data === "object" ? data : {};
86
- const agentId = body.agentId;
90
+ const suppliedAgentId = body.agentId;
87
91
  const publicKey = body.publicKey;
88
- if (!isValidAgentId(agentId)) {
89
- return jsonRefusal(400, REGISTRATION_REQUEST_INVALID, invalidAgentIdMessage(agentId));
92
+ if (isUnsafeAgentIdWireValue(suppliedAgentId)) {
93
+ return jsonRefusal(400, REGISTRATION_REQUEST_INVALID, AGENT_ID_STRING_REMEDY);
90
94
  }
95
+ if (!isValidAgentId(suppliedAgentId)) {
96
+ return jsonRefusal(400, REGISTRATION_REQUEST_INVALID, invalidAgentIdMessage(suppliedAgentId));
97
+ }
98
+ // The rule accepts a number; the Agent row's key and the audit row's
99
+ // agentId are strings, so resolve the id to its string form once.
100
+ const agentId = String(suppliedAgentId);
91
101
  if (!isCanonicalEd25519Base64url(publicKey)) {
92
102
  return jsonRefusal(400, REGISTRATION_REQUEST_INVALID, "publicKey must be a canonical base64url encoding of 32 bytes");
93
103
  }
@@ -142,28 +152,40 @@ export class AgentKeyRegister extends Resource {
142
152
  keyFingerprint: fingerprint,
143
153
  createdAt: now,
144
154
  }, c);
145
- await events.put({
155
+ const event = {
146
156
  id: `${actorId}-${now}-${registrationId}`,
147
157
  authorId: actorId,
148
158
  kind: AGENT_KEY_REGISTERED_EVENT,
149
159
  summary: `registered a public key for ${agentId}`,
150
160
  detail: `key fingerprint ${fingerprint}`,
151
- refId: agentId,
161
+ refId: String(agentId),
152
162
  createdAt: now,
153
163
  updatedAt: now,
154
- }, c);
164
+ };
165
+ // Test-only: the hook may corrupt the exact row about to be staged
166
+ // (inert unless a fixture installs one).
167
+ maybeFaultOrgEventRow("agent-key-register", event);
168
+ validateServerRow(events, event);
169
+ await events.put(event, c);
155
170
  // Reject a row difference that persists and is visible at the confirmation read.
156
171
  // A write that restores the original values is not detected.
157
172
  await confirmCommittedRow(table, agentId, (committed) => {
158
173
  const row = asRow(committed);
159
174
  return row !== null && isDeepStrictEqual({ ...row }, basis);
160
175
  });
161
- return { kind: "registered", registrationId, updatedAt: now };
176
+ // Test-only: inert unless the fault-injection env opt-in is set and
177
+ // armed. Holds the registration after its final pre-commit
178
+ // confirmation and before its owned transaction commits, the window
179
+ // where a newer write can discard this write's effect (flair#2656).
180
+ const commitPause = txnPausePoint("agent-key-register-commit");
181
+ if (commitPause)
182
+ await commitPause;
183
+ return { kind: "registered", registrationId, updatedAt: now, basis };
162
184
  }), LOCK_ATTEMPTS, LOCK_WAIT_MS);
163
185
  }
164
186
  catch (err) {
165
187
  if (err instanceof CommittedRowChanged) {
166
- return jsonRefusal(409, REGISTRATION_CONFLICT, "the agent row changed while the key was being registered; nothing was changed");
188
+ return jsonRefusal(409, REGISTRATION_CONFLICT, "the agent row changed while the key was being registered; nothing was changed", "conflict");
167
189
  }
168
190
  // Constant format string + a structured data object (unsafe-formatstring).
169
191
  console.error("[agent-key-register] the registration transaction failed; nothing was changed", { agentId, err });
@@ -198,17 +220,29 @@ export class AgentKeyRegister extends Resource {
198
220
  const readBackPause = txnPausePoint("agent-key-register-read-back");
199
221
  if (readBackPause)
200
222
  await readBackPause;
201
- let readBack;
223
+ // The registration is NON-IDEMPOTENT: it transitions a pending key once and
224
+ // writes a fresh audit row per attempt. Re-planning from a fresh read is
225
+ // unsafe after an unconfirmed commit: it can write another audit row. This
226
+ // handler does not retry; a post-commit mismatch or an unreadable read-back
227
+ // is answered 503 with outcome `unconfirmed`. Its commit is
228
+ // confirmed by commit-specific evidence — the AgentKeyRegistration row this
229
+ // attempt wrote under `registrationId` — together with the staged Agent
230
+ // fields; value equality alone does not name the attempt that committed.
231
+ const readBackVerdict = await verifyCommittedFields(table, agentId, value.basis, { publicKey: registered, updatedAt: value.updatedAt });
232
+ let registrationRow;
233
+ let registrationReadable = true;
202
234
  try {
203
- readBack = asRow(await table.get(agentId, {}));
235
+ registrationRow = await audit.get(value.registrationId, {});
204
236
  }
205
- catch (err) {
206
- console.error("[agent-key-register] the read-back of the committed key failed", { agentId, err });
207
- return jsonRefusal(503, REGISTRATION_UNAVAILABLE, "the committed key could not be read back; the stored state is unconfirmed");
237
+ catch {
238
+ registrationReadable = false;
239
+ }
240
+ if (readBackVerdict === "unreadable" || !registrationReadable) {
241
+ return jsonRefusal(503, REGISTRATION_UNAVAILABLE, "the committed key or its registration audit row could not be read back; the stored state is unconfirmed", "unconfirmed");
208
242
  }
209
- if (readBack === null || readBack.publicKey !== registered || readBack.updatedAt !== value.updatedAt) {
210
- return jsonRefusal(503, REGISTRATION_UNAVAILABLE, "the committed key could not be read back equal to the registered key; the stored state is unconfirmed");
243
+ if (readBackVerdict !== "shown" || registrationRow == null || registrationRow.agentId !== agentId) {
244
+ return jsonRefusal(503, REGISTRATION_UNAVAILABLE, "the committed key could not be read back as this registration's row and audit; the stored state is unconfirmed", "unconfirmed");
211
245
  }
212
- return new Response(JSON.stringify({ agentId, publicKey: readBack.publicKey, updatedAt: readBack.updatedAt, registrationId: value.registrationId }), { status: 200, headers: { "content-type": "application/json" } });
246
+ return new Response(JSON.stringify({ agentId, publicKey: registered, updatedAt: value.updatedAt, registrationId: value.registrationId }), { status: 200, headers: { "content-type": "application/json" } });
213
247
  }
214
248
  }
@@ -11,6 +11,7 @@ import { Resource } from "harper";
11
11
  import { allowVerified, resolveAgentAuth } from "./agent-auth.js";
12
12
  import { ORG_EVENT_STREAM } from "./agent-read-position-lib.js";
13
13
  import { advanceReadPosition, defaultReadPositionTable, getReadPosition, } from "./agent-read-position.js";
14
+ import { refuseRewrittenAgentId } from "./path-id-rewrite.js";
14
15
  function pathAgentId(pathInfo, resource) {
15
16
  return ((typeof pathInfo === "object" && pathInfo !== null ? pathInfo.id : null) ??
16
17
  (typeof pathInfo === "string" ? pathInfo : null) ??
@@ -45,6 +46,9 @@ export class AgentReadPosition extends Resource {
45
46
  if (!agentId) {
46
47
  return new Response(JSON.stringify({ error: "agentId required in path: GET /AgentReadPosition/{agentId}" }), { status: 400, headers: { "Content-Type": "application/json" } });
47
48
  }
49
+ const rewritten = refuseRewrittenAgentId(this.getContext?.(), agentId);
50
+ if (rewritten)
51
+ return rewritten;
48
52
  if (ownerDenied(auth, agentId))
49
53
  return denyOwner();
50
54
  const stream = queryValue(pathInfo, "stream") || ORG_EVENT_STREAM;
@@ -60,6 +64,9 @@ export class AgentReadPosition extends Resource {
60
64
  if (!agentId) {
61
65
  return new Response(JSON.stringify({ error: "agentId required in path: POST /AgentReadPosition/{agentId}" }), { status: 400, headers: { "Content-Type": "application/json" } });
62
66
  }
67
+ const rewritten = refuseRewrittenAgentId(this.getContext?.(), agentId);
68
+ if (rewritten)
69
+ return rewritten;
63
70
  if (ownerDenied(auth, agentId))
64
71
  return denyOwner();
65
72
  const stream = (content && typeof content === "object" && content.stream) || ORG_EVENT_STREAM;