@tpsdev-ai/flair 0.59.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 +10 -10
- package/SECURITY.md +49 -5
- package/config.yaml +23 -12
- package/dist/bridges/builtins/mem0.js +63 -28
- package/dist/bridges/runtime/execute.js +1 -0
- package/dist/bridges/runtime/import-runner.js +12 -0
- package/dist/bridges/runtime/load-plugin.js +42 -13
- package/dist/bridges/runtime/yaml-loader.js +4 -2
- package/dist/bridges/types.js +1 -0
- package/dist/build-info.json +3 -3
- package/dist/cli.js +1054 -367
- package/dist/commands/agent.js +233 -90
- package/dist/commands/attention.js +4 -3
- package/dist/commands/backup-approval.js +218 -0
- package/dist/commands/backup.js +211 -39
- package/dist/commands/bootstrap.js +3 -1
- package/dist/commands/bridge.js +172 -119
- package/dist/commands/deploy.js +71 -8
- package/dist/commands/doctor.js +711 -146
- package/dist/commands/export.js +57 -23
- package/dist/commands/federation.js +787 -82
- package/dist/commands/grant.js +5 -6
- package/dist/commands/help.js +25 -0
- package/dist/commands/hook.js +155 -2
- package/dist/commands/idp.js +27 -19
- package/dist/commands/import.js +136 -20
- package/dist/commands/init.js +469 -200
- package/dist/commands/integrity.js +387 -0
- package/dist/commands/keys.js +247 -58
- package/dist/commands/mcp.js +108 -52
- package/dist/commands/memory.js +203 -35
- package/dist/commands/migrate-harness-memory.js +3 -2
- package/dist/commands/orgevent.js +51 -47
- package/dist/commands/presence.js +4 -3
- package/dist/commands/principal.js +428 -62
- package/dist/commands/quality.js +13 -1
- package/dist/commands/reembed.js +141 -17
- package/dist/commands/relationship.js +2 -1
- package/dist/commands/rem.js +537 -80
- package/dist/commands/restore.js +413 -65
- package/dist/commands/search.js +6 -4
- package/dist/commands/service.js +235 -40
- package/dist/commands/soul.js +4 -9
- package/dist/commands/status.js +94 -38
- package/dist/commands/test.js +7 -3
- package/dist/commands/upgrade.js +77 -23
- package/dist/commands/workspace.js +13 -11
- package/dist/component-env.js +31 -41
- package/dist/deploy.js +136 -4
- package/dist/doctor-client.js +534 -92
- package/dist/engine-version-contract.js +1 -0
- package/dist/engine-version.js +23 -3
- package/dist/fabric-upgrade.js +12 -2
- package/dist/federation/presence-send.js +139 -0
- package/dist/federation-verify.js +273 -180
- package/dist/hook-install.js +670 -6
- package/dist/install/clients.js +171 -35
- package/dist/keystore.js +72 -0
- package/dist/lib/action-recall-runtime.js +328 -0
- package/dist/lib/agent-home-fields.js +132 -0
- package/dist/lib/agent-home.js +427 -0
- package/dist/lib/agent-id-rule.js +88 -0
- package/dist/lib/agent-roster.js +33 -0
- package/dist/lib/atomic-write.js +1 -1
- package/dist/lib/auth-resolve.js +1069 -60
- package/dist/lib/backup-approval-store.js +612 -0
- package/dist/lib/backup-artifact.js +343 -0
- package/dist/lib/capture-runtime.js +124 -0
- package/dist/lib/config-critical-section.js +212 -25
- package/dist/lib/connect-phase.js +33 -0
- package/dist/lib/credential-status-rule.js +78 -0
- package/dist/lib/daemon-liveness.js +43 -11
- package/dist/lib/doctor-run.js +75 -37
- package/dist/lib/durability-copy.js +10 -0
- package/dist/lib/embedding-space-doctor.js +75 -0
- 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/flair-agent-role.js +4 -0
- package/dist/lib/hub-url.js +12 -0
- package/dist/lib/init-admin-pass.js +88 -12
- package/dist/lib/init-listener-environ.js +1 -2
- package/dist/lib/init-occupied-listener.js +15 -111
- package/dist/lib/init-spawn-attribution.js +73 -0
- package/dist/lib/init-tcp-probe.js +33 -0
- package/dist/lib/instance-identity-row.js +20 -0
- package/dist/lib/instruction-event-contract.js +17 -0
- package/dist/lib/instruction-event-doctor.js +102 -0
- package/dist/lib/launchd-management.js +38 -3
- package/dist/lib/listener-table.js +268 -0
- package/dist/lib/local-delete-instance.js +27 -0
- package/dist/lib/local-instance-pair.js +256 -0
- package/dist/lib/mcp-enable.js +1182 -341
- package/dist/lib/mcp-oauth-env-core.js +133 -0
- package/dist/lib/mcp-oauth-env.js +125 -0
- package/dist/lib/mcp-spec.js +17 -1
- package/dist/lib/memory-attributes.js +4 -0
- package/dist/lib/memory-id-policy.js +46 -0
- package/dist/lib/memory-integrity.js +309 -0
- package/dist/lib/memory-provider-timeout.js +33 -0
- package/dist/lib/memory-purge-response.js +20 -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-table-count.js +25 -0
- package/dist/lib/ops-url.js +52 -0
- package/dist/lib/owned-pins.js +67 -10
- package/dist/lib/peer-status.js +27 -0
- package/dist/lib/principal-status.js +29 -0
- package/dist/lib/process-start-time.js +76 -12
- package/dist/lib/promotion-content-hash.js +20 -0
- package/dist/lib/proto-safe-record.js +42 -0
- package/dist/lib/record-id-path.js +25 -0
- package/dist/lib/reembed-server-support.js +66 -0
- package/dist/lib/restore-archive.js +760 -0
- package/dist/lib/restore-verify.js +104 -0
- package/dist/lib/scheduler-platform.js +10 -6
- package/dist/lib/secret-keys.js +25 -0
- package/dist/lib/secrets-push.js +50 -22
- package/dist/lib/skill-assignment-preflight.js +159 -0
- package/dist/lib/skill-seed-pending.js +24 -0
- package/dist/lib/skill-seed.js +448 -0
- package/dist/lib/skill-tombstone-doctor.js +133 -0
- package/dist/lib/soul-scope-fields.js +26 -0
- package/dist/lib/stop-start-recovery.js +54 -0
- package/dist/lib/uninstall-purge.js +266 -11
- package/dist/lib/upgrade-prior-liveness.js +2 -1
- package/dist/lib/using-flair-skill.js +87 -0
- package/dist/mcp-client-assertion.js +114 -14
- package/dist/memory-id-checkpoint.js +347 -0
- package/dist/memory-node-compare.js +207 -0
- package/dist/mqtt-off-deploy.js +550 -0
- package/dist/packages/flair-mcp/src/secret-redaction.js +113 -0
- package/dist/rem/promote-policy.js +3 -3
- package/dist/rem/restore.js +303 -26
- package/dist/rem/runner.js +317 -96
- 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 +463 -33
- package/dist/resources/AgentCard.js +4 -0
- package/dist/resources/AgentKeyRegister.js +248 -0
- package/dist/resources/AgentKeyRegistration.js +28 -0
- package/dist/resources/AgentReadPosition.js +7 -0
- package/dist/resources/AgentSeed.js +238 -107
- package/dist/resources/AutoPromoteCandidates.js +413 -78
- package/dist/resources/Credential.js +183 -10
- package/dist/resources/Federation.js +915 -145
- package/dist/resources/FederationRetry.js +140 -0
- package/dist/resources/InstructionVersion.js +220 -0
- package/dist/resources/Integration.js +300 -25
- package/dist/resources/MCPClientMetadata.js +6 -3
- package/dist/resources/Memory.js +3300 -758
- package/dist/resources/MemoryArchive.js +171 -53
- package/dist/resources/MemoryBootstrap.js +122 -61
- package/dist/resources/MemoryCandidate.js +37 -3
- package/dist/resources/MemoryConsolidate.js +2 -2
- package/dist/resources/MemoryDedupStats.js +30 -1
- package/dist/resources/MemoryFeed.js +545 -50
- package/dist/resources/MemoryGrant.js +21 -1
- package/dist/resources/MemoryMaintenance.js +368 -46
- package/dist/resources/MemoryPurge.js +348 -0
- package/dist/resources/MemoryReflect.js +71 -12
- package/dist/resources/MemoryReindex.js +111 -17
- package/dist/resources/Message.js +16 -5
- package/dist/resources/OAuth.js +342 -48
- package/dist/resources/OAuthClient.js +1 -1
- package/dist/resources/OrgEvent.js +405 -19
- 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 +166 -51
- package/dist/resources/PromoteMemoryCandidate.js +24 -7
- package/dist/resources/RecordUsage.js +2 -4
- package/dist/resources/Relationship.js +23 -0
- package/dist/resources/SemanticSearch.js +63 -32
- package/dist/resources/Soul.js +191 -76
- package/dist/resources/SoulFeed.js +2 -1
- package/dist/resources/TeamDirectory.js +35 -0
- package/dist/resources/WorkspaceLatest.js +4 -0
- package/dist/resources/WorkspaceState.js +21 -1
- package/dist/resources/XAA.js +207 -63
- 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 +138 -83
- 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 +534 -171
- 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/ed25519-auth.js +1 -1
- package/dist/resources/embedding-space-guard.js +366 -72
- package/dist/resources/embeddings-provider.js +25 -0
- package/dist/resources/engine-version-stamp-boot.js +53 -0
- package/dist/resources/federation-classify.js +161 -0
- package/dist/resources/federation-crypto.js +5 -5
- package/dist/resources/federation-retry-lib.js +60 -0
- package/dist/resources/grant-visibility.js +135 -0
- package/dist/resources/harper-routing.js +83 -0
- package/dist/resources/health.js +163 -22
- package/dist/resources/host-pointer/registry.js +29 -0
- package/dist/resources/host-pointer-adapter.js +1 -0
- package/dist/resources/host-source-citation.js +49 -0
- package/dist/resources/host-source-visibility.js +7 -6
- package/dist/resources/in-process.js +24 -22
- package/dist/resources/instance-create-lock.js +17 -0
- package/dist/resources/instance-identity.js +23 -0
- package/dist/resources/instruction-version-record.js +587 -0
- package/dist/resources/internal-authority.js +13 -0
- package/dist/resources/key-lock.js +3 -3
- package/dist/resources/mcp-handler.js +141 -19
- package/dist/resources/mcp-oauth-env-guard.js +36 -0
- package/dist/resources/mcp-oauth-flag.js +12 -14
- package/dist/resources/mcp-oauth.js +450 -56
- package/dist/resources/mcp-tool-arguments.js +4 -6
- package/dist/resources/mcp-tools.js +187 -40
- package/dist/resources/memory-bootstrap-lib.js +5 -15
- package/dist/resources/memory-declared-attributes.js +4 -1
- package/dist/resources/memory-deletion-history.js +55 -0
- package/dist/resources/memory-durability.js +54 -0
- package/dist/resources/memory-embed-hash.js +144 -0
- package/dist/resources/memory-embedding-value.js +8 -0
- package/dist/resources/memory-host-source.js +32 -7
- package/dist/resources/memory-id-guard.js +75 -0
- package/dist/resources/memory-redaction.js +236 -0
- package/dist/resources/memory-reflect-lib.js +1 -1
- package/dist/resources/memory-supplied-vector.js +72 -0
- package/dist/resources/memory-write-lock.js +489 -0
- package/dist/resources/memory-write-response.js +139 -0
- 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 +90 -19
- package/dist/resources/migrations/dir-safety.js +61 -3
- package/dist/resources/migrations/embedding-stamp.js +462 -82
- package/dist/resources/migrations/export.js +1 -0
- package/dist/resources/migrations/graph-heal.js +27 -27
- package/dist/resources/migrations/ledger.js +5 -2
- package/dist/resources/migrations/lock.js +870 -77
- package/dist/resources/migrations/progress.js +71 -10
- package/dist/resources/migrations/runner.js +212 -18
- package/dist/resources/migrations/snapshot.js +1 -0
- package/dist/resources/migrations/source-fields.js +5 -5
- package/dist/resources/migrations/state.js +36 -1
- package/dist/resources/migrations/status.js +2 -13
- package/dist/resources/migrations/synthetic-test-migration.js +81 -12
- package/dist/resources/migrations/types.js +26 -1
- package/dist/resources/migrations/visibility-backfill.js +113 -72
- package/dist/resources/oauth-discovery.js +0 -5
- package/dist/resources/object-body-guard.js +40 -0
- package/dist/resources/org-event-created-at.js +133 -0
- package/dist/resources/org-event-reserved.js +92 -0
- package/dist/resources/org-event-write-fault.js +19 -0
- package/dist/resources/originator-instance.js +39 -7
- package/dist/resources/owner-delete-recheck.js +78 -0
- package/dist/resources/owner-field-guard.js +39 -5
- package/dist/resources/owner-scoped-write-policy.js +256 -0
- package/dist/resources/owner-scoped-writes.js +89 -0
- package/dist/resources/path-id-rewrite.js +76 -0
- package/dist/resources/presence-internal.js +5 -5
- package/dist/resources/presence-receipt.js +236 -0
- package/dist/resources/promotion-binding.js +43 -0
- package/dist/resources/promotion-stamp.js +143 -17
- package/dist/resources/protocol-context.js +189 -0
- package/dist/resources/record-owner-guard.js +74 -26
- package/dist/resources/record-type-kit.js +2 -4
- package/dist/resources/record-types.js +1 -1
- package/dist/resources/relay-ops.js +78 -6
- package/dist/resources/replay-store.js +96 -19
- package/dist/resources/request-target.js +163 -0
- package/dist/resources/request-transaction.js +46 -1
- package/dist/resources/search-readiness.js +4 -1
- package/dist/resources/seed-ids.js +9 -0
- package/dist/resources/seed-reservation.js +116 -0
- package/dist/resources/semantic-retrieval-core.js +27 -15
- package/dist/resources/server-row-validation.js +71 -0
- package/dist/resources/skill-manifest.js +24 -14
- package/dist/resources/skill-subject.js +53 -0
- package/dist/resources/skill-version-write.js +789 -0
- package/dist/resources/skill-write-fault.js +20 -0
- package/dist/resources/skill-write-policy.js +68 -0
- package/dist/resources/skill-write.js +67 -7
- package/dist/resources/soul-write-policy.js +26 -7
- package/dist/resources/table-helpers.js +10 -7
- package/dist/resources/table-subscription-policy.js +518 -85
- package/dist/resources/table-subscriptions.js +20 -7
- package/dist/resources/team-directory.js +248 -0
- package/dist/resources/tool-descriptors/index.js +69 -8
- package/dist/resources/txn-pause-point.js +235 -0
- package/dist/resources/usage-recording.js +186 -70
- package/dist/resources/write-back.js +383 -0
- package/dist/resources/write-journal-context.js +5 -0
- package/dist/resources/write-journal.js +289 -0
- package/dist/src/engine-version-contract.js +1 -0
- package/dist/src/keystore.js +72 -0
- package/dist/src/lib/agent-home-fields.js +132 -0
- package/dist/src/lib/agent-id-rule.js +88 -0
- package/dist/src/lib/agent-key-register.js +80 -0
- package/dist/src/lib/atomic-write.js +256 -0
- package/dist/src/lib/credential-status-rule.js +78 -0
- package/dist/src/lib/expired-by-agent.js +37 -0
- package/dist/src/lib/federation-retry-row.js +101 -0
- package/dist/src/lib/flair-agent-role.js +4 -0
- package/dist/src/lib/idp-mapping-rule.js +81 -0
- package/dist/src/lib/instance-identity-row.js +20 -0
- package/dist/src/lib/instruction-event-contract.js +17 -0
- package/dist/src/lib/mcp-oauth-env-core.js +133 -0
- package/dist/src/lib/memory-attributes.js +4 -0
- package/dist/src/lib/memory-id-policy.js +46 -0
- package/dist/src/lib/open-live-row.js +20 -0
- package/dist/src/lib/principal-status.js +29 -0
- package/dist/src/lib/proto-safe-record.js +42 -0
- package/dist/src/lib/reembed-server-support.js +66 -0
- package/dist/src/lib/scheduler-platform.js +10 -6
- package/dist/src/lib/soul-scope-fields.js +26 -0
- package/dist/src/lib/systemd-agent-id.js +38 -0
- package/dist/src/rem/promote-policy.js +3 -3
- package/dist/src/rem/scheduler.js +21 -4
- package/docs/access-control.md +164 -54
- package/docs/api-reference.md +165 -32
- package/docs/auth.md +46 -30
- package/docs/bridges.md +11 -0
- package/docs/claude-code.md +37 -7
- package/docs/deploying-on-fabric.md +178 -0
- package/docs/deployment.md +19 -0
- package/docs/embedding-in-a-harper-app.md +17 -15
- package/docs/entity-vocabulary.md +3 -6
- package/docs/federation.md +61 -3
- package/docs/hosted-on-fabric.md +43 -36
- package/docs/integrations.md +14 -14
- package/docs/mcp-clients.md +12 -7
- package/docs/n8n.md +17 -11
- package/docs/notes/mcp-agent-auth-consumer.md +16 -13
- package/docs/notes/mcp-oauth-model2.md +40 -11
- package/docs/openclaw.md +1 -1
- package/docs/quickstart-fabric.md +4 -4
- package/docs/quickstart.md +12 -4
- package/docs/releasing.md +25 -19
- package/docs/rem.md +32 -3
- package/docs/secrets-and-keys.md +21 -4
- package/docs/standalone-local.md +30 -2
- package/docs/supply-chain-policy.md +34 -16
- package/docs/the-team.md +2 -2
- package/docs/upgrade.md +46 -6
- package/package.json +24 -12
- package/schemas/agent-key-registration.graphql +22 -0
- package/schemas/agent.graphql +6 -3
- package/schemas/federation.graphql +41 -1
- package/schemas/memory.graphql +91 -7
- package/schemas/oauth.graphql +19 -0
- package/schemas/schema.graphql +2 -0
- 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
|
@@ -1,33 +1,54 @@
|
|
|
1
|
+
import { isEmptyEmbedding, normalizeEmptyEmbedding } from "./memory-embedding-value.js";
|
|
2
|
+
import { discardSuppliedVector, suppliedVectorFlags } from "./memory-supplied-vector.js";
|
|
1
3
|
import { databases } from "harper";
|
|
2
4
|
import { randomUUID } from "node:crypto";
|
|
5
|
+
import { isOperatorSeedPut, redactMemoryWrite, redactSkillWrite, storedMemoryText, suppliedMemoryTextFields, suppliedStoredTextFields } from "./memory-redaction.js";
|
|
6
|
+
import { REDACTION_RULES, buildFromAllowlist, storageResult, withheldWriteResult, writeResultResponse } from "./memory-write-response.js";
|
|
7
|
+
import { isDeepStrictEqual } from "node:util";
|
|
3
8
|
import { patchRecord, withDetachedTxn } from "./table-helpers.js";
|
|
4
|
-
import {
|
|
9
|
+
import { annotatedCallerIsAdmin, resolveAgentAuth } from "./agent-auth.js";
|
|
5
10
|
import { guardAuthorityFields } from "./authority-field-guard.js";
|
|
6
11
|
import { isForbiddenOwnerMutation } from "./record-owner-guard.js";
|
|
7
12
|
import { guardOwnerFieldImmutable } from "./owner-field-guard.js";
|
|
13
|
+
import { ownerChangedRefusal } from "./owner-delete-recheck.js";
|
|
8
14
|
import { applyFederationBookkeeping, applyOriginatorInstanceId, dropClientFederationBookkeeping, keepStoredOriginator, resolveStoredRow, stampOriginatorOnCreate } from "./originator-instance.js";
|
|
9
15
|
import { getEmbedding, getModelId } from "./embeddings-provider.js";
|
|
10
16
|
import { isEmbeddingSpaceUniform, noteWriteStamp } from "./embedding-space-guard.js";
|
|
11
17
|
import { scanFields, isStrictMode } from "./content-safety.js";
|
|
12
18
|
import { invalidEntitiesResponse } from "./entity-vocab.js";
|
|
13
19
|
import { checkRateLimit, rateLimitResponse } from "./rate-limiter.js";
|
|
20
|
+
import { isOpenLiveRow } from "../src/lib/open-live-row.js";
|
|
14
21
|
import { assertValidVisibility, assertVisibilityAllowedForDurability, PRIVATE_VISIBILITY, SHARED_VISIBILITY } from "./memory-visibility.js";
|
|
15
22
|
import { validateHostSource } from "./host-source.js";
|
|
16
23
|
import { buildPointerRow, extractPointerInputs, isPointerEchoOf, loadStoredPointer, projectRowsThroughPointers, } from "./memory-host-source.js";
|
|
17
|
-
import { putPointerRow, deletePointerRowViaTable } from "./host-pointer-adapter.js";
|
|
18
|
-
import { stripUndeclaredMemoryAttributes, stripServerStampedFields } from "./memory-declared-attributes.js";
|
|
19
|
-
import { isJoinableTransaction, withSharedWriteTransaction } from "./request-transaction.js";
|
|
20
|
-
import {
|
|
21
|
-
import {
|
|
24
|
+
import { putPointerRow, deletePointerRowViaTable, restorePointerRowIfAbsent, PointerAlreadyStoredError } from "./host-pointer-adapter.js";
|
|
25
|
+
import { DECLARED_MEMORY_ATTRIBUTES, stripUndeclaredMemoryAttributes, stripServerStampedFields } from "./memory-declared-attributes.js";
|
|
26
|
+
import { composesCallerWrite, isJoinableTransaction, withOwnedTransaction, withSharedWriteTransaction } from "./request-transaction.js";
|
|
27
|
+
import { PredecessorVisibilityChanged, applyGrantedVisibility, committedVisibilityDiffers, predecessorVisibilityChangedRefusal } from "./grant-visibility.js";
|
|
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";
|
|
32
|
+
import { assertValidDurability, stampEphemeralExpiry } from "./memory-durability.js";
|
|
33
|
+
import { embedTextField, enforceSkillDurability, isSkillWrite, rejectSkillWritePath, refuseSkillWriteSource, skillEmbedText, skillScanGate, skillMetadataHasDuplicateKey } from "./skill-write.js";
|
|
34
|
+
import { embeddedTextHash, hashEmbeddedText } from "./memory-embed-hash.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";
|
|
37
|
+
import { deriveSkillSubjectId } from "./skill-subject.js";
|
|
22
38
|
import { DEDUP_COSINE_THRESHOLD_DEFAULT, DEDUP_LEXICAL_THRESHOLD_DEFAULT, DEDUP_MIN_CONTENT_LENGTH, computeMatchConfidence, cosineSimilarity, isConservativeMatch, } from "./dedup.js";
|
|
23
|
-
import { buildProvenance, makeAuthGate, makeReadScope, makeByIdReadGate, makeScopedSearch, resolveAuthGate, stampAttribution, FORBIDDEN, UNAUTH, } from "./record-type-kit.js";
|
|
39
|
+
import { buildProvenance, makeAuthGate, makeReadScope, makeByIdReadGate, makeScopedSearch, resolveAuthGate, stampAttribution, FORBIDDEN, UNAUTH, NOT_FOUND, } from "./record-type-kit.js";
|
|
24
40
|
import { isSemanticPatch, MEMORY_SEMANTIC_FIELDS } from "./provenance.js";
|
|
25
41
|
import { RECORD_TYPES } from "./record-types.js";
|
|
26
42
|
import { attachTrust } from "./trust-block.js";
|
|
27
43
|
import { recordCitations } from "./usage-recording.js";
|
|
28
44
|
import { noteMemoryUpsert, noteMemoryDelete } from "./bm25-index-service.js";
|
|
45
|
+
import { recordMemoryDeletion, removeMemoryDeletionRecords } from "./memory-deletion-history.js";
|
|
29
46
|
import { applyHitStats, clearHitStats, overlayHitStatsResult } from "./hit-tracking.js";
|
|
47
|
+
import { applyPromotionBinding } from "./promotion-binding.js";
|
|
30
48
|
import { refuseStaleClientWrite, stripClientVersionPassthrough } from "./client-version-gate.js";
|
|
49
|
+
import { refuseReservedSeedWrite, reservedSeedWriteDenial, reservedSeedSubjectDenial, isReservedSeedId, writeTargetIds } from "./seed-reservation.js";
|
|
50
|
+
import { refuseContentSuffixId, resolveMemoryReferenceId, supersedesTargetMissing, supersedesTargetUnreadable } from "./memory-id-guard.js";
|
|
51
|
+
import { guardObjectBody } from "./object-body-guard.js";
|
|
31
52
|
/** flair#1940 A1' — a named 400 for an invalid host pointer (reject, never
|
|
32
53
|
* truncate). Same shape the pre-A1' inline checks returned. */
|
|
33
54
|
function hostSourceBadRequest(error, message) {
|
|
@@ -53,6 +74,16 @@ function withoutCallerSelection(query) {
|
|
|
53
74
|
delete copy.property;
|
|
54
75
|
return copy;
|
|
55
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
|
+
}
|
|
56
87
|
/**
|
|
57
88
|
* Write the Memory row joining transaction `c` (0a). Resource.prototype.post
|
|
58
89
|
* uses the instance's OWN `#context`, which an internal caller (a direct
|
|
@@ -60,16 +91,24 @@ function withoutCallerSelection(query) {
|
|
|
60
91
|
* so the base collection `create(id, record, context)` is used, which honours
|
|
61
92
|
* an explicit context and joins `c.transaction`. Returns the new id. Falls
|
|
62
93
|
* back to the static post for the unit mock (which models post, not create).
|
|
94
|
+
* flair#2561: a Response from the storage layer is returned as the
|
|
95
|
+
* `write_response_withheld` refusal (storageResult), never as an id.
|
|
63
96
|
*/
|
|
64
97
|
async function writeMemoryRowPost(cls, content, c) {
|
|
65
98
|
if (typeof cls?.create === "function") {
|
|
66
|
-
const created = await cls.create(content.id ?? null, content, c);
|
|
99
|
+
const created = storageResult(await cls.create(content.id ?? null, content, c));
|
|
100
|
+
if (created instanceof Response)
|
|
101
|
+
return created;
|
|
67
102
|
if (typeof created === "string")
|
|
68
103
|
return created;
|
|
69
|
-
|
|
104
|
+
const id = created?.getId?.() ?? created?.id;
|
|
105
|
+
return typeof id === "string" ? id : withheldWriteResult();
|
|
70
106
|
}
|
|
71
|
-
const r = await databases.flair.Memory.post(content, c);
|
|
72
|
-
|
|
107
|
+
const r = storageResult(await databases.flair.Memory.post(content, c));
|
|
108
|
+
if (r instanceof Response)
|
|
109
|
+
return r;
|
|
110
|
+
const id = typeof r === "string" ? r : r?.id;
|
|
111
|
+
return typeof id === "string" ? id : withheldWriteResult();
|
|
73
112
|
}
|
|
74
113
|
/** The authenticated author id for a pointer row, or "" when there is no
|
|
75
114
|
* principal (internal write). NEVER the body. */
|
|
@@ -163,6 +202,309 @@ function abortRequestTransaction(ctx) {
|
|
|
163
202
|
// failure MUST propagate rather than being swallowed behind a 500 body.
|
|
164
203
|
txn.abort();
|
|
165
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
|
+
}
|
|
220
|
+
/**
|
|
221
|
+
* flair#2478 slice 1 — the `Memory.primaryStore` write-lock handle. Production
|
|
222
|
+
* is a real Harper table (a `primaryStore` with `tryLock`/`unlock`). A store
|
|
223
|
+
* without a lock reports `unavailable`, and PUT/PATCH refuse with 503
|
|
224
|
+
* `memory_lock_unavailable`; they never run unserialized. A unit-test double
|
|
225
|
+
* supplies a lock on its mock table's `primaryStore`.
|
|
226
|
+
*/
|
|
227
|
+
function memoryWriteLockStore() {
|
|
228
|
+
return databases?.flair?.Memory?.primaryStore;
|
|
229
|
+
}
|
|
230
|
+
/** The lock ids a Memory verb names: the URL-bound id and body id(s), dropping
|
|
231
|
+
* non-id values so the sorted, deduplicated key set is real. */
|
|
232
|
+
function putLockIds(resource, content) {
|
|
233
|
+
return writeTargetIds(resource, content)
|
|
234
|
+
.filter((id) => typeof id === "string" || typeof id === "number")
|
|
235
|
+
.map((id) => String(id));
|
|
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
|
+
}
|
|
321
|
+
/** The caller id a lock-miss refusal carries — the request's agent annotation,
|
|
322
|
+
* else `anonymous`/`internal`. Never stored-row state (Sherlock S7). */
|
|
323
|
+
function memoryLockCallerId(resource) {
|
|
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) {
|
|
329
|
+
const request = ctx?.request ?? ctx;
|
|
330
|
+
if (typeof request?.tpsAgent === "string" && request.tpsAgent.length > 0)
|
|
331
|
+
return request.tpsAgent;
|
|
332
|
+
if (request?.tpsAnonymous === true)
|
|
333
|
+
return "anonymous";
|
|
334
|
+
return "internal";
|
|
335
|
+
}
|
|
336
|
+
/** PUT and PATCH require a target id before entering the lock helper. */
|
|
337
|
+
function memoryIdRequiredResponse() {
|
|
338
|
+
return new Response(JSON.stringify({
|
|
339
|
+
error: "memory_id_required",
|
|
340
|
+
message: "a Memory PUT or PATCH names the memory id in the URL or the body; to create a memory without choosing an id, use POST",
|
|
341
|
+
}), { status: 400, headers: { "content-type": "application/json" } });
|
|
342
|
+
}
|
|
343
|
+
/**
|
|
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
|
|
348
|
+
* update instead of replacing it (flair#2470), so a differing `archived` is not
|
|
349
|
+
* evidence that this write did not land.
|
|
350
|
+
*/
|
|
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
|
+
}
|
|
371
|
+
function sameDeclaredField(stored, declared) {
|
|
372
|
+
return isDeepStrictEqual(stored, declared);
|
|
373
|
+
}
|
|
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) {
|
|
380
|
+
const id = declared?.id ?? fallbackId;
|
|
381
|
+
if (id === undefined || id === null)
|
|
382
|
+
return { unknown: true };
|
|
383
|
+
let row;
|
|
384
|
+
try {
|
|
385
|
+
row = await table.get(id, {});
|
|
386
|
+
}
|
|
387
|
+
catch {
|
|
388
|
+
return { unknown: true };
|
|
389
|
+
}
|
|
390
|
+
if (!row)
|
|
391
|
+
return { mismatch: true };
|
|
392
|
+
if ((row.instanceToken ?? null) !== (identity.expectedToken ?? null))
|
|
393
|
+
return { mismatch: true };
|
|
394
|
+
for (const field of fields) {
|
|
395
|
+
if (!Object.prototype.hasOwnProperty.call(declared, field))
|
|
396
|
+
continue;
|
|
397
|
+
if (!sameDeclaredField(row[field], declared[field]))
|
|
398
|
+
return { mismatch: true };
|
|
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
|
+
}
|
|
415
|
+
return {};
|
|
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
|
+
}
|
|
488
|
+
/** Mark the id after a failed post-commit verification read (flair#2478). */
|
|
489
|
+
function writeOutcomeUnknownFor(id) {
|
|
490
|
+
if (typeof id === "string" || typeof id === "number")
|
|
491
|
+
markMemoryWriteOutcomeUnknown(id);
|
|
492
|
+
return writeOutcomeUnknownResponse();
|
|
493
|
+
}
|
|
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
|
+
});
|
|
507
|
+
}
|
|
166
508
|
/**
|
|
167
509
|
* flair#1940 A1' item 2 — persist the pointer row in the SAME request
|
|
168
510
|
* transaction as the Memory row. The request context is passed to the table
|
|
@@ -295,13 +637,9 @@ const memoryAuthGate = makeAuthGate();
|
|
|
295
637
|
* Memory.post() directly, got ZERO dedup checking. Moving the gate here makes
|
|
296
638
|
* it apply uniformly regardless of transport (HTTP PUT vs in-process post()).
|
|
297
639
|
*
|
|
298
|
-
* NOTE on HTTP verbs:
|
|
299
|
-
*
|
|
300
|
-
*
|
|
301
|
-
* `Memory.post()` IS reachable, but only via an in-process resource
|
|
302
|
-
* instantiation (as resources/mcp-tools.ts does) — never via the real HTTP
|
|
303
|
-
* POST route. Because flair-client's write() (used by flair-mcp, the CLI, and
|
|
304
|
-
* 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
|
|
305
643
|
* field-observed bug (#526) flows through Memory.put(), not Memory.post().
|
|
306
644
|
* The gate below is therefore a SHARED helper invoked from both post() and
|
|
307
645
|
* put() — anchored in the same place the design calls out (Memory.post), but
|
|
@@ -313,10 +651,15 @@ async function findConservativeDedupMatch(ctx, agentId, contentText, embedding,
|
|
|
313
651
|
if (!agentId || !embedding || embedding.length === 0)
|
|
314
652
|
return null;
|
|
315
653
|
// ── Vector-space uniformity guard (embedding-space-guard slice 1) ──────────
|
|
316
|
-
// When the
|
|
317
|
-
// compare below
|
|
318
|
-
//
|
|
319
|
-
//
|
|
654
|
+
// When the stored model stamps are NOT KNOWN uniform in the current embedding
|
|
655
|
+
// space, the cosine compare below could cross vector spaces or produce an
|
|
656
|
+
// invalid score (Harper zero-pads a mismatched-dimension vector). No-op the
|
|
657
|
+
// dedup cosine leg — treat as no-match — through
|
|
658
|
+
// the SAME single chokepoint the recall leg (SemanticSearch) consults. The
|
|
659
|
+
// guard fails CLOSED (flair#2530): it returns false for an UNKNOWN verdict too
|
|
660
|
+
// (before the first scan completes, or after a scan error), so this leg no-ops
|
|
661
|
+
// in exactly those states — the same no-match behavior as the `mixed` state. This
|
|
662
|
+
// leg surfaces no warning (a skipped comparison is invisible by design).
|
|
320
663
|
// ADVISORY ONLY: the write always proceeds (runDedupGate already computed and
|
|
321
664
|
// stamped a fresh CURRENT-space embedding); this only skips a comparison that
|
|
322
665
|
// can't be trusted while spaces are mixed. Never suppresses a write.
|
|
@@ -432,7 +775,7 @@ async function findConservativeDedupMatch(ctx, agentId, contentText, embedding,
|
|
|
432
775
|
*
|
|
433
776
|
* Returns the match signal, or null (no match / gate not applicable).
|
|
434
777
|
*/
|
|
435
|
-
async function runDedupGate(ctx, content) {
|
|
778
|
+
async function runDedupGate(ctx, content, bounded = false) {
|
|
436
779
|
const cosineThreshold = typeof content.dedupThreshold === "number" ? content.dedupThreshold : DEDUP_COSINE_THRESHOLD_DEFAULT;
|
|
437
780
|
const lexicalThreshold = typeof content.lexicalThreshold === "number" ? content.lexicalThreshold : DEDUP_LEXICAL_THRESHOLD_DEFAULT;
|
|
438
781
|
delete content.dedup;
|
|
@@ -470,9 +813,11 @@ async function runDedupGate(ctx, content) {
|
|
|
470
813
|
let embedding = Array.isArray(content.embedding) ? content.embedding : null;
|
|
471
814
|
if (!embedding) {
|
|
472
815
|
try {
|
|
473
|
-
embedding = await getEmbedding(embedText, "document");
|
|
816
|
+
embedding = bounded ? await embedUnderLock(embedText) : await getEmbedding(embedText, "document");
|
|
474
817
|
}
|
|
475
|
-
catch {
|
|
818
|
+
catch (err) {
|
|
819
|
+
if (err instanceof MemoryProviderTimeout)
|
|
820
|
+
throw err;
|
|
476
821
|
embedding = null;
|
|
477
822
|
}
|
|
478
823
|
if (embedding) {
|
|
@@ -484,101 +829,337 @@ async function runDedupGate(ctx, content) {
|
|
|
484
829
|
return null;
|
|
485
830
|
return findConservativeDedupMatch(ctx, content.agentId, embedText, embedding, cosineThreshold, lexicalThreshold);
|
|
486
831
|
}
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
832
|
+
const RESPONSE_ID = Object.freeze({ type: "string", required: true });
|
|
833
|
+
const RESPONSE_WRITTEN = Object.freeze({ type: "boolean", required: true });
|
|
834
|
+
const MEMORY_WRITE_RESPONSE_RULES = Object.freeze({
|
|
835
|
+
id: RESPONSE_ID,
|
|
836
|
+
written: RESPONSE_WRITTEN,
|
|
837
|
+
deduplicated: Object.freeze({ type: "boolean", required: true }),
|
|
838
|
+
visibility: Object.freeze({ type: "string" }),
|
|
839
|
+
matchedId: Object.freeze({ type: "string" }),
|
|
840
|
+
matchConfidence: Object.freeze({
|
|
841
|
+
type: "object",
|
|
842
|
+
fields: Object.freeze({ cosine: Object.freeze({ type: "number" }), lexical: Object.freeze({ type: "number" }) }),
|
|
843
|
+
}),
|
|
844
|
+
...REDACTION_RULES,
|
|
845
|
+
});
|
|
846
|
+
const SKILL_RESULT_RULES = Object.freeze({
|
|
847
|
+
id: RESPONSE_ID,
|
|
848
|
+
written: RESPONSE_WRITTEN,
|
|
849
|
+
visibility: Object.freeze({ type: "string" }),
|
|
850
|
+
});
|
|
851
|
+
const ROW_WRITE_RESPONSE_RULES = Object.freeze({ id: RESPONSE_ID, written: RESPONSE_WRITTEN, ...REDACTION_RULES });
|
|
852
|
+
const REEMBED_RESPONSE_RULES = Object.freeze({
|
|
853
|
+
id: RESPONSE_ID,
|
|
854
|
+
updatedAt: Object.freeze({ type: "string", required: true }),
|
|
855
|
+
});
|
|
856
|
+
function redactionValues(redactedValues, stored) {
|
|
857
|
+
return redactedValues > 0 ? { redactedValues, stored: stored ?? undefined } : {};
|
|
858
|
+
}
|
|
859
|
+
function skillWriteResponse(result, redactedValues, stored) {
|
|
860
|
+
if (result instanceof Response)
|
|
861
|
+
return writeResultResponse(result);
|
|
862
|
+
const built = buildFromAllowlist(result, SKILL_RESULT_RULES);
|
|
863
|
+
if (built instanceof Response || redactedValues <= 0)
|
|
864
|
+
return built;
|
|
865
|
+
const redaction = buildFromAllowlist(redactionValues(redactedValues, stored), REDACTION_RULES);
|
|
866
|
+
return redaction instanceof Response ? redaction : Object.assign(built, redaction);
|
|
867
|
+
}
|
|
868
|
+
/**
|
|
869
|
+
* The answer of a PATCH and of the admin `_reindex` re-PUT. A Response from
|
|
870
|
+
* storage is refused (writeResultResponse). A write that replaced no value
|
|
871
|
+
* answers with no body (HTTP 204), the answer Harper gives for a PATCH; a write
|
|
872
|
+
* that replaced a value answers `{ id, written, redactedValues, stored }`, built
|
|
873
|
+
* from those named fields. Any other storage result is never read into the answer.
|
|
874
|
+
*/
|
|
875
|
+
function rowWriteResponse(result, id, redactedValues, stored) {
|
|
876
|
+
if (result instanceof Response)
|
|
877
|
+
return writeResultResponse(result);
|
|
878
|
+
if (redactedValues <= 0)
|
|
879
|
+
return undefined;
|
|
880
|
+
return buildFromAllowlist({ id, written: true, ...redactionValues(redactedValues, stored) }, ROW_WRITE_RESPONSE_RULES);
|
|
881
|
+
}
|
|
882
|
+
function buildWriteResponse(content, result, dedupMatch, redactedValues, stored, rowId) {
|
|
883
|
+
if (result instanceof Response)
|
|
884
|
+
return writeResultResponse(result);
|
|
885
|
+
return buildFromAllowlist({
|
|
886
|
+
id: content.id ?? rowId,
|
|
514
887
|
written: true,
|
|
515
888
|
deduplicated: !!dedupMatch,
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
889
|
+
visibility: content.visibility,
|
|
890
|
+
matchedId: dedupMatch?.matchedId,
|
|
891
|
+
matchConfidence: dedupMatch ? { cosine: dedupMatch.cosine, lexical: dedupMatch.lexical } : undefined,
|
|
892
|
+
...redactionValues(redactedValues, stored),
|
|
893
|
+
}, MEMORY_WRITE_RESPONSE_RULES);
|
|
894
|
+
}
|
|
895
|
+
const REINDEX_BOOKKEEPING_FIELDS = new Set([
|
|
896
|
+
"embedding", "embeddingModel", "contentHash", "retrievalCount", "lastRetrieved", "usageCount",
|
|
897
|
+
]);
|
|
898
|
+
const REINDEX_PROTECTED_FIELDS = DECLARED_MEMORY_ATTRIBUTES.filter((field) => !REINDEX_BOOKKEEPING_FIELDS.has(field));
|
|
899
|
+
function reindexDrift(content, existing) {
|
|
900
|
+
const isSkill = rowIsSkill(existing);
|
|
901
|
+
if (!isSkill && rowIsSkill(content))
|
|
902
|
+
return "tags";
|
|
903
|
+
for (const field of REINDEX_PROTECTED_FIELDS) {
|
|
904
|
+
if (!Object.prototype.hasOwnProperty.call(content, field))
|
|
905
|
+
continue;
|
|
906
|
+
const submitted = content[field];
|
|
907
|
+
const stored = existing[field];
|
|
908
|
+
if (submitted === stored)
|
|
909
|
+
continue;
|
|
910
|
+
if ((field === "metadata" || Array.isArray(submitted)) && JSON.stringify(submitted ?? null) === JSON.stringify(stored ?? null))
|
|
911
|
+
continue;
|
|
912
|
+
return field;
|
|
913
|
+
}
|
|
914
|
+
return null;
|
|
915
|
+
}
|
|
916
|
+
/** The row a `_reindex` re-PUT writes over `existing` (the stored row), or its
|
|
917
|
+
* refusal. Memory.put()'s `_reindex` branch and the MemoryReindex write-back
|
|
918
|
+
* both build their row here (flair#2354). */
|
|
919
|
+
export function buildReindexRow(content, existing) {
|
|
920
|
+
delete content._reindex;
|
|
921
|
+
// A1' item 1: the reindex branch keeps declared and named retained
|
|
922
|
+
// attributes. Pinned by test/unit/memory-host-source.test.ts
|
|
923
|
+
// (r20-put-reindex) — RED if this call is removed.
|
|
924
|
+
stripUndeclaredMemoryAttributes(content);
|
|
925
|
+
// A1-iv items 1/3: strip a client-supplied server-stamped field, then
|
|
926
|
+
// PRESERVE the existing row's incarnation token (reindex is a re-PUT of
|
|
927
|
+
// an existing row, never a reincarnation).
|
|
928
|
+
const reindexBody = { ...content };
|
|
929
|
+
stripServerStampedFields(content);
|
|
930
|
+
// A reindex is a re-PUT of an EXISTING row, so an absent stored row is
|
|
931
|
+
// refused — it is never re-created/re-stamped.
|
|
932
|
+
if (!existing) {
|
|
933
|
+
return { status: 404, error: "reindex_row_not_found", message: "the _reindex re-PUT requires an existing stored row" };
|
|
934
|
+
}
|
|
935
|
+
const effective = { ...existing, ...content };
|
|
936
|
+
if (rowIsSkill(effective) && skillMetadataHasDuplicateKey(effective.metadata)) {
|
|
937
|
+
return { status: 400, error: "skill_metadata_duplicate_key", message: "skill metadata requires distinct top-level keys" };
|
|
938
|
+
}
|
|
939
|
+
const drift = reindexDrift(reindexBody, existing);
|
|
940
|
+
if (drift) {
|
|
941
|
+
return { status: 409, error: "reindex_would_change_row", message: `the _reindex re-PUT may not change '${drift}'` };
|
|
942
|
+
}
|
|
943
|
+
stampInstanceToken(content, existing);
|
|
944
|
+
for (const field of REINDEX_PROTECTED_FIELDS) {
|
|
945
|
+
if (!Object.prototype.hasOwnProperty.call(content, field) && existing[field] !== undefined) {
|
|
946
|
+
content[field] = existing[field];
|
|
947
|
+
}
|
|
948
|
+
}
|
|
949
|
+
// Keep the EXISTING row's STORED provenance byte-for-byte. The rest of
|
|
950
|
+
// the row is filtered above and may gain an absent incarnation token.
|
|
951
|
+
// The body's provenance was stripped above so it cannot be forged;
|
|
952
|
+
// restoring it from `existing` (never from the submitted value)
|
|
953
|
+
// keeps provenance byte-identical across a corpus-wide reindex.
|
|
954
|
+
// Pinned by test/unit/memory-host-source.test.ts (r20-put-reindex) — RED
|
|
955
|
+
// if this restore is removed.
|
|
956
|
+
if (typeof existing.provenance === "string") {
|
|
957
|
+
content.provenance = existing.provenance;
|
|
519
958
|
}
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
959
|
+
// flair#1965: a reindex is a re-PUT of an EXISTING row (an UPDATE), so the
|
|
960
|
+
// row's stored originatorInstanceId stands; a body value is dropped, and a
|
|
961
|
+
// legacy row with no value is left un-stamped. See
|
|
962
|
+
// resources/originator-instance.ts.
|
|
963
|
+
keepStoredOriginator(content, existing);
|
|
964
|
+
// The receiver-side federation bookkeeping likewise stands as stored.
|
|
965
|
+
applyFederationBookkeeping(content, existing);
|
|
966
|
+
// Preserve stored visibility on updates before applying write policy:
|
|
967
|
+
// a reindex payload that omits it keeps the record's stored value.
|
|
968
|
+
if (content.visibility === undefined || content.visibility === null) {
|
|
969
|
+
if (existing.visibility === PRIVATE_VISIBILITY || existing.visibility === SHARED_VISIBILITY) {
|
|
970
|
+
content.visibility = existing.visibility;
|
|
971
|
+
}
|
|
523
972
|
}
|
|
524
|
-
|
|
973
|
+
normalizeEmptyEmbedding(content);
|
|
974
|
+
return { row: content };
|
|
975
|
+
}
|
|
976
|
+
/** Aborts the close's owned transaction: the row changed after the transaction read it. */
|
|
977
|
+
class CloseTargetChanged extends Error {
|
|
525
978
|
}
|
|
979
|
+
/** Attempts of the close before it gives up on a row that keeps changing. */
|
|
980
|
+
const SUPERSEDE_CLOSE_ATTEMPTS = 3;
|
|
526
981
|
/**
|
|
527
|
-
* Read-modify-write close
|
|
528
|
-
*
|
|
529
|
-
*
|
|
530
|
-
*
|
|
531
|
-
*
|
|
532
|
-
*
|
|
982
|
+
* Read-modify-write close for ordinary Memory writes. Does NOT swallow failures —
|
|
983
|
+
* throws so the caller can log it. Never called before the new record is
|
|
984
|
+
* already written.
|
|
985
|
+
*
|
|
986
|
+
* flair#2307: the read and write run in ONE owned
|
|
987
|
+
* transaction (withOwnedTransaction, the MemoryMaintenance pattern: the
|
|
988
|
+
* request's transaction is detached and a fresh one this call owns is created),
|
|
989
|
+
* and the write is built from the row read inside it. `expectedOwner`, when
|
|
990
|
+
* supplied by a non-admin agent's close plan, is the owner the authorization
|
|
991
|
+
* read saw; a differing owner at the transaction read throws instead of closing.
|
|
992
|
+
* Admin and internal close plans have no expected owner.
|
|
993
|
+
*
|
|
994
|
+
* Harper 5.2.8 has no compare-and-set on a table write: a transaction does not
|
|
995
|
+
* fail when a row it read is changed by another write before it commits;
|
|
996
|
+
* Harper applies both writes, ordered by transaction timestamp. So once the
|
|
997
|
+
* write is staged, and before the transaction commits, the close re-reads the
|
|
998
|
+
* committed row outside the transaction (an empty context: Harper's latest
|
|
999
|
+
* committed state, not this transaction's snapshot or its staged write). If
|
|
1000
|
+
* that row is no longer the one read inside the transaction, the transaction
|
|
1001
|
+
* is aborted (the staged write is discarded) and the close starts over from
|
|
1002
|
+
* the committed row: SUPERSEDE_CLOSE_ATTEMPTS (three) attempts in all, so at
|
|
1003
|
+
* most two retries. A change committed after that re-read and before the commit is not
|
|
1004
|
+
* seen by it; Harper orders the two writes by timestamp.
|
|
1005
|
+
*
|
|
1006
|
+
* A close a "write" grant authorizes does not run here: it is staged in the
|
|
1007
|
+
* successor's own transaction (stageGrantedClose).
|
|
533
1008
|
*/
|
|
534
|
-
async function closeSupersededRecord(ctx, oldId, patch) {
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
1009
|
+
async function closeSupersededRecord(ctx, oldId, patch, expectedOwner) {
|
|
1010
|
+
for (let attempt = 1;; attempt++) {
|
|
1011
|
+
let closedRow;
|
|
1012
|
+
try {
|
|
1013
|
+
closedRow = await withOwnedTransaction(ctx, async (c) => {
|
|
1014
|
+
const existing = await databases.flair.Memory.get(oldId, c);
|
|
1015
|
+
if (!existing) {
|
|
1016
|
+
throw new Error(`supersede-close: record ${oldId} not found`);
|
|
1017
|
+
}
|
|
1018
|
+
if (expectedOwner !== undefined && existing.agentId !== expectedOwner) {
|
|
1019
|
+
throw new Error(`supersede-close: record ${oldId} is no longer owned by the authorized owner`);
|
|
1020
|
+
}
|
|
1021
|
+
// Test-only: inert unless the fault-injection env opt-in is set and armed.
|
|
1022
|
+
const pause = txnPausePoint("supersede-close");
|
|
1023
|
+
if (pause)
|
|
1024
|
+
await pause;
|
|
1025
|
+
const closed = { ...existing, ...patch };
|
|
1026
|
+
stripUndeclaredMemoryAttributes(closed);
|
|
1027
|
+
normalizeEmptyEmbedding(closed);
|
|
1028
|
+
await databases.flair.Memory.put(closed, c);
|
|
1029
|
+
// Test-only: inert unless armed — here the write is staged, so a
|
|
1030
|
+
// competing write and the committed-state re-reads below can be exercised
|
|
1031
|
+
// in either order.
|
|
1032
|
+
const stagedPause = txnPausePoint("supersede-close-staged");
|
|
1033
|
+
if (stagedPause)
|
|
1034
|
+
await stagedPause;
|
|
1035
|
+
const committed = await databases.flair.Memory.get(oldId, {});
|
|
1036
|
+
if (!isDeepStrictEqual(committed, existing))
|
|
1037
|
+
throw new CloseTargetChanged();
|
|
1038
|
+
return closed;
|
|
1039
|
+
});
|
|
1040
|
+
}
|
|
1041
|
+
catch (err) {
|
|
1042
|
+
if (!(err instanceof CloseTargetChanged))
|
|
1043
|
+
throw err;
|
|
1044
|
+
if (attempt < SUPERSEDE_CLOSE_ATTEMPTS)
|
|
1045
|
+
continue;
|
|
1046
|
+
throw new Error(`supersede-close: record ${oldId} changed during each of ${SUPERSEDE_CLOSE_ATTEMPTS} attempts; not closed`);
|
|
1047
|
+
}
|
|
1048
|
+
// flair#1357 — a supersede-close sets `validTo`, which the retrieval filters
|
|
1049
|
+
// read, so the lexical index has to see it as eagerly as a content write.
|
|
1050
|
+
noteMemoryUpsert(closedRow);
|
|
1051
|
+
return;
|
|
1052
|
+
}
|
|
1053
|
+
}
|
|
1054
|
+
/**
|
|
1055
|
+
* Stamp `lastReflected` on each existing `derivedFrom` source of a new row
|
|
1056
|
+
* (best-effort bookkeeping; a failure is swallowed). Called only after the new
|
|
1057
|
+
* row was written (flair#2307): a refused write changes no source row.
|
|
1058
|
+
* lastReflected keys off updatedAt (the write moment), NOT createdAt — since
|
|
1059
|
+
* #1336 a create may carry a backdated caller createdAt, and the reflection
|
|
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.
|
|
1069
|
+
*/
|
|
1070
|
+
async function markDerivedSourcesReflected(content) {
|
|
1071
|
+
if (!Array.isArray(content.derivedFrom) || content.derivedFrom.length === 0)
|
|
1072
|
+
return;
|
|
1073
|
+
const now = content.updatedAt;
|
|
1074
|
+
const table = databases.flair.Memory;
|
|
1075
|
+
for (const sourceId of content.derivedFrom) {
|
|
1076
|
+
try {
|
|
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);
|
|
1110
|
+
}
|
|
1111
|
+
}
|
|
1112
|
+
catch { }
|
|
538
1113
|
}
|
|
539
|
-
const closed = { ...existing, ...patch };
|
|
540
|
-
stripUndeclaredMemoryAttributes(closed);
|
|
541
|
-
await withDetachedTxn(ctx, () => databases.flair.Memory.put(closed));
|
|
542
|
-
// flair#1357 — a supersede-close sets `validTo`, which the retrieval filters
|
|
543
|
-
// read, so the lexical index has to see it as eagerly as a content write.
|
|
544
|
-
noteMemoryUpsert(closed);
|
|
545
1114
|
}
|
|
546
1115
|
/** Does an agent hold a "write" grant from `ownerId`? Same MemoryGrant lookup
|
|
547
1116
|
* the read paths used before the open-within-org reframe (reads no longer
|
|
548
1117
|
* consult MemoryGrant); it survives here for the "write" scope that gates
|
|
549
1118
|
* cross-agent supersede. */
|
|
550
|
-
async function hasWriteGrant(granteeId, ownerId) {
|
|
551
|
-
|
|
552
|
-
for await (const grant of databases.flair.MemoryGrant.search({
|
|
553
|
-
conditions: [
|
|
554
|
-
{ attribute: "granteeId", comparator: "equals", value: granteeId },
|
|
555
|
-
{ attribute: "ownerId", comparator: "equals", value: ownerId },
|
|
556
|
-
],
|
|
557
|
-
})) {
|
|
558
|
-
if (grant.scope === "write")
|
|
559
|
-
return true;
|
|
560
|
-
}
|
|
561
|
-
}
|
|
562
|
-
catch {
|
|
563
|
-
/* MemoryGrant table not yet populated — no grant */
|
|
564
|
-
}
|
|
565
|
-
return false;
|
|
1119
|
+
async function hasWriteGrant(granteeId, ownerId, ctx) {
|
|
1120
|
+
return writeGrantHeld(databases.flair.MemoryGrant, granteeId, ownerId, ctx);
|
|
566
1121
|
}
|
|
567
1122
|
/**
|
|
568
|
-
* Shared by post() AND put():
|
|
569
|
-
*
|
|
570
|
-
*
|
|
571
|
-
*
|
|
572
|
-
*
|
|
573
|
-
* flair-client's write()/update() — used by flair-mcp, the CLI, and every
|
|
574
|
-
* other integration package — issue HTTP PUT, `supersedes` must be fully
|
|
575
|
-
* handled (validated, authorized, and closed) from BOTH entry points for the
|
|
576
|
-
* 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.
|
|
577
1128
|
*
|
|
578
1129
|
* Validates the `supersedes` field's shape and, for a cross-agent supersede,
|
|
579
1130
|
* requires a "write" MemoryGrant from the target's owner (reuses the existing
|
|
580
|
-
* agent-auth/grant machinery — no parallel auth logic). Returns a
|
|
581
|
-
* short-circuit with
|
|
1131
|
+
* agent-auth/grant machinery — no parallel auth logic). Returns `denial` (a
|
|
1132
|
+
* Response to short-circuit with) or the `close` the write is authorized to
|
|
1133
|
+
* perform once the new record is written (null: close nothing).
|
|
1134
|
+
*
|
|
1135
|
+
* flair#2307: `content.supersedes` is already the canonical id
|
|
1136
|
+
* (canonicalizeSupersedes), so the reserved-id check, the authorization read,
|
|
1137
|
+
* the stored reference and the close all name the same row. For a non-admin
|
|
1138
|
+
* agent, a failed target read refuses (supersedesTargetUnreadable) and a
|
|
1139
|
+
* missing target refuses (supersedesTargetMissing) — except a reference that is
|
|
1140
|
+
* unchanged from the stored row's own `supersedes` (a re-PUT of a successor
|
|
1141
|
+
* whose predecessor was since deleted), which is kept and closes nothing.
|
|
1142
|
+
* For a non-admin agent's ordinary Memory write, the close carries the owner the read saw;
|
|
1143
|
+
* a change visible at the close's committed re-read stops it from landing over
|
|
1144
|
+
* that change: closeSupersededRecord (the owner's own close) retries from the
|
|
1145
|
+
* committed row, and stageGrantedClose (a grant-authorized one) refuses the
|
|
1146
|
+
* whole write.
|
|
1147
|
+
* Later changes follow Harper's timestamp order (see the PR residual-gap note).
|
|
1148
|
+
* An admin or internal write has no authorization read or owner comparison.
|
|
1149
|
+
*
|
|
1150
|
+
* A write grant does not include changing a record's visibility; visibility is
|
|
1151
|
+
* set by the owner or an admin. For the grant-authorized supersede write,
|
|
1152
|
+
* `requestedVisibility` (the visibility the caller's body named, read before
|
|
1153
|
+
* any merge, carry or default) must read the same as the target's as this
|
|
1154
|
+
* authorization read sees it, and the successor is given that visibility. The
|
|
1155
|
+
* close, staged in the successor's transaction, then compares it with the
|
|
1156
|
+
* target's visibility at its final committed-state re-read (stageGrantedClose;
|
|
1157
|
+
* the skill-version writer for a skill); a mismatch writes nothing, and a
|
|
1158
|
+
* change committed after that re-read is not seen by it. The rule governs this
|
|
1159
|
+
* write: an ordinary successor
|
|
1160
|
+
* is the grantee's own row, so the grantee may later change that row's
|
|
1161
|
+
* visibility as its owner, and a skill successor keeps its lineage owner
|
|
1162
|
+
* (resources/grant-visibility.ts).
|
|
582
1163
|
*
|
|
583
1164
|
* flair#704: an explicit `supersedes: null` — the shape most JSON writers
|
|
584
1165
|
* produce for an unset optional field (`JSON.stringify({supersedes: undefined})`
|
|
@@ -595,40 +1176,92 @@ async function hasWriteGrant(granteeId, ownerId) {
|
|
|
595
1176
|
* closeSupersededIfNeeded) already treats it as unset with no further
|
|
596
1177
|
* changes needed.
|
|
597
1178
|
*/
|
|
598
|
-
async function validateAndAuthorizeSupersedes(content, auth) {
|
|
1179
|
+
async function validateAndAuthorizeSupersedes(content, auth, ctx, stored, requestedVisibility) {
|
|
1180
|
+
const refuse = (denial) => ({ denial, close: null });
|
|
599
1181
|
if (content.supersedes === null) {
|
|
600
1182
|
delete content.supersedes;
|
|
601
1183
|
}
|
|
602
1184
|
if (content.supersedes !== undefined && typeof content.supersedes !== "string") {
|
|
603
|
-
return new Response(JSON.stringify({ error: "supersedes must be a string (memory ID)" }), {
|
|
1185
|
+
return refuse(new Response(JSON.stringify({ error: "supersedes must be a string (memory ID)" }), {
|
|
604
1186
|
status: 400, headers: { "Content-Type": "application/json" },
|
|
605
|
-
});
|
|
1187
|
+
}));
|
|
606
1188
|
}
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
1189
|
+
// flair#2141 S2: superseding closes the target row, so a reserved seed id
|
|
1190
|
+
// needs operator authority here too (resources/seed-reservation.ts).
|
|
1191
|
+
const seedDenial = reservedSeedWriteDenial("Memory", [content.supersedes], ctx, auth);
|
|
1192
|
+
if (seedDenial)
|
|
1193
|
+
return refuse(seedDenial);
|
|
1194
|
+
if (!content.supersedes)
|
|
1195
|
+
return { denial: null, close: null };
|
|
1196
|
+
if (auth.kind !== "agent" || auth.isAdmin)
|
|
1197
|
+
return { denial: null, close: { id: content.supersedes } };
|
|
1198
|
+
let target;
|
|
1199
|
+
try {
|
|
1200
|
+
target = await databases.flair.Memory.get(content.supersedes);
|
|
1201
|
+
}
|
|
1202
|
+
catch (err) {
|
|
1203
|
+
return refuse(supersedesTargetUnreadable(err));
|
|
1204
|
+
}
|
|
1205
|
+
if (!target) {
|
|
1206
|
+
if (stored?.supersedes === content.supersedes)
|
|
1207
|
+
return { denial: null, close: null };
|
|
1208
|
+
return refuse(supersedesTargetMissing());
|
|
1209
|
+
}
|
|
1210
|
+
if (target.agentId !== auth.agentId) {
|
|
1211
|
+
if (!(await hasWriteGrant(auth.agentId, target.agentId))) {
|
|
1212
|
+
return refuse(FORBIDDEN("forbidden: cannot supersede a memory owned by another agent without a write grant"));
|
|
613
1213
|
}
|
|
1214
|
+
// A write grant does not include changing a record's visibility; visibility
|
|
1215
|
+
// is set by the owner or an admin. This grant-authorized write gives the
|
|
1216
|
+
// successor the predecessor's visibility as read here, and the ephemeral
|
|
1217
|
+
// private-only rule (flair#1257) is applied to that value. The close
|
|
1218
|
+
// compares it with the predecessor's visibility at its final
|
|
1219
|
+
// committed-state re-read (stageGrantedClose, resources/grant-visibility.ts).
|
|
1220
|
+
const visibilityDenial = applyGrantedVisibility(content, target, requestedVisibility);
|
|
1221
|
+
if (visibilityDenial)
|
|
1222
|
+
return refuse(visibilityDenial);
|
|
1223
|
+
const tierError = assertVisibilityAllowedForDurability(content.durability ?? stored?.durability, content.visibility);
|
|
1224
|
+
if (tierError) {
|
|
1225
|
+
return refuse(new Response(JSON.stringify({ error: "invalid_visibility_for_durability", message: tierError }), { status: 400, headers: { "content-type": "application/json" } }));
|
|
1226
|
+
}
|
|
1227
|
+
// flair#2333 (H10): the close re-checks this grant against committed state
|
|
1228
|
+
// before it lands, so the grantee id travels with the close plan.
|
|
1229
|
+
return { denial: null, close: { id: content.supersedes, ownerId: target.agentId, granteeId: auth.agentId } };
|
|
614
1230
|
}
|
|
615
|
-
return null;
|
|
1231
|
+
return { denial: null, close: { id: content.supersedes, ownerId: target.agentId } };
|
|
1232
|
+
}
|
|
1233
|
+
/**
|
|
1234
|
+
* flair#2307: resolve a write's `supersedes` reference to its canonical id ONCE
|
|
1235
|
+
* (resolveMemoryReferenceId), before anything reads it, and store that id back
|
|
1236
|
+
* on the body. Every later use — the skill body's predecessor read, the
|
|
1237
|
+
* reserved-id check, the authorization read, the stored reference and the
|
|
1238
|
+
* close — then names the same row. A non-string is left for the shape check.
|
|
1239
|
+
*/
|
|
1240
|
+
function canonicalizeSupersedes(content) {
|
|
1241
|
+
if (content && typeof content === "object" && typeof content.supersedes === "string") {
|
|
1242
|
+
content.supersedes = resolveMemoryReferenceId(content.supersedes);
|
|
1243
|
+
}
|
|
1244
|
+
}
|
|
1245
|
+
/** The patch a supersede's close applies to its predecessor. */
|
|
1246
|
+
function supersedeClosePatch(content) {
|
|
1247
|
+
return {
|
|
1248
|
+
validTo: content.validFrom ?? content.createdAt,
|
|
1249
|
+
updatedAt: content.createdAt ?? content.updatedAt,
|
|
1250
|
+
};
|
|
616
1251
|
}
|
|
617
1252
|
/**
|
|
618
1253
|
* Close the superseded record — called AFTER the new record has already been
|
|
619
1254
|
* written (write-new-BEFORE-close-old). Safe failure state is
|
|
620
1255
|
* two active records (recoverable), never a tombstoned-old-with-lost-new.
|
|
621
|
-
* Failure is logged (observable), never silently swallowed. No-op
|
|
622
|
-
*
|
|
1256
|
+
* Failure is logged (observable), never silently swallowed. No-op when
|
|
1257
|
+
* validateAndAuthorizeSupersedes authorized no close. A grant-authorized close
|
|
1258
|
+
* (`close.granteeId`) does not run here (closeGrantedSupersedeStaged).
|
|
623
1259
|
*/
|
|
624
|
-
async function closeSupersededIfNeeded(ctx, content, methodLabel) {
|
|
625
|
-
if (!
|
|
1260
|
+
async function closeSupersededIfNeeded(ctx, content, close, methodLabel) {
|
|
1261
|
+
if (!close)
|
|
626
1262
|
return;
|
|
627
1263
|
try {
|
|
628
|
-
await closeSupersededRecord(ctx,
|
|
629
|
-
validTo: content.validFrom ?? content.createdAt,
|
|
630
|
-
updatedAt: content.createdAt ?? content.updatedAt,
|
|
631
|
-
});
|
|
1264
|
+
await closeSupersededRecord(ctx, close.id, supersedeClosePatch(content), close.ownerId);
|
|
632
1265
|
}
|
|
633
1266
|
catch (err) {
|
|
634
1267
|
// Constant format string + structured data: memory ids are agent-controlled,
|
|
@@ -636,9 +1269,100 @@ async function closeSupersededIfNeeded(ctx, content, methodLabel) {
|
|
|
636
1269
|
// `err` arg) would let an id containing %s/%o consume/hide the real error
|
|
637
1270
|
// (semgrep unsafe-formatstring). Keep all dynamic values in the data object.
|
|
638
1271
|
console.error("Memory.closeSuperseded: failed to close superseded record after writing new record " +
|
|
639
|
-
"(observable, not silent; new record is safely written, old record remains active until retried)", { method: methodLabel, supersededId:
|
|
1272
|
+
"(observable, not silent; new record is safely written, old record remains active until retried)", { method: methodLabel, supersededId: close.id, newRecordId: content.id, err });
|
|
1273
|
+
}
|
|
1274
|
+
}
|
|
1275
|
+
/** A grant-authorized close found its predecessor gone, owned by another
|
|
1276
|
+
* agent, or changed since the write's transaction read it (stageGrantedClose). */
|
|
1277
|
+
class GrantedCloseTargetChanged extends Error {
|
|
1278
|
+
}
|
|
1279
|
+
class GrantedCloseStorageRefused extends Error {
|
|
1280
|
+
}
|
|
1281
|
+
/**
|
|
1282
|
+
* flair#2564: stage a grant-authorized supersede's close (`close.granteeId`)
|
|
1283
|
+
* in `shared`, the successor's transaction (request, caller or write-owned).
|
|
1284
|
+
*
|
|
1285
|
+
* A storage Response aborts the write with write_response_withheld. After
|
|
1286
|
+
* staging the close, the committed row (an empty context) is checked:
|
|
1287
|
+
*
|
|
1288
|
+
* - the committed visibility must read the same as the successor's
|
|
1289
|
+
* (`successorVisibility`): a write grant does not include changing a
|
|
1290
|
+
* record's visibility (grant-visibility.ts). A mismatch throws
|
|
1291
|
+
* PredecessorVisibilityChanged;
|
|
1292
|
+
* - the committed row must still be the one read: a staged write carries its
|
|
1293
|
+
* transaction's timestamp, and Harper orders it before any later-committed
|
|
1294
|
+
* change, so a close staged over a changed row is not retried here. It
|
|
1295
|
+
* throws GrantedCloseTargetChanged, as does a predecessor that is gone or
|
|
1296
|
+
* owned by another agent at the read;
|
|
1297
|
+
* - flair#2333 (H10): the grant is re-checked on committed state; a revoked
|
|
1298
|
+
* grant throws GrantedCloseRevoked.
|
|
1299
|
+
*
|
|
1300
|
+
* The caller aborts the transaction on any of these, so nothing is written,
|
|
1301
|
+
* and a retry runs in a new transaction. As with the other committed re-reads,
|
|
1302
|
+
* a change committed after this final re-read and before the transaction
|
|
1303
|
+
* commits is not seen by it; Harper orders the writes by transaction timestamp.
|
|
1304
|
+
*/
|
|
1305
|
+
async function stageGrantedClose(shared, close, patch, successorVisibility) {
|
|
1306
|
+
const existing = await databases.flair.Memory.get(close.id, shared);
|
|
1307
|
+
if (!existing || existing.agentId !== close.ownerId)
|
|
1308
|
+
throw new GrantedCloseTargetChanged();
|
|
1309
|
+
// Test-only: inert unless the fault-injection env opt-in is set and armed.
|
|
1310
|
+
const pause = txnPausePoint("granted-close");
|
|
1311
|
+
if (pause)
|
|
1312
|
+
await pause;
|
|
1313
|
+
const closed = { ...existing, ...patch };
|
|
1314
|
+
stripUndeclaredMemoryAttributes(closed);
|
|
1315
|
+
const result = await databases.flair.Memory.put(closed, shared);
|
|
1316
|
+
if (result instanceof Response)
|
|
1317
|
+
throw new GrantedCloseStorageRefused();
|
|
1318
|
+
// Test-only: inert unless armed — here the close is staged, so a competing
|
|
1319
|
+
// write and the committed-state re-reads below can be exercised in either
|
|
1320
|
+
// order.
|
|
1321
|
+
const stagedPause = txnPausePoint("granted-close-staged");
|
|
1322
|
+
if (stagedPause)
|
|
1323
|
+
await stagedPause;
|
|
1324
|
+
const committed = await databases.flair.Memory.get(close.id, {});
|
|
1325
|
+
if (committedVisibilityDiffers(committed, successorVisibility))
|
|
1326
|
+
throw new PredecessorVisibilityChanged();
|
|
1327
|
+
if (!isDeepStrictEqual(committed, existing))
|
|
1328
|
+
throw new GrantedCloseTargetChanged();
|
|
1329
|
+
if (!(await writeGrantHeld(databases.flair.MemoryGrant, close.granteeId, close.ownerId, {}))) {
|
|
1330
|
+
throw new GrantedCloseRevoked();
|
|
1331
|
+
}
|
|
1332
|
+
return closed;
|
|
1333
|
+
}
|
|
1334
|
+
/**
|
|
1335
|
+
* Run a grant-authorized close (stageGrantedClose) inside the write's
|
|
1336
|
+
* transaction callback, after the successor and its pointer row are staged.
|
|
1337
|
+
* On any failure the whole write aborts: a joined request or caller
|
|
1338
|
+
* transaction is aborted here, and a transaction withSharedWriteTransaction
|
|
1339
|
+
* owns aborts when the error leaves its callback. Returns the staged closed row,
|
|
1340
|
+
* or null for an owner, admin or internal close (closeSupersededIfNeeded).
|
|
1341
|
+
*/
|
|
1342
|
+
async function closeGrantedSupersedeStaged(shared, content, close, joinsRequestTxn) {
|
|
1343
|
+
if (!close || close.granteeId === undefined)
|
|
1344
|
+
return null;
|
|
1345
|
+
try {
|
|
1346
|
+
return await stageGrantedClose(shared, close, supersedeClosePatch(content), content.visibility);
|
|
1347
|
+
}
|
|
1348
|
+
catch (err) {
|
|
1349
|
+
if (joinsRequestTxn)
|
|
1350
|
+
abortRequestTransaction(shared);
|
|
1351
|
+
throw err;
|
|
640
1352
|
}
|
|
641
1353
|
}
|
|
1354
|
+
/** The named refusal for a grant-authorized close that did not land, else null. */
|
|
1355
|
+
function grantedCloseRefusal(err) {
|
|
1356
|
+
if (err instanceof GrantedCloseStorageRefused)
|
|
1357
|
+
return withheldWriteResult();
|
|
1358
|
+
if (err instanceof PredecessorVisibilityChanged)
|
|
1359
|
+
return predecessorVisibilityChangedRefusal();
|
|
1360
|
+
if (err instanceof GrantedCloseRevoked)
|
|
1361
|
+
return grantedCloseRevokedRefusal();
|
|
1362
|
+
if (err instanceof GrantedCloseTargetChanged)
|
|
1363
|
+
return storedRowChangedRefusal("Memory");
|
|
1364
|
+
return null;
|
|
1365
|
+
}
|
|
642
1366
|
/**
|
|
643
1367
|
* ─── Durability-keyed default visibility (Layer 1, part A) ─────────────────
|
|
644
1368
|
*
|
|
@@ -684,85 +1408,789 @@ function defaultVisibilityForDurability(durability) {
|
|
|
684
1408
|
* rationale. `content.originatorInstanceId == null` is no longer read here: a
|
|
685
1409
|
* body value is not trusted at any point.
|
|
686
1410
|
*/
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
1411
|
+
/**
|
|
1412
|
+
* flair#2139 S2 — write a skill create/update atomically through the
|
|
1413
|
+
* transactional writer.
|
|
1414
|
+
*/
|
|
1415
|
+
async function writeSkillCreateOrUpdate(args) {
|
|
1416
|
+
const { ctx, auth, content, storedRow, explicitPredecessor, method, pointer, inPlaceId, reembedding, requestedPayload } = args;
|
|
1417
|
+
const now = new Date().toISOString();
|
|
1418
|
+
const explicitSuccessor = !!explicitPredecessor && (!storedRow || content.supersedes !== storedRow.supersedes);
|
|
1419
|
+
let successorId = inPlaceId
|
|
1420
|
+
? inPlaceId
|
|
1421
|
+
: explicitSuccessor || !storedRow
|
|
1422
|
+
? String(content.id ?? `${content.agentId}-${randomUUID()}`)
|
|
1423
|
+
: `${content.agentId}-${randomUUID()}`;
|
|
1424
|
+
const subjectId = deriveSkillSubjectId({ newPhysicalId: successorId, storedHead: storedRow, predecessor: explicitPredecessor });
|
|
1425
|
+
// flair#2139 S2 — the reservation covers the whole logical lineage: a write
|
|
1426
|
+
// whose subject is the seed's requires the operator source, not only one that
|
|
1427
|
+
// names the seed's physical id.
|
|
1428
|
+
const seedLineageDenial = reservedSeedSubjectDenial("Memory", [subjectId], ctx, auth);
|
|
1429
|
+
if (seedLineageDenial)
|
|
1430
|
+
return seedLineageDenial;
|
|
1431
|
+
const addressedId = storedRow ? String(storedRow.id) : explicitPredecessor ? String(explicitPredecessor.id) : null;
|
|
1432
|
+
const captured = { row: null, closed: null };
|
|
1433
|
+
let unchangedHead = null;
|
|
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({
|
|
1443
|
+
ctx,
|
|
1444
|
+
joinCallerTransaction: method === "post",
|
|
1445
|
+
subjectId,
|
|
1446
|
+
agentId: String(content.agentId),
|
|
1447
|
+
deferConfirmation: true,
|
|
1448
|
+
heldMemoryIds: [...heldIds],
|
|
1449
|
+
head: (shared) => resolveSkillHead(subjectId, addressedId, 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
|
+
}
|
|
1466
|
+
const stale = await validateSkillSnapshots(storedRow, explicitPredecessor, content.id ?? null, shared);
|
|
1467
|
+
const denied = await authorizeSkillOwners(ctx, auth, [storedRow, explicitPredecessor, head ?? content], shared);
|
|
1468
|
+
if (denied)
|
|
1469
|
+
return denied;
|
|
1470
|
+
if (inPlaceId && method === "put" && !reembedding && !explicitPredecessor && !pointer?.row &&
|
|
1471
|
+
head?.id === inPlaceId && requestedPayload && skillPayloadUnchanged(requestedPayload, head)) {
|
|
1472
|
+
unchangedHead = head;
|
|
1473
|
+
return null;
|
|
1474
|
+
}
|
|
1475
|
+
if (stale)
|
|
1476
|
+
return stale;
|
|
1477
|
+
if ((storedRow || explicitPredecessor) && !head)
|
|
1478
|
+
return skillWriteConflict("skill_head_missing");
|
|
1479
|
+
if (explicitSuccessor && head?.id !== explicitPredecessor?.id)
|
|
1480
|
+
return skillWriteConflict("skill_predecessor_stale");
|
|
1481
|
+
if (storedRow && head?.id !== storedRow.id)
|
|
1482
|
+
return skillWriteConflict("skill_target_stale");
|
|
1483
|
+
const reembedInPlace = method === "put" && reembedding && head &&
|
|
1484
|
+
head.id === storedRow?.id && skillPayloadUnchanged(content, head);
|
|
1485
|
+
if (reembedInPlace)
|
|
1486
|
+
successorId = String(head.id);
|
|
1487
|
+
const liveHead = head;
|
|
1488
|
+
const successor = buildSkillSuccessorRow({
|
|
1489
|
+
auth,
|
|
1490
|
+
base: { ...content, agentId: liveHead?.agentId ?? content.agentId }, predecessorRow: liveHead, successorId, subjectId,
|
|
1491
|
+
// An in-place (reserved seed) write keeps the same physical id, so it
|
|
1492
|
+
// sets no `supersedes` and closes no row.
|
|
1493
|
+
supersedes: reembedInPlace ? head.supersedes ?? null : inPlaceId || !liveHead ? null : String(liveHead.id), now,
|
|
1494
|
+
});
|
|
1495
|
+
if (reembedInPlace) {
|
|
1496
|
+
successor.instanceToken = typeof head.instanceToken === "string" && head.instanceToken.length > 0
|
|
1497
|
+
? head.instanceToken : content.instanceToken;
|
|
1498
|
+
}
|
|
1499
|
+
await applyOriginatorInstanceId(successor, liveHead);
|
|
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
|
+
}
|
|
1508
|
+
captured.row = successor;
|
|
1509
|
+
const value = typeof successor.content === "string" ? successor.content : null;
|
|
1510
|
+
const visibility = skillVersionVisibility(successor);
|
|
1511
|
+
if (inPlaceId || reembedInPlace) {
|
|
1512
|
+
return liveHead
|
|
1513
|
+
? { kind: "update", predecessor: null, successor, closePatch: {}, value, visibility, grantedClose: null }
|
|
1514
|
+
: { kind: "create", predecessor: null, successor, closePatch: {}, value, visibility, grantedClose: null };
|
|
1515
|
+
}
|
|
1516
|
+
if (!liveHead)
|
|
1517
|
+
return { kind: "create", predecessor: null, successor, closePatch: {}, value, visibility, grantedClose: null };
|
|
1518
|
+
captured.closed = liveHead;
|
|
1519
|
+
return { kind: "update", predecessor: liveHead, successor, closePatch: { skillSubjectId: subjectId, validTo: now, updatedAt: now }, value, visibility, grantedClose: grantedSkillClose(liveHead, ctx, auth) };
|
|
1520
|
+
},
|
|
1521
|
+
hooks: {
|
|
1522
|
+
...defaultSkillHooks,
|
|
1523
|
+
authorizeClose: (row, shared) => authorizeSkillOwners(ctx, auth, [row], shared),
|
|
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;
|
|
1530
|
+
if (captured.closed) {
|
|
1531
|
+
const denial = await deletePointerRow(String(captured.closed.id), shared);
|
|
1532
|
+
if (denial)
|
|
1533
|
+
return denial;
|
|
1534
|
+
}
|
|
1535
|
+
const pointerDenial = pointer?.row
|
|
1536
|
+
? await persistPointerRow({ ...pointer.row, memoryId: successorId, memoryInstanceToken: captured.row?.instanceToken }, shared)
|
|
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;
|
|
1548
|
+
},
|
|
1549
|
+
},
|
|
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]);
|
|
1595
|
+
if (!outcome.ok)
|
|
1596
|
+
return outcome.response;
|
|
1597
|
+
if (captured.closed)
|
|
1598
|
+
noteMemoryDelete(String(captured.closed.id));
|
|
1599
|
+
if (captured.row) {
|
|
1600
|
+
noteMemoryUpsert(captured.row);
|
|
1601
|
+
// An in-place update replaces the live head without recording it in
|
|
1602
|
+
// `captured.closed`, so no closed row is passed as unknown (undefined),
|
|
1603
|
+
// never as "replaced no row".
|
|
1604
|
+
noteWriteStamp(captured.row.embeddingModel, captured.closed ?? undefined);
|
|
1605
|
+
}
|
|
1606
|
+
if (args.staged)
|
|
1607
|
+
args.staged.text = captured.row ? storedMemoryText(captured.row, args.staged.supplied) : null;
|
|
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));
|
|
1757
|
+
}
|
|
1758
|
+
/** Close the live head and delete its pointer in the version transaction. */
|
|
1759
|
+
async function writeSkillDelete(args) {
|
|
1760
|
+
const { ctx, auth, record, headLock } = args;
|
|
1761
|
+
let closedId = "";
|
|
1762
|
+
let closedRow = null;
|
|
1763
|
+
let pointerBefore = null;
|
|
1764
|
+
const now = new Date().toISOString();
|
|
1765
|
+
const subjectId = String(record.skillSubjectId ?? record.id);
|
|
1766
|
+
const seedLineageDenial = reservedSeedSubjectDenial("Memory", [subjectId], ctx, auth);
|
|
1767
|
+
if (seedLineageDenial)
|
|
1768
|
+
return seedLineageDenial;
|
|
1769
|
+
const outcome = await runSkillVersionWrite({
|
|
1770
|
+
ctx,
|
|
1771
|
+
subjectId,
|
|
1772
|
+
agentId: String(record.agentId),
|
|
1773
|
+
heldMemoryIds: headLock?.ids,
|
|
1774
|
+
head: (shared) => resolveSkillHead(subjectId, String(record.id), shared),
|
|
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
|
+
}
|
|
1784
|
+
// flair#2355: for a non-admin caller, re-read the COMMITTED rows before
|
|
1785
|
+
// the close. The delete is refused, and nothing is closed, when the
|
|
1786
|
+
// addressed row is present with an owner other than the caller (409
|
|
1787
|
+
// `owner_changed`), when the head this delete closes (a stale id resolves
|
|
1788
|
+
// a different row as the head) is absent (409 `skill_head_missing`), or
|
|
1789
|
+
// when the head's owner differs from the owner this transaction read and
|
|
1790
|
+
// authorizeSkillOwners checks below (409 `owner_changed`).
|
|
1791
|
+
if (auth.kind === "agent" && !auth.isAdmin) {
|
|
1792
|
+
const pause = txnPausePoint("memory-skill-delete");
|
|
1793
|
+
if (pause)
|
|
1794
|
+
await pause;
|
|
1795
|
+
const confirmed = await databases.flair.Memory.get(String(record.id), {});
|
|
1796
|
+
if (confirmed && isForbiddenOwnerMutation(confirmed, RECORD_TYPES.Memory.ownerField, auth.agentId)) {
|
|
1797
|
+
return ownerChangedRefusal("Memory");
|
|
1798
|
+
}
|
|
1799
|
+
if (head) {
|
|
1800
|
+
const confirmedHead = await databases.flair.Memory.get(String(head.id), {});
|
|
1801
|
+
if (!confirmedHead)
|
|
1802
|
+
return skillWriteConflict("skill_head_missing");
|
|
1803
|
+
if (confirmedHead[RECORD_TYPES.Memory.ownerField] !== head[RECORD_TYPES.Memory.ownerField]) {
|
|
1804
|
+
return ownerChangedRefusal("Memory");
|
|
1805
|
+
}
|
|
1806
|
+
}
|
|
1807
|
+
}
|
|
1808
|
+
const stale = await validateSkillSnapshots(record, null, String(record.id), shared);
|
|
1809
|
+
if (stale)
|
|
1810
|
+
return stale;
|
|
1811
|
+
const denied = await authorizeSkillOwners(ctx, auth, [record, head], shared);
|
|
1812
|
+
if (denied)
|
|
1813
|
+
return denied;
|
|
1814
|
+
if (!head)
|
|
1815
|
+
return skillWriteConflict("skill_head_missing");
|
|
1816
|
+
if (memoryWriteOutcomeUnknown(String(head.id)))
|
|
1817
|
+
return writeOutcomeUnknownResponse();
|
|
1818
|
+
const liveHead = head;
|
|
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);
|
|
1824
|
+
// flair#2511: a stale id resolves the live head, which can be another
|
|
1825
|
+
// agent's row a "write" grant authorizes this caller to close; the writer
|
|
1826
|
+
// re-checks that grant after the close is staged.
|
|
1827
|
+
return { kind: "delete", predecessor: liveHead, closePatch: { skillSubjectId: subjectId, validTo: now, updatedAt: now }, value: null, visibility: skillVersionVisibility(liveHead), grantedClose: grantedSkillClose(liveHead, ctx, auth) };
|
|
1828
|
+
},
|
|
1829
|
+
hooks: { ...defaultSkillHooks, authorizeClose: (row, shared) => authorizeSkillOwners(ctx, auth, [row], shared), pointer: async (shared) => deletePointerRow(closedId, shared) },
|
|
1830
|
+
});
|
|
1831
|
+
if (!outcome.ok)
|
|
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;
|
|
1841
|
+
noteMemoryDelete(closedId);
|
|
1842
|
+
return new Response(JSON.stringify({ id: closedId, deleted: true }), {
|
|
1843
|
+
status: 200, headers: { "Content-Type": "application/json" },
|
|
1844
|
+
});
|
|
1845
|
+
}
|
|
1846
|
+
/** flair#2296: a PATCH body that sets both embedding fields to null and nothing else (an `id` aside). */
|
|
1847
|
+
function isReembedPatch(content) {
|
|
1848
|
+
if (!content || typeof content !== "object" || Array.isArray(content))
|
|
1849
|
+
return false;
|
|
1850
|
+
if (content.embedding !== null || content.embeddingModel !== null)
|
|
1851
|
+
return false;
|
|
1852
|
+
return Object.keys(content).every((key) => key === "id" || key === "embedding" || key === "embeddingModel");
|
|
1853
|
+
}
|
|
1854
|
+
/** A vector the re-embed may stamp: a non-empty array of finite numbers. */
|
|
1855
|
+
function isUsableEmbeddingVector(value) {
|
|
1856
|
+
return Array.isArray(value) && value.length > 0 &&
|
|
1857
|
+
value.every((n) => typeof n === "number" && Number.isFinite(n));
|
|
1858
|
+
}
|
|
1859
|
+
/** Attempts of a re-embed before it gives up on a row whose text keeps changing. */
|
|
1860
|
+
const REEMBED_WRITE_ATTEMPTS = 3;
|
|
1861
|
+
/** A row's incarnation token, or null when it carries none (a legacy row). */
|
|
1862
|
+
function storedInstanceToken(row) {
|
|
1863
|
+
return row && typeof row.instanceToken === "string" && row.instanceToken.length > 0 ? row.instanceToken : null;
|
|
1864
|
+
}
|
|
1865
|
+
/**
|
|
1866
|
+
* flair#2390: write the re-embed of Memory row `id`.
|
|
1867
|
+
*
|
|
1868
|
+
* `preRead` is the row as the caller first read it and `vector` the embedding
|
|
1869
|
+
* computed from its text, outside this call. This re-reads the committed row
|
|
1870
|
+
* inside the transaction that writes (the static table handle, with the
|
|
1871
|
+
* attempt's owned context), so the write is built from the row as stored at
|
|
1872
|
+
* that read, not from the pre-await read: a field another writer committed
|
|
1873
|
+
* while the vector was computed is kept, and the caller's authorization is
|
|
1874
|
+
* re-checked against the row's CURRENT owner.
|
|
1875
|
+
*
|
|
1876
|
+
* If the stored text is no longer the text the vector was computed from, this
|
|
1877
|
+
* recomputes from the stored text (at most REEMBED_WRITE_ATTEMPTS times).
|
|
1878
|
+
* If the text keeps changing across the REEMBED_WRITE_ATTEMPTS attempts, it returns
|
|
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
|
|
1881
|
+
* own re-read, a row with no text, or a caller no longer authorized for the row
|
|
1882
|
+
* is refused the same way the first read refused it.
|
|
1883
|
+
*
|
|
1884
|
+
* flair#2465: the attempt STAGES the field-only incremental update, then
|
|
1885
|
+
* confirms the COMMITTED row (an explicit fresh context) is still the row this
|
|
1886
|
+
* transaction read and re-authorized — the same identity (id, agentId,
|
|
1887
|
+
* instanceToken, contentHash, createdAt) and the same embedding text, compared
|
|
1888
|
+
* as text. A row gone or changed in either at confirmation aborts the owned
|
|
1889
|
+
* transaction (the staged write is discarded) and the caller answers
|
|
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.
|
|
1894
|
+
*
|
|
1895
|
+
* The staged update also records `embeddedContentHash`, the newly computed hash
|
|
1896
|
+
* of the text the vector was computed from (null for an empty owner), so the
|
|
1897
|
+
* stored vector and its hash name the same text (flair#2465).
|
|
1898
|
+
*
|
|
1899
|
+
* flair#2478: a legacy row that carries no incarnation token gets one in the
|
|
1900
|
+
* same update, and a success reports the token of the row written, so the
|
|
1901
|
+
* calling PATCH can confirm after the commit that the row is still that one.
|
|
1902
|
+
* The calling PATCH holds the row's per-id write lock across this write and its
|
|
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.
|
|
1915
|
+
*/
|
|
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) {
|
|
1937
|
+
let textToEmbed = skillEmbedText(preRead);
|
|
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
|
+
};
|
|
1948
|
+
for (let attempt = 1; attempt <= REEMBED_WRITE_ATTEMPTS; attempt++) {
|
|
1949
|
+
let outcome;
|
|
1950
|
+
try {
|
|
1951
|
+
outcome = await withOwnedTransaction(ctx, async (owned) => {
|
|
1952
|
+
const stored = await databases.flair.Memory.get(id, owned);
|
|
1953
|
+
if (!stored)
|
|
1954
|
+
return { kind: "not_found" };
|
|
1955
|
+
if (auth.kind === "agent" && !auth.isAdmin &&
|
|
1956
|
+
isForbiddenOwnerMutation(stored, RECORD_TYPES.Memory.ownerField, auth.agentId)) {
|
|
1957
|
+
return { kind: "forbidden" };
|
|
1958
|
+
}
|
|
1959
|
+
const storedText = skillEmbedText(stored);
|
|
1960
|
+
if (typeof storedText !== "string" || storedText.length === 0)
|
|
1961
|
+
return { kind: "no_text" };
|
|
1962
|
+
if (storedText !== textToEmbed)
|
|
1963
|
+
return { kind: "recompute", text: storedText };
|
|
1964
|
+
const model = getModelId();
|
|
1965
|
+
const updatedAt = new Date().toISOString();
|
|
1966
|
+
const token = storedInstanceToken(stored) ?? newInstanceToken();
|
|
1967
|
+
// flair#2465: an incremental update, NOT a full-row put. Harper orders a
|
|
1968
|
+
// transaction by its first read, so this write can land after an edit the
|
|
1969
|
+
// owner committed while the vector was computed; a full-row put would
|
|
1970
|
+
// carry the row this transaction read and revert that edit.
|
|
1971
|
+
// flair#2465: the update also records the newly computed hash of
|
|
1972
|
+
// `textToEmbed`, the text this vector was computed from (null for an
|
|
1973
|
+
// empty owner).
|
|
1974
|
+
// flair#2478: a legacy row that carries no incarnation token gets one in
|
|
1975
|
+
// this same update; a row that has one keeps it.
|
|
1976
|
+
const legacyToken = storedInstanceToken(stored) ? {} : { instanceToken: token };
|
|
1977
|
+
// flair#2561: a Response from the storage layer is not reported (storageResult).
|
|
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));
|
|
1980
|
+
if (result instanceof Response)
|
|
1981
|
+
return { kind: "withheld", response: result };
|
|
1982
|
+
// Test-only: inert unless the fault-injection env opt-in is set and armed.
|
|
1983
|
+
const stagedPause = txnPausePoint("memory-reembed-staged");
|
|
1984
|
+
if (stagedPause)
|
|
1985
|
+
await stagedPause;
|
|
1986
|
+
// flair#2465: STAGE first, THEN confirm the COMMITTED row (an explicit
|
|
1987
|
+
// fresh context — never contextless, which joins this transaction and
|
|
1988
|
+
// sees its snapshot or its staged write) is still the row this transaction
|
|
1989
|
+
// read and re-authorized: the same identity (id, agentId, instanceToken,
|
|
1990
|
+
// contentHash, createdAt) AND, compared as text, the same embedding text
|
|
1991
|
+
// the vector was computed from (`textToEmbed`). The text check catches an
|
|
1992
|
+
// edit that changed the text but no identity field. A row gone or changed
|
|
1993
|
+
// at confirmation aborts this owned transaction, discarding the staged
|
|
1994
|
+
// write; the caller answers stored_row_changed (409), or write_outcome_unknown
|
|
1995
|
+
// when an earlier attempt committed unconfirmed. Only a text change
|
|
1996
|
+
// is logged. Neither the staged vector, its hash, nor a staged legacy
|
|
1997
|
+
// token is written. Post-commit verification retries surviving
|
|
1998
|
+
// differences in compared fields, identity or text from a fresh read.
|
|
1999
|
+
await confirmCommittedRow(databases.flair.Memory, id, (committed) => {
|
|
2000
|
+
if (!sameStoredRow(committed, stored))
|
|
2001
|
+
return false;
|
|
2002
|
+
if (skillEmbedText(committed) !== textToEmbed) {
|
|
2003
|
+
console.warn(`[reembed] ${id}: the embedding text changed after the vector was computed; the write is discarded`);
|
|
2004
|
+
return false;
|
|
2005
|
+
}
|
|
2006
|
+
return true;
|
|
2007
|
+
});
|
|
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 };
|
|
2018
|
+
});
|
|
2019
|
+
}
|
|
2020
|
+
catch (err) {
|
|
2021
|
+
// The owned transaction was aborted by the throw; this attempt wrote
|
|
2022
|
+
// nothing (an earlier unconfirmed attempt may have; settle answers that).
|
|
2023
|
+
if (err instanceof CommittedRowChanged)
|
|
2024
|
+
return settle(storedRowChangedRefusal("Memory"), "stored_row_changed");
|
|
2025
|
+
throw err;
|
|
2026
|
+
}
|
|
2027
|
+
if (outcome.kind === "withheld")
|
|
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);
|
|
2035
|
+
return { response: NOT_FOUND() };
|
|
2036
|
+
}
|
|
2037
|
+
if (outcome.kind === "forbidden")
|
|
2038
|
+
return settle(FORBIDDEN("forbidden: cannot write memory owned by another agent"), "forbidden");
|
|
2039
|
+
if (outcome.kind === "no_text") {
|
|
2040
|
+
return settle(Response.json({ error: "reembed_no_text", message: "the stored row has no text to embed" }, { status: 422 }), "reembed_no_text");
|
|
2041
|
+
}
|
|
2042
|
+
if (outcome.kind === "recompute") {
|
|
2043
|
+
if (attempt === REEMBED_WRITE_ATTEMPTS) {
|
|
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");
|
|
2045
|
+
}
|
|
2046
|
+
textToEmbed = outcome.text;
|
|
2047
|
+
let recomputed;
|
|
2048
|
+
try {
|
|
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));
|
|
2052
|
+
}
|
|
2053
|
+
catch (err) {
|
|
2054
|
+
if (err instanceof MemoryProviderTimeout)
|
|
2055
|
+
return settle(memoryProviderTimeoutResponse(), "memory_provider_timeout");
|
|
2056
|
+
throw err;
|
|
2057
|
+
}
|
|
2058
|
+
if (!isUsableEmbeddingVector(recomputed)) {
|
|
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");
|
|
2060
|
+
}
|
|
2061
|
+
embedding = recomputed;
|
|
2062
|
+
continue;
|
|
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;
|
|
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
|
+
}
|
|
2099
|
+
// flair#2561: the response names the row and its new updatedAt, and
|
|
2100
|
+
// carries no embedding field; `flair reembed` reads the model stamp from
|
|
2101
|
+
// the stored row.
|
|
2102
|
+
const body = buildFromAllowlist({ id, updatedAt: outcome.updatedAt }, REEMBED_RESPONSE_RULES);
|
|
2103
|
+
return { response: body instanceof Response ? body : Response.json(body), token: outcome.token };
|
|
2104
|
+
}
|
|
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");
|
|
2106
|
+
}
|
|
2107
|
+
export class Memory extends databases.flair.Memory {
|
|
2108
|
+
/**
|
|
2109
|
+
* Self-authorize now that the global gate is non-rejecting. Closes the P0
|
|
2110
|
+
* leak: Harper routes `GET /Memory/<id>` to get() and the collection
|
|
2111
|
+
* describe (`GET /Memory`) to a path outside search() — neither was gated
|
|
2112
|
+
* before this fix, so an anonymous caller got a 200 with full record
|
|
2113
|
+
* content / schema even though search() (and the write paths) correctly
|
|
2114
|
+
* 401/403'd. Per-record read scoping happens in get() below (its own records
|
|
2115
|
+
* at any visibility plus every other agent's non-private records — grants are
|
|
2116
|
+
* not consulted on reads; resolveReadScope()); the collection scope is still
|
|
2117
|
+
* in search().
|
|
2118
|
+
*
|
|
2119
|
+
* allowCreate/allowUpdate/allowDelete are deliberately NOT added here:
|
|
2120
|
+
* post()/put()/delete() already self-enforce per-agent ownership inline
|
|
2121
|
+
* (resolveAgentAuth + explicit agentId checks in post()/put(), and the
|
|
2122
|
+
* stored-owner check in delete()). Adding allow* on top of that,
|
|
2123
|
+
* unverified, risks regressing owner writes/deletes on a P0 security fix
|
|
2124
|
+
* that is scoped to the read leak — left as-is on purpose.
|
|
2125
|
+
*/
|
|
2126
|
+
allowRead() { return memoryAuthGate.call(this); }
|
|
2127
|
+
/**
|
|
2128
|
+
* Override get() to apply Memory's open-within-org scope to by-id reads,
|
|
2129
|
+
* as search() does for collection reads. For a verified non-admin agent,
|
|
2130
|
+
* a missing record and one outside its read scope both return 404; this
|
|
2131
|
+
* does not disclose whether another agent's private record exists.
|
|
2132
|
+
* Anonymous HTTP requests are denied by allowRead(), while administrator
|
|
2133
|
+
* and trusted internal reads are unfiltered. Wired through
|
|
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.
|
|
2137
|
+
*/
|
|
2138
|
+
async get(target, opts) {
|
|
2139
|
+
// Collection / query reads — the `GET /Memory/?<query>` form and the bare
|
|
2140
|
+
// collection — arrive as a RequestTarget with `isCollection === true`, and
|
|
2141
|
+
// are governed by search() (same open-within-org read scope; grants are not
|
|
2142
|
+
// consulted on reads). Only a genuine by-id
|
|
2143
|
+
// get is ownership-checked below. Without this guard, get() would receive
|
|
2144
|
+
// the query's RequestTarget, super.get() would return the (truthy) result
|
|
2145
|
+
// set, the single-record check would find no `.agentId` on it, and a valid
|
|
2146
|
+
// authenticated self-query would 404 (regression caught by the auth-
|
|
2147
|
+
// middleware e2e "TPS-Ed25519 on GET /Memory/?agentId=X → 200"). A by-id
|
|
2148
|
+
// get (RequestTarget with isCollection false, or a bare id) falls through.
|
|
2149
|
+
// makeByIdReadGate re-applies this same guard internally (delegating to
|
|
2150
|
+
// this.search via `.call(this, ...)`) — kept here too as documentation of
|
|
2151
|
+
// the invariant at the call site, harmless no-op double-check. The trust
|
|
2152
|
+
// block (flair#744) is NOT attached on the collection path — that routes to
|
|
2153
|
+
// search(), which is out of this slice's by-id `get` surface.
|
|
2154
|
+
if (!target || (typeof target === "object" && target.isCollection)) {
|
|
2155
|
+
return this.search(target);
|
|
2156
|
+
}
|
|
2157
|
+
const ctx = this.getContext?.();
|
|
2158
|
+
const auth = await resolveAgentAuth(ctx);
|
|
2159
|
+
// flair#1940 round 18 (design ruling): a non-admin read ignores the caller's
|
|
2160
|
+
// `select`/`property` whatever the target shape — the same contract the auth
|
|
2161
|
+
// middleware enforces for a REST read, applied here for a direct contextual
|
|
2162
|
+
// read. Read the FULL stored row through the shared by-id gate (which builds
|
|
2163
|
+
// its own plain id-only target) so the pointer decision below always sees
|
|
2164
|
+
// the stored `id`, `agentId`, `instanceToken`, `archived` and `visibility`.
|
|
2165
|
+
// A shaped read — a caller target carrying a selection, or a class that
|
|
2166
|
+
// installs one — can never hand the join an already-projected value.
|
|
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;
|
|
2171
|
+
let readTarget = target;
|
|
2172
|
+
if (nonAdminAgent || legacyProperty || (typeof target === "object" && (target.select != null || target.property != null))) {
|
|
2173
|
+
const targetId = legacyProperty ? boundId : typeof target === "string" ? target : target?.id;
|
|
2174
|
+
readTarget = targetId != null ? { id: targetId } : {};
|
|
2175
|
+
}
|
|
2176
|
+
const result = await memoryByIdReadGate.call(this, readTarget, (t) => super.get(t));
|
|
2177
|
+
if (nonAdminAgent && result && typeof result === "object" && !(result instanceof Response)) {
|
|
2178
|
+
if (!(await closedSkillPayloadReadable(result, auth.agentId)))
|
|
2179
|
+
return NOT_FOUND();
|
|
2180
|
+
}
|
|
2181
|
+
// flair#1940 A3 (by-ID surface): the pointer is projected for THIS reader
|
|
2182
|
+
// BEFORE the trust block is attached. Admin/internal stay unfiltered (they
|
|
2183
|
+
// read the unredacted row, like every other field); a non-admin agent is
|
|
2184
|
+
// the reader the withheld rule protects. The FULL stored row goes through
|
|
2185
|
+
// the helper: the gated join renders a pointer ONLY when the row carries
|
|
2186
|
+
// its `id` and `instanceToken`, and an inline pointer field on the Memory
|
|
2187
|
+
// row is stripped from the returned object.
|
|
2188
|
+
let projected = result;
|
|
2189
|
+
if (result && typeof result === "object" && !(result instanceof Response)) {
|
|
2190
|
+
if (nonAdminAgent) {
|
|
2191
|
+
// A1' item 4 / A1-iv item 2: the gated join, through the ONE reader
|
|
2192
|
+
// helper (projectRowsThroughPointers) — pointer | "withheld" | nothing.
|
|
2193
|
+
projected = (await projectRowsThroughPointers([result], auth.agentId))[0];
|
|
766
2194
|
}
|
|
767
2195
|
}
|
|
768
2196
|
// flair#744 slice 1 — opt-in inline trust-evidence block, attached ONLY to
|
|
@@ -775,9 +2203,11 @@ export class Memory extends databases.flair.Memory {
|
|
|
775
2203
|
if (result && typeof result === "object" && !(result instanceof Response) && typeof result.agentId === "string") {
|
|
776
2204
|
const ctx = this.getContext?.();
|
|
777
2205
|
const withHits = await applyHitStats(projected, ctx);
|
|
778
|
-
|
|
2206
|
+
const bound = applyPromotionBinding(attachTrust(withHits, wantsTrust(target, opts)));
|
|
2207
|
+
return nonAdminAgent ? bound : projectMemoryRead(this.constructor, bound, selectionTarget, ctx, true);
|
|
779
2208
|
}
|
|
780
|
-
|
|
2209
|
+
const bound = applyPromotionBinding(projected);
|
|
2210
|
+
return nonAdminAgent ? bound : projectMemoryRead(this.constructor, bound, selectionTarget, ctx, true);
|
|
781
2211
|
}
|
|
782
2212
|
/**
|
|
783
2213
|
* Override search() to scope collection GETs by authenticated agent.
|
|
@@ -790,7 +2220,9 @@ export class Memory extends databases.flair.Memory {
|
|
|
790
2220
|
* Non-admin calls are scoped to the reader's own records at any visibility
|
|
791
2221
|
* plus every other agent's non-private records — the shipped open-within-org
|
|
792
2222
|
* read model. MemoryGrant is NOT consulted on reads; the one place the scope
|
|
793
|
-
* 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.
|
|
794
2226
|
*/
|
|
795
2227
|
async search(query) {
|
|
796
2228
|
// Access request context via Harper's Resource instance context.
|
|
@@ -804,15 +2236,25 @@ export class Memory extends databases.flair.Memory {
|
|
|
804
2236
|
const gate = await resolveAuthGate(ctx, UNAUTH());
|
|
805
2237
|
if (gate.kind === "denied")
|
|
806
2238
|
return gate.response;
|
|
807
|
-
if (gate.kind === "unfiltered")
|
|
808
|
-
|
|
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
|
+
}
|
|
809
2249
|
// Non-admin agent: scope to own records at any visibility plus every other
|
|
810
2250
|
// agent's non-private records (open-within-org; MemoryGrant is not
|
|
811
2251
|
// consulted on reads). Centralized in
|
|
812
2252
|
// memoryReadScope (record-type-kit.ts's makeReadScope(), parameterized
|
|
813
2253
|
// from RECORD_TYPES.Memory — see this file's header — delegating
|
|
814
2254
|
// "open-within-org" to memory-read-scope.ts's resolveReadScope()
|
|
815
|
-
// 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.
|
|
816
2258
|
//
|
|
817
2259
|
// The scope condition is nested as the outermost AND block via
|
|
818
2260
|
// makeScopedSearch (record-type-kit.ts) — same correct composition
|
|
@@ -847,7 +2289,11 @@ export class Memory extends databases.flair.Memory {
|
|
|
847
2289
|
rows = [];
|
|
848
2290
|
const projected = await projectRowsThroughPointers(batch, readerAgentId);
|
|
849
2291
|
for (const row of projected) {
|
|
850
|
-
|
|
2292
|
+
// flair#2139 S2 — close-payload bypass (see get()): filter a retained
|
|
2293
|
+
// closed skill payload the reader may not read. Open rows pass.
|
|
2294
|
+
if (!(await closedSkillPayloadReadable(row, readerAgentId)))
|
|
2295
|
+
continue;
|
|
2296
|
+
yield await applyHitStats(applyPromotionBinding(row), ctx);
|
|
851
2297
|
}
|
|
852
2298
|
};
|
|
853
2299
|
// memoryScopedSearch returns a Promise of the iterable (its scopedSearch
|
|
@@ -862,7 +2308,75 @@ export class Memory extends databases.flair.Memory {
|
|
|
862
2308
|
})();
|
|
863
2309
|
return joined;
|
|
864
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. */
|
|
865
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;
|
|
2372
|
+
// flair#2141 S2: check the seed's fixed id against the operator-source
|
|
2373
|
+
// reservation (resources/seed-reservation.ts).
|
|
2374
|
+
const seedDenial = await refuseReservedSeedWrite("Memory", writeTargetIds(this, content), this.getContext?.());
|
|
2375
|
+
if (seedDenial)
|
|
2376
|
+
return seedDenial;
|
|
2377
|
+
const contentSuffixDenial = refuseContentSuffixId(writeTargetIds(this, content), context);
|
|
2378
|
+
if (contentSuffixDenial)
|
|
2379
|
+
return contentSuffixDenial;
|
|
866
2380
|
const authorityDenial = await guardAuthorityFields(() => super.get(), content, "Memory");
|
|
867
2381
|
if (authorityDenial)
|
|
868
2382
|
return authorityDenial;
|
|
@@ -906,13 +2420,49 @@ export class Memory extends databases.flair.Memory {
|
|
|
906
2420
|
if (attr.denied)
|
|
907
2421
|
return attr.denied;
|
|
908
2422
|
}
|
|
2423
|
+
const postUrlTargetId = this.getId?.();
|
|
2424
|
+
if (content && typeof content === "object" && content.id == null &&
|
|
2425
|
+
(typeof postUrlTargetId === "string" || typeof postUrlTargetId === "number")) {
|
|
2426
|
+
content.id = postUrlTargetId;
|
|
2427
|
+
}
|
|
2428
|
+
const postStored = content.id ? await databases.flair.Memory.get(content.id) : null;
|
|
2429
|
+
// flair#2561: the fields this request supplies that `stored` can report —
|
|
2430
|
+
// its string-valued text fields and, for a skill, the skill fields it
|
|
2431
|
+
// supplies (flair#2575) — read before a skill predecessor is merged into the
|
|
2432
|
+
// body; `stored` reports only these. Redaction runs after prepareSkillBody
|
|
2433
|
+
// (below) and keeps a string a string, so reading them first names the
|
|
2434
|
+
// same fields.
|
|
2435
|
+
const suppliedText = suppliedStoredTextFields(content);
|
|
2436
|
+
// `content.supersedes` is already canonical: post() resolved it before
|
|
2437
|
+
// lock selection (canonicalizeSupersedes runs once per request).
|
|
2438
|
+
// flair#2573: an empty `embedding` in the body is an omitted one. It is
|
|
2439
|
+
// removed before the omission check and prepareSkillBody, so every later
|
|
2440
|
+
// step, a skill update's carried vector included, sees a body without it.
|
|
2441
|
+
if (isEmptyEmbedding(content?.embedding))
|
|
2442
|
+
delete content.embedding;
|
|
2443
|
+
// flair#2573 slice 2: did the CALLER supply a non-null embedding, and/or an
|
|
2444
|
+
// `embeddingModel` stamp, that differs from the stored row's? Captured before
|
|
2445
|
+
// prepareSkillBody can merge a stored row's vector into the body.
|
|
2446
|
+
const { vector: postSuppliedVector, stamp: postSuppliedStamp } = suppliedVectorFlags(content, postStored);
|
|
2447
|
+
// The visibility the caller named, before any merge or default fills it.
|
|
2448
|
+
const requestedVisibility = content?.visibility;
|
|
2449
|
+
// flair#2465: a body that omits `embedding` can have the stored row's vector
|
|
2450
|
+
// carried in by prepareSkillBody, with the hash it retained for that vector.
|
|
2451
|
+
const postOmitsEmbedding = content?.embedding === undefined;
|
|
2452
|
+
const preparedSkill = await prepareSkillBody(content, postStored, auth);
|
|
2453
|
+
if (preparedSkill instanceof Response)
|
|
2454
|
+
return preparedSkill;
|
|
2455
|
+
content = preparedSkill.content;
|
|
2456
|
+
let redactedValues = redactMemoryWrite(content).count;
|
|
2457
|
+
// Duplicate top-level metadata keys are refused; otherwise redact name/description and tags.
|
|
2458
|
+
redactedValues += redactSkillWrite(content);
|
|
2459
|
+
const postCarriedHash = postOmitsEmbedding && Array.isArray(content?.embedding) && content.embedding.length > 0
|
|
2460
|
+
? (content.embeddedContentHash ?? null)
|
|
2461
|
+
: null;
|
|
909
2462
|
// flair#744 slice A: citation-on-write — consume-and-strip, same
|
|
910
2463
|
// discipline as `claimedClient` below. Pull the optional
|
|
911
2464
|
// `usedMemoryIds` off the write body now, BEFORE anything else touches
|
|
912
2465
|
// `content`, so it is NEVER persisted on the Memory record itself.
|
|
913
|
-
// Recording happens POST-COMMIT, only when this was present (see the
|
|
914
|
-
// failure-isolated recordCitations() call near the return below) —
|
|
915
|
-
// omitted ⇒ `undefined` ⇒ zero new calls, byte-identical behavior.
|
|
916
2466
|
const usedMemoryIds = content?.usedMemoryIds;
|
|
917
2467
|
if (content && typeof content === "object")
|
|
918
2468
|
delete content.usedMemoryIds;
|
|
@@ -1000,31 +2550,12 @@ export class Memory extends databases.flair.Memory {
|
|
|
1000
2550
|
if (content.visibility === undefined || content.visibility === null) {
|
|
1001
2551
|
content.visibility = defaultVisibilityForDurability(content.durability);
|
|
1002
2552
|
}
|
|
1003
|
-
// Validate derivedFrom source IDs exist (best-effort, non-blocking).
|
|
1004
|
-
// lastReflected keys off updatedAt (the write moment), NOT createdAt —
|
|
1005
|
-
// since #1336 a create may carry a backdated caller createdAt, and the
|
|
1006
|
-
// reflection bookkeeping must record when the derivation actually ran.
|
|
1007
|
-
// (Pre-#1336 the two were always identical here.)
|
|
1008
|
-
if (Array.isArray(content.derivedFrom) && content.derivedFrom.length > 0) {
|
|
1009
|
-
const now = content.updatedAt;
|
|
1010
|
-
for (const sourceId of content.derivedFrom) {
|
|
1011
|
-
try {
|
|
1012
|
-
const src = await databases.flair.Memory.get(sourceId);
|
|
1013
|
-
if (src) {
|
|
1014
|
-
const reflectPatch = { lastReflected: now };
|
|
1015
|
-
stripUndeclaredMemoryAttributes(reflectPatch);
|
|
1016
|
-
patchRecord(databases.flair.Memory, sourceId, reflectPatch).catch(() => { });
|
|
1017
|
-
}
|
|
1018
|
-
}
|
|
1019
|
-
catch { }
|
|
1020
|
-
}
|
|
1021
|
-
}
|
|
1022
2553
|
// supersedes: optional reference to the ID of the memory this one
|
|
1023
2554
|
// replaces. Validates shape + cross-agent-write authorization (shared
|
|
1024
2555
|
// with put() — see validateAndAuthorizeSupersedes doc).
|
|
1025
|
-
const
|
|
1026
|
-
if (
|
|
1027
|
-
return
|
|
2556
|
+
const supersede = await validateAndAuthorizeSupersedes(content, auth, ctx, postStored, requestedVisibility);
|
|
2557
|
+
if (supersede.denial)
|
|
2558
|
+
return supersede.denial;
|
|
1028
2559
|
// Temporal validity: validFrom defaults to now, validTo left null for active facts.
|
|
1029
2560
|
if (!content.validFrom) {
|
|
1030
2561
|
content.validFrom = content.createdAt;
|
|
@@ -1036,10 +2567,17 @@ export class Memory extends databases.flair.Memory {
|
|
|
1036
2567
|
const entitiesError = invalidEntitiesResponse(content.entities);
|
|
1037
2568
|
if (entitiesError)
|
|
1038
2569
|
return entitiesError;
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
content.
|
|
2570
|
+
// A new row cannot be its own derivedFrom source (flair#2354).
|
|
2571
|
+
if (content.id != null && Array.isArray(content.derivedFrom) &&
|
|
2572
|
+
content.derivedFrom.some((sourceId) => String(sourceId) === String(content.id))) {
|
|
2573
|
+
return Response.json({
|
|
2574
|
+
error: "derived_from_self",
|
|
2575
|
+
message: "derivedFrom may not include the id of the memory being written",
|
|
2576
|
+
}, { status: 400 });
|
|
1042
2577
|
}
|
|
2578
|
+
const expiryError = stampEphemeralExpiry(content);
|
|
2579
|
+
if (expiryError)
|
|
2580
|
+
return Response.json({ error: "invalid_expiry", message: expiryError }, { status: 400 });
|
|
1043
2581
|
// Content safety scan — covers content + summary (defense-in-depth for
|
|
1044
2582
|
// agent-set summaries).
|
|
1045
2583
|
if (content.content || content.summary) {
|
|
@@ -1075,9 +2613,30 @@ export class Memory extends databases.flair.Memory {
|
|
|
1075
2613
|
// this a duplicate of something else" situation — bypass the gate for it
|
|
1076
2614
|
// (this also gives memory_update's preserveHistory mode dedup-bypass for
|
|
1077
2615
|
// free, without a separate flag). NEVER suppresses the write either way.
|
|
2616
|
+
// Discard the non-admin caller's vector and stamp that differ from the
|
|
2617
|
+
// stored row's, after redaction, before dedup and embedding. Compute an
|
|
2618
|
+
// embedding when the resulting write needs one.
|
|
2619
|
+
if (postSuppliedVector || postSuppliedStamp) {
|
|
2620
|
+
discardSuppliedVector(content, auth, { vector: postSuppliedVector, stamp: postSuppliedStamp }, postStored);
|
|
2621
|
+
}
|
|
2622
|
+
// flair#2573: an empty vector that reaches this point (one carried from a
|
|
2623
|
+
// stored skill row; the body's own was removed above) is no vector. It is
|
|
2624
|
+
// normalized before the dedup gate and the embed step, which can then
|
|
2625
|
+
// compute and stamp one when embedding succeeds.
|
|
2626
|
+
normalizeEmptyEmbedding(content);
|
|
2627
|
+
// flair#2465: did the caller supply a vector that survived redaction? A
|
|
2628
|
+
// vector accepted from the caller gets no newly computed hash.
|
|
2629
|
+
const embeddingSupplied = Array.isArray(content.embedding) && content.embedding.length > 0;
|
|
1078
2630
|
let dedupMatch = null;
|
|
1079
2631
|
if (!content.supersedes) {
|
|
1080
|
-
|
|
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
|
+
}
|
|
1081
2640
|
}
|
|
1082
2641
|
else {
|
|
1083
2642
|
delete content.dedup;
|
|
@@ -1091,7 +2650,15 @@ export class Memory extends databases.flair.Memory {
|
|
|
1091
2650
|
// (skillEmbedText), not `content`.
|
|
1092
2651
|
const embedText = skillEmbedText(content);
|
|
1093
2652
|
if (embedText && !content.embedding) {
|
|
1094
|
-
|
|
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
|
+
}
|
|
1095
2662
|
if (vec) {
|
|
1096
2663
|
content.embedding = vec;
|
|
1097
2664
|
content.embeddingModel = getModelId();
|
|
@@ -1107,6 +2674,16 @@ export class Memory extends databases.flair.Memory {
|
|
|
1107
2674
|
// A1-iv item 3: strip every server-stamped field a client body may not set
|
|
1108
2675
|
// (instanceToken, provenance). They are re-stamped below.
|
|
1109
2676
|
stripServerStampedFields(content);
|
|
2677
|
+
// flair#2465: a vector the server computed here gets a newly computed
|
|
2678
|
+
// hash of the text it embedded (null for an empty owner). A skill's stored
|
|
2679
|
+
// vector that prepareSkillBody carried in keeps the hash prepareSkillBody
|
|
2680
|
+
// retained with it (possibly null), so a successor of a row whose hash
|
|
2681
|
+
// differs from its text's expected hash still differs. A vector accepted
|
|
2682
|
+
// and stored from the caller gets null; the stamp migration then skips only
|
|
2683
|
+
// the hash comparison for the row.
|
|
2684
|
+
content.embeddedContentHash = !embeddingSupplied && Array.isArray(content.embedding) && content.embedding.length > 0
|
|
2685
|
+
? (embeddedTextHash(content) ?? null)
|
|
2686
|
+
: postCarriedHash;
|
|
1110
2687
|
// A1-iv item 1: a NEW row gets a server-stamped incarnation token.
|
|
1111
2688
|
content.instanceToken = newInstanceToken();
|
|
1112
2689
|
const pointer = buildPointerForWrite({ inputs: pointerInputs, memoryId: content.id ?? "", visibility: content.visibility, auth, memoryInstanceToken: content.instanceToken });
|
|
@@ -1141,25 +2718,105 @@ export class Memory extends databases.flair.Memory {
|
|
|
1141
2718
|
// Pinned by test/unit/memory-host-source.test.ts (r20-post) — RED if this
|
|
1142
2719
|
// call is removed.
|
|
1143
2720
|
stripUndeclaredMemoryAttributes(content);
|
|
1144
|
-
|
|
1145
|
-
//
|
|
1146
|
-
//
|
|
1147
|
-
//
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
const
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
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);
|
|
2726
|
+
if (isSkillWrite(content)) {
|
|
2727
|
+
const reservedId = [content?.id, this.getId?.()].find((candidate) => isReservedSeedId("Memory", candidate));
|
|
2728
|
+
const skillStaged = { supplied: suppliedText, text: null };
|
|
2729
|
+
const skillResult = await writeSkillCreateOrUpdate({
|
|
2730
|
+
ctx, auth, content, storedRow: postStored, explicitPredecessor: preparedSkill.predecessor, method: "post", pointer,
|
|
2731
|
+
inPlaceId: reservedId != null ? String(reservedId) : null, staged: skillStaged, held,
|
|
2732
|
+
});
|
|
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
|
+
}
|
|
2754
|
+
await markDerivedSourcesReflected(content);
|
|
2755
|
+
return skillWriteResponse(skillResult, redactedValues, skillStaged.text);
|
|
2756
|
+
};
|
|
2757
|
+
if (skillResult?.confirm)
|
|
2758
|
+
return { skillThen: finish };
|
|
2759
|
+
return await finish();
|
|
2760
|
+
}
|
|
2761
|
+
// flair#2467: the post-redaction text fields this write stages, for the response.
|
|
2762
|
+
let postStaged = {};
|
|
2763
|
+
let stagedRow;
|
|
2764
|
+
let postResult;
|
|
2765
|
+
let postRowId;
|
|
2766
|
+
let grantedClosed = null;
|
|
2767
|
+
try {
|
|
2768
|
+
postResult = await withSharedWriteTransaction(ctx, async (c) => {
|
|
2769
|
+
postStaged = storedMemoryText(content, suppliedText);
|
|
2770
|
+
stagedRow = structuredClone(content);
|
|
2771
|
+
const newId = await writeMemoryRowPost(this.constructor, content, c);
|
|
2772
|
+
if (newId instanceof Response)
|
|
2773
|
+
return newId;
|
|
2774
|
+
postRowId = newId;
|
|
2775
|
+
if (pointer.row) {
|
|
2776
|
+
pointer.row.memoryId = newId;
|
|
2777
|
+
const persistDenial = await persistPointerRow(pointer.row, c);
|
|
2778
|
+
if (persistDenial)
|
|
2779
|
+
return persistDenial;
|
|
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;
|
|
2786
|
+
// Stage a grant-authorized close in the successor's transaction.
|
|
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
|
+
}
|
|
2798
|
+
return null;
|
|
2799
|
+
});
|
|
2800
|
+
}
|
|
2801
|
+
catch (err) {
|
|
2802
|
+
if (err instanceof CommittedRowChanged)
|
|
2803
|
+
return storedRowChangedRefusal("Memory");
|
|
2804
|
+
const refusal = grantedCloseRefusal(err);
|
|
2805
|
+
if (refusal)
|
|
2806
|
+
return refusal;
|
|
2807
|
+
throw err;
|
|
2808
|
+
}
|
|
1161
2809
|
if (postResult instanceof Response)
|
|
1162
|
-
return postResult;
|
|
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
|
+
}
|
|
2818
|
+
if (grantedClosed)
|
|
2819
|
+
noteMemoryUpsert(grantedClosed);
|
|
1163
2820
|
const result = {};
|
|
1164
2821
|
// flair#1357 — read-your-write for the lexical leg. The table change feed
|
|
1165
2822
|
// (resources/bm25-index-service.ts) is the CORRECTNESS mechanism; this
|
|
@@ -1170,37 +2827,79 @@ export class Memory extends databases.flair.Memory {
|
|
|
1170
2827
|
// a persisted FOREIGN stamp (federation / replication / an explicit-stamp
|
|
1171
2828
|
// write) trips the gate; a normal local write stamps the current id and
|
|
1172
2829
|
// never does.
|
|
1173
|
-
|
|
2830
|
+
// `postStored` is the row this write replaces; a read that found none is
|
|
2831
|
+
// passed as null (no previous row), not as unknown.
|
|
2832
|
+
noteWriteStamp(content?.embeddingModel, postStored ?? null);
|
|
1174
2833
|
// ── THEN close the superseded record ────────────────────────────────────
|
|
1175
2834
|
// Write-new-BEFORE-close-old: the previous order (close-old via a fire-
|
|
1176
2835
|
// and-forget `.catch(()=>{})` BEFORE the new write) could tombstone the
|
|
1177
2836
|
// old record and then lose the new one if the write failed afterward.
|
|
1178
2837
|
// Now the safe failure state is two active records (recoverable), never
|
|
1179
2838
|
// a lost write — and the failure is logged, never silently swallowed.
|
|
1180
|
-
|
|
1181
|
-
//
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
//
|
|
1186
|
-
//
|
|
2839
|
+
// A grant-authorized close was staged in the successor's transaction
|
|
2840
|
+
// (closeGrantedSupersedeStaged).
|
|
2841
|
+
if (supersede.close?.granteeId === undefined)
|
|
2842
|
+
await closeSupersededIfNeeded(ctx, content, supersede.close, "post");
|
|
2843
|
+
await markDerivedSourcesReflected(content);
|
|
2844
|
+
// flair#744: queue citation-on-write for post() (flair#2858).
|
|
2845
|
+
// A completed credit error is logged without changing the response payload.
|
|
1187
2846
|
if (usedMemoryIds !== undefined) {
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
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
|
+
});
|
|
1194
2855
|
}
|
|
1195
|
-
return buildWriteResponse(content, result, dedupMatch);
|
|
2856
|
+
return buildWriteResponse(content, result, dedupMatch, redactedValues, postStaged, postRowId);
|
|
1196
2857
|
}
|
|
1197
2858
|
// PATCH routes past put(), so agentId immutability is enforced on both verbs
|
|
1198
2859
|
// via the one shared delegate. (Admin/internal — including the _reindex
|
|
1199
2860
|
// path in put() — pass through the delegate untouched.)
|
|
2861
|
+
/** PATCH requires a target id and lock before its body runs. Ordinary and
|
|
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). */
|
|
1200
2865
|
async patch(content, query) {
|
|
1201
|
-
const
|
|
1202
|
-
if (
|
|
1203
|
-
return
|
|
2866
|
+
const ids = putLockIds(this, content);
|
|
2867
|
+
if (ids.length === 0)
|
|
2868
|
+
return memoryIdRequiredResponse();
|
|
2869
|
+
const phase = isReembedPatch(content) ? "patch-reembed" : "patch";
|
|
2870
|
+
const outcome = await withMemoryWriteLock(memoryWriteLockStore(), ids, async () => {
|
|
2871
|
+
const result = await this.patchLocked(content, query);
|
|
2872
|
+
// Test-only: the verb body has returned and the lock is still held. A body
|
|
2873
|
+
// that owned its transaction has committed it.
|
|
2874
|
+
const committed = txnPausePoint("memory-patch-committed");
|
|
2875
|
+
if (committed)
|
|
2876
|
+
await committed;
|
|
2877
|
+
return result;
|
|
2878
|
+
}, { phase });
|
|
2879
|
+
if (outcome.kind === "done")
|
|
2880
|
+
return outcome.value;
|
|
2881
|
+
return memoryLockRefusal(outcome, memoryLockCallerId(this));
|
|
2882
|
+
}
|
|
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);
|
|
2887
|
+
const entry = txnPausePoint("memory-patch-entry");
|
|
2888
|
+
if (entry)
|
|
2889
|
+
await entry;
|
|
2890
|
+
// flair#2296: decided on the body as sent; the guards below add fields to it.
|
|
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");
|
|
2895
|
+
// flair#2141 S2: check the seed's fixed id against the operator-source
|
|
2896
|
+
// reservation (resources/seed-reservation.ts).
|
|
2897
|
+
const seedDenial = await refuseReservedSeedWrite("Memory", writeTargetIds(this, content), this.getContext?.());
|
|
2898
|
+
if (seedDenial)
|
|
2899
|
+
return seedDenial;
|
|
2900
|
+
const contentSuffixDenial = refuseContentSuffixId(writeTargetIds(this, content), query);
|
|
2901
|
+
if (contentSuffixDenial)
|
|
2902
|
+
return contentSuffixDenial;
|
|
1204
2903
|
// flair#1383 — patch() routes past put(), so it needs its own refuse.
|
|
1205
2904
|
{
|
|
1206
2905
|
const stale = refuseStaleClientWrite(this.getContext?.()?.request, content);
|
|
@@ -1208,6 +2907,22 @@ export class Memory extends databases.flair.Memory {
|
|
|
1208
2907
|
return stale;
|
|
1209
2908
|
}
|
|
1210
2909
|
stripClientVersionPassthrough(content);
|
|
2910
|
+
// flair#2573: an empty embedding becomes `null` here, before redaction.
|
|
2911
|
+
if (content != null && typeof content === "object")
|
|
2912
|
+
normalizeEmptyEmbedding(content);
|
|
2913
|
+
// flair#2407: redact credential-shaped text on a PATCH too, before the body
|
|
2914
|
+
// is merged into the stored row.
|
|
2915
|
+
const redaction = redactMemoryWrite(content);
|
|
2916
|
+
const redactedValues = redaction.count;
|
|
2917
|
+
// flair#2573 slice 2: a non-admin write's caller-supplied vector and stamp
|
|
2918
|
+
// (one that differs from the stored row's) are discarded inside the
|
|
2919
|
+
// transaction, right after the stored read (see post()/put()). A stamp-only
|
|
2920
|
+
// body (no `embedding`) has its stamp discarded too, so a non-admin PATCH
|
|
2921
|
+
// cannot relabel a stored vector. The PATCH then behaves exactly as one that
|
|
2922
|
+
// sent neither.
|
|
2923
|
+
// flair#2561: the string-valued text fields this request supplies;
|
|
2924
|
+
// `stored` reports only these.
|
|
2925
|
+
const suppliedText = suppliedMemoryTextFields(content);
|
|
1211
2926
|
// flair#1960 r2: capture the (undeclared) authorship-claim inputs BEFORE the
|
|
1212
2927
|
// undeclared-attribute strip removes them, so a semantic PATCH re-stamps
|
|
1213
2928
|
// provenance with the SAME claims a post()/put() would record from this body
|
|
@@ -1223,127 +2938,457 @@ export class Memory extends databases.flair.Memory {
|
|
|
1223
2938
|
extractPointerInputs(content);
|
|
1224
2939
|
stripUndeclaredMemoryAttributes(content);
|
|
1225
2940
|
// A1-iv item 3: strip server-stamped fields on patch too (a PATCH body may
|
|
1226
|
-
// not set instanceToken or provenance; the stored values stand
|
|
2941
|
+
// not set instanceToken or provenance; the stored values stand, except that
|
|
2942
|
+
// a row with no instanceToken is given one by the server below, flair#2478).
|
|
1227
2943
|
stripServerStampedFields(content);
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
//
|
|
1232
|
-
//
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
2944
|
+
// flair#2465: a body `embeddedContentHash` is dropped. A PATCH merges, so
|
|
2945
|
+
// the STORED value is retained unless the refresh path below writes a newly
|
|
2946
|
+
// computed hash of the text it embeds (null for an empty owner, or when the
|
|
2947
|
+
// engine returns no vector), or the re-embed writes one with its vector. A
|
|
2948
|
+
// PATCH that supplies its own vector retains the stored hash beside it.
|
|
2949
|
+
delete content.embeddedContentHash;
|
|
2950
|
+
const declaredFields = patchDeclaredFields(content);
|
|
2951
|
+
// flair#2478 slice 1 — the ordinary PATCH runs in ONE owned transaction whose
|
|
2952
|
+
// FIRST operation is the authoritative stored read; the read, the decision
|
|
2953
|
+
// and the COMMIT all happen before the write lock releases. Harper orders a
|
|
2954
|
+
// transaction by its first read, so the read and every decision drawn from
|
|
2955
|
+
// it share this commit. (A re-embed PATCH writes in its own inner owned
|
|
2956
|
+
// transaction instead, which also commits before the lock releases.)
|
|
2957
|
+
const ctx = this.getContext?.();
|
|
2958
|
+
const patchScope = locked
|
|
2959
|
+
? (cx, fn) => locked.admission.join(cx, fn)
|
|
2960
|
+
: withOwnedTransaction;
|
|
2961
|
+
const patched = await patchScope(ctx, async (c) => {
|
|
2962
|
+
// The FIRST operation inside the owned transaction: the authoritative
|
|
2963
|
+
// stored read, by the URL-BOUND target id (a body id that disagrees with
|
|
2964
|
+
// the address, or a lookup that FAILS, is refused; a failed read is never
|
|
2965
|
+
// read as "no stored row").
|
|
2966
|
+
const resolvedStored = await resolveStoredRow(this, "Memory", content, () => super.get(), c);
|
|
2967
|
+
if (resolvedStored.denial)
|
|
2968
|
+
return resolvedStored.denial;
|
|
2969
|
+
const existingForSkill = resolvedStored.row;
|
|
2970
|
+
if (!reembedRequest) {
|
|
2971
|
+
const { vector, stamp } = suppliedVectorFlags(content, existingForSkill);
|
|
2972
|
+
if (vector || stamp) {
|
|
2973
|
+
discardSuppliedVector(content, await resolveAgentAuth(ctx), { vector, stamp }, existingForSkill);
|
|
2974
|
+
}
|
|
1240
2975
|
}
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
2976
|
+
// Authorize inside the transaction: the authority then owner guards read
|
|
2977
|
+
// the stored row from this transaction's own snapshot.
|
|
2978
|
+
const authorityDenial = await guardAuthorityFields(() => super.get(), content, "Memory");
|
|
2979
|
+
if (authorityDenial)
|
|
2980
|
+
return authorityDenial;
|
|
2981
|
+
const denial = await guardOwnerFieldImmutable(this, () => super.get(), content, "agentId");
|
|
2982
|
+
if (denial)
|
|
2983
|
+
return denial;
|
|
2984
|
+
// Preserve stored visibility on updates before applying write policy: a
|
|
2985
|
+
// null is no change (PATCH merges), and a present value goes through the
|
|
2986
|
+
// same validator and ephemeral-tier guard as put().
|
|
2987
|
+
if (content && "visibility" in content && content.visibility == null)
|
|
2988
|
+
delete content.visibility;
|
|
2989
|
+
if (content && (content.visibility !== undefined || content.durability !== undefined)) {
|
|
2990
|
+
const durabilityError = assertValidDurability(content.durability);
|
|
2991
|
+
if (durabilityError) {
|
|
2992
|
+
return new Response(JSON.stringify({ error: "invalid_durability", message: durabilityError }), { status: 400, headers: { "content-type": "application/json" } });
|
|
2993
|
+
}
|
|
2994
|
+
const visibilityError = assertValidVisibility(content.visibility);
|
|
2995
|
+
if (visibilityError) {
|
|
2996
|
+
return new Response(JSON.stringify({ error: "invalid_visibility", message: visibilityError }), { status: 400, headers: { "content-type": "application/json" } });
|
|
2997
|
+
}
|
|
2998
|
+
// The stored row the tier guard compares against: the row this
|
|
2999
|
+
// transaction's first read resolved. When the resolver found no
|
|
3000
|
+
// URL-bound id to read by (an in-process harness), fall back to the
|
|
3001
|
+
// resource's own bound-record read so an update still consults the
|
|
3002
|
+
// stored visibility.
|
|
3003
|
+
const stored = existingForSkill ?? (await super.get());
|
|
3004
|
+
const tierError = assertVisibilityAllowedForDurability(content.durability ?? stored?.durability, content.visibility ?? stored?.visibility);
|
|
3005
|
+
if (tierError) {
|
|
3006
|
+
return new Response(JSON.stringify({ error: "invalid_visibility_for_durability", message: tierError }), { status: 400, headers: { "content-type": "application/json" } });
|
|
3007
|
+
}
|
|
1244
3008
|
}
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
3009
|
+
// ── flair#1542 + residual (Kern #1543 review 5135715289): reject skill patches ──
|
|
3010
|
+
// patch() routes past put() (and thus past the SkillScan gate + forced
|
|
3011
|
+
// durability), so a skill write on this verb would land unscanned. There are
|
|
3012
|
+
// TWO ways a patch is a skill write, and the mint-time check saw only the first:
|
|
3013
|
+
// 1. the PATCH BODY carries the skill tag — rejectSkillWritePath(content).
|
|
3014
|
+
// 2. the STORED record is ALREADY a skill, and the body mutates `content`
|
|
3015
|
+
// (or anything else) WITHOUT re-declaring the tag. isSkillWrite(body) is
|
|
3016
|
+
// then false, so the pre-residual check let the edit land — a skill's
|
|
3017
|
+
// procedure could be rewritten with NO SkillScan (the residual). Fold
|
|
3018
|
+
// the existing record into the check: a patch to a row whose STORED tags
|
|
3019
|
+
// include `skill` is rejected the same as a mint-time skill write.
|
|
3020
|
+
// Skills are written via skill_store (→ Memory.post) or Memory.put; no
|
|
3021
|
+
// memory_patch tool exists and no internal path patches a skill row (hit-
|
|
3022
|
+
// tracking goes through table.put, not this override), so rejecting is safe.
|
|
3023
|
+
// flair#1965 r3 + flair#1960 r3: `existingForSkill` is the row resolved by
|
|
3024
|
+
// this transaction's FIRST read (the authoritative stored read above), by the
|
|
3025
|
+
// URL-BOUND target id. This ONE resolved row drives the skill-row check, the
|
|
3026
|
+
// semantic-PATCH provenance decision below, AND the originatorInstanceId
|
|
3027
|
+
// create/update rule.
|
|
3028
|
+
// flair#2296: re-embed intentionally changes only embedding, embeddingModel
|
|
3029
|
+
// and updatedAt, plus the embedded-text hash (flair#2465) (flair#2478: and
|
|
3030
|
+
// gives a legacy row with no instanceToken one).
|
|
3031
|
+
// flair#2390: the vector is computed OUTSIDE the write. The write itself
|
|
3032
|
+
// re-reads the committed row inside its own transaction (reembedStoredRow),
|
|
3033
|
+
// re-checks the owner and the text, stages ONLY those fields (flair#2465;
|
|
3034
|
+
// plus instanceToken for a legacy row that has none, flair#2478), then
|
|
3035
|
+
// confirms the committed row has the identity and embedding text it read
|
|
3036
|
+
// (flair#2465). A row gone or changed in either at confirmation aborts with
|
|
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
|
|
3041
|
+
// compares the token; a storage Response returns before that read.
|
|
3042
|
+
if (reembedRequest) {
|
|
3043
|
+
if (!existingForSkill)
|
|
3044
|
+
return NOT_FOUND();
|
|
3045
|
+
const auth = await resolveAgentAuth(this.getContext?.());
|
|
3046
|
+
if (auth.kind === "agent" && !auth.isAdmin &&
|
|
3047
|
+
isForbiddenOwnerMutation(existingForSkill, RECORD_TYPES.Memory.ownerField, auth.agentId)) {
|
|
3048
|
+
return FORBIDDEN("forbidden: cannot write memory owned by another agent");
|
|
3049
|
+
}
|
|
3050
|
+
const embedText = skillEmbedText(existingForSkill);
|
|
3051
|
+
if (typeof embedText !== "string" || embedText.length === 0) {
|
|
3052
|
+
return Response.json({ error: "reembed_no_text", message: "the stored row has no text to embed" }, { status: 422 });
|
|
3053
|
+
}
|
|
3054
|
+
// Test-only: inert unless the fault-injection env opt-in is set and armed.
|
|
3055
|
+
const pause = txnPausePoint("memory-reembed");
|
|
3056
|
+
if (pause)
|
|
3057
|
+
await pause;
|
|
3058
|
+
let embedding;
|
|
3059
|
+
try {
|
|
3060
|
+
embedding = await embedUnderLock(embedText);
|
|
3061
|
+
}
|
|
3062
|
+
catch (err) {
|
|
3063
|
+
if (err instanceof MemoryProviderTimeout)
|
|
3064
|
+
return memoryProviderTimeoutResponse();
|
|
3065
|
+
throw err;
|
|
3066
|
+
}
|
|
3067
|
+
if (!isUsableEmbeddingVector(embedding)) {
|
|
3068
|
+
return Response.json({ error: "embedding_unavailable", message: "the embedding engine returned no vector; the stored row is unchanged, retry" }, { status: 503 });
|
|
3069
|
+
}
|
|
3070
|
+
// The re-embed writes and commits in its own owned transaction. A refusal
|
|
3071
|
+
// is answered as is; a success is answered only after the post-commit
|
|
3072
|
+
// identity check below (flair#2478).
|
|
3073
|
+
const reembedded = await reembedStoredRow(String(existingForSkill.id), existingForSkill, embedding, auth, this.getContext?.());
|
|
3074
|
+
if (reembedded.token === undefined)
|
|
3075
|
+
return reembedded.response;
|
|
3076
|
+
return { reembed: reembedded.response, identity: { expectedToken: reembedded.token } };
|
|
1249
3077
|
}
|
|
3078
|
+
const skillDenial = rejectSkillWritePath(content) ?? rejectSkillWritePath(existingForSkill);
|
|
3079
|
+
if (skillDenial)
|
|
3080
|
+
return skillDenial;
|
|
3081
|
+
// ── flair#1960 r2: a SEMANTIC patch re-stamps provenance ────────────────
|
|
3082
|
+
// patch() strips a caller-supplied `provenance` (above) so a body can never
|
|
3083
|
+
// SET a `verified.*` field, but stripping alone would leave the STORED blob
|
|
3084
|
+
// in place — including a legacy row whose `verified.timestamp` came from a
|
|
3085
|
+
// client `createdAt` before this release. A patch that changes the record's
|
|
3086
|
+
// content is a fresh authored write, so it re-stamps from the resolved auth
|
|
3087
|
+
// and ONE server clock read (never the caller's `createdAt`, never a carried-
|
|
3088
|
+
// forward stored value). A metadata-only patch (no semantic field changes)
|
|
3089
|
+
// keeps the stored, previously-stamped blob: no new content was authored, so
|
|
3090
|
+
// there is no new write to attribute. See resources/provenance.ts
|
|
3091
|
+
// (isSemanticPatch / MEMORY_SEMANTIC_FIELDS) for the field set.
|
|
3092
|
+
if (isSemanticPatch(content, existingForSkill, MEMORY_SEMANTIC_FIELDS)) {
|
|
3093
|
+
const ctx = this.getContext?.();
|
|
3094
|
+
const auth = await resolveAgentAuth(ctx);
|
|
3095
|
+
content.provenance = buildProvenance(auth, content.createdAt ?? existingForSkill?.createdAt, claimInputs);
|
|
3096
|
+
}
|
|
3097
|
+
// flair#1965 r2: a PATCH over an EXISTING row keeps the stored
|
|
3098
|
+
// originatorInstanceId (a body value is dropped); a PATCH whose URL target
|
|
3099
|
+
// has NO stored row is a CREATE when it reaches the table — Harper's patch
|
|
3100
|
+
// path has no existing-row requirement — so it must stamp the local id
|
|
3101
|
+
// rather than leave the new row un-stamped. Only an administrator's or a
|
|
3102
|
+
// trusted internal PATCH gets that far; the table guard
|
|
3103
|
+
// (resources/table-patch-policy.ts) refuses the rest. See
|
|
3104
|
+
// resources/originator-instance.ts.
|
|
3105
|
+
await applyOriginatorInstanceId(content, existingForSkill);
|
|
3106
|
+
// The receiver-side federation bookkeeping keeps its stored value (a patch
|
|
3107
|
+
// merges); a client body value is dropped.
|
|
3108
|
+
dropClientFederationBookkeeping(content);
|
|
3109
|
+
const expiryError = stampEphemeralExpiry(content, existingForSkill);
|
|
3110
|
+
if (expiryError)
|
|
3111
|
+
return Response.json({ error: "invalid_expiry", message: expiryError }, { status: 400 });
|
|
3112
|
+
// flair#2466: this non-re-embed branch refreshes the embedding when the
|
|
3113
|
+
// body's `content` changes the compared row's text and `embedding` is absent
|
|
3114
|
+
// after redaction. Skill writes are refused above. A surviving
|
|
3115
|
+
// supplied vector is stored as supplied, without text/vector validation.
|
|
3116
|
+
// Without a refresh, the stored vector survives only if the body omits
|
|
3117
|
+
// `embedding` after redaction; an explicit `embedding: null` that survives
|
|
3118
|
+
// redaction clears it. Redaction that changes `content` or `trigger` removes
|
|
3119
|
+
// both embedding fields when either is non-null, so such a null does not survive.
|
|
3120
|
+
//
|
|
3121
|
+
// The vector is computed the way put() embeds a write that carries no vector
|
|
3122
|
+
// (same engine, `getEmbedding(..., "document")`; same stamps, embeddingModel
|
|
3123
|
+
// and updatedAt). When the engine returns no vector, embedding and
|
|
3124
|
+
// embeddingModel are written as null: the row keeps no vector for text it no
|
|
3125
|
+
// longer holds, and the embedding-stamp re-embed selects a null stamp.
|
|
3126
|
+
//
|
|
3127
|
+
// A fresh committed-row read runs only when the initial comparison selected
|
|
3128
|
+
// no embedding, a stored row exists, and the body omits `embedding` and carries the
|
|
3129
|
+
// embedding-text field. If that comparison finds changed text, refresh from
|
|
3130
|
+
// the body's text. Other paths write without this confirmation. Harper has
|
|
3131
|
+
// no compare-and-set: changes after the fresh read are not seen by it.
|
|
3132
|
+
//
|
|
3133
|
+
// A PATCH whose URL target has no stored row (a create, admin or internal
|
|
3134
|
+
// only) refreshes only when redaction removed a supplied embedding field
|
|
3135
|
+
// and the body carries `content`.
|
|
3136
|
+
const body = content != null && typeof content === "object" ? content : {};
|
|
3137
|
+
/** The field to embed this body's text from, if writing it over `stored` needs a vector; else null. */
|
|
3138
|
+
const vectorFieldOver = (stored) => {
|
|
3139
|
+
const field = embedTextField({ ...(stored ?? {}), ...body });
|
|
3140
|
+
if (!Object.prototype.hasOwnProperty.call(body, field) || Object.prototype.hasOwnProperty.call(body, "embedding"))
|
|
3141
|
+
return null;
|
|
3142
|
+
if (stored == null)
|
|
3143
|
+
return redaction.embeddingDiscarded ? field : null;
|
|
3144
|
+
return skillEmbedText({ ...stored, ...body }) !== skillEmbedText(stored) ? field : null;
|
|
3145
|
+
};
|
|
3146
|
+
const storeVectorFor = async (field) => {
|
|
3147
|
+
const embedText = body[field];
|
|
3148
|
+
let vec = null;
|
|
3149
|
+
if (typeof embedText === "string" && embedText.length > 0) {
|
|
3150
|
+
try {
|
|
3151
|
+
vec = await embedUnderLock(embedText);
|
|
3152
|
+
}
|
|
3153
|
+
catch (err) {
|
|
3154
|
+
if (err instanceof MemoryProviderTimeout)
|
|
3155
|
+
return memoryProviderTimeoutResponse();
|
|
3156
|
+
throw err;
|
|
3157
|
+
}
|
|
3158
|
+
}
|
|
3159
|
+
const computed = Array.isArray(vec) && vec.length > 0;
|
|
3160
|
+
body.embedding = computed ? vec : null;
|
|
3161
|
+
body.embeddingModel = computed ? getModelId() : null;
|
|
3162
|
+
// flair#2465: the refreshed vector gets a newly computed hash of the text
|
|
3163
|
+
// it embedded (null for an empty owner).
|
|
3164
|
+
body.embeddedContentHash = computed ? (embeddedTextHash({ ...(existingForSkill ?? {}), ...body }) ?? null) : null;
|
|
3165
|
+
body.updatedAt = new Date().toISOString();
|
|
3166
|
+
return null;
|
|
3167
|
+
};
|
|
3168
|
+
const readField = vectorFieldOver(existingForSkill);
|
|
3169
|
+
if (readField) {
|
|
3170
|
+
const denied = await storeVectorFor(readField);
|
|
3171
|
+
if (denied)
|
|
3172
|
+
return denied;
|
|
3173
|
+
}
|
|
3174
|
+
// Test-only: inert unless the fault-injection env opt-in is set and armed.
|
|
3175
|
+
// Holds the PATCH after its stored-row read and any embed, before the
|
|
3176
|
+
// conditional committed-row read and the write.
|
|
3177
|
+
const beforePatchWrite = txnPausePoint("memory-patch");
|
|
3178
|
+
if (beforePatchWrite)
|
|
3179
|
+
await beforePatchWrite;
|
|
3180
|
+
if (!readField && existingForSkill != null && !Object.prototype.hasOwnProperty.call(body, "embedding") &&
|
|
3181
|
+
Object.prototype.hasOwnProperty.call(body, embedTextField({ ...existingForSkill, ...body }))) {
|
|
3182
|
+
const committed = await databases.flair.Memory.get(String(existingForSkill.id), {});
|
|
3183
|
+
const committedField = committed ? vectorFieldOver(committed) : null;
|
|
3184
|
+
if (committedField) {
|
|
3185
|
+
const denied = await storeVectorFor(committedField);
|
|
3186
|
+
if (denied)
|
|
3187
|
+
return denied;
|
|
3188
|
+
}
|
|
3189
|
+
}
|
|
3190
|
+
// flair#2478: a stored row that has a token keeps it (the
|
|
3191
|
+
// body's own was stripped above); a legacy row without one, or a row this
|
|
3192
|
+
// PATCH creates (an admin or internal caller only), is given a fresh one
|
|
3193
|
+
// in this same write.
|
|
3194
|
+
const keptToken = storedInstanceToken(existingForSkill);
|
|
3195
|
+
if (keptToken === null)
|
|
3196
|
+
content.instanceToken = newInstanceToken();
|
|
3197
|
+
const expectedToken = keptToken ?? content.instanceToken;
|
|
3198
|
+
// flair#2573: the guard is notified after the commit (below) when the
|
|
3199
|
+
// staged vector or stamp differs from the row read in this transaction.
|
|
3200
|
+
const embeddingChanged = Object.prototype.hasOwnProperty.call(body, "embedding") &&
|
|
3201
|
+
!isDeepStrictEqual(body.embedding, existingForSkill?.embedding);
|
|
3202
|
+
const stampChanged = Object.prototype.hasOwnProperty.call(body, "embeddingModel") &&
|
|
3203
|
+
!isDeepStrictEqual(body.embeddingModel, existingForSkill?.embeddingModel);
|
|
3204
|
+
const stampNote = embeddingChanged || stampChanged
|
|
3205
|
+
? {
|
|
3206
|
+
stamp: (Object.prototype.hasOwnProperty.call(body, "embeddingModel")
|
|
3207
|
+
? body.embeddingModel : existingForSkill?.embeddingModel),
|
|
3208
|
+
previous: existingForSkill ?? null,
|
|
3209
|
+
}
|
|
3210
|
+
: null;
|
|
3211
|
+
// flair#2478 slice 1: the ordinary PATCH runs in the transaction this call
|
|
3212
|
+
// already owns (opened in patchLocked); super.patch joins it, so the row
|
|
3213
|
+
// write commits when this callback returns, before the write lock releases.
|
|
3214
|
+
// flair#2561: a Response from the storage layer is not reported
|
|
3215
|
+
// (storageResult); it is returned from this transaction as the
|
|
3216
|
+
// write_response_withheld refusal.
|
|
3217
|
+
const staged = structuredClone(content);
|
|
3218
|
+
const result = storageResult(await super.patch(staged, query));
|
|
3219
|
+
if (result instanceof Response)
|
|
3220
|
+
return result;
|
|
3221
|
+
return { result, staged, identity: { expectedToken }, rowId: existingForSkill?.id, stampNote };
|
|
3222
|
+
});
|
|
3223
|
+
// flair#2561: a refusal this path built is returned as built; a
|
|
3224
|
+
// successful Response is replaced by the write_response_withheld refusal
|
|
3225
|
+
// (writeResultResponse).
|
|
3226
|
+
if (patched instanceof Response)
|
|
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;
|
|
3233
|
+
// flair#2573: the row write has committed (its transaction returned it), so
|
|
3234
|
+
// the embedding-space guard is notified now, before the verification read:
|
|
3235
|
+
// a refused or unknown verification still leaves the guard told about the
|
|
3236
|
+
// vector or stamp this PATCH stored. The re-embed notifies in
|
|
3237
|
+
// reembedStoredRow and stages no note here.
|
|
3238
|
+
const stampNote = patched.stampNote;
|
|
3239
|
+
if (stampNote)
|
|
3240
|
+
noteWriteStamp(stampNote.stamp, stampNote.previous);
|
|
3241
|
+
// Verify the ordinary owned PATCH after a normal storage result; refusals
|
|
3242
|
+
// and storage Responses return above before this read. A successful re-embed is also
|
|
3243
|
+
// checked after its inner owned commit; refusals return above.
|
|
3244
|
+
// Compare ordinary PATCH fields against the staged write, including storage coercion.
|
|
3245
|
+
// Test-only: holds the PATCH after its commit, before the verification read.
|
|
3246
|
+
const verifyPause = txnPausePoint("memory-patch-verify");
|
|
3247
|
+
if (verifyPause)
|
|
3248
|
+
await verifyPause;
|
|
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);
|
|
3251
|
+
if (verified.unknown)
|
|
3252
|
+
return writeOutcomeUnknownFor(content?.id ?? this.getId?.());
|
|
3253
|
+
if (verified.mismatch)
|
|
3254
|
+
return storedRowChangedRefusal("Memory");
|
|
3255
|
+
// A verified re-embed answers with its own response (it declares no text
|
|
3256
|
+
// fields, so its check is the row's identity).
|
|
3257
|
+
if (patched.reembed)
|
|
3258
|
+
return patched.reembed;
|
|
3259
|
+
// As in put(): the verified row gates the answer; the response is the
|
|
3260
|
+
// PATCH's own result, never the stored row (see put()).
|
|
3261
|
+
return rowWriteResponse(patched.result, content?.id ?? this.getId?.() ?? patched.rowId, redactedValues, storedMemoryText(staged, suppliedText));
|
|
3262
|
+
}
|
|
3263
|
+
/**
|
|
3264
|
+
* flair#2478 slice 1 — the owner PUT runs under the per-id memory write lock
|
|
3265
|
+
* and its ordinary row write owns its transaction, so the read, the decision
|
|
3266
|
+
* and the COMMIT all happen before the lock releases (the protocol's rule).
|
|
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
|
|
3270
|
+
* that names no id is refused 400 before the lock; a store with no lock is
|
|
3271
|
+
* refused 503 `memory_lock_unavailable`. See resources/memory-write-lock.ts.
|
|
3272
|
+
*/
|
|
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);
|
|
3277
|
+
const ids = putLockIds(this, content);
|
|
3278
|
+
if (ids.length === 0)
|
|
3279
|
+
return memoryIdRequiredResponse();
|
|
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();
|
|
3293
|
+
return result;
|
|
3294
|
+
}, { phase: "put" });
|
|
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;
|
|
1250
3326
|
}
|
|
1251
|
-
|
|
1252
|
-
// patch() routes past put() (and thus past the SkillScan gate + forced
|
|
1253
|
-
// durability), so a skill write on this verb would land unscanned. There are
|
|
1254
|
-
// TWO ways a patch is a skill write, and the mint-time check saw only the first:
|
|
1255
|
-
// 1. the PATCH BODY carries the skill tag — rejectSkillWritePath(content).
|
|
1256
|
-
// 2. the STORED record is ALREADY a skill, and the body mutates `content`
|
|
1257
|
-
// (or anything else) WITHOUT re-declaring the tag. isSkillWrite(body) is
|
|
1258
|
-
// then false, so the pre-residual check let the edit land — a skill's
|
|
1259
|
-
// procedure could be rewritten with NO SkillScan (the residual). Fold
|
|
1260
|
-
// the existing record into the check: a patch to a row whose STORED tags
|
|
1261
|
-
// include `skill` is rejected the same as a mint-time skill write.
|
|
1262
|
-
// Skills are written via skill_store (→ Memory.post) or Memory.put; no
|
|
1263
|
-
// memory_patch tool exists and no internal path patches a skill row (hit-
|
|
1264
|
-
// tracking goes through table.put, not this override), so rejecting is safe.
|
|
1265
|
-
// flair#1965 r3 + flair#1960 r3: resolve the stored row ONCE, by the
|
|
1266
|
-
// URL-BOUND target id — refusing a body `id` that disagrees with the
|
|
1267
|
-
// address, and refusing a lookup that FAILS (a failed read is never "no
|
|
1268
|
-
// stored row"). This ONE resolved row drives BOTH rule sets: the skill-row
|
|
1269
|
-
// check and semantic-PATCH provenance decision below, AND the
|
|
1270
|
-
// originatorInstanceId create/update rule. The previous `.catch(() => null)`
|
|
1271
|
-
// turned a read ERROR into "no stored row"; isSemanticPatch returns false
|
|
1272
|
-
// for `null`, so the patch fell through to `super.patch()` as a
|
|
1273
|
-
// METADATA-ONLY write and kept a legacy stored blob — including a
|
|
1274
|
-
// caller-chosen `verified.timestamp` — in place, and (b) stamped a CREATE
|
|
1275
|
-
// over a row that actually exists. See resources/originator-instance.ts's
|
|
1276
|
-
// resolveStoredRow.
|
|
1277
|
-
const resolvedStored = await resolveStoredRow(this, "Memory", content, () => super.get());
|
|
1278
|
-
if (resolvedStored.denial)
|
|
1279
|
-
return resolvedStored.denial;
|
|
1280
|
-
const existingForSkill = resolvedStored.row;
|
|
1281
|
-
const skillDenial = rejectSkillWritePath(content) ?? rejectSkillWritePath(existingForSkill);
|
|
1282
|
-
if (skillDenial)
|
|
1283
|
-
return skillDenial;
|
|
1284
|
-
// ── flair#1960 r2: a SEMANTIC patch re-stamps provenance ────────────────
|
|
1285
|
-
// patch() strips a caller-supplied `provenance` (above) so a body can never
|
|
1286
|
-
// SET a `verified.*` field, but stripping alone would leave the STORED blob
|
|
1287
|
-
// in place — including a legacy row whose `verified.timestamp` came from a
|
|
1288
|
-
// client `createdAt` before this release. A patch that changes the record's
|
|
1289
|
-
// content is a fresh authored write, so it re-stamps from the resolved auth
|
|
1290
|
-
// and ONE server clock read (never the caller's `createdAt`, never a carried-
|
|
1291
|
-
// forward stored value). A metadata-only patch (no semantic field changes)
|
|
1292
|
-
// keeps the stored, previously-stamped blob: no new content was authored, so
|
|
1293
|
-
// there is no new write to attribute. See resources/provenance.ts
|
|
1294
|
-
// (isSemanticPatch / MEMORY_SEMANTIC_FIELDS) for the field set.
|
|
1295
|
-
if (isSemanticPatch(content, existingForSkill, MEMORY_SEMANTIC_FIELDS)) {
|
|
1296
|
-
const ctx = this.getContext?.();
|
|
1297
|
-
const auth = await resolveAgentAuth(ctx);
|
|
1298
|
-
content.provenance = buildProvenance(auth, content.createdAt ?? existingForSkill?.createdAt, claimInputs);
|
|
1299
|
-
}
|
|
1300
|
-
// flair#1965 r2: a PATCH over an EXISTING row keeps the stored
|
|
1301
|
-
// originatorInstanceId (a body value is dropped); a PATCH whose URL target
|
|
1302
|
-
// has NO stored row is a CREATE when it reaches the table — Harper's patch
|
|
1303
|
-
// path has no existing-row requirement — so it must stamp the local id
|
|
1304
|
-
// rather than leave the new row un-stamped. Only an administrator's or a
|
|
1305
|
-
// trusted internal PATCH gets that far; the table guard
|
|
1306
|
-
// (resources/table-patch-policy.ts) refuses the rest. See
|
|
1307
|
-
// resources/originator-instance.ts.
|
|
1308
|
-
await applyOriginatorInstanceId(content, existingForSkill);
|
|
1309
|
-
// The receiver-side federation bookkeeping keeps its stored value (a patch
|
|
1310
|
-
// merges); a client body value is dropped.
|
|
1311
|
-
dropClientFederationBookkeeping(content);
|
|
1312
|
-
return super.patch(content, query);
|
|
3327
|
+
return skillWriteConflict("skill_head_moved");
|
|
1313
3328
|
}
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
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;
|
|
3344
|
+
}
|
|
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);
|
|
3353
|
+
const reembedding = content?.embedding === null && content?.embeddingModel === null;
|
|
3354
|
+
// flair#2141 S2: check the seed's fixed id against the operator-source
|
|
3355
|
+
// reservation (resources/seed-reservation.ts).
|
|
3356
|
+
const seedDenial = await refuseReservedSeedWrite("Memory", writeTargetIds(this, content), this.getContext?.());
|
|
3357
|
+
if (seedDenial)
|
|
3358
|
+
return seedDenial;
|
|
3359
|
+
const contentSuffixDenial = refuseContentSuffixId(writeTargetIds(this, content), query);
|
|
3360
|
+
if (contentSuffixDenial)
|
|
3361
|
+
return contentSuffixDenial;
|
|
3362
|
+
// Reindex bypass: an admin-only escape hatch that re-PUTs declared and named
|
|
3363
|
+
// retained fields (no updatedAt bump, no embedding regen, no safety rescan)
|
|
3364
|
+
// so Harper repopulates secondary indices. The row is built by
|
|
3365
|
+
// buildReindexRow, the path this branch shares with the MemoryReindex admin
|
|
3366
|
+
// endpoint's write-back. Other undeclared fields are stripped and
|
|
1325
3367
|
// an absent incarnation token is generated. Because this skips safety and
|
|
1326
3368
|
// auditability, it must be gated to admins. Internal calls (no auth
|
|
1327
3369
|
// context) pass through, matching the pattern used in delete().
|
|
1328
3370
|
if (content._reindex === true) {
|
|
3371
|
+
if (locked)
|
|
3372
|
+
throw uncheckedBodyRefusal("_reindex");
|
|
1329
3373
|
const ctx = this.getContext?.();
|
|
1330
3374
|
const request = ctx?.request ?? ctx;
|
|
1331
3375
|
const actorId = request?.tpsAgent;
|
|
1332
|
-
if (actorId && !(await
|
|
3376
|
+
if (actorId && !(await annotatedCallerIsAdmin(request))) {
|
|
1333
3377
|
return new Response(JSON.stringify({ error: "reindex_admin_only" }), {
|
|
1334
3378
|
status: 403,
|
|
1335
3379
|
headers: { "Content-Type": "application/json" },
|
|
1336
3380
|
});
|
|
1337
3381
|
}
|
|
1338
|
-
|
|
1339
|
-
//
|
|
1340
|
-
//
|
|
1341
|
-
//
|
|
1342
|
-
|
|
1343
|
-
//
|
|
1344
|
-
//
|
|
1345
|
-
|
|
1346
|
-
|
|
3382
|
+
// An UNRESOLVED caller (anonymous HTTP, or an identity that did not
|
|
3383
|
+
// resolve) may not reindex: it answers the same 401 an unresolved caller
|
|
3384
|
+
// gets on the ordinary write path (resources/owner-field-guard.ts). This
|
|
3385
|
+
// guard ran before the reindex branch on main; the read-first restructure
|
|
3386
|
+
// moved it inside the owned ordinary transaction, which the reindex branch
|
|
3387
|
+
// returns before, so re-assert it here. Internal callers (no auth context)
|
|
3388
|
+
// pass, as on the ordinary path.
|
|
3389
|
+
const reindexOwnerDenial = await guardOwnerFieldImmutable(this, () => super.get(), content, "agentId");
|
|
3390
|
+
if (reindexOwnerDenial)
|
|
3391
|
+
return reindexOwnerDenial;
|
|
1347
3392
|
// flair#1965 r3: resolve the stored row by the URL-BOUND target id (never a
|
|
1348
3393
|
// body id alone); a body id that disagrees with the address, or a lookup
|
|
1349
3394
|
// that FAILS, refuses the reindex. A reindex is a re-PUT of an EXISTING
|
|
@@ -1354,383 +3399,713 @@ export class Memory extends databases.flair.Memory {
|
|
|
1354
3399
|
if (resolvedReindex.denial)
|
|
1355
3400
|
return resolvedReindex.denial;
|
|
1356
3401
|
const reindexExisting = resolvedReindex.row;
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
message: "the _reindex re-PUT requires an existing stored row",
|
|
1361
|
-
}), { status: 404, headers: { "content-type": "application/json" } });
|
|
3402
|
+
const built = buildReindexRow(content, reindexExisting);
|
|
3403
|
+
if (!("row" in built)) {
|
|
3404
|
+
return new Response(JSON.stringify({ error: built.error, message: built.message }), { status: built.status, headers: { "content-type": "application/json" } });
|
|
1362
3405
|
}
|
|
1363
|
-
|
|
1364
|
-
//
|
|
1365
|
-
// the
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
// if this restore is removed.
|
|
1371
|
-
if (reindexExisting && typeof reindexExisting.provenance === "string") {
|
|
1372
|
-
content.provenance = reindexExisting.provenance;
|
|
3406
|
+
const reindexRow = built.row;
|
|
3407
|
+
// The URL-bound target id is the row this re-PUT lands on; stamp it when
|
|
3408
|
+
// the body omits it (the same carry the ordinary put path performs).
|
|
3409
|
+
const reindexTargetId = this.getId?.();
|
|
3410
|
+
if (reindexRow && typeof reindexRow === "object" && reindexRow.id == null &&
|
|
3411
|
+
(typeof reindexTargetId === "string" || typeof reindexTargetId === "number")) {
|
|
3412
|
+
reindexRow.id = reindexTargetId;
|
|
1373
3413
|
}
|
|
1374
|
-
// flair#
|
|
1375
|
-
//
|
|
1376
|
-
//
|
|
1377
|
-
//
|
|
1378
|
-
|
|
1379
|
-
//
|
|
1380
|
-
|
|
1381
|
-
//
|
|
1382
|
-
//
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
3414
|
+
// flair#2450: the re-PUT writes over the row read as `reindexExisting`.
|
|
3415
|
+
// Inside the write's transaction, confirm the COMMITTED row is still that
|
|
3416
|
+
// one — before the row is staged, and again before the commit
|
|
3417
|
+
// (confirmCommittedRow: the transaction is aborted and the staged row
|
|
3418
|
+
// discarded). A missing row or an identity change seen by either read is
|
|
3419
|
+
// refused with the named 409 stored_row_changed. Both reads use an explicit
|
|
3420
|
+
// fresh context, never a contextless one (see resources/write-back.ts).
|
|
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.
|
|
3425
|
+
const beforeReindex = txnPausePoint("memory-reindex-pre");
|
|
3426
|
+
if (beforeReindex)
|
|
3427
|
+
await beforeReindex;
|
|
3428
|
+
let reindexed;
|
|
3429
|
+
try {
|
|
3430
|
+
reindexed = await withOwnedTransaction(ctx, async (c) => {
|
|
3431
|
+
const confirmPause = txnPausePoint("memory-reindex");
|
|
3432
|
+
if (confirmPause)
|
|
3433
|
+
await confirmPause;
|
|
3434
|
+
const confirmed = await databases.flair.Memory.get(reindexExisting.id, {});
|
|
3435
|
+
if (!confirmed || !sameStoredRow(confirmed, reindexExisting))
|
|
3436
|
+
return storedRowChangedRefusal("Memory");
|
|
3437
|
+
const r = storageResult(await databases.flair.Memory.put(reindexRow, c));
|
|
3438
|
+
if (r instanceof Response)
|
|
3439
|
+
return r;
|
|
3440
|
+
// Test-only: holds the staged re-PUT before its commit, so a delete, a
|
|
3441
|
+
// purge or a same-id replace can commit in that window.
|
|
3442
|
+
const stagedPause = txnPausePoint("memory-reindex-staged");
|
|
3443
|
+
if (stagedPause)
|
|
3444
|
+
await stagedPause;
|
|
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;
|
|
3451
|
+
return r;
|
|
3452
|
+
});
|
|
1388
3453
|
}
|
|
1389
|
-
|
|
3454
|
+
catch (err) {
|
|
3455
|
+
if (err instanceof CommittedRowChanged)
|
|
3456
|
+
return storedRowChangedRefusal("Memory");
|
|
3457
|
+
throw err;
|
|
3458
|
+
}
|
|
3459
|
+
// flair#2561: a refusal this path built is returned as built; a
|
|
3460
|
+
// successful Response is replaced by the write_response_withheld
|
|
3461
|
+
// refusal (writeResultResponse).
|
|
3462
|
+
if (reindexed instanceof Response)
|
|
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");
|
|
1390
3483
|
noteMemoryUpsert(content);
|
|
1391
|
-
|
|
1392
|
-
return reindexed;
|
|
3484
|
+
return rowWriteResponse(reindexed, reindexRow?.id, 0);
|
|
1393
3485
|
}
|
|
1394
|
-
//
|
|
1395
|
-
//
|
|
1396
|
-
//
|
|
1397
|
-
//
|
|
3486
|
+
// flair#2441 + flair#2478 slice 1: a test-only pause of this PUT before its
|
|
3487
|
+
// transaction opens (other writers, background ones included, can still
|
|
3488
|
+
// change the row meanwhile); then the ordinary write runs in ONE owned
|
|
3489
|
+
// transaction whose FIRST operation is the authoritative stored read —
|
|
3490
|
+
// Harper orders a transaction by its first read, so the read and every
|
|
3491
|
+
// decision drawn from it share this write's commit and commit before the
|
|
3492
|
+
// write lock releases. A composed put, below, joins its caller's transaction
|
|
3493
|
+
// instead.
|
|
3494
|
+
const beforePut = txnPausePoint("memory-put-pre");
|
|
3495
|
+
if (beforePut)
|
|
3496
|
+
await beforePut;
|
|
1398
3497
|
const ctx = this.getContext?.();
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
|
|
1457
|
-
|
|
1458
|
-
// the visibility default (Layer 1 part A): patchRecord/supersede-
|
|
1459
|
-
// close all route through put() with a MERGED
|
|
1460
|
-
// `{...existing, ...patch}` payload, and must never have their stored
|
|
1461
|
-
// visibility overwritten by a default recomputed from that merged content
|
|
1462
|
-
// — only a genuinely NEW id gets the default stamped.
|
|
1463
|
-
// The row is resolved by the URL-BOUND target id, never the request body's
|
|
1464
|
-
// `id`: Harper writes to the URL target and rewrites the row's primary key
|
|
1465
|
-
// to it, so a body id names a row this PUT does NOT land on. A body id that
|
|
1466
|
-
// disagrees with the target, or a lookup that FAILS, refuses the write — a
|
|
1467
|
-
// failed read must never look like "no record". See
|
|
1468
|
-
// resources/originator-instance.ts's resolveStoredRow.
|
|
1469
|
-
const resolvedExisting = await resolveStoredRow(this, "Memory", content, () => super.get());
|
|
1470
|
-
if (resolvedExisting.denial)
|
|
1471
|
-
return resolvedExisting.denial;
|
|
1472
|
-
const preExisting = resolvedExisting.row;
|
|
1473
|
-
// Preserve stored visibility on updates before applying write policy
|
|
1474
|
-
// (only the two writable values; the guards below see the result).
|
|
1475
|
-
if (preExisting &&
|
|
1476
|
-
(content.visibility === undefined || content.visibility === null) &&
|
|
1477
|
-
(preExisting.visibility === PRIVATE_VISIBILITY || preExisting.visibility === SHARED_VISIBILITY)) {
|
|
1478
|
-
content.visibility = preExisting.visibility;
|
|
1479
|
-
}
|
|
1480
|
-
// ─── Default visibility (durability-keyed) — Layer 1, part A ────────────
|
|
1481
|
-
// Explicit visibility on the write ALWAYS overrides; only stamp the
|
|
1482
|
-
// default when the caller left it unset AND this is a fresh record.
|
|
1483
|
-
// permanent|persistent → shared; standard|ephemeral|absent → private.
|
|
1484
|
-
// ── flair#1009: refuse an unrecognised visibility BEFORE defaulting ──
|
|
1485
|
-
// isPrivateVisibility() is an exact match on "private", so on the READ
|
|
1486
|
-
// side every other value (a typo, a wrong case, a retired tier like
|
|
1487
|
-
// "office") resolves to non-private and is readable by every agent on the
|
|
1488
|
-
// instance. #1006 closed that at the CLI flag and the MCP tool argument;
|
|
1489
|
-
// REST and the in-process API reach here without passing either.
|
|
1490
|
-
//
|
|
1491
|
-
// Refusing, rather than dropping the key: dropping it falls through to the
|
|
1492
|
-
// durability-keyed default below, which for a permanent or persistent
|
|
1493
|
-
// write is "shared" - the same widening, arrived at silently. A misspelled
|
|
1494
|
-
// argument must not decide who can read a memory.
|
|
1495
|
-
{
|
|
1496
|
-
const visibilityError = assertValidVisibility(content.visibility);
|
|
1497
|
-
if (visibilityError) {
|
|
1498
|
-
return new Response(JSON.stringify({ error: "invalid_visibility", message: visibilityError }), { status: 400, headers: { "content-type": "application/json" } });
|
|
1499
|
-
}
|
|
1500
|
-
}
|
|
1501
|
-
// ── flair#1257: ephemeral memories are private-only (hard precondition) ──
|
|
1502
|
-
// Same rule as post(), with one PUT-specific wrinkle: an update payload
|
|
1503
|
-
// may omit durability entirely (put() stamps no durability default), so
|
|
1504
|
-
// `PUT /Memory/<id> {"visibility":"shared"}` against a stored ephemeral
|
|
1505
|
-
// row names no durability of its own — the EFFECTIVE durability is the
|
|
1506
|
-
// pre-existing row's, and the flip must refuse just like a fresh
|
|
1507
|
-
// ephemeral+shared create. An explicit durability on the write wins: a
|
|
1508
|
-
// write that promotes the row OUT of ephemeral (e.g. distillation lifting
|
|
1509
|
-
// it to persistent, #1205) while sharing it is a legitimate promotion,
|
|
1510
|
-
// not an ephemeral share. preExisting was fetched above.
|
|
1511
|
-
{
|
|
1512
|
-
const effectiveDurability = content.durability ?? preExisting?.durability;
|
|
1513
|
-
const tierError = assertVisibilityAllowedForDurability(effectiveDurability, content.visibility);
|
|
1514
|
-
if (tierError) {
|
|
1515
|
-
return new Response(JSON.stringify({ error: "invalid_visibility_for_durability", message: tierError }), { status: 400, headers: { "content-type": "application/json" } });
|
|
1516
|
-
}
|
|
1517
|
-
}
|
|
1518
|
-
if (!preExisting && (content.visibility === undefined || content.visibility === null)) {
|
|
1519
|
-
content.visibility = defaultVisibilityForDurability(content.durability);
|
|
1520
|
-
}
|
|
1521
|
-
// ── flair#1257 slice 3: stamp the ephemeral TTL on the PUT path too ──────
|
|
1522
|
-
// post() has stamped expiresAt for ephemeral rows since the tier shipped,
|
|
1523
|
-
// but put() — the verb the continuity capture hook actually writes with
|
|
1524
|
-
// (`PUT /Memory/<id>`, packages/flair-mcp/src/continuity-capture-hook.ts)
|
|
1525
|
-
// — never did. MemoryMaintenance's reap keys on expiresAt (expired =
|
|
1526
|
-
// expiresAt < now), so hook-written journal rows carried NO expiry and
|
|
1527
|
-
// the tier's load-bearing 24h containment bound (the exposure window the
|
|
1528
|
-
// #1257 rulings cite) silently never engaged on the real write path.
|
|
1529
|
-
// Effective durability = the write's, else the pre-existing row's (same
|
|
1530
|
-
// resolution the visibility guard above uses). A pre-existing expiry is
|
|
1531
|
-
// carried forward, never re-stamped — an update must not extend the
|
|
1532
|
-
// exposure window; an explicit caller-provided expiresAt always wins.
|
|
1533
|
-
{
|
|
1534
|
-
const effectiveDurability = content.durability ?? preExisting?.durability;
|
|
1535
|
-
if (effectiveDurability === "ephemeral" && !content.expiresAt) {
|
|
1536
|
-
if (preExisting?.expiresAt) {
|
|
1537
|
-
content.expiresAt = preExisting.expiresAt;
|
|
3498
|
+
// A caller that composes this put into its OWN open write transaction
|
|
3499
|
+
// (withComposedWriteTransaction: manual promotion, whose verdict stamp must
|
|
3500
|
+
// commit or abort with this row, flair#2354) is joined, not detached: the
|
|
3501
|
+
// caller owns the commit, which lands after this lock is released, and there
|
|
3502
|
+
// is no post-commit verification here (manual promotion's stamp reads the
|
|
3503
|
+
// row in that transaction and refuses when there is none; it does not
|
|
3504
|
+
// compare the written identity). Every other ordinary put owns its
|
|
3505
|
+
// transaction, as the `_reindex` re-PUT above does.
|
|
3506
|
+
const composed = !locked && composesCallerWrite(ctx);
|
|
3507
|
+
let putResult;
|
|
3508
|
+
// flair#2467: the post-redaction text fields this write stages, for the response.
|
|
3509
|
+
let putStaged = {};
|
|
3510
|
+
let putGrantedClosed = null;
|
|
3511
|
+
try {
|
|
3512
|
+
const writeScope = locked
|
|
3513
|
+
? (cx, fn) => locked.admission.join(cx, fn)
|
|
3514
|
+
: composed ? withSharedWriteTransaction : withOwnedTransaction;
|
|
3515
|
+
putResult = await writeScope(ctx, async (c) => {
|
|
3516
|
+
// The authoritative stored read: the FIRST operation of an ordinary PUT's
|
|
3517
|
+
// owned transaction (a composed put runs it in its caller's transaction,
|
|
3518
|
+
// which may already have read). It reads by the URL-BOUND target id (a
|
|
3519
|
+
// body id that disagrees with the address, or a lookup that FAILS, is
|
|
3520
|
+
// refused; a failed read is never read as "no stored row").
|
|
3521
|
+
const resolvedExisting = await resolveStoredRow(this, "Memory", content, () => super.get(), c);
|
|
3522
|
+
if (resolvedExisting.denial)
|
|
3523
|
+
return resolvedExisting.denial;
|
|
3524
|
+
const preExisting = resolvedExisting.row;
|
|
3525
|
+
// Authorize inside the transaction: the owner-field then authority guards
|
|
3526
|
+
// read the stored row from this transaction's own snapshot.
|
|
3527
|
+
const __ownerDenial = await guardOwnerFieldImmutable(this, () => super.get(), content, "agentId");
|
|
3528
|
+
if (__ownerDenial)
|
|
3529
|
+
return __ownerDenial;
|
|
3530
|
+
const authorityDenial = await guardAuthorityFields(() => super.get(), content, "Memory");
|
|
3531
|
+
if (authorityDenial)
|
|
3532
|
+
return authorityDenial;
|
|
3533
|
+
// Create/update ownership (same rule as post): a non-admin agent may only
|
|
3534
|
+
// write memories it owns, via resolveAgentAuth (gate annotation), not
|
|
3535
|
+
// context.user.username (the dormant-de-elevation fallback is "admin").
|
|
3536
|
+
// The _reindex admin path above bypasses this.
|
|
3537
|
+
let auth;
|
|
3538
|
+
{
|
|
3539
|
+
auth = await resolveAgentAuth(ctx);
|
|
3540
|
+
// Anonymous HTTP must NOT write (non-rejecting gate → self-enforce here).
|
|
3541
|
+
if (auth.kind === "anonymous") {
|
|
3542
|
+
return UNAUTH();
|
|
3543
|
+
}
|
|
3544
|
+
// flair#1383 — same write-path refuse as post().
|
|
3545
|
+
{
|
|
3546
|
+
const stale = refuseStaleClientWrite(ctx?.request, content);
|
|
3547
|
+
if (stale)
|
|
3548
|
+
return stale;
|
|
3549
|
+
}
|
|
3550
|
+
stripClientVersionPassthrough(content);
|
|
3551
|
+
// No-forge attribution — mode/field drawn from RECORD_TYPES.Memory,
|
|
3552
|
+
// same rule as post(). "validate-truthy" (see record-type-kit.ts's
|
|
3553
|
+
// stampAttribution doc).
|
|
3554
|
+
const attr = stampAttribution(auth, content, RECORD_TYPES.Memory.ownerField, RECORD_TYPES.Memory.attribution.put, "forbidden: cannot write memory owned by another agent");
|
|
3555
|
+
if (attr.denied)
|
|
3556
|
+
return attr.denied;
|
|
1538
3557
|
}
|
|
1539
|
-
|
|
1540
|
-
|
|
1541
|
-
|
|
3558
|
+
// flair#2561: the fields this request supplies that `stored` can report —
|
|
3559
|
+
// its string-valued text fields and, for a skill, the skill fields it
|
|
3560
|
+
// supplies (flair#2575) — read before the stored row or a skill predecessor
|
|
3561
|
+
// is merged into the body; `stored` reports only these. Redaction runs after
|
|
3562
|
+
// prepareSkillBody (below) and keeps a string a string, so reading them
|
|
3563
|
+
// first names the same fields.
|
|
3564
|
+
const suppliedText = suppliedStoredTextFields(content);
|
|
3565
|
+
canonicalizeSupersedes(content);
|
|
3566
|
+
// flair#2573: an empty `embedding` in the body is an omitted one (see post()).
|
|
3567
|
+
if (isEmptyEmbedding(content?.embedding))
|
|
3568
|
+
delete content.embedding;
|
|
3569
|
+
const requestedPayload = { ...content };
|
|
3570
|
+
// The visibility the caller named, before any merge, carry or default fills it.
|
|
3571
|
+
const requestedVisibility = content?.visibility;
|
|
3572
|
+
const urlTargetId = this.getId?.();
|
|
3573
|
+
if (content && typeof content === "object" && content.id == null &&
|
|
3574
|
+
(typeof urlTargetId === "string" || typeof urlTargetId === "number")) {
|
|
3575
|
+
content.id = urlTargetId;
|
|
1542
3576
|
}
|
|
1543
|
-
|
|
1544
|
-
|
|
1545
|
-
|
|
1546
|
-
|
|
1547
|
-
|
|
1548
|
-
|
|
1549
|
-
|
|
1550
|
-
|
|
1551
|
-
|
|
1552
|
-
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
|
|
1559
|
-
|
|
1560
|
-
|
|
1561
|
-
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
|
|
1565
|
-
|
|
1566
|
-
|
|
1567
|
-
|
|
1568
|
-
|
|
3577
|
+
// flair#2465: as in post(), a body that omits `embedding` can have a stored
|
|
3578
|
+
// vector carried in by prepareSkillBody, with the hash it retained for it.
|
|
3579
|
+
const putOmitsEmbedding = content?.embedding === undefined;
|
|
3580
|
+
// flair#2573 slice 2: did the CALLER supply a non-null embedding, and/or an
|
|
3581
|
+
// `embeddingModel` stamp, that differs from the stored row's? Captured
|
|
3582
|
+
// before prepareSkillBody can merge a stored row's vector into the body.
|
|
3583
|
+
const { vector: putSuppliedVector, stamp: putSuppliedStamp } = suppliedVectorFlags(content, preExisting);
|
|
3584
|
+
const preparedSkill = await prepareSkillBody(content, preExisting, auth);
|
|
3585
|
+
if (preparedSkill instanceof Response)
|
|
3586
|
+
return preparedSkill;
|
|
3587
|
+
content = preparedSkill.content;
|
|
3588
|
+
const operatorSeed = isOperatorSeedPut(ctx, auth, writeTargetIds(this, content));
|
|
3589
|
+
let redactedValues = operatorSeed ? 0 : redactMemoryWrite(content).count;
|
|
3590
|
+
// Duplicate top-level metadata keys are refused; otherwise redact name/description and tags.
|
|
3591
|
+
redactedValues += redactSkillWrite(content);
|
|
3592
|
+
const putCarriedVector = putOmitsEmbedding && Array.isArray(content?.embedding) && content.embedding.length > 0;
|
|
3593
|
+
const putCarriedHash = putCarriedVector ? (content.embeddedContentHash ?? null) : null;
|
|
3594
|
+
// flair#744 slice A: citation-on-write — same consume-and-strip
|
|
3595
|
+
// discipline as post() above. Stripped before persistence so it is
|
|
3596
|
+
// never stored on the row; recorded post-commit
|
|
3597
|
+
// below only when present.
|
|
3598
|
+
const usedMemoryIds = content?.usedMemoryIds;
|
|
3599
|
+
if (content && typeof content === "object")
|
|
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");
|
|
3605
|
+
// ── flair#1238: refuse an unrecognised durability (mirrors post()) ──
|
|
3606
|
+
// put() is the other HTTP-reachable write path (fresh create via CLI, and
|
|
3607
|
+
// the update/patch path). Same guard as post(): a present-but-unknown
|
|
3608
|
+
// durability is refused with 400; absent is accepted.
|
|
3609
|
+
{
|
|
3610
|
+
const durabilityError = assertValidDurability(content.durability);
|
|
3611
|
+
if (durabilityError) {
|
|
3612
|
+
return new Response(JSON.stringify({ error: "invalid_durability", message: durabilityError }), { status: 400, headers: { "content-type": "application/json" } });
|
|
3613
|
+
}
|
|
1569
3614
|
}
|
|
1570
|
-
|
|
1571
|
-
|
|
1572
|
-
|
|
1573
|
-
//
|
|
1574
|
-
|
|
1575
|
-
|
|
1576
|
-
|
|
1577
|
-
|
|
1578
|
-
|
|
1579
|
-
|
|
1580
|
-
|
|
1581
|
-
|
|
1582
|
-
|
|
1583
|
-
|
|
1584
|
-
|
|
1585
|
-
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
|
|
1592
|
-
|
|
1593
|
-
|
|
1594
|
-
|
|
1595
|
-
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
|
|
1599
|
-
|
|
1600
|
-
|
|
1601
|
-
|
|
1602
|
-
|
|
1603
|
-
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
|
|
1608
|
-
|
|
1609
|
-
|
|
1610
|
-
|
|
1611
|
-
|
|
1612
|
-
|
|
1613
|
-
|
|
1614
|
-
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
|
|
1618
|
-
|
|
1619
|
-
|
|
1620
|
-
|
|
1621
|
-
|
|
1622
|
-
|
|
1623
|
-
|
|
1624
|
-
|
|
1625
|
-
|
|
1626
|
-
|
|
1627
|
-
|
|
1628
|
-
|
|
1629
|
-
|
|
1630
|
-
|
|
3615
|
+
// ── flair#1542: skills are forced durability=persistent (mirrors post()) ──
|
|
3616
|
+
// put() stamps no durability default (updates carry the pre-existing tier),
|
|
3617
|
+
// so this runs on the raw write value: a skill-tagged write with an explicit
|
|
3618
|
+
// ephemeral/session tier is rejected, and every other value (including an
|
|
3619
|
+
// absent one) is forced to "persistent" so the reaper never archives a skill.
|
|
3620
|
+
{
|
|
3621
|
+
const skillDurabilityDenial = enforceSkillDurability(content);
|
|
3622
|
+
if (skillDurabilityDenial)
|
|
3623
|
+
return skillDurabilityDenial;
|
|
3624
|
+
}
|
|
3625
|
+
const now = new Date().toISOString();
|
|
3626
|
+
content.updatedAt = now;
|
|
3627
|
+
// Set defaults that post() sets — put() is also used for new records via CLI
|
|
3628
|
+
content.archived = content.archived ?? false;
|
|
3629
|
+
content.createdAt = content.createdAt ?? now;
|
|
3630
|
+
// Preserve stored visibility on updates before applying write policy
|
|
3631
|
+
// (only the two writable values; the guards below see the result).
|
|
3632
|
+
if (preExisting &&
|
|
3633
|
+
(content.visibility === undefined || content.visibility === null) &&
|
|
3634
|
+
(preExisting.visibility === PRIVATE_VISIBILITY || preExisting.visibility === SHARED_VISIBILITY)) {
|
|
3635
|
+
content.visibility = preExisting.visibility;
|
|
3636
|
+
}
|
|
3637
|
+
// ─── Default visibility (durability-keyed) — Layer 1, part A ────────────
|
|
3638
|
+
// Explicit visibility on the write ALWAYS overrides; only stamp the
|
|
3639
|
+
// default when the caller left it unset AND this is a fresh record.
|
|
3640
|
+
// permanent|persistent → shared; standard|ephemeral|absent → private.
|
|
3641
|
+
// ── flair#1009: refuse an unrecognised visibility BEFORE defaulting ──
|
|
3642
|
+
// isPrivateVisibility() is an exact match on "private", so on the READ
|
|
3643
|
+
// side every other value (a typo, a wrong case, a retired tier like
|
|
3644
|
+
// "office") resolves to non-private and is readable by every agent on the
|
|
3645
|
+
// instance. #1006 closed that at the CLI flag and the MCP tool argument;
|
|
3646
|
+
// REST and the in-process API reach here without passing either.
|
|
3647
|
+
//
|
|
3648
|
+
// Refusing, rather than dropping the key: dropping it falls through to the
|
|
3649
|
+
// durability-keyed default below, which for a permanent or persistent
|
|
3650
|
+
// write is "shared" - the same widening, arrived at silently. A misspelled
|
|
3651
|
+
// argument must not decide who can read a memory.
|
|
3652
|
+
{
|
|
3653
|
+
const visibilityError = assertValidVisibility(content.visibility);
|
|
3654
|
+
if (visibilityError) {
|
|
3655
|
+
return new Response(JSON.stringify({ error: "invalid_visibility", message: visibilityError }), { status: 400, headers: { "content-type": "application/json" } });
|
|
3656
|
+
}
|
|
3657
|
+
}
|
|
3658
|
+
// ── flair#1257: ephemeral memories are private-only (hard precondition) ──
|
|
3659
|
+
// Same rule as post(), with one PUT-specific wrinkle: an update payload
|
|
3660
|
+
// may omit durability entirely (put() stamps no durability default), so
|
|
3661
|
+
// `PUT /Memory/<id> {"visibility":"shared"}` against a stored ephemeral
|
|
3662
|
+
// row names no durability of its own — the EFFECTIVE durability is the
|
|
3663
|
+
// pre-existing row's, and the flip must refuse just like a fresh
|
|
3664
|
+
// ephemeral+shared create. An explicit durability on the write wins: a
|
|
3665
|
+
// write that promotes the row OUT of ephemeral (e.g. distillation lifting
|
|
3666
|
+
// it to persistent, #1205) while sharing it is a legitimate promotion,
|
|
3667
|
+
// not an ephemeral share. preExisting was fetched above.
|
|
3668
|
+
{
|
|
3669
|
+
const effectiveDurability = content.durability ?? preExisting?.durability;
|
|
3670
|
+
const tierError = assertVisibilityAllowedForDurability(effectiveDurability, content.visibility);
|
|
3671
|
+
if (tierError) {
|
|
3672
|
+
return new Response(JSON.stringify({ error: "invalid_visibility_for_durability", message: tierError }), { status: 400, headers: { "content-type": "application/json" } });
|
|
3673
|
+
}
|
|
3674
|
+
}
|
|
3675
|
+
if (!preExisting && (content.visibility === undefined || content.visibility === null)) {
|
|
3676
|
+
content.visibility = defaultVisibilityForDurability(content.durability);
|
|
3677
|
+
}
|
|
3678
|
+
const expiryError = stampEphemeralExpiry(content, preExisting);
|
|
3679
|
+
if (expiryError)
|
|
3680
|
+
return Response.json({ error: "invalid_expiry", message: expiryError }, { status: 400 });
|
|
3681
|
+
// supersedes: optional reference to the ID of the memory this one
|
|
3682
|
+
// replaces. Validates shape + cross-agent-write authorization (shared
|
|
3683
|
+
// with post() — see validateAndAuthorizeSupersedes doc for why PUT needs
|
|
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`).
|
|
3688
|
+
const supersede = await validateAndAuthorizeSupersedes(content, auth, ctx, preExisting, requestedVisibility);
|
|
3689
|
+
if (supersede.denial)
|
|
3690
|
+
return supersede.denial;
|
|
3691
|
+
if (content.supersedes && !content.validFrom) {
|
|
3692
|
+
content.validFrom = content.createdAt;
|
|
3693
|
+
}
|
|
3694
|
+
// attention-plane vocabulary gate (flair#675) — see post()'s comment above.
|
|
3695
|
+
const entitiesError = invalidEntitiesResponse(content.entities);
|
|
3696
|
+
if (entitiesError)
|
|
3697
|
+
return entitiesError;
|
|
3698
|
+
// Content safety scan on updated content + summary.
|
|
3699
|
+
if (content.content || content.summary) {
|
|
3700
|
+
const safety = scanFields(content, ["content", "summary"]);
|
|
3701
|
+
if (!safety.safe) {
|
|
3702
|
+
if (isStrictMode()) {
|
|
3703
|
+
return new Response(JSON.stringify({
|
|
3704
|
+
error: "content_safety_violation",
|
|
3705
|
+
flags: safety.flags,
|
|
3706
|
+
message: "Content flagged for potential prompt injection.",
|
|
3707
|
+
}), { status: 400, headers: { "Content-Type": "application/json" } });
|
|
3708
|
+
}
|
|
3709
|
+
content._safetyFlags = safety.flags;
|
|
3710
|
+
}
|
|
3711
|
+
else {
|
|
3712
|
+
// Clear previous flags if both fields are now clean
|
|
3713
|
+
content._safetyFlags = null;
|
|
3714
|
+
}
|
|
3715
|
+
}
|
|
3716
|
+
// ── flair#1542: SkillScan gate BEFORE the embed (mirrors post()) ──
|
|
3717
|
+
// Every skill-tagged write is statically scanned before any embedding is
|
|
3718
|
+
// computed, so a rejected write pays no embed. Fail-closed on high/critical;
|
|
3719
|
+
// allow-with-flag on medium. Non-skill writes are a no-op.
|
|
3720
|
+
{
|
|
3721
|
+
const skillScanDenial = skillScanGate(content);
|
|
3722
|
+
if (skillScanDenial)
|
|
3723
|
+
return skillScanDenial;
|
|
3724
|
+
}
|
|
3725
|
+
{
|
|
3726
|
+
const skillSourceDenial = refuseSkillWriteSource(content);
|
|
3727
|
+
if (skillSourceDenial)
|
|
3728
|
+
return skillSourceDenial;
|
|
3729
|
+
}
|
|
3730
|
+
// Server-side conservative-duplicate gate (memory-integrity fix). PUT is
|
|
3731
|
+
// an upsert: only run the gate for a FRESH create (target id does not yet
|
|
3732
|
+
// exist) that is NOT a supersede-link write. An update of an EXISTING id
|
|
3733
|
+
// (memory_update's default same-id overwrite path) is an intentional,
|
|
3734
|
+
// explicit overwrite, and a supersede-link write is an intentional
|
|
3735
|
+
// version-link — neither is an ambiguous "is this a duplicate of
|
|
3736
|
+
// something else" write, so both are dedup-bypassed automatically, no
|
|
3737
|
+
// separate flag needed. NEVER suppresses the write either way.
|
|
3738
|
+
// flair#2573 slice 2: a non-admin write's vector and stamp that differ
|
|
3739
|
+
// from the stored row's are discarded here, after redaction and before
|
|
3740
|
+
// the dedup gate and the embed step (see post()).
|
|
3741
|
+
if (putSuppliedVector || putSuppliedStamp) {
|
|
3742
|
+
discardSuppliedVector(content, auth, { vector: putSuppliedVector, stamp: putSuppliedStamp }, preExisting);
|
|
3743
|
+
}
|
|
3744
|
+
// flair#2573: an empty vector that reaches this point is no vector (see post()).
|
|
3745
|
+
normalizeEmptyEmbedding(content);
|
|
3746
|
+
// flair#2465: did the caller supply a vector? See post().
|
|
3747
|
+
const embeddingSupplied = Array.isArray(content.embedding) && content.embedding.length > 0;
|
|
3748
|
+
let dedupMatch = null;
|
|
3749
|
+
try {
|
|
3750
|
+
if (content.supersedes) {
|
|
3751
|
+
delete content.dedup;
|
|
3752
|
+
delete content.dedupThreshold;
|
|
3753
|
+
delete content.lexicalThreshold;
|
|
3754
|
+
}
|
|
3755
|
+
else if (content.id) {
|
|
3756
|
+
if (!preExisting) {
|
|
3757
|
+
dedupMatch = await runDedupGate(ctx, content, true);
|
|
3758
|
+
}
|
|
3759
|
+
else {
|
|
3760
|
+
delete content.dedup;
|
|
3761
|
+
delete content.dedupThreshold;
|
|
3762
|
+
delete content.lexicalThreshold;
|
|
3763
|
+
}
|
|
3764
|
+
}
|
|
3765
|
+
else {
|
|
3766
|
+
dedupMatch = await runDedupGate(ctx, content, true);
|
|
3767
|
+
}
|
|
3768
|
+
}
|
|
3769
|
+
catch (err) {
|
|
3770
|
+
if (err instanceof MemoryProviderTimeout)
|
|
3771
|
+
return memoryProviderTimeoutResponse();
|
|
3772
|
+
throw err;
|
|
3773
|
+
}
|
|
3774
|
+
// Re-generate embedding if content changed (no-op if the dedup gate above
|
|
3775
|
+
// already computed one for this content). flair#504 Phase 2: 'document'
|
|
3776
|
+
const embedText = skillEmbedText(content);
|
|
3777
|
+
if (embedText && !content.embedding) {
|
|
3778
|
+
let vec;
|
|
3779
|
+
try {
|
|
3780
|
+
vec = await embedUnderLock(embedText);
|
|
3781
|
+
}
|
|
3782
|
+
catch (err) {
|
|
3783
|
+
if (err instanceof MemoryProviderTimeout)
|
|
3784
|
+
return memoryProviderTimeoutResponse();
|
|
3785
|
+
throw err;
|
|
3786
|
+
}
|
|
3787
|
+
if (vec) {
|
|
3788
|
+
content.embedding = vec;
|
|
3789
|
+
content.embeddingModel = getModelId();
|
|
3790
|
+
}
|
|
3791
|
+
}
|
|
3792
|
+
// If archiving, record who + when
|
|
3793
|
+
if (content.archived === true && !content.archivedAt) {
|
|
3794
|
+
content.archivedAt = now;
|
|
3795
|
+
// archivedBy should be set by the caller (CLI stamps req.tpsAgent via query param)
|
|
3796
|
+
}
|
|
3797
|
+
// ── flair#1940 slice 1 (A1'): the host pointer is NOT a Memory attribute. ──
|
|
3798
|
+
// Identical rule to post(): consume the write-body-only pointer inputs OUT
|
|
3799
|
+
// of the row, validate them, and build the pointer row written alongside
|
|
3800
|
+
// the Memory row below. A client-supplied `hostSourceVisibility` is dropped
|
|
3801
|
+
// (never read). Reject, never truncate/coerce.
|
|
3802
|
+
const pointerInputs = extractPointerInputs(content);
|
|
3803
|
+
// A1-iv item 3: strip server-stamped fields (a client may not set them).
|
|
3804
|
+
stripServerStampedFields(content);
|
|
3805
|
+
// flair#2465: a vector the server computed here gets a newly computed hash
|
|
3806
|
+
// (see post()). A skill vector prepareSkillBody carried in keeps the hash it
|
|
3807
|
+
// retained (possibly null) — including a superseding create at a new id,
|
|
3808
|
+
// which has no stored row of its own. Any other put that does not compute a
|
|
3809
|
+
// vector (one accepted from the caller, an echoed one, or a failed embed)
|
|
3810
|
+
// retains this row's stored hash, if any; `preExisting` is the row this
|
|
3811
|
+
// owned transaction read first (flair#2478). A retained hash is a preserved
|
|
3812
|
+
// value that may describe an earlier server-computed vector, not
|
|
3813
|
+
// necessarily the vector stored now. One that differs from the current
|
|
3814
|
+
// text's expected hash re-queues the row in the stamp migration; with no
|
|
3815
|
+
// stored hash the comparison is skipped.
|
|
3816
|
+
content.embeddedContentHash = !embeddingSupplied && Array.isArray(content.embedding) && content.embedding.length > 0
|
|
3817
|
+
? (embeddedTextHash(content) ?? null)
|
|
3818
|
+
: putCarriedVector ? putCarriedHash : (preExisting?.embeddedContentHash ?? null);
|
|
3819
|
+
// A1-iv item 1: PRESERVE the existing row's incarnation token on an update,
|
|
3820
|
+
// else generate one (a fresh create via put).
|
|
3821
|
+
stampInstanceToken(content, preExisting);
|
|
3822
|
+
// A1'' item 5: a partial PUT (one that omits `visibility`, e.g. a
|
|
3823
|
+
// memory_update full put) must stamp scopeAtWrite from the record's
|
|
3824
|
+
// EFFECTIVE visibility — the existing row's when the body omits it — not
|
|
3825
|
+
// from an undefined body value that would wrongly yield author-only.
|
|
3826
|
+
const effectiveVisibility = content.visibility ?? preExisting?.visibility;
|
|
3827
|
+
// A partial PUT carries the stored visibility it read at the start of the
|
|
3828
|
+
// request (one carry, above, before the write-policy guards).
|
|
3829
|
+
// Adjudication B (round 4): load the stored pointer row so an echo of it is
|
|
3830
|
+
// recognised and not replaced (see buildPointerForWrite).
|
|
3831
|
+
let storedPointer = null;
|
|
3832
|
+
if (content.id &&
|
|
3833
|
+
pointerInputs.hostSource !== undefined &&
|
|
3834
|
+
pointerInputs.hostSource !== null &&
|
|
3835
|
+
pointerInputs.hostSourceScope === undefined) {
|
|
3836
|
+
storedPointer = await loadStoredPointer(content.id);
|
|
3837
|
+
}
|
|
3838
|
+
const pointer = buildPointerForWrite({ inputs: pointerInputs, memoryId: content.id ?? "", visibility: effectiveVisibility, auth, memoryInstanceToken: content.instanceToken, storedPointer });
|
|
3839
|
+
if (pointer.denial)
|
|
3840
|
+
return pointer.denial;
|
|
3841
|
+
// Write-time provenance stamp (memory-provenance slice 1) — see
|
|
3842
|
+
// buildProvenance's doc above post(). Applies to every put() (fresh
|
|
3843
|
+
// create AND update/patch) — never gated on preExisting, so an update
|
|
3844
|
+
// always gets a freshly-stamped provenance reflecting the CURRENT
|
|
3845
|
+
// authenticated actor performing this write.
|
|
3846
|
+
content.provenance = buildProvenance(auth, content.createdAt, content);
|
|
3847
|
+
// flair#1940 A4: a client-supplied `receivedAt` is IGNORED (stripped; the
|
|
3848
|
+
// server's receipt time lives inside provenance, stamped above).
|
|
3849
|
+
delete content.receivedAt;
|
|
3850
|
+
// flair#718 authorship-provenance — see post()'s identical comment above:
|
|
3851
|
+
// strip the write-body-only `claimedClient` passthrough now that it's
|
|
3852
|
+
// folded into `provenance.claimed.client`. Never persisted as a row field.
|
|
3853
|
+
delete content.claimedClient;
|
|
3854
|
+
// Write-time originatorInstanceId (federation-edge-hardening slice 1):
|
|
3855
|
+
// a CREATE (no pre-existing row) stamps this instance's own id, ignoring
|
|
3856
|
+
// any body value; an UPDATE keeps the STORED value — a body value neither
|
|
3857
|
+
// replaces nor clears it. A federation-synced record never reaches this
|
|
3858
|
+
// method at all (the merge path writes via the raw table handle). See
|
|
3859
|
+
// resources/originator-instance.ts.
|
|
3860
|
+
await applyOriginatorInstanceId(content, preExisting);
|
|
3861
|
+
// The receiver-side federation bookkeeping stands as stored on an update,
|
|
3862
|
+
// and a client body may not set it on a create. See
|
|
3863
|
+
// resources/originator-instance.ts.
|
|
3864
|
+
applyFederationBookkeeping(content, preExisting);
|
|
3865
|
+
// ── Write the new/updated record FIRST ──────────────────────────────────
|
|
3866
|
+
// A1' item 1: persist ONLY declared Memory attributes (see post()).
|
|
3867
|
+
// Pinned by test/unit/memory-host-source.test.ts (r20-put) — RED if this
|
|
3868
|
+
// call is removed.
|
|
3869
|
+
stripUndeclaredMemoryAttributes(content);
|
|
3870
|
+
normalizeEmptyEmbedding(content);
|
|
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");
|
|
3875
|
+
const reservedId = [content?.id, this.getId?.()].find((candidate) => isReservedSeedId("Memory", candidate));
|
|
3876
|
+
const skillStaged = { supplied: suppliedText, text: null };
|
|
3877
|
+
// A PUT whose redaction replaced a value commits its redacted effective
|
|
3878
|
+
// row, inherited fields included, so each field the reply's `stored`
|
|
3879
|
+
// reports (the fields the request supplied, flair#2561) is what the row
|
|
3880
|
+
// holds: the in-place unchanged-row check gets no requested fields for it.
|
|
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) };
|
|
3901
|
+
}
|
|
3902
|
+
// flair#2441: this put is over the row read as `preExisting` (which
|
|
3903
|
+
// `stampInstanceToken` copied its incarnation token from). The write
|
|
3904
|
+
// confirms, against the COMMITTED row, that it is still that one
|
|
3905
|
+
// (sameStoredRow): once before the row is staged (nothing is staged yet,
|
|
3906
|
+
// so the refusal is returned) and once after, before the commit
|
|
3907
|
+
// (confirmCommittedRow: the transaction is aborted and the staged rows
|
|
3908
|
+
// discarded). Both reads use an explicit fresh context, never contextless
|
|
3909
|
+
// (see resources/write-back.ts).
|
|
3910
|
+
const confirmPause = txnPausePoint("memory-put");
|
|
3911
|
+
if (confirmPause)
|
|
3912
|
+
await confirmPause;
|
|
3913
|
+
if (preExisting) {
|
|
3914
|
+
const confirmed = await databases.flair.Memory.get(preExisting.id, {});
|
|
3915
|
+
if (!confirmed || !sameStoredRow(confirmed, preExisting))
|
|
3916
|
+
return storedRowChangedRefusal("Memory");
|
|
3917
|
+
}
|
|
3918
|
+
putStaged = storedMemoryText(content, suppliedText);
|
|
3919
|
+
const r = storageResult(await databases.flair.Memory.put(content, c));
|
|
3920
|
+
if (r instanceof Response)
|
|
3921
|
+
return r;
|
|
3922
|
+
if (pointer.row) {
|
|
3923
|
+
pointer.row.memoryId = r?.id ?? content.id ?? "";
|
|
3924
|
+
const persistDenial = await persistPointerRow(pointer.row, c);
|
|
3925
|
+
if (persistDenial)
|
|
3926
|
+
return persistDenial;
|
|
3927
|
+
}
|
|
3928
|
+
if (preExisting) {
|
|
3929
|
+
// Measured over HTTP on Harper 5.3.1: a competitor committed after this
|
|
3930
|
+
// write was staged keeps its row even without this re-check (Harper
|
|
3931
|
+
// orders the staged write by this transaction's earlier timestamp); the
|
|
3932
|
+
// re-check is what refuses the put by name instead of answering success
|
|
3933
|
+
// for a write that did not land. Test-only: holds the staged write.
|
|
3934
|
+
const stagedPause = txnPausePoint("memory-put-staged");
|
|
3935
|
+
if (stagedPause)
|
|
3936
|
+
await stagedPause;
|
|
3937
|
+
// The committed row must still be the one read; the throw leaves this
|
|
3938
|
+
// callback, so the owned transaction aborts and the staged write is
|
|
3939
|
+
// discarded, and the caller answers 409. A composing caller's
|
|
3940
|
+
// transaction is not aborted by the throw, so it is aborted here.
|
|
3941
|
+
try {
|
|
3942
|
+
await confirmCommittedRow(databases.flair.Memory, preExisting.id, (committed) => sameStoredRow(committed, preExisting));
|
|
3943
|
+
}
|
|
3944
|
+
catch (err) {
|
|
3945
|
+
if (err instanceof CommittedRowChanged && composed)
|
|
3946
|
+
abortRequestTransaction(c);
|
|
3947
|
+
throw err;
|
|
3948
|
+
}
|
|
3949
|
+
}
|
|
3950
|
+
// Stage a grant-authorized close in the successor's transaction: the
|
|
3951
|
+
// transaction this put owns (a throw leaves this callback and aborts it)
|
|
3952
|
+
// or, for a composed put, its caller's (aborted explicitly).
|
|
3953
|
+
putGrantedClosed = await closeGrantedSupersedeStaged(c, content, supersede.close, composed);
|
|
3954
|
+
return { content, result: r, dedupMatch, redactedValues, usedMemoryIds, close: supersede.close, auth, fallbackId: preExisting?.id, previous: preExisting ?? null };
|
|
3955
|
+
});
|
|
1631
3956
|
}
|
|
1632
|
-
|
|
1633
|
-
|
|
1634
|
-
|
|
1635
|
-
|
|
3957
|
+
catch (err) {
|
|
3958
|
+
if (err instanceof CommittedRowChanged)
|
|
3959
|
+
return storedRowChangedRefusal("Memory");
|
|
3960
|
+
const refusal = grantedCloseRefusal(err);
|
|
3961
|
+
if (refusal)
|
|
3962
|
+
return refusal;
|
|
3963
|
+
throw err;
|
|
1636
3964
|
}
|
|
1637
|
-
//
|
|
1638
|
-
|
|
1639
|
-
|
|
1640
|
-
|
|
1641
|
-
// (never read). Reject, never truncate/coerce.
|
|
1642
|
-
const pointerInputs = extractPointerInputs(content);
|
|
1643
|
-
// A1-iv item 3: strip server-stamped fields (a client may not set them).
|
|
1644
|
-
stripServerStampedFields(content);
|
|
1645
|
-
// A1-iv item 1: PRESERVE the existing row's incarnation token on an update,
|
|
1646
|
-
// else generate one (a fresh create via put).
|
|
1647
|
-
stampInstanceToken(content, preExisting);
|
|
1648
|
-
// A1'' item 5: a partial PUT (one that omits `visibility`, e.g. a
|
|
1649
|
-
// memory_update full put) must stamp scopeAtWrite from the record's
|
|
1650
|
-
// EFFECTIVE visibility — the existing row's when the body omits it — not
|
|
1651
|
-
// from an undefined body value that would wrongly yield author-only.
|
|
1652
|
-
const effectiveVisibility = content.visibility ?? preExisting?.visibility;
|
|
1653
|
-
// A partial PUT carries the stored visibility it read at the start of the
|
|
1654
|
-
// request (one carry, above, before the write-policy guards).
|
|
1655
|
-
// Adjudication B (round 4): load the stored pointer row so an echo of it is
|
|
1656
|
-
// recognised and not replaced (see buildPointerForWrite).
|
|
1657
|
-
let storedPointer = null;
|
|
1658
|
-
if (content.id &&
|
|
1659
|
-
pointerInputs.hostSource !== undefined &&
|
|
1660
|
-
pointerInputs.hostSource !== null &&
|
|
1661
|
-
pointerInputs.hostSourceScope === undefined) {
|
|
1662
|
-
storedPointer = await loadStoredPointer(content.id);
|
|
1663
|
-
}
|
|
1664
|
-
const pointer = buildPointerForWrite({ inputs: pointerInputs, memoryId: content.id ?? "", visibility: effectiveVisibility, auth, memoryInstanceToken: content.instanceToken, storedPointer });
|
|
1665
|
-
if (pointer.denial)
|
|
1666
|
-
return pointer.denial;
|
|
1667
|
-
// Write-time provenance stamp (memory-provenance slice 1) — see
|
|
1668
|
-
// buildProvenance's doc above post(). Applies to every put() (fresh
|
|
1669
|
-
// create AND update/patch) — never gated on preExisting, so an update
|
|
1670
|
-
// always gets a freshly-stamped provenance reflecting the CURRENT
|
|
1671
|
-
// authenticated actor performing this write.
|
|
1672
|
-
content.provenance = buildProvenance(auth, content.createdAt, content);
|
|
1673
|
-
// flair#1940 A4: a client-supplied `receivedAt` is IGNORED (stripped; the
|
|
1674
|
-
// server's receipt time lives inside provenance, stamped above).
|
|
1675
|
-
delete content.receivedAt;
|
|
1676
|
-
// flair#718 authorship-provenance — see post()'s identical comment above:
|
|
1677
|
-
// strip the write-body-only `claimedClient` passthrough now that it's
|
|
1678
|
-
// folded into `provenance.claimed.client`. Never persisted as a row field.
|
|
1679
|
-
delete content.claimedClient;
|
|
1680
|
-
// Write-time originatorInstanceId (federation-edge-hardening slice 1):
|
|
1681
|
-
// a CREATE (no pre-existing row) stamps this instance's own id, ignoring
|
|
1682
|
-
// any body value; an UPDATE keeps the STORED value — a body value neither
|
|
1683
|
-
// replaces nor clears it. A federation-synced record never reaches this
|
|
1684
|
-
// method at all (the merge path writes via the raw table handle). See
|
|
1685
|
-
// resources/originator-instance.ts.
|
|
1686
|
-
await applyOriginatorInstanceId(content, preExisting);
|
|
1687
|
-
// The receiver-side federation bookkeeping stands as stored on an update,
|
|
1688
|
-
// and a client body may not set it on a create. See
|
|
1689
|
-
// resources/originator-instance.ts.
|
|
1690
|
-
applyFederationBookkeeping(content, preExisting);
|
|
1691
|
-
// ── Write the new/updated record FIRST ──────────────────────────────────
|
|
1692
|
-
// A1' item 1: persist ONLY declared Memory attributes (see post()).
|
|
1693
|
-
// Pinned by test/unit/memory-host-source.test.ts (r20-put) — RED if this
|
|
1694
|
-
// call is removed.
|
|
1695
|
-
stripUndeclaredMemoryAttributes(content);
|
|
1696
|
-
// A1' item 2 (adjudication 0a): share ONE transaction with the pointer row
|
|
1697
|
-
// (see post()). The shared helper's owned-transaction branch is pinned by
|
|
1698
|
-
// test/unit/memory-host-source.test.ts (r20-atomic, which drives POST);
|
|
1699
|
-
// request-context PUT rollback is pinned by
|
|
1700
|
-
// test/integration/host-source-atomicity-1940.test.ts (t2).
|
|
1701
|
-
const putResult = await withSharedWriteTransaction(ctx, async (c) => {
|
|
1702
|
-
const r = await databases.flair.Memory.put(content, c);
|
|
1703
|
-
if (pointer.row) {
|
|
1704
|
-
pointer.row.memoryId = r?.id ?? content.id ?? "";
|
|
1705
|
-
const persistDenial = await persistPointerRow(pointer.row, c);
|
|
1706
|
-
if (persistDenial)
|
|
1707
|
-
return persistDenial;
|
|
1708
|
-
}
|
|
1709
|
-
return r;
|
|
1710
|
-
});
|
|
1711
|
-
if (putResult instanceof Response)
|
|
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")
|
|
1712
3969
|
return putResult;
|
|
1713
|
-
|
|
3970
|
+
// A skill PUT answers from its own write (no ordinary-row post-commit step).
|
|
3971
|
+
if (putResult && putResult.skill !== undefined)
|
|
3972
|
+
return putResult.skill;
|
|
3973
|
+
// flair#2561: a refusal this path built is returned as built; a
|
|
3974
|
+
// successful Response is replaced by the write_response_withheld refusal
|
|
3975
|
+
// (a storage-layer Response was replaced in the transaction, storageResult).
|
|
3976
|
+
if (putResult instanceof Response)
|
|
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;
|
|
3983
|
+
// embedding-space-guard slice 1 (see post()): the ordinary row write has
|
|
3984
|
+
// returned from its transaction, so the guard is notified now, with the
|
|
3985
|
+
// stored stamp and the row this PUT replaced (flair#2573), before the
|
|
3986
|
+
// verification read: a refused or unknown verification still leaves the
|
|
3987
|
+
// guard told about the stored vector.
|
|
3988
|
+
noteWriteStamp(putResult.content?.embeddingModel, putResult.previous ?? null);
|
|
3989
|
+
// Verify the ordinary owned row PUT after a normal storage result.
|
|
3990
|
+
// Refusals, storage Responses and skill PUT return above; composed promotion skips
|
|
3991
|
+
// this read and uses its caller's in-transaction existence check.
|
|
3992
|
+
// Compare the token and declared agentId/content/visibility/durability;
|
|
3993
|
+
// other field changes pass. A failed read marks the id and answers 503.
|
|
3994
|
+
if (!composed) {
|
|
3995
|
+
// Test-only: holds the PUT after its commit, before the verification read.
|
|
3996
|
+
const verifyPause = txnPausePoint("memory-put-verify");
|
|
3997
|
+
if (verifyPause)
|
|
3998
|
+
await verifyPause;
|
|
3999
|
+
const verified = await verifyWrittenRow(databases.flair.Memory, putResult.content, putResult.fallbackId, { expectedToken: putResult.content?.instanceToken }, POSTCOMMIT_VERIFY_FIELDS, locked ? { exactFields: locked.confirmFields } : undefined);
|
|
4000
|
+
if (verified.unknown)
|
|
4001
|
+
return writeOutcomeUnknownFor(putResult.content?.id ?? putResult.fallbackId);
|
|
4002
|
+
if (verified.mismatch)
|
|
4003
|
+
return storedRowChangedRefusal("Memory");
|
|
4004
|
+
}
|
|
4005
|
+
// The verification only decides whether the write is answered; the response
|
|
4006
|
+
// is built from the write's own result, never from the verified row. The
|
|
4007
|
+
// stored row carries per-row values that are not part of the write response
|
|
4008
|
+
// (`instanceToken`, `embedding`, `provenance`). Built this way, two otherwise
|
|
4009
|
+
// identical writes, one citing a memory the writer cannot read and one citing
|
|
4010
|
+
// a nonexistent id, answer identically once writer ids and timestamps are
|
|
4011
|
+
// normalized: nothing in the answer depends on the cited id (flair#775).
|
|
4012
|
+
const result = putResult.result;
|
|
1714
4013
|
// flair#1357 — read-your-write for the lexical leg (see post()).
|
|
1715
|
-
noteMemoryUpsert(content);
|
|
1716
|
-
noteWriteStamp(content?.embeddingModel); // embedding-space-guard slice 1 (see post())
|
|
4014
|
+
noteMemoryUpsert(putResult.content);
|
|
1717
4015
|
// ── THEN close the superseded record (see post()) ───────────────────────
|
|
1718
|
-
|
|
4016
|
+
// A grant-authorized close was staged in the successor's transaction
|
|
4017
|
+
// (closeGrantedSupersedeStaged).
|
|
4018
|
+
if (putGrantedClosed)
|
|
4019
|
+
noteMemoryUpsert(putGrantedClosed);
|
|
4020
|
+
if (putResult.close?.granteeId === undefined)
|
|
4021
|
+
await closeSupersededIfNeeded(ctx, putResult.content, putResult.close, "put");
|
|
1719
4022
|
// flair#744 slice A: citation-on-write — POST-COMMIT, fully
|
|
1720
|
-
// failure-isolated (see post()'s identical comment above).
|
|
1721
|
-
|
|
1722
|
-
|
|
1723
|
-
|
|
1724
|
-
|
|
1725
|
-
|
|
1726
|
-
|
|
1727
|
-
|
|
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.
|
|
4025
|
+
if (putResult.usedMemoryIds !== undefined) {
|
|
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
|
+
});
|
|
1728
4035
|
}
|
|
1729
|
-
return buildWriteResponse(content, result, dedupMatch);
|
|
4036
|
+
return buildWriteResponse(putResult.content, result, putResult.dedupMatch, putResult.redactedValues, putStaged);
|
|
1730
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). */
|
|
1731
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.
|
|
4052
|
+
const ctx = this.getContext?.();
|
|
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) {
|
|
4084
|
+
if (auth.kind === "anonymous")
|
|
4085
|
+
return UNAUTH();
|
|
4086
|
+
// flair#2478: a DELETE of an id whose last owned PUT/PATCH settled with an
|
|
4087
|
+
// unknown outcome waits for reconciliation too: refused until restart, as a
|
|
4088
|
+
// later PUT or PATCH of that id is.
|
|
4089
|
+
if ([id, ...writeTargetIds(this, id && typeof id === "object" ? id : undefined)]
|
|
4090
|
+
.some((t) => (typeof t === "string" || typeof t === "number") && memoryWriteOutcomeUnknown(t))) {
|
|
4091
|
+
return writeOutcomeUnknownResponse();
|
|
4092
|
+
}
|
|
4093
|
+
// flair#2141 S2: check the seed's fixed id against the operator-source
|
|
4094
|
+
// reservation (resources/seed-reservation.ts).
|
|
4095
|
+
const seedDenial = reservedSeedWriteDenial("Memory", [id, ...writeTargetIds(this, id && typeof id === "object" ? id : undefined)], ctx, auth);
|
|
4096
|
+
if (seedDenial)
|
|
4097
|
+
return seedDenial;
|
|
4098
|
+
const contentSuffixDenial = refuseContentSuffixId([id, ...writeTargetIds(this, id && typeof id === "object" ? id : undefined)], id);
|
|
4099
|
+
if (contentSuffixDenial)
|
|
4100
|
+
return contentSuffixDenial;
|
|
4101
|
+
return null;
|
|
4102
|
+
}
|
|
4103
|
+
async deleteLocked(id, headLock) {
|
|
1732
4104
|
const ctx = this.getContext?.();
|
|
1733
4105
|
const auth = await resolveAgentAuth(ctx);
|
|
4106
|
+
const refusal = this.deleteRefusalBeforeRead(id, ctx, auth);
|
|
4107
|
+
if (refusal)
|
|
4108
|
+
return refusal;
|
|
1734
4109
|
if (auth.kind === "anonymous")
|
|
1735
4110
|
return UNAUTH();
|
|
1736
4111
|
// Read stored ownership, not the read-scoped get() response. Enforce here
|
|
@@ -1740,37 +4115,204 @@ export class Memory extends databases.flair.Memory {
|
|
|
1740
4115
|
isForbiddenOwnerMutation(record, RECORD_TYPES.Memory.ownerField, auth.agentId)) {
|
|
1741
4116
|
return FORBIDDEN("forbidden: cannot delete memory owned by another agent");
|
|
1742
4117
|
}
|
|
4118
|
+
const reservedSeed = [id, this.getId?.(), ...writeTargetIds(this, id && typeof id === "object" ? id : undefined)]
|
|
4119
|
+
.some((candidate) => isReservedSeedId("Memory", candidate));
|
|
4120
|
+
if (!reservedSeed && rowIsSkill(record)) {
|
|
4121
|
+
// flair#2355: hold the row still before the version writer's transaction
|
|
4122
|
+
// opens, so a competing owner change can commit first and be seen by the
|
|
4123
|
+
// confirmation read inside.
|
|
4124
|
+
const beforeSkillDelete = txnPausePoint("memory-skill-delete-pre");
|
|
4125
|
+
if (beforeSkillDelete)
|
|
4126
|
+
await beforeSkillDelete;
|
|
4127
|
+
return await writeSkillDelete({ ctx, auth, record, headLock });
|
|
4128
|
+
}
|
|
1743
4129
|
// Durability controls retention, not the owner's authority to delete.
|
|
1744
|
-
// A1' item 2 (adjudication 0a/0c): the Memory delete
|
|
1745
|
-
//
|
|
1746
|
-
//
|
|
1747
|
-
//
|
|
1748
|
-
//
|
|
1749
|
-
//
|
|
1750
|
-
|
|
1751
|
-
|
|
1752
|
-
|
|
1753
|
-
|
|
1754
|
-
|
|
1755
|
-
|
|
1756
|
-
|
|
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).
|
|
4136
|
+
const deletionActor = auth.kind === "agent" ? auth.agentId : null;
|
|
4137
|
+
const deletionSourceClass = auth.kind === "internal" ? "internal" : auth.isAdmin ? "admin" : "agent";
|
|
4138
|
+
// flair#2355: hold the row still before the delete stages, so a competing
|
|
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;
|
|
4145
|
+
const beforeDelete = txnPausePoint("memory-delete-pre");
|
|
4146
|
+
if (beforeDelete)
|
|
4147
|
+
await beforeDelete;
|
|
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");
|
|
1757
4190
|
const pointerDenial = await deletePointerRow(deletedId, c);
|
|
1758
4191
|
if (pointerDenial)
|
|
1759
|
-
return 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")
|
|
4205
|
+
return false;
|
|
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;
|
|
4213
|
+
}
|
|
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;
|
|
1760
4224
|
}
|
|
1761
|
-
|
|
1762
|
-
|
|
1763
|
-
|
|
1764
|
-
|
|
1765
|
-
//
|
|
1766
|
-
|
|
1767
|
-
|
|
1768
|
-
|
|
1769
|
-
|
|
1770
|
-
|
|
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);
|
|
1771
4236
|
}
|
|
1772
4237
|
if (typeof id === "string")
|
|
1773
4238
|
await clearHitStats(id, ctx).catch(() => { });
|
|
1774
|
-
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));
|
|
4280
|
+
}
|
|
4281
|
+
catch (error) {
|
|
4282
|
+
return Promise.reject(error);
|
|
1775
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);
|
|
1776
4318
|
}
|