@tpsdev-ai/flair 0.62.0 → 0.63.1
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 +14 -13
- package/SECURITY.md +73 -43
- package/config.yaml +11 -11
- package/dist/bridges/runtime/execute.js +1 -0
- package/dist/bridges/runtime/import-runner.js +4 -0
- package/dist/bridges/types.js +1 -0
- package/dist/build-info.json +3 -3
- package/dist/cli.js +309 -205
- package/dist/commands/agent.js +325 -137
- package/dist/commands/attention.js +2 -0
- package/dist/commands/backup-approval.js +218 -0
- package/dist/commands/backup.js +37 -33
- package/dist/commands/bootstrap.js +5 -1
- package/dist/commands/bridge.js +10 -0
- package/dist/commands/deploy.js +37 -7
- package/dist/commands/doctor.js +206 -42
- package/dist/commands/export.js +144 -15
- package/dist/commands/federation.js +653 -68
- package/dist/commands/grant.js +5 -6
- package/dist/commands/help.js +25 -0
- package/dist/commands/idp.js +14 -19
- package/dist/commands/import.js +167 -34
- package/dist/commands/init.js +380 -164
- package/dist/commands/integrity.js +5 -6
- package/dist/commands/keys.js +12 -8
- package/dist/commands/mcp.js +157 -79
- package/dist/commands/memory.js +38 -17
- package/dist/commands/migrate-harness-memory.js +9 -3
- package/dist/commands/orgevent.js +5 -10
- package/dist/commands/principal.js +32 -39
- package/dist/commands/quality.js +26 -3
- package/dist/commands/reembed.js +468 -111
- package/dist/commands/rem.js +484 -65
- package/dist/commands/restore.js +352 -44
- package/dist/commands/search.js +2 -0
- package/dist/commands/service.js +109 -2
- package/dist/commands/soul.js +0 -6
- package/dist/commands/status.js +165 -124
- package/dist/commands/test.js +4 -1
- package/dist/commands/upgrade.js +53 -22
- package/dist/commands/workspace.js +7 -8
- package/dist/deploy.js +59 -3
- package/dist/doctor-client.js +9 -25
- package/dist/fabric-upgrade.js +12 -2
- package/dist/federation/presence-send.js +139 -0
- package/dist/federation/scheduler.js +148 -12
- package/dist/federation-verify.js +269 -177
- package/dist/install/clients.js +171 -35
- package/dist/keystore.js +77 -10
- package/dist/lib/agent-id-rule.js +44 -2
- package/dist/lib/agent-key-file.js +509 -0
- package/dist/lib/agent-rotation-lock.js +249 -0
- package/dist/lib/atomic-write.js +3 -3
- package/dist/lib/auth-resolve.js +1040 -64
- package/dist/lib/backup-approval-store.js +612 -0
- package/dist/lib/backup-artifact.js +343 -0
- package/dist/lib/config-critical-section.js +212 -25
- package/dist/lib/connect-phase.js +33 -0
- package/dist/lib/daemon-liveness.js +2 -1
- package/dist/lib/federation-pair-access.js +4 -0
- package/dist/lib/federation-retry-queue.js +283 -0
- package/dist/lib/federation-retry-row.js +101 -0
- package/dist/lib/instruction-event-contract.js +17 -0
- package/dist/lib/instruction-event-doctor.js +102 -0
- package/dist/lib/key-dir.js +203 -0
- package/dist/lib/launchd-management.js +21 -6
- package/dist/lib/local-instance-pair.js +8 -1
- package/dist/lib/mcp-enable.js +14 -15
- package/dist/lib/memory-attributes.js +2 -0
- package/dist/lib/memory-provider-timeout.js +33 -0
- package/dist/lib/mqtt-config.js +132 -0
- package/dist/lib/mqtt-listener-doctor.js +104 -0
- package/dist/lib/node-alias-path.js +50 -2
- package/dist/lib/open-live-row.js +20 -0
- package/dist/lib/ops-url.js +52 -0
- package/dist/lib/promotion-content-hash.js +20 -0
- package/dist/lib/remote-admin-pass.js +157 -0
- package/dist/lib/restore-archive.js +760 -0
- package/dist/lib/restore-verify.js +1 -1
- package/dist/lib/scheduler-platform.js +13 -0
- package/dist/lib/service-repoint.js +13 -4
- package/dist/lib/skill-assignment-preflight.js +159 -0
- package/dist/lib/skill-seed.js +125 -10
- package/dist/lib/skill-tombstone-doctor.js +133 -0
- package/dist/lib/soul-scope-fields.js +26 -0
- package/dist/lib/terminal-text.js +32 -0
- package/dist/lib/uninstall-purge.js +266 -11
- package/dist/lib/upgrade-prior-liveness.js +2 -1
- package/dist/mcp-client-assertion.js +7 -14
- package/dist/memory-id-checkpoint.js +28 -7
- package/dist/mqtt-off-deploy.js +550 -0
- package/dist/rem/promote-policy.js +3 -3
- package/dist/rem/restore.js +302 -26
- package/dist/rem/runner.js +220 -58
- package/dist/rem/scheduler.js +21 -4
- package/dist/resources/A2AAdapter.js +131 -178
- package/dist/resources/AdminMemory.js +2 -0
- package/dist/resources/AdminMemoryCandidates.js +116 -0
- package/dist/resources/Agent.js +155 -45
- package/dist/resources/AgentCard.js +4 -0
- package/dist/resources/AgentKeyRegister.js +56 -22
- package/dist/resources/AgentReadPosition.js +7 -0
- package/dist/resources/AgentSeed.js +232 -107
- package/dist/resources/AutoPromoteCandidates.js +413 -84
- package/dist/resources/Credential.js +6 -8
- package/dist/resources/Federation.js +219 -57
- package/dist/resources/FederationRetry.js +4 -4
- package/dist/resources/InstructionVersion.js +1 -1
- package/dist/resources/MCPClientMetadata.js +6 -3
- package/dist/resources/Memory.js +1348 -271
- package/dist/resources/MemoryArchive.js +149 -64
- package/dist/resources/MemoryBootstrap.js +12 -22
- package/dist/resources/MemoryCandidate.js +16 -2
- package/dist/resources/MemoryConsolidate.js +2 -2
- package/dist/resources/MemoryFeed.js +360 -147
- package/dist/resources/MemoryMaintenance.js +290 -72
- package/dist/resources/MemoryPurge.js +138 -22
- package/dist/resources/MemoryReflect.js +68 -14
- package/dist/resources/MemoryReindex.js +91 -13
- package/dist/resources/Message.js +11 -2
- package/dist/resources/OAuth.js +156 -39
- package/dist/resources/OAuthClient.js +1 -1
- package/dist/resources/OrgEvent.js +292 -29
- package/dist/resources/OrgEventCatchup.js +7 -0
- package/dist/resources/OrgEventMaintenance.js +48 -10
- package/dist/resources/PairingToken.js +1 -1
- package/dist/resources/Presence.js +31 -11
- package/dist/resources/PromoteMemoryCandidate.js +8 -2
- package/dist/resources/RecordUsage.js +2 -4
- package/dist/resources/Soul.js +2 -0
- package/dist/resources/SoulFeed.js +2 -1
- package/dist/resources/WorkspaceLatest.js +4 -0
- package/dist/resources/XAA.js +36 -10
- package/dist/resources/a2a-stream.js +313 -0
- package/dist/resources/a2a-url.js +4 -5
- package/dist/resources/agent-admin.js +10 -1
- package/dist/resources/agent-auth.js +98 -68
- package/dist/resources/agent-read-position-lib.js +4 -1
- package/dist/resources/agent-status-guard.js +9 -7
- package/dist/resources/auth-middleware.js +166 -42
- package/dist/resources/authority-field-guard.js +9 -11
- package/dist/resources/auto-promote-lib.js +8 -5
- package/dist/resources/basic-auth-header.js +21 -0
- package/dist/resources/bm25-index-service.js +4 -5
- package/dist/resources/dedup-cluster.js +6 -1
- package/dist/resources/embeddings-provider.js +25 -0
- package/dist/resources/federation-classify.js +89 -0
- package/dist/resources/federation-retry-lib.js +6 -81
- package/dist/resources/health.js +75 -19
- package/dist/resources/host-pointer/registry.js +29 -0
- package/dist/resources/host-pointer-adapter.js +1 -0
- package/dist/resources/in-process-api.js +74 -11
- package/dist/resources/in-process.js +24 -22
- package/dist/resources/instruction-version-record.js +251 -7
- package/dist/resources/internal-authority.js +13 -0
- package/dist/resources/mcp-client-metadata-fields.js +4 -0
- package/dist/resources/mcp-handler.js +146 -13
- package/dist/resources/mcp-oauth-flag.js +12 -14
- package/dist/resources/mcp-oauth.js +446 -53
- package/dist/resources/mcp-tool-scopes.js +69 -0
- package/dist/resources/mcp-tools.js +70 -22
- package/dist/resources/memory-declared-attributes.js +1 -0
- package/dist/resources/memory-embed-hash.js +56 -0
- package/dist/resources/memory-host-source.js +5 -2
- package/dist/resources/memory-reflect-lib.js +1 -1
- package/dist/resources/memory-write-lock.js +202 -23
- package/dist/resources/memory-write-response.js +1 -1
- package/dist/resources/memory-write-transaction.js +243 -0
- package/dist/resources/migration-boot.js +17 -12
- package/dist/resources/migrations/boot-progress.js +25 -0
- package/dist/resources/migrations/data-dir.js +16 -3
- package/dist/resources/migrations/dir-safety.js +60 -2
- package/dist/resources/migrations/embedding-stamp.js +315 -49
- package/dist/resources/migrations/graph-heal.js +9 -2
- package/dist/resources/migrations/ledger.js +5 -2
- package/dist/resources/migrations/lock.js +867 -80
- package/dist/resources/migrations/progress.js +71 -10
- package/dist/resources/migrations/runner.js +212 -18
- package/dist/resources/migrations/state.js +36 -1
- package/dist/resources/migrations/status.js +2 -13
- package/dist/resources/migrations/synthetic-test-migration.js +78 -12
- package/dist/resources/migrations/types.js +26 -1
- package/dist/resources/migrations/visibility-backfill.js +111 -70
- package/dist/resources/oauth-discovery.js +0 -5
- package/dist/resources/object-body-guard.js +12 -5
- package/dist/resources/org-event-reserved.js +92 -0
- package/dist/resources/org-event-write-fault.js +19 -0
- package/dist/resources/owner-field-guard.js +1 -1
- package/dist/resources/owner-scoped-write-policy.js +65 -21
- package/dist/resources/owner-scoped-writes.js +37 -6
- package/dist/resources/path-id-rewrite.js +76 -0
- package/dist/resources/presence-internal.js +5 -5
- package/dist/resources/promotion-binding.js +43 -0
- package/dist/resources/promotion-stamp.js +124 -33
- package/dist/resources/protocol-context.js +189 -0
- package/dist/resources/record-type-kit.js +2 -4
- package/dist/resources/request-target.js +28 -1
- package/dist/resources/request-transaction.js +11 -1
- package/dist/resources/seed-reservation.js +1 -2
- package/dist/resources/semantic-retrieval-core.js +7 -6
- package/dist/resources/server-row-validation.js +71 -0
- package/dist/resources/skill-manifest.js +4 -3
- package/dist/resources/skill-version-write.js +400 -27
- package/dist/resources/skill-write-fault.js +6 -3
- package/dist/resources/skill-write-policy.js +2 -1
- package/dist/resources/soul-write-policy.js +26 -7
- package/dist/resources/table-helpers.js +1 -1
- package/dist/resources/table-subscription-policy.js +518 -85
- package/dist/resources/table-subscriptions.js +20 -7
- package/dist/resources/txn-pause-point.js +122 -5
- package/dist/resources/usage-recording.js +54 -46
- package/dist/resources/write-back.js +176 -11
- package/dist/resources/write-journal-context.js +5 -0
- package/dist/resources/write-journal.js +289 -0
- package/dist/src/keystore.js +77 -10
- package/dist/src/lib/agent-id-rule.js +44 -2
- package/dist/src/lib/atomic-write.js +3 -3
- package/dist/src/lib/federation-retry-row.js +101 -0
- package/dist/src/lib/instruction-event-contract.js +17 -0
- package/dist/src/lib/key-dir.js +203 -0
- package/dist/src/lib/memory-attributes.js +2 -0
- package/dist/src/lib/open-live-row.js +20 -0
- package/dist/src/lib/scheduler-platform.js +13 -0
- package/dist/src/lib/soul-scope-fields.js +26 -0
- package/dist/src/rem/promote-policy.js +3 -3
- package/dist/src/rem/scheduler.js +21 -4
- package/docs/access-control.md +39 -21
- package/docs/api-reference.md +161 -52
- package/docs/auth.md +69 -38
- package/docs/claude-code.md +3 -3
- package/docs/deploying-on-fabric.md +118 -2
- package/docs/deployment.md +17 -0
- package/docs/embedding-in-a-harper-app.md +23 -21
- package/docs/entity-vocabulary.md +7 -11
- package/docs/federation.md +29 -2
- package/docs/hosted-on-fabric.md +1 -1
- package/docs/integrations.md +11 -11
- package/docs/mcp-clients.md +7 -5
- package/docs/notes/mcp-agent-auth-consumer.md +4 -9
- package/docs/notes/mcp-oauth-model2.md +6 -6
- package/docs/openclaw.md +1 -1
- package/docs/quickstart-fabric.md +2 -2
- package/docs/quickstart.md +3 -3
- package/docs/releasing.md +13 -13
- package/docs/rem.md +24 -3
- package/docs/secrets-and-keys.md +9 -14
- package/docs/standalone-local.md +29 -2
- package/docs/supply-chain-policy.md +28 -20
- package/docs/the-team.md +2 -2
- package/docs/upgrade.md +29 -5
- package/package.json +18 -11
- package/schemas/agent.graphql +3 -3
- package/schemas/federation.graphql +10 -7
- package/schemas/memory.graphql +7 -2
- package/templates/bin/flair-rem-nightly.sh.tmpl +7 -1
- package/templates/launchd/start-flair-with-admin-pass.sh +188 -10
- package/dist/resources/soul-adk-guard.js +0 -68
package/dist/resources/Memory.js
CHANGED
|
@@ -6,7 +6,7 @@ import { isOperatorSeedPut, redactMemoryWrite, redactSkillWrite, storedMemoryTex
|
|
|
6
6
|
import { REDACTION_RULES, buildFromAllowlist, storageResult, withheldWriteResult, writeResultResponse } from "./memory-write-response.js";
|
|
7
7
|
import { isDeepStrictEqual } from "node:util";
|
|
8
8
|
import { patchRecord, withDetachedTxn } from "./table-helpers.js";
|
|
9
|
-
import {
|
|
9
|
+
import { annotatedCallerIsAdmin, resolveAgentAuth } from "./agent-auth.js";
|
|
10
10
|
import { guardAuthorityFields } from "./authority-field-guard.js";
|
|
11
11
|
import { isForbiddenOwnerMutation } from "./record-owner-guard.js";
|
|
12
12
|
import { guardOwnerFieldImmutable } from "./owner-field-guard.js";
|
|
@@ -17,20 +17,23 @@ import { isEmbeddingSpaceUniform, noteWriteStamp } from "./embedding-space-guard
|
|
|
17
17
|
import { scanFields, isStrictMode } from "./content-safety.js";
|
|
18
18
|
import { invalidEntitiesResponse } from "./entity-vocab.js";
|
|
19
19
|
import { checkRateLimit, rateLimitResponse } from "./rate-limiter.js";
|
|
20
|
+
import { isOpenLiveRow } from "../src/lib/open-live-row.js";
|
|
20
21
|
import { assertValidVisibility, assertVisibilityAllowedForDurability, PRIVATE_VISIBILITY, SHARED_VISIBILITY } from "./memory-visibility.js";
|
|
21
22
|
import { validateHostSource } from "./host-source.js";
|
|
22
23
|
import { buildPointerRow, extractPointerInputs, isPointerEchoOf, loadStoredPointer, projectRowsThroughPointers, } from "./memory-host-source.js";
|
|
23
|
-
import { putPointerRow, deletePointerRowViaTable } from "./host-pointer-adapter.js";
|
|
24
|
+
import { putPointerRow, deletePointerRowViaTable, restorePointerRowIfAbsent, PointerAlreadyStoredError } from "./host-pointer-adapter.js";
|
|
24
25
|
import { DECLARED_MEMORY_ATTRIBUTES, stripUndeclaredMemoryAttributes, stripServerStampedFields } from "./memory-declared-attributes.js";
|
|
25
26
|
import { composesCallerWrite, isJoinableTransaction, withOwnedTransaction, withSharedWriteTransaction } from "./request-transaction.js";
|
|
26
27
|
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,
|
|
28
|
+
import { CommittedRowChanged, GrantedCloseRevoked, confirmCommittedRow, grantedCloseRevokedRefusal, sameStoredRow, storedRowChangedRefusal, verifyCommittedFields, withoutHarperManagedFields, writeGrantHeld } from "./write-back.js";
|
|
29
|
+
import { PAUSE_LIMIT_MS, txnFault, txnPausePoint } from "./txn-pause-point.js";
|
|
30
|
+
import { markMemoryWriteOutcomeUnknown, memoryWriteOutcomeUnknown, memoryLockRefusal, memoryBusyResponse, boundLockedProviderCall, memoryLockedProviderTimeoutMs, MemoryProviderTimeout, memoryProviderTimeoutResponse, withMemoryWriteLock, withMemoryWriteLockOnce, writeOutcomeUnknownResponse, MemoryWriteCapabilityError, memoryWriteLockTokenIds, } from "./memory-write-lock.js";
|
|
31
|
+
import { admitLockedMemoryWrite } from "./memory-write-transaction.js";
|
|
30
32
|
import { assertValidDurability, stampEphemeralExpiry } from "./memory-durability.js";
|
|
31
33
|
import { embedTextField, enforceSkillDurability, isSkillWrite, rejectSkillWritePath, refuseSkillWriteSource, skillEmbedText, skillScanGate, skillMetadataHasDuplicateKey } from "./skill-write.js";
|
|
32
34
|
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";
|
|
35
|
+
import { afterCloseStaged, buildSkillSuccessorRow, closedSkillPayloadReadable, defaultSkillHooks, grantedSkillClose, resolveSkillHead, rowIsSkill, runSkillVersionWrite, skillTargetSnapshotChanged, skillVersionVisibility, skillPayloadUnchanged, prepareSkillBody, validateSkillSnapshots, authorizeSkillOwners, skillWriteConflict } from "./skill-version-write.js";
|
|
36
|
+
import { SKILL_SUBJECT_TYPE, removeAppendedVersion } from "./instruction-version-record.js";
|
|
34
37
|
import { deriveSkillSubjectId } from "./skill-subject.js";
|
|
35
38
|
import { DEDUP_COSINE_THRESHOLD_DEFAULT, DEDUP_LEXICAL_THRESHOLD_DEFAULT, DEDUP_MIN_CONTENT_LENGTH, computeMatchConfidence, cosineSimilarity, isConservativeMatch, } from "./dedup.js";
|
|
36
39
|
import { buildProvenance, makeAuthGate, makeReadScope, makeByIdReadGate, makeScopedSearch, resolveAuthGate, stampAttribution, FORBIDDEN, UNAUTH, NOT_FOUND, } from "./record-type-kit.js";
|
|
@@ -39,11 +42,13 @@ import { RECORD_TYPES } from "./record-types.js";
|
|
|
39
42
|
import { attachTrust } from "./trust-block.js";
|
|
40
43
|
import { recordCitations } from "./usage-recording.js";
|
|
41
44
|
import { noteMemoryUpsert, noteMemoryDelete } from "./bm25-index-service.js";
|
|
42
|
-
import { recordMemoryDeletion } from "./memory-deletion-history.js";
|
|
45
|
+
import { recordMemoryDeletion, removeMemoryDeletionRecords } from "./memory-deletion-history.js";
|
|
43
46
|
import { applyHitStats, clearHitStats, overlayHitStatsResult } from "./hit-tracking.js";
|
|
47
|
+
import { applyPromotionBinding } from "./promotion-binding.js";
|
|
44
48
|
import { refuseStaleClientWrite, stripClientVersionPassthrough } from "./client-version-gate.js";
|
|
45
49
|
import { refuseReservedSeedWrite, reservedSeedWriteDenial, reservedSeedSubjectDenial, isReservedSeedId, writeTargetIds } from "./seed-reservation.js";
|
|
46
50
|
import { refuseContentSuffixId, resolveMemoryReferenceId, supersedesTargetMissing, supersedesTargetUnreadable } from "./memory-id-guard.js";
|
|
51
|
+
import { guardObjectBody } from "./object-body-guard.js";
|
|
47
52
|
/** flair#1940 A1' — a named 400 for an invalid host pointer (reject, never
|
|
48
53
|
* truncate). Same shape the pre-A1' inline checks returned. */
|
|
49
54
|
function hostSourceBadRequest(error, message) {
|
|
@@ -69,6 +74,16 @@ function withoutCallerSelection(query) {
|
|
|
69
74
|
delete copy.property;
|
|
70
75
|
return copy;
|
|
71
76
|
}
|
|
77
|
+
function projectMemoryRead(table, row, target, ctx, byId = false) {
|
|
78
|
+
if (row == null || row instanceof Response || typeof row !== "object")
|
|
79
|
+
return row;
|
|
80
|
+
const select = byId && table.loadAsInstance !== false && target?.property
|
|
81
|
+
? target.property : target?.select || target?.property;
|
|
82
|
+
if (!select)
|
|
83
|
+
return row;
|
|
84
|
+
const selected = table.transformEntryForSelect(select, ctx, table._readTxnForContext(ctx))({ key: row.id, value: row });
|
|
85
|
+
return byId && selected === null ? Response.json(null) : selected;
|
|
86
|
+
}
|
|
72
87
|
/**
|
|
73
88
|
* Write the Memory row joining transaction `c` (0a). Resource.prototype.post
|
|
74
89
|
* uses the instance's OWN `#context`, which an internal caller (a direct
|
|
@@ -187,6 +202,21 @@ function abortRequestTransaction(ctx) {
|
|
|
187
202
|
// failure MUST propagate rather than being swallowed behind a 500 body.
|
|
188
203
|
txn.abort();
|
|
189
204
|
}
|
|
205
|
+
const checkedEntries = new WeakMap();
|
|
206
|
+
/** The checked entry the body was handed, or null for an ordinary verb call. */
|
|
207
|
+
function takeCheckedEntry(entry) {
|
|
208
|
+
if (entry === undefined)
|
|
209
|
+
return null;
|
|
210
|
+
const checked = entry !== null && typeof entry === "object" ? checkedEntries.get(entry) : undefined;
|
|
211
|
+
if (!checked || checked.used)
|
|
212
|
+
throw new MemoryWriteCapabilityError("not_a_transaction", "not a checked Memory write entry");
|
|
213
|
+
checked.used = true;
|
|
214
|
+
return checked;
|
|
215
|
+
}
|
|
216
|
+
/** A checked write refuses a body that would leave its locked scope. */
|
|
217
|
+
function uncheckedBodyRefusal(what) {
|
|
218
|
+
return new MemoryWriteCapabilityError("transaction_mismatch", `a checked Memory write does not take the ${what} path`);
|
|
219
|
+
}
|
|
190
220
|
/**
|
|
191
221
|
* flair#2478 slice 1 — the `Memory.primaryStore` write-lock handle. Production
|
|
192
222
|
* is a real Harper table (a `primaryStore` with `tryLock`/`unlock`). A store
|
|
@@ -204,10 +234,98 @@ function putLockIds(resource, content) {
|
|
|
204
234
|
.filter((id) => typeof id === "string" || typeof id === "number")
|
|
205
235
|
.map((id) => String(id));
|
|
206
236
|
}
|
|
237
|
+
/** The lock ids a POST names: the addressed/body ids plus its `supersedes`
|
|
238
|
+
* reference, which post() has already resolved to its canonical id
|
|
239
|
+
* (canonicalizeSupersedes), the id the predecessor read and the close name.
|
|
240
|
+
* A pure create under a fresh server-allocated id names no id and takes no
|
|
241
|
+
* lock (the design's create case). */
|
|
242
|
+
function postLockIds(resource, content) {
|
|
243
|
+
const ids = putLockIds(resource, content);
|
|
244
|
+
const supersedes = content?.supersedes;
|
|
245
|
+
if (typeof supersedes === "string" || typeof supersedes === "number")
|
|
246
|
+
ids.push(String(supersedes));
|
|
247
|
+
return [...new Set(ids)];
|
|
248
|
+
}
|
|
249
|
+
/** The lock ids a DELETE names: the addressed id and any body id(s), dropping
|
|
250
|
+
* non-id values. For a skill row, delete() adds the live head it closes when
|
|
251
|
+
* its discovery read finds that head and it is another row. */
|
|
252
|
+
function deleteLockIds(resource, id) {
|
|
253
|
+
const ids = putLockIds(resource, id && typeof id === "object" ? id : undefined);
|
|
254
|
+
if (typeof id === "string" || typeof id === "number")
|
|
255
|
+
ids.push(String(id));
|
|
256
|
+
return ids;
|
|
257
|
+
}
|
|
258
|
+
/** Attempts of a DELETE to lock the live head its skill writer closes, when
|
|
259
|
+
* the head the writer resolves under the locks is not one of the held ids. */
|
|
260
|
+
const SKILL_DELETE_HEAD_ATTEMPTS = 3;
|
|
261
|
+
/** Bounds the retry loop that re-acquires the per-id Memory locks with the
|
|
262
|
+
* stored row and live head its read names, re-resolving after each
|
|
263
|
+
* acquisition (flair#2950). put() acquires once before it and hands the body
|
|
264
|
+
* to putSkillLocked, so a PUT makes up to one acquisition more than this;
|
|
265
|
+
* post() runs this loop from its first attempt. */
|
|
266
|
+
const SKILL_WRITE_HEAD_LOCK_ATTEMPTS = 3;
|
|
267
|
+
/** The ids a skill write's caller must add to its lock set before it retries.
|
|
268
|
+
* Returned by the writer and consumed by put()/post() on the next acquisition;
|
|
269
|
+
* it is never a write result. */
|
|
270
|
+
class SkillLockExtension {
|
|
271
|
+
ids;
|
|
272
|
+
constructor(ids) {
|
|
273
|
+
this.ids = ids;
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
/** Clone object bodies for lock retries (flair#2950). */
|
|
277
|
+
function replayWriteBody(content) {
|
|
278
|
+
return content === null || typeof content !== "object" ? content : structuredClone(content);
|
|
279
|
+
}
|
|
280
|
+
/** Check object bodies before PUT and named-id POST lock attempts. */
|
|
281
|
+
function uncloneableWriteBodyResponse(content) {
|
|
282
|
+
if (content === null || typeof content !== "object")
|
|
283
|
+
return null;
|
|
284
|
+
try {
|
|
285
|
+
structuredClone(content);
|
|
286
|
+
return null;
|
|
287
|
+
}
|
|
288
|
+
catch {
|
|
289
|
+
return Response.json({
|
|
290
|
+
error: "memory_body_uncloneable",
|
|
291
|
+
message: "the write body must be clonable for a lock retry; it carries a value that is not",
|
|
292
|
+
}, { status: 400 });
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
function skillLockExtension(value) {
|
|
296
|
+
return value instanceof SkillLockExtension ? value.ids : null;
|
|
297
|
+
}
|
|
298
|
+
function skillThen(value) {
|
|
299
|
+
const then = value && typeof value === "object" ? value.skillThen : null;
|
|
300
|
+
return typeof then === "function" ? then : null;
|
|
301
|
+
}
|
|
302
|
+
/** Discovery only, with no lock held: when the addressed row is a skill row,
|
|
303
|
+
* the live head a DELETE of it closes (resolveSkillHead), if that head is
|
|
304
|
+
* another row (an older version's DELETE closes its subject's head). `read`
|
|
305
|
+
* reads the addressed row as deleteLocked's first read does. A discovery read
|
|
306
|
+
* that fails, or finds more than one live head, adds no head. Either way the
|
|
307
|
+
* skill writer resolves the head again under the locks and writes only when
|
|
308
|
+
* that head is one of the held ids. */
|
|
309
|
+
async function skillDeleteHeadId(read) {
|
|
310
|
+
try {
|
|
311
|
+
const record = await read();
|
|
312
|
+
if (!record || !rowIsSkill(record))
|
|
313
|
+
return null;
|
|
314
|
+
const head = await resolveSkillHead(String(record.skillSubjectId ?? record.id), String(record.id), {});
|
|
315
|
+
return head && String(head.id) !== String(record.id) ? String(head.id) : null;
|
|
316
|
+
}
|
|
317
|
+
catch {
|
|
318
|
+
return null;
|
|
319
|
+
}
|
|
320
|
+
}
|
|
207
321
|
/** The caller id a lock-miss refusal carries — the request's agent annotation,
|
|
208
322
|
* else `anonymous`/`internal`. Never stored-row state (Sherlock S7). */
|
|
209
323
|
function memoryLockCallerId(resource) {
|
|
210
|
-
|
|
324
|
+
return memoryLockCallerIdFor(resource?.getContext?.());
|
|
325
|
+
}
|
|
326
|
+
/** {@link memoryLockCallerId} for a request context (flair#2478 part 3a: the
|
|
327
|
+
* archive takes the lock itself and answers its refusal with the same body). */
|
|
328
|
+
export function memoryLockCallerIdFor(ctx) {
|
|
211
329
|
const request = ctx?.request ?? ctx;
|
|
212
330
|
if (typeof request?.tpsAgent === "string" && request.tpsAgent.length > 0)
|
|
213
331
|
return request.tpsAgent;
|
|
@@ -215,16 +333,6 @@ function memoryLockCallerId(resource) {
|
|
|
215
333
|
return "anonymous";
|
|
216
334
|
return "internal";
|
|
217
335
|
}
|
|
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
336
|
/** PUT and PATCH require a target id before entering the lock helper. */
|
|
229
337
|
function memoryIdRequiredResponse() {
|
|
230
338
|
return new Response(JSON.stringify({
|
|
@@ -233,33 +341,42 @@ function memoryIdRequiredResponse() {
|
|
|
233
341
|
}), { status: 400, headers: { "content-type": "application/json" } });
|
|
234
342
|
}
|
|
235
343
|
/**
|
|
236
|
-
* The durable fields a post-commit read must still find at the value
|
|
237
|
-
* declared (flair#2478). A field the write did not declare is not compared
|
|
238
|
-
* stored value stands for it. `archived` is not compared: the maintenance
|
|
239
|
-
* flips it as a newer field-only write, which folds around this older full
|
|
344
|
+
* The durable fields a PUT's post-commit read must still find at the value the
|
|
345
|
+
* write declared (flair#2478). A field the write did not declare is not compared
|
|
346
|
+
* — the stored value stands for it. `archived` is not compared: the maintenance
|
|
347
|
+
* sweep flips it as a newer field-only write, which folds around this older full
|
|
240
348
|
* update instead of replacing it (flair#2470), so a differing `archived` is not
|
|
241
349
|
* evidence that this write did not land.
|
|
242
350
|
*/
|
|
243
351
|
const POSTCOMMIT_VERIFY_FIELDS = ["agentId", "content", "visibility", "durability"];
|
|
352
|
+
/** Fields a PATCH body may carry but the server owns (it strips, restores or
|
|
353
|
+
* stamps them, so the request does not declare their application). */
|
|
354
|
+
const PATCH_SERVER_OWNED_FIELDS = new Set([
|
|
355
|
+
"id",
|
|
356
|
+
"instanceToken",
|
|
357
|
+
"provenance",
|
|
358
|
+
"skillSubjectId",
|
|
359
|
+
"originatorInstanceId",
|
|
360
|
+
"embeddedContentHash",
|
|
361
|
+
"promotionStatus",
|
|
362
|
+
"promotedAt",
|
|
363
|
+
"promotedBy",
|
|
364
|
+
]);
|
|
365
|
+
/** Request field names retained before server additions; values come from the staged write. */
|
|
366
|
+
function patchDeclaredFields(content) {
|
|
367
|
+
if (!content || typeof content !== "object" || Array.isArray(content))
|
|
368
|
+
return [];
|
|
369
|
+
return Object.keys(content).filter((field) => !PATCH_SERVER_OWNED_FIELDS.has(field));
|
|
370
|
+
}
|
|
244
371
|
function sameDeclaredField(stored, declared) {
|
|
245
|
-
|
|
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;
|
|
372
|
+
return isDeepStrictEqual(stored, declared);
|
|
253
373
|
}
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
* missing id yields an unknown outcome (503).
|
|
261
|
-
*/
|
|
262
|
-
async function verifyCommittedWrite(table, declared, fallbackId, identity) {
|
|
374
|
+
async function pausePostVerification(skill) {
|
|
375
|
+
const pause = skill ? txnPausePoint("memory-post-skill-verify") : txnPausePoint("memory-post-verify");
|
|
376
|
+
if (pause)
|
|
377
|
+
await pause;
|
|
378
|
+
}
|
|
379
|
+
async function verifyWrittenRow(table, declared, fallbackId, identity, fields = POSTCOMMIT_VERIFY_FIELDS, checked) {
|
|
263
380
|
const id = declared?.id ?? fallbackId;
|
|
264
381
|
if (id === undefined || id === null)
|
|
265
382
|
return { unknown: true };
|
|
@@ -274,23 +391,119 @@ async function verifyCommittedWrite(table, declared, fallbackId, identity) {
|
|
|
274
391
|
return { mismatch: true };
|
|
275
392
|
if ((row.instanceToken ?? null) !== (identity.expectedToken ?? null))
|
|
276
393
|
return { mismatch: true };
|
|
277
|
-
for (const field of
|
|
394
|
+
for (const field of fields) {
|
|
278
395
|
if (!Object.prototype.hasOwnProperty.call(declared, field))
|
|
279
396
|
continue;
|
|
280
397
|
if (!sameDeclaredField(row[field], declared[field]))
|
|
281
398
|
return { mismatch: true };
|
|
282
399
|
}
|
|
400
|
+
// flair#2478 part 3a: a checked write also confirms the row's id and its
|
|
401
|
+
// `exactFields`, whether or not the write declared them: a field that reads
|
|
402
|
+
// as undefined in the staged write must read as undefined in the row, and a
|
|
403
|
+
// defined one must be equal (a null is a value).
|
|
404
|
+
if (checked) {
|
|
405
|
+
if (String(row.id) !== String(id))
|
|
406
|
+
return { mismatch: true };
|
|
407
|
+
for (const field of checked.exactFields) {
|
|
408
|
+
const staged = declared?.[field];
|
|
409
|
+
if ((row[field] === undefined) !== (staged === undefined))
|
|
410
|
+
return { mismatch: true };
|
|
411
|
+
if (staged !== undefined && !sameDeclaredField(row[field], staged))
|
|
412
|
+
return { mismatch: true };
|
|
413
|
+
}
|
|
414
|
+
}
|
|
283
415
|
return {};
|
|
284
416
|
}
|
|
417
|
+
/** Attempts of an ordinary, non-skill Memory DELETE whose removal did not land. */
|
|
418
|
+
const DELETE_APPLY_ATTEMPTS = 3;
|
|
419
|
+
/**
|
|
420
|
+
* flair#2632 — 409 when an ordinary, non-skill Memory DELETE exhausts its
|
|
421
|
+
* removal attempts. The skill path closes the live head instead of removing it.
|
|
422
|
+
*/
|
|
423
|
+
function deleteNotAppliedRefusal(tableName, attempts) {
|
|
424
|
+
return new Response(JSON.stringify({
|
|
425
|
+
error: "delete_not_applied",
|
|
426
|
+
message: `${tableName} row removal was not applied after ${attempts} attempts; not deleted`,
|
|
427
|
+
}), { status: 409, headers: { "content-type": "application/json" } });
|
|
428
|
+
}
|
|
429
|
+
/** 500 when ordinary DELETE compensation cannot confirm history removal or
|
|
430
|
+
* the restored/preserved pointer's identity. */
|
|
431
|
+
function deleteCompensationFailure(message) {
|
|
432
|
+
return new Response(JSON.stringify({ error: "delete_compensation_failed", message }), { status: 500, headers: { "content-type": "application/json" } });
|
|
433
|
+
}
|
|
434
|
+
function sameDeleteTarget(row, target, ownerField) {
|
|
435
|
+
return row != null && String(row.id) === target.id &&
|
|
436
|
+
(row[ownerField] ?? null) === target.owner &&
|
|
437
|
+
(row.instanceToken ?? null) === target.token;
|
|
438
|
+
}
|
|
439
|
+
/**
|
|
440
|
+
* flair#2632 — remove failed history; for a captured pointer, preserve an
|
|
441
|
+
* existing pointer or restore it if absent, then verify identity.
|
|
442
|
+
*/
|
|
443
|
+
async function compensateDroppedRemoval(memoryId, historyId, pointerBefore, ctx) {
|
|
444
|
+
try {
|
|
445
|
+
if (historyId !== null) {
|
|
446
|
+
const left = await removeMemoryDeletionRecords([historyId], ctx);
|
|
447
|
+
if (left.length > 0) {
|
|
448
|
+
return deleteCompensationFailure("the deletion-history record of a row that was not deleted is still stored");
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
if (pointerBefore) {
|
|
452
|
+
let expected = await loadStoredPointer(memoryId, {});
|
|
453
|
+
if (!expected) {
|
|
454
|
+
const pause = txnPausePoint("memory-delete-pointer-restore");
|
|
455
|
+
if (pause)
|
|
456
|
+
await pause;
|
|
457
|
+
try {
|
|
458
|
+
await withOwnedTransaction(ctx, async (c) => {
|
|
459
|
+
expected = await loadStoredPointer(memoryId, c);
|
|
460
|
+
if (!expected) {
|
|
461
|
+
await restorePointerRowIfAbsent(pointerBefore, c);
|
|
462
|
+
const staged = txnPausePoint("memory-delete-pointer-restore-staged");
|
|
463
|
+
if (staged)
|
|
464
|
+
await staged;
|
|
465
|
+
expected = pointerBefore;
|
|
466
|
+
}
|
|
467
|
+
});
|
|
468
|
+
}
|
|
469
|
+
catch (err) {
|
|
470
|
+
if (!(err instanceof PointerAlreadyStoredError))
|
|
471
|
+
throw err;
|
|
472
|
+
expected = err.pointer;
|
|
473
|
+
}
|
|
474
|
+
}
|
|
475
|
+
const resulting = await loadStoredPointer(memoryId, {});
|
|
476
|
+
const fields = ["memoryId", "hostSource", "scopeAtWrite", "authorId", "memoryInstanceToken", "receivedAt"];
|
|
477
|
+
if (!resulting || fields.some((field) => resulting[field] !== expected?.[field])) {
|
|
478
|
+
return deleteCompensationFailure("the restored or preserved host-pointer identity could not be confirmed");
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
return null;
|
|
482
|
+
}
|
|
483
|
+
catch (err) {
|
|
484
|
+
console.error("Memory.delete: undoing a removal that did not land failed", err);
|
|
485
|
+
return deleteCompensationFailure("the partial writes of a delete that did not land could not be undone");
|
|
486
|
+
}
|
|
487
|
+
}
|
|
285
488
|
/** Mark the id after a failed post-commit verification read (flair#2478). */
|
|
286
489
|
function writeOutcomeUnknownFor(id) {
|
|
287
490
|
if (typeof id === "string" || typeof id === "number")
|
|
288
491
|
markMemoryWriteOutcomeUnknown(id);
|
|
289
492
|
return writeOutcomeUnknownResponse();
|
|
290
493
|
}
|
|
291
|
-
/** Refuse a provider call still pending when the timeout callback runs, or settling after the bound.
|
|
292
|
-
|
|
293
|
-
|
|
494
|
+
/** Refuse a provider call still pending when the timeout callback runs, or settling after the bound.
|
|
495
|
+
* `pausePoint` (test-only, inert unless the fault-injection opt-in is set and
|
|
496
|
+
* armed) holds the provider call inside its bound; the pause's own limit
|
|
497
|
+
* outlasts the bound, so an armed pause ends in the bound's refusal. */
|
|
498
|
+
function embedUnderLock(text, pausePoint) {
|
|
499
|
+
return boundLockedProviderCall(async () => {
|
|
500
|
+
if (pausePoint) {
|
|
501
|
+
const pause = pausePoint(memoryLockedProviderTimeoutMs() + PAUSE_LIMIT_MS);
|
|
502
|
+
if (pause)
|
|
503
|
+
await pause;
|
|
504
|
+
}
|
|
505
|
+
return getEmbedding(text, "document");
|
|
506
|
+
});
|
|
294
507
|
}
|
|
295
508
|
/**
|
|
296
509
|
* flair#1940 A1' item 2 — persist the pointer row in the SAME request
|
|
@@ -424,13 +637,9 @@ const memoryAuthGate = makeAuthGate();
|
|
|
424
637
|
* Memory.post() directly, got ZERO dedup checking. Moving the gate here makes
|
|
425
638
|
* it apply uniformly regardless of transport (HTTP PUT vs in-process post()).
|
|
426
639
|
*
|
|
427
|
-
* NOTE on HTTP verbs:
|
|
428
|
-
*
|
|
429
|
-
*
|
|
430
|
-
* `Memory.post()` IS reachable, but only via an in-process resource
|
|
431
|
-
* instantiation (as resources/mcp-tools.ts does) — never via the real HTTP
|
|
432
|
-
* POST route. Because flair-client's write() (used by flair-mcp, the CLI, and
|
|
433
|
-
* every other integration package) issues an HTTP PUT, the actual
|
|
640
|
+
* NOTE on HTTP verbs: `Memory.post()` is reached by an HTTP POST /Memory and
|
|
641
|
+
* by an in-process resource instantiation (as resources/mcp-tools.ts does).
|
|
642
|
+
* Because flair-client's write() issues an HTTP PUT, the actual
|
|
434
643
|
* field-observed bug (#526) flows through Memory.put(), not Memory.post().
|
|
435
644
|
* The gate below is therefore a SHARED helper invoked from both post() and
|
|
436
645
|
* put() — anchored in the same place the design calls out (Memory.post), but
|
|
@@ -849,20 +1058,55 @@ async function closeSupersededRecord(ctx, oldId, patch, expectedOwner) {
|
|
|
849
1058
|
* lastReflected keys off updatedAt (the write moment), NOT createdAt — since
|
|
850
1059
|
* #1336 a create may carry a backdated caller createdAt, and the reflection
|
|
851
1060
|
* bookkeeping must record when the derivation actually ran.
|
|
1061
|
+
*
|
|
1062
|
+
* flair#2478 slice 3b: each stamp takes the source id's per-id Memory write
|
|
1063
|
+
* lock, once and without waiting, and reads the committed row under it. A held
|
|
1064
|
+
* id, an outcome-unknown marker or a store with no lock skips that source and
|
|
1065
|
+
* reports it; the stamp is an automatic writer, and its incremental update
|
|
1066
|
+
* preserves the owner's other fields while updating `lastReflected`. The patch
|
|
1067
|
+
* is an incremental update of `lastReflected`, decided on the committed row,
|
|
1068
|
+
* and confirmed on the committed row after the commit.
|
|
852
1069
|
*/
|
|
853
1070
|
async function markDerivedSourcesReflected(content) {
|
|
854
1071
|
if (!Array.isArray(content.derivedFrom) || content.derivedFrom.length === 0)
|
|
855
1072
|
return;
|
|
856
1073
|
const now = content.updatedAt;
|
|
1074
|
+
const table = databases.flair.Memory;
|
|
857
1075
|
for (const sourceId of content.derivedFrom) {
|
|
858
1076
|
try {
|
|
859
|
-
const
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
await
|
|
864
|
-
|
|
865
|
-
|
|
1077
|
+
const reflectPatch = { lastReflected: now };
|
|
1078
|
+
stripUndeclaredMemoryAttributes(reflectPatch);
|
|
1079
|
+
const outcome = await withMemoryWriteLockOnce(memoryWriteLockStore(), [String(sourceId)], async () => {
|
|
1080
|
+
// The committed row, read under the lock.
|
|
1081
|
+
const stored = await table.get(String(sourceId), {});
|
|
1082
|
+
if (stored == null)
|
|
1083
|
+
return { kind: "gone" };
|
|
1084
|
+
try {
|
|
1085
|
+
await patchRecord(databases.flair.Memory, String(sourceId), reflectPatch, {
|
|
1086
|
+
pausePre: () => txnPausePoint("last-reflected-pre"),
|
|
1087
|
+
pausePoint: () => txnPausePoint("last-reflected"),
|
|
1088
|
+
pauseAfterStage: () => txnPausePoint("last-reflected-staged"),
|
|
1089
|
+
pauseBeforeCommit: () => txnPausePoint("last-reflected-commit"),
|
|
1090
|
+
expectedRow: stored,
|
|
1091
|
+
});
|
|
1092
|
+
}
|
|
1093
|
+
catch (err) {
|
|
1094
|
+
console.warn("[Memory] lastReflected stamp skipped for %s (write-back refused: %s)", String(sourceId), err?.name ?? "error");
|
|
1095
|
+
return { kind: "failed" };
|
|
1096
|
+
}
|
|
1097
|
+
const verdict = await verifyCommittedFields(table, String(sourceId), stored, reflectPatch);
|
|
1098
|
+
if (verdict !== "shown") {
|
|
1099
|
+
console.warn("[Memory] lastReflected stamp skipped for %s (unconfirmed: %s)", String(sourceId), verdict);
|
|
1100
|
+
return { kind: "unconfirmed" };
|
|
1101
|
+
}
|
|
1102
|
+
// Test-only: the update committed and the lock is still held.
|
|
1103
|
+
const committed = txnPausePoint("last-reflected-committed");
|
|
1104
|
+
if (committed)
|
|
1105
|
+
await committed;
|
|
1106
|
+
return { kind: "stamped" };
|
|
1107
|
+
}, { phase: "last-reflected" });
|
|
1108
|
+
if (outcome.kind !== "done") {
|
|
1109
|
+
console.warn("[Memory] lastReflected stamp skipped for %s (%s)", String(sourceId), outcome.kind);
|
|
866
1110
|
}
|
|
867
1111
|
}
|
|
868
1112
|
catch { }
|
|
@@ -876,15 +1120,11 @@ async function hasWriteGrant(granteeId, ownerId, ctx) {
|
|
|
876
1120
|
return writeGrantHeld(databases.flair.MemoryGrant, granteeId, ownerId, ctx);
|
|
877
1121
|
}
|
|
878
1122
|
/**
|
|
879
|
-
* Shared by post() AND put():
|
|
880
|
-
*
|
|
881
|
-
*
|
|
882
|
-
*
|
|
883
|
-
*
|
|
884
|
-
* flair-client's write()/update() — used by flair-mcp, the CLI, and every
|
|
885
|
-
* other integration package — issue HTTP PUT, `supersedes` must be fully
|
|
886
|
-
* handled (validated, authorized, and closed) from BOTH entry points for the
|
|
887
|
-
* real-world write path to actually get the fix, not just the in-process one.
|
|
1123
|
+
* Shared by post() AND put(): Memory.post() is reached by an HTTP POST /Memory
|
|
1124
|
+
* and by an in-process resource instantiation (resources/mcp-tools.ts does
|
|
1125
|
+
* this), and flair-client's write()/update() issue HTTP PUT, so `supersedes`
|
|
1126
|
+
* must be fully handled (validated, authorized, and closed) from BOTH entry
|
|
1127
|
+
* points.
|
|
888
1128
|
*
|
|
889
1129
|
* Validates the `supersedes` field's shape and, for a cross-agent supersede,
|
|
890
1130
|
* requires a "write" MemoryGrant from the target's owner (reuses the existing
|
|
@@ -1191,12 +1431,45 @@ async function writeSkillCreateOrUpdate(args) {
|
|
|
1191
1431
|
const addressedId = storedRow ? String(storedRow.id) : explicitPredecessor ? String(explicitPredecessor.id) : null;
|
|
1192
1432
|
const captured = { row: null, closed: null };
|
|
1193
1433
|
let unchangedHead = null;
|
|
1194
|
-
|
|
1434
|
+
let joinsCaller = false;
|
|
1435
|
+
let successorBasis = null;
|
|
1436
|
+
// flair#2950: a skill create/update writes Memory rows too — its successor,
|
|
1437
|
+
// the row it addresses and the row it closes — so the verb takes the same
|
|
1438
|
+
// per-id Memory write lock as the feed path. A fresh skill POST with a
|
|
1439
|
+
// server-allocated id takes no per-id lock. Under the lock this writer
|
|
1440
|
+
// resolves the live head; a head outside the held set is reported so the
|
|
1441
|
+
// verb can re-plan with it.
|
|
1442
|
+
const runSkillWrite = (heldIds, headMoved) => runSkillVersionWrite({
|
|
1195
1443
|
ctx,
|
|
1444
|
+
// A POST that SUPERSEDES an existing target plans in a fresh OWNED
|
|
1445
|
+
// transaction (flair#3170): the joined request transaction's reads can
|
|
1446
|
+
// predate a commit the verb's target read already saw (a previous write's
|
|
1447
|
+
// embedding backfill), and the stale-target check would refuse the retry.
|
|
1448
|
+
// An in-place reserved seed POST supersedes nothing and joins the caller's
|
|
1449
|
+
// transaction when one is open and joinable, so a caller abort still
|
|
1450
|
+
// undoes it.
|
|
1451
|
+
joinCallerTransaction: method === "post" && (!storedRow || inPlaceId != null),
|
|
1196
1452
|
subjectId,
|
|
1197
1453
|
agentId: String(content.agentId),
|
|
1454
|
+
deferConfirmation: true,
|
|
1455
|
+
heldMemoryIds: [...heldIds],
|
|
1198
1456
|
head: (shared) => resolveSkillHead(subjectId, addressedId, shared),
|
|
1199
|
-
plan: async (head, shared) => {
|
|
1457
|
+
plan: async (head, shared, attempt) => {
|
|
1458
|
+
if (head && !heldIds.has(String(head.id))) {
|
|
1459
|
+
headMoved.id = String(head.id);
|
|
1460
|
+
return skillWriteConflict("skill_head_moved");
|
|
1461
|
+
}
|
|
1462
|
+
// A superseding plan from a joined attempt is planned again, owned
|
|
1463
|
+
// (flair#2645); no state from the earlier attempt carries over.
|
|
1464
|
+
joinsCaller = attempt.joined;
|
|
1465
|
+
captured.row = null;
|
|
1466
|
+
captured.closed = null;
|
|
1467
|
+
unchangedHead = null;
|
|
1468
|
+
successorBasis = null;
|
|
1469
|
+
if (args.staged) {
|
|
1470
|
+
delete args.staged.row;
|
|
1471
|
+
delete args.staged.joined;
|
|
1472
|
+
}
|
|
1200
1473
|
const stale = await validateSkillSnapshots(storedRow, explicitPredecessor, content.id ?? null, shared);
|
|
1201
1474
|
const denied = await authorizeSkillOwners(ctx, auth, [storedRow, explicitPredecessor, head ?? content], shared);
|
|
1202
1475
|
if (denied)
|
|
@@ -1232,6 +1505,13 @@ async function writeSkillCreateOrUpdate(args) {
|
|
|
1232
1505
|
}
|
|
1233
1506
|
await applyOriginatorInstanceId(successor, liveHead);
|
|
1234
1507
|
applyFederationBookkeeping(successor, liveHead);
|
|
1508
|
+
normalizeEmptyEmbedding(successor);
|
|
1509
|
+
if (joinsCaller)
|
|
1510
|
+
successorBasis = await databases.flair.Memory.get(successorId, shared);
|
|
1511
|
+
if (args.staged) {
|
|
1512
|
+
args.staged.row = structuredClone(successor);
|
|
1513
|
+
args.staged.joined = joinsCaller;
|
|
1514
|
+
}
|
|
1235
1515
|
captured.row = successor;
|
|
1236
1516
|
const value = typeof successor.content === "string" ? successor.content : null;
|
|
1237
1517
|
const visibility = skillVersionVisibility(successor);
|
|
@@ -1247,18 +1527,83 @@ async function writeSkillCreateOrUpdate(args) {
|
|
|
1247
1527
|
},
|
|
1248
1528
|
hooks: {
|
|
1249
1529
|
...defaultSkillHooks,
|
|
1530
|
+
authorizeClose: (row, shared) => authorizeSkillOwners(ctx, auth, [row], shared),
|
|
1250
1531
|
pointer: async (shared) => {
|
|
1532
|
+
// Test-only: holds a skill POST after its successor (and predecessor
|
|
1533
|
+
// close) are staged, before the transaction commits (flair#2656).
|
|
1534
|
+
const stagedPause = txnPausePoint("memory-post-skill-staged");
|
|
1535
|
+
if (stagedPause)
|
|
1536
|
+
await stagedPause;
|
|
1251
1537
|
if (captured.closed) {
|
|
1252
1538
|
const denial = await deletePointerRow(String(captured.closed.id), shared);
|
|
1253
1539
|
if (denial)
|
|
1254
1540
|
return denial;
|
|
1255
1541
|
}
|
|
1256
|
-
|
|
1257
|
-
? persistPointerRow({ ...pointer.row, memoryId: successorId, memoryInstanceToken: captured.row?.instanceToken }, shared)
|
|
1542
|
+
const pointerDenial = pointer?.row
|
|
1543
|
+
? await persistPointerRow({ ...pointer.row, memoryId: successorId, memoryInstanceToken: captured.row?.instanceToken }, shared)
|
|
1258
1544
|
: null;
|
|
1545
|
+
if (pointerDenial)
|
|
1546
|
+
return pointerDenial;
|
|
1547
|
+
if (joinsCaller) {
|
|
1548
|
+
await pausePostVerification(true);
|
|
1549
|
+
const committed = await databases.flair.Memory.get(successorId, {});
|
|
1550
|
+
// A skill write keeps its own target-changed refusal (flair#2263).
|
|
1551
|
+
if (!sameStoredRow(committed, successorBasis))
|
|
1552
|
+
return skillWriteConflict("skill_target_changed");
|
|
1553
|
+
}
|
|
1554
|
+
return null;
|
|
1259
1555
|
},
|
|
1260
1556
|
},
|
|
1261
1557
|
});
|
|
1558
|
+
// The plan's rows: the stored row this write addresses, and the live head
|
|
1559
|
+
// when the addressed version is closed. The verb holds the addressed id
|
|
1560
|
+
// before its read; a head only a read can name is returned for the next
|
|
1561
|
+
// acquisition. The writer's head check adds the explicit predecessor it
|
|
1562
|
+
// validates and closes, so both are held before the write. A server-allocated
|
|
1563
|
+
// successor names no stored row until this write creates it, so it is not
|
|
1564
|
+
// held. A pure create under a fresh server-allocated id writes no row another
|
|
1565
|
+
// writer can name, so it takes no per-id lock (the design's create case).
|
|
1566
|
+
// Under the locks the head is resolved again; a head outside the held set is
|
|
1567
|
+
// refused, so a moved or vanished head is never written through.
|
|
1568
|
+
const heldIds = new Set((args.held?.ids ?? []).map(String));
|
|
1569
|
+
const pureCreate = !addressedId && !explicitPredecessor && !inPlaceId && content.id == null;
|
|
1570
|
+
if (!pureCreate) {
|
|
1571
|
+
// A server-allocated successor id is not required: it names no stored row
|
|
1572
|
+
// until this write creates it. A stored row this write addresses is.
|
|
1573
|
+
const rows = storedRow ? [String(storedRow.id)] : [];
|
|
1574
|
+
const missing = rows.filter((id) => id.length > 0 && !heldIds.has(id));
|
|
1575
|
+
if (missing.length > 0)
|
|
1576
|
+
return new SkillLockExtension(missing);
|
|
1577
|
+
}
|
|
1578
|
+
// The addressed version (or an explicit predecessor) is closed, so the row
|
|
1579
|
+
// this write closes is the subject's live head. Only a head read names it;
|
|
1580
|
+
// return that read to the verb so the head is held before the instruction
|
|
1581
|
+
// lock, not after it.
|
|
1582
|
+
const addressedClosed = (storedRow && !isOpenLiveRow(storedRow)) ||
|
|
1583
|
+
(!storedRow && explicitPredecessor && !isOpenLiveRow(explicitPredecessor));
|
|
1584
|
+
if (addressedClosed && addressedId) {
|
|
1585
|
+
// The head this write closes is named only by a read. A head the attempt
|
|
1586
|
+
// does not hold is returned for the next acquisition; when there is none
|
|
1587
|
+
// (a deleted head), the plan below refuses with main's 409.
|
|
1588
|
+
let head = null;
|
|
1589
|
+
try {
|
|
1590
|
+
head = await resolveSkillHead(subjectId, addressedId, {});
|
|
1591
|
+
}
|
|
1592
|
+
catch {
|
|
1593
|
+
/* the plan's read under the locks decides */
|
|
1594
|
+
}
|
|
1595
|
+
if (head && !heldIds.has(String(head.id)))
|
|
1596
|
+
return new SkillLockExtension([String(head.id)]);
|
|
1597
|
+
}
|
|
1598
|
+
const headMoved = { id: null };
|
|
1599
|
+
// Test-only: holds a skill POST before its plan runs under the lock, after
|
|
1600
|
+
// the verb read its target (flair#3170).
|
|
1601
|
+
const planPause = txnPausePoint("memory-post-skill-plan");
|
|
1602
|
+
if (planPause)
|
|
1603
|
+
await planPause;
|
|
1604
|
+
const outcome = await runSkillWrite(heldIds, headMoved);
|
|
1605
|
+
if (headMoved.id)
|
|
1606
|
+
return new SkillLockExtension([headMoved.id]);
|
|
1262
1607
|
if (!outcome.ok)
|
|
1263
1608
|
return outcome.response;
|
|
1264
1609
|
if (captured.closed)
|
|
@@ -1272,12 +1617,162 @@ async function writeSkillCreateOrUpdate(args) {
|
|
|
1272
1617
|
}
|
|
1273
1618
|
if (args.staged)
|
|
1274
1619
|
args.staged.text = captured.row ? storedMemoryText(captured.row, args.staged.supplied) : null;
|
|
1275
|
-
return {
|
|
1620
|
+
return {
|
|
1621
|
+
id: successorId,
|
|
1622
|
+
written: captured.row !== null,
|
|
1623
|
+
visibility: skillVersionVisibility(captured.row ?? unchangedHead),
|
|
1624
|
+
confirm: "confirm" in outcome ? outcome.confirm : undefined,
|
|
1625
|
+
};
|
|
1626
|
+
}
|
|
1627
|
+
/** Attempts at re-applying a skill close whose committed write did not land (flair#2642). */
|
|
1628
|
+
const SKILL_DELETE_CLOSE_ATTEMPTS = 3;
|
|
1629
|
+
/** The named 500 for unconfirmed skill-close compensation. */
|
|
1630
|
+
function skillDeleteCompensationFailure(message) {
|
|
1631
|
+
return Response.json({ error: "skill_delete_compensation_failed", message }, { status: 500 });
|
|
1632
|
+
}
|
|
1633
|
+
/** The named 500 for a confirmation read that failed: the close is unverified, never success. */
|
|
1634
|
+
function skillDeleteUnconfirmedFailure() {
|
|
1635
|
+
return Response.json({
|
|
1636
|
+
error: "skill_delete_unconfirmed",
|
|
1637
|
+
message: "the committed skill row could not be read; the delete is unverified",
|
|
1638
|
+
}, { status: 500 });
|
|
1639
|
+
}
|
|
1640
|
+
/** The named 409 for a skill DELETE whose version close still is not visible after the bounded re-applies. */
|
|
1641
|
+
function skillDeleteNotClosedRefusal(attempts) {
|
|
1642
|
+
return Response.json({
|
|
1643
|
+
error: "skill_delete_not_closed",
|
|
1644
|
+
message: `the skill version close was not applied after ${attempts} attempts; not deleted`,
|
|
1645
|
+
}, { status: 409 });
|
|
1646
|
+
}
|
|
1647
|
+
/** Compensate an unlanded close. */
|
|
1648
|
+
async function compensateUnlandedSkillClose(args) {
|
|
1649
|
+
const { ctx, subjectId, closedId, closeVersionId, pointerBefore } = args;
|
|
1650
|
+
try {
|
|
1651
|
+
const removal = await removeAppendedVersion(ctx, SKILL_SUBJECT_TYPE, subjectId, closeVersionId);
|
|
1652
|
+
if (removal !== "removed") {
|
|
1653
|
+
return skillDeleteCompensationFailure("removal of the close version record could not be confirmed");
|
|
1654
|
+
}
|
|
1655
|
+
if (pointerBefore) {
|
|
1656
|
+
let expected = await loadStoredPointer(closedId, {});
|
|
1657
|
+
let pointerOutcome = "left_in_place";
|
|
1658
|
+
if (!expected) {
|
|
1659
|
+
const pause = txnPausePoint("skill-delete-pointer-restore");
|
|
1660
|
+
if (pause)
|
|
1661
|
+
await pause;
|
|
1662
|
+
try {
|
|
1663
|
+
await withOwnedTransaction(ctx, async (c) => {
|
|
1664
|
+
expected = await loadStoredPointer(closedId, c);
|
|
1665
|
+
if (!expected) {
|
|
1666
|
+
await restorePointerRowIfAbsent(pointerBefore, c);
|
|
1667
|
+
const staged = txnPausePoint("skill-delete-pointer-restore-staged");
|
|
1668
|
+
if (staged)
|
|
1669
|
+
await staged;
|
|
1670
|
+
expected = pointerBefore;
|
|
1671
|
+
pointerOutcome = "restored";
|
|
1672
|
+
}
|
|
1673
|
+
});
|
|
1674
|
+
}
|
|
1675
|
+
catch (err) {
|
|
1676
|
+
if (!(err instanceof PointerAlreadyStoredError))
|
|
1677
|
+
throw err;
|
|
1678
|
+
expected = err.pointer;
|
|
1679
|
+
pointerOutcome = "left_in_place";
|
|
1680
|
+
}
|
|
1681
|
+
}
|
|
1682
|
+
const resulting = await loadStoredPointer(closedId, {});
|
|
1683
|
+
const fields = ["memoryId", "hostSource", "scopeAtWrite", "authorId", "memoryInstanceToken", "receivedAt"];
|
|
1684
|
+
if (!resulting || fields.some((field) => resulting[field] !== expected?.[field])) {
|
|
1685
|
+
return skillDeleteCompensationFailure("the restored or preserved host-pointer identity could not be confirmed");
|
|
1686
|
+
}
|
|
1687
|
+
return pointerOutcome;
|
|
1688
|
+
}
|
|
1689
|
+
return "not_needed";
|
|
1690
|
+
}
|
|
1691
|
+
catch (err) {
|
|
1692
|
+
console.error("Memory.delete: undoing an unapplied skill close failed", err);
|
|
1693
|
+
return skillDeleteCompensationFailure("compensation for the unapplied skill close could not be confirmed");
|
|
1694
|
+
}
|
|
1695
|
+
}
|
|
1696
|
+
/**
|
|
1697
|
+
* flair#2642 — a skill DELETE confirms the close in a fresh committed read
|
|
1698
|
+
* before answering success. Harper can resolve the close's commit while skipping
|
|
1699
|
+
* the queued full put (it loses to a newer write of the same row) and still
|
|
1700
|
+
* commit the tombstone and pointer writes. A close that did not land is
|
|
1701
|
+
* re-applied from a fresh read, re-checking the row's identity and the caller's
|
|
1702
|
+
* authority. Unconfirmed compensation answers 500.
|
|
1703
|
+
* Returns null only when the close is confirmed (or the row is gone).
|
|
1704
|
+
*/
|
|
1705
|
+
async function confirmSkillDelete(args) {
|
|
1706
|
+
const { ctx, auth, subjectId, closedId, closedRow, closeVersionId, pointerBefore, now } = args;
|
|
1707
|
+
const table = databases.flair.Memory;
|
|
1708
|
+
const undo = async (refusal) => {
|
|
1709
|
+
const compensation = await compensateUnlandedSkillClose({ ctx, subjectId, closedId, closeVersionId, pointerBefore });
|
|
1710
|
+
if (compensation instanceof Response)
|
|
1711
|
+
return compensation;
|
|
1712
|
+
return Response.json({ ...await refusal.json(), pointerCompensation: compensation }, { status: refusal.status });
|
|
1713
|
+
};
|
|
1714
|
+
for (let attempt = 1;; attempt++) {
|
|
1715
|
+
let committed;
|
|
1716
|
+
try {
|
|
1717
|
+
committed = await table.get(closedId, {});
|
|
1718
|
+
}
|
|
1719
|
+
catch {
|
|
1720
|
+
return skillDeleteUnconfirmedFailure();
|
|
1721
|
+
}
|
|
1722
|
+
if (!committed)
|
|
1723
|
+
return null;
|
|
1724
|
+
if (!sameStoredRow(committed, closedRow)) {
|
|
1725
|
+
// Replaced between the reads: not the row the caller meant.
|
|
1726
|
+
return undo(storedRowChangedRefusal("Memory"));
|
|
1727
|
+
}
|
|
1728
|
+
if (typeof committed.validTo === "string" && committed.validTo.length > 0)
|
|
1729
|
+
return null;
|
|
1730
|
+
if (attempt > SKILL_DELETE_CLOSE_ATTEMPTS)
|
|
1731
|
+
break;
|
|
1732
|
+
let applied;
|
|
1733
|
+
try {
|
|
1734
|
+
applied = await withOwnedTransaction(ctx, async (c) => {
|
|
1735
|
+
const stored = await table.get(closedId, c);
|
|
1736
|
+
if (!stored)
|
|
1737
|
+
return "staged";
|
|
1738
|
+
if (!sameStoredRow(stored, closedRow))
|
|
1739
|
+
return storedRowChangedRefusal("Memory");
|
|
1740
|
+
const denied = await authorizeSkillOwners(ctx, auth, [stored], c);
|
|
1741
|
+
if (denied)
|
|
1742
|
+
return denied;
|
|
1743
|
+
const closed = { ...stored, skillSubjectId: subjectId, validTo: now, updatedAt: now };
|
|
1744
|
+
normalizeEmptyEmbedding(closed);
|
|
1745
|
+
const result = storageResult(await table.put(closed, c));
|
|
1746
|
+
if (result instanceof Response)
|
|
1747
|
+
throw result;
|
|
1748
|
+
const pause = attempt === 1 ? txnPausePoint("skill-delete-retry-first")
|
|
1749
|
+
: attempt === 2 ? txnPausePoint("skill-delete-retry-second")
|
|
1750
|
+
: txnPausePoint("skill-delete-retry-third");
|
|
1751
|
+
if (pause)
|
|
1752
|
+
await pause;
|
|
1753
|
+
const revoked = await afterCloseStaged(grantedSkillClose(stored, ctx, auth));
|
|
1754
|
+
if (revoked)
|
|
1755
|
+
throw revoked;
|
|
1756
|
+
return "staged";
|
|
1757
|
+
});
|
|
1758
|
+
}
|
|
1759
|
+
catch (err) {
|
|
1760
|
+
if (err instanceof Response)
|
|
1761
|
+
applied = err;
|
|
1762
|
+
else
|
|
1763
|
+
return skillDeleteUnconfirmedFailure();
|
|
1764
|
+
}
|
|
1765
|
+
if (applied instanceof Response)
|
|
1766
|
+
return undo(applied);
|
|
1767
|
+
}
|
|
1768
|
+
return undo(skillDeleteNotClosedRefusal(SKILL_DELETE_CLOSE_ATTEMPTS));
|
|
1276
1769
|
}
|
|
1277
1770
|
/** Close the live head and delete its pointer in the version transaction. */
|
|
1278
1771
|
async function writeSkillDelete(args) {
|
|
1279
|
-
const { ctx, auth, record } = args;
|
|
1772
|
+
const { ctx, auth, record, headLock } = args;
|
|
1280
1773
|
let closedId = "";
|
|
1774
|
+
let closedRow = null;
|
|
1775
|
+
let pointerBefore = null;
|
|
1281
1776
|
const now = new Date().toISOString();
|
|
1282
1777
|
const subjectId = String(record.skillSubjectId ?? record.id);
|
|
1283
1778
|
const seedLineageDenial = reservedSeedSubjectDenial("Memory", [subjectId], ctx, auth);
|
|
@@ -1287,8 +1782,17 @@ async function writeSkillDelete(args) {
|
|
|
1287
1782
|
ctx,
|
|
1288
1783
|
subjectId,
|
|
1289
1784
|
agentId: String(record.agentId),
|
|
1785
|
+
heldMemoryIds: headLock?.ids,
|
|
1290
1786
|
head: (shared) => resolveSkillHead(subjectId, String(record.id), shared),
|
|
1291
1787
|
plan: async (head, shared) => {
|
|
1788
|
+
// flair#2478: the head this delete closes must be an id the DELETE holds.
|
|
1789
|
+
// A head outside the held ids is not locked: write nothing; delete()
|
|
1790
|
+
// discovers and locks again.
|
|
1791
|
+
if (headLock) {
|
|
1792
|
+
headLock.outside = !!head && !headLock.ids.includes(String(head.id));
|
|
1793
|
+
if (headLock.outside)
|
|
1794
|
+
return storedRowChangedRefusal("Memory");
|
|
1795
|
+
}
|
|
1292
1796
|
// flair#2355: for a non-admin caller, re-read the COMMITTED rows before
|
|
1293
1797
|
// the close. The delete is refused, and nothing is closed, when the
|
|
1294
1798
|
// addressed row is present with an owner other than the caller (409
|
|
@@ -1325,15 +1829,27 @@ async function writeSkillDelete(args) {
|
|
|
1325
1829
|
return writeOutcomeUnknownResponse();
|
|
1326
1830
|
const liveHead = head;
|
|
1327
1831
|
closedId = String(liveHead.id);
|
|
1832
|
+
closedRow = liveHead;
|
|
1833
|
+
// Captured for compensation: this attempt's pointer delete can land even
|
|
1834
|
+
// when its close does not.
|
|
1835
|
+
pointerBefore = await loadStoredPointer(closedId, shared);
|
|
1328
1836
|
// flair#2511: a stale id resolves the live head, which can be another
|
|
1329
1837
|
// agent's row a "write" grant authorizes this caller to close; the writer
|
|
1330
1838
|
// re-checks that grant after the close is staged.
|
|
1331
1839
|
return { kind: "delete", predecessor: liveHead, closePatch: { skillSubjectId: subjectId, validTo: now, updatedAt: now }, value: null, visibility: skillVersionVisibility(liveHead), grantedClose: grantedSkillClose(liveHead, ctx, auth) };
|
|
1332
1840
|
},
|
|
1333
|
-
hooks: { ...defaultSkillHooks, pointer: async (shared) => deletePointerRow(closedId, shared) },
|
|
1841
|
+
hooks: { ...defaultSkillHooks, authorizeClose: (row, shared) => authorizeSkillOwners(ctx, auth, [row], shared), pointer: async (shared) => deletePointerRow(closedId, shared) },
|
|
1334
1842
|
});
|
|
1335
1843
|
if (!outcome.ok)
|
|
1336
1844
|
return outcome.response;
|
|
1845
|
+
// flair#2642: the owned transaction has committed, but its success is not
|
|
1846
|
+
// proof that the queued close was applied. Confirm against the committed
|
|
1847
|
+
// store before answering success.
|
|
1848
|
+
const confirmation = await confirmSkillDelete({
|
|
1849
|
+
ctx, auth, subjectId, closedId, closedRow: closedRow, closeVersionId: outcome.version, pointerBefore, now,
|
|
1850
|
+
});
|
|
1851
|
+
if (confirmation)
|
|
1852
|
+
return confirmation;
|
|
1337
1853
|
noteMemoryDelete(closedId);
|
|
1338
1854
|
return new Response(JSON.stringify({ id: closedId, deleted: true }), {
|
|
1339
1855
|
status: 200, headers: { "Content-Type": "application/json" },
|
|
@@ -1372,7 +1888,8 @@ function storedInstanceToken(row) {
|
|
|
1372
1888
|
* If the stored text is no longer the text the vector was computed from, this
|
|
1373
1889
|
* recomputes from the stored text (at most REEMBED_WRITE_ATTEMPTS times).
|
|
1374
1890
|
* If the text keeps changing across the REEMBED_WRITE_ATTEMPTS attempts, it returns
|
|
1375
|
-
* reembed_row_changed (409) and writes nothing
|
|
1891
|
+
* reembed_row_changed (409) and writes nothing, when no attempt has committed
|
|
1892
|
+
* (otherwise 503 write_outcome_unknown, see flair#2478 below). A row absent at the attempt's
|
|
1376
1893
|
* own re-read, a row with no text, or a caller no longer authorized for the row
|
|
1377
1894
|
* is refused the same way the first read refused it.
|
|
1378
1895
|
*
|
|
@@ -1382,9 +1899,10 @@ function storedInstanceToken(row) {
|
|
|
1382
1899
|
* instanceToken, contentHash, createdAt) and the same embedding text, compared
|
|
1383
1900
|
* as text. A row gone or changed in either at confirmation aborts the owned
|
|
1384
1901
|
* transaction (the staged write is discarded) and the caller answers
|
|
1385
|
-
* stored_row_changed (409)
|
|
1386
|
-
*
|
|
1387
|
-
*
|
|
1902
|
+
* stored_row_changed (409) when no earlier attempt has committed, otherwise
|
|
1903
|
+
* 503 write_outcome_unknown (flair#2478 below). A same-id replacement with the same identity and
|
|
1904
|
+
* text passes. Post-commit verification retries surviving differences in
|
|
1905
|
+
* compared fields, identity or text from a fresh read within the attempt bound.
|
|
1388
1906
|
*
|
|
1389
1907
|
* The staged update also records `embeddedContentHash`, the newly computed hash
|
|
1390
1908
|
* of the text the vector was computed from (null for an empty owner), so the
|
|
@@ -1395,10 +1913,50 @@ function storedInstanceToken(row) {
|
|
|
1395
1913
|
* calling PATCH can confirm after the commit that the row is still that one.
|
|
1396
1914
|
* The calling PATCH holds the row's per-id write lock across this write and its
|
|
1397
1915
|
* commit.
|
|
1916
|
+
*
|
|
1917
|
+
* flair#2478: once an attempt's commit has resolved and no read-back has shown
|
|
1918
|
+
* its write (the read-back mismatched, or a step after the commit, such as the
|
|
1919
|
+
* write-stamp notifier, threw before it), the row may hold that write. Every
|
|
1920
|
+
* exit of the call from then on, other than a later verified success, answers
|
|
1921
|
+
* `503 write_outcome_unknown` and marks the id outcome-unknown: a refusal, a
|
|
1922
|
+
* 409 (exhausted text changes or a change seen at a confirmation), a provider
|
|
1923
|
+
* timeout, an unusable vector, the final attempt's mismatch, or any thrown
|
|
1924
|
+
* error. The one exception is a later attempt whose fresh read finds no row:
|
|
1925
|
+
* no write of this call remains on one, so it answers 404 as before and does
|
|
1926
|
+
* not fence the id.
|
|
1398
1927
|
*/
|
|
1399
1928
|
async function reembedStoredRow(id, preRead, vector, auth, ctx) {
|
|
1929
|
+
// flair#2478: one guard over every attempt. Once an attempt's commit has
|
|
1930
|
+
// resolved and no read-back has shown its write, the call answers either the
|
|
1931
|
+
// verified success, the deleted-row 404, or write_outcome_unknown (marking
|
|
1932
|
+
// the id): the attempts settle their refusals through `settle`, and any
|
|
1933
|
+
// thrown error, the write-stamp notifier after a commit included, lands here.
|
|
1934
|
+
const state = { committedUnconfirmed: false };
|
|
1935
|
+
try {
|
|
1936
|
+
return await reembedAttempts(id, preRead, vector, auth, ctx, state);
|
|
1937
|
+
}
|
|
1938
|
+
catch (err) {
|
|
1939
|
+
if (!state.committedUnconfirmed)
|
|
1940
|
+
throw err;
|
|
1941
|
+
console.warn("[reembed] %s: a committed attempt's write is not confirmed; the call ended with an error (%s); outcome: unconfirmed", id, err?.name ?? "unknown");
|
|
1942
|
+
return { response: writeOutcomeUnknownFor(id) };
|
|
1943
|
+
}
|
|
1944
|
+
}
|
|
1945
|
+
/** The attempts of {@link reembedStoredRow}. `state.committedUnconfirmed` is set
|
|
1946
|
+
* when an attempt's commit resolves, before anything else runs, and stays set
|
|
1947
|
+
* unless that attempt's read-back shows the write (which answers success). */
|
|
1948
|
+
async function reembedAttempts(id, preRead, vector, auth, ctx, state) {
|
|
1400
1949
|
let textToEmbed = skillEmbedText(preRead);
|
|
1401
1950
|
let embedding = vector;
|
|
1951
|
+
// Every refusal of a later attempt, once a committed write is unconfirmed,
|
|
1952
|
+
// answers write_outcome_unknown and marks the id, never a refusal that says
|
|
1953
|
+
// nothing was written.
|
|
1954
|
+
const settle = (response, ended) => {
|
|
1955
|
+
if (!state.committedUnconfirmed)
|
|
1956
|
+
return { response };
|
|
1957
|
+
console.warn("[reembed] %s: a committed attempt's write is not confirmed; this attempt ended with %s; outcome: unconfirmed", id, ended);
|
|
1958
|
+
return { response: writeOutcomeUnknownFor(id) };
|
|
1959
|
+
};
|
|
1402
1960
|
for (let attempt = 1; attempt <= REEMBED_WRITE_ATTEMPTS; attempt++) {
|
|
1403
1961
|
let outcome;
|
|
1404
1962
|
try {
|
|
@@ -1429,7 +1987,8 @@ async function reembedStoredRow(id, preRead, vector, auth, ctx) {
|
|
|
1429
1987
|
// this same update; a row that has one keeps it.
|
|
1430
1988
|
const legacyToken = storedInstanceToken(stored) ? {} : { instanceToken: token };
|
|
1431
1989
|
// flair#2561: a Response from the storage layer is not reported (storageResult).
|
|
1432
|
-
const
|
|
1990
|
+
const reembedUpdate = { ...legacyToken, embedding, embeddingModel: model, updatedAt, embeddedContentHash: hashEmbeddedText(stored.agentId, textToEmbed) ?? null };
|
|
1991
|
+
const result = storageResult(await databases.flair.Memory.update(id, reembedUpdate, owned));
|
|
1433
1992
|
if (result instanceof Response)
|
|
1434
1993
|
return { kind: "withheld", response: result };
|
|
1435
1994
|
// Test-only: inert unless the fault-injection env opt-in is set and armed.
|
|
@@ -1444,10 +2003,11 @@ async function reembedStoredRow(id, preRead, vector, auth, ctx) {
|
|
|
1444
2003
|
// the vector was computed from (`textToEmbed`). The text check catches an
|
|
1445
2004
|
// edit that changed the text but no identity field. A row gone or changed
|
|
1446
2005
|
// at confirmation aborts this owned transaction, discarding the staged
|
|
1447
|
-
// write; the caller answers stored_row_changed (409)
|
|
2006
|
+
// write; the caller answers stored_row_changed (409), or write_outcome_unknown
|
|
2007
|
+
// when an earlier attempt committed unconfirmed. Only a text change
|
|
1448
2008
|
// is logged. Neither the staged vector, its hash, nor a staged legacy
|
|
1449
|
-
// token is written.
|
|
1450
|
-
//
|
|
2009
|
+
// token is written. Post-commit verification retries surviving
|
|
2010
|
+
// differences in compared fields, identity or text from a fresh read.
|
|
1451
2011
|
await confirmCommittedRow(databases.flair.Memory, id, (committed) => {
|
|
1452
2012
|
if (!sameStoredRow(committed, stored))
|
|
1453
2013
|
return false;
|
|
@@ -1457,54 +2017,104 @@ async function reembedStoredRow(id, preRead, vector, auth, ctx) {
|
|
|
1457
2017
|
}
|
|
1458
2018
|
return true;
|
|
1459
2019
|
});
|
|
1460
|
-
|
|
2020
|
+
// Test-only: inert unless the fault-injection env opt-in is set and
|
|
2021
|
+
// armed. Holds the re-embed after its final pre-commit confirmation and
|
|
2022
|
+
// before its owned transaction commits, the window where a newer write
|
|
2023
|
+
// can discard this write's effect (flair#2656).
|
|
2024
|
+
const commitPause = txnPausePoint("memory-reembed-commit");
|
|
2025
|
+
if (commitPause)
|
|
2026
|
+
await commitPause;
|
|
2027
|
+
// The identity is the row this update writes: a legacy row gains the
|
|
2028
|
+
// token this attempt stages.
|
|
2029
|
+
return { kind: "written", model, updatedAt, token, identity: { ...stored, instanceToken: token }, fields: reembedUpdate };
|
|
1461
2030
|
});
|
|
1462
2031
|
}
|
|
1463
2032
|
catch (err) {
|
|
1464
|
-
// The owned transaction was aborted by the throw;
|
|
2033
|
+
// The owned transaction was aborted by the throw; this attempt wrote
|
|
2034
|
+
// nothing (an earlier unconfirmed attempt may have; settle answers that).
|
|
1465
2035
|
if (err instanceof CommittedRowChanged)
|
|
1466
|
-
return
|
|
2036
|
+
return settle(storedRowChangedRefusal("Memory"), "stored_row_changed");
|
|
1467
2037
|
throw err;
|
|
1468
2038
|
}
|
|
1469
2039
|
if (outcome.kind === "withheld")
|
|
1470
|
-
return
|
|
1471
|
-
if (outcome.kind === "not_found")
|
|
2040
|
+
return settle(outcome.response, "a withheld storage result");
|
|
2041
|
+
if (outcome.kind === "not_found") {
|
|
2042
|
+
// The fresh read finds no row, so no write of this call remains on one:
|
|
2043
|
+
// 404 states that even after an earlier unconfirmed attempt, and the id is
|
|
2044
|
+
// not fenced (an outcome-unknown mark lasts until restart).
|
|
2045
|
+
if (state.committedUnconfirmed)
|
|
2046
|
+
console.warn("[reembed] %s: a committed attempt's write is not confirmed, but the row is now absent, so no write of this call remains on it; answered not_found", id);
|
|
1472
2047
|
return { response: NOT_FOUND() };
|
|
2048
|
+
}
|
|
1473
2049
|
if (outcome.kind === "forbidden")
|
|
1474
|
-
return
|
|
2050
|
+
return settle(FORBIDDEN("forbidden: cannot write memory owned by another agent"), "forbidden");
|
|
1475
2051
|
if (outcome.kind === "no_text") {
|
|
1476
|
-
return
|
|
2052
|
+
return settle(Response.json({ error: "reembed_no_text", message: "the stored row has no text to embed" }, { status: 422 }), "reembed_no_text");
|
|
1477
2053
|
}
|
|
1478
2054
|
if (outcome.kind === "recompute") {
|
|
1479
2055
|
if (attempt === REEMBED_WRITE_ATTEMPTS) {
|
|
1480
|
-
return
|
|
2056
|
+
return settle(Response.json({ error: "reembed_row_changed", message: "the stored text changed during each re-embed attempt; retry" }, { status: 409 }), "reembed_row_changed");
|
|
1481
2057
|
}
|
|
1482
2058
|
textToEmbed = outcome.text;
|
|
1483
2059
|
let recomputed;
|
|
1484
2060
|
try {
|
|
1485
|
-
|
|
2061
|
+
// Test-only pause point: inert unless the fault-injection opt-in is set
|
|
2062
|
+
// and armed; it holds this provider call inside its bound.
|
|
2063
|
+
recomputed = await embedUnderLock(textToEmbed, (limitMs) => txnPausePoint("memory-reembed-recompute", process.env, limitMs));
|
|
1486
2064
|
}
|
|
1487
2065
|
catch (err) {
|
|
1488
2066
|
if (err instanceof MemoryProviderTimeout)
|
|
1489
|
-
return
|
|
2067
|
+
return settle(memoryProviderTimeoutResponse(), "memory_provider_timeout");
|
|
1490
2068
|
throw err;
|
|
1491
2069
|
}
|
|
1492
2070
|
if (!isUsableEmbeddingVector(recomputed)) {
|
|
1493
|
-
return
|
|
2071
|
+
return settle(Response.json({ error: "embedding_unavailable", message: "the embedding engine returned no vector; the stored row is unchanged, retry" }, { status: 503 }), "embedding_unavailable");
|
|
1494
2072
|
}
|
|
1495
2073
|
embedding = recomputed;
|
|
1496
2074
|
continue;
|
|
1497
2075
|
}
|
|
2076
|
+
// The commit has resolved: until a read-back shows the write, every exit of
|
|
2077
|
+
// the call is settled as unknown (the notifier below included).
|
|
2078
|
+
state.committedUnconfirmed = true;
|
|
1498
2079
|
noteWriteStamp(outcome.model, preRead);
|
|
2080
|
+
const verifyPause = txnPausePoint("memory-reembed-verify");
|
|
2081
|
+
if (verifyPause)
|
|
2082
|
+
await verifyPause;
|
|
2083
|
+
// flair#2656: the commit is not proof the re-embed landed. Re-read the
|
|
2084
|
+
// committed row in a fresh context and answer success only when it shows
|
|
2085
|
+
// the staged values on the same row identity. A mismatch retries from the
|
|
2086
|
+
// next attempt's fresh read (which re-checks the text, the owner and the
|
|
2087
|
+
// identity); an unreadable read is unknown. Both unconfirmed outcomes mark
|
|
2088
|
+
// the id outcome-unknown (writeOutcomeUnknownFor), so a later PUT, PATCH or
|
|
2089
|
+
// DELETE of it is refused as after an ordinary PUT or PATCH.
|
|
2090
|
+
const verdict = await verifyCommittedFields(databases.flair.Memory, id, outcome.identity, outcome.fields, (committed) => skillEmbedText(committed) === textToEmbed);
|
|
2091
|
+
if (verdict === "unreadable")
|
|
2092
|
+
return { response: writeOutcomeUnknownFor(id) };
|
|
2093
|
+
if (verdict !== "shown") {
|
|
2094
|
+
// Safe to retry from a fresh read: for unchanged text and owner the next
|
|
2095
|
+
// attempt writes the same vector and hash (changed text recomputes them)
|
|
2096
|
+
// and restages `updatedAt` (and a new `instanceToken` on a legacy row that
|
|
2097
|
+
// still lacks one), so a post-commit mismatch retries from the next
|
|
2098
|
+
// attempt's fresh read. A post-commit mismatch on the final attempt is an
|
|
2099
|
+
// unconfirmed outcome (the commit resolved, so nothing here proves no
|
|
2100
|
+
// write landed). state.committedUnconfirmed stays set, so every later
|
|
2101
|
+
// exit of this call is settled as unknown: a later refusal, provider
|
|
2102
|
+
// timeout or error answers write_outcome_unknown and marks the id. Text
|
|
2103
|
+
// changes that exhaust the attempts through recomputation, and a change
|
|
2104
|
+
// seen at a confirmation, answer 409 only when no attempt has committed.
|
|
2105
|
+
if (attempt === REEMBED_WRITE_ATTEMPTS) {
|
|
2106
|
+
console.warn(`[reembed] ${id}: the committed vector was not confirmed after ${REEMBED_WRITE_ATTEMPTS} attempts; outcome: unconfirmed`);
|
|
2107
|
+
return { response: writeOutcomeUnknownFor(id) };
|
|
2108
|
+
}
|
|
2109
|
+
continue;
|
|
2110
|
+
}
|
|
1499
2111
|
// flair#2561: the response names the row and its new updatedAt, and
|
|
1500
2112
|
// carries no embedding field; `flair reembed` reads the model stamp from
|
|
1501
2113
|
// the stored row.
|
|
1502
2114
|
const body = buildFromAllowlist({ id, updatedAt: outcome.updatedAt }, REEMBED_RESPONSE_RULES);
|
|
1503
2115
|
return { response: body instanceof Response ? body : Response.json(body), token: outcome.token };
|
|
1504
2116
|
}
|
|
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
|
-
};
|
|
2117
|
+
return settle(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" } }), "reembed_row_changed");
|
|
1508
2118
|
}
|
|
1509
2119
|
export class Memory extends databases.flair.Memory {
|
|
1510
2120
|
/**
|
|
@@ -1533,7 +2143,9 @@ export class Memory extends databases.flair.Memory {
|
|
|
1533
2143
|
* does not disclose whether another agent's private record exists.
|
|
1534
2144
|
* Anonymous HTTP requests are denied by allowRead(), while administrator
|
|
1535
2145
|
* and trusted internal reads are unfiltered. Wired through
|
|
1536
|
-
* record-type-kit.ts's makeByIdReadGate.
|
|
2146
|
+
* record-type-kit.ts's makeByIdReadGate. Non-admin reads of retained closed
|
|
2147
|
+
* skill payloads also apply `closedSkillPayloadReadable`; a failed check
|
|
2148
|
+
* returns 404 by id or omits the collection row.
|
|
1537
2149
|
*/
|
|
1538
2150
|
async get(target, opts) {
|
|
1539
2151
|
// Collection / query reads — the `GET /Memory/?<query>` form and the bare
|
|
@@ -1563,12 +2175,14 @@ export class Memory extends databases.flair.Memory {
|
|
|
1563
2175
|
// its own plain id-only target) so the pointer decision below always sees
|
|
1564
2176
|
// the stored `id`, `agentId`, `instanceToken`, `archived` and `visibility`.
|
|
1565
2177
|
// A shaped read — a caller target carrying a selection, or a class that
|
|
1566
|
-
// installs one — can never hand the join an already-projected value.
|
|
1567
|
-
// internal and admin reads keep their target unchanged.
|
|
2178
|
+
// installs one — can never hand the join an already-projected value.
|
|
1568
2179
|
const nonAdminAgent = auth.kind === "agent" && !auth.isAdmin;
|
|
2180
|
+
const boundId = this.getId?.();
|
|
2181
|
+
const legacyProperty = typeof target === "string" && this.constructor.loadAsInstance !== false && boundId != null;
|
|
2182
|
+
const selectionTarget = legacyProperty ? { property: target } : target;
|
|
1569
2183
|
let readTarget = target;
|
|
1570
|
-
if (nonAdminAgent) {
|
|
1571
|
-
const targetId = typeof target === "string" ? target : target?.id;
|
|
2184
|
+
if (nonAdminAgent || legacyProperty || (typeof target === "object" && (target.select != null || target.property != null))) {
|
|
2185
|
+
const targetId = legacyProperty ? boundId : typeof target === "string" ? target : target?.id;
|
|
1572
2186
|
readTarget = targetId != null ? { id: targetId } : {};
|
|
1573
2187
|
}
|
|
1574
2188
|
const result = await memoryByIdReadGate.call(this, readTarget, (t) => super.get(t));
|
|
@@ -1601,9 +2215,11 @@ export class Memory extends databases.flair.Memory {
|
|
|
1601
2215
|
if (result && typeof result === "object" && !(result instanceof Response) && typeof result.agentId === "string") {
|
|
1602
2216
|
const ctx = this.getContext?.();
|
|
1603
2217
|
const withHits = await applyHitStats(projected, ctx);
|
|
1604
|
-
|
|
2218
|
+
const bound = applyPromotionBinding(attachTrust(withHits, wantsTrust(target, opts)));
|
|
2219
|
+
return nonAdminAgent ? bound : projectMemoryRead(this.constructor, bound, selectionTarget, ctx, true);
|
|
1605
2220
|
}
|
|
1606
|
-
|
|
2221
|
+
const bound = applyPromotionBinding(projected);
|
|
2222
|
+
return nonAdminAgent ? bound : projectMemoryRead(this.constructor, bound, selectionTarget, ctx, true);
|
|
1607
2223
|
}
|
|
1608
2224
|
/**
|
|
1609
2225
|
* Override search() to scope collection GETs by authenticated agent.
|
|
@@ -1616,7 +2232,9 @@ export class Memory extends databases.flair.Memory {
|
|
|
1616
2232
|
* Non-admin calls are scoped to the reader's own records at any visibility
|
|
1617
2233
|
* plus every other agent's non-private records — the shipped open-within-org
|
|
1618
2234
|
* read model. MemoryGrant is NOT consulted on reads; the one place the scope
|
|
1619
|
-
* is resolved is memory-read-scope.ts's resolveReadScope().
|
|
2235
|
+
* is resolved is memory-read-scope.ts's resolveReadScope(). Non-admin reads
|
|
2236
|
+
* of retained closed skill payloads also apply `closedSkillPayloadReadable`;
|
|
2237
|
+
* a failed check returns 404 by id or omits the collection row.
|
|
1620
2238
|
*/
|
|
1621
2239
|
async search(query) {
|
|
1622
2240
|
// Access request context via Harper's Resource instance context.
|
|
@@ -1630,15 +2248,25 @@ export class Memory extends databases.flair.Memory {
|
|
|
1630
2248
|
const gate = await resolveAuthGate(ctx, UNAUTH());
|
|
1631
2249
|
if (gate.kind === "denied")
|
|
1632
2250
|
return gate.response;
|
|
1633
|
-
if (gate.kind === "unfiltered")
|
|
1634
|
-
|
|
2251
|
+
if (gate.kind === "unfiltered") {
|
|
2252
|
+
const source = await overlayHitStatsResult(super.search(withoutCallerSelection(query)), ctx);
|
|
2253
|
+
if (!source || source instanceof Response || typeof source[Symbol.asyncIterator] !== "function")
|
|
2254
|
+
return source;
|
|
2255
|
+
const table = this.constructor;
|
|
2256
|
+
return (async function* promotionBound() {
|
|
2257
|
+
for await (const row of source)
|
|
2258
|
+
yield projectMemoryRead(table, applyPromotionBinding(row), query, ctx);
|
|
2259
|
+
})();
|
|
2260
|
+
}
|
|
1635
2261
|
// Non-admin agent: scope to own records at any visibility plus every other
|
|
1636
2262
|
// agent's non-private records (open-within-org; MemoryGrant is not
|
|
1637
2263
|
// consulted on reads). Centralized in
|
|
1638
2264
|
// memoryReadScope (record-type-kit.ts's makeReadScope(), parameterized
|
|
1639
2265
|
// from RECORD_TYPES.Memory — see this file's header — delegating
|
|
1640
2266
|
// "open-within-org" to memory-read-scope.ts's resolveReadScope()
|
|
1641
|
-
// unchanged) so get() above and search() here cannot drift.
|
|
2267
|
+
// unchanged) so get() above and search() here cannot drift. Non-admin reads
|
|
2268
|
+
// of retained closed skill payloads also apply `closedSkillPayloadReadable`;
|
|
2269
|
+
// a failed check returns 404 by id or omits the collection row.
|
|
1642
2270
|
//
|
|
1643
2271
|
// The scope condition is nested as the outermost AND block via
|
|
1644
2272
|
// makeScopedSearch (record-type-kit.ts) — same correct composition
|
|
@@ -1677,7 +2305,7 @@ export class Memory extends databases.flair.Memory {
|
|
|
1677
2305
|
// closed skill payload the reader may not read. Open rows pass.
|
|
1678
2306
|
if (!(await closedSkillPayloadReadable(row, readerAgentId)))
|
|
1679
2307
|
continue;
|
|
1680
|
-
yield await applyHitStats(row, ctx);
|
|
2308
|
+
yield await applyHitStats(applyPromotionBinding(row), ctx);
|
|
1681
2309
|
}
|
|
1682
2310
|
};
|
|
1683
2311
|
// memoryScopedSearch returns a Promise of the iterable (its scopedSearch
|
|
@@ -1692,7 +2320,73 @@ export class Memory extends databases.flair.Memory {
|
|
|
1692
2320
|
})();
|
|
1693
2321
|
return joined;
|
|
1694
2322
|
}
|
|
2323
|
+
/** A POST that names an id (URL or body) or a `supersedes` reference takes
|
|
2324
|
+
* the per-id lock for those ids, the reference under its canonical id, and
|
|
2325
|
+
* holds it across the handler's
|
|
2326
|
+
* read, decision and write and the predecessor's close (flair#2478 slice 1
|
|
2327
|
+
* part 2). Its non-skill row writes join an open request transaction, which
|
|
2328
|
+
* commits after the lock is released; a superseding skill write owns its
|
|
2329
|
+
* commit. A POST that names neither takes no lock. */
|
|
1695
2330
|
async post(content, context) {
|
|
2331
|
+
// Test-only: on the HTTP request path, holds a POST after its request
|
|
2332
|
+
// transaction opened and before it takes the target's lock and reads it, so
|
|
2333
|
+
// a concurrent commit can land in between (flair#3170).
|
|
2334
|
+
const targetReadPause = txnPausePoint("memory-post-target-read");
|
|
2335
|
+
if (targetReadPause)
|
|
2336
|
+
await targetReadPause;
|
|
2337
|
+
// flair#2307: resolve the `supersedes` reference to its canonical id once,
|
|
2338
|
+
// before lock selection (some POSTs take no lock), so the predecessor read,
|
|
2339
|
+
// the close and any lock taken name that id (a selector or encoded
|
|
2340
|
+
// spelling resolves to it).
|
|
2341
|
+
canonicalizeSupersedes(content);
|
|
2342
|
+
// flair#2858: release an ordinary superseding POST's predecessor lock
|
|
2343
|
+
// before processing its queued citations.
|
|
2344
|
+
const afterRelease = [];
|
|
2345
|
+
const ids = postLockIds(this, content);
|
|
2346
|
+
if (ids.length === 0) {
|
|
2347
|
+
const result = await this.postLocked(content, context, false, afterRelease, { ids: [] });
|
|
2348
|
+
for (const step of afterRelease)
|
|
2349
|
+
await step();
|
|
2350
|
+
return result;
|
|
2351
|
+
}
|
|
2352
|
+
// The initial write plan returns missing ids for a new acquisition before
|
|
2353
|
+
// the next attempt's authoritative read (flair#2950).
|
|
2354
|
+
const uncloneable = uncloneableWriteBodyResponse(content);
|
|
2355
|
+
if (uncloneable)
|
|
2356
|
+
return uncloneable;
|
|
2357
|
+
const pristine = replayWriteBody(content);
|
|
2358
|
+
let lockIds = ids;
|
|
2359
|
+
for (let attempt = 0; attempt < SKILL_WRITE_HEAD_LOCK_ATTEMPTS; attempt++) {
|
|
2360
|
+
const body = attempt === 0 ? content : replayWriteBody(pristine);
|
|
2361
|
+
const outcome = await withMemoryWriteLock(memoryWriteLockStore(), lockIds, (held) => this.postLocked(body, context, true, afterRelease, { ids: memoryWriteLockTokenIds(held) }), { phase: attempt === 0 ? "post" : "memory-skill-write" });
|
|
2362
|
+
if (outcome.kind !== "done")
|
|
2363
|
+
return memoryLockRefusal(outcome, memoryLockCallerId(this));
|
|
2364
|
+
const extend = skillLockExtension(outcome.value);
|
|
2365
|
+
if (extend) {
|
|
2366
|
+
lockIds = this.skillLockIds(lockIds, outcome.value);
|
|
2367
|
+
continue;
|
|
2368
|
+
}
|
|
2369
|
+
for (const step of afterRelease)
|
|
2370
|
+
await step();
|
|
2371
|
+
const then = skillThen(outcome.value);
|
|
2372
|
+
return then ? await then() : outcome.value;
|
|
2373
|
+
}
|
|
2374
|
+
return skillWriteConflict("skill_head_moved");
|
|
2375
|
+
}
|
|
2376
|
+
/** `locked`: the POST holds the per-id lock, so its provider calls take the
|
|
2377
|
+
* bounded path putLocked's take (MEMORY_LOCKED_PROVIDER_TIMEOUT_MS): a call
|
|
2378
|
+
* still pending at the bound, or answering after it, is refused once the
|
|
2379
|
+
* event loop runs again; a provider that never yields it can prevent that. */
|
|
2380
|
+
async postLocked(content, context, locked, afterRelease, held) {
|
|
2381
|
+
// flair#2612: a POST body that is not a single JSON object — an array, null,
|
|
2382
|
+
// a string or a number — is refused here with a named 400 before any write
|
|
2383
|
+
// path runs. Without it, an array reaches Harper's collection create, which
|
|
2384
|
+
// answers an unnamed 500 ("Can not create a record without an object"); null,
|
|
2385
|
+
// a string or a number throws a TypeError inside post() itself, also an
|
|
2386
|
+
// unnamed 500.
|
|
2387
|
+
const bodyDenial = guardObjectBody(content);
|
|
2388
|
+
if (bodyDenial)
|
|
2389
|
+
return bodyDenial;
|
|
1696
2390
|
// flair#2141 S2: check the seed's fixed id against the operator-source
|
|
1697
2391
|
// reservation (resources/seed-reservation.ts).
|
|
1698
2392
|
const seedDenial = await refuseReservedSeedWrite("Memory", writeTargetIds(this, content), this.getContext?.());
|
|
@@ -1749,7 +2443,33 @@ export class Memory extends databases.flair.Memory {
|
|
|
1749
2443
|
(typeof postUrlTargetId === "string" || typeof postUrlTargetId === "number")) {
|
|
1750
2444
|
content.id = postUrlTargetId;
|
|
1751
2445
|
}
|
|
1752
|
-
const
|
|
2446
|
+
const postSnapshot = content.id ? await databases.flair.Memory.get(content.id) : null;
|
|
2447
|
+
// The in-place predicate the skill plan uses, a reserved seed id named by
|
|
2448
|
+
// the body or the URL: an in-place POST supersedes nothing, so it keeps the
|
|
2449
|
+
// request-snapshot target read and the caller's transaction (flair#3170).
|
|
2450
|
+
const postInPlace = [content?.id, postUrlTargetId].some((candidate) => isReservedSeedId("Memory", candidate));
|
|
2451
|
+
// flair#3170: a skill POST that supersedes a target present in the request
|
|
2452
|
+
// snapshot reads the target as committed when it still exists. The only
|
|
2453
|
+
// change that window accepts is the previous write's embedding backfill
|
|
2454
|
+
// fields. The plan's stale-target check then compares two committed reads
|
|
2455
|
+
// and the retry is not refused. Any other change to the target in that
|
|
2456
|
+
// window answers 409 skill_target_changed, and a target gone by this read
|
|
2457
|
+
// is refused the same way, recreating no row and appending no
|
|
2458
|
+
// InstructionVersion. The body may omit `tags` and inherit the skill
|
|
2459
|
+
// tag from the stored row, the source prepareSkillBody uses, so either
|
|
2460
|
+
// row's tags decide whether this read applies.
|
|
2461
|
+
const postStoredRead = !!(postSnapshot && !postInPlace && (isSkillWrite(content) || rowIsSkill(postSnapshot)));
|
|
2462
|
+
// Test-only: holds a skill POST after its request-snapshot read and before
|
|
2463
|
+
// its committed target read, so a concurrent delete can land in between
|
|
2464
|
+
// (flair#3170).
|
|
2465
|
+
const committedReadPause = postStoredRead ? txnPausePoint("memory-post-committed-read") : undefined;
|
|
2466
|
+
if (committedReadPause)
|
|
2467
|
+
await committedReadPause;
|
|
2468
|
+
const postCommitted = postStoredRead && postSnapshot ? await databases.flair.Memory.get(String(postSnapshot.id), {}) : null;
|
|
2469
|
+
if (postStoredRead && postSnapshot && (!postCommitted || skillTargetSnapshotChanged(postSnapshot, postCommitted))) {
|
|
2470
|
+
return skillWriteConflict("skill_target_changed");
|
|
2471
|
+
}
|
|
2472
|
+
const postStored = postStoredRead && postSnapshot ? (postCommitted ?? postSnapshot) : postSnapshot;
|
|
1753
2473
|
// flair#2561: the fields this request supplies that `stored` can report —
|
|
1754
2474
|
// its string-valued text fields and, for a skill, the skill fields it
|
|
1755
2475
|
// supplies (flair#2575) — read before a skill predecessor is merged into the
|
|
@@ -1757,7 +2477,8 @@ export class Memory extends databases.flair.Memory {
|
|
|
1757
2477
|
// (below) and keeps a string a string, so reading them first names the
|
|
1758
2478
|
// same fields.
|
|
1759
2479
|
const suppliedText = suppliedStoredTextFields(content);
|
|
1760
|
-
|
|
2480
|
+
// `content.supersedes` is already canonical: post() resolved it before
|
|
2481
|
+
// lock selection (canonicalizeSupersedes runs once per request).
|
|
1761
2482
|
// flair#2573: an empty `embedding` in the body is an omitted one. It is
|
|
1762
2483
|
// removed before the omission check and prepareSkillBody, so every later
|
|
1763
2484
|
// step, a skill update's carried vector included, sees a body without it.
|
|
@@ -1786,9 +2507,6 @@ export class Memory extends databases.flair.Memory {
|
|
|
1786
2507
|
// discipline as `claimedClient` below. Pull the optional
|
|
1787
2508
|
// `usedMemoryIds` off the write body now, BEFORE anything else touches
|
|
1788
2509
|
// `content`, so it is NEVER persisted on the Memory record itself.
|
|
1789
|
-
// Recording happens POST-COMMIT, only when this was present (see the
|
|
1790
|
-
// failure-isolated recordCitations() call near the return below) —
|
|
1791
|
-
// omitted ⇒ `undefined` ⇒ zero new calls, byte-identical behavior.
|
|
1792
2510
|
const usedMemoryIds = content?.usedMemoryIds;
|
|
1793
2511
|
if (content && typeof content === "object")
|
|
1794
2512
|
delete content.usedMemoryIds;
|
|
@@ -1955,7 +2673,14 @@ export class Memory extends databases.flair.Memory {
|
|
|
1955
2673
|
const embeddingSupplied = Array.isArray(content.embedding) && content.embedding.length > 0;
|
|
1956
2674
|
let dedupMatch = null;
|
|
1957
2675
|
if (!content.supersedes) {
|
|
1958
|
-
|
|
2676
|
+
try {
|
|
2677
|
+
dedupMatch = await runDedupGate(ctx, content, locked);
|
|
2678
|
+
}
|
|
2679
|
+
catch (err) {
|
|
2680
|
+
if (err instanceof MemoryProviderTimeout)
|
|
2681
|
+
return memoryProviderTimeoutResponse();
|
|
2682
|
+
throw err;
|
|
2683
|
+
}
|
|
1959
2684
|
}
|
|
1960
2685
|
else {
|
|
1961
2686
|
delete content.dedup;
|
|
@@ -1969,7 +2694,15 @@ export class Memory extends databases.flair.Memory {
|
|
|
1969
2694
|
// (skillEmbedText), not `content`.
|
|
1970
2695
|
const embedText = skillEmbedText(content);
|
|
1971
2696
|
if (embedText && !content.embedding) {
|
|
1972
|
-
|
|
2697
|
+
let vec;
|
|
2698
|
+
try {
|
|
2699
|
+
vec = locked ? await embedUnderLock(embedText) : await getEmbedding(embedText, "document");
|
|
2700
|
+
}
|
|
2701
|
+
catch (err) {
|
|
2702
|
+
if (err instanceof MemoryProviderTimeout)
|
|
2703
|
+
return memoryProviderTimeoutResponse();
|
|
2704
|
+
throw err;
|
|
2705
|
+
}
|
|
1973
2706
|
if (vec) {
|
|
1974
2707
|
content.embedding = vec;
|
|
1975
2708
|
content.embeddingModel = getModelId();
|
|
@@ -2030,35 +2763,55 @@ export class Memory extends databases.flair.Memory {
|
|
|
2030
2763
|
// call is removed.
|
|
2031
2764
|
stripUndeclaredMemoryAttributes(content);
|
|
2032
2765
|
normalizeEmptyEmbedding(content);
|
|
2766
|
+
// POST joins an open caller transaction and confirms before its commit;
|
|
2767
|
+
// post-commit verification belongs to that owner (#2656 slice B).
|
|
2768
|
+
// Without a caller transaction, POST owns the commit and verifies after it.
|
|
2769
|
+
const postJoinsRequestTxn = isJoinableTransaction(ctx);
|
|
2033
2770
|
if (isSkillWrite(content)) {
|
|
2034
2771
|
const reservedId = [content?.id, this.getId?.()].find((candidate) => isReservedSeedId("Memory", candidate));
|
|
2035
2772
|
const skillStaged = { supplied: suppliedText, text: null };
|
|
2036
2773
|
const skillResult = await writeSkillCreateOrUpdate({
|
|
2037
2774
|
ctx, auth, content, storedRow: postStored, explicitPredecessor: preparedSkill.predecessor, method: "post", pointer,
|
|
2038
|
-
inPlaceId: reservedId != null ? String(reservedId) : null, staged: skillStaged,
|
|
2775
|
+
inPlaceId: reservedId != null ? String(reservedId) : null, staged: skillStaged, held,
|
|
2039
2776
|
});
|
|
2040
|
-
if (
|
|
2777
|
+
if (skillResult instanceof SkillLockExtension)
|
|
2778
|
+
return skillResult;
|
|
2779
|
+
if (skillResult instanceof Response)
|
|
2780
|
+
return skillWriteResponse(skillResult, redactedValues, skillStaged.text);
|
|
2781
|
+
const finish = async () => {
|
|
2782
|
+
// The write has committed; the pre-confirmation work runs after this
|
|
2783
|
+
// verb's Memory lock releases (flair#2645).
|
|
2784
|
+
if (skillResult?.confirm) {
|
|
2785
|
+
const denial = await skillResult.confirm();
|
|
2786
|
+
if (denial)
|
|
2787
|
+
return denial;
|
|
2788
|
+
}
|
|
2789
|
+
// Verify after the commit when this write owned it, as a skill POST
|
|
2790
|
+
// that supersedes a version does (flair#2645).
|
|
2791
|
+
if (skillStaged.joined !== true) {
|
|
2792
|
+
await pausePostVerification(true);
|
|
2793
|
+
const skillVerified = await verifyWrittenRow(databases.flair.Memory, skillStaged.row, skillResult.id, { expectedToken: skillStaged.row?.instanceToken }, [...POSTCOMMIT_VERIFY_FIELDS, "summary", "trigger", "metadata", "tags"]);
|
|
2794
|
+
if (skillVerified.unknown || skillVerified.mismatch) {
|
|
2795
|
+
return skillVerified.unknown ? writeOutcomeUnknownFor(skillResult.id) : skillWriteConflict("skill_target_changed");
|
|
2796
|
+
}
|
|
2797
|
+
}
|
|
2041
2798
|
await markDerivedSourcesReflected(content);
|
|
2042
|
-
|
|
2043
|
-
|
|
2044
|
-
|
|
2045
|
-
|
|
2046
|
-
|
|
2047
|
-
|
|
2048
|
-
// the Memory row back too instead of leaving it pointer-less.
|
|
2049
|
-
// Pinned by test/unit/memory-host-source.test.ts (r20-atomic) — RED if the
|
|
2050
|
-
// owned-transaction branch is bypassed.
|
|
2799
|
+
return skillWriteResponse(skillResult, redactedValues, skillStaged.text);
|
|
2800
|
+
};
|
|
2801
|
+
if (skillResult?.confirm)
|
|
2802
|
+
return { skillThen: finish };
|
|
2803
|
+
return await finish();
|
|
2804
|
+
}
|
|
2051
2805
|
// flair#2467: the post-redaction text fields this write stages, for the response.
|
|
2052
2806
|
let postStaged = {};
|
|
2053
|
-
|
|
2054
|
-
// transaction is joinable too.
|
|
2055
|
-
const postJoinsRequestTxn = isJoinableTransaction(ctx);
|
|
2807
|
+
let stagedRow;
|
|
2056
2808
|
let postResult;
|
|
2057
2809
|
let postRowId;
|
|
2058
2810
|
let grantedClosed = null;
|
|
2059
2811
|
try {
|
|
2060
2812
|
postResult = await withSharedWriteTransaction(ctx, async (c) => {
|
|
2061
2813
|
postStaged = storedMemoryText(content, suppliedText);
|
|
2814
|
+
stagedRow = structuredClone(content);
|
|
2062
2815
|
const newId = await writeMemoryRowPost(this.constructor, content, c);
|
|
2063
2816
|
if (newId instanceof Response)
|
|
2064
2817
|
return newId;
|
|
@@ -2069,12 +2822,29 @@ export class Memory extends databases.flair.Memory {
|
|
|
2069
2822
|
if (persistDenial)
|
|
2070
2823
|
return persistDenial;
|
|
2071
2824
|
}
|
|
2825
|
+
// Test-only: holds the POST after its row and any pointer are staged, before
|
|
2826
|
+
// the transaction commits (flair#2656).
|
|
2827
|
+
const stagedPause = txnPausePoint("memory-post-staged");
|
|
2828
|
+
if (stagedPause)
|
|
2829
|
+
await stagedPause;
|
|
2072
2830
|
// Stage a grant-authorized close in the successor's transaction.
|
|
2073
2831
|
grantedClosed = await closeGrantedSupersedeStaged(c, content, supersede.close, postJoinsRequestTxn);
|
|
2832
|
+
if (postJoinsRequestTxn) {
|
|
2833
|
+
await pausePostVerification(false);
|
|
2834
|
+
try {
|
|
2835
|
+
await confirmCommittedRow(databases.flair.Memory, newId, (committed) => sameStoredRow(committed, postStored));
|
|
2836
|
+
}
|
|
2837
|
+
catch (err) {
|
|
2838
|
+
abortRequestTransaction(c);
|
|
2839
|
+
throw err;
|
|
2840
|
+
}
|
|
2841
|
+
}
|
|
2074
2842
|
return null;
|
|
2075
2843
|
});
|
|
2076
2844
|
}
|
|
2077
2845
|
catch (err) {
|
|
2846
|
+
if (err instanceof CommittedRowChanged)
|
|
2847
|
+
return storedRowChangedRefusal("Memory");
|
|
2078
2848
|
const refusal = grantedCloseRefusal(err);
|
|
2079
2849
|
if (refusal)
|
|
2080
2850
|
return refusal;
|
|
@@ -2082,6 +2852,13 @@ export class Memory extends databases.flair.Memory {
|
|
|
2082
2852
|
}
|
|
2083
2853
|
if (postResult instanceof Response)
|
|
2084
2854
|
return writeResultResponse(postResult);
|
|
2855
|
+
if (!postJoinsRequestTxn) {
|
|
2856
|
+
await pausePostVerification(false);
|
|
2857
|
+
const verified = await verifyWrittenRow(databases.flair.Memory, stagedRow, postRowId, { expectedToken: stagedRow.instanceToken }, POSTCOMMIT_VERIFY_FIELDS);
|
|
2858
|
+
if (verified.unknown || verified.mismatch) {
|
|
2859
|
+
return verified.unknown ? writeOutcomeUnknownFor(content.id ?? postRowId) : storedRowChangedRefusal("Memory");
|
|
2860
|
+
}
|
|
2861
|
+
}
|
|
2085
2862
|
if (grantedClosed)
|
|
2086
2863
|
noteMemoryUpsert(grantedClosed);
|
|
2087
2864
|
const result = {};
|
|
@@ -2108,19 +2885,17 @@ export class Memory extends databases.flair.Memory {
|
|
|
2108
2885
|
if (supersede.close?.granteeId === undefined)
|
|
2109
2886
|
await closeSupersededIfNeeded(ctx, content, supersede.close, "post");
|
|
2110
2887
|
await markDerivedSourcesReflected(content);
|
|
2111
|
-
// flair#744
|
|
2112
|
-
//
|
|
2113
|
-
// final; crediting each cited memory through the shared usage ledger
|
|
2114
|
-
// (same path as POST /RecordUsage) must never affect this response —
|
|
2115
|
-
// any failure here is logged server-side and swallowed, never surfaced
|
|
2116
|
-
// to the caller, never rolls back or retries the write.
|
|
2888
|
+
// flair#744: queue citation-on-write for post() (flair#2858).
|
|
2889
|
+
// A completed credit error is logged without changing the response payload.
|
|
2117
2890
|
if (usedMemoryIds !== undefined) {
|
|
2118
|
-
|
|
2119
|
-
|
|
2120
|
-
|
|
2121
|
-
|
|
2122
|
-
|
|
2123
|
-
|
|
2891
|
+
afterRelease.push(async () => {
|
|
2892
|
+
try {
|
|
2893
|
+
await recordCitations(ctx, auth, usedMemoryIds, new Date().toISOString());
|
|
2894
|
+
}
|
|
2895
|
+
catch (err) {
|
|
2896
|
+
console.error("Memory.post: citation recording failed", err);
|
|
2897
|
+
}
|
|
2898
|
+
});
|
|
2124
2899
|
}
|
|
2125
2900
|
return buildWriteResponse(content, result, dedupMatch, redactedValues, postStaged, postRowId);
|
|
2126
2901
|
}
|
|
@@ -2128,31 +2903,39 @@ export class Memory extends databases.flair.Memory {
|
|
|
2128
2903
|
// via the one shared delegate. (Admin/internal — including the _reindex
|
|
2129
2904
|
// path in put() — pass through the delegate untouched.)
|
|
2130
2905
|
/** PATCH requires a target id and lock before its body runs. Ordinary and
|
|
2131
|
-
* re-embed owned writes commit before releasing the lock.
|
|
2906
|
+
* re-embed owned writes commit before releasing the lock. A re-embed body
|
|
2907
|
+
* (flair#2296) holds the lock under its own phase name, `patch-reembed`, so
|
|
2908
|
+
* a hold warning names the re-embed (flair#2478 slice 3). */
|
|
2132
2909
|
async patch(content, query) {
|
|
2133
2910
|
const ids = putLockIds(this, content);
|
|
2134
2911
|
if (ids.length === 0)
|
|
2135
2912
|
return memoryIdRequiredResponse();
|
|
2913
|
+
const phase = isReembedPatch(content) ? "patch-reembed" : "patch";
|
|
2136
2914
|
const outcome = await withMemoryWriteLock(memoryWriteLockStore(), ids, async () => {
|
|
2137
2915
|
const result = await this.patchLocked(content, query);
|
|
2138
2916
|
// Test-only: the verb body has returned and the lock is still held. A body
|
|
2139
|
-
// that owned its transaction has committed it
|
|
2140
|
-
// that joined another transaction has not.
|
|
2917
|
+
// that owned its transaction has committed it.
|
|
2141
2918
|
const committed = txnPausePoint("memory-patch-committed");
|
|
2142
2919
|
if (committed)
|
|
2143
2920
|
await committed;
|
|
2144
2921
|
return result;
|
|
2145
|
-
}, { phase
|
|
2922
|
+
}, { phase });
|
|
2146
2923
|
if (outcome.kind === "done")
|
|
2147
2924
|
return outcome.value;
|
|
2148
2925
|
return memoryLockRefusal(outcome, memoryLockCallerId(this));
|
|
2149
2926
|
}
|
|
2150
|
-
async patchLocked(content, query) {
|
|
2927
|
+
async patchLocked(content, query, checked) {
|
|
2928
|
+
// flair#2478 part 3a: a checked write (patchMemoryWithLock) joins its locked
|
|
2929
|
+
// transaction; the ordinary verb passes no entry.
|
|
2930
|
+
const locked = takeCheckedEntry(checked);
|
|
2151
2931
|
const entry = txnPausePoint("memory-patch-entry");
|
|
2152
2932
|
if (entry)
|
|
2153
2933
|
await entry;
|
|
2154
2934
|
// flair#2296: decided on the body as sent; the guards below add fields to it.
|
|
2155
2935
|
const reembedRequest = isReembedPatch(content);
|
|
2936
|
+
// The re-embed writes in its own owned transaction, outside a locked scope.
|
|
2937
|
+
if (locked && reembedRequest)
|
|
2938
|
+
throw uncheckedBodyRefusal("re-embed");
|
|
2156
2939
|
// flair#2141 S2: check the seed's fixed id against the operator-source
|
|
2157
2940
|
// reservation (resources/seed-reservation.ts).
|
|
2158
2941
|
const seedDenial = await refuseReservedSeedWrite("Memory", writeTargetIds(this, content), this.getContext?.());
|
|
@@ -2208,6 +2991,7 @@ export class Memory extends databases.flair.Memory {
|
|
|
2208
2991
|
// engine returns no vector), or the re-embed writes one with its vector. A
|
|
2209
2992
|
// PATCH that supplies its own vector retains the stored hash beside it.
|
|
2210
2993
|
delete content.embeddedContentHash;
|
|
2994
|
+
const declaredFields = patchDeclaredFields(content);
|
|
2211
2995
|
// flair#2478 slice 1 — the ordinary PATCH runs in ONE owned transaction whose
|
|
2212
2996
|
// FIRST operation is the authoritative stored read; the read, the decision
|
|
2213
2997
|
// and the COMMIT all happen before the write lock releases. Harper orders a
|
|
@@ -2215,9 +2999,10 @@ export class Memory extends databases.flair.Memory {
|
|
|
2215
2999
|
// it share this commit. (A re-embed PATCH writes in its own inner owned
|
|
2216
3000
|
// transaction instead, which also commits before the lock releases.)
|
|
2217
3001
|
const ctx = this.getContext?.();
|
|
2218
|
-
|
|
2219
|
-
|
|
2220
|
-
|
|
3002
|
+
const patchScope = locked
|
|
3003
|
+
? (cx, fn) => locked.admission.join(cx, fn)
|
|
3004
|
+
: withOwnedTransaction;
|
|
3005
|
+
const patched = await patchScope(ctx, async (c) => {
|
|
2221
3006
|
// The FIRST operation inside the owned transaction: the authoritative
|
|
2222
3007
|
// stored read, by the URL-BOUND target id (a body id that disagrees with
|
|
2223
3008
|
// the address, or a lookup that FAILS, is refused; a failed read is never
|
|
@@ -2293,9 +3078,10 @@ export class Memory extends databases.flair.Memory {
|
|
|
2293
3078
|
// plus instanceToken for a legacy row that has none, flair#2478), then
|
|
2294
3079
|
// confirms the committed row has the identity and embedding text it read
|
|
2295
3080
|
// (flair#2465). A row gone or changed in either at confirmation aborts with
|
|
2296
|
-
// 409 stored_row_changed.
|
|
2297
|
-
//
|
|
2298
|
-
//
|
|
3081
|
+
// 409 stored_row_changed. Post-commit verification retries surviving
|
|
3082
|
+
// differences in compared fields, identity or text from a fresh read
|
|
3083
|
+
// within the attempt bound.
|
|
3084
|
+
// After a normal storage result and inner commit, PATCH
|
|
2299
3085
|
// compares the token; a storage Response returns before that read.
|
|
2300
3086
|
if (reembedRequest) {
|
|
2301
3087
|
if (!existingForSkill)
|
|
@@ -2445,9 +3231,6 @@ export class Memory extends databases.flair.Memory {
|
|
|
2445
3231
|
return denied;
|
|
2446
3232
|
}
|
|
2447
3233
|
}
|
|
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
3234
|
// flair#2478: a stored row that has a token keeps it (the
|
|
2452
3235
|
// body's own was stripped above); a legacy row without one, or a row this
|
|
2453
3236
|
// PATCH creates (an admin or internal caller only), is given a fresh one
|
|
@@ -2475,16 +3258,22 @@ export class Memory extends databases.flair.Memory {
|
|
|
2475
3258
|
// flair#2561: a Response from the storage layer is not reported
|
|
2476
3259
|
// (storageResult); it is returned from this transaction as the
|
|
2477
3260
|
// write_response_withheld refusal.
|
|
2478
|
-
const
|
|
3261
|
+
const staged = structuredClone(content);
|
|
3262
|
+
const result = storageResult(await super.patch(staged, query));
|
|
2479
3263
|
if (result instanceof Response)
|
|
2480
3264
|
return result;
|
|
2481
|
-
return { result, identity: { expectedToken }, rowId: existingForSkill?.id, stampNote };
|
|
3265
|
+
return { result, staged, identity: { expectedToken }, rowId: existingForSkill?.id, stampNote };
|
|
2482
3266
|
});
|
|
2483
3267
|
// flair#2561: a refusal this path built is returned as built; a
|
|
2484
3268
|
// successful Response is replaced by the write_response_withheld refusal
|
|
2485
3269
|
// (writeResultResponse).
|
|
2486
3270
|
if (patched instanceof Response)
|
|
2487
3271
|
return writeResultResponse(patched);
|
|
3272
|
+
// A checked write has only staged its row. It continues below once its
|
|
3273
|
+
// locked scope has committed, as that scope's confirmation; a scope that
|
|
3274
|
+
// does not commit ends it here (flair#2478 part 3a).
|
|
3275
|
+
if (locked && !(await locked.stage()))
|
|
3276
|
+
return undefined;
|
|
2488
3277
|
// flair#2573: the row write has committed (its transaction returned it), so
|
|
2489
3278
|
// the embedding-space guard is notified now, before the verification read:
|
|
2490
3279
|
// a refused or unknown verification still leaves the guard told about the
|
|
@@ -2496,13 +3285,13 @@ export class Memory extends databases.flair.Memory {
|
|
|
2496
3285
|
// Verify the ordinary owned PATCH after a normal storage result; refusals
|
|
2497
3286
|
// and storage Responses return above before this read. A successful re-embed is also
|
|
2498
3287
|
// checked after its inner owned commit; refusals return above.
|
|
2499
|
-
// Compare the
|
|
2500
|
-
// other field changes pass. A failed read is an unknown outcome (503).
|
|
3288
|
+
// Compare ordinary PATCH fields against the staged write, including storage coercion.
|
|
2501
3289
|
// Test-only: holds the PATCH after its commit, before the verification read.
|
|
2502
3290
|
const verifyPause = txnPausePoint("memory-patch-verify");
|
|
2503
3291
|
if (verifyPause)
|
|
2504
3292
|
await verifyPause;
|
|
2505
|
-
const
|
|
3293
|
+
const staged = "staged" in patched ? patched.staged : content;
|
|
3294
|
+
const verified = await verifyWrittenRow(databases.flair.Memory, staged, this.getId?.(), patched.identity, reembedRequest ? [] : declaredFields, locked ? { exactFields: locked.confirmFields } : undefined);
|
|
2506
3295
|
if (verified.unknown)
|
|
2507
3296
|
return writeOutcomeUnknownFor(content?.id ?? this.getId?.());
|
|
2508
3297
|
if (verified.mismatch)
|
|
@@ -2513,38 +3302,98 @@ export class Memory extends databases.flair.Memory {
|
|
|
2513
3302
|
return patched.reembed;
|
|
2514
3303
|
// As in put(): the verified row gates the answer; the response is the
|
|
2515
3304
|
// PATCH's own result, never the stored row (see put()).
|
|
2516
|
-
return rowWriteResponse(patched.result, content?.id ?? this.getId?.() ?? patched.rowId, redactedValues,
|
|
3305
|
+
return rowWriteResponse(patched.result, content?.id ?? this.getId?.() ?? patched.rowId, redactedValues, storedMemoryText(staged, suppliedText));
|
|
2517
3306
|
}
|
|
2518
3307
|
/**
|
|
2519
3308
|
* flair#2478 slice 1 — the owner PUT runs under the per-id memory write lock
|
|
2520
3309
|
* and its ordinary row write owns its transaction, so the read, the decision
|
|
2521
3310
|
* and the COMMIT all happen before the lock releases (the protocol's rule).
|
|
2522
|
-
*
|
|
2523
|
-
*
|
|
2524
|
-
*
|
|
2525
|
-
* carries an open transaction. A PUT
|
|
3311
|
+
* A put composed into its caller's transaction (manual promotion; see
|
|
3312
|
+
* putLocked) joins a transaction it does not own, which then commits after
|
|
3313
|
+
* the lock releases. A PUT
|
|
2526
3314
|
* that names no id is refused 400 before the lock; a store with no lock is
|
|
2527
3315
|
* refused 503 `memory_lock_unavailable`. See resources/memory-write-lock.ts.
|
|
2528
3316
|
*/
|
|
2529
3317
|
async put(content, query) {
|
|
3318
|
+
// Resolve a selector/encoded `supersedes` spelling once, before the lock
|
|
3319
|
+
// plan reads the predecessor (flair#2950); putLocked keeps the same id.
|
|
3320
|
+
canonicalizeSupersedes(content);
|
|
2530
3321
|
const ids = putLockIds(this, content);
|
|
2531
3322
|
if (ids.length === 0)
|
|
2532
3323
|
return memoryIdRequiredResponse();
|
|
2533
|
-
|
|
2534
|
-
|
|
2535
|
-
|
|
2536
|
-
|
|
2537
|
-
|
|
2538
|
-
|
|
2539
|
-
|
|
2540
|
-
|
|
3324
|
+
// Citation-on-write, queued by putLocked, runs after this lock is released:
|
|
3325
|
+
// it tries each cited id's lock, and the target id's lock is not held then.
|
|
3326
|
+
const afterRelease = [];
|
|
3327
|
+
// One acquisition of the ids this verb can name before its authoritative
|
|
3328
|
+
// read. A skill write that names an id it does not hold returns it from
|
|
3329
|
+
// putLocked, and putSkillLocked re-acquires with it (flair#2950).
|
|
3330
|
+
const uncloneable = uncloneableWriteBodyResponse(content);
|
|
3331
|
+
if (uncloneable)
|
|
3332
|
+
return uncloneable;
|
|
3333
|
+
const pristine = replayWriteBody(content);
|
|
3334
|
+
const outcome = await withMemoryWriteLock(memoryWriteLockStore(), ids, async (held) => {
|
|
3335
|
+
const result = await this.putLocked(content, query, afterRelease, undefined, { ids: memoryWriteLockTokenIds(held) });
|
|
3336
|
+
await this.afterPutBody();
|
|
2541
3337
|
return result;
|
|
2542
3338
|
}, { phase: "put" });
|
|
2543
|
-
if (outcome.kind
|
|
2544
|
-
return outcome
|
|
2545
|
-
|
|
3339
|
+
if (outcome.kind !== "done")
|
|
3340
|
+
return memoryLockRefusal(outcome, memoryLockCallerId(this));
|
|
3341
|
+
const extend = skillLockExtension(outcome.value);
|
|
3342
|
+
if (extend)
|
|
3343
|
+
return this.putSkillLocked(pristine, query, afterRelease, this.skillLockIds(ids, outcome.value));
|
|
3344
|
+
await this.drainAfterRelease(afterRelease);
|
|
3345
|
+
const then = skillThen(outcome.value);
|
|
3346
|
+
return then ? await then() : outcome.value;
|
|
3347
|
+
}
|
|
3348
|
+
/** A skill PUT that needs an id it did not hold retries under one acquisition
|
|
3349
|
+
* of the extended set, re-reading and re-resolving the head (flair#2950). */
|
|
3350
|
+
async putSkillLocked(content, query, afterRelease, initialIds) {
|
|
3351
|
+
const pristine = replayWriteBody(content);
|
|
3352
|
+
let lockIds = initialIds;
|
|
3353
|
+
for (let attempt = 0; attempt < SKILL_WRITE_HEAD_LOCK_ATTEMPTS; attempt++) {
|
|
3354
|
+
const body = replayWriteBody(pristine);
|
|
3355
|
+
const outcome = await withMemoryWriteLock(memoryWriteLockStore(), lockIds, async (held) => {
|
|
3356
|
+
const result = await this.putLocked(body, query, afterRelease, undefined, { ids: memoryWriteLockTokenIds(held) });
|
|
3357
|
+
await this.afterPutBody();
|
|
3358
|
+
return result;
|
|
3359
|
+
}, { phase: "memory-skill-write" });
|
|
3360
|
+
if (outcome.kind !== "done")
|
|
3361
|
+
return memoryLockRefusal(outcome, memoryLockCallerId(this));
|
|
3362
|
+
const extend = skillLockExtension(outcome.value);
|
|
3363
|
+
if (extend) {
|
|
3364
|
+
lockIds = this.skillLockIds(lockIds, outcome.value);
|
|
3365
|
+
continue;
|
|
3366
|
+
}
|
|
3367
|
+
await this.drainAfterRelease(afterRelease);
|
|
3368
|
+
const then = skillThen(outcome.value);
|
|
3369
|
+
return then ? await then() : outcome.value;
|
|
3370
|
+
}
|
|
3371
|
+
return skillWriteConflict("skill_head_moved");
|
|
3372
|
+
}
|
|
3373
|
+
/** The next acquisition's id set: the ids this attempt held plus any the
|
|
3374
|
+
* skill writer returned (flair#2950). */
|
|
3375
|
+
skillLockIds(lockIds, value) {
|
|
3376
|
+
const ids = [...lockIds];
|
|
3377
|
+
if (value instanceof SkillLockExtension)
|
|
3378
|
+
ids.push(...value.ids);
|
|
3379
|
+
return [...new Set(ids)];
|
|
3380
|
+
}
|
|
3381
|
+
/** Test-only: the verb body has returned and the lock is still held. A body
|
|
3382
|
+
* that owned its transaction has committed it; a composed put that joined
|
|
3383
|
+
* another transaction has not. */
|
|
3384
|
+
async afterPutBody() {
|
|
3385
|
+
const committed = txnPausePoint("memory-put-committed");
|
|
3386
|
+
if (committed)
|
|
3387
|
+
await committed;
|
|
2546
3388
|
}
|
|
2547
|
-
async
|
|
3389
|
+
async drainAfterRelease(afterRelease) {
|
|
3390
|
+
for (const step of afterRelease)
|
|
3391
|
+
await step();
|
|
3392
|
+
}
|
|
3393
|
+
async putLocked(content, query, afterRelease, entry, held) {
|
|
3394
|
+
// flair#2478 part 3a: a checked write (putMemoryWithLock) joins its locked
|
|
3395
|
+
// transaction; the ordinary verb passes no entry.
|
|
3396
|
+
const locked = takeCheckedEntry(entry);
|
|
2548
3397
|
const reembedding = content?.embedding === null && content?.embeddingModel === null;
|
|
2549
3398
|
// flair#2141 S2: check the seed's fixed id against the operator-source
|
|
2550
3399
|
// reservation (resources/seed-reservation.ts).
|
|
@@ -2563,10 +3412,12 @@ export class Memory extends databases.flair.Memory {
|
|
|
2563
3412
|
// auditability, it must be gated to admins. Internal calls (no auth
|
|
2564
3413
|
// context) pass through, matching the pattern used in delete().
|
|
2565
3414
|
if (content._reindex === true) {
|
|
3415
|
+
if (locked)
|
|
3416
|
+
throw uncheckedBodyRefusal("_reindex");
|
|
2566
3417
|
const ctx = this.getContext?.();
|
|
2567
3418
|
const request = ctx?.request ?? ctx;
|
|
2568
3419
|
const actorId = request?.tpsAgent;
|
|
2569
|
-
if (actorId && !(await
|
|
3420
|
+
if (actorId && !(await annotatedCallerIsAdmin(request))) {
|
|
2570
3421
|
return new Response(JSON.stringify({ error: "reindex_admin_only" }), {
|
|
2571
3422
|
status: 403,
|
|
2572
3423
|
headers: { "Content-Type": "application/json" },
|
|
@@ -2609,16 +3460,18 @@ export class Memory extends databases.flair.Memory {
|
|
|
2609
3460
|
// one — before the row is staged, and again before the commit
|
|
2610
3461
|
// (confirmCommittedRow: the transaction is aborted and the staged row
|
|
2611
3462
|
// discarded). A missing row or an identity change seen by either read is
|
|
2612
|
-
// refused with the named 409 stored_row_changed
|
|
2613
|
-
// the final confirm read is not seen. Both reads use an explicit
|
|
3463
|
+
// refused with the named 409 stored_row_changed. Both reads use an explicit
|
|
2614
3464
|
// fresh context, never a contextless one (see resources/write-back.ts).
|
|
2615
|
-
|
|
3465
|
+
// flair#2656: the re-PUT owns its transaction even when the request
|
|
3466
|
+
// carries one (it writes one row and no pointer), so its commit has
|
|
3467
|
+
// settled when withOwnedTransaction returns and the read-back below runs
|
|
3468
|
+
// after it.
|
|
2616
3469
|
const beforeReindex = txnPausePoint("memory-reindex-pre");
|
|
2617
3470
|
if (beforeReindex)
|
|
2618
3471
|
await beforeReindex;
|
|
2619
3472
|
let reindexed;
|
|
2620
3473
|
try {
|
|
2621
|
-
reindexed = await
|
|
3474
|
+
reindexed = await withOwnedTransaction(ctx, async (c) => {
|
|
2622
3475
|
const confirmPause = txnPausePoint("memory-reindex");
|
|
2623
3476
|
if (confirmPause)
|
|
2624
3477
|
await confirmPause;
|
|
@@ -2633,14 +3486,12 @@ export class Memory extends databases.flair.Memory {
|
|
|
2633
3486
|
const stagedPause = txnPausePoint("memory-reindex-staged");
|
|
2634
3487
|
if (stagedPause)
|
|
2635
3488
|
await stagedPause;
|
|
2636
|
-
|
|
2637
|
-
|
|
2638
|
-
|
|
2639
|
-
|
|
2640
|
-
|
|
2641
|
-
|
|
2642
|
-
throw err;
|
|
2643
|
-
}
|
|
3489
|
+
await confirmCommittedRow(databases.flair.Memory, reindexExisting.id, (committed) => sameStoredRow(committed, reindexExisting));
|
|
3490
|
+
// Test-only: holds the re-PUT after its final pre-commit confirmation,
|
|
3491
|
+
// before its transaction commits.
|
|
3492
|
+
const confirmedPause = txnPausePoint("memory-reindex-confirmed");
|
|
3493
|
+
if (confirmedPause)
|
|
3494
|
+
await confirmedPause;
|
|
2644
3495
|
return r;
|
|
2645
3496
|
});
|
|
2646
3497
|
}
|
|
@@ -2654,8 +3505,26 @@ export class Memory extends databases.flair.Memory {
|
|
|
2654
3505
|
// refusal (writeResultResponse).
|
|
2655
3506
|
if (reindexed instanceof Response)
|
|
2656
3507
|
return writeResultResponse(reindexed);
|
|
3508
|
+
// embedding-space-guard slice 1 (see put()): the owned transaction has
|
|
3509
|
+
// returned, so notify the guard of the ATTEMPTED stamp now, before the
|
|
3510
|
+
// verification read; the read-back determines whether that stamp remains
|
|
3511
|
+
// stored. A refused or unknown verification still leaves the guard told
|
|
3512
|
+
// about the attempt.
|
|
3513
|
+
noteWriteStamp(reindexRow?.embeddingModel, reindexExisting);
|
|
3514
|
+
// flair#2478 slice 3c + flair#2656: read the committed row back after the
|
|
3515
|
+
// commit. A row that does not show the re-PUT answers 409
|
|
3516
|
+
// stored_row_changed; a failed read marks the id and answers 503
|
|
3517
|
+
// write_outcome_unknown.
|
|
3518
|
+
// Test-only: a fault-injection switch makes this read throw.
|
|
3519
|
+
const verifyTable = txnFault("memory-reindex-verify")
|
|
3520
|
+
? { get: async () => { throw new Error("injected post-commit read failure"); } }
|
|
3521
|
+
: databases.flair.Memory;
|
|
3522
|
+
const committedVerdict = await verifyCommittedFields(verifyTable, reindexRow.id, reindexRow, withoutHarperManagedFields(reindexRow));
|
|
3523
|
+
if (committedVerdict === "unreadable")
|
|
3524
|
+
return writeOutcomeUnknownFor(reindexRow.id);
|
|
3525
|
+
if (committedVerdict !== "shown")
|
|
3526
|
+
return storedRowChangedRefusal("Memory");
|
|
2657
3527
|
noteMemoryUpsert(content);
|
|
2658
|
-
noteWriteStamp(reindexRow?.embeddingModel, reindexExisting); // embedding-space-guard slice 1 (see post())
|
|
2659
3528
|
return rowWriteResponse(reindexed, reindexRow?.id, 0);
|
|
2660
3529
|
}
|
|
2661
3530
|
// flair#2441 + flair#2478 slice 1: a test-only pause of this PUT before its
|
|
@@ -2677,15 +3546,17 @@ export class Memory extends databases.flair.Memory {
|
|
|
2677
3546
|
// is no post-commit verification here (manual promotion's stamp reads the
|
|
2678
3547
|
// row in that transaction and refuses when there is none; it does not
|
|
2679
3548
|
// compare the written identity). Every other ordinary put owns its
|
|
2680
|
-
// transaction
|
|
2681
|
-
|
|
2682
|
-
const composed = composesCallerWrite(ctx);
|
|
3549
|
+
// transaction, as the `_reindex` re-PUT above does.
|
|
3550
|
+
const composed = !locked && composesCallerWrite(ctx);
|
|
2683
3551
|
let putResult;
|
|
2684
3552
|
// flair#2467: the post-redaction text fields this write stages, for the response.
|
|
2685
3553
|
let putStaged = {};
|
|
2686
3554
|
let putGrantedClosed = null;
|
|
2687
3555
|
try {
|
|
2688
|
-
|
|
3556
|
+
const writeScope = locked
|
|
3557
|
+
? (cx, fn) => locked.admission.join(cx, fn)
|
|
3558
|
+
: composed ? withSharedWriteTransaction : withOwnedTransaction;
|
|
3559
|
+
putResult = await writeScope(ctx, async (c) => {
|
|
2689
3560
|
// The authoritative stored read: the FIRST operation of an ordinary PUT's
|
|
2690
3561
|
// owned transaction (a composed put runs it in its caller's transaction,
|
|
2691
3562
|
// which may already have read). It reads by the URL-BOUND target id (a
|
|
@@ -2771,6 +3642,10 @@ export class Memory extends databases.flair.Memory {
|
|
|
2771
3642
|
const usedMemoryIds = content?.usedMemoryIds;
|
|
2772
3643
|
if (content && typeof content === "object")
|
|
2773
3644
|
delete content.usedMemoryIds;
|
|
3645
|
+
// A checked write records no citations: they take the cited ids' locks
|
|
3646
|
+
// after the write's lock is released, which its caller holds.
|
|
3647
|
+
if (locked && usedMemoryIds !== undefined)
|
|
3648
|
+
throw uncheckedBodyRefusal("citation-on-write");
|
|
2774
3649
|
// ── flair#1238: refuse an unrecognised durability (mirrors post()) ──
|
|
2775
3650
|
// put() is the other HTTP-reachable write path (fresh create via CLI, and
|
|
2776
3651
|
// the update/patch path). Same guard as post(): a present-but-unknown
|
|
@@ -2850,7 +3725,10 @@ export class Memory extends databases.flair.Memory {
|
|
|
2850
3725
|
// supersedes: optional reference to the ID of the memory this one
|
|
2851
3726
|
// replaces. Validates shape + cross-agent-write authorization (shared
|
|
2852
3727
|
// with post() — see validateAndAuthorizeSupersedes doc for why PUT needs
|
|
2853
|
-
// this too:
|
|
3728
|
+
// this too: HTTP POST /Memory reaches Memory.post(), and flair-client's
|
|
3729
|
+
// write() and update() both send PUT: default update() addresses the
|
|
3730
|
+
// existing id, while its preserveHistory option supplies a new id and
|
|
3731
|
+
// `supersedes`).
|
|
2854
3732
|
const supersede = await validateAndAuthorizeSupersedes(content, auth, ctx, preExisting, requestedVisibility);
|
|
2855
3733
|
if (supersede.denial)
|
|
2856
3734
|
return supersede.denial;
|
|
@@ -3035,17 +3913,35 @@ export class Memory extends databases.flair.Memory {
|
|
|
3035
3913
|
stripUndeclaredMemoryAttributes(content);
|
|
3036
3914
|
normalizeEmptyEmbedding(content);
|
|
3037
3915
|
if (isSkillWrite(content)) {
|
|
3916
|
+
// A skill write is a skill version write (part 3c), not a checked write.
|
|
3917
|
+
if (locked)
|
|
3918
|
+
throw uncheckedBodyRefusal("skill version");
|
|
3038
3919
|
const reservedId = [content?.id, this.getId?.()].find((candidate) => isReservedSeedId("Memory", candidate));
|
|
3039
3920
|
const skillStaged = { supplied: suppliedText, text: null };
|
|
3040
3921
|
// A PUT whose redaction replaced a value commits its redacted effective
|
|
3041
3922
|
// row, inherited fields included, so each field the reply's `stored`
|
|
3042
3923
|
// reports (the fields the request supplied, flair#2561) is what the row
|
|
3043
3924
|
// holds: the in-place unchanged-row check gets no requested fields for it.
|
|
3044
|
-
|
|
3045
|
-
|
|
3046
|
-
|
|
3047
|
-
|
|
3048
|
-
|
|
3925
|
+
const skillResult = await writeSkillCreateOrUpdate({
|
|
3926
|
+
ctx, auth, content, storedRow: preExisting, explicitPredecessor: preparedSkill.predecessor, method: "put", pointer,
|
|
3927
|
+
reembedding, requestedPayload: redactedValues > 0 ? undefined : requestedPayload,
|
|
3928
|
+
inPlaceId: reservedId != null ? String(reservedId) : null, staged: skillStaged, held,
|
|
3929
|
+
});
|
|
3930
|
+
if (skillResult instanceof SkillLockExtension)
|
|
3931
|
+
return skillResult;
|
|
3932
|
+
if (skillResult?.confirm) {
|
|
3933
|
+
// The write has committed; run the pre-confirmation work after this
|
|
3934
|
+
// verb's Memory lock releases, so a later same-subject write can run.
|
|
3935
|
+
return {
|
|
3936
|
+
skillThen: async () => {
|
|
3937
|
+
const denial = await skillResult.confirm();
|
|
3938
|
+
if (denial)
|
|
3939
|
+
return denial;
|
|
3940
|
+
return skillWriteResponse(skillResult, redactedValues, skillStaged.text);
|
|
3941
|
+
},
|
|
3942
|
+
};
|
|
3943
|
+
}
|
|
3944
|
+
return { skill: skillWriteResponse(skillResult, redactedValues, skillStaged.text) };
|
|
3049
3945
|
}
|
|
3050
3946
|
// flair#2441: this put is over the row read as `preExisting` (which
|
|
3051
3947
|
// `stampInstanceToken` copied its incarnation token from). The write
|
|
@@ -3110,6 +4006,11 @@ export class Memory extends databases.flair.Memory {
|
|
|
3110
4006
|
return refusal;
|
|
3111
4007
|
throw err;
|
|
3112
4008
|
}
|
|
4009
|
+
// A skill PUT that needs ids it did not hold asks the verb for them.
|
|
4010
|
+
if (putResult instanceof SkillLockExtension)
|
|
4011
|
+
return putResult;
|
|
4012
|
+
if (putResult && typeof putResult.skillThen === "function")
|
|
4013
|
+
return putResult;
|
|
3113
4014
|
// A skill PUT answers from its own write (no ordinary-row post-commit step).
|
|
3114
4015
|
if (putResult && putResult.skill !== undefined)
|
|
3115
4016
|
return putResult.skill;
|
|
@@ -3118,6 +4019,11 @@ export class Memory extends databases.flair.Memory {
|
|
|
3118
4019
|
// (a storage-layer Response was replaced in the transaction, storageResult).
|
|
3119
4020
|
if (putResult instanceof Response)
|
|
3120
4021
|
return writeResultResponse(putResult);
|
|
4022
|
+
// A checked write has only staged its row. It continues below once its
|
|
4023
|
+
// locked scope has committed, as that scope's confirmation; a scope that
|
|
4024
|
+
// does not commit ends it here (flair#2478 part 3a).
|
|
4025
|
+
if (locked && !(await locked.stage()))
|
|
4026
|
+
return undefined;
|
|
3121
4027
|
// embedding-space-guard slice 1 (see post()): the ordinary row write has
|
|
3122
4028
|
// returned from its transaction, so the guard is notified now, with the
|
|
3123
4029
|
// stored stamp and the row this PUT replaced (flair#2573), before the
|
|
@@ -3134,7 +4040,7 @@ export class Memory extends databases.flair.Memory {
|
|
|
3134
4040
|
const verifyPause = txnPausePoint("memory-put-verify");
|
|
3135
4041
|
if (verifyPause)
|
|
3136
4042
|
await verifyPause;
|
|
3137
|
-
const verified = await
|
|
4043
|
+
const verified = await verifyWrittenRow(databases.flair.Memory, putResult.content, putResult.fallbackId, { expectedToken: putResult.content?.instanceToken }, POSTCOMMIT_VERIFY_FIELDS, locked ? { exactFields: locked.confirmFields } : undefined);
|
|
3138
4044
|
if (verified.unknown)
|
|
3139
4045
|
return writeOutcomeUnknownFor(putResult.content?.id ?? putResult.fallbackId);
|
|
3140
4046
|
if (verified.mismatch)
|
|
@@ -3158,20 +4064,67 @@ export class Memory extends databases.flair.Memory {
|
|
|
3158
4064
|
if (putResult.close?.granteeId === undefined)
|
|
3159
4065
|
await closeSupersededIfNeeded(ctx, putResult.content, putResult.close, "put");
|
|
3160
4066
|
// flair#744 slice A: citation-on-write — POST-COMMIT, fully
|
|
3161
|
-
// failure-isolated (see post()'s identical comment above).
|
|
4067
|
+
// failure-isolated (see post()'s identical comment above). flair#2478: it
|
|
4068
|
+
// is queued here and put() runs it after releasing this id's lock.
|
|
3162
4069
|
if (putResult.usedMemoryIds !== undefined) {
|
|
3163
|
-
|
|
3164
|
-
|
|
3165
|
-
|
|
3166
|
-
|
|
3167
|
-
|
|
3168
|
-
|
|
4070
|
+
const { auth: citingAuth, usedMemoryIds } = putResult;
|
|
4071
|
+
afterRelease.push(async () => {
|
|
4072
|
+
try {
|
|
4073
|
+
await recordCitations(ctx, citingAuth, usedMemoryIds, new Date().toISOString());
|
|
4074
|
+
}
|
|
4075
|
+
catch (err) {
|
|
4076
|
+
console.error("Memory.put: citation recording failed (write already committed)", err);
|
|
4077
|
+
}
|
|
4078
|
+
});
|
|
3169
4079
|
}
|
|
3170
4080
|
return buildWriteResponse(putResult.content, result, putResult.dedupMatch, putResult.redactedValues, putStaged);
|
|
3171
4081
|
}
|
|
4082
|
+
/** Past the refusals that read no row, DELETE reads the addressed row with no
|
|
4083
|
+
* lock held (discovery only) and, for a skill row, finds the live head its
|
|
4084
|
+
* skill writer closes (for an older version, another row). It then takes the
|
|
4085
|
+
* addressed id's lock and that head's, which cover the authorization,
|
|
4086
|
+
* planning, write and owned transaction's commit that follow. When the head
|
|
4087
|
+
* the skill writer resolves under the locks is not one of the held ids,
|
|
4088
|
+
* nothing is written and the DELETE discovers and locks again, at most
|
|
4089
|
+
* SKILL_DELETE_HEAD_ATTEMPTS attempts in all, then answers `503 memory_busy`
|
|
4090
|
+
* (flair#2478 slice 1 part 2). */
|
|
3172
4091
|
async delete(id) {
|
|
4092
|
+
const ids = deleteLockIds(this, id);
|
|
4093
|
+
if (ids.length === 0)
|
|
4094
|
+
return this.deleteLocked(id);
|
|
4095
|
+
// The refusals that read no row answer before the head discovery reads it.
|
|
3173
4096
|
const ctx = this.getContext?.();
|
|
3174
|
-
const
|
|
4097
|
+
const early = this.deleteRefusalBeforeRead(id, ctx, await resolveAgentAuth(ctx));
|
|
4098
|
+
if (early)
|
|
4099
|
+
return early;
|
|
4100
|
+
for (let attempt = 1; attempt <= SKILL_DELETE_HEAD_ATTEMPTS; attempt++) {
|
|
4101
|
+
const head = await skillDeleteHeadId(() => super.get(id));
|
|
4102
|
+
if (head !== null) {
|
|
4103
|
+
// Test-only: held after this attempt found the head, before it takes
|
|
4104
|
+
// the locks.
|
|
4105
|
+
const discovered = attempt === 1 ? txnPausePoint("memory-delete-head-first")
|
|
4106
|
+
: attempt === 2 ? txnPausePoint("memory-delete-head-second")
|
|
4107
|
+
: txnPausePoint("memory-delete-head-third");
|
|
4108
|
+
if (discovered)
|
|
4109
|
+
await discovered;
|
|
4110
|
+
}
|
|
4111
|
+
const headLock = { ids: [], outside: false };
|
|
4112
|
+
const outcome = await withMemoryWriteLock(memoryWriteLockStore(), head === null ? ids : [...ids, head], (locked) => {
|
|
4113
|
+
headLock.ids = memoryWriteLockTokenIds(locked);
|
|
4114
|
+
return this.deleteLocked(id, headLock);
|
|
4115
|
+
}, { phase: "delete" });
|
|
4116
|
+
if (outcome.kind !== "done")
|
|
4117
|
+
return memoryLockRefusal(outcome, memoryLockCallerId(this));
|
|
4118
|
+
if (!headLock.outside)
|
|
4119
|
+
return outcome.value;
|
|
4120
|
+
}
|
|
4121
|
+
return memoryBusyResponse(memoryLockCallerId(this));
|
|
4122
|
+
}
|
|
4123
|
+
/** The DELETE refusals that read no Memory row: an anonymous caller, an
|
|
4124
|
+
* outcome-unknown id, a reserved seed id and a `.content`-suffixed target.
|
|
4125
|
+
* delete() answers them before its head discovery reads the row;
|
|
4126
|
+
* deleteLocked checks them again under the lock. */
|
|
4127
|
+
deleteRefusalBeforeRead(id, ctx, auth) {
|
|
3175
4128
|
if (auth.kind === "anonymous")
|
|
3176
4129
|
return UNAUTH();
|
|
3177
4130
|
// flair#2478: a DELETE of an id whose last owned PUT/PATCH settled with an
|
|
@@ -3189,6 +4142,16 @@ export class Memory extends databases.flair.Memory {
|
|
|
3189
4142
|
const contentSuffixDenial = refuseContentSuffixId([id, ...writeTargetIds(this, id && typeof id === "object" ? id : undefined)], id);
|
|
3190
4143
|
if (contentSuffixDenial)
|
|
3191
4144
|
return contentSuffixDenial;
|
|
4145
|
+
return null;
|
|
4146
|
+
}
|
|
4147
|
+
async deleteLocked(id, headLock) {
|
|
4148
|
+
const ctx = this.getContext?.();
|
|
4149
|
+
const auth = await resolveAgentAuth(ctx);
|
|
4150
|
+
const refusal = this.deleteRefusalBeforeRead(id, ctx, auth);
|
|
4151
|
+
if (refusal)
|
|
4152
|
+
return refusal;
|
|
4153
|
+
if (auth.kind === "anonymous")
|
|
4154
|
+
return UNAUTH();
|
|
3192
4155
|
// Read stored ownership, not the read-scoped get() response. Enforce here
|
|
3193
4156
|
// as well as middleware so MCP/in-process callers have the same policy.
|
|
3194
4157
|
const record = await super.get(id);
|
|
@@ -3205,81 +4168,195 @@ export class Memory extends databases.flair.Memory {
|
|
|
3205
4168
|
const beforeSkillDelete = txnPausePoint("memory-skill-delete-pre");
|
|
3206
4169
|
if (beforeSkillDelete)
|
|
3207
4170
|
await beforeSkillDelete;
|
|
3208
|
-
return await writeSkillDelete({ ctx, auth, record });
|
|
4171
|
+
return await writeSkillDelete({ ctx, auth, record, headLock });
|
|
3209
4172
|
}
|
|
3210
4173
|
// Durability controls retention, not the owner's authority to delete.
|
|
3211
|
-
// A1' item 2 (adjudication 0a/0c): the Memory delete
|
|
3212
|
-
//
|
|
3213
|
-
//
|
|
3214
|
-
//
|
|
3215
|
-
//
|
|
3216
|
-
//
|
|
3217
|
-
// owned here can use the synchronous hook after the shared write returns.
|
|
3218
|
-
// Capture ownership before the helper changes the context's transaction.
|
|
3219
|
-
const requestOwnsTransaction = isJoinableTransaction(ctx);
|
|
4174
|
+
// A1' item 2 (adjudication 0a/0c): the Memory delete, its pointer delete
|
|
4175
|
+
// and its deletion-history record share ONE owned transaction; a failing
|
|
4176
|
+
// pointer delete aborts it, so nothing is deleted; failures are NOT
|
|
4177
|
+
// swallowed. The transaction is OWNED here (withOwnedTransaction) so it
|
|
4178
|
+
// commits before this method returns, which lets the confirmation below
|
|
4179
|
+
// read the committed store (flair#2632).
|
|
3220
4180
|
const deletionActor = auth.kind === "agent" ? auth.agentId : null;
|
|
3221
4181
|
const deletionSourceClass = auth.kind === "internal" ? "internal" : auth.isAdmin ? "admin" : "agent";
|
|
3222
4182
|
// 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.
|
|
3224
|
-
|
|
3225
|
-
|
|
4183
|
+
// owner change can commit first and be seen by the re-read inside.
|
|
4184
|
+
const target = record ? {
|
|
4185
|
+
id: String(record.id),
|
|
4186
|
+
owner: record[RECORD_TYPES.Memory.ownerField] ?? null,
|
|
4187
|
+
token: record.instanceToken ?? null,
|
|
4188
|
+
} : null;
|
|
3226
4189
|
const beforeDelete = txnPausePoint("memory-delete-pre");
|
|
3227
4190
|
if (beforeDelete)
|
|
3228
4191
|
await beforeDelete;
|
|
3229
|
-
|
|
3230
|
-
|
|
3231
|
-
|
|
3232
|
-
|
|
3233
|
-
|
|
3234
|
-
|
|
4192
|
+
// flair#2632: ordinary, non-skill DELETE confirms committed row absence.
|
|
4193
|
+
// Retry dropped removals with fresh reads; refuse a changed id/owner/token.
|
|
4194
|
+
const targetIdProbe = typeof id === "string" ? id : record?.id;
|
|
4195
|
+
let applied = false;
|
|
4196
|
+
for (let attempt = 1; attempt <= DELETE_APPLY_ATTEMPTS; attempt++) {
|
|
4197
|
+
let historyId = null;
|
|
4198
|
+
let pointerBefore = null;
|
|
4199
|
+
const outcome = await withOwnedTransaction(ctx, async (c) => {
|
|
4200
|
+
const deletedId = typeof id === "string" ? id : record?.id;
|
|
4201
|
+
if (typeof deletedId !== "string" || !deletedId)
|
|
4202
|
+
return { kind: "absent" };
|
|
4203
|
+
const stored = await databases.flair.Memory.get(deletedId, c);
|
|
4204
|
+
if (!stored)
|
|
4205
|
+
return { kind: "absent" };
|
|
4206
|
+
const nonAdmin = auth.kind === "agent" && !auth.isAdmin;
|
|
4207
|
+
if (nonAdmin && isForbiddenOwnerMutation(stored, RECORD_TYPES.Memory.ownerField, auth.agentId)) {
|
|
4208
|
+
// The caller passed the owner check at the pre-read above, so a
|
|
4209
|
+
// mismatch here is a change committed since — refuse it, do not delete.
|
|
4210
|
+
return { kind: "response", response: ownerChangedRefusal("Memory") };
|
|
4211
|
+
}
|
|
4212
|
+
if (!target || !sameDeleteTarget(stored, target, RECORD_TYPES.Memory.ownerField)) {
|
|
4213
|
+
return { kind: "response", response: storedRowChangedRefusal("Memory") };
|
|
4214
|
+
}
|
|
4215
|
+
if (nonAdmin) {
|
|
4216
|
+
// Test-only: the transaction pauses between its ownership read and its
|
|
4217
|
+
// delete.
|
|
4218
|
+
const pause = txnPausePoint("memory-delete");
|
|
4219
|
+
if (pause)
|
|
4220
|
+
await pause;
|
|
4221
|
+
// Confirmation read of the COMMITTED row in an explicit fresh context
|
|
4222
|
+
// (never contextless — see resources/owner-delete-recheck.ts's header).
|
|
4223
|
+
const confirmed = await databases.flair.Memory.get(deletedId, {});
|
|
4224
|
+
if (confirmed && isForbiddenOwnerMutation(confirmed, RECORD_TYPES.Memory.ownerField, auth.agentId)) {
|
|
4225
|
+
return { kind: "response", response: ownerChangedRefusal("Memory") };
|
|
4226
|
+
}
|
|
4227
|
+
}
|
|
4228
|
+
// Captured for compensation: this attempt's pointer delete may land even
|
|
4229
|
+
// when its row removal is dropped.
|
|
4230
|
+
pointerBefore = await loadStoredPointer(deletedId, c);
|
|
4231
|
+
const d = await databases.flair.Memory.delete(deletedId, c);
|
|
4232
|
+
if (d !== true)
|
|
4233
|
+
throw new Error("Memory row delete was not confirmed");
|
|
4234
|
+
const pointerDenial = await deletePointerRow(deletedId, c);
|
|
4235
|
+
if (pointerDenial)
|
|
4236
|
+
return { kind: "response", response: pointerDenial };
|
|
4237
|
+
historyId = await recordMemoryDeletion({
|
|
4238
|
+
memoryId: deletedId,
|
|
4239
|
+
memoryInstanceToken: stored.instanceToken ?? null,
|
|
4240
|
+
durability: stored.durability ?? null,
|
|
4241
|
+
actor: deletionActor,
|
|
4242
|
+
sourceClass: deletionSourceClass,
|
|
4243
|
+
}, c);
|
|
4244
|
+
return { kind: "staged" };
|
|
4245
|
+
});
|
|
4246
|
+
if (outcome.kind === "response")
|
|
4247
|
+
return outcome.response;
|
|
4248
|
+
if (outcome.kind === "absent")
|
|
3235
4249
|
return false;
|
|
3236
|
-
|
|
3237
|
-
|
|
3238
|
-
|
|
3239
|
-
|
|
3240
|
-
|
|
4250
|
+
// The owned transaction has committed. Its success is not proof that the
|
|
4251
|
+
// queued delete was applied: confirm against the committed store.
|
|
4252
|
+
const targetId = String(targetIdProbe);
|
|
4253
|
+
const after = await databases.flair.Memory.get(targetId, {});
|
|
4254
|
+
if (!after) {
|
|
4255
|
+
applied = true;
|
|
4256
|
+
break;
|
|
3241
4257
|
}
|
|
3242
|
-
|
|
3243
|
-
|
|
3244
|
-
|
|
3245
|
-
|
|
3246
|
-
|
|
3247
|
-
|
|
3248
|
-
//
|
|
3249
|
-
|
|
3250
|
-
|
|
3251
|
-
|
|
3252
|
-
return ownerChangedRefusal("Memory");
|
|
3253
|
-
}
|
|
4258
|
+
// Still stored: the removal was dropped while this attempt's history and
|
|
4259
|
+
// pointer writes landed. Undo them before the next attempt.
|
|
4260
|
+
const compensation = await compensateDroppedRemoval(targetId, historyId, pointerBefore, ctx);
|
|
4261
|
+
if (compensation)
|
|
4262
|
+
return compensation;
|
|
4263
|
+
if (attempt < DELETE_APPLY_ATTEMPTS) {
|
|
4264
|
+
// Test-only: holds a delete whose removal did not land between attempts.
|
|
4265
|
+
const retry = txnPausePoint("memory-delete-retry");
|
|
4266
|
+
if (retry)
|
|
4267
|
+
await retry;
|
|
3254
4268
|
}
|
|
3255
|
-
|
|
3256
|
-
|
|
3257
|
-
|
|
3258
|
-
|
|
3259
|
-
|
|
3260
|
-
|
|
3261
|
-
|
|
3262
|
-
|
|
3263
|
-
|
|
3264
|
-
|
|
3265
|
-
|
|
3266
|
-
sourceClass: deletionSourceClass,
|
|
3267
|
-
}, c);
|
|
3268
|
-
return d;
|
|
3269
|
-
});
|
|
3270
|
-
if (deleteResult instanceof Response)
|
|
3271
|
-
return deleteResult;
|
|
3272
|
-
if (deleteResult === false)
|
|
3273
|
-
return false;
|
|
3274
|
-
// Use the RESOLVED deleted id (a by-record delete carries only `id`, so the
|
|
3275
|
-
// stored row's id is the fallback). An owned transaction has committed;
|
|
3276
|
-
// a request-owned write waits for the committed change feed instead.
|
|
3277
|
-
const resolvedDeletedId = typeof id === "string" ? id : record?.id;
|
|
3278
|
-
if (!requestOwnsTransaction && typeof resolvedDeletedId === "string" && resolvedDeletedId.length > 0) {
|
|
3279
|
-
noteMemoryDelete(resolvedDeletedId);
|
|
4269
|
+
}
|
|
4270
|
+
if (!applied)
|
|
4271
|
+
return deleteNotAppliedRefusal("Memory", DELETE_APPLY_ATTEMPTS);
|
|
4272
|
+
// Test-only: held after the owned transaction committed and the removal was
|
|
4273
|
+
// confirmed, while the id's lock is still held (flair#2478).
|
|
4274
|
+
const committedPause = txnPausePoint("memory-delete-committed");
|
|
4275
|
+
if (committedPause)
|
|
4276
|
+
await committedPause;
|
|
4277
|
+
// An owned transaction has committed and its removal is confirmed.
|
|
4278
|
+
if (typeof targetIdProbe === "string" && targetIdProbe.length > 0) {
|
|
4279
|
+
noteMemoryDelete(targetIdProbe);
|
|
3280
4280
|
}
|
|
3281
4281
|
if (typeof id === "string")
|
|
3282
4282
|
await clearHitStats(id, ctx).catch(() => { });
|
|
3283
|
-
return
|
|
4283
|
+
return true;
|
|
4284
|
+
}
|
|
4285
|
+
}
|
|
4286
|
+
/** The ids a checked write writes: its target, the body id and, for a PUT, the
|
|
4287
|
+
* `supersedes` target it closes (raw and canonical). */
|
|
4288
|
+
function checkedWriteIds(verb, input) {
|
|
4289
|
+
const ids = [input.id];
|
|
4290
|
+
const bodyId = input.content.id;
|
|
4291
|
+
if (typeof bodyId === "string" || typeof bodyId === "number")
|
|
4292
|
+
ids.push(String(bodyId));
|
|
4293
|
+
const supersedes = input.content.supersedes;
|
|
4294
|
+
if (verb === "put" && typeof supersedes === "string") {
|
|
4295
|
+
ids.push(supersedes);
|
|
4296
|
+
const canonical = resolveMemoryReferenceId(supersedes);
|
|
4297
|
+
if (canonical !== undefined)
|
|
4298
|
+
ids.push(canonical);
|
|
4299
|
+
}
|
|
4300
|
+
return ids;
|
|
4301
|
+
}
|
|
4302
|
+
function enterCheckedWrite(verb, held, tx, input) {
|
|
4303
|
+
let admission;
|
|
4304
|
+
let snapshot;
|
|
4305
|
+
try {
|
|
4306
|
+
if (!input || typeof input.id !== "string" || input.id.length === 0 ||
|
|
4307
|
+
input.content === null || typeof input.content !== "object" || Array.isArray(input.content)) {
|
|
4308
|
+
throw new TypeError("a checked Memory write names a string id and an object body");
|
|
4309
|
+
}
|
|
4310
|
+
// One snapshot, taken before admission, decides the write set and is the
|
|
4311
|
+
// write. The write set comes from its id strings, so a later change to
|
|
4312
|
+
// the caller's input cannot change it. The body is a structuredClone
|
|
4313
|
+
// (not a JSON round trip: a body read from a stored row can hold values
|
|
4314
|
+
// JSON would not keep as they are, a typed-array vector or a Date), so
|
|
4315
|
+
// a later change to a nested value does not reach the write either,
|
|
4316
|
+
// except through memory a SharedArrayBuffer shares, which a clone keeps
|
|
4317
|
+
// shared. A body it cannot clone is rejected here, before admission.
|
|
4318
|
+
snapshot = Object.freeze({
|
|
4319
|
+
id: input.id,
|
|
4320
|
+
content: structuredClone(input.content),
|
|
4321
|
+
confirmFields: Object.freeze([...(input.confirmFields ?? [])]),
|
|
4322
|
+
});
|
|
4323
|
+
admission = admitLockedMemoryWrite(held, tx, memoryWriteLockStore(), checkedWriteIds(verb, snapshot));
|
|
3284
4324
|
}
|
|
4325
|
+
catch (error) {
|
|
4326
|
+
return Promise.reject(error);
|
|
4327
|
+
}
|
|
4328
|
+
return admission.track(snapshot.id, async (stage) => {
|
|
4329
|
+
const getResource = Memory.getResource;
|
|
4330
|
+
if (typeof getResource !== "function")
|
|
4331
|
+
throw new Error("flair: Memory.getResource is unavailable; a checked Memory write is refused");
|
|
4332
|
+
const resource = await getResource.call(Memory, { id: snapshot.id }, admission.context, { hasContent: true, type: "update", method: verb });
|
|
4333
|
+
const entry = Object.freeze({});
|
|
4334
|
+
checkedEntries.set(entry, { admission, confirmFields: snapshot.confirmFields, stage, used: false });
|
|
4335
|
+
const body = snapshot.content;
|
|
4336
|
+
return verb === "put" ? resource.putLocked(body, undefined, [], entry) : resource.patchLocked(body, undefined, entry);
|
|
4337
|
+
});
|
|
4338
|
+
}
|
|
4339
|
+
/**
|
|
4340
|
+
* flair#2478 part 3a — a Memory PUT made while the caller already holds the
|
|
4341
|
+
* per-id lock. Not a Harper verb: an ordinary function. `held` must be a live
|
|
4342
|
+
* lock token acquired on `Memory.primaryStore` for every id the write names
|
|
4343
|
+
* (its target, the body id and a `supersedes` target), and `tx` the locked
|
|
4344
|
+
* transaction scope opened on that acquisition (resources/memory-write-transaction.ts);
|
|
4345
|
+
* otherwise it is refused (`MemoryWriteCapabilityError`) and nothing is staged.
|
|
4346
|
+
* It enters the ordinary PUT's write body without acquiring a lock or opening a
|
|
4347
|
+
* transaction, joins the scope's transaction and returns `staged`. After the
|
|
4348
|
+
* scope commits, the body resumes for the PUT's post-commit steps; its
|
|
4349
|
+
* verification also compares the row's id and `confirmFields`. A skill write
|
|
4350
|
+
* or an `_reindex` body is refused.
|
|
4351
|
+
*/
|
|
4352
|
+
export function putMemoryWithLock(held, tx, input) {
|
|
4353
|
+
return enterCheckedWrite("put", held, tx, input);
|
|
4354
|
+
}
|
|
4355
|
+
/**
|
|
4356
|
+
* flair#2478 part 3a — a Memory PATCH made while the caller already holds the
|
|
4357
|
+
* per-id lock; the PATCH counterpart of {@link putMemoryWithLock} (its target
|
|
4358
|
+
* and body id are its write set). A re-embed body is refused.
|
|
4359
|
+
*/
|
|
4360
|
+
export function patchMemoryWithLock(held, tx, input) {
|
|
4361
|
+
return enterCheckedWrite("patch", held, tx, input);
|
|
3285
4362
|
}
|