@tpsdev-ai/flair 0.59.0 → 0.62.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 (259) hide show
  1. package/README.md +4 -4
  2. package/SECURITY.md +36 -0
  3. package/config.yaml +12 -1
  4. package/dist/bridges/builtins/mem0.js +63 -28
  5. package/dist/bridges/runtime/import-runner.js +12 -0
  6. package/dist/bridges/runtime/load-plugin.js +42 -13
  7. package/dist/bridges/runtime/yaml-loader.js +4 -2
  8. package/dist/build-info.json +3 -3
  9. package/dist/cli.js +991 -248
  10. package/dist/commands/agent.js +224 -43
  11. package/dist/commands/attention.js +4 -3
  12. package/dist/commands/backup.js +202 -34
  13. package/dist/commands/bridge.js +172 -119
  14. package/dist/commands/deploy.js +37 -4
  15. package/dist/commands/doctor.js +592 -146
  16. package/dist/commands/export.js +54 -19
  17. package/dist/commands/federation.js +141 -21
  18. package/dist/commands/hook.js +155 -2
  19. package/dist/commands/idp.js +14 -1
  20. package/dist/commands/import.js +7 -3
  21. package/dist/commands/init.js +462 -193
  22. package/dist/commands/integrity.js +388 -0
  23. package/dist/commands/keys.js +247 -58
  24. package/dist/commands/mcp.js +97 -35
  25. package/dist/commands/memory.js +171 -21
  26. package/dist/commands/migrate-harness-memory.js +3 -2
  27. package/dist/commands/orgevent.js +46 -37
  28. package/dist/commands/presence.js +4 -3
  29. package/dist/commands/principal.js +426 -48
  30. package/dist/commands/quality.js +10 -1
  31. package/dist/commands/reembed.js +141 -17
  32. package/dist/commands/relationship.js +2 -1
  33. package/dist/commands/rem.js +56 -18
  34. package/dist/commands/restore.js +101 -61
  35. package/dist/commands/search.js +6 -4
  36. package/dist/commands/service.js +151 -38
  37. package/dist/commands/soul.js +4 -3
  38. package/dist/commands/status.js +43 -5
  39. package/dist/commands/test.js +3 -2
  40. package/dist/commands/upgrade.js +24 -1
  41. package/dist/commands/workspace.js +6 -3
  42. package/dist/component-env.js +31 -41
  43. package/dist/deploy.js +77 -1
  44. package/dist/doctor-client.js +529 -92
  45. package/dist/engine-version-contract.js +1 -0
  46. package/dist/engine-version.js +23 -3
  47. package/dist/federation-verify.js +4 -3
  48. package/dist/hook-install.js +670 -6
  49. package/dist/keystore.js +72 -0
  50. package/dist/lib/action-recall-runtime.js +328 -0
  51. package/dist/lib/agent-home-fields.js +132 -0
  52. package/dist/lib/agent-home.js +427 -0
  53. package/dist/lib/agent-id-rule.js +46 -0
  54. package/dist/lib/agent-roster.js +33 -0
  55. package/dist/lib/auth-resolve.js +49 -16
  56. package/dist/lib/capture-runtime.js +124 -0
  57. package/dist/lib/credential-status-rule.js +78 -0
  58. package/dist/lib/daemon-liveness.js +41 -10
  59. package/dist/lib/doctor-run.js +75 -37
  60. package/dist/lib/durability-copy.js +10 -0
  61. package/dist/lib/embedding-space-doctor.js +75 -0
  62. package/dist/lib/flair-agent-role.js +4 -0
  63. package/dist/lib/hub-url.js +12 -0
  64. package/dist/lib/init-admin-pass.js +88 -12
  65. package/dist/lib/init-listener-environ.js +1 -2
  66. package/dist/lib/init-occupied-listener.js +15 -111
  67. package/dist/lib/init-spawn-attribution.js +73 -0
  68. package/dist/lib/init-tcp-probe.js +33 -0
  69. package/dist/lib/instance-identity-row.js +20 -0
  70. package/dist/lib/launchd-management.js +24 -0
  71. package/dist/lib/listener-table.js +268 -0
  72. package/dist/lib/local-delete-instance.js +27 -0
  73. package/dist/lib/local-instance-pair.js +256 -0
  74. package/dist/lib/mcp-enable.js +1168 -326
  75. package/dist/lib/mcp-oauth-env-core.js +133 -0
  76. package/dist/lib/mcp-oauth-env.js +125 -0
  77. package/dist/lib/mcp-spec.js +17 -1
  78. package/dist/lib/memory-attributes.js +2 -0
  79. package/dist/lib/memory-id-policy.js +46 -0
  80. package/dist/lib/memory-integrity.js +309 -0
  81. package/dist/lib/memory-purge-response.js +20 -0
  82. package/dist/lib/ops-table-count.js +25 -0
  83. package/dist/lib/owned-pins.js +67 -10
  84. package/dist/lib/peer-status.js +27 -0
  85. package/dist/lib/principal-status.js +29 -0
  86. package/dist/lib/process-start-time.js +76 -12
  87. package/dist/lib/proto-safe-record.js +42 -0
  88. package/dist/lib/record-id-path.js +25 -0
  89. package/dist/lib/reembed-server-support.js +66 -0
  90. package/dist/lib/restore-verify.js +104 -0
  91. package/dist/lib/scheduler-platform.js +10 -6
  92. package/dist/lib/secret-keys.js +25 -0
  93. package/dist/lib/secrets-push.js +50 -22
  94. package/dist/lib/skill-seed-pending.js +24 -0
  95. package/dist/lib/skill-seed.js +365 -0
  96. package/dist/lib/stop-start-recovery.js +54 -0
  97. package/dist/lib/using-flair-skill.js +87 -0
  98. package/dist/mcp-client-assertion.js +112 -4
  99. package/dist/memory-id-checkpoint.js +326 -0
  100. package/dist/memory-node-compare.js +207 -0
  101. package/dist/packages/flair-mcp/src/secret-redaction.js +113 -0
  102. package/dist/rem/restore.js +6 -5
  103. package/dist/rem/runner.js +103 -44
  104. package/dist/resources/Agent.js +321 -1
  105. package/dist/resources/AgentKeyRegister.js +214 -0
  106. package/dist/resources/AgentKeyRegistration.js +28 -0
  107. package/dist/resources/AgentSeed.js +10 -4
  108. package/dist/resources/AutoPromoteCandidates.js +7 -1
  109. package/dist/resources/Credential.js +177 -2
  110. package/dist/resources/Federation.js +751 -143
  111. package/dist/resources/FederationRetry.js +140 -0
  112. package/dist/resources/InstructionVersion.js +220 -0
  113. package/dist/resources/Integration.js +300 -25
  114. package/dist/resources/Memory.js +2113 -604
  115. package/dist/resources/MemoryArchive.js +75 -42
  116. package/dist/resources/MemoryBootstrap.js +110 -39
  117. package/dist/resources/MemoryCandidate.js +21 -1
  118. package/dist/resources/MemoryDedupStats.js +30 -1
  119. package/dist/resources/MemoryFeed.js +327 -45
  120. package/dist/resources/MemoryGrant.js +21 -1
  121. package/dist/resources/MemoryMaintenance.js +129 -25
  122. package/dist/resources/MemoryPurge.js +232 -0
  123. package/dist/resources/MemoryReflect.js +7 -2
  124. package/dist/resources/MemoryReindex.js +24 -8
  125. package/dist/resources/Message.js +5 -3
  126. package/dist/resources/OAuth.js +186 -9
  127. package/dist/resources/OrgEvent.js +126 -3
  128. package/dist/resources/Presence.js +144 -49
  129. package/dist/resources/PromoteMemoryCandidate.js +18 -7
  130. package/dist/resources/Relationship.js +23 -0
  131. package/dist/resources/SemanticSearch.js +63 -32
  132. package/dist/resources/Soul.js +189 -76
  133. package/dist/resources/TeamDirectory.js +35 -0
  134. package/dist/resources/WorkspaceState.js +21 -1
  135. package/dist/resources/XAA.js +181 -63
  136. package/dist/resources/agent-auth.js +40 -15
  137. package/dist/resources/auth-middleware.js +400 -161
  138. package/dist/resources/ed25519-auth.js +1 -1
  139. package/dist/resources/embedding-space-guard.js +366 -72
  140. package/dist/resources/engine-version-stamp-boot.js +53 -0
  141. package/dist/resources/federation-classify.js +72 -0
  142. package/dist/resources/federation-crypto.js +5 -5
  143. package/dist/resources/federation-retry-lib.js +135 -0
  144. package/dist/resources/grant-visibility.js +135 -0
  145. package/dist/resources/harper-routing.js +83 -0
  146. package/dist/resources/health.js +120 -18
  147. package/dist/resources/host-source-citation.js +49 -0
  148. package/dist/resources/host-source-visibility.js +7 -6
  149. package/dist/resources/instance-create-lock.js +17 -0
  150. package/dist/resources/instance-identity.js +23 -0
  151. package/dist/resources/instruction-version-record.js +343 -0
  152. package/dist/resources/key-lock.js +3 -3
  153. package/dist/resources/mcp-handler.js +36 -8
  154. package/dist/resources/mcp-oauth-env-guard.js +36 -0
  155. package/dist/resources/mcp-oauth.js +23 -6
  156. package/dist/resources/mcp-tool-arguments.js +4 -6
  157. package/dist/resources/mcp-tools.js +128 -19
  158. package/dist/resources/memory-bootstrap-lib.js +5 -15
  159. package/dist/resources/memory-declared-attributes.js +3 -1
  160. package/dist/resources/memory-deletion-history.js +55 -0
  161. package/dist/resources/memory-durability.js +54 -0
  162. package/dist/resources/memory-embed-hash.js +88 -0
  163. package/dist/resources/memory-embedding-value.js +8 -0
  164. package/dist/resources/memory-host-source.js +27 -5
  165. package/dist/resources/memory-id-guard.js +75 -0
  166. package/dist/resources/memory-redaction.js +236 -0
  167. package/dist/resources/memory-supplied-vector.js +72 -0
  168. package/dist/resources/memory-write-lock.js +310 -0
  169. package/dist/resources/memory-write-response.js +139 -0
  170. package/dist/resources/migrations/data-dir.js +74 -16
  171. package/dist/resources/migrations/dir-safety.js +1 -1
  172. package/dist/resources/migrations/embedding-stamp.js +193 -79
  173. package/dist/resources/migrations/export.js +1 -0
  174. package/dist/resources/migrations/graph-heal.js +18 -25
  175. package/dist/resources/migrations/lock.js +7 -1
  176. package/dist/resources/migrations/snapshot.js +1 -0
  177. package/dist/resources/migrations/source-fields.js +5 -5
  178. package/dist/resources/migrations/synthetic-test-migration.js +14 -11
  179. package/dist/resources/migrations/visibility-backfill.js +29 -29
  180. package/dist/resources/object-body-guard.js +33 -0
  181. package/dist/resources/org-event-created-at.js +133 -0
  182. package/dist/resources/originator-instance.js +39 -7
  183. package/dist/resources/owner-delete-recheck.js +78 -0
  184. package/dist/resources/owner-field-guard.js +39 -5
  185. package/dist/resources/owner-scoped-write-policy.js +212 -0
  186. package/dist/resources/owner-scoped-writes.js +58 -0
  187. package/dist/resources/presence-receipt.js +236 -0
  188. package/dist/resources/promotion-stamp.js +47 -12
  189. package/dist/resources/record-owner-guard.js +74 -26
  190. package/dist/resources/record-types.js +1 -1
  191. package/dist/resources/relay-ops.js +78 -6
  192. package/dist/resources/replay-store.js +96 -19
  193. package/dist/resources/request-target.js +136 -0
  194. package/dist/resources/request-transaction.js +35 -0
  195. package/dist/resources/search-readiness.js +4 -1
  196. package/dist/resources/seed-ids.js +9 -0
  197. package/dist/resources/seed-reservation.js +117 -0
  198. package/dist/resources/semantic-retrieval-core.js +20 -9
  199. package/dist/resources/skill-manifest.js +20 -11
  200. package/dist/resources/skill-subject.js +53 -0
  201. package/dist/resources/skill-version-write.js +432 -0
  202. package/dist/resources/skill-write-fault.js +17 -0
  203. package/dist/resources/skill-write-policy.js +67 -0
  204. package/dist/resources/skill-write.js +67 -7
  205. package/dist/resources/table-helpers.js +10 -7
  206. package/dist/resources/team-directory.js +248 -0
  207. package/dist/resources/tool-descriptors/index.js +69 -8
  208. package/dist/resources/txn-pause-point.js +118 -0
  209. package/dist/resources/usage-recording.js +171 -63
  210. package/dist/resources/write-back.js +218 -0
  211. package/dist/src/engine-version-contract.js +1 -0
  212. package/dist/src/keystore.js +72 -0
  213. package/dist/src/lib/agent-home-fields.js +132 -0
  214. package/dist/src/lib/agent-id-rule.js +46 -0
  215. package/dist/src/lib/agent-key-register.js +80 -0
  216. package/dist/src/lib/atomic-write.js +256 -0
  217. package/dist/src/lib/credential-status-rule.js +78 -0
  218. package/dist/src/lib/expired-by-agent.js +37 -0
  219. package/dist/src/lib/flair-agent-role.js +4 -0
  220. package/dist/src/lib/idp-mapping-rule.js +81 -0
  221. package/dist/src/lib/instance-identity-row.js +20 -0
  222. package/dist/src/lib/mcp-oauth-env-core.js +133 -0
  223. package/dist/src/lib/memory-attributes.js +2 -0
  224. package/dist/src/lib/memory-id-policy.js +46 -0
  225. package/dist/src/lib/principal-status.js +29 -0
  226. package/dist/src/lib/proto-safe-record.js +42 -0
  227. package/dist/src/lib/reembed-server-support.js +66 -0
  228. package/dist/src/lib/scheduler-platform.js +10 -6
  229. package/dist/src/lib/systemd-agent-id.js +38 -0
  230. package/docs/access-control.md +146 -45
  231. package/docs/api-reference.md +46 -11
  232. package/docs/auth.md +6 -12
  233. package/docs/bridges.md +11 -0
  234. package/docs/claude-code.md +34 -4
  235. package/docs/deploying-on-fabric.md +70 -0
  236. package/docs/deployment.md +2 -0
  237. package/docs/embedding-in-a-harper-app.md +1 -1
  238. package/docs/federation.md +33 -2
  239. package/docs/hosted-on-fabric.md +43 -36
  240. package/docs/integrations.md +5 -5
  241. package/docs/mcp-clients.md +5 -2
  242. package/docs/n8n.md +17 -11
  243. package/docs/notes/mcp-agent-auth-consumer.md +12 -4
  244. package/docs/notes/mcp-oauth-model2.md +34 -5
  245. package/docs/quickstart-fabric.md +2 -2
  246. package/docs/quickstart.md +9 -1
  247. package/docs/releasing.md +12 -6
  248. package/docs/rem.md +8 -0
  249. package/docs/secrets-and-keys.md +19 -2
  250. package/docs/standalone-local.md +1 -0
  251. package/docs/supply-chain-policy.md +13 -3
  252. package/docs/upgrade.md +32 -6
  253. package/package.json +10 -5
  254. package/schemas/agent-key-registration.graphql +22 -0
  255. package/schemas/agent.graphql +3 -0
  256. package/schemas/federation.graphql +38 -1
  257. package/schemas/memory.graphql +84 -5
  258. package/schemas/oauth.graphql +19 -0
  259. package/schemas/schema.graphql +2 -0
