@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
@@ -3,31 +3,64 @@
3
3
  *
4
4
  * POST /MemoryArchive — sets or clears the `archived` visibility flag on a
5
5
  * memory by id:
6
- * - `action: "basement"` → archived=true + stamps archivedAt (and archivedBy)
6
+ * - `action: "basement"` sets `archived: true` and `archivedBy` to the
7
+ * caller; Memory's shared locked PUT body (putLocked) supplies `archivedAt`
8
+ * when it is absent or falsy.
7
9
  * - `action: "restore"` → archived=false + clears archivedAt/archivedBy
8
10
  *
9
- * `archived` is a VISIBILITY flag, not a deletion: basementing removes a
10
- * memory from bootstrap + default search but leaves the row, its provenance,
11
- * and its history fully intact (still retrievable via memory_get and
12
- * memory_search(includeArchived:true)). Restore is the deliberate, GLOBAL
13
- * inverse — it un-retires the memory for EVERY session, not a session-local
14
- * view (per-session reuse is drawers, Deliverable B, which does not exist
15
- * yet). The CLI help text must make that global scope explicit.
11
+ * `archived` is a VISIBILITY flag, not a deletion. Basementing retains the row
12
+ * and excludes it from bootstrap and default semantic search; the write still
13
+ * applies Memory.put()'s validation, redaction and provenance stamping.
14
+ * By-id retrieval remains subject to Memory's read checks; `includeArchived:
15
+ * true` removes the semantic-search archive filter while retaining the other
16
+ * retrieval filters. Restore is the deliberate inverse: it clears the archive
17
+ * state globally, not in a session-local view (per-session reuse is drawers,
18
+ * Deliverable B, which does not exist yet); other read and retrieval
19
+ * conditions still apply. The CLI help text must make that global scope
20
+ * explicit.
16
21
  *
17
- * Own-lane scope: the read uses Memory.get()'s read-scope gate and the write
18
- * uses Memory.put()'s ownership gate (stampAttribution), so a caller can
19
- * neither read nor write another agent's memory here. Anonymous HTTP is
20
- * denied (401).
22
+ * Scope: reads use Memory.get()'s read policy; non-admin callers may archive
23
+ * or restore only their own memories (Memory.put()'s ownership gate,
24
+ * stampAttribution), while administrators may act on another agent's memory.
25
+ * Anonymous HTTP is refused by allowCreate() before post() runs, with the
26
+ * status Harper returns for a denied allowCreate() (403 for SkillScan's same
27
+ * allowVerified() gate in test/integration/gate4-authgate.test.ts).
28
+ *
29
+ * The write of a non-skill row (flair#2478 part 3a): after the read above,
30
+ * the archive takes the per-id Memory write lock for the id (and for the row
31
+ * its `supersedes` names, which the PUT body may close: for its owner or an
32
+ * admin after the commit, best effort, a failed close logged; under a write
33
+ * grant staged in the write's transaction, so a failed close aborts the
34
+ * write; a non-admin write whose stored predecessor is missing closes
35
+ * nothing) under phase `archive-basement` /
36
+ * `archive-restore`, opens a locked transaction scope
37
+ * (resources/memory-write-transaction.ts), re-reads the row inside it, and
38
+ * writes through `putMemoryWithLock`. The scope commits, then
39
+ * confirms the row's identity, the PUT's verified fields and the archive fields
40
+ * (`archived`, `archivedAt`, `archivedBy`), and only then answers; the lock is
41
+ * held throughout. An owner PUT or PATCH of a held id waits within its budget
42
+ * and, if the hold outlasts it, answers `503 memory_busy` (an id with an
43
+ * unresolved write outcome answers `503 write_outcome_unknown` first); when
44
+ * the archive cannot take the lock, it answers the lock's refusal itself. A skill row keeps the existing
45
+ * Memory.put() path and its skill-state refusals (`skill_state_requires_delete`
46
+ * for `archived: true`); the skill version writer is converted later.
21
47
  *
22
48
  * Registered automatically at /MemoryArchive via config.yaml's
23
49
  * `jsResource: files: dist/resources/*.js` (named export → export name).
24
50
  */
25
51
  import { Resource, databases } from "harper";
26
52
  import { isDeepStrictEqual } from "node:util";
27
- import { Memory } from "./Memory.js";
53
+ import { Memory, memoryLockCallerIdFor, putMemoryWithLock } from "./Memory.js";
28
54
  import { resolveAgentAuth, allowVerified } from "./agent-auth.js";
29
55
  import { withOwnedTransaction } from "./request-transaction.js";
30
56
  import { txnPausePoint } from "./txn-pause-point.js";
57
+ import { memoryBusyResponse, memoryLockUnavailableResponse, withMemoryWriteLock, writeOutcomeUnknownResponse } from "./memory-write-lock.js";
58
+ import { lockedTransactionContext, withLockedMemoryTransaction } from "./memory-write-transaction.js";
59
+ import { resolveMemoryReferenceId } from "./memory-id-guard.js";
60
+ import { rowIsSkill } from "./skill-version-write.js";
61
+ import { memoryPrimaryStore } from "./promotion-stamp.js";
62
+ /** The archive fields the post-commit confirmation compares exactly. */
63
+ const ARCHIVE_FIELDS = Object.freeze(["archived", "archivedAt", "archivedBy"]);
31
64
  function json(status, body) {
32
65
  return new Response(JSON.stringify(body), {
33
66
  status,
@@ -36,9 +69,11 @@ function json(status, body) {
36
69
  }
37
70
  /**
38
71
  * A refusal or failure from Memory.get()/Memory.put() is a Harper `Response`
39
- * (it carries `.status` + `.json`); a successful read/write is a plain record.
40
- * Return the Response as-is so the endpoint answers with THAT HTTP status and
41
- * its named error, and pass a record through unchanged.
72
+ * (it carries `.status` + `.json`). A successful read returns the readable
73
+ * memory, and a successful ordinary write returns a write receipt; returned
74
+ * refusal Responses retain their HTTP status and body. Return the Response
75
+ * as-is so the endpoint answers with THAT HTTP status and its named error, and
76
+ * pass a successful result through unchanged.
42
77
  * Returning an unwrapped write refusal would serialize it as HTTP 200;
43
78
  * unwrapping a read refusal would replace it with the generic 404 below.
44
79
  */
@@ -48,6 +83,53 @@ function asResponse(value) {
48
83
  }
49
84
  return null;
50
85
  }
86
+ /**
87
+ * The archive's authoritative read and its write body: re-read the row with
88
+ * `c` (in the transaction `c` carries), return a read refusal with its own
89
+ * status, refuse a missing row (404) or one whose persisted row differs from
90
+ * the basis (409 `memory_changed`), and merge
91
+ * the archive fields into the re-read row. The re-read row's embedding is kept;
92
+ * pointer fields are omitted so the stored pointer row stands.
93
+ */
94
+ async function rereadAndMerge(id, c, persistedBasis, archived, callerId) {
95
+ const reread = await Memory.get(id, c);
96
+ const rereadRefusal = asResponse(reread);
97
+ if (rereadRefusal)
98
+ return rereadRefusal;
99
+ if (!reread || typeof reread !== "object" || !reread.id) {
100
+ return json(404, { error: "memory not found" });
101
+ }
102
+ const persistedReread = await databases.flair.Memory.get(id, c);
103
+ if (!persistedReread)
104
+ return json(404, { error: "memory not found" });
105
+ if (!isDeepStrictEqual(persistedReread, persistedBasis)) {
106
+ return json(409, { error: "memory_changed" });
107
+ }
108
+ const merged = {
109
+ ...reread,
110
+ archived,
111
+ updatedAt: new Date().toISOString(),
112
+ };
113
+ if (archived) {
114
+ // archivedBy is set by the caller. Memory's shared locked PUT body
115
+ // (putLocked, which putMemoryWithLock enters for this non-skill row)
116
+ // handles text redaction and embedding, and the archivedAt stamp the file
117
+ // header describes. The archive request retains the existing embedding — do NOT
118
+ // clear it (clearing would force a needless re-embed and, if the
119
+ // embedding engine is unavailable, silently drop the vector).
120
+ merged.archivedBy = callerId;
121
+ }
122
+ else {
123
+ delete merged.archivedAt;
124
+ delete merged.archivedBy;
125
+ }
126
+ // flair#1940 A3 (item 9): omit every pointer field from the write-back so
127
+ // the stored pointer row, its full URL and its scope stand.
128
+ delete merged.hostSource;
129
+ delete merged.hostSourceScope;
130
+ delete merged.hostSourceVisibility;
131
+ return merged;
132
+ }
51
133
  export class MemoryArchive extends Resource {
52
134
  /** POST requires auth — an agent acting on its own memories (or admin). */
53
135
  async allowCreate() {
@@ -68,6 +150,9 @@ export class MemoryArchive extends Resource {
68
150
  return json(403, { error: "forbidden" });
69
151
  // Read the existing record — Memory.get()'s read-scope gate applies (own +
70
152
  // org-non-private only). A non-readable id returns a 404 Response.
153
+ // Non-admin reads of retained closed skill payloads also apply
154
+ // `closedSkillPayloadReadable`; a failed check returns 404 by id or omits
155
+ // the collection row.
71
156
  const existing = await Memory.get(id, ctx);
72
157
  const readRefusal = asResponse(existing);
73
158
  if (readRefusal)
@@ -84,53 +169,53 @@ export class MemoryArchive extends Resource {
84
169
  const beforeReread = txnPausePoint("memory-archive-pre");
85
170
  if (beforeReread)
86
171
  await beforeReread;
87
- // flair#2275: re-read the row INSIDE a transaction this call OWNS and build
88
- // the write from THAT read — never from the basis above, which another
89
- // writer may have changed before the write. Unequal persisted rows are
90
- // refused (409); a non-readable row returns 404. Changes after the re-read
91
- // are not checked.
92
- return await withOwnedTransaction(ctx, async (c) => {
93
- const reread = await Memory.get(id, c);
94
- const rereadRefusal = asResponse(reread);
95
- if (rereadRefusal)
96
- return rereadRefusal;
97
- if (!reread || typeof reread !== "object" || !reread.id) {
98
- return json(404, { error: "memory not found" });
99
- }
100
- const persistedReread = await databases.flair.Memory.get(id, c);
101
- if (!persistedReread)
102
- return json(404, { error: "memory not found" });
103
- if (!isDeepStrictEqual(persistedReread, persistedBasis)) {
104
- return json(409, { error: "memory_changed" });
105
- }
106
- const merged = {
107
- ...reread,
108
- archived,
109
- updatedAt: new Date().toISOString(),
110
- };
111
- if (archived) {
112
- // archivedBy is set by the caller (Memory.put() stamps archivedAt when
113
- // archived===true). The content is unchanged, so the existing embedding
114
- // stays valid — do NOT clear it (clearing would force a needless re-embed
115
- // and, if the embedding engine is unavailable, silently drop the vector).
116
- merged.archivedBy = auth.agentId;
117
- }
118
- else {
119
- delete merged.archivedAt;
120
- delete merged.archivedBy;
121
- }
122
- // flair#1940 A3 (item 9): omit every pointer field from the write-back so
123
- // the stored pointer row, its full URL and its scope stand.
124
- delete merged.hostSource;
125
- delete merged.hostSourceScope;
126
- delete merged.hostSourceVisibility;
127
- // Write back — Memory.put()'s ownership gate applies (stampAttribution), so
128
- // a non-admin caller cannot flip another agent's memory (403).
129
- const result = await Memory.put(merged, c);
130
- const writeRefusal = asResponse(result);
131
- if (writeRefusal)
132
- return writeRefusal;
133
- return result;
134
- });
172
+ // A skill row keeps the existing Memory.put() path, and its skill-state
173
+ // refusals, in a transaction this call owns (not converted to the checked
174
+ // write yet).
175
+ if (rowIsSkill(persistedBasis)) {
176
+ return await withOwnedTransaction(ctx, async (c) => {
177
+ const merged = await rereadAndMerge(id, c, persistedBasis, archived, auth.agentId);
178
+ if (merged instanceof Response)
179
+ return merged;
180
+ const result = await Memory.put(merged, c);
181
+ return asResponse(result) ?? result;
182
+ });
183
+ }
184
+ // flair#2478 part 3a: the lock set is the id and the row its `supersedes`
185
+ // names (the PUT body's possible close target), read from the basis. A
186
+ // row whose stored reference differs at the re-read is refused 409 below,
187
+ // before any write.
188
+ const targetId = String(persistedBasis.id);
189
+ const lockIds = [targetId];
190
+ if (typeof persistedBasis.supersedes === "string") {
191
+ lockIds.push(persistedBasis.supersedes);
192
+ const canonical = resolveMemoryReferenceId(persistedBasis.supersedes);
193
+ if (canonical !== undefined)
194
+ lockIds.push(canonical);
195
+ }
196
+ const outcome = await withMemoryWriteLock(memoryPrimaryStore(), lockIds, (held) => withLockedMemoryTransaction(held, ctx, async (tx) => {
197
+ // flair#2275: re-read the row INSIDE the locked transaction and build the
198
+ // write from THAT read — never from the basis above, which another writer
199
+ // may have changed before the lock was taken. Unequal persisted rows are
200
+ // refused (409); a read refusal keeps its own status, and a missing row
201
+ // returns 404.
202
+ const merged = await rereadAndMerge(id, lockedTransactionContext(tx), persistedBasis, archived, auth.agentId);
203
+ if (merged instanceof Response)
204
+ return merged;
205
+ // Memory.put()'s write body, joined to this transaction: its ownership
206
+ // gate (stampAttribution) applies, so a non-admin caller cannot flip
207
+ // another agent's memory (403).
208
+ return putMemoryWithLock(held, tx, { id: targetId, content: merged, confirmFields: ARCHIVE_FIELDS });
209
+ }), { phase: `archive-${action}` });
210
+ if (outcome.kind === "busy")
211
+ return memoryBusyResponse(memoryLockCallerIdFor(ctx));
212
+ if (outcome.kind === "unknown")
213
+ return writeOutcomeUnknownResponse();
214
+ if (outcome.kind === "unavailable")
215
+ return memoryLockUnavailableResponse();
216
+ const written = outcome.value;
217
+ if (written.kind === "refused")
218
+ return written.response;
219
+ return written.confirmed[0];
135
220
  }
136
221
  }
@@ -29,6 +29,7 @@ import { SKILL_ASSIGNMENT_KEY } from "./skill-provenance.js";
29
29
  import { SKILL_TAG } from "./skill-write.js";
30
30
  import { SKILL_ROW_SELECT, receivesOrgSkills, resolvableSkillRows, resolveSkillManifest, skillLine, } from "./skill-manifest.js";
31
31
  import { localInstanceId } from "./instance-identity.js";
32
+ import { RESERVED_EVENT_KINDS } from "./org-event-reserved.js";
32
33
  /**
33
34
  * POST /MemoryBootstrap
34
35
  *
@@ -302,11 +303,8 @@ export class BootstrapMemories extends Resource {
302
303
  includeTrust = false, // flair#744 slice 1 — opt-in per-memory trust block
303
304
  abstain = false, // flair#744 slice 2 — opt-in task-relevance abstention
304
305
  // flair#1199 — org-event knobs. `maxEvents` caps how many events ship
305
- // (default MAX_ORG_EVENTS); `includeEventDetail` gates the verbose per-event
306
- // `detail` JSON (default OFF — mirrors the includeContext opt-in). By
307
- // default bootstrap ships LEAN events (id/kind/summary/createdAt/targetIds/
308
- // scope); `detail` restates the summary + migration internals and is pure
309
- // bloat for a connector, so it is opt-in. Both are also counted against the
306
+ // (default MAX_ORG_EVENTS); `includeEventDetail` gates ordinary event
307
+ // `detail` JSON (default OFF). Events are counted against the
310
308
  // shared tokenBudget below (before #1199 the events array was assembled but
311
309
  // NEVER charged, so a maxTokens=4000 request serialized well past budget).
312
310
  maxEvents, includeEventDetail = false,
@@ -1461,7 +1459,7 @@ export class BootstrapMemories extends Resource {
1461
1459
  ...(seekTs
1462
1460
  ? { conditions: [{ attribute: "createdAt", comparator: "greater_than_equal", value: seekTs }] }
1463
1461
  : {}),
1464
- select: ["id", "kind", "summary", "detail", "targetIds", "createdAt", "expiresAt", "scope"],
1462
+ select: ["id", "kind", "summary", "detail", "targetIds", "createdAt", "expiresAt", "scope", "refId"],
1465
1463
  }));
1466
1464
  for await (const event of recentEvents) {
1467
1465
  if (!isCatchupEligible(event, { participantId: agentId, after: eventWatermark, since: sinceFloor }))
@@ -1477,18 +1475,11 @@ export class BootstrapMemories extends Resource {
1477
1475
  continue;
1478
1476
  eventResults.push(event);
1479
1477
  }
1480
- // flair#1200 — collapse byte-identical duplicate events before rendering.
1481
- // The same logical event can land in the table more than once (a producer
1482
- // that double-fires, or the same broadcast emitted from two paths); each
1483
- // physical row has a distinct id/createdAt (OrgEvent.post keys the id off
1484
- // a millisecond timestamp), so they aren't caught by primary-key upsert
1485
- // and render as exact dupes. Org-event slots are scarce, so dedup BEFORE
1486
- // admission — otherwise ~half the slots are wasted on duplicates. Keyed on
1487
- // the CONTENT (kind + summary + detail + targets), keeping the most-recent
1488
- // occurrence per signature.
1478
+ // flair#1200 — dedup before admission, keeping the most recent occurrence.
1479
+ // Instruction events use version refs; other events use content.
1489
1480
  const eventBySignature = new Map();
1490
1481
  for (const evt of eventResults) {
1491
- const sig = JSON.stringify([
1482
+ const sig = JSON.stringify(RESERVED_EVENT_KINDS.includes(evt.kind) ? ["instruction", evt.refId] : [
1492
1483
  evt.kind ?? "",
1493
1484
  evt.summary ?? "",
1494
1485
  evt.detail ?? "",
@@ -1504,7 +1495,7 @@ export class BootstrapMemories extends Resource {
1504
1495
  // NEVER charged: a maxTokens=4000 request serialized at 6286 (+57%), the
1505
1496
  // bulk being 10 events each shipping a `detail` JSON. Now each event's
1506
1497
  // REAL serialized cost (the structured object that actually ships — lean by
1507
- // default, `detail` only under includeEventDetail) is charged against the
1498
+ // default, ordinary `detail` under includeEventDetail) is charged against the
1508
1499
  // remaining budget, so events respect maxTokens the same way every other
1509
1500
  // content section does. An event that doesn't fit is skipped, not silently
1510
1501
  // over-budget; smaller later events may still fit (hence continue, not
@@ -1519,18 +1510,17 @@ export class BootstrapMemories extends Resource {
1519
1510
  eventsRemaining++;
1520
1511
  continue;
1521
1512
  }
1522
- // The structured object a connector actually reads (flair#1206). Lean by
1523
- // default; `detail` (the verbose migration-internals/summary-restating
1524
- // JSON) only when explicitly requested. Optional fields are omitted when
1525
- // absent so the object stays compact.
1513
+ // The structured object a connector actually reads (flair#1206).
1514
+ const instructionEvent = RESERVED_EVENT_KINDS.includes(evt.kind);
1526
1515
  const structured = {
1527
1516
  id: evt.id,
1528
1517
  kind: evt.kind,
1529
1518
  summary: evt.summary,
1530
- ...(includeEventDetail && evt.detail != null ? { detail: evt.detail } : {}),
1519
+ ...((includeEventDetail || instructionEvent) && evt.detail != null ? { detail: evt.detail } : {}),
1531
1520
  ...(Array.isArray(evt.targetIds) && evt.targetIds.length > 0 ? { targetIds: evt.targetIds } : {}),
1532
1521
  createdAt: evt.createdAt ?? null,
1533
1522
  ...(evt.scope != null ? { scope: evt.scope } : {}),
1523
+ ...(instructionEvent && evt.refId != null ? { refId: evt.refId } : {}),
1534
1524
  };
1535
1525
  // Charge the REAL serialized cost of what ships (structured object on the
1536
1526
  // /mcp path; the prose line is a subset of it). This is the #1199 fix:
@@ -1,6 +1,7 @@
1
1
  import { databases } from "harper";
2
2
  import { resolveAgentAuth } from "./agent-auth.js";
3
3
  import { guardOwnerFieldImmutable } from "./owner-field-guard.js";
4
+ import { guardAuthorityFields } from "./authority-field-guard.js";
4
5
  import { deleteOwnedRow } from "./owner-delete-recheck.js";
5
6
  import { txnPausePoint } from "./txn-pause-point.js";
6
7
  import { makeAuthGate, makeReadScope, makeScopedSearch, makeByIdReadGate, resolveAuthGate, stampAttribution, FORBIDDEN, UNAUTH, } from "./record-type-kit.js";
@@ -53,8 +54,11 @@ const memoryCandidateAuthGate = makeAuthGate();
53
54
  * (mirrors MemoryGrant.ts's delete() ownership check). Internal calls (the
54
55
  * FLAIR-NIGHTLY-REM staging writer — resources/MemoryReflect.ts's
55
56
  * `databases.flair.MemoryCandidate.put(row)` — and resources/health.ts's
56
- * pending-count read) and admin agents pass every method unfiltered, exactly
57
- * like every other table this pattern covers.
57
+ * pending-count read) and admin agents pass the ownership checks of every
58
+ * method unfiltered, exactly like every other table this pattern covers. The
59
+ * promoted-row identity (`promotedRowId`, `promotedRowInstanceToken`,
60
+ * flair#2645) is server-written: a REST POST, PUT or PATCH that changes it is
61
+ * refused for every caller, admin included.
58
62
  */
59
63
  export class MemoryCandidate extends databases.flair.MemoryCandidate {
60
64
  /**
@@ -114,6 +118,10 @@ export class MemoryCandidate extends databases.flair.MemoryCandidate {
114
118
  const auth = await resolveAgentAuth(ctx);
115
119
  if (auth.kind === "anonymous")
116
120
  return UNAUTH();
121
+ // flair#2645: the promoted-row identity is server-written.
122
+ const authorityDenial = await guardAuthorityFields(() => undefined, content, "MemoryCandidate");
123
+ if (authorityDenial)
124
+ return authorityDenial;
117
125
  const attr = stampAttribution(auth, content, RECORD_TYPES.MemoryCandidate.ownerField, RECORD_TYPES.MemoryCandidate.attribution.post, "forbidden: cannot stage a memory candidate for another agent");
118
126
  if (attr.denied)
119
127
  return attr.denied;
@@ -134,12 +142,18 @@ export class MemoryCandidate extends databases.flair.MemoryCandidate {
134
142
  const denial = await guardOwnerFieldImmutable(this, () => super.get(), content, "agentId");
135
143
  if (denial)
136
144
  return denial;
145
+ const authorityDenial = await guardAuthorityFields(() => super.get(), content, "MemoryCandidate");
146
+ if (authorityDenial)
147
+ return authorityDenial;
137
148
  return super.patch(content, query);
138
149
  }
139
150
  async put(content) {
140
151
  const __ownerDenial = await guardOwnerFieldImmutable(this, () => super.get(), content, "agentId");
141
152
  if (__ownerDenial)
142
153
  return __ownerDenial;
154
+ const __authorityDenial = await guardAuthorityFields(() => super.get(), content, "MemoryCandidate");
155
+ if (__authorityDenial)
156
+ return __authorityDenial;
143
157
  const ctx = this.getContext?.();
144
158
  const auth = await resolveAgentAuth(ctx);
145
159
  if (auth.kind === "anonymous")
@@ -16,7 +16,7 @@
16
16
  * prompt string
17
17
  */
18
18
  import { Resource, databases } from "harper";
19
- import { isAdmin, allowVerified } from "./agent-auth.js";
19
+ import { annotatedCallerIsAdmin, allowVerified } from "./agent-auth.js";
20
20
  import { evaluate, parseDuration } from "./memory-consolidate-lib.js";
21
21
  import { applyHitStats } from "./hit-tracking.js";
22
22
  export class ConsolidateMemories extends Resource {
@@ -35,7 +35,7 @@ export class ConsolidateMemories extends Resource {
35
35
  const request = ctx?.request ?? ctx;
36
36
  const actorId = request?.tpsAgent;
37
37
  const callerIsAdmin = request?.tpsAgentIsAdmin === true
38
- || (actorId ? await isAdmin(actorId) : false);
38
+ || (await annotatedCallerIsAdmin(request));
39
39
  if (!bodyAgentId && !actorId) {
40
40
  return new Response(JSON.stringify({ error: "agentId required" }), { status: 400 });
41
41
  }