@tpsdev-ai/flair 0.62.0 → 0.63.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (232) hide show
  1. package/README.md +6 -6
  2. package/SECURITY.md +18 -10
  3. package/config.yaml +11 -11
  4. package/dist/bridges/runtime/execute.js +1 -0
  5. package/dist/bridges/types.js +1 -0
  6. package/dist/build-info.json +3 -3
  7. package/dist/cli.js +66 -122
  8. package/dist/commands/agent.js +27 -65
  9. package/dist/commands/backup-approval.js +218 -0
  10. package/dist/commands/backup.js +37 -33
  11. package/dist/commands/bootstrap.js +3 -1
  12. package/dist/commands/deploy.js +37 -7
  13. package/dist/commands/doctor.js +119 -0
  14. package/dist/commands/export.js +3 -4
  15. package/dist/commands/federation.js +653 -68
  16. package/dist/commands/grant.js +5 -6
  17. package/dist/commands/help.js +25 -0
  18. package/dist/commands/idp.js +14 -19
  19. package/dist/commands/import.js +131 -19
  20. package/dist/commands/init.js +7 -7
  21. package/dist/commands/integrity.js +5 -6
  22. package/dist/commands/mcp.js +11 -17
  23. package/dist/commands/memory.js +33 -15
  24. package/dist/commands/orgevent.js +5 -10
  25. package/dist/commands/principal.js +13 -25
  26. package/dist/commands/quality.js +3 -0
  27. package/dist/commands/rem.js +484 -65
  28. package/dist/commands/restore.js +352 -44
  29. package/dist/commands/service.js +84 -2
  30. package/dist/commands/soul.js +0 -6
  31. package/dist/commands/status.js +51 -33
  32. package/dist/commands/test.js +4 -1
  33. package/dist/commands/upgrade.js +53 -22
  34. package/dist/commands/workspace.js +7 -8
  35. package/dist/deploy.js +59 -3
  36. package/dist/doctor-client.js +7 -2
  37. package/dist/fabric-upgrade.js +12 -2
  38. package/dist/federation/presence-send.js +139 -0
  39. package/dist/federation-verify.js +269 -177
  40. package/dist/install/clients.js +171 -35
  41. package/dist/lib/agent-id-rule.js +44 -2
  42. package/dist/lib/atomic-write.js +1 -1
  43. package/dist/lib/auth-resolve.js +1028 -52
  44. package/dist/lib/backup-approval-store.js +612 -0
  45. package/dist/lib/backup-artifact.js +343 -0
  46. package/dist/lib/config-critical-section.js +212 -25
  47. package/dist/lib/connect-phase.js +33 -0
  48. package/dist/lib/daemon-liveness.js +2 -1
  49. package/dist/lib/federation-pair-access.js +4 -0
  50. package/dist/lib/federation-retry-queue.js +283 -0
  51. package/dist/lib/federation-retry-row.js +101 -0
  52. package/dist/lib/instruction-event-contract.js +17 -0
  53. package/dist/lib/instruction-event-doctor.js +102 -0
  54. package/dist/lib/launchd-management.js +14 -3
  55. package/dist/lib/mcp-enable.js +14 -15
  56. package/dist/lib/memory-attributes.js +2 -0
  57. package/dist/lib/memory-provider-timeout.js +33 -0
  58. package/dist/lib/mqtt-config.js +132 -0
  59. package/dist/lib/mqtt-listener-doctor.js +104 -0
  60. package/dist/lib/open-live-row.js +20 -0
  61. package/dist/lib/ops-url.js +52 -0
  62. package/dist/lib/promotion-content-hash.js +20 -0
  63. package/dist/lib/restore-archive.js +760 -0
  64. package/dist/lib/restore-verify.js +1 -1
  65. package/dist/lib/skill-assignment-preflight.js +159 -0
  66. package/dist/lib/skill-seed.js +91 -8
  67. package/dist/lib/skill-tombstone-doctor.js +133 -0
  68. package/dist/lib/soul-scope-fields.js +26 -0
  69. package/dist/lib/uninstall-purge.js +266 -11
  70. package/dist/lib/upgrade-prior-liveness.js +2 -1
  71. package/dist/mcp-client-assertion.js +2 -10
  72. package/dist/memory-id-checkpoint.js +28 -7
  73. package/dist/mqtt-off-deploy.js +550 -0
  74. package/dist/rem/promote-policy.js +3 -3
  75. package/dist/rem/restore.js +302 -26
  76. package/dist/rem/runner.js +220 -58
  77. package/dist/rem/scheduler.js +21 -4
  78. package/dist/resources/A2AAdapter.js +131 -178
  79. package/dist/resources/AdminMemory.js +2 -0
  80. package/dist/resources/AdminMemoryCandidates.js +116 -0
  81. package/dist/resources/Agent.js +155 -45
  82. package/dist/resources/AgentCard.js +4 -0
  83. package/dist/resources/AgentKeyRegister.js +56 -22
  84. package/dist/resources/AgentReadPosition.js +7 -0
  85. package/dist/resources/AgentSeed.js +232 -107
  86. package/dist/resources/AutoPromoteCandidates.js +413 -84
  87. package/dist/resources/Credential.js +6 -8
  88. package/dist/resources/Federation.js +219 -57
  89. package/dist/resources/FederationRetry.js +4 -4
  90. package/dist/resources/InstructionVersion.js +1 -1
  91. package/dist/resources/MCPClientMetadata.js +6 -3
  92. package/dist/resources/Memory.js +1303 -270
  93. package/dist/resources/MemoryArchive.js +149 -64
  94. package/dist/resources/MemoryBootstrap.js +12 -22
  95. package/dist/resources/MemoryCandidate.js +16 -2
  96. package/dist/resources/MemoryConsolidate.js +2 -2
  97. package/dist/resources/MemoryFeed.js +360 -147
  98. package/dist/resources/MemoryMaintenance.js +290 -72
  99. package/dist/resources/MemoryPurge.js +138 -22
  100. package/dist/resources/MemoryReflect.js +68 -14
  101. package/dist/resources/MemoryReindex.js +91 -13
  102. package/dist/resources/Message.js +11 -2
  103. package/dist/resources/OAuth.js +156 -39
  104. package/dist/resources/OAuthClient.js +1 -1
  105. package/dist/resources/OrgEvent.js +292 -29
  106. package/dist/resources/OrgEventCatchup.js +7 -0
  107. package/dist/resources/OrgEventMaintenance.js +48 -10
  108. package/dist/resources/PairingToken.js +1 -1
  109. package/dist/resources/Presence.js +31 -11
  110. package/dist/resources/PromoteMemoryCandidate.js +8 -2
  111. package/dist/resources/RecordUsage.js +2 -4
  112. package/dist/resources/Soul.js +2 -0
  113. package/dist/resources/SoulFeed.js +2 -1
  114. package/dist/resources/WorkspaceLatest.js +4 -0
  115. package/dist/resources/XAA.js +36 -10
  116. package/dist/resources/a2a-stream.js +313 -0
  117. package/dist/resources/a2a-url.js +4 -5
  118. package/dist/resources/agent-admin.js +10 -1
  119. package/dist/resources/agent-auth.js +98 -68
  120. package/dist/resources/agent-read-position-lib.js +4 -1
  121. package/dist/resources/agent-status-guard.js +9 -7
  122. package/dist/resources/auth-middleware.js +166 -42
  123. package/dist/resources/authority-field-guard.js +9 -11
  124. package/dist/resources/auto-promote-lib.js +8 -5
  125. package/dist/resources/basic-auth-header.js +21 -0
  126. package/dist/resources/bm25-index-service.js +4 -5
  127. package/dist/resources/dedup-cluster.js +6 -1
  128. package/dist/resources/embeddings-provider.js +25 -0
  129. package/dist/resources/federation-classify.js +89 -0
  130. package/dist/resources/federation-retry-lib.js +6 -81
  131. package/dist/resources/health.js +43 -4
  132. package/dist/resources/host-pointer/registry.js +29 -0
  133. package/dist/resources/host-pointer-adapter.js +1 -0
  134. package/dist/resources/in-process.js +24 -22
  135. package/dist/resources/instruction-version-record.js +251 -7
  136. package/dist/resources/internal-authority.js +13 -0
  137. package/dist/resources/mcp-handler.js +106 -12
  138. package/dist/resources/mcp-oauth-flag.js +12 -14
  139. package/dist/resources/mcp-oauth.js +430 -53
  140. package/dist/resources/mcp-tools.js +60 -22
  141. package/dist/resources/memory-declared-attributes.js +1 -0
  142. package/dist/resources/memory-embed-hash.js +56 -0
  143. package/dist/resources/memory-host-source.js +5 -2
  144. package/dist/resources/memory-reflect-lib.js +1 -1
  145. package/dist/resources/memory-write-lock.js +202 -23
  146. package/dist/resources/memory-write-response.js +1 -1
  147. package/dist/resources/memory-write-transaction.js +243 -0
  148. package/dist/resources/migration-boot.js +17 -12
  149. package/dist/resources/migrations/boot-progress.js +25 -0
  150. package/dist/resources/migrations/data-dir.js +16 -3
  151. package/dist/resources/migrations/dir-safety.js +60 -2
  152. package/dist/resources/migrations/embedding-stamp.js +315 -49
  153. package/dist/resources/migrations/graph-heal.js +9 -2
  154. package/dist/resources/migrations/ledger.js +5 -2
  155. package/dist/resources/migrations/lock.js +867 -80
  156. package/dist/resources/migrations/progress.js +71 -10
  157. package/dist/resources/migrations/runner.js +212 -18
  158. package/dist/resources/migrations/state.js +36 -1
  159. package/dist/resources/migrations/status.js +2 -13
  160. package/dist/resources/migrations/synthetic-test-migration.js +78 -12
  161. package/dist/resources/migrations/types.js +26 -1
  162. package/dist/resources/migrations/visibility-backfill.js +111 -70
  163. package/dist/resources/oauth-discovery.js +0 -5
  164. package/dist/resources/object-body-guard.js +12 -5
  165. package/dist/resources/org-event-reserved.js +92 -0
  166. package/dist/resources/org-event-write-fault.js +19 -0
  167. package/dist/resources/owner-field-guard.js +1 -1
  168. package/dist/resources/owner-scoped-write-policy.js +65 -21
  169. package/dist/resources/owner-scoped-writes.js +37 -6
  170. package/dist/resources/path-id-rewrite.js +76 -0
  171. package/dist/resources/presence-internal.js +5 -5
  172. package/dist/resources/promotion-binding.js +43 -0
  173. package/dist/resources/promotion-stamp.js +124 -33
  174. package/dist/resources/protocol-context.js +189 -0
  175. package/dist/resources/record-type-kit.js +2 -4
  176. package/dist/resources/request-target.js +28 -1
  177. package/dist/resources/request-transaction.js +11 -1
  178. package/dist/resources/seed-reservation.js +1 -2
  179. package/dist/resources/semantic-retrieval-core.js +7 -6
  180. package/dist/resources/server-row-validation.js +71 -0
  181. package/dist/resources/skill-manifest.js +4 -3
  182. package/dist/resources/skill-version-write.js +384 -27
  183. package/dist/resources/skill-write-fault.js +6 -3
  184. package/dist/resources/skill-write-policy.js +2 -1
  185. package/dist/resources/soul-write-policy.js +26 -7
  186. package/dist/resources/table-helpers.js +1 -1
  187. package/dist/resources/table-subscription-policy.js +518 -85
  188. package/dist/resources/table-subscriptions.js +20 -7
  189. package/dist/resources/txn-pause-point.js +122 -5
  190. package/dist/resources/usage-recording.js +54 -46
  191. package/dist/resources/write-back.js +176 -11
  192. package/dist/resources/write-journal-context.js +5 -0
  193. package/dist/resources/write-journal.js +289 -0
  194. package/dist/src/lib/agent-id-rule.js +44 -2
  195. package/dist/src/lib/atomic-write.js +1 -1
  196. package/dist/src/lib/federation-retry-row.js +101 -0
  197. package/dist/src/lib/instruction-event-contract.js +17 -0
  198. package/dist/src/lib/memory-attributes.js +2 -0
  199. package/dist/src/lib/open-live-row.js +20 -0
  200. package/dist/src/lib/soul-scope-fields.js +26 -0
  201. package/dist/src/rem/promote-policy.js +3 -3
  202. package/dist/src/rem/scheduler.js +21 -4
  203. package/docs/access-control.md +18 -9
  204. package/docs/api-reference.md +126 -28
  205. package/docs/auth.md +40 -18
  206. package/docs/claude-code.md +3 -3
  207. package/docs/deploying-on-fabric.md +108 -0
  208. package/docs/deployment.md +17 -0
  209. package/docs/embedding-in-a-harper-app.md +16 -14
  210. package/docs/entity-vocabulary.md +3 -6
  211. package/docs/federation.md +29 -2
  212. package/docs/integrations.md +11 -11
  213. package/docs/mcp-clients.md +7 -5
  214. package/docs/notes/mcp-agent-auth-consumer.md +4 -9
  215. package/docs/notes/mcp-oauth-model2.md +6 -6
  216. package/docs/openclaw.md +1 -1
  217. package/docs/quickstart-fabric.md +2 -2
  218. package/docs/quickstart.md +3 -3
  219. package/docs/releasing.md +13 -13
  220. package/docs/rem.md +24 -3
  221. package/docs/secrets-and-keys.md +2 -2
  222. package/docs/standalone-local.md +29 -2
  223. package/docs/supply-chain-policy.md +28 -20
  224. package/docs/the-team.md +2 -2
  225. package/docs/upgrade.md +14 -0
  226. package/package.json +18 -11
  227. package/schemas/agent.graphql +3 -3
  228. package/schemas/federation.graphql +10 -7
  229. package/schemas/memory.graphql +7 -2
  230. package/templates/bin/flair-rem-nightly.sh.tmpl +7 -1
  231. package/templates/launchd/start-flair-with-admin-pass.sh +188 -10
  232. package/dist/resources/soul-adk-guard.js +0 -68