@@ -2,7 +2,75 @@ import { databases } from "harper";
2
2
  import { resolveAgentAuth, allowVerified, allowAdmin, invalidateAdminCache } from "./agent-auth.js";
3
3
  import { agentRecordIsAdmin, reconcileAdminFields } from "./agent-admin.js";
4
4
  import { admitPrincipalWrite, statusWriteRefusal } from "./agent-status-guard.js";
5
- import { applyOriginatorInstanceId, resolveStoredRow, stampOriginatorOnCreate } from "./originator-instance.js";
5
+ import { applyFederationBookkeeping, applyOriginatorInstanceId, dropClientFederationBookkeeping, resolveStoredRow, stampOriginatorOnCreate } from "./originator-instance.js";
6
+ import { currentInstanceId, localInstanceId } from "./instance-identity.js";
7
+ import { AGENT_ID_ERROR, invalidAgentIdMessage, isValidAgentId } from "../src/lib/agent-id-rule.js";
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
+ import { withOwnedTransaction } from "./request-transaction.js";
10
+ import { txnPausePoint } from "./txn-pause-point.js";
11
+ /**
12
+ * The id this write lands on: the URL-bound target (`getId()`) when there is
13
+ * one, otherwise the body `id` (an in-process call, where the body id IS the
14
+ * write key). `present` is true only when an id was SUPPLIED — a body carrying
15
+ * an `id` key whose value is `null` is present, while a body with no `id` key
16
+ * is absent. A non-scalar target is ignored.
17
+ */
18
+ 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
+ }
28
+ if (content != null && typeof content === "object" && "id" in content && content.id !== undefined) {
29
+ return { present: true, value: content.id };
30
+ }
31
+ return { present: false, value: undefined };
32
+ }
33
+ /** A 400 refusing a SUPPLIED agent id outside the shared rule, before anything
34
+ * is written. An ABSENT id is allowed: a collection POST with no `id` key lets
35
+ * Harper generate one (a UUID, which matches the rule), and a PUT/PATCH with
36
+ * neither a URL target nor a body id has no id to validate. A body that
37
+ * supplies `id: null` is present and refused — null is not an id. */
38
+ function agentIdDenial(target) {
39
+ if (!target.present)
40
+ return null;
41
+ if (isValidAgentId(target.value))
42
+ return null;
43
+ return new Response(JSON.stringify({ error: AGENT_ID_ERROR, message: invalidAgentIdMessage(target.value) }), { status: 400, headers: { "content-type": "application/json" } });
44
+ }
45
+ /**
46
+ * Thrown INSIDE the guarded home stamp's owned transaction to ABORT it when the
47
+ * confirmation read finds the committed row no longer eligible (it gained a home
48
+ * or provenance) or gone. Aborting discards the staged write; the caller maps the
49
+ * reason to the response. See Agent.applyGuardedHomeStamp (flair#2472).
50
+ */
51
+ class AgentHomeStampAborted extends Error {
52
+ reason;
53
+ constructor(reason) {
54
+ super(`agent home stamp aborted: ${reason}`);
55
+ this.reason = reason;
56
+ this.name = "AgentHomeStampAborted";
57
+ }
58
+ }
59
+ /**
60
+ * Thrown INSIDE the guarded principal write-back's owned transaction to ABORT it
61
+ * when the confirmation read finds the committed row no longer eligible: its home
62
+ * differs from the resolved local ID at that read, or the row is gone. Aborting
63
+ * discards the staged write; the caller maps the reason to the response. See
64
+ * Agent.applyGuardedPrincipalWriteBack (flair#2473).
65
+ */
66
+ class PrincipalWriteBackAborted extends Error {
67
+ reason;
68
+ constructor(reason) {
69
+ super(`agent principal write-back aborted: ${reason}`);
70
+ this.reason = reason;
71
+ this.name = "PrincipalWriteBackAborted";
72
+ }
73
+ }
6
74
  /**
7
75
  * Agent resource — serves as the Principal table in 1.0.
8
76
  *
@@ -29,6 +97,11 @@ export class Agent extends databases.flair.Agent {
29
97
  allowUpdate() { return allowVerified(this.getContext?.()); }
30
98
  allowDelete() { return allowAdmin(this.getContext?.()); }
31
99
  async post(content, context) {
100
+ // flair#2359 — the ONE agent-ID rule, before any field is defaulted or
101
+ // written. A create must never store an id AgentSeed would refuse.
102
+ const idDenial = agentIdDenial(writeTargetId(this, content));
103
+ if (idDenial)
104
+ return idDenial;
32
105
  const now = new Date().toISOString();
33
106
  // Backward compat: set type for legacy code
34
107
  content.type ||= "agent";
@@ -57,6 +130,7 @@ export class Agent extends databases.flair.Agent {
57
130
  // contract (create/update rule; the federation merge path is the raw
58
131
  // table writer and never consults a body).
59
132
  await stampOriginatorOnCreate(content);
133
+ dropClientFederationBookkeeping(content);
60
134
  return super.post(content, context);
61
135
  }
62
136
  /**
@@ -132,6 +206,11 @@ export class Agent extends databases.flair.Agent {
132
206
  return null;
133
207
  }
134
208
  async put(content) {
209
+ // 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).
211
+ const idDenial = agentIdDenial(writeTargetId(this, content));
212
+ if (idDenial)
213
+ return idDenial;
135
214
  const denial = await this.authorizePrincipalWrite(content);
136
215
  if (denial)
137
216
  return denial;
@@ -153,6 +232,7 @@ export class Agent extends databases.flair.Agent {
153
232
  if (resolvedOriginRow.denial)
154
233
  return resolvedOriginRow.denial;
155
234
  await applyOriginatorInstanceId(content, resolvedOriginRow.row);
235
+ applyFederationBookkeeping(content, resolvedOriginRow.row);
156
236
  const result = await super.put(content);
157
237
  invalidateAdminCache();
158
238
  return result;
@@ -174,9 +254,42 @@ export class Agent extends databases.flair.Agent {
174
254
  * Both verbs now share authorizePrincipalWrite().
175
255
  */
