@tpsdev-ai/flair 0.57.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.
- package/README.md +4 -4
- package/SECURITY.md +4 -1
- package/dist/build-info.json +3 -3
- package/dist/cli.js +1685 -279
- package/dist/commands/doctor.js +162 -4
- package/dist/commands/federation.js +2 -1
- package/dist/commands/hook.js +10 -2
- package/dist/commands/init.js +150 -44
- package/dist/commands/memory.js +24 -2
- package/dist/commands/quality.js +26 -18
- package/dist/commands/service.js +137 -22
- package/dist/commands/status.js +114 -3
- package/dist/commands/upgrade.js +204 -84
- package/dist/doctor-client.js +50 -4
- package/dist/federation/scheduler.js +253 -4
- package/dist/install/clients.js +89 -23
- package/dist/install/global-bin-path.js +26 -6
- package/dist/lib/atomic-write.js +256 -0
- package/dist/lib/daemon-liveness.js +61 -0
- package/dist/lib/doctor-run.js +5 -0
- package/dist/lib/embed-gpu-doctor.js +49 -26
- package/dist/lib/federation-memory-attributes.js +15 -0
- package/dist/lib/init-admin-pass.js +4 -2
- package/dist/lib/init-listener-environ.js +38 -0
- package/dist/lib/init-occupied-listener.js +165 -0
- package/dist/lib/launchd-domain-preflight.js +448 -0
- package/dist/lib/launchd-management.js +176 -6
- package/dist/lib/launchd-repair.js +95 -0
- package/dist/lib/memory-attributes.js +77 -0
- package/dist/lib/node-alias-path.js +95 -0
- package/dist/lib/npm-registry.js +119 -6
- package/dist/lib/owned-pins.js +20 -6
- package/dist/lib/service-repoint-apply.js +267 -0
- package/dist/lib/service-repoint.js +575 -0
- package/dist/lib/toml-string-array.js +104 -0
- package/dist/lib/tree-divergence.js +716 -0
- package/dist/lib/upgrade-plain-tree.js +18 -8
- package/dist/lib/upgrade-prior-liveness.js +69 -0
- package/dist/lib/upgrade-rollback.js +116 -0
- package/dist/rem/runner.js +11 -0
- package/dist/resources/Agent.js +27 -14
- package/dist/resources/AgentSeed.js +35 -1
- package/dist/resources/Federation.js +70 -52
- package/dist/resources/Memory.js +567 -72
- package/dist/resources/MemoryArchive.js +9 -0
- package/dist/resources/MemoryBootstrap.js +4 -0
- package/dist/resources/MemoryFeed.js +204 -3
- package/dist/resources/MemoryHostSource.js +90 -0
- package/dist/resources/MemoryMaintenance.js +121 -32
- package/dist/resources/MemoryReflect.js +4 -1
- package/dist/resources/MemoryReindex.js +7 -4
- package/dist/resources/MemoryUsage.js +53 -3
- package/dist/resources/Presence.js +18 -10
- package/dist/resources/RecordUsage.js +30 -40
- package/dist/resources/Relationship.js +167 -78
- package/dist/resources/SemanticSearch.js +19 -6
- package/dist/resources/Soul.js +31 -19
- package/dist/resources/XAA.js +7 -3
- package/dist/resources/agent-auth.js +16 -10
- package/dist/resources/auth-middleware.js +135 -48
- package/dist/resources/auto-promote-lib.js +4 -4
- package/dist/resources/bm25-index-service.js +246 -32
- package/dist/resources/bm25-status.js +132 -0
- package/dist/resources/ed25519-auth.js +11 -54
- package/dist/resources/embed-gpu.js +262 -47
- package/dist/resources/embeddings-boot.js +52 -17
- package/dist/resources/federation-classify.js +12 -0
- package/dist/resources/federation-crypto.js +65 -19
- package/dist/resources/health.js +57 -14
- package/dist/resources/host-pointer/registry.js +35 -0
- package/dist/resources/host-pointer-adapter.js +15 -0
- package/dist/resources/host-source-visibility.js +167 -0
- package/dist/resources/host-source.js +151 -0
- package/dist/resources/instance-identity.js +3 -2
- package/dist/resources/mcp-handler.js +147 -51
- package/dist/resources/mcp-tools.js +25 -21
- package/dist/resources/memory-consolidate-lib.js +3 -1
- package/dist/resources/memory-declared-attributes.js +103 -0
- package/dist/resources/memory-feed-lib.js +5 -1
- package/dist/resources/memory-host-source.js +163 -0
- package/dist/resources/migrations/synthetic-test-migration.js +4 -1
- package/dist/resources/migrations/visibility-backfill.js +4 -1
- package/dist/resources/originator-instance.js +235 -0
- package/dist/resources/promotion-stamp.js +2 -0
- package/dist/resources/provenance.js +111 -11
- package/dist/resources/record-owner-guard.js +19 -0
- package/dist/resources/record-type-kit.js +9 -12
- package/dist/resources/record-types.js +6 -6
- package/dist/resources/relay-ops.js +28 -3
- package/dist/resources/replay-store.js +289 -0
- package/dist/resources/request-transaction.js +78 -0
- package/dist/resources/search-readiness.js +19 -21
- package/dist/resources/semantic-retrieval-core.js +5 -1
- package/dist/resources/table-patch-policy.js +109 -0
- package/dist/resources/table-patches.js +17 -0
- package/dist/resources/table-post-policy.js +138 -0
- package/dist/resources/table-posts.js +22 -0
- package/dist/resources/table-subscription-policy.js +135 -0
- package/dist/resources/table-subscriptions.js +19 -0
- package/dist/resources/tool-descriptors/index.js +15 -15
- package/dist/resources/trust-block.js +10 -3
- package/dist/resources/usage-recording.js +169 -41
- package/dist/src/lib/memory-attributes.js +77 -0
- package/docs/api-reference.md +79 -15
- package/docs/claude-code.md +132 -0
- package/docs/deployment.md +1 -1
- package/docs/federation.md +1 -1
- package/docs/integrations.md +5 -5
- package/docs/mcp-clients.md +11 -21
- package/docs/notes/mcp-oauth-model2.md +15 -1
- package/docs/quickstart.md +5 -0
- package/docs/releasing.md +134 -2
- package/docs/supply-chain-policy.md +10 -5
- package/docs/troubleshooting.md +11 -0
- package/docs/upgrade.md +187 -61
- package/package.json +9 -5
- package/schemas/agent.graphql +9 -6
- package/schemas/federation.graphql +2 -11
- package/schemas/memory.graphql +106 -17
- package/schemas/replay.graphql +18 -0
- package/templates/launchd/start-flair-with-admin-pass.sh +22 -0
- package/dist/resources/federation-nonce-store.js +0 -195
package/dist/resources/Memory.js
CHANGED
|
@@ -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 {
|
|
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
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)
|
|
@@ -346,6 +537,7 @@ async function closeSupersededRecord(ctx, oldId, patch) {
|
|
|
346
537
|
throw new Error(`supersede-close: record ${oldId} not found`);
|
|
347
538
|
}
|
|
348
539
|
const closed = { ...existing, ...patch };
|
|
540
|
+
stripUndeclaredMemoryAttributes(closed);
|
|
349
541
|
await withDetachedTxn(ctx, () => databases.flair.Memory.put(closed));
|
|
350
542
|
// flair#1357 — a supersede-close sets `validTo`, which the retrieval filters
|
|
351
543
|
// read, so the lexical index has to see it as eagerly as a content write.
|
|
@@ -471,43 +663,27 @@ function defaultVisibilityForDurability(durability) {
|
|
|
471
663
|
* "reuse buildProvenance as-is" contract) instead of a hand-copied format
|
|
472
664
|
* that could drift. See that module for the full field-by-field rationale
|
|
473
665
|
* (verified.agentId from the auth verdict never the body, verified.timestamp
|
|
474
|
-
* = the
|
|
475
|
-
* claimed.client passthroughs — the
|
|
476
|
-
* provenance). Deliberately NOT implemented
|
|
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
|
|
477
670
|
* context-fingerprint field — bootstrap doesn't return the IDs a fingerprint
|
|
478
671
|
* would need, so it requires client cooperation that's out of scope here.
|
|
479
672
|
*/
|
|
480
673
|
/**
|
|
481
|
-
* ─── Write-time originatorInstanceId
|
|
482
|
-
*
|
|
483
|
-
* Stamps this instance's own federation identity (resources/instance-
|
|
484
|
-
* identity.ts's localInstanceId(), cached — never a DB read per write) onto
|
|
485
|
-
* every LOCAL write. Deliberately a no-op when `content.originatorInstanceId`
|
|
486
|
-
* already carries a non-null value: this is the anti-clobber rule that keeps
|
|
487
|
-
* a federation-synced record's true origin intact.
|
|
674
|
+
* ─── Write-time originatorInstanceId (federation-edge-hardening slice 1) ─────
|
|
488
675
|
*
|
|
489
|
-
*
|
|
490
|
-
*
|
|
491
|
-
*
|
|
492
|
-
*
|
|
493
|
-
*
|
|
494
|
-
*
|
|
495
|
-
*
|
|
496
|
-
*
|
|
497
|
-
*
|
|
498
|
-
*
|
|
499
|
-
* through this class's post()/put() — so the invariant holds even if that
|
|
500
|
-
* assumption ever changes.
|
|
501
|
-
*
|
|
502
|
-
* `localInstanceId()` resolves to null on an instance that has never been
|
|
503
|
-
* federation-bootstrapped (no Instance row yet) — the field is nullable by
|
|
504
|
-
* 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.
|
|
505
686
|
*/
|
|
506
|
-
async function stampOriginatorInstanceId(content) {
|
|
507
|
-
if (content.originatorInstanceId == null) {
|
|
508
|
-
content.originatorInstanceId = await localInstanceId();
|
|
509
|
-
}
|
|
510
|
-
}
|
|
511
687
|
export class Memory extends databases.flair.Memory {
|
|
512
688
|
/**
|
|
513
689
|
* Self-authorize now that the global gate is non-rejecting. Closes the P0
|
|
@@ -529,13 +705,13 @@ export class Memory extends databases.flair.Memory {
|
|
|
529
705
|
*/
|
|
530
706
|
allowRead() { return memoryAuthGate.call(this); }
|
|
531
707
|
/**
|
|
532
|
-
* Override get() to scope by-id reads
|
|
533
|
-
* collection reads
|
|
534
|
-
*
|
|
535
|
-
*
|
|
536
|
-
*
|
|
537
|
-
*
|
|
538
|
-
*
|
|
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.
|
|
539
715
|
*/
|
|
540
716
|
async get(target, opts) {
|
|
541
717
|
// Collection / query reads — the `GET /Memory/?<query>` form and the bare
|
|
@@ -556,7 +732,39 @@ export class Memory extends databases.flair.Memory {
|
|
|
556
732
|
if (!target || (typeof target === "object" && target.isCollection)) {
|
|
557
733
|
return this.search(target);
|
|
558
734
|
}
|
|
559
|
-
const
|
|
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
|
+
}
|
|
560
768
|
// flair#744 slice 1 — opt-in inline trust-evidence block, attached ONLY to
|
|
561
769
|
// a genuine by-id record (never a NOT_FOUND `Response`, never null), and
|
|
562
770
|
// ONLY after the ownership/read-scope gate above has already resolved. The
|
|
@@ -566,10 +774,10 @@ export class Memory extends databases.flair.Memory {
|
|
|
566
774
|
// byte-identical to pre-slice-1.
|
|
567
775
|
if (result && typeof result === "object" && !(result instanceof Response) && typeof result.agentId === "string") {
|
|
568
776
|
const ctx = this.getContext?.();
|
|
569
|
-
const withHits = await applyHitStats(
|
|
777
|
+
const withHits = await applyHitStats(projected, ctx);
|
|
570
778
|
return attachTrust(withHits, wantsTrust(target, opts));
|
|
571
779
|
}
|
|
572
|
-
return
|
|
780
|
+
return projected;
|
|
573
781
|
}
|
|
574
782
|
/**
|
|
575
783
|
* Override search() to scope collection GETs by authenticated agent.
|
|
@@ -610,7 +818,49 @@ export class Memory extends databases.flair.Memory {
|
|
|
610
818
|
// makeScopedSearch (record-type-kit.ts) — same correct composition
|
|
611
819
|
// MemoryCandidate.search() already applies — so a caller-supplied
|
|
612
820
|
// `operator: "or"` cannot boolean-inject past the owner scope.
|
|
613
|
-
|
|
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;
|
|
614
864
|
}
|
|
615
865
|
async post(content, context) {
|
|
616
866
|
const authorityDenial = await guardAuthorityFields(() => super.get(), content, "Memory");
|
|
@@ -761,7 +1011,9 @@ export class Memory extends databases.flair.Memory {
|
|
|
761
1011
|
try {
|
|
762
1012
|
const src = await databases.flair.Memory.get(sourceId);
|
|
763
1013
|
if (src) {
|
|
764
|
-
|
|
1014
|
+
const reflectPatch = { lastReflected: now };
|
|
1015
|
+
stripUndeclaredMemoryAttributes(reflectPatch);
|
|
1016
|
+
patchRecord(databases.flair.Memory, sourceId, reflectPatch).catch(() => { });
|
|
765
1017
|
}
|
|
766
1018
|
}
|
|
767
1019
|
catch { }
|
|
@@ -845,22 +1097,70 @@ export class Memory extends databases.flair.Memory {
|
|
|
845
1097
|
content.embeddingModel = getModelId();
|
|
846
1098
|
}
|
|
847
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;
|
|
848
1115
|
// Write-time provenance stamp (memory-provenance slice 1) — see
|
|
849
1116
|
// buildProvenance's doc above. Stamped last, right before persist, so it
|
|
850
1117
|
// reflects the final resolved `content.createdAt`.
|
|
851
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;
|
|
852
1123
|
// flair#718 authorship-provenance: `claimedClient` is a WRITE-BODY-ONLY
|
|
853
1124
|
// passthrough — buildProvenance above already folded it into
|
|
854
1125
|
// `provenance.claimed.client` (sanitized/capped). Strip it from the row
|
|
855
1126
|
// itself so it is NEVER persisted as a second, undeclared/unsanitized
|
|
856
1127
|
// top-level field — authorship lives in the provenance JSON only.
|
|
857
1128
|
delete content.claimedClient;
|
|
858
|
-
// Write-time originatorInstanceId
|
|
859
|
-
//
|
|
860
|
-
//
|
|
861
|
-
await
|
|
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);
|
|
862
1137
|
// ── Write the new record FIRST ──────────────────────────────────────────
|
|
863
|
-
|
|
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 = {};
|
|
864
1164
|
// flair#1357 — read-your-write for the lexical leg. The table change feed
|
|
865
1165
|
// (resources/bm25-index-service.ts) is the CORRECTNESS mechanism; this
|
|
866
1166
|
// synchronous hook is what makes a store immediately searchable rather
|
|
@@ -908,6 +1208,23 @@ export class Memory extends databases.flair.Memory {
|
|
|
908
1208
|
return stale;
|
|
909
1209
|
}
|
|
910
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);
|
|
911
1228
|
const denial = await guardOwnerFieldImmutable(this, () => super.get(), content, "agentId");
|
|
912
1229
|
if (denial)
|
|
913
1230
|
return denial;
|
|
@@ -917,6 +1234,10 @@ export class Memory extends databases.flair.Memory {
|
|
|
917
1234
|
if (content && "visibility" in content && content.visibility == null)
|
|
918
1235
|
delete content.visibility;
|
|
919
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
|
+
}
|
|
920
1241
|
const visibilityError = assertValidVisibility(content.visibility);
|
|
921
1242
|
if (visibilityError) {
|
|
922
1243
|
return new Response(JSON.stringify({ error: "invalid_visibility", message: visibilityError }), { status: 400, headers: { "content-type": "application/json" } });
|
|
@@ -941,10 +1262,53 @@ export class Memory extends databases.flair.Memory {
|
|
|
941
1262
|
// Skills are written via skill_store (→ Memory.post) or Memory.put; no
|
|
942
1263
|
// memory_patch tool exists and no internal path patches a skill row (hit-
|
|
943
1264
|
// tracking goes through table.put, not this override), so rejecting is safe.
|
|
944
|
-
|
|
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;
|
|
945
1281
|
const skillDenial = rejectSkillWritePath(content) ?? rejectSkillWritePath(existingForSkill);
|
|
946
1282
|
if (skillDenial)
|
|
947
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);
|
|
948
1312
|
return super.patch(content, query);
|
|
949
1313
|
}
|
|
950
1314
|
async put(content) {
|
|
@@ -955,9 +1319,10 @@ export class Memory extends databases.flair.Memory {
|
|
|
955
1319
|
if (__ownerDenial)
|
|
956
1320
|
return __ownerDenial;
|
|
957
1321
|
// Reindex migration bypass: admin-only escape hatch used by the
|
|
958
|
-
// MemoryReindex admin endpoint to re-PUT
|
|
1322
|
+
// MemoryReindex admin endpoint to re-PUT declared and named retained fields
|
|
959
1323
|
// (no updatedAt bump, no embedding regen, no safety rescan) so Harper
|
|
960
|
-
// repopulates secondary indices.
|
|
1324
|
+
// repopulates secondary indices. Other undeclared fields are stripped and
|
|
1325
|
+
// an absent incarnation token is generated. Because this skips safety and
|
|
961
1326
|
// auditability, it must be gated to admins. Internal calls (no auth
|
|
962
1327
|
// context) pass through, matching the pattern used in delete().
|
|
963
1328
|
if (content._reindex === true) {
|
|
@@ -971,6 +1336,48 @@ export class Memory extends databases.flair.Memory {
|
|
|
971
1336
|
});
|
|
972
1337
|
}
|
|
973
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);
|
|
974
1381
|
// Preserve stored visibility on updates before applying write policy:
|
|
975
1382
|
// a reindex payload that omits it keeps the record's stored value.
|
|
976
1383
|
if (content.visibility === undefined || content.visibility === null) {
|
|
@@ -1053,10 +1460,16 @@ export class Memory extends databases.flair.Memory {
|
|
|
1053
1460
|
// `{...existing, ...patch}` payload, and must never have their stored
|
|
1054
1461
|
// visibility overwritten by a default recomputed from that merged content
|
|
1055
1462
|
// — only a genuinely NEW id gets the default stamped.
|
|
1056
|
-
//
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
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;
|
|
1060
1473
|
// Preserve stored visibility on updates before applying write policy
|
|
1061
1474
|
// (only the two writable values; the guards below see the result).
|
|
1062
1475
|
if (preExisting &&
|
|
@@ -1221,26 +1634,83 @@ export class Memory extends databases.flair.Memory {
|
|
|
1221
1634
|
content.archivedAt = now;
|
|
1222
1635
|
// archivedBy should be set by the caller (CLI stamps req.tpsAgent via query param)
|
|
1223
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;
|
|
1224
1667
|
// Write-time provenance stamp (memory-provenance slice 1) — see
|
|
1225
1668
|
// buildProvenance's doc above post(). Applies to every put() (fresh
|
|
1226
1669
|
// create AND update/patch) — never gated on preExisting, so an update
|
|
1227
1670
|
// always gets a freshly-stamped provenance reflecting the CURRENT
|
|
1228
1671
|
// authenticated actor performing this write.
|
|
1229
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;
|
|
1230
1676
|
// flair#718 authorship-provenance — see post()'s identical comment above:
|
|
1231
1677
|
// strip the write-body-only `claimedClient` passthrough now that it's
|
|
1232
1678
|
// folded into `provenance.claimed.client`. Never persisted as a row field.
|
|
1233
1679
|
delete content.claimedClient;
|
|
1234
|
-
// Write-time originatorInstanceId
|
|
1235
|
-
//
|
|
1236
|
-
//
|
|
1237
|
-
//
|
|
1238
|
-
//
|
|
1239
|
-
//
|
|
1240
|
-
|
|
1241
|
-
|
|
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);
|
|
1242
1691
|
// ── Write the new/updated record FIRST ──────────────────────────────────
|
|
1243
|
-
|
|
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;
|
|
1244
1714
|
// flair#1357 — read-your-write for the lexical leg (see post()).
|
|
1245
1715
|
noteMemoryUpsert(content);
|
|
1246
1716
|
noteWriteStamp(content?.embeddingModel); // embedding-space-guard slice 1 (see post())
|
|
@@ -1259,7 +1729,8 @@ export class Memory extends databases.flair.Memory {
|
|
|
1259
1729
|
return buildWriteResponse(content, result, dedupMatch);
|
|
1260
1730
|
}
|
|
1261
1731
|
async delete(id) {
|
|
1262
|
-
const
|
|
1732
|
+
const ctx = this.getContext?.();
|
|
1733
|
+
const auth = await resolveAgentAuth(ctx);
|
|
1263
1734
|
if (auth.kind === "anonymous")
|
|
1264
1735
|
return UNAUTH();
|
|
1265
1736
|
// Read stored ownership, not the read-scoped get() response. Enforce here
|
|
@@ -1270,12 +1741,36 @@ export class Memory extends databases.flair.Memory {
|
|
|
1270
1741
|
return FORBIDDEN("forbidden: cannot delete memory owned by another agent");
|
|
1271
1742
|
}
|
|
1272
1743
|
// Durability controls retention, not the owner's authority to delete.
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
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);
|
|
1278
1771
|
}
|
|
1279
|
-
|
|
1772
|
+
if (typeof id === "string")
|
|
1773
|
+
await clearHitStats(id, ctx).catch(() => { });
|
|
1774
|
+
return deleteResult;
|
|
1280
1775
|
}
|
|
1281
1776
|
}
|