certal 0.0.0-stage → 0.1.1
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/.claude-plugin/plugin.json +11 -0
- package/CHANGELOG.md +56 -0
- package/LICENSE +21 -0
- package/README.md +289 -2
- package/SECURITY.md +36 -0
- package/bin/certal.mjs +12 -0
- package/certal.schema.json +156 -0
- package/dist/adapters/approval-channel.d.ts +44 -0
- package/dist/adapters/approval-channel.js +74 -0
- package/dist/adapters/commands.d.ts +77 -0
- package/dist/adapters/commands.js +209 -0
- package/dist/adapters/contracts.d.ts +59 -0
- package/dist/adapters/contracts.js +1 -0
- package/dist/adapters/file-watcher.d.ts +88 -0
- package/dist/adapters/file-watcher.js +297 -0
- package/dist/adapters/in-memory.d.ts +53 -0
- package/dist/adapters/in-memory.js +165 -0
- package/dist/adapters/index.d.ts +8 -0
- package/dist/adapters/index.js +8 -0
- package/dist/adapters/manifest.d.ts +105 -0
- package/dist/adapters/manifest.js +465 -0
- package/dist/adapters/operator-auth.d.ts +53 -0
- package/dist/adapters/operator-auth.js +81 -0
- package/dist/adapters/tool-sdk.d.ts +150 -0
- package/dist/adapters/tool-sdk.js +336 -0
- package/dist/cli/index.d.ts +1 -0
- package/dist/cli/index.js +1 -0
- package/dist/cli/main.d.ts +1 -0
- package/dist/cli/main.js +384 -0
- package/dist/kernel/common.d.ts +46 -0
- package/dist/kernel/common.js +238 -0
- package/dist/kernel/crypto.d.ts +35 -0
- package/dist/kernel/crypto.js +54 -0
- package/dist/kernel/effects.d.ts +4 -0
- package/dist/kernel/effects.js +178 -0
- package/dist/kernel/index.d.ts +9 -0
- package/dist/kernel/index.js +9 -0
- package/dist/kernel/jcs.d.ts +24 -0
- package/dist/kernel/jcs.js +93 -0
- package/dist/kernel/leases.d.ts +11 -0
- package/dist/kernel/leases.js +86 -0
- package/dist/kernel/step.d.ts +10 -0
- package/dist/kernel/step.js +967 -0
- package/dist/kernel/types.d.ts +538 -0
- package/dist/kernel/types.js +1 -0
- package/dist/kernel/undo.d.ts +4 -0
- package/dist/kernel/undo.js +180 -0
- package/dist/kernel/validation.d.ts +13 -0
- package/dist/kernel/validation.js +307 -0
- package/dist/kernel/witness.d.ts +34 -0
- package/dist/kernel/witness.js +279 -0
- package/dist/mcp/host.d.ts +141 -0
- package/dist/mcp/host.js +517 -0
- package/dist/mcp/index.d.ts +2 -0
- package/dist/mcp/index.js +2 -0
- package/dist/mcp/server.d.ts +72 -0
- package/dist/mcp/server.js +549 -0
- package/dist/runtime/dp1.d.ts +48 -0
- package/dist/runtime/dp1.js +229 -0
- package/dist/runtime/engine.d.ts +86 -0
- package/dist/runtime/engine.js +320 -0
- package/dist/runtime/index.d.ts +4 -0
- package/dist/runtime/index.js +4 -0
- package/dist/runtime/outbox.d.ts +69 -0
- package/dist/runtime/outbox.js +238 -0
- package/dist/runtime/store.d.ts +214 -0
- package/dist/runtime/store.js +788 -0
- package/package.json +91 -4
- package/presets/exchange-firewall.json +41 -0
- package/presets/sdk.json +32 -0
- package/presets/solver.json +23 -0
- package/presets/vibeops.json +35 -0
- package/skills/certal/SKILL.md +49 -0
|
@@ -0,0 +1,967 @@
|
|
|
1
|
+
import { DEFAULT_POLICY, EMPTY_SNAPSHOT_HASH, GENESIS_HASH, MAX_RETAINED_BATCHES, MAX_RETAINED_EFFECTS, RECENT_SPENT_APPROVALS_LIMIT, activeLeasesAt, activePinsAt, archiveAttempt, bumpScopeEpoch, commitEntry, computePolicyHash, computeScopeHash, isPauseApprovalReason, leaseMatches, pinMatches, recordConflictStreak, recordFailStreak, replaceAttempt, scopeEpochOf, slotKey, } from './common.js';
|
|
2
|
+
import { hashBinding } from './crypto.js';
|
|
3
|
+
import { handleEffectTransition } from './effects.js';
|
|
4
|
+
import { hashCanonical, sortDeterministically } from './jcs.js';
|
|
5
|
+
import { handleAcquireLease, handleReleaseLease, handleRenewLease } from './leases.js';
|
|
6
|
+
import { handleOriginUndo } from './undo.js';
|
|
7
|
+
import { eventScopeAndClass, validateEnvelopeShape, validatePolicyBounds } from './validation.js';
|
|
8
|
+
import { computeToolAutonomy, computeVerifyId, handleWitnessVerdict, recordClusterOutcome, } from './witness.js';
|
|
9
|
+
export { DEFAULT_POLICY, computePolicyHash, computeScopeHash, scopeEpochOf, slotKey };
|
|
10
|
+
const ACTIVE_EFFECT_STATUSES = new Set([
|
|
11
|
+
'INTENT',
|
|
12
|
+
'IN_FLIGHT',
|
|
13
|
+
'UNKNOWN',
|
|
14
|
+
'RECONCILE_EXHAUSTED',
|
|
15
|
+
'COMP_INTENT',
|
|
16
|
+
'COMP_IN_FLIGHT',
|
|
17
|
+
'COMP_UNKNOWN',
|
|
18
|
+
]);
|
|
19
|
+
export function createInitialState(policyOverrides) {
|
|
20
|
+
const policy = {
|
|
21
|
+
...DEFAULT_POLICY,
|
|
22
|
+
...policyOverrides,
|
|
23
|
+
resourcePoolCapacity: {
|
|
24
|
+
...DEFAULT_POLICY.resourcePoolCapacity,
|
|
25
|
+
...(policyOverrides?.resourcePoolCapacity ?? {}),
|
|
26
|
+
},
|
|
27
|
+
};
|
|
28
|
+
return {
|
|
29
|
+
schemaVersion: 1,
|
|
30
|
+
serverSeq: 0,
|
|
31
|
+
epoch: 0,
|
|
32
|
+
scopeEpochs: {},
|
|
33
|
+
lastNowMs: 0,
|
|
34
|
+
taskStatus: 'ACTIVE',
|
|
35
|
+
haltReason: null,
|
|
36
|
+
pauseReason: null,
|
|
37
|
+
policy,
|
|
38
|
+
policyHash: computePolicyHash(policy),
|
|
39
|
+
slots: {},
|
|
40
|
+
pins: [],
|
|
41
|
+
leases: [],
|
|
42
|
+
nextLeaseEpoch: 1,
|
|
43
|
+
activeAttempts: [],
|
|
44
|
+
recentArchivedAttempts: [],
|
|
45
|
+
batches: [],
|
|
46
|
+
effects: [],
|
|
47
|
+
spentApprovals: [],
|
|
48
|
+
budgets: {
|
|
49
|
+
attempts: 0,
|
|
50
|
+
failStreak: 0,
|
|
51
|
+
conflictStreak: 0,
|
|
52
|
+
cpuMs: 0,
|
|
53
|
+
costMicroUnits: 0,
|
|
54
|
+
},
|
|
55
|
+
undoExpiredScopes: [],
|
|
56
|
+
toolClusterStats: {},
|
|
57
|
+
clusters: [],
|
|
58
|
+
recentOps: [],
|
|
59
|
+
lastEntryHash: GENESIS_HASH,
|
|
60
|
+
metrics: {
|
|
61
|
+
idempotentReplays: 0,
|
|
62
|
+
redactedSecretsTotal: 0,
|
|
63
|
+
rejectedCount: 0,
|
|
64
|
+
orphanVerdicts: 0,
|
|
65
|
+
},
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
export function computeStateHash(state) {
|
|
69
|
+
return hashCanonical('kernel_state', state.schemaVersion, state);
|
|
70
|
+
}
|
|
71
|
+
function computeDiffHash(ops) {
|
|
72
|
+
return hashCanonical('diff', 1, ops);
|
|
73
|
+
}
|
|
74
|
+
function checkOpsBaseConsistency(state, scopeId, ops) {
|
|
75
|
+
const seen = new Set();
|
|
76
|
+
for (const op of ops) {
|
|
77
|
+
const key = slotKey(scopeId, op.classId, op.objectId, op.field);
|
|
78
|
+
if (seen.has(key))
|
|
79
|
+
return false;
|
|
80
|
+
seen.add(key);
|
|
81
|
+
const existing = state.slots[key];
|
|
82
|
+
const currentRev = existing ? existing.rev : 0;
|
|
83
|
+
if (currentRev !== op.expectedBeforeRev) {
|
|
84
|
+
return false;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return true;
|
|
88
|
+
}
|
|
89
|
+
function hasOutOfLeaseClass(attemptClassId, ops) {
|
|
90
|
+
if (attemptClassId === '*')
|
|
91
|
+
return false;
|
|
92
|
+
for (const op of ops) {
|
|
93
|
+
if (op.classId !== attemptClassId)
|
|
94
|
+
return true;
|
|
95
|
+
}
|
|
96
|
+
return false;
|
|
97
|
+
}
|
|
98
|
+
function evaluatePinsForOps(state, scopeId, ops, nowMs) {
|
|
99
|
+
const pins = activePinsAt(state.pins, nowMs);
|
|
100
|
+
let blockedByTemp = false;
|
|
101
|
+
let softPenalty = 0;
|
|
102
|
+
let softEscalate = false;
|
|
103
|
+
const countedSoftPins = new Set();
|
|
104
|
+
for (const op of ops) {
|
|
105
|
+
for (const pin of pins) {
|
|
106
|
+
if (!pinMatches(pin, scopeId, op.classId))
|
|
107
|
+
continue;
|
|
108
|
+
if (pin.kind === 'H') {
|
|
109
|
+
return { blockedBy: 'PIN_HARD_BLOCKED', softPenalty: 0, softEscalate: false };
|
|
110
|
+
}
|
|
111
|
+
if (pin.kind === 'T') {
|
|
112
|
+
blockedByTemp = true;
|
|
113
|
+
}
|
|
114
|
+
if (pin.kind === 'N' && !countedSoftPins.has(pin.pinId)) {
|
|
115
|
+
countedSoftPins.add(pin.pinId);
|
|
116
|
+
softPenalty += pin.costPenaltyMicroUnits ?? 0;
|
|
117
|
+
if (state.policy.escalateSoftPinToC2) {
|
|
118
|
+
softEscalate = true;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
return {
|
|
124
|
+
blockedBy: blockedByTemp ? 'PIN_TEMP_BLOCKED' : null,
|
|
125
|
+
softPenalty,
|
|
126
|
+
softEscalate,
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
function checkApprovalValidity(state, approval, expectedAttemptId, expectedBinding, nowMs, hooks) {
|
|
130
|
+
if (approval.attemptId !== expectedAttemptId)
|
|
131
|
+
return 'APPROVAL_WRONG_ATTEMPT';
|
|
132
|
+
if (hooks?.isApprovalSpent?.(approval.approvalId) || state.spentApprovals.includes(approval.approvalId)) {
|
|
133
|
+
return 'APPROVAL_ALREADY_SPENT';
|
|
134
|
+
}
|
|
135
|
+
if (nowMs > approval.expiresAtMs)
|
|
136
|
+
return 'APPROVAL_EXPIRED';
|
|
137
|
+
if (approval.binding.diffHash !== expectedBinding.diffHash ||
|
|
138
|
+
approval.binding.scopeHash !== expectedBinding.scopeHash ||
|
|
139
|
+
approval.binding.inputSnapshotHash !== expectedBinding.inputSnapshotHash) {
|
|
140
|
+
return 'APPROVAL_BINDING_MISMATCH';
|
|
141
|
+
}
|
|
142
|
+
const verifier = hooks?.signatureVerifier;
|
|
143
|
+
if (state.policy.enforceApprovalSignature || (approval.signature && verifier)) {
|
|
144
|
+
if (!approval.signature || !verifier) {
|
|
145
|
+
return 'INVALID_APPROVAL_SIGNATURE';
|
|
146
|
+
}
|
|
147
|
+
const valid = verifier.verifyApprovalSignature({
|
|
148
|
+
algorithm: approval.signature.algorithm,
|
|
149
|
+
keyId: approval.signature.keyId,
|
|
150
|
+
signature: approval.signature.value,
|
|
151
|
+
payload: {
|
|
152
|
+
approvalId: approval.approvalId,
|
|
153
|
+
humanId: approval.humanId,
|
|
154
|
+
attemptId: approval.attemptId,
|
|
155
|
+
bindingHash: hashBinding(approval.binding.diffHash, approval.binding.scopeHash, approval.binding.inputSnapshotHash),
|
|
156
|
+
expiresAtMs: approval.expiresAtMs,
|
|
157
|
+
singleUse: true,
|
|
158
|
+
},
|
|
159
|
+
});
|
|
160
|
+
if (!valid)
|
|
161
|
+
return 'INVALID_APPROVAL_SIGNATURE';
|
|
162
|
+
}
|
|
163
|
+
return null;
|
|
164
|
+
}
|
|
165
|
+
function appendSpentApproval(spent, approvalId) {
|
|
166
|
+
const next = [...spent, approvalId];
|
|
167
|
+
return next.length > RECENT_SPENT_APPROVALS_LIMIT
|
|
168
|
+
? next.slice(next.length - RECENT_SPENT_APPROVALS_LIMIT)
|
|
169
|
+
: next;
|
|
170
|
+
}
|
|
171
|
+
function pruneRetainedHistory(batches, effects, nowMs, undoWindowTtlMs) {
|
|
172
|
+
const activeBatchIds = new Set();
|
|
173
|
+
for (const eff of effects) {
|
|
174
|
+
if (ACTIVE_EFFECT_STATUSES.has(eff.status)) {
|
|
175
|
+
activeBatchIds.add(eff.batchId);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
let nextBatches = [...batches];
|
|
179
|
+
if (nextBatches.length > MAX_RETAINED_BATCHES) {
|
|
180
|
+
const kept = [];
|
|
181
|
+
let toDrop = nextBatches.length - MAX_RETAINED_BATCHES;
|
|
182
|
+
for (const batch of nextBatches) {
|
|
183
|
+
const expired = nowMs - batch.committedAtMs > undoWindowTtlMs;
|
|
184
|
+
if (toDrop > 0 && !activeBatchIds.has(batch.batchId) && (batch.undone || expired)) {
|
|
185
|
+
toDrop -= 1;
|
|
186
|
+
continue;
|
|
187
|
+
}
|
|
188
|
+
kept.push(batch);
|
|
189
|
+
}
|
|
190
|
+
nextBatches = kept;
|
|
191
|
+
}
|
|
192
|
+
const keptBatchIds = new Set(nextBatches.map((b) => b.batchId));
|
|
193
|
+
let nextEffects = [...effects];
|
|
194
|
+
if (nextEffects.length > MAX_RETAINED_EFFECTS) {
|
|
195
|
+
const keptEff = [];
|
|
196
|
+
let toDrop = nextEffects.length - MAX_RETAINED_EFFECTS;
|
|
197
|
+
for (const eff of nextEffects) {
|
|
198
|
+
if (toDrop > 0 && !ACTIVE_EFFECT_STATUSES.has(eff.status) && !keptBatchIds.has(eff.batchId)) {
|
|
199
|
+
toDrop -= 1;
|
|
200
|
+
continue;
|
|
201
|
+
}
|
|
202
|
+
keptEff.push(eff);
|
|
203
|
+
}
|
|
204
|
+
nextEffects = keptEff;
|
|
205
|
+
}
|
|
206
|
+
return { batches: nextBatches, effects: nextEffects };
|
|
207
|
+
}
|
|
208
|
+
function isPauseApprovalOrAutonomyReason(reason) {
|
|
209
|
+
return isPauseApprovalReason(reason) || reason === 'AUTONOMY_APPROVAL_REQUIRED';
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* Pure, deterministic transition function of the Certal kernel.
|
|
213
|
+
* No I/O, no Date.now(), no Math.random(), no regular expressions. It never mutates the input state.
|
|
214
|
+
*/
|
|
215
|
+
export function step(state, envelope, hooks) {
|
|
216
|
+
const shapeError = validateEnvelopeShape(envelope);
|
|
217
|
+
if (shapeError !== null) {
|
|
218
|
+
return {
|
|
219
|
+
state,
|
|
220
|
+
decision: { code: 'REJECT', reason: shapeError },
|
|
221
|
+
intents: [],
|
|
222
|
+
logEntry: null,
|
|
223
|
+
idempotentReplay: false,
|
|
224
|
+
schemaRejected: true,
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
const redactedCount = envelope.dp1Meta?.redactedCount ?? 0;
|
|
228
|
+
const stateAfterRedact = redactedCount > 0
|
|
229
|
+
? {
|
|
230
|
+
...state,
|
|
231
|
+
metrics: {
|
|
232
|
+
...state.metrics,
|
|
233
|
+
redactedSecretsTotal: state.metrics.redactedSecretsTotal + redactedCount,
|
|
234
|
+
},
|
|
235
|
+
}
|
|
236
|
+
: state;
|
|
237
|
+
const ev = envelope.event;
|
|
238
|
+
const payloadHash = hashCanonical('event_payload', 1, ev);
|
|
239
|
+
const { scopeId, classId } = eventScopeAndClass(state, ev);
|
|
240
|
+
const existingOp = hooks?.lookupOpId?.(envelope.opId) ??
|
|
241
|
+
state.recentOps.find((rec) => rec.opId === envelope.opId) ??
|
|
242
|
+
null;
|
|
243
|
+
if (existingOp) {
|
|
244
|
+
if (existingOp.payloadHash === payloadHash) {
|
|
245
|
+
const replayedState = {
|
|
246
|
+
...stateAfterRedact,
|
|
247
|
+
metrics: {
|
|
248
|
+
...stateAfterRedact.metrics,
|
|
249
|
+
idempotentReplays: stateAfterRedact.metrics.idempotentReplays + 1,
|
|
250
|
+
},
|
|
251
|
+
};
|
|
252
|
+
return {
|
|
253
|
+
state: replayedState,
|
|
254
|
+
decision: existingOp.decision,
|
|
255
|
+
intents: [],
|
|
256
|
+
logEntry: null,
|
|
257
|
+
idempotentReplay: true,
|
|
258
|
+
schemaRejected: false,
|
|
259
|
+
...(existingOp.undoReport !== undefined ? { undoReport: existingOp.undoReport } : {}),
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
const { nextState, decision } = recordFailStreak(stateAfterRedact, 'OP_ID_CONFLICT');
|
|
263
|
+
return commitEntry(state, nextState, envelope, payloadHash, false, decision, [], scopeId, classId, null, EMPTY_SNAPSHOT_HASH, undefined, true);
|
|
264
|
+
}
|
|
265
|
+
if (envelope.nowMs < state.lastNowMs) {
|
|
266
|
+
return commitEntry(state, stateAfterRedact, envelope, payloadHash, false, { code: 'REJECT', reason: 'CLOCK_REGRESSION' }, [], scopeId, classId, null, EMPTY_SNAPSHOT_HASH);
|
|
267
|
+
}
|
|
268
|
+
const origin = envelope.auth.origin;
|
|
269
|
+
const isHuman = origin.kind === 'Human';
|
|
270
|
+
const isSystem = origin.kind === 'System';
|
|
271
|
+
if (state.taskStatus === 'HALTED') {
|
|
272
|
+
const allowedWhenHalted = ev.kind === 'HumanReset' ||
|
|
273
|
+
ev.kind === 'OriginUndo' ||
|
|
274
|
+
ev.kind === 'ExpireUndoWindow' ||
|
|
275
|
+
ev.kind === 'EffectTransition' ||
|
|
276
|
+
(ev.kind === 'PolicyUpdated' && isHuman);
|
|
277
|
+
if (!allowedWhenHalted) {
|
|
278
|
+
return commitEntry(state, stateAfterRedact, envelope, payloadHash, false, { code: 'HALT', reason: state.haltReason ?? 'TASK_HALTED' }, [], scopeId, classId, null, EMPTY_SNAPSHOT_HASH);
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
if (state.taskStatus === 'PAUSED') {
|
|
282
|
+
const allowedWhenPaused = ev.kind === 'HumanResume' ||
|
|
283
|
+
ev.kind === 'HumanHalt' ||
|
|
284
|
+
ev.kind === 'HumanReset' ||
|
|
285
|
+
ev.kind === 'HumanEdit' ||
|
|
286
|
+
((ev.kind === 'SetPin' || ev.kind === 'RemovePin') && isHuman) ||
|
|
287
|
+
ev.kind === 'GrantApproval' ||
|
|
288
|
+
ev.kind === 'CancelAttempt' ||
|
|
289
|
+
ev.kind === 'OriginUndo' ||
|
|
290
|
+
ev.kind === 'ExpireUndoWindow' ||
|
|
291
|
+
ev.kind === 'EffectTransition' ||
|
|
292
|
+
(ev.kind === 'PolicyUpdated' && isHuman) ||
|
|
293
|
+
(ev.kind === 'FinalizeBatch' && isPauseApprovalOrAutonomyReason(state.pauseReason));
|
|
294
|
+
if (!allowedWhenPaused) {
|
|
295
|
+
return commitEntry(state, stateAfterRedact, envelope, payloadHash, false, { code: 'PAUSE', reason: state.pauseReason ?? 'TASK_PAUSED' }, [], scopeId, classId, null, EMPTY_SNAPSHOT_HASH);
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
switch (ev.kind) {
|
|
299
|
+
case 'PolicyUpdated': {
|
|
300
|
+
if (!isHuman && !isSystem) {
|
|
301
|
+
const { nextState, decision } = recordFailStreak(stateAfterRedact, 'FORBIDDEN_ORIGIN');
|
|
302
|
+
return commitEntry(state, nextState, envelope, payloadHash, false, decision, [], scopeId, classId, null, EMPTY_SNAPSHOT_HASH);
|
|
303
|
+
}
|
|
304
|
+
const boundsErr = validatePolicyBounds(ev.policy);
|
|
305
|
+
if (boundsErr !== null) {
|
|
306
|
+
return commitEntry(state, stateAfterRedact, envelope, payloadHash, false, { code: 'REJECT', reason: boundsErr }, [], scopeId, classId, null, EMPTY_SNAPSHOT_HASH);
|
|
307
|
+
}
|
|
308
|
+
const nextPolicy = {
|
|
309
|
+
...state.policy,
|
|
310
|
+
...ev.policy,
|
|
311
|
+
resourcePoolCapacity: {
|
|
312
|
+
...state.policy.resourcePoolCapacity,
|
|
313
|
+
...(ev.policy.resourcePoolCapacity ?? {}),
|
|
314
|
+
},
|
|
315
|
+
};
|
|
316
|
+
const nextState = {
|
|
317
|
+
...stateAfterRedact,
|
|
318
|
+
policy: nextPolicy,
|
|
319
|
+
policyHash: computePolicyHash(nextPolicy),
|
|
320
|
+
};
|
|
321
|
+
return commitEntry(state, nextState, envelope, payloadHash, true, { code: 'ALLOW', reason: 'POLICY_UPDATED' }, [], scopeId, classId, null, EMPTY_SNAPSHOT_HASH);
|
|
322
|
+
}
|
|
323
|
+
case 'HumanEdit': {
|
|
324
|
+
if (!isHuman) {
|
|
325
|
+
const { nextState, decision } = recordFailStreak(stateAfterRedact, 'FORBIDDEN_ORIGIN');
|
|
326
|
+
return commitEntry(state, nextState, envelope, payloadHash, false, decision, [], scopeId, classId, null, EMPTY_SNAPSHOT_HASH);
|
|
327
|
+
}
|
|
328
|
+
const nextEpoch = state.epoch + 1;
|
|
329
|
+
const key = slotKey(ev.scopeId, ev.classId, ev.objectId, ev.field);
|
|
330
|
+
const prevSlot = state.slots[key];
|
|
331
|
+
const nextSlot = {
|
|
332
|
+
objectId: ev.objectId,
|
|
333
|
+
classId: ev.classId,
|
|
334
|
+
field: ev.field,
|
|
335
|
+
rev: (prevSlot?.rev ?? 0) + 1,
|
|
336
|
+
value: ev.value,
|
|
337
|
+
owner: origin,
|
|
338
|
+
batchId: null,
|
|
339
|
+
...(ev.parentObjectId !== undefined
|
|
340
|
+
? { parentObjectId: ev.parentObjectId }
|
|
341
|
+
: prevSlot?.parentObjectId !== undefined
|
|
342
|
+
? { parentObjectId: prevSlot.parentObjectId }
|
|
343
|
+
: {}),
|
|
344
|
+
};
|
|
345
|
+
const nextSlots = { ...state.slots, [key]: nextSlot };
|
|
346
|
+
const activeLeases = activeLeasesAt(state.leases, envelope.nowMs).filter((l) => !leaseMatches(l, ev.scopeId, ev.classId));
|
|
347
|
+
const autoPinId = `auto-t:${ev.scopeId}:${ev.classId}:${nextEpoch}`;
|
|
348
|
+
const existingPinsWithoutOldAuto = state.pins.filter((p) => !(p.kind === 'T' && p.pinId.startsWith(`auto-t:${ev.scopeId}:${ev.classId}:`)));
|
|
349
|
+
const autoPin = {
|
|
350
|
+
pinId: autoPinId,
|
|
351
|
+
kind: 'T',
|
|
352
|
+
scopeId: ev.scopeId,
|
|
353
|
+
classId: ev.classId,
|
|
354
|
+
ruleId: 'human_touch',
|
|
355
|
+
ownerId: origin.actorId,
|
|
356
|
+
...(ev.autoPinTtlMs !== undefined ? { expiresAtMs: envelope.nowMs + ev.autoPinTtlMs } : {}),
|
|
357
|
+
};
|
|
358
|
+
const nextState = {
|
|
359
|
+
...stateAfterRedact,
|
|
360
|
+
epoch: nextEpoch,
|
|
361
|
+
scopeEpochs: bumpScopeEpoch(state.scopeEpochs, ev.scopeId),
|
|
362
|
+
slots: nextSlots,
|
|
363
|
+
leases: activeLeases,
|
|
364
|
+
pins: sortDeterministically([...existingPinsWithoutOldAuto, autoPin], (p) => p.pinId),
|
|
365
|
+
};
|
|
366
|
+
return commitEntry(state, nextState, envelope, payloadHash, true, { code: 'ALLOW', reason: 'HUMAN_EDIT_APPLIED' }, [], ev.scopeId, ev.classId, null, EMPTY_SNAPSHOT_HASH);
|
|
367
|
+
}
|
|
368
|
+
case 'SetPin': {
|
|
369
|
+
// A non-human origin may set only a soft pin that it owns, and may not replace a pin
|
|
370
|
+
// that is hard, timed or owned by someone else.
|
|
371
|
+
const replacesForeignPin = state.pins.some((p) => p.pinId === ev.pin.pinId && (p.kind !== 'N' || p.ownerId !== origin.actorId));
|
|
372
|
+
if (!isHuman && (ev.pin.kind !== 'N' || ev.pin.ownerId !== origin.actorId || replacesForeignPin)) {
|
|
373
|
+
const { nextState, decision } = recordFailStreak(stateAfterRedact, 'FORBIDDEN_PIN_OP');
|
|
374
|
+
return commitEntry(state, nextState, envelope, payloadHash, false, decision, [], scopeId, classId, null, EMPTY_SNAPSHOT_HASH);
|
|
375
|
+
}
|
|
376
|
+
const nextEpoch = isHuman ? state.epoch + 1 : state.epoch;
|
|
377
|
+
const filtered = state.pins.filter((p) => p.pinId !== ev.pin.pinId);
|
|
378
|
+
const nextPins = sortDeterministically([...filtered, ev.pin], (p) => p.pinId);
|
|
379
|
+
const nextLeases = isHuman
|
|
380
|
+
? activeLeasesAt(state.leases, envelope.nowMs).filter((l) => !leaseMatches(l, ev.pin.scopeId, ev.pin.classId))
|
|
381
|
+
: state.leases;
|
|
382
|
+
const nextState = {
|
|
383
|
+
...stateAfterRedact,
|
|
384
|
+
epoch: nextEpoch,
|
|
385
|
+
scopeEpochs: isHuman ? bumpScopeEpoch(state.scopeEpochs, ev.pin.scopeId) : state.scopeEpochs,
|
|
386
|
+
pins: nextPins,
|
|
387
|
+
leases: nextLeases,
|
|
388
|
+
};
|
|
389
|
+
return commitEntry(state, nextState, envelope, payloadHash, true, { code: 'ALLOW', reason: 'PIN_SET' }, [], ev.pin.scopeId, ev.pin.classId, null, EMPTY_SNAPSHOT_HASH);
|
|
390
|
+
}
|
|
391
|
+
case 'RemovePin': {
|
|
392
|
+
const target = state.pins.find((p) => p.pinId === ev.pinId);
|
|
393
|
+
if (!target) {
|
|
394
|
+
return commitEntry(state, stateAfterRedact, envelope, payloadHash, false, { code: 'REJECT', reason: 'PIN_NOT_FOUND' }, [], ev.scopeId, '*', null, EMPTY_SNAPSHOT_HASH);
|
|
395
|
+
}
|
|
396
|
+
const removesForeignPin = state.pins.some((p) => p.pinId === ev.pinId && (p.kind !== 'N' || p.ownerId !== origin.actorId));
|
|
397
|
+
if (!isHuman && removesForeignPin) {
|
|
398
|
+
const { nextState, decision } = recordFailStreak(stateAfterRedact, 'FORBIDDEN_PIN_OP');
|
|
399
|
+
return commitEntry(state, nextState, envelope, payloadHash, false, decision, [], ev.scopeId, target.classId, null, EMPTY_SNAPSHOT_HASH);
|
|
400
|
+
}
|
|
401
|
+
const nextState = {
|
|
402
|
+
...stateAfterRedact,
|
|
403
|
+
epoch: isHuman ? state.epoch + 1 : state.epoch,
|
|
404
|
+
scopeEpochs: isHuman ? bumpScopeEpoch(state.scopeEpochs, target.scopeId) : state.scopeEpochs,
|
|
405
|
+
pins: state.pins.filter((p) => p.pinId !== ev.pinId),
|
|
406
|
+
};
|
|
407
|
+
return commitEntry(state, nextState, envelope, payloadHash, true, { code: 'ALLOW', reason: 'PIN_REMOVED' }, [], ev.scopeId, target.classId, null, EMPTY_SNAPSHOT_HASH);
|
|
408
|
+
}
|
|
409
|
+
case 'HumanHalt': {
|
|
410
|
+
if (!isHuman) {
|
|
411
|
+
const { nextState, decision } = recordFailStreak(stateAfterRedact, 'FORBIDDEN_ORIGIN');
|
|
412
|
+
return commitEntry(state, nextState, envelope, payloadHash, false, decision, [], ev.scopeId, '*', null, EMPTY_SNAPSHOT_HASH);
|
|
413
|
+
}
|
|
414
|
+
const nextState = {
|
|
415
|
+
...stateAfterRedact,
|
|
416
|
+
epoch: state.epoch + 1,
|
|
417
|
+
scopeEpochs: bumpScopeEpoch(state.scopeEpochs, '*'),
|
|
418
|
+
taskStatus: 'HALTED',
|
|
419
|
+
haltReason: ev.reason,
|
|
420
|
+
leases: [],
|
|
421
|
+
};
|
|
422
|
+
return commitEntry(state, nextState, envelope, payloadHash, true, { code: 'HALT', reason: ev.reason }, [], ev.scopeId, '*', null, EMPTY_SNAPSHOT_HASH);
|
|
423
|
+
}
|
|
424
|
+
case 'HumanResume': {
|
|
425
|
+
if (!isHuman) {
|
|
426
|
+
const { nextState, decision } = recordFailStreak(stateAfterRedact, 'FORBIDDEN_ORIGIN');
|
|
427
|
+
return commitEntry(state, nextState, envelope, payloadHash, false, decision, [], ev.scopeId, '*', null, EMPTY_SNAPSHOT_HASH);
|
|
428
|
+
}
|
|
429
|
+
if (state.taskStatus !== 'PAUSED') {
|
|
430
|
+
return commitEntry(state, stateAfterRedact, envelope, payloadHash, false, { code: 'REJECT', reason: 'NOT_PAUSED' }, [], ev.scopeId, '*', null, EMPTY_SNAPSHOT_HASH);
|
|
431
|
+
}
|
|
432
|
+
const nextPolicy = {
|
|
433
|
+
...state.policy,
|
|
434
|
+
maxAttempts: state.policy.maxAttempts + (ev.extraAttempts ?? 0),
|
|
435
|
+
maxCpuMs: state.policy.maxCpuMs + (ev.extraCpuMs ?? 0),
|
|
436
|
+
maxCostMicroUnits: state.policy.maxCostMicroUnits + (ev.extraCostMicroUnits ?? 0),
|
|
437
|
+
};
|
|
438
|
+
const nextState = {
|
|
439
|
+
...stateAfterRedact,
|
|
440
|
+
epoch: state.epoch + 1,
|
|
441
|
+
scopeEpochs: bumpScopeEpoch(state.scopeEpochs, '*'),
|
|
442
|
+
taskStatus: 'ACTIVE',
|
|
443
|
+
pauseReason: null,
|
|
444
|
+
policy: nextPolicy,
|
|
445
|
+
policyHash: computePolicyHash(nextPolicy),
|
|
446
|
+
budgets: { ...state.budgets, conflictStreak: 0 },
|
|
447
|
+
};
|
|
448
|
+
return commitEntry(state, nextState, envelope, payloadHash, true, { code: 'ALLOW', reason: 'RESUMED' }, [], ev.scopeId, '*', null, EMPTY_SNAPSHOT_HASH);
|
|
449
|
+
}
|
|
450
|
+
case 'HumanReset': {
|
|
451
|
+
if (!isHuman) {
|
|
452
|
+
const { nextState, decision } = recordFailStreak(stateAfterRedact, 'FORBIDDEN_ORIGIN');
|
|
453
|
+
return commitEntry(state, nextState, envelope, payloadHash, false, decision, [], ev.scopeId, '*', null, EMPTY_SNAPSHOT_HASH);
|
|
454
|
+
}
|
|
455
|
+
const nextState = {
|
|
456
|
+
...stateAfterRedact,
|
|
457
|
+
epoch: state.epoch + 1,
|
|
458
|
+
scopeEpochs: bumpScopeEpoch(state.scopeEpochs, '*'),
|
|
459
|
+
taskStatus: 'ACTIVE',
|
|
460
|
+
haltReason: null,
|
|
461
|
+
pauseReason: null,
|
|
462
|
+
leases: [],
|
|
463
|
+
budgets: { ...state.budgets, failStreak: 0, conflictStreak: 0 },
|
|
464
|
+
};
|
|
465
|
+
return commitEntry(state, nextState, envelope, payloadHash, true, { code: 'ALLOW', reason: 'RESET_BY_HUMAN' }, [], ev.scopeId, '*', null, EMPTY_SNAPSHOT_HASH);
|
|
466
|
+
}
|
|
467
|
+
case 'AcquireLease':
|
|
468
|
+
return handleAcquireLease(state, stateAfterRedact, envelope, payloadHash, ev);
|
|
469
|
+
case 'RenewLease':
|
|
470
|
+
return handleRenewLease(state, stateAfterRedact, envelope, payloadHash, ev, scopeId, classId);
|
|
471
|
+
case 'ReleaseLease':
|
|
472
|
+
return handleReleaseLease(state, stateAfterRedact, envelope, payloadHash, ev, scopeId, classId);
|
|
473
|
+
case 'OpenAttempt': {
|
|
474
|
+
if (origin.kind !== 'Agent' ||
|
|
475
|
+
origin.actorId !== ev.executorId ||
|
|
476
|
+
origin.attemptId !== ev.attemptId ||
|
|
477
|
+
origin.taskId !== ev.taskId) {
|
|
478
|
+
const { nextState, decision } = recordFailStreak(stateAfterRedact, 'FORBIDDEN_ORIGIN');
|
|
479
|
+
return commitEntry(state, nextState, envelope, payloadHash, false, decision, [], ev.scopeId, ev.classId, null, EMPTY_SNAPSHOT_HASH);
|
|
480
|
+
}
|
|
481
|
+
if (state.activeAttempts.some((a) => a.attemptId === ev.attemptId)) {
|
|
482
|
+
const { nextState, decision } = recordFailStreak(stateAfterRedact, 'DUPLICATE_ATTEMPT_ID');
|
|
483
|
+
return commitEntry(state, nextState, envelope, payloadHash, false, decision, [], ev.scopeId, ev.classId, null, EMPTY_SNAPSHOT_HASH);
|
|
484
|
+
}
|
|
485
|
+
const currentScopeHash = computeScopeHash(state, ev.scopeId, ev.classId, envelope.nowMs);
|
|
486
|
+
if (ev.expectedScopeHash !== currentScopeHash) {
|
|
487
|
+
const { nextState, decision } = recordConflictStreak(stateAfterRedact, 'STALE_SCOPE');
|
|
488
|
+
return commitEntry(state, nextState, envelope, payloadHash, false, decision, [], ev.scopeId, ev.classId, null, EMPTY_SNAPSHOT_HASH);
|
|
489
|
+
}
|
|
490
|
+
const nextAttemptsCount = state.budgets.attempts + 1;
|
|
491
|
+
if (nextAttemptsCount > state.policy.maxAttempts) {
|
|
492
|
+
const nextState = {
|
|
493
|
+
...stateAfterRedact,
|
|
494
|
+
taskStatus: 'PAUSED',
|
|
495
|
+
pauseReason: 'BUDGET_EXHAUSTED',
|
|
496
|
+
};
|
|
497
|
+
return commitEntry(state, nextState, envelope, payloadHash, false, { code: 'PAUSE', reason: 'BUDGET_EXHAUSTED' }, [], ev.scopeId, ev.classId, null, EMPTY_SNAPSHOT_HASH);
|
|
498
|
+
}
|
|
499
|
+
const attempt = {
|
|
500
|
+
attemptId: ev.attemptId,
|
|
501
|
+
taskId: ev.taskId,
|
|
502
|
+
toolId: ev.toolId,
|
|
503
|
+
clusterId: ev.clusterId,
|
|
504
|
+
executorId: ev.executorId,
|
|
505
|
+
scopeId: ev.scopeId,
|
|
506
|
+
classId: ev.classId,
|
|
507
|
+
status: 'OPEN',
|
|
508
|
+
openedAtEpoch: scopeEpochOf(state, ev.scopeId),
|
|
509
|
+
openedScopeHash: currentScopeHash,
|
|
510
|
+
diffHash: null,
|
|
511
|
+
binding: null,
|
|
512
|
+
ops: [],
|
|
513
|
+
snapshot: null,
|
|
514
|
+
needsApproval: false,
|
|
515
|
+
approvalReason: null,
|
|
516
|
+
approval: null,
|
|
517
|
+
pendingVerify: null,
|
|
518
|
+
stages: [],
|
|
519
|
+
optimizationEnabled: false,
|
|
520
|
+
lastOptimization: null,
|
|
521
|
+
isRiskReducing: ev.isRiskReducing ?? false,
|
|
522
|
+
};
|
|
523
|
+
const nextState = {
|
|
524
|
+
...stateAfterRedact,
|
|
525
|
+
activeAttempts: [...state.activeAttempts, attempt],
|
|
526
|
+
budgets: { ...state.budgets, attempts: nextAttemptsCount },
|
|
527
|
+
};
|
|
528
|
+
return commitEntry(state, nextState, envelope, payloadHash, true, { code: 'ALLOW', reason: 'ATTEMPT_OPENED' }, [], ev.scopeId, ev.classId, null, EMPTY_SNAPSHOT_HASH);
|
|
529
|
+
}
|
|
530
|
+
case 'SubmitBatch': {
|
|
531
|
+
const attempt = state.activeAttempts.find((a) => a.attemptId === ev.attemptId);
|
|
532
|
+
if (!attempt || attempt.status !== 'OPEN') {
|
|
533
|
+
const { nextState, decision } = recordFailStreak(stateAfterRedact, 'ATTEMPT_NOT_OPEN');
|
|
534
|
+
return commitEntry(state, nextState, envelope, payloadHash, false, decision, [], scopeId, classId, null, ev.snapshot.hash);
|
|
535
|
+
}
|
|
536
|
+
if (origin.kind !== 'Agent' ||
|
|
537
|
+
origin.actorId !== ev.executorId ||
|
|
538
|
+
origin.attemptId !== ev.attemptId) {
|
|
539
|
+
const { nextState, decision } = recordFailStreak(stateAfterRedact, 'FORBIDDEN_ORIGIN');
|
|
540
|
+
return commitEntry(state, nextState, envelope, payloadHash, false, decision, [], attempt.scopeId, attempt.classId, null, ev.snapshot.hash);
|
|
541
|
+
}
|
|
542
|
+
if (ev.executorId !== attempt.executorId) {
|
|
543
|
+
const archived = archiveAttempt(state, { ...attempt, status: 'HALTED' });
|
|
544
|
+
const nextState = {
|
|
545
|
+
...stateAfterRedact,
|
|
546
|
+
taskStatus: 'HALTED',
|
|
547
|
+
haltReason: 'C6_ACTOR_DRIFT',
|
|
548
|
+
...recordClusterOutcome(state, attempt.toolId, attempt.clusterId, 'VIOLATION', state.serverSeq + 1, hooks),
|
|
549
|
+
...archived,
|
|
550
|
+
};
|
|
551
|
+
return commitEntry(state, nextState, envelope, payloadHash, false, { code: 'HALT', reason: 'C6_ACTOR_DRIFT' }, [], attempt.scopeId, attempt.classId, null, ev.snapshot.hash);
|
|
552
|
+
}
|
|
553
|
+
if (hasOutOfLeaseClass(attempt.classId, ev.ops)) {
|
|
554
|
+
const { nextState, decision } = recordFailStreak({
|
|
555
|
+
...stateAfterRedact,
|
|
556
|
+
...recordClusterOutcome(state, attempt.toolId, attempt.clusterId, 'VIOLATION', state.serverSeq + 1, hooks),
|
|
557
|
+
}, 'OP_CLASS_OUT_OF_LEASE');
|
|
558
|
+
return commitEntry(state, nextState, envelope, payloadHash, false, decision, [], attempt.scopeId, attempt.classId, null, ev.snapshot.hash);
|
|
559
|
+
}
|
|
560
|
+
const currentLeases = activeLeasesAt(state.leases, envelope.nowMs);
|
|
561
|
+
const lease = currentLeases.find((l) => l.leaseId === ev.leaseId &&
|
|
562
|
+
l.leaseEpoch === ev.leaseEpoch &&
|
|
563
|
+
l.attemptId === attempt.attemptId &&
|
|
564
|
+
l.ownerId === attempt.executorId &&
|
|
565
|
+
leaseMatches(l, attempt.scopeId, attempt.classId));
|
|
566
|
+
if (!lease) {
|
|
567
|
+
const { nextState, decision } = recordConflictStreak({ ...stateAfterRedact, leases: currentLeases }, 'LEASE_CONFLICT');
|
|
568
|
+
return commitEntry(state, nextState, envelope, payloadHash, false, decision, [], attempt.scopeId, attempt.classId, null, ev.snapshot.hash);
|
|
569
|
+
}
|
|
570
|
+
if (attempt.openedAtEpoch !== scopeEpochOf(state, attempt.scopeId)) {
|
|
571
|
+
const { nextState, decision } = recordConflictStreak(stateAfterRedact, 'STALE_EPOCH');
|
|
572
|
+
return commitEntry(state, nextState, envelope, payloadHash, false, decision, [], attempt.scopeId, attempt.classId, null, ev.snapshot.hash);
|
|
573
|
+
}
|
|
574
|
+
const currentScopeHash = computeScopeHash(state, attempt.scopeId, attempt.classId, envelope.nowMs);
|
|
575
|
+
if (ev.expectedScopeHash !== currentScopeHash || attempt.openedScopeHash !== currentScopeHash) {
|
|
576
|
+
const { nextState, decision } = recordConflictStreak(stateAfterRedact, 'STALE_SCOPE');
|
|
577
|
+
return commitEntry(state, nextState, envelope, payloadHash, false, decision, [], attempt.scopeId, attempt.classId, null, ev.snapshot.hash);
|
|
578
|
+
}
|
|
579
|
+
if (ev.snapshot.confidence === 'unknown' && !attempt.isRiskReducing) {
|
|
580
|
+
const { nextState, decision } = recordFailStreak({
|
|
581
|
+
...stateAfterRedact,
|
|
582
|
+
...recordClusterOutcome(state, attempt.toolId, attempt.clusterId, 'VIOLATION', state.serverSeq + 1, hooks),
|
|
583
|
+
}, 'DENY_UNKNOWN_INPUT');
|
|
584
|
+
return commitEntry(state, nextState, envelope, payloadHash, false, decision, [], attempt.scopeId, attempt.classId, null, ev.snapshot.hash);
|
|
585
|
+
}
|
|
586
|
+
if (ev.snapshot.confidence === 'partial' && state.policy.denyPartial && !attempt.isRiskReducing) {
|
|
587
|
+
const { nextState, decision } = recordFailStreak(stateAfterRedact, 'DENY_PARTIAL_INPUT');
|
|
588
|
+
return commitEntry(state, nextState, envelope, payloadHash, false, decision, [], attempt.scopeId, attempt.classId, null, ev.snapshot.hash);
|
|
589
|
+
}
|
|
590
|
+
const pinEval = evaluatePinsForOps(state, attempt.scopeId, ev.ops, envelope.nowMs);
|
|
591
|
+
if (pinEval.blockedBy === 'PIN_HARD_BLOCKED') {
|
|
592
|
+
const { nextState, decision } = recordFailStreak({
|
|
593
|
+
...stateAfterRedact,
|
|
594
|
+
...recordClusterOutcome(state, attempt.toolId, attempt.clusterId, 'VIOLATION', state.serverSeq + 1, hooks),
|
|
595
|
+
}, 'PIN_HARD_BLOCKED');
|
|
596
|
+
return commitEntry(state, nextState, envelope, payloadHash, false, decision, [], attempt.scopeId, attempt.classId, null, ev.snapshot.hash);
|
|
597
|
+
}
|
|
598
|
+
if (pinEval.blockedBy === 'PIN_TEMP_BLOCKED') {
|
|
599
|
+
const { nextState, decision } = recordConflictStreak(stateAfterRedact, 'PIN_TEMP_BLOCKED');
|
|
600
|
+
return commitEntry(state, nextState, envelope, payloadHash, false, decision, [], attempt.scopeId, attempt.classId, null, ev.snapshot.hash);
|
|
601
|
+
}
|
|
602
|
+
// Autonomy ladder: SHADOW blocks external effects and requires approval, APPROVAL requires approval
|
|
603
|
+
const autonomy = state.policy.enforceAutonomyLadder
|
|
604
|
+
? computeToolAutonomy(state, attempt.toolId)
|
|
605
|
+
: null;
|
|
606
|
+
if (autonomy !== null &&
|
|
607
|
+
autonomy.tier === 'SHADOW' &&
|
|
608
|
+
ev.ops.some((o) => o.externalEffect !== undefined)) {
|
|
609
|
+
const { nextState, decision } = recordFailStreak(stateAfterRedact, 'AUTONOMY_SHADOW_EXTERNAL_BLOCKED');
|
|
610
|
+
return commitEntry(state, nextState, envelope, payloadHash, false, decision, [], attempt.scopeId, attempt.classId, null, ev.snapshot.hash);
|
|
611
|
+
}
|
|
612
|
+
if (!checkOpsBaseConsistency(state, attempt.scopeId, ev.ops)) {
|
|
613
|
+
const { nextState, decision } = recordConflictStreak(stateAfterRedact, 'STALE_BASE');
|
|
614
|
+
return commitEntry(state, nextState, envelope, payloadHash, false, decision, [], attempt.scopeId, attempt.classId, null, ev.snapshot.hash);
|
|
615
|
+
}
|
|
616
|
+
const estCost = (ev.costEstimateMicroUnits ?? 0) + pinEval.softPenalty;
|
|
617
|
+
if (state.budgets.costMicroUnits + estCost > state.policy.maxCostMicroUnits ||
|
|
618
|
+
state.budgets.cpuMs >= state.policy.maxCpuMs) {
|
|
619
|
+
const nextState = {
|
|
620
|
+
...stateAfterRedact,
|
|
621
|
+
taskStatus: 'PAUSED',
|
|
622
|
+
pauseReason: 'BUDGET_EXHAUSTED',
|
|
623
|
+
};
|
|
624
|
+
return commitEntry(state, nextState, envelope, payloadHash, false, { code: 'PAUSE', reason: 'BUDGET_EXHAUSTED' }, [], attempt.scopeId, attempt.classId, null, ev.snapshot.hash);
|
|
625
|
+
}
|
|
626
|
+
const diffHash = computeDiffHash(ev.ops);
|
|
627
|
+
const binding = {
|
|
628
|
+
diffHash,
|
|
629
|
+
scopeHash: currentScopeHash,
|
|
630
|
+
inputSnapshotHash: ev.snapshot.hash,
|
|
631
|
+
};
|
|
632
|
+
const hasIrreversible = ev.ops.some((o) => o.reversibility === 'IRREVERSIBLE');
|
|
633
|
+
const autonomyNeedsApproval = autonomy !== null && (autonomy.tier === 'SHADOW' || autonomy.tier === 'APPROVAL');
|
|
634
|
+
const needsApproval = hasIrreversible ||
|
|
635
|
+
(ev.snapshot.confidence === 'partial' && state.policy.escalatePartialToC2) ||
|
|
636
|
+
pinEval.softEscalate ||
|
|
637
|
+
autonomyNeedsApproval;
|
|
638
|
+
const approvalReason = hasIrreversible
|
|
639
|
+
? 'IRREVERSIBLE_APPROVAL'
|
|
640
|
+
: ev.snapshot.confidence === 'partial'
|
|
641
|
+
? 'PARTIAL_INPUT_APPROVAL'
|
|
642
|
+
: pinEval.softEscalate
|
|
643
|
+
? 'SOFT_PIN_APPROVAL'
|
|
644
|
+
: autonomyNeedsApproval
|
|
645
|
+
? 'AUTONOMY_APPROVAL_REQUIRED'
|
|
646
|
+
: null;
|
|
647
|
+
const stages = state.policy.requiredWitnessStages;
|
|
648
|
+
const firstStage = stages[0] ?? 'L0';
|
|
649
|
+
const verifyId = computeVerifyId(attempt.attemptId, scopeEpochOf(state, attempt.scopeId), currentScopeHash, firstStage);
|
|
650
|
+
const budgetCpuMs = Math.min(ev.budgetCpuMs ?? state.policy.maxCpuMs, state.policy.maxCpuMs - state.budgets.cpuMs);
|
|
651
|
+
const requireNearMiss = ev.requireNearMiss ?? firstStage === 'L2';
|
|
652
|
+
const updatedAttempt = {
|
|
653
|
+
...attempt,
|
|
654
|
+
status: 'VERIFYING',
|
|
655
|
+
diffHash,
|
|
656
|
+
binding,
|
|
657
|
+
ops: ev.ops,
|
|
658
|
+
snapshot: ev.snapshot,
|
|
659
|
+
needsApproval,
|
|
660
|
+
approvalReason,
|
|
661
|
+
optimizationEnabled: ev.optimizationEnabled ?? false,
|
|
662
|
+
pendingVerify: {
|
|
663
|
+
verifyId,
|
|
664
|
+
stage: firstStage,
|
|
665
|
+
attemptId: attempt.attemptId,
|
|
666
|
+
epoch: scopeEpochOf(state, attempt.scopeId),
|
|
667
|
+
scopeHash: currentScopeHash,
|
|
668
|
+
inputSnapshotHash: ev.snapshot.hash,
|
|
669
|
+
budgetCpuMs,
|
|
670
|
+
requireNearMiss,
|
|
671
|
+
},
|
|
672
|
+
};
|
|
673
|
+
const verifyIntent = {
|
|
674
|
+
kind: 'Verify',
|
|
675
|
+
verifyId,
|
|
676
|
+
attemptId: attempt.attemptId,
|
|
677
|
+
stage: firstStage,
|
|
678
|
+
budgetCpuMs,
|
|
679
|
+
requireNearMiss,
|
|
680
|
+
binding,
|
|
681
|
+
};
|
|
682
|
+
const nextState = {
|
|
683
|
+
...stateAfterRedact,
|
|
684
|
+
activeAttempts: replaceAttempt(state.activeAttempts, updatedAttempt),
|
|
685
|
+
budgets: { ...state.budgets, costMicroUnits: state.budgets.costMicroUnits + estCost },
|
|
686
|
+
};
|
|
687
|
+
return commitEntry(state, nextState, envelope, payloadHash, true, { code: 'ALLOW', reason: 'VERIFY_DISPATCHED' }, [verifyIntent], attempt.scopeId, attempt.classId, diffHash, ev.snapshot.hash);
|
|
688
|
+
}
|
|
689
|
+
case 'WitnessVerdict':
|
|
690
|
+
return handleWitnessVerdict(state, stateAfterRedact, envelope, payloadHash, ev, hooks);
|
|
691
|
+
case 'GrantApproval': {
|
|
692
|
+
if (!isHuman || ev.approval.humanId !== origin.actorId) {
|
|
693
|
+
const { nextState, decision } = recordFailStreak(stateAfterRedact, 'FORBIDDEN_ORIGIN');
|
|
694
|
+
return commitEntry(state, nextState, envelope, payloadHash, false, decision, [], scopeId, classId, null, EMPTY_SNAPSHOT_HASH);
|
|
695
|
+
}
|
|
696
|
+
const attempt = state.activeAttempts.find((a) => a.attemptId === ev.approval.attemptId);
|
|
697
|
+
if (!attempt || !attempt.binding || (attempt.status !== 'VERIFYING' && attempt.status !== 'VERIFIED')) {
|
|
698
|
+
return commitEntry(state, stateAfterRedact, envelope, payloadHash, false, { code: 'REJECT', reason: 'ATTEMPT_NOT_APPROVABLE' }, [], attempt?.scopeId ?? '*', attempt?.classId ?? '*', attempt?.diffHash ?? null, ev.approval.binding.inputSnapshotHash);
|
|
699
|
+
}
|
|
700
|
+
const currentScopeHash = computeScopeHash(state, attempt.scopeId, attempt.classId, envelope.nowMs);
|
|
701
|
+
if (attempt.openedAtEpoch !== scopeEpochOf(state, attempt.scopeId) || attempt.binding.scopeHash !== currentScopeHash) {
|
|
702
|
+
return commitEntry(state, stateAfterRedact, envelope, payloadHash, false, { code: 'REJECT', reason: 'STALE_SCOPE' }, [], attempt.scopeId, attempt.classId, attempt.diffHash, attempt.binding.inputSnapshotHash);
|
|
703
|
+
}
|
|
704
|
+
const approvalErr = checkApprovalValidity(state, ev.approval, attempt.attemptId, attempt.binding, envelope.nowMs, hooks);
|
|
705
|
+
if (approvalErr !== null) {
|
|
706
|
+
return commitEntry(state, stateAfterRedact, envelope, payloadHash, false, { code: 'REJECT', reason: approvalErr }, [], attempt.scopeId, attempt.classId, attempt.diffHash, attempt.binding.inputSnapshotHash);
|
|
707
|
+
}
|
|
708
|
+
const updatedAttempt = { ...attempt, approval: ev.approval };
|
|
709
|
+
const shouldUnpause = state.taskStatus === 'PAUSED' && isPauseApprovalOrAutonomyReason(state.pauseReason);
|
|
710
|
+
const nextState = {
|
|
711
|
+
...stateAfterRedact,
|
|
712
|
+
taskStatus: shouldUnpause ? 'ACTIVE' : state.taskStatus,
|
|
713
|
+
pauseReason: shouldUnpause ? null : state.pauseReason,
|
|
714
|
+
activeAttempts: replaceAttempt(state.activeAttempts, updatedAttempt),
|
|
715
|
+
};
|
|
716
|
+
return commitEntry(state, nextState, envelope, payloadHash, true, { code: 'ALLOW', reason: 'APPROVAL_GRANTED' }, [], attempt.scopeId, attempt.classId, attempt.diffHash, attempt.binding.inputSnapshotHash);
|
|
717
|
+
}
|
|
718
|
+
case 'FinalizeBatch': {
|
|
719
|
+
const attempt = state.activeAttempts.find((a) => a.attemptId === ev.attemptId);
|
|
720
|
+
if (!attempt || attempt.status !== 'VERIFIED' || !attempt.binding || !attempt.snapshot) {
|
|
721
|
+
return commitEntry(state, stateAfterRedact, envelope, payloadHash, false, { code: 'REJECT', reason: 'NO_VALID_PROOF' }, [], attempt?.scopeId ?? '*', attempt?.classId ?? '*', attempt?.diffHash ?? null, EMPTY_SNAPSHOT_HASH);
|
|
722
|
+
}
|
|
723
|
+
if (origin.kind !== 'Agent' ||
|
|
724
|
+
origin.actorId !== attempt.executorId ||
|
|
725
|
+
origin.attemptId !== ev.attemptId) {
|
|
726
|
+
const { nextState, decision } = recordFailStreak(stateAfterRedact, 'FORBIDDEN_ORIGIN');
|
|
727
|
+
return commitEntry(state, nextState, envelope, payloadHash, false, decision, [], attempt.scopeId, attempt.classId, attempt.diffHash, attempt.snapshot.hash);
|
|
728
|
+
}
|
|
729
|
+
if (hasOutOfLeaseClass(attempt.classId, attempt.ops)) {
|
|
730
|
+
const { nextState, decision } = recordFailStreak({
|
|
731
|
+
...stateAfterRedact,
|
|
732
|
+
...recordClusterOutcome(state, attempt.toolId, attempt.clusterId, 'VIOLATION', state.serverSeq + 1, hooks),
|
|
733
|
+
}, 'OP_CLASS_OUT_OF_LEASE');
|
|
734
|
+
return commitEntry(state, nextState, envelope, payloadHash, false, decision, [], attempt.scopeId, attempt.classId, attempt.diffHash, attempt.snapshot.hash);
|
|
735
|
+
}
|
|
736
|
+
if (attempt.openedAtEpoch !== scopeEpochOf(state, attempt.scopeId)) {
|
|
737
|
+
const { nextState, decision } = recordConflictStreak(stateAfterRedact, 'STALE_EPOCH');
|
|
738
|
+
return commitEntry(state, nextState, envelope, payloadHash, false, decision, [], attempt.scopeId, attempt.classId, attempt.diffHash, attempt.snapshot.hash);
|
|
739
|
+
}
|
|
740
|
+
const currentScopeHash = computeScopeHash(state, attempt.scopeId, attempt.classId, envelope.nowMs);
|
|
741
|
+
if (attempt.binding.scopeHash !== currentScopeHash) {
|
|
742
|
+
const { nextState, decision } = recordConflictStreak(stateAfterRedact, 'STALE_SCOPE');
|
|
743
|
+
return commitEntry(state, nextState, envelope, payloadHash, false, decision, [], attempt.scopeId, attempt.classId, attempt.diffHash, attempt.snapshot.hash);
|
|
744
|
+
}
|
|
745
|
+
const pinEval = evaluatePinsForOps(state, attempt.scopeId, attempt.ops, envelope.nowMs);
|
|
746
|
+
if (pinEval.blockedBy === 'PIN_HARD_BLOCKED') {
|
|
747
|
+
const { nextState, decision } = recordFailStreak({
|
|
748
|
+
...stateAfterRedact,
|
|
749
|
+
...recordClusterOutcome(state, attempt.toolId, attempt.clusterId, 'VIOLATION', state.serverSeq + 1, hooks),
|
|
750
|
+
}, 'PIN_HARD_BLOCKED');
|
|
751
|
+
return commitEntry(state, nextState, envelope, payloadHash, false, decision, [], attempt.scopeId, attempt.classId, attempt.diffHash, attempt.snapshot.hash);
|
|
752
|
+
}
|
|
753
|
+
if (pinEval.blockedBy === 'PIN_TEMP_BLOCKED') {
|
|
754
|
+
const { nextState, decision } = recordConflictStreak(stateAfterRedact, 'PIN_TEMP_BLOCKED');
|
|
755
|
+
return commitEntry(state, nextState, envelope, payloadHash, false, decision, [], attempt.scopeId, attempt.classId, attempt.diffHash, attempt.snapshot.hash);
|
|
756
|
+
}
|
|
757
|
+
const autonomy = state.policy.enforceAutonomyLadder
|
|
758
|
+
? computeToolAutonomy(state, attempt.toolId)
|
|
759
|
+
: null;
|
|
760
|
+
if (autonomy !== null &&
|
|
761
|
+
autonomy.tier === 'SHADOW' &&
|
|
762
|
+
attempt.ops.some((o) => o.externalEffect !== undefined)) {
|
|
763
|
+
const { nextState, decision } = recordFailStreak(stateAfterRedact, 'AUTONOMY_SHADOW_EXTERNAL_BLOCKED');
|
|
764
|
+
return commitEntry(state, nextState, envelope, payloadHash, false, decision, [], attempt.scopeId, attempt.classId, attempt.diffHash, attempt.snapshot.hash);
|
|
765
|
+
}
|
|
766
|
+
let nextSpent = state.spentApprovals;
|
|
767
|
+
let consumedApproval = null;
|
|
768
|
+
const requiresApproval = attempt.needsApproval ||
|
|
769
|
+
attempt.ops.some((o) => o.reversibility === 'IRREVERSIBLE') ||
|
|
770
|
+
(autonomy !== null && (autonomy.tier === 'SHADOW' || autonomy.tier === 'APPROVAL')) ||
|
|
771
|
+
ev.approvalId !== undefined;
|
|
772
|
+
if (requiresApproval) {
|
|
773
|
+
if (!attempt.approval || (ev.approvalId !== undefined && attempt.approval.approvalId !== ev.approvalId)) {
|
|
774
|
+
const pausedState = {
|
|
775
|
+
...stateAfterRedact,
|
|
776
|
+
taskStatus: 'PAUSED',
|
|
777
|
+
pauseReason: attempt.approvalReason ?? 'APPROVAL_REQUIRED',
|
|
778
|
+
};
|
|
779
|
+
return commitEntry(state, pausedState, envelope, payloadHash, false, { code: 'PAUSE', reason: attempt.approvalReason ?? 'APPROVAL_REQUIRED' }, [], attempt.scopeId, attempt.classId, attempt.diffHash, attempt.snapshot.hash);
|
|
780
|
+
}
|
|
781
|
+
const approvalErr = checkApprovalValidity(state, attempt.approval, attempt.attemptId, attempt.binding, envelope.nowMs, hooks);
|
|
782
|
+
if (approvalErr !== null) {
|
|
783
|
+
return commitEntry(state, stateAfterRedact, envelope, payloadHash, false, { code: 'REJECT', reason: approvalErr }, [], attempt.scopeId, attempt.classId, attempt.diffHash, attempt.snapshot.hash);
|
|
784
|
+
}
|
|
785
|
+
consumedApproval = attempt.approval;
|
|
786
|
+
nextSpent = appendSpentApproval(state.spentApprovals, attempt.approval.approvalId);
|
|
787
|
+
}
|
|
788
|
+
if (!checkOpsBaseConsistency(state, attempt.scopeId, attempt.ops)) {
|
|
789
|
+
const { nextState, decision } = recordConflictStreak(stateAfterRedact, 'STALE_BASE');
|
|
790
|
+
return commitEntry(state, nextState, envelope, payloadHash, false, decision, [], attempt.scopeId, attempt.classId, attempt.diffHash, attempt.snapshot.hash);
|
|
791
|
+
}
|
|
792
|
+
const nextSlots = { ...state.slots };
|
|
793
|
+
const agentOrigin = {
|
|
794
|
+
kind: 'Agent',
|
|
795
|
+
actorId: attempt.executorId,
|
|
796
|
+
taskId: attempt.taskId,
|
|
797
|
+
attemptId: attempt.attemptId,
|
|
798
|
+
};
|
|
799
|
+
const newEffects = [];
|
|
800
|
+
const intents = [];
|
|
801
|
+
const effectIds = [];
|
|
802
|
+
let batchRev = 'REVERSIBLE';
|
|
803
|
+
for (let i = 0; i < attempt.ops.length; i += 1) {
|
|
804
|
+
const op = attempt.ops[i];
|
|
805
|
+
if (op.reversibility === 'IRREVERSIBLE') {
|
|
806
|
+
batchRev = 'IRREVERSIBLE';
|
|
807
|
+
}
|
|
808
|
+
else if (op.reversibility === 'COMPENSABLE' && batchRev === 'REVERSIBLE') {
|
|
809
|
+
batchRev = 'COMPENSABLE';
|
|
810
|
+
}
|
|
811
|
+
const key = slotKey(attempt.scopeId, op.classId, op.objectId, op.field);
|
|
812
|
+
const existing = nextSlots[key];
|
|
813
|
+
nextSlots[key] = {
|
|
814
|
+
objectId: op.objectId,
|
|
815
|
+
classId: op.classId,
|
|
816
|
+
field: op.field,
|
|
817
|
+
rev: (existing?.rev ?? 0) + 1,
|
|
818
|
+
value: op.afterValue,
|
|
819
|
+
owner: agentOrigin,
|
|
820
|
+
batchId: attempt.attemptId,
|
|
821
|
+
...(op.parentObjectId !== undefined
|
|
822
|
+
? { parentObjectId: op.parentObjectId }
|
|
823
|
+
: existing?.parentObjectId !== undefined
|
|
824
|
+
? { parentObjectId: existing.parentObjectId }
|
|
825
|
+
: {}),
|
|
826
|
+
};
|
|
827
|
+
if (op.externalEffect) {
|
|
828
|
+
const effectId = hashCanonical('effect', 1, {
|
|
829
|
+
batchId: attempt.attemptId,
|
|
830
|
+
opIndex: op.opIndex,
|
|
831
|
+
effectKey: op.externalEffect.effectKey,
|
|
832
|
+
});
|
|
833
|
+
effectIds.push(effectId);
|
|
834
|
+
newEffects.push({
|
|
835
|
+
effectId,
|
|
836
|
+
batchId: attempt.attemptId,
|
|
837
|
+
attemptId: attempt.attemptId,
|
|
838
|
+
scopeId: attempt.scopeId,
|
|
839
|
+
classId: attempt.classId,
|
|
840
|
+
effectKey: op.externalEffect.effectKey,
|
|
841
|
+
recipientId: op.externalEffect.recipientId,
|
|
842
|
+
supportsCas: op.externalEffect.supportsCas,
|
|
843
|
+
actionPayload: op.externalEffect.actionPayload,
|
|
844
|
+
inversePayload: op.externalEffect.inversePayload ?? null,
|
|
845
|
+
binding: attempt.binding,
|
|
846
|
+
approvalId: consumedApproval?.approvalId ?? null,
|
|
847
|
+
approvalExpiresAtMs: consumedApproval?.expiresAtMs ?? null,
|
|
848
|
+
status: 'INTENT',
|
|
849
|
+
reconcileCount: 0,
|
|
850
|
+
orderIndex: newEffects.length,
|
|
851
|
+
compensating: false,
|
|
852
|
+
originalEffectId: null,
|
|
853
|
+
});
|
|
854
|
+
intents.push({
|
|
855
|
+
kind: 'Deliver',
|
|
856
|
+
effectId,
|
|
857
|
+
batchId: attempt.attemptId,
|
|
858
|
+
scopeId: attempt.scopeId,
|
|
859
|
+
classId: attempt.classId,
|
|
860
|
+
recipientId: op.externalEffect.recipientId,
|
|
861
|
+
supportsCas: op.externalEffect.supportsCas,
|
|
862
|
+
binding: attempt.binding,
|
|
863
|
+
postCommitScopeHash: '',
|
|
864
|
+
approvalExpiresAtMs: consumedApproval?.expiresAtMs ?? null,
|
|
865
|
+
payload: op.externalEffect.actionPayload,
|
|
866
|
+
});
|
|
867
|
+
}
|
|
868
|
+
}
|
|
869
|
+
const archived = archiveAttempt(state, { ...attempt, status: 'FINALIZED', approval: null });
|
|
870
|
+
const clusterPatch = recordClusterOutcome(state, attempt.toolId, attempt.clusterId, 'CLEAN', state.serverSeq + 1, hooks);
|
|
871
|
+
const batchRecord = {
|
|
872
|
+
batchId: attempt.attemptId,
|
|
873
|
+
attemptId: attempt.attemptId,
|
|
874
|
+
taskId: attempt.taskId,
|
|
875
|
+
committedAtMs: envelope.nowMs,
|
|
876
|
+
committedAtSeq: state.serverSeq + 1,
|
|
877
|
+
scopeId: attempt.scopeId,
|
|
878
|
+
reversibility: batchRev,
|
|
879
|
+
ops: attempt.ops,
|
|
880
|
+
effectIds,
|
|
881
|
+
undone: false,
|
|
882
|
+
};
|
|
883
|
+
const retained = pruneRetainedHistory([...state.batches, batchRecord], [...state.effects, ...newEffects], envelope.nowMs, state.policy.undoWindowTtlMs);
|
|
884
|
+
const nextStateDraft = {
|
|
885
|
+
...stateAfterRedact,
|
|
886
|
+
taskStatus: state.taskStatus === 'PAUSED' && isPauseApprovalOrAutonomyReason(state.pauseReason)
|
|
887
|
+
? 'ACTIVE'
|
|
888
|
+
: state.taskStatus,
|
|
889
|
+
pauseReason: state.taskStatus === 'PAUSED' && isPauseApprovalOrAutonomyReason(state.pauseReason)
|
|
890
|
+
? null
|
|
891
|
+
: state.pauseReason,
|
|
892
|
+
slots: nextSlots,
|
|
893
|
+
spentApprovals: nextSpent,
|
|
894
|
+
leases: activeLeasesAt(state.leases, envelope.nowMs).filter((l) => l.attemptId !== attempt.attemptId),
|
|
895
|
+
...archived,
|
|
896
|
+
batches: retained.batches,
|
|
897
|
+
effects: retained.effects,
|
|
898
|
+
...clusterPatch,
|
|
899
|
+
budgets: { ...state.budgets, failStreak: 0, conflictStreak: 0 },
|
|
900
|
+
};
|
|
901
|
+
const postCommitScopeHash = computeScopeHash(nextStateDraft, attempt.scopeId, attempt.classId, envelope.nowMs);
|
|
902
|
+
const intentsWithPostScope = intents.map((intent) => intent.kind === 'Deliver' ? { ...intent, postCommitScopeHash } : intent);
|
|
903
|
+
return commitEntry(state, nextStateDraft, envelope, payloadHash, true, { code: 'ALLOW', reason: 'BATCH_FINALIZED' }, intentsWithPostScope, attempt.scopeId, attempt.classId, attempt.diffHash, attempt.snapshot.hash);
|
|
904
|
+
}
|
|
905
|
+
case 'CancelAttempt': {
|
|
906
|
+
const attempt = state.activeAttempts.find((a) => a.attemptId === ev.attemptId);
|
|
907
|
+
if (!attempt || (attempt.status !== 'OPEN' && attempt.status !== 'VERIFYING' && attempt.status !== 'VERIFIED')) {
|
|
908
|
+
return commitEntry(state, stateAfterRedact, envelope, payloadHash, false, { code: 'REJECT', reason: 'ATTEMPT_NOT_CANCELLABLE' }, [], attempt?.scopeId ?? '*', attempt?.classId ?? '*', attempt?.diffHash ?? null, EMPTY_SNAPSHOT_HASH);
|
|
909
|
+
}
|
|
910
|
+
const isAttemptOwner = origin.kind === 'Agent' &&
|
|
911
|
+
origin.actorId === attempt.executorId &&
|
|
912
|
+
origin.attemptId === ev.attemptId;
|
|
913
|
+
if (!isHuman && !isAttemptOwner) {
|
|
914
|
+
const { nextState, decision } = recordFailStreak(stateAfterRedact, 'FORBIDDEN_ORIGIN');
|
|
915
|
+
return commitEntry(state, nextState, envelope, payloadHash, false, decision, [], attempt.scopeId, attempt.classId, attempt.diffHash, EMPTY_SNAPSHOT_HASH);
|
|
916
|
+
}
|
|
917
|
+
const archived = archiveAttempt(state, { ...attempt, status: 'ABORTED', pendingVerify: null });
|
|
918
|
+
const nextState = {
|
|
919
|
+
...stateAfterRedact,
|
|
920
|
+
...archived,
|
|
921
|
+
leases: activeLeasesAt(state.leases, envelope.nowMs).filter((l) => l.attemptId !== attempt.attemptId),
|
|
922
|
+
};
|
|
923
|
+
return commitEntry(state, nextState, envelope, payloadHash, true, { code: 'ALLOW', reason: 'ATTEMPT_CANCELLED' }, [], attempt.scopeId, attempt.classId, attempt.diffHash, attempt.snapshot?.hash ?? EMPTY_SNAPSHOT_HASH);
|
|
924
|
+
}
|
|
925
|
+
case 'EffectTransition':
|
|
926
|
+
return handleEffectTransition(state, stateAfterRedact, envelope, payloadHash, ev);
|
|
927
|
+
case 'OriginUndo':
|
|
928
|
+
return handleOriginUndo(state, stateAfterRedact, envelope, payloadHash, ev, hooks);
|
|
929
|
+
case 'ExpireUndoWindow': {
|
|
930
|
+
if (!isHuman && !isSystem) {
|
|
931
|
+
const { nextState, decision } = recordFailStreak(stateAfterRedact, 'FORBIDDEN_ORIGIN');
|
|
932
|
+
return commitEntry(state, nextState, envelope, payloadHash, false, decision, [], ev.scopeId, '*', null, EMPTY_SNAPSHOT_HASH);
|
|
933
|
+
}
|
|
934
|
+
const hasExpired = state.batches.some((b) => b.scopeId === ev.scopeId &&
|
|
935
|
+
!b.undone &&
|
|
936
|
+
envelope.nowMs - b.committedAtMs > state.policy.undoWindowTtlMs);
|
|
937
|
+
if (!hasExpired) {
|
|
938
|
+
return commitEntry(state, stateAfterRedact, envelope, payloadHash, false, { code: 'REJECT', reason: 'NO_EXPIRED_UNDO_WINDOW' }, [], ev.scopeId, '*', null, EMPTY_SNAPSHOT_HASH);
|
|
939
|
+
}
|
|
940
|
+
const nextUndoExpiredScopes = state.undoExpiredScopes.includes(ev.scopeId)
|
|
941
|
+
? state.undoExpiredScopes
|
|
942
|
+
: sortDeterministically([...state.undoExpiredScopes, ev.scopeId], (s) => s);
|
|
943
|
+
const nextState = {
|
|
944
|
+
...stateAfterRedact,
|
|
945
|
+
taskStatus: state.taskStatus,
|
|
946
|
+
undoExpiredScopes: nextUndoExpiredScopes,
|
|
947
|
+
};
|
|
948
|
+
return commitEntry(state, nextState, envelope, payloadHash, true, { code: 'ALLOW', reason: 'UNDO_WINDOW_EXPIRED' }, [], ev.scopeId, '*', null, EMPTY_SNAPSHOT_HASH);
|
|
949
|
+
}
|
|
950
|
+
case 'RuntimeBudgetReported': {
|
|
951
|
+
if (!isSystem) {
|
|
952
|
+
const { nextState, decision } = recordFailStreak(stateAfterRedact, 'FORBIDDEN_ORIGIN');
|
|
953
|
+
return commitEntry(state, nextState, envelope, payloadHash, false, decision, [], ev.scopeId, '*', null, EMPTY_SNAPSHOT_HASH);
|
|
954
|
+
}
|
|
955
|
+
const nextCpu = state.budgets.cpuMs + ev.cpuMs;
|
|
956
|
+
const nextCost = state.budgets.costMicroUnits + ev.costMicroUnits;
|
|
957
|
+
const exhausted = nextCpu > state.policy.maxCpuMs || nextCost > state.policy.maxCostMicroUnits;
|
|
958
|
+
const nextState = {
|
|
959
|
+
...stateAfterRedact,
|
|
960
|
+
taskStatus: exhausted && state.taskStatus === 'ACTIVE' ? 'PAUSED' : state.taskStatus,
|
|
961
|
+
pauseReason: exhausted && state.taskStatus === 'ACTIVE' ? 'BUDGET_EXHAUSTED' : state.pauseReason,
|
|
962
|
+
budgets: { ...state.budgets, cpuMs: nextCpu, costMicroUnits: nextCost },
|
|
963
|
+
};
|
|
964
|
+
return commitEntry(state, nextState, envelope, payloadHash, true, exhausted ? { code: 'PAUSE', reason: 'BUDGET_EXHAUSTED' } : { code: 'ALLOW', reason: 'BUDGET_RECORDED' }, [], ev.scopeId, '*', null, EMPTY_SNAPSHOT_HASH);
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
}
|