176
256
  async patch(content, query) {
257
+ // flair#2359 — refuse an id outside the shared rule before any read or
258
+ // write.
259
+ const idDenial = agentIdDenial(writeTargetId(this, content));
260
+ if (idDenial)
261
+ return idDenial;
177
262
  const denial = await this.authorizePrincipalWrite(content);
178
263
  if (denial)
179
264
  return denial;
265
+ // flair#2472 — the guarded home stamp, the write `flair agent stamp-home
266
+ // --apply` sends. This is NOT an ordinary merge: it decides and writes
267
+ // inside a FRESH OWNED transaction (see applyGuardedHomeStamp), never from
268
+ // the request's pinned read snapshot. Handled before the generic merge so
269
+ // it does not stamp a row that its owned read or its confirmation read sees
270
+ // with a home or provenance, and does not re-create a row either read finds
271
+ // absent.
272
+ if (content != null && typeof content === "object" && content[AGENT_HOME_STAMP_FIELD] === true) {
273
+ delete content[AGENT_HOME_STAMP_FIELD];
274
+ return this.applyGuardedHomeStamp(content);
275
+ }
276
+ // flair#2473 — the guarded write-back `flair principal add` sends when its
277
+ // create-only insert was SKIPPED: the row exists, so the record is written
278
+ // back WITHOUT the home field. It runs in a FRESH OWNED transaction (see
279
+ // applyGuardedPrincipalWriteBack) and refuses when its owned read or its
280
+ // confirmation read sees a stored home differing from the resolved local ID.
281
+ //
282
+ // Any admitted administrator or trusted internal caller can send the flag.
283
+ // It writes only the allow-list in applyGuardedPrincipalWriteBack.
284
+ // Admitted non-admin callers follow the ordinary PATCH path, which strips
285
+ // a client-supplied home and federation bookkeeping.
286
+ if (content != null && typeof content === "object" && content[AGENT_PRINCIPAL_WRITE_BACK_FIELD] === true) {
287
+ delete content[AGENT_PRINCIPAL_WRITE_BACK_FIELD];
288
+ const admission = admitPrincipalWrite(await resolveAgentAuth(this.getContext?.()));
289
+ if (admission === "admin" || admission === "internal") {
290
+ return this.applyGuardedPrincipalWriteBack(content);
291
+ }
292
+ }
180
293
  if (content != null && typeof content === "object") {
181
294
  // A partial update must not be able to leave the record's two admin
182
295
  // fields disagreeing, so reconcile against the MERGED result rather than
@@ -201,10 +314,217 @@ export class Agent extends databases.flair.Agent {
201
314
  if (resolvedOriginRow.denial)
202
315
  return resolvedOriginRow.denial;
203
316
  await applyOriginatorInstanceId(content, resolvedOriginRow.row);
317
+ applyFederationBookkeeping(content, resolvedOriginRow.row);
204
318
  content.updatedAt = new Date().toISOString();
205
319
  }
206
320
  const result = await super.patch(content, query);
207
321
  invalidateAdminCache();
208
322
  return result;
209
323
  }
324
+ /**
325
+ * The guarded home stamp (flair#2472), the ONE write `flair agent stamp-home
326
+ * --apply` sends. It is decided and applied inside a FRESH OWNED transaction,
327
+ * never from the request's pinned read snapshot.
328
+ *
329
+ * Harper loads `/Agent/:id` before this override runs, so the request context
330
+ * already carries this row in its read snapshot. A decision made from that
331
+ * snapshot is stale: a federation merge or another creator that commits in
332
+ * between is invisible. `withOwnedTransaction` detaches the request's
333
+ * transaction for this call and reads the row in a scope this call OWNS.
334
+ *
335
+ * The rules, evaluated inside that owned transaction:
336
+ * - this instance's own id — never the request body's — is the value stamped.
337
+ * It is read from the CURRENT `Instance` table at the start of the owned
338
+ * transaction (`currentInstanceId`, a fresh read every call — never the
339
+ * process-cached `localInstanceId`, which keeps a successful id after the
340
+ * table changes). If it could not confirm a single canonical Instance row,
341
+ * the write is REFUSED by name
342
+ * (`agent_home_stamp_no_instance`, 409) and nothing is staged;
343
+ * - a row the owned read finds absent is refused (404, `agent_home_stamp_no_row`);
344
+ * a stamp NEVER creates, so a row whose deletion that read sees is not
345
+ * re-created;
346
+ * - a row that is not home-less, or that carries federation-sync provenance,
347
+ * is reported `stamped: false` (a 200, nothing written, no `updatedAt` change);
348
+ * - otherwise the update is STAGED, then the COMMITTED row is re-read in an
349
+ * explicit fresh context (never this transaction's snapshot or its staged
350
+ * write). A row that confirmation read sees with a home or provenance, or
351
+ * sees as gone, ABORTS this owned transaction and discards the staged write.
352
+ *
353
+ * The guarded writes do not use compare-and-set: a home or provenance committed, or a deletion
354
+ * or an `Instance` table change made, after the read that checked it and before
355
+ * this transaction's commit is still not seen (the residual window; per-id
356
+ * serialization is tracked in flair#2478).
357
+ *
358
+ * The CLI reports a row `stamped` only when this resource confirms it applied
359
+ * the stamp (`stamped: true`): a read-back that merely shows this instance's
360
+ * home is not enough — another writer may have set it.
361
+ */
362
+ async applyGuardedHomeStamp(content) {
363
+ const admission = admitPrincipalWrite(await resolveAgentAuth(this.getContext?.()));
364
+ if (admission !== "admin" && admission !== "internal") {
365
+ return new Response(JSON.stringify({ error: "agent_home_stamp_forbidden", message: "the home stamp is an administrator or trusted-internal write" }), { status: 403, headers: { "content-type": "application/json" } });
366
+ }
367
+ const target = writeTargetId(this, content);
368
+ const id = target.present && (typeof target.value === "string" || typeof target.value === "number")
369
+ ? String(target.value)
370
+ : null;
371
+ const noRow = () => new Response(JSON.stringify({ error: "agent_home_stamp_no_row", message: "could not confirm a stored agent row to stamp" }), { status: 404, headers: { "content-type": "application/json" } });
372
+ const ineligible = () => new Response(JSON.stringify({ id, stamped: false, reason: "ineligible" }), { status: 200, headers: { "content-type": "application/json" } });
373
+ if (id === null)
374
+ return noRow();
375
+ // Could not confirm a single canonical Instance row: refuse with nothing staged.
376
+ const noInstance = () => new Response(JSON.stringify({ error: "agent_home_stamp_no_instance", message: "could not confirm a single canonical Instance row to stamp as the home; the row was not written" }), { status: 409, headers: { "content-type": "application/json" } });
377
+ const table = databases.flair?.Agent;
378
+ const readRow = async (context) => {
379
+ if (!table || typeof table.get !== "function")
380
+ return null;
381
+ const row = await table.get(id, context);
382
+ return row && typeof row === "object" && !(row instanceof Response) ? row : null;
383
+ };
384
+ const eligible = (row) => isHomeLessAgentRow(row) && !isSyncOriginatedAgentRow(row);
385
+ const updatedAt = new Date().toISOString();
386
+ let outcome;
387
+ try {
388
+ outcome = await withOwnedTransaction(this.getContext?.(), async (c) => {
389
+ // The value to stamp: this instance's id from the Instance table AS IT IS
390
+ // NOW (a fresh read, never the process cache), resolved BEFORE the
391
+ // eligibility read (flair#2478 pattern) so nothing awaits between that
392
+ // read and the staging, where a writer could commit unseen by the
393
+ // confirmation read.
394
+ const home = await currentInstanceId();
395
+ if (home === null)
396
+ return { kind: "no-instance" };
397
+ const stampBody = { originatorInstanceId: home, updatedAt };
398
+ // The row as this call OWNS it — a scope the request's snapshot does not pin.
399
+ const stored = await readRow(c);
400
+ if (stored === null)
401
+ return { kind: "no-row" };
402
+ if (!eligible(stored))
403
+ return { kind: "ineligible" };
404
+ if (!table || typeof table.update !== "function")
405
+ return { kind: "no-row" };
406
+ // STAGE the write of the home and updatedAt in this transaction's own scope.
407
+ await table.update(id, stampBody, c);
408
+ // Test-only: inert unless the fault-injection env opt-in is set and armed.
409
+ // The name is a DIRECT string literal at the call site (flair#2382's
410
+ // checker scans resources/ and src/ and resolves only literals); it must
411
+ // stay equal to AGENT_HOME_STAMP_PAUSE_POINT, which the integration test
412
+ // arms (test/integration/agent-home-2433.test.ts).
413
+ const pause = txnPausePoint("agent-home-stamp");
414
+ if (pause)
415
+ await pause;
416
+ // CONFIRM the COMMITTED row (an explicit fresh context, never this
417
+ // transaction's snapshot or its staged write) is still eligible. A row
418
+ // that gained a home or provenance, or that is gone, ABORTS this owned
419
+ // transaction: the staged write is discarded and the caller is told.
420
+ const committed = await readRow({});
421
+ if (committed === null)
422
+ throw new AgentHomeStampAborted("no-row");
423
+ if (!eligible(committed))
424
+ throw new AgentHomeStampAborted("ineligible");
425
+ return { kind: "applied" };
426
+ });
427
+ }
428
+ catch (err) {
429
+ if (err instanceof AgentHomeStampAborted)
430
+ return err.reason === "no-row" ? noRow() : ineligible();
431
+ throw err;
432
+ }
433
+ if (outcome.kind === "no-instance")
434
+ return noInstance();
435
+ invalidateAdminCache();
436
+ if (outcome.kind === "no-row")
437
+ return noRow();
438
+ if (outcome.kind === "ineligible")
439
+ return ineligible();
440
+ return new Response(JSON.stringify({ id, stamped: true }), { status: 200, headers: { "content-type": "application/json" } });
441
+ }
442
+ /**
443
+ * The guarded write-back (flair#2473), the ONE write `flair principal add`
444
+ * sends when its create-only `insert` was SKIPPED because the row already
445
+ * exists. It runs inside a FRESH OWNED transaction, never from the request's
446
+ * pinned read snapshot, and it refuses by name in two cases:
447
+ *
448
+ * - the row is ABSENT (at the owned read before staging, or at the
449
+ * confirmation read): Harper's `table.update` would INSERT a missing row,
450
+ * so a deletion either read sees leaves the table without the row rather
451
+ * than re-creating it home-less (404, `agent_principal_write_back_no_row`);
452
+ * - a non-empty string stored home differs from the resolved local ID
453
+ * (`localInstanceId()`, cached after its first success, or null):
454
+ * the write is refused (`originator_instance_immutable`).
455
+ *
456
+ * The body this path writes is the EXPLICIT ALLOW-LIST
457
+ * (`pickPrincipalWriteBackFields`) plus the write key — never a home and never
458
+ * a federation stamp, whatever the request body carried — so an admitted caller
459
+ * cannot use the flag to change a stored home.
460
+ *
461
+ * The update is STAGED first, then the COMMITTED row is re-read in an explicit
462
+ * fresh context. If that read finds no row or a non-empty home differing from
463
+ * the resolved local ID, it ABORTS this owned transaction and discards the
464
+ * staged write. The guarded writes do not use compare-and-set: a home that changes, or a
465
+ * deletion, after the confirmation and before the commit is still not seen (the
466
+ * residual window; per-id serialization is tracked in flair#2478).
467
+ */
468
+ async applyGuardedPrincipalWriteBack(content) {
469
+ const immutable = () => new Response(JSON.stringify({ error: "originator_instance_immutable", message: "originator_instance_immutable: the stored home differs from the resolved local ID; refusing to change it" }), { status: 409, headers: { "content-type": "application/json" } });
470
+ const unavailable = () => new Response(JSON.stringify({ error: "originator_instance_immutable", message: "could not confirm an eligible agent row for write-back; refusing to change it" }), { status: 409, headers: { "content-type": "application/json" } });
471
+ const noRow = () => new Response(JSON.stringify({ error: AGENT_PRINCIPAL_WRITE_BACK_NO_ROW_ERROR, message: `${AGENT_PRINCIPAL_WRITE_BACK_NO_ROW_ERROR}: could not confirm a stored agent row; the write-back was refused and did not re-create it` }), { status: 404, headers: { "content-type": "application/json" } });
472
+ const target = writeTargetId(this, content);
473
+ const id = target.present && (typeof target.value === "string" || typeof target.value === "number")
474
+ ? String(target.value)
475
+ : null;
476
+ if (id === null)
477
+ return unavailable();
478
+ // Resolve everything that can yield FIRST (flair#2478 pattern) — this
479
+ // instance's own id — so nothing awaits between the eligibility read and the
480
+ // staging. ONLY the allow-listed fields are written back; the body carries no
481
+ // home field, so the stored home stands.
482
+ const home = await localInstanceId();
483
+ const table = databases.flair?.Agent;
484
+ const body = { ...pickPrincipalWriteBackFields(content), id };
485
+ let outcome;
486
+ try {
487
+ outcome = await withOwnedTransaction(this.getContext?.(), async (c) => {
488
+ if (!table || typeof table.get !== "function" || typeof table.update !== "function") {
489
+ return { kind: "unavailable" };
490
+ }
491
+ const stored = await table.get(id, c);
492
+ const storedRow = stored && typeof stored === "object" && !(stored instanceof Response) ? stored : null;
493
+ // Refuse an ABSENT row BEFORE staging: `table.update` would CREATE it, and
494
+ // this write-back must not re-create a row this read finds absent.
495
+ if (storedRow === null)
496
+ return { kind: "no-row" };
497
+ if (isForeignAgentHome(storedRow, home))
498
+ return { kind: "refused" };
499
+ // STAGE the write-back in this transaction's own scope.
500
+ await table.update(id, body, c);
501
+ // Test-only: inert unless the fault-injection env opt-in is set and armed.
502
+ const pause = txnPausePoint("agent-principal-write-back");
503
+ if (pause)
504
+ await pause;
505
+ // CONFIRM the COMMITTED row is present and has no non-empty home differing
506
+ // from the resolved local ID; otherwise abort and discard the staged write.
507
+ const committed = await table.get(id, {});
508
+ const committedRow = committed && typeof committed === "object" && !(committed instanceof Response) ? committed : null;
509
+ if (committedRow === null)
510
+ throw new PrincipalWriteBackAborted("no-row");
511
+ if (isForeignAgentHome(committedRow, home))
512
+ throw new PrincipalWriteBackAborted("foreign");
513
+ return { kind: "applied" };
514
+ });
515
+ }
516
+ catch (err) {
517
+ if (err instanceof PrincipalWriteBackAborted)
518
+ return err.reason === "no-row" ? noRow() : immutable();
519
+ throw err;
520
+ }
521
+ invalidateAdminCache();
522
+ if (outcome.kind === "no-row")
523
+ return noRow();
524
+ if (outcome.kind === "unavailable")
525
+ return unavailable();
526
+ if (outcome.kind === "refused")
527
+ return immutable();
528
+ return new Response(JSON.stringify({ id, writtenBack: true }), { status: 200, headers: { "content-type": "application/json" } });
529
+ }
210
530
  }
