@tpsdev-ai/flair 0.58.0 → 0.62.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -6
- package/SECURITY.md +36 -0
- package/config.yaml +15 -1
- package/dist/bridges/builtins/mem0.js +63 -28
- package/dist/bridges/runtime/import-runner.js +12 -0
- package/dist/bridges/runtime/load-plugin.js +42 -13
- package/dist/bridges/runtime/yaml-loader.js +4 -2
- package/dist/build-info.json +3 -3
- package/dist/cli.js +1030 -343
- package/dist/commands/agent.js +384 -45
- package/dist/commands/attention.js +4 -3
- package/dist/commands/backup.js +202 -34
- package/dist/commands/bridge.js +172 -119
- package/dist/commands/deploy.js +37 -4
- package/dist/commands/doctor.js +601 -163
- package/dist/commands/export.js +54 -19
- package/dist/commands/federation.js +141 -21
- package/dist/commands/hook.js +155 -2
- package/dist/commands/idp.js +14 -1
- package/dist/commands/import.js +7 -3
- package/dist/commands/init.js +462 -193
- package/dist/commands/integrity.js +388 -0
- package/dist/commands/keys.js +247 -58
- package/dist/commands/mcp.js +146 -53
- package/dist/commands/memory.js +171 -21
- package/dist/commands/migrate-harness-memory.js +3 -2
- package/dist/commands/orgevent.js +46 -37
- package/dist/commands/presence.js +4 -3
- package/dist/commands/principal.js +426 -48
- package/dist/commands/quality.js +10 -1
- package/dist/commands/reembed.js +141 -17
- package/dist/commands/relationship.js +2 -1
- package/dist/commands/rem.js +56 -18
- package/dist/commands/restore.js +101 -61
- package/dist/commands/search.js +6 -4
- package/dist/commands/service.js +151 -38
- package/dist/commands/soul.js +4 -3
- package/dist/commands/status.js +43 -5
- package/dist/commands/test.js +3 -2
- package/dist/commands/upgrade.js +24 -1
- package/dist/commands/workspace.js +6 -3
- package/dist/component-env.js +31 -41
- package/dist/deploy.js +77 -1
- package/dist/doctor-client.js +529 -92
- package/dist/engine-version-contract.js +1 -0
- package/dist/engine-version.js +23 -3
- package/dist/federation-verify.js +4 -3
- package/dist/hook-install.js +670 -6
- package/dist/keystore.js +72 -0
- package/dist/lib/action-recall-runtime.js +328 -0
- package/dist/lib/agent-home-fields.js +132 -0
- package/dist/lib/agent-home.js +427 -0
- package/dist/lib/agent-id-rule.js +46 -0
- package/dist/lib/agent-roster.js +33 -0
- package/dist/lib/auth-resolve.js +49 -16
- package/dist/lib/capture-runtime.js +124 -0
- package/dist/lib/credential-status-rule.js +78 -0
- package/dist/lib/daemon-liveness.js +81 -8
- package/dist/lib/doctor-run.js +140 -35
- package/dist/lib/durability-copy.js +10 -0
- package/dist/lib/embedding-space-doctor.js +75 -0
- package/dist/lib/flair-agent-role.js +120 -0
- package/dist/lib/hub-url.js +12 -0
- package/dist/lib/init-admin-pass.js +88 -12
- package/dist/lib/init-listener-environ.js +1 -2
- package/dist/lib/init-occupied-listener.js +15 -111
- package/dist/lib/init-spawn-attribution.js +73 -0
- package/dist/lib/init-tcp-probe.js +33 -0
- package/dist/lib/instance-identity-row.js +20 -0
- package/dist/lib/launchd-management.js +27 -2
- package/dist/lib/listener-table.js +268 -0
- package/dist/lib/local-delete-instance.js +27 -0
- package/dist/lib/local-instance-pair.js +256 -0
- package/dist/lib/mcp-enable.js +1775 -338
- package/dist/lib/mcp-oauth-env-core.js +133 -0
- package/dist/lib/mcp-oauth-env.js +125 -0
- package/dist/lib/mcp-spec.js +17 -1
- package/dist/lib/memory-attributes.js +2 -0
- package/dist/lib/memory-id-policy.js +46 -0
- package/dist/lib/memory-integrity.js +309 -0
- package/dist/lib/memory-purge-response.js +20 -0
- package/dist/lib/ops-table-count.js +25 -0
- package/dist/lib/owned-pins.js +67 -10
- package/dist/lib/peer-status.js +27 -0
- package/dist/lib/principal-status.js +29 -0
- package/dist/lib/process-start-time.js +103 -7
- package/dist/lib/proto-safe-record.js +42 -0
- package/dist/lib/record-id-path.js +25 -0
- package/dist/lib/reembed-server-support.js +66 -0
- package/dist/lib/restore-verify.js +104 -0
- package/dist/lib/scheduler-platform.js +10 -6
- package/dist/lib/secret-keys.js +25 -0
- package/dist/lib/secrets-push.js +50 -22
- package/dist/lib/skill-seed-pending.js +24 -0
- package/dist/lib/skill-seed.js +365 -0
- package/dist/lib/stop-start-recovery.js +54 -0
- package/dist/lib/using-flair-skill.js +87 -0
- package/dist/mcp-client-assertion.js +112 -4
- package/dist/memory-id-checkpoint.js +326 -0
- package/dist/memory-node-compare.js +207 -0
- package/dist/packages/flair-mcp/src/secret-redaction.js +113 -0
- package/dist/rem/restore.js +6 -5
- package/dist/rem/runner.js +103 -44
- package/dist/resources/Agent.js +348 -8
- package/dist/resources/AgentKeyRegister.js +214 -0
- package/dist/resources/AgentKeyRegistration.js +28 -0
- package/dist/resources/AgentSeed.js +19 -4
- package/dist/resources/AutoPromoteCandidates.js +7 -1
- package/dist/resources/Credential.js +177 -2
- package/dist/resources/Federation.js +752 -132
- package/dist/resources/FederationRetry.js +140 -0
- package/dist/resources/InstructionVersion.js +220 -0
- package/dist/resources/Integration.js +300 -25
- package/dist/resources/Memory.js +2113 -604
- package/dist/resources/MemoryArchive.js +75 -42
- package/dist/resources/MemoryBootstrap.js +227 -64
- package/dist/resources/MemoryCandidate.js +21 -1
- package/dist/resources/MemoryDedupStats.js +30 -1
- package/dist/resources/MemoryFeed.js +327 -45
- package/dist/resources/MemoryGrant.js +21 -1
- package/dist/resources/MemoryMaintenance.js +129 -25
- package/dist/resources/MemoryPurge.js +232 -0
- package/dist/resources/MemoryReflect.js +7 -2
- package/dist/resources/MemoryReindex.js +24 -8
- package/dist/resources/Message.js +5 -3
- package/dist/resources/OAuth.js +186 -9
- package/dist/resources/OrgEvent.js +126 -3
- package/dist/resources/OrgSkillAssignment.js +209 -0
- package/dist/resources/Presence.js +144 -49
- package/dist/resources/PromoteMemoryCandidate.js +18 -7
- package/dist/resources/Relationship.js +23 -0
- package/dist/resources/SemanticSearch.js +63 -32
- package/dist/resources/Soul.js +189 -76
- package/dist/resources/TeamDirectory.js +35 -0
- package/dist/resources/WorkspaceState.js +21 -1
- package/dist/resources/XAA.js +212 -65
- package/dist/resources/agent-auth.js +40 -15
- package/dist/resources/agent-status-guard.js +63 -0
- package/dist/resources/auth-middleware.js +402 -162
- package/dist/resources/ed25519-auth.js +1 -1
- package/dist/resources/embedding-space-guard.js +366 -72
- package/dist/resources/engine-version-stamp-boot.js +53 -0
- package/dist/resources/federation-classify.js +94 -0
- package/dist/resources/federation-crypto.js +5 -5
- package/dist/resources/federation-retry-lib.js +135 -0
- package/dist/resources/flair-agent-role-boot.js +26 -0
- package/dist/resources/grant-visibility.js +135 -0
- package/dist/resources/harper-routing.js +83 -0
- package/dist/resources/health.js +130 -20
- package/dist/resources/host-source-citation.js +49 -0
- package/dist/resources/host-source-visibility.js +7 -6
- package/dist/resources/instance-create-lock.js +17 -0
- package/dist/resources/instance-identity.js +23 -0
- package/dist/resources/instruction-version-record.js +343 -0
- package/dist/resources/key-lock.js +31 -0
- package/dist/resources/mcp-handler.js +36 -8
- package/dist/resources/mcp-oauth-env-guard.js +36 -0
- package/dist/resources/mcp-oauth.js +26 -12
- package/dist/resources/mcp-tool-arguments.js +4 -6
- package/dist/resources/mcp-tools.js +150 -23
- package/dist/resources/memory-bootstrap-lib.js +5 -15
- package/dist/resources/memory-declared-attributes.js +3 -1
- package/dist/resources/memory-deletion-history.js +55 -0
- package/dist/resources/memory-durability.js +54 -0
- package/dist/resources/memory-embed-hash.js +88 -0
- package/dist/resources/memory-embedding-value.js +8 -0
- package/dist/resources/memory-host-source.js +27 -5
- package/dist/resources/memory-id-guard.js +75 -0
- package/dist/resources/memory-redaction.js +236 -0
- package/dist/resources/memory-supplied-vector.js +72 -0
- package/dist/resources/memory-write-lock.js +310 -0
- package/dist/resources/memory-write-response.js +139 -0
- package/dist/resources/migrations/data-dir.js +74 -16
- package/dist/resources/migrations/dir-safety.js +1 -1
- package/dist/resources/migrations/embedding-stamp.js +193 -79
- package/dist/resources/migrations/export.js +1 -0
- package/dist/resources/migrations/graph-heal.js +18 -25
- package/dist/resources/migrations/lock.js +7 -1
- package/dist/resources/migrations/snapshot.js +1 -0
- package/dist/resources/migrations/source-fields.js +5 -5
- package/dist/resources/migrations/synthetic-test-migration.js +14 -11
- package/dist/resources/migrations/visibility-backfill.js +29 -29
- package/dist/resources/multi-worker-guard.js +121 -0
- package/dist/resources/oauth-discovery.js +1 -0
- package/dist/resources/oauth-wellknown.js +8 -4
- package/dist/resources/object-body-guard.js +33 -0
- package/dist/resources/org-event-created-at.js +133 -0
- package/dist/resources/originator-instance.js +39 -7
- package/dist/resources/owner-delete-recheck.js +78 -0
- package/dist/resources/owner-field-guard.js +39 -5
- package/dist/resources/owner-scoped-write-policy.js +212 -0
- package/dist/resources/owner-scoped-writes.js +58 -0
- package/dist/resources/presence-receipt.js +236 -0
- package/dist/resources/promotion-stamp.js +47 -12
- package/dist/resources/record-owner-guard.js +74 -26
- package/dist/resources/record-types.js +17 -1
- package/dist/resources/relay-ops.js +78 -6
- package/dist/resources/replay-store.js +145 -21
- package/dist/resources/request-target.js +136 -0
- package/dist/resources/request-transaction.js +35 -0
- package/dist/resources/search-readiness.js +4 -1
- package/dist/resources/seed-ids.js +9 -0
- package/dist/resources/seed-reservation.js +117 -0
- package/dist/resources/semantic-retrieval-core.js +20 -9
- package/dist/resources/skill-manifest.js +190 -0
- package/dist/resources/skill-provenance.js +15 -10
- package/dist/resources/skill-subject.js +53 -0
- package/dist/resources/skill-version-write.js +432 -0
- package/dist/resources/skill-write-fault.js +17 -0
- package/dist/resources/skill-write-policy.js +67 -0
- package/dist/resources/skill-write.js +67 -7
- package/dist/resources/table-helpers.js +10 -7
- package/dist/resources/team-directory.js +248 -0
- package/dist/resources/tool-descriptors/index.js +69 -8
- package/dist/resources/txn-pause-point.js +118 -0
- package/dist/resources/usage-recording.js +171 -63
- package/dist/resources/write-back.js +218 -0
- package/dist/src/engine-version-contract.js +1 -0
- package/dist/src/keystore.js +72 -0
- package/dist/src/lib/agent-home-fields.js +132 -0
- package/dist/src/lib/agent-id-rule.js +46 -0
- package/dist/src/lib/agent-key-register.js +80 -0
- package/dist/src/lib/atomic-write.js +256 -0
- package/dist/src/lib/credential-status-rule.js +78 -0
- package/dist/src/lib/expired-by-agent.js +37 -0
- package/dist/src/lib/flair-agent-role.js +120 -0
- package/dist/src/lib/idp-mapping-rule.js +81 -0
- package/dist/src/lib/instance-identity-row.js +20 -0
- package/dist/src/lib/mcp-oauth-env-core.js +133 -0
- package/dist/src/lib/memory-attributes.js +2 -0
- package/dist/src/lib/memory-id-policy.js +46 -0
- package/dist/src/lib/principal-status.js +29 -0
- package/dist/src/lib/proto-safe-record.js +42 -0
- package/dist/src/lib/reembed-server-support.js +66 -0
- package/dist/src/lib/scheduler-platform.js +10 -6
- package/dist/src/lib/systemd-agent-id.js +38 -0
- package/docs/access-control.md +768 -0
- package/docs/api-reference.md +52 -13
- package/docs/auth.md +10 -12
- package/docs/bridges.md +11 -0
- package/docs/claude-code.md +34 -4
- package/docs/deepseek-harness.md +1 -1
- package/docs/deploying-on-fabric.md +70 -0
- package/docs/deployment.md +2 -0
- package/docs/embedding-in-a-harper-app.md +1 -1
- package/docs/federation.md +33 -2
- package/docs/hosted-on-fabric.md +43 -36
- package/docs/integrations.md +6 -6
- package/docs/mcp-clients.md +10 -5
- package/docs/n8n.md +17 -11
- package/docs/notes/mcp-agent-auth-consumer.md +12 -4
- package/docs/notes/mcp-oauth-model2.md +34 -5
- package/docs/quickstart-fabric.md +2 -2
- package/docs/quickstart.md +9 -1
- package/docs/releasing.md +34 -28
- package/docs/rem.md +8 -0
- package/docs/secrets-and-keys.md +19 -2
- package/docs/standalone-local.md +1 -0
- package/docs/supply-chain-policy.md +13 -3
- package/docs/upgrade.md +32 -6
- package/package.json +12 -6
- package/schemas/agent-key-registration.graphql +22 -0
- package/schemas/agent.graphql +3 -0
- package/schemas/federation.graphql +38 -1
- package/schemas/memory.graphql +115 -5
- package/schemas/oauth.graphql +27 -4
- package/schemas/schema.graphql +2 -0
- package/templates/launchd/start-flair-with-admin-pass.sh +89 -16
package/dist/resources/Memory.js
CHANGED
|
@@ -1,10 +1,16 @@
|
|
|
1
|
+
import { isEmptyEmbedding, normalizeEmptyEmbedding } from "./memory-embedding-value.js";
|
|
2
|
+
import { discardSuppliedVector, suppliedVectorFlags } from "./memory-supplied-vector.js";
|
|
1
3
|
import { databases } from "harper";
|
|
2
4
|
import { randomUUID } from "node:crypto";
|
|
5
|
+
import { isOperatorSeedPut, redactMemoryWrite, redactSkillWrite, storedMemoryText, suppliedMemoryTextFields, suppliedStoredTextFields } from "./memory-redaction.js";
|
|
6
|
+
import { REDACTION_RULES, buildFromAllowlist, storageResult, withheldWriteResult, writeResultResponse } from "./memory-write-response.js";
|
|
7
|
+
import { isDeepStrictEqual } from "node:util";
|
|
3
8
|
import { patchRecord, withDetachedTxn } from "./table-helpers.js";
|
|
4
9
|
import { isAdmin, resolveAgentAuth } from "./agent-auth.js";
|
|
5
10
|
import { guardAuthorityFields } from "./authority-field-guard.js";
|
|
6
11
|
import { isForbiddenOwnerMutation } from "./record-owner-guard.js";
|
|
7
12
|
import { guardOwnerFieldImmutable } from "./owner-field-guard.js";
|
|
13
|
+
import { ownerChangedRefusal } from "./owner-delete-recheck.js";
|
|
8
14
|
import { applyFederationBookkeeping, applyOriginatorInstanceId, dropClientFederationBookkeeping, keepStoredOriginator, resolveStoredRow, stampOriginatorOnCreate } from "./originator-instance.js";
|
|
9
15
|
import { getEmbedding, getModelId } from "./embeddings-provider.js";
|
|
10
16
|
import { isEmbeddingSpaceUniform, noteWriteStamp } from "./embedding-space-guard.js";
|
|
@@ -15,19 +21,29 @@ import { assertValidVisibility, assertVisibilityAllowedForDurability, PRIVATE_VI
|
|
|
15
21
|
import { validateHostSource } from "./host-source.js";
|
|
16
22
|
import { buildPointerRow, extractPointerInputs, isPointerEchoOf, loadStoredPointer, projectRowsThroughPointers, } from "./memory-host-source.js";
|
|
17
23
|
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";
|
|
20
|
-
import {
|
|
21
|
-
import {
|
|
24
|
+
import { DECLARED_MEMORY_ATTRIBUTES, stripUndeclaredMemoryAttributes, stripServerStampedFields } from "./memory-declared-attributes.js";
|
|
25
|
+
import { composesCallerWrite, isJoinableTransaction, withOwnedTransaction, withSharedWriteTransaction } from "./request-transaction.js";
|
|
26
|
+
import { PredecessorVisibilityChanged, applyGrantedVisibility, committedVisibilityDiffers, predecessorVisibilityChangedRefusal } from "./grant-visibility.js";
|
|
27
|
+
import { CommittedRowChanged, GrantedCloseRevoked, confirmCommittedRow, grantedCloseRevokedRefusal, sameStoredRow, storedRowChangedRefusal, writeGrantHeld } from "./write-back.js";
|
|
28
|
+
import { txnPausePoint } from "./txn-pause-point.js";
|
|
29
|
+
import { markMemoryWriteOutcomeUnknown, memoryWriteOutcomeUnknown, memoryBusyResponse, memoryLockUnavailableResponse, boundLockedProviderCall, MemoryProviderTimeout, memoryProviderTimeoutResponse, withMemoryWriteLock, writeOutcomeUnknownResponse, } from "./memory-write-lock.js";
|
|
30
|
+
import { assertValidDurability, stampEphemeralExpiry } from "./memory-durability.js";
|
|
31
|
+
import { embedTextField, enforceSkillDurability, isSkillWrite, rejectSkillWritePath, refuseSkillWriteSource, skillEmbedText, skillScanGate, skillMetadataHasDuplicateKey } from "./skill-write.js";
|
|
32
|
+
import { embeddedTextHash, hashEmbeddedText } from "./memory-embed-hash.js";
|
|
33
|
+
import { buildSkillSuccessorRow, closedSkillPayloadReadable, defaultSkillHooks, grantedSkillClose, resolveSkillHead, rowIsSkill, runSkillVersionWrite, skillVersionVisibility, skillPayloadUnchanged, prepareSkillBody, validateSkillSnapshots, authorizeSkillOwners, skillWriteConflict } from "./skill-version-write.js";
|
|
34
|
+
import { deriveSkillSubjectId } from "./skill-subject.js";
|
|
22
35
|
import { DEDUP_COSINE_THRESHOLD_DEFAULT, DEDUP_LEXICAL_THRESHOLD_DEFAULT, DEDUP_MIN_CONTENT_LENGTH, computeMatchConfidence, cosineSimilarity, isConservativeMatch, } from "./dedup.js";
|
|
23
|
-
import { buildProvenance, makeAuthGate, makeReadScope, makeByIdReadGate, makeScopedSearch, resolveAuthGate, stampAttribution, FORBIDDEN, UNAUTH, } from "./record-type-kit.js";
|
|
36
|
+
import { buildProvenance, makeAuthGate, makeReadScope, makeByIdReadGate, makeScopedSearch, resolveAuthGate, stampAttribution, FORBIDDEN, UNAUTH, NOT_FOUND, } from "./record-type-kit.js";
|
|
24
37
|
import { isSemanticPatch, MEMORY_SEMANTIC_FIELDS } from "./provenance.js";
|
|
25
38
|
import { RECORD_TYPES } from "./record-types.js";
|
|
26
39
|
import { attachTrust } from "./trust-block.js";
|
|
27
40
|
import { recordCitations } from "./usage-recording.js";
|
|
28
41
|
import { noteMemoryUpsert, noteMemoryDelete } from "./bm25-index-service.js";
|
|
42
|
+
import { recordMemoryDeletion } from "./memory-deletion-history.js";
|
|
29
43
|
import { applyHitStats, clearHitStats, overlayHitStatsResult } from "./hit-tracking.js";
|
|
30
44
|
import { refuseStaleClientWrite, stripClientVersionPassthrough } from "./client-version-gate.js";
|
|
45
|
+
import { refuseReservedSeedWrite, reservedSeedWriteDenial, reservedSeedSubjectDenial, isReservedSeedId, writeTargetIds } from "./seed-reservation.js";
|
|
46
|
+
import { refuseContentSuffixId, resolveMemoryReferenceId, supersedesTargetMissing, supersedesTargetUnreadable } from "./memory-id-guard.js";
|
|
31
47
|
/** flair#1940 A1' — a named 400 for an invalid host pointer (reject, never
|
|
32
48
|
* truncate). Same shape the pre-A1' inline checks returned. */
|
|
33
49
|
function hostSourceBadRequest(error, message) {
|
|
@@ -60,16 +76,24 @@ function withoutCallerSelection(query) {
|
|
|
60
76
|
* so the base collection `create(id, record, context)` is used, which honours
|
|
61
77
|
* an explicit context and joins `c.transaction`. Returns the new id. Falls
|
|
62
78
|
* back to the static post for the unit mock (which models post, not create).
|
|
79
|
+
* flair#2561: a Response from the storage layer is returned as the
|
|
80
|
+
* `write_response_withheld` refusal (storageResult), never as an id.
|
|
63
81
|
*/
|
|
64
82
|
async function writeMemoryRowPost(cls, content, c) {
|
|
65
83
|
if (typeof cls?.create === "function") {
|
|
66
|
-
const created = await cls.create(content.id ?? null, content, c);
|
|
84
|
+
const created = storageResult(await cls.create(content.id ?? null, content, c));
|
|
85
|
+
if (created instanceof Response)
|
|
86
|
+
return created;
|
|
67
87
|
if (typeof created === "string")
|
|
68
88
|
return created;
|
|
69
|
-
|
|
89
|
+
const id = created?.getId?.() ?? created?.id;
|
|
90
|
+
return typeof id === "string" ? id : withheldWriteResult();
|
|
70
91
|
}
|
|
71
|
-
const r = await databases.flair.Memory.post(content, c);
|
|
72
|
-
|
|
92
|
+
const r = storageResult(await databases.flair.Memory.post(content, c));
|
|
93
|
+
if (r instanceof Response)
|
|
94
|
+
return r;
|
|
95
|
+
const id = typeof r === "string" ? r : r?.id;
|
|
96
|
+
return typeof id === "string" ? id : withheldWriteResult();
|
|
73
97
|
}
|
|
74
98
|
/** The authenticated author id for a pointer row, or "" when there is no
|
|
75
99
|
* principal (internal write). NEVER the body. */
|
|
@@ -163,6 +187,111 @@ function abortRequestTransaction(ctx) {
|
|
|
163
187
|
// failure MUST propagate rather than being swallowed behind a 500 body.
|
|
164
188
|
txn.abort();
|
|
165
189
|
}
|
|
190
|
+
/**
|
|
191
|
+
* flair#2478 slice 1 — the `Memory.primaryStore` write-lock handle. Production
|
|
192
|
+
* is a real Harper table (a `primaryStore` with `tryLock`/`unlock`). A store
|
|
193
|
+
* without a lock reports `unavailable`, and PUT/PATCH refuse with 503
|
|
194
|
+
* `memory_lock_unavailable`; they never run unserialized. A unit-test double
|
|
195
|
+
* supplies a lock on its mock table's `primaryStore`.
|
|
196
|
+
*/
|
|
197
|
+
function memoryWriteLockStore() {
|
|
198
|
+
return databases?.flair?.Memory?.primaryStore;
|
|
199
|
+
}
|
|
200
|
+
/** The lock ids a Memory verb names: the URL-bound id and body id(s), dropping
|
|
201
|
+
* non-id values so the sorted, deduplicated key set is real. */
|
|
202
|
+
function putLockIds(resource, content) {
|
|
203
|
+
return writeTargetIds(resource, content)
|
|
204
|
+
.filter((id) => typeof id === "string" || typeof id === "number")
|
|
205
|
+
.map((id) => String(id));
|
|
206
|
+
}
|
|
207
|
+
/** The caller id a lock-miss refusal carries — the request's agent annotation,
|
|
208
|
+
* else `anonymous`/`internal`. Never stored-row state (Sherlock S7). */
|
|
209
|
+
function memoryLockCallerId(resource) {
|
|
210
|
+
const ctx = resource?.getContext?.();
|
|
211
|
+
const request = ctx?.request ?? ctx;
|
|
212
|
+
if (typeof request?.tpsAgent === "string" && request.tpsAgent.length > 0)
|
|
213
|
+
return request.tpsAgent;
|
|
214
|
+
if (request?.tpsAnonymous === true)
|
|
215
|
+
return "anonymous";
|
|
216
|
+
return "internal";
|
|
217
|
+
}
|
|
218
|
+
/** Map a lock outcome to its refusal `Response`, or `null` when the verb ran. */
|
|
219
|
+
function memoryLockRefusal(outcome, callerId) {
|
|
220
|
+
if (outcome.kind === "busy")
|
|
221
|
+
return memoryBusyResponse(callerId);
|
|
222
|
+
if (outcome.kind === "unknown")
|
|
223
|
+
return writeOutcomeUnknownResponse();
|
|
224
|
+
if (outcome.kind === "unavailable")
|
|
225
|
+
return memoryLockUnavailableResponse();
|
|
226
|
+
return null;
|
|
227
|
+
}
|
|
228
|
+
/** PUT and PATCH require a target id before entering the lock helper. */
|
|
229
|
+
function memoryIdRequiredResponse() {
|
|
230
|
+
return new Response(JSON.stringify({
|
|
231
|
+
error: "memory_id_required",
|
|
232
|
+
message: "a Memory PUT or PATCH names the memory id in the URL or the body; to create a memory without choosing an id, use POST",
|
|
233
|
+
}), { status: 400, headers: { "content-type": "application/json" } });
|
|
234
|
+
}
|
|
235
|
+
/**
|
|
236
|
+
* The durable fields a post-commit read must still find at the value this write
|
|
237
|
+
* declared (flair#2478). A field the write did not declare is not compared — the
|
|
238
|
+
* stored value stands for it. `archived` is not compared: the maintenance sweep
|
|
239
|
+
* flips it as a newer field-only write, which folds around this older full
|
|
240
|
+
* update instead of replacing it (flair#2470), so a differing `archived` is not
|
|
241
|
+
* evidence that this write did not land.
|
|
242
|
+
*/
|
|
243
|
+
const POSTCOMMIT_VERIFY_FIELDS = ["agentId", "content", "visibility", "durability"];
|
|
244
|
+
function sameDeclaredField(stored, declared) {
|
|
245
|
+
if (stored === declared)
|
|
246
|
+
return true;
|
|
247
|
+
if (stored == null || declared == null)
|
|
248
|
+
return stored === declared;
|
|
249
|
+
if (typeof stored === "object" || typeof declared === "object") {
|
|
250
|
+
return JSON.stringify(stored) === JSON.stringify(declared);
|
|
251
|
+
}
|
|
252
|
+
return false;
|
|
253
|
+
}
|
|
254
|
+
/**
|
|
255
|
+
* Compare the token and declared POSTCOMMIT_VERIFY_FIELDS after an ordinary
|
|
256
|
+
* owned row write with a normal storage result, or a successful re-embed's
|
|
257
|
+
* inner commit, under the lock. Refusals, storage Responses and skill PUT return before
|
|
258
|
+
* this read; composed promotion uses its caller's in-transaction existence check.
|
|
259
|
+
* Return a verdict, never the stored row: mismatch yields 409; a failed read or
|
|
260
|
+
* missing id yields an unknown outcome (503).
|
|
261
|
+
*/
|
|
262
|
+
async function verifyCommittedWrite(table, declared, fallbackId, identity) {
|
|
263
|
+
const id = declared?.id ?? fallbackId;
|
|
264
|
+
if (id === undefined || id === null)
|
|
265
|
+
return { unknown: true };
|
|
266
|
+
let row;
|
|
267
|
+
try {
|
|
268
|
+
row = await table.get(id, {});
|
|
269
|
+
}
|
|
270
|
+
catch {
|
|
271
|
+
return { unknown: true };
|
|
272
|
+
}
|
|
273
|
+
if (!row)
|
|
274
|
+
return { mismatch: true };
|
|
275
|
+
if ((row.instanceToken ?? null) !== (identity.expectedToken ?? null))
|
|
276
|
+
return { mismatch: true };
|
|
277
|
+
for (const field of POSTCOMMIT_VERIFY_FIELDS) {
|
|
278
|
+
if (!Object.prototype.hasOwnProperty.call(declared, field))
|
|
279
|
+
continue;
|
|
280
|
+
if (!sameDeclaredField(row[field], declared[field]))
|
|
281
|
+
return { mismatch: true };
|
|
282
|
+
}
|
|
283
|
+
return {};
|
|
284
|
+
}
|
|
285
|
+
/** Mark the id after a failed post-commit verification read (flair#2478). */
|
|
286
|
+
function writeOutcomeUnknownFor(id) {
|
|
287
|
+
if (typeof id === "string" || typeof id === "number")
|
|
288
|
+
markMemoryWriteOutcomeUnknown(id);
|
|
289
|
+
return writeOutcomeUnknownResponse();
|
|
290
|
+
}
|
|
291
|
+
/** Refuse a provider call still pending when the timeout callback runs, or settling after the bound. */
|
|
292
|
+
function embedUnderLock(text) {
|
|
293
|
+
return boundLockedProviderCall(() => getEmbedding(text, "document"));
|
|
294
|
+
}
|
|
166
295
|
/**
|
|
167
296
|
* flair#1940 A1' item 2 — persist the pointer row in the SAME request
|
|
168
297
|
* transaction as the Memory row. The request context is passed to the table
|
|
@@ -313,10 +442,15 @@ async function findConservativeDedupMatch(ctx, agentId, contentText, embedding,
|
|
|
313
442
|
if (!agentId || !embedding || embedding.length === 0)
|
|
314
443
|
return null;
|
|
315
444
|
// ── Vector-space uniformity guard (embedding-space-guard slice 1) ──────────
|
|
316
|
-
// When the
|
|
317
|
-
// compare below
|
|
318
|
-
//
|
|
319
|
-
//
|
|
445
|
+
// When the stored model stamps are NOT KNOWN uniform in the current embedding
|
|
446
|
+
// space, the cosine compare below could cross vector spaces or produce an
|
|
447
|
+
// invalid score (Harper zero-pads a mismatched-dimension vector). No-op the
|
|
448
|
+
// dedup cosine leg — treat as no-match — through
|
|
449
|
+
// the SAME single chokepoint the recall leg (SemanticSearch) consults. The
|
|
450
|
+
// guard fails CLOSED (flair#2530): it returns false for an UNKNOWN verdict too
|
|
451
|
+
// (before the first scan completes, or after a scan error), so this leg no-ops
|
|
452
|
+
// in exactly those states — the same no-match behavior as the `mixed` state. This
|
|
453
|
+
// leg surfaces no warning (a skipped comparison is invisible by design).
|
|
320
454
|
// ADVISORY ONLY: the write always proceeds (runDedupGate already computed and
|
|
321
455
|
// stamped a fresh CURRENT-space embedding); this only skips a comparison that
|
|
322
456
|
// can't be trusted while spaces are mixed. Never suppresses a write.
|
|
@@ -432,7 +566,7 @@ async function findConservativeDedupMatch(ctx, agentId, contentText, embedding,
|
|
|
432
566
|
*
|
|
433
567
|
* Returns the match signal, or null (no match / gate not applicable).
|
|
434
568
|
*/
|
|
435
|
-
async function runDedupGate(ctx, content) {
|
|
569
|
+
async function runDedupGate(ctx, content, bounded = false) {
|
|
436
570
|
const cosineThreshold = typeof content.dedupThreshold === "number" ? content.dedupThreshold : DEDUP_COSINE_THRESHOLD_DEFAULT;
|
|
437
571
|
const lexicalThreshold = typeof content.lexicalThreshold === "number" ? content.lexicalThreshold : DEDUP_LEXICAL_THRESHOLD_DEFAULT;
|
|
438
572
|
delete content.dedup;
|
|
@@ -470,9 +604,11 @@ async function runDedupGate(ctx, content) {
|
|
|
470
604
|
let embedding = Array.isArray(content.embedding) ? content.embedding : null;
|
|
471
605
|
if (!embedding) {
|
|
472
606
|
try {
|
|
473
|
-
embedding = await getEmbedding(embedText, "document");
|
|
607
|
+
embedding = bounded ? await embedUnderLock(embedText) : await getEmbedding(embedText, "document");
|
|
474
608
|
}
|
|
475
|
-
catch {
|
|
609
|
+
catch (err) {
|
|
610
|
+
if (err instanceof MemoryProviderTimeout)
|
|
611
|
+
throw err;
|
|
476
612
|
embedding = null;
|
|
477
613
|
}
|
|
478
614
|
if (embedding) {
|
|
@@ -484,85 +620,260 @@ async function runDedupGate(ctx, content) {
|
|
|
484
620
|
return null;
|
|
485
621
|
return findConservativeDedupMatch(ctx, content.agentId, embedText, embedding, cosineThreshold, lexicalThreshold);
|
|
486
622
|
}
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
623
|
+
const RESPONSE_ID = Object.freeze({ type: "string", required: true });
|
|
624
|
+
const RESPONSE_WRITTEN = Object.freeze({ type: "boolean", required: true });
|
|
625
|
+
const MEMORY_WRITE_RESPONSE_RULES = Object.freeze({
|
|
626
|
+
id: RESPONSE_ID,
|
|
627
|
+
written: RESPONSE_WRITTEN,
|
|
628
|
+
deduplicated: Object.freeze({ type: "boolean", required: true }),
|
|
629
|
+
visibility: Object.freeze({ type: "string" }),
|
|
630
|
+
matchedId: Object.freeze({ type: "string" }),
|
|
631
|
+
matchConfidence: Object.freeze({
|
|
632
|
+
type: "object",
|
|
633
|
+
fields: Object.freeze({ cosine: Object.freeze({ type: "number" }), lexical: Object.freeze({ type: "number" }) }),
|
|
634
|
+
}),
|
|
635
|
+
...REDACTION_RULES,
|
|
636
|
+
});
|
|
637
|
+
const SKILL_RESULT_RULES = Object.freeze({
|
|
638
|
+
id: RESPONSE_ID,
|
|
639
|
+
written: RESPONSE_WRITTEN,
|
|
640
|
+
visibility: Object.freeze({ type: "string" }),
|
|
641
|
+
});
|
|
642
|
+
const ROW_WRITE_RESPONSE_RULES = Object.freeze({ id: RESPONSE_ID, written: RESPONSE_WRITTEN, ...REDACTION_RULES });
|
|
643
|
+
const REEMBED_RESPONSE_RULES = Object.freeze({
|
|
644
|
+
id: RESPONSE_ID,
|
|
645
|
+
updatedAt: Object.freeze({ type: "string", required: true }),
|
|
646
|
+
});
|
|
647
|
+
function redactionValues(redactedValues, stored) {
|
|
648
|
+
return redactedValues > 0 ? { redactedValues, stored: stored ?? undefined } : {};
|
|
649
|
+
}
|
|
650
|
+
function skillWriteResponse(result, redactedValues, stored) {
|
|
651
|
+
if (result instanceof Response)
|
|
652
|
+
return writeResultResponse(result);
|
|
653
|
+
const built = buildFromAllowlist(result, SKILL_RESULT_RULES);
|
|
654
|
+
if (built instanceof Response || redactedValues <= 0)
|
|
655
|
+
return built;
|
|
656
|
+
const redaction = buildFromAllowlist(redactionValues(redactedValues, stored), REDACTION_RULES);
|
|
657
|
+
return redaction instanceof Response ? redaction : Object.assign(built, redaction);
|
|
658
|
+
}
|
|
659
|
+
/**
|
|
660
|
+
* The answer of a PATCH and of the admin `_reindex` re-PUT. A Response from
|
|
661
|
+
* storage is refused (writeResultResponse). A write that replaced no value
|
|
662
|
+
* answers with no body (HTTP 204), the answer Harper gives for a PATCH; a write
|
|
663
|
+
* that replaced a value answers `{ id, written, redactedValues, stored }`, built
|
|
664
|
+
* from those named fields. Any other storage result is never read into the answer.
|
|
665
|
+
*/
|
|
666
|
+
function rowWriteResponse(result, id, redactedValues, stored) {
|
|
667
|
+
if (result instanceof Response)
|
|
668
|
+
return writeResultResponse(result);
|
|
669
|
+
if (redactedValues <= 0)
|
|
670
|
+
return undefined;
|
|
671
|
+
return buildFromAllowlist({ id, written: true, ...redactionValues(redactedValues, stored) }, ROW_WRITE_RESPONSE_RULES);
|
|
672
|
+
}
|
|
673
|
+
function buildWriteResponse(content, result, dedupMatch, redactedValues, stored, rowId) {
|
|
674
|
+
if (result instanceof Response)
|
|
675
|
+
return writeResultResponse(result);
|
|
676
|
+
return buildFromAllowlist({
|
|
677
|
+
id: content.id ?? rowId,
|
|
514
678
|
written: true,
|
|
515
679
|
deduplicated: !!dedupMatch,
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
680
|
+
visibility: content.visibility,
|
|
681
|
+
matchedId: dedupMatch?.matchedId,
|
|
682
|
+
matchConfidence: dedupMatch ? { cosine: dedupMatch.cosine, lexical: dedupMatch.lexical } : undefined,
|
|
683
|
+
...redactionValues(redactedValues, stored),
|
|
684
|
+
}, MEMORY_WRITE_RESPONSE_RULES);
|
|
685
|
+
}
|
|
686
|
+
const REINDEX_BOOKKEEPING_FIELDS = new Set([
|
|
687
|
+
"embedding", "embeddingModel", "contentHash", "retrievalCount", "lastRetrieved", "usageCount",
|
|
688
|
+
]);
|
|
689
|
+
const REINDEX_PROTECTED_FIELDS = DECLARED_MEMORY_ATTRIBUTES.filter((field) => !REINDEX_BOOKKEEPING_FIELDS.has(field));
|
|
690
|
+
function reindexDrift(content, existing) {
|
|
691
|
+
const isSkill = rowIsSkill(existing);
|
|
692
|
+
if (!isSkill && rowIsSkill(content))
|
|
693
|
+
return "tags";
|
|
694
|
+
for (const field of REINDEX_PROTECTED_FIELDS) {
|
|
695
|
+
if (!Object.prototype.hasOwnProperty.call(content, field))
|
|
696
|
+
continue;
|
|
697
|
+
const submitted = content[field];
|
|
698
|
+
const stored = existing[field];
|
|
699
|
+
if (submitted === stored)
|
|
700
|
+
continue;
|
|
701
|
+
if ((field === "metadata" || Array.isArray(submitted)) && JSON.stringify(submitted ?? null) === JSON.stringify(stored ?? null))
|
|
702
|
+
continue;
|
|
703
|
+
return field;
|
|
704
|
+
}
|
|
705
|
+
return null;
|
|
706
|
+
}
|
|
707
|
+
/** The row a `_reindex` re-PUT writes over `existing` (the stored row), or its
|
|
708
|
+
* refusal. Memory.put()'s `_reindex` branch and the MemoryReindex write-back
|
|
709
|
+
* both build their row here (flair#2354). */
|
|
710
|
+
export function buildReindexRow(content, existing) {
|
|
711
|
+
delete content._reindex;
|
|
712
|
+
// A1' item 1: the reindex branch keeps declared and named retained
|
|
713
|
+
// attributes. Pinned by test/unit/memory-host-source.test.ts
|
|
714
|
+
// (r20-put-reindex) — RED if this call is removed.
|
|
715
|
+
stripUndeclaredMemoryAttributes(content);
|
|
716
|
+
// A1-iv items 1/3: strip a client-supplied server-stamped field, then
|
|
717
|
+
// PRESERVE the existing row's incarnation token (reindex is a re-PUT of
|
|
718
|
+
// an existing row, never a reincarnation).
|
|
719
|
+
const reindexBody = { ...content };
|
|
720
|
+
stripServerStampedFields(content);
|
|
721
|
+
// A reindex is a re-PUT of an EXISTING row, so an absent stored row is
|
|
722
|
+
// refused — it is never re-created/re-stamped.
|
|
723
|
+
if (!existing) {
|
|
724
|
+
return { status: 404, error: "reindex_row_not_found", message: "the _reindex re-PUT requires an existing stored row" };
|
|
519
725
|
}
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
726
|
+
const effective = { ...existing, ...content };
|
|
727
|
+
if (rowIsSkill(effective) && skillMetadataHasDuplicateKey(effective.metadata)) {
|
|
728
|
+
return { status: 400, error: "skill_metadata_duplicate_key", message: "skill metadata requires distinct top-level keys" };
|
|
523
729
|
}
|
|
524
|
-
|
|
730
|
+
const drift = reindexDrift(reindexBody, existing);
|
|
731
|
+
if (drift) {
|
|
732
|
+
return { status: 409, error: "reindex_would_change_row", message: `the _reindex re-PUT may not change '${drift}'` };
|
|
733
|
+
}
|
|
734
|
+
stampInstanceToken(content, existing);
|
|
735
|
+
for (const field of REINDEX_PROTECTED_FIELDS) {
|
|
736
|
+
if (!Object.prototype.hasOwnProperty.call(content, field) && existing[field] !== undefined) {
|
|
737
|
+
content[field] = existing[field];
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
// Keep the EXISTING row's STORED provenance byte-for-byte. The rest of
|
|
741
|
+
// the row is filtered above and may gain an absent incarnation token.
|
|
742
|
+
// The body's provenance was stripped above so it cannot be forged;
|
|
743
|
+
// restoring it from `existing` (never from the submitted value)
|
|
744
|
+
// keeps provenance byte-identical across a corpus-wide reindex.
|
|
745
|
+
// Pinned by test/unit/memory-host-source.test.ts (r20-put-reindex) — RED
|
|
746
|
+
// if this restore is removed.
|
|
747
|
+
if (typeof existing.provenance === "string") {
|
|
748
|
+
content.provenance = existing.provenance;
|
|
749
|
+
}
|
|
750
|
+
// flair#1965: a reindex is a re-PUT of an EXISTING row (an UPDATE), so the
|
|
751
|
+
// row's stored originatorInstanceId stands; a body value is dropped, and a
|
|
752
|
+
// legacy row with no value is left un-stamped. See
|
|
753
|
+
// resources/originator-instance.ts.
|
|
754
|
+
keepStoredOriginator(content, existing);
|
|
755
|
+
// The receiver-side federation bookkeeping likewise stands as stored.
|
|
756
|
+
applyFederationBookkeeping(content, existing);
|
|
757
|
+
// Preserve stored visibility on updates before applying write policy:
|
|
758
|
+
// a reindex payload that omits it keeps the record's stored value.
|
|
759
|
+
if (content.visibility === undefined || content.visibility === null) {
|
|
760
|
+
if (existing.visibility === PRIVATE_VISIBILITY || existing.visibility === SHARED_VISIBILITY) {
|
|
761
|
+
content.visibility = existing.visibility;
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
normalizeEmptyEmbedding(content);
|
|
765
|
+
return { row: content };
|
|
525
766
|
}
|
|
767
|
+
/** Aborts the close's owned transaction: the row changed after the transaction read it. */
|
|
768
|
+
class CloseTargetChanged extends Error {
|
|
769
|
+
}
|
|
770
|
+
/** Attempts of the close before it gives up on a row that keeps changing. */
|
|
771
|
+
const SUPERSEDE_CLOSE_ATTEMPTS = 3;
|
|
526
772
|
/**
|
|
527
|
-
* Read-modify-write close
|
|
528
|
-
*
|
|
529
|
-
*
|
|
530
|
-
*
|
|
531
|
-
*
|
|
532
|
-
*
|
|
773
|
+
* Read-modify-write close for ordinary Memory writes. Does NOT swallow failures —
|
|
774
|
+
* throws so the caller can log it. Never called before the new record is
|
|
775
|
+
* already written.
|
|
776
|
+
*
|
|
777
|
+
* flair#2307: the read and write run in ONE owned
|
|
778
|
+
* transaction (withOwnedTransaction, the MemoryMaintenance pattern: the
|
|
779
|
+
* request's transaction is detached and a fresh one this call owns is created),
|
|
780
|
+
* and the write is built from the row read inside it. `expectedOwner`, when
|
|
781
|
+
* supplied by a non-admin agent's close plan, is the owner the authorization
|
|
782
|
+
* read saw; a differing owner at the transaction read throws instead of closing.
|
|
783
|
+
* Admin and internal close plans have no expected owner.
|
|
784
|
+
*
|
|
785
|
+
* Harper 5.2.8 has no compare-and-set on a table write: a transaction does not
|
|
786
|
+
* fail when a row it read is changed by another write before it commits;
|
|
787
|
+
* Harper applies both writes, ordered by transaction timestamp. So once the
|
|
788
|
+
* write is staged, and before the transaction commits, the close re-reads the
|
|
789
|
+
* committed row outside the transaction (an empty context: Harper's latest
|
|
790
|
+
* committed state, not this transaction's snapshot or its staged write). If
|
|
791
|
+
* that row is no longer the one read inside the transaction, the transaction
|
|
792
|
+
* is aborted (the staged write is discarded) and the close starts over from
|
|
793
|
+
* the committed row: SUPERSEDE_CLOSE_ATTEMPTS (three) attempts in all, so at
|
|
794
|
+
* most two retries. A change committed after that re-read and before the commit is not
|
|
795
|
+
* seen by it; Harper orders the two writes by timestamp.
|
|
796
|
+
*
|
|
797
|
+
* A close a "write" grant authorizes does not run here: it is staged in the
|
|
798
|
+
* successor's own transaction (stageGrantedClose).
|
|
533
799
|
*/
|
|
534
|
-
async function closeSupersededRecord(ctx, oldId, patch) {
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
800
|
+
async function closeSupersededRecord(ctx, oldId, patch, expectedOwner) {
|
|
801
|
+
for (let attempt = 1;; attempt++) {
|
|
802
|
+
let closedRow;
|
|
803
|
+
try {
|
|
804
|
+
closedRow = await withOwnedTransaction(ctx, async (c) => {
|
|
805
|
+
const existing = await databases.flair.Memory.get(oldId, c);
|
|
806
|
+
if (!existing) {
|
|
807
|
+
throw new Error(`supersede-close: record ${oldId} not found`);
|
|
808
|
+
}
|
|
809
|
+
if (expectedOwner !== undefined && existing.agentId !== expectedOwner) {
|
|
810
|
+
throw new Error(`supersede-close: record ${oldId} is no longer owned by the authorized owner`);
|
|
811
|
+
}
|
|
812
|
+
// Test-only: inert unless the fault-injection env opt-in is set and armed.
|
|
813
|
+
const pause = txnPausePoint("supersede-close");
|
|
814
|
+
if (pause)
|
|
815
|
+
await pause;
|
|
816
|
+
const closed = { ...existing, ...patch };
|
|
817
|
+
stripUndeclaredMemoryAttributes(closed);
|
|
818
|
+
normalizeEmptyEmbedding(closed);
|
|
819
|
+
await databases.flair.Memory.put(closed, c);
|
|
820
|
+
// Test-only: inert unless armed — here the write is staged, so a
|
|
821
|
+
// competing write and the committed-state re-reads below can be exercised
|
|
822
|
+
// in either order.
|
|
823
|
+
const stagedPause = txnPausePoint("supersede-close-staged");
|
|
824
|
+
if (stagedPause)
|
|
825
|
+
await stagedPause;
|
|
826
|
+
const committed = await databases.flair.Memory.get(oldId, {});
|
|
827
|
+
if (!isDeepStrictEqual(committed, existing))
|
|
828
|
+
throw new CloseTargetChanged();
|
|
829
|
+
return closed;
|
|
830
|
+
});
|
|
831
|
+
}
|
|
832
|
+
catch (err) {
|
|
833
|
+
if (!(err instanceof CloseTargetChanged))
|
|
834
|
+
throw err;
|
|
835
|
+
if (attempt < SUPERSEDE_CLOSE_ATTEMPTS)
|
|
836
|
+
continue;
|
|
837
|
+
throw new Error(`supersede-close: record ${oldId} changed during each of ${SUPERSEDE_CLOSE_ATTEMPTS} attempts; not closed`);
|
|
838
|
+
}
|
|
839
|
+
// flair#1357 — a supersede-close sets `validTo`, which the retrieval filters
|
|
840
|
+
// read, so the lexical index has to see it as eagerly as a content write.
|
|
841
|
+
noteMemoryUpsert(closedRow);
|
|
842
|
+
return;
|
|
843
|
+
}
|
|
844
|
+
}
|
|
845
|
+
/**
|
|
846
|
+
* Stamp `lastReflected` on each existing `derivedFrom` source of a new row
|
|
847
|
+
* (best-effort bookkeeping; a failure is swallowed). Called only after the new
|
|
848
|
+
* row was written (flair#2307): a refused write changes no source row.
|
|
849
|
+
* lastReflected keys off updatedAt (the write moment), NOT createdAt — since
|
|
850
|
+
* #1336 a create may carry a backdated caller createdAt, and the reflection
|
|
851
|
+
* bookkeeping must record when the derivation actually ran.
|
|
852
|
+
*/
|
|
853
|
+
async function markDerivedSourcesReflected(content) {
|
|
854
|
+
if (!Array.isArray(content.derivedFrom) || content.derivedFrom.length === 0)
|
|
855
|
+
return;
|
|
856
|
+
const now = content.updatedAt;
|
|
857
|
+
for (const sourceId of content.derivedFrom) {
|
|
858
|
+
try {
|
|
859
|
+
const src = await databases.flair.Memory.get(sourceId);
|
|
860
|
+
if (src) {
|
|
861
|
+
const reflectPatch = { lastReflected: now };
|
|
862
|
+
stripUndeclaredMemoryAttributes(reflectPatch);
|
|
863
|
+
await patchRecord(databases.flair.Memory, sourceId, reflectPatch, {
|
|
864
|
+
pausePre: () => txnPausePoint("last-reflected-pre"), pausePoint: () => txnPausePoint("last-reflected"), expectedRow: src,
|
|
865
|
+
}).catch(() => { });
|
|
866
|
+
}
|
|
867
|
+
}
|
|
868
|
+
catch { }
|
|
538
869
|
}
|
|
539
|
-
const closed = { ...existing, ...patch };
|
|
540
|
-
stripUndeclaredMemoryAttributes(closed);
|
|
541
|
-
await withDetachedTxn(ctx, () => databases.flair.Memory.put(closed));
|
|
542
|
-
// flair#1357 — a supersede-close sets `validTo`, which the retrieval filters
|
|
543
|
-
// read, so the lexical index has to see it as eagerly as a content write.
|
|
544
|
-
noteMemoryUpsert(closed);
|
|
545
870
|
}
|
|
546
871
|
/** Does an agent hold a "write" grant from `ownerId`? Same MemoryGrant lookup
|
|
547
872
|
* the read paths used before the open-within-org reframe (reads no longer
|
|
548
873
|
* consult MemoryGrant); it survives here for the "write" scope that gates
|
|
549
874
|
* cross-agent supersede. */
|
|
550
|
-
async function hasWriteGrant(granteeId, ownerId) {
|
|
551
|
-
|
|
552
|
-
for await (const grant of databases.flair.MemoryGrant.search({
|
|
553
|
-
conditions: [
|
|
554
|
-
{ attribute: "granteeId", comparator: "equals", value: granteeId },
|
|
555
|
-
{ attribute: "ownerId", comparator: "equals", value: ownerId },
|
|
556
|
-
],
|
|
557
|
-
})) {
|
|
558
|
-
if (grant.scope === "write")
|
|
559
|
-
return true;
|
|
560
|
-
}
|
|
561
|
-
}
|
|
562
|
-
catch {
|
|
563
|
-
/* MemoryGrant table not yet populated — no grant */
|
|
564
|
-
}
|
|
565
|
-
return false;
|
|
875
|
+
async function hasWriteGrant(granteeId, ownerId, ctx) {
|
|
876
|
+
return writeGrantHeld(databases.flair.MemoryGrant, granteeId, ownerId, ctx);
|
|
566
877
|
}
|
|
567
878
|
/**
|
|
568
879
|
* Shared by post() AND put(): the Memory schema only exposes a working HTTP
|
|
@@ -577,8 +888,38 @@ async function hasWriteGrant(granteeId, ownerId) {
|
|
|
577
888
|
*
|
|
578
889
|
* Validates the `supersedes` field's shape and, for a cross-agent supersede,
|
|
579
890
|
* requires a "write" MemoryGrant from the target's owner (reuses the existing
|
|
580
|
-
* agent-auth/grant machinery — no parallel auth logic). Returns a
|
|
581
|
-
* short-circuit with
|
|
891
|
+
* agent-auth/grant machinery — no parallel auth logic). Returns `denial` (a
|
|
892
|
+
* Response to short-circuit with) or the `close` the write is authorized to
|
|
893
|
+
* perform once the new record is written (null: close nothing).
|
|
894
|
+
*
|
|
895
|
+
* flair#2307: `content.supersedes` is already the canonical id
|
|
896
|
+
* (canonicalizeSupersedes), so the reserved-id check, the authorization read,
|
|
897
|
+
* the stored reference and the close all name the same row. For a non-admin
|
|
898
|
+
* agent, a failed target read refuses (supersedesTargetUnreadable) and a
|
|
899
|
+
* missing target refuses (supersedesTargetMissing) — except a reference that is
|
|
900
|
+
* unchanged from the stored row's own `supersedes` (a re-PUT of a successor
|
|
901
|
+
* whose predecessor was since deleted), which is kept and closes nothing.
|
|
902
|
+
* For a non-admin agent's ordinary Memory write, the close carries the owner the read saw;
|
|
903
|
+
* a change visible at the close's committed re-read stops it from landing over
|
|
904
|
+
* that change: closeSupersededRecord (the owner's own close) retries from the
|
|
905
|
+
* committed row, and stageGrantedClose (a grant-authorized one) refuses the
|
|
906
|
+
* whole write.
|
|
907
|
+
* Later changes follow Harper's timestamp order (see the PR residual-gap note).
|
|
908
|
+
* An admin or internal write has no authorization read or owner comparison.
|
|
909
|
+
*
|
|
910
|
+
* A write grant does not include changing a record's visibility; visibility is
|
|
911
|
+
* set by the owner or an admin. For the grant-authorized supersede write,
|
|
912
|
+
* `requestedVisibility` (the visibility the caller's body named, read before
|
|
913
|
+
* any merge, carry or default) must read the same as the target's as this
|
|
914
|
+
* authorization read sees it, and the successor is given that visibility. The
|
|
915
|
+
* close, staged in the successor's transaction, then compares it with the
|
|
916
|
+
* target's visibility at its final committed-state re-read (stageGrantedClose;
|
|
917
|
+
* the skill-version writer for a skill); a mismatch writes nothing, and a
|
|
918
|
+
* change committed after that re-read is not seen by it. The rule governs this
|
|
919
|
+
* write: an ordinary successor
|
|
920
|
+
* is the grantee's own row, so the grantee may later change that row's
|
|
921
|
+
* visibility as its owner, and a skill successor keeps its lineage owner
|
|
922
|
+
* (resources/grant-visibility.ts).
|
|
582
923
|
*
|
|
583
924
|
* flair#704: an explicit `supersedes: null` — the shape most JSON writers
|
|
584
925
|
* produce for an unset optional field (`JSON.stringify({supersedes: undefined})`
|
|
@@ -595,40 +936,92 @@ async function hasWriteGrant(granteeId, ownerId) {
|
|
|
595
936
|
* closeSupersededIfNeeded) already treats it as unset with no further
|
|
596
937
|
* changes needed.
|
|
597
938
|
*/
|
|
598
|
-
async function validateAndAuthorizeSupersedes(content, auth) {
|
|
939
|
+
async function validateAndAuthorizeSupersedes(content, auth, ctx, stored, requestedVisibility) {
|
|
940
|
+
const refuse = (denial) => ({ denial, close: null });
|
|
599
941
|
if (content.supersedes === null) {
|
|
600
942
|
delete content.supersedes;
|
|
601
943
|
}
|
|
602
944
|
if (content.supersedes !== undefined && typeof content.supersedes !== "string") {
|
|
603
|
-
return new Response(JSON.stringify({ error: "supersedes must be a string (memory ID)" }), {
|
|
945
|
+
return refuse(new Response(JSON.stringify({ error: "supersedes must be a string (memory ID)" }), {
|
|
604
946
|
status: 400, headers: { "Content-Type": "application/json" },
|
|
605
|
-
});
|
|
947
|
+
}));
|
|
606
948
|
}
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
949
|
+
// flair#2141 S2: superseding closes the target row, so a reserved seed id
|
|
950
|
+
// needs operator authority here too (resources/seed-reservation.ts).
|
|
951
|
+
const seedDenial = reservedSeedWriteDenial("Memory", [content.supersedes], ctx, auth);
|
|
952
|
+
if (seedDenial)
|
|
953
|
+
return refuse(seedDenial);
|
|
954
|
+
if (!content.supersedes)
|
|
955
|
+
return { denial: null, close: null };
|
|
956
|
+
if (auth.kind !== "agent" || auth.isAdmin)
|
|
957
|
+
return { denial: null, close: { id: content.supersedes } };
|
|
958
|
+
let target;
|
|
959
|
+
try {
|
|
960
|
+
target = await databases.flair.Memory.get(content.supersedes);
|
|
961
|
+
}
|
|
962
|
+
catch (err) {
|
|
963
|
+
return refuse(supersedesTargetUnreadable(err));
|
|
964
|
+
}
|
|
965
|
+
if (!target) {
|
|
966
|
+
if (stored?.supersedes === content.supersedes)
|
|
967
|
+
return { denial: null, close: null };
|
|
968
|
+
return refuse(supersedesTargetMissing());
|
|
969
|
+
}
|
|
970
|
+
if (target.agentId !== auth.agentId) {
|
|
971
|
+
if (!(await hasWriteGrant(auth.agentId, target.agentId))) {
|
|
972
|
+
return refuse(FORBIDDEN("forbidden: cannot supersede a memory owned by another agent without a write grant"));
|
|
973
|
+
}
|
|
974
|
+
// A write grant does not include changing a record's visibility; visibility
|
|
975
|
+
// is set by the owner or an admin. This grant-authorized write gives the
|
|
976
|
+
// successor the predecessor's visibility as read here, and the ephemeral
|
|
977
|
+
// private-only rule (flair#1257) is applied to that value. The close
|
|
978
|
+
// compares it with the predecessor's visibility at its final
|
|
979
|
+
// committed-state re-read (stageGrantedClose, resources/grant-visibility.ts).
|
|
980
|
+
const visibilityDenial = applyGrantedVisibility(content, target, requestedVisibility);
|
|
981
|
+
if (visibilityDenial)
|
|
982
|
+
return refuse(visibilityDenial);
|
|
983
|
+
const tierError = assertVisibilityAllowedForDurability(content.durability ?? stored?.durability, content.visibility);
|
|
984
|
+
if (tierError) {
|
|
985
|
+
return refuse(new Response(JSON.stringify({ error: "invalid_visibility_for_durability", message: tierError }), { status: 400, headers: { "content-type": "application/json" } }));
|
|
613
986
|
}
|
|
987
|
+
// flair#2333 (H10): the close re-checks this grant against committed state
|
|
988
|
+
// before it lands, so the grantee id travels with the close plan.
|
|
989
|
+
return { denial: null, close: { id: content.supersedes, ownerId: target.agentId, granteeId: auth.agentId } };
|
|
614
990
|
}
|
|
615
|
-
return null;
|
|
991
|
+
return { denial: null, close: { id: content.supersedes, ownerId: target.agentId } };
|
|
992
|
+
}
|
|
993
|
+
/**
|
|
994
|
+
* flair#2307: resolve a write's `supersedes` reference to its canonical id ONCE
|
|
995
|
+
* (resolveMemoryReferenceId), before anything reads it, and store that id back
|
|
996
|
+
* on the body. Every later use — the skill body's predecessor read, the
|
|
997
|
+
* reserved-id check, the authorization read, the stored reference and the
|
|
998
|
+
* close — then names the same row. A non-string is left for the shape check.
|
|
999
|
+
*/
|
|
1000
|
+
function canonicalizeSupersedes(content) {
|
|
1001
|
+
if (content && typeof content === "object" && typeof content.supersedes === "string") {
|
|
1002
|
+
content.supersedes = resolveMemoryReferenceId(content.supersedes);
|
|
1003
|
+
}
|
|
1004
|
+
}
|
|
1005
|
+
/** The patch a supersede's close applies to its predecessor. */
|
|
1006
|
+
function supersedeClosePatch(content) {
|
|
1007
|
+
return {
|
|
1008
|
+
validTo: content.validFrom ?? content.createdAt,
|
|
1009
|
+
updatedAt: content.createdAt ?? content.updatedAt,
|
|
1010
|
+
};
|
|
616
1011
|
}
|
|
617
1012
|
/**
|
|
618
1013
|
* Close the superseded record — called AFTER the new record has already been
|
|
619
1014
|
* written (write-new-BEFORE-close-old). Safe failure state is
|
|
620
1015
|
* two active records (recoverable), never a tombstoned-old-with-lost-new.
|
|
621
|
-
* Failure is logged (observable), never silently swallowed. No-op
|
|
622
|
-
*
|
|
1016
|
+
* Failure is logged (observable), never silently swallowed. No-op when
|
|
1017
|
+
* validateAndAuthorizeSupersedes authorized no close. A grant-authorized close
|
|
1018
|
+
* (`close.granteeId`) does not run here (closeGrantedSupersedeStaged).
|
|
623
1019
|
*/
|
|
624
|
-
async function closeSupersededIfNeeded(ctx, content, methodLabel) {
|
|
625
|
-
if (!
|
|
1020
|
+
async function closeSupersededIfNeeded(ctx, content, close, methodLabel) {
|
|
1021
|
+
if (!close)
|
|
626
1022
|
return;
|
|
627
1023
|
try {
|
|
628
|
-
await closeSupersededRecord(ctx,
|
|
629
|
-
validTo: content.validFrom ?? content.createdAt,
|
|
630
|
-
updatedAt: content.createdAt ?? content.updatedAt,
|
|
631
|
-
});
|
|
1024
|
+
await closeSupersededRecord(ctx, close.id, supersedeClosePatch(content), close.ownerId);
|
|
632
1025
|
}
|
|
633
1026
|
catch (err) {
|
|
634
1027
|
// Constant format string + structured data: memory ids are agent-controlled,
|
|
@@ -636,9 +1029,100 @@ async function closeSupersededIfNeeded(ctx, content, methodLabel) {
|
|
|
636
1029
|
// `err` arg) would let an id containing %s/%o consume/hide the real error
|
|
637
1030
|
// (semgrep unsafe-formatstring). Keep all dynamic values in the data object.
|
|
638
1031
|
console.error("Memory.closeSuperseded: failed to close superseded record after writing new record " +
|
|
639
|
-
"(observable, not silent; new record is safely written, old record remains active until retried)", { method: methodLabel, supersededId:
|
|
1032
|
+
"(observable, not silent; new record is safely written, old record remains active until retried)", { method: methodLabel, supersededId: close.id, newRecordId: content.id, err });
|
|
640
1033
|
}
|
|
641
1034
|
}
|
|
1035
|
+
/** A grant-authorized close found its predecessor gone, owned by another
|
|
1036
|
+
* agent, or changed since the write's transaction read it (stageGrantedClose). */
|
|
1037
|
+
class GrantedCloseTargetChanged extends Error {
|
|
1038
|
+
}
|
|
1039
|
+
class GrantedCloseStorageRefused extends Error {
|
|
1040
|
+
}
|
|
1041
|
+
/**
|
|
1042
|
+
* flair#2564: stage a grant-authorized supersede's close (`close.granteeId`)
|
|
1043
|
+
* in `shared`, the successor's transaction (request, caller or write-owned).
|
|
1044
|
+
*
|
|
1045
|
+
* A storage Response aborts the write with write_response_withheld. After
|
|
1046
|
+
* staging the close, the committed row (an empty context) is checked:
|
|
1047
|
+
*
|
|
1048
|
+
* - the committed visibility must read the same as the successor's
|
|
1049
|
+
* (`successorVisibility`): a write grant does not include changing a
|
|
1050
|
+
* record's visibility (grant-visibility.ts). A mismatch throws
|
|
1051
|
+
* PredecessorVisibilityChanged;
|
|
1052
|
+
* - the committed row must still be the one read: a staged write carries its
|
|
1053
|
+
* transaction's timestamp, and Harper orders it before any later-committed
|
|
1054
|
+
* change, so a close staged over a changed row is not retried here. It
|
|
1055
|
+
* throws GrantedCloseTargetChanged, as does a predecessor that is gone or
|
|
1056
|
+
* owned by another agent at the read;
|
|
1057
|
+
* - flair#2333 (H10): the grant is re-checked on committed state; a revoked
|
|
1058
|
+
* grant throws GrantedCloseRevoked.
|
|
1059
|
+
*
|
|
1060
|
+
* The caller aborts the transaction on any of these, so nothing is written,
|
|
1061
|
+
* and a retry runs in a new transaction. As with the other committed re-reads,
|
|
1062
|
+
* a change committed after this final re-read and before the transaction
|
|
1063
|
+
* commits is not seen by it; Harper orders the writes by transaction timestamp.
|
|
1064
|
+
*/
|
|
1065
|
+
async function stageGrantedClose(shared, close, patch, successorVisibility) {
|
|
1066
|
+
const existing = await databases.flair.Memory.get(close.id, shared);
|
|
1067
|
+
if (!existing || existing.agentId !== close.ownerId)
|
|
1068
|
+
throw new GrantedCloseTargetChanged();
|
|
1069
|
+
// Test-only: inert unless the fault-injection env opt-in is set and armed.
|
|
1070
|
+
const pause = txnPausePoint("granted-close");
|
|
1071
|
+
if (pause)
|
|
1072
|
+
await pause;
|
|
1073
|
+
const closed = { ...existing, ...patch };
|
|
1074
|
+
stripUndeclaredMemoryAttributes(closed);
|
|
1075
|
+
const result = await databases.flair.Memory.put(closed, shared);
|
|
1076
|
+
if (result instanceof Response)
|
|
1077
|
+
throw new GrantedCloseStorageRefused();
|
|
1078
|
+
// Test-only: inert unless armed — here the close is staged, so a competing
|
|
1079
|
+
// write and the committed-state re-reads below can be exercised in either
|
|
1080
|
+
// order.
|
|
1081
|
+
const stagedPause = txnPausePoint("granted-close-staged");
|
|
1082
|
+
if (stagedPause)
|
|
1083
|
+
await stagedPause;
|
|
1084
|
+
const committed = await databases.flair.Memory.get(close.id, {});
|
|
1085
|
+
if (committedVisibilityDiffers(committed, successorVisibility))
|
|
1086
|
+
throw new PredecessorVisibilityChanged();
|
|
1087
|
+
if (!isDeepStrictEqual(committed, existing))
|
|
1088
|
+
throw new GrantedCloseTargetChanged();
|
|
1089
|
+
if (!(await writeGrantHeld(databases.flair.MemoryGrant, close.granteeId, close.ownerId, {}))) {
|
|
1090
|
+
throw new GrantedCloseRevoked();
|
|
1091
|
+
}
|
|
1092
|
+
return closed;
|
|
1093
|
+
}
|
|
1094
|
+
/**
|
|
1095
|
+
* Run a grant-authorized close (stageGrantedClose) inside the write's
|
|
1096
|
+
* transaction callback, after the successor and its pointer row are staged.
|
|
1097
|
+
* On any failure the whole write aborts: a joined request or caller
|
|
1098
|
+
* transaction is aborted here, and a transaction withSharedWriteTransaction
|
|
1099
|
+
* owns aborts when the error leaves its callback. Returns the staged closed row,
|
|
1100
|
+
* or null for an owner, admin or internal close (closeSupersededIfNeeded).
|
|
1101
|
+
*/
|
|
1102
|
+
async function closeGrantedSupersedeStaged(shared, content, close, joinsRequestTxn) {
|
|
1103
|
+
if (!close || close.granteeId === undefined)
|
|
1104
|
+
return null;
|
|
1105
|
+
try {
|
|
1106
|
+
return await stageGrantedClose(shared, close, supersedeClosePatch(content), content.visibility);
|
|
1107
|
+
}
|
|
1108
|
+
catch (err) {
|
|
1109
|
+
if (joinsRequestTxn)
|
|
1110
|
+
abortRequestTransaction(shared);
|
|
1111
|
+
throw err;
|
|
1112
|
+
}
|
|
1113
|
+
}
|
|
1114
|
+
/** The named refusal for a grant-authorized close that did not land, else null. */
|
|
1115
|
+
function grantedCloseRefusal(err) {
|
|
1116
|
+
if (err instanceof GrantedCloseStorageRefused)
|
|
1117
|
+
return withheldWriteResult();
|
|
1118
|
+
if (err instanceof PredecessorVisibilityChanged)
|
|
1119
|
+
return predecessorVisibilityChangedRefusal();
|
|
1120
|
+
if (err instanceof GrantedCloseRevoked)
|
|
1121
|
+
return grantedCloseRevokedRefusal();
|
|
1122
|
+
if (err instanceof GrantedCloseTargetChanged)
|
|
1123
|
+
return storedRowChangedRefusal("Memory");
|
|
1124
|
+
return null;
|
|
1125
|
+
}
|
|
642
1126
|
/**
|
|
643
1127
|
* ─── Durability-keyed default visibility (Layer 1, part A) ─────────────────
|
|
644
1128
|
*
|
|
@@ -684,6 +1168,344 @@ function defaultVisibilityForDurability(durability) {
|
|
|
684
1168
|
* rationale. `content.originatorInstanceId == null` is no longer read here: a
|
|
685
1169
|
* body value is not trusted at any point.
|
|
686
1170
|
*/
|
|
1171
|
+
/**
|
|
1172
|
+
* flair#2139 S2 — write a skill create/update atomically through the
|
|
1173
|
+
* transactional writer.
|
|
1174
|
+
*/
|
|
1175
|
+
async function writeSkillCreateOrUpdate(args) {
|
|
1176
|
+
const { ctx, auth, content, storedRow, explicitPredecessor, method, pointer, inPlaceId, reembedding, requestedPayload } = args;
|
|
1177
|
+
const now = new Date().toISOString();
|
|
1178
|
+
const explicitSuccessor = !!explicitPredecessor && (!storedRow || content.supersedes !== storedRow.supersedes);
|
|
1179
|
+
let successorId = inPlaceId
|
|
1180
|
+
? inPlaceId
|
|
1181
|
+
: explicitSuccessor || !storedRow
|
|
1182
|
+
? String(content.id ?? `${content.agentId}-${randomUUID()}`)
|
|
1183
|
+
: `${content.agentId}-${randomUUID()}`;
|
|
1184
|
+
const subjectId = deriveSkillSubjectId({ newPhysicalId: successorId, storedHead: storedRow, predecessor: explicitPredecessor });
|
|
1185
|
+
// flair#2139 S2 — the reservation covers the whole logical lineage: a write
|
|
1186
|
+
// whose subject is the seed's requires the operator source, not only one that
|
|
1187
|
+
// names the seed's physical id.
|
|
1188
|
+
const seedLineageDenial = reservedSeedSubjectDenial("Memory", [subjectId], ctx, auth);
|
|
1189
|
+
if (seedLineageDenial)
|
|
1190
|
+
return seedLineageDenial;
|
|
1191
|
+
const addressedId = storedRow ? String(storedRow.id) : explicitPredecessor ? String(explicitPredecessor.id) : null;
|
|
1192
|
+
const captured = { row: null, closed: null };
|
|
1193
|
+
let unchangedHead = null;
|
|
1194
|
+
const outcome = await runSkillVersionWrite({
|
|
1195
|
+
ctx,
|
|
1196
|
+
subjectId,
|
|
1197
|
+
agentId: String(content.agentId),
|
|
1198
|
+
head: (shared) => resolveSkillHead(subjectId, addressedId, shared),
|
|
1199
|
+
plan: async (head, shared) => {
|
|
1200
|
+
const stale = await validateSkillSnapshots(storedRow, explicitPredecessor, content.id ?? null, shared);
|
|
1201
|
+
const denied = await authorizeSkillOwners(ctx, auth, [storedRow, explicitPredecessor, head ?? content], shared);
|
|
1202
|
+
if (denied)
|
|
1203
|
+
return denied;
|
|
1204
|
+
if (inPlaceId && method === "put" && !reembedding && !explicitPredecessor && !pointer?.row &&
|
|
1205
|
+
head?.id === inPlaceId && requestedPayload && skillPayloadUnchanged(requestedPayload, head)) {
|
|
1206
|
+
unchangedHead = head;
|
|
1207
|
+
return null;
|
|
1208
|
+
}
|
|
1209
|
+
if (stale)
|
|
1210
|
+
return stale;
|
|
1211
|
+
if ((storedRow || explicitPredecessor) && !head)
|
|
1212
|
+
return skillWriteConflict("skill_head_missing");
|
|
1213
|
+
if (explicitSuccessor && head?.id !== explicitPredecessor?.id)
|
|
1214
|
+
return skillWriteConflict("skill_predecessor_stale");
|
|
1215
|
+
if (storedRow && head?.id !== storedRow.id)
|
|
1216
|
+
return skillWriteConflict("skill_target_stale");
|
|
1217
|
+
const reembedInPlace = method === "put" && reembedding && head &&
|
|
1218
|
+
head.id === storedRow?.id && skillPayloadUnchanged(content, head);
|
|
1219
|
+
if (reembedInPlace)
|
|
1220
|
+
successorId = String(head.id);
|
|
1221
|
+
const liveHead = head;
|
|
1222
|
+
const successor = buildSkillSuccessorRow({
|
|
1223
|
+
auth,
|
|
1224
|
+
base: { ...content, agentId: liveHead?.agentId ?? content.agentId }, predecessorRow: liveHead, successorId, subjectId,
|
|
1225
|
+
// An in-place (reserved seed) write keeps the same physical id, so it
|
|
1226
|
+
// sets no `supersedes` and closes no row.
|
|
1227
|
+
supersedes: reembedInPlace ? head.supersedes ?? null : inPlaceId || !liveHead ? null : String(liveHead.id), now,
|
|
1228
|
+
});
|
|
1229
|
+
if (reembedInPlace) {
|
|
1230
|
+
successor.instanceToken = typeof head.instanceToken === "string" && head.instanceToken.length > 0
|
|
1231
|
+
? head.instanceToken : content.instanceToken;
|
|
1232
|
+
}
|
|
1233
|
+
await applyOriginatorInstanceId(successor, liveHead);
|
|
1234
|
+
applyFederationBookkeeping(successor, liveHead);
|
|
1235
|
+
captured.row = successor;
|
|
1236
|
+
const value = typeof successor.content === "string" ? successor.content : null;
|
|
1237
|
+
const visibility = skillVersionVisibility(successor);
|
|
1238
|
+
if (inPlaceId || reembedInPlace) {
|
|
1239
|
+
return liveHead
|
|
1240
|
+
? { kind: "update", predecessor: null, successor, closePatch: {}, value, visibility, grantedClose: null }
|
|
1241
|
+
: { kind: "create", predecessor: null, successor, closePatch: {}, value, visibility, grantedClose: null };
|
|
1242
|
+
}
|
|
1243
|
+
if (!liveHead)
|
|
1244
|
+
return { kind: "create", predecessor: null, successor, closePatch: {}, value, visibility, grantedClose: null };
|
|
1245
|
+
captured.closed = liveHead;
|
|
1246
|
+
return { kind: "update", predecessor: liveHead, successor, closePatch: { skillSubjectId: subjectId, validTo: now, updatedAt: now }, value, visibility, grantedClose: grantedSkillClose(liveHead, ctx, auth) };
|
|
1247
|
+
},
|
|
1248
|
+
hooks: {
|
|
1249
|
+
...defaultSkillHooks,
|
|
1250
|
+
pointer: async (shared) => {
|
|
1251
|
+
if (captured.closed) {
|
|
1252
|
+
const denial = await deletePointerRow(String(captured.closed.id), shared);
|
|
1253
|
+
if (denial)
|
|
1254
|
+
return denial;
|
|
1255
|
+
}
|
|
1256
|
+
return pointer?.row
|
|
1257
|
+
? persistPointerRow({ ...pointer.row, memoryId: successorId, memoryInstanceToken: captured.row?.instanceToken }, shared)
|
|
1258
|
+
: null;
|
|
1259
|
+
},
|
|
1260
|
+
},
|
|
1261
|
+
});
|
|
1262
|
+
if (!outcome.ok)
|
|
1263
|
+
return outcome.response;
|
|
1264
|
+
if (captured.closed)
|
|
1265
|
+
noteMemoryDelete(String(captured.closed.id));
|
|
1266
|
+
if (captured.row) {
|
|
1267
|
+
noteMemoryUpsert(captured.row);
|
|
1268
|
+
// An in-place update replaces the live head without recording it in
|
|
1269
|
+
// `captured.closed`, so no closed row is passed as unknown (undefined),
|
|
1270
|
+
// never as "replaced no row".
|
|
1271
|
+
noteWriteStamp(captured.row.embeddingModel, captured.closed ?? undefined);
|
|
1272
|
+
}
|
|
1273
|
+
if (args.staged)
|
|
1274
|
+
args.staged.text = captured.row ? storedMemoryText(captured.row, args.staged.supplied) : null;
|
|
1275
|
+
return { id: successorId, written: captured.row !== null, visibility: skillVersionVisibility(captured.row ?? unchangedHead) };
|
|
1276
|
+
}
|
|
1277
|
+
/** Close the live head and delete its pointer in the version transaction. */
|
|
1278
|
+
async function writeSkillDelete(args) {
|
|
1279
|
+
const { ctx, auth, record } = args;
|
|
1280
|
+
let closedId = "";
|
|
1281
|
+
const now = new Date().toISOString();
|
|
1282
|
+
const subjectId = String(record.skillSubjectId ?? record.id);
|
|
1283
|
+
const seedLineageDenial = reservedSeedSubjectDenial("Memory", [subjectId], ctx, auth);
|
|
1284
|
+
if (seedLineageDenial)
|
|
1285
|
+
return seedLineageDenial;
|
|
1286
|
+
const outcome = await runSkillVersionWrite({
|
|
1287
|
+
ctx,
|
|
1288
|
+
subjectId,
|
|
1289
|
+
agentId: String(record.agentId),
|
|
1290
|
+
head: (shared) => resolveSkillHead(subjectId, String(record.id), shared),
|
|
1291
|
+
plan: async (head, shared) => {
|
|
1292
|
+
// flair#2355: for a non-admin caller, re-read the COMMITTED rows before
|
|
1293
|
+
// the close. The delete is refused, and nothing is closed, when the
|
|
1294
|
+
// addressed row is present with an owner other than the caller (409
|
|
1295
|
+
// `owner_changed`), when the head this delete closes (a stale id resolves
|
|
1296
|
+
// a different row as the head) is absent (409 `skill_head_missing`), or
|
|
1297
|
+
// when the head's owner differs from the owner this transaction read and
|
|
1298
|
+
// authorizeSkillOwners checks below (409 `owner_changed`).
|
|
1299
|
+
if (auth.kind === "agent" && !auth.isAdmin) {
|
|
1300
|
+
const pause = txnPausePoint("memory-skill-delete");
|
|
1301
|
+
if (pause)
|
|
1302
|
+
await pause;
|
|
1303
|
+
const confirmed = await databases.flair.Memory.get(String(record.id), {});
|
|
1304
|
+
if (confirmed && isForbiddenOwnerMutation(confirmed, RECORD_TYPES.Memory.ownerField, auth.agentId)) {
|
|
1305
|
+
return ownerChangedRefusal("Memory");
|
|
1306
|
+
}
|
|
1307
|
+
if (head) {
|
|
1308
|
+
const confirmedHead = await databases.flair.Memory.get(String(head.id), {});
|
|
1309
|
+
if (!confirmedHead)
|
|
1310
|
+
return skillWriteConflict("skill_head_missing");
|
|
1311
|
+
if (confirmedHead[RECORD_TYPES.Memory.ownerField] !== head[RECORD_TYPES.Memory.ownerField]) {
|
|
1312
|
+
return ownerChangedRefusal("Memory");
|
|
1313
|
+
}
|
|
1314
|
+
}
|
|
1315
|
+
}
|
|
1316
|
+
const stale = await validateSkillSnapshots(record, null, String(record.id), shared);
|
|
1317
|
+
if (stale)
|
|
1318
|
+
return stale;
|
|
1319
|
+
const denied = await authorizeSkillOwners(ctx, auth, [record, head], shared);
|
|
1320
|
+
if (denied)
|
|
1321
|
+
return denied;
|
|
1322
|
+
if (!head)
|
|
1323
|
+
return skillWriteConflict("skill_head_missing");
|
|
1324
|
+
if (memoryWriteOutcomeUnknown(String(head.id)))
|
|
1325
|
+
return writeOutcomeUnknownResponse();
|
|
1326
|
+
const liveHead = head;
|
|
1327
|
+
closedId = String(liveHead.id);
|
|
1328
|
+
// flair#2511: a stale id resolves the live head, which can be another
|
|
1329
|
+
// agent's row a "write" grant authorizes this caller to close; the writer
|
|
1330
|
+
// re-checks that grant after the close is staged.
|
|
1331
|
+
return { kind: "delete", predecessor: liveHead, closePatch: { skillSubjectId: subjectId, validTo: now, updatedAt: now }, value: null, visibility: skillVersionVisibility(liveHead), grantedClose: grantedSkillClose(liveHead, ctx, auth) };
|
|
1332
|
+
},
|
|
1333
|
+
hooks: { ...defaultSkillHooks, pointer: async (shared) => deletePointerRow(closedId, shared) },
|
|
1334
|
+
});
|
|
1335
|
+
if (!outcome.ok)
|
|
1336
|
+
return outcome.response;
|
|
1337
|
+
noteMemoryDelete(closedId);
|
|
1338
|
+
return new Response(JSON.stringify({ id: closedId, deleted: true }), {
|
|
1339
|
+
status: 200, headers: { "Content-Type": "application/json" },
|
|
1340
|
+
});
|
|
1341
|
+
}
|
|
1342
|
+
/** flair#2296: a PATCH body that sets both embedding fields to null and nothing else (an `id` aside). */
|
|
1343
|
+
function isReembedPatch(content) {
|
|
1344
|
+
if (!content || typeof content !== "object" || Array.isArray(content))
|
|
1345
|
+
return false;
|
|
1346
|
+
if (content.embedding !== null || content.embeddingModel !== null)
|
|
1347
|
+
return false;
|
|
1348
|
+
return Object.keys(content).every((key) => key === "id" || key === "embedding" || key === "embeddingModel");
|
|
1349
|
+
}
|
|
1350
|
+
/** A vector the re-embed may stamp: a non-empty array of finite numbers. */
|
|
1351
|
+
function isUsableEmbeddingVector(value) {
|
|
1352
|
+
return Array.isArray(value) && value.length > 0 &&
|
|
1353
|
+
value.every((n) => typeof n === "number" && Number.isFinite(n));
|
|
1354
|
+
}
|
|
1355
|
+
/** Attempts of a re-embed before it gives up on a row whose text keeps changing. */
|
|
1356
|
+
const REEMBED_WRITE_ATTEMPTS = 3;
|
|
1357
|
+
/** A row's incarnation token, or null when it carries none (a legacy row). */
|
|
1358
|
+
function storedInstanceToken(row) {
|
|
1359
|
+
return row && typeof row.instanceToken === "string" && row.instanceToken.length > 0 ? row.instanceToken : null;
|
|
1360
|
+
}
|
|
1361
|
+
/**
|
|
1362
|
+
* flair#2390: write the re-embed of Memory row `id`.
|
|
1363
|
+
*
|
|
1364
|
+
* `preRead` is the row as the caller first read it and `vector` the embedding
|
|
1365
|
+
* computed from its text, outside this call. This re-reads the committed row
|
|
1366
|
+
* inside the transaction that writes (the static table handle, with the
|
|
1367
|
+
* attempt's owned context), so the write is built from the row as stored at
|
|
1368
|
+
* that read, not from the pre-await read: a field another writer committed
|
|
1369
|
+
* while the vector was computed is kept, and the caller's authorization is
|
|
1370
|
+
* re-checked against the row's CURRENT owner.
|
|
1371
|
+
*
|
|
1372
|
+
* If the stored text is no longer the text the vector was computed from, this
|
|
1373
|
+
* recomputes from the stored text (at most REEMBED_WRITE_ATTEMPTS times).
|
|
1374
|
+
* If the text keeps changing across the REEMBED_WRITE_ATTEMPTS attempts, it returns
|
|
1375
|
+
* reembed_row_changed (409) and writes nothing. A row absent at the attempt's
|
|
1376
|
+
* own re-read, a row with no text, or a caller no longer authorized for the row
|
|
1377
|
+
* is refused the same way the first read refused it.
|
|
1378
|
+
*
|
|
1379
|
+
* flair#2465: the attempt STAGES the field-only incremental update, then
|
|
1380
|
+
* confirms the COMMITTED row (an explicit fresh context) is still the row this
|
|
1381
|
+
* transaction read and re-authorized — the same identity (id, agentId,
|
|
1382
|
+
* instanceToken, contentHash, createdAt) and the same embedding text, compared
|
|
1383
|
+
* as text. A row gone or changed in either at confirmation aborts the owned
|
|
1384
|
+
* transaction (the staged write is discarded) and the caller answers
|
|
1385
|
+
* stored_row_changed (409). A same-id replacement with the same identity and
|
|
1386
|
+
* text passes. Harper has no compare-and-set: a change committed after that
|
|
1387
|
+
* confirm and before the commit is not seen by it.
|
|
1388
|
+
*
|
|
1389
|
+
* The staged update also records `embeddedContentHash`, the newly computed hash
|
|
1390
|
+
* of the text the vector was computed from (null for an empty owner), so the
|
|
1391
|
+
* stored vector and its hash name the same text (flair#2465).
|
|
1392
|
+
*
|
|
1393
|
+
* flair#2478: a legacy row that carries no incarnation token gets one in the
|
|
1394
|
+
* same update, and a success reports the token of the row written, so the
|
|
1395
|
+
* calling PATCH can confirm after the commit that the row is still that one.
|
|
1396
|
+
* The calling PATCH holds the row's per-id write lock across this write and its
|
|
1397
|
+
* commit.
|
|
1398
|
+
*/
|
|
1399
|
+
async function reembedStoredRow(id, preRead, vector, auth, ctx) {
|
|
1400
|
+
let textToEmbed = skillEmbedText(preRead);
|
|
1401
|
+
let embedding = vector;
|
|
1402
|
+
for (let attempt = 1; attempt <= REEMBED_WRITE_ATTEMPTS; attempt++) {
|
|
1403
|
+
let outcome;
|
|
1404
|
+
try {
|
|
1405
|
+
outcome = await withOwnedTransaction(ctx, async (owned) => {
|
|
1406
|
+
const stored = await databases.flair.Memory.get(id, owned);
|
|
1407
|
+
if (!stored)
|
|
1408
|
+
return { kind: "not_found" };
|
|
1409
|
+
if (auth.kind === "agent" && !auth.isAdmin &&
|
|
1410
|
+
isForbiddenOwnerMutation(stored, RECORD_TYPES.Memory.ownerField, auth.agentId)) {
|
|
1411
|
+
return { kind: "forbidden" };
|
|
1412
|
+
}
|
|
1413
|
+
const storedText = skillEmbedText(stored);
|
|
1414
|
+
if (typeof storedText !== "string" || storedText.length === 0)
|
|
1415
|
+
return { kind: "no_text" };
|
|
1416
|
+
if (storedText !== textToEmbed)
|
|
1417
|
+
return { kind: "recompute", text: storedText };
|
|
1418
|
+
const model = getModelId();
|
|
1419
|
+
const updatedAt = new Date().toISOString();
|
|
1420
|
+
const token = storedInstanceToken(stored) ?? newInstanceToken();
|
|
1421
|
+
// flair#2465: an incremental update, NOT a full-row put. Harper orders a
|
|
1422
|
+
// transaction by its first read, so this write can land after an edit the
|
|
1423
|
+
// owner committed while the vector was computed; a full-row put would
|
|
1424
|
+
// carry the row this transaction read and revert that edit.
|
|
1425
|
+
// flair#2465: the update also records the newly computed hash of
|
|
1426
|
+
// `textToEmbed`, the text this vector was computed from (null for an
|
|
1427
|
+
// empty owner).
|
|
1428
|
+
// flair#2478: a legacy row that carries no incarnation token gets one in
|
|
1429
|
+
// this same update; a row that has one keeps it.
|
|
1430
|
+
const legacyToken = storedInstanceToken(stored) ? {} : { instanceToken: token };
|
|
1431
|
+
// flair#2561: a Response from the storage layer is not reported (storageResult).
|
|
1432
|
+
const result = storageResult(await databases.flair.Memory.update(id, { ...legacyToken, embedding, embeddingModel: model, updatedAt, embeddedContentHash: hashEmbeddedText(stored.agentId, textToEmbed) ?? null }, owned));
|
|
1433
|
+
if (result instanceof Response)
|
|
1434
|
+
return { kind: "withheld", response: result };
|
|
1435
|
+
// Test-only: inert unless the fault-injection env opt-in is set and armed.
|
|
1436
|
+
const stagedPause = txnPausePoint("memory-reembed-staged");
|
|
1437
|
+
if (stagedPause)
|
|
1438
|
+
await stagedPause;
|
|
1439
|
+
// flair#2465: STAGE first, THEN confirm the COMMITTED row (an explicit
|
|
1440
|
+
// fresh context — never contextless, which joins this transaction and
|
|
1441
|
+
// sees its snapshot or its staged write) is still the row this transaction
|
|
1442
|
+
// read and re-authorized: the same identity (id, agentId, instanceToken,
|
|
1443
|
+
// contentHash, createdAt) AND, compared as text, the same embedding text
|
|
1444
|
+
// the vector was computed from (`textToEmbed`). The text check catches an
|
|
1445
|
+
// edit that changed the text but no identity field. A row gone or changed
|
|
1446
|
+
// at confirmation aborts this owned transaction, discarding the staged
|
|
1447
|
+
// write; the caller answers stored_row_changed (409). Only a text change
|
|
1448
|
+
// is logged. Neither the staged vector, its hash, nor a staged legacy
|
|
1449
|
+
// token is written. A change committed after this confirm and before the
|
|
1450
|
+
// commit is not seen (no compare-and-set).
|
|
1451
|
+
await confirmCommittedRow(databases.flair.Memory, id, (committed) => {
|
|
1452
|
+
if (!sameStoredRow(committed, stored))
|
|
1453
|
+
return false;
|
|
1454
|
+
if (skillEmbedText(committed) !== textToEmbed) {
|
|
1455
|
+
console.warn(`[reembed] ${id}: the embedding text changed after the vector was computed; the write is discarded`);
|
|
1456
|
+
return false;
|
|
1457
|
+
}
|
|
1458
|
+
return true;
|
|
1459
|
+
});
|
|
1460
|
+
return { kind: "written", model, updatedAt, token };
|
|
1461
|
+
});
|
|
1462
|
+
}
|
|
1463
|
+
catch (err) {
|
|
1464
|
+
// The owned transaction was aborted by the throw; nothing was written.
|
|
1465
|
+
if (err instanceof CommittedRowChanged)
|
|
1466
|
+
return { response: storedRowChangedRefusal("Memory") };
|
|
1467
|
+
throw err;
|
|
1468
|
+
}
|
|
1469
|
+
if (outcome.kind === "withheld")
|
|
1470
|
+
return { response: outcome.response };
|
|
1471
|
+
if (outcome.kind === "not_found")
|
|
1472
|
+
return { response: NOT_FOUND() };
|
|
1473
|
+
if (outcome.kind === "forbidden")
|
|
1474
|
+
return { response: FORBIDDEN("forbidden: cannot write memory owned by another agent") };
|
|
1475
|
+
if (outcome.kind === "no_text") {
|
|
1476
|
+
return { response: Response.json({ error: "reembed_no_text", message: "the stored row has no text to embed" }, { status: 422 }) };
|
|
1477
|
+
}
|
|
1478
|
+
if (outcome.kind === "recompute") {
|
|
1479
|
+
if (attempt === REEMBED_WRITE_ATTEMPTS) {
|
|
1480
|
+
return { response: Response.json({ error: "reembed_row_changed", message: "the stored text changed during each re-embed attempt; retry" }, { status: 409 }) };
|
|
1481
|
+
}
|
|
1482
|
+
textToEmbed = outcome.text;
|
|
1483
|
+
let recomputed;
|
|
1484
|
+
try {
|
|
1485
|
+
recomputed = await embedUnderLock(textToEmbed);
|
|
1486
|
+
}
|
|
1487
|
+
catch (err) {
|
|
1488
|
+
if (err instanceof MemoryProviderTimeout)
|
|
1489
|
+
return { response: memoryProviderTimeoutResponse() };
|
|
1490
|
+
throw err;
|
|
1491
|
+
}
|
|
1492
|
+
if (!isUsableEmbeddingVector(recomputed)) {
|
|
1493
|
+
return { response: Response.json({ error: "embedding_unavailable", message: "the embedding engine returned no vector; the stored row is unchanged, retry" }, { status: 503 }) };
|
|
1494
|
+
}
|
|
1495
|
+
embedding = recomputed;
|
|
1496
|
+
continue;
|
|
1497
|
+
}
|
|
1498
|
+
noteWriteStamp(outcome.model, preRead);
|
|
1499
|
+
// flair#2561: the response names the row and its new updatedAt, and
|
|
1500
|
+
// carries no embedding field; `flair reembed` reads the model stamp from
|
|
1501
|
+
// the stored row.
|
|
1502
|
+
const body = buildFromAllowlist({ id, updatedAt: outcome.updatedAt }, REEMBED_RESPONSE_RULES);
|
|
1503
|
+
return { response: body instanceof Response ? body : Response.json(body), token: outcome.token };
|
|
1504
|
+
}
|
|
1505
|
+
return {
|
|
1506
|
+
response: new Response(JSON.stringify({ error: "reembed_row_changed", message: "the stored text changed during each re-embed attempt; retry" }), { status: 409, headers: { "content-type": "application/json" } }),
|
|
1507
|
+
};
|
|
1508
|
+
}
|
|
687
1509
|
export class Memory extends databases.flair.Memory {
|
|
688
1510
|
/**
|
|
689
1511
|
* Self-authorize now that the global gate is non-rejecting. Closes the P0
|
|
@@ -750,6 +1572,10 @@ export class Memory extends databases.flair.Memory {
|
|
|
750
1572
|
readTarget = targetId != null ? { id: targetId } : {};
|
|
751
1573
|
}
|
|
752
1574
|
const result = await memoryByIdReadGate.call(this, readTarget, (t) => super.get(t));
|
|
1575
|
+
if (nonAdminAgent && result && typeof result === "object" && !(result instanceof Response)) {
|
|
1576
|
+
if (!(await closedSkillPayloadReadable(result, auth.agentId)))
|
|
1577
|
+
return NOT_FOUND();
|
|
1578
|
+
}
|
|
753
1579
|
// flair#1940 A3 (by-ID surface): the pointer is projected for THIS reader
|
|
754
1580
|
// BEFORE the trust block is attached. Admin/internal stay unfiltered (they
|
|
755
1581
|
// read the unredacted row, like every other field); a non-admin agent is
|
|
@@ -847,6 +1673,10 @@ export class Memory extends databases.flair.Memory {
|
|
|
847
1673
|
rows = [];
|
|
848
1674
|
const projected = await projectRowsThroughPointers(batch, readerAgentId);
|
|
849
1675
|
for (const row of projected) {
|
|
1676
|
+
// flair#2139 S2 — close-payload bypass (see get()): filter a retained
|
|
1677
|
+
// closed skill payload the reader may not read. Open rows pass.
|
|
1678
|
+
if (!(await closedSkillPayloadReadable(row, readerAgentId)))
|
|
1679
|
+
continue;
|
|
850
1680
|
yield await applyHitStats(row, ctx);
|
|
851
1681
|
}
|
|
852
1682
|
};
|
|
@@ -863,6 +1693,14 @@ export class Memory extends databases.flair.Memory {
|
|
|
863
1693
|
return joined;
|
|
864
1694
|
}
|
|
865
1695
|
async post(content, context) {
|
|
1696
|
+
// flair#2141 S2: check the seed's fixed id against the operator-source
|
|
1697
|
+
// reservation (resources/seed-reservation.ts).
|
|
1698
|
+
const seedDenial = await refuseReservedSeedWrite("Memory", writeTargetIds(this, content), this.getContext?.());
|
|
1699
|
+
if (seedDenial)
|
|
1700
|
+
return seedDenial;
|
|
1701
|
+
const contentSuffixDenial = refuseContentSuffixId(writeTargetIds(this, content), context);
|
|
1702
|
+
if (contentSuffixDenial)
|
|
1703
|
+
return contentSuffixDenial;
|
|
866
1704
|
const authorityDenial = await guardAuthorityFields(() => super.get(), content, "Memory");
|
|
867
1705
|
if (authorityDenial)
|
|
868
1706
|
return authorityDenial;
|
|
@@ -906,6 +1744,44 @@ export class Memory extends databases.flair.Memory {
|
|
|
906
1744
|
if (attr.denied)
|
|
907
1745
|
return attr.denied;
|
|
908
1746
|
}
|
|
1747
|
+
const postUrlTargetId = this.getId?.();
|
|
1748
|
+
if (content && typeof content === "object" && content.id == null &&
|
|
1749
|
+
(typeof postUrlTargetId === "string" || typeof postUrlTargetId === "number")) {
|
|
1750
|
+
content.id = postUrlTargetId;
|
|
1751
|
+
}
|
|
1752
|
+
const postStored = content.id ? await databases.flair.Memory.get(content.id) : null;
|
|
1753
|
+
// flair#2561: the fields this request supplies that `stored` can report —
|
|
1754
|
+
// its string-valued text fields and, for a skill, the skill fields it
|
|
1755
|
+
// supplies (flair#2575) — read before a skill predecessor is merged into the
|
|
1756
|
+
// body; `stored` reports only these. Redaction runs after prepareSkillBody
|
|
1757
|
+
// (below) and keeps a string a string, so reading them first names the
|
|
1758
|
+
// same fields.
|
|
1759
|
+
const suppliedText = suppliedStoredTextFields(content);
|
|
1760
|
+
canonicalizeSupersedes(content);
|
|
1761
|
+
// flair#2573: an empty `embedding` in the body is an omitted one. It is
|
|
1762
|
+
// removed before the omission check and prepareSkillBody, so every later
|
|
1763
|
+
// step, a skill update's carried vector included, sees a body without it.
|
|
1764
|
+
if (isEmptyEmbedding(content?.embedding))
|
|
1765
|
+
delete content.embedding;
|
|
1766
|
+
// flair#2573 slice 2: did the CALLER supply a non-null embedding, and/or an
|
|
1767
|
+
// `embeddingModel` stamp, that differs from the stored row's? Captured before
|
|
1768
|
+
// prepareSkillBody can merge a stored row's vector into the body.
|
|
1769
|
+
const { vector: postSuppliedVector, stamp: postSuppliedStamp } = suppliedVectorFlags(content, postStored);
|
|
1770
|
+
// The visibility the caller named, before any merge or default fills it.
|
|
1771
|
+
const requestedVisibility = content?.visibility;
|
|
1772
|
+
// flair#2465: a body that omits `embedding` can have the stored row's vector
|
|
1773
|
+
// carried in by prepareSkillBody, with the hash it retained for that vector.
|
|
1774
|
+
const postOmitsEmbedding = content?.embedding === undefined;
|
|
1775
|
+
const preparedSkill = await prepareSkillBody(content, postStored, auth);
|
|
1776
|
+
if (preparedSkill instanceof Response)
|
|
1777
|
+
return preparedSkill;
|
|
1778
|
+
content = preparedSkill.content;
|
|
1779
|
+
let redactedValues = redactMemoryWrite(content).count;
|
|
1780
|
+
// Duplicate top-level metadata keys are refused; otherwise redact name/description and tags.
|
|
1781
|
+
redactedValues += redactSkillWrite(content);
|
|
1782
|
+
const postCarriedHash = postOmitsEmbedding && Array.isArray(content?.embedding) && content.embedding.length > 0
|
|
1783
|
+
? (content.embeddedContentHash ?? null)
|
|
1784
|
+
: null;
|
|
909
1785
|
// flair#744 slice A: citation-on-write — consume-and-strip, same
|
|
910
1786
|
// discipline as `claimedClient` below. Pull the optional
|
|
911
1787
|
// `usedMemoryIds` off the write body now, BEFORE anything else touches
|
|
@@ -1000,31 +1876,12 @@ export class Memory extends databases.flair.Memory {
|
|
|
1000
1876
|
if (content.visibility === undefined || content.visibility === null) {
|
|
1001
1877
|
content.visibility = defaultVisibilityForDurability(content.durability);
|
|
1002
1878
|
}
|
|
1003
|
-
// Validate derivedFrom source IDs exist (best-effort, non-blocking).
|
|
1004
|
-
// lastReflected keys off updatedAt (the write moment), NOT createdAt —
|
|
1005
|
-
// since #1336 a create may carry a backdated caller createdAt, and the
|
|
1006
|
-
// reflection bookkeeping must record when the derivation actually ran.
|
|
1007
|
-
// (Pre-#1336 the two were always identical here.)
|
|
1008
|
-
if (Array.isArray(content.derivedFrom) && content.derivedFrom.length > 0) {
|
|
1009
|
-
const now = content.updatedAt;
|
|
1010
|
-
for (const sourceId of content.derivedFrom) {
|
|
1011
|
-
try {
|
|
1012
|
-
const src = await databases.flair.Memory.get(sourceId);
|
|
1013
|
-
if (src) {
|
|
1014
|
-
const reflectPatch = { lastReflected: now };
|
|
1015
|
-
stripUndeclaredMemoryAttributes(reflectPatch);
|
|
1016
|
-
patchRecord(databases.flair.Memory, sourceId, reflectPatch).catch(() => { });
|
|
1017
|
-
}
|
|
1018
|
-
}
|
|
1019
|
-
catch { }
|
|
1020
|
-
}
|
|
1021
|
-
}
|
|
1022
1879
|
// supersedes: optional reference to the ID of the memory this one
|
|
1023
1880
|
// replaces. Validates shape + cross-agent-write authorization (shared
|
|
1024
1881
|
// with put() — see validateAndAuthorizeSupersedes doc).
|
|
1025
|
-
const
|
|
1026
|
-
if (
|
|
1027
|
-
return
|
|
1882
|
+
const supersede = await validateAndAuthorizeSupersedes(content, auth, ctx, postStored, requestedVisibility);
|
|
1883
|
+
if (supersede.denial)
|
|
1884
|
+
return supersede.denial;
|
|
1028
1885
|
// Temporal validity: validFrom defaults to now, validTo left null for active facts.
|
|
1029
1886
|
if (!content.validFrom) {
|
|
1030
1887
|
content.validFrom = content.createdAt;
|
|
@@ -1036,10 +1893,17 @@ export class Memory extends databases.flair.Memory {
|
|
|
1036
1893
|
const entitiesError = invalidEntitiesResponse(content.entities);
|
|
1037
1894
|
if (entitiesError)
|
|
1038
1895
|
return entitiesError;
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
content.
|
|
1896
|
+
// A new row cannot be its own derivedFrom source (flair#2354).
|
|
1897
|
+
if (content.id != null && Array.isArray(content.derivedFrom) &&
|
|
1898
|
+
content.derivedFrom.some((sourceId) => String(sourceId) === String(content.id))) {
|
|
1899
|
+
return Response.json({
|
|
1900
|
+
error: "derived_from_self",
|
|
1901
|
+
message: "derivedFrom may not include the id of the memory being written",
|
|
1902
|
+
}, { status: 400 });
|
|
1042
1903
|
}
|
|
1904
|
+
const expiryError = stampEphemeralExpiry(content);
|
|
1905
|
+
if (expiryError)
|
|
1906
|
+
return Response.json({ error: "invalid_expiry", message: expiryError }, { status: 400 });
|
|
1043
1907
|
// Content safety scan — covers content + summary (defense-in-depth for
|
|
1044
1908
|
// agent-set summaries).
|
|
1045
1909
|
if (content.content || content.summary) {
|
|
@@ -1075,6 +1939,20 @@ export class Memory extends databases.flair.Memory {
|
|
|
1075
1939
|
// this a duplicate of something else" situation — bypass the gate for it
|
|
1076
1940
|
// (this also gives memory_update's preserveHistory mode dedup-bypass for
|
|
1077
1941
|
// free, without a separate flag). NEVER suppresses the write either way.
|
|
1942
|
+
// Discard the non-admin caller's vector and stamp that differ from the
|
|
1943
|
+
// stored row's, after redaction, before dedup and embedding. Compute an
|
|
1944
|
+
// embedding when the resulting write needs one.
|
|
1945
|
+
if (postSuppliedVector || postSuppliedStamp) {
|
|
1946
|
+
discardSuppliedVector(content, auth, { vector: postSuppliedVector, stamp: postSuppliedStamp }, postStored);
|
|
1947
|
+
}
|
|
1948
|
+
// flair#2573: an empty vector that reaches this point (one carried from a
|
|
1949
|
+
// stored skill row; the body's own was removed above) is no vector. It is
|
|
1950
|
+
// normalized before the dedup gate and the embed step, which can then
|
|
1951
|
+
// compute and stamp one when embedding succeeds.
|
|
1952
|
+
normalizeEmptyEmbedding(content);
|
|
1953
|
+
// flair#2465: did the caller supply a vector that survived redaction? A
|
|
1954
|
+
// vector accepted from the caller gets no newly computed hash.
|
|
1955
|
+
const embeddingSupplied = Array.isArray(content.embedding) && content.embedding.length > 0;
|
|
1078
1956
|
let dedupMatch = null;
|
|
1079
1957
|
if (!content.supersedes) {
|
|
1080
1958
|
dedupMatch = await runDedupGate(ctx, content);
|
|
@@ -1107,6 +1985,16 @@ export class Memory extends databases.flair.Memory {
|
|
|
1107
1985
|
// A1-iv item 3: strip every server-stamped field a client body may not set
|
|
1108
1986
|
// (instanceToken, provenance). They are re-stamped below.
|
|
1109
1987
|
stripServerStampedFields(content);
|
|
1988
|
+
// flair#2465: a vector the server computed here gets a newly computed
|
|
1989
|
+
// hash of the text it embedded (null for an empty owner). A skill's stored
|
|
1990
|
+
// vector that prepareSkillBody carried in keeps the hash prepareSkillBody
|
|
1991
|
+
// retained with it (possibly null), so a successor of a row whose hash
|
|
1992
|
+
// differs from its text's expected hash still differs. A vector accepted
|
|
1993
|
+
// and stored from the caller gets null; the stamp migration then skips only
|
|
1994
|
+
// the hash comparison for the row.
|
|
1995
|
+
content.embeddedContentHash = !embeddingSupplied && Array.isArray(content.embedding) && content.embedding.length > 0
|
|
1996
|
+
? (embeddedTextHash(content) ?? null)
|
|
1997
|
+
: postCarriedHash;
|
|
1110
1998
|
// A1-iv item 1: a NEW row gets a server-stamped incarnation token.
|
|
1111
1999
|
content.instanceToken = newInstanceToken();
|
|
1112
2000
|
const pointer = buildPointerForWrite({ inputs: pointerInputs, memoryId: content.id ?? "", visibility: content.visibility, auth, memoryInstanceToken: content.instanceToken });
|
|
@@ -1141,6 +2029,18 @@ export class Memory extends databases.flair.Memory {
|
|
|
1141
2029
|
// Pinned by test/unit/memory-host-source.test.ts (r20-post) — RED if this
|
|
1142
2030
|
// call is removed.
|
|
1143
2031
|
stripUndeclaredMemoryAttributes(content);
|
|
2032
|
+
normalizeEmptyEmbedding(content);
|
|
2033
|
+
if (isSkillWrite(content)) {
|
|
2034
|
+
const reservedId = [content?.id, this.getId?.()].find((candidate) => isReservedSeedId("Memory", candidate));
|
|
2035
|
+
const skillStaged = { supplied: suppliedText, text: null };
|
|
2036
|
+
const skillResult = await writeSkillCreateOrUpdate({
|
|
2037
|
+
ctx, auth, content, storedRow: postStored, explicitPredecessor: preparedSkill.predecessor, method: "post", pointer,
|
|
2038
|
+
inPlaceId: reservedId != null ? String(reservedId) : null, staged: skillStaged,
|
|
2039
|
+
});
|
|
2040
|
+
if (!(skillResult instanceof Response))
|
|
2041
|
+
await markDerivedSourcesReflected(content);
|
|
2042
|
+
return skillWriteResponse(skillResult, redactedValues, skillStaged.text);
|
|
2043
|
+
}
|
|
1144
2044
|
// A1' item 2 (adjudication 0a): the Memory row and its pointer row share ONE
|
|
1145
2045
|
// transaction. With a request context they join its open transaction; with
|
|
1146
2046
|
// NO context (an internal direct call, e.g. new Memory().post(...))
|
|
@@ -1148,18 +2048,42 @@ export class Memory extends databases.flair.Memory {
|
|
|
1148
2048
|
// the Memory row back too instead of leaving it pointer-less.
|
|
1149
2049
|
// Pinned by test/unit/memory-host-source.test.ts (r20-atomic) — RED if the
|
|
1150
2050
|
// owned-transaction branch is bypassed.
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
2051
|
+
// flair#2467: the post-redaction text fields this write stages, for the response.
|
|
2052
|
+
let postStaged = {};
|
|
2053
|
+
// Read before the write: inside withSharedWriteTransaction an owned
|
|
2054
|
+
// transaction is joinable too.
|
|
2055
|
+
const postJoinsRequestTxn = isJoinableTransaction(ctx);
|
|
2056
|
+
let postResult;
|
|
2057
|
+
let postRowId;
|
|
2058
|
+
let grantedClosed = null;
|
|
2059
|
+
try {
|
|
2060
|
+
postResult = await withSharedWriteTransaction(ctx, async (c) => {
|
|
2061
|
+
postStaged = storedMemoryText(content, suppliedText);
|
|
2062
|
+
const newId = await writeMemoryRowPost(this.constructor, content, c);
|
|
2063
|
+
if (newId instanceof Response)
|
|
2064
|
+
return newId;
|
|
2065
|
+
postRowId = newId;
|
|
2066
|
+
if (pointer.row) {
|
|
2067
|
+
pointer.row.memoryId = newId;
|
|
2068
|
+
const persistDenial = await persistPointerRow(pointer.row, c);
|
|
2069
|
+
if (persistDenial)
|
|
2070
|
+
return persistDenial;
|
|
2071
|
+
}
|
|
2072
|
+
// Stage a grant-authorized close in the successor's transaction.
|
|
2073
|
+
grantedClosed = await closeGrantedSupersedeStaged(c, content, supersede.close, postJoinsRequestTxn);
|
|
2074
|
+
return null;
|
|
2075
|
+
});
|
|
2076
|
+
}
|
|
2077
|
+
catch (err) {
|
|
2078
|
+
const refusal = grantedCloseRefusal(err);
|
|
2079
|
+
if (refusal)
|
|
2080
|
+
return refusal;
|
|
2081
|
+
throw err;
|
|
2082
|
+
}
|
|
1161
2083
|
if (postResult instanceof Response)
|
|
1162
|
-
return postResult;
|
|
2084
|
+
return writeResultResponse(postResult);
|
|
2085
|
+
if (grantedClosed)
|
|
2086
|
+
noteMemoryUpsert(grantedClosed);
|
|
1163
2087
|
const result = {};
|
|
1164
2088
|
// flair#1357 — read-your-write for the lexical leg. The table change feed
|
|
1165
2089
|
// (resources/bm25-index-service.ts) is the CORRECTNESS mechanism; this
|
|
@@ -1170,14 +2094,20 @@ export class Memory extends databases.flair.Memory {
|
|
|
1170
2094
|
// a persisted FOREIGN stamp (federation / replication / an explicit-stamp
|
|
1171
2095
|
// write) trips the gate; a normal local write stamps the current id and
|
|
1172
2096
|
// never does.
|
|
1173
|
-
|
|
2097
|
+
// `postStored` is the row this write replaces; a read that found none is
|
|
2098
|
+
// passed as null (no previous row), not as unknown.
|
|
2099
|
+
noteWriteStamp(content?.embeddingModel, postStored ?? null);
|
|
1174
2100
|
// ── THEN close the superseded record ────────────────────────────────────
|
|
1175
2101
|
// Write-new-BEFORE-close-old: the previous order (close-old via a fire-
|
|
1176
2102
|
// and-forget `.catch(()=>{})` BEFORE the new write) could tombstone the
|
|
1177
2103
|
// old record and then lose the new one if the write failed afterward.
|
|
1178
2104
|
// Now the safe failure state is two active records (recoverable), never
|
|
1179
2105
|
// a lost write — and the failure is logged, never silently swallowed.
|
|
1180
|
-
|
|
2106
|
+
// A grant-authorized close was staged in the successor's transaction
|
|
2107
|
+
// (closeGrantedSupersedeStaged).
|
|
2108
|
+
if (supersede.close?.granteeId === undefined)
|
|
2109
|
+
await closeSupersededIfNeeded(ctx, content, supersede.close, "post");
|
|
2110
|
+
await markDerivedSourcesReflected(content);
|
|
1181
2111
|
// flair#744 slice A: citation-on-write — POST-COMMIT, fully
|
|
1182
2112
|
// failure-isolated. The write above already succeeded and `result` is
|
|
1183
2113
|
// final; crediting each cited memory through the shared usage ledger
|
|
@@ -1192,15 +2122,45 @@ export class Memory extends databases.flair.Memory {
|
|
|
1192
2122
|
console.error("Memory.post: citation recording failed (write already committed)", err);
|
|
1193
2123
|
}
|
|
1194
2124
|
}
|
|
1195
|
-
return buildWriteResponse(content, result, dedupMatch);
|
|
2125
|
+
return buildWriteResponse(content, result, dedupMatch, redactedValues, postStaged, postRowId);
|
|
1196
2126
|
}
|
|
1197
2127
|
// PATCH routes past put(), so agentId immutability is enforced on both verbs
|
|
1198
2128
|
// via the one shared delegate. (Admin/internal — including the _reindex
|
|
1199
2129
|
// path in put() — pass through the delegate untouched.)
|
|
2130
|
+
/** PATCH requires a target id and lock before its body runs. Ordinary and
|
|
2131
|
+
* re-embed owned writes commit before releasing the lock. */
|
|
1200
2132
|
async patch(content, query) {
|
|
1201
|
-
const
|
|
1202
|
-
if (
|
|
1203
|
-
return
|
|
2133
|
+
const ids = putLockIds(this, content);
|
|
2134
|
+
if (ids.length === 0)
|
|
2135
|
+
return memoryIdRequiredResponse();
|
|
2136
|
+
const outcome = await withMemoryWriteLock(memoryWriteLockStore(), ids, async () => {
|
|
2137
|
+
const result = await this.patchLocked(content, query);
|
|
2138
|
+
// Test-only: the verb body has returned and the lock is still held. A body
|
|
2139
|
+
// that owned its transaction has committed it; a composed or `_reindex` put
|
|
2140
|
+
// that joined another transaction has not.
|
|
2141
|
+
const committed = txnPausePoint("memory-patch-committed");
|
|
2142
|
+
if (committed)
|
|
2143
|
+
await committed;
|
|
2144
|
+
return result;
|
|
2145
|
+
}, { phase: "patch" });
|
|
2146
|
+
if (outcome.kind === "done")
|
|
2147
|
+
return outcome.value;
|
|
2148
|
+
return memoryLockRefusal(outcome, memoryLockCallerId(this));
|
|
2149
|
+
}
|
|
2150
|
+
async patchLocked(content, query) {
|
|
2151
|
+
const entry = txnPausePoint("memory-patch-entry");
|
|
2152
|
+
if (entry)
|
|
2153
|
+
await entry;
|
|
2154
|
+
// flair#2296: decided on the body as sent; the guards below add fields to it.
|
|
2155
|
+
const reembedRequest = isReembedPatch(content);
|
|
2156
|
+
// flair#2141 S2: check the seed's fixed id against the operator-source
|
|
2157
|
+
// reservation (resources/seed-reservation.ts).
|
|
2158
|
+
const seedDenial = await refuseReservedSeedWrite("Memory", writeTargetIds(this, content), this.getContext?.());
|
|
2159
|
+
if (seedDenial)
|
|
2160
|
+
return seedDenial;
|
|
2161
|
+
const contentSuffixDenial = refuseContentSuffixId(writeTargetIds(this, content), query);
|
|
2162
|
+
if (contentSuffixDenial)
|
|
2163
|
+
return contentSuffixDenial;
|
|
1204
2164
|
// flair#1383 — patch() routes past put(), so it needs its own refuse.
|
|
1205
2165
|
{
|
|
1206
2166
|
const stale = refuseStaleClientWrite(this.getContext?.()?.request, content);
|
|
@@ -1208,6 +2168,22 @@ export class Memory extends databases.flair.Memory {
|
|
|
1208
2168
|
return stale;
|
|
1209
2169
|
}
|
|
1210
2170
|
stripClientVersionPassthrough(content);
|
|
2171
|
+
// flair#2573: an empty embedding becomes `null` here, before redaction.
|
|
2172
|
+
if (content != null && typeof content === "object")
|
|
2173
|
+
normalizeEmptyEmbedding(content);
|
|
2174
|
+
// flair#2407: redact credential-shaped text on a PATCH too, before the body
|
|
2175
|
+
// is merged into the stored row.
|
|
2176
|
+
const redaction = redactMemoryWrite(content);
|
|
2177
|
+
const redactedValues = redaction.count;
|
|
2178
|
+
// flair#2573 slice 2: a non-admin write's caller-supplied vector and stamp
|
|
2179
|
+
// (one that differs from the stored row's) are discarded inside the
|
|
2180
|
+
// transaction, right after the stored read (see post()/put()). A stamp-only
|
|
2181
|
+
// body (no `embedding`) has its stamp discarded too, so a non-admin PATCH
|
|
2182
|
+
// cannot relabel a stored vector. The PATCH then behaves exactly as one that
|
|
2183
|
+
// sent neither.
|
|
2184
|
+
// flair#2561: the string-valued text fields this request supplies;
|
|
2185
|
+
// `stored` reports only these.
|
|
2186
|
+
const suppliedText = suppliedMemoryTextFields(content);
|
|
1211
2187
|
// flair#1960 r2: capture the (undeclared) authorship-claim inputs BEFORE the
|
|
1212
2188
|
// undeclared-attribute strip removes them, so a semantic PATCH re-stamps
|
|
1213
2189
|
// provenance with the SAME claims a post()/put() would record from this body
|
|
@@ -1223,105 +2199,366 @@ export class Memory extends databases.flair.Memory {
|
|
|
1223
2199
|
extractPointerInputs(content);
|
|
1224
2200
|
stripUndeclaredMemoryAttributes(content);
|
|
1225
2201
|
// 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
|
|
2202
|
+
// not set instanceToken or provenance; the stored values stand, except that
|
|
2203
|
+
// a row with no instanceToken is given one by the server below, flair#2478).
|
|
1227
2204
|
stripServerStampedFields(content);
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
//
|
|
1232
|
-
//
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
2205
|
+
// flair#2465: a body `embeddedContentHash` is dropped. A PATCH merges, so
|
|
2206
|
+
// the STORED value is retained unless the refresh path below writes a newly
|
|
2207
|
+
// computed hash of the text it embeds (null for an empty owner, or when the
|
|
2208
|
+
// engine returns no vector), or the re-embed writes one with its vector. A
|
|
2209
|
+
// PATCH that supplies its own vector retains the stored hash beside it.
|
|
2210
|
+
delete content.embeddedContentHash;
|
|
2211
|
+
// flair#2478 slice 1 — the ordinary PATCH runs in ONE owned transaction whose
|
|
2212
|
+
// FIRST operation is the authoritative stored read; the read, the decision
|
|
2213
|
+
// and the COMMIT all happen before the write lock releases. Harper orders a
|
|
2214
|
+
// transaction by its first read, so the read and every decision drawn from
|
|
2215
|
+
// it share this commit. (A re-embed PATCH writes in its own inner owned
|
|
2216
|
+
// transaction instead, which also commits before the lock releases.)
|
|
2217
|
+
const ctx = this.getContext?.();
|
|
2218
|
+
// flair#2467: the post-redaction text fields this PATCH stages, for the response.
|
|
2219
|
+
let patchStaged = {};
|
|
2220
|
+
const patched = await withOwnedTransaction(ctx, async (c) => {
|
|
2221
|
+
// The FIRST operation inside the owned transaction: the authoritative
|
|
2222
|
+
// stored read, by the URL-BOUND target id (a body id that disagrees with
|
|
2223
|
+
// the address, or a lookup that FAILS, is refused; a failed read is never
|
|
2224
|
+
// read as "no stored row").
|
|
2225
|
+
const resolvedStored = await resolveStoredRow(this, "Memory", content, () => super.get(), c);
|
|
2226
|
+
if (resolvedStored.denial)
|
|
2227
|
+
return resolvedStored.denial;
|
|
2228
|
+
const existingForSkill = resolvedStored.row;
|
|
2229
|
+
if (!reembedRequest) {
|
|
2230
|
+
const { vector, stamp } = suppliedVectorFlags(content, existingForSkill);
|
|
2231
|
+
if (vector || stamp) {
|
|
2232
|
+
discardSuppliedVector(content, await resolveAgentAuth(ctx), { vector, stamp }, existingForSkill);
|
|
2233
|
+
}
|
|
1240
2234
|
}
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
2235
|
+
// Authorize inside the transaction: the authority then owner guards read
|
|
2236
|
+
// the stored row from this transaction's own snapshot.
|
|
2237
|
+
const authorityDenial = await guardAuthorityFields(() => super.get(), content, "Memory");
|
|
2238
|
+
if (authorityDenial)
|
|
2239
|
+
return authorityDenial;
|
|
2240
|
+
const denial = await guardOwnerFieldImmutable(this, () => super.get(), content, "agentId");
|
|
2241
|
+
if (denial)
|
|
2242
|
+
return denial;
|
|
2243
|
+
// Preserve stored visibility on updates before applying write policy: a
|
|
2244
|
+
// null is no change (PATCH merges), and a present value goes through the
|
|
2245
|
+
// same validator and ephemeral-tier guard as put().
|
|
2246
|
+
if (content && "visibility" in content && content.visibility == null)
|
|
2247
|
+
delete content.visibility;
|
|
2248
|
+
if (content && (content.visibility !== undefined || content.durability !== undefined)) {
|
|
2249
|
+
const durabilityError = assertValidDurability(content.durability);
|
|
2250
|
+
if (durabilityError) {
|
|
2251
|
+
return new Response(JSON.stringify({ error: "invalid_durability", message: durabilityError }), { status: 400, headers: { "content-type": "application/json" } });
|
|
2252
|
+
}
|
|
2253
|
+
const visibilityError = assertValidVisibility(content.visibility);
|
|
2254
|
+
if (visibilityError) {
|
|
2255
|
+
return new Response(JSON.stringify({ error: "invalid_visibility", message: visibilityError }), { status: 400, headers: { "content-type": "application/json" } });
|
|
2256
|
+
}
|
|
2257
|
+
// The stored row the tier guard compares against: the row this
|
|
2258
|
+
// transaction's first read resolved. When the resolver found no
|
|
2259
|
+
// URL-bound id to read by (an in-process harness), fall back to the
|
|
2260
|
+
// resource's own bound-record read so an update still consults the
|
|
2261
|
+
// stored visibility.
|
|
2262
|
+
const stored = existingForSkill ?? (await super.get());
|
|
2263
|
+
const tierError = assertVisibilityAllowedForDurability(content.durability ?? stored?.durability, content.visibility ?? stored?.visibility);
|
|
2264
|
+
if (tierError) {
|
|
2265
|
+
return new Response(JSON.stringify({ error: "invalid_visibility_for_durability", message: tierError }), { status: 400, headers: { "content-type": "application/json" } });
|
|
2266
|
+
}
|
|
1244
2267
|
}
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
2268
|
+
// ── flair#1542 + residual (Kern #1543 review 5135715289): reject skill patches ──
|
|
2269
|
+
// patch() routes past put() (and thus past the SkillScan gate + forced
|
|
2270
|
+
// durability), so a skill write on this verb would land unscanned. There are
|
|
2271
|
+
// TWO ways a patch is a skill write, and the mint-time check saw only the first:
|
|
2272
|
+
// 1. the PATCH BODY carries the skill tag — rejectSkillWritePath(content).
|
|
2273
|
+
// 2. the STORED record is ALREADY a skill, and the body mutates `content`
|
|
2274
|
+
// (or anything else) WITHOUT re-declaring the tag. isSkillWrite(body) is
|
|
2275
|
+
// then false, so the pre-residual check let the edit land — a skill's
|
|
2276
|
+
// procedure could be rewritten with NO SkillScan (the residual). Fold
|
|
2277
|
+
// the existing record into the check: a patch to a row whose STORED tags
|
|
2278
|
+
// include `skill` is rejected the same as a mint-time skill write.
|
|
2279
|
+
// Skills are written via skill_store (→ Memory.post) or Memory.put; no
|
|
2280
|
+
// memory_patch tool exists and no internal path patches a skill row (hit-
|
|
2281
|
+
// tracking goes through table.put, not this override), so rejecting is safe.
|
|
2282
|
+
// flair#1965 r3 + flair#1960 r3: `existingForSkill` is the row resolved by
|
|
2283
|
+
// this transaction's FIRST read (the authoritative stored read above), by the
|
|
2284
|
+
// URL-BOUND target id. This ONE resolved row drives the skill-row check, the
|
|
2285
|
+
// semantic-PATCH provenance decision below, AND the originatorInstanceId
|
|
2286
|
+
// create/update rule.
|
|
2287
|
+
// flair#2296: re-embed intentionally changes only embedding, embeddingModel
|
|
2288
|
+
// and updatedAt, plus the embedded-text hash (flair#2465) (flair#2478: and
|
|
2289
|
+
// gives a legacy row with no instanceToken one).
|
|
2290
|
+
// flair#2390: the vector is computed OUTSIDE the write. The write itself
|
|
2291
|
+
// re-reads the committed row inside its own transaction (reembedStoredRow),
|
|
2292
|
+
// re-checks the owner and the text, stages ONLY those fields (flair#2465;
|
|
2293
|
+
// plus instanceToken for a legacy row that has none, flair#2478), then
|
|
2294
|
+
// confirms the committed row has the identity and embedding text it read
|
|
2295
|
+
// (flair#2465). A row gone or changed in either at confirmation aborts with
|
|
2296
|
+
// 409 stored_row_changed. The vector is computed for the re-read text; a
|
|
2297
|
+
// change committed after confirmation and before commit is not seen by that
|
|
2298
|
+
// confirmation. After a normal storage result and inner commit, PATCH
|
|
2299
|
+
// compares the token; a storage Response returns before that read.
|
|
2300
|
+
if (reembedRequest) {
|
|
2301
|
+
if (!existingForSkill)
|
|
2302
|
+
return NOT_FOUND();
|
|
2303
|
+
const auth = await resolveAgentAuth(this.getContext?.());
|
|
2304
|
+
if (auth.kind === "agent" && !auth.isAdmin &&
|
|
2305
|
+
isForbiddenOwnerMutation(existingForSkill, RECORD_TYPES.Memory.ownerField, auth.agentId)) {
|
|
2306
|
+
return FORBIDDEN("forbidden: cannot write memory owned by another agent");
|
|
2307
|
+
}
|
|
2308
|
+
const embedText = skillEmbedText(existingForSkill);
|
|
2309
|
+
if (typeof embedText !== "string" || embedText.length === 0) {
|
|
2310
|
+
return Response.json({ error: "reembed_no_text", message: "the stored row has no text to embed" }, { status: 422 });
|
|
2311
|
+
}
|
|
2312
|
+
// Test-only: inert unless the fault-injection env opt-in is set and armed.
|
|
2313
|
+
const pause = txnPausePoint("memory-reembed");
|
|
2314
|
+
if (pause)
|
|
2315
|
+
await pause;
|
|
2316
|
+
let embedding;
|
|
2317
|
+
try {
|
|
2318
|
+
embedding = await embedUnderLock(embedText);
|
|
2319
|
+
}
|
|
2320
|
+
catch (err) {
|
|
2321
|
+
if (err instanceof MemoryProviderTimeout)
|
|
2322
|
+
return memoryProviderTimeoutResponse();
|
|
2323
|
+
throw err;
|
|
2324
|
+
}
|
|
2325
|
+
if (!isUsableEmbeddingVector(embedding)) {
|
|
2326
|
+
return Response.json({ error: "embedding_unavailable", message: "the embedding engine returned no vector; the stored row is unchanged, retry" }, { status: 503 });
|
|
2327
|
+
}
|
|
2328
|
+
// The re-embed writes and commits in its own owned transaction. A refusal
|
|
2329
|
+
// is answered as is; a success is answered only after the post-commit
|
|
2330
|
+
// identity check below (flair#2478).
|
|
2331
|
+
const reembedded = await reembedStoredRow(String(existingForSkill.id), existingForSkill, embedding, auth, this.getContext?.());
|
|
2332
|
+
if (reembedded.token === undefined)
|
|
2333
|
+
return reembedded.response;
|
|
2334
|
+
return { reembed: reembedded.response, identity: { expectedToken: reembedded.token } };
|
|
1249
2335
|
}
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1273
|
-
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
2336
|
+
const skillDenial = rejectSkillWritePath(content) ?? rejectSkillWritePath(existingForSkill);
|
|
2337
|
+
if (skillDenial)
|
|
2338
|
+
return skillDenial;
|
|
2339
|
+
// ── flair#1960 r2: a SEMANTIC patch re-stamps provenance ────────────────
|
|
2340
|
+
// patch() strips a caller-supplied `provenance` (above) so a body can never
|
|
2341
|
+
// SET a `verified.*` field, but stripping alone would leave the STORED blob
|
|
2342
|
+
// in place — including a legacy row whose `verified.timestamp` came from a
|
|
2343
|
+
// client `createdAt` before this release. A patch that changes the record's
|
|
2344
|
+
// content is a fresh authored write, so it re-stamps from the resolved auth
|
|
2345
|
+
// and ONE server clock read (never the caller's `createdAt`, never a carried-
|
|
2346
|
+
// forward stored value). A metadata-only patch (no semantic field changes)
|
|
2347
|
+
// keeps the stored, previously-stamped blob: no new content was authored, so
|
|
2348
|
+
// there is no new write to attribute. See resources/provenance.ts
|
|
2349
|
+
// (isSemanticPatch / MEMORY_SEMANTIC_FIELDS) for the field set.
|
|
2350
|
+
if (isSemanticPatch(content, existingForSkill, MEMORY_SEMANTIC_FIELDS)) {
|
|
2351
|
+
const ctx = this.getContext?.();
|
|
2352
|
+
const auth = await resolveAgentAuth(ctx);
|
|
2353
|
+
content.provenance = buildProvenance(auth, content.createdAt ?? existingForSkill?.createdAt, claimInputs);
|
|
2354
|
+
}
|
|
2355
|
+
// flair#1965 r2: a PATCH over an EXISTING row keeps the stored
|
|
2356
|
+
// originatorInstanceId (a body value is dropped); a PATCH whose URL target
|
|
2357
|
+
// has NO stored row is a CREATE when it reaches the table — Harper's patch
|
|
2358
|
+
// path has no existing-row requirement — so it must stamp the local id
|
|
2359
|
+
// rather than leave the new row un-stamped. Only an administrator's or a
|
|
2360
|
+
// trusted internal PATCH gets that far; the table guard
|
|
2361
|
+
// (resources/table-patch-policy.ts) refuses the rest. See
|
|
2362
|
+
// resources/originator-instance.ts.
|
|
2363
|
+
await applyOriginatorInstanceId(content, existingForSkill);
|
|
2364
|
+
// The receiver-side federation bookkeeping keeps its stored value (a patch
|
|
2365
|
+
// merges); a client body value is dropped.
|
|
2366
|
+
dropClientFederationBookkeeping(content);
|
|
2367
|
+
const expiryError = stampEphemeralExpiry(content, existingForSkill);
|
|
2368
|
+
if (expiryError)
|
|
2369
|
+
return Response.json({ error: "invalid_expiry", message: expiryError }, { status: 400 });
|
|
2370
|
+
// flair#2466: this non-re-embed branch refreshes the embedding when the
|
|
2371
|
+
// body's `content` changes the compared row's text and `embedding` is absent
|
|
2372
|
+
// after redaction. Skill writes are refused above. A surviving
|
|
2373
|
+
// supplied vector is stored as supplied, without text/vector validation.
|
|
2374
|
+
// Without a refresh, the stored vector survives only if the body omits
|
|
2375
|
+
// `embedding` after redaction; an explicit `embedding: null` that survives
|
|
2376
|
+
// redaction clears it. Redaction that changes `content` or `trigger` removes
|
|
2377
|
+
// both embedding fields when either is non-null, so such a null does not survive.
|
|
2378
|
+
//
|
|
2379
|
+
// The vector is computed the way put() embeds a write that carries no vector
|
|
2380
|
+
// (same engine, `getEmbedding(..., "document")`; same stamps, embeddingModel
|
|
2381
|
+
// and updatedAt). When the engine returns no vector, embedding and
|
|
2382
|
+
// embeddingModel are written as null: the row keeps no vector for text it no
|
|
2383
|
+
// longer holds, and the embedding-stamp re-embed selects a null stamp.
|
|
2384
|
+
//
|
|
2385
|
+
// A fresh committed-row read runs only when the initial comparison selected
|
|
2386
|
+
// no embedding, a stored row exists, and the body omits `embedding` and carries the
|
|
2387
|
+
// embedding-text field. If that comparison finds changed text, refresh from
|
|
2388
|
+
// the body's text. Other paths write without this confirmation. Harper has
|
|
2389
|
+
// no compare-and-set: changes after the fresh read are not seen by it.
|
|
2390
|
+
//
|
|
2391
|
+
// A PATCH whose URL target has no stored row (a create, admin or internal
|
|
2392
|
+
// only) refreshes only when redaction removed a supplied embedding field
|
|
2393
|
+
// and the body carries `content`.
|
|
2394
|
+
const body = content != null && typeof content === "object" ? content : {};
|
|
2395
|
+
/** The field to embed this body's text from, if writing it over `stored` needs a vector; else null. */
|
|
2396
|
+
const vectorFieldOver = (stored) => {
|
|
2397
|
+
const field = embedTextField({ ...(stored ?? {}), ...body });
|
|
2398
|
+
if (!Object.prototype.hasOwnProperty.call(body, field) || Object.prototype.hasOwnProperty.call(body, "embedding"))
|
|
2399
|
+
return null;
|
|
2400
|
+
if (stored == null)
|
|
2401
|
+
return redaction.embeddingDiscarded ? field : null;
|
|
2402
|
+
return skillEmbedText({ ...stored, ...body }) !== skillEmbedText(stored) ? field : null;
|
|
2403
|
+
};
|
|
2404
|
+
const storeVectorFor = async (field) => {
|
|
2405
|
+
const embedText = body[field];
|
|
2406
|
+
let vec = null;
|
|
2407
|
+
if (typeof embedText === "string" && embedText.length > 0) {
|
|
2408
|
+
try {
|
|
2409
|
+
vec = await embedUnderLock(embedText);
|
|
2410
|
+
}
|
|
2411
|
+
catch (err) {
|
|
2412
|
+
if (err instanceof MemoryProviderTimeout)
|
|
2413
|
+
return memoryProviderTimeoutResponse();
|
|
2414
|
+
throw err;
|
|
2415
|
+
}
|
|
2416
|
+
}
|
|
2417
|
+
const computed = Array.isArray(vec) && vec.length > 0;
|
|
2418
|
+
body.embedding = computed ? vec : null;
|
|
2419
|
+
body.embeddingModel = computed ? getModelId() : null;
|
|
2420
|
+
// flair#2465: the refreshed vector gets a newly computed hash of the text
|
|
2421
|
+
// it embedded (null for an empty owner).
|
|
2422
|
+
body.embeddedContentHash = computed ? (embeddedTextHash({ ...(existingForSkill ?? {}), ...body }) ?? null) : null;
|
|
2423
|
+
body.updatedAt = new Date().toISOString();
|
|
2424
|
+
return null;
|
|
2425
|
+
};
|
|
2426
|
+
const readField = vectorFieldOver(existingForSkill);
|
|
2427
|
+
if (readField) {
|
|
2428
|
+
const denied = await storeVectorFor(readField);
|
|
2429
|
+
if (denied)
|
|
2430
|
+
return denied;
|
|
2431
|
+
}
|
|
2432
|
+
// Test-only: inert unless the fault-injection env opt-in is set and armed.
|
|
2433
|
+
// Holds the PATCH after its stored-row read and any embed, before the
|
|
2434
|
+
// conditional committed-row read and the write.
|
|
2435
|
+
const beforePatchWrite = txnPausePoint("memory-patch");
|
|
2436
|
+
if (beforePatchWrite)
|
|
2437
|
+
await beforePatchWrite;
|
|
2438
|
+
if (!readField && existingForSkill != null && !Object.prototype.hasOwnProperty.call(body, "embedding") &&
|
|
2439
|
+
Object.prototype.hasOwnProperty.call(body, embedTextField({ ...existingForSkill, ...body }))) {
|
|
2440
|
+
const committed = await databases.flair.Memory.get(String(existingForSkill.id), {});
|
|
2441
|
+
const committedField = committed ? vectorFieldOver(committed) : null;
|
|
2442
|
+
if (committedField) {
|
|
2443
|
+
const denied = await storeVectorFor(committedField);
|
|
2444
|
+
if (denied)
|
|
2445
|
+
return denied;
|
|
2446
|
+
}
|
|
2447
|
+
}
|
|
2448
|
+
// flair#2467: a PATCH commits only the fields in its body; these are the
|
|
2449
|
+
// post-redaction text fields among them, for the response.
|
|
2450
|
+
patchStaged = storedMemoryText(content, suppliedText);
|
|
2451
|
+
// flair#2478: a stored row that has a token keeps it (the
|
|
2452
|
+
// body's own was stripped above); a legacy row without one, or a row this
|
|
2453
|
+
// PATCH creates (an admin or internal caller only), is given a fresh one
|
|
2454
|
+
// in this same write.
|
|
2455
|
+
const keptToken = storedInstanceToken(existingForSkill);
|
|
2456
|
+
if (keptToken === null)
|
|
2457
|
+
content.instanceToken = newInstanceToken();
|
|
2458
|
+
const expectedToken = keptToken ?? content.instanceToken;
|
|
2459
|
+
// flair#2573: the guard is notified after the commit (below) when the
|
|
2460
|
+
// staged vector or stamp differs from the row read in this transaction.
|
|
2461
|
+
const embeddingChanged = Object.prototype.hasOwnProperty.call(body, "embedding") &&
|
|
2462
|
+
!isDeepStrictEqual(body.embedding, existingForSkill?.embedding);
|
|
2463
|
+
const stampChanged = Object.prototype.hasOwnProperty.call(body, "embeddingModel") &&
|
|
2464
|
+
!isDeepStrictEqual(body.embeddingModel, existingForSkill?.embeddingModel);
|
|
2465
|
+
const stampNote = embeddingChanged || stampChanged
|
|
2466
|
+
? {
|
|
2467
|
+
stamp: (Object.prototype.hasOwnProperty.call(body, "embeddingModel")
|
|
2468
|
+
? body.embeddingModel : existingForSkill?.embeddingModel),
|
|
2469
|
+
previous: existingForSkill ?? null,
|
|
2470
|
+
}
|
|
2471
|
+
: null;
|
|
2472
|
+
// flair#2478 slice 1: the ordinary PATCH runs in the transaction this call
|
|
2473
|
+
// already owns (opened in patchLocked); super.patch joins it, so the row
|
|
2474
|
+
// write commits when this callback returns, before the write lock releases.
|
|
2475
|
+
// flair#2561: a Response from the storage layer is not reported
|
|
2476
|
+
// (storageResult); it is returned from this transaction as the
|
|
2477
|
+
// write_response_withheld refusal.
|
|
2478
|
+
const result = storageResult(await super.patch(content, query));
|
|
2479
|
+
if (result instanceof Response)
|
|
2480
|
+
return result;
|
|
2481
|
+
return { result, identity: { expectedToken }, rowId: existingForSkill?.id, stampNote };
|
|
2482
|
+
});
|
|
2483
|
+
// flair#2561: a refusal this path built is returned as built; a
|
|
2484
|
+
// successful Response is replaced by the write_response_withheld refusal
|
|
2485
|
+
// (writeResultResponse).
|
|
2486
|
+
if (patched instanceof Response)
|
|
2487
|
+
return writeResultResponse(patched);
|
|
2488
|
+
// flair#2573: the row write has committed (its transaction returned it), so
|
|
2489
|
+
// the embedding-space guard is notified now, before the verification read:
|
|
2490
|
+
// a refused or unknown verification still leaves the guard told about the
|
|
2491
|
+
// vector or stamp this PATCH stored. The re-embed notifies in
|
|
2492
|
+
// reembedStoredRow and stages no note here.
|
|
2493
|
+
const stampNote = patched.stampNote;
|
|
2494
|
+
if (stampNote)
|
|
2495
|
+
noteWriteStamp(stampNote.stamp, stampNote.previous);
|
|
2496
|
+
// Verify the ordinary owned PATCH after a normal storage result; refusals
|
|
2497
|
+
// and storage Responses return above before this read. A successful re-embed is also
|
|
2498
|
+
// checked after its inner owned commit; refusals return above.
|
|
2499
|
+
// Compare the token and declared agentId/content/visibility/durability;
|
|
2500
|
+
// other field changes pass. A failed read is an unknown outcome (503).
|
|
2501
|
+
// Test-only: holds the PATCH after its commit, before the verification read.
|
|
2502
|
+
const verifyPause = txnPausePoint("memory-patch-verify");
|
|
2503
|
+
if (verifyPause)
|
|
2504
|
+
await verifyPause;
|
|
2505
|
+
const verified = await verifyCommittedWrite(databases.flair.Memory, content, this.getId?.(), patched.identity);
|
|
2506
|
+
if (verified.unknown)
|
|
2507
|
+
return writeOutcomeUnknownFor(content?.id ?? this.getId?.());
|
|
2508
|
+
if (verified.mismatch)
|
|
2509
|
+
return storedRowChangedRefusal("Memory");
|
|
2510
|
+
// A verified re-embed answers with its own response (it declares no text
|
|
2511
|
+
// fields, so its check is the row's identity).
|
|
2512
|
+
if (patched.reembed)
|
|
2513
|
+
return patched.reembed;
|
|
2514
|
+
// As in put(): the verified row gates the answer; the response is the
|
|
2515
|
+
// PATCH's own result, never the stored row (see put()).
|
|
2516
|
+
return rowWriteResponse(patched.result, content?.id ?? this.getId?.() ?? patched.rowId, redactedValues, patchStaged);
|
|
1313
2517
|
}
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
2518
|
+
/**
|
|
2519
|
+
* flair#2478 slice 1 — the owner PUT runs under the per-id memory write lock
|
|
2520
|
+
* and its ordinary row write owns its transaction, so the read, the decision
|
|
2521
|
+
* and the COMMIT all happen before the lock releases (the protocol's rule).
|
|
2522
|
+
* Two puts can join a transaction they do not own, which then commits after
|
|
2523
|
+
* the lock releases: one composed into its caller's transaction (manual
|
|
2524
|
+
* promotion; see putLocked), and the admin `_reindex` re-PUT when the request
|
|
2525
|
+
* carries an open transaction. A PUT
|
|
2526
|
+
* that names no id is refused 400 before the lock; a store with no lock is
|
|
2527
|
+
* refused 503 `memory_lock_unavailable`. See resources/memory-write-lock.ts.
|
|
2528
|
+
*/
|
|
2529
|
+
async put(content, query) {
|
|
2530
|
+
const ids = putLockIds(this, content);
|
|
2531
|
+
if (ids.length === 0)
|
|
2532
|
+
return memoryIdRequiredResponse();
|
|
2533
|
+
const outcome = await withMemoryWriteLock(memoryWriteLockStore(), ids, async () => {
|
|
2534
|
+
const result = await this.putLocked(content, query);
|
|
2535
|
+
// Test-only: the verb body has returned and the lock is still held. A body
|
|
2536
|
+
// that owned its transaction has committed it; a composed or `_reindex` put
|
|
2537
|
+
// that joined another transaction has not.
|
|
2538
|
+
const committed = txnPausePoint("memory-put-committed");
|
|
2539
|
+
if (committed)
|
|
2540
|
+
await committed;
|
|
2541
|
+
return result;
|
|
2542
|
+
}, { phase: "put" });
|
|
2543
|
+
if (outcome.kind === "done")
|
|
2544
|
+
return outcome.value;
|
|
2545
|
+
return memoryLockRefusal(outcome, memoryLockCallerId(this));
|
|
2546
|
+
}
|
|
2547
|
+
async putLocked(content, query) {
|
|
2548
|
+
const reembedding = content?.embedding === null && content?.embeddingModel === null;
|
|
2549
|
+
// flair#2141 S2: check the seed's fixed id against the operator-source
|
|
2550
|
+
// reservation (resources/seed-reservation.ts).
|
|
2551
|
+
const seedDenial = await refuseReservedSeedWrite("Memory", writeTargetIds(this, content), this.getContext?.());
|
|
2552
|
+
if (seedDenial)
|
|
2553
|
+
return seedDenial;
|
|
2554
|
+
const contentSuffixDenial = refuseContentSuffixId(writeTargetIds(this, content), query);
|
|
2555
|
+
if (contentSuffixDenial)
|
|
2556
|
+
return contentSuffixDenial;
|
|
2557
|
+
// Reindex bypass: an admin-only escape hatch that re-PUTs declared and named
|
|
2558
|
+
// retained fields (no updatedAt bump, no embedding regen, no safety rescan)
|
|
2559
|
+
// so Harper repopulates secondary indices. The row is built by
|
|
2560
|
+
// buildReindexRow, the path this branch shares with the MemoryReindex admin
|
|
2561
|
+
// endpoint's write-back. Other undeclared fields are stripped and
|
|
1325
2562
|
// an absent incarnation token is generated. Because this skips safety and
|
|
1326
2563
|
// auditability, it must be gated to admins. Internal calls (no auth
|
|
1327
2564
|
// context) pass through, matching the pattern used in delete().
|
|
@@ -1335,15 +2572,16 @@ export class Memory extends databases.flair.Memory {
|
|
|
1335
2572
|
headers: { "Content-Type": "application/json" },
|
|
1336
2573
|
});
|
|
1337
2574
|
}
|
|
1338
|
-
|
|
1339
|
-
//
|
|
1340
|
-
//
|
|
1341
|
-
//
|
|
1342
|
-
|
|
1343
|
-
//
|
|
1344
|
-
//
|
|
1345
|
-
|
|
1346
|
-
|
|
2575
|
+
// An UNRESOLVED caller (anonymous HTTP, or an identity that did not
|
|
2576
|
+
// resolve) may not reindex: it answers the same 401 an unresolved caller
|
|
2577
|
+
// gets on the ordinary write path (resources/owner-field-guard.ts). This
|
|
2578
|
+
// guard ran before the reindex branch on main; the read-first restructure
|
|
2579
|
+
// moved it inside the owned ordinary transaction, which the reindex branch
|
|
2580
|
+
// returns before, so re-assert it here. Internal callers (no auth context)
|
|
2581
|
+
// pass, as on the ordinary path.
|
|
2582
|
+
const reindexOwnerDenial = await guardOwnerFieldImmutable(this, () => super.get(), content, "agentId");
|
|
2583
|
+
if (reindexOwnerDenial)
|
|
2584
|
+
return reindexOwnerDenial;
|
|
1347
2585
|
// flair#1965 r3: resolve the stored row by the URL-BOUND target id (never a
|
|
1348
2586
|
// body id alone); a body id that disagrees with the address, or a lookup
|
|
1349
2587
|
// that FAILS, refuses the reindex. A reindex is a re-PUT of an EXISTING
|
|
@@ -1354,385 +2592,603 @@ export class Memory extends databases.flair.Memory {
|
|
|
1354
2592
|
if (resolvedReindex.denial)
|
|
1355
2593
|
return resolvedReindex.denial;
|
|
1356
2594
|
const reindexExisting = resolvedReindex.row;
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
message: "the _reindex re-PUT requires an existing stored row",
|
|
1361
|
-
}), { status: 404, headers: { "content-type": "application/json" } });
|
|
2595
|
+
const built = buildReindexRow(content, reindexExisting);
|
|
2596
|
+
if (!("row" in built)) {
|
|
2597
|
+
return new Response(JSON.stringify({ error: built.error, message: built.message }), { status: built.status, headers: { "content-type": "application/json" } });
|
|
1362
2598
|
}
|
|
1363
|
-
|
|
1364
|
-
//
|
|
1365
|
-
// the
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
// if this restore is removed.
|
|
1371
|
-
if (reindexExisting && typeof reindexExisting.provenance === "string") {
|
|
1372
|
-
content.provenance = reindexExisting.provenance;
|
|
2599
|
+
const reindexRow = built.row;
|
|
2600
|
+
// The URL-bound target id is the row this re-PUT lands on; stamp it when
|
|
2601
|
+
// the body omits it (the same carry the ordinary put path performs).
|
|
2602
|
+
const reindexTargetId = this.getId?.();
|
|
2603
|
+
if (reindexRow && typeof reindexRow === "object" && reindexRow.id == null &&
|
|
2604
|
+
(typeof reindexTargetId === "string" || typeof reindexTargetId === "number")) {
|
|
2605
|
+
reindexRow.id = reindexTargetId;
|
|
1373
2606
|
}
|
|
1374
|
-
// flair#
|
|
1375
|
-
//
|
|
1376
|
-
//
|
|
1377
|
-
//
|
|
1378
|
-
|
|
1379
|
-
//
|
|
1380
|
-
|
|
1381
|
-
//
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
2607
|
+
// flair#2450: the re-PUT writes over the row read as `reindexExisting`.
|
|
2608
|
+
// Inside the write's transaction, confirm the COMMITTED row is still that
|
|
2609
|
+
// one — before the row is staged, and again before the commit
|
|
2610
|
+
// (confirmCommittedRow: the transaction is aborted and the staged row
|
|
2611
|
+
// discarded). A missing row or an identity change seen by either read is
|
|
2612
|
+
// refused with the named 409 stored_row_changed; a change committed after
|
|
2613
|
+
// the final confirm read is not seen. Both reads use an explicit
|
|
2614
|
+
// fresh context, never a contextless one (see resources/write-back.ts).
|
|
2615
|
+
const reindexJoinsRequestTxn = isJoinableTransaction(ctx);
|
|
2616
|
+
const beforeReindex = txnPausePoint("memory-reindex-pre");
|
|
2617
|
+
if (beforeReindex)
|
|
2618
|
+
await beforeReindex;
|
|
2619
|
+
let reindexed;
|
|
2620
|
+
try {
|
|
2621
|
+
reindexed = await withSharedWriteTransaction(ctx, async (c) => {
|
|
2622
|
+
const confirmPause = txnPausePoint("memory-reindex");
|
|
2623
|
+
if (confirmPause)
|
|
2624
|
+
await confirmPause;
|
|
2625
|
+
const confirmed = await databases.flair.Memory.get(reindexExisting.id, {});
|
|
2626
|
+
if (!confirmed || !sameStoredRow(confirmed, reindexExisting))
|
|
2627
|
+
return storedRowChangedRefusal("Memory");
|
|
2628
|
+
const r = storageResult(await databases.flair.Memory.put(reindexRow, c));
|
|
2629
|
+
if (r instanceof Response)
|
|
2630
|
+
return r;
|
|
2631
|
+
// Test-only: holds the staged re-PUT before its commit, so a delete, a
|
|
2632
|
+
// purge or a same-id replace can commit in that window.
|
|
2633
|
+
const stagedPause = txnPausePoint("memory-reindex-staged");
|
|
2634
|
+
if (stagedPause)
|
|
2635
|
+
await stagedPause;
|
|
2636
|
+
try {
|
|
2637
|
+
await confirmCommittedRow(databases.flair.Memory, reindexExisting.id, (committed) => sameStoredRow(committed, reindexExisting));
|
|
2638
|
+
}
|
|
2639
|
+
catch (err) {
|
|
2640
|
+
if (err instanceof CommittedRowChanged && reindexJoinsRequestTxn)
|
|
2641
|
+
abortRequestTransaction(c);
|
|
2642
|
+
throw err;
|
|
2643
|
+
}
|
|
2644
|
+
return r;
|
|
2645
|
+
});
|
|
1388
2646
|
}
|
|
1389
|
-
|
|
2647
|
+
catch (err) {
|
|
2648
|
+
if (err instanceof CommittedRowChanged)
|
|
2649
|
+
return storedRowChangedRefusal("Memory");
|
|
2650
|
+
throw err;
|
|
2651
|
+
}
|
|
2652
|
+
// flair#2561: a refusal this path built is returned as built; a
|
|
2653
|
+
// successful Response is replaced by the write_response_withheld
|
|
2654
|
+
// refusal (writeResultResponse).
|
|
2655
|
+
if (reindexed instanceof Response)
|
|
2656
|
+
return writeResultResponse(reindexed);
|
|
1390
2657
|
noteMemoryUpsert(content);
|
|
1391
|
-
noteWriteStamp(
|
|
1392
|
-
return reindexed;
|
|
2658
|
+
noteWriteStamp(reindexRow?.embeddingModel, reindexExisting); // embedding-space-guard slice 1 (see post())
|
|
2659
|
+
return rowWriteResponse(reindexed, reindexRow?.id, 0);
|
|
1393
2660
|
}
|
|
1394
|
-
//
|
|
1395
|
-
//
|
|
1396
|
-
//
|
|
1397
|
-
//
|
|
2661
|
+
// flair#2441 + flair#2478 slice 1: a test-only pause of this PUT before its
|
|
2662
|
+
// transaction opens (other writers, background ones included, can still
|
|
2663
|
+
// change the row meanwhile); then the ordinary write runs in ONE owned
|
|
2664
|
+
// transaction whose FIRST operation is the authoritative stored read —
|
|
2665
|
+
// Harper orders a transaction by its first read, so the read and every
|
|
2666
|
+
// decision drawn from it share this write's commit and commit before the
|
|
2667
|
+
// write lock releases. A composed put, below, joins its caller's transaction
|
|
2668
|
+
// instead.
|
|
2669
|
+
const beforePut = txnPausePoint("memory-put-pre");
|
|
2670
|
+
if (beforePut)
|
|
2671
|
+
await beforePut;
|
|
1398
2672
|
const ctx = this.getContext?.();
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
// untouched). See the dedup-gate block further down for why an existing
|
|
1457
|
-
// id skips the gate; the SAME "does a record already exist" check gates
|
|
1458
|
-
// the visibility default (Layer 1 part A): patchRecord/supersede-
|
|
1459
|
-
// close all route through put() with a MERGED
|
|
1460
|
-
// `{...existing, ...patch}` payload, and must never have their stored
|
|
1461
|
-
// visibility overwritten by a default recomputed from that merged content
|
|
1462
|
-
// — only a genuinely NEW id gets the default stamped.
|
|
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
|
-
}
|
|
1480
|
-
// ─── Default visibility (durability-keyed) — Layer 1, part A ────────────
|
|
1481
|
-
// Explicit visibility on the write ALWAYS overrides; only stamp the
|
|
1482
|
-
// default when the caller left it unset AND this is a fresh record.
|
|
1483
|
-
// permanent|persistent → shared; standard|ephemeral|absent → private.
|
|
1484
|
-
// ── flair#1009: refuse an unrecognised visibility BEFORE defaulting ──
|
|
1485
|
-
// isPrivateVisibility() is an exact match on "private", so on the READ
|
|
1486
|
-
// side every other value (a typo, a wrong case, a retired tier like
|
|
1487
|
-
// "office") resolves to non-private and is readable by every agent on the
|
|
1488
|
-
// instance. #1006 closed that at the CLI flag and the MCP tool argument;
|
|
1489
|
-
// REST and the in-process API reach here without passing either.
|
|
1490
|
-
//
|
|
1491
|
-
// Refusing, rather than dropping the key: dropping it falls through to the
|
|
1492
|
-
// durability-keyed default below, which for a permanent or persistent
|
|
1493
|
-
// write is "shared" - the same widening, arrived at silently. A misspelled
|
|
1494
|
-
// argument must not decide who can read a memory.
|
|
1495
|
-
{
|
|
1496
|
-
const visibilityError = assertValidVisibility(content.visibility);
|
|
1497
|
-
if (visibilityError) {
|
|
1498
|
-
return new Response(JSON.stringify({ error: "invalid_visibility", message: visibilityError }), { status: 400, headers: { "content-type": "application/json" } });
|
|
1499
|
-
}
|
|
1500
|
-
}
|
|
1501
|
-
// ── flair#1257: ephemeral memories are private-only (hard precondition) ──
|
|
1502
|
-
// Same rule as post(), with one PUT-specific wrinkle: an update payload
|
|
1503
|
-
// may omit durability entirely (put() stamps no durability default), so
|
|
1504
|
-
// `PUT /Memory/<id> {"visibility":"shared"}` against a stored ephemeral
|
|
1505
|
-
// row names no durability of its own — the EFFECTIVE durability is the
|
|
1506
|
-
// pre-existing row's, and the flip must refuse just like a fresh
|
|
1507
|
-
// ephemeral+shared create. An explicit durability on the write wins: a
|
|
1508
|
-
// write that promotes the row OUT of ephemeral (e.g. distillation lifting
|
|
1509
|
-
// it to persistent, #1205) while sharing it is a legitimate promotion,
|
|
1510
|
-
// not an ephemeral share. preExisting was fetched above.
|
|
1511
|
-
{
|
|
1512
|
-
const effectiveDurability = content.durability ?? preExisting?.durability;
|
|
1513
|
-
const tierError = assertVisibilityAllowedForDurability(effectiveDurability, content.visibility);
|
|
1514
|
-
if (tierError) {
|
|
1515
|
-
return new Response(JSON.stringify({ error: "invalid_visibility_for_durability", message: tierError }), { status: 400, headers: { "content-type": "application/json" } });
|
|
1516
|
-
}
|
|
1517
|
-
}
|
|
1518
|
-
if (!preExisting && (content.visibility === undefined || content.visibility === null)) {
|
|
1519
|
-
content.visibility = defaultVisibilityForDurability(content.durability);
|
|
1520
|
-
}
|
|
1521
|
-
// ── flair#1257 slice 3: stamp the ephemeral TTL on the PUT path too ──────
|
|
1522
|
-
// post() has stamped expiresAt for ephemeral rows since the tier shipped,
|
|
1523
|
-
// but put() — the verb the continuity capture hook actually writes with
|
|
1524
|
-
// (`PUT /Memory/<id>`, packages/flair-mcp/src/continuity-capture-hook.ts)
|
|
1525
|
-
// — never did. MemoryMaintenance's reap keys on expiresAt (expired =
|
|
1526
|
-
// expiresAt < now), so hook-written journal rows carried NO expiry and
|
|
1527
|
-
// the tier's load-bearing 24h containment bound (the exposure window the
|
|
1528
|
-
// #1257 rulings cite) silently never engaged on the real write path.
|
|
1529
|
-
// Effective durability = the write's, else the pre-existing row's (same
|
|
1530
|
-
// resolution the visibility guard above uses). A pre-existing expiry is
|
|
1531
|
-
// carried forward, never re-stamped — an update must not extend the
|
|
1532
|
-
// exposure window; an explicit caller-provided expiresAt always wins.
|
|
1533
|
-
{
|
|
1534
|
-
const effectiveDurability = content.durability ?? preExisting?.durability;
|
|
1535
|
-
if (effectiveDurability === "ephemeral" && !content.expiresAt) {
|
|
1536
|
-
if (preExisting?.expiresAt) {
|
|
1537
|
-
content.expiresAt = preExisting.expiresAt;
|
|
2673
|
+
// A caller that composes this put into its OWN open write transaction
|
|
2674
|
+
// (withComposedWriteTransaction: manual promotion, whose verdict stamp must
|
|
2675
|
+
// commit or abort with this row, flair#2354) is joined, not detached: the
|
|
2676
|
+
// caller owns the commit, which lands after this lock is released, and there
|
|
2677
|
+
// is no post-commit verification here (manual promotion's stamp reads the
|
|
2678
|
+
// row in that transaction and refuses when there is none; it does not
|
|
2679
|
+
// compare the written identity). Every other ordinary put owns its
|
|
2680
|
+
// transaction; the `_reindex` re-PUT above joins a request transaction when
|
|
2681
|
+
// one is open, as it did before the lock.
|
|
2682
|
+
const composed = composesCallerWrite(ctx);
|
|
2683
|
+
let putResult;
|
|
2684
|
+
// flair#2467: the post-redaction text fields this write stages, for the response.
|
|
2685
|
+
let putStaged = {};
|
|
2686
|
+
let putGrantedClosed = null;
|
|
2687
|
+
try {
|
|
2688
|
+
putResult = await (composed ? withSharedWriteTransaction : withOwnedTransaction)(ctx, async (c) => {
|
|
2689
|
+
// The authoritative stored read: the FIRST operation of an ordinary PUT's
|
|
2690
|
+
// owned transaction (a composed put runs it in its caller's transaction,
|
|
2691
|
+
// which may already have read). It reads by the URL-BOUND target id (a
|
|
2692
|
+
// body id that disagrees with the address, or a lookup that FAILS, is
|
|
2693
|
+
// refused; a failed read is never read as "no stored row").
|
|
2694
|
+
const resolvedExisting = await resolveStoredRow(this, "Memory", content, () => super.get(), c);
|
|
2695
|
+
if (resolvedExisting.denial)
|
|
2696
|
+
return resolvedExisting.denial;
|
|
2697
|
+
const preExisting = resolvedExisting.row;
|
|
2698
|
+
// Authorize inside the transaction: the owner-field then authority guards
|
|
2699
|
+
// read the stored row from this transaction's own snapshot.
|
|
2700
|
+
const __ownerDenial = await guardOwnerFieldImmutable(this, () => super.get(), content, "agentId");
|
|
2701
|
+
if (__ownerDenial)
|
|
2702
|
+
return __ownerDenial;
|
|
2703
|
+
const authorityDenial = await guardAuthorityFields(() => super.get(), content, "Memory");
|
|
2704
|
+
if (authorityDenial)
|
|
2705
|
+
return authorityDenial;
|
|
2706
|
+
// Create/update ownership (same rule as post): a non-admin agent may only
|
|
2707
|
+
// write memories it owns, via resolveAgentAuth (gate annotation), not
|
|
2708
|
+
// context.user.username (the dormant-de-elevation fallback is "admin").
|
|
2709
|
+
// The _reindex admin path above bypasses this.
|
|
2710
|
+
let auth;
|
|
2711
|
+
{
|
|
2712
|
+
auth = await resolveAgentAuth(ctx);
|
|
2713
|
+
// Anonymous HTTP must NOT write (non-rejecting gate → self-enforce here).
|
|
2714
|
+
if (auth.kind === "anonymous") {
|
|
2715
|
+
return UNAUTH();
|
|
2716
|
+
}
|
|
2717
|
+
// flair#1383 — same write-path refuse as post().
|
|
2718
|
+
{
|
|
2719
|
+
const stale = refuseStaleClientWrite(ctx?.request, content);
|
|
2720
|
+
if (stale)
|
|
2721
|
+
return stale;
|
|
2722
|
+
}
|
|
2723
|
+
stripClientVersionPassthrough(content);
|
|
2724
|
+
// No-forge attribution — mode/field drawn from RECORD_TYPES.Memory,
|
|
2725
|
+
// same rule as post(). "validate-truthy" (see record-type-kit.ts's
|
|
2726
|
+
// stampAttribution doc).
|
|
2727
|
+
const attr = stampAttribution(auth, content, RECORD_TYPES.Memory.ownerField, RECORD_TYPES.Memory.attribution.put, "forbidden: cannot write memory owned by another agent");
|
|
2728
|
+
if (attr.denied)
|
|
2729
|
+
return attr.denied;
|
|
1538
2730
|
}
|
|
1539
|
-
|
|
1540
|
-
|
|
1541
|
-
|
|
2731
|
+
// flair#2561: the fields this request supplies that `stored` can report —
|
|
2732
|
+
// its string-valued text fields and, for a skill, the skill fields it
|
|
2733
|
+
// supplies (flair#2575) — read before the stored row or a skill predecessor
|
|
2734
|
+
// is merged into the body; `stored` reports only these. Redaction runs after
|
|
2735
|
+
// prepareSkillBody (below) and keeps a string a string, so reading them
|
|
2736
|
+
// first names the same fields.
|
|
2737
|
+
const suppliedText = suppliedStoredTextFields(content);
|
|
2738
|
+
canonicalizeSupersedes(content);
|
|
2739
|
+
// flair#2573: an empty `embedding` in the body is an omitted one (see post()).
|
|
2740
|
+
if (isEmptyEmbedding(content?.embedding))
|
|
2741
|
+
delete content.embedding;
|
|
2742
|
+
const requestedPayload = { ...content };
|
|
2743
|
+
// The visibility the caller named, before any merge, carry or default fills it.
|
|
2744
|
+
const requestedVisibility = content?.visibility;
|
|
2745
|
+
const urlTargetId = this.getId?.();
|
|
2746
|
+
if (content && typeof content === "object" && content.id == null &&
|
|
2747
|
+
(typeof urlTargetId === "string" || typeof urlTargetId === "number")) {
|
|
2748
|
+
content.id = urlTargetId;
|
|
1542
2749
|
}
|
|
1543
|
-
|
|
1544
|
-
|
|
1545
|
-
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
|
|
1549
|
-
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
|
|
1565
|
-
|
|
1566
|
-
|
|
1567
|
-
|
|
1568
|
-
|
|
2750
|
+
// flair#2465: as in post(), a body that omits `embedding` can have a stored
|
|
2751
|
+
// vector carried in by prepareSkillBody, with the hash it retained for it.
|
|
2752
|
+
const putOmitsEmbedding = content?.embedding === undefined;
|
|
2753
|
+
// flair#2573 slice 2: did the CALLER supply a non-null embedding, and/or an
|
|
2754
|
+
// `embeddingModel` stamp, that differs from the stored row's? Captured
|
|
2755
|
+
// before prepareSkillBody can merge a stored row's vector into the body.
|
|
2756
|
+
const { vector: putSuppliedVector, stamp: putSuppliedStamp } = suppliedVectorFlags(content, preExisting);
|
|
2757
|
+
const preparedSkill = await prepareSkillBody(content, preExisting, auth);
|
|
2758
|
+
if (preparedSkill instanceof Response)
|
|
2759
|
+
return preparedSkill;
|
|
2760
|
+
content = preparedSkill.content;
|
|
2761
|
+
const operatorSeed = isOperatorSeedPut(ctx, auth, writeTargetIds(this, content));
|
|
2762
|
+
let redactedValues = operatorSeed ? 0 : redactMemoryWrite(content).count;
|
|
2763
|
+
// Duplicate top-level metadata keys are refused; otherwise redact name/description and tags.
|
|
2764
|
+
redactedValues += redactSkillWrite(content);
|
|
2765
|
+
const putCarriedVector = putOmitsEmbedding && Array.isArray(content?.embedding) && content.embedding.length > 0;
|
|
2766
|
+
const putCarriedHash = putCarriedVector ? (content.embeddedContentHash ?? null) : null;
|
|
2767
|
+
// flair#744 slice A: citation-on-write — same consume-and-strip
|
|
2768
|
+
// discipline as post() above. Stripped before persistence so it is
|
|
2769
|
+
// never stored on the row; recorded post-commit
|
|
2770
|
+
// below only when present.
|
|
2771
|
+
const usedMemoryIds = content?.usedMemoryIds;
|
|
2772
|
+
if (content && typeof content === "object")
|
|
2773
|
+
delete content.usedMemoryIds;
|
|
2774
|
+
// ── flair#1238: refuse an unrecognised durability (mirrors post()) ──
|
|
2775
|
+
// put() is the other HTTP-reachable write path (fresh create via CLI, and
|
|
2776
|
+
// the update/patch path). Same guard as post(): a present-but-unknown
|
|
2777
|
+
// durability is refused with 400; absent is accepted.
|
|
2778
|
+
{
|
|
2779
|
+
const durabilityError = assertValidDurability(content.durability);
|
|
2780
|
+
if (durabilityError) {
|
|
2781
|
+
return new Response(JSON.stringify({ error: "invalid_durability", message: durabilityError }), { status: 400, headers: { "content-type": "application/json" } });
|
|
2782
|
+
}
|
|
1569
2783
|
}
|
|
1570
|
-
|
|
1571
|
-
|
|
1572
|
-
|
|
1573
|
-
//
|
|
1574
|
-
|
|
1575
|
-
|
|
1576
|
-
|
|
1577
|
-
|
|
1578
|
-
|
|
1579
|
-
|
|
1580
|
-
|
|
1581
|
-
|
|
1582
|
-
|
|
1583
|
-
|
|
1584
|
-
|
|
1585
|
-
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
|
|
1592
|
-
|
|
1593
|
-
|
|
1594
|
-
|
|
1595
|
-
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
|
|
1599
|
-
|
|
1600
|
-
|
|
1601
|
-
|
|
1602
|
-
|
|
1603
|
-
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
|
|
1608
|
-
|
|
1609
|
-
|
|
1610
|
-
|
|
1611
|
-
|
|
1612
|
-
|
|
1613
|
-
|
|
1614
|
-
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
|
|
1623
|
-
|
|
1624
|
-
|
|
1625
|
-
|
|
1626
|
-
|
|
1627
|
-
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
|
|
1633
|
-
|
|
1634
|
-
|
|
1635
|
-
|
|
2784
|
+
// ── flair#1542: skills are forced durability=persistent (mirrors post()) ──
|
|
2785
|
+
// put() stamps no durability default (updates carry the pre-existing tier),
|
|
2786
|
+
// so this runs on the raw write value: a skill-tagged write with an explicit
|
|
2787
|
+
// ephemeral/session tier is rejected, and every other value (including an
|
|
2788
|
+
// absent one) is forced to "persistent" so the reaper never archives a skill.
|
|
2789
|
+
{
|
|
2790
|
+
const skillDurabilityDenial = enforceSkillDurability(content);
|
|
2791
|
+
if (skillDurabilityDenial)
|
|
2792
|
+
return skillDurabilityDenial;
|
|
2793
|
+
}
|
|
2794
|
+
const now = new Date().toISOString();
|
|
2795
|
+
content.updatedAt = now;
|
|
2796
|
+
// Set defaults that post() sets — put() is also used for new records via CLI
|
|
2797
|
+
content.archived = content.archived ?? false;
|
|
2798
|
+
content.createdAt = content.createdAt ?? now;
|
|
2799
|
+
// Preserve stored visibility on updates before applying write policy
|
|
2800
|
+
// (only the two writable values; the guards below see the result).
|
|
2801
|
+
if (preExisting &&
|
|
2802
|
+
(content.visibility === undefined || content.visibility === null) &&
|
|
2803
|
+
(preExisting.visibility === PRIVATE_VISIBILITY || preExisting.visibility === SHARED_VISIBILITY)) {
|
|
2804
|
+
content.visibility = preExisting.visibility;
|
|
2805
|
+
}
|
|
2806
|
+
// ─── Default visibility (durability-keyed) — Layer 1, part A ────────────
|
|
2807
|
+
// Explicit visibility on the write ALWAYS overrides; only stamp the
|
|
2808
|
+
// default when the caller left it unset AND this is a fresh record.
|
|
2809
|
+
// permanent|persistent → shared; standard|ephemeral|absent → private.
|
|
2810
|
+
// ── flair#1009: refuse an unrecognised visibility BEFORE defaulting ──
|
|
2811
|
+
// isPrivateVisibility() is an exact match on "private", so on the READ
|
|
2812
|
+
// side every other value (a typo, a wrong case, a retired tier like
|
|
2813
|
+
// "office") resolves to non-private and is readable by every agent on the
|
|
2814
|
+
// instance. #1006 closed that at the CLI flag and the MCP tool argument;
|
|
2815
|
+
// REST and the in-process API reach here without passing either.
|
|
2816
|
+
//
|
|
2817
|
+
// Refusing, rather than dropping the key: dropping it falls through to the
|
|
2818
|
+
// durability-keyed default below, which for a permanent or persistent
|
|
2819
|
+
// write is "shared" - the same widening, arrived at silently. A misspelled
|
|
2820
|
+
// argument must not decide who can read a memory.
|
|
2821
|
+
{
|
|
2822
|
+
const visibilityError = assertValidVisibility(content.visibility);
|
|
2823
|
+
if (visibilityError) {
|
|
2824
|
+
return new Response(JSON.stringify({ error: "invalid_visibility", message: visibilityError }), { status: 400, headers: { "content-type": "application/json" } });
|
|
2825
|
+
}
|
|
2826
|
+
}
|
|
2827
|
+
// ── flair#1257: ephemeral memories are private-only (hard precondition) ──
|
|
2828
|
+
// Same rule as post(), with one PUT-specific wrinkle: an update payload
|
|
2829
|
+
// may omit durability entirely (put() stamps no durability default), so
|
|
2830
|
+
// `PUT /Memory/<id> {"visibility":"shared"}` against a stored ephemeral
|
|
2831
|
+
// row names no durability of its own — the EFFECTIVE durability is the
|
|
2832
|
+
// pre-existing row's, and the flip must refuse just like a fresh
|
|
2833
|
+
// ephemeral+shared create. An explicit durability on the write wins: a
|
|
2834
|
+
// write that promotes the row OUT of ephemeral (e.g. distillation lifting
|
|
2835
|
+
// it to persistent, #1205) while sharing it is a legitimate promotion,
|
|
2836
|
+
// not an ephemeral share. preExisting was fetched above.
|
|
2837
|
+
{
|
|
2838
|
+
const effectiveDurability = content.durability ?? preExisting?.durability;
|
|
2839
|
+
const tierError = assertVisibilityAllowedForDurability(effectiveDurability, content.visibility);
|
|
2840
|
+
if (tierError) {
|
|
2841
|
+
return new Response(JSON.stringify({ error: "invalid_visibility_for_durability", message: tierError }), { status: 400, headers: { "content-type": "application/json" } });
|
|
2842
|
+
}
|
|
2843
|
+
}
|
|
2844
|
+
if (!preExisting && (content.visibility === undefined || content.visibility === null)) {
|
|
2845
|
+
content.visibility = defaultVisibilityForDurability(content.durability);
|
|
2846
|
+
}
|
|
2847
|
+
const expiryError = stampEphemeralExpiry(content, preExisting);
|
|
2848
|
+
if (expiryError)
|
|
2849
|
+
return Response.json({ error: "invalid_expiry", message: expiryError }, { status: 400 });
|
|
2850
|
+
// supersedes: optional reference to the ID of the memory this one
|
|
2851
|
+
// replaces. Validates shape + cross-agent-write authorization (shared
|
|
2852
|
+
// with post() — see validateAndAuthorizeSupersedes doc for why PUT needs
|
|
2853
|
+
// this too: it's the only HTTP-reachable create path).
|
|
2854
|
+
const supersede = await validateAndAuthorizeSupersedes(content, auth, ctx, preExisting, requestedVisibility);
|
|
2855
|
+
if (supersede.denial)
|
|
2856
|
+
return supersede.denial;
|
|
2857
|
+
if (content.supersedes && !content.validFrom) {
|
|
2858
|
+
content.validFrom = content.createdAt;
|
|
2859
|
+
}
|
|
2860
|
+
// attention-plane vocabulary gate (flair#675) — see post()'s comment above.
|
|
2861
|
+
const entitiesError = invalidEntitiesResponse(content.entities);
|
|
2862
|
+
if (entitiesError)
|
|
2863
|
+
return entitiesError;
|
|
2864
|
+
// Content safety scan on updated content + summary.
|
|
2865
|
+
if (content.content || content.summary) {
|
|
2866
|
+
const safety = scanFields(content, ["content", "summary"]);
|
|
2867
|
+
if (!safety.safe) {
|
|
2868
|
+
if (isStrictMode()) {
|
|
2869
|
+
return new Response(JSON.stringify({
|
|
2870
|
+
error: "content_safety_violation",
|
|
2871
|
+
flags: safety.flags,
|
|
2872
|
+
message: "Content flagged for potential prompt injection.",
|
|
2873
|
+
}), { status: 400, headers: { "Content-Type": "application/json" } });
|
|
2874
|
+
}
|
|
2875
|
+
content._safetyFlags = safety.flags;
|
|
2876
|
+
}
|
|
2877
|
+
else {
|
|
2878
|
+
// Clear previous flags if both fields are now clean
|
|
2879
|
+
content._safetyFlags = null;
|
|
2880
|
+
}
|
|
2881
|
+
}
|
|
2882
|
+
// ── flair#1542: SkillScan gate BEFORE the embed (mirrors post()) ──
|
|
2883
|
+
// Every skill-tagged write is statically scanned before any embedding is
|
|
2884
|
+
// computed, so a rejected write pays no embed. Fail-closed on high/critical;
|
|
2885
|
+
// allow-with-flag on medium. Non-skill writes are a no-op.
|
|
2886
|
+
{
|
|
2887
|
+
const skillScanDenial = skillScanGate(content);
|
|
2888
|
+
if (skillScanDenial)
|
|
2889
|
+
return skillScanDenial;
|
|
2890
|
+
}
|
|
2891
|
+
{
|
|
2892
|
+
const skillSourceDenial = refuseSkillWriteSource(content);
|
|
2893
|
+
if (skillSourceDenial)
|
|
2894
|
+
return skillSourceDenial;
|
|
2895
|
+
}
|
|
2896
|
+
// Server-side conservative-duplicate gate (memory-integrity fix). PUT is
|
|
2897
|
+
// an upsert: only run the gate for a FRESH create (target id does not yet
|
|
2898
|
+
// exist) that is NOT a supersede-link write. An update of an EXISTING id
|
|
2899
|
+
// (memory_update's default same-id overwrite path) is an intentional,
|
|
2900
|
+
// explicit overwrite, and a supersede-link write is an intentional
|
|
2901
|
+
// version-link — neither is an ambiguous "is this a duplicate of
|
|
2902
|
+
// something else" write, so both are dedup-bypassed automatically, no
|
|
2903
|
+
// separate flag needed. NEVER suppresses the write either way.
|
|
2904
|
+
// flair#2573 slice 2: a non-admin write's vector and stamp that differ
|
|
2905
|
+
// from the stored row's are discarded here, after redaction and before
|
|
2906
|
+
// the dedup gate and the embed step (see post()).
|
|
2907
|
+
if (putSuppliedVector || putSuppliedStamp) {
|
|
2908
|
+
discardSuppliedVector(content, auth, { vector: putSuppliedVector, stamp: putSuppliedStamp }, preExisting);
|
|
2909
|
+
}
|
|
2910
|
+
// flair#2573: an empty vector that reaches this point is no vector (see post()).
|
|
2911
|
+
normalizeEmptyEmbedding(content);
|
|
2912
|
+
// flair#2465: did the caller supply a vector? See post().
|
|
2913
|
+
const embeddingSupplied = Array.isArray(content.embedding) && content.embedding.length > 0;
|
|
2914
|
+
let dedupMatch = null;
|
|
2915
|
+
try {
|
|
2916
|
+
if (content.supersedes) {
|
|
2917
|
+
delete content.dedup;
|
|
2918
|
+
delete content.dedupThreshold;
|
|
2919
|
+
delete content.lexicalThreshold;
|
|
2920
|
+
}
|
|
2921
|
+
else if (content.id) {
|
|
2922
|
+
if (!preExisting) {
|
|
2923
|
+
dedupMatch = await runDedupGate(ctx, content, true);
|
|
2924
|
+
}
|
|
2925
|
+
else {
|
|
2926
|
+
delete content.dedup;
|
|
2927
|
+
delete content.dedupThreshold;
|
|
2928
|
+
delete content.lexicalThreshold;
|
|
2929
|
+
}
|
|
2930
|
+
}
|
|
2931
|
+
else {
|
|
2932
|
+
dedupMatch = await runDedupGate(ctx, content, true);
|
|
2933
|
+
}
|
|
2934
|
+
}
|
|
2935
|
+
catch (err) {
|
|
2936
|
+
if (err instanceof MemoryProviderTimeout)
|
|
2937
|
+
return memoryProviderTimeoutResponse();
|
|
2938
|
+
throw err;
|
|
2939
|
+
}
|
|
2940
|
+
// Re-generate embedding if content changed (no-op if the dedup gate above
|
|
2941
|
+
// already computed one for this content). flair#504 Phase 2: 'document'
|
|
2942
|
+
const embedText = skillEmbedText(content);
|
|
2943
|
+
if (embedText && !content.embedding) {
|
|
2944
|
+
let vec;
|
|
2945
|
+
try {
|
|
2946
|
+
vec = await embedUnderLock(embedText);
|
|
2947
|
+
}
|
|
2948
|
+
catch (err) {
|
|
2949
|
+
if (err instanceof MemoryProviderTimeout)
|
|
2950
|
+
return memoryProviderTimeoutResponse();
|
|
2951
|
+
throw err;
|
|
2952
|
+
}
|
|
2953
|
+
if (vec) {
|
|
2954
|
+
content.embedding = vec;
|
|
2955
|
+
content.embeddingModel = getModelId();
|
|
2956
|
+
}
|
|
2957
|
+
}
|
|
2958
|
+
// If archiving, record who + when
|
|
2959
|
+
if (content.archived === true && !content.archivedAt) {
|
|
2960
|
+
content.archivedAt = now;
|
|
2961
|
+
// archivedBy should be set by the caller (CLI stamps req.tpsAgent via query param)
|
|
2962
|
+
}
|
|
2963
|
+
// ── flair#1940 slice 1 (A1'): the host pointer is NOT a Memory attribute. ──
|
|
2964
|
+
// Identical rule to post(): consume the write-body-only pointer inputs OUT
|
|
2965
|
+
// of the row, validate them, and build the pointer row written alongside
|
|
2966
|
+
// the Memory row below. A client-supplied `hostSourceVisibility` is dropped
|
|
2967
|
+
// (never read). Reject, never truncate/coerce.
|
|
2968
|
+
const pointerInputs = extractPointerInputs(content);
|
|
2969
|
+
// A1-iv item 3: strip server-stamped fields (a client may not set them).
|
|
2970
|
+
stripServerStampedFields(content);
|
|
2971
|
+
// flair#2465: a vector the server computed here gets a newly computed hash
|
|
2972
|
+
// (see post()). A skill vector prepareSkillBody carried in keeps the hash it
|
|
2973
|
+
// retained (possibly null) — including a superseding create at a new id,
|
|
2974
|
+
// which has no stored row of its own. Any other put that does not compute a
|
|
2975
|
+
// vector (one accepted from the caller, an echoed one, or a failed embed)
|
|
2976
|
+
// retains this row's stored hash, if any; `preExisting` is the row this
|
|
2977
|
+
// owned transaction read first (flair#2478). A retained hash is a preserved
|
|
2978
|
+
// value that may describe an earlier server-computed vector, not
|
|
2979
|
+
// necessarily the vector stored now. One that differs from the current
|
|
2980
|
+
// text's expected hash re-queues the row in the stamp migration; with no
|
|
2981
|
+
// stored hash the comparison is skipped.
|
|
2982
|
+
content.embeddedContentHash = !embeddingSupplied && Array.isArray(content.embedding) && content.embedding.length > 0
|
|
2983
|
+
? (embeddedTextHash(content) ?? null)
|
|
2984
|
+
: putCarriedVector ? putCarriedHash : (preExisting?.embeddedContentHash ?? null);
|
|
2985
|
+
// A1-iv item 1: PRESERVE the existing row's incarnation token on an update,
|
|
2986
|
+
// else generate one (a fresh create via put).
|
|
2987
|
+
stampInstanceToken(content, preExisting);
|
|
2988
|
+
// A1'' item 5: a partial PUT (one that omits `visibility`, e.g. a
|
|
2989
|
+
// memory_update full put) must stamp scopeAtWrite from the record's
|
|
2990
|
+
// EFFECTIVE visibility — the existing row's when the body omits it — not
|
|
2991
|
+
// from an undefined body value that would wrongly yield author-only.
|
|
2992
|
+
const effectiveVisibility = content.visibility ?? preExisting?.visibility;
|
|
2993
|
+
// A partial PUT carries the stored visibility it read at the start of the
|
|
2994
|
+
// request (one carry, above, before the write-policy guards).
|
|
2995
|
+
// Adjudication B (round 4): load the stored pointer row so an echo of it is
|
|
2996
|
+
// recognised and not replaced (see buildPointerForWrite).
|
|
2997
|
+
let storedPointer = null;
|
|
2998
|
+
if (content.id &&
|
|
2999
|
+
pointerInputs.hostSource !== undefined &&
|
|
3000
|
+
pointerInputs.hostSource !== null &&
|
|
3001
|
+
pointerInputs.hostSourceScope === undefined) {
|
|
3002
|
+
storedPointer = await loadStoredPointer(content.id);
|
|
3003
|
+
}
|
|
3004
|
+
const pointer = buildPointerForWrite({ inputs: pointerInputs, memoryId: content.id ?? "", visibility: effectiveVisibility, auth, memoryInstanceToken: content.instanceToken, storedPointer });
|
|
3005
|
+
if (pointer.denial)
|
|
3006
|
+
return pointer.denial;
|
|
3007
|
+
// Write-time provenance stamp (memory-provenance slice 1) — see
|
|
3008
|
+
// buildProvenance's doc above post(). Applies to every put() (fresh
|
|
3009
|
+
// create AND update/patch) — never gated on preExisting, so an update
|
|
3010
|
+
// always gets a freshly-stamped provenance reflecting the CURRENT
|
|
3011
|
+
// authenticated actor performing this write.
|
|
3012
|
+
content.provenance = buildProvenance(auth, content.createdAt, content);
|
|
3013
|
+
// flair#1940 A4: a client-supplied `receivedAt` is IGNORED (stripped; the
|
|
3014
|
+
// server's receipt time lives inside provenance, stamped above).
|
|
3015
|
+
delete content.receivedAt;
|
|
3016
|
+
// flair#718 authorship-provenance — see post()'s identical comment above:
|
|
3017
|
+
// strip the write-body-only `claimedClient` passthrough now that it's
|
|
3018
|
+
// folded into `provenance.claimed.client`. Never persisted as a row field.
|
|
3019
|
+
delete content.claimedClient;
|
|
3020
|
+
// Write-time originatorInstanceId (federation-edge-hardening slice 1):
|
|
3021
|
+
// a CREATE (no pre-existing row) stamps this instance's own id, ignoring
|
|
3022
|
+
// any body value; an UPDATE keeps the STORED value — a body value neither
|
|
3023
|
+
// replaces nor clears it. A federation-synced record never reaches this
|
|
3024
|
+
// method at all (the merge path writes via the raw table handle). See
|
|
3025
|
+
// resources/originator-instance.ts.
|
|
3026
|
+
await applyOriginatorInstanceId(content, preExisting);
|
|
3027
|
+
// The receiver-side federation bookkeeping stands as stored on an update,
|
|
3028
|
+
// and a client body may not set it on a create. See
|
|
3029
|
+
// resources/originator-instance.ts.
|
|
3030
|
+
applyFederationBookkeeping(content, preExisting);
|
|
3031
|
+
// ── Write the new/updated record FIRST ──────────────────────────────────
|
|
3032
|
+
// A1' item 1: persist ONLY declared Memory attributes (see post()).
|
|
3033
|
+
// Pinned by test/unit/memory-host-source.test.ts (r20-put) — RED if this
|
|
3034
|
+
// call is removed.
|
|
3035
|
+
stripUndeclaredMemoryAttributes(content);
|
|
3036
|
+
normalizeEmptyEmbedding(content);
|
|
3037
|
+
if (isSkillWrite(content)) {
|
|
3038
|
+
const reservedId = [content?.id, this.getId?.()].find((candidate) => isReservedSeedId("Memory", candidate));
|
|
3039
|
+
const skillStaged = { supplied: suppliedText, text: null };
|
|
3040
|
+
// A PUT whose redaction replaced a value commits its redacted effective
|
|
3041
|
+
// row, inherited fields included, so each field the reply's `stored`
|
|
3042
|
+
// reports (the fields the request supplied, flair#2561) is what the row
|
|
3043
|
+
// holds: the in-place unchanged-row check gets no requested fields for it.
|
|
3044
|
+
return { skill: skillWriteResponse(await writeSkillCreateOrUpdate({
|
|
3045
|
+
ctx, auth, content, storedRow: preExisting, explicitPredecessor: preparedSkill.predecessor, method: "put", pointer,
|
|
3046
|
+
reembedding, requestedPayload: redactedValues > 0 ? undefined : requestedPayload,
|
|
3047
|
+
inPlaceId: reservedId != null ? String(reservedId) : null, staged: skillStaged,
|
|
3048
|
+
}), redactedValues, skillStaged.text) };
|
|
3049
|
+
}
|
|
3050
|
+
// flair#2441: this put is over the row read as `preExisting` (which
|
|
3051
|
+
// `stampInstanceToken` copied its incarnation token from). The write
|
|
3052
|
+
// confirms, against the COMMITTED row, that it is still that one
|
|
3053
|
+
// (sameStoredRow): once before the row is staged (nothing is staged yet,
|
|
3054
|
+
// so the refusal is returned) and once after, before the commit
|
|
3055
|
+
// (confirmCommittedRow: the transaction is aborted and the staged rows
|
|
3056
|
+
// discarded). Both reads use an explicit fresh context, never contextless
|
|
3057
|
+
// (see resources/write-back.ts).
|
|
3058
|
+
const confirmPause = txnPausePoint("memory-put");
|
|
3059
|
+
if (confirmPause)
|
|
3060
|
+
await confirmPause;
|
|
3061
|
+
if (preExisting) {
|
|
3062
|
+
const confirmed = await databases.flair.Memory.get(preExisting.id, {});
|
|
3063
|
+
if (!confirmed || !sameStoredRow(confirmed, preExisting))
|
|
3064
|
+
return storedRowChangedRefusal("Memory");
|
|
3065
|
+
}
|
|
3066
|
+
putStaged = storedMemoryText(content, suppliedText);
|
|
3067
|
+
const r = storageResult(await databases.flair.Memory.put(content, c));
|
|
3068
|
+
if (r instanceof Response)
|
|
3069
|
+
return r;
|
|
3070
|
+
if (pointer.row) {
|
|
3071
|
+
pointer.row.memoryId = r?.id ?? content.id ?? "";
|
|
3072
|
+
const persistDenial = await persistPointerRow(pointer.row, c);
|
|
3073
|
+
if (persistDenial)
|
|
3074
|
+
return persistDenial;
|
|
3075
|
+
}
|
|
3076
|
+
if (preExisting) {
|
|
3077
|
+
// Measured over HTTP on Harper 5.3.1: a competitor committed after this
|
|
3078
|
+
// write was staged keeps its row even without this re-check (Harper
|
|
3079
|
+
// orders the staged write by this transaction's earlier timestamp); the
|
|
3080
|
+
// re-check is what refuses the put by name instead of answering success
|
|
3081
|
+
// for a write that did not land. Test-only: holds the staged write.
|
|
3082
|
+
const stagedPause = txnPausePoint("memory-put-staged");
|
|
3083
|
+
if (stagedPause)
|
|
3084
|
+
await stagedPause;
|
|
3085
|
+
// The committed row must still be the one read; the throw leaves this
|
|
3086
|
+
// callback, so the owned transaction aborts and the staged write is
|
|
3087
|
+
// discarded, and the caller answers 409. A composing caller's
|
|
3088
|
+
// transaction is not aborted by the throw, so it is aborted here.
|
|
3089
|
+
try {
|
|
3090
|
+
await confirmCommittedRow(databases.flair.Memory, preExisting.id, (committed) => sameStoredRow(committed, preExisting));
|
|
3091
|
+
}
|
|
3092
|
+
catch (err) {
|
|
3093
|
+
if (err instanceof CommittedRowChanged && composed)
|
|
3094
|
+
abortRequestTransaction(c);
|
|
3095
|
+
throw err;
|
|
3096
|
+
}
|
|
3097
|
+
}
|
|
3098
|
+
// Stage a grant-authorized close in the successor's transaction: the
|
|
3099
|
+
// transaction this put owns (a throw leaves this callback and aborts it)
|
|
3100
|
+
// or, for a composed put, its caller's (aborted explicitly).
|
|
3101
|
+
putGrantedClosed = await closeGrantedSupersedeStaged(c, content, supersede.close, composed);
|
|
3102
|
+
return { content, result: r, dedupMatch, redactedValues, usedMemoryIds, close: supersede.close, auth, fallbackId: preExisting?.id, previous: preExisting ?? null };
|
|
3103
|
+
});
|
|
1636
3104
|
}
|
|
1637
|
-
|
|
1638
|
-
|
|
1639
|
-
|
|
1640
|
-
|
|
1641
|
-
|
|
1642
|
-
|
|
1643
|
-
|
|
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);
|
|
3105
|
+
catch (err) {
|
|
3106
|
+
if (err instanceof CommittedRowChanged)
|
|
3107
|
+
return storedRowChangedRefusal("Memory");
|
|
3108
|
+
const refusal = grantedCloseRefusal(err);
|
|
3109
|
+
if (refusal)
|
|
3110
|
+
return refusal;
|
|
3111
|
+
throw err;
|
|
1663
3112
|
}
|
|
1664
|
-
|
|
1665
|
-
if (
|
|
1666
|
-
return
|
|
1667
|
-
//
|
|
1668
|
-
//
|
|
1669
|
-
//
|
|
1670
|
-
// always gets a freshly-stamped provenance reflecting the CURRENT
|
|
1671
|
-
// authenticated actor performing this write.
|
|
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;
|
|
1676
|
-
// flair#718 authorship-provenance — see post()'s identical comment above:
|
|
1677
|
-
// strip the write-body-only `claimedClient` passthrough now that it's
|
|
1678
|
-
// folded into `provenance.claimed.client`. Never persisted as a row field.
|
|
1679
|
-
delete content.claimedClient;
|
|
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);
|
|
1691
|
-
// ── Write the new/updated record FIRST ──────────────────────────────────
|
|
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
|
-
});
|
|
3113
|
+
// A skill PUT answers from its own write (no ordinary-row post-commit step).
|
|
3114
|
+
if (putResult && putResult.skill !== undefined)
|
|
3115
|
+
return putResult.skill;
|
|
3116
|
+
// flair#2561: a refusal this path built is returned as built; a
|
|
3117
|
+
// successful Response is replaced by the write_response_withheld refusal
|
|
3118
|
+
// (a storage-layer Response was replaced in the transaction, storageResult).
|
|
1711
3119
|
if (putResult instanceof Response)
|
|
1712
|
-
return putResult;
|
|
1713
|
-
|
|
3120
|
+
return writeResultResponse(putResult);
|
|
3121
|
+
// embedding-space-guard slice 1 (see post()): the ordinary row write has
|
|
3122
|
+
// returned from its transaction, so the guard is notified now, with the
|
|
3123
|
+
// stored stamp and the row this PUT replaced (flair#2573), before the
|
|
3124
|
+
// verification read: a refused or unknown verification still leaves the
|
|
3125
|
+
// guard told about the stored vector.
|
|
3126
|
+
noteWriteStamp(putResult.content?.embeddingModel, putResult.previous ?? null);
|
|
3127
|
+
// Verify the ordinary owned row PUT after a normal storage result.
|
|
3128
|
+
// Refusals, storage Responses and skill PUT return above; composed promotion skips
|
|
3129
|
+
// this read and uses its caller's in-transaction existence check.
|
|
3130
|
+
// Compare the token and declared agentId/content/visibility/durability;
|
|
3131
|
+
// other field changes pass. A failed read marks the id and answers 503.
|
|
3132
|
+
if (!composed) {
|
|
3133
|
+
// Test-only: holds the PUT after its commit, before the verification read.
|
|
3134
|
+
const verifyPause = txnPausePoint("memory-put-verify");
|
|
3135
|
+
if (verifyPause)
|
|
3136
|
+
await verifyPause;
|
|
3137
|
+
const verified = await verifyCommittedWrite(databases.flair.Memory, putResult.content, putResult.fallbackId, { expectedToken: putResult.content?.instanceToken });
|
|
3138
|
+
if (verified.unknown)
|
|
3139
|
+
return writeOutcomeUnknownFor(putResult.content?.id ?? putResult.fallbackId);
|
|
3140
|
+
if (verified.mismatch)
|
|
3141
|
+
return storedRowChangedRefusal("Memory");
|
|
3142
|
+
}
|
|
3143
|
+
// The verification only decides whether the write is answered; the response
|
|
3144
|
+
// is built from the write's own result, never from the verified row. The
|
|
3145
|
+
// stored row carries per-row values that are not part of the write response
|
|
3146
|
+
// (`instanceToken`, `embedding`, `provenance`). Built this way, two otherwise
|
|
3147
|
+
// identical writes, one citing a memory the writer cannot read and one citing
|
|
3148
|
+
// a nonexistent id, answer identically once writer ids and timestamps are
|
|
3149
|
+
// normalized: nothing in the answer depends on the cited id (flair#775).
|
|
3150
|
+
const result = putResult.result;
|
|
1714
3151
|
// flair#1357 — read-your-write for the lexical leg (see post()).
|
|
1715
|
-
noteMemoryUpsert(content);
|
|
1716
|
-
noteWriteStamp(content?.embeddingModel); // embedding-space-guard slice 1 (see post())
|
|
3152
|
+
noteMemoryUpsert(putResult.content);
|
|
1717
3153
|
// ── THEN close the superseded record (see post()) ───────────────────────
|
|
1718
|
-
|
|
3154
|
+
// A grant-authorized close was staged in the successor's transaction
|
|
3155
|
+
// (closeGrantedSupersedeStaged).
|
|
3156
|
+
if (putGrantedClosed)
|
|
3157
|
+
noteMemoryUpsert(putGrantedClosed);
|
|
3158
|
+
if (putResult.close?.granteeId === undefined)
|
|
3159
|
+
await closeSupersededIfNeeded(ctx, putResult.content, putResult.close, "put");
|
|
1719
3160
|
// flair#744 slice A: citation-on-write — POST-COMMIT, fully
|
|
1720
3161
|
// failure-isolated (see post()'s identical comment above).
|
|
1721
|
-
if (usedMemoryIds !== undefined) {
|
|
3162
|
+
if (putResult.usedMemoryIds !== undefined) {
|
|
1722
3163
|
try {
|
|
1723
|
-
await recordCitations(ctx, auth, usedMemoryIds, new Date().toISOString());
|
|
3164
|
+
await recordCitations(ctx, putResult.auth, putResult.usedMemoryIds, new Date().toISOString());
|
|
1724
3165
|
}
|
|
1725
3166
|
catch (err) {
|
|
1726
3167
|
console.error("Memory.put: citation recording failed (write already committed)", err);
|
|
1727
3168
|
}
|
|
1728
3169
|
}
|
|
1729
|
-
return buildWriteResponse(content, result, dedupMatch);
|
|
3170
|
+
return buildWriteResponse(putResult.content, result, putResult.dedupMatch, putResult.redactedValues, putStaged);
|
|
1730
3171
|
}
|
|
1731
3172
|
async delete(id) {
|
|
1732
3173
|
const ctx = this.getContext?.();
|
|
1733
3174
|
const auth = await resolveAgentAuth(ctx);
|
|
1734
3175
|
if (auth.kind === "anonymous")
|
|
1735
3176
|
return UNAUTH();
|
|
3177
|
+
// flair#2478: a DELETE of an id whose last owned PUT/PATCH settled with an
|
|
3178
|
+
// unknown outcome waits for reconciliation too: refused until restart, as a
|
|
3179
|
+
// later PUT or PATCH of that id is.
|
|
3180
|
+
if ([id, ...writeTargetIds(this, id && typeof id === "object" ? id : undefined)]
|
|
3181
|
+
.some((t) => (typeof t === "string" || typeof t === "number") && memoryWriteOutcomeUnknown(t))) {
|
|
3182
|
+
return writeOutcomeUnknownResponse();
|
|
3183
|
+
}
|
|
3184
|
+
// flair#2141 S2: check the seed's fixed id against the operator-source
|
|
3185
|
+
// reservation (resources/seed-reservation.ts).
|
|
3186
|
+
const seedDenial = reservedSeedWriteDenial("Memory", [id, ...writeTargetIds(this, id && typeof id === "object" ? id : undefined)], ctx, auth);
|
|
3187
|
+
if (seedDenial)
|
|
3188
|
+
return seedDenial;
|
|
3189
|
+
const contentSuffixDenial = refuseContentSuffixId([id, ...writeTargetIds(this, id && typeof id === "object" ? id : undefined)], id);
|
|
3190
|
+
if (contentSuffixDenial)
|
|
3191
|
+
return contentSuffixDenial;
|
|
1736
3192
|
// Read stored ownership, not the read-scoped get() response. Enforce here
|
|
1737
3193
|
// as well as middleware so MCP/in-process callers have the same policy.
|
|
1738
3194
|
const record = await super.get(id);
|
|
@@ -1740,6 +3196,17 @@ export class Memory extends databases.flair.Memory {
|
|
|
1740
3196
|
isForbiddenOwnerMutation(record, RECORD_TYPES.Memory.ownerField, auth.agentId)) {
|
|
1741
3197
|
return FORBIDDEN("forbidden: cannot delete memory owned by another agent");
|
|
1742
3198
|
}
|
|
3199
|
+
const reservedSeed = [id, this.getId?.(), ...writeTargetIds(this, id && typeof id === "object" ? id : undefined)]
|
|
3200
|
+
.some((candidate) => isReservedSeedId("Memory", candidate));
|
|
3201
|
+
if (!reservedSeed && rowIsSkill(record)) {
|
|
3202
|
+
// flair#2355: hold the row still before the version writer's transaction
|
|
3203
|
+
// opens, so a competing owner change can commit first and be seen by the
|
|
3204
|
+
// confirmation read inside.
|
|
3205
|
+
const beforeSkillDelete = txnPausePoint("memory-skill-delete-pre");
|
|
3206
|
+
if (beforeSkillDelete)
|
|
3207
|
+
await beforeSkillDelete;
|
|
3208
|
+
return await writeSkillDelete({ ctx, auth, record });
|
|
3209
|
+
}
|
|
1743
3210
|
// Durability controls retention, not the owner's authority to delete.
|
|
1744
3211
|
// A1' item 2 (adjudication 0a/0c): the Memory delete and its pointer
|
|
1745
3212
|
// delete share ONE transaction; with no request context
|
|
@@ -1750,18 +3217,60 @@ export class Memory extends databases.flair.Memory {
|
|
|
1750
3217
|
// owned here can use the synchronous hook after the shared write returns.
|
|
1751
3218
|
// Capture ownership before the helper changes the context's transaction.
|
|
1752
3219
|
const requestOwnsTransaction = isJoinableTransaction(ctx);
|
|
3220
|
+
const deletionActor = auth.kind === "agent" ? auth.agentId : null;
|
|
3221
|
+
const deletionSourceClass = auth.kind === "internal" ? "internal" : auth.isAdmin ? "admin" : "agent";
|
|
3222
|
+
// flair#2355: hold the row still before the delete stages, so a competing
|
|
3223
|
+
// owner change can commit first and be seen by the re-read inside. This
|
|
3224
|
+
// ordinary delete runs through withSharedWriteTransaction, which JOINS a
|
|
3225
|
+
// request-owned transaction when one exists and creates one otherwise.
|
|
3226
|
+
const beforeDelete = txnPausePoint("memory-delete-pre");
|
|
3227
|
+
if (beforeDelete)
|
|
3228
|
+
await beforeDelete;
|
|
1753
3229
|
const deleteResult = await withSharedWriteTransaction(ctx, async (c) => {
|
|
1754
|
-
const d = await databases.flair.Memory.delete(id, c);
|
|
1755
3230
|
const deletedId = typeof id === "string" ? id : record?.id;
|
|
1756
|
-
if (typeof deletedId
|
|
1757
|
-
|
|
1758
|
-
|
|
1759
|
-
|
|
3231
|
+
if (typeof deletedId !== "string" || !deletedId)
|
|
3232
|
+
return false;
|
|
3233
|
+
const stored = await databases.flair.Memory.get(deletedId, c);
|
|
3234
|
+
if (!stored)
|
|
3235
|
+
return false;
|
|
3236
|
+
const nonAdmin = auth.kind === "agent" && !auth.isAdmin;
|
|
3237
|
+
if (nonAdmin && isForbiddenOwnerMutation(stored, RECORD_TYPES.Memory.ownerField, auth.agentId)) {
|
|
3238
|
+
// The caller passed the owner check at the pre-read above, so a
|
|
3239
|
+
// mismatch here is a change committed since — refuse it, do not delete.
|
|
3240
|
+
return ownerChangedRefusal("Memory");
|
|
3241
|
+
}
|
|
3242
|
+
if (nonAdmin) {
|
|
3243
|
+
// Test-only: the transaction pauses between its ownership read and its
|
|
3244
|
+
// delete.
|
|
3245
|
+
const pause = txnPausePoint("memory-delete");
|
|
3246
|
+
if (pause)
|
|
3247
|
+
await pause;
|
|
3248
|
+
// Confirmation read of the COMMITTED row in an explicit fresh context
|
|
3249
|
+
// (never contextless — see resources/owner-delete-recheck.ts's header).
|
|
3250
|
+
const confirmed = await databases.flair.Memory.get(deletedId, {});
|
|
3251
|
+
if (confirmed && isForbiddenOwnerMutation(confirmed, RECORD_TYPES.Memory.ownerField, auth.agentId)) {
|
|
3252
|
+
return ownerChangedRefusal("Memory");
|
|
3253
|
+
}
|
|
1760
3254
|
}
|
|
3255
|
+
const d = await databases.flair.Memory.delete(deletedId, c);
|
|
3256
|
+
if (d !== true)
|
|
3257
|
+
throw new Error("Memory row delete was not confirmed");
|
|
3258
|
+
const pointerDenial = await deletePointerRow(deletedId, c);
|
|
3259
|
+
if (pointerDenial)
|
|
3260
|
+
return pointerDenial;
|
|
3261
|
+
await recordMemoryDeletion({
|
|
3262
|
+
memoryId: deletedId,
|
|
3263
|
+
memoryInstanceToken: stored.instanceToken ?? null,
|
|
3264
|
+
durability: stored.durability ?? null,
|
|
3265
|
+
actor: deletionActor,
|
|
3266
|
+
sourceClass: deletionSourceClass,
|
|
3267
|
+
}, c);
|
|
1761
3268
|
return d;
|
|
1762
3269
|
});
|
|
1763
3270
|
if (deleteResult instanceof Response)
|
|
1764
3271
|
return deleteResult;
|
|
3272
|
+
if (deleteResult === false)
|
|
3273
|
+
return false;
|
|
1765
3274
|
// Use the RESOLVED deleted id (a by-record delete carries only `id`, so the
|
|
1766
3275
|
// stored row's id is the fallback). An owned transaction has committed;
|
|
1767
3276
|
// a request-owned write waits for the committed change feed instead.
|