@tpsdev-ai/flair 0.62.0 → 0.63.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -6
- package/SECURITY.md +18 -10
- package/config.yaml +11 -11
- package/dist/bridges/runtime/execute.js +1 -0
- package/dist/bridges/types.js +1 -0
- package/dist/build-info.json +3 -3
- package/dist/cli.js +66 -122
- package/dist/commands/agent.js +27 -65
- package/dist/commands/backup-approval.js +218 -0
- package/dist/commands/backup.js +37 -33
- package/dist/commands/bootstrap.js +3 -1
- package/dist/commands/deploy.js +37 -7
- package/dist/commands/doctor.js +119 -0
- package/dist/commands/export.js +3 -4
- package/dist/commands/federation.js +653 -68
- package/dist/commands/grant.js +5 -6
- package/dist/commands/help.js +25 -0
- package/dist/commands/idp.js +14 -19
- package/dist/commands/import.js +131 -19
- package/dist/commands/init.js +7 -7
- package/dist/commands/integrity.js +5 -6
- package/dist/commands/mcp.js +11 -17
- package/dist/commands/memory.js +33 -15
- package/dist/commands/orgevent.js +5 -10
- package/dist/commands/principal.js +13 -25
- package/dist/commands/quality.js +3 -0
- package/dist/commands/rem.js +484 -65
- package/dist/commands/restore.js +352 -44
- package/dist/commands/service.js +84 -2
- package/dist/commands/soul.js +0 -6
- package/dist/commands/status.js +51 -33
- package/dist/commands/test.js +4 -1
- package/dist/commands/upgrade.js +53 -22
- package/dist/commands/workspace.js +7 -8
- package/dist/deploy.js +59 -3
- package/dist/doctor-client.js +7 -2
- package/dist/fabric-upgrade.js +12 -2
- package/dist/federation/presence-send.js +139 -0
- package/dist/federation-verify.js +269 -177
- package/dist/install/clients.js +171 -35
- package/dist/lib/agent-id-rule.js +44 -2
- package/dist/lib/atomic-write.js +1 -1
- package/dist/lib/auth-resolve.js +1028 -52
- package/dist/lib/backup-approval-store.js +612 -0
- package/dist/lib/backup-artifact.js +343 -0
- package/dist/lib/config-critical-section.js +212 -25
- package/dist/lib/connect-phase.js +33 -0
- package/dist/lib/daemon-liveness.js +2 -1
- package/dist/lib/federation-pair-access.js +4 -0
- package/dist/lib/federation-retry-queue.js +283 -0
- package/dist/lib/federation-retry-row.js +101 -0
- package/dist/lib/instruction-event-contract.js +17 -0
- package/dist/lib/instruction-event-doctor.js +102 -0
- package/dist/lib/launchd-management.js +14 -3
- package/dist/lib/mcp-enable.js +14 -15
- package/dist/lib/memory-attributes.js +2 -0
- package/dist/lib/memory-provider-timeout.js +33 -0
- package/dist/lib/mqtt-config.js +132 -0
- package/dist/lib/mqtt-listener-doctor.js +104 -0
- package/dist/lib/open-live-row.js +20 -0
- package/dist/lib/ops-url.js +52 -0
- package/dist/lib/promotion-content-hash.js +20 -0
- package/dist/lib/restore-archive.js +760 -0
- package/dist/lib/restore-verify.js +1 -1
- package/dist/lib/skill-assignment-preflight.js +159 -0
- package/dist/lib/skill-seed.js +91 -8
- package/dist/lib/skill-tombstone-doctor.js +133 -0
- package/dist/lib/soul-scope-fields.js +26 -0
- package/dist/lib/uninstall-purge.js +266 -11
- package/dist/lib/upgrade-prior-liveness.js +2 -1
- package/dist/mcp-client-assertion.js +2 -10
- package/dist/memory-id-checkpoint.js +28 -7
- package/dist/mqtt-off-deploy.js +550 -0
- package/dist/rem/promote-policy.js +3 -3
- package/dist/rem/restore.js +302 -26
- package/dist/rem/runner.js +220 -58
- package/dist/rem/scheduler.js +21 -4
- package/dist/resources/A2AAdapter.js +131 -178
- package/dist/resources/AdminMemory.js +2 -0
- package/dist/resources/AdminMemoryCandidates.js +116 -0
- package/dist/resources/Agent.js +155 -45
- package/dist/resources/AgentCard.js +4 -0
- package/dist/resources/AgentKeyRegister.js +56 -22
- package/dist/resources/AgentReadPosition.js +7 -0
- package/dist/resources/AgentSeed.js +232 -107
- package/dist/resources/AutoPromoteCandidates.js +413 -84
- package/dist/resources/Credential.js +6 -8
- package/dist/resources/Federation.js +219 -57
- package/dist/resources/FederationRetry.js +4 -4
- package/dist/resources/InstructionVersion.js +1 -1
- package/dist/resources/MCPClientMetadata.js +6 -3
- package/dist/resources/Memory.js +1303 -270
- package/dist/resources/MemoryArchive.js +149 -64
- package/dist/resources/MemoryBootstrap.js +12 -22
- package/dist/resources/MemoryCandidate.js +16 -2
- package/dist/resources/MemoryConsolidate.js +2 -2
- package/dist/resources/MemoryFeed.js +360 -147
- package/dist/resources/MemoryMaintenance.js +290 -72
- package/dist/resources/MemoryPurge.js +138 -22
- package/dist/resources/MemoryReflect.js +68 -14
- package/dist/resources/MemoryReindex.js +91 -13
- package/dist/resources/Message.js +11 -2
- package/dist/resources/OAuth.js +156 -39
- package/dist/resources/OAuthClient.js +1 -1
- package/dist/resources/OrgEvent.js +292 -29
- package/dist/resources/OrgEventCatchup.js +7 -0
- package/dist/resources/OrgEventMaintenance.js +48 -10
- package/dist/resources/PairingToken.js +1 -1
- package/dist/resources/Presence.js +31 -11
- package/dist/resources/PromoteMemoryCandidate.js +8 -2
- package/dist/resources/RecordUsage.js +2 -4
- package/dist/resources/Soul.js +2 -0
- package/dist/resources/SoulFeed.js +2 -1
- package/dist/resources/WorkspaceLatest.js +4 -0
- package/dist/resources/XAA.js +36 -10
- package/dist/resources/a2a-stream.js +313 -0
- package/dist/resources/a2a-url.js +4 -5
- package/dist/resources/agent-admin.js +10 -1
- package/dist/resources/agent-auth.js +98 -68
- package/dist/resources/agent-read-position-lib.js +4 -1
- package/dist/resources/agent-status-guard.js +9 -7
- package/dist/resources/auth-middleware.js +166 -42
- package/dist/resources/authority-field-guard.js +9 -11
- package/dist/resources/auto-promote-lib.js +8 -5
- package/dist/resources/basic-auth-header.js +21 -0
- package/dist/resources/bm25-index-service.js +4 -5
- package/dist/resources/dedup-cluster.js +6 -1
- package/dist/resources/embeddings-provider.js +25 -0
- package/dist/resources/federation-classify.js +89 -0
- package/dist/resources/federation-retry-lib.js +6 -81
- package/dist/resources/health.js +43 -4
- package/dist/resources/host-pointer/registry.js +29 -0
- package/dist/resources/host-pointer-adapter.js +1 -0
- package/dist/resources/in-process.js +24 -22
- package/dist/resources/instruction-version-record.js +251 -7
- package/dist/resources/internal-authority.js +13 -0
- package/dist/resources/mcp-handler.js +106 -12
- package/dist/resources/mcp-oauth-flag.js +12 -14
- package/dist/resources/mcp-oauth.js +430 -53
- package/dist/resources/mcp-tools.js +60 -22
- package/dist/resources/memory-declared-attributes.js +1 -0
- package/dist/resources/memory-embed-hash.js +56 -0
- package/dist/resources/memory-host-source.js +5 -2
- package/dist/resources/memory-reflect-lib.js +1 -1
- package/dist/resources/memory-write-lock.js +202 -23
- package/dist/resources/memory-write-response.js +1 -1
- package/dist/resources/memory-write-transaction.js +243 -0
- package/dist/resources/migration-boot.js +17 -12
- package/dist/resources/migrations/boot-progress.js +25 -0
- package/dist/resources/migrations/data-dir.js +16 -3
- package/dist/resources/migrations/dir-safety.js +60 -2
- package/dist/resources/migrations/embedding-stamp.js +315 -49
- package/dist/resources/migrations/graph-heal.js +9 -2
- package/dist/resources/migrations/ledger.js +5 -2
- package/dist/resources/migrations/lock.js +867 -80
- package/dist/resources/migrations/progress.js +71 -10
- package/dist/resources/migrations/runner.js +212 -18
- package/dist/resources/migrations/state.js +36 -1
- package/dist/resources/migrations/status.js +2 -13
- package/dist/resources/migrations/synthetic-test-migration.js +78 -12
- package/dist/resources/migrations/types.js +26 -1
- package/dist/resources/migrations/visibility-backfill.js +111 -70
- package/dist/resources/oauth-discovery.js +0 -5
- package/dist/resources/object-body-guard.js +12 -5
- package/dist/resources/org-event-reserved.js +92 -0
- package/dist/resources/org-event-write-fault.js +19 -0
- package/dist/resources/owner-field-guard.js +1 -1
- package/dist/resources/owner-scoped-write-policy.js +65 -21
- package/dist/resources/owner-scoped-writes.js +37 -6
- package/dist/resources/path-id-rewrite.js +76 -0
- package/dist/resources/presence-internal.js +5 -5
- package/dist/resources/promotion-binding.js +43 -0
- package/dist/resources/promotion-stamp.js +124 -33
- package/dist/resources/protocol-context.js +189 -0
- package/dist/resources/record-type-kit.js +2 -4
- package/dist/resources/request-target.js +28 -1
- package/dist/resources/request-transaction.js +11 -1
- package/dist/resources/seed-reservation.js +1 -2
- package/dist/resources/semantic-retrieval-core.js +7 -6
- package/dist/resources/server-row-validation.js +71 -0
- package/dist/resources/skill-manifest.js +4 -3
- package/dist/resources/skill-version-write.js +384 -27
- package/dist/resources/skill-write-fault.js +6 -3
- package/dist/resources/skill-write-policy.js +2 -1
- package/dist/resources/soul-write-policy.js +26 -7
- package/dist/resources/table-helpers.js +1 -1
- package/dist/resources/table-subscription-policy.js +518 -85
- package/dist/resources/table-subscriptions.js +20 -7
- package/dist/resources/txn-pause-point.js +122 -5
- package/dist/resources/usage-recording.js +54 -46
- package/dist/resources/write-back.js +176 -11
- package/dist/resources/write-journal-context.js +5 -0
- package/dist/resources/write-journal.js +289 -0
- package/dist/src/lib/agent-id-rule.js +44 -2
- package/dist/src/lib/atomic-write.js +1 -1
- package/dist/src/lib/federation-retry-row.js +101 -0
- package/dist/src/lib/instruction-event-contract.js +17 -0
- package/dist/src/lib/memory-attributes.js +2 -0
- package/dist/src/lib/open-live-row.js +20 -0
- package/dist/src/lib/soul-scope-fields.js +26 -0
- package/dist/src/rem/promote-policy.js +3 -3
- package/dist/src/rem/scheduler.js +21 -4
- package/docs/access-control.md +18 -9
- package/docs/api-reference.md +126 -28
- package/docs/auth.md +40 -18
- package/docs/claude-code.md +3 -3
- package/docs/deploying-on-fabric.md +108 -0
- package/docs/deployment.md +17 -0
- package/docs/embedding-in-a-harper-app.md +16 -14
- package/docs/entity-vocabulary.md +3 -6
- package/docs/federation.md +29 -2
- package/docs/integrations.md +11 -11
- package/docs/mcp-clients.md +7 -5
- package/docs/notes/mcp-agent-auth-consumer.md +4 -9
- package/docs/notes/mcp-oauth-model2.md +6 -6
- package/docs/openclaw.md +1 -1
- package/docs/quickstart-fabric.md +2 -2
- package/docs/quickstart.md +3 -3
- package/docs/releasing.md +13 -13
- package/docs/rem.md +24 -3
- package/docs/secrets-and-keys.md +2 -2
- package/docs/standalone-local.md +29 -2
- package/docs/supply-chain-policy.md +28 -20
- package/docs/the-team.md +2 -2
- package/docs/upgrade.md +14 -0
- package/package.json +18 -11
- package/schemas/agent.graphql +3 -3
- package/schemas/federation.graphql +10 -7
- package/schemas/memory.graphql +7 -2
- package/templates/bin/flair-rem-nightly.sh.tmpl +7 -1
- package/templates/launchd/start-flair-with-admin-pass.sh +188 -10
- package/dist/resources/soul-adk-guard.js +0 -68
|
@@ -1,11 +1,24 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Installs the table-subscription guard
|
|
3
|
-
* on every table class in the flair
|
|
4
|
-
* component loads: the static `connect()`
|
|
5
|
-
* Harper uses for an exported table's SSE and WebSocket subscription
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
2
|
+
* Installs the table-subscription guard
|
|
3
|
+
* (resources/table-subscription-policy.ts) on every table class in the flair
|
|
4
|
+
* database's table registry when the component loads: the static `connect()`
|
|
5
|
+
* (the entry Harper uses for an exported table's SSE and WebSocket subscription
|
|
6
|
+
* routes), `subscribe()` (an MQTT SUBSCRIBE, and Harper's native MCP
|
|
7
|
+
* `resources/subscribe` when that component is configured) and `publish()` (an
|
|
8
|
+
* MQTT PUBLISH) of each table class admit only administrators and trusted
|
|
9
|
+
* internal calls, and so do its static `put()` and `delete()` for a call where
|
|
10
|
+
* an argument Harper may take as the context carries the markers of an MQTT
|
|
11
|
+
* session's context or of a copy of a stored will record Harper replays (a
|
|
12
|
+
* retained MQTT PUBLISH or last-will); every other put()/delete() call passes
|
|
13
|
+
* through with the same arguments and no caller resolved. Each guarded static
|
|
14
|
+
* decides the contexts Harper may take from the call's arguments (every listed
|
|
15
|
+
* reading, or for put()/delete() every marked candidate; see the policy module
|
|
16
|
+
* for what is read and what is listed); the guard's boundary is protocol-layer
|
|
17
|
+
* callers, whose contexts Harper constructs, and in-process code is trusted.
|
|
18
|
+
* Harper's native MCP route resolves every caller as anonymous, so it refuses
|
|
19
|
+
* administrators too (see the policy module). The tables are read from the
|
|
20
|
+
* registry, so the class of a table added to the schema gets the guard without
|
|
21
|
+
* being named here.
|
|
9
22
|
*
|
|
10
23
|
* This module deliberately exports nothing: Harper registers exported values of
|
|
11
24
|
* a resource module as routes.
|
|
@@ -24,9 +24,8 @@ const POLL_MS = 20;
|
|
|
24
24
|
* (after the pre-existing ownership read, before the delete's transactional
|
|
25
25
|
* re-read or staging) and an in-transaction point (between that transaction's
|
|
26
26
|
* ownership re-read and its delete), so both interleavings of a concurrent
|
|
27
|
-
* owner change can be exercised. The write transaction is one the delete
|
|
28
|
-
*
|
|
29
|
-
* request-owned transaction when one exists and creates one otherwise.
|
|
27
|
+
* owner change can be exercised. The write transaction is one the delete owns
|
|
28
|
+
* (Memory's ordinary delete included, since flair#2632).
|
|
30
29
|
*/
|
|
31
30
|
export const PAUSE_POINT_PATTERN = /^[a-z]+(?:-[a-z]+)*$/;
|
|
32
31
|
/** The named error a pause-point name that does not match `PAUSE_POINT_PATTERN` is refused with (flair#2382). */
|
|
@@ -47,7 +46,125 @@ function logRefusal() {
|
|
|
47
46
|
refusalLogged = true;
|
|
48
47
|
console.warn("txn-pause-point: filesystem check failed; hook inert");
|
|
49
48
|
}
|
|
50
|
-
|
|
49
|
+
/**
|
|
50
|
+
* A test-only failure switch, gated and path-checked like {@link txnPausePoint}:
|
|
51
|
+
* true when the caller armed `fail.<point>`. The caller turns it into the
|
|
52
|
+
* failure its branch handles (a thrown read, a skipped write). Inert unless
|
|
53
|
+
* the fault-injection opt-in is set.
|
|
54
|
+
*/
|
|
55
|
+
export function txnFault(point, env = process.env) {
|
|
56
|
+
if (!PAUSE_POINT_PATTERN.test(point))
|
|
57
|
+
throw new InvalidPausePointError(point);
|
|
58
|
+
if (env[TEST_FAULT_INJECTION_ENV] !== "1")
|
|
59
|
+
return false;
|
|
60
|
+
let armPath;
|
|
61
|
+
try {
|
|
62
|
+
const configured = env[TEST_PAUSE_DIR_ENV];
|
|
63
|
+
if (!configured || !isAbsolute(configured) || !process.getuid || !constants.O_NOFOLLOW)
|
|
64
|
+
throw new Error();
|
|
65
|
+
const dir = realpathSync(configured);
|
|
66
|
+
const info = statSync(dir);
|
|
67
|
+
if (lstatSync(configured).isSymbolicLink() || !isInside(realpathSync(tmpdir()), dir) ||
|
|
68
|
+
!info.isDirectory() || info.uid !== process.getuid() || (info.mode & 0o022) !== 0)
|
|
69
|
+
throw new Error();
|
|
70
|
+
armPath = join(dir, `fail.${point}`);
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
logRefusal();
|
|
74
|
+
return false;
|
|
75
|
+
}
|
|
76
|
+
try {
|
|
77
|
+
const fd = openSync(armPath, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
78
|
+
if (!fstatSync(fd).isFile()) {
|
|
79
|
+
closeSync(fd);
|
|
80
|
+
return false;
|
|
81
|
+
}
|
|
82
|
+
closeSync(fd);
|
|
83
|
+
unlinkSync(armPath);
|
|
84
|
+
return true;
|
|
85
|
+
}
|
|
86
|
+
catch (error) {
|
|
87
|
+
if (error.code === "ENOENT")
|
|
88
|
+
return false;
|
|
89
|
+
logRefusal();
|
|
90
|
+
return false;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
/**
|
|
94
|
+
* Synchronous form of {@link txnPausePoint} for callers that cannot await
|
|
95
|
+
* (migration-lock acquisition is synchronous). It claims the same
|
|
96
|
+
* `arm.<point>` / `paused.<point>` / `released.<point>` / `go.<point>` marker
|
|
97
|
+
* files and blocks the calling thread in bounded sleeps until the go file
|
|
98
|
+
* appears or `limitMs` expires. Inert unless the fault-injection opt-in is
|
|
99
|
+
* set (flair#2866).
|
|
100
|
+
*/
|
|
101
|
+
export function txnPausePointSync(point, env = process.env, limitMs = PAUSE_LIMIT_MS, snapshot) {
|
|
102
|
+
if (!PAUSE_POINT_PATTERN.test(point))
|
|
103
|
+
throw new InvalidPausePointError(point);
|
|
104
|
+
if (env[TEST_FAULT_INJECTION_ENV] !== "1")
|
|
105
|
+
return;
|
|
106
|
+
let armFd;
|
|
107
|
+
let pausedFd;
|
|
108
|
+
let releasedFd;
|
|
109
|
+
let dir;
|
|
110
|
+
try {
|
|
111
|
+
const configured = env[TEST_PAUSE_DIR_ENV];
|
|
112
|
+
if (!configured || !isAbsolute(configured) || !process.getuid || !constants.O_NOFOLLOW)
|
|
113
|
+
throw new Error();
|
|
114
|
+
dir = realpathSync(configured);
|
|
115
|
+
const info = statSync(dir);
|
|
116
|
+
if (lstatSync(configured).isSymbolicLink() || !isInside(realpathSync(tmpdir()), dir) ||
|
|
117
|
+
!info.isDirectory() || info.uid !== process.getuid() || (info.mode & 0o022) !== 0)
|
|
118
|
+
throw new Error();
|
|
119
|
+
const armPath = join(dir, `arm.${point}`);
|
|
120
|
+
try {
|
|
121
|
+
armFd = openSync(armPath, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
122
|
+
}
|
|
123
|
+
catch (error) {
|
|
124
|
+
if (error.code === "ENOENT")
|
|
125
|
+
return;
|
|
126
|
+
throw error;
|
|
127
|
+
}
|
|
128
|
+
if (!fstatSync(armFd).isFile())
|
|
129
|
+
throw new Error();
|
|
130
|
+
const flags = constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW;
|
|
131
|
+
closeSync(openSync(join(dir, `claimed.${point}`), flags, 0o600));
|
|
132
|
+
pausedFd = openSync(join(dir, `paused.${point}`), flags, 0o600);
|
|
133
|
+
releasedFd = openSync(join(dir, `released.${point}`), flags, 0o600);
|
|
134
|
+
writeFileSync(pausedFd, snapshot === undefined ? String(Date.now()) : JSON.stringify(snapshot));
|
|
135
|
+
unlinkSync(armPath);
|
|
136
|
+
}
|
|
137
|
+
catch {
|
|
138
|
+
if (pausedFd !== undefined)
|
|
139
|
+
closeSync(pausedFd);
|
|
140
|
+
if (releasedFd !== undefined)
|
|
141
|
+
closeSync(releasedFd);
|
|
142
|
+
logRefusal();
|
|
143
|
+
return;
|
|
144
|
+
}
|
|
145
|
+
finally {
|
|
146
|
+
if (armFd !== undefined)
|
|
147
|
+
closeSync(armFd);
|
|
148
|
+
}
|
|
149
|
+
const paused = pausedFd;
|
|
150
|
+
const released = releasedFd;
|
|
151
|
+
try {
|
|
152
|
+
const go = join(dir, `go.${point}`);
|
|
153
|
+
const deadline = Date.now() + limitMs;
|
|
154
|
+
const sleeper = new Int32Array(new SharedArrayBuffer(4));
|
|
155
|
+
while (!existsSync(go) && Date.now() < deadline)
|
|
156
|
+
Atomics.wait(sleeper, 0, 0, POLL_MS);
|
|
157
|
+
writeFileSync(released, existsSync(go) ? "go" : "timeout");
|
|
158
|
+
}
|
|
159
|
+
catch {
|
|
160
|
+
logRefusal();
|
|
161
|
+
}
|
|
162
|
+
finally {
|
|
163
|
+
closeSync(paused);
|
|
164
|
+
closeSync(released);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
export function txnPausePoint(point, env = process.env, limitMs = PAUSE_LIMIT_MS, snapshot) {
|
|
51
168
|
if (!PAUSE_POINT_PATTERN.test(point))
|
|
52
169
|
throw new InvalidPausePointError(point);
|
|
53
170
|
if (env[TEST_FAULT_INJECTION_ENV] !== "1")
|
|
@@ -81,7 +198,7 @@ export function txnPausePoint(point, env = process.env, limitMs = PAUSE_LIMIT_MS
|
|
|
81
198
|
closeSync(claimedFd);
|
|
82
199
|
pausedFd = openSync(join(dir, `paused.${point}`), flags, 0o600);
|
|
83
200
|
releasedFd = openSync(join(dir, `released.${point}`), flags, 0o600);
|
|
84
|
-
writeFileSync(pausedFd, String(Date.now()));
|
|
201
|
+
writeFileSync(pausedFd, snapshot === undefined ? String(Date.now()) : JSON.stringify(snapshot));
|
|
85
202
|
unlinkSync(armPath);
|
|
86
203
|
}
|
|
87
204
|
catch {
|
|
@@ -58,6 +58,7 @@ import { withKeyLock } from "./key-lock.js";
|
|
|
58
58
|
import { withDetachedTxn } from "./table-helpers.js";
|
|
59
59
|
import { withOwnedTransaction } from "./request-transaction.js";
|
|
60
60
|
import { WriteBackConflictError, writeBackCommittedRow } from "./write-back.js";
|
|
61
|
+
import { withMemoryWriteLockOnce } from "./memory-write-lock.js";
|
|
61
62
|
import { txnPausePoint } from "./txn-pause-point.js";
|
|
62
63
|
import { resolveReadScope } from "./memory-read-scope.js";
|
|
63
64
|
/**
|
|
@@ -106,16 +107,23 @@ export class UsageLedgerReadError extends Error {
|
|
|
106
107
|
* The ledger read and any create share an owned transaction. The count bump
|
|
107
108
|
* uses a separate owned transaction through writeBackCommittedRow.
|
|
108
109
|
*
|
|
110
|
+
* flair#2478: the whole contribution runs under the memory id's per-id write
|
|
111
|
+
* lock (resources/memory-write-lock.ts), taken before the ledger lock and once
|
|
112
|
+
* without waiting. The count bump is then decided on a committed row that an
|
|
113
|
+
* ordinary owner PUT, PATCH or DELETE in the same Harper process, which holds
|
|
114
|
+
* the lock until it commits, cannot change under it. Not serialized with it: a
|
|
115
|
+
* composed PUT that commits after releasing its lock, and a raw operations
|
|
116
|
+
* write. A contribution that cannot take that lock, or the ledger lock,
|
|
117
|
+
* writes nothing for that id and is logged as skipped.
|
|
118
|
+
*
|
|
109
119
|
* The count bump is the shared write-back helper (write-back.ts): the row is
|
|
110
120
|
* read inside a transaction this call OWNS, the bump is built from THAT read,
|
|
111
121
|
* and the committed row is re-read before commit. The plan skips an absent
|
|
112
122
|
* row or one outside the agent's read scope before any identity comparison.
|
|
113
123
|
* For a row the plan does not skip, an identity change the in-transaction read
|
|
114
|
-
* already sees throws WriteBackConflictError at once (no retry). Only a
|
|
115
|
-
*
|
|
116
|
-
*
|
|
117
|
-
* WriteBackConflictError). recordUsageBatch / recordCitations log either
|
|
118
|
-
* refusal with the reason `stored_row_changed`. The earlier read only decides
|
|
124
|
+
* already sees throws WriteBackConflictError at once (no retry). Only a
|
|
125
|
+
* pre-commit conflict retries. A post-commit mismatch is terminal and
|
|
126
|
+
* unconfirmed. The earlier read only decides
|
|
119
127
|
* the read-scope gate above; it never authorizes the count write on its own.
|
|
120
128
|
*
|
|
121
129
|
* Called by recordUsageBatch() (POST /RecordUsage, explicit usage feedback)
|
|
@@ -123,15 +131,38 @@ export class UsageLedgerReadError extends Error {
|
|
|
123
131
|
* semantics regardless of which surface triggered the contribution.
|
|
124
132
|
*/
|
|
125
133
|
export async function recordUsageContribution(ctx, agentId, memoryId, attribution, now, canRead) {
|
|
126
|
-
//
|
|
127
|
-
//
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
//
|
|
131
|
-
//
|
|
132
|
-
//
|
|
133
|
-
|
|
134
|
+
// Global lock order (flair#2478): the sorted Memory id locks first, then the
|
|
135
|
+
// usage ledger. Memory.put() records its citations after releasing its target
|
|
136
|
+
// id's lock, so a citation holds no other Memory id lock when it tries this
|
|
137
|
+
// one. The whole contribution — the ledger check, any ledger create
|
|
138
|
+
// and the count bump — runs under the memory id's write lock, taken once with
|
|
139
|
+
// no wait: the count bump's decision is then made on a committed row an
|
|
140
|
+
// ordinary owner PUT or PATCH cannot change under it (the writes it does not
|
|
141
|
+
// serialize are named above).
|
|
142
|
+
// Test-only: before this contribution tries the memory id's lock.
|
|
143
|
+
const beforeLock = txnPausePoint("usage-contribution-lock");
|
|
144
|
+
if (beforeLock)
|
|
145
|
+
await beforeLock;
|
|
146
|
+
const memoryOutcome = await withMemoryWriteLockOnce(databases?.flair?.Memory?.primaryStore, [memoryId], async () => {
|
|
147
|
+
// Within one Harper process, the per-(agentId, memoryId) lock serializes
|
|
148
|
+
// contributions across the ledger check, any create and any count bump.
|
|
149
|
+
const store = databases?.flair?.MemoryUsage?.primaryStore;
|
|
150
|
+
return withKeyLock(store, [USAGE_LEDGER_LOCK_NAMESPACE, agentId, memoryId], () => recordUsageContributionLocked(ctx, agentId, memoryId, attribution, now, canRead), USAGE_LOCK_ATTEMPTS, USAGE_LOCK_WAIT_MS);
|
|
151
|
+
}, { phase: "usage-count" });
|
|
152
|
+
// The memory lock could not be acquired (a held id, an outcome-unknown
|
|
153
|
+
// marker, or a store with no lock): this contribution writes nothing and is
|
|
154
|
+
// skipped, never written unserialized over an owner's write. It is reported
|
|
155
|
+
// here; the caller still gets its recorded response. Other ids in the same
|
|
156
|
+
// batch may already have been credited.
|
|
157
|
+
if (memoryOutcome.kind !== "done") {
|
|
158
|
+
console.warn("[usage-recording] contribution skipped: %s for memory %s", memoryOutcome.kind, memoryId);
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
// The ledger lock could not be acquired: same skip, same report.
|
|
162
|
+
if (memoryOutcome.value.kind !== "done") {
|
|
163
|
+
console.warn("[usage-recording] contribution skipped: usage_ledger_%s for memory %s", memoryOutcome.value.kind, memoryId);
|
|
134
164
|
return;
|
|
165
|
+
}
|
|
135
166
|
// Test-only: pause after the ledger lock releases and the owned transaction
|
|
136
167
|
// commits, before this request's transaction commits (flair#2333).
|
|
137
168
|
const committed = txnPausePoint("usage-ledger-lock-released");
|
|
@@ -195,18 +226,6 @@ async function recordUsageContributionLocked(ctx, agentId, memoryId, attribution
|
|
|
195
226
|
});
|
|
196
227
|
if (!prepared)
|
|
197
228
|
return;
|
|
198
|
-
// Targeted usageCount-ONLY bump: an INCREMENTAL update of exactly this one
|
|
199
|
-
// field through the shared helper, against the RAW Memory table, NEVER
|
|
200
|
-
// Memory.put() (the resource class): that would 403 this cross-agent write via
|
|
201
|
-
// its ownership check, and bypassing that check directly would risk letting
|
|
202
|
-
// this write path smuggle OTHER field changes through instead of just the
|
|
203
|
-
// count (RecordUsage.ts module doc's "WHY THIS IS ITS OWN ENDPOINT"). The helper
|
|
204
|
-
// confirms, inside its own transaction, that the stored row is still the one
|
|
205
|
-
// this contribution was checked against (flair#2441): a row deleted or purged
|
|
206
|
-
// before the in-transaction read is skipped by the plan (absent row), as is a
|
|
207
|
-
// row outside the agent's read scope; for any other row an identity mismatch
|
|
208
|
-
// seen by the check is refused. An error from the transactional read is not
|
|
209
|
-
// caught here: it propagates to the caller.
|
|
210
229
|
await writeBackCommittedRow(databases.flair.Memory, memoryId, (row) => {
|
|
211
230
|
// Deleted, or moved out of the agent's read scope, between the check
|
|
212
231
|
// above and this read — the count is not bumped (the ledger row written
|
|
@@ -214,9 +233,7 @@ async function recordUsageContributionLocked(ctx, agentId, memoryId, attribution
|
|
|
214
233
|
// read scope.
|
|
215
234
|
if (!row || !canRead(row))
|
|
216
235
|
return { skip: true };
|
|
217
|
-
|
|
218
|
-
// full-row put of the row read above (flair#2470).
|
|
219
|
-
return { update: { usageCount: (row.usageCount ?? 0) + 1 } };
|
|
236
|
+
return { idempotent: false, commitMarkerField: "writeBackWriteId", update: { usageCount: (row.usageCount ?? 0) + 1 } };
|
|
220
237
|
}, {
|
|
221
238
|
ctx,
|
|
222
239
|
label: "usage-recording",
|
|
@@ -226,6 +243,9 @@ async function recordUsageContributionLocked(ctx, agentId, memoryId, attribution
|
|
|
226
243
|
expectedRow: prepared,
|
|
227
244
|
pausePre: () => txnPausePoint("usage-count-pre"),
|
|
228
245
|
pausePoint: () => txnPausePoint("usage-count"),
|
|
246
|
+
pauseAfterStage: () => txnPausePoint("usage-count-staged"),
|
|
247
|
+
pauseBeforeCommit: () => txnPausePoint("usage-count-commit"),
|
|
248
|
+
pauseBeforeVerify: () => txnPausePoint("usage-count-verify"),
|
|
229
249
|
});
|
|
230
250
|
}
|
|
231
251
|
/**
|
|
@@ -322,14 +342,9 @@ export async function recordCitations(ctx, auth, usedMemoryIds, now, recordFn =
|
|
|
322
342
|
await recordFn(ctx, auth.agentId, id, undefined, now, scope.isAllowed);
|
|
323
343
|
}
|
|
324
344
|
catch (err) {
|
|
325
|
-
//
|
|
326
|
-
// as RecordUsage.post()'s loop, log server-side only.
|
|
345
|
+
// Log per-id failures without stopping the batch.
|
|
327
346
|
if (err instanceof WriteBackConflictError) {
|
|
328
|
-
|
|
329
|
-
// replace, or a change found on every attempt); the count bump was
|
|
330
|
-
// refused. The ledger row was already written and committed before the
|
|
331
|
-
// bump, so it stays, and the count is not bumped.
|
|
332
|
-
console.error("recordCitations: not credited, stored_row_changed (no-op)", { memoryId: id, reason: "stored_row_changed", err });
|
|
347
|
+
console.error("recordCitations: %s, %s", err.outcome === "conflict" ? "contribution count write aborted" : "usage count unconfirmed", err.outcome === "conflict" ? "stored_row_changed" : "write_unconfirmed", { memoryId: id, reason: err.outcome === "conflict" ? "stored_row_changed" : "write_unconfirmed", outcome: err.outcome, err });
|
|
333
348
|
}
|
|
334
349
|
else if (err instanceof UsageLedgerReadError) {
|
|
335
350
|
// flair#2333: the ledger read that decides whether this pair already
|
|
@@ -338,7 +353,7 @@ export async function recordCitations(ctx, auth, usedMemoryIds, now, recordFn =
|
|
|
338
353
|
console.error("recordCitations: not credited, ledger read failed (no-op)", { memoryId: id, ledgerId: err.ledgerId, reason: "ledger_read_failed", err });
|
|
339
354
|
}
|
|
340
355
|
else {
|
|
341
|
-
console.error("recordCitations: failed to credit
|
|
356
|
+
console.error("recordCitations: failed to credit", { memoryId: id, err });
|
|
342
357
|
}
|
|
343
358
|
}
|
|
344
359
|
}
|
|
@@ -378,16 +393,9 @@ export async function recordUsageBatch(ctx, agentId, memoryIds, attribution, now
|
|
|
378
393
|
await recordFn(ctx, agentId, memoryId, attribution, now, scope.isAllowed);
|
|
379
394
|
}
|
|
380
395
|
catch (err) {
|
|
381
|
-
//
|
|
382
|
-
// error leak existence information either — log server-side, collapse
|
|
383
|
-
// to the same no-op the response already returns for every other
|
|
384
|
-
// outcome.
|
|
396
|
+
// Log per-id failures without changing the response.
|
|
385
397
|
if (err instanceof WriteBackConflictError) {
|
|
386
|
-
|
|
387
|
-
// replace, or a change found on every attempt); the count bump was
|
|
388
|
-
// refused. The ledger row was already written and committed before the
|
|
389
|
-
// bump, so it stays, and the count is not bumped.
|
|
390
|
-
console.error("RecordUsage.post: not recorded, stored_row_changed (treated as no-op)", { memoryId, reason: "stored_row_changed", err });
|
|
398
|
+
console.error("RecordUsage.post: %s, %s", err.outcome === "conflict" ? "contribution count write aborted" : "usage count unconfirmed", err.outcome === "conflict" ? "stored_row_changed" : "write_unconfirmed", { memoryId, reason: err.outcome === "conflict" ? "stored_row_changed" : "write_unconfirmed", outcome: err.outcome, err });
|
|
391
399
|
}
|
|
392
400
|
else if (err instanceof UsageLedgerReadError) {
|
|
393
401
|
// flair#2333: the ledger read failed — not "no row". This contribution
|
|
@@ -395,7 +403,7 @@ export async function recordUsageBatch(ctx, agentId, memoryIds, attribution, now
|
|
|
395
403
|
console.error("RecordUsage.post: not recorded, ledger read failed (treated as no-op)", { memoryId, ledgerId: err.ledgerId, reason: "ledger_read_failed", err });
|
|
396
404
|
}
|
|
397
405
|
else {
|
|
398
|
-
console.error("RecordUsage.post: failed to record usage
|
|
406
|
+
console.error("RecordUsage.post: failed to record usage", { memoryId, err });
|
|
399
407
|
}
|
|
400
408
|
}
|
|
401
409
|
}
|
|
@@ -1,4 +1,7 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
1
2
|
import { isDeepStrictEqual } from "node:util";
|
|
3
|
+
import { appendFileSync } from "node:fs";
|
|
4
|
+
import { join } from "node:path";
|
|
2
5
|
import { withOwnedTransaction } from "./request-transaction.js";
|
|
3
6
|
/** The fields of `expectedRow` (or of the helper's own first read) it compares
|
|
4
7
|
* with the row read inside its transaction, besides `matchFields`. */
|
|
@@ -43,17 +46,35 @@ export function writeBackIdentity(row) {
|
|
|
43
46
|
/** Attempts of a write-back before it gives up on a row that keeps changing. */
|
|
44
47
|
export const WRITE_BACK_ATTEMPTS = 3;
|
|
45
48
|
/**
|
|
46
|
-
*
|
|
47
|
-
*
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
49
|
+
* Test-only: record attempt starts and settled outcomes when fault injection
|
|
50
|
+
* is armed and a pause directory is configured.
|
|
51
|
+
*/
|
|
52
|
+
function noteTestAttempt(label, id, attempt, outcome) {
|
|
53
|
+
if (process.env.FLAIR_ENABLE_TEST_FAULT_INJECTION !== "1")
|
|
54
|
+
return;
|
|
55
|
+
const dir = process.env.FLAIR_TEST_PAUSE_DIR;
|
|
56
|
+
if (!dir)
|
|
57
|
+
return;
|
|
58
|
+
try {
|
|
59
|
+
appendFileSync(join(dir, "attempts.write-back"), `${label}\t${id}\t${attempt}${outcome ? `\t${outcome}` : ""}\n`);
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
// Append errors are ignored.
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* The helper's named failure. `outcome: "conflict"`: a check before the commit
|
|
67
|
+
* aborted the transaction, so this attempt committed no write. `outcome:
|
|
68
|
+
* "unconfirmed"`: the transaction's commit resolved, but a fresh committed read
|
|
69
|
+
* did not show the staged values (or could not be read), so whether the write
|
|
70
|
+
* landed is unknown.
|
|
52
71
|
*/
|
|
53
72
|
export class WriteBackConflictError extends Error {
|
|
73
|
+
outcome;
|
|
54
74
|
id;
|
|
55
|
-
constructor(label, id, attempts) {
|
|
56
|
-
super(`${label}: row ${id}
|
|
75
|
+
constructor(label, id, attempts, outcome = "conflict") {
|
|
76
|
+
super(`${label}: row ${id}; ${outcome}: ${outcome === "conflict" ? "write aborted; no write committed by this attempt" : "staged values unconfirmed after commit"} (${attempts} attempts)`);
|
|
77
|
+
this.outcome = outcome;
|
|
57
78
|
this.name = "WriteBackConflictError";
|
|
58
79
|
this.id = id;
|
|
59
80
|
}
|
|
@@ -184,8 +205,11 @@ export async function writeBackCommittedRow(table, id, plan, opts) {
|
|
|
184
205
|
await pre;
|
|
185
206
|
}
|
|
186
207
|
for (let attempt = 1;; attempt++) {
|
|
208
|
+
noteTestAttempt(opts.label, id, attempt);
|
|
209
|
+
let decision;
|
|
210
|
+
let writeId;
|
|
187
211
|
try {
|
|
188
|
-
|
|
212
|
+
decision = await withOwnedTransaction(opts.ctx, async (c) => {
|
|
189
213
|
const row = await table.get(id, c);
|
|
190
214
|
if (opts.matches && !opts.matches(row))
|
|
191
215
|
return { skip: true };
|
|
@@ -200,19 +224,160 @@ export async function writeBackCommittedRow(table, id, plan, opts) {
|
|
|
200
224
|
if (pause)
|
|
201
225
|
await pause;
|
|
202
226
|
}
|
|
227
|
+
let values = "update" in decision ? decision.update : decision.write;
|
|
228
|
+
if (!decision.idempotent) {
|
|
229
|
+
if (!decision.commitMarkerField)
|
|
230
|
+
throw new Error("write-back: non-idempotent plans require a commit marker field");
|
|
231
|
+
writeId = randomUUID();
|
|
232
|
+
values = { ...values, [decision.commitMarkerField]: writeId };
|
|
233
|
+
}
|
|
203
234
|
if ("update" in decision)
|
|
204
|
-
await applyFieldUpdate(table, id,
|
|
235
|
+
await applyFieldUpdate(table, id, values, c);
|
|
205
236
|
else
|
|
206
|
-
await table.put(
|
|
237
|
+
await table.put(values, c);
|
|
238
|
+
if (opts.pauseAfterStage) {
|
|
239
|
+
const staged = opts.pauseAfterStage();
|
|
240
|
+
if (staged)
|
|
241
|
+
await staged;
|
|
242
|
+
}
|
|
207
243
|
await confirmCommittedRow(table, id, (committed) => isDeepStrictEqual(committed, row));
|
|
244
|
+
if (opts.confirmPoint) {
|
|
245
|
+
const confirmed = opts.confirmPoint();
|
|
246
|
+
if (confirmed)
|
|
247
|
+
await confirmed;
|
|
248
|
+
}
|
|
249
|
+
// Test-only: holds this write after its last pre-commit confirmation,
|
|
250
|
+
// before the transaction commits (flair#2653).
|
|
251
|
+
if (opts.pauseBeforeCommit) {
|
|
252
|
+
const pause = opts.pauseBeforeCommit();
|
|
253
|
+
if (pause)
|
|
254
|
+
await pause;
|
|
255
|
+
}
|
|
208
256
|
return decision;
|
|
209
257
|
});
|
|
210
258
|
}
|
|
211
259
|
catch (err) {
|
|
260
|
+
noteTestAttempt(opts.label, id, attempt, "refused");
|
|
212
261
|
if (!(err instanceof CommittedRowChanged))
|
|
213
262
|
throw err;
|
|
214
263
|
if (attempt >= attempts)
|
|
215
264
|
throw new WriteBackConflictError(opts.label, id, attempts);
|
|
265
|
+
continue;
|
|
266
|
+
}
|
|
267
|
+
if ("skip" in decision) {
|
|
268
|
+
noteTestAttempt(opts.label, id, attempt, "skipped");
|
|
269
|
+
return decision;
|
|
270
|
+
}
|
|
271
|
+
// flair#2653: the transaction's commit is not proof that the write landed.
|
|
272
|
+
// A newer write committing in the window above can make Harper resolve the
|
|
273
|
+
// commit while discarding this write. Re-read the committed store in a
|
|
274
|
+
// fresh context; an unreadable read is a failure, never a pass.
|
|
275
|
+
if (opts.pauseBeforeVerify) {
|
|
276
|
+
const pause = opts.pauseBeforeVerify();
|
|
277
|
+
if (pause)
|
|
278
|
+
await pause;
|
|
279
|
+
}
|
|
280
|
+
let committed;
|
|
281
|
+
try {
|
|
282
|
+
committed = await table.get(id, {});
|
|
283
|
+
}
|
|
284
|
+
catch (err) {
|
|
285
|
+
opts.onUnconfirmed?.();
|
|
286
|
+
noteTestAttempt(opts.label, id, attempt, "unconfirmed");
|
|
287
|
+
if (!decision.idempotent)
|
|
288
|
+
throw new WriteBackConflictError(opts.label, id, attempt, "unconfirmed");
|
|
289
|
+
throw err;
|
|
290
|
+
}
|
|
291
|
+
if (!committedShowsWrite(committed, basis, decision, writeId) || (opts.verifyAlso !== undefined && !opts.verifyAlso(committed))) {
|
|
292
|
+
opts.onUnconfirmed?.();
|
|
293
|
+
noteTestAttempt(opts.label, id, attempt, "unconfirmed");
|
|
294
|
+
if (!decision.idempotent)
|
|
295
|
+
throw new WriteBackConflictError(opts.label, id, attempt, "unconfirmed");
|
|
296
|
+
if (attempt >= attempts)
|
|
297
|
+
throw new WriteBackConflictError(opts.label, id, attempts, "unconfirmed");
|
|
298
|
+
continue;
|
|
299
|
+
}
|
|
300
|
+
noteTestAttempt(opts.label, id, attempt, "applied");
|
|
301
|
+
return decision;
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
/**
|
|
305
|
+
* Does `committed` show the write `identity` describes with every `fields`
|
|
306
|
+
* entry at its staged value? The identity check is {@link sameStoredRow}.
|
|
307
|
+
*/
|
|
308
|
+
export function committedShowsFields(committed, identity, fields) {
|
|
309
|
+
return sameStoredRow(committed, identity) &&
|
|
310
|
+
Object.entries(fields).every(([field, value]) => isDeepStrictEqual(committed?.[field], value));
|
|
311
|
+
}
|
|
312
|
+
/**
|
|
313
|
+
* Read `id` in a fresh committed context (never contextless) and report whether
|
|
314
|
+
* it shows the write: the row is still `identity`'s row and every named field
|
|
315
|
+
* holds its staged value. A failed read is `unreadable`, never `shown`.
|
|
316
|
+
*
|
|
317
|
+
* The post-commit shape a writer outside {@link writeBackCommittedRow} uses:
|
|
318
|
+
* after its owned transaction resolves, a newer write that committed in the
|
|
319
|
+
* final-confirmation-to-commit window may have discarded this write's effect
|
|
320
|
+
* while the commit still resolved (flair#2653, flair#2656).
|
|
321
|
+
*
|
|
322
|
+
* `also` re-checks a fact the decision depended on that is not one of the
|
|
323
|
+
* written fields — a re-embed's text basis, for instance.
|
|
324
|
+
*/
|
|
325
|
+
export async function verifyCommittedFields(table, id, identity, fields, also) {
|
|
326
|
+
let committed;
|
|
327
|
+
try {
|
|
328
|
+
committed = await table.get(id, {});
|
|
329
|
+
}
|
|
330
|
+
catch {
|
|
331
|
+
return "unreadable";
|
|
332
|
+
}
|
|
333
|
+
if (committed == null)
|
|
334
|
+
return "mismatch";
|
|
335
|
+
return (also === undefined || also(committed)) && committedShowsFields(committed, identity, fields) ? "shown" : "mismatch";
|
|
336
|
+
}
|
|
337
|
+
// Harper assigns these timestamps; they are not staged application fields.
|
|
338
|
+
export const HARPER_MANAGED_FIELDS = ["__createdtime__", "__updatedtime__"];
|
|
339
|
+
/**
|
|
340
|
+
* A copy of `row` without {@link HARPER_MANAGED_FIELDS}: the application fields
|
|
341
|
+
* of a row staged by spreading a stored row, as the `fields` a caller hands
|
|
342
|
+
* {@link verifyCommittedFields}. Every other field is kept; `row` is unchanged.
|
|
343
|
+
*/
|
|
344
|
+
export function withoutHarperManagedFields(row) {
|
|
345
|
+
const fields = { ...row };
|
|
346
|
+
for (const field of HARPER_MANAGED_FIELDS)
|
|
347
|
+
delete fields[field];
|
|
348
|
+
return fields;
|
|
349
|
+
}
|
|
350
|
+
/**
|
|
351
|
+
* Does the committed row show this attempt's write? Its identity is the row
|
|
352
|
+
* this attempt wrote — for an update, the basis with every identity field the
|
|
353
|
+
* update itself stages replaced by the staged value; each field the plan wrote
|
|
354
|
+
* holds its staged value, and a non-idempotent plan is confirmed by this
|
|
355
|
+
* attempt's commit marker (`writeId`), not by value equality.
|
|
356
|
+
*/
|
|
357
|
+
function committedShowsWrite(committed, basis, decision, writeId) {
|
|
358
|
+
if ("skip" in decision)
|
|
359
|
+
return true;
|
|
360
|
+
if (!decision.idempotent && committed?.[decision.commitMarkerField] !== writeId)
|
|
361
|
+
return false;
|
|
362
|
+
if ("update" in decision) {
|
|
363
|
+
// An update may change an identity field (the federation merge carries the
|
|
364
|
+
// inbound contentHash). The committed row must then show the staged value
|
|
365
|
+
// of every identity field the update names, and the basis value of the
|
|
366
|
+
// others.
|
|
367
|
+
const identity = basis == null ? basis : { ...basis };
|
|
368
|
+
if (identity != null) {
|
|
369
|
+
for (const field of WRITE_BACK_IDENTITY_FIELDS) {
|
|
370
|
+
if (Object.hasOwn(decision.update, field))
|
|
371
|
+
identity[field] = decision.update[field];
|
|
372
|
+
}
|
|
216
373
|
}
|
|
374
|
+
if (!sameStoredRow(committed, identity))
|
|
375
|
+
return false;
|
|
376
|
+
return Object.entries(decision.update).every(([field, value]) => (!decision.idempotent && field === decision.commitMarkerField) || isDeepStrictEqual(committed?.[field], value));
|
|
217
377
|
}
|
|
378
|
+
if (!sameStoredRow(committed, decision.write))
|
|
379
|
+
return false;
|
|
380
|
+
const managed = new Set(HARPER_MANAGED_FIELDS);
|
|
381
|
+
return Object.entries(decision.write).every(([field, value]) => managed.has(field) || (!decision.idempotent && field === decision.commitMarkerField) || isDeepStrictEqual(committed?.[field], value)) &&
|
|
382
|
+
Object.keys(committed).every((field) => managed.has(field) || Object.hasOwn(decision.write, field) || (!decision.idempotent && field === decision.commitMarkerField));
|
|
218
383
|
}
|