@@ -0,0 +1,214 @@
1
+ /**
2
+ * AgentKeyRegister.ts — POST /AgentKeyRegister (flair#2266).
3
+ *
4
+ * Register an agent key. Admin only.
5
+ *
6
+ * A standalone CUSTOM Resource, not a verb on the Agent resource: the ordinary
7
+ * agent-authentication middleware resolves the verification key from the STORED
8
+ * row (resources/agent-auth.ts), and a pending row's stored value is the literal
9
+ * string `pending`, which can never verify — so a pending agent cannot
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
13
+ * `allowCreate()` returns true and the handler
14
+ * decides: it admits only an admin and re-reads the row, failing closed on
15
+ * absent evidence.
16
+ *
17
+ * The write runs under the per-agent lock (resources/key-lock.ts, the pairing
18
+ * composition in resources/Federation.ts) inside ONE owned transaction
19
+ * (resources/request-transaction.ts): a fresh read, the exactly-`pending` /
20
+ * local / non-deactivated checks, then the key, the private audit row and the
21
+ * OrgEvent (`detail`: fingerprint; `refId` and `summary`: target id) are staged together, the COMMITTED Agent row is confirmed
22
+ * (resources/write-back.ts) before the commit, and the stored key is read back
23
+ * AFTER the commit. The lock serializes registrations for that agent within one
24
+ * 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 response is returned only when the read-back is equal.
27
+ *
28
+ * Accepted credentials: Basic admin or a verified Ed25519 agent with the admin
29
+ * annotation. A Harper Bearer token is refused.
30
+ */
31
+ import { Resource, databases } from "harper";
32
+ import { randomUUID } from "node:crypto";
33
+ import { isDeepStrictEqual } from "node:util";
34
+ import { resolveAgentAuth } from "./agent-auth.js";
35
+ import { withKeyLock } from "./key-lock.js";
36
+ import { withOwnedTransaction } from "./request-transaction.js";
37
+ import { CommittedRowChanged, confirmCommittedRow } from "./write-back.js";
38
+ import { txnPausePoint } from "./txn-pause-point.js";
39
+ import { isPrincipalDeactivated } from "../src/lib/principal-status.js";
40
+ import { isForeignAgentHome, isSyncOriginatedAgentRow } from "../src/lib/agent-home-fields.js";
41
+ import { isValidAgentId, invalidAgentIdMessage } from "../src/lib/agent-id-rule.js";
42
+ import { localInstanceId } from "./instance-identity.js";
43
+ 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
+ /** The lock namespace for one agent's registration. */
45
+ const LOCK_NAMESPACE = "flair-agent-key-register";
46
+ /** Attempts and spacing of the per-agent lock, mirroring the pairing claim. */
47
+ const LOCK_ATTEMPTS = 40;
48
+ const LOCK_WAIT_MS = 25;
49
+ const jsonRefusal = (status, error, message) => new Response(JSON.stringify({ error, message }), { status, headers: { "content-type": "application/json" } });
50
+ /** Read a header off either header-object shape Harper hands us. */
51
+ function readHeader(reqLike, name) {
52
+ return reqLike?.headers?.get?.(name) ?? reqLike?.headers?.asObject?.[name] ?? "";
53
+ }
54
+ /** The Harper username on the request, if any; an audit label only. */
55
+ function operatorOf(reqLike) {
56
+ const username = reqLike?.user?.username;
57
+ return typeof username === "string" && username.length > 0 ? username : null;
58
+ }
59
+ /** A stored row from a table read, or null when the read refused / returned no row. */
60
+ function asRow(value) {
61
+ return value && typeof value === "object" && !(value instanceof Response) ? value : null;
62
+ }
63
+ export class AgentKeyRegister extends Resource {
64
+ // Permissive so the handler's admin check answers a verified non-admin an
65
+ // explicit 403 and an anonymous caller an explicit 401, rather than Harper's
66
+ // generic denial.
67
+ allowCreate() {
68
+ return true;
69
+ }
70
+ async post(data) {
71
+ const ctx = this.getContext?.() ?? {};
72
+ const req = ctx.request ?? ctx;
73
+ if (!/^(Basic|TPS-Ed25519)(\s|$)/i.test(readHeader(req, "authorization"))) {
74
+ return jsonRefusal(401, "authentication required", "an admin credential is required to register a key");
75
+ }
76
+ const auth = await resolveAgentAuth(ctx);
77
+ if (auth.kind !== "agent" || !auth.isAdmin) {
78
+ return auth.kind === "anonymous"
79
+ ? jsonRefusal(401, "authentication required", "an admin credential is required to register a key")
80
+ : jsonRefusal(403, "forbidden", "an admin credential is required to register a key");
81
+ }
82
+ // The admin agent id (TPS-Ed25519) or the Harper username (Basic).
83
+ const actorId = auth.agentId;
84
+ // Validate the body.
85
+ const body = data && typeof data === "object" ? data : {};
86
+ const agentId = body.agentId;
87
+ const publicKey = body.publicKey;
88
+ if (!isValidAgentId(agentId)) {
89
+ return jsonRefusal(400, REGISTRATION_REQUEST_INVALID, invalidAgentIdMessage(agentId));
90
+ }
91
+ if (!isCanonicalEd25519Base64url(publicKey)) {
92
+ return jsonRefusal(400, REGISTRATION_REQUEST_INVALID, "publicKey must be a canonical base64url encoding of 32 bytes");
93
+ }
94
+ const registered = publicKey;
95
+ // Resolve the instance ID before the transaction.
96
+ const selfInstanceId = await localInstanceId();
97
+ const table = databases.flair?.Agent;
98
+ const audit = databases.flair?.AgentKeyRegistration;
99
+ const events = databases.flair?.OrgEvent;
100
+ if (!table || typeof table.get !== "function" || typeof table.update !== "function" || !audit || typeof audit.put !== "function" || !events || typeof events.put !== "function") {
101
+ return jsonRefusal(503, REGISTRATION_UNAVAILABLE, "the Agent, AgentKeyRegistration or OrgEvent store is not available on this instance");
102
+ }
103
+ const fingerprint = await keyFingerprint(registered);
104
+ const operator = operatorOf(req);
105
+ let outcome;
106
+ try {
107
+ outcome = await withKeyLock(table.primaryStore, [LOCK_NAMESPACE, agentId], () => withOwnedTransaction(ctx, async (c) => {
108
+ // Fresh read inside the owned transaction.
109
+ const stored = asRow(await table.get(agentId, c));
110
+ if (stored === null)
111
+ return { kind: "not-found" };
112
+ if (isForeignAgentHome(stored, selfInstanceId) || isSyncOriginatedAgentRow(stored))
113
+ return { kind: "not-local" };
114
+ if (isPrincipalDeactivated(stored))
115
+ return { kind: "inactive" };
116
+ if (stored.publicKey !== PENDING_PUBLIC_KEY)
117
+ return { kind: "not-pending" };
118
+ const basis = { ...stored };
119
+ // Test-only: inert unless the fault-injection env opt-in is set and
120
+ // armed. Placed after the fresh read and before the staging, inside
121
+ // this owned transaction, so the concurrency test can hold this
122
+ // registration while a second one runs or a competing write commits.
123
+ // The name is a DIRECT string literal at the call site (flair#2382's
124
+ // checker resolves only literals or `spec.point`); it must stay equal
125
+ // to AGENT_KEY_REGISTER_PAUSE_POINT, which the test arms.
126
+ const pause = txnPausePoint("agent-key-register");
127
+ if (pause)
128
+ await pause;
129
+ const registrationId = randomUUID();
130
+ const now = new Date().toISOString();
131
+ // Stage the key and updatedAt (incremental update: unrelated fields
132
+ // and the stored originator stand).
133
+ await table.update(agentId, { publicKey: registered, updatedAt: now }, c);
134
+ // Stage the private audit row and the OrgEvent in the SAME
135
+ // transaction: all three commit together or none does.
136
+ await audit.put({
137
+ id: registrationId,
138
+ actorId,
139
+ operator,
140
+ agentId,
141
+ instanceId: selfInstanceId,
142
+ keyFingerprint: fingerprint,
143
+ createdAt: now,
144
+ }, c);
145
+ await events.put({
146
+ id: `${actorId}-${now}-${registrationId}`,
147
+ authorId: actorId,
148
+ kind: AGENT_KEY_REGISTERED_EVENT,
149
+ summary: `registered a public key for ${agentId}`,
150
+ detail: `key fingerprint ${fingerprint}`,
151
+ refId: agentId,
152
+ createdAt: now,
153
+ updatedAt: now,
154
+ }, c);
155
+ // Reject a row difference that persists and is visible at the confirmation read.
156
+ // A write that restores the original values is not detected.
157
+ await confirmCommittedRow(table, agentId, (committed) => {
158
+ const row = asRow(committed);
159
+ return row !== null && isDeepStrictEqual({ ...row }, basis);
160
+ });
161
+ return { kind: "registered", registrationId, updatedAt: now };
162
+ }), LOCK_ATTEMPTS, LOCK_WAIT_MS);
163
+ }
164
+ catch (err) {
165
+ if (err instanceof CommittedRowChanged) {
166
+ return jsonRefusal(409, REGISTRATION_CONFLICT, "the agent row changed while the key was being registered; nothing was changed");
167
+ }
168
+ // Constant format string + a structured data object (unsafe-formatstring).
169
+ console.error("[agent-key-register] the registration transaction failed; nothing was changed", { agentId, err });
170
+ return jsonRefusal(503, REGISTRATION_UNAVAILABLE, "the registration could not be completed; nothing was changed");
171
+ }
172
+ if (outcome.kind === "busy") {
173
+ return jsonRefusal(409, REGISTRATION_CONFLICT, "another registration of this agent is in progress; retry");
174
+ }
175
+ if (outcome.kind === "unavailable") {
176
+ return jsonRefusal(503, REGISTRATION_UNAVAILABLE, "this instance's Agent store has no per-key lock, so the registration was refused");
177
+ }
178
+ const value = outcome.value;
179
+ if (value.kind === "not-found") {
180
+ return jsonRefusal(404, AGENT_NOT_FOUND, "no such agent");
181
+ }
182
+ if (value.kind === "not-local") {
183
+ return jsonRefusal(403, AGENT_NOT_LOCAL, "the agent did not originate on this instance, so this instance is not its authority");
184
+ }
185
+ if (value.kind === "inactive") {
186
+ return jsonRefusal(403, AGENT_INACTIVE, "the agent is deactivated");
187
+ }
188
+ if (value.kind === "not-pending") {
189
+ return jsonRefusal(409, AGENT_KEY_NOT_PENDING, "the stored public key is not exactly pending; use the key-rotation path to replace an existing key");
190
+ }
191
+ // value.kind === "registered": read the committed key back and report the
192
+ // result ONLY when it is equal to the key that was registered.
193
+ // Test-only: inert unless the fault-injection env opt-in is set and armed.
194
+ // Placed after the commit and before the read-back, so a test can commit a
195
+ // competing key change in between and assert the read-back refusal. A DIRECT
196
+ // string literal (flair#2382); it must stay equal to
197
+ // AGENT_KEY_REGISTER_READ_BACK_PAUSE_POINT, which the test arms.
198
+ const readBackPause = txnPausePoint("agent-key-register-read-back");
199
+ if (readBackPause)
200
+ await readBackPause;
201
+ let readBack;
202
+ try {
203
+ readBack = asRow(await table.get(agentId, {}));
204
+ }
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");
208
+ }
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");
211
+ }
212
+ return new Response(JSON.stringify({ agentId, publicKey: readBack.publicKey, updatedAt: readBack.updatedAt, registrationId: value.registrationId }), { status: 200, headers: { "content-type": "application/json" } });
213
+ }
214
+ }
@@ -0,0 +1,28 @@
1
+ /**
2
+ * AgentKeyRegistration.ts — the Flair resource route for the key-registration
3
+ * audit log (flair#2266).
4
+ *
5
+ * One row per committed POST /AgentKeyRegister. It carries no secret: its key
6
+ * field is the FINGERPRINT, not the key, and `agentId` is the target agent's
7
+ * id. On this route reads are admin-only and create,
8
+ * update and delete are refused. The registration operation is the table's only
9
+ * application writer, through the raw table in its registration transaction.
10
+ * The Harper operations API is a separate raw-table trust root, not governed
11
+ * here.
12
+ */
13
+ import { databases } from "harper";
14
+ import { allowAdmin } from "./agent-auth.js";
15
+ export class AgentKeyRegistration extends databases.flair.AgentKeyRegistration {
16
+ allowRead() {
17
+ return allowAdmin(this.getContext?.());
18
+ }
19
+ allowCreate() {
20
+ return false;
21
+ }
22
+ allowUpdate() {
23
+ return false;
24
+ }
25
+ allowDelete() {
26
+ return false;
27
+ }
28
+ }
@@ -1,3 +1,4 @@
1
+ import { AGENT_ID_ERROR, invalidAgentIdMessage, isValidAgentId } from "../src/lib/agent-id-rule.js";
1
2
  import { randomUUID } from "node:crypto";
