certal 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/.claude-plugin/plugin.json +11 -0
  2. package/CHANGELOG.md +32 -0
  3. package/LICENSE +21 -0
  4. package/README.md +277 -2
  5. package/SECURITY.md +36 -0
  6. package/bin/certal.mjs +12 -0
  7. package/certal.schema.json +156 -0
  8. package/dist/adapters/approval-channel.d.ts +44 -0
  9. package/dist/adapters/approval-channel.js +74 -0
  10. package/dist/adapters/commands.d.ts +73 -0
  11. package/dist/adapters/commands.js +185 -0
  12. package/dist/adapters/contracts.d.ts +59 -0
  13. package/dist/adapters/contracts.js +1 -0
  14. package/dist/adapters/file-watcher.d.ts +53 -0
  15. package/dist/adapters/file-watcher.js +142 -0
  16. package/dist/adapters/in-memory.d.ts +53 -0
  17. package/dist/adapters/in-memory.js +165 -0
  18. package/dist/adapters/index.d.ts +8 -0
  19. package/dist/adapters/index.js +8 -0
  20. package/dist/adapters/manifest.d.ts +105 -0
  21. package/dist/adapters/manifest.js +438 -0
  22. package/dist/adapters/operator-auth.d.ts +47 -0
  23. package/dist/adapters/operator-auth.js +72 -0
  24. package/dist/adapters/tool-sdk.d.ts +150 -0
  25. package/dist/adapters/tool-sdk.js +336 -0
  26. package/dist/cli/index.d.ts +1 -0
  27. package/dist/cli/index.js +1 -0
  28. package/dist/cli/main.d.ts +1 -0
  29. package/dist/cli/main.js +386 -0
  30. package/dist/kernel/common.d.ts +46 -0
  31. package/dist/kernel/common.js +238 -0
  32. package/dist/kernel/crypto.d.ts +35 -0
  33. package/dist/kernel/crypto.js +54 -0
  34. package/dist/kernel/effects.d.ts +4 -0
  35. package/dist/kernel/effects.js +178 -0
  36. package/dist/kernel/index.d.ts +9 -0
  37. package/dist/kernel/index.js +9 -0
  38. package/dist/kernel/jcs.d.ts +24 -0
  39. package/dist/kernel/jcs.js +93 -0
  40. package/dist/kernel/leases.d.ts +11 -0
  41. package/dist/kernel/leases.js +86 -0
  42. package/dist/kernel/step.d.ts +10 -0
  43. package/dist/kernel/step.js +967 -0
  44. package/dist/kernel/types.d.ts +538 -0
  45. package/dist/kernel/types.js +1 -0
  46. package/dist/kernel/undo.d.ts +4 -0
  47. package/dist/kernel/undo.js +180 -0
  48. package/dist/kernel/validation.d.ts +13 -0
  49. package/dist/kernel/validation.js +307 -0
  50. package/dist/kernel/witness.d.ts +34 -0
  51. package/dist/kernel/witness.js +279 -0
  52. package/dist/mcp/host.d.ts +141 -0
  53. package/dist/mcp/host.js +517 -0
  54. package/dist/mcp/index.d.ts +2 -0
  55. package/dist/mcp/index.js +2 -0
  56. package/dist/mcp/server.d.ts +70 -0
  57. package/dist/mcp/server.js +508 -0
  58. package/dist/runtime/dp1.d.ts +48 -0
  59. package/dist/runtime/dp1.js +229 -0
  60. package/dist/runtime/engine.d.ts +86 -0
  61. package/dist/runtime/engine.js +320 -0
  62. package/dist/runtime/index.d.ts +4 -0
  63. package/dist/runtime/index.js +4 -0
  64. package/dist/runtime/outbox.d.ts +69 -0
  65. package/dist/runtime/outbox.js +238 -0
  66. package/dist/runtime/store.d.ts +204 -0
  67. package/dist/runtime/store.js +746 -0
  68. package/package.json +91 -4
  69. package/presets/exchange-firewall.json +40 -0
  70. package/presets/sdk.json +32 -0
  71. package/presets/solver.json +22 -0
  72. package/presets/vibeops.json +34 -0
  73. package/skills/certal/SKILL.md +49 -0
@@ -0,0 +1,180 @@
1
+ import { EMPTY_SNAPSHOT_HASH, bumpScopeEpoch, commitEntry, pauseUnlessHalted, recordFailStreak, slotKey, } from './common.js';
2
+ import { hashCanonical, sortDeterministically } from './jcs.js';
3
+ const ACTIVE_EFFECT_STATUSES = new Set([
4
+ 'INTENT',
5
+ 'IN_FLIGHT',
6
+ 'UNKNOWN',
7
+ 'RECONCILE_EXHAUSTED',
8
+ 'COMP_INTENT',
9
+ 'COMP_IN_FLIGHT',
10
+ 'COMP_UNKNOWN',
11
+ ]);
12
+ export function handleOriginUndo(prevState, stateAfterRedact, cleanEnvelope, payloadHash, ev, hooks) {
13
+ if (cleanEnvelope.auth.origin.kind !== 'Human') {
14
+ const { nextState, decision } = recordFailStreak(stateAfterRedact, 'FORBIDDEN_ORIGIN');
15
+ return commitEntry(prevState, nextState, cleanEnvelope, payloadHash, false, decision, [], ev.scopeId, '*', null, EMPTY_SNAPSHOT_HASH);
16
+ }
17
+ const batch = prevState.batches.find((b) => b.batchId === ev.batchId);
18
+ if (!batch || batch.undone) {
19
+ return commitEntry(prevState, stateAfterRedact, cleanEnvelope, payloadHash, false, { code: 'REJECT', reason: 'BATCH_NOT_UNDOABLE' }, [], ev.scopeId, '*', null, EMPTY_SNAPSHOT_HASH);
20
+ }
21
+ if (cleanEnvelope.nowMs - batch.committedAtMs > prevState.policy.undoWindowTtlMs) {
22
+ const nextUndoExpiredScopes = prevState.undoExpiredScopes.includes(ev.scopeId)
23
+ ? prevState.undoExpiredScopes
24
+ : sortDeterministically([...prevState.undoExpiredScopes, ev.scopeId], (s) => s);
25
+ const expiredState = {
26
+ ...stateAfterRedact,
27
+ taskStatus: prevState.taskStatus,
28
+ undoExpiredScopes: nextUndoExpiredScopes,
29
+ };
30
+ return commitEntry(prevState, expiredState, cleanEnvelope, payloadHash, false, { code: 'REJECT', reason: 'UNDO_EXPIRED' }, [], ev.scopeId, '*', null, EMPTY_SNAPSHOT_HASH);
31
+ }
32
+ if (batch.reversibility === 'IRREVERSIBLE') {
33
+ return commitEntry(prevState, stateAfterRedact, cleanEnvelope, payloadHash, false, { code: 'REJECT', reason: 'IRREVERSIBLE' }, [], ev.scopeId, '*', null, EMPTY_SNAPSHOT_HASH);
34
+ }
35
+ // Race guard: do not undo a batch while any of its external effects is still in a non-terminal state
36
+ const hasActiveEffect = prevState.effects.some((e) => e.batchId === batch.batchId && ACTIVE_EFFECT_STATUSES.has(e.status));
37
+ if (hasActiveEffect) {
38
+ return commitEntry(prevState, stateAfterRedact, cleanEnvelope, payloadHash, false, { code: 'PAUSE', reason: 'UNDO_BLOCKED_ACTIVE_EFFECT' }, [], batch.scopeId, '*', null, EMPTY_SNAPSHOT_HASH);
39
+ }
40
+ const nextSlots = { ...prevState.slots };
41
+ const appliedFields = [];
42
+ const skippedConflicts = [];
43
+ for (let i = batch.ops.length - 1; i >= 0; i -= 1) {
44
+ const op = batch.ops[i];
45
+ const key = slotKey(batch.scopeId, op.classId, op.objectId, op.field);
46
+ const currentSlot = nextSlots[key];
47
+ if (!currentSlot)
48
+ continue;
49
+ if (currentSlot.batchId !== batch.batchId) {
50
+ skippedConflicts.push({
51
+ objectId: op.objectId,
52
+ field: op.field,
53
+ reason: currentSlot.owner.kind === 'Human' ? 'HUMAN_OVERWRITE' : 'AGENT_OVERWRITE',
54
+ detail: `Overwritten by ${currentSlot.owner.kind}:${currentSlot.owner.actorId}`,
55
+ });
56
+ continue;
57
+ }
58
+ const dep = hooks?.checkUndoDependencies?.(prevState, {
59
+ batchId: batch.batchId,
60
+ objectId: op.objectId,
61
+ field: op.field,
62
+ restoreValue: op.beforeValue,
63
+ });
64
+ if (dep?.blocked) {
65
+ skippedConflicts.push({
66
+ objectId: op.objectId,
67
+ field: op.field,
68
+ reason: 'SKIPPED_DEPENDENT_REF',
69
+ detail: dep.reason ?? 'Dependent object created by a human',
70
+ });
71
+ continue;
72
+ }
73
+ nextSlots[key] = {
74
+ ...currentSlot,
75
+ rev: currentSlot.rev + 1,
76
+ value: op.beforeValue,
77
+ owner: cleanEnvelope.auth.origin,
78
+ batchId: null,
79
+ };
80
+ appliedFields.push({ objectId: op.objectId, field: op.field });
81
+ }
82
+ // A field conflict means that local state and the recipient would disagree after an automatic
83
+ // compensation. The event's policy decides: abort, hand the case to the operator, or force it.
84
+ const policy = ev.compensationPolicy ?? 'COMPENSATE_ONLY_IF_ALL_REVERTED';
85
+ const hasConflict = skippedConflicts.length > 0;
86
+ const hasCompensableEffect = batch.reversibility === 'COMPENSABLE' &&
87
+ prevState.effects.some((e) => e.batchId === batch.batchId && !e.compensating && e.status === 'APPLIED');
88
+ const conflictReport = {
89
+ batchId: batch.batchId,
90
+ appliedFields: [],
91
+ skippedConflicts: sortDeterministically(skippedConflicts, (c) => `${c.objectId}\0${c.field}\0${c.reason}`),
92
+ compensationMode: 'NONE',
93
+ };
94
+ if (hasConflict && policy === 'ABORT_ON_CONFLICT') {
95
+ return commitEntry(prevState, stateAfterRedact, cleanEnvelope, payloadHash, false, { code: 'REJECT', reason: 'UNDO_ABORTED_ON_CONFLICT' }, [], batch.scopeId, '*', null, EMPTY_SNAPSHOT_HASH, conflictReport);
96
+ }
97
+ if (hasConflict && hasCompensableEffect && policy === 'COMPENSATE_ONLY_IF_ALL_REVERTED') {
98
+ const pausedStatus = pauseUnlessHalted(prevState.taskStatus);
99
+ const pausedState = {
100
+ ...stateAfterRedact,
101
+ taskStatus: pausedStatus,
102
+ pauseReason: pausedStatus === 'PAUSED' ? 'UNDO_PARTIAL_CONFLICT_APPROVAL' : prevState.pauseReason,
103
+ };
104
+ return commitEntry(prevState, pausedState, cleanEnvelope, payloadHash, false, { code: 'PAUSE', reason: 'UNDO_PARTIAL_CONFLICT_APPROVAL' }, [], batch.scopeId, '*', null, EMPTY_SNAPSHOT_HASH, conflictReport);
105
+ }
106
+ let nextEffects = [...prevState.effects];
107
+ const compIntents = [];
108
+ let compMode = 'NONE';
109
+ let needsManual = false;
110
+ if (batch.reversibility === 'COMPENSABLE') {
111
+ const batchEffects = prevState.effects
112
+ .filter((e) => e.batchId === batch.batchId && !e.compensating && e.status === 'APPLIED')
113
+ .sort((a, b) => b.orderIndex - a.orderIndex);
114
+ for (const eff of batchEffects) {
115
+ if (!eff.supportsCas) {
116
+ needsManual = true;
117
+ compMode = 'MANUAL_REQUIRED';
118
+ nextEffects = nextEffects.map((x) => x.effectId === eff.effectId ? { ...x, status: 'MANUAL_COMPENSATION_REQUIRED' } : x);
119
+ }
120
+ else {
121
+ if (!needsManual)
122
+ compMode = 'QUEUED';
123
+ const compId = hashCanonical('comp_effect', 1, { originalEffectId: eff.effectId });
124
+ nextEffects.push({
125
+ effectId: compId,
126
+ batchId: eff.batchId,
127
+ attemptId: eff.attemptId,
128
+ scopeId: eff.scopeId,
129
+ classId: eff.classId,
130
+ effectKey: `${eff.effectKey}/undo`,
131
+ recipientId: eff.recipientId,
132
+ supportsCas: eff.supportsCas,
133
+ actionPayload: eff.inversePayload,
134
+ inversePayload: null,
135
+ binding: eff.binding,
136
+ approvalId: null,
137
+ approvalExpiresAtMs: null,
138
+ status: 'COMP_INTENT',
139
+ reconcileCount: 0,
140
+ orderIndex: eff.orderIndex,
141
+ compensating: true,
142
+ originalEffectId: eff.effectId,
143
+ });
144
+ compIntents.push({
145
+ kind: 'Compensate',
146
+ compensationId: compId,
147
+ originalEffectId: eff.effectId,
148
+ recipientId: eff.recipientId,
149
+ supportsCas: eff.supportsCas,
150
+ inversePayload: eff.inversePayload,
151
+ });
152
+ }
153
+ }
154
+ }
155
+ const undoReport = {
156
+ batchId: batch.batchId,
157
+ appliedFields: sortDeterministically(appliedFields, (f) => `${f.objectId}\0${f.field}`),
158
+ skippedConflicts: sortDeterministically(skippedConflicts, (c) => `${c.objectId}\0${c.field}\0${c.reason}`),
159
+ compensationMode: compMode,
160
+ };
161
+ const nextBatches = prevState.batches.map((b) => b.batchId === batch.batchId ? { ...b, undone: true } : b);
162
+ const nextTaskStatus = needsManual ? pauseUnlessHalted(prevState.taskStatus) : prevState.taskStatus;
163
+ const nextState = {
164
+ ...stateAfterRedact,
165
+ epoch: prevState.epoch + 1,
166
+ scopeEpochs: bumpScopeEpoch(prevState.scopeEpochs, batch.scopeId),
167
+ slots: nextSlots,
168
+ batches: nextBatches,
169
+ effects: nextEffects,
170
+ taskStatus: nextTaskStatus,
171
+ pauseReason: needsManual && nextTaskStatus === 'PAUSED'
172
+ ? 'MANUAL_COMPENSATION_REQUIRED'
173
+ : prevState.pauseReason,
174
+ };
175
+ return commitEntry(prevState, nextState, cleanEnvelope, payloadHash, true, needsManual
176
+ ? nextTaskStatus === 'HALTED'
177
+ ? { code: 'HALT', reason: prevState.haltReason ?? 'MANUAL_COMPENSATION_REQUIRED' }
178
+ : { code: 'PAUSE', reason: 'MANUAL_COMPENSATION_REQUIRED' }
179
+ : { code: 'ALLOW', reason: 'ORIGIN_UNDO_APPLIED' }, compIntents, batch.scopeId, '*', null, EMPTY_SNAPSHOT_HASH, undoReport);
180
+ }
@@ -0,0 +1,13 @@
1
+ import type { EventEnvelope, KernelEvent, KernelState, PolicyConfig } from './types.ts';
2
+ /**
3
+ * Pure validation of the envelope shape and the authenticated context. It runs before a serverSeq is assigned.
4
+ */
5
+ export declare function validateEnvelopeShape(envelope: EventEnvelope): string | null;
6
+ /**
7
+ * Validates safe bounds of the fields in a PolicyUpdated event.
8
+ */
9
+ export declare function validatePolicyBounds(policy: Partial<PolicyConfig>): string | null;
10
+ export declare function eventScopeAndClass(state: KernelState, ev: KernelEvent): {
11
+ scopeId: string;
12
+ classId: string;
13
+ };
@@ -0,0 +1,307 @@
1
+ import { jcs } from './jcs.js';
2
+ function isNonEmptyString(v) {
3
+ return typeof v === 'string' && v.length > 0;
4
+ }
5
+ function isNonNegSafeInt(v) {
6
+ return typeof v === 'number' && Number.isSafeInteger(v) && v >= 0;
7
+ }
8
+ function isPosSafeInt(v) {
9
+ return typeof v === 'number' && Number.isSafeInteger(v) && v >= 1;
10
+ }
11
+ /** Optional field: absent or a non-negative safe integer. A negative value would lower the spent budget. */
12
+ function isOptionalNonNegSafeInt(v) {
13
+ return v === undefined || isNonNegSafeInt(v);
14
+ }
15
+ function isOptionalNonEmptyString(v) {
16
+ return v === undefined || isNonEmptyString(v);
17
+ }
18
+ /** Shape of one operation in a batch. A malformed operation must not reach the log. */
19
+ function isValidStateOp(op) {
20
+ if (op === null || typeof op !== 'object')
21
+ return false;
22
+ const o = op;
23
+ if (!isNonNegSafeInt(o['opIndex']) ||
24
+ !isNonEmptyString(o['objectId']) ||
25
+ !isNonEmptyString(o['classId']) ||
26
+ !isNonEmptyString(o['field']) ||
27
+ !isNonNegSafeInt(o['expectedBeforeRev']) ||
28
+ !(o['reversibility'] === 'REVERSIBLE' || o['reversibility'] === 'COMPENSABLE' || o['reversibility'] === 'IRREVERSIBLE') ||
29
+ !isOptionalNonEmptyString(o['parentObjectId'])) {
30
+ return false;
31
+ }
32
+ const effect = o['externalEffect'];
33
+ if (effect === undefined)
34
+ return true;
35
+ if (effect === null || typeof effect !== 'object')
36
+ return false;
37
+ const e = effect;
38
+ return isNonEmptyString(e['effectKey']) && isNonEmptyString(e['recipientId']) && typeof e['supportsCas'] === 'boolean';
39
+ }
40
+ const VALID_STAGES = new Set(['L0', 'L1', 'L2', 'L3']);
41
+ /**
42
+ * Pure validation of the envelope shape and the authenticated context. It runs before a serverSeq is assigned.
43
+ */
44
+ export function validateEnvelopeShape(envelope) {
45
+ if (!envelope || typeof envelope !== 'object')
46
+ return 'SCHEMA_INVALID';
47
+ if (!isNonEmptyString(envelope.opId))
48
+ return 'SCHEMA_INVALID';
49
+ if (!isNonNegSafeInt(envelope.nowMs))
50
+ return 'SCHEMA_INVALID';
51
+ const auth = envelope.auth;
52
+ if (!auth || typeof auth !== 'object' || !auth.origin || typeof auth.origin !== 'object') {
53
+ return 'AUTH_INVALID';
54
+ }
55
+ if (!isNonEmptyString(auth.authMethod) || !Array.isArray(auth.roles)) {
56
+ return 'AUTH_INVALID';
57
+ }
58
+ if (!isNonEmptyString(auth.origin.actorId))
59
+ return 'AUTH_INVALID';
60
+ if (auth.origin.kind === 'Agent') {
61
+ if (!isNonEmptyString(auth.origin.taskId) || !isNonEmptyString(auth.origin.attemptId)) {
62
+ return 'AUTH_INVALID';
63
+ }
64
+ }
65
+ else if (auth.origin.kind !== 'Human' &&
66
+ auth.origin.kind !== 'Sensor' &&
67
+ auth.origin.kind !== 'System') {
68
+ return 'AUTH_INVALID';
69
+ }
70
+ const ev = envelope.event;
71
+ if (!ev || typeof ev !== 'object' || !isNonEmptyString(ev.kind))
72
+ return 'SCHEMA_INVALID';
73
+ try {
74
+ jcs(ev);
75
+ }
76
+ catch (err) {
77
+ const msg = err instanceof Error ? err.message : '';
78
+ if (msg.startsWith('FLOAT_NOT_ALLOWED_IN_HASH'))
79
+ return 'FLOAT_NOT_ALLOWED';
80
+ return 'SCHEMA_INVALID';
81
+ }
82
+ switch (ev.kind) {
83
+ case 'PolicyUpdated':
84
+ return ev.policy && typeof ev.policy === 'object' ? null : 'SCHEMA_INVALID';
85
+ case 'HumanEdit':
86
+ return isNonEmptyString(ev.scopeId) &&
87
+ isNonEmptyString(ev.classId) &&
88
+ isNonEmptyString(ev.objectId) &&
89
+ isNonEmptyString(ev.field) &&
90
+ isOptionalNonEmptyString(ev.parentObjectId) &&
91
+ isOptionalNonNegSafeInt(ev.autoPinTtlMs)
92
+ ? null
93
+ : 'SCHEMA_INVALID';
94
+ case 'SetPin':
95
+ return ev.pin &&
96
+ isNonEmptyString(ev.pin.pinId) &&
97
+ (ev.pin.kind === 'H' || ev.pin.kind === 'T' || ev.pin.kind === 'N') &&
98
+ isNonEmptyString(ev.pin.scopeId) &&
99
+ isNonEmptyString(ev.pin.classId) &&
100
+ isNonEmptyString(ev.pin.ruleId) &&
101
+ isNonEmptyString(ev.pin.ownerId) &&
102
+ isOptionalNonNegSafeInt(ev.pin.expiresAtMs) &&
103
+ isOptionalNonNegSafeInt(ev.pin.contractVersion) &&
104
+ isOptionalNonNegSafeInt(ev.pin.costPenaltyMicroUnits)
105
+ ? null
106
+ : 'SCHEMA_INVALID';
107
+ case 'RemovePin':
108
+ return isNonEmptyString(ev.pinId) && isNonEmptyString(ev.scopeId) && isNonEmptyString(ev.reason)
109
+ ? null
110
+ : 'SCHEMA_INVALID';
111
+ case 'HumanHalt':
112
+ case 'HumanReset':
113
+ return isNonEmptyString(ev.scopeId) && isNonEmptyString(ev.reason) ? null : 'SCHEMA_INVALID';
114
+ case 'HumanResume':
115
+ return isNonEmptyString(ev.scopeId) &&
116
+ isOptionalNonNegSafeInt(ev.extraAttempts) &&
117
+ isOptionalNonNegSafeInt(ev.extraCpuMs) &&
118
+ isOptionalNonNegSafeInt(ev.extraCostMicroUnits)
119
+ ? null
120
+ : 'SCHEMA_INVALID';
121
+ case 'ExpireUndoWindow':
122
+ return isNonEmptyString(ev.scopeId) ? null : 'SCHEMA_INVALID';
123
+ case 'AcquireLease':
124
+ return isNonEmptyString(ev.leaseId) &&
125
+ isNonEmptyString(ev.scopeId) &&
126
+ isNonEmptyString(ev.classId) &&
127
+ isNonEmptyString(ev.attemptId) &&
128
+ isOptionalNonNegSafeInt(ev.ttlMs) &&
129
+ ev.units &&
130
+ isNonNegSafeInt(ev.units.inferenceSlots) &&
131
+ isNonNegSafeInt(ev.units.witnessSlots) &&
132
+ isNonNegSafeInt(ev.units.mutationSlots)
133
+ ? null
134
+ : 'SCHEMA_INVALID';
135
+ case 'RenewLease':
136
+ return isNonEmptyString(ev.leaseId) && isNonNegSafeInt(ev.leaseEpoch) && isOptionalNonNegSafeInt(ev.ttlMs)
137
+ ? null
138
+ : 'SCHEMA_INVALID';
139
+ case 'ReleaseLease':
140
+ return isNonEmptyString(ev.leaseId) && isNonNegSafeInt(ev.leaseEpoch) ? null : 'SCHEMA_INVALID';
141
+ case 'OpenAttempt':
142
+ return isNonEmptyString(ev.attemptId) &&
143
+ isNonEmptyString(ev.taskId) &&
144
+ isNonEmptyString(ev.toolId) &&
145
+ isNonEmptyString(ev.clusterId) &&
146
+ isNonEmptyString(ev.executorId) &&
147
+ isNonEmptyString(ev.scopeId) &&
148
+ isNonEmptyString(ev.classId) &&
149
+ isNonEmptyString(ev.expectedScopeHash)
150
+ ? null
151
+ : 'SCHEMA_INVALID';
152
+ case 'SubmitBatch':
153
+ return isNonEmptyString(ev.attemptId) &&
154
+ isNonEmptyString(ev.executorId) &&
155
+ isNonEmptyString(ev.leaseId) &&
156
+ isNonNegSafeInt(ev.leaseEpoch) &&
157
+ isNonEmptyString(ev.expectedScopeHash) &&
158
+ Array.isArray(ev.ops) &&
159
+ ev.ops.length > 0 &&
160
+ ev.ops.every(isValidStateOp) &&
161
+ ev.snapshot &&
162
+ isNonEmptyString(ev.snapshot.hash) &&
163
+ isOptionalNonNegSafeInt(ev.budgetCpuMs) &&
164
+ isOptionalNonNegSafeInt(ev.costEstimateMicroUnits) &&
165
+ (ev.snapshot.confidence === 'exact' ||
166
+ ev.snapshot.confidence === 'partial' ||
167
+ ev.snapshot.confidence === 'unknown')
168
+ ? null
169
+ : 'SCHEMA_INVALID';
170
+ case 'WitnessVerdict':
171
+ return isNonEmptyString(ev.attemptId) &&
172
+ isNonEmptyString(ev.verifyId) &&
173
+ isNonEmptyString(ev.scopeHash) &&
174
+ isNonEmptyString(ev.inputSnapshotHash) &&
175
+ isNonNegSafeInt(ev.epoch) &&
176
+ isNonNegSafeInt(ev.cpuMs) &&
177
+ typeof ev.nearMissPassed === 'boolean' &&
178
+ (ev.verdict === 'PASS' || ev.verdict === 'FAIL' || ev.verdict === 'UNKNOWN')
179
+ ? null
180
+ : 'SCHEMA_INVALID';
181
+ case 'GrantApproval':
182
+ return ev.approval &&
183
+ isNonEmptyString(ev.approval.approvalId) &&
184
+ isNonEmptyString(ev.approval.humanId) &&
185
+ isNonEmptyString(ev.approval.attemptId) &&
186
+ ev.approval.singleUse === true &&
187
+ isNonNegSafeInt(ev.approval.expiresAtMs) &&
188
+ ev.approval.binding &&
189
+ isNonEmptyString(ev.approval.binding.diffHash) &&
190
+ isNonEmptyString(ev.approval.binding.scopeHash) &&
191
+ isNonEmptyString(ev.approval.binding.inputSnapshotHash)
192
+ ? null
193
+ : 'SCHEMA_INVALID';
194
+ case 'FinalizeBatch':
195
+ return isNonEmptyString(ev.attemptId) ? null : 'SCHEMA_INVALID';
196
+ case 'CancelAttempt':
197
+ return isNonEmptyString(ev.attemptId) && isNonEmptyString(ev.reason) ? null : 'SCHEMA_INVALID';
198
+ case 'EffectTransition':
199
+ return isNonEmptyString(ev.effectId) && isNonEmptyString(ev.outcome) ? null : 'SCHEMA_INVALID';
200
+ case 'OriginUndo':
201
+ return isNonEmptyString(ev.batchId) &&
202
+ isNonEmptyString(ev.scopeId) &&
203
+ isNonEmptyString(ev.reason) &&
204
+ (ev.compensationPolicy === undefined ||
205
+ ev.compensationPolicy === 'ABORT_ON_CONFLICT' ||
206
+ ev.compensationPolicy === 'COMPENSATE_ONLY_IF_ALL_REVERTED' ||
207
+ ev.compensationPolicy === 'FORCE_COMPENSATE')
208
+ ? null
209
+ : 'SCHEMA_INVALID';
210
+ case 'RuntimeBudgetReported':
211
+ return isNonEmptyString(ev.scopeId) && isNonNegSafeInt(ev.cpuMs) && isNonNegSafeInt(ev.costMicroUnits)
212
+ ? null
213
+ : 'SCHEMA_INVALID';
214
+ default:
215
+ return 'SCHEMA_INVALID';
216
+ }
217
+ }
218
+ /**
219
+ * Validates safe bounds of the fields in a PolicyUpdated event.
220
+ */
221
+ export function validatePolicyBounds(policy) {
222
+ if (policy.schemaVersion !== undefined && !isPosSafeInt(policy.schemaVersion))
223
+ return 'INVALID_POLICY_BOUNDS';
224
+ if (policy.maxAttempts !== undefined && !isPosSafeInt(policy.maxAttempts))
225
+ return 'INVALID_POLICY_BOUNDS';
226
+ if (policy.maxFailStreak !== undefined && !isPosSafeInt(policy.maxFailStreak))
227
+ return 'INVALID_POLICY_BOUNDS';
228
+ if (policy.maxConflictStreak !== undefined && !isPosSafeInt(policy.maxConflictStreak))
229
+ return 'INVALID_POLICY_BOUNDS';
230
+ if (policy.maxCpuMs !== undefined && !isPosSafeInt(policy.maxCpuMs))
231
+ return 'INVALID_POLICY_BOUNDS';
232
+ if (policy.maxCostMicroUnits !== undefined && !isNonNegSafeInt(policy.maxCostMicroUnits))
233
+ return 'INVALID_POLICY_BOUNDS';
234
+ if (policy.maxReconcileAttempts !== undefined && !isPosSafeInt(policy.maxReconcileAttempts))
235
+ return 'INVALID_POLICY_BOUNDS';
236
+ if (policy.undoWindowTtlMs !== undefined && !isNonNegSafeInt(policy.undoWindowTtlMs))
237
+ return 'INVALID_POLICY_BOUNDS';
238
+ if (policy.defaultLeaseTtlMs !== undefined && !isPosSafeInt(policy.defaultLeaseTtlMs))
239
+ return 'INVALID_POLICY_BOUNDS';
240
+ if (policy.maxConcurrentPerScope !== undefined && !isPosSafeInt(policy.maxConcurrentPerScope))
241
+ return 'INVALID_POLICY_BOUNDS';
242
+ if (policy.minImprovementMicroUnits !== undefined && !isNonNegSafeInt(policy.minImprovementMicroUnits))
243
+ return 'INVALID_POLICY_BOUNDS';
244
+ if (policy.maxEventBytes !== undefined && (!isPosSafeInt(policy.maxEventBytes) || policy.maxEventBytes < 1024)) {
245
+ return 'INVALID_POLICY_BOUNDS';
246
+ }
247
+ if (policy.resourcePoolCapacity !== undefined) {
248
+ const cap = policy.resourcePoolCapacity;
249
+ if (!isNonNegSafeInt(cap.inferenceSlots) ||
250
+ !isNonNegSafeInt(cap.witnessSlots) ||
251
+ !isNonNegSafeInt(cap.mutationSlots)) {
252
+ return 'INVALID_POLICY_BOUNDS';
253
+ }
254
+ }
255
+ if (policy.requiredWitnessStages !== undefined) {
256
+ if (!Array.isArray(policy.requiredWitnessStages) || policy.requiredWitnessStages.length === 0) {
257
+ return 'INVALID_POLICY_BOUNDS';
258
+ }
259
+ for (const s of policy.requiredWitnessStages) {
260
+ if (!VALID_STAGES.has(s))
261
+ return 'INVALID_POLICY_BOUNDS';
262
+ }
263
+ }
264
+ return null;
265
+ }
266
+ export function eventScopeAndClass(state, ev) {
267
+ switch (ev.kind) {
268
+ case 'HumanEdit':
269
+ case 'AcquireLease':
270
+ case 'OpenAttempt':
271
+ return { scopeId: ev.scopeId, classId: ev.classId };
272
+ case 'SetPin':
273
+ return { scopeId: ev.pin.scopeId, classId: ev.pin.classId };
274
+ case 'RemovePin':
275
+ case 'HumanHalt':
276
+ case 'HumanResume':
277
+ case 'HumanReset':
278
+ case 'OriginUndo':
279
+ case 'ExpireUndoWindow':
280
+ case 'RuntimeBudgetReported':
281
+ return { scopeId: ev.scopeId, classId: '*' };
282
+ case 'PolicyUpdated':
283
+ return { scopeId: ev.scopeId ?? '*', classId: '*' };
284
+ case 'RenewLease':
285
+ case 'ReleaseLease': {
286
+ const l = state.leases.find((x) => x.leaseId === ev.leaseId);
287
+ return l ? { scopeId: l.scopeId, classId: l.classId } : { scopeId: '*', classId: '*' };
288
+ }
289
+ case 'SubmitBatch':
290
+ case 'WitnessVerdict':
291
+ case 'FinalizeBatch':
292
+ case 'CancelAttempt': {
293
+ const a = state.activeAttempts.find((x) => x.attemptId === ev.attemptId);
294
+ return a ? { scopeId: a.scopeId, classId: a.classId } : { scopeId: '*', classId: '*' };
295
+ }
296
+ case 'GrantApproval': {
297
+ const a = state.activeAttempts.find((x) => x.attemptId === ev.approval.attemptId);
298
+ return a ? { scopeId: a.scopeId, classId: a.classId } : { scopeId: '*', classId: '*' };
299
+ }
300
+ case 'EffectTransition': {
301
+ const e = state.effects.find((x) => x.effectId === ev.effectId);
302
+ if (!e)
303
+ return { scopeId: '*', classId: '*' };
304
+ return { scopeId: e.scopeId, classId: e.classId };
305
+ }
306
+ }
307
+ }
@@ -0,0 +1,34 @@
1
+ import type { ClusterRecord, DeterministicHooks, EventEnvelope, KernelEvent, KernelState, OptimizationVector, StepResult, ToolAutonomyStatus, ToolClusterStats, WitnessStage } from './types.ts';
2
+ /**
3
+ * Epoch that the witness echoes in `WitnessVerdict.epoch`: the scope epoch stored in the pending verification.
4
+ * Returns null when the attempt is not waiting for a verdict.
5
+ */
6
+ export declare function pendingVerifyEpoch(state: KernelState, attemptId: string): number | null;
7
+ export declare function computeVerifyId(attemptId: string, epoch: number, scopeHash: string, stage: WitnessStage): string;
8
+ export declare function checkOptimizationDominance(opt: OptimizationVector, minImprovement: number): {
9
+ ok: true;
10
+ escalateCost: boolean;
11
+ } | {
12
+ ok: false;
13
+ reason: string;
14
+ };
15
+ /**
16
+ * Records a cluster outcome in the bounded window of recent clusters and in the per-tool counters.
17
+ * When a cluster changes its outcome, the changed record always moves to the end of the returned array.
18
+ */
19
+ export declare function recordClusterOutcome(state: KernelState, toolId: string, clusterId: string, outcome: 'CLEAN' | 'VIOLATION', seq: number, hooks?: DeterministicHooks): {
20
+ readonly clusters: readonly ClusterRecord[];
21
+ readonly toolClusterStats: Readonly<Record<string, ToolClusterStats>>;
22
+ };
23
+ /**
24
+ * Marks a cluster as poisoned on a KernelState. Helper for callers outside the kernel.
25
+ */
26
+ export declare function markClusterViolation(state: KernelState, toolId: string, clusterId: string, hooks?: DeterministicHooks): KernelState;
27
+ /**
28
+ * Computes the autonomy tier of a tool: Shadow -> n=59 Approval -> n=299 Auto
29
+ * with an immediate downgrade to SHADOW when a violation is found.
30
+ */
31
+ export declare function computeToolAutonomy(state: KernelState, toolId: string): ToolAutonomyStatus;
32
+ export declare function handleWitnessVerdict(prevState: KernelState, stateAfterRedact: KernelState, cleanEnvelope: EventEnvelope, payloadHash: string, ev: Extract<KernelEvent, {
33
+ kind: 'WitnessVerdict';
34
+ }>, hooks?: DeterministicHooks): StepResult;