@@ -6,8 +6,10 @@
6
6
  * resources/record-owner-guard.ts's OWNER_FIELDS, through a resource class that
7
7
  * extends that table:
8
8
  * - addressed to one record (POST/PUT/PATCH/DELETE to `/<Table>/<id>`) is
9
- * checked for a differing string or number body `id` on POST/PUT/PATCH
10
- * (`writeIdNotAddressedRefusal`, 403), then for a stored owner other than
9
+ * checked on POST/PUT/PATCH for a body `id` that names a record other than
10
+ * the addressed one (`bodyIdRefusal`: `writeIdNotAddressedRefusal`, 403,
11
+ * for a string or number id; `idTargetMismatchRefusal`, 400, for a present,
12
+ * non-null id of any other type; an absent or null id passes), then for a stored owner other than
11
13
  * the caller (`ownerMutationRefusal`, 403), if reached. The middleware can
12
14
  * return the owner refusal first on a plain addressed URL;
13
15
  * - addressed to no single record (the table's collection, with or without a
@@ -56,7 +58,7 @@ export const OWNER_SCOPED_WRITE_GUARD = Symbol.for("flair.ownerScopedWriteGuard"
56
58
  export const GUARDED_WRITE_METHODS = Object.freeze(["put", "patch", "delete", "post"]);
57
59
  /** Methods refused on a collection target, where the request does not resolve to one addressed row. */
58
60
  const STORED_RECORD_METHODS = new Set(["put", "patch", "delete"]);
59
- /** Methods whose string or number body `id` must name the addressed record. */
61
+ /** Methods whose body `id` must name the addressed record. */
60
62
  const BODY_ID_METHODS = new Set(["put", "patch", "post"]);
61
63
  /**
62
64
  * Whether `target` carries a non-null, non-false permission marker.
@@ -90,20 +92,52 @@ export function writeIdNotAddressedRefusal() {
90
92
  }), { status: 403, headers: { "Content-Type": "application/json" } });
91
93
  }
92
94
  /**
93
- * Whether a parsed request `body` carries a string or number body `id` that
94
- * names a record other than `targetId` (the addressed record).
95
+ * The named refusal for an addressed write whose body `id` is present, not
96
+ * null, not a string or number, and not the addressed key. It answers the error and status of
97
+ * resources/originator-instance.ts's body-id check and echoes no submitted value.
95
98
  */
96
- export function bodyNamesDifferentRecord(targetId, body) {
97
- if (targetId == null)
98
- return false;
99
- if (body == null || typeof body !== "object" || Array.isArray(body))
100
- return false;
101
- const bodyId = body.id;
102
- if (bodyId == null)
103
- return false;
104
- if (typeof bodyId !== "string" && typeof bodyId !== "number")
105
- return false;
106
- return String(bodyId) !== String(targetId);
99
+ export function idTargetMismatchRefusal() {
100
+ return new Response(JSON.stringify({
101
+ error: "id_target_mismatch",
102
+ message: "the request body id does not match the address it was sent to",
103
+ }), { status: 400, headers: { "Content-Type": "application/json" } });
104
+ }
105
+ function isScalarId(id) {
106
+ return typeof id === "string" || typeof id === "number";
107
+ }
108
+ /**
109
+ * Whether `id` is the key `targetId` addresses: the same text for a string or
110
+ * number pair, or two arrays whose elements are strictly equal in order.
111
+ */
112
+ export function isAddressedKey(targetId, id) {
113
+ if (isScalarId(targetId) && isScalarId(id))
114
+ return String(id) === String(targetId);
115
+ if (Array.isArray(targetId) && Array.isArray(id)) {
116
+ return targetId.length === id.length && targetId.every((part, i) => part === id[i]);
117
+ }
118
+ return false;
119
+ }
120
+ /**
121
+ * The refusal for a write addressed to `targetId` whose parsed `body` names a
122
+ * record other than the addressed one, or null. It checks the body when it is
123
+ * an object, and each object element of an array body. A record whose `id` is
124
+ * absent, null or the addressed key passes. Otherwise a string or number `id`
125
+ * at a string or number address gets `writeIdNotAddressedRefusal` (403), and
126
+ * any other `id` gets `idTargetMismatchRefusal` (400).
127
+ */
128
+ export function bodyIdRefusal(targetId, body) {
129
+ if (targetId == null || body == null || typeof body !== "object")
130
+ return null;
131
+ const records = Array.isArray(body) ? body : [body];
132
+ for (const record of records) {
133
+ if (record == null || typeof record !== "object" || Array.isArray(record))
134
+ continue;
135
+ const id = record.id;
136
+ if (id == null || isAddressedKey(targetId, id))
137
+ continue;
138
+ return isScalarId(id) && isScalarId(targetId) ? writeIdNotAddressedRefusal() : idTargetMismatchRefusal();
139
+ }
140
+ return null;
107
141
  }
108
142
  /**
109
143
  * Decide one entry write. Resolves when the write may proceed; rejects with the
@@ -113,8 +147,8 @@ export function bodyNamesDifferentRecord(targetId, body) {
113
147
  * In order: resolve the caller (an unresolvable one is refused); leave an
114
148
  * administrator, a trusted internal call and an anonymous caller to their
115
149
  * existing handling; refuse a collection PUT/PATCH/DELETE; refuse an addressed
116
- * POST/PUT/PATCH whose string or number body `id` names a record other than the
117
- * addressed one; then refuse a write to a stored record owned by another
150
+ * POST/PUT/PATCH whose body names a record other than the addressed one
151
+ * (`bodyIdRefusal`); then refuse a write to a stored record owned by another
118
152
  * principal. Each refusal by this guard leaves the target row unchanged.
119
153
  */
120
154
  export async function admitOwnerScopedWrite(table, ownerField, method, target, context, deps) {
@@ -127,12 +161,21 @@ export async function admitOwnerScopedWrite(table, ownerField, method, target, c
127
161
  }
128
162
  if (caller.kind !== "agent" || caller.isAdmin === true)
129
163
  return;
164
+ // A table-specific refusal runs before this guard's collection and ownership
165
+ // branches. When this pre-check can identify a reserved record (a proposed
166
+ // body marker or a readable stored row),
167
+ // its named refusal replaces this guard's generic one. A collection delete
168
+ // this pre-check cannot resolve is still refused by the collection branch
169
+ // below. Only callers reaching OrgEvent.delete() run its selection pre-scan.
170
+ const reserved = await deps.refuseReservedWrite?.(table, method, target, context);
171
+ if (reserved)
172
+ throw reserved;
130
173
  if (addressesNoSingleRecord(target)) {
131
174
  if (STORED_RECORD_METHODS.has(method))
132
175
  throw collectionWriteRefusal(table);
133
176
  return;
134
177
  }
135
- // Addressed write: a string or number body `id` must name the addressed record.
178
+ // Addressed write: the body may name only the addressed record.
136
179
  if (BODY_ID_METHODS.has(method)) {
137
180
  let body;
138
181
  try {
@@ -142,8 +185,9 @@ export async function admitOwnerScopedWrite(table, ownerField, method, target, c
142
185
  // A body that cannot be read cannot be checked: refuse rather than admit.
143
186
  throw writeBodyUnreadableRefusal(table);
144
187
  }
145
- if (bodyNamesDifferentRecord(target.id, body))
146
- throw writeIdNotAddressedRefusal();
188
+ const idRefusal = bodyIdRefusal(target.id, body);
189
+ if (idRefusal)
190
+ throw idRefusal;
147
191
  }
148
192
  let stored;
149
193
  try {
@@ -3,7 +3,7 @@
3
3
  * on every table class named in resources/record-owner-guard.ts's OWNER_FIELDS
4
4
  * when the component loads. For a non-admin HTTP request to a resource class
5
5
  * that extends one of those tables: an addressed write (POST/PUT/PATCH/DELETE
6
- * to `/<Table>/<id>`) checks a string or number body `id` on POST/PUT/PATCH before the
6
+ * to `/<Table>/<id>`) checks the body `id` on POST/PUT/PATCH before the
7
7
  * stored owner, if reached; middleware can return the owner refusal first.
8
8
  * For collection PUT/PATCH/DELETE, if reached, the table guard returns the
9
9
  * collection refusal; existing DELETE middleware may refuse earlier. A POST to a collection is delegated
@@ -21,11 +21,7 @@
21
21
  *
22
22
  * ─── No static auth import; agent-auth.js loads on the first guarded write ──
23
23
  * Harper links a component's resource modules concurrently while it starts.
24
- * This module's static imports are `harper` and two modules with no
25
- * authentication-module dependency (record-owner-guard.ts, which also supplies
26
- * the `owner_check_unavailable` refusal, and owner-scoped-write-policy.ts), so
27
- * loading it adds no link of the authentication module graph to that startup
28
- * phase; a static import of agent-auth.js from here stopped Harper from
24
+ * A static import of agent-auth.js from here stopped Harper from
29
25
  * starting under Bun (test/integration/init-persisted-admin-harper5.test.ts).
30
26
  *
31
27
  * agent-auth.js is imported once, when the first guarded write needs its
@@ -36,6 +32,7 @@
36
32
  */
37
33
  import { databases } from "harper";
38
34
  import { OWNER_FIELDS, ownerCheckUnavailable } from "./record-owner-guard.js";
35
+ import { isReservedEventRecord, reservedEventProposedRefusal, reservedEventRefusal, reservedEventStoredRefusal } from "./org-event-reserved.js";
39
36
  import { guardOwnerScopedWrites, ownerScopedWriteGuardGaps } from "./owner-scoped-write-policy.js";
40
37
  let agentAuthModule;
41
38
  function agentAuth() {
@@ -51,6 +48,40 @@ const guarded = guardOwnerScopedWrites(registry, OWNER_FIELDS, {
51
48
  readStored: (table, id) => registry[table].get(id, {}),
52
49
  unreadable: ownerCheckUnavailable,
53
50
  readBody: (context) => context?.data,
51
+ refuseReservedWrite: async (table, method, target, context) => {
52
+ if (table !== "OrgEvent")
53
+ return null;
54
+ const readStored = (id) => registry.OrgEvent.get(id, {});
55
+ if (method === "delete")
56
+ return reservedEventStoredRefusal(target?.id, readStored);
57
+ let body;
58
+ try {
59
+ body = await Promise.resolve(context?.data);
60
+ }
61
+ catch {
62
+ return null; // the guard's own readBody refusal owns an unreadable body
63
+ }
64
+ const proposed = reservedEventProposedRefusal(body);
65
+ if (proposed)
66
+ return proposed;
67
+ // A stored read that FAILS is left to this guard's owner check and the
68
+ // resource's own checks, which refuse with their named errors. This
69
+ // pre-check only adds the reserved refusal when the row is readable.
70
+ try {
71
+ const records = Array.isArray(body) ? body : [body];
72
+ for (const record of records) {
73
+ const id = record && typeof record === "object" && !Array.isArray(record) ? record.id : undefined;
74
+ if (typeof id === "string" && id !== "" && isReservedEventRecord(await readStored(id)))
75
+ return reservedEventRefusal();
76
+ }
77
+ if (target && target.id != null && isReservedEventRecord(await readStored(target.id)))
78
+ return reservedEventRefusal();
79
+ }
80
+ catch {
81
+ return null;
82
+ }
83
+ return null;
84
+ },
54
85
  });
55
86
  const gaps = ownerScopedWriteGuardGaps(registry, OWNER_FIELDS, guarded);
56
87
  if (gaps.length > 0) {
@@ -0,0 +1,76 @@
1
+ /**
2
+ * path-id-rewrite.ts — refuse a path agent id that Harper's path parsing
3
+ * changed before the route received it (flair#2845).
4
+ *
5
+ * Harper decodes the path after a resource's name into the request's id, and
6
+ * `Resource.parsePath` (harper `dist/resources/Resource.js`) can then change
7
+ * that id: when the text after its first dot is `json`, `csv`, `cbor` or
8
+ * `msgpack`, the dot and that text are removed as a content-type request, so
9
+ * `agent.json` reaches the route as `agent`. A route calls
10
+ * `refuseRewrittenAgentId` with the id it received and returns the 400 it
11
+ * gives back, instead of answering for the changed id.
12
+ *
13
+ * Imports only the pure path helpers in request-target.js.
14
+ */
15
+ import { requestPath, routedResourceAndRemainder } from "./request-target.js";
16
+ /** The named error a rewritten path agent id is refused with. */
17
+ export const AGENT_ID_REWRITTEN_ERROR = "agent_id_rewritten";
18
+ /**
19
+ * The origin-form path and query of a raw request target. A target that starts
20
+ * with `/` is returned as is. Any other target (such as an absolute URL) is cut
21
+ * the way Harper's `BunRequest` cuts its full URL (harper
22
+ * `dist/server/serverHelpers/Request.js`): from the first `/` found two
23
+ * characters past the first `//` (from index 1 when there is no `//`), or to
24
+ * `/` when no `/` is found.
25
+ */
26
+ function originFormTarget(rawUrl) {
27
+ if (rawUrl.startsWith("/"))
28
+ return rawUrl;
29
+ const pathStart = rawUrl.indexOf("/", rawUrl.indexOf("//") + 2);
30
+ return pathStart >= 0 ? rawUrl.slice(pathStart) : "/";
31
+ }
32
+ /**
33
+ * Compare the id a route received with the id its raw request target names,
34
+ * read the way Harper reads it: the path ends at the first `?` (a raw `#` and
35
+ * the text after it stay in the path), and the text after its first segment is
36
+ * decoded with decodeURIComponent, as Harper's RequestTarget decodes it.
37
+ * `rawUrl` is the request's `url`: a path (with any query) or an absolute URL
38
+ * (see originFormTarget). Returns both ids when they differ. A remainder that
39
+ * is not valid percent-encoding is returned undecoded as the requested id.
40
+ * Returns null when the ids are equal, when `rawUrl` is not a non-empty string
41
+ * (no request path was parsed), or when the path has nothing after its first
42
+ * segment (the received id did not come from the path).
43
+ */
44
+ export function rewrittenPathId(rawUrl, received) {
45
+ if (typeof rawUrl !== "string" || rawUrl === "")
46
+ return null;
47
+ const { remainder } = routedResourceAndRemainder(requestPath(originFormTarget(rawUrl)));
48
+ if (remainder === "")
49
+ return null;
50
+ let requested;
51
+ try {
52
+ requested = decodeURIComponent(remainder);
53
+ }
54
+ catch {
55
+ return { requested: remainder, received };
56
+ }
57
+ return requested === received ? null : { requested, received };
58
+ }
59
+ /** The named 400 for a rewritten path agent id, naming both ids. */
60
+ export function agentIdRewrittenRefusal(rewritten) {
61
+ return new Response(JSON.stringify({
62
+ error: AGENT_ID_REWRITTEN_ERROR,
63
+ message: `the request path names agent id ${JSON.stringify(rewritten.requested)}, but Harper's path parsing passed ${JSON.stringify(rewritten.received)} to this route, so the request is refused instead of answered for ${JSON.stringify(rewritten.received)}`,
64
+ requestedAgentId: rewritten.requested,
65
+ receivedAgentId: rewritten.received,
66
+ }), { status: 400, headers: { "Content-Type": "application/json" } });
67
+ }
68
+ /**
69
+ * The 400 for a request whose path agent id Harper changed, or null. `context`
70
+ * is the resource's `getContext()`; its request URL is the path compared.
71
+ */
72
+ export function refuseRewrittenAgentId(context, received) {
73
+ const request = context?.request ?? context;
74
+ const rewritten = rewrittenPathId(request?.url, String(received));
75
+ return rewritten ? agentIdRewrittenRefusal(rewritten) : null;
76
+ }
@@ -2,11 +2,11 @@ function presenceDelegationContext(auth) {
2
2
  const agentAuth = auth.kind === "agent"
3
3
  ? { agentId: auth.agentId, isAdmin: auth.isAdmin }
4
4
  : { agentId: "internal", isAdmin: true };
5
- // `__flairInternal` marks the `internal` branch as DELIBERATE (flair#936) —
6
- // an "internal" verdict relayed here is a trusted in-process call this file
7
- // has already established, not a caller who forgot to pass a context. It is
8
- // read only by resources/agent-auth.ts's accidental-omission warning; it
9
- // grants nothing and is never consulted for an authorization decision.
5
+ // `__flairInternal` belongs to the context of this synthetic Presence read.
6
+ // isDeliberateInternalCall (resources/agent-auth.ts, the omission warning)
7
+ // reads it, and so does isDeliberateInternalVerdict
8
+ // (resources/internal-authority.ts), which allowAdmin, soulWriteSource and
9
+ // skillWriteSource call.
10
10
  return { request: { _flairAgentAuth: agentAuth }, __flairInternal: true };
11
11
  }
12
12
  /**
@@ -0,0 +1,43 @@
1
+ import { createHash } from "node:crypto";
2
+ /** Server-only SHA-256 of the stored, post-redaction content at stamping time. */
3
+ export const PROMOTION_CONTENT_HASH_FIELD = "promotionContentHash";
4
+ /** The binding fields (the three verdict fields and the content hash) the accessor suppresses together. */
5
+ export const PROMOTION_BINDING_FIELDS = [
6
+ "promotionStatus",
7
+ "promotedAt",
8
+ "promotedBy",
9
+ PROMOTION_CONTENT_HASH_FIELD,
10
+ ];
11
+ /** SHA-256 over the exact stored, post-redaction content as UTF-8. */
12
+ export function promotionContentHash(content) {
13
+ const text = typeof content === "string" ? content : content == null ? "" : String(content);
14
+ return createHash("sha256").update(text, "utf8").digest("hex");
15
+ }
16
+ /**
17
+ * Does `row` carry a promotion binding that matches its current content? An
18
+ * absent hash (a legacy verdict) does not match.
19
+ */
20
+ export function promotionBindingMatches(row) {
21
+ if (row == null || typeof row !== "object")
22
+ return false;
23
+ const stored = row[PROMOTION_CONTENT_HASH_FIELD];
24
+ if (typeof stored !== "string" || stored.length === 0)
25
+ return false;
26
+ return stored === promotionContentHash(row.content);
27
+ }
28
+ /**
29
+ * Return `row` with an absent or mismatched promotion binding suppressed. The
30
+ * input is not mutated; a matching binding and a row with none of the four
31
+ * binding fields are returned as-is.
32
+ */
33
+ export function applyPromotionBinding(row) {
34
+ if (row == null || typeof row !== "object" || Array.isArray(row))
35
+ return row;
36
+ const source = row;
37
+ const hasVerdict = PROMOTION_BINDING_FIELDS.some((field) => source[field] != null);
38
+ if (!hasVerdict)
39
+ return row;
40
+ if (promotionBindingMatches(source))
41
+ return row;
42
+ return { ...source, promotionStatus: null, promotedAt: null, promotedBy: null, promotionContentHash: null };
43
+ }
@@ -1,9 +1,10 @@
1
1
  import { databases } from "harper";
2
- import { stripUndeclaredMemoryAttributes } from "./memory-declared-attributes.js";
3
2
  import { noteMemoryUpsert } from "./bm25-index-service.js";
4
- import { writeBackCommittedRow } from "./write-back.js";
3
+ import { WriteBackConflictError, writeBackCommittedRow } from "./write-back.js";
5
4
  import { txnPausePoint } from "./txn-pause-point.js";
6
5
  import { isJoinableTransaction } from "./request-transaction.js";
6
+ import { promotionContentHash } from "./promotion-binding.js";
7
+ import { withMemoryWriteLock, withMemoryWriteLockOnce } from "./memory-write-lock.js";
7
8
  /** The stamp's first read is not the row the promotion wrote: nothing stamped. */
8
9
  export class PromotedRowChangedError extends Error {
9
10
  constructor(id) {
@@ -11,9 +12,61 @@ export class PromotedRowChangedError extends Error {
11
12
  this.name = "PromotedRowChangedError";
12
13
  }
13
14
  }
15
+ export class PromotionStampStaleRowError extends Error {
16
+ constructor(id) {
17
+ super(`promotion-stamp: row ${id} has a stale content binding; no stamp written`);
18
+ this.name = "PromotionStampStaleRowError";
19
+ }
20
+ }
21
+ /** The memory id's write lock answered something other than a completed
22
+ * callback: nothing was stamped. */
23
+ export class PromotionStampLockError extends Error {
24
+ constructor(kind, id) {
25
+ super(`promotion-stamp: the memory write lock for ${id} answered ${kind}; no stamp written`);
26
+ this.name = "PromotionStampLockError";
27
+ }
28
+ }
14
29
  function isWrittenRow(row, written) {
15
- return written != null && typeof written.instanceToken === "string" && written.instanceToken.length > 0 &&
16
- row.agentId === written.agentId && row.content === written.content && row.instanceToken === written.instanceToken;
30
+ if (written == null || typeof written.instanceToken !== "string" || written.instanceToken.length === 0)
31
+ return false;
32
+ if (row.agentId !== written.agentId || row.content !== written.content ||
33
+ row.instanceToken !== written.instanceToken)
34
+ return false;
35
+ if (written.unstamped && row.promotionStatus != null)
36
+ return false;
37
+ if (written.unarchived && row.archived === true)
38
+ return false;
39
+ if (written.visibility !== undefined && row.visibility !== written.visibility)
40
+ return false;
41
+ if (written.durability !== undefined && row.durability !== written.durability)
42
+ return false;
43
+ if (written.tags !== undefined &&
44
+ (!Array.isArray(row.tags) || !written.tags.every((tag) => row.tags.includes(tag))))
45
+ return false;
46
+ return true;
47
+ }
48
+ /** The incremental update a stamp writes: the verdict fields plus the hash of
49
+ * the EXACT stored, post-redaction content the verdict is bound to. */
50
+ function promotionStampUpdate(stored, reviewerId, decidedAt) {
51
+ return {
52
+ promotionStatus: "approved",
53
+ promotedBy: reviewerId,
54
+ promotedAt: decidedAt,
55
+ promotionContentHash: promotionContentHash(stored.content),
56
+ };
57
+ }
58
+ /** Automatic stamping checks the written row's identity; both paths skip an
59
+ * already mismatched content hash. */
60
+ function isStaleBasis(stored, written) {
61
+ if (written != null && !isWrittenRow(stored, written))
62
+ return true;
63
+ const bound = stored?.promotionContentHash;
64
+ return typeof bound === "string" && bound.length > 0 && bound !== promotionContentHash(stored.content);
65
+ }
66
+ /** The `Memory.primaryStore` write-lock handle. Also used by auto-promotion's
67
+ * adoption of a recorded row (AutoPromoteCandidates.ts, flair#2714). */
68
+ export function memoryPrimaryStore() {
69
+ return databases?.flair?.Memory?.primaryStore;
17
70
  }
18
71
  // Called only after the promotion workflow has authorized and written a Memory
19
72
  // through its resource (safety, embedding, ownership and provenance still run).
@@ -22,45 +75,83 @@ function isWrittenRow(row, written) {
22
75
  // It also supplies the identity of the row it wrote; the stamp's first read
23
76
  // must be that row. Manual promotion passes the context of the open
24
77
  // transaction its Memory write used, and the stamp joins it.
25
- export async function stampMemoryPromotion(id, reviewerId, decidedAt, enumerationContext, stagedContext, written) {
78
+ //
79
+ // Both stamps share the per-id Memory lock with owner PUT/PATCH and update
80
+ // only verdict fields. The automatic write confirms identity, content and hash.
81
+ export async function stampMemoryPromotion(id, reviewerId, decidedAt, enumerationContext, stagedContext, written, onUnconfirmed) {
26
82
  const table = databases.flair.Memory;
27
- const stamp = (stored) => {
28
- if (!stored)
29
- throw new Error(`Promotion memory ${id} was not written`);
30
- const row = { ...stored, promotionStatus: "approved", promotedBy: reviewerId, promotedAt: decidedAt };
31
- stripUndeclaredMemoryAttributes(row);
32
- return row;
33
- };
34
83
  if (isJoinableTransaction(stagedContext)) {
35
- const row = stamp(await table.get(id, stagedContext));
36
- await table.put(row, stagedContext);
37
- noteMemoryUpsert(row);
84
+ // Manual promotion: the Memory write and this stamp share the caller's
85
+ // transaction. The memory lock is taken for the stamp's own read/decision/
86
+ // write; the enclosing transaction commits after it releases (the composed
87
+ // limit in resources/memory-write-lock.ts).
88
+ const outcome = await withMemoryWriteLock(memoryPrimaryStore(), [id], async () => {
89
+ const row = await table.get(id, stagedContext);
90
+ if (!row)
91
+ throw new Error(`Promotion memory ${id} was not written`);
92
+ if (isStaleBasis(row, written))
93
+ return false;
94
+ // Test-only: inert unless the fault-injection opt-in is armed. The lock is
95
+ // held and the caller's transaction is open.
96
+ const paused = txnPausePoint("promotion-stamp-manual");
97
+ if (paused)
98
+ await paused;
99
+ const update = promotionStampUpdate(row, reviewerId, decidedAt);
100
+ await table.update(id, update, stagedContext);
101
+ noteMemoryUpsert({ ...row, ...update });
102
+ return true;
103
+ }, { phase: "promotion-stamp-manual" });
104
+ if (outcome.kind !== "done")
105
+ throw new PromotionStampLockError(outcome.kind, id);
106
+ if (outcome.value === false)
107
+ throw new PromotionStampStaleRowError(id);
38
108
  return;
39
109
  }
40
- // Test-only: inert unless the fault-injection opt-in is armed.
41
- const beforeFirstRead = txnPausePoint("promotion-stamp-select");
42
- if (beforeFirstRead)
43
- await beforeFirstRead;
44
- const selected = await table.get(id, {});
45
- if (!selected)
46
- throw new Error(`Promotion memory ${id} was not written`);
47
- if (!isWrittenRow(selected, written))
48
- throw new PromotedRowChangedError(id);
49
- const outcome = await writeBackCommittedRow(table, id, (stored) => ({ write: stamp(stored) }), { ctx: enumerationContext, label: "promotion-stamp", pausePre: () => txnPausePoint("promotion-stamp-pre"), pausePoint: () => txnPausePoint("promotion-stamp"), matchFields: ["content"], expectedRow: selected });
50
- if ("write" in outcome)
51
- noteMemoryUpsert(outcome.write);
110
+ // Test-only: the promotion's Memory write has committed; the stamp has not
111
+ // taken the lock yet. Inert unless the fault-injection opt-in is armed.
112
+ const entry = txnPausePoint("promotion-stamp-entry");
113
+ if (entry)
114
+ await entry;
115
+ const outcome = await withMemoryWriteLockOnce(memoryPrimaryStore(), [id], async () => {
116
+ const beforeFirstRead = txnPausePoint("promotion-stamp-select");
117
+ if (beforeFirstRead)
118
+ await beforeFirstRead;
119
+ const selected = await table.get(id, {});
120
+ if (!selected)
121
+ throw new Error(`Promotion memory ${id} was not written`);
122
+ if (isStaleBasis(selected, written))
123
+ throw new PromotedRowChangedError(id);
124
+ const writeBack = await writeBackCommittedRow(table, id, (stored) => {
125
+ const update = promotionStampUpdate(stored, reviewerId, decidedAt);
126
+ // Idempotent: the update rewrites the same verdict fields and re-derives
127
+ // the same content hash from content the update does not change, so
128
+ // re-planning from a fresh read after it commits writes the same values.
129
+ return { idempotent: true, update };
130
+ }, { ctx: enumerationContext, onUnconfirmed, label: "promotion-stamp", pausePre: () => txnPausePoint("promotion-stamp-pre"), pausePoint: () => txnPausePoint("promotion-stamp"), confirmPoint: () => txnPausePoint("promotion-stamp-confirmed"), pauseBeforeCommit: () => txnPausePoint("promotion-stamp-commit"), matchFields: ["content", "promotionContentHash"], expectedRow: selected });
131
+ // Test-only: the write-back committed and the lock is still held.
132
+ const committed = txnPausePoint("promotion-stamp-committed");
133
+ if (committed)
134
+ await committed;
135
+ if ("update" in writeBack)
136
+ noteMemoryUpsert({ ...selected, ...writeBack.update });
137
+ return writeBack;
138
+ }, { phase: "promotion-stamp-auto" });
139
+ if (outcome.kind !== "done")
140
+ throw new PromotionStampLockError(outcome.kind, id);
52
141
  }
53
- /** Stamp after a successful Memory write. Failures must not abort a sweep or
54
- * leave a candidate pending (that re-writes the same claim next cycle).
55
- * Auto-promotion uses this non-fatal wrapper; manual promotion calls
56
- * stampMemoryPromotion directly, so a stamp failure fails that request. */
142
+ /** Stamp after a successful Memory write. Report failures without aborting the sweep.
143
+ * Auto-promotion uses this non-fatal wrapper and leaves its candidate pending
144
+ * with `stamp_refused` (flair#2651), so the next sweep retries it; manual
145
+ * promotion calls stampMemoryPromotion directly, so a stamp failure fails that
146
+ * request. */
57
147
  export async function stampMemoryPromotionIsolated(id, reviewerId, decidedAt, enumerationContext, written) {
148
+ let unconfirmed = false;
58
149
  try {
59
- await stampMemoryPromotion(id, reviewerId, decidedAt, enumerationContext, undefined, written);
150
+ await stampMemoryPromotion(id, reviewerId, decidedAt, enumerationContext, undefined, written, () => { unconfirmed = true; });
60
151
  return true;
61
152
  }
62
153
  catch (err) {
63
- console.warn(`stampMemoryPromotion failed for ${id}: ${err?.message ?? err}`);
154
+ console.warn("stampMemoryPromotion %s for %s: %s", unconfirmed ? "outcome unconfirmed" : "failed", id, err?.message ?? err, ...(unconfirmed ? [{ outcome: "unconfirmed" }] : err instanceof WriteBackConflictError ? [{ outcome: err.outcome }] : []));
64
155
  return false;
65
156
  }
66
157
  }