@feltdb/core 0.12.1 → 0.12.2
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/dist/build-identity.json +13 -4
- package/dist/cli/commands.js +88 -43
- package/dist/collection.d.ts +41 -4
- package/dist/collection.d.ts.map +1 -1
- package/dist/collection.js +116 -47
- package/dist/composition.d.ts.map +1 -1
- package/dist/composition.js +11 -1
- package/dist/create/build-identity.json +13 -4
- package/dist/create/cli.js +3 -3
- package/dist/create/create.js +17 -19
- package/dist/create/package-versions.js +1 -1
- package/dist/create/server-source/Cargo.lock +18 -3
- package/dist/create/server-source/Cargo.toml +4 -2
- package/dist/create/server-source/crates/feltdb/Cargo.toml +20 -0
- package/dist/create/server-source/crates/feltdb/LICENSE +21 -0
- package/dist/create/server-source/crates/feltdb/README.md +75 -0
- package/dist/create/server-source/crates/feltdb/src/agent_state.rs +320 -0
- package/dist/create/server-source/crates/feltdb/src/agent_transition_contract.rs +1545 -0
- package/dist/create/server-source/crates/feltdb/src/authority.rs +145 -15
- package/dist/create/server-source/crates/feltdb/src/lib.rs +227 -23
- package/dist/create/server-source/crates/feltdb/src/state_model.rs +1 -5
- package/dist/create/server-source/crates/feltdb/tests/agent_state_native.rs +1188 -0
- package/dist/create/server-source/crates/feltdb/tests/agent_transition_contract_conformance.rs +2884 -0
- package/dist/create/server-source/crates/feltdb/tests/authority_transaction_identity.rs +534 -0
- package/dist/create/server-source/crates/feltdb/tests/fixtures/agent_transition_corpus.json +23340 -0
- package/dist/create/server-source/crates/feltdb-client/Cargo.toml +29 -0
- package/dist/create/server-source/crates/feltdb-client/LICENSE +21 -0
- package/dist/create/server-source/crates/feltdb-client/README.md +70 -0
- package/dist/create/server-source/crates/feltdb-client/src/application.rs +527 -0
- package/dist/create/server-source/crates/feltdb-client/src/authority.rs +679 -0
- package/dist/create/server-source/crates/feltdb-client/src/control.rs +292 -0
- package/dist/create/server-source/crates/feltdb-client/src/error.rs +227 -0
- package/dist/create/server-source/crates/feltdb-client/src/events.rs +146 -0
- package/dist/create/server-source/crates/feltdb-client/src/lib.rs +466 -0
- package/dist/create/server-source/crates/feltdb-client/tests/fixtures/README.md +4 -0
- package/dist/create/server-source/crates/feltdb-client/tests/fixtures/private-ca.pem +20 -0
- package/dist/create/server-source/crates/feltdb-client/tests/fixtures/server-key.pem +28 -0
- package/dist/create/server-source/crates/feltdb-client/tests/fixtures/server.pem +20 -0
- package/dist/create/server-source/crates/feltdb-client/tests/private_ca.rs +95 -0
- package/dist/create/server-source/crates/feltdb-server/Cargo.toml +20 -1
- package/dist/create/server-source/crates/feltdb-server/LICENSE +21 -0
- package/dist/create/server-source/crates/feltdb-server/README.md +12 -1
- package/dist/create/server-source/crates/feltdb-server/src/backup.rs +6 -2
- package/dist/create/server-source/crates/feltdb-server/src/lib.rs +20 -0
- package/dist/create/server-source/crates/feltdb-server/src/main.rs +1 -3
- package/dist/create/server-source/crates/feltdb-server/tests/rust_client.rs +683 -0
- package/dist/create/server-source/crates/feltdb-wasm/Cargo.toml +3 -1
- package/dist/create/template/default-project/README.md +12 -7
- package/dist/create/template/default-project/src/pages/Dashboard.tsx +1 -1
- package/dist/create/template/dot-feltdb-README.md +3 -3
- package/dist/db.d.ts.map +1 -1
- package/dist/db.js +43 -17
- package/dist/development-runtime-bridge.d.ts.map +1 -1
- package/dist/development-runtime-bridge.js +22 -1
- package/dist/embedded-transaction.d.ts +75 -8
- package/dist/embedded-transaction.d.ts.map +1 -1
- package/dist/embedded-transaction.js +124 -18
- package/dist/error-codes.d.ts +2 -0
- package/dist/error-codes.d.ts.map +1 -1
- package/dist/error-codes.js +2 -0
- package/dist/feltdb.d.ts +1 -11
- package/dist/feltdb.d.ts.map +1 -1
- package/dist/file-db.d.ts +6 -0
- package/dist/file-db.d.ts.map +1 -1
- package/dist/file-db.js +43 -11
- package/dist/indexeddb-db.d.ts.map +1 -1
- package/dist/indexeddb-db.js +65 -41
- package/dist/memory-db.d.ts.map +1 -1
- package/dist/memory-db.js +29 -8
- package/dist/studio/{KeyManagementPanel-DZuSeWBK.js → KeyManagementPanel-D5FMvvU9.js} +1 -0
- package/dist/studio/app.d.ts.map +1 -1
- package/dist/studio/components/KeyManagementPanel.d.ts.map +1 -1
- package/dist/studio/components/KeyManagementPanel.js +1 -1
- package/dist/studio/components/RouteErrorBoundary.d.ts +5 -0
- package/dist/studio/components/RouteErrorBoundary.d.ts.map +1 -0
- package/dist/studio/components/index.js +2 -2
- package/dist/studio/{components-Bivm2lX6.js → components-B4eKIUN5.js} +1 -1
- package/dist/studio/control-plane/Agents.d.ts.map +1 -1
- package/dist/studio/control-plane/Data.d.ts.map +1 -1
- package/dist/studio/control-plane/Instance.d.ts.map +1 -1
- package/dist/studio/control-plane/Overview.d.ts.map +1 -1
- package/dist/studio/control-plane/Schema.d.ts.map +1 -1
- package/dist/studio/control-plane/context.d.ts +4 -1
- package/dist/studio/control-plane/context.d.ts.map +1 -1
- package/dist/studio/control-plane/index.js +2 -2
- package/dist/studio/control-plane/primitives.d.ts +8 -0
- package/dist/studio/control-plane/primitives.d.ts.map +1 -1
- package/dist/studio/{control-plane-CLm69XwX.js → control-plane-fxMcJn74.js} +1371 -1319
- package/dist/studio/index.js +146 -105
- package/dist/studio/utils/control-plane-api.d.ts.map +1 -1
- package/dist/studio/utils/control-plane-api.js +4 -3
- package/dist/studio/utils/service-api.d.ts.map +1 -1
- package/dist/studio/utils/service-api.js +5 -4
- package/dist/studio-app/assets/{feltdb_wasm-DACcD-zs.js → feltdb_wasm-BatwwogY.js} +1 -1
- package/dist/studio-app/assets/feltdb_wasm_bg-BX0newOr.wasm +0 -0
- package/dist/studio-app/assets/index-DoVvbIay.js +30 -0
- package/dist/studio-app/index.html +1 -1
- package/dist/telemetry.d.ts +1 -0
- package/dist/telemetry.d.ts.map +1 -1
- package/dist/telemetry.js +4 -3
- package/dist/transaction-identity.d.ts +62 -0
- package/dist/transaction-identity.d.ts.map +1 -0
- package/dist/transaction-identity.js +138 -0
- package/dist/transaction.d.ts +50 -5
- package/dist/transaction.d.ts.map +1 -1
- package/dist/transaction.js +28 -0
- package/dist/wasm/feltdb_wasm_bg.wasm +0 -0
- package/dist/wasm/package.json +1 -1
- package/package.json +1 -1
- package/dist/create/server-source/crates/feltdb-wasm/test.db +0 -0
- package/dist/studio-app/assets/feltdb_wasm_bg-BejThWID.wasm +0 -0
- package/dist/studio-app/assets/index-CoZaxnlm.js +0 -30
|
@@ -0,0 +1,1545 @@
|
|
|
1
|
+
//! The deterministic contract behind durable agent-state transitions.
|
|
2
|
+
//!
|
|
3
|
+
//! ```text
|
|
4
|
+
//! canonical input -> deterministic decision -> canonical output
|
|
5
|
+
//! ```
|
|
6
|
+
//!
|
|
7
|
+
//! The decision is: *given these records, at this authority time, may this
|
|
8
|
+
//! operation proceed, and if so which writes and preconditions make it so?*
|
|
9
|
+
//!
|
|
10
|
+
//! The contract is a **decision, not a transaction executor**. It reads nothing
|
|
11
|
+
//! but its input, never consults a clock (the authority's time arrives as
|
|
12
|
+
//! `now_ms`), never reads storage and never commits anything. A caller that
|
|
13
|
+
//! wants the decision to become real must
|
|
14
|
+
//!
|
|
15
|
+
//! 1. read the records the operation names, with their versions;
|
|
16
|
+
//! 2. obtain the authority's time and pass it as `now_ms`;
|
|
17
|
+
//! 3. call [`evaluate`];
|
|
18
|
+
//! 4. commit the returned writes and guards through one guarded transaction,
|
|
19
|
+
//! each write carrying the precondition the contract attached to it; and
|
|
20
|
+
//! 5. report success only if that commit succeeded.
|
|
21
|
+
//!
|
|
22
|
+
//! A precondition that fails is a lost race, not a reason to resend the same
|
|
23
|
+
//! writes: the caller re-reads and decides again. [`crate::agent_state`] is the
|
|
24
|
+
//! production implementation of those five steps.
|
|
25
|
+
//!
|
|
26
|
+
//! # What the contract enforces, and what it cannot
|
|
27
|
+
//!
|
|
28
|
+
//! It enforces lifecycle legality, ownership, fencing, lease expiry, evidence
|
|
29
|
+
//! preconditions and the uncertain-outcome rules. It does **not** verify the
|
|
30
|
+
//! external world. Evidence arrives as a list of *observations* that FeltDB
|
|
31
|
+
//! itself made when it read the cited records; the contract requires every
|
|
32
|
+
//! cited record to have been observed and pins the observed version with a
|
|
33
|
+
//! guard, so the citation cannot be committed against a record that has
|
|
34
|
+
//! changed. A caller cannot assert that something was verified: there is no
|
|
35
|
+
//! such field in the input.
|
|
36
|
+
//!
|
|
37
|
+
//! Record identities, version-numbering and lease predicates are defined by the
|
|
38
|
+
//! existing guarded-transaction primitive; this module only names them.
|
|
39
|
+
|
|
40
|
+
use serde::de::{DeserializeOwned, Deserializer};
|
|
41
|
+
use serde::{Deserialize, Serialize};
|
|
42
|
+
use serde_json::{json, Map, Value};
|
|
43
|
+
|
|
44
|
+
pub const AGENT_TRANSITION_CONTRACT_ID: &str = "feltdb.agent.transition";
|
|
45
|
+
pub const AGENT_TRANSITION_CONTRACT_VERSION: u32 = 1;
|
|
46
|
+
|
|
47
|
+
pub const TASK_COLLECTION: &str = "_feltdb.AgentTask";
|
|
48
|
+
pub const CHECKPOINT_COLLECTION: &str = "_feltdb.AgentCheckpoint";
|
|
49
|
+
pub const HANDOFF_COLLECTION: &str = "_feltdb.AgentHandoff";
|
|
50
|
+
pub const INTENT_COLLECTION: &str = "_feltdb.AgentIntent";
|
|
51
|
+
|
|
52
|
+
/// Identifiers (task, actor, lease, handoff, idempotency key): 1..=128 bytes of
|
|
53
|
+
/// `[A-Za-z0-9_.:@-]`. The composite record ids use `~` as a separator, which
|
|
54
|
+
/// is outside this set, so two different (task, key) pairs cannot collide.
|
|
55
|
+
pub const MAX_IDENTIFIER_BYTES: usize = 128;
|
|
56
|
+
pub const MAX_TEXT_BYTES: usize = 1024;
|
|
57
|
+
pub const MAX_EVIDENCE: usize = 16;
|
|
58
|
+
pub const MAX_LEASE_MS: u64 = 86_400_000;
|
|
59
|
+
/// Evidence collections beginning with this prefix are the agent's own
|
|
60
|
+
/// records. A claim cannot be evidence for itself.
|
|
61
|
+
pub const AGENT_COLLECTION_PREFIX: &str = "_feltdb.Agent";
|
|
62
|
+
|
|
63
|
+
/// Why a decision is a refusal. Codes carry no message on purpose: a free-form
|
|
64
|
+
/// string would be a divergence surface that says nothing about semantics.
|
|
65
|
+
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
|
66
|
+
pub enum ErrorCode {
|
|
67
|
+
ContractInputInvalid,
|
|
68
|
+
ContractIdMismatch,
|
|
69
|
+
ContractVersionUnsupported,
|
|
70
|
+
NotFound,
|
|
71
|
+
AlreadyExists,
|
|
72
|
+
InvalidTransition,
|
|
73
|
+
Terminal,
|
|
74
|
+
FenceStale,
|
|
75
|
+
OwnershipConflict,
|
|
76
|
+
LeaseMismatch,
|
|
77
|
+
LeaseExpired,
|
|
78
|
+
LeaseHeld,
|
|
79
|
+
VersionConflict,
|
|
80
|
+
EvidenceInvalid,
|
|
81
|
+
EvidenceRequired,
|
|
82
|
+
OutcomeUncertain,
|
|
83
|
+
IntentUnknown,
|
|
84
|
+
IntentResolved,
|
|
85
|
+
HandoffClaimed,
|
|
86
|
+
HandoffStale,
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
impl ErrorCode {
|
|
90
|
+
pub fn as_str(self) -> &'static str {
|
|
91
|
+
match self {
|
|
92
|
+
Self::ContractInputInvalid => "CONTRACT_INPUT_INVALID",
|
|
93
|
+
Self::ContractIdMismatch => "CONTRACT_ID_MISMATCH",
|
|
94
|
+
Self::ContractVersionUnsupported => "CONTRACT_VERSION_UNSUPPORTED",
|
|
95
|
+
Self::NotFound => "NOT_FOUND",
|
|
96
|
+
Self::AlreadyExists => "ALREADY_EXISTS",
|
|
97
|
+
Self::InvalidTransition => "INVALID_TRANSITION",
|
|
98
|
+
Self::Terminal => "TERMINAL",
|
|
99
|
+
Self::FenceStale => "FENCE_STALE",
|
|
100
|
+
Self::OwnershipConflict => "OWNERSHIP_CONFLICT",
|
|
101
|
+
Self::LeaseMismatch => "LEASE_MISMATCH",
|
|
102
|
+
Self::LeaseExpired => "LEASE_EXPIRED",
|
|
103
|
+
Self::LeaseHeld => "LEASE_HELD",
|
|
104
|
+
Self::VersionConflict => "VERSION_CONFLICT",
|
|
105
|
+
Self::EvidenceInvalid => "EVIDENCE_INVALID",
|
|
106
|
+
Self::EvidenceRequired => "EVIDENCE_REQUIRED",
|
|
107
|
+
Self::OutcomeUncertain => "OUTCOME_UNCERTAIN",
|
|
108
|
+
Self::IntentUnknown => "INTENT_UNKNOWN",
|
|
109
|
+
Self::IntentResolved => "INTENT_RESOLVED",
|
|
110
|
+
Self::HandoffClaimed => "HANDOFF_CLAIMED",
|
|
111
|
+
Self::HandoffStale => "HANDOFF_STALE",
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
use ErrorCode as E;
|
|
117
|
+
|
|
118
|
+
// ---------------------------------------------------------------------------
|
|
119
|
+
// Input
|
|
120
|
+
// ---------------------------------------------------------------------------
|
|
121
|
+
|
|
122
|
+
/// Deserializes a member that, when present, must not be `null`.
|
|
123
|
+
fn strict<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
|
|
124
|
+
where
|
|
125
|
+
D: Deserializer<'de>,
|
|
126
|
+
T: DeserializeOwned,
|
|
127
|
+
{
|
|
128
|
+
T::deserialize(deserializer).map(Some)
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/// Deserializes a member that must be present and may be `null`.
|
|
132
|
+
fn nullable<'de, D, T>(deserializer: D) -> Result<Option<T>, D::Error>
|
|
133
|
+
where
|
|
134
|
+
D: Deserializer<'de>,
|
|
135
|
+
T: DeserializeOwned,
|
|
136
|
+
{
|
|
137
|
+
Option::<T>::deserialize(deserializer)
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
|
141
|
+
#[serde(deny_unknown_fields)]
|
|
142
|
+
pub struct AgentTransitionInput {
|
|
143
|
+
pub contract: String,
|
|
144
|
+
pub now_ms: u64,
|
|
145
|
+
pub operation: Operation,
|
|
146
|
+
pub records: Records,
|
|
147
|
+
pub version: u32,
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/// Every member any operation may carry. Which are required and which are
|
|
151
|
+
/// forbidden is a property of `op`, checked in [`Operation::validate`].
|
|
152
|
+
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
|
|
153
|
+
#[serde(deny_unknown_fields)]
|
|
154
|
+
pub struct Operation {
|
|
155
|
+
pub op: String,
|
|
156
|
+
#[serde(
|
|
157
|
+
default,
|
|
158
|
+
deserialize_with = "strict",
|
|
159
|
+
skip_serializing_if = "Option::is_none"
|
|
160
|
+
)]
|
|
161
|
+
pub action: Option<String>,
|
|
162
|
+
#[serde(
|
|
163
|
+
default,
|
|
164
|
+
deserialize_with = "strict",
|
|
165
|
+
skip_serializing_if = "Option::is_none"
|
|
166
|
+
)]
|
|
167
|
+
pub actor: Option<String>,
|
|
168
|
+
#[serde(
|
|
169
|
+
default,
|
|
170
|
+
deserialize_with = "strict",
|
|
171
|
+
skip_serializing_if = "Option::is_none"
|
|
172
|
+
)]
|
|
173
|
+
pub claimant: Option<String>,
|
|
174
|
+
#[serde(
|
|
175
|
+
default,
|
|
176
|
+
deserialize_with = "strict",
|
|
177
|
+
skip_serializing_if = "Option::is_none"
|
|
178
|
+
)]
|
|
179
|
+
pub conclusion: Option<String>,
|
|
180
|
+
#[serde(
|
|
181
|
+
default,
|
|
182
|
+
deserialize_with = "strict",
|
|
183
|
+
skip_serializing_if = "Option::is_none"
|
|
184
|
+
)]
|
|
185
|
+
pub evidence: Option<Vec<EvidenceRef>>,
|
|
186
|
+
#[serde(
|
|
187
|
+
default,
|
|
188
|
+
deserialize_with = "strict",
|
|
189
|
+
skip_serializing_if = "Option::is_none"
|
|
190
|
+
)]
|
|
191
|
+
pub expected_version: Option<u64>,
|
|
192
|
+
#[serde(
|
|
193
|
+
default,
|
|
194
|
+
deserialize_with = "strict",
|
|
195
|
+
skip_serializing_if = "Option::is_none"
|
|
196
|
+
)]
|
|
197
|
+
pub fence: Option<u64>,
|
|
198
|
+
#[serde(
|
|
199
|
+
default,
|
|
200
|
+
deserialize_with = "strict",
|
|
201
|
+
skip_serializing_if = "Option::is_none"
|
|
202
|
+
)]
|
|
203
|
+
pub handoff_id: Option<String>,
|
|
204
|
+
#[serde(
|
|
205
|
+
default,
|
|
206
|
+
deserialize_with = "strict",
|
|
207
|
+
skip_serializing_if = "Option::is_none"
|
|
208
|
+
)]
|
|
209
|
+
pub idempotency_key: Option<String>,
|
|
210
|
+
#[serde(
|
|
211
|
+
default,
|
|
212
|
+
deserialize_with = "strict",
|
|
213
|
+
skip_serializing_if = "Option::is_none"
|
|
214
|
+
)]
|
|
215
|
+
pub lease_id: Option<String>,
|
|
216
|
+
#[serde(
|
|
217
|
+
default,
|
|
218
|
+
deserialize_with = "strict",
|
|
219
|
+
skip_serializing_if = "Option::is_none"
|
|
220
|
+
)]
|
|
221
|
+
pub lease_ms: Option<u64>,
|
|
222
|
+
#[serde(
|
|
223
|
+
default,
|
|
224
|
+
deserialize_with = "strict",
|
|
225
|
+
skip_serializing_if = "Option::is_none"
|
|
226
|
+
)]
|
|
227
|
+
pub objective: Option<String>,
|
|
228
|
+
#[serde(
|
|
229
|
+
default,
|
|
230
|
+
deserialize_with = "strict",
|
|
231
|
+
skip_serializing_if = "Option::is_none"
|
|
232
|
+
)]
|
|
233
|
+
pub result: Option<String>,
|
|
234
|
+
#[serde(
|
|
235
|
+
default,
|
|
236
|
+
deserialize_with = "strict",
|
|
237
|
+
skip_serializing_if = "Option::is_none"
|
|
238
|
+
)]
|
|
239
|
+
pub status: Option<String>,
|
|
240
|
+
#[serde(
|
|
241
|
+
default,
|
|
242
|
+
deserialize_with = "strict",
|
|
243
|
+
skip_serializing_if = "Option::is_none"
|
|
244
|
+
)]
|
|
245
|
+
pub summary: Option<String>,
|
|
246
|
+
#[serde(
|
|
247
|
+
default,
|
|
248
|
+
deserialize_with = "strict",
|
|
249
|
+
skip_serializing_if = "Option::is_none"
|
|
250
|
+
)]
|
|
251
|
+
pub task_id: Option<String>,
|
|
252
|
+
#[serde(
|
|
253
|
+
default,
|
|
254
|
+
deserialize_with = "strict",
|
|
255
|
+
skip_serializing_if = "Option::is_none"
|
|
256
|
+
)]
|
|
257
|
+
pub to: Option<String>,
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/// A caller's citation. It says what is cited, never that it was verified.
|
|
261
|
+
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
|
262
|
+
#[serde(deny_unknown_fields)]
|
|
263
|
+
pub struct EvidenceRef {
|
|
264
|
+
pub kind: String,
|
|
265
|
+
#[serde(
|
|
266
|
+
default,
|
|
267
|
+
deserialize_with = "strict",
|
|
268
|
+
skip_serializing_if = "Option::is_none"
|
|
269
|
+
)]
|
|
270
|
+
pub collection: Option<String>,
|
|
271
|
+
#[serde(
|
|
272
|
+
default,
|
|
273
|
+
deserialize_with = "strict",
|
|
274
|
+
skip_serializing_if = "Option::is_none"
|
|
275
|
+
)]
|
|
276
|
+
pub id: Option<String>,
|
|
277
|
+
#[serde(
|
|
278
|
+
default,
|
|
279
|
+
deserialize_with = "strict",
|
|
280
|
+
skip_serializing_if = "Option::is_none"
|
|
281
|
+
)]
|
|
282
|
+
pub uri: Option<String>,
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/// The records an operation was decided against. A key is present exactly when
|
|
286
|
+
/// the record exists; the operation determines which keys are legal.
|
|
287
|
+
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
|
|
288
|
+
#[serde(deny_unknown_fields)]
|
|
289
|
+
pub struct Records {
|
|
290
|
+
/// What FeltDB itself observed when it read each cited record. Never
|
|
291
|
+
/// supplied by the caller of an operation.
|
|
292
|
+
#[serde(
|
|
293
|
+
default,
|
|
294
|
+
deserialize_with = "strict",
|
|
295
|
+
skip_serializing_if = "Option::is_none"
|
|
296
|
+
)]
|
|
297
|
+
pub evidence: Option<Vec<Observation>>,
|
|
298
|
+
#[serde(
|
|
299
|
+
default,
|
|
300
|
+
deserialize_with = "strict",
|
|
301
|
+
skip_serializing_if = "Option::is_none"
|
|
302
|
+
)]
|
|
303
|
+
pub handoff: Option<Stored<HandoffValue>>,
|
|
304
|
+
#[serde(
|
|
305
|
+
default,
|
|
306
|
+
deserialize_with = "strict",
|
|
307
|
+
skip_serializing_if = "Option::is_none"
|
|
308
|
+
)]
|
|
309
|
+
pub intent: Option<Stored<IntentValue>>,
|
|
310
|
+
#[serde(
|
|
311
|
+
default,
|
|
312
|
+
deserialize_with = "strict",
|
|
313
|
+
skip_serializing_if = "Option::is_none"
|
|
314
|
+
)]
|
|
315
|
+
pub task: Option<Stored<TaskValue>>,
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
|
319
|
+
#[serde(deny_unknown_fields)]
|
|
320
|
+
pub struct Observation {
|
|
321
|
+
pub collection: String,
|
|
322
|
+
pub id: String,
|
|
323
|
+
pub version: u64,
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/// A stored record: its value and the authority's version of it.
|
|
327
|
+
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
|
328
|
+
#[serde(deny_unknown_fields)]
|
|
329
|
+
pub struct Stored<T> {
|
|
330
|
+
pub value: T,
|
|
331
|
+
pub version: u64,
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
|
335
|
+
#[serde(deny_unknown_fields)]
|
|
336
|
+
pub struct Lease {
|
|
337
|
+
/// `expiresAt` and `leaseId` keep the spelling the guarded-transaction
|
|
338
|
+
/// primitive reads, so its lease predicate applies to these records.
|
|
339
|
+
#[serde(rename = "expiresAt")]
|
|
340
|
+
pub expires_at: u64,
|
|
341
|
+
#[serde(rename = "leaseId")]
|
|
342
|
+
pub lease_id: String,
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
|
346
|
+
#[serde(deny_unknown_fields)]
|
|
347
|
+
pub struct TaskValue {
|
|
348
|
+
pub checkpoint_version: u64,
|
|
349
|
+
pub created_at_ms: u64,
|
|
350
|
+
pub fence: u64,
|
|
351
|
+
#[serde(deserialize_with = "nullable")]
|
|
352
|
+
pub lease: Option<Lease>,
|
|
353
|
+
pub objective: String,
|
|
354
|
+
pub owner: String,
|
|
355
|
+
pub status: String,
|
|
356
|
+
pub task_id: String,
|
|
357
|
+
pub unresolved_intents: u64,
|
|
358
|
+
pub updated_at_ms: u64,
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
|
362
|
+
#[serde(deny_unknown_fields)]
|
|
363
|
+
pub struct HandoffValue {
|
|
364
|
+
pub checkpoint_version: u64,
|
|
365
|
+
#[serde(
|
|
366
|
+
default,
|
|
367
|
+
deserialize_with = "strict",
|
|
368
|
+
skip_serializing_if = "Option::is_none"
|
|
369
|
+
)]
|
|
370
|
+
pub claimant: Option<String>,
|
|
371
|
+
#[serde(
|
|
372
|
+
default,
|
|
373
|
+
deserialize_with = "strict",
|
|
374
|
+
skip_serializing_if = "Option::is_none"
|
|
375
|
+
)]
|
|
376
|
+
pub claimed_fence: Option<u64>,
|
|
377
|
+
pub from: String,
|
|
378
|
+
pub from_fence: u64,
|
|
379
|
+
pub handoff_id: String,
|
|
380
|
+
pub status: String,
|
|
381
|
+
pub task_id: String,
|
|
382
|
+
#[serde(
|
|
383
|
+
default,
|
|
384
|
+
deserialize_with = "strict",
|
|
385
|
+
skip_serializing_if = "Option::is_none"
|
|
386
|
+
)]
|
|
387
|
+
pub to: Option<String>,
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
/// A citation as stored: what was cited and whether FeltDB observed it.
|
|
391
|
+
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
|
392
|
+
#[serde(deny_unknown_fields)]
|
|
393
|
+
pub struct Citation {
|
|
394
|
+
#[serde(
|
|
395
|
+
default,
|
|
396
|
+
deserialize_with = "strict",
|
|
397
|
+
skip_serializing_if = "Option::is_none"
|
|
398
|
+
)]
|
|
399
|
+
pub collection: Option<String>,
|
|
400
|
+
#[serde(
|
|
401
|
+
default,
|
|
402
|
+
deserialize_with = "strict",
|
|
403
|
+
skip_serializing_if = "Option::is_none"
|
|
404
|
+
)]
|
|
405
|
+
pub id: Option<String>,
|
|
406
|
+
pub kind: String,
|
|
407
|
+
#[serde(
|
|
408
|
+
default,
|
|
409
|
+
deserialize_with = "strict",
|
|
410
|
+
skip_serializing_if = "Option::is_none"
|
|
411
|
+
)]
|
|
412
|
+
pub uri: Option<String>,
|
|
413
|
+
pub verified: bool,
|
|
414
|
+
#[serde(
|
|
415
|
+
default,
|
|
416
|
+
deserialize_with = "strict",
|
|
417
|
+
skip_serializing_if = "Option::is_none"
|
|
418
|
+
)]
|
|
419
|
+
pub version: Option<u64>,
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
|
423
|
+
#[serde(deny_unknown_fields)]
|
|
424
|
+
pub struct IntentValue {
|
|
425
|
+
pub action: String,
|
|
426
|
+
#[serde(
|
|
427
|
+
default,
|
|
428
|
+
deserialize_with = "strict",
|
|
429
|
+
skip_serializing_if = "Option::is_none"
|
|
430
|
+
)]
|
|
431
|
+
pub conclusion: Option<String>,
|
|
432
|
+
pub evidence: Vec<Citation>,
|
|
433
|
+
pub intended_at_ms: u64,
|
|
434
|
+
pub intended_fence: u64,
|
|
435
|
+
pub key: String,
|
|
436
|
+
#[serde(
|
|
437
|
+
default,
|
|
438
|
+
deserialize_with = "strict",
|
|
439
|
+
skip_serializing_if = "Option::is_none"
|
|
440
|
+
)]
|
|
441
|
+
pub result: Option<String>,
|
|
442
|
+
pub state: String,
|
|
443
|
+
pub task_id: String,
|
|
444
|
+
pub verified: bool,
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
// ---------------------------------------------------------------------------
|
|
448
|
+
// Output
|
|
449
|
+
// ---------------------------------------------------------------------------
|
|
450
|
+
|
|
451
|
+
/// What a committed write must find in the record it replaces.
|
|
452
|
+
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
453
|
+
pub enum Expect {
|
|
454
|
+
/// The record must not exist.
|
|
455
|
+
Absent,
|
|
456
|
+
/// The record must be at `version`, and when `lease_id` is present it must
|
|
457
|
+
/// also hold that lease, unexpired, at commit time on the authority.
|
|
458
|
+
Version {
|
|
459
|
+
version: u64,
|
|
460
|
+
lease_id: Option<String>,
|
|
461
|
+
},
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
#[derive(Debug, Clone, PartialEq)]
|
|
465
|
+
pub struct Write {
|
|
466
|
+
pub collection: &'static str,
|
|
467
|
+
pub id: String,
|
|
468
|
+
pub expect: Expect,
|
|
469
|
+
pub value: Value,
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
/// A record the decision depended on but does not change. It must still be at
|
|
473
|
+
/// `version` (and hold `lease_id`, when present) at commit.
|
|
474
|
+
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
475
|
+
pub struct Guard {
|
|
476
|
+
pub collection: String,
|
|
477
|
+
pub id: String,
|
|
478
|
+
pub version: u64,
|
|
479
|
+
pub lease_id: Option<String>,
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
#[derive(Debug, Clone, PartialEq)]
|
|
483
|
+
pub enum Decision {
|
|
484
|
+
/// Apply these writes and guards atomically, or none of them.
|
|
485
|
+
Commit {
|
|
486
|
+
writes: Vec<Write>,
|
|
487
|
+
guards: Vec<Guard>,
|
|
488
|
+
},
|
|
489
|
+
/// The operation is a recognized repeat and changes nothing.
|
|
490
|
+
Noop,
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
type Outcome = Result<Decision, ErrorCode>;
|
|
494
|
+
|
|
495
|
+
// ---------------------------------------------------------------------------
|
|
496
|
+
// Entry points
|
|
497
|
+
// ---------------------------------------------------------------------------
|
|
498
|
+
|
|
499
|
+
/// Canonical bytes in, canonical bytes out. Every input, including a malformed
|
|
500
|
+
/// one, yields a valid output: an unusable input is a decision, never a trap.
|
|
501
|
+
pub fn evaluate_canonical(input: &[u8]) -> Vec<u8> {
|
|
502
|
+
encode(&evaluate_bytes(input))
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
/// Parses `input` and decides.
|
|
506
|
+
pub fn evaluate_bytes(input: &[u8]) -> Outcome {
|
|
507
|
+
let parsed: AgentTransitionInput =
|
|
508
|
+
serde_json::from_slice(input).map_err(|_| E::ContractInputInvalid)?;
|
|
509
|
+
evaluate(&parsed)
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
/// The decision itself. Shape before identity, so an input that is both
|
|
513
|
+
/// malformed and misaddressed reports the same thing on every implementation.
|
|
514
|
+
pub fn evaluate(input: &AgentTransitionInput) -> Outcome {
|
|
515
|
+
input.operation.validate()?;
|
|
516
|
+
input.records.validate_for(&input.operation.op)?;
|
|
517
|
+
if input.contract != AGENT_TRANSITION_CONTRACT_ID {
|
|
518
|
+
return Err(E::ContractIdMismatch);
|
|
519
|
+
}
|
|
520
|
+
if input.version != AGENT_TRANSITION_CONTRACT_VERSION {
|
|
521
|
+
return Err(E::ContractVersionUnsupported);
|
|
522
|
+
}
|
|
523
|
+
let now = input.now_ms;
|
|
524
|
+
let op = &input.operation;
|
|
525
|
+
let records = &input.records;
|
|
526
|
+
match op.op.as_str() {
|
|
527
|
+
"create_task" => create_task(op, records, now),
|
|
528
|
+
"acquire" => acquire(op, records, now),
|
|
529
|
+
"renew" => renew(op, records, now),
|
|
530
|
+
"checkpoint" => checkpoint(op, records, now),
|
|
531
|
+
"record_intent" => record_intent(op, records, now),
|
|
532
|
+
"record_outcome" => record_outcome(op, records, now),
|
|
533
|
+
"reconcile" => reconcile(op, records, now),
|
|
534
|
+
"create_handoff" => create_handoff(op, records, now),
|
|
535
|
+
"claim_handoff" => claim_handoff(op, records, now),
|
|
536
|
+
"accept_handoff" => accept_handoff(op, records, now),
|
|
537
|
+
_ => Err(E::ContractInputInvalid),
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
// ---------------------------------------------------------------------------
|
|
542
|
+
// Shape validation
|
|
543
|
+
// ---------------------------------------------------------------------------
|
|
544
|
+
|
|
545
|
+
fn identifier_ok(value: &str) -> bool {
|
|
546
|
+
!value.is_empty()
|
|
547
|
+
&& value.len() <= MAX_IDENTIFIER_BYTES
|
|
548
|
+
&& value
|
|
549
|
+
.bytes()
|
|
550
|
+
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.' | b':' | b'@' | b'-'))
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
fn text_ok(value: &str) -> bool {
|
|
554
|
+
!value.is_empty() && value.len() <= MAX_TEXT_BYTES
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
const STATUSES: [&str; 5] = ["ready", "running", "blocked", "completed", "cancelled"];
|
|
558
|
+
|
|
559
|
+
fn terminal(status: &str) -> bool {
|
|
560
|
+
matches!(status, "completed" | "cancelled")
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
impl Operation {
|
|
564
|
+
/// Required and optional members per operation. Everything else is
|
|
565
|
+
/// forbidden: an operation carries exactly the members it is defined by.
|
|
566
|
+
fn members(&self) -> Option<(&'static [&'static str], &'static [&'static str])> {
|
|
567
|
+
Some(match self.op.as_str() {
|
|
568
|
+
"create_task" => (
|
|
569
|
+
&["task_id", "actor", "objective", "lease_id", "lease_ms"],
|
|
570
|
+
&[],
|
|
571
|
+
),
|
|
572
|
+
"acquire" => (&["task_id", "actor", "lease_id", "lease_ms"], &[]),
|
|
573
|
+
"renew" => (&["task_id", "actor", "fence", "lease_id", "lease_ms"], &[]),
|
|
574
|
+
"checkpoint" => (
|
|
575
|
+
&[
|
|
576
|
+
"task_id",
|
|
577
|
+
"actor",
|
|
578
|
+
"fence",
|
|
579
|
+
"lease_id",
|
|
580
|
+
"expected_version",
|
|
581
|
+
"summary",
|
|
582
|
+
"evidence",
|
|
583
|
+
],
|
|
584
|
+
&["status"],
|
|
585
|
+
),
|
|
586
|
+
"record_intent" => (
|
|
587
|
+
&[
|
|
588
|
+
"task_id",
|
|
589
|
+
"actor",
|
|
590
|
+
"fence",
|
|
591
|
+
"lease_id",
|
|
592
|
+
"idempotency_key",
|
|
593
|
+
"action",
|
|
594
|
+
],
|
|
595
|
+
&[],
|
|
596
|
+
),
|
|
597
|
+
"record_outcome" => (
|
|
598
|
+
&[
|
|
599
|
+
"task_id",
|
|
600
|
+
"actor",
|
|
601
|
+
"fence",
|
|
602
|
+
"lease_id",
|
|
603
|
+
"idempotency_key",
|
|
604
|
+
"result",
|
|
605
|
+
"evidence",
|
|
606
|
+
],
|
|
607
|
+
&[],
|
|
608
|
+
),
|
|
609
|
+
"reconcile" => (
|
|
610
|
+
&[
|
|
611
|
+
"task_id",
|
|
612
|
+
"actor",
|
|
613
|
+
"fence",
|
|
614
|
+
"lease_id",
|
|
615
|
+
"idempotency_key",
|
|
616
|
+
"conclusion",
|
|
617
|
+
"evidence",
|
|
618
|
+
],
|
|
619
|
+
&[],
|
|
620
|
+
),
|
|
621
|
+
"create_handoff" => (
|
|
622
|
+
&["task_id", "handoff_id", "actor", "fence", "lease_id"],
|
|
623
|
+
&["to"],
|
|
624
|
+
),
|
|
625
|
+
"claim_handoff" => (&["handoff_id", "claimant", "lease_id", "lease_ms"], &[]),
|
|
626
|
+
"accept_handoff" => (&["handoff_id", "claimant", "fence", "lease_id"], &[]),
|
|
627
|
+
_ => return None,
|
|
628
|
+
})
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
fn present(&self, name: &str) -> bool {
|
|
632
|
+
match name {
|
|
633
|
+
"action" => self.action.is_some(),
|
|
634
|
+
"actor" => self.actor.is_some(),
|
|
635
|
+
"claimant" => self.claimant.is_some(),
|
|
636
|
+
"conclusion" => self.conclusion.is_some(),
|
|
637
|
+
"evidence" => self.evidence.is_some(),
|
|
638
|
+
"expected_version" => self.expected_version.is_some(),
|
|
639
|
+
"fence" => self.fence.is_some(),
|
|
640
|
+
"handoff_id" => self.handoff_id.is_some(),
|
|
641
|
+
"idempotency_key" => self.idempotency_key.is_some(),
|
|
642
|
+
"lease_id" => self.lease_id.is_some(),
|
|
643
|
+
"lease_ms" => self.lease_ms.is_some(),
|
|
644
|
+
"objective" => self.objective.is_some(),
|
|
645
|
+
"result" => self.result.is_some(),
|
|
646
|
+
"status" => self.status.is_some(),
|
|
647
|
+
"summary" => self.summary.is_some(),
|
|
648
|
+
"task_id" => self.task_id.is_some(),
|
|
649
|
+
"to" => self.to.is_some(),
|
|
650
|
+
_ => false,
|
|
651
|
+
}
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
fn validate(&self) -> Result<(), ErrorCode> {
|
|
655
|
+
let (required, optional) = self.members().ok_or(E::ContractInputInvalid)?;
|
|
656
|
+
const ALL: [&str; 17] = [
|
|
657
|
+
"action",
|
|
658
|
+
"actor",
|
|
659
|
+
"claimant",
|
|
660
|
+
"conclusion",
|
|
661
|
+
"evidence",
|
|
662
|
+
"expected_version",
|
|
663
|
+
"fence",
|
|
664
|
+
"handoff_id",
|
|
665
|
+
"idempotency_key",
|
|
666
|
+
"lease_id",
|
|
667
|
+
"lease_ms",
|
|
668
|
+
"objective",
|
|
669
|
+
"result",
|
|
670
|
+
"status",
|
|
671
|
+
"summary",
|
|
672
|
+
"task_id",
|
|
673
|
+
"to",
|
|
674
|
+
];
|
|
675
|
+
for name in ALL {
|
|
676
|
+
let allowed = required.contains(&name) || optional.contains(&name);
|
|
677
|
+
if self.present(name) && !allowed {
|
|
678
|
+
return Err(E::ContractInputInvalid);
|
|
679
|
+
}
|
|
680
|
+
if required.contains(&name) && !self.present(name) {
|
|
681
|
+
return Err(E::ContractInputInvalid);
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
for id in [
|
|
685
|
+
&self.actor,
|
|
686
|
+
&self.claimant,
|
|
687
|
+
&self.handoff_id,
|
|
688
|
+
&self.idempotency_key,
|
|
689
|
+
&self.lease_id,
|
|
690
|
+
&self.task_id,
|
|
691
|
+
&self.to,
|
|
692
|
+
]
|
|
693
|
+
.into_iter()
|
|
694
|
+
.flatten()
|
|
695
|
+
{
|
|
696
|
+
if !identifier_ok(id) {
|
|
697
|
+
return Err(E::ContractInputInvalid);
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
for t in [&self.action, &self.objective, &self.summary]
|
|
701
|
+
.into_iter()
|
|
702
|
+
.flatten()
|
|
703
|
+
{
|
|
704
|
+
if !text_ok(t) {
|
|
705
|
+
return Err(E::ContractInputInvalid);
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
if self.fence == Some(0) || self.expected_version == Some(0) {
|
|
709
|
+
return Err(E::ContractInputInvalid);
|
|
710
|
+
}
|
|
711
|
+
if let Some(ms) = self.lease_ms {
|
|
712
|
+
if ms == 0 || ms > MAX_LEASE_MS {
|
|
713
|
+
return Err(E::ContractInputInvalid);
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
if let Some(status) = &self.status {
|
|
717
|
+
if !STATUSES.contains(&status.as_str()) {
|
|
718
|
+
return Err(E::ContractInputInvalid);
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
if let Some(result) = &self.result {
|
|
722
|
+
if !matches!(result.as_str(), "succeeded" | "failed") {
|
|
723
|
+
return Err(E::ContractInputInvalid);
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
if let Some(conclusion) = &self.conclusion {
|
|
727
|
+
if !matches!(conclusion.as_str(), "executed" | "not_executed") {
|
|
728
|
+
return Err(E::ContractInputInvalid);
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
if let Some(evidence) = &self.evidence {
|
|
732
|
+
if evidence.len() > MAX_EVIDENCE {
|
|
733
|
+
return Err(E::ContractInputInvalid);
|
|
734
|
+
}
|
|
735
|
+
for reference in evidence {
|
|
736
|
+
reference.validate()?;
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
Ok(())
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
impl EvidenceRef {
|
|
744
|
+
/// Structure only. Whether a cited record exists is decided later, against
|
|
745
|
+
/// the observations; whether the citation is admissible, later still.
|
|
746
|
+
fn validate(&self) -> Result<(), ErrorCode> {
|
|
747
|
+
let bounded =
|
|
748
|
+
|s: &Option<String>| s.as_ref().is_some_and(|s| !s.is_empty() && s.len() <= 256);
|
|
749
|
+
match self.kind.as_str() {
|
|
750
|
+
"record" if bounded(&self.collection) && bounded(&self.id) && self.uri.is_none() => {
|
|
751
|
+
Ok(())
|
|
752
|
+
}
|
|
753
|
+
"external"
|
|
754
|
+
if self.uri.as_ref().is_some_and(|u| text_ok(u))
|
|
755
|
+
&& self.collection.is_none()
|
|
756
|
+
&& self.id.is_none() =>
|
|
757
|
+
{
|
|
758
|
+
Ok(())
|
|
759
|
+
}
|
|
760
|
+
_ => Err(E::ContractInputInvalid),
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
impl Records {
|
|
766
|
+
fn validate_for(&self, op: &str) -> Result<(), ErrorCode> {
|
|
767
|
+
// Which record keys an operation may carry. A key is present exactly
|
|
768
|
+
// when the record exists, so absence of a record is a decision
|
|
769
|
+
// (`NOT_FOUND`, `INTENT_UNKNOWN`), never a malformed input. Evidence
|
|
770
|
+
// observations are a required list, possibly empty, for the operations
|
|
771
|
+
// that cite evidence.
|
|
772
|
+
let (task, handoff, intent, evidence) = match op {
|
|
773
|
+
"create_task" | "acquire" | "renew" => (true, false, false, false),
|
|
774
|
+
"checkpoint" => (true, false, false, true),
|
|
775
|
+
"record_intent" => (true, false, true, false),
|
|
776
|
+
"record_outcome" | "reconcile" => (true, false, true, true),
|
|
777
|
+
"create_handoff" => (true, true, false, false),
|
|
778
|
+
"claim_handoff" | "accept_handoff" => (true, true, false, false),
|
|
779
|
+
_ => return Err(E::ContractInputInvalid),
|
|
780
|
+
};
|
|
781
|
+
if (!task && self.task.is_some())
|
|
782
|
+
|| (!handoff && self.handoff.is_some())
|
|
783
|
+
|| (!intent && self.intent.is_some())
|
|
784
|
+
|| (evidence != self.evidence.is_some())
|
|
785
|
+
{
|
|
786
|
+
return Err(E::ContractInputInvalid);
|
|
787
|
+
}
|
|
788
|
+
if let Some(stored) = &self.task {
|
|
789
|
+
stored.value.validate()?;
|
|
790
|
+
}
|
|
791
|
+
if let Some(stored) = &self.handoff {
|
|
792
|
+
let h = &stored.value;
|
|
793
|
+
if !matches!(h.status.as_str(), "open" | "claimed" | "accepted") {
|
|
794
|
+
return Err(E::ContractInputInvalid);
|
|
795
|
+
}
|
|
796
|
+
// A claimed or accepted handoff names its claimant and the fence
|
|
797
|
+
// that claim created; an open one names neither.
|
|
798
|
+
let claimed = h.claimant.is_some() && h.claimed_fence.is_some();
|
|
799
|
+
let unclaimed = h.claimant.is_none() && h.claimed_fence.is_none();
|
|
800
|
+
if (h.status == "open" && !unclaimed) || (h.status != "open" && !claimed) {
|
|
801
|
+
return Err(E::ContractInputInvalid);
|
|
802
|
+
}
|
|
803
|
+
}
|
|
804
|
+
if let Some(stored) = &self.intent {
|
|
805
|
+
if !matches!(
|
|
806
|
+
stored.value.state.as_str(),
|
|
807
|
+
"intended" | "reported" | "resolved"
|
|
808
|
+
) {
|
|
809
|
+
return Err(E::ContractInputInvalid);
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
if let Some(observed) = &self.evidence {
|
|
813
|
+
for (index, o) in observed.iter().enumerate() {
|
|
814
|
+
if observed[..index]
|
|
815
|
+
.iter()
|
|
816
|
+
.any(|p| p.collection == o.collection && p.id == o.id)
|
|
817
|
+
{
|
|
818
|
+
return Err(E::ContractInputInvalid);
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
Ok(())
|
|
823
|
+
}
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
impl TaskValue {
|
|
827
|
+
/// A task is terminal exactly when it holds no lease.
|
|
828
|
+
fn validate(&self) -> Result<(), ErrorCode> {
|
|
829
|
+
if !STATUSES.contains(&self.status.as_str())
|
|
830
|
+
|| self.fence == 0
|
|
831
|
+
|| self.checkpoint_version == 0
|
|
832
|
+
|| terminal(&self.status) != self.lease.is_none()
|
|
833
|
+
{
|
|
834
|
+
return Err(E::ContractInputInvalid);
|
|
835
|
+
}
|
|
836
|
+
Ok(())
|
|
837
|
+
}
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
// ---------------------------------------------------------------------------
|
|
841
|
+
// Shared rules
|
|
842
|
+
// ---------------------------------------------------------------------------
|
|
843
|
+
|
|
844
|
+
fn s(value: &Option<String>) -> &str {
|
|
845
|
+
value.as_deref().unwrap_or_default()
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
fn intent_id(task: &str, key: &str) -> String {
|
|
849
|
+
format!("{task}~{key}")
|
|
850
|
+
}
|
|
851
|
+
|
|
852
|
+
fn task_json(value: &TaskValue) -> Value {
|
|
853
|
+
serde_json::to_value(value).expect("task serializes")
|
|
854
|
+
}
|
|
855
|
+
|
|
856
|
+
fn lease_expired(lease: &Lease, now: u64) -> bool {
|
|
857
|
+
now >= lease.expires_at
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
fn new_lease(now: u64, lease_id: &str, lease_ms: u64) -> Result<Lease, ErrorCode> {
|
|
861
|
+
Ok(Lease {
|
|
862
|
+
expires_at: now.checked_add(lease_ms).ok_or(E::ContractInputInvalid)?,
|
|
863
|
+
lease_id: lease_id.to_string(),
|
|
864
|
+
})
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
/// The one ownership rule. Order is part of the contract, so two refusals that
|
|
868
|
+
/// both apply always report the same one.
|
|
869
|
+
fn owner_checks(
|
|
870
|
+
task: &TaskValue,
|
|
871
|
+
actor: &str,
|
|
872
|
+
fence: u64,
|
|
873
|
+
lease_id: &str,
|
|
874
|
+
now: u64,
|
|
875
|
+
) -> Result<Lease, ErrorCode> {
|
|
876
|
+
if terminal(&task.status) {
|
|
877
|
+
return Err(E::Terminal);
|
|
878
|
+
}
|
|
879
|
+
if fence != task.fence {
|
|
880
|
+
return Err(E::FenceStale);
|
|
881
|
+
}
|
|
882
|
+
if actor != task.owner {
|
|
883
|
+
return Err(E::OwnershipConflict);
|
|
884
|
+
}
|
|
885
|
+
let lease = task.lease.clone().ok_or(E::ContractInputInvalid)?;
|
|
886
|
+
if lease_id != lease.lease_id {
|
|
887
|
+
return Err(E::LeaseMismatch);
|
|
888
|
+
}
|
|
889
|
+
if lease_expired(&lease, now) {
|
|
890
|
+
return Err(E::LeaseExpired);
|
|
891
|
+
}
|
|
892
|
+
Ok(lease)
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
fn task_expect(stored: &Stored<TaskValue>, lease: &Lease) -> Expect {
|
|
896
|
+
Expect::Version {
|
|
897
|
+
version: stored.version,
|
|
898
|
+
lease_id: Some(lease.lease_id.clone()),
|
|
899
|
+
}
|
|
900
|
+
}
|
|
901
|
+
|
|
902
|
+
fn task_guard(stored: &Stored<TaskValue>, lease: &Lease) -> Guard {
|
|
903
|
+
Guard {
|
|
904
|
+
collection: TASK_COLLECTION.into(),
|
|
905
|
+
id: stored.value.task_id.clone(),
|
|
906
|
+
version: stored.version,
|
|
907
|
+
lease_id: Some(lease.lease_id.clone()),
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
struct Resolved {
|
|
912
|
+
citations: Vec<Citation>,
|
|
913
|
+
guards: Vec<Guard>,
|
|
914
|
+
verified: usize,
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
/// Turns a caller's citations into stored citations, using only what FeltDB
|
|
918
|
+
/// observed. A record citation with no matching observation is refused, as is
|
|
919
|
+
/// one aimed at the agent's own records. Every observation must correspond to
|
|
920
|
+
/// a cited record, so the native layer cannot smuggle in extras.
|
|
921
|
+
fn resolve_evidence(refs: &[EvidenceRef], observed: &[Observation]) -> Result<Resolved, ErrorCode> {
|
|
922
|
+
let mut citations = Vec::new();
|
|
923
|
+
let mut guards = Vec::new();
|
|
924
|
+
let mut cited_records = 0;
|
|
925
|
+
for (index, reference) in refs.iter().enumerate() {
|
|
926
|
+
if refs[..index].iter().any(|p| p == reference) {
|
|
927
|
+
return Err(E::EvidenceInvalid);
|
|
928
|
+
}
|
|
929
|
+
if reference.kind == "external" {
|
|
930
|
+
citations.push(Citation {
|
|
931
|
+
collection: None,
|
|
932
|
+
id: None,
|
|
933
|
+
kind: "external".into(),
|
|
934
|
+
uri: reference.uri.clone(),
|
|
935
|
+
verified: false,
|
|
936
|
+
version: None,
|
|
937
|
+
});
|
|
938
|
+
continue;
|
|
939
|
+
}
|
|
940
|
+
let (collection, id) = (s(&reference.collection), s(&reference.id));
|
|
941
|
+
if collection.starts_with(AGENT_COLLECTION_PREFIX) {
|
|
942
|
+
return Err(E::EvidenceInvalid);
|
|
943
|
+
}
|
|
944
|
+
let seen = observed
|
|
945
|
+
.iter()
|
|
946
|
+
.find(|o| o.collection == collection && o.id == id)
|
|
947
|
+
.ok_or(E::EvidenceInvalid)?;
|
|
948
|
+
cited_records += 1;
|
|
949
|
+
citations.push(Citation {
|
|
950
|
+
collection: Some(collection.into()),
|
|
951
|
+
id: Some(id.into()),
|
|
952
|
+
kind: "record".into(),
|
|
953
|
+
uri: None,
|
|
954
|
+
verified: true,
|
|
955
|
+
version: Some(seen.version),
|
|
956
|
+
});
|
|
957
|
+
guards.push(Guard {
|
|
958
|
+
collection: collection.into(),
|
|
959
|
+
id: id.into(),
|
|
960
|
+
version: seen.version,
|
|
961
|
+
lease_id: None,
|
|
962
|
+
});
|
|
963
|
+
}
|
|
964
|
+
if observed.len() != cited_records {
|
|
965
|
+
return Err(E::ContractInputInvalid);
|
|
966
|
+
}
|
|
967
|
+
Ok(Resolved {
|
|
968
|
+
verified: cited_records,
|
|
969
|
+
citations,
|
|
970
|
+
guards,
|
|
971
|
+
})
|
|
972
|
+
}
|
|
973
|
+
|
|
974
|
+
fn allowed_transition(from: &str, to: &str) -> bool {
|
|
975
|
+
from == to && !terminal(from)
|
|
976
|
+
|| matches!(
|
|
977
|
+
(from, to),
|
|
978
|
+
("ready", "running")
|
|
979
|
+
| ("ready", "cancelled")
|
|
980
|
+
| ("running", "blocked")
|
|
981
|
+
| ("running", "completed")
|
|
982
|
+
| ("running", "cancelled")
|
|
983
|
+
| ("blocked", "running")
|
|
984
|
+
| ("blocked", "cancelled")
|
|
985
|
+
)
|
|
986
|
+
}
|
|
987
|
+
|
|
988
|
+
// ---------------------------------------------------------------------------
|
|
989
|
+
// Operations
|
|
990
|
+
// ---------------------------------------------------------------------------
|
|
991
|
+
|
|
992
|
+
fn create_task(op: &Operation, records: &Records, now: u64) -> Outcome {
|
|
993
|
+
let (id, actor, objective) = (s(&op.task_id), s(&op.actor), s(&op.objective));
|
|
994
|
+
if let Some(existing) = &records.task {
|
|
995
|
+
let t = &existing.value;
|
|
996
|
+
return if t.objective == objective && t.owner == actor {
|
|
997
|
+
Ok(Decision::Noop)
|
|
998
|
+
} else {
|
|
999
|
+
Err(E::AlreadyExists)
|
|
1000
|
+
};
|
|
1001
|
+
}
|
|
1002
|
+
let lease = new_lease(now, s(&op.lease_id), op.lease_ms.unwrap_or_default())?;
|
|
1003
|
+
let task = TaskValue {
|
|
1004
|
+
checkpoint_version: 1,
|
|
1005
|
+
created_at_ms: now,
|
|
1006
|
+
fence: 1,
|
|
1007
|
+
lease: Some(lease),
|
|
1008
|
+
objective: objective.into(),
|
|
1009
|
+
owner: actor.into(),
|
|
1010
|
+
status: "ready".into(),
|
|
1011
|
+
task_id: id.into(),
|
|
1012
|
+
unresolved_intents: 0,
|
|
1013
|
+
updated_at_ms: now,
|
|
1014
|
+
};
|
|
1015
|
+
Ok(Decision::Commit {
|
|
1016
|
+
writes: vec![
|
|
1017
|
+
Write {
|
|
1018
|
+
collection: TASK_COLLECTION,
|
|
1019
|
+
id: id.into(),
|
|
1020
|
+
expect: Expect::Absent,
|
|
1021
|
+
value: task_json(&task),
|
|
1022
|
+
},
|
|
1023
|
+
Write {
|
|
1024
|
+
collection: CHECKPOINT_COLLECTION,
|
|
1025
|
+
id: format!("{id}~v1"),
|
|
1026
|
+
expect: Expect::Absent,
|
|
1027
|
+
value: json!({
|
|
1028
|
+
"actor": actor, "created_at_ms": now, "evidence": [], "fence": 1,
|
|
1029
|
+
"status": "ready", "summary": "Task created.", "task_id": id, "version": 1,
|
|
1030
|
+
}),
|
|
1031
|
+
},
|
|
1032
|
+
],
|
|
1033
|
+
guards: vec![],
|
|
1034
|
+
})
|
|
1035
|
+
}
|
|
1036
|
+
|
|
1037
|
+
fn acquire(op: &Operation, records: &Records, now: u64) -> Outcome {
|
|
1038
|
+
let stored = records.task.as_ref().ok_or(E::NotFound)?;
|
|
1039
|
+
let task = &stored.value;
|
|
1040
|
+
if terminal(&task.status) {
|
|
1041
|
+
return Err(E::Terminal);
|
|
1042
|
+
}
|
|
1043
|
+
let held = task.lease.as_ref().ok_or(E::ContractInputInvalid)?;
|
|
1044
|
+
if !lease_expired(held, now) {
|
|
1045
|
+
return Err(E::LeaseHeld);
|
|
1046
|
+
}
|
|
1047
|
+
if s(&op.lease_id) == held.lease_id {
|
|
1048
|
+
return Err(E::LeaseMismatch);
|
|
1049
|
+
}
|
|
1050
|
+
let mut next = task.clone();
|
|
1051
|
+
next.owner = s(&op.actor).into();
|
|
1052
|
+
next.fence = task.fence.checked_add(1).ok_or(E::ContractInputInvalid)?;
|
|
1053
|
+
next.lease = Some(new_lease(
|
|
1054
|
+
now,
|
|
1055
|
+
s(&op.lease_id),
|
|
1056
|
+
op.lease_ms.unwrap_or_default(),
|
|
1057
|
+
)?);
|
|
1058
|
+
next.updated_at_ms = now;
|
|
1059
|
+
// The version guard, not a time predicate, protects "this lease is
|
|
1060
|
+
// expired": time only moves forward, and any renewal, claim or
|
|
1061
|
+
// acquisition changes the record's version.
|
|
1062
|
+
Ok(Decision::Commit {
|
|
1063
|
+
writes: vec![Write {
|
|
1064
|
+
collection: TASK_COLLECTION,
|
|
1065
|
+
id: task.task_id.clone(),
|
|
1066
|
+
expect: Expect::Version {
|
|
1067
|
+
version: stored.version,
|
|
1068
|
+
lease_id: None,
|
|
1069
|
+
},
|
|
1070
|
+
value: task_json(&next),
|
|
1071
|
+
}],
|
|
1072
|
+
guards: vec![],
|
|
1073
|
+
})
|
|
1074
|
+
}
|
|
1075
|
+
|
|
1076
|
+
fn renew(op: &Operation, records: &Records, now: u64) -> Outcome {
|
|
1077
|
+
let stored = records.task.as_ref().ok_or(E::NotFound)?;
|
|
1078
|
+
let task = &stored.value;
|
|
1079
|
+
let lease = owner_checks(
|
|
1080
|
+
task,
|
|
1081
|
+
s(&op.actor),
|
|
1082
|
+
op.fence.unwrap_or_default(),
|
|
1083
|
+
s(&op.lease_id),
|
|
1084
|
+
now,
|
|
1085
|
+
)?;
|
|
1086
|
+
let mut next = task.clone();
|
|
1087
|
+
next.lease = Some(new_lease(
|
|
1088
|
+
now,
|
|
1089
|
+
&lease.lease_id,
|
|
1090
|
+
op.lease_ms.unwrap_or_default(),
|
|
1091
|
+
)?);
|
|
1092
|
+
next.updated_at_ms = now;
|
|
1093
|
+
Ok(Decision::Commit {
|
|
1094
|
+
writes: vec![Write {
|
|
1095
|
+
collection: TASK_COLLECTION,
|
|
1096
|
+
id: task.task_id.clone(),
|
|
1097
|
+
expect: task_expect(stored, &lease),
|
|
1098
|
+
value: task_json(&next),
|
|
1099
|
+
}],
|
|
1100
|
+
guards: vec![],
|
|
1101
|
+
})
|
|
1102
|
+
}
|
|
1103
|
+
|
|
1104
|
+
fn checkpoint(op: &Operation, records: &Records, now: u64) -> Outcome {
|
|
1105
|
+
let stored = records.task.as_ref().ok_or(E::NotFound)?;
|
|
1106
|
+
let task = &stored.value;
|
|
1107
|
+
let lease = owner_checks(
|
|
1108
|
+
task,
|
|
1109
|
+
s(&op.actor),
|
|
1110
|
+
op.fence.unwrap_or_default(),
|
|
1111
|
+
s(&op.lease_id),
|
|
1112
|
+
now,
|
|
1113
|
+
)?;
|
|
1114
|
+
if op.expected_version != Some(task.checkpoint_version) {
|
|
1115
|
+
return Err(E::VersionConflict);
|
|
1116
|
+
}
|
|
1117
|
+
let status = op.status.clone().unwrap_or_else(|| task.status.clone());
|
|
1118
|
+
if !allowed_transition(&task.status, &status) {
|
|
1119
|
+
return Err(E::InvalidTransition);
|
|
1120
|
+
}
|
|
1121
|
+
let resolved = resolve_evidence(
|
|
1122
|
+
op.evidence.as_deref().unwrap_or_default(),
|
|
1123
|
+
records.evidence.as_deref().unwrap_or_default(),
|
|
1124
|
+
)?;
|
|
1125
|
+
if status == "completed" {
|
|
1126
|
+
// A completion is a claim until FeltDB has seen something that backs
|
|
1127
|
+
// it, and it cannot stand while an action may or may not have run.
|
|
1128
|
+
if resolved.verified == 0 {
|
|
1129
|
+
return Err(E::EvidenceRequired);
|
|
1130
|
+
}
|
|
1131
|
+
if task.unresolved_intents > 0 {
|
|
1132
|
+
return Err(E::OutcomeUncertain);
|
|
1133
|
+
}
|
|
1134
|
+
}
|
|
1135
|
+
let version = task
|
|
1136
|
+
.checkpoint_version
|
|
1137
|
+
.checked_add(1)
|
|
1138
|
+
.ok_or(E::ContractInputInvalid)?;
|
|
1139
|
+
let mut next = task.clone();
|
|
1140
|
+
next.status = status.clone();
|
|
1141
|
+
next.checkpoint_version = version;
|
|
1142
|
+
next.updated_at_ms = now;
|
|
1143
|
+
if terminal(&status) {
|
|
1144
|
+
next.lease = None;
|
|
1145
|
+
}
|
|
1146
|
+
let mut guards = resolved.guards;
|
|
1147
|
+
guards.sort_by(|a, b| (&a.collection, &a.id).cmp(&(&b.collection, &b.id)));
|
|
1148
|
+
Ok(Decision::Commit {
|
|
1149
|
+
writes: vec![
|
|
1150
|
+
Write {
|
|
1151
|
+
collection: TASK_COLLECTION,
|
|
1152
|
+
id: task.task_id.clone(),
|
|
1153
|
+
expect: task_expect(stored, &lease),
|
|
1154
|
+
value: task_json(&next),
|
|
1155
|
+
},
|
|
1156
|
+
Write {
|
|
1157
|
+
collection: CHECKPOINT_COLLECTION,
|
|
1158
|
+
id: format!("{}~v{}", task.task_id, version),
|
|
1159
|
+
expect: Expect::Absent,
|
|
1160
|
+
value: json!({
|
|
1161
|
+
"actor": s(&op.actor), "created_at_ms": now, "evidence": resolved.citations,
|
|
1162
|
+
"fence": task.fence, "status": status, "summary": s(&op.summary),
|
|
1163
|
+
"task_id": task.task_id, "version": version,
|
|
1164
|
+
}),
|
|
1165
|
+
},
|
|
1166
|
+
],
|
|
1167
|
+
guards,
|
|
1168
|
+
})
|
|
1169
|
+
}
|
|
1170
|
+
|
|
1171
|
+
fn record_intent(op: &Operation, records: &Records, now: u64) -> Outcome {
|
|
1172
|
+
let stored = records.task.as_ref().ok_or(E::NotFound)?;
|
|
1173
|
+
let task = &stored.value;
|
|
1174
|
+
let lease = owner_checks(
|
|
1175
|
+
task,
|
|
1176
|
+
s(&op.actor),
|
|
1177
|
+
op.fence.unwrap_or_default(),
|
|
1178
|
+
s(&op.lease_id),
|
|
1179
|
+
now,
|
|
1180
|
+
)?;
|
|
1181
|
+
if task.status != "running" {
|
|
1182
|
+
return Err(E::InvalidTransition);
|
|
1183
|
+
}
|
|
1184
|
+
if let Some(existing) = &records.intent {
|
|
1185
|
+
// A key already recorded is never a fresh start. While its outcome is
|
|
1186
|
+
// unknown, the action may have run, and saying so is the point.
|
|
1187
|
+
return Err(if existing.value.state == "resolved" {
|
|
1188
|
+
E::IntentResolved
|
|
1189
|
+
} else {
|
|
1190
|
+
E::OutcomeUncertain
|
|
1191
|
+
});
|
|
1192
|
+
}
|
|
1193
|
+
let mut next = task.clone();
|
|
1194
|
+
next.unresolved_intents = task
|
|
1195
|
+
.unresolved_intents
|
|
1196
|
+
.checked_add(1)
|
|
1197
|
+
.ok_or(E::ContractInputInvalid)?;
|
|
1198
|
+
next.updated_at_ms = now;
|
|
1199
|
+
let key = s(&op.idempotency_key);
|
|
1200
|
+
Ok(Decision::Commit {
|
|
1201
|
+
writes: vec![
|
|
1202
|
+
Write {
|
|
1203
|
+
collection: TASK_COLLECTION,
|
|
1204
|
+
id: task.task_id.clone(),
|
|
1205
|
+
expect: task_expect(stored, &lease),
|
|
1206
|
+
value: task_json(&next),
|
|
1207
|
+
},
|
|
1208
|
+
Write {
|
|
1209
|
+
collection: INTENT_COLLECTION,
|
|
1210
|
+
id: intent_id(&task.task_id, key),
|
|
1211
|
+
expect: Expect::Absent,
|
|
1212
|
+
value: json!({
|
|
1213
|
+
"action": s(&op.action), "evidence": [], "intended_at_ms": now,
|
|
1214
|
+
"intended_fence": task.fence, "key": key, "state": "intended",
|
|
1215
|
+
"task_id": task.task_id, "verified": false,
|
|
1216
|
+
}),
|
|
1217
|
+
},
|
|
1218
|
+
],
|
|
1219
|
+
guards: vec![],
|
|
1220
|
+
})
|
|
1221
|
+
}
|
|
1222
|
+
|
|
1223
|
+
/// Shared by `record_outcome` and `reconcile`: the owner-checked update of one
|
|
1224
|
+
/// intent and the unresolved-intent count on the task.
|
|
1225
|
+
fn settle(
|
|
1226
|
+
op: &Operation,
|
|
1227
|
+
records: &Records,
|
|
1228
|
+
now: u64,
|
|
1229
|
+
allowed_from: &[&str],
|
|
1230
|
+
build: impl FnOnce(&IntentValue, Resolved) -> Result<(IntentValue, bool), ErrorCode>,
|
|
1231
|
+
) -> Outcome {
|
|
1232
|
+
let stored = records.task.as_ref().ok_or(E::NotFound)?;
|
|
1233
|
+
let task = &stored.value;
|
|
1234
|
+
let lease = owner_checks(
|
|
1235
|
+
task,
|
|
1236
|
+
s(&op.actor),
|
|
1237
|
+
op.fence.unwrap_or_default(),
|
|
1238
|
+
s(&op.lease_id),
|
|
1239
|
+
now,
|
|
1240
|
+
)?;
|
|
1241
|
+
let intent = records.intent.as_ref().ok_or(E::IntentUnknown)?;
|
|
1242
|
+
if !allowed_from.contains(&intent.value.state.as_str()) {
|
|
1243
|
+
return Err(E::IntentResolved);
|
|
1244
|
+
}
|
|
1245
|
+
let resolved = resolve_evidence(
|
|
1246
|
+
op.evidence.as_deref().unwrap_or_default(),
|
|
1247
|
+
records.evidence.as_deref().unwrap_or_default(),
|
|
1248
|
+
)?;
|
|
1249
|
+
let guards = resolved.guards.clone();
|
|
1250
|
+
let (next_intent, resolves) = build(&intent.value, resolved)?;
|
|
1251
|
+
let mut next = task.clone();
|
|
1252
|
+
if resolves {
|
|
1253
|
+
next.unresolved_intents = task
|
|
1254
|
+
.unresolved_intents
|
|
1255
|
+
.checked_sub(1)
|
|
1256
|
+
.ok_or(E::ContractInputInvalid)?;
|
|
1257
|
+
}
|
|
1258
|
+
next.updated_at_ms = now;
|
|
1259
|
+
let mut guards = guards;
|
|
1260
|
+
guards.sort_by(|a, b| (&a.collection, &a.id).cmp(&(&b.collection, &b.id)));
|
|
1261
|
+
Ok(Decision::Commit {
|
|
1262
|
+
writes: vec![
|
|
1263
|
+
Write {
|
|
1264
|
+
collection: TASK_COLLECTION,
|
|
1265
|
+
id: task.task_id.clone(),
|
|
1266
|
+
expect: task_expect(stored, &lease),
|
|
1267
|
+
value: task_json(&next),
|
|
1268
|
+
},
|
|
1269
|
+
Write {
|
|
1270
|
+
collection: INTENT_COLLECTION,
|
|
1271
|
+
id: intent_id(&task.task_id, s(&op.idempotency_key)),
|
|
1272
|
+
expect: Expect::Version {
|
|
1273
|
+
version: intent.version,
|
|
1274
|
+
lease_id: None,
|
|
1275
|
+
},
|
|
1276
|
+
value: serde_json::to_value(&next_intent).expect("intent serializes"),
|
|
1277
|
+
},
|
|
1278
|
+
],
|
|
1279
|
+
guards,
|
|
1280
|
+
})
|
|
1281
|
+
}
|
|
1282
|
+
|
|
1283
|
+
fn record_outcome(op: &Operation, records: &Records, now: u64) -> Outcome {
|
|
1284
|
+
settle(op, records, now, &["intended"], |intent, resolved| {
|
|
1285
|
+
// A reported outcome is a claim. Only an outcome FeltDB saw evidence
|
|
1286
|
+
// for resolves the intent.
|
|
1287
|
+
let verified = resolved.verified > 0;
|
|
1288
|
+
let mut next = intent.clone();
|
|
1289
|
+
next.result = op.result.clone();
|
|
1290
|
+
next.evidence = resolved.citations;
|
|
1291
|
+
next.verified = verified;
|
|
1292
|
+
next.state = if verified { "resolved" } else { "reported" }.into();
|
|
1293
|
+
Ok((next, verified))
|
|
1294
|
+
})
|
|
1295
|
+
}
|
|
1296
|
+
|
|
1297
|
+
fn reconcile(op: &Operation, records: &Records, now: u64) -> Outcome {
|
|
1298
|
+
settle(
|
|
1299
|
+
op,
|
|
1300
|
+
records,
|
|
1301
|
+
now,
|
|
1302
|
+
&["intended", "reported"],
|
|
1303
|
+
|intent, resolved| {
|
|
1304
|
+
// Settling an uncertain action, in either direction, needs evidence.
|
|
1305
|
+
// The absence of an outcome record is not evidence of non-execution.
|
|
1306
|
+
if resolved.verified == 0 {
|
|
1307
|
+
return Err(E::EvidenceRequired);
|
|
1308
|
+
}
|
|
1309
|
+
let mut next = intent.clone();
|
|
1310
|
+
next.conclusion = op.conclusion.clone();
|
|
1311
|
+
next.evidence = [intent.evidence.clone(), resolved.citations].concat();
|
|
1312
|
+
next.verified = true;
|
|
1313
|
+
next.state = "resolved".into();
|
|
1314
|
+
Ok((next, true))
|
|
1315
|
+
},
|
|
1316
|
+
)
|
|
1317
|
+
}
|
|
1318
|
+
|
|
1319
|
+
fn create_handoff(op: &Operation, records: &Records, now: u64) -> Outcome {
|
|
1320
|
+
let stored = records.task.as_ref().ok_or(E::NotFound)?;
|
|
1321
|
+
let task = &stored.value;
|
|
1322
|
+
let lease = owner_checks(
|
|
1323
|
+
task,
|
|
1324
|
+
s(&op.actor),
|
|
1325
|
+
op.fence.unwrap_or_default(),
|
|
1326
|
+
s(&op.lease_id),
|
|
1327
|
+
now,
|
|
1328
|
+
)?;
|
|
1329
|
+
if records.handoff.is_some() {
|
|
1330
|
+
return Err(E::AlreadyExists);
|
|
1331
|
+
}
|
|
1332
|
+
let handoff = HandoffValue {
|
|
1333
|
+
checkpoint_version: task.checkpoint_version,
|
|
1334
|
+
claimant: None,
|
|
1335
|
+
claimed_fence: None,
|
|
1336
|
+
from: s(&op.actor).into(),
|
|
1337
|
+
from_fence: task.fence,
|
|
1338
|
+
handoff_id: s(&op.handoff_id).into(),
|
|
1339
|
+
status: "open".into(),
|
|
1340
|
+
task_id: task.task_id.clone(),
|
|
1341
|
+
to: op.to.clone(),
|
|
1342
|
+
};
|
|
1343
|
+
Ok(Decision::Commit {
|
|
1344
|
+
writes: vec![Write {
|
|
1345
|
+
collection: HANDOFF_COLLECTION,
|
|
1346
|
+
id: handoff.handoff_id.clone(),
|
|
1347
|
+
expect: Expect::Absent,
|
|
1348
|
+
value: serde_json::to_value(&handoff).expect("handoff serializes"),
|
|
1349
|
+
}],
|
|
1350
|
+
guards: vec![task_guard(stored, &lease)],
|
|
1351
|
+
})
|
|
1352
|
+
}
|
|
1353
|
+
|
|
1354
|
+
fn claim_handoff(op: &Operation, records: &Records, now: u64) -> Outcome {
|
|
1355
|
+
let (handoff_stored, task_stored) = (
|
|
1356
|
+
records.handoff.as_ref().ok_or(E::NotFound)?,
|
|
1357
|
+
records.task.as_ref().ok_or(E::NotFound)?,
|
|
1358
|
+
);
|
|
1359
|
+
let (handoff, task) = (&handoff_stored.value, &task_stored.value);
|
|
1360
|
+
let claimant = s(&op.claimant);
|
|
1361
|
+
if handoff.task_id != task.task_id {
|
|
1362
|
+
return Err(E::ContractInputInvalid);
|
|
1363
|
+
}
|
|
1364
|
+
if handoff.status == "accepted" {
|
|
1365
|
+
return Err(E::HandoffClaimed);
|
|
1366
|
+
}
|
|
1367
|
+
if terminal(&task.status) {
|
|
1368
|
+
return Err(E::Terminal);
|
|
1369
|
+
}
|
|
1370
|
+
if handoff.to.as_deref().is_some_and(|to| to != claimant) {
|
|
1371
|
+
return Err(E::OwnershipConflict);
|
|
1372
|
+
}
|
|
1373
|
+
let held = task.lease.as_ref().ok_or(E::ContractInputInvalid)?;
|
|
1374
|
+
if handoff.status == "claimed" {
|
|
1375
|
+
if !lease_expired(held, now) {
|
|
1376
|
+
let holder_retry = handoff.claimant.as_deref() == Some(claimant)
|
|
1377
|
+
&& task.owner == claimant
|
|
1378
|
+
&& held.lease_id == s(&op.lease_id);
|
|
1379
|
+
return if holder_retry {
|
|
1380
|
+
Ok(Decision::Noop)
|
|
1381
|
+
} else {
|
|
1382
|
+
Err(E::HandoffClaimed)
|
|
1383
|
+
};
|
|
1384
|
+
}
|
|
1385
|
+
// An abandoned claim is recoverable only while the task is still with
|
|
1386
|
+
// the claimant that abandoned it.
|
|
1387
|
+
if handoff.claimant.as_deref() != Some(task.owner.as_str()) {
|
|
1388
|
+
return Err(E::HandoffStale);
|
|
1389
|
+
}
|
|
1390
|
+
} else if task.owner != handoff.from
|
|
1391
|
+
|| task.fence != handoff.from_fence
|
|
1392
|
+
|| task.checkpoint_version != handoff.checkpoint_version
|
|
1393
|
+
{
|
|
1394
|
+
return Err(E::HandoffStale);
|
|
1395
|
+
}
|
|
1396
|
+
if s(&op.lease_id) == held.lease_id {
|
|
1397
|
+
return Err(E::LeaseMismatch);
|
|
1398
|
+
}
|
|
1399
|
+
let fence = task.fence.checked_add(1).ok_or(E::ContractInputInvalid)?;
|
|
1400
|
+
let mut next_task = task.clone();
|
|
1401
|
+
next_task.owner = claimant.into();
|
|
1402
|
+
next_task.fence = fence;
|
|
1403
|
+
next_task.lease = Some(new_lease(
|
|
1404
|
+
now,
|
|
1405
|
+
s(&op.lease_id),
|
|
1406
|
+
op.lease_ms.unwrap_or_default(),
|
|
1407
|
+
)?);
|
|
1408
|
+
next_task.updated_at_ms = now;
|
|
1409
|
+
let mut next_handoff = handoff.clone();
|
|
1410
|
+
next_handoff.status = "claimed".into();
|
|
1411
|
+
next_handoff.claimant = Some(claimant.into());
|
|
1412
|
+
next_handoff.claimed_fence = Some(fence);
|
|
1413
|
+
Ok(Decision::Commit {
|
|
1414
|
+
writes: vec![
|
|
1415
|
+
Write {
|
|
1416
|
+
collection: HANDOFF_COLLECTION,
|
|
1417
|
+
id: handoff.handoff_id.clone(),
|
|
1418
|
+
expect: Expect::Version {
|
|
1419
|
+
version: handoff_stored.version,
|
|
1420
|
+
lease_id: None,
|
|
1421
|
+
},
|
|
1422
|
+
value: serde_json::to_value(&next_handoff).expect("handoff serializes"),
|
|
1423
|
+
},
|
|
1424
|
+
Write {
|
|
1425
|
+
collection: TASK_COLLECTION,
|
|
1426
|
+
id: task.task_id.clone(),
|
|
1427
|
+
expect: Expect::Version {
|
|
1428
|
+
version: task_stored.version,
|
|
1429
|
+
lease_id: None,
|
|
1430
|
+
},
|
|
1431
|
+
value: task_json(&next_task),
|
|
1432
|
+
},
|
|
1433
|
+
],
|
|
1434
|
+
guards: vec![],
|
|
1435
|
+
})
|
|
1436
|
+
}
|
|
1437
|
+
|
|
1438
|
+
fn accept_handoff(op: &Operation, records: &Records, now: u64) -> Outcome {
|
|
1439
|
+
let (handoff_stored, task_stored) = (
|
|
1440
|
+
records.handoff.as_ref().ok_or(E::NotFound)?,
|
|
1441
|
+
records.task.as_ref().ok_or(E::NotFound)?,
|
|
1442
|
+
);
|
|
1443
|
+
let (handoff, task) = (&handoff_stored.value, &task_stored.value);
|
|
1444
|
+
let claimant = s(&op.claimant);
|
|
1445
|
+
if handoff.task_id != task.task_id {
|
|
1446
|
+
return Err(E::ContractInputInvalid);
|
|
1447
|
+
}
|
|
1448
|
+
match handoff.status.as_str() {
|
|
1449
|
+
"accepted" => {
|
|
1450
|
+
return if handoff.claimant.as_deref() == Some(claimant) {
|
|
1451
|
+
Ok(Decision::Noop)
|
|
1452
|
+
} else {
|
|
1453
|
+
Err(E::HandoffClaimed)
|
|
1454
|
+
};
|
|
1455
|
+
}
|
|
1456
|
+
"open" => return Err(E::InvalidTransition),
|
|
1457
|
+
_ => {}
|
|
1458
|
+
}
|
|
1459
|
+
if handoff.claimant.as_deref() != Some(claimant) {
|
|
1460
|
+
return Err(E::OwnershipConflict);
|
|
1461
|
+
}
|
|
1462
|
+
let lease = owner_checks(
|
|
1463
|
+
task,
|
|
1464
|
+
claimant,
|
|
1465
|
+
op.fence.unwrap_or_default(),
|
|
1466
|
+
s(&op.lease_id),
|
|
1467
|
+
now,
|
|
1468
|
+
)?;
|
|
1469
|
+
if handoff.claimed_fence != Some(task.fence) {
|
|
1470
|
+
return Err(E::HandoffStale);
|
|
1471
|
+
}
|
|
1472
|
+
let mut next = handoff.clone();
|
|
1473
|
+
next.status = "accepted".into();
|
|
1474
|
+
Ok(Decision::Commit {
|
|
1475
|
+
writes: vec![Write {
|
|
1476
|
+
collection: HANDOFF_COLLECTION,
|
|
1477
|
+
id: handoff.handoff_id.clone(),
|
|
1478
|
+
expect: Expect::Version {
|
|
1479
|
+
version: handoff_stored.version,
|
|
1480
|
+
lease_id: None,
|
|
1481
|
+
},
|
|
1482
|
+
value: serde_json::to_value(&next).expect("handoff serializes"),
|
|
1483
|
+
}],
|
|
1484
|
+
guards: vec![task_guard(task_stored, &lease)],
|
|
1485
|
+
})
|
|
1486
|
+
}
|
|
1487
|
+
|
|
1488
|
+
// ---------------------------------------------------------------------------
|
|
1489
|
+
// Canonical output
|
|
1490
|
+
// ---------------------------------------------------------------------------
|
|
1491
|
+
|
|
1492
|
+
fn expect_json(expect: &Expect) -> Value {
|
|
1493
|
+
match expect {
|
|
1494
|
+
Expect::Absent => json!({"absent": true}),
|
|
1495
|
+
Expect::Version {
|
|
1496
|
+
version,
|
|
1497
|
+
lease_id: None,
|
|
1498
|
+
} => json!({"version": version}),
|
|
1499
|
+
Expect::Version {
|
|
1500
|
+
version,
|
|
1501
|
+
lease_id: Some(lease),
|
|
1502
|
+
} => json!({"lease_id": lease, "version": version}),
|
|
1503
|
+
}
|
|
1504
|
+
}
|
|
1505
|
+
|
|
1506
|
+
/// `serde_json::Map` is a `BTreeMap`, so every object is emitted in sorted key
|
|
1507
|
+
/// order. Arrays are ordered by the contract, not by this encoder.
|
|
1508
|
+
pub fn encode(outcome: &Outcome) -> Vec<u8> {
|
|
1509
|
+
let mut document = Map::new();
|
|
1510
|
+
document.insert("contract".into(), json!(AGENT_TRANSITION_CONTRACT_ID));
|
|
1511
|
+
document.insert("version".into(), json!(AGENT_TRANSITION_CONTRACT_VERSION));
|
|
1512
|
+
match outcome {
|
|
1513
|
+
Err(code) => {
|
|
1514
|
+
document.insert("error".into(), json!({"code": code.as_str()}));
|
|
1515
|
+
}
|
|
1516
|
+
Ok(Decision::Noop) => {
|
|
1517
|
+
document.insert("outcome".into(), json!({"kind": "noop"}));
|
|
1518
|
+
}
|
|
1519
|
+
Ok(Decision::Commit { writes, guards }) => {
|
|
1520
|
+
let writes: Vec<Value> = writes
|
|
1521
|
+
.iter()
|
|
1522
|
+
.map(|w| {
|
|
1523
|
+
json!({
|
|
1524
|
+
"collection": w.collection, "expect": expect_json(&w.expect),
|
|
1525
|
+
"id": w.id, "value": w.value,
|
|
1526
|
+
})
|
|
1527
|
+
})
|
|
1528
|
+
.collect();
|
|
1529
|
+
let guards: Vec<Value> = guards
|
|
1530
|
+
.iter()
|
|
1531
|
+
.map(|g| match &g.lease_id {
|
|
1532
|
+
None => json!({"collection": g.collection, "id": g.id, "version": g.version}),
|
|
1533
|
+
Some(lease) => json!({
|
|
1534
|
+
"collection": g.collection, "id": g.id, "lease_id": lease, "version": g.version,
|
|
1535
|
+
}),
|
|
1536
|
+
})
|
|
1537
|
+
.collect();
|
|
1538
|
+
document.insert(
|
|
1539
|
+
"outcome".into(),
|
|
1540
|
+
json!({"guards": guards, "kind": "commit", "writes": writes}),
|
|
1541
|
+
);
|
|
1542
|
+
}
|
|
1543
|
+
}
|
|
1544
|
+
serde_json::to_vec(&Value::Object(document)).expect("output serializes")
|
|
1545
|
+
}
|