2
3
  /**
3
4
  * POST /AgentSeed
@@ -26,6 +27,7 @@ import { reconcileAdminFields } from "./agent-admin.js";
26
27
  import { noteMemoryUpsert } from "./bm25-index-service.js";
27
28
  import { stripUndeclaredMemoryAttributes, stripServerStampedFields } from "./memory-declared-attributes.js";
28
29
  import { rejectSkillWritePath } from "./skill-write.js";
30
+ import { stampEphemeralExpiry } from "./memory-durability.js";
29
31
  import { stampOriginatorOnCreate } from "./originator-instance.js";
30
32
  import { SKILL_ASSIGNMENT_KEY } from "./skill-provenance.js";
31
33
  const DEFAULT_SOUL_KEYS = (agentId, displayName, role, now) => ({
@@ -59,10 +61,10 @@ export class AgentSeed extends Resource {
59
61
  if (denied)
60
62
  return denied;
61
63
  const { agentId, displayName, role = "agent", soulTemplate, starterMemories } = data || {};
62
- if (!agentId)
63
- return new Response(JSON.stringify({ error: "agentId required" }), { status: 400 });
64
- if (!/^[a-zA-Z0-9_-]{1,64}$/.test(agentId)) {
65
- return new Response(JSON.stringify({ error: "invalid agentId" }), { status: 400 });
64
+ // flair#2359 — the ONE shared agent-ID rule, which refuses an absent id
65
+ // (`undefined`/`null`/empty) exactly as it refuses a malformed one.
66
+ if (!isValidAgentId(agentId)) {
67
+ return new Response(JSON.stringify({ error: AGENT_ID_ERROR, message: invalidAgentIdMessage(agentId) }), { status: 400, headers: { "content-type": "application/json" } });
66
68
  }
67
69
  const now = new Date().toISOString();
68
70
  const name = displayName || agentId;
@@ -186,6 +188,10 @@ export class AgentSeed extends Resource {
186
188
  record.instanceToken = randomUUID();
187
189
  // flair#1965 r2: raw Memory create — stamp the local instance id.
188
190
  await stampOriginatorOnCreate(record);
191
+ // flair#2274: the seed is a Memory writer — give an ephemeral starter
192
+ // memory the tier expiry the shared rule stamps (this raw put bypasses
193
+ // Memory.post()/put()).
194
+ stampEphemeralExpiry(record);
189
195
  await databases.flair.Memory.put(record);
190
196
  noteMemoryUpsert(record);
191
197
  memories.push(record);