@tpsdev-ai/flair 0.56.0 → 0.58.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 (153) hide show
  1. package/README.md +19 -20
  2. package/SECURITY.md +4 -1
  3. package/dist/build-info.json +3 -3
  4. package/dist/cli.js +1800 -293
  5. package/dist/commands/agent.js +22 -15
  6. package/dist/commands/bridge.js +40 -3
  7. package/dist/commands/doctor.js +214 -4
  8. package/dist/commands/federation.js +265 -38
  9. package/dist/commands/hook.js +10 -2
  10. package/dist/commands/init.js +179 -48
  11. package/dist/commands/memory.js +24 -2
  12. package/dist/commands/quality.js +26 -18
  13. package/dist/commands/service.js +137 -22
  14. package/dist/commands/status.js +114 -3
  15. package/dist/commands/upgrade.js +204 -84
  16. package/dist/doctor-client.js +50 -4
  17. package/dist/federation/scheduler.js +253 -4
  18. package/dist/install/clients.js +89 -23
  19. package/dist/install/global-bin-path.js +26 -6
  20. package/dist/lib/atomic-write.js +256 -0
  21. package/dist/lib/auth-resolve.js +46 -0
  22. package/dist/lib/daemon-liveness.js +61 -0
  23. package/dist/lib/doctor-run.js +5 -0
  24. package/dist/lib/embed-gpu-doctor.js +49 -26
  25. package/dist/lib/federation-memory-attributes.js +15 -0
  26. package/dist/lib/init-admin-pass.js +4 -2
  27. package/dist/lib/init-listener-environ.js +38 -0
  28. package/dist/lib/init-occupied-listener.js +165 -0
  29. package/dist/lib/instance-identity-row.js +580 -0
  30. package/dist/lib/launchd-domain-preflight.js +448 -0
  31. package/dist/lib/launchd-management.js +176 -6
  32. package/dist/lib/launchd-repair.js +95 -0
  33. package/dist/lib/memory-attributes.js +77 -0
  34. package/dist/lib/node-alias-path.js +95 -0
  35. package/dist/lib/npm-registry.js +119 -6
  36. package/dist/lib/owned-pins.js +20 -6
  37. package/dist/lib/redact-token-id.js +197 -0
  38. package/dist/lib/service-repoint-apply.js +267 -0
  39. package/dist/lib/service-repoint.js +575 -0
  40. package/dist/lib/toml-string-array.js +104 -0
  41. package/dist/lib/tree-divergence.js +716 -0
  42. package/dist/lib/upgrade-plain-tree.js +18 -8
  43. package/dist/lib/upgrade-prior-liveness.js +69 -0
  44. package/dist/lib/upgrade-rollback.js +116 -0
  45. package/dist/rem/runner.js +11 -0
  46. package/dist/resources/Agent.js +27 -14
  47. package/dist/resources/AgentSeed.js +39 -2
  48. package/dist/resources/Asset.js +3 -11
  49. package/dist/resources/Credential.js +4 -10
  50. package/dist/resources/Federation.js +299 -127
  51. package/dist/resources/Integration.js +8 -32
  52. package/dist/resources/Memory.js +623 -86
  53. package/dist/resources/MemoryArchive.js +9 -0
  54. package/dist/resources/MemoryBootstrap.js +23 -12
  55. package/dist/resources/MemoryCandidate.js +3 -11
  56. package/dist/resources/MemoryDedupStats.js +1 -1
  57. package/dist/resources/MemoryFeed.js +214 -5
  58. package/dist/resources/MemoryGrant.js +19 -40
  59. package/dist/resources/MemoryHostSource.js +90 -0
  60. package/dist/resources/MemoryMaintenance.js +121 -32
  61. package/dist/resources/MemoryReflect.js +4 -1
  62. package/dist/resources/MemoryReindex.js +7 -4
  63. package/dist/resources/MemoryUsage.js +55 -18
  64. package/dist/resources/Presence.js +18 -10
  65. package/dist/resources/RecordUsage.js +30 -40
  66. package/dist/resources/Relationship.js +170 -89
  67. package/dist/resources/SemanticSearch.js +44 -19
  68. package/dist/resources/Soul.js +31 -19
  69. package/dist/resources/XAA.js +7 -3
  70. package/dist/resources/agent-auth.js +16 -10
  71. package/dist/resources/auth-middleware.js +164 -50
  72. package/dist/resources/auto-promote-lib.js +4 -4
  73. package/dist/resources/bm25-index-service.js +246 -32
  74. package/dist/resources/bm25-status.js +132 -0
  75. package/dist/resources/bm25.js +13 -14
  76. package/dist/resources/ed25519-auth.js +11 -54
  77. package/dist/resources/embed-gpu.js +262 -47
  78. package/dist/resources/embeddings-boot.js +52 -17
  79. package/dist/resources/federation-classify.js +12 -0
  80. package/dist/resources/federation-cleanup.js +289 -51
  81. package/dist/resources/federation-crypto.js +65 -19
  82. package/dist/resources/health.js +105 -22
  83. package/dist/resources/host-pointer/registry.js +35 -0
  84. package/dist/resources/host-pointer-adapter.js +15 -0
  85. package/dist/resources/host-source-visibility.js +167 -0
  86. package/dist/resources/host-source.js +151 -0
  87. package/dist/resources/in-process-api.js +2 -1
  88. package/dist/resources/instance-create-lock.js +363 -0
  89. package/dist/resources/instance-identity-rows.js +43 -0
  90. package/dist/resources/instance-identity.js +97 -12
  91. package/dist/resources/mcp-handler.js +155 -51
  92. package/dist/resources/mcp-tool-arguments.js +83 -0
  93. package/dist/resources/mcp-tools.js +28 -25
  94. package/dist/resources/memory-consolidate-lib.js +3 -1
  95. package/dist/resources/memory-declared-attributes.js +103 -0
  96. package/dist/resources/memory-feed-lib.js +5 -1
  97. package/dist/resources/memory-host-source.js +163 -0
  98. package/dist/resources/memory-visibility.js +10 -7
  99. package/dist/resources/migrations/synthetic-test-migration.js +4 -1
  100. package/dist/resources/migrations/visibility-backfill.js +4 -1
  101. package/dist/resources/originator-instance.js +235 -0
  102. package/dist/resources/promotion-stamp.js +2 -0
  103. package/dist/resources/provenance.js +111 -11
  104. package/dist/resources/rate-limit.js +6 -4
  105. package/dist/resources/record-owner-guard.js +19 -0
  106. package/dist/resources/record-type-kit.js +44 -23
  107. package/dist/resources/record-types.js +6 -6
  108. package/dist/resources/relay-ops.js +28 -3
  109. package/dist/resources/replay-store.js +289 -0
  110. package/dist/resources/request-transaction.js +78 -0
  111. package/dist/resources/search-readiness.js +26 -22
  112. package/dist/resources/semantic-retrieval-core.js +103 -4
  113. package/dist/resources/table-helpers.js +33 -0
  114. package/dist/resources/table-patch-policy.js +109 -0
  115. package/dist/resources/table-patches.js +17 -0
  116. package/dist/resources/table-post-policy.js +138 -0
  117. package/dist/resources/table-posts.js +22 -0
  118. package/dist/resources/table-subscription-policy.js +135 -0
  119. package/dist/resources/table-subscriptions.js +19 -0
  120. package/dist/resources/tool-descriptors/index.js +15 -15
  121. package/dist/resources/trust-block.js +10 -3
  122. package/dist/resources/usage-recording.js +169 -41
  123. package/dist/src/lib/instance-identity-row.js +580 -0
  124. package/dist/src/lib/memory-attributes.js +77 -0
  125. package/dist/src/lib/redact-token-id.js +197 -0
  126. package/docs/api-reference.md +80 -16
  127. package/docs/auth.md +5 -5
  128. package/docs/claude-code.md +137 -6
  129. package/docs/deploying-on-fabric.md +6 -3
  130. package/docs/deployment.md +1 -1
  131. package/docs/embedding-in-a-harper-app.md +3 -3
  132. package/docs/federation.md +17 -10
  133. package/docs/hosted-on-fabric.md +4 -3
  134. package/docs/integrations.md +28 -19
  135. package/docs/mcp-clients.md +26 -32
  136. package/docs/n8n.md +8 -8
  137. package/docs/notes/mcp-oauth-model2.md +27 -18
  138. package/docs/openclaw.md +29 -28
  139. package/docs/quickstart.md +5 -0
  140. package/docs/releasing.md +134 -2
  141. package/docs/spoke-bringup.md +14 -11
  142. package/docs/standalone-local.md +2 -2
  143. package/docs/supply-chain-policy.md +28 -10
  144. package/docs/system-requirements.md +1 -1
  145. package/docs/troubleshooting.md +11 -0
  146. package/docs/upgrade.md +189 -63
  147. package/package.json +9 -5
  148. package/schemas/agent.graphql +9 -6
  149. package/schemas/federation.graphql +2 -11
  150. package/schemas/memory.graphql +106 -17
  151. package/schemas/replay.graphql +18 -0
  152. package/templates/launchd/start-flair-with-admin-pass.sh +22 -0
  153. package/dist/resources/federation-nonce-store.js +0 -195
@@ -1,26 +1,217 @@
1
1
  import { databases } from "harper";
2
+ import { randomUUID } from "node:crypto";
2
3
  import { patchRecord, withDetachedTxn } from "./table-helpers.js";
3
4
  import { isAdmin, resolveAgentAuth } from "./agent-auth.js";
4
5
  import { guardAuthorityFields } from "./authority-field-guard.js";
5
6
  import { isForbiddenOwnerMutation } from "./record-owner-guard.js";
6
7
  import { guardOwnerFieldImmutable } from "./owner-field-guard.js";
7
- import { localInstanceId } from "./instance-identity.js";
8
+ import { applyFederationBookkeeping, applyOriginatorInstanceId, dropClientFederationBookkeeping, keepStoredOriginator, resolveStoredRow, stampOriginatorOnCreate } from "./originator-instance.js";
8
9
  import { getEmbedding, getModelId } from "./embeddings-provider.js";
9
10
  import { isEmbeddingSpaceUniform, noteWriteStamp } from "./embedding-space-guard.js";
10
11
  import { scanFields, isStrictMode } from "./content-safety.js";
11
12
  import { invalidEntitiesResponse } from "./entity-vocab.js";
12
13
  import { checkRateLimit, rateLimitResponse } from "./rate-limiter.js";
13
- import { assertValidVisibility, assertVisibilityAllowedForDurability } from "./memory-visibility.js";
14
+ import { assertValidVisibility, assertVisibilityAllowedForDurability, PRIVATE_VISIBILITY, SHARED_VISIBILITY } from "./memory-visibility.js";
15
+ import { validateHostSource } from "./host-source.js";
16
+ import { buildPointerRow, extractPointerInputs, isPointerEchoOf, loadStoredPointer, projectRowsThroughPointers, } from "./memory-host-source.js";
17
+ import { putPointerRow, deletePointerRowViaTable } from "./host-pointer-adapter.js";
18
+ import { stripUndeclaredMemoryAttributes, stripServerStampedFields } from "./memory-declared-attributes.js";
19
+ import { isJoinableTransaction, withSharedWriteTransaction } from "./request-transaction.js";
14
20
  import { assertValidDurability } from "./memory-durability.js";
15
21
  import { enforceSkillDurability, rejectSkillWritePath, refuseSkillWriteSource, skillEmbedText, skillScanGate } from "./skill-write.js";
16
22
  import { DEDUP_COSINE_THRESHOLD_DEFAULT, DEDUP_LEXICAL_THRESHOLD_DEFAULT, DEDUP_MIN_CONTENT_LENGTH, computeMatchConfidence, cosineSimilarity, isConservativeMatch, } from "./dedup.js";
17
23
  import { buildProvenance, makeAuthGate, makeReadScope, makeByIdReadGate, makeScopedSearch, resolveAuthGate, stampAttribution, FORBIDDEN, UNAUTH, } from "./record-type-kit.js";
24
+ import { isSemanticPatch, MEMORY_SEMANTIC_FIELDS } from "./provenance.js";
18
25
  import { RECORD_TYPES } from "./record-types.js";
19
26
  import { attachTrust } from "./trust-block.js";
20
27
  import { recordCitations } from "./usage-recording.js";
21
28
  import { noteMemoryUpsert, noteMemoryDelete } from "./bm25-index-service.js";
22
29
  import { applyHitStats, clearHitStats, overlayHitStatsResult } from "./hit-tracking.js";
23
30
  import { refuseStaleClientWrite, stripClientVersionPassthrough } from "./client-version-gate.js";
31
+ /** flair#1940 A1' — a named 400 for an invalid host pointer (reject, never
32
+ * truncate). Same shape the pre-A1' inline checks returned. */
33
+ function hostSourceBadRequest(error, message) {
34
+ return new Response(JSON.stringify({ error, message }), {
35
+ status: 400,
36
+ headers: { "content-type": "application/json" },
37
+ });
38
+ }
39
+ /**
40
+ * flair#1940 round 18 — drop a caller `select`/`property` from a non-admin
41
+ * collection read so the gated pointer join sees the stored rows. This is NOT a
42
+ * selection parser: it removes the two keys and leaves every other query
43
+ * property (conditions, operator, sort, limit, offset, ...) exactly as sent. A
44
+ * query without a selection is returned unchanged.
45
+ */
46
+ function withoutCallerSelection(query) {
47
+ if (!query || typeof query !== "object")
48
+ return query;
49
+ if (query.select === undefined && query.property === undefined)
50
+ return query;
51
+ const copy = Array.isArray(query) ? query.slice() : { ...query };
52
+ delete copy.select;
53
+ delete copy.property;
54
+ return copy;
55
+ }
56
+ /**
57
+ * Write the Memory row joining transaction `c` (0a). Resource.prototype.post
58
+ * uses the instance's OWN `#context`, which an internal caller (a direct
59
+ * `new Memory().post(...)`) does not have, and the base table has no `post` —
60
+ * so the base collection `create(id, record, context)` is used, which honours
61
+ * an explicit context and joins `c.transaction`. Returns the new id. Falls
62
+ * back to the static post for the unit mock (which models post, not create).
63
+ */
64
+ async function writeMemoryRowPost(cls, content, c) {
65
+ if (typeof cls?.create === "function") {
66
+ const created = await cls.create(content.id ?? null, content, c);
67
+ if (typeof created === "string")
68
+ return created;
69
+ return created?.getId?.() ?? created?.id ?? content.id ?? "";
70
+ }
71
+ const r = await databases.flair.Memory.post(content, c);
72
+ return r?.id ?? content.id ?? "";
73
+ }
74
+ /** The authenticated author id for a pointer row, or "" when there is no
75
+ * principal (internal write). NEVER the body. */
76
+ function pointerAuthorId(auth) {
77
+ return auth.kind === "agent" ? auth.agentId : "";
78
+ }
79
+ /** A fresh server-stamped row incarnation token (flair#1940 A1-iv item 1). */
80
+ function newInstanceToken() {
81
+ return randomUUID();
82
+ }
83
+ /** Stamp the row incarnation token for a write: PRESERVE the existing row's
84
+ * token on an update, else generate a fresh one (call AFTER
85
+ * stripServerStampedFields, so a client-supplied value is gone first). */
86
+ function stampInstanceToken(content, existing) {
87
+ const preserved = existing && typeof existing.instanceToken === "string" && existing.instanceToken.length > 0
88
+ ? existing.instanceToken
89
+ : null;
90
+ content.instanceToken = preserved ?? newInstanceToken();
91
+ }
92
+ /**
93
+ * flair#1940 A1' — validate the write body's pointer inputs and build the
94
+ * pointer row (canonical hostSource + scopeAtWrite + server-stamped
95
+ * authorId/receivedAt). Returns a 400 `denial` on an invalid pointer/scope,
96
+ * `row: null` when the body carries no pointer, else the row to persist.
97
+ */
98
+ function buildPointerForWrite(args) {
99
+ const { inputs, memoryId, visibility, auth, memoryInstanceToken, storedPointer } = args;
100
+ if (inputs.hostSource === undefined || inputs.hostSource === null) {
101
+ if (inputs.hostSourceScope !== undefined) {
102
+ return { row: null, denial: hostSourceBadRequest("invalid_host_source_scope", "hostSourceScope requires a hostSource") };
103
+ }
104
+ return { row: null };
105
+ }
106
+ const hs = validateHostSource(inputs.hostSource);
107
+ if (!hs.ok)
108
+ return { row: null, denial: hostSourceBadRequest("invalid_host_source", hs.error) };
109
+ // Only an author's exact echo of the stored full canonical value preserves
110
+ // the pointer row. A normally projected URL has its query and fragment
111
+ // removed and is not an exact echo.
112
+ if (inputs.hostSourceScope === undefined &&
113
+ storedPointer &&
114
+ isPointerEchoOf(inputs.hostSource, storedPointer, pointerAuthorId(auth))) {
115
+ return { row: null };
116
+ }
117
+ let scopeAtWrite = null;
118
+ if (inputs.hostSourceScope !== undefined) {
119
+ if (inputs.hostSourceScope !== "record") {
120
+ return {
121
+ row: null,
122
+ denial: hostSourceBadRequest("invalid_host_source_scope", `hostSourceScope must be "record" or omitted; a scope wider than the record is refused (got ${JSON.stringify(inputs.hostSourceScope)})`),
123
+ };
124
+ }
125
+ scopeAtWrite = visibility ?? null;
126
+ }
127
+ return {
128
+ row: buildPointerRow({
129
+ memoryId,
130
+ canonical: hs.canonical,
131
+ scopeAtWrite,
132
+ authorId: pointerAuthorId(auth),
133
+ memoryInstanceToken: memoryInstanceToken ?? null,
134
+ receivedAt: new Date().toISOString(),
135
+ }),
136
+ };
137
+ }
138
+ /** A fixed 500 body for a pointer that could not be persisted. The RESPONSE
139
+ * carries only a fixed message, never the raw error/stack (CodeQL:
140
+ * information exposure through a stack trace). */
141
+ function hostSourcePersistFailure(message) {
142
+ return new Response(JSON.stringify({ error: "host_source_persist_failed", message }), {
143
+ status: 500,
144
+ headers: { "content-type": "application/json" },
145
+ });
146
+ }
147
+ /**
148
+ * Abort the request's open transaction so the Memory row staged into it is
149
+ * rolled back with the failed pointer row (flair#1940 A1' item 2). This is
150
+ * exactly harper 5.2.8's `transaction.abort(context)` (dist/resources/
151
+ * transaction.js): resolve `context.transaction` and abort it. The module is
152
+ * not importable as a named export of the `harper` package (its exports map
153
+ * exposes only "."), so we call the transaction object the context already
154
+ * carries. A context with no open transaction has nothing to abort (the unit
155
+ * lane's hand-built contexts).
156
+ */
157
+ function abortRequestTransaction(ctx) {
158
+ const txn = ctx?.transaction;
159
+ if (!txn || typeof txn.abort !== "function")
160
+ return;
161
+ // A failed abort is an ERROR, not a normal response (A1-iv item 4): if the
162
+ // transaction cannot be aborted, the rollback is not established, so the
163
+ // failure MUST propagate rather than being swallowed behind a 500 body.
164
+ txn.abort();
165
+ }
166
+ /**
167
+ * flair#1940 A1' item 2 — persist the pointer row in the SAME request
168
+ * transaction as the Memory row. The request context is passed to the table
169
+ * write so Harper's `txnForContext` joins the write to the request's open
170
+ * transaction (`context.transaction`, joinable) instead of opening its own —
171
+ * both tables live in database flair, so both rows commit together or not at
172
+ * all. On failure the request transaction is ABORTED, so the already-staged
173
+ * Memory row never commits, and the fixed 500 body is returned. There is no
174
+ * compensating delete: the transaction is the mechanism. Returns null on
175
+ * success.
176
+ */
177
+ async function persistPointerRow(row, ctx) {
178
+ try {
179
+ // The pointer-table ADAPTER (flair#1940 A1-iv item 6) writes via the real
180
+ // MemoryHostSource table in production; a test drives a failing write from
181
+ // TEST code (the shared Harper mock). A missing table throws (fail closed).
182
+ await putPointerRow(row, ctx);
183
+ return null;
184
+ }
185
+ catch (err) {
186
+ // Abort the request transaction so NEITHER row commits, then fail the
187
+ // write. No silent loss (A7): the write fails loudly.
188
+ abortRequestTransaction(ctx);
189
+ console.error("Memory: host-source pointer persist failed (write aborted)", err);
190
+ return hostSourcePersistFailure("host-source pointer could not be persisted");
191
+ }
192
+ }
193
+ /** flair#1940 A1' item 6 (A1'' item 2) — cascade: delete the pointer row where a
194
+ * Memory row dies. The delete is passed the request context so it JOINS the
195
+ * request transaction (both tables in database flair), so a failing pointer
196
+ * delete fails the whole operation atomically; failures are NEVER swallowed.
197
+ * Returns null on success, a fixed 500 body on failure (after aborting the
198
+ * request transaction so nothing commits). */
199
+ async function deletePointerRow(memoryId, ctx) {
200
+ try {
201
+ // The pointer-table ADAPTER (A1-iv item 6); a missing table throws (fail
202
+ // closed, never a silent skip).
203
+ await deletePointerRowViaTable(memoryId, ctx);
204
+ return null;
205
+ }
206
+ catch (err) {
207
+ abortRequestTransaction(ctx);
208
+ console.error("Memory: host-source pointer delete failed (delete aborted)", err);
209
+ return new Response(JSON.stringify({ error: "host_source_delete_failed", message: "host-source pointer could not be deleted" }), {
210
+ status: 500,
211
+ headers: { "content-type": "application/json" },
212
+ });
213
+ }
214
+ }
24
215
  /**
25
216
  * flair#744 slice 1 — read the opt-in `includeTrust` flag for a by-id get.
26
217
  * Two entry shapes: an in-process caller (resources/mcp-tools.ts's memory_get)
@@ -47,8 +238,10 @@ function wantsTrust(target, opts) {
47
238
  return raw === "true" || raw === true;
48
239
  }
49
240
  /**
50
- * Owner ids a non-admin agent may READ (resolveAllowedOwners) live in
51
- * ./memory-read-scope.ts — still exported/used elsewhere (admin tooling).
241
+ * resolveAllowedOwners (./memory-read-scope.ts) no longer bounds reads — a
242
+ * non-admin reader sees its own records at any visibility plus every other
243
+ * agent's non-private records (resolveReadScope()); the helper is kept for
244
+ * admin tooling only.
52
245
  * The full read-scope condition + private-exclusion predicate is now
53
246
  * consumed through ./record-type-kit.ts's makeReadScope(), parameterized
54
247
  * from RECORD_TYPES.Memory (record-types slice 2, flair#520) rather than a
@@ -292,7 +485,7 @@ async function runDedupGate(ctx, content) {
292
485
  return findConservativeDedupMatch(ctx, content.agentId, embedText, embedding, cosineThreshold, lexicalThreshold);
293
486
  }
294
487
  /** Build the final write response: always `written: true`, always includes
295
- * `id`, `visibility`, and layers the dedup collision signal on top when
488
+ * `id`, includes `visibility` when the persisted row has one, and layers the dedup collision signal on top when
296
489
  * present. Never a code path where a match suppresses these base fields.
297
490
  *
298
491
  * ── Why `visibility` is in the write response (flair#991) ──────────────────
@@ -309,9 +502,9 @@ async function runDedupGate(ctx, content) {
309
502
  * Read from `content`, not from `base`: `content.visibility` is the value
310
503
  * that was actually persisted a few lines earlier, and assigning after the
311
504
  * `...base` spread means the persisted value wins over anything the storage
312
- * layer echoes back. Omitted (not `null`) when unset, which happens only on
313
- * the put()-over-an-existing-record path where a partial merge carried no
314
- * visibility — reporting `null` there would read as "no one but the owner",
505
+ * layer echoes back. Omitted (not `null`) when unset, which happens only for
506
+ * an existing record that has no stored writable visibility — reporting `null`
507
+ * there would read as "no one but the owner",
315
508
  * the opposite of what an absent field means to `isPrivateVisibility()`. */
316
509
  function buildWriteResponse(content, result, dedupMatch) {
317
510
  const base = result && typeof result === "object" && !Array.isArray(result) ? result : {};
@@ -344,14 +537,16 @@ async function closeSupersededRecord(ctx, oldId, patch) {
344
537
  throw new Error(`supersede-close: record ${oldId} not found`);
345
538
  }
346
539
  const closed = { ...existing, ...patch };
540
+ stripUndeclaredMemoryAttributes(closed);
347
541
  await withDetachedTxn(ctx, () => databases.flair.Memory.put(closed));
348
542
  // flair#1357 — a supersede-close sets `validTo`, which the retrieval filters
349
543
  // read, so the lexical index has to see it as eagerly as a content write.
350
544
  noteMemoryUpsert(closed);
351
545
  }
352
546
  /** Does an agent hold a "write" grant from `ownerId`? Same MemoryGrant lookup
353
- * pattern as Memory.search()/SemanticSearch.ts (read/search scopes) — reused
354
- * here for the "write" scope that gates cross-agent supersede. */
547
+ * the read paths used before the open-within-org reframe (reads no longer
548
+ * consult MemoryGrant); it survives here for the "write" scope that gates
549
+ * cross-agent supersede. */
355
550
  async function hasWriteGrant(granteeId, ownerId) {
356
551
  try {
357
552
  for await (const grant of databases.flair.MemoryGrant.search({
@@ -468,43 +663,27 @@ function defaultVisibilityForDurability(durability) {
468
663
  * "reuse buildProvenance as-is" contract) instead of a hand-copied format
469
664
  * that could drift. See that module for the full field-by-field rationale
470
665
  * (verified.agentId from the auth verdict never the body, verified.timestamp
471
- * = the server-computed createdAt, optional unverified claimed.model /
472
- * claimed.client passthroughs — the latter added by flair#718 authorship-
473
- * provenance). Deliberately NOT implemented in this slice: a
666
+ * = the SERVER write instant (flair#1960), optional unverified
667
+ * claimed.createdAt / claimed.model / claimed.client passthroughs — the last
668
+ * two added by flair#718 authorship-provenance). Deliberately NOT implemented
669
+ * in this slice: a
474
670
  * context-fingerprint field — bootstrap doesn't return the IDs a fingerprint
475
671
  * would need, so it requires client cooperation that's out of scope here.
476
672
  */
477
673
  /**
478
- * ─── Write-time originatorInstanceId stamp (federation-edge-hardening slice 1) ──
479
- *
480
- * Stamps this instance's own federation identity (resources/instance-
481
- * identity.ts's localInstanceId(), cached — never a DB read per write) onto
482
- * every LOCAL write. Deliberately a no-op when `content.originatorInstanceId`
483
- * already carries a non-null value: this is the anti-clobber rule that keeps
484
- * a federation-synced record's true origin intact.
485
- *
486
- * Why this can never clobber a synced record: FederationSync.post()
487
- * (resources/Federation.ts) merges incoming records via the RAW table object
488
- * (`(databases as any).flair.Memory.put(mergedData)`) — Harper's static
489
- * table-level put, not this Resource subclass's instance put() below. The
490
- * merge path never runs this function at all, so a record arriving from
491
- * instance B keeps whatever `originatorInstanceId` it already carried in
492
- * `mergedData` (that instance's own write-time stamp, carried through in the
493
- * synced row) with no risk of this instance overwriting it with its own id.
494
- * The `content.originatorInstanceId == null` guard below is still applied —
495
- * defense-in-depth for any future path that might route a synced payload
496
- * through this class's post()/put() — so the invariant holds even if that
497
- * assumption ever changes.
674
+ * ─── Write-time originatorInstanceId (federation-edge-hardening slice 1) ─────
498
675
  *
499
- * `localInstanceId()` resolves to null on an instance that has never been
500
- * federation-bootstrapped (no Instance row yet) — the field is nullable by
501
- * design, so this stamps null rather than inventing an id.
676
+ * The server-stamped `originatorInstanceId` contract and the create/update rule
677
+ * live in resources/originator-instance.ts — the single delegate Memory, Soul,
678
+ * Agent and Relationship share, so the four writers cannot drift. In short:
679
+ * a CREATE stamps this instance's own id (any body value is ignored); an UPDATE
680
+ * keeps the stored value (a body value neither replaces nor clears it); and a
681
+ * federation merge — resources/Federation.ts's FederationSync.post(), which
682
+ * applies inbound rows through the RAW table handle, never a resource method —
683
+ * preserves the originating instance's value. See that module for the full
684
+ * rationale. `content.originatorInstanceId == null` is no longer read here: a
685
+ * body value is not trusted at any point.
502
686
  */
503
- async function stampOriginatorInstanceId(content) {
504
- if (content.originatorInstanceId == null) {
505
- content.originatorInstanceId = await localInstanceId();
506
- }
507
- }
508
687
  export class Memory extends databases.flair.Memory {
509
688
  /**
510
689
  * Self-authorize now that the global gate is non-rejecting. Closes the P0
@@ -512,8 +691,10 @@ export class Memory extends databases.flair.Memory {
512
691
  * describe (`GET /Memory`) to a path outside search() — neither was gated
513
692
  * before this fix, so an anonymous caller got a 200 with full record
514
693
  * content / schema even though search() (and the write paths) correctly
515
- * 401/403'd. Per-record ownership/grant scoping happens in get() below;
516
- * the collection scope is still in search().
694
+ * 401/403'd. Per-record read scoping happens in get() below (its own records
695
+ * at any visibility plus every other agent's non-private records — grants are
696
+ * not consulted on reads; resolveReadScope()); the collection scope is still
697
+ * in search().
517
698
  *
518
699
  * allowCreate/allowUpdate/allowDelete are deliberately NOT added here:
519
700
  * post()/put()/delete() already self-enforce per-agent ownership inline
@@ -524,18 +705,19 @@ export class Memory extends databases.flair.Memory {
524
705
  */
525
706
  allowRead() { return memoryAuthGate.call(this); }
526
707
  /**
527
- * Override get() to scope by-id reads the same way search() scopes
528
- * collection reads (memory-soul-read-gate fix). Never distinguishes
529
- * "doesn't exist" from "exists but not yours" — both return 404, never
530
- * 403, so a denied caller can't use get() to enumerate other agents'
531
- * memory ids. Wired through record-type-kit.ts's makeByIdReadGate, scoped
532
- * with Memory's own "open-within-org" read-scope resolver above — same
533
- * dispatch shape Relationship.ts/WorkspaceState.ts's get() overrides use.
708
+ * Override get() to apply Memory's open-within-org scope to by-id reads,
709
+ * as search() does for collection reads. For a verified non-admin agent,
710
+ * a missing record and one outside its read scope both return 404; this
711
+ * does not disclose whether another agent's private record exists.
712
+ * Anonymous HTTP requests are denied by allowRead(), while administrator
713
+ * and trusted internal reads are unfiltered. Wired through
714
+ * record-type-kit.ts's makeByIdReadGate.
534
715
  */
535
716
  async get(target, opts) {
536
717
  // Collection / query reads — the `GET /Memory/?<query>` form and the bare
537
718
  // collection — arrive as a RequestTarget with `isCollection === true`, and
538
- // are governed by search() (same owner/grant scoping). Only a genuine by-id
719
+ // are governed by search() (same open-within-org read scope; grants are not
720
+ // consulted on reads). Only a genuine by-id
539
721
  // get is ownership-checked below. Without this guard, get() would receive
540
722
  // the query's RequestTarget, super.get() would return the (truthy) result
541
723
  // set, the single-record check would find no `.agentId` on it, and a valid
@@ -550,7 +732,39 @@ export class Memory extends databases.flair.Memory {
550
732
  if (!target || (typeof target === "object" && target.isCollection)) {
551
733
  return this.search(target);
552
734
  }
553
- const result = await memoryByIdReadGate.call(this, target, (t) => super.get(t));
735
+ const ctx = this.getContext?.();
736
+ const auth = await resolveAgentAuth(ctx);
737
+ // flair#1940 round 18 (design ruling): a non-admin read ignores the caller's
738
+ // `select`/`property` whatever the target shape — the same contract the auth
739
+ // middleware enforces for a REST read, applied here for a direct contextual
740
+ // read. Read the FULL stored row through the shared by-id gate (which builds
741
+ // its own plain id-only target) so the pointer decision below always sees
742
+ // the stored `id`, `agentId`, `instanceToken`, `archived` and `visibility`.
743
+ // A shaped read — a caller target carrying a selection, or a class that
744
+ // installs one — can never hand the join an already-projected value. Trusted
745
+ // internal and admin reads keep their target unchanged.
746
+ const nonAdminAgent = auth.kind === "agent" && !auth.isAdmin;
747
+ let readTarget = target;
748
+ if (nonAdminAgent) {
749
+ const targetId = typeof target === "string" ? target : target?.id;
750
+ readTarget = targetId != null ? { id: targetId } : {};
751
+ }
752
+ const result = await memoryByIdReadGate.call(this, readTarget, (t) => super.get(t));
753
+ // flair#1940 A3 (by-ID surface): the pointer is projected for THIS reader
754
+ // BEFORE the trust block is attached. Admin/internal stay unfiltered (they
755
+ // read the unredacted row, like every other field); a non-admin agent is
756
+ // the reader the withheld rule protects. The FULL stored row goes through
757
+ // the helper: the gated join renders a pointer ONLY when the row carries
758
+ // its `id` and `instanceToken`, and an inline pointer field on the Memory
759
+ // row is stripped from the returned object.
760
+ let projected = result;
761
+ if (result && typeof result === "object" && !(result instanceof Response)) {
762
+ if (nonAdminAgent) {
763
+ // A1' item 4 / A1-iv item 2: the gated join, through the ONE reader
764
+ // helper (projectRowsThroughPointers) — pointer | "withheld" | nothing.
765
+ projected = (await projectRowsThroughPointers([result], auth.agentId))[0];
766
+ }
767
+ }
554
768
  // flair#744 slice 1 — opt-in inline trust-evidence block, attached ONLY to
555
769
  // a genuine by-id record (never a NOT_FOUND `Response`, never null), and
556
770
  // ONLY after the ownership/read-scope gate above has already resolved. The
@@ -560,10 +774,10 @@ export class Memory extends databases.flair.Memory {
560
774
  // byte-identical to pre-slice-1.
561
775
  if (result && typeof result === "object" && !(result instanceof Response) && typeof result.agentId === "string") {
562
776
  const ctx = this.getContext?.();
563
- const withHits = await applyHitStats(result, ctx);
777
+ const withHits = await applyHitStats(projected, ctx);
564
778
  return attachTrust(withHits, wantsTrust(target, opts));
565
779
  }
566
- return result;
780
+ return projected;
567
781
  }
568
782
  /**
569
783
  * Override search() to scope collection GETs by authenticated agent.
@@ -573,7 +787,10 @@ export class Memory extends databases.flair.Memory {
573
787
  * boolean injection (e.g. [..., "or", { wildcard }]).
574
788
  *
575
789
  * Admin agents and unauthenticated internal calls pass through unfiltered.
576
- * Non-admin calls also check MemoryGrant to include granted memories.
790
+ * Non-admin calls are scoped to the reader's own records at any visibility
791
+ * plus every other agent's non-private records — the shipped open-within-org
792
+ * read model. MemoryGrant is NOT consulted on reads; the one place the scope
793
+ * is resolved is memory-read-scope.ts's resolveReadScope().
577
794
  */
578
795
  async search(query) {
579
796
  // Access request context via Harper's Resource instance context.
@@ -589,8 +806,9 @@ export class Memory extends databases.flair.Memory {
589
806
  return gate.response;
590
807
  if (gate.kind === "unfiltered")
591
808
  return overlayHitStatsResult(super.search(query), ctx);
592
- // Non-admin agent: scope to own (any visibility) + granted owners' SHARED
593
- // memories only (Layer 1 private-exclusion). Centralized in
809
+ // Non-admin agent: scope to own records at any visibility plus every other
810
+ // agent's non-private records (open-within-org; MemoryGrant is not
811
+ // consulted on reads). Centralized in
594
812
  // memoryReadScope (record-type-kit.ts's makeReadScope(), parameterized
595
813
  // from RECORD_TYPES.Memory — see this file's header — delegating
596
814
  // "open-within-org" to memory-read-scope.ts's resolveReadScope()
@@ -600,7 +818,49 @@ export class Memory extends databases.flair.Memory {
600
818
  // makeScopedSearch (record-type-kit.ts) — same correct composition
601
819
  // MemoryCandidate.search() already applies — so a caller-supplied
602
820
  // `operator: "or"` cannot boolean-inject past the owner scope.
603
- return overlayHitStatsResult(memoryScopedSearch(gate.agentId, query, (q) => withDetachedTxn(ctx, () => super.search(q))), ctx);
821
+ // Fetch pointers once per bounded chunk, then yield its projected rows
822
+ // before consuming the next chunk (never one pointer query per row).
823
+ const readerAgentId = gate.agentId;
824
+ // flair#1940 round 18 (design ruling): a non-admin read ignores the caller's
825
+ // `select`/`property`. For a REST read the auth middleware drops the
826
+ // selection from the request URL before Harper parses it; for a direct
827
+ // contextual read the selection is dropped here, before the scoped search,
828
+ // so the gated pointer join below always sees the stored rows. This is a key
829
+ // deletion, not a selection parser: the read runs on the same conditions,
830
+ // operator, sort, limit and offset, unselected, and the hit-stat overlay
831
+ // still runs on the full row.
832
+ const source = memoryScopedSearch(readerAgentId, withoutCallerSelection(query), (q) => withDetachedTxn(ctx, () => super.search(q)));
833
+ // A1-iv item 2 + round 22: stream in FIXED-SIZE chunks. Each chunk is
834
+ // projected through the ONE reader helper (ONE batched pointer query for
835
+ // that chunk) and yielded BEFORE the next chunk is read, so a non-admin
836
+ // listing no longer buffers the reader's whole readable corpus and every
837
+ // pointer query stays bounded. Result order and the per-row projection are
838
+ // preserved (rows are yielded in source order, each through
839
+ // applyHitStats). Pinned by test/unit/memory-host-source.test.ts
840
+ // (r22-search-chunks) — RED if the chunked flush is reverted to one
841
+ // whole-set buffer.
842
+ const POINTER_JOIN_CHUNK = 200;
843
+ const joined = (async function* joinPointerBatch() {
844
+ let rows = [];
845
+ const flush = async function* () {
846
+ const batch = rows;
847
+ rows = [];
848
+ const projected = await projectRowsThroughPointers(batch, readerAgentId);
849
+ for (const row of projected) {
850
+ yield await applyHitStats(row, ctx);
851
+ }
852
+ };
853
+ // memoryScopedSearch returns a Promise of the iterable (its scopedSearch
854
+ // is async); await it before iterating.
855
+ for await (const row of await source) {
856
+ rows.push(row);
857
+ if (rows.length >= POINTER_JOIN_CHUNK)
858
+ yield* flush();
859
+ }
860
+ if (rows.length > 0)
861
+ yield* flush();
862
+ })();
863
+ return joined;
604
864
  }
605
865
  async post(content, context) {
606
866
  const authorityDenial = await guardAuthorityFields(() => super.get(), content, "Memory");
@@ -751,7 +1011,9 @@ export class Memory extends databases.flair.Memory {
751
1011
  try {
752
1012
  const src = await databases.flair.Memory.get(sourceId);
753
1013
  if (src) {
754
- patchRecord(databases.flair.Memory, sourceId, { lastReflected: now }).catch(() => { });
1014
+ const reflectPatch = { lastReflected: now };
1015
+ stripUndeclaredMemoryAttributes(reflectPatch);
1016
+ patchRecord(databases.flair.Memory, sourceId, reflectPatch).catch(() => { });
755
1017
  }
756
1018
  }
757
1019
  catch { }
@@ -835,22 +1097,70 @@ export class Memory extends databases.flair.Memory {
835
1097
  content.embeddingModel = getModelId();
836
1098
  }
837
1099
  }
1100
+ // ── flair#1940 slice 1 (A1'): the host pointer is NOT a Memory attribute. ──
1101
+ // Consume the write-body-only pointer inputs OUT of the row (they must
1102
+ // never be persisted on the Memory row), validate them, and build the
1103
+ // pointer row written alongside the Memory row below. A client-supplied
1104
+ // `hostSourceVisibility` is a FORGERY of the server's write-time stamp and
1105
+ // is dropped here (never read). Reject, never truncate/coerce.
1106
+ const pointerInputs = extractPointerInputs(content);
1107
+ // A1-iv item 3: strip every server-stamped field a client body may not set
1108
+ // (instanceToken, provenance). They are re-stamped below.
1109
+ stripServerStampedFields(content);
1110
+ // A1-iv item 1: a NEW row gets a server-stamped incarnation token.
1111
+ content.instanceToken = newInstanceToken();
1112
+ const pointer = buildPointerForWrite({ inputs: pointerInputs, memoryId: content.id ?? "", visibility: content.visibility, auth, memoryInstanceToken: content.instanceToken });
1113
+ if (pointer.denial)
1114
+ return pointer.denial;
838
1115
  // Write-time provenance stamp (memory-provenance slice 1) — see
839
1116
  // buildProvenance's doc above. Stamped last, right before persist, so it
840
1117
  // reflects the final resolved `content.createdAt`.
841
1118
  content.provenance = buildProvenance(auth, content.createdAt, content);
1119
+ // flair#1940 A4: `receivedAt` is SERVER-stamped inside provenance above; a
1120
+ // client-supplied top-level `receivedAt` is IGNORED (stripped here so it is
1121
+ // never persisted as a row field).
1122
+ delete content.receivedAt;
842
1123
  // flair#718 authorship-provenance: `claimedClient` is a WRITE-BODY-ONLY
843
1124
  // passthrough — buildProvenance above already folded it into
844
1125
  // `provenance.claimed.client` (sanitized/capped). Strip it from the row
845
1126
  // itself so it is NEVER persisted as a second, undeclared/unsanitized
846
1127
  // top-level field — authorship lives in the provenance JSON only.
847
1128
  delete content.claimedClient;
848
- // Write-time originatorInstanceId stamp (federation-edge-hardening slice
849
- // 1) — see stampOriginatorInstanceId's doc above. No-op if already set
850
- // (never fires for a genuine local write — no client sets this field).
851
- await stampOriginatorInstanceId(content);
1129
+ // Write-time originatorInstanceId (federation-edge-hardening slice 1): a
1130
+ // post() is always a CREATE, so this instance's own id is stamped and any
1131
+ // request-body value is ignored — see resources/originator-instance.ts.
1132
+ await stampOriginatorOnCreate(content);
1133
+ // flair#1965 r2: the receiver-side federation bookkeeping (`_originatorInstanceId`
1134
+ // et al.) is a client-unsettable stamp; a CREATE must not carry one from the
1135
+ // body. See resources/originator-instance.ts.
1136
+ dropClientFederationBookkeeping(content);
852
1137
  // ── Write the new record FIRST ──────────────────────────────────────────
853
- const result = await super.post(content);
1138
+ // A1' item 1: the guard keeps declared Memory attributes and the explicit
1139
+ // `UNDECLARED_ALLOWED` fields, so an undeclared key (including a pointer
1140
+ // field a raw writer tried to slip in) is dropped.
1141
+ // Pinned by test/unit/memory-host-source.test.ts (r20-post) — RED if this
1142
+ // call is removed.
1143
+ stripUndeclaredMemoryAttributes(content);
1144
+ // A1' item 2 (adjudication 0a): the Memory row and its pointer row share ONE
1145
+ // transaction. With a request context they join its open transaction; with
1146
+ // NO context (an internal direct call, e.g. new Memory().post(...))
1147
+ // withSharedWriteTransaction creates one, so a failed pointer write rolls
1148
+ // the Memory row back too instead of leaving it pointer-less.
1149
+ // Pinned by test/unit/memory-host-source.test.ts (r20-atomic) — RED if the
1150
+ // owned-transaction branch is bypassed.
1151
+ const postResult = await withSharedWriteTransaction(ctx, async (c) => {
1152
+ const newId = await writeMemoryRowPost(this.constructor, content, c);
1153
+ if (pointer.row) {
1154
+ pointer.row.memoryId = newId;
1155
+ const persistDenial = await persistPointerRow(pointer.row, c);
1156
+ if (persistDenial)
1157
+ return persistDenial;
1158
+ }
1159
+ return null;
1160
+ });
1161
+ if (postResult instanceof Response)
1162
+ return postResult;
1163
+ const result = {};
854
1164
  // flair#1357 — read-your-write for the lexical leg. The table change feed
855
1165
  // (resources/bm25-index-service.ts) is the CORRECTNESS mechanism; this
856
1166
  // synchronous hook is what makes a store immediately searchable rather
@@ -898,9 +1208,46 @@ export class Memory extends databases.flair.Memory {
898
1208
  return stale;
899
1209
  }
900
1210
  stripClientVersionPassthrough(content);
1211
+ // flair#1960 r2: capture the (undeclared) authorship-claim inputs BEFORE the
1212
+ // undeclared-attribute strip removes them, so a semantic PATCH re-stamps
1213
+ // provenance with the SAME claims a post()/put() would record from this body
1214
+ // (a PATCH body's `model`/`claimedClient` are folded into `claimed` only).
1215
+ const claimInputs = { model: content?.model, claimedClient: content?.claimedClient };
1216
+ // A1' item 1: patch() is a Memory writer too. Drop any pointer inputs and
1217
+ // every undeclared attribute here, so a PATCH can never carry a pointer
1218
+ // onto the row (the pointer is written ONLY by post()/put() and the table
1219
+ // resource). These paths discard the supplied pointer input and create no
1220
+ // pointer row; an existing pointer row stays bound to the updated Memory.
1221
+ // Pinned by test/unit/memory-host-source.test.ts (r20-patch) — RED if this
1222
+ // guard call is removed.
1223
+ extractPointerInputs(content);
1224
+ stripUndeclaredMemoryAttributes(content);
1225
+ // A1-iv item 3: strip server-stamped fields on patch too (a PATCH body may
1226
+ // not set instanceToken or provenance; the stored values stand).
1227
+ stripServerStampedFields(content);
901
1228
  const denial = await guardOwnerFieldImmutable(this, () => super.get(), content, "agentId");
902
1229
  if (denial)
903
1230
  return denial;
1231
+ // Preserve stored visibility on updates before applying write policy: a
1232
+ // null is no change (PATCH merges), and a present value goes through the
1233
+ // same validator and ephemeral-tier guard as put().
1234
+ if (content && "visibility" in content && content.visibility == null)
1235
+ delete content.visibility;
1236
+ if (content && (content.visibility !== undefined || content.durability !== undefined)) {
1237
+ const durabilityError = assertValidDurability(content.durability);
1238
+ if (durabilityError) {
1239
+ return new Response(JSON.stringify({ error: "invalid_durability", message: durabilityError }), { status: 400, headers: { "content-type": "application/json" } });
1240
+ }
1241
+ const visibilityError = assertValidVisibility(content.visibility);
1242
+ if (visibilityError) {
1243
+ return new Response(JSON.stringify({ error: "invalid_visibility", message: visibilityError }), { status: 400, headers: { "content-type": "application/json" } });
1244
+ }
1245
+ const stored = await super.get();
1246
+ const tierError = assertVisibilityAllowedForDurability(content.durability ?? stored?.durability, content.visibility ?? stored?.visibility);
1247
+ if (tierError) {
1248
+ return new Response(JSON.stringify({ error: "invalid_visibility_for_durability", message: tierError }), { status: 400, headers: { "content-type": "application/json" } });
1249
+ }
1250
+ }
904
1251
  // ── flair#1542 + residual (Kern #1543 review 5135715289): reject skill patches ──
905
1252
  // patch() routes past put() (and thus past the SkillScan gate + forced
906
1253
  // durability), so a skill write on this verb would land unscanned. There are
@@ -915,10 +1262,53 @@ export class Memory extends databases.flair.Memory {
915
1262
  // Skills are written via skill_store (→ Memory.post) or Memory.put; no
916
1263
  // memory_patch tool exists and no internal path patches a skill row (hit-
917
1264
  // tracking goes through table.put, not this override), so rejecting is safe.
918
- const existingForSkill = (await Promise.resolve(super.get()).catch(() => null));
1265
+ // flair#1965 r3 + flair#1960 r3: resolve the stored row ONCE, by the
1266
+ // URL-BOUND target id — refusing a body `id` that disagrees with the
1267
+ // address, and refusing a lookup that FAILS (a failed read is never "no
1268
+ // stored row"). This ONE resolved row drives BOTH rule sets: the skill-row
1269
+ // check and semantic-PATCH provenance decision below, AND the
1270
+ // originatorInstanceId create/update rule. The previous `.catch(() => null)`
1271
+ // turned a read ERROR into "no stored row"; isSemanticPatch returns false
1272
+ // for `null`, so the patch fell through to `super.patch()` as a
1273
+ // METADATA-ONLY write and kept a legacy stored blob — including a
1274
+ // caller-chosen `verified.timestamp` — in place, and (b) stamped a CREATE
1275
+ // over a row that actually exists. See resources/originator-instance.ts's
1276
+ // resolveStoredRow.
1277
+ const resolvedStored = await resolveStoredRow(this, "Memory", content, () => super.get());
1278
+ if (resolvedStored.denial)
1279
+ return resolvedStored.denial;
1280
+ const existingForSkill = resolvedStored.row;
919
1281
  const skillDenial = rejectSkillWritePath(content) ?? rejectSkillWritePath(existingForSkill);
920
1282
  if (skillDenial)
921
1283
  return skillDenial;
1284
+ // ── flair#1960 r2: a SEMANTIC patch re-stamps provenance ────────────────
1285
+ // patch() strips a caller-supplied `provenance` (above) so a body can never
1286
+ // SET a `verified.*` field, but stripping alone would leave the STORED blob
1287
+ // in place — including a legacy row whose `verified.timestamp` came from a
1288
+ // client `createdAt` before this release. A patch that changes the record's
1289
+ // content is a fresh authored write, so it re-stamps from the resolved auth
1290
+ // and ONE server clock read (never the caller's `createdAt`, never a carried-
1291
+ // forward stored value). A metadata-only patch (no semantic field changes)
1292
+ // keeps the stored, previously-stamped blob: no new content was authored, so
1293
+ // there is no new write to attribute. See resources/provenance.ts
1294
+ // (isSemanticPatch / MEMORY_SEMANTIC_FIELDS) for the field set.
1295
+ if (isSemanticPatch(content, existingForSkill, MEMORY_SEMANTIC_FIELDS)) {
1296
+ const ctx = this.getContext?.();
1297
+ const auth = await resolveAgentAuth(ctx);
1298
+ content.provenance = buildProvenance(auth, content.createdAt ?? existingForSkill?.createdAt, claimInputs);
1299
+ }
1300
+ // flair#1965 r2: a PATCH over an EXISTING row keeps the stored
1301
+ // originatorInstanceId (a body value is dropped); a PATCH whose URL target
1302
+ // has NO stored row is a CREATE when it reaches the table — Harper's patch
1303
+ // path has no existing-row requirement — so it must stamp the local id
1304
+ // rather than leave the new row un-stamped. Only an administrator's or a
1305
+ // trusted internal PATCH gets that far; the table guard
1306
+ // (resources/table-patch-policy.ts) refuses the rest. See
1307
+ // resources/originator-instance.ts.
1308
+ await applyOriginatorInstanceId(content, existingForSkill);
1309
+ // The receiver-side federation bookkeeping keeps its stored value (a patch
1310
+ // merges); a client body value is dropped.
1311
+ dropClientFederationBookkeeping(content);
922
1312
  return super.patch(content, query);
923
1313
  }
924
1314
  async put(content) {
@@ -929,9 +1319,10 @@ export class Memory extends databases.flair.Memory {
929
1319
  if (__ownerDenial)
930
1320
  return __ownerDenial;
931
1321
  // Reindex migration bypass: admin-only escape hatch used by the
932
- // MemoryReindex admin endpoint to re-PUT each existing record byte-for-byte
1322
+ // MemoryReindex admin endpoint to re-PUT declared and named retained fields
933
1323
  // (no updatedAt bump, no embedding regen, no safety rescan) so Harper
934
- // repopulates secondary indices. Because this skips content safety and
1324
+ // repopulates secondary indices. Other undeclared fields are stripped and
1325
+ // an absent incarnation token is generated. Because this skips safety and
935
1326
  // auditability, it must be gated to admins. Internal calls (no auth
936
1327
  // context) pass through, matching the pattern used in delete().
937
1328
  if (content._reindex === true) {
@@ -945,6 +1336,56 @@ export class Memory extends databases.flair.Memory {
945
1336
  });
946
1337
  }
947
1338
  delete content._reindex;
1339
+ // A1' item 1: the reindex branch keeps declared and named retained
1340
+ // attributes. Pinned by test/unit/memory-host-source.test.ts
1341
+ // (r20-put-reindex) — RED if this call is removed.
1342
+ stripUndeclaredMemoryAttributes(content);
1343
+ // A1-iv items 1/3: strip a client-supplied server-stamped field, then
1344
+ // PRESERVE the existing row's incarnation token (reindex is a re-PUT of
1345
+ // an existing row, never a reincarnation).
1346
+ stripServerStampedFields(content);
1347
+ // flair#1965 r3: resolve the stored row by the URL-BOUND target id (never a
1348
+ // body id alone); a body id that disagrees with the address, or a lookup
1349
+ // that FAILS, refuses the reindex. A reindex is a re-PUT of an EXISTING
1350
+ // row, so an absent stored row is refused too — a failed read must never
1351
+ // be read as "no row" and re-created/re-stamped. See
1352
+ // resources/originator-instance.ts's resolveStoredRow.
1353
+ const resolvedReindex = await resolveStoredRow(this, "Memory", content, () => super.get());
1354
+ if (resolvedReindex.denial)
1355
+ return resolvedReindex.denial;
1356
+ const reindexExisting = resolvedReindex.row;
1357
+ if (!reindexExisting) {
1358
+ return new Response(JSON.stringify({
1359
+ error: "reindex_row_not_found",
1360
+ message: "the _reindex re-PUT requires an existing stored row",
1361
+ }), { status: 404, headers: { "content-type": "application/json" } });
1362
+ }
1363
+ stampInstanceToken(content, reindexExisting);
1364
+ // Keep the EXISTING row's STORED provenance byte-for-byte. The rest of
1365
+ // the row is filtered above and may gain an absent incarnation token.
1366
+ // The body's provenance was stripped above so it cannot be forged;
1367
+ // restoring it from `reindexExisting` (never from the submitted value)
1368
+ // keeps provenance byte-identical across a corpus-wide reindex.
1369
+ // Pinned by test/unit/memory-host-source.test.ts (r20-put-reindex) — RED
1370
+ // if this restore is removed.
1371
+ if (reindexExisting && typeof reindexExisting.provenance === "string") {
1372
+ content.provenance = reindexExisting.provenance;
1373
+ }
1374
+ // flair#1965: a reindex is a re-PUT of an EXISTING row (an UPDATE), so the
1375
+ // row's stored originatorInstanceId stands; a body value is dropped, and a
1376
+ // legacy row with no value is left un-stamped. See
1377
+ // resources/originator-instance.ts.
1378
+ keepStoredOriginator(content, reindexExisting);
1379
+ // The receiver-side federation bookkeeping likewise stands as stored.
1380
+ applyFederationBookkeeping(content, reindexExisting);
1381
+ // Preserve stored visibility on updates before applying write policy:
1382
+ // a reindex payload that omits it keeps the record's stored value.
1383
+ if (content.visibility === undefined || content.visibility === null) {
1384
+ const stored = await super.get();
1385
+ if (stored && (stored.visibility === PRIVATE_VISIBILITY || stored.visibility === SHARED_VISIBILITY)) {
1386
+ content.visibility = stored.visibility;
1387
+ }
1388
+ }
948
1389
  const reindexed = await super.put(content);
949
1390
  noteMemoryUpsert(content);
950
1391
  noteWriteStamp(content?.embeddingModel); // embedding-space-guard slice 1 (see post())
@@ -1019,9 +1460,23 @@ export class Memory extends databases.flair.Memory {
1019
1460
  // `{...existing, ...patch}` payload, and must never have their stored
1020
1461
  // visibility overwritten by a default recomputed from that merged content
1021
1462
  // — only a genuinely NEW id gets the default stamped.
1022
- const preExisting = content.id
1023
- ? await databases.flair.Memory.get(content.id).catch(() => null)
1024
- : null;
1463
+ // The row is resolved by the URL-BOUND target id, never the request body's
1464
+ // `id`: Harper writes to the URL target and rewrites the row's primary key
1465
+ // to it, so a body id names a row this PUT does NOT land on. A body id that
1466
+ // disagrees with the target, or a lookup that FAILS, refuses the write — a
1467
+ // failed read must never look like "no record". See
1468
+ // resources/originator-instance.ts's resolveStoredRow.
1469
+ const resolvedExisting = await resolveStoredRow(this, "Memory", content, () => super.get());
1470
+ if (resolvedExisting.denial)
1471
+ return resolvedExisting.denial;
1472
+ const preExisting = resolvedExisting.row;
1473
+ // Preserve stored visibility on updates before applying write policy
1474
+ // (only the two writable values; the guards below see the result).
1475
+ if (preExisting &&
1476
+ (content.visibility === undefined || content.visibility === null) &&
1477
+ (preExisting.visibility === PRIVATE_VISIBILITY || preExisting.visibility === SHARED_VISIBILITY)) {
1478
+ content.visibility = preExisting.visibility;
1479
+ }
1025
1480
  // ─── Default visibility (durability-keyed) — Layer 1, part A ────────────
1026
1481
  // Explicit visibility on the write ALWAYS overrides; only stamp the
1027
1482
  // default when the caller left it unset AND this is a fresh record.
@@ -1179,26 +1634,83 @@ export class Memory extends databases.flair.Memory {
1179
1634
  content.archivedAt = now;
1180
1635
  // archivedBy should be set by the caller (CLI stamps req.tpsAgent via query param)
1181
1636
  }
1637
+ // ── flair#1940 slice 1 (A1'): the host pointer is NOT a Memory attribute. ──
1638
+ // Identical rule to post(): consume the write-body-only pointer inputs OUT
1639
+ // of the row, validate them, and build the pointer row written alongside
1640
+ // the Memory row below. A client-supplied `hostSourceVisibility` is dropped
1641
+ // (never read). Reject, never truncate/coerce.
1642
+ const pointerInputs = extractPointerInputs(content);
1643
+ // A1-iv item 3: strip server-stamped fields (a client may not set them).
1644
+ stripServerStampedFields(content);
1645
+ // A1-iv item 1: PRESERVE the existing row's incarnation token on an update,
1646
+ // else generate one (a fresh create via put).
1647
+ stampInstanceToken(content, preExisting);
1648
+ // A1'' item 5: a partial PUT (one that omits `visibility`, e.g. a
1649
+ // memory_update full put) must stamp scopeAtWrite from the record's
1650
+ // EFFECTIVE visibility — the existing row's when the body omits it — not
1651
+ // from an undefined body value that would wrongly yield author-only.
1652
+ const effectiveVisibility = content.visibility ?? preExisting?.visibility;
1653
+ // A partial PUT carries the stored visibility it read at the start of the
1654
+ // request (one carry, above, before the write-policy guards).
1655
+ // Adjudication B (round 4): load the stored pointer row so an echo of it is
1656
+ // recognised and not replaced (see buildPointerForWrite).
1657
+ let storedPointer = null;
1658
+ if (content.id &&
1659
+ pointerInputs.hostSource !== undefined &&
1660
+ pointerInputs.hostSource !== null &&
1661
+ pointerInputs.hostSourceScope === undefined) {
1662
+ storedPointer = await loadStoredPointer(content.id);
1663
+ }
1664
+ const pointer = buildPointerForWrite({ inputs: pointerInputs, memoryId: content.id ?? "", visibility: effectiveVisibility, auth, memoryInstanceToken: content.instanceToken, storedPointer });
1665
+ if (pointer.denial)
1666
+ return pointer.denial;
1182
1667
  // Write-time provenance stamp (memory-provenance slice 1) — see
1183
1668
  // buildProvenance's doc above post(). Applies to every put() (fresh
1184
1669
  // create AND update/patch) — never gated on preExisting, so an update
1185
1670
  // always gets a freshly-stamped provenance reflecting the CURRENT
1186
1671
  // authenticated actor performing this write.
1187
1672
  content.provenance = buildProvenance(auth, content.createdAt, content);
1673
+ // flair#1940 A4: a client-supplied `receivedAt` is IGNORED (stripped; the
1674
+ // server's receipt time lives inside provenance, stamped above).
1675
+ delete content.receivedAt;
1188
1676
  // flair#718 authorship-provenance — see post()'s identical comment above:
1189
1677
  // strip the write-body-only `claimedClient` passthrough now that it's
1190
1678
  // folded into `provenance.claimed.client`. Never persisted as a row field.
1191
1679
  delete content.claimedClient;
1192
- // Write-time originatorInstanceId stamp (federation-edge-hardening slice
1193
- // 1) — see stampOriginatorInstanceId's doc above post(). No-op if
1194
- // already set: an update/patch of an existing local record carries its
1195
- // own already-stamped originatorInstanceId forward unchanged (the
1196
- // `{...existing, ...patch}` merge pattern every put() caller uses), and a
1197
- // federation-synced record never reaches this method at all (see that
1198
- // function's doc for why the merge path can't clobber it here either).
1199
- await stampOriginatorInstanceId(content);
1680
+ // Write-time originatorInstanceId (federation-edge-hardening slice 1):
1681
+ // a CREATE (no pre-existing row) stamps this instance's own id, ignoring
1682
+ // any body value; an UPDATE keeps the STORED value — a body value neither
1683
+ // replaces nor clears it. A federation-synced record never reaches this
1684
+ // method at all (the merge path writes via the raw table handle). See
1685
+ // resources/originator-instance.ts.
1686
+ await applyOriginatorInstanceId(content, preExisting);
1687
+ // The receiver-side federation bookkeeping stands as stored on an update,
1688
+ // and a client body may not set it on a create. See
1689
+ // resources/originator-instance.ts.
1690
+ applyFederationBookkeeping(content, preExisting);
1200
1691
  // ── Write the new/updated record FIRST ──────────────────────────────────
1201
- const result = await super.put(content);
1692
+ // A1' item 1: persist ONLY declared Memory attributes (see post()).
1693
+ // Pinned by test/unit/memory-host-source.test.ts (r20-put) — RED if this
1694
+ // call is removed.
1695
+ stripUndeclaredMemoryAttributes(content);
1696
+ // A1' item 2 (adjudication 0a): share ONE transaction with the pointer row
1697
+ // (see post()). The shared helper's owned-transaction branch is pinned by
1698
+ // test/unit/memory-host-source.test.ts (r20-atomic, which drives POST);
1699
+ // request-context PUT rollback is pinned by
1700
+ // test/integration/host-source-atomicity-1940.test.ts (t2).
1701
+ const putResult = await withSharedWriteTransaction(ctx, async (c) => {
1702
+ const r = await databases.flair.Memory.put(content, c);
1703
+ if (pointer.row) {
1704
+ pointer.row.memoryId = r?.id ?? content.id ?? "";
1705
+ const persistDenial = await persistPointerRow(pointer.row, c);
1706
+ if (persistDenial)
1707
+ return persistDenial;
1708
+ }
1709
+ return r;
1710
+ });
1711
+ if (putResult instanceof Response)
1712
+ return putResult;
1713
+ const result = putResult;
1202
1714
  // flair#1357 — read-your-write for the lexical leg (see post()).
1203
1715
  noteMemoryUpsert(content);
1204
1716
  noteWriteStamp(content?.embeddingModel); // embedding-space-guard slice 1 (see post())
@@ -1217,7 +1729,8 @@ export class Memory extends databases.flair.Memory {
1217
1729
  return buildWriteResponse(content, result, dedupMatch);
1218
1730
  }
1219
1731
  async delete(id) {
1220
- const auth = await resolveAgentAuth(this.getContext?.());
1732
+ const ctx = this.getContext?.();
1733
+ const auth = await resolveAgentAuth(ctx);
1221
1734
  if (auth.kind === "anonymous")
1222
1735
  return UNAUTH();
1223
1736
  // Read stored ownership, not the read-scoped get() response. Enforce here
@@ -1228,12 +1741,36 @@ export class Memory extends databases.flair.Memory {
1228
1741
  return FORBIDDEN("forbidden: cannot delete memory owned by another agent");
1229
1742
  }
1230
1743
  // Durability controls retention, not the owner's authority to delete.
1231
- const deleted = await super.delete(id);
1232
- noteMemoryDelete(id);
1233
- const deletedId = typeof id === "string" ? id : record?.id;
1234
- if (typeof deletedId === "string" && deletedId.length > 0) {
1235
- await clearHitStats(deletedId, this.getContext?.()).catch(() => { });
1744
+ // A1' item 2 (adjudication 0a/0c): the Memory delete and its pointer
1745
+ // delete share ONE transaction; with no request context
1746
+ // withSharedWriteTransaction creates one. A failing pointer delete aborts
1747
+ // it, so nothing is deleted; failures are NOT swallowed.
1748
+ // A request-owned transaction may still abort after this method returns.
1749
+ // Its committed change feed updates BM25 after commit; only a transaction
1750
+ // owned here can use the synchronous hook after the shared write returns.
1751
+ // Capture ownership before the helper changes the context's transaction.
1752
+ const requestOwnsTransaction = isJoinableTransaction(ctx);
1753
+ const deleteResult = await withSharedWriteTransaction(ctx, async (c) => {
1754
+ const d = await databases.flair.Memory.delete(id, c);
1755
+ const deletedId = typeof id === "string" ? id : record?.id;
1756
+ if (typeof deletedId === "string" && deletedId.length > 0) {
1757
+ const pointerDenial = await deletePointerRow(deletedId, c);
1758
+ if (pointerDenial)
1759
+ return pointerDenial;
1760
+ }
1761
+ return d;
1762
+ });
1763
+ if (deleteResult instanceof Response)
1764
+ return deleteResult;
1765
+ // Use the RESOLVED deleted id (a by-record delete carries only `id`, so the
1766
+ // stored row's id is the fallback). An owned transaction has committed;
1767
+ // a request-owned write waits for the committed change feed instead.
1768
+ const resolvedDeletedId = typeof id === "string" ? id : record?.id;
1769
+ if (!requestOwnsTransaction && typeof resolvedDeletedId === "string" && resolvedDeletedId.length > 0) {
1770
+ noteMemoryDelete(resolvedDeletedId);
1236
1771
  }
1237
- return deleted;
1772
+ if (typeof id === "string")
1773
+ await clearHitStats(id, ctx).catch(() => { });
1774
+ return deleteResult;
1238
1775
  }
1239
1776
  }