@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
|
@@ -0,0 +1,789 @@
|
|
|
1
|
+
import { WriteJournal, currentWriteJournal } from "./write-journal.js";
|
|
2
|
+
import { withKeyLock } from "./key-lock.js";
|
|
3
|
+
import { withMemoryWriteLock } from "./memory-write-lock.js";
|
|
4
|
+
import { normalizeEmptyEmbedding } from "./memory-embedding-value.js";
|
|
5
|
+
/** Skill writes share the ["flair-instruction-version", "skill"] lock. */
|
|
6
|
+
import { databases } from "harper";
|
|
7
|
+
import { storageResult } from "./memory-write-response.js";
|
|
8
|
+
import { randomUUID } from "node:crypto";
|
|
9
|
+
import { isDeepStrictEqual } from "node:util";
|
|
10
|
+
import { recordVersion, readHead, readVersionRecord, readVersionRecordAfter, skillRefReadable, SKILL_SUBJECT_TYPE } from "./instruction-version-record.js";
|
|
11
|
+
import { SKILL_TAG, enforceSkillDurability, skillEmbedText, skillMetadataHasDuplicateKey } from "./skill-write.js";
|
|
12
|
+
import { stripUndeclaredMemoryAttributes } from "./memory-declared-attributes.js";
|
|
13
|
+
import { skillWriteSource } from "./skill-write-policy.js";
|
|
14
|
+
import { keepsSuppliedVector } from "./memory-supplied-vector.js";
|
|
15
|
+
import { FORBIDDEN } from "./record-type-kit.js";
|
|
16
|
+
import { PRIVATE_VISIBILITY, SHARED_VISIBILITY } from "./memory-visibility.js";
|
|
17
|
+
import { maybeThrowSkillWriteFault } from "./skill-write-fault.js";
|
|
18
|
+
import { supersedesTargetUnreadable } from "./memory-id-guard.js";
|
|
19
|
+
import { grantedCloseRevokedRefusal, sameStoredRow, storedRowChangedRefusal, writeGrantHeld } from "./write-back.js";
|
|
20
|
+
import { isJoinableTransaction, withOwnedTransaction } from "./request-transaction.js";
|
|
21
|
+
import { txnPausePoint } from "./txn-pause-point.js";
|
|
22
|
+
import { committedVisibilityDiffers, grantedSuccessorVisibilityDenial, predecessorVisibilityChangedRefusal } from "./grant-visibility.js";
|
|
23
|
+
import { isOpenLiveRow } from "../src/lib/open-live-row.js";
|
|
24
|
+
/** Durability-keyed default visibility (mirrors Memory's write default). */
|
|
25
|
+
function defaultVisibilityForDurability(durability) {
|
|
26
|
+
return durability === "permanent" || durability === "persistent" ? "shared" : "private";
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* The effective visibility stamped on a skill version row (flair#2139 S2
|
|
30
|
+
* decision 3): the row's writable visibility, else the durability-keyed default.
|
|
31
|
+
* Never absent: a legacy row missing visibility is normalized at capture time
|
|
32
|
+
* rather than left to read as public.
|
|
33
|
+
*/
|
|
34
|
+
export function skillVersionVisibility(row) {
|
|
35
|
+
const v = row?.visibility;
|
|
36
|
+
if (v === PRIVATE_VISIBILITY || v === SHARED_VISIBILITY)
|
|
37
|
+
return v;
|
|
38
|
+
return defaultVisibilityForDurability(row?.durability);
|
|
39
|
+
}
|
|
40
|
+
export async function closedSkillPayloadReadable(row, readerId, read = {}) {
|
|
41
|
+
if (!row || typeof row !== "object" || !rowIsSkill(row))
|
|
42
|
+
return true;
|
|
43
|
+
if (isOpenLiveRow(row))
|
|
44
|
+
return true;
|
|
45
|
+
if (!skillRefReadable({ agentId: row.agentId, visibility: row.visibility }, readerId))
|
|
46
|
+
return false;
|
|
47
|
+
const subjectId = typeof row.skillSubjectId === "string" && row.skillSubjectId.length > 0
|
|
48
|
+
? row.skillSubjectId
|
|
49
|
+
: String(row.id);
|
|
50
|
+
const headOf = read.headOf ?? ((sid) => readHead(SKILL_SUBJECT_TYPE, sid));
|
|
51
|
+
let versionHead;
|
|
52
|
+
try {
|
|
53
|
+
versionHead = await headOf(subjectId);
|
|
54
|
+
}
|
|
55
|
+
catch {
|
|
56
|
+
return false;
|
|
57
|
+
}
|
|
58
|
+
if (!versionHead || versionHead.subjectType !== SKILL_SUBJECT_TYPE || versionHead.subjectId !== subjectId)
|
|
59
|
+
return false;
|
|
60
|
+
if (!skillRefReadable(versionHead, versionHead.agentId))
|
|
61
|
+
return false;
|
|
62
|
+
if (versionHead.kind === "delete") {
|
|
63
|
+
return versionHead.memoryId === null && skillRefReadable(versionHead, readerId);
|
|
64
|
+
}
|
|
65
|
+
if (versionHead.kind !== "create" && versionHead.kind !== "update")
|
|
66
|
+
return false;
|
|
67
|
+
if (typeof versionHead.memoryId !== "string" || versionHead.memoryId.length === 0)
|
|
68
|
+
return false;
|
|
69
|
+
const memoryGet = read.memoryGet ?? ((id) => databases.flair?.Memory?.get(id));
|
|
70
|
+
let live;
|
|
71
|
+
try {
|
|
72
|
+
live = await memoryGet(versionHead.memoryId);
|
|
73
|
+
}
|
|
74
|
+
catch {
|
|
75
|
+
return false;
|
|
76
|
+
}
|
|
77
|
+
if (!live || live.id !== versionHead.memoryId || live.skillSubjectId !== subjectId)
|
|
78
|
+
return false;
|
|
79
|
+
if (live.agentId !== versionHead.agentId || !rowIsSkill(live) || live.archived === true)
|
|
80
|
+
return false;
|
|
81
|
+
for (const end of [live.validTo, live.expiresAt]) {
|
|
82
|
+
if (end == null)
|
|
83
|
+
continue;
|
|
84
|
+
if (typeof end !== "string" || !(Date.parse(end) > Date.now()))
|
|
85
|
+
return false;
|
|
86
|
+
}
|
|
87
|
+
return skillRefReadable({ agentId: live.agentId, visibility: live.visibility }, readerId);
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Build the successor Memory row for a superseded skill. Retains declared and explicitly allowed fields.
|
|
91
|
+
*/
|
|
92
|
+
export function buildSkillSuccessorRow(args) {
|
|
93
|
+
const { auth, base, predecessorRow, successorId, subjectId, supersedes, now } = args;
|
|
94
|
+
const row = predecessorRow ? { ...predecessorRow, ...base } : { ...base };
|
|
95
|
+
if (!keepsSuppliedVector(auth)) {
|
|
96
|
+
for (const field of ["embedding", "embeddingModel"]) {
|
|
97
|
+
if (!Object.prototype.hasOwnProperty.call(base, field))
|
|
98
|
+
delete row[field];
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
row.id = successorId;
|
|
102
|
+
row.skillSubjectId = subjectId;
|
|
103
|
+
if (supersedes)
|
|
104
|
+
row.supersedes = supersedes;
|
|
105
|
+
else
|
|
106
|
+
delete row.supersedes;
|
|
107
|
+
row.updatedAt = now;
|
|
108
|
+
row.archived = false;
|
|
109
|
+
delete row.validTo;
|
|
110
|
+
delete row.archivedAt;
|
|
111
|
+
delete row.archivedBy;
|
|
112
|
+
if (!predecessorRow)
|
|
113
|
+
row.createdAt = typeof base.createdAt === "string" ? base.createdAt : now;
|
|
114
|
+
row.instanceToken = randomUUID();
|
|
115
|
+
enforceSkillDurability(row);
|
|
116
|
+
stripUndeclaredMemoryAttributes(row);
|
|
117
|
+
return row;
|
|
118
|
+
}
|
|
119
|
+
function okResponse() {
|
|
120
|
+
return new Response(JSON.stringify({ ok: true }), { status: 200, headers: { "Content-Type": "application/json" } });
|
|
121
|
+
}
|
|
122
|
+
/** Is this row a skill-tagged Memory row? */
|
|
123
|
+
export function rowIsSkill(row) {
|
|
124
|
+
return !!row && Array.isArray(row.tags) && row.tags.includes(SKILL_TAG);
|
|
125
|
+
}
|
|
126
|
+
export function skillPayloadUnchanged(base, head) {
|
|
127
|
+
const bookkeeping = new Set([
|
|
128
|
+
"embedding", "embeddingModel", "embeddedContentHash", "contentHash", "updatedAt", "instanceToken",
|
|
129
|
+
"provenance", "skillSubjectId", "_safetyFlags", "_skillScan",
|
|
130
|
+
"retrievalCount", "lastRetrieved",
|
|
131
|
+
]);
|
|
132
|
+
return Object.entries(base).every(([key, value]) => bookkeeping.has(key) || isDeepStrictEqual(value, head[key]));
|
|
133
|
+
}
|
|
134
|
+
export function skillWriteConflict(error) {
|
|
135
|
+
return Response.json({ error }, { status: 409 });
|
|
136
|
+
}
|
|
137
|
+
export async function prepareSkillBody(content, stored, auth) {
|
|
138
|
+
let predecessor = null;
|
|
139
|
+
if (typeof content.supersedes === "string" && content.supersedes.length > 0) {
|
|
140
|
+
// flair#2307: a failed read of the `supersedes` target refuses the write
|
|
141
|
+
// with a named error; it is never read as "no predecessor".
|
|
142
|
+
try {
|
|
143
|
+
predecessor = await databases.flair.Memory.get(content.supersedes);
|
|
144
|
+
}
|
|
145
|
+
catch (err) {
|
|
146
|
+
return supersedesTargetUnreadable(err);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
if (!rowIsSkill(content) && !rowIsSkill(stored) && !rowIsSkill(predecessor)) {
|
|
150
|
+
return { content, predecessor };
|
|
151
|
+
}
|
|
152
|
+
if (content.supersedes && content.supersedes === content.id)
|
|
153
|
+
return skillWriteConflict("skill_self_supersede");
|
|
154
|
+
if (content.supersedes && !predecessor && content.supersedes !== stored?.supersedes) {
|
|
155
|
+
return skillWriteConflict("skill_predecessor_missing");
|
|
156
|
+
}
|
|
157
|
+
if (content.tags !== undefined && (!Array.isArray(content.tags) || !content.tags.includes(SKILL_TAG))) {
|
|
158
|
+
return Response.json({ error: "skill_lineage_tag_removed" }, { status: 400 });
|
|
159
|
+
}
|
|
160
|
+
if ((content.archived != null && content.archived !== false) || (content.validTo != null && content.validTo !== "")) {
|
|
161
|
+
return Response.json({ error: "skill_state_requires_delete" }, { status: 400 });
|
|
162
|
+
}
|
|
163
|
+
const source = stored ?? predecessor ?? {};
|
|
164
|
+
const effective = { ...source, ...content };
|
|
165
|
+
effective.tags = content.tags ?? (rowIsSkill(stored) ? stored.tags : predecessor?.tags);
|
|
166
|
+
if (skillMetadataHasDuplicateKey(effective.metadata)) {
|
|
167
|
+
return Response.json({ error: "skill_metadata_duplicate_key" }, { status: 400 });
|
|
168
|
+
}
|
|
169
|
+
const textUnchanged = skillEmbedText(effective) === skillEmbedText(source);
|
|
170
|
+
if (content.embedding === undefined && !textUnchanged) {
|
|
171
|
+
effective.embedding = null;
|
|
172
|
+
effective.embeddingModel = null;
|
|
173
|
+
}
|
|
174
|
+
// flair#2465: the successor keeps the stored `embeddedContentHash` only when
|
|
175
|
+
// the stored row has a vector, the body omits `embedding` (so that vector is
|
|
176
|
+
// carried), and the embedding text is unchanged; otherwise null. A body value
|
|
177
|
+
// is never kept. A Feed successor stores this value; Memory.post()/put() keep
|
|
178
|
+
// it when they store the carried vector, and otherwise set their own.
|
|
179
|
+
const sourceHasVector = Array.isArray(source.embedding) && source.embedding.length > 0;
|
|
180
|
+
// Non-admin writes keep a carried vector's stored stamp. Administrator and
|
|
181
|
+
// trusted in-process writes may replace it and may supply their own vector.
|
|
182
|
+
if (!keepsSuppliedVector(auth) && content.embedding === undefined && sourceHasVector && textUnchanged) {
|
|
183
|
+
if (source.embeddingModel === undefined)
|
|
184
|
+
delete effective.embeddingModel;
|
|
185
|
+
else
|
|
186
|
+
effective.embeddingModel = source.embeddingModel;
|
|
187
|
+
}
|
|
188
|
+
effective.embeddedContentHash = sourceHasVector && content.embedding === undefined && textUnchanged
|
|
189
|
+
? (source.embeddedContentHash ?? null)
|
|
190
|
+
: null;
|
|
191
|
+
if (content.id === undefined)
|
|
192
|
+
delete effective.id;
|
|
193
|
+
return { content: effective, predecessor };
|
|
194
|
+
}
|
|
195
|
+
/** Return the sole live head, or null if none; refuse ambiguity. */
|
|
196
|
+
export async function resolveSkillHead(subjectId, addressedId, shared) {
|
|
197
|
+
const table = databases.flair?.Memory;
|
|
198
|
+
if (!table || typeof table.search !== "function")
|
|
199
|
+
throw new Error("flair: the Memory table is unavailable");
|
|
200
|
+
const live = new Map();
|
|
201
|
+
if (subjectId) {
|
|
202
|
+
for await (const row of table.search({
|
|
203
|
+
conditions: [{ attribute: "skillSubjectId", comparator: "equals", value: subjectId }],
|
|
204
|
+
}, shared)) {
|
|
205
|
+
if (isOpenLiveRow(row))
|
|
206
|
+
live.set(String(row.id), row);
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
if (addressedId) {
|
|
210
|
+
const row = await table.get(addressedId, shared);
|
|
211
|
+
if (isOpenLiveRow(row) && (!row.skillSubjectId || row.skillSubjectId === subjectId))
|
|
212
|
+
live.set(String(row.id), row);
|
|
213
|
+
}
|
|
214
|
+
if (live.size > 1)
|
|
215
|
+
throw new Error("skill_head_ambiguous");
|
|
216
|
+
return live.values().next().value ?? null;
|
|
217
|
+
}
|
|
218
|
+
export async function authorizeSkillOwners(ctx, auth, rows, shared) {
|
|
219
|
+
for (const row of rows.filter(Boolean)) {
|
|
220
|
+
if (typeof row.agentId !== "string" || !row.agentId.trim())
|
|
221
|
+
return FORBIDDEN("skill_owner_missing");
|
|
222
|
+
if (skillWriteSource(ctx, auth) !== "agent" || auth.kind !== "agent" || row.agentId === auth.agentId)
|
|
223
|
+
continue;
|
|
224
|
+
let granted = false;
|
|
225
|
+
for await (const grant of databases.flair.MemoryGrant.search({ conditions: [
|
|
226
|
+
{ attribute: "granteeId", comparator: "equals", value: auth.agentId },
|
|
227
|
+
{ attribute: "ownerId", comparator: "equals", value: row.agentId },
|
|
228
|
+
] }, shared)) {
|
|
229
|
+
if (grant.scope === "write")
|
|
230
|
+
granted = true;
|
|
231
|
+
}
|
|
232
|
+
if (!granted)
|
|
233
|
+
return FORBIDDEN("forbidden: cannot write a skill owned by another agent without a write grant");
|
|
234
|
+
}
|
|
235
|
+
return null;
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* flair#2511: the "write" grant a cross-agent close of `closed` stands on, or
|
|
239
|
+
* null when the close is not a grant-authorized cross-agent one — an operator,
|
|
240
|
+
* internal or same-agent caller. The same predicate {@link authorizeSkillOwners}
|
|
241
|
+
* uses to demand the grant; the shared writer re-checks it on committed state
|
|
242
|
+
* after the close is staged. Every plan that closes a row passes this for the
|
|
243
|
+
* row it closes.
|
|
244
|
+
*/
|
|
245
|
+
export function grantedSkillClose(closed, ctx, auth) {
|
|
246
|
+
if (!closed || typeof closed.agentId !== "string" || !closed.agentId.trim())
|
|
247
|
+
return null;
|
|
248
|
+
if (skillWriteSource(ctx, auth) !== "agent" || auth.kind !== "agent")
|
|
249
|
+
return null;
|
|
250
|
+
if (closed.agentId === auth.agentId)
|
|
251
|
+
return null;
|
|
252
|
+
return { granteeId: auth.agentId, ownerId: closed.agentId };
|
|
253
|
+
}
|
|
254
|
+
export async function validateSkillSnapshots(stored, predecessor, targetId, shared) {
|
|
255
|
+
for (const [id, expected] of [[targetId, stored], [predecessor?.id, predecessor]]) {
|
|
256
|
+
if (!id)
|
|
257
|
+
continue;
|
|
258
|
+
const current = await databases.flair.Memory.get(id, shared);
|
|
259
|
+
if (!isDeepStrictEqual(current ?? null, expected ?? null))
|
|
260
|
+
return skillWriteConflict("skill_target_changed");
|
|
261
|
+
}
|
|
262
|
+
return null;
|
|
263
|
+
}
|
|
264
|
+
/**
|
|
265
|
+
* The default Memory-table hooks: the successor is upserted and the predecessor
|
|
266
|
+
* is read-modify-written (full-record PUT, its stored fields preserved), both
|
|
267
|
+
* through the shared transaction so the helper's rollback covers them.
|
|
268
|
+
*/
|
|
269
|
+
export const defaultSkillHooks = {
|
|
270
|
+
createSuccessor: async (successor, shared) => {
|
|
271
|
+
normalizeEmptyEmbedding(successor);
|
|
272
|
+
// Not pre-validated: this row carries the caller's fields without that
|
|
273
|
+
// coercion, so a defect in it — a server-stamped field included — stays a
|
|
274
|
+
// caller error (400) at commit. Pre-validation covers the A2A,
|
|
275
|
+
// agent-key-register and instruction-version writer events and the
|
|
276
|
+
// migration rows (resources/server-row-validation.ts).
|
|
277
|
+
const result = storageResult(await databases.flair.Memory.put(successor, shared));
|
|
278
|
+
if (result instanceof Response)
|
|
279
|
+
return result;
|
|
280
|
+
return String(successor.id);
|
|
281
|
+
},
|
|
282
|
+
closePredecessor: async (predecessor, patch, shared) => {
|
|
283
|
+
const closed = { ...predecessor, ...patch };
|
|
284
|
+
normalizeEmptyEmbedding(closed);
|
|
285
|
+
// Not pre-validated: a close carries the caller's row; its defects stay a
|
|
286
|
+
// caller error at commit (see the successor note above).
|
|
287
|
+
const result = storageResult(await databases.flair.Memory.put(closed, shared));
|
|
288
|
+
if (result instanceof Response)
|
|
289
|
+
return result;
|
|
290
|
+
},
|
|
291
|
+
};
|
|
292
|
+
/**
|
|
293
|
+
* flair#2511: run once a close's write is staged — a supersede's predecessor
|
|
294
|
+
* close or a delete's head close. A grant-authorized cross-agent close stands on
|
|
295
|
+
* the grant read at authorization time; re-read it on committed state HERE,
|
|
296
|
+
* after the close is staged, through the shared write-back helper the non-skill
|
|
297
|
+
* close uses (Memory.ts closeSupersededRecord, flair#2333 H10).
|
|
298
|
+
*
|
|
299
|
+
* For a grant-authorized supersede, `successor` is the planned successor row.
|
|
300
|
+
* Before the grant re-check, the predecessor's COMMITTED row (an empty-context
|
|
301
|
+
* read, as for the grant) must read with the successor's visibility: a write
|
|
302
|
+
* grant does not include changing a record's visibility (grant-visibility.ts).
|
|
303
|
+
* A mismatch returns the named 409 predecessor_visibility_changed.
|
|
304
|
+
* As with the grant, a change committed
|
|
305
|
+
* after this re-read and before the transaction commits is not seen by it.
|
|
306
|
+
*/
|
|
307
|
+
export async function afterCloseStaged(granted, supersede) {
|
|
308
|
+
// Test-only: inert unless armed — here the close write is staged, so a
|
|
309
|
+
// competing grant revocation or row change and the committed-state re-checks
|
|
310
|
+
// below can be exercised in either order (the skill-path counterpart of Memory's "granted-close-staged").
|
|
311
|
+
const stagedPause = txnPausePoint("skill-close-staged");
|
|
312
|
+
if (stagedPause)
|
|
313
|
+
await stagedPause;
|
|
314
|
+
if (!granted)
|
|
315
|
+
return null;
|
|
316
|
+
if (supersede) {
|
|
317
|
+
const committed = await databases.flair.Memory.get(supersede.predecessorId, {});
|
|
318
|
+
if (committedVisibilityDiffers(committed, supersede.successor.visibility))
|
|
319
|
+
return predecessorVisibilityChangedRefusal();
|
|
320
|
+
}
|
|
321
|
+
const held = await writeGrantHeld(databases.flair.MemoryGrant, granted.granteeId, granted.ownerId, {});
|
|
322
|
+
return held ? null : grantedCloseRevokedRefusal();
|
|
323
|
+
}
|
|
324
|
+
/** Attempts at re-applying a skill update's close whose committed write did not land (flair#2645). */
|
|
325
|
+
const SKILL_UPDATE_CLOSE_ATTEMPTS = 3;
|
|
326
|
+
/** No caller-held Memory ids. */
|
|
327
|
+
const NO_HELD_IDS = new Set();
|
|
328
|
+
/**
|
|
329
|
+
* Acquire missing Memory ids in sorted order. Inline compensation skips
|
|
330
|
+
* caller-held ids; deferred confirmation and compensation reacquire after
|
|
331
|
+
* release (flair#2950).
|
|
332
|
+
* Returns `locked: false` when a missing id's lock could not be taken.
|
|
333
|
+
*/
|
|
334
|
+
async function withSkillMemoryLocks(ids, held, fn) {
|
|
335
|
+
const missing = [...new Set(ids.map((id) => String(id)))].filter((id) => !held.has(id)).sort();
|
|
336
|
+
if (missing.length === 0)
|
|
337
|
+
return { locked: true, value: await fn() };
|
|
338
|
+
const outcome = await withMemoryWriteLock(databases?.flair?.Memory?.primaryStore, missing, fn, {
|
|
339
|
+
phase: "skill-version-write",
|
|
340
|
+
});
|
|
341
|
+
return outcome.kind === "done" ? { locked: true, value: outcome.value } : { locked: false };
|
|
342
|
+
}
|
|
343
|
+
/** The named 500 when the skill update cannot be confirmed. */
|
|
344
|
+
function skillUpdateUnconfirmedFailure() {
|
|
345
|
+
return Response.json({
|
|
346
|
+
error: "skill_update_unconfirmed",
|
|
347
|
+
message: "the skill update could not be confirmed",
|
|
348
|
+
}, { status: 500 });
|
|
349
|
+
}
|
|
350
|
+
/** The named 409 for an update whose close still is not visible after the bounded re-applies. */
|
|
351
|
+
function skillUpdateNotClosedRefusal(attempts) {
|
|
352
|
+
return Response.json({
|
|
353
|
+
error: "skill_update_not_closed",
|
|
354
|
+
message: `the skill version close was not applied after ${attempts} attempts; not updated`,
|
|
355
|
+
}, { status: 409 });
|
|
356
|
+
}
|
|
357
|
+
/** The named 409 when neither a sole live successor nor ordered supersession is confirmed. */
|
|
358
|
+
function skillUpdateNotConfirmedRefusal() {
|
|
359
|
+
return Response.json({
|
|
360
|
+
error: "skill_update_not_confirmed",
|
|
361
|
+
message: "the committed store confirms neither this update's successor as the only live head nor its closure with this request's version record present, the record with the next sequence number linked to it by hash, and that later version deleting the successor or its row naming the successor as superseded",
|
|
362
|
+
}, { status: 409 });
|
|
363
|
+
}
|
|
364
|
+
/** The named 500 when compensation cannot be confirmed. */
|
|
365
|
+
function skillUpdateCompensationFailure(message) {
|
|
366
|
+
return Response.json({ error: "skill_update_compensation_failed", message }, { status: 500 });
|
|
367
|
+
}
|
|
368
|
+
async function compensateUnlandedSkillUpdate(args) {
|
|
369
|
+
args.journal.compensationAttempted = true;
|
|
370
|
+
try {
|
|
371
|
+
const table = databases.flair?.InstructionVersion;
|
|
372
|
+
// Memory id locks before the instruction-version lock (the global order),
|
|
373
|
+
// so the undo's Memory writes are serialized with the other per-id-locked
|
|
374
|
+
// writers of those ids, not just the version append (flair#2950).
|
|
375
|
+
const locked = await withSkillMemoryLocks(args.journal.memoryWriteIds(), args.held ?? NO_HELD_IDS, async () => withKeyLock(table?.primaryStore, ["flair-instruction-version", "skill"], async () => {
|
|
376
|
+
const appended = [...args.journal.entries].reverse().find((entry) => entry.after?.subjectType === "skill");
|
|
377
|
+
if (appended) {
|
|
378
|
+
const head = await readHead(SKILL_SUBJECT_TYPE, appended.after.subjectId, {});
|
|
379
|
+
if (head && String(head.id) !== String(appended.after.id))
|
|
380
|
+
return false;
|
|
381
|
+
}
|
|
382
|
+
return args.journal.undo(args.ctx, withOwnedTransaction);
|
|
383
|
+
}, 200, 10));
|
|
384
|
+
if (!locked.locked)
|
|
385
|
+
throw new Error("the Memory write lock could not be acquired for the skill write's undo");
|
|
386
|
+
const result = locked.value;
|
|
387
|
+
if (result.kind === "done" && result.value)
|
|
388
|
+
return null;
|
|
389
|
+
}
|
|
390
|
+
catch (err) {
|
|
391
|
+
console.error("skill-version-write: update undo could not be confirmed", err);
|
|
392
|
+
}
|
|
393
|
+
return skillUpdateCompensationFailure("the skill write's undo could not be confirmed; check its outcome, because its version and event may persist" +
|
|
394
|
+
(args.journal.pointerChanged ? "; a different host-pointer row was left in place" : ""));
|
|
395
|
+
}
|
|
396
|
+
/**
|
|
397
|
+
* flair#2645 — confirm a closed successor only when this request's update
|
|
398
|
+
* record is present, the record with the next sequence number links to it by
|
|
399
|
+
* hash, and that later version either deletes this successor (its `rowId`) or
|
|
400
|
+
* has a row that names this successor as superseded.
|
|
401
|
+
*/
|
|
402
|
+
async function confirmSupersededInOrder(args) {
|
|
403
|
+
if (!args.appendedVersionId)
|
|
404
|
+
return skillUpdateNotConfirmedRefusal();
|
|
405
|
+
let appended;
|
|
406
|
+
let following;
|
|
407
|
+
try {
|
|
408
|
+
appended = await readVersionRecord(SKILL_SUBJECT_TYPE, args.subjectId, args.appendedVersionId, {});
|
|
409
|
+
following = appended
|
|
410
|
+
? await readVersionRecordAfter(SKILL_SUBJECT_TYPE, args.subjectId, appended.version, {})
|
|
411
|
+
: null;
|
|
412
|
+
}
|
|
413
|
+
catch {
|
|
414
|
+
return skillUpdateUnconfirmedFailure();
|
|
415
|
+
}
|
|
416
|
+
if (!appended || appended.kind !== "update" || String(appended.memoryId) !== String(args.successor.id)) {
|
|
417
|
+
return skillUpdateNotConfirmedRefusal();
|
|
418
|
+
}
|
|
419
|
+
if (!following || following.previousVersionHash !== appended.recordHash)
|
|
420
|
+
return skillUpdateNotConfirmedRefusal();
|
|
421
|
+
if (following.kind === "delete") {
|
|
422
|
+
return String(following.rowId ?? "") === String(args.successor.id) ? null : skillUpdateNotConfirmedRefusal();
|
|
423
|
+
}
|
|
424
|
+
if (following.kind !== "update")
|
|
425
|
+
return skillUpdateNotConfirmedRefusal();
|
|
426
|
+
const followingId = typeof following.memoryId === "string" ? following.memoryId : null;
|
|
427
|
+
if (!followingId)
|
|
428
|
+
return skillUpdateNotConfirmedRefusal();
|
|
429
|
+
let followingRow;
|
|
430
|
+
try {
|
|
431
|
+
followingRow = await args.memory.get(followingId, {});
|
|
432
|
+
}
|
|
433
|
+
catch {
|
|
434
|
+
return skillUpdateUnconfirmedFailure();
|
|
435
|
+
}
|
|
436
|
+
if (!followingRow || String(followingRow.supersedes ?? "") !== String(args.successor.id)) {
|
|
437
|
+
return skillUpdateNotConfirmedRefusal();
|
|
438
|
+
}
|
|
439
|
+
return null;
|
|
440
|
+
}
|
|
441
|
+
/**
|
|
442
|
+
* flair#2645 — confirm a skill close in a fresh committed read, then answer
|
|
443
|
+
* success only when the committed store shows it. Harper can resolve the
|
|
444
|
+
* close's commit while skipping the queued full put (it loses to a newer write
|
|
445
|
+
* of the same row) and still commit the request's other writes. A close that
|
|
446
|
+
* did not land is re-applied from a fresh read, re-checking the row's identity
|
|
447
|
+
* and the caller's authority. Exhausted retries run compensation before the
|
|
448
|
+
* named refusal; unconfirmed compensation returns a named 500.
|
|
449
|
+
* Returns null only when the close and any caller-supplied effect are confirmed.
|
|
450
|
+
*/
|
|
451
|
+
export async function confirmSkillClose(args) {
|
|
452
|
+
const journal = currentWriteJournal() ?? new WriteJournal();
|
|
453
|
+
return journal.run(async () => {
|
|
454
|
+
const result = await confirmSkillCloseInner(args, journal);
|
|
455
|
+
if (result && !journal.compensationAttempted && journal.entries.some((entry) => entry.applied)) {
|
|
456
|
+
return (await compensateUnlandedSkillUpdate({ ctx: args.ctx, journal, held: args.held })) ?? result;
|
|
457
|
+
}
|
|
458
|
+
return result;
|
|
459
|
+
});
|
|
460
|
+
}
|
|
461
|
+
async function confirmSkillCloseInner(args, journal) {
|
|
462
|
+
const { ctx, table, expected, closePatch, authorize, afterStaged, confirmEffect, refusal, unconfirmed } = args;
|
|
463
|
+
const compensate = () => compensateUnlandedSkillUpdate({ ctx, journal, held: args.held });
|
|
464
|
+
const attempts = args.attempts ?? SKILL_UPDATE_CLOSE_ATTEMPTS;
|
|
465
|
+
const id = String(expected.id);
|
|
466
|
+
for (let attempt = 1;; attempt++) {
|
|
467
|
+
let committed;
|
|
468
|
+
try {
|
|
469
|
+
committed = await table.get(id, {});
|
|
470
|
+
}
|
|
471
|
+
catch {
|
|
472
|
+
return unconfirmed();
|
|
473
|
+
}
|
|
474
|
+
if (!committed) {
|
|
475
|
+
const denied = args.missing?.() ?? storedRowChangedRefusal("Memory");
|
|
476
|
+
return (await compensate()) ?? denied;
|
|
477
|
+
}
|
|
478
|
+
if (!sameStoredRow(committed, expected)) {
|
|
479
|
+
// Replaced between the reads: not the row the caller meant.
|
|
480
|
+
return (await compensate()) ?? storedRowChangedRefusal("Memory");
|
|
481
|
+
}
|
|
482
|
+
if (typeof committed.validTo === "string" && committed.validTo.length > 0) {
|
|
483
|
+
const denied = confirmEffect ? await confirmEffect() : null;
|
|
484
|
+
return denied ? (await compensate()) ?? denied : null;
|
|
485
|
+
}
|
|
486
|
+
if (attempt > attempts)
|
|
487
|
+
break;
|
|
488
|
+
let applied;
|
|
489
|
+
try {
|
|
490
|
+
// Hold the row's id across the retry's fresh transaction (flair#2950).
|
|
491
|
+
const locked = await withSkillMemoryLocks([id], args.held ?? NO_HELD_IDS, () => withOwnedTransaction(ctx, async (c) => {
|
|
492
|
+
const stored = await table.get(id, c);
|
|
493
|
+
if (!stored)
|
|
494
|
+
return "staged";
|
|
495
|
+
if (!sameStoredRow(stored, expected))
|
|
496
|
+
return storedRowChangedRefusal("Memory");
|
|
497
|
+
const denied = await authorize(stored, c);
|
|
498
|
+
if (denied)
|
|
499
|
+
return denied;
|
|
500
|
+
const closed = { ...stored, ...closePatch };
|
|
501
|
+
normalizeEmptyEmbedding(closed);
|
|
502
|
+
const result = storageResult(await table.put(closed, c));
|
|
503
|
+
if (result instanceof Response)
|
|
504
|
+
throw result;
|
|
505
|
+
const revoked = await afterStaged?.(stored, attempt);
|
|
506
|
+
if (revoked)
|
|
507
|
+
throw revoked;
|
|
508
|
+
return "staged";
|
|
509
|
+
}));
|
|
510
|
+
if (!locked.locked)
|
|
511
|
+
return unconfirmed();
|
|
512
|
+
applied = locked.value;
|
|
513
|
+
}
|
|
514
|
+
catch (err) {
|
|
515
|
+
if (err instanceof Response)
|
|
516
|
+
applied = err;
|
|
517
|
+
else
|
|
518
|
+
return unconfirmed();
|
|
519
|
+
}
|
|
520
|
+
if (applied instanceof Response)
|
|
521
|
+
return (await compensate()) ?? applied;
|
|
522
|
+
}
|
|
523
|
+
return (await compensate()) ?? refusal();
|
|
524
|
+
}
|
|
525
|
+
/**
|
|
526
|
+
* flair#2645 — confirm the predecessor close and either this request's
|
|
527
|
+
* successor as the subject's only live head or its ordered supersession while closed.
|
|
528
|
+
*/
|
|
529
|
+
async function confirmSkillUpdate(args) {
|
|
530
|
+
const { ctx, subjectId, predecessor, closePatch, successor, grantedClose, authorize } = args;
|
|
531
|
+
const table = databases.flair?.Memory;
|
|
532
|
+
if (!table || typeof table.get !== "function" || typeof table.put !== "function") {
|
|
533
|
+
return skillUpdateUnconfirmedFailure();
|
|
534
|
+
}
|
|
535
|
+
const confirmsSingleHead = async () => {
|
|
536
|
+
let successorCommitted;
|
|
537
|
+
try {
|
|
538
|
+
successorCommitted = await table.get(String(successor.id), {});
|
|
539
|
+
}
|
|
540
|
+
catch {
|
|
541
|
+
return skillUpdateUnconfirmedFailure();
|
|
542
|
+
}
|
|
543
|
+
if (!successorCommitted || !sameStoredRow(successorCommitted, successor)) {
|
|
544
|
+
return skillUpdateNotConfirmedRefusal();
|
|
545
|
+
}
|
|
546
|
+
if (!isOpenLiveRow(successorCommitted)) {
|
|
547
|
+
if (typeof successorCommitted.validTo !== "string" || successorCommitted.validTo.length === 0) {
|
|
548
|
+
return skillUpdateNotConfirmedRefusal();
|
|
549
|
+
}
|
|
550
|
+
// The successor is closed; confirm the ordered supersession.
|
|
551
|
+
return confirmSupersededInOrder({
|
|
552
|
+
subjectId,
|
|
553
|
+
successor,
|
|
554
|
+
appendedVersionId: args.appendedVersionId,
|
|
555
|
+
memory: table,
|
|
556
|
+
});
|
|
557
|
+
}
|
|
558
|
+
if (typeof table.search !== "function")
|
|
559
|
+
return skillUpdateUnconfirmedFailure();
|
|
560
|
+
const live = [];
|
|
561
|
+
try {
|
|
562
|
+
for await (const row of table.search({ conditions: [
|
|
563
|
+
{ attribute: "skillSubjectId", comparator: "equals", value: subjectId },
|
|
564
|
+
] }, {})) {
|
|
565
|
+
if (isOpenLiveRow(row))
|
|
566
|
+
live.push(String(row.id));
|
|
567
|
+
}
|
|
568
|
+
}
|
|
569
|
+
catch {
|
|
570
|
+
return skillUpdateUnconfirmedFailure();
|
|
571
|
+
}
|
|
572
|
+
return live.length === 1 && live[0] === String(successor.id) ? null : skillUpdateNotConfirmedRefusal();
|
|
573
|
+
};
|
|
574
|
+
return confirmSkillClose({
|
|
575
|
+
ctx,
|
|
576
|
+
table,
|
|
577
|
+
expected: predecessor,
|
|
578
|
+
closePatch,
|
|
579
|
+
authorize,
|
|
580
|
+
afterStaged: async (_row, attempt) => {
|
|
581
|
+
const pause = attempt === 1 ? txnPausePoint("skill-update-retry-first")
|
|
582
|
+
: attempt === 2 ? txnPausePoint("skill-update-retry-second")
|
|
583
|
+
: txnPausePoint("skill-update-retry-third");
|
|
584
|
+
if (pause)
|
|
585
|
+
await pause;
|
|
586
|
+
return afterCloseStaged(grantedClose, { predecessorId: String(predecessor.id), successor });
|
|
587
|
+
},
|
|
588
|
+
confirmEffect: confirmsSingleHead,
|
|
589
|
+
missing: () => storedRowChangedRefusal("Memory"),
|
|
590
|
+
refusal: () => skillUpdateNotClosedRefusal(SKILL_UPDATE_CLOSE_ATTEMPTS),
|
|
591
|
+
unconfirmed: skillUpdateUnconfirmedFailure,
|
|
592
|
+
held: args.held,
|
|
593
|
+
});
|
|
594
|
+
}
|
|
595
|
+
/**
|
|
596
|
+
* Run one skill version write atomically. The append helper owns the lock, the
|
|
597
|
+
* version row; this function performs the Memory-side
|
|
598
|
+
* successor/close/pointer writes inside that same transaction.
|
|
599
|
+
*/
|
|
600
|
+
export async function runSkillVersionWrite(args) {
|
|
601
|
+
// A raw table `create` inside the write (the InstructionVersion append, or
|
|
602
|
+
// the successor upsert) can set Harper's `createdResource` flag on the
|
|
603
|
+
// request context, which would surface as HTTP 201. The path a skill write
|
|
604
|
+
// replaces returned 200, so restore the flag's prior value on the way out.
|
|
605
|
+
const restoreCreated = captureCreatedFlag(args.ctx);
|
|
606
|
+
const held = new Set((args.heldMemoryIds ?? []).map((id) => String(id)));
|
|
607
|
+
try {
|
|
608
|
+
const journal = new WriteJournal();
|
|
609
|
+
const result = await journal.run(async () => {
|
|
610
|
+
const r = await runSkillVersionWriteInner(args);
|
|
611
|
+
if (!r.ok && !journal.compensationAttempted && journal.entries.some((entry) => entry.applied)) {
|
|
612
|
+
const failure = await compensateUnlandedSkillUpdate({ ctx: args.ctx, journal, held });
|
|
613
|
+
if (failure)
|
|
614
|
+
return { ok: false, response: failure };
|
|
615
|
+
}
|
|
616
|
+
return r;
|
|
617
|
+
});
|
|
618
|
+
if (result.ok && result.confirm) {
|
|
619
|
+
const confirm = result.confirm;
|
|
620
|
+
return {
|
|
621
|
+
...result,
|
|
622
|
+
confirm: async () => {
|
|
623
|
+
const denial = await confirm();
|
|
624
|
+
if (!denial)
|
|
625
|
+
return null;
|
|
626
|
+
// The caller released the write's Memory locks before this ran.
|
|
627
|
+
const failure = await compensateUnlandedSkillUpdate({ ctx: args.ctx, journal });
|
|
628
|
+
return failure ?? denial;
|
|
629
|
+
},
|
|
630
|
+
};
|
|
631
|
+
}
|
|
632
|
+
return result;
|
|
633
|
+
}
|
|
634
|
+
finally {
|
|
635
|
+
restoreCreated();
|
|
636
|
+
}
|
|
637
|
+
}
|
|
638
|
+
/** Capture the `createdResource` flag on a context and its request, and return a
|
|
639
|
+
* restore callback that puts them back exactly as they were. */
|
|
640
|
+
export function captureCreatedFlag(ctx) {
|
|
641
|
+
const targets = [ctx, ctx?.request].filter((t) => !!t && typeof t === "object");
|
|
642
|
+
const before = targets.map((t) => [t, Object.prototype.hasOwnProperty.call(t, "createdResource"), t.createdResource]);
|
|
643
|
+
return () => {
|
|
644
|
+
for (const [t, had, value] of before) {
|
|
645
|
+
if (had)
|
|
646
|
+
t.createdResource = value;
|
|
647
|
+
else
|
|
648
|
+
delete t.createdResource;
|
|
649
|
+
}
|
|
650
|
+
};
|
|
651
|
+
}
|
|
652
|
+
/** A plan whose success {@link confirmSkillUpdate} checks after the commit. */
|
|
653
|
+
function supersedesPredecessor(plan) {
|
|
654
|
+
return plan.kind === "update" && !!plan.predecessor;
|
|
655
|
+
}
|
|
656
|
+
/** A joined attempt's signal that its plan needs a commit this write owns. */
|
|
657
|
+
const OWNED_COMMIT_REQUIRED = Symbol("skill-version-write.owned-commit-required");
|
|
658
|
+
async function runSkillVersionWriteInner(args) {
|
|
659
|
+
const joined = args.joinCallerTransaction === true && isJoinableTransaction(args.ctx);
|
|
660
|
+
const first = await runSkillVersionAttempt(args, joined);
|
|
661
|
+
if (first !== OWNED_COMMIT_REQUIRED)
|
|
662
|
+
return first;
|
|
663
|
+
// flair#2645: the update is confirmed against the committed store after its
|
|
664
|
+
// commit, which a joined write leaves to the caller. The joined attempt
|
|
665
|
+
// stopped before staging a write; plan again from a fresh head, owned.
|
|
666
|
+
const owned = await runSkillVersionAttempt(args, false);
|
|
667
|
+
if (owned === OWNED_COMMIT_REQUIRED)
|
|
668
|
+
throw new Error("skill-version-write: an owned attempt cannot require an owned commit");
|
|
669
|
+
return owned;
|
|
670
|
+
}
|
|
671
|
+
async function runSkillVersionAttempt(args, joined) {
|
|
672
|
+
let plan = null;
|
|
673
|
+
let owner = "";
|
|
674
|
+
let ownedCommitRequired = false;
|
|
675
|
+
const outcome = await recordVersion(args.ctx, {
|
|
676
|
+
subjectType: "skill",
|
|
677
|
+
prepare: async (shared) => {
|
|
678
|
+
const head = await args.head(shared);
|
|
679
|
+
const built = await args.plan(head, shared, { joined });
|
|
680
|
+
if (built === null)
|
|
681
|
+
return null;
|
|
682
|
+
if (built instanceof Response)
|
|
683
|
+
return built;
|
|
684
|
+
if (joined && supersedesPredecessor(built)) {
|
|
685
|
+
ownedCommitRequired = true;
|
|
686
|
+
return skillUpdateUnconfirmedFailure();
|
|
687
|
+
}
|
|
688
|
+
// A write grant does not include changing a record's visibility;
|
|
689
|
+
// visibility is set by the owner or an admin (grant-visibility.ts). The
|
|
690
|
+
// plan is checked here and again on committed state once the close is
|
|
691
|
+
// staged (afterCloseStaged).
|
|
692
|
+
const visibilityDenial = grantedSuccessorVisibilityDenial(built);
|
|
693
|
+
if (visibilityDenial)
|
|
694
|
+
return visibilityDenial;
|
|
695
|
+
plan = built;
|
|
696
|
+
const target = built.kind === "delete" ? built.predecessor : built.successor;
|
|
697
|
+
owner = String(target.agentId);
|
|
698
|
+
return {
|
|
699
|
+
subjectType: "skill",
|
|
700
|
+
subjectId: args.subjectId,
|
|
701
|
+
agentId: String(target.agentId),
|
|
702
|
+
key: null,
|
|
703
|
+
kind: built.kind,
|
|
704
|
+
rowId: String(target.id),
|
|
705
|
+
value: built.kind === "delete" ? null : built.value,
|
|
706
|
+
memoryId: built.kind === "delete" ? null : String(built.successor.id),
|
|
707
|
+
visibility: built.visibility,
|
|
708
|
+
expectedVersion: args.expectedVersion ?? null,
|
|
709
|
+
};
|
|
710
|
+
},
|
|
711
|
+
}, async (shared) => {
|
|
712
|
+
if (plan === null)
|
|
713
|
+
return okResponse();
|
|
714
|
+
const writePlan = plan;
|
|
715
|
+
if (writePlan.kind === "delete") {
|
|
716
|
+
maybeThrowSkillWriteFault("close", owner);
|
|
717
|
+
const closed = await args.hooks.closePredecessor(writePlan.predecessor, writePlan.closePatch, shared);
|
|
718
|
+
if (closed instanceof Response)
|
|
719
|
+
return storageResult(closed);
|
|
720
|
+
// flair#2511: the grant re-check, after the close is staged.
|
|
721
|
+
const revoked = await afterCloseStaged(writePlan.grantedClose);
|
|
722
|
+
if (revoked)
|
|
723
|
+
return revoked;
|
|
724
|
+
}
|
|
725
|
+
else {
|
|
726
|
+
maybeThrowSkillWriteFault("successor", owner, writePlan.successor);
|
|
727
|
+
const created = await args.hooks.createSuccessor(writePlan.successor, shared);
|
|
728
|
+
if (created instanceof Response)
|
|
729
|
+
return storageResult(created);
|
|
730
|
+
if (writePlan.predecessor) {
|
|
731
|
+
maybeThrowSkillWriteFault("close", owner);
|
|
732
|
+
const closed = await args.hooks.closePredecessor(writePlan.predecessor, writePlan.closePatch, shared);
|
|
733
|
+
if (closed instanceof Response)
|
|
734
|
+
return storageResult(closed);
|
|
735
|
+
// flair#2511: the grant re-check, after the close is staged, with the
|
|
736
|
+
// committed-visibility check for a grant-authorized successor.
|
|
737
|
+
const revoked = await afterCloseStaged(writePlan.grantedClose, {
|
|
738
|
+
predecessorId: String(writePlan.predecessor.id), successor: writePlan.successor,
|
|
739
|
+
});
|
|
740
|
+
if (revoked)
|
|
741
|
+
return revoked;
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
maybeThrowSkillWriteFault("pointer", owner);
|
|
745
|
+
const pointerDenial = await args.hooks.pointer?.(shared);
|
|
746
|
+
if (pointerDenial)
|
|
747
|
+
return pointerDenial;
|
|
748
|
+
return okResponse();
|
|
749
|
+
}, joined);
|
|
750
|
+
if (ownedCommitRequired)
|
|
751
|
+
return OWNED_COMMIT_REQUIRED;
|
|
752
|
+
if (!outcome.ok || plan === null)
|
|
753
|
+
return outcome;
|
|
754
|
+
const writePlan = plan;
|
|
755
|
+
if (!supersedesPredecessor(writePlan))
|
|
756
|
+
return outcome;
|
|
757
|
+
const confirm = async () => {
|
|
758
|
+
// Test-only: inert unless armed. Pauses between the committed write and the
|
|
759
|
+
// confirmation read, so a later update of the same subject can complete.
|
|
760
|
+
// The pause stays outside the confirmation's lock acquisition.
|
|
761
|
+
const confirmPause = txnPausePoint("skill-update-confirm");
|
|
762
|
+
if (confirmPause)
|
|
763
|
+
await confirmPause;
|
|
764
|
+
const authorize = args.hooks.authorizeClose ?? (async () => skillUpdateUnconfirmedFailure());
|
|
765
|
+
// A deferred confirmation runs after the verb released its Memory locks; an
|
|
766
|
+
// inline one runs under the locks the caller still holds (flair#2950).
|
|
767
|
+
const held = args.deferConfirmation ? NO_HELD_IDS : new Set((args.heldMemoryIds ?? []).map(String));
|
|
768
|
+
// flair#2645: the owned transaction has committed, but its success is not
|
|
769
|
+
// proof that the queued close was applied. Confirm against the committed
|
|
770
|
+
// store before answering success.
|
|
771
|
+
return await confirmSkillUpdate({
|
|
772
|
+
ctx: args.ctx,
|
|
773
|
+
subjectId: args.subjectId,
|
|
774
|
+
predecessor: writePlan.predecessor,
|
|
775
|
+
closePatch: writePlan.closePatch,
|
|
776
|
+
successor: writePlan.successor,
|
|
777
|
+
grantedClose: writePlan.grantedClose,
|
|
778
|
+
authorize,
|
|
779
|
+
held,
|
|
780
|
+
appendedVersionId: outcome.version || null,
|
|
781
|
+
});
|
|
782
|
+
};
|
|
783
|
+
if (args.deferConfirmation)
|
|
784
|
+
return { ...outcome, confirm };
|
|
785
|
+
const confirmation = await confirm();
|
|
786
|
+
if (confirmation)
|
|
787
|
+
return { ok: false, response: confirmation };
|
|
788
|
+
return outcome;
|
|
789
|
+
}
|