@tpsdev-ai/flair 0.62.0 → 0.63.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -6
- package/SECURITY.md +18 -10
- package/config.yaml +11 -11
- package/dist/bridges/runtime/execute.js +1 -0
- package/dist/bridges/types.js +1 -0
- package/dist/build-info.json +3 -3
- package/dist/cli.js +66 -122
- package/dist/commands/agent.js +27 -65
- package/dist/commands/backup-approval.js +218 -0
- package/dist/commands/backup.js +37 -33
- package/dist/commands/bootstrap.js +3 -1
- package/dist/commands/deploy.js +37 -7
- package/dist/commands/doctor.js +119 -0
- package/dist/commands/export.js +3 -4
- 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 +131 -19
- package/dist/commands/init.js +7 -7
- package/dist/commands/integrity.js +5 -6
- package/dist/commands/mcp.js +11 -17
- package/dist/commands/memory.js +33 -15
- package/dist/commands/orgevent.js +5 -10
- package/dist/commands/principal.js +13 -25
- package/dist/commands/quality.js +3 -0
- package/dist/commands/rem.js +484 -65
- package/dist/commands/restore.js +352 -44
- package/dist/commands/service.js +84 -2
- package/dist/commands/soul.js +0 -6
- package/dist/commands/status.js +51 -33
- 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 +7 -2
- package/dist/fabric-upgrade.js +12 -2
- package/dist/federation/presence-send.js +139 -0
- package/dist/federation-verify.js +269 -177
- package/dist/install/clients.js +171 -35
- package/dist/lib/agent-id-rule.js +44 -2
- package/dist/lib/atomic-write.js +1 -1
- package/dist/lib/auth-resolve.js +1028 -52
- 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/launchd-management.js +14 -3
- 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/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/restore-archive.js +760 -0
- package/dist/lib/restore-verify.js +1 -1
- package/dist/lib/skill-assignment-preflight.js +159 -0
- package/dist/lib/skill-seed.js +91 -8
- package/dist/lib/skill-tombstone-doctor.js +133 -0
- package/dist/lib/soul-scope-fields.js +26 -0
- package/dist/lib/uninstall-purge.js +266 -11
- package/dist/lib/upgrade-prior-liveness.js +2 -1
- package/dist/mcp-client-assertion.js +2 -10
- 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 +1303 -270
- 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 +43 -4
- package/dist/resources/host-pointer/registry.js +29 -0
- package/dist/resources/host-pointer-adapter.js +1 -0
- 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-handler.js +106 -12
- package/dist/resources/mcp-oauth-flag.js +12 -14
- package/dist/resources/mcp-oauth.js +430 -53
- package/dist/resources/mcp-tools.js +60 -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 +384 -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/lib/agent-id-rule.js +44 -2
- package/dist/src/lib/atomic-write.js +1 -1
- package/dist/src/lib/federation-retry-row.js +101 -0
- package/dist/src/lib/instruction-event-contract.js +17 -0
- package/dist/src/lib/memory-attributes.js +2 -0
- package/dist/src/lib/open-live-row.js +20 -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 +18 -9
- package/docs/api-reference.md +126 -28
- package/docs/auth.md +40 -18
- package/docs/claude-code.md +3 -3
- package/docs/deploying-on-fabric.md +108 -0
- package/docs/deployment.md +17 -0
- package/docs/embedding-in-a-harper-app.md +16 -14
- package/docs/entity-vocabulary.md +3 -6
- package/docs/federation.md +29 -2
- 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 +2 -2
- 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 +14 -0
- 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, 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,38 @@ 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
|
+
joinCallerTransaction: method === "post",
|
|
1196
1445
|
subjectId,
|
|
1197
1446
|
agentId: String(content.agentId),
|
|
1447
|
+
deferConfirmation: true,
|
|
1448
|
+
heldMemoryIds: [...heldIds],
|
|
1198
1449
|
head: (shared) => resolveSkillHead(subjectId, addressedId, shared),
|
|
1199
|
-
plan: async (head, shared) => {
|
|
1450
|
+
plan: async (head, shared, attempt) => {
|
|
1451
|
+
if (head && !heldIds.has(String(head.id))) {
|
|
1452
|
+
headMoved.id = String(head.id);
|
|
1453
|
+
return skillWriteConflict("skill_head_moved");
|
|
1454
|
+
}
|
|
1455
|
+
// A superseding plan from a joined attempt is planned again, owned
|
|
1456
|
+
// (flair#2645); no state from the earlier attempt carries over.
|
|
1457
|
+
joinsCaller = attempt.joined;
|
|
1458
|
+
captured.row = null;
|
|
1459
|
+
captured.closed = null;
|
|
1460
|
+
unchangedHead = null;
|
|
1461
|
+
successorBasis = null;
|
|
1462
|
+
if (args.staged) {
|
|
1463
|
+
delete args.staged.row;
|
|
1464
|
+
delete args.staged.joined;
|
|
1465
|
+
}
|
|
1200
1466
|
const stale = await validateSkillSnapshots(storedRow, explicitPredecessor, content.id ?? null, shared);
|
|
1201
1467
|
const denied = await authorizeSkillOwners(ctx, auth, [storedRow, explicitPredecessor, head ?? content], shared);
|
|
1202
1468
|
if (denied)
|
|
@@ -1232,6 +1498,13 @@ async function writeSkillCreateOrUpdate(args) {
|
|
|
1232
1498
|
}
|
|
1233
1499
|
await applyOriginatorInstanceId(successor, liveHead);
|
|
1234
1500
|
applyFederationBookkeeping(successor, liveHead);
|
|
1501
|
+
normalizeEmptyEmbedding(successor);
|
|
1502
|
+
if (joinsCaller)
|
|
1503
|
+
successorBasis = await databases.flair.Memory.get(successorId, shared);
|
|
1504
|
+
if (args.staged) {
|
|
1505
|
+
args.staged.row = structuredClone(successor);
|
|
1506
|
+
args.staged.joined = joinsCaller;
|
|
1507
|
+
}
|
|
1235
1508
|
captured.row = successor;
|
|
1236
1509
|
const value = typeof successor.content === "string" ? successor.content : null;
|
|
1237
1510
|
const visibility = skillVersionVisibility(successor);
|
|
@@ -1247,18 +1520,78 @@ async function writeSkillCreateOrUpdate(args) {
|
|
|
1247
1520
|
},
|
|
1248
1521
|
hooks: {
|
|
1249
1522
|
...defaultSkillHooks,
|
|
1523
|
+
authorizeClose: (row, shared) => authorizeSkillOwners(ctx, auth, [row], shared),
|
|
1250
1524
|
pointer: async (shared) => {
|
|
1525
|
+
// Test-only: holds a skill POST after its successor (and predecessor
|
|
1526
|
+
// close) are staged, before the transaction commits (flair#2656).
|
|
1527
|
+
const stagedPause = txnPausePoint("memory-post-skill-staged");
|
|
1528
|
+
if (stagedPause)
|
|
1529
|
+
await stagedPause;
|
|
1251
1530
|
if (captured.closed) {
|
|
1252
1531
|
const denial = await deletePointerRow(String(captured.closed.id), shared);
|
|
1253
1532
|
if (denial)
|
|
1254
1533
|
return denial;
|
|
1255
1534
|
}
|
|
1256
|
-
|
|
1257
|
-
? persistPointerRow({ ...pointer.row, memoryId: successorId, memoryInstanceToken: captured.row?.instanceToken }, shared)
|
|
1535
|
+
const pointerDenial = pointer?.row
|
|
1536
|
+
? await persistPointerRow({ ...pointer.row, memoryId: successorId, memoryInstanceToken: captured.row?.instanceToken }, shared)
|
|
1258
1537
|
: null;
|
|
1538
|
+
if (pointerDenial)
|
|
1539
|
+
return pointerDenial;
|
|
1540
|
+
if (joinsCaller) {
|
|
1541
|
+
await pausePostVerification(true);
|
|
1542
|
+
const committed = await databases.flair.Memory.get(successorId, {});
|
|
1543
|
+
// A skill write keeps its own target-changed refusal (flair#2263).
|
|
1544
|
+
if (!sameStoredRow(committed, successorBasis))
|
|
1545
|
+
return skillWriteConflict("skill_target_changed");
|
|
1546
|
+
}
|
|
1547
|
+
return null;
|
|
1259
1548
|
},
|
|
1260
1549
|
},
|
|
1261
1550
|
});
|
|
1551
|
+
// The plan's rows: the stored row this write addresses, and the live head
|
|
1552
|
+
// when the addressed version is closed. The verb holds the addressed id
|
|
1553
|
+
// before its read; a head only a read can name is returned for the next
|
|
1554
|
+
// acquisition. The writer's head check adds the explicit predecessor it
|
|
1555
|
+
// validates and closes, so both are held before the write. A server-allocated
|
|
1556
|
+
// successor names no stored row until this write creates it, so it is not
|
|
1557
|
+
// held. A pure create under a fresh server-allocated id writes no row another
|
|
1558
|
+
// writer can name, so it takes no per-id lock (the design's create case).
|
|
1559
|
+
// Under the locks the head is resolved again; a head outside the held set is
|
|
1560
|
+
// refused, so a moved or vanished head is never written through.
|
|
1561
|
+
const heldIds = new Set((args.held?.ids ?? []).map(String));
|
|
1562
|
+
const pureCreate = !addressedId && !explicitPredecessor && !inPlaceId && content.id == null;
|
|
1563
|
+
if (!pureCreate) {
|
|
1564
|
+
// A server-allocated successor id is not required: it names no stored row
|
|
1565
|
+
// until this write creates it. A stored row this write addresses is.
|
|
1566
|
+
const rows = storedRow ? [String(storedRow.id)] : [];
|
|
1567
|
+
const missing = rows.filter((id) => id.length > 0 && !heldIds.has(id));
|
|
1568
|
+
if (missing.length > 0)
|
|
1569
|
+
return new SkillLockExtension(missing);
|
|
1570
|
+
}
|
|
1571
|
+
// The addressed version (or an explicit predecessor) is closed, so the row
|
|
1572
|
+
// this write closes is the subject's live head. Only a head read names it;
|
|
1573
|
+
// return that read to the verb so the head is held before the instruction
|
|
1574
|
+
// lock, not after it.
|
|
1575
|
+
const addressedClosed = (storedRow && !isOpenLiveRow(storedRow)) ||
|
|
1576
|
+
(!storedRow && explicitPredecessor && !isOpenLiveRow(explicitPredecessor));
|
|
1577
|
+
if (addressedClosed && addressedId) {
|
|
1578
|
+
// The head this write closes is named only by a read. A head the attempt
|
|
1579
|
+
// does not hold is returned for the next acquisition; when there is none
|
|
1580
|
+
// (a deleted head), the plan below refuses with main's 409.
|
|
1581
|
+
let head = null;
|
|
1582
|
+
try {
|
|
1583
|
+
head = await resolveSkillHead(subjectId, addressedId, {});
|
|
1584
|
+
}
|
|
1585
|
+
catch {
|
|
1586
|
+
/* the plan's read under the locks decides */
|
|
1587
|
+
}
|
|
1588
|
+
if (head && !heldIds.has(String(head.id)))
|
|
1589
|
+
return new SkillLockExtension([String(head.id)]);
|
|
1590
|
+
}
|
|
1591
|
+
const headMoved = { id: null };
|
|
1592
|
+
const outcome = await runSkillWrite(heldIds, headMoved);
|
|
1593
|
+
if (headMoved.id)
|
|
1594
|
+
return new SkillLockExtension([headMoved.id]);
|
|
1262
1595
|
if (!outcome.ok)
|
|
1263
1596
|
return outcome.response;
|
|
1264
1597
|
if (captured.closed)
|
|
@@ -1272,12 +1605,162 @@ async function writeSkillCreateOrUpdate(args) {
|
|
|
1272
1605
|
}
|
|
1273
1606
|
if (args.staged)
|
|
1274
1607
|
args.staged.text = captured.row ? storedMemoryText(captured.row, args.staged.supplied) : null;
|
|
1275
|
-
return {
|
|
1608
|
+
return {
|
|
1609
|
+
id: successorId,
|
|
1610
|
+
written: captured.row !== null,
|
|
1611
|
+
visibility: skillVersionVisibility(captured.row ?? unchangedHead),
|
|
1612
|
+
confirm: "confirm" in outcome ? outcome.confirm : undefined,
|
|
1613
|
+
};
|
|
1614
|
+
}
|
|
1615
|
+
/** Attempts at re-applying a skill close whose committed write did not land (flair#2642). */
|
|
1616
|
+
const SKILL_DELETE_CLOSE_ATTEMPTS = 3;
|
|
1617
|
+
/** The named 500 for unconfirmed skill-close compensation. */
|
|
1618
|
+
function skillDeleteCompensationFailure(message) {
|
|
1619
|
+
return Response.json({ error: "skill_delete_compensation_failed", message }, { status: 500 });
|
|
1620
|
+
}
|
|
1621
|
+
/** The named 500 for a confirmation read that failed: the close is unverified, never success. */
|
|
1622
|
+
function skillDeleteUnconfirmedFailure() {
|
|
1623
|
+
return Response.json({
|
|
1624
|
+
error: "skill_delete_unconfirmed",
|
|
1625
|
+
message: "the committed skill row could not be read; the delete is unverified",
|
|
1626
|
+
}, { status: 500 });
|
|
1627
|
+
}
|
|
1628
|
+
/** The named 409 for a skill DELETE whose version close still is not visible after the bounded re-applies. */
|
|
1629
|
+
function skillDeleteNotClosedRefusal(attempts) {
|
|
1630
|
+
return Response.json({
|
|
1631
|
+
error: "skill_delete_not_closed",
|
|
1632
|
+
message: `the skill version close was not applied after ${attempts} attempts; not deleted`,
|
|
1633
|
+
}, { status: 409 });
|
|
1634
|
+
}
|
|
1635
|
+
/** Compensate an unlanded close. */
|
|
1636
|
+
async function compensateUnlandedSkillClose(args) {
|
|
1637
|
+
const { ctx, subjectId, closedId, closeVersionId, pointerBefore } = args;
|
|
1638
|
+
try {
|
|
1639
|
+
const removal = await removeAppendedVersion(ctx, SKILL_SUBJECT_TYPE, subjectId, closeVersionId);
|
|
1640
|
+
if (removal !== "removed") {
|
|
1641
|
+
return skillDeleteCompensationFailure("removal of the close version record could not be confirmed");
|
|
1642
|
+
}
|
|
1643
|
+
if (pointerBefore) {
|
|
1644
|
+
let expected = await loadStoredPointer(closedId, {});
|
|
1645
|
+
let pointerOutcome = "left_in_place";
|
|
1646
|
+
if (!expected) {
|
|
1647
|
+
const pause = txnPausePoint("skill-delete-pointer-restore");
|
|
1648
|
+
if (pause)
|
|
1649
|
+
await pause;
|
|
1650
|
+
try {
|
|
1651
|
+
await withOwnedTransaction(ctx, async (c) => {
|
|
1652
|
+
expected = await loadStoredPointer(closedId, c);
|
|
1653
|
+
if (!expected) {
|
|
1654
|
+
await restorePointerRowIfAbsent(pointerBefore, c);
|
|
1655
|
+
const staged = txnPausePoint("skill-delete-pointer-restore-staged");
|
|
1656
|
+
if (staged)
|
|
1657
|
+
await staged;
|
|
1658
|
+
expected = pointerBefore;
|
|
1659
|
+
pointerOutcome = "restored";
|
|
1660
|
+
}
|
|
1661
|
+
});
|
|
1662
|
+
}
|
|
1663
|
+
catch (err) {
|
|
1664
|
+
if (!(err instanceof PointerAlreadyStoredError))
|
|
1665
|
+
throw err;
|
|
1666
|
+
expected = err.pointer;
|
|
1667
|
+
pointerOutcome = "left_in_place";
|
|
1668
|
+
}
|
|
1669
|
+
}
|
|
1670
|
+
const resulting = await loadStoredPointer(closedId, {});
|
|
1671
|
+
const fields = ["memoryId", "hostSource", "scopeAtWrite", "authorId", "memoryInstanceToken", "receivedAt"];
|
|
1672
|
+
if (!resulting || fields.some((field) => resulting[field] !== expected?.[field])) {
|
|
1673
|
+
return skillDeleteCompensationFailure("the restored or preserved host-pointer identity could not be confirmed");
|
|
1674
|
+
}
|
|
1675
|
+
return pointerOutcome;
|
|
1676
|
+
}
|
|
1677
|
+
return "not_needed";
|
|
1678
|
+
}
|
|
1679
|
+
catch (err) {
|
|
1680
|
+
console.error("Memory.delete: undoing an unapplied skill close failed", err);
|
|
1681
|
+
return skillDeleteCompensationFailure("compensation for the unapplied skill close could not be confirmed");
|
|
1682
|
+
}
|
|
1683
|
+
}
|
|
1684
|
+
/**
|
|
1685
|
+
* flair#2642 — a skill DELETE confirms the close in a fresh committed read
|
|
1686
|
+
* before answering success. Harper can resolve the close's commit while skipping
|
|
1687
|
+
* the queued full put (it loses to a newer write of the same row) and still
|
|
1688
|
+
* commit the tombstone and pointer writes. A close that did not land is
|
|
1689
|
+
* re-applied from a fresh read, re-checking the row's identity and the caller's
|
|
1690
|
+
* authority. Unconfirmed compensation answers 500.
|
|
1691
|
+
* Returns null only when the close is confirmed (or the row is gone).
|
|
1692
|
+
*/
|
|
1693
|
+
async function confirmSkillDelete(args) {
|
|
1694
|
+
const { ctx, auth, subjectId, closedId, closedRow, closeVersionId, pointerBefore, now } = args;
|
|
1695
|
+
const table = databases.flair.Memory;
|
|
1696
|
+
const undo = async (refusal) => {
|
|
1697
|
+
const compensation = await compensateUnlandedSkillClose({ ctx, subjectId, closedId, closeVersionId, pointerBefore });
|
|
1698
|
+
if (compensation instanceof Response)
|
|
1699
|
+
return compensation;
|
|
1700
|
+
return Response.json({ ...await refusal.json(), pointerCompensation: compensation }, { status: refusal.status });
|
|
1701
|
+
};
|
|
1702
|
+
for (let attempt = 1;; attempt++) {
|
|
1703
|
+
let committed;
|
|
1704
|
+
try {
|
|
1705
|
+
committed = await table.get(closedId, {});
|
|
1706
|
+
}
|
|
1707
|
+
catch {
|
|
1708
|
+
return skillDeleteUnconfirmedFailure();
|
|
1709
|
+
}
|
|
1710
|
+
if (!committed)
|
|
1711
|
+
return null;
|
|
1712
|
+
if (!sameStoredRow(committed, closedRow)) {
|
|
1713
|
+
// Replaced between the reads: not the row the caller meant.
|
|
1714
|
+
return undo(storedRowChangedRefusal("Memory"));
|
|
1715
|
+
}
|
|
1716
|
+
if (typeof committed.validTo === "string" && committed.validTo.length > 0)
|
|
1717
|
+
return null;
|
|
1718
|
+
if (attempt > SKILL_DELETE_CLOSE_ATTEMPTS)
|
|
1719
|
+
break;
|
|
1720
|
+
let applied;
|
|
1721
|
+
try {
|
|
1722
|
+
applied = await withOwnedTransaction(ctx, async (c) => {
|
|
1723
|
+
const stored = await table.get(closedId, c);
|
|
1724
|
+
if (!stored)
|
|
1725
|
+
return "staged";
|
|
1726
|
+
if (!sameStoredRow(stored, closedRow))
|
|
1727
|
+
return storedRowChangedRefusal("Memory");
|
|
1728
|
+
const denied = await authorizeSkillOwners(ctx, auth, [stored], c);
|
|
1729
|
+
if (denied)
|
|
1730
|
+
return denied;
|
|
1731
|
+
const closed = { ...stored, skillSubjectId: subjectId, validTo: now, updatedAt: now };
|
|
1732
|
+
normalizeEmptyEmbedding(closed);
|
|
1733
|
+
const result = storageResult(await table.put(closed, c));
|
|
1734
|
+
if (result instanceof Response)
|
|
1735
|
+
throw result;
|
|
1736
|
+
const pause = attempt === 1 ? txnPausePoint("skill-delete-retry-first")
|
|
1737
|
+
: attempt === 2 ? txnPausePoint("skill-delete-retry-second")
|
|
1738
|
+
: txnPausePoint("skill-delete-retry-third");
|
|
1739
|
+
if (pause)
|
|
1740
|
+
await pause;
|
|
1741
|
+
const revoked = await afterCloseStaged(grantedSkillClose(stored, ctx, auth));
|
|
1742
|
+
if (revoked)
|
|
1743
|
+
throw revoked;
|
|
1744
|
+
return "staged";
|
|
1745
|
+
});
|
|
1746
|
+
}
|
|
1747
|
+
catch (err) {
|
|
1748
|
+
if (err instanceof Response)
|
|
1749
|
+
applied = err;
|
|
1750
|
+
else
|
|
1751
|
+
return skillDeleteUnconfirmedFailure();
|
|
1752
|
+
}
|
|
1753
|
+
if (applied instanceof Response)
|
|
1754
|
+
return undo(applied);
|
|
1755
|
+
}
|
|
1756
|
+
return undo(skillDeleteNotClosedRefusal(SKILL_DELETE_CLOSE_ATTEMPTS));
|
|
1276
1757
|
}
|
|
1277
1758
|
/** Close the live head and delete its pointer in the version transaction. */
|
|
1278
1759
|
async function writeSkillDelete(args) {
|
|
1279
|
-
const { ctx, auth, record } = args;
|
|
1760
|
+
const { ctx, auth, record, headLock } = args;
|
|
1280
1761
|
let closedId = "";
|
|
1762
|
+
let closedRow = null;
|
|
1763
|
+
let pointerBefore = null;
|
|
1281
1764
|
const now = new Date().toISOString();
|
|
1282
1765
|
const subjectId = String(record.skillSubjectId ?? record.id);
|
|
1283
1766
|
const seedLineageDenial = reservedSeedSubjectDenial("Memory", [subjectId], ctx, auth);
|
|
@@ -1287,8 +1770,17 @@ async function writeSkillDelete(args) {
|
|
|
1287
1770
|
ctx,
|
|
1288
1771
|
subjectId,
|
|
1289
1772
|
agentId: String(record.agentId),
|
|
1773
|
+
heldMemoryIds: headLock?.ids,
|
|
1290
1774
|
head: (shared) => resolveSkillHead(subjectId, String(record.id), shared),
|
|
1291
1775
|
plan: async (head, shared) => {
|
|
1776
|
+
// flair#2478: the head this delete closes must be an id the DELETE holds.
|
|
1777
|
+
// A head outside the held ids is not locked: write nothing; delete()
|
|
1778
|
+
// discovers and locks again.
|
|
1779
|
+
if (headLock) {
|
|
1780
|
+
headLock.outside = !!head && !headLock.ids.includes(String(head.id));
|
|
1781
|
+
if (headLock.outside)
|
|
1782
|
+
return storedRowChangedRefusal("Memory");
|
|
1783
|
+
}
|
|
1292
1784
|
// flair#2355: for a non-admin caller, re-read the COMMITTED rows before
|
|
1293
1785
|
// the close. The delete is refused, and nothing is closed, when the
|
|
1294
1786
|
// addressed row is present with an owner other than the caller (409
|
|
@@ -1325,15 +1817,27 @@ async function writeSkillDelete(args) {
|
|
|
1325
1817
|
return writeOutcomeUnknownResponse();
|
|
1326
1818
|
const liveHead = head;
|
|
1327
1819
|
closedId = String(liveHead.id);
|
|
1820
|
+
closedRow = liveHead;
|
|
1821
|
+
// Captured for compensation: this attempt's pointer delete can land even
|
|
1822
|
+
// when its close does not.
|
|
1823
|
+
pointerBefore = await loadStoredPointer(closedId, shared);
|
|
1328
1824
|
// flair#2511: a stale id resolves the live head, which can be another
|
|
1329
1825
|
// agent's row a "write" grant authorizes this caller to close; the writer
|
|
1330
1826
|
// re-checks that grant after the close is staged.
|
|
1331
1827
|
return { kind: "delete", predecessor: liveHead, closePatch: { skillSubjectId: subjectId, validTo: now, updatedAt: now }, value: null, visibility: skillVersionVisibility(liveHead), grantedClose: grantedSkillClose(liveHead, ctx, auth) };
|
|
1332
1828
|
},
|
|
1333
|
-
hooks: { ...defaultSkillHooks, pointer: async (shared) => deletePointerRow(closedId, shared) },
|
|
1829
|
+
hooks: { ...defaultSkillHooks, authorizeClose: (row, shared) => authorizeSkillOwners(ctx, auth, [row], shared), pointer: async (shared) => deletePointerRow(closedId, shared) },
|
|
1334
1830
|
});
|
|
1335
1831
|
if (!outcome.ok)
|
|
1336
1832
|
return outcome.response;
|
|
1833
|
+
// flair#2642: the owned transaction has committed, but its success is not
|
|
1834
|
+
// proof that the queued close was applied. Confirm against the committed
|
|
1835
|
+
// store before answering success.
|
|
1836
|
+
const confirmation = await confirmSkillDelete({
|
|
1837
|
+
ctx, auth, subjectId, closedId, closedRow: closedRow, closeVersionId: outcome.version, pointerBefore, now,
|
|
1838
|
+
});
|
|
1839
|
+
if (confirmation)
|
|
1840
|
+
return confirmation;
|
|
1337
1841
|
noteMemoryDelete(closedId);
|
|
1338
1842
|
return new Response(JSON.stringify({ id: closedId, deleted: true }), {
|
|
1339
1843
|
status: 200, headers: { "Content-Type": "application/json" },
|
|
@@ -1372,7 +1876,8 @@ function storedInstanceToken(row) {
|
|
|
1372
1876
|
* If the stored text is no longer the text the vector was computed from, this
|
|
1373
1877
|
* recomputes from the stored text (at most REEMBED_WRITE_ATTEMPTS times).
|
|
1374
1878
|
* If the text keeps changing across the REEMBED_WRITE_ATTEMPTS attempts, it returns
|
|
1375
|
-
* reembed_row_changed (409) and writes nothing
|
|
1879
|
+
* reembed_row_changed (409) and writes nothing, when no attempt has committed
|
|
1880
|
+
* (otherwise 503 write_outcome_unknown, see flair#2478 below). A row absent at the attempt's
|
|
1376
1881
|
* own re-read, a row with no text, or a caller no longer authorized for the row
|
|
1377
1882
|
* is refused the same way the first read refused it.
|
|
1378
1883
|
*
|
|
@@ -1382,9 +1887,10 @@ function storedInstanceToken(row) {
|
|
|
1382
1887
|
* instanceToken, contentHash, createdAt) and the same embedding text, compared
|
|
1383
1888
|
* as text. A row gone or changed in either at confirmation aborts the owned
|
|
1384
1889
|
* transaction (the staged write is discarded) and the caller answers
|
|
1385
|
-
* stored_row_changed (409)
|
|
1386
|
-
*
|
|
1387
|
-
*
|
|
1890
|
+
* stored_row_changed (409) when no earlier attempt has committed, otherwise
|
|
1891
|
+
* 503 write_outcome_unknown (flair#2478 below). A same-id replacement with the same identity and
|
|
1892
|
+
* text passes. Post-commit verification retries surviving differences in
|
|
1893
|
+
* compared fields, identity or text from a fresh read within the attempt bound.
|
|
1388
1894
|
*
|
|
1389
1895
|
* The staged update also records `embeddedContentHash`, the newly computed hash
|
|
1390
1896
|
* of the text the vector was computed from (null for an empty owner), so the
|
|
@@ -1395,10 +1901,50 @@ function storedInstanceToken(row) {
|
|
|
1395
1901
|
* calling PATCH can confirm after the commit that the row is still that one.
|
|
1396
1902
|
* The calling PATCH holds the row's per-id write lock across this write and its
|
|
1397
1903
|
* commit.
|
|
1904
|
+
*
|
|
1905
|
+
* flair#2478: once an attempt's commit has resolved and no read-back has shown
|
|
1906
|
+
* its write (the read-back mismatched, or a step after the commit, such as the
|
|
1907
|
+
* write-stamp notifier, threw before it), the row may hold that write. Every
|
|
1908
|
+
* exit of the call from then on, other than a later verified success, answers
|
|
1909
|
+
* `503 write_outcome_unknown` and marks the id outcome-unknown: a refusal, a
|
|
1910
|
+
* 409 (exhausted text changes or a change seen at a confirmation), a provider
|
|
1911
|
+
* timeout, an unusable vector, the final attempt's mismatch, or any thrown
|
|
1912
|
+
* error. The one exception is a later attempt whose fresh read finds no row:
|
|
1913
|
+
* no write of this call remains on one, so it answers 404 as before and does
|
|
1914
|
+
* not fence the id.
|
|
1398
1915
|
*/
|
|
1399
1916
|
async function reembedStoredRow(id, preRead, vector, auth, ctx) {
|
|
1917
|
+
// flair#2478: one guard over every attempt. Once an attempt's commit has
|
|
1918
|
+
// resolved and no read-back has shown its write, the call answers either the
|
|
1919
|
+
// verified success, the deleted-row 404, or write_outcome_unknown (marking
|
|
1920
|
+
// the id): the attempts settle their refusals through `settle`, and any
|
|
1921
|
+
// thrown error, the write-stamp notifier after a commit included, lands here.
|
|
1922
|
+
const state = { committedUnconfirmed: false };
|
|
1923
|
+
try {
|
|
1924
|
+
return await reembedAttempts(id, preRead, vector, auth, ctx, state);
|
|
1925
|
+
}
|
|
1926
|
+
catch (err) {
|
|
1927
|
+
if (!state.committedUnconfirmed)
|
|
1928
|
+
throw err;
|
|
1929
|
+
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");
|
|
1930
|
+
return { response: writeOutcomeUnknownFor(id) };
|
|
1931
|
+
}
|
|
1932
|
+
}
|
|
1933
|
+
/** The attempts of {@link reembedStoredRow}. `state.committedUnconfirmed` is set
|
|
1934
|
+
* when an attempt's commit resolves, before anything else runs, and stays set
|
|
1935
|
+
* unless that attempt's read-back shows the write (which answers success). */
|
|
1936
|
+
async function reembedAttempts(id, preRead, vector, auth, ctx, state) {
|
|
1400
1937
|
let textToEmbed = skillEmbedText(preRead);
|
|
1401
1938
|
let embedding = vector;
|
|
1939
|
+
// Every refusal of a later attempt, once a committed write is unconfirmed,
|
|
1940
|
+
// answers write_outcome_unknown and marks the id, never a refusal that says
|
|
1941
|
+
// nothing was written.
|
|
1942
|
+
const settle = (response, ended) => {
|
|
1943
|
+
if (!state.committedUnconfirmed)
|
|
1944
|
+
return { response };
|
|
1945
|
+
console.warn("[reembed] %s: a committed attempt's write is not confirmed; this attempt ended with %s; outcome: unconfirmed", id, ended);
|
|
1946
|
+
return { response: writeOutcomeUnknownFor(id) };
|
|
1947
|
+
};
|
|
1402
1948
|
for (let attempt = 1; attempt <= REEMBED_WRITE_ATTEMPTS; attempt++) {
|
|
1403
1949
|
let outcome;
|
|
1404
1950
|
try {
|
|
@@ -1429,7 +1975,8 @@ async function reembedStoredRow(id, preRead, vector, auth, ctx) {
|
|
|
1429
1975
|
// this same update; a row that has one keeps it.
|
|
1430
1976
|
const legacyToken = storedInstanceToken(stored) ? {} : { instanceToken: token };
|
|
1431
1977
|
// flair#2561: a Response from the storage layer is not reported (storageResult).
|
|
1432
|
-
const
|
|
1978
|
+
const reembedUpdate = { ...legacyToken, embedding, embeddingModel: model, updatedAt, embeddedContentHash: hashEmbeddedText(stored.agentId, textToEmbed) ?? null };
|
|
1979
|
+
const result = storageResult(await databases.flair.Memory.update(id, reembedUpdate, owned));
|
|
1433
1980
|
if (result instanceof Response)
|
|
1434
1981
|
return { kind: "withheld", response: result };
|
|
1435
1982
|
// Test-only: inert unless the fault-injection env opt-in is set and armed.
|
|
@@ -1444,10 +1991,11 @@ async function reembedStoredRow(id, preRead, vector, auth, ctx) {
|
|
|
1444
1991
|
// the vector was computed from (`textToEmbed`). The text check catches an
|
|
1445
1992
|
// edit that changed the text but no identity field. A row gone or changed
|
|
1446
1993
|
// at confirmation aborts this owned transaction, discarding the staged
|
|
1447
|
-
// write; the caller answers stored_row_changed (409)
|
|
1994
|
+
// write; the caller answers stored_row_changed (409), or write_outcome_unknown
|
|
1995
|
+
// when an earlier attempt committed unconfirmed. Only a text change
|
|
1448
1996
|
// is logged. Neither the staged vector, its hash, nor a staged legacy
|
|
1449
|
-
// token is written.
|
|
1450
|
-
//
|
|
1997
|
+
// token is written. Post-commit verification retries surviving
|
|
1998
|
+
// differences in compared fields, identity or text from a fresh read.
|
|
1451
1999
|
await confirmCommittedRow(databases.flair.Memory, id, (committed) => {
|
|
1452
2000
|
if (!sameStoredRow(committed, stored))
|
|
1453
2001
|
return false;
|
|
@@ -1457,54 +2005,104 @@ async function reembedStoredRow(id, preRead, vector, auth, ctx) {
|
|
|
1457
2005
|
}
|
|
1458
2006
|
return true;
|
|
1459
2007
|
});
|
|
1460
|
-
|
|
2008
|
+
// Test-only: inert unless the fault-injection env opt-in is set and
|
|
2009
|
+
// armed. Holds the re-embed after its final pre-commit confirmation and
|
|
2010
|
+
// before its owned transaction commits, the window where a newer write
|
|
2011
|
+
// can discard this write's effect (flair#2656).
|
|
2012
|
+
const commitPause = txnPausePoint("memory-reembed-commit");
|
|
2013
|
+
if (commitPause)
|
|
2014
|
+
await commitPause;
|
|
2015
|
+
// The identity is the row this update writes: a legacy row gains the
|
|
2016
|
+
// token this attempt stages.
|
|
2017
|
+
return { kind: "written", model, updatedAt, token, identity: { ...stored, instanceToken: token }, fields: reembedUpdate };
|
|
1461
2018
|
});
|
|
1462
2019
|
}
|
|
1463
2020
|
catch (err) {
|
|
1464
|
-
// The owned transaction was aborted by the throw;
|
|
2021
|
+
// The owned transaction was aborted by the throw; this attempt wrote
|
|
2022
|
+
// nothing (an earlier unconfirmed attempt may have; settle answers that).
|
|
1465
2023
|
if (err instanceof CommittedRowChanged)
|
|
1466
|
-
return
|
|
2024
|
+
return settle(storedRowChangedRefusal("Memory"), "stored_row_changed");
|
|
1467
2025
|
throw err;
|
|
1468
2026
|
}
|
|
1469
2027
|
if (outcome.kind === "withheld")
|
|
1470
|
-
return
|
|
1471
|
-
if (outcome.kind === "not_found")
|
|
2028
|
+
return settle(outcome.response, "a withheld storage result");
|
|
2029
|
+
if (outcome.kind === "not_found") {
|
|
2030
|
+
// The fresh read finds no row, so no write of this call remains on one:
|
|
2031
|
+
// 404 states that even after an earlier unconfirmed attempt, and the id is
|
|
2032
|
+
// not fenced (an outcome-unknown mark lasts until restart).
|
|
2033
|
+
if (state.committedUnconfirmed)
|
|
2034
|
+
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
2035
|
return { response: NOT_FOUND() };
|
|
2036
|
+
}
|
|
1473
2037
|
if (outcome.kind === "forbidden")
|
|
1474
|
-
return
|
|
2038
|
+
return settle(FORBIDDEN("forbidden: cannot write memory owned by another agent"), "forbidden");
|
|
1475
2039
|
if (outcome.kind === "no_text") {
|
|
1476
|
-
return
|
|
2040
|
+
return settle(Response.json({ error: "reembed_no_text", message: "the stored row has no text to embed" }, { status: 422 }), "reembed_no_text");
|
|
1477
2041
|
}
|
|
1478
2042
|
if (outcome.kind === "recompute") {
|
|
1479
2043
|
if (attempt === REEMBED_WRITE_ATTEMPTS) {
|
|
1480
|
-
return
|
|
2044
|
+
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
2045
|
}
|
|
1482
2046
|
textToEmbed = outcome.text;
|
|
1483
2047
|
let recomputed;
|
|
1484
2048
|
try {
|
|
1485
|
-
|
|
2049
|
+
// Test-only pause point: inert unless the fault-injection opt-in is set
|
|
2050
|
+
// and armed; it holds this provider call inside its bound.
|
|
2051
|
+
recomputed = await embedUnderLock(textToEmbed, (limitMs) => txnPausePoint("memory-reembed-recompute", process.env, limitMs));
|
|
1486
2052
|
}
|
|
1487
2053
|
catch (err) {
|
|
1488
2054
|
if (err instanceof MemoryProviderTimeout)
|
|
1489
|
-
return
|
|
2055
|
+
return settle(memoryProviderTimeoutResponse(), "memory_provider_timeout");
|
|
1490
2056
|
throw err;
|
|
1491
2057
|
}
|
|
1492
2058
|
if (!isUsableEmbeddingVector(recomputed)) {
|
|
1493
|
-
return
|
|
2059
|
+
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
2060
|
}
|
|
1495
2061
|
embedding = recomputed;
|
|
1496
2062
|
continue;
|
|
1497
2063
|
}
|
|
2064
|
+
// The commit has resolved: until a read-back shows the write, every exit of
|
|
2065
|
+
// the call is settled as unknown (the notifier below included).
|
|
2066
|
+
state.committedUnconfirmed = true;
|
|
1498
2067
|
noteWriteStamp(outcome.model, preRead);
|
|
2068
|
+
const verifyPause = txnPausePoint("memory-reembed-verify");
|
|
2069
|
+
if (verifyPause)
|
|
2070
|
+
await verifyPause;
|
|
2071
|
+
// flair#2656: the commit is not proof the re-embed landed. Re-read the
|
|
2072
|
+
// committed row in a fresh context and answer success only when it shows
|
|
2073
|
+
// the staged values on the same row identity. A mismatch retries from the
|
|
2074
|
+
// next attempt's fresh read (which re-checks the text, the owner and the
|
|
2075
|
+
// identity); an unreadable read is unknown. Both unconfirmed outcomes mark
|
|
2076
|
+
// the id outcome-unknown (writeOutcomeUnknownFor), so a later PUT, PATCH or
|
|
2077
|
+
// DELETE of it is refused as after an ordinary PUT or PATCH.
|
|
2078
|
+
const verdict = await verifyCommittedFields(databases.flair.Memory, id, outcome.identity, outcome.fields, (committed) => skillEmbedText(committed) === textToEmbed);
|
|
2079
|
+
if (verdict === "unreadable")
|
|
2080
|
+
return { response: writeOutcomeUnknownFor(id) };
|
|
2081
|
+
if (verdict !== "shown") {
|
|
2082
|
+
// Safe to retry from a fresh read: for unchanged text and owner the next
|
|
2083
|
+
// attempt writes the same vector and hash (changed text recomputes them)
|
|
2084
|
+
// and restages `updatedAt` (and a new `instanceToken` on a legacy row that
|
|
2085
|
+
// still lacks one), so a post-commit mismatch retries from the next
|
|
2086
|
+
// attempt's fresh read. A post-commit mismatch on the final attempt is an
|
|
2087
|
+
// unconfirmed outcome (the commit resolved, so nothing here proves no
|
|
2088
|
+
// write landed). state.committedUnconfirmed stays set, so every later
|
|
2089
|
+
// exit of this call is settled as unknown: a later refusal, provider
|
|
2090
|
+
// timeout or error answers write_outcome_unknown and marks the id. Text
|
|
2091
|
+
// changes that exhaust the attempts through recomputation, and a change
|
|
2092
|
+
// seen at a confirmation, answer 409 only when no attempt has committed.
|
|
2093
|
+
if (attempt === REEMBED_WRITE_ATTEMPTS) {
|
|
2094
|
+
console.warn(`[reembed] ${id}: the committed vector was not confirmed after ${REEMBED_WRITE_ATTEMPTS} attempts; outcome: unconfirmed`);
|
|
2095
|
+
return { response: writeOutcomeUnknownFor(id) };
|
|
2096
|
+
}
|
|
2097
|
+
continue;
|
|
2098
|
+
}
|
|
1499
2099
|
// flair#2561: the response names the row and its new updatedAt, and
|
|
1500
2100
|
// carries no embedding field; `flair reembed` reads the model stamp from
|
|
1501
2101
|
// the stored row.
|
|
1502
2102
|
const body = buildFromAllowlist({ id, updatedAt: outcome.updatedAt }, REEMBED_RESPONSE_RULES);
|
|
1503
2103
|
return { response: body instanceof Response ? body : Response.json(body), token: outcome.token };
|
|
1504
2104
|
}
|
|
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
|
-
};
|
|
2105
|
+
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
2106
|
}
|
|
1509
2107
|
export class Memory extends databases.flair.Memory {
|
|
1510
2108
|
/**
|
|
@@ -1533,7 +2131,9 @@ export class Memory extends databases.flair.Memory {
|
|
|
1533
2131
|
* does not disclose whether another agent's private record exists.
|
|
1534
2132
|
* Anonymous HTTP requests are denied by allowRead(), while administrator
|
|
1535
2133
|
* and trusted internal reads are unfiltered. Wired through
|
|
1536
|
-
* record-type-kit.ts's makeByIdReadGate.
|
|
2134
|
+
* record-type-kit.ts's makeByIdReadGate. Non-admin reads of retained closed
|
|
2135
|
+
* skill payloads also apply `closedSkillPayloadReadable`; a failed check
|
|
2136
|
+
* returns 404 by id or omits the collection row.
|
|
1537
2137
|
*/
|
|
1538
2138
|
async get(target, opts) {
|
|
1539
2139
|
// Collection / query reads — the `GET /Memory/?<query>` form and the bare
|
|
@@ -1563,12 +2163,14 @@ export class Memory extends databases.flair.Memory {
|
|
|
1563
2163
|
// its own plain id-only target) so the pointer decision below always sees
|
|
1564
2164
|
// the stored `id`, `agentId`, `instanceToken`, `archived` and `visibility`.
|
|
1565
2165
|
// 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.
|
|
2166
|
+
// installs one — can never hand the join an already-projected value.
|
|
1568
2167
|
const nonAdminAgent = auth.kind === "agent" && !auth.isAdmin;
|
|
2168
|
+
const boundId = this.getId?.();
|
|
2169
|
+
const legacyProperty = typeof target === "string" && this.constructor.loadAsInstance !== false && boundId != null;
|
|
2170
|
+
const selectionTarget = legacyProperty ? { property: target } : target;
|
|
1569
2171
|
let readTarget = target;
|
|
1570
|
-
if (nonAdminAgent) {
|
|
1571
|
-
const targetId = typeof target === "string" ? target : target?.id;
|
|
2172
|
+
if (nonAdminAgent || legacyProperty || (typeof target === "object" && (target.select != null || target.property != null))) {
|
|
2173
|
+
const targetId = legacyProperty ? boundId : typeof target === "string" ? target : target?.id;
|
|
1572
2174
|
readTarget = targetId != null ? { id: targetId } : {};
|
|
1573
2175
|
}
|
|
1574
2176
|
const result = await memoryByIdReadGate.call(this, readTarget, (t) => super.get(t));
|
|
@@ -1601,9 +2203,11 @@ export class Memory extends databases.flair.Memory {
|
|
|
1601
2203
|
if (result && typeof result === "object" && !(result instanceof Response) && typeof result.agentId === "string") {
|
|
1602
2204
|
const ctx = this.getContext?.();
|
|
1603
2205
|
const withHits = await applyHitStats(projected, ctx);
|
|
1604
|
-
|
|
2206
|
+
const bound = applyPromotionBinding(attachTrust(withHits, wantsTrust(target, opts)));
|
|
2207
|
+
return nonAdminAgent ? bound : projectMemoryRead(this.constructor, bound, selectionTarget, ctx, true);
|
|
1605
2208
|
}
|
|
1606
|
-
|
|
2209
|
+
const bound = applyPromotionBinding(projected);
|
|
2210
|
+
return nonAdminAgent ? bound : projectMemoryRead(this.constructor, bound, selectionTarget, ctx, true);
|
|
1607
2211
|
}
|
|
1608
2212
|
/**
|
|
1609
2213
|
* Override search() to scope collection GETs by authenticated agent.
|
|
@@ -1616,7 +2220,9 @@ export class Memory extends databases.flair.Memory {
|
|
|
1616
2220
|
* Non-admin calls are scoped to the reader's own records at any visibility
|
|
1617
2221
|
* plus every other agent's non-private records — the shipped open-within-org
|
|
1618
2222
|
* read model. MemoryGrant is NOT consulted on reads; the one place the scope
|
|
1619
|
-
* is resolved is memory-read-scope.ts's resolveReadScope().
|
|
2223
|
+
* is resolved is memory-read-scope.ts's resolveReadScope(). Non-admin reads
|
|
2224
|
+
* of retained closed skill payloads also apply `closedSkillPayloadReadable`;
|
|
2225
|
+
* a failed check returns 404 by id or omits the collection row.
|
|
1620
2226
|
*/
|
|
1621
2227
|
async search(query) {
|
|
1622
2228
|
// Access request context via Harper's Resource instance context.
|
|
@@ -1630,15 +2236,25 @@ export class Memory extends databases.flair.Memory {
|
|
|
1630
2236
|
const gate = await resolveAuthGate(ctx, UNAUTH());
|
|
1631
2237
|
if (gate.kind === "denied")
|
|
1632
2238
|
return gate.response;
|
|
1633
|
-
if (gate.kind === "unfiltered")
|
|
1634
|
-
|
|
2239
|
+
if (gate.kind === "unfiltered") {
|
|
2240
|
+
const source = await overlayHitStatsResult(super.search(withoutCallerSelection(query)), ctx);
|
|
2241
|
+
if (!source || source instanceof Response || typeof source[Symbol.asyncIterator] !== "function")
|
|
2242
|
+
return source;
|
|
2243
|
+
const table = this.constructor;
|
|
2244
|
+
return (async function* promotionBound() {
|
|
2245
|
+
for await (const row of source)
|
|
2246
|
+
yield projectMemoryRead(table, applyPromotionBinding(row), query, ctx);
|
|
2247
|
+
})();
|
|
2248
|
+
}
|
|
1635
2249
|
// Non-admin agent: scope to own records at any visibility plus every other
|
|
1636
2250
|
// agent's non-private records (open-within-org; MemoryGrant is not
|
|
1637
2251
|
// consulted on reads). Centralized in
|
|
1638
2252
|
// memoryReadScope (record-type-kit.ts's makeReadScope(), parameterized
|
|
1639
2253
|
// from RECORD_TYPES.Memory — see this file's header — delegating
|
|
1640
2254
|
// "open-within-org" to memory-read-scope.ts's resolveReadScope()
|
|
1641
|
-
// unchanged) so get() above and search() here cannot drift.
|
|
2255
|
+
// unchanged) so get() above and search() here cannot drift. Non-admin reads
|
|
2256
|
+
// of retained closed skill payloads also apply `closedSkillPayloadReadable`;
|
|
2257
|
+
// a failed check returns 404 by id or omits the collection row.
|
|
1642
2258
|
//
|
|
1643
2259
|
// The scope condition is nested as the outermost AND block via
|
|
1644
2260
|
// makeScopedSearch (record-type-kit.ts) — same correct composition
|
|
@@ -1677,7 +2293,7 @@ export class Memory extends databases.flair.Memory {
|
|
|
1677
2293
|
// closed skill payload the reader may not read. Open rows pass.
|
|
1678
2294
|
if (!(await closedSkillPayloadReadable(row, readerAgentId)))
|
|
1679
2295
|
continue;
|
|
1680
|
-
yield await applyHitStats(row, ctx);
|
|
2296
|
+
yield await applyHitStats(applyPromotionBinding(row), ctx);
|
|
1681
2297
|
}
|
|
1682
2298
|
};
|
|
1683
2299
|
// memoryScopedSearch returns a Promise of the iterable (its scopedSearch
|
|
@@ -1692,7 +2308,67 @@ export class Memory extends databases.flair.Memory {
|
|
|
1692
2308
|
})();
|
|
1693
2309
|
return joined;
|
|
1694
2310
|
}
|
|
2311
|
+
/** A POST that names an id (URL or body) or a `supersedes` reference takes
|
|
2312
|
+
* the per-id lock for those ids, the reference under its canonical id, and
|
|
2313
|
+
* holds it across the handler's
|
|
2314
|
+
* read, decision and write and the predecessor's close (flair#2478 slice 1
|
|
2315
|
+
* part 2). Its non-skill row writes join an open request transaction, which
|
|
2316
|
+
* commits after the lock is released; a superseding skill write owns its
|
|
2317
|
+
* commit. A POST that names neither takes no lock. */
|
|
1695
2318
|
async post(content, context) {
|
|
2319
|
+
// flair#2307: resolve the `supersedes` reference to its canonical id once,
|
|
2320
|
+
// before lock selection (some POSTs take no lock), so the predecessor read,
|
|
2321
|
+
// the close and any lock taken name that id (a selector or encoded
|
|
2322
|
+
// spelling resolves to it).
|
|
2323
|
+
canonicalizeSupersedes(content);
|
|
2324
|
+
// flair#2858: release an ordinary superseding POST's predecessor lock
|
|
2325
|
+
// before processing its queued citations.
|
|
2326
|
+
const afterRelease = [];
|
|
2327
|
+
const ids = postLockIds(this, content);
|
|
2328
|
+
if (ids.length === 0) {
|
|
2329
|
+
const result = await this.postLocked(content, context, false, afterRelease, { ids: [] });
|
|
2330
|
+
for (const step of afterRelease)
|
|
2331
|
+
await step();
|
|
2332
|
+
return result;
|
|
2333
|
+
}
|
|
2334
|
+
// The initial write plan returns missing ids for a new acquisition before
|
|
2335
|
+
// the next attempt's authoritative read (flair#2950).
|
|
2336
|
+
const uncloneable = uncloneableWriteBodyResponse(content);
|
|
2337
|
+
if (uncloneable)
|
|
2338
|
+
return uncloneable;
|
|
2339
|
+
const pristine = replayWriteBody(content);
|
|
2340
|
+
let lockIds = ids;
|
|
2341
|
+
for (let attempt = 0; attempt < SKILL_WRITE_HEAD_LOCK_ATTEMPTS; attempt++) {
|
|
2342
|
+
const body = attempt === 0 ? content : replayWriteBody(pristine);
|
|
2343
|
+
const outcome = await withMemoryWriteLock(memoryWriteLockStore(), lockIds, (held) => this.postLocked(body, context, true, afterRelease, { ids: memoryWriteLockTokenIds(held) }), { phase: attempt === 0 ? "post" : "memory-skill-write" });
|
|
2344
|
+
if (outcome.kind !== "done")
|
|
2345
|
+
return memoryLockRefusal(outcome, memoryLockCallerId(this));
|
|
2346
|
+
const extend = skillLockExtension(outcome.value);
|
|
2347
|
+
if (extend) {
|
|
2348
|
+
lockIds = this.skillLockIds(lockIds, outcome.value);
|
|
2349
|
+
continue;
|
|
2350
|
+
}
|
|
2351
|
+
for (const step of afterRelease)
|
|
2352
|
+
await step();
|
|
2353
|
+
const then = skillThen(outcome.value);
|
|
2354
|
+
return then ? await then() : outcome.value;
|
|
2355
|
+
}
|
|
2356
|
+
return skillWriteConflict("skill_head_moved");
|
|
2357
|
+
}
|
|
2358
|
+
/** `locked`: the POST holds the per-id lock, so its provider calls take the
|
|
2359
|
+
* bounded path putLocked's take (MEMORY_LOCKED_PROVIDER_TIMEOUT_MS): a call
|
|
2360
|
+
* still pending at the bound, or answering after it, is refused once the
|
|
2361
|
+
* event loop runs again; a provider that never yields it can prevent that. */
|
|
2362
|
+
async postLocked(content, context, locked, afterRelease, held) {
|
|
2363
|
+
// flair#2612: a POST body that is not a single JSON object — an array, null,
|
|
2364
|
+
// a string or a number — is refused here with a named 400 before any write
|
|
2365
|
+
// path runs. Without it, an array reaches Harper's collection create, which
|
|
2366
|
+
// answers an unnamed 500 ("Can not create a record without an object"); null,
|
|
2367
|
+
// a string or a number throws a TypeError inside post() itself, also an
|
|
2368
|
+
// unnamed 500.
|
|
2369
|
+
const bodyDenial = guardObjectBody(content);
|
|
2370
|
+
if (bodyDenial)
|
|
2371
|
+
return bodyDenial;
|
|
1696
2372
|
// flair#2141 S2: check the seed's fixed id against the operator-source
|
|
1697
2373
|
// reservation (resources/seed-reservation.ts).
|
|
1698
2374
|
const seedDenial = await refuseReservedSeedWrite("Memory", writeTargetIds(this, content), this.getContext?.());
|
|
@@ -1757,7 +2433,8 @@ export class Memory extends databases.flair.Memory {
|
|
|
1757
2433
|
// (below) and keeps a string a string, so reading them first names the
|
|
1758
2434
|
// same fields.
|
|
1759
2435
|
const suppliedText = suppliedStoredTextFields(content);
|
|
1760
|
-
|
|
2436
|
+
// `content.supersedes` is already canonical: post() resolved it before
|
|
2437
|
+
// lock selection (canonicalizeSupersedes runs once per request).
|
|
1761
2438
|
// flair#2573: an empty `embedding` in the body is an omitted one. It is
|
|
1762
2439
|
// removed before the omission check and prepareSkillBody, so every later
|
|
1763
2440
|
// step, a skill update's carried vector included, sees a body without it.
|
|
@@ -1786,9 +2463,6 @@ export class Memory extends databases.flair.Memory {
|
|
|
1786
2463
|
// discipline as `claimedClient` below. Pull the optional
|
|
1787
2464
|
// `usedMemoryIds` off the write body now, BEFORE anything else touches
|
|
1788
2465
|
// `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
2466
|
const usedMemoryIds = content?.usedMemoryIds;
|
|
1793
2467
|
if (content && typeof content === "object")
|
|
1794
2468
|
delete content.usedMemoryIds;
|
|
@@ -1955,7 +2629,14 @@ export class Memory extends databases.flair.Memory {
|
|
|
1955
2629
|
const embeddingSupplied = Array.isArray(content.embedding) && content.embedding.length > 0;
|
|
1956
2630
|
let dedupMatch = null;
|
|
1957
2631
|
if (!content.supersedes) {
|
|
1958
|
-
|
|
2632
|
+
try {
|
|
2633
|
+
dedupMatch = await runDedupGate(ctx, content, locked);
|
|
2634
|
+
}
|
|
2635
|
+
catch (err) {
|
|
2636
|
+
if (err instanceof MemoryProviderTimeout)
|
|
2637
|
+
return memoryProviderTimeoutResponse();
|
|
2638
|
+
throw err;
|
|
2639
|
+
}
|
|
1959
2640
|
}
|
|
1960
2641
|
else {
|
|
1961
2642
|
delete content.dedup;
|
|
@@ -1969,7 +2650,15 @@ export class Memory extends databases.flair.Memory {
|
|
|
1969
2650
|
// (skillEmbedText), not `content`.
|
|
1970
2651
|
const embedText = skillEmbedText(content);
|
|
1971
2652
|
if (embedText && !content.embedding) {
|
|
1972
|
-
|
|
2653
|
+
let vec;
|
|
2654
|
+
try {
|
|
2655
|
+
vec = locked ? await embedUnderLock(embedText) : await getEmbedding(embedText, "document");
|
|
2656
|
+
}
|
|
2657
|
+
catch (err) {
|
|
2658
|
+
if (err instanceof MemoryProviderTimeout)
|
|
2659
|
+
return memoryProviderTimeoutResponse();
|
|
2660
|
+
throw err;
|
|
2661
|
+
}
|
|
1973
2662
|
if (vec) {
|
|
1974
2663
|
content.embedding = vec;
|
|
1975
2664
|
content.embeddingModel = getModelId();
|
|
@@ -2030,35 +2719,55 @@ export class Memory extends databases.flair.Memory {
|
|
|
2030
2719
|
// call is removed.
|
|
2031
2720
|
stripUndeclaredMemoryAttributes(content);
|
|
2032
2721
|
normalizeEmptyEmbedding(content);
|
|
2722
|
+
// POST joins an open caller transaction and confirms before its commit;
|
|
2723
|
+
// post-commit verification belongs to that owner (#2656 slice B).
|
|
2724
|
+
// Without a caller transaction, POST owns the commit and verifies after it.
|
|
2725
|
+
const postJoinsRequestTxn = isJoinableTransaction(ctx);
|
|
2033
2726
|
if (isSkillWrite(content)) {
|
|
2034
2727
|
const reservedId = [content?.id, this.getId?.()].find((candidate) => isReservedSeedId("Memory", candidate));
|
|
2035
2728
|
const skillStaged = { supplied: suppliedText, text: null };
|
|
2036
2729
|
const skillResult = await writeSkillCreateOrUpdate({
|
|
2037
2730
|
ctx, auth, content, storedRow: postStored, explicitPredecessor: preparedSkill.predecessor, method: "post", pointer,
|
|
2038
|
-
inPlaceId: reservedId != null ? String(reservedId) : null, staged: skillStaged,
|
|
2731
|
+
inPlaceId: reservedId != null ? String(reservedId) : null, staged: skillStaged, held,
|
|
2039
2732
|
});
|
|
2040
|
-
if (
|
|
2733
|
+
if (skillResult instanceof SkillLockExtension)
|
|
2734
|
+
return skillResult;
|
|
2735
|
+
if (skillResult instanceof Response)
|
|
2736
|
+
return skillWriteResponse(skillResult, redactedValues, skillStaged.text);
|
|
2737
|
+
const finish = async () => {
|
|
2738
|
+
// The write has committed; the pre-confirmation work runs after this
|
|
2739
|
+
// verb's Memory lock releases (flair#2645).
|
|
2740
|
+
if (skillResult?.confirm) {
|
|
2741
|
+
const denial = await skillResult.confirm();
|
|
2742
|
+
if (denial)
|
|
2743
|
+
return denial;
|
|
2744
|
+
}
|
|
2745
|
+
// Verify after the commit when this write owned it, as a skill POST
|
|
2746
|
+
// that supersedes a version does (flair#2645).
|
|
2747
|
+
if (skillStaged.joined !== true) {
|
|
2748
|
+
await pausePostVerification(true);
|
|
2749
|
+
const skillVerified = await verifyWrittenRow(databases.flair.Memory, skillStaged.row, skillResult.id, { expectedToken: skillStaged.row?.instanceToken }, [...POSTCOMMIT_VERIFY_FIELDS, "summary", "trigger", "metadata", "tags"]);
|
|
2750
|
+
if (skillVerified.unknown || skillVerified.mismatch) {
|
|
2751
|
+
return skillVerified.unknown ? writeOutcomeUnknownFor(skillResult.id) : skillWriteConflict("skill_target_changed");
|
|
2752
|
+
}
|
|
2753
|
+
}
|
|
2041
2754
|
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.
|
|
2755
|
+
return skillWriteResponse(skillResult, redactedValues, skillStaged.text);
|
|
2756
|
+
};
|
|
2757
|
+
if (skillResult?.confirm)
|
|
2758
|
+
return { skillThen: finish };
|
|
2759
|
+
return await finish();
|
|
2760
|
+
}
|
|
2051
2761
|
// flair#2467: the post-redaction text fields this write stages, for the response.
|
|
2052
2762
|
let postStaged = {};
|
|
2053
|
-
|
|
2054
|
-
// transaction is joinable too.
|
|
2055
|
-
const postJoinsRequestTxn = isJoinableTransaction(ctx);
|
|
2763
|
+
let stagedRow;
|
|
2056
2764
|
let postResult;
|
|
2057
2765
|
let postRowId;
|
|
2058
2766
|
let grantedClosed = null;
|
|
2059
2767
|
try {
|
|
2060
2768
|
postResult = await withSharedWriteTransaction(ctx, async (c) => {
|
|
2061
2769
|
postStaged = storedMemoryText(content, suppliedText);
|
|
2770
|
+
stagedRow = structuredClone(content);
|
|
2062
2771
|
const newId = await writeMemoryRowPost(this.constructor, content, c);
|
|
2063
2772
|
if (newId instanceof Response)
|
|
2064
2773
|
return newId;
|
|
@@ -2069,12 +2778,29 @@ export class Memory extends databases.flair.Memory {
|
|
|
2069
2778
|
if (persistDenial)
|
|
2070
2779
|
return persistDenial;
|
|
2071
2780
|
}
|
|
2781
|
+
// Test-only: holds the POST after its row and any pointer are staged, before
|
|
2782
|
+
// the transaction commits (flair#2656).
|
|
2783
|
+
const stagedPause = txnPausePoint("memory-post-staged");
|
|
2784
|
+
if (stagedPause)
|
|
2785
|
+
await stagedPause;
|
|
2072
2786
|
// Stage a grant-authorized close in the successor's transaction.
|
|
2073
2787
|
grantedClosed = await closeGrantedSupersedeStaged(c, content, supersede.close, postJoinsRequestTxn);
|
|
2788
|
+
if (postJoinsRequestTxn) {
|
|
2789
|
+
await pausePostVerification(false);
|
|
2790
|
+
try {
|
|
2791
|
+
await confirmCommittedRow(databases.flair.Memory, newId, (committed) => sameStoredRow(committed, postStored));
|
|
2792
|
+
}
|
|
2793
|
+
catch (err) {
|
|
2794
|
+
abortRequestTransaction(c);
|
|
2795
|
+
throw err;
|
|
2796
|
+
}
|
|
2797
|
+
}
|
|
2074
2798
|
return null;
|
|
2075
2799
|
});
|
|
2076
2800
|
}
|
|
2077
2801
|
catch (err) {
|
|
2802
|
+
if (err instanceof CommittedRowChanged)
|
|
2803
|
+
return storedRowChangedRefusal("Memory");
|
|
2078
2804
|
const refusal = grantedCloseRefusal(err);
|
|
2079
2805
|
if (refusal)
|
|
2080
2806
|
return refusal;
|
|
@@ -2082,6 +2808,13 @@ export class Memory extends databases.flair.Memory {
|
|
|
2082
2808
|
}
|
|
2083
2809
|
if (postResult instanceof Response)
|
|
2084
2810
|
return writeResultResponse(postResult);
|
|
2811
|
+
if (!postJoinsRequestTxn) {
|
|
2812
|
+
await pausePostVerification(false);
|
|
2813
|
+
const verified = await verifyWrittenRow(databases.flair.Memory, stagedRow, postRowId, { expectedToken: stagedRow.instanceToken }, POSTCOMMIT_VERIFY_FIELDS);
|
|
2814
|
+
if (verified.unknown || verified.mismatch) {
|
|
2815
|
+
return verified.unknown ? writeOutcomeUnknownFor(content.id ?? postRowId) : storedRowChangedRefusal("Memory");
|
|
2816
|
+
}
|
|
2817
|
+
}
|
|
2085
2818
|
if (grantedClosed)
|
|
2086
2819
|
noteMemoryUpsert(grantedClosed);
|
|
2087
2820
|
const result = {};
|
|
@@ -2108,19 +2841,17 @@ export class Memory extends databases.flair.Memory {
|
|
|
2108
2841
|
if (supersede.close?.granteeId === undefined)
|
|
2109
2842
|
await closeSupersededIfNeeded(ctx, content, supersede.close, "post");
|
|
2110
2843
|
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.
|
|
2844
|
+
// flair#744: queue citation-on-write for post() (flair#2858).
|
|
2845
|
+
// A completed credit error is logged without changing the response payload.
|
|
2117
2846
|
if (usedMemoryIds !== undefined) {
|
|
2118
|
-
|
|
2119
|
-
|
|
2120
|
-
|
|
2121
|
-
|
|
2122
|
-
|
|
2123
|
-
|
|
2847
|
+
afterRelease.push(async () => {
|
|
2848
|
+
try {
|
|
2849
|
+
await recordCitations(ctx, auth, usedMemoryIds, new Date().toISOString());
|
|
2850
|
+
}
|
|
2851
|
+
catch (err) {
|
|
2852
|
+
console.error("Memory.post: citation recording failed", err);
|
|
2853
|
+
}
|
|
2854
|
+
});
|
|
2124
2855
|
}
|
|
2125
2856
|
return buildWriteResponse(content, result, dedupMatch, redactedValues, postStaged, postRowId);
|
|
2126
2857
|
}
|
|
@@ -2128,31 +2859,39 @@ export class Memory extends databases.flair.Memory {
|
|
|
2128
2859
|
// via the one shared delegate. (Admin/internal — including the _reindex
|
|
2129
2860
|
// path in put() — pass through the delegate untouched.)
|
|
2130
2861
|
/** PATCH requires a target id and lock before its body runs. Ordinary and
|
|
2131
|
-
* re-embed owned writes commit before releasing the lock.
|
|
2862
|
+
* re-embed owned writes commit before releasing the lock. A re-embed body
|
|
2863
|
+
* (flair#2296) holds the lock under its own phase name, `patch-reembed`, so
|
|
2864
|
+
* a hold warning names the re-embed (flair#2478 slice 3). */
|
|
2132
2865
|
async patch(content, query) {
|
|
2133
2866
|
const ids = putLockIds(this, content);
|
|
2134
2867
|
if (ids.length === 0)
|
|
2135
2868
|
return memoryIdRequiredResponse();
|
|
2869
|
+
const phase = isReembedPatch(content) ? "patch-reembed" : "patch";
|
|
2136
2870
|
const outcome = await withMemoryWriteLock(memoryWriteLockStore(), ids, async () => {
|
|
2137
2871
|
const result = await this.patchLocked(content, query);
|
|
2138
2872
|
// 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.
|
|
2873
|
+
// that owned its transaction has committed it.
|
|
2141
2874
|
const committed = txnPausePoint("memory-patch-committed");
|
|
2142
2875
|
if (committed)
|
|
2143
2876
|
await committed;
|
|
2144
2877
|
return result;
|
|
2145
|
-
}, { phase
|
|
2878
|
+
}, { phase });
|
|
2146
2879
|
if (outcome.kind === "done")
|
|
2147
2880
|
return outcome.value;
|
|
2148
2881
|
return memoryLockRefusal(outcome, memoryLockCallerId(this));
|
|
2149
2882
|
}
|
|
2150
|
-
async patchLocked(content, query) {
|
|
2883
|
+
async patchLocked(content, query, checked) {
|
|
2884
|
+
// flair#2478 part 3a: a checked write (patchMemoryWithLock) joins its locked
|
|
2885
|
+
// transaction; the ordinary verb passes no entry.
|
|
2886
|
+
const locked = takeCheckedEntry(checked);
|
|
2151
2887
|
const entry = txnPausePoint("memory-patch-entry");
|
|
2152
2888
|
if (entry)
|
|
2153
2889
|
await entry;
|
|
2154
2890
|
// flair#2296: decided on the body as sent; the guards below add fields to it.
|
|
2155
2891
|
const reembedRequest = isReembedPatch(content);
|
|
2892
|
+
// The re-embed writes in its own owned transaction, outside a locked scope.
|
|
2893
|
+
if (locked && reembedRequest)
|
|
2894
|
+
throw uncheckedBodyRefusal("re-embed");
|
|
2156
2895
|
// flair#2141 S2: check the seed's fixed id against the operator-source
|
|
2157
2896
|
// reservation (resources/seed-reservation.ts).
|
|
2158
2897
|
const seedDenial = await refuseReservedSeedWrite("Memory", writeTargetIds(this, content), this.getContext?.());
|
|
@@ -2208,6 +2947,7 @@ export class Memory extends databases.flair.Memory {
|
|
|
2208
2947
|
// engine returns no vector), or the re-embed writes one with its vector. A
|
|
2209
2948
|
// PATCH that supplies its own vector retains the stored hash beside it.
|
|
2210
2949
|
delete content.embeddedContentHash;
|
|
2950
|
+
const declaredFields = patchDeclaredFields(content);
|
|
2211
2951
|
// flair#2478 slice 1 — the ordinary PATCH runs in ONE owned transaction whose
|
|
2212
2952
|
// FIRST operation is the authoritative stored read; the read, the decision
|
|
2213
2953
|
// and the COMMIT all happen before the write lock releases. Harper orders a
|
|
@@ -2215,9 +2955,10 @@ export class Memory extends databases.flair.Memory {
|
|
|
2215
2955
|
// it share this commit. (A re-embed PATCH writes in its own inner owned
|
|
2216
2956
|
// transaction instead, which also commits before the lock releases.)
|
|
2217
2957
|
const ctx = this.getContext?.();
|
|
2218
|
-
|
|
2219
|
-
|
|
2220
|
-
|
|
2958
|
+
const patchScope = locked
|
|
2959
|
+
? (cx, fn) => locked.admission.join(cx, fn)
|
|
2960
|
+
: withOwnedTransaction;
|
|
2961
|
+
const patched = await patchScope(ctx, async (c) => {
|
|
2221
2962
|
// The FIRST operation inside the owned transaction: the authoritative
|
|
2222
2963
|
// stored read, by the URL-BOUND target id (a body id that disagrees with
|
|
2223
2964
|
// the address, or a lookup that FAILS, is refused; a failed read is never
|
|
@@ -2293,9 +3034,10 @@ export class Memory extends databases.flair.Memory {
|
|
|
2293
3034
|
// plus instanceToken for a legacy row that has none, flair#2478), then
|
|
2294
3035
|
// confirms the committed row has the identity and embedding text it read
|
|
2295
3036
|
// (flair#2465). A row gone or changed in either at confirmation aborts with
|
|
2296
|
-
// 409 stored_row_changed.
|
|
2297
|
-
//
|
|
2298
|
-
//
|
|
3037
|
+
// 409 stored_row_changed. Post-commit verification retries surviving
|
|
3038
|
+
// differences in compared fields, identity or text from a fresh read
|
|
3039
|
+
// within the attempt bound.
|
|
3040
|
+
// After a normal storage result and inner commit, PATCH
|
|
2299
3041
|
// compares the token; a storage Response returns before that read.
|
|
2300
3042
|
if (reembedRequest) {
|
|
2301
3043
|
if (!existingForSkill)
|
|
@@ -2445,9 +3187,6 @@ export class Memory extends databases.flair.Memory {
|
|
|
2445
3187
|
return denied;
|
|
2446
3188
|
}
|
|
2447
3189
|
}
|
|
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
3190
|
// flair#2478: a stored row that has a token keeps it (the
|
|
2452
3191
|
// body's own was stripped above); a legacy row without one, or a row this
|
|
2453
3192
|
// PATCH creates (an admin or internal caller only), is given a fresh one
|
|
@@ -2475,16 +3214,22 @@ export class Memory extends databases.flair.Memory {
|
|
|
2475
3214
|
// flair#2561: a Response from the storage layer is not reported
|
|
2476
3215
|
// (storageResult); it is returned from this transaction as the
|
|
2477
3216
|
// write_response_withheld refusal.
|
|
2478
|
-
const
|
|
3217
|
+
const staged = structuredClone(content);
|
|
3218
|
+
const result = storageResult(await super.patch(staged, query));
|
|
2479
3219
|
if (result instanceof Response)
|
|
2480
3220
|
return result;
|
|
2481
|
-
return { result, identity: { expectedToken }, rowId: existingForSkill?.id, stampNote };
|
|
3221
|
+
return { result, staged, identity: { expectedToken }, rowId: existingForSkill?.id, stampNote };
|
|
2482
3222
|
});
|
|
2483
3223
|
// flair#2561: a refusal this path built is returned as built; a
|
|
2484
3224
|
// successful Response is replaced by the write_response_withheld refusal
|
|
2485
3225
|
// (writeResultResponse).
|
|
2486
3226
|
if (patched instanceof Response)
|
|
2487
3227
|
return writeResultResponse(patched);
|
|
3228
|
+
// A checked write has only staged its row. It continues below once its
|
|
3229
|
+
// locked scope has committed, as that scope's confirmation; a scope that
|
|
3230
|
+
// does not commit ends it here (flair#2478 part 3a).
|
|
3231
|
+
if (locked && !(await locked.stage()))
|
|
3232
|
+
return undefined;
|
|
2488
3233
|
// flair#2573: the row write has committed (its transaction returned it), so
|
|
2489
3234
|
// the embedding-space guard is notified now, before the verification read:
|
|
2490
3235
|
// a refused or unknown verification still leaves the guard told about the
|
|
@@ -2496,13 +3241,13 @@ export class Memory extends databases.flair.Memory {
|
|
|
2496
3241
|
// Verify the ordinary owned PATCH after a normal storage result; refusals
|
|
2497
3242
|
// and storage Responses return above before this read. A successful re-embed is also
|
|
2498
3243
|
// 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).
|
|
3244
|
+
// Compare ordinary PATCH fields against the staged write, including storage coercion.
|
|
2501
3245
|
// Test-only: holds the PATCH after its commit, before the verification read.
|
|
2502
3246
|
const verifyPause = txnPausePoint("memory-patch-verify");
|
|
2503
3247
|
if (verifyPause)
|
|
2504
3248
|
await verifyPause;
|
|
2505
|
-
const
|
|
3249
|
+
const staged = "staged" in patched ? patched.staged : content;
|
|
3250
|
+
const verified = await verifyWrittenRow(databases.flair.Memory, staged, this.getId?.(), patched.identity, reembedRequest ? [] : declaredFields, locked ? { exactFields: locked.confirmFields } : undefined);
|
|
2506
3251
|
if (verified.unknown)
|
|
2507
3252
|
return writeOutcomeUnknownFor(content?.id ?? this.getId?.());
|
|
2508
3253
|
if (verified.mismatch)
|
|
@@ -2513,38 +3258,98 @@ export class Memory extends databases.flair.Memory {
|
|
|
2513
3258
|
return patched.reembed;
|
|
2514
3259
|
// As in put(): the verified row gates the answer; the response is the
|
|
2515
3260
|
// PATCH's own result, never the stored row (see put()).
|
|
2516
|
-
return rowWriteResponse(patched.result, content?.id ?? this.getId?.() ?? patched.rowId, redactedValues,
|
|
3261
|
+
return rowWriteResponse(patched.result, content?.id ?? this.getId?.() ?? patched.rowId, redactedValues, storedMemoryText(staged, suppliedText));
|
|
2517
3262
|
}
|
|
2518
3263
|
/**
|
|
2519
3264
|
* flair#2478 slice 1 — the owner PUT runs under the per-id memory write lock
|
|
2520
3265
|
* and its ordinary row write owns its transaction, so the read, the decision
|
|
2521
3266
|
* and the COMMIT all happen before the lock releases (the protocol's rule).
|
|
2522
|
-
*
|
|
2523
|
-
*
|
|
2524
|
-
*
|
|
2525
|
-
* carries an open transaction. A PUT
|
|
3267
|
+
* A put composed into its caller's transaction (manual promotion; see
|
|
3268
|
+
* putLocked) joins a transaction it does not own, which then commits after
|
|
3269
|
+
* the lock releases. A PUT
|
|
2526
3270
|
* that names no id is refused 400 before the lock; a store with no lock is
|
|
2527
3271
|
* refused 503 `memory_lock_unavailable`. See resources/memory-write-lock.ts.
|
|
2528
3272
|
*/
|
|
2529
3273
|
async put(content, query) {
|
|
3274
|
+
// Resolve a selector/encoded `supersedes` spelling once, before the lock
|
|
3275
|
+
// plan reads the predecessor (flair#2950); putLocked keeps the same id.
|
|
3276
|
+
canonicalizeSupersedes(content);
|
|
2530
3277
|
const ids = putLockIds(this, content);
|
|
2531
3278
|
if (ids.length === 0)
|
|
2532
3279
|
return memoryIdRequiredResponse();
|
|
2533
|
-
|
|
2534
|
-
|
|
2535
|
-
|
|
2536
|
-
|
|
2537
|
-
|
|
2538
|
-
|
|
2539
|
-
|
|
2540
|
-
|
|
3280
|
+
// Citation-on-write, queued by putLocked, runs after this lock is released:
|
|
3281
|
+
// it tries each cited id's lock, and the target id's lock is not held then.
|
|
3282
|
+
const afterRelease = [];
|
|
3283
|
+
// One acquisition of the ids this verb can name before its authoritative
|
|
3284
|
+
// read. A skill write that names an id it does not hold returns it from
|
|
3285
|
+
// putLocked, and putSkillLocked re-acquires with it (flair#2950).
|
|
3286
|
+
const uncloneable = uncloneableWriteBodyResponse(content);
|
|
3287
|
+
if (uncloneable)
|
|
3288
|
+
return uncloneable;
|
|
3289
|
+
const pristine = replayWriteBody(content);
|
|
3290
|
+
const outcome = await withMemoryWriteLock(memoryWriteLockStore(), ids, async (held) => {
|
|
3291
|
+
const result = await this.putLocked(content, query, afterRelease, undefined, { ids: memoryWriteLockTokenIds(held) });
|
|
3292
|
+
await this.afterPutBody();
|
|
2541
3293
|
return result;
|
|
2542
3294
|
}, { phase: "put" });
|
|
2543
|
-
if (outcome.kind
|
|
2544
|
-
return outcome
|
|
2545
|
-
|
|
3295
|
+
if (outcome.kind !== "done")
|
|
3296
|
+
return memoryLockRefusal(outcome, memoryLockCallerId(this));
|
|
3297
|
+
const extend = skillLockExtension(outcome.value);
|
|
3298
|
+
if (extend)
|
|
3299
|
+
return this.putSkillLocked(pristine, query, afterRelease, this.skillLockIds(ids, outcome.value));
|
|
3300
|
+
await this.drainAfterRelease(afterRelease);
|
|
3301
|
+
const then = skillThen(outcome.value);
|
|
3302
|
+
return then ? await then() : outcome.value;
|
|
3303
|
+
}
|
|
3304
|
+
/** A skill PUT that needs an id it did not hold retries under one acquisition
|
|
3305
|
+
* of the extended set, re-reading and re-resolving the head (flair#2950). */
|
|
3306
|
+
async putSkillLocked(content, query, afterRelease, initialIds) {
|
|
3307
|
+
const pristine = replayWriteBody(content);
|
|
3308
|
+
let lockIds = initialIds;
|
|
3309
|
+
for (let attempt = 0; attempt < SKILL_WRITE_HEAD_LOCK_ATTEMPTS; attempt++) {
|
|
3310
|
+
const body = replayWriteBody(pristine);
|
|
3311
|
+
const outcome = await withMemoryWriteLock(memoryWriteLockStore(), lockIds, async (held) => {
|
|
3312
|
+
const result = await this.putLocked(body, query, afterRelease, undefined, { ids: memoryWriteLockTokenIds(held) });
|
|
3313
|
+
await this.afterPutBody();
|
|
3314
|
+
return result;
|
|
3315
|
+
}, { phase: "memory-skill-write" });
|
|
3316
|
+
if (outcome.kind !== "done")
|
|
3317
|
+
return memoryLockRefusal(outcome, memoryLockCallerId(this));
|
|
3318
|
+
const extend = skillLockExtension(outcome.value);
|
|
3319
|
+
if (extend) {
|
|
3320
|
+
lockIds = this.skillLockIds(lockIds, outcome.value);
|
|
3321
|
+
continue;
|
|
3322
|
+
}
|
|
3323
|
+
await this.drainAfterRelease(afterRelease);
|
|
3324
|
+
const then = skillThen(outcome.value);
|
|
3325
|
+
return then ? await then() : outcome.value;
|
|
3326
|
+
}
|
|
3327
|
+
return skillWriteConflict("skill_head_moved");
|
|
3328
|
+
}
|
|
3329
|
+
/** The next acquisition's id set: the ids this attempt held plus any the
|
|
3330
|
+
* skill writer returned (flair#2950). */
|
|
3331
|
+
skillLockIds(lockIds, value) {
|
|
3332
|
+
const ids = [...lockIds];
|
|
3333
|
+
if (value instanceof SkillLockExtension)
|
|
3334
|
+
ids.push(...value.ids);
|
|
3335
|
+
return [...new Set(ids)];
|
|
3336
|
+
}
|
|
3337
|
+
/** Test-only: the verb body has returned and the lock is still held. A body
|
|
3338
|
+
* that owned its transaction has committed it; a composed put that joined
|
|
3339
|
+
* another transaction has not. */
|
|
3340
|
+
async afterPutBody() {
|
|
3341
|
+
const committed = txnPausePoint("memory-put-committed");
|
|
3342
|
+
if (committed)
|
|
3343
|
+
await committed;
|
|
2546
3344
|
}
|
|
2547
|
-
async
|
|
3345
|
+
async drainAfterRelease(afterRelease) {
|
|
3346
|
+
for (const step of afterRelease)
|
|
3347
|
+
await step();
|
|
3348
|
+
}
|
|
3349
|
+
async putLocked(content, query, afterRelease, entry, held) {
|
|
3350
|
+
// flair#2478 part 3a: a checked write (putMemoryWithLock) joins its locked
|
|
3351
|
+
// transaction; the ordinary verb passes no entry.
|
|
3352
|
+
const locked = takeCheckedEntry(entry);
|
|
2548
3353
|
const reembedding = content?.embedding === null && content?.embeddingModel === null;
|
|
2549
3354
|
// flair#2141 S2: check the seed's fixed id against the operator-source
|
|
2550
3355
|
// reservation (resources/seed-reservation.ts).
|
|
@@ -2563,10 +3368,12 @@ export class Memory extends databases.flair.Memory {
|
|
|
2563
3368
|
// auditability, it must be gated to admins. Internal calls (no auth
|
|
2564
3369
|
// context) pass through, matching the pattern used in delete().
|
|
2565
3370
|
if (content._reindex === true) {
|
|
3371
|
+
if (locked)
|
|
3372
|
+
throw uncheckedBodyRefusal("_reindex");
|
|
2566
3373
|
const ctx = this.getContext?.();
|
|
2567
3374
|
const request = ctx?.request ?? ctx;
|
|
2568
3375
|
const actorId = request?.tpsAgent;
|
|
2569
|
-
if (actorId && !(await
|
|
3376
|
+
if (actorId && !(await annotatedCallerIsAdmin(request))) {
|
|
2570
3377
|
return new Response(JSON.stringify({ error: "reindex_admin_only" }), {
|
|
2571
3378
|
status: 403,
|
|
2572
3379
|
headers: { "Content-Type": "application/json" },
|
|
@@ -2609,16 +3416,18 @@ export class Memory extends databases.flair.Memory {
|
|
|
2609
3416
|
// one — before the row is staged, and again before the commit
|
|
2610
3417
|
// (confirmCommittedRow: the transaction is aborted and the staged row
|
|
2611
3418
|
// 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
|
|
3419
|
+
// refused with the named 409 stored_row_changed. Both reads use an explicit
|
|
2614
3420
|
// fresh context, never a contextless one (see resources/write-back.ts).
|
|
2615
|
-
|
|
3421
|
+
// flair#2656: the re-PUT owns its transaction even when the request
|
|
3422
|
+
// carries one (it writes one row and no pointer), so its commit has
|
|
3423
|
+
// settled when withOwnedTransaction returns and the read-back below runs
|
|
3424
|
+
// after it.
|
|
2616
3425
|
const beforeReindex = txnPausePoint("memory-reindex-pre");
|
|
2617
3426
|
if (beforeReindex)
|
|
2618
3427
|
await beforeReindex;
|
|
2619
3428
|
let reindexed;
|
|
2620
3429
|
try {
|
|
2621
|
-
reindexed = await
|
|
3430
|
+
reindexed = await withOwnedTransaction(ctx, async (c) => {
|
|
2622
3431
|
const confirmPause = txnPausePoint("memory-reindex");
|
|
2623
3432
|
if (confirmPause)
|
|
2624
3433
|
await confirmPause;
|
|
@@ -2633,14 +3442,12 @@ export class Memory extends databases.flair.Memory {
|
|
|
2633
3442
|
const stagedPause = txnPausePoint("memory-reindex-staged");
|
|
2634
3443
|
if (stagedPause)
|
|
2635
3444
|
await stagedPause;
|
|
2636
|
-
|
|
2637
|
-
|
|
2638
|
-
|
|
2639
|
-
|
|
2640
|
-
|
|
2641
|
-
|
|
2642
|
-
throw err;
|
|
2643
|
-
}
|
|
3445
|
+
await confirmCommittedRow(databases.flair.Memory, reindexExisting.id, (committed) => sameStoredRow(committed, reindexExisting));
|
|
3446
|
+
// Test-only: holds the re-PUT after its final pre-commit confirmation,
|
|
3447
|
+
// before its transaction commits.
|
|
3448
|
+
const confirmedPause = txnPausePoint("memory-reindex-confirmed");
|
|
3449
|
+
if (confirmedPause)
|
|
3450
|
+
await confirmedPause;
|
|
2644
3451
|
return r;
|
|
2645
3452
|
});
|
|
2646
3453
|
}
|
|
@@ -2654,8 +3461,26 @@ export class Memory extends databases.flair.Memory {
|
|
|
2654
3461
|
// refusal (writeResultResponse).
|
|
2655
3462
|
if (reindexed instanceof Response)
|
|
2656
3463
|
return writeResultResponse(reindexed);
|
|
3464
|
+
// embedding-space-guard slice 1 (see put()): the owned transaction has
|
|
3465
|
+
// returned, so notify the guard of the ATTEMPTED stamp now, before the
|
|
3466
|
+
// verification read; the read-back determines whether that stamp remains
|
|
3467
|
+
// stored. A refused or unknown verification still leaves the guard told
|
|
3468
|
+
// about the attempt.
|
|
3469
|
+
noteWriteStamp(reindexRow?.embeddingModel, reindexExisting);
|
|
3470
|
+
// flair#2478 slice 3c + flair#2656: read the committed row back after the
|
|
3471
|
+
// commit. A row that does not show the re-PUT answers 409
|
|
3472
|
+
// stored_row_changed; a failed read marks the id and answers 503
|
|
3473
|
+
// write_outcome_unknown.
|
|
3474
|
+
// Test-only: a fault-injection switch makes this read throw.
|
|
3475
|
+
const verifyTable = txnFault("memory-reindex-verify")
|
|
3476
|
+
? { get: async () => { throw new Error("injected post-commit read failure"); } }
|
|
3477
|
+
: databases.flair.Memory;
|
|
3478
|
+
const committedVerdict = await verifyCommittedFields(verifyTable, reindexRow.id, reindexRow, withoutHarperManagedFields(reindexRow));
|
|
3479
|
+
if (committedVerdict === "unreadable")
|
|
3480
|
+
return writeOutcomeUnknownFor(reindexRow.id);
|
|
3481
|
+
if (committedVerdict !== "shown")
|
|
3482
|
+
return storedRowChangedRefusal("Memory");
|
|
2657
3483
|
noteMemoryUpsert(content);
|
|
2658
|
-
noteWriteStamp(reindexRow?.embeddingModel, reindexExisting); // embedding-space-guard slice 1 (see post())
|
|
2659
3484
|
return rowWriteResponse(reindexed, reindexRow?.id, 0);
|
|
2660
3485
|
}
|
|
2661
3486
|
// flair#2441 + flair#2478 slice 1: a test-only pause of this PUT before its
|
|
@@ -2677,15 +3502,17 @@ export class Memory extends databases.flair.Memory {
|
|
|
2677
3502
|
// is no post-commit verification here (manual promotion's stamp reads the
|
|
2678
3503
|
// row in that transaction and refuses when there is none; it does not
|
|
2679
3504
|
// compare the written identity). Every other ordinary put owns its
|
|
2680
|
-
// transaction
|
|
2681
|
-
|
|
2682
|
-
const composed = composesCallerWrite(ctx);
|
|
3505
|
+
// transaction, as the `_reindex` re-PUT above does.
|
|
3506
|
+
const composed = !locked && composesCallerWrite(ctx);
|
|
2683
3507
|
let putResult;
|
|
2684
3508
|
// flair#2467: the post-redaction text fields this write stages, for the response.
|
|
2685
3509
|
let putStaged = {};
|
|
2686
3510
|
let putGrantedClosed = null;
|
|
2687
3511
|
try {
|
|
2688
|
-
|
|
3512
|
+
const writeScope = locked
|
|
3513
|
+
? (cx, fn) => locked.admission.join(cx, fn)
|
|
3514
|
+
: composed ? withSharedWriteTransaction : withOwnedTransaction;
|
|
3515
|
+
putResult = await writeScope(ctx, async (c) => {
|
|
2689
3516
|
// The authoritative stored read: the FIRST operation of an ordinary PUT's
|
|
2690
3517
|
// owned transaction (a composed put runs it in its caller's transaction,
|
|
2691
3518
|
// which may already have read). It reads by the URL-BOUND target id (a
|
|
@@ -2771,6 +3598,10 @@ export class Memory extends databases.flair.Memory {
|
|
|
2771
3598
|
const usedMemoryIds = content?.usedMemoryIds;
|
|
2772
3599
|
if (content && typeof content === "object")
|
|
2773
3600
|
delete content.usedMemoryIds;
|
|
3601
|
+
// A checked write records no citations: they take the cited ids' locks
|
|
3602
|
+
// after the write's lock is released, which its caller holds.
|
|
3603
|
+
if (locked && usedMemoryIds !== undefined)
|
|
3604
|
+
throw uncheckedBodyRefusal("citation-on-write");
|
|
2774
3605
|
// ── flair#1238: refuse an unrecognised durability (mirrors post()) ──
|
|
2775
3606
|
// put() is the other HTTP-reachable write path (fresh create via CLI, and
|
|
2776
3607
|
// the update/patch path). Same guard as post(): a present-but-unknown
|
|
@@ -2850,7 +3681,10 @@ export class Memory extends databases.flair.Memory {
|
|
|
2850
3681
|
// supersedes: optional reference to the ID of the memory this one
|
|
2851
3682
|
// replaces. Validates shape + cross-agent-write authorization (shared
|
|
2852
3683
|
// with post() — see validateAndAuthorizeSupersedes doc for why PUT needs
|
|
2853
|
-
// this too:
|
|
3684
|
+
// this too: HTTP POST /Memory reaches Memory.post(), and flair-client's
|
|
3685
|
+
// write() and update() both send PUT: default update() addresses the
|
|
3686
|
+
// existing id, while its preserveHistory option supplies a new id and
|
|
3687
|
+
// `supersedes`).
|
|
2854
3688
|
const supersede = await validateAndAuthorizeSupersedes(content, auth, ctx, preExisting, requestedVisibility);
|
|
2855
3689
|
if (supersede.denial)
|
|
2856
3690
|
return supersede.denial;
|
|
@@ -3035,17 +3869,35 @@ export class Memory extends databases.flair.Memory {
|
|
|
3035
3869
|
stripUndeclaredMemoryAttributes(content);
|
|
3036
3870
|
normalizeEmptyEmbedding(content);
|
|
3037
3871
|
if (isSkillWrite(content)) {
|
|
3872
|
+
// A skill write is a skill version write (part 3c), not a checked write.
|
|
3873
|
+
if (locked)
|
|
3874
|
+
throw uncheckedBodyRefusal("skill version");
|
|
3038
3875
|
const reservedId = [content?.id, this.getId?.()].find((candidate) => isReservedSeedId("Memory", candidate));
|
|
3039
3876
|
const skillStaged = { supplied: suppliedText, text: null };
|
|
3040
3877
|
// A PUT whose redaction replaced a value commits its redacted effective
|
|
3041
3878
|
// row, inherited fields included, so each field the reply's `stored`
|
|
3042
3879
|
// reports (the fields the request supplied, flair#2561) is what the row
|
|
3043
3880
|
// holds: the in-place unchanged-row check gets no requested fields for it.
|
|
3044
|
-
|
|
3045
|
-
|
|
3046
|
-
|
|
3047
|
-
|
|
3048
|
-
|
|
3881
|
+
const skillResult = await writeSkillCreateOrUpdate({
|
|
3882
|
+
ctx, auth, content, storedRow: preExisting, explicitPredecessor: preparedSkill.predecessor, method: "put", pointer,
|
|
3883
|
+
reembedding, requestedPayload: redactedValues > 0 ? undefined : requestedPayload,
|
|
3884
|
+
inPlaceId: reservedId != null ? String(reservedId) : null, staged: skillStaged, held,
|
|
3885
|
+
});
|
|
3886
|
+
if (skillResult instanceof SkillLockExtension)
|
|
3887
|
+
return skillResult;
|
|
3888
|
+
if (skillResult?.confirm) {
|
|
3889
|
+
// The write has committed; run the pre-confirmation work after this
|
|
3890
|
+
// verb's Memory lock releases, so a later same-subject write can run.
|
|
3891
|
+
return {
|
|
3892
|
+
skillThen: async () => {
|
|
3893
|
+
const denial = await skillResult.confirm();
|
|
3894
|
+
if (denial)
|
|
3895
|
+
return denial;
|
|
3896
|
+
return skillWriteResponse(skillResult, redactedValues, skillStaged.text);
|
|
3897
|
+
},
|
|
3898
|
+
};
|
|
3899
|
+
}
|
|
3900
|
+
return { skill: skillWriteResponse(skillResult, redactedValues, skillStaged.text) };
|
|
3049
3901
|
}
|
|
3050
3902
|
// flair#2441: this put is over the row read as `preExisting` (which
|
|
3051
3903
|
// `stampInstanceToken` copied its incarnation token from). The write
|
|
@@ -3110,6 +3962,11 @@ export class Memory extends databases.flair.Memory {
|
|
|
3110
3962
|
return refusal;
|
|
3111
3963
|
throw err;
|
|
3112
3964
|
}
|
|
3965
|
+
// A skill PUT that needs ids it did not hold asks the verb for them.
|
|
3966
|
+
if (putResult instanceof SkillLockExtension)
|
|
3967
|
+
return putResult;
|
|
3968
|
+
if (putResult && typeof putResult.skillThen === "function")
|
|
3969
|
+
return putResult;
|
|
3113
3970
|
// A skill PUT answers from its own write (no ordinary-row post-commit step).
|
|
3114
3971
|
if (putResult && putResult.skill !== undefined)
|
|
3115
3972
|
return putResult.skill;
|
|
@@ -3118,6 +3975,11 @@ export class Memory extends databases.flair.Memory {
|
|
|
3118
3975
|
// (a storage-layer Response was replaced in the transaction, storageResult).
|
|
3119
3976
|
if (putResult instanceof Response)
|
|
3120
3977
|
return writeResultResponse(putResult);
|
|
3978
|
+
// A checked write has only staged its row. It continues below once its
|
|
3979
|
+
// locked scope has committed, as that scope's confirmation; a scope that
|
|
3980
|
+
// does not commit ends it here (flair#2478 part 3a).
|
|
3981
|
+
if (locked && !(await locked.stage()))
|
|
3982
|
+
return undefined;
|
|
3121
3983
|
// embedding-space-guard slice 1 (see post()): the ordinary row write has
|
|
3122
3984
|
// returned from its transaction, so the guard is notified now, with the
|
|
3123
3985
|
// stored stamp and the row this PUT replaced (flair#2573), before the
|
|
@@ -3134,7 +3996,7 @@ export class Memory extends databases.flair.Memory {
|
|
|
3134
3996
|
const verifyPause = txnPausePoint("memory-put-verify");
|
|
3135
3997
|
if (verifyPause)
|
|
3136
3998
|
await verifyPause;
|
|
3137
|
-
const verified = await
|
|
3999
|
+
const verified = await verifyWrittenRow(databases.flair.Memory, putResult.content, putResult.fallbackId, { expectedToken: putResult.content?.instanceToken }, POSTCOMMIT_VERIFY_FIELDS, locked ? { exactFields: locked.confirmFields } : undefined);
|
|
3138
4000
|
if (verified.unknown)
|
|
3139
4001
|
return writeOutcomeUnknownFor(putResult.content?.id ?? putResult.fallbackId);
|
|
3140
4002
|
if (verified.mismatch)
|
|
@@ -3158,20 +4020,67 @@ export class Memory extends databases.flair.Memory {
|
|
|
3158
4020
|
if (putResult.close?.granteeId === undefined)
|
|
3159
4021
|
await closeSupersededIfNeeded(ctx, putResult.content, putResult.close, "put");
|
|
3160
4022
|
// flair#744 slice A: citation-on-write — POST-COMMIT, fully
|
|
3161
|
-
// failure-isolated (see post()'s identical comment above).
|
|
4023
|
+
// failure-isolated (see post()'s identical comment above). flair#2478: it
|
|
4024
|
+
// is queued here and put() runs it after releasing this id's lock.
|
|
3162
4025
|
if (putResult.usedMemoryIds !== undefined) {
|
|
3163
|
-
|
|
3164
|
-
|
|
3165
|
-
|
|
3166
|
-
|
|
3167
|
-
|
|
3168
|
-
|
|
4026
|
+
const { auth: citingAuth, usedMemoryIds } = putResult;
|
|
4027
|
+
afterRelease.push(async () => {
|
|
4028
|
+
try {
|
|
4029
|
+
await recordCitations(ctx, citingAuth, usedMemoryIds, new Date().toISOString());
|
|
4030
|
+
}
|
|
4031
|
+
catch (err) {
|
|
4032
|
+
console.error("Memory.put: citation recording failed (write already committed)", err);
|
|
4033
|
+
}
|
|
4034
|
+
});
|
|
3169
4035
|
}
|
|
3170
4036
|
return buildWriteResponse(putResult.content, result, putResult.dedupMatch, putResult.redactedValues, putStaged);
|
|
3171
4037
|
}
|
|
4038
|
+
/** Past the refusals that read no row, DELETE reads the addressed row with no
|
|
4039
|
+
* lock held (discovery only) and, for a skill row, finds the live head its
|
|
4040
|
+
* skill writer closes (for an older version, another row). It then takes the
|
|
4041
|
+
* addressed id's lock and that head's, which cover the authorization,
|
|
4042
|
+
* planning, write and owned transaction's commit that follow. When the head
|
|
4043
|
+
* the skill writer resolves under the locks is not one of the held ids,
|
|
4044
|
+
* nothing is written and the DELETE discovers and locks again, at most
|
|
4045
|
+
* SKILL_DELETE_HEAD_ATTEMPTS attempts in all, then answers `503 memory_busy`
|
|
4046
|
+
* (flair#2478 slice 1 part 2). */
|
|
3172
4047
|
async delete(id) {
|
|
4048
|
+
const ids = deleteLockIds(this, id);
|
|
4049
|
+
if (ids.length === 0)
|
|
4050
|
+
return this.deleteLocked(id);
|
|
4051
|
+
// The refusals that read no row answer before the head discovery reads it.
|
|
3173
4052
|
const ctx = this.getContext?.();
|
|
3174
|
-
const
|
|
4053
|
+
const early = this.deleteRefusalBeforeRead(id, ctx, await resolveAgentAuth(ctx));
|
|
4054
|
+
if (early)
|
|
4055
|
+
return early;
|
|
4056
|
+
for (let attempt = 1; attempt <= SKILL_DELETE_HEAD_ATTEMPTS; attempt++) {
|
|
4057
|
+
const head = await skillDeleteHeadId(() => super.get(id));
|
|
4058
|
+
if (head !== null) {
|
|
4059
|
+
// Test-only: held after this attempt found the head, before it takes
|
|
4060
|
+
// the locks.
|
|
4061
|
+
const discovered = attempt === 1 ? txnPausePoint("memory-delete-head-first")
|
|
4062
|
+
: attempt === 2 ? txnPausePoint("memory-delete-head-second")
|
|
4063
|
+
: txnPausePoint("memory-delete-head-third");
|
|
4064
|
+
if (discovered)
|
|
4065
|
+
await discovered;
|
|
4066
|
+
}
|
|
4067
|
+
const headLock = { ids: [], outside: false };
|
|
4068
|
+
const outcome = await withMemoryWriteLock(memoryWriteLockStore(), head === null ? ids : [...ids, head], (locked) => {
|
|
4069
|
+
headLock.ids = memoryWriteLockTokenIds(locked);
|
|
4070
|
+
return this.deleteLocked(id, headLock);
|
|
4071
|
+
}, { phase: "delete" });
|
|
4072
|
+
if (outcome.kind !== "done")
|
|
4073
|
+
return memoryLockRefusal(outcome, memoryLockCallerId(this));
|
|
4074
|
+
if (!headLock.outside)
|
|
4075
|
+
return outcome.value;
|
|
4076
|
+
}
|
|
4077
|
+
return memoryBusyResponse(memoryLockCallerId(this));
|
|
4078
|
+
}
|
|
4079
|
+
/** The DELETE refusals that read no Memory row: an anonymous caller, an
|
|
4080
|
+
* outcome-unknown id, a reserved seed id and a `.content`-suffixed target.
|
|
4081
|
+
* delete() answers them before its head discovery reads the row;
|
|
4082
|
+
* deleteLocked checks them again under the lock. */
|
|
4083
|
+
deleteRefusalBeforeRead(id, ctx, auth) {
|
|
3175
4084
|
if (auth.kind === "anonymous")
|
|
3176
4085
|
return UNAUTH();
|
|
3177
4086
|
// flair#2478: a DELETE of an id whose last owned PUT/PATCH settled with an
|
|
@@ -3189,6 +4098,16 @@ export class Memory extends databases.flair.Memory {
|
|
|
3189
4098
|
const contentSuffixDenial = refuseContentSuffixId([id, ...writeTargetIds(this, id && typeof id === "object" ? id : undefined)], id);
|
|
3190
4099
|
if (contentSuffixDenial)
|
|
3191
4100
|
return contentSuffixDenial;
|
|
4101
|
+
return null;
|
|
4102
|
+
}
|
|
4103
|
+
async deleteLocked(id, headLock) {
|
|
4104
|
+
const ctx = this.getContext?.();
|
|
4105
|
+
const auth = await resolveAgentAuth(ctx);
|
|
4106
|
+
const refusal = this.deleteRefusalBeforeRead(id, ctx, auth);
|
|
4107
|
+
if (refusal)
|
|
4108
|
+
return refusal;
|
|
4109
|
+
if (auth.kind === "anonymous")
|
|
4110
|
+
return UNAUTH();
|
|
3192
4111
|
// Read stored ownership, not the read-scoped get() response. Enforce here
|
|
3193
4112
|
// as well as middleware so MCP/in-process callers have the same policy.
|
|
3194
4113
|
const record = await super.get(id);
|
|
@@ -3205,81 +4124,195 @@ export class Memory extends databases.flair.Memory {
|
|
|
3205
4124
|
const beforeSkillDelete = txnPausePoint("memory-skill-delete-pre");
|
|
3206
4125
|
if (beforeSkillDelete)
|
|
3207
4126
|
await beforeSkillDelete;
|
|
3208
|
-
return await writeSkillDelete({ ctx, auth, record });
|
|
4127
|
+
return await writeSkillDelete({ ctx, auth, record, headLock });
|
|
3209
4128
|
}
|
|
3210
4129
|
// 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);
|
|
4130
|
+
// A1' item 2 (adjudication 0a/0c): the Memory delete, its pointer delete
|
|
4131
|
+
// and its deletion-history record share ONE owned transaction; a failing
|
|
4132
|
+
// pointer delete aborts it, so nothing is deleted; failures are NOT
|
|
4133
|
+
// swallowed. The transaction is OWNED here (withOwnedTransaction) so it
|
|
4134
|
+
// commits before this method returns, which lets the confirmation below
|
|
4135
|
+
// read the committed store (flair#2632).
|
|
3220
4136
|
const deletionActor = auth.kind === "agent" ? auth.agentId : null;
|
|
3221
4137
|
const deletionSourceClass = auth.kind === "internal" ? "internal" : auth.isAdmin ? "admin" : "agent";
|
|
3222
4138
|
// 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
|
-
|
|
4139
|
+
// owner change can commit first and be seen by the re-read inside.
|
|
4140
|
+
const target = record ? {
|
|
4141
|
+
id: String(record.id),
|
|
4142
|
+
owner: record[RECORD_TYPES.Memory.ownerField] ?? null,
|
|
4143
|
+
token: record.instanceToken ?? null,
|
|
4144
|
+
} : null;
|
|
3226
4145
|
const beforeDelete = txnPausePoint("memory-delete-pre");
|
|
3227
4146
|
if (beforeDelete)
|
|
3228
4147
|
await beforeDelete;
|
|
3229
|
-
|
|
3230
|
-
|
|
3231
|
-
|
|
3232
|
-
|
|
3233
|
-
|
|
3234
|
-
|
|
4148
|
+
// flair#2632: ordinary, non-skill DELETE confirms committed row absence.
|
|
4149
|
+
// Retry dropped removals with fresh reads; refuse a changed id/owner/token.
|
|
4150
|
+
const targetIdProbe = typeof id === "string" ? id : record?.id;
|
|
4151
|
+
let applied = false;
|
|
4152
|
+
for (let attempt = 1; attempt <= DELETE_APPLY_ATTEMPTS; attempt++) {
|
|
4153
|
+
let historyId = null;
|
|
4154
|
+
let pointerBefore = null;
|
|
4155
|
+
const outcome = await withOwnedTransaction(ctx, async (c) => {
|
|
4156
|
+
const deletedId = typeof id === "string" ? id : record?.id;
|
|
4157
|
+
if (typeof deletedId !== "string" || !deletedId)
|
|
4158
|
+
return { kind: "absent" };
|
|
4159
|
+
const stored = await databases.flair.Memory.get(deletedId, c);
|
|
4160
|
+
if (!stored)
|
|
4161
|
+
return { kind: "absent" };
|
|
4162
|
+
const nonAdmin = auth.kind === "agent" && !auth.isAdmin;
|
|
4163
|
+
if (nonAdmin && isForbiddenOwnerMutation(stored, RECORD_TYPES.Memory.ownerField, auth.agentId)) {
|
|
4164
|
+
// The caller passed the owner check at the pre-read above, so a
|
|
4165
|
+
// mismatch here is a change committed since — refuse it, do not delete.
|
|
4166
|
+
return { kind: "response", response: ownerChangedRefusal("Memory") };
|
|
4167
|
+
}
|
|
4168
|
+
if (!target || !sameDeleteTarget(stored, target, RECORD_TYPES.Memory.ownerField)) {
|
|
4169
|
+
return { kind: "response", response: storedRowChangedRefusal("Memory") };
|
|
4170
|
+
}
|
|
4171
|
+
if (nonAdmin) {
|
|
4172
|
+
// Test-only: the transaction pauses between its ownership read and its
|
|
4173
|
+
// delete.
|
|
4174
|
+
const pause = txnPausePoint("memory-delete");
|
|
4175
|
+
if (pause)
|
|
4176
|
+
await pause;
|
|
4177
|
+
// Confirmation read of the COMMITTED row in an explicit fresh context
|
|
4178
|
+
// (never contextless — see resources/owner-delete-recheck.ts's header).
|
|
4179
|
+
const confirmed = await databases.flair.Memory.get(deletedId, {});
|
|
4180
|
+
if (confirmed && isForbiddenOwnerMutation(confirmed, RECORD_TYPES.Memory.ownerField, auth.agentId)) {
|
|
4181
|
+
return { kind: "response", response: ownerChangedRefusal("Memory") };
|
|
4182
|
+
}
|
|
4183
|
+
}
|
|
4184
|
+
// Captured for compensation: this attempt's pointer delete may land even
|
|
4185
|
+
// when its row removal is dropped.
|
|
4186
|
+
pointerBefore = await loadStoredPointer(deletedId, c);
|
|
4187
|
+
const d = await databases.flair.Memory.delete(deletedId, c);
|
|
4188
|
+
if (d !== true)
|
|
4189
|
+
throw new Error("Memory row delete was not confirmed");
|
|
4190
|
+
const pointerDenial = await deletePointerRow(deletedId, c);
|
|
4191
|
+
if (pointerDenial)
|
|
4192
|
+
return { kind: "response", response: pointerDenial };
|
|
4193
|
+
historyId = await recordMemoryDeletion({
|
|
4194
|
+
memoryId: deletedId,
|
|
4195
|
+
memoryInstanceToken: stored.instanceToken ?? null,
|
|
4196
|
+
durability: stored.durability ?? null,
|
|
4197
|
+
actor: deletionActor,
|
|
4198
|
+
sourceClass: deletionSourceClass,
|
|
4199
|
+
}, c);
|
|
4200
|
+
return { kind: "staged" };
|
|
4201
|
+
});
|
|
4202
|
+
if (outcome.kind === "response")
|
|
4203
|
+
return outcome.response;
|
|
4204
|
+
if (outcome.kind === "absent")
|
|
3235
4205
|
return false;
|
|
3236
|
-
|
|
3237
|
-
|
|
3238
|
-
|
|
3239
|
-
|
|
3240
|
-
|
|
4206
|
+
// The owned transaction has committed. Its success is not proof that the
|
|
4207
|
+
// queued delete was applied: confirm against the committed store.
|
|
4208
|
+
const targetId = String(targetIdProbe);
|
|
4209
|
+
const after = await databases.flair.Memory.get(targetId, {});
|
|
4210
|
+
if (!after) {
|
|
4211
|
+
applied = true;
|
|
4212
|
+
break;
|
|
3241
4213
|
}
|
|
3242
|
-
|
|
3243
|
-
|
|
3244
|
-
|
|
3245
|
-
|
|
3246
|
-
|
|
3247
|
-
|
|
3248
|
-
//
|
|
3249
|
-
|
|
3250
|
-
|
|
3251
|
-
|
|
3252
|
-
return ownerChangedRefusal("Memory");
|
|
3253
|
-
}
|
|
4214
|
+
// Still stored: the removal was dropped while this attempt's history and
|
|
4215
|
+
// pointer writes landed. Undo them before the next attempt.
|
|
4216
|
+
const compensation = await compensateDroppedRemoval(targetId, historyId, pointerBefore, ctx);
|
|
4217
|
+
if (compensation)
|
|
4218
|
+
return compensation;
|
|
4219
|
+
if (attempt < DELETE_APPLY_ATTEMPTS) {
|
|
4220
|
+
// Test-only: holds a delete whose removal did not land between attempts.
|
|
4221
|
+
const retry = txnPausePoint("memory-delete-retry");
|
|
4222
|
+
if (retry)
|
|
4223
|
+
await retry;
|
|
3254
4224
|
}
|
|
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);
|
|
4225
|
+
}
|
|
4226
|
+
if (!applied)
|
|
4227
|
+
return deleteNotAppliedRefusal("Memory", DELETE_APPLY_ATTEMPTS);
|
|
4228
|
+
// Test-only: held after the owned transaction committed and the removal was
|
|
4229
|
+
// confirmed, while the id's lock is still held (flair#2478).
|
|
4230
|
+
const committedPause = txnPausePoint("memory-delete-committed");
|
|
4231
|
+
if (committedPause)
|
|
4232
|
+
await committedPause;
|
|
4233
|
+
// An owned transaction has committed and its removal is confirmed.
|
|
4234
|
+
if (typeof targetIdProbe === "string" && targetIdProbe.length > 0) {
|
|
4235
|
+
noteMemoryDelete(targetIdProbe);
|
|
3280
4236
|
}
|
|
3281
4237
|
if (typeof id === "string")
|
|
3282
4238
|
await clearHitStats(id, ctx).catch(() => { });
|
|
3283
|
-
return
|
|
4239
|
+
return true;
|
|
4240
|
+
}
|
|
4241
|
+
}
|
|
4242
|
+
/** The ids a checked write writes: its target, the body id and, for a PUT, the
|
|
4243
|
+
* `supersedes` target it closes (raw and canonical). */
|
|
4244
|
+
function checkedWriteIds(verb, input) {
|
|
4245
|
+
const ids = [input.id];
|
|
4246
|
+
const bodyId = input.content.id;
|
|
4247
|
+
if (typeof bodyId === "string" || typeof bodyId === "number")
|
|
4248
|
+
ids.push(String(bodyId));
|
|
4249
|
+
const supersedes = input.content.supersedes;
|
|
4250
|
+
if (verb === "put" && typeof supersedes === "string") {
|
|
4251
|
+
ids.push(supersedes);
|
|
4252
|
+
const canonical = resolveMemoryReferenceId(supersedes);
|
|
4253
|
+
if (canonical !== undefined)
|
|
4254
|
+
ids.push(canonical);
|
|
4255
|
+
}
|
|
4256
|
+
return ids;
|
|
4257
|
+
}
|
|
4258
|
+
function enterCheckedWrite(verb, held, tx, input) {
|
|
4259
|
+
let admission;
|
|
4260
|
+
let snapshot;
|
|
4261
|
+
try {
|
|
4262
|
+
if (!input || typeof input.id !== "string" || input.id.length === 0 ||
|
|
4263
|
+
input.content === null || typeof input.content !== "object" || Array.isArray(input.content)) {
|
|
4264
|
+
throw new TypeError("a checked Memory write names a string id and an object body");
|
|
4265
|
+
}
|
|
4266
|
+
// One snapshot, taken before admission, decides the write set and is the
|
|
4267
|
+
// write. The write set comes from its id strings, so a later change to
|
|
4268
|
+
// the caller's input cannot change it. The body is a structuredClone
|
|
4269
|
+
// (not a JSON round trip: a body read from a stored row can hold values
|
|
4270
|
+
// JSON would not keep as they are, a typed-array vector or a Date), so
|
|
4271
|
+
// a later change to a nested value does not reach the write either,
|
|
4272
|
+
// except through memory a SharedArrayBuffer shares, which a clone keeps
|
|
4273
|
+
// shared. A body it cannot clone is rejected here, before admission.
|
|
4274
|
+
snapshot = Object.freeze({
|
|
4275
|
+
id: input.id,
|
|
4276
|
+
content: structuredClone(input.content),
|
|
4277
|
+
confirmFields: Object.freeze([...(input.confirmFields ?? [])]),
|
|
4278
|
+
});
|
|
4279
|
+
admission = admitLockedMemoryWrite(held, tx, memoryWriteLockStore(), checkedWriteIds(verb, snapshot));
|
|
3284
4280
|
}
|
|
4281
|
+
catch (error) {
|
|
4282
|
+
return Promise.reject(error);
|
|
4283
|
+
}
|
|
4284
|
+
return admission.track(snapshot.id, async (stage) => {
|
|
4285
|
+
const getResource = Memory.getResource;
|
|
4286
|
+
if (typeof getResource !== "function")
|
|
4287
|
+
throw new Error("flair: Memory.getResource is unavailable; a checked Memory write is refused");
|
|
4288
|
+
const resource = await getResource.call(Memory, { id: snapshot.id }, admission.context, { hasContent: true, type: "update", method: verb });
|
|
4289
|
+
const entry = Object.freeze({});
|
|
4290
|
+
checkedEntries.set(entry, { admission, confirmFields: snapshot.confirmFields, stage, used: false });
|
|
4291
|
+
const body = snapshot.content;
|
|
4292
|
+
return verb === "put" ? resource.putLocked(body, undefined, [], entry) : resource.patchLocked(body, undefined, entry);
|
|
4293
|
+
});
|
|
4294
|
+
}
|
|
4295
|
+
/**
|
|
4296
|
+
* flair#2478 part 3a — a Memory PUT made while the caller already holds the
|
|
4297
|
+
* per-id lock. Not a Harper verb: an ordinary function. `held` must be a live
|
|
4298
|
+
* lock token acquired on `Memory.primaryStore` for every id the write names
|
|
4299
|
+
* (its target, the body id and a `supersedes` target), and `tx` the locked
|
|
4300
|
+
* transaction scope opened on that acquisition (resources/memory-write-transaction.ts);
|
|
4301
|
+
* otherwise it is refused (`MemoryWriteCapabilityError`) and nothing is staged.
|
|
4302
|
+
* It enters the ordinary PUT's write body without acquiring a lock or opening a
|
|
4303
|
+
* transaction, joins the scope's transaction and returns `staged`. After the
|
|
4304
|
+
* scope commits, the body resumes for the PUT's post-commit steps; its
|
|
4305
|
+
* verification also compares the row's id and `confirmFields`. A skill write
|
|
4306
|
+
* or an `_reindex` body is refused.
|
|
4307
|
+
*/
|
|
4308
|
+
export function putMemoryWithLock(held, tx, input) {
|
|
4309
|
+
return enterCheckedWrite("put", held, tx, input);
|
|
4310
|
+
}
|
|
4311
|
+
/**
|
|
4312
|
+
* flair#2478 part 3a — a Memory PATCH made while the caller already holds the
|
|
4313
|
+
* per-id lock; the PATCH counterpart of {@link putMemoryWithLock} (its target
|
|
4314
|
+
* and body id are its write set). A re-embed body is refused.
|
|
4315
|
+
*/
|
|
4316
|
+
export function patchMemoryWithLock(held, tx, input) {
|
|
4317
|
+
return enterCheckedWrite("patch", held, tx, input);
|
|
3285
4318
|
}
|