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.
Files changed (73) hide show
  1. package/.claude-plugin/plugin.json +11 -0
  2. package/CHANGELOG.md +56 -0
  3. package/LICENSE +21 -0
  4. package/README.md +289 -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 +77 -0
  11. package/dist/adapters/commands.js +209 -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 +88 -0
  15. package/dist/adapters/file-watcher.js +297 -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 +465 -0
  22. package/dist/adapters/operator-auth.d.ts +53 -0
  23. package/dist/adapters/operator-auth.js +81 -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 +384 -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 +72 -0
  57. package/dist/mcp/server.js +549 -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 +214 -0
  67. package/dist/runtime/store.js +788 -0
  68. package/package.json +91 -4
  69. package/presets/exchange-firewall.json +41 -0
  70. package/presets/sdk.json +32 -0
  71. package/presets/solver.json +23 -0
  72. package/presets/vibeops.json +35 -0
  73. package/skills/certal/SKILL.md +49 -0
@@ -0,0 +1,35 @@
1
+ export type SignatureAlgorithm = 'HMAC-SHA256' | 'Ed25519';
2
+ export interface ApprovalSignaturePayload {
3
+ readonly approvalId: string;
4
+ readonly humanId: string;
5
+ readonly attemptId: string;
6
+ readonly bindingHash: string;
7
+ readonly expiresAtMs: number;
8
+ readonly singleUse: true;
9
+ }
10
+ export interface SignatureVerificationInput {
11
+ readonly algorithm: SignatureAlgorithm;
12
+ readonly keyId: string;
13
+ readonly signature: string;
14
+ readonly payload: ApprovalSignaturePayload;
15
+ }
16
+ export interface SignatureVerifier {
17
+ verifyApprovalSignature(input: SignatureVerificationInput): boolean;
18
+ }
19
+ export interface KeyringConfig {
20
+ readonly hmacSecrets?: Readonly<Record<string, string>>;
21
+ readonly ed25519PublicKeysPem?: Readonly<Record<string, string>>;
22
+ }
23
+ /**
24
+ * Builds a deterministic verifier for approval signatures (HMAC-SHA256 and Ed25519).
25
+ */
26
+ export declare function createKeyringSignatureVerifier(keyring: KeyringConfig): SignatureVerifier;
27
+ /**
28
+ * Signs an approval token with an HMAC-SHA256 key. For use outside the kernel and in tests.
29
+ */
30
+ export declare function signApprovalHmac(secret: string, payload: ApprovalSignaturePayload): string;
31
+ /**
32
+ * Signs an approval token with an Ed25519 private key in PEM format. Returns base64.
33
+ */
34
+ export declare function signApprovalEd25519(privateKeyPem: string, payload: ApprovalSignaturePayload): string;
35
+ export declare function hashBinding(diffHash: string, scopeHash: string, inputSnapshotHash: string): string;
@@ -0,0 +1,54 @@
1
+ import { createHmac, sign, timingSafeEqual, verify } from 'node:crypto';
2
+ import { hashCanonical, jcs } from './jcs.js';
3
+ function approvalSignaturePreimage(payload) {
4
+ return Buffer.from(`certal:v1:approval_sig:1\0${jcs(payload)}`, 'utf8');
5
+ }
6
+ /**
7
+ * Builds a deterministic verifier for approval signatures (HMAC-SHA256 and Ed25519).
8
+ */
9
+ export function createKeyringSignatureVerifier(keyring) {
10
+ return {
11
+ verifyApprovalSignature(input) {
12
+ const message = approvalSignaturePreimage(input.payload);
13
+ if (input.algorithm === 'HMAC-SHA256') {
14
+ const secret = keyring.hmacSecrets?.[input.keyId];
15
+ if (!secret)
16
+ return false;
17
+ const expected = createHmac('sha256', secret).update(message).digest('hex');
18
+ const actualBuf = Buffer.from(input.signature, 'utf8');
19
+ const expectedBuf = Buffer.from(expected, 'utf8');
20
+ if (actualBuf.length !== expectedBuf.length)
21
+ return false;
22
+ return timingSafeEqual(actualBuf, expectedBuf);
23
+ }
24
+ if (input.algorithm === 'Ed25519') {
25
+ const pem = keyring.ed25519PublicKeysPem?.[input.keyId];
26
+ if (!pem)
27
+ return false;
28
+ try {
29
+ const sigBuf = Buffer.from(input.signature, 'base64');
30
+ return verify(null, message, pem, sigBuf);
31
+ }
32
+ catch {
33
+ return false;
34
+ }
35
+ }
36
+ return false;
37
+ },
38
+ };
39
+ }
40
+ /**
41
+ * Signs an approval token with an HMAC-SHA256 key. For use outside the kernel and in tests.
42
+ */
43
+ export function signApprovalHmac(secret, payload) {
44
+ return createHmac('sha256', secret).update(approvalSignaturePreimage(payload)).digest('hex');
45
+ }
46
+ /**
47
+ * Signs an approval token with an Ed25519 private key in PEM format. Returns base64.
48
+ */
49
+ export function signApprovalEd25519(privateKeyPem, payload) {
50
+ return sign(null, approvalSignaturePreimage(payload), privateKeyPem).toString('base64');
51
+ }
52
+ export function hashBinding(diffHash, scopeHash, inputSnapshotHash) {
53
+ return hashCanonical('binding', 1, { diffHash, scopeHash, inputSnapshotHash });
54
+ }
@@ -0,0 +1,4 @@
1
+ import type { EventEnvelope, KernelEvent, KernelState, StepResult } from './types.ts';
2
+ export declare function handleEffectTransition(prevState: KernelState, stateAfterRedact: KernelState, cleanEnvelope: EventEnvelope, payloadHash: string, ev: Extract<KernelEvent, {
3
+ kind: 'EffectTransition';
4
+ }>): StepResult;
@@ -0,0 +1,178 @@
1
+ import { EMPTY_SNAPSHOT_HASH, commitEntry, pauseUnlessHalted, recordFailStreak, replaceEffect, } from './common.js';
2
+ import { hashCanonical } from './jcs.js';
3
+ export function handleEffectTransition(prevState, stateAfterRedact, cleanEnvelope, payloadHash, ev) {
4
+ if (cleanEnvelope.auth.origin.kind !== 'System') {
5
+ const { nextState, decision } = recordFailStreak(stateAfterRedact, 'FORBIDDEN_ORIGIN');
6
+ return commitEntry(prevState, nextState, cleanEnvelope, payloadHash, false, decision, [], '*', '*', null, EMPTY_SNAPSHOT_HASH);
7
+ }
8
+ const eff = prevState.effects.find((e) => e.effectId === ev.effectId);
9
+ if (!eff) {
10
+ return commitEntry(prevState, stateAfterRedact, cleanEnvelope, payloadHash, false, { code: 'REJECT', reason: 'EFFECT_NOT_FOUND' }, [], '*', '*', null, EMPTY_SNAPSHOT_HASH);
11
+ }
12
+ const effScope = eff.scopeId;
13
+ const effClass = eff.classId;
14
+ if (ev.outcome === 'EXPIRED_BEFORE_SEND') {
15
+ if (eff.status !== 'INTENT' && eff.status !== 'COMP_INTENT') {
16
+ return commitEntry(prevState, stateAfterRedact, cleanEnvelope, payloadHash, false, { code: 'REJECT', reason: 'INVALID_EFFECT_TRANSITION' }, [], effScope, effClass, eff.binding.diffHash, eff.binding.inputSnapshotHash);
17
+ }
18
+ const nextStatus = eff.compensating ? 'COMP_FAILED' : 'ABORTED_EXPIRED';
19
+ const nextEffects = replaceEffect(prevState.effects, { ...eff, status: nextStatus });
20
+ const nextState = { ...stateAfterRedact, effects: nextEffects };
21
+ return commitEntry(prevState, nextState, cleanEnvelope, payloadHash, true, { code: 'REJECT', reason: ev.reason ?? 'APPROVAL_EXPIRED_BEFORE_SEND' }, [], effScope, effClass, eff.binding.diffHash, eff.binding.inputSnapshotHash);
22
+ }
23
+ if (ev.outcome === 'IN_FLIGHT') {
24
+ if (eff.status !== 'INTENT' && eff.status !== 'COMP_INTENT') {
25
+ return commitEntry(prevState, stateAfterRedact, cleanEnvelope, payloadHash, false, { code: 'REJECT', reason: 'INVALID_EFFECT_TRANSITION' }, [], effScope, effClass, eff.binding.diffHash, eff.binding.inputSnapshotHash);
26
+ }
27
+ if (!eff.compensating && eff.approvalExpiresAtMs !== null && cleanEnvelope.nowMs > eff.approvalExpiresAtMs) {
28
+ const nextEffects = replaceEffect(prevState.effects, { ...eff, status: 'ABORTED_EXPIRED' });
29
+ const nextState = { ...stateAfterRedact, effects: nextEffects };
30
+ return commitEntry(prevState, nextState, cleanEnvelope, payloadHash, true, { code: 'REJECT', reason: 'APPROVAL_EXPIRED_BEFORE_SEND' }, [], effScope, effClass, eff.binding.diffHash, eff.binding.inputSnapshotHash);
31
+ }
32
+ const nextStatus = eff.compensating ? 'COMP_IN_FLIGHT' : 'IN_FLIGHT';
33
+ const nextState = {
34
+ ...stateAfterRedact,
35
+ effects: replaceEffect(prevState.effects, { ...eff, status: nextStatus }),
36
+ };
37
+ return commitEntry(prevState, nextState, cleanEnvelope, payloadHash, true, { code: 'ALLOW', reason: 'EFFECT_IN_FLIGHT' }, [], effScope, effClass, eff.binding.diffHash, eff.binding.inputSnapshotHash);
38
+ }
39
+ if (ev.outcome === 'UNKNOWN') {
40
+ const canRecoverIntent = ev.recoveredFromCrash === true &&
41
+ (eff.compensating ? eff.status === 'COMP_INTENT' : eff.status === 'INTENT');
42
+ const validStates = canRecoverIntent ||
43
+ (eff.compensating
44
+ ? eff.status === 'COMP_IN_FLIGHT' || eff.status === 'COMP_UNKNOWN'
45
+ : eff.status === 'IN_FLIGHT' || eff.status === 'UNKNOWN');
46
+ if (!validStates) {
47
+ return commitEntry(prevState, stateAfterRedact, cleanEnvelope, payloadHash, false, { code: 'REJECT', reason: 'INVALID_EFFECT_TRANSITION' }, [], effScope, effClass, eff.binding.diffHash, eff.binding.inputSnapshotHash);
48
+ }
49
+ const nextCount = eff.reconcileCount + 1;
50
+ const exhausted = nextCount > prevState.policy.maxReconcileAttempts;
51
+ const nextStatus = exhausted
52
+ ? 'RECONCILE_EXHAUSTED'
53
+ : eff.compensating
54
+ ? 'COMP_UNKNOWN'
55
+ : 'UNKNOWN';
56
+ const nextEffects = replaceEffect(prevState.effects, {
57
+ ...eff,
58
+ status: nextStatus,
59
+ reconcileCount: nextCount,
60
+ });
61
+ if (exhausted) {
62
+ const haltedState = {
63
+ ...stateAfterRedact,
64
+ effects: nextEffects,
65
+ taskStatus: 'HALTED',
66
+ haltReason: 'RECONCILE_EXHAUSTED',
67
+ };
68
+ return commitEntry(prevState, haltedState, cleanEnvelope, payloadHash, true, { code: 'HALT', reason: 'RECONCILE_EXHAUSTED' }, [], effScope, effClass, eff.binding.diffHash, eff.binding.inputSnapshotHash);
69
+ }
70
+ const nextState = { ...stateAfterRedact, effects: nextEffects };
71
+ const reconcileIntent = {
72
+ kind: 'Reconcile',
73
+ effectId: eff.effectId,
74
+ recipientId: eff.recipientId,
75
+ attemptNumber: nextCount,
76
+ };
77
+ return commitEntry(prevState, nextState, cleanEnvelope, payloadHash, true, { code: 'ALLOW', reason: 'EFFECT_UNKNOWN_RECONCILE' }, [reconcileIntent], effScope, effClass, eff.binding.diffHash, eff.binding.inputSnapshotHash);
78
+ }
79
+ if (ev.outcome === 'APPLIED') {
80
+ const validStates = eff.compensating
81
+ ? eff.status === 'COMP_IN_FLIGHT' || eff.status === 'COMP_UNKNOWN'
82
+ : eff.status === 'IN_FLIGHT' || eff.status === 'UNKNOWN';
83
+ if (!validStates) {
84
+ return commitEntry(prevState, stateAfterRedact, cleanEnvelope, payloadHash, false, { code: 'REJECT', reason: 'INVALID_EFFECT_TRANSITION' }, [], effScope, effClass, eff.binding.diffHash, eff.binding.inputSnapshotHash);
85
+ }
86
+ const nextStatus = eff.compensating ? 'COMPENSATED' : 'APPLIED';
87
+ const nextState = {
88
+ ...stateAfterRedact,
89
+ effects: replaceEffect(prevState.effects, { ...eff, status: nextStatus }),
90
+ };
91
+ return commitEntry(prevState, nextState, cleanEnvelope, payloadHash, true, { code: 'ALLOW', reason: eff.compensating ? 'COMPENSATION_APPLIED' : 'EFFECT_APPLIED' }, [], effScope, effClass, eff.binding.diffHash, eff.binding.inputSnapshotHash);
92
+ }
93
+ if (ev.outcome === 'REFUSED') {
94
+ const validStates = eff.compensating
95
+ ? eff.status === 'COMP_IN_FLIGHT' || eff.status === 'COMP_UNKNOWN'
96
+ : eff.status === 'IN_FLIGHT' || eff.status === 'UNKNOWN';
97
+ if (!validStates) {
98
+ return commitEntry(prevState, stateAfterRedact, cleanEnvelope, payloadHash, false, { code: 'REJECT', reason: 'INVALID_EFFECT_TRANSITION' }, [], effScope, effClass, eff.binding.diffHash, eff.binding.inputSnapshotHash);
99
+ }
100
+ if (eff.compensating) {
101
+ const nextStatus = pauseUnlessHalted(prevState.taskStatus);
102
+ const nextState = {
103
+ ...stateAfterRedact,
104
+ taskStatus: nextStatus,
105
+ pauseReason: nextStatus === 'PAUSED' ? 'COMPENSATION_FAILED' : prevState.pauseReason,
106
+ effects: replaceEffect(prevState.effects, { ...eff, status: 'COMP_FAILED' }),
107
+ };
108
+ return commitEntry(prevState, nextState, cleanEnvelope, payloadHash, true, nextStatus === 'HALTED'
109
+ ? { code: 'HALT', reason: prevState.haltReason ?? 'COMPENSATION_FAILED' }
110
+ : { code: 'PAUSE', reason: 'COMPENSATION_FAILED' }, [], effScope, effClass, eff.binding.diffHash, eff.binding.inputSnapshotHash);
111
+ }
112
+ let nextEffects = replaceEffect(prevState.effects, { ...eff, status: 'DELIVERY_FAILED' });
113
+ const appliedPrefix = nextEffects
114
+ .filter((e) => e.batchId === eff.batchId &&
115
+ !e.compensating &&
116
+ e.status === 'APPLIED' &&
117
+ e.orderIndex < eff.orderIndex)
118
+ .sort((a, b) => b.orderIndex - a.orderIndex);
119
+ const compIntents = [];
120
+ let requiresManual = false;
121
+ for (const prevEff of appliedPrefix) {
122
+ if (!prevEff.supportsCas) {
123
+ requiresManual = true;
124
+ nextEffects = replaceEffect(nextEffects, {
125
+ ...prevEff,
126
+ status: 'MANUAL_COMPENSATION_REQUIRED',
127
+ });
128
+ }
129
+ else {
130
+ const compId = hashCanonical('comp_effect', 1, { originalEffectId: prevEff.effectId });
131
+ const compRec = {
132
+ effectId: compId,
133
+ batchId: prevEff.batchId,
134
+ attemptId: prevEff.attemptId,
135
+ scopeId: prevEff.scopeId,
136
+ classId: prevEff.classId,
137
+ effectKey: `${prevEff.effectKey}/comp`,
138
+ recipientId: prevEff.recipientId,
139
+ supportsCas: prevEff.supportsCas,
140
+ actionPayload: prevEff.inversePayload,
141
+ inversePayload: null,
142
+ binding: prevEff.binding,
143
+ approvalId: null,
144
+ approvalExpiresAtMs: null,
145
+ status: 'COMP_INTENT',
146
+ reconcileCount: 0,
147
+ orderIndex: prevEff.orderIndex,
148
+ compensating: true,
149
+ originalEffectId: prevEff.effectId,
150
+ };
151
+ nextEffects = [...nextEffects, compRec];
152
+ compIntents.push({
153
+ kind: 'Compensate',
154
+ compensationId: compId,
155
+ originalEffectId: prevEff.effectId,
156
+ recipientId: prevEff.recipientId,
157
+ supportsCas: prevEff.supportsCas,
158
+ inversePayload: prevEff.inversePayload,
159
+ });
160
+ }
161
+ }
162
+ const nextTaskStatus = requiresManual ? pauseUnlessHalted(prevState.taskStatus) : prevState.taskStatus;
163
+ const nextState = {
164
+ ...stateAfterRedact,
165
+ effects: nextEffects,
166
+ taskStatus: nextTaskStatus,
167
+ pauseReason: requiresManual && nextTaskStatus === 'PAUSED'
168
+ ? 'MANUAL_COMPENSATION_REQUIRED'
169
+ : prevState.pauseReason,
170
+ };
171
+ return commitEntry(prevState, nextState, cleanEnvelope, payloadHash, true, requiresManual
172
+ ? nextTaskStatus === 'HALTED'
173
+ ? { code: 'HALT', reason: prevState.haltReason ?? 'MANUAL_COMPENSATION_REQUIRED' }
174
+ : { code: 'PAUSE', reason: 'MANUAL_COMPENSATION_REQUIRED' }
175
+ : { code: 'REJECT', reason: 'RECEIVER_REFUSED' }, compIntents, effScope, effClass, eff.binding.diffHash, eff.binding.inputSnapshotHash);
176
+ }
177
+ return commitEntry(prevState, stateAfterRedact, cleanEnvelope, payloadHash, false, { code: 'REJECT', reason: 'INVALID_EFFECT_OUTCOME' }, [], effScope, effClass, eff.binding.diffHash, eff.binding.inputSnapshotHash);
178
+ }
@@ -0,0 +1,9 @@
1
+ export * from './types.ts';
2
+ export * from './jcs.ts';
3
+ export * from './crypto.ts';
4
+ export * from './validation.ts';
5
+ export * from './leases.ts';
6
+ export * from './witness.ts';
7
+ export * from './effects.ts';
8
+ export * from './undo.ts';
9
+ export * from './step.ts';
@@ -0,0 +1,9 @@
1
+ export * from './types.js';
2
+ export * from './jcs.js';
3
+ export * from './crypto.js';
4
+ export * from './validation.js';
5
+ export * from './leases.js';
6
+ export * from './witness.js';
7
+ export * from './effects.js';
8
+ export * from './undo.js';
9
+ export * from './step.js';
@@ -0,0 +1,24 @@
1
+ export declare const HASH_ALG: 'sha256-jcs-v1';
2
+ export type HashAlgorithm = typeof HASH_ALG;
3
+ /**
4
+ * Compares two strings by UTF-16 code units, as RFC 8785 (JCS) requires.
5
+ */
6
+ export declare function compareUtf16(a: string, b: string): number;
7
+ /**
8
+ * Single-pass RFC 8785 (JCS) serialization. It does not clone objects
9
+ * and sorts keys once. It rejects floating-point numbers.
10
+ */
11
+ export declare function jcs(value: unknown): string;
12
+ /**
13
+ * Computes a SHA-256 hash with domain separation and a schema version:
14
+ * SHA-256("certal:v1:" + domain + ":" + schemaVersion + "\0" + JCS(payload))
15
+ */
16
+ export declare function hashCanonical(domain: string, schemaVersion: number, payload: unknown): string;
17
+ /**
18
+ * Deep-freezes an object so tests can prove that the kernel does not mutate its input.
19
+ */
20
+ export declare function deepFreeze<T>(value: T): T;
21
+ /**
22
+ * Sorts a copy of the array by a deterministic string key.
23
+ */
24
+ export declare function sortDeterministically<T>(items: readonly T[], keyOf: (item: T) => string): readonly T[];
@@ -0,0 +1,93 @@
1
+ import { createHash } from 'node:crypto';
2
+ export const HASH_ALG = 'sha256-jcs-v1';
3
+ /**
4
+ * Compares two strings by UTF-16 code units, as RFC 8785 (JCS) requires.
5
+ */
6
+ export function compareUtf16(a, b) {
7
+ if (a < b)
8
+ return -1;
9
+ if (a > b)
10
+ return 1;
11
+ return 0;
12
+ }
13
+ /**
14
+ * Single-pass RFC 8785 (JCS) serialization. It does not clone objects
15
+ * and sorts keys once. It rejects floating-point numbers.
16
+ */
17
+ export function jcs(value) {
18
+ if (value === null || typeof value === 'boolean' || typeof value === 'string') {
19
+ return JSON.stringify(value);
20
+ }
21
+ if (typeof value === 'number') {
22
+ if (!Number.isFinite(value) || !Number.isInteger(value) || !Number.isSafeInteger(value)) {
23
+ throw new Error(`FLOAT_NOT_ALLOWED_IN_HASH: number not allowed: ${String(value)}`);
24
+ }
25
+ return Object.is(value, -0) ? '0' : String(value);
26
+ }
27
+ if (typeof value === 'bigint') {
28
+ return JSON.stringify(value.toString(10));
29
+ }
30
+ if (Array.isArray(value)) {
31
+ const parts = [];
32
+ for (let i = 0; i < value.length; i += 1) {
33
+ const item = value[i];
34
+ parts.push(item === undefined ? 'null' : jcs(item));
35
+ }
36
+ return `[${parts.join(',')}]`;
37
+ }
38
+ if (typeof value === 'object') {
39
+ const record = value;
40
+ const keys = Object.keys(record).sort(compareUtf16);
41
+ const parts = [];
42
+ for (let i = 0; i < keys.length; i += 1) {
43
+ const key = keys[i];
44
+ const prop = record[key];
45
+ if (prop !== undefined) {
46
+ parts.push(`${JSON.stringify(key)}:${jcs(prop)}`);
47
+ }
48
+ }
49
+ return `{${parts.join(',')}}`;
50
+ }
51
+ throw new Error(`UNSUPPORTED_JCS_TYPE: unsupported type ${typeof value}`);
52
+ }
53
+ /**
54
+ * Computes a SHA-256 hash with domain separation and a schema version:
55
+ * SHA-256("certal:v1:" + domain + ":" + schemaVersion + "\0" + JCS(payload))
56
+ */
57
+ export function hashCanonical(domain, schemaVersion, payload) {
58
+ if (!Number.isInteger(schemaVersion) || schemaVersion < 1) {
59
+ throw new Error(`INVALID_SCHEMA_VERSION: ${String(schemaVersion)}`);
60
+ }
61
+ const canonical = jcs(payload);
62
+ const preimage = `certal:v1:${domain}:${schemaVersion}\0${canonical}`;
63
+ return createHash('sha256').update(preimage, 'utf8').digest('hex');
64
+ }
65
+ /**
66
+ * Deep-freezes an object so tests can prove that the kernel does not mutate its input.
67
+ */
68
+ export function deepFreeze(value) {
69
+ if (value === null || typeof value !== 'object') {
70
+ return value;
71
+ }
72
+ if (!Object.isFrozen(value)) {
73
+ Object.freeze(value);
74
+ }
75
+ if (Array.isArray(value)) {
76
+ for (let i = 0; i < value.length; i += 1) {
77
+ deepFreeze(value[i]);
78
+ }
79
+ }
80
+ else {
81
+ const record = value;
82
+ for (const key of Object.keys(record)) {
83
+ deepFreeze(record[key]);
84
+ }
85
+ }
86
+ return value;
87
+ }
88
+ /**
89
+ * Sorts a copy of the array by a deterministic string key.
90
+ */
91
+ export function sortDeterministically(items, keyOf) {
92
+ return [...items].sort((a, b) => compareUtf16(keyOf(a), keyOf(b)));
93
+ }
@@ -0,0 +1,11 @@
1
+ import type { EventEnvelope, KernelEvent, KernelState, Lease2D, ResourceUnits, StepResult } from './types.ts';
2
+ export declare function usedResourceUnits(leases: readonly Lease2D[]): ResourceUnits;
3
+ export declare function handleAcquireLease(prevState: KernelState, stateAfterRedact: KernelState, cleanEnvelope: EventEnvelope, payloadHash: string, ev: Extract<KernelEvent, {
4
+ kind: 'AcquireLease';
5
+ }>): StepResult;
6
+ export declare function handleRenewLease(prevState: KernelState, stateAfterRedact: KernelState, cleanEnvelope: EventEnvelope, payloadHash: string, ev: Extract<KernelEvent, {
7
+ kind: 'RenewLease';
8
+ }>, scopeId: string, classId: string): StepResult;
9
+ export declare function handleReleaseLease(prevState: KernelState, stateAfterRedact: KernelState, cleanEnvelope: EventEnvelope, payloadHash: string, ev: Extract<KernelEvent, {
10
+ kind: 'ReleaseLease';
11
+ }>, scopeId: string, classId: string): StepResult;
@@ -0,0 +1,86 @@
1
+ import { EMPTY_SNAPSHOT_HASH, activeLeasesAt, commitEntry, leaseMatches, recordConflictStreak, recordFailStreak, } from './common.js';
2
+ import { sortDeterministically } from './jcs.js';
3
+ export function usedResourceUnits(leases) {
4
+ let inferenceSlots = 0;
5
+ let witnessSlots = 0;
6
+ let mutationSlots = 0;
7
+ for (const l of leases) {
8
+ inferenceSlots += l.units.inferenceSlots;
9
+ witnessSlots += l.units.witnessSlots;
10
+ mutationSlots += l.units.mutationSlots;
11
+ }
12
+ return { inferenceSlots, witnessSlots, mutationSlots };
13
+ }
14
+ export function handleAcquireLease(prevState, stateAfterRedact, cleanEnvelope, payloadHash, ev) {
15
+ if (cleanEnvelope.auth.origin.kind !== 'Agent' ||
16
+ cleanEnvelope.auth.origin.attemptId !== ev.attemptId) {
17
+ const { nextState, decision } = recordFailStreak(stateAfterRedact, 'FORBIDDEN_ORIGIN');
18
+ return commitEntry(prevState, nextState, cleanEnvelope, payloadHash, false, decision, [], ev.scopeId, ev.classId, null, EMPTY_SNAPSHOT_HASH);
19
+ }
20
+ const currentLeases = activeLeasesAt(prevState.leases, cleanEnvelope.nowMs);
21
+ const duplicateId = currentLeases.find((l) => l.leaseId === ev.leaseId);
22
+ const colliding = currentLeases.find((l) => leaseMatches(l, ev.scopeId, ev.classId));
23
+ const sameScopeCount = currentLeases.filter((l) => l.scopeId === ev.scopeId).length;
24
+ const used = usedResourceUnits(currentLeases);
25
+ const cap = prevState.policy.resourcePoolCapacity;
26
+ const overCapacity = used.inferenceSlots + ev.units.inferenceSlots > cap.inferenceSlots ||
27
+ used.witnessSlots + ev.units.witnessSlots > cap.witnessSlots ||
28
+ used.mutationSlots + ev.units.mutationSlots > cap.mutationSlots;
29
+ if (duplicateId || colliding || sameScopeCount >= prevState.policy.maxConcurrentPerScope || overCapacity) {
30
+ const { nextState, decision } = recordConflictStreak({ ...stateAfterRedact, leases: currentLeases }, 'LEASE_CONFLICT');
31
+ return commitEntry(prevState, nextState, cleanEnvelope, payloadHash, false, decision, [], ev.scopeId, ev.classId, null, EMPTY_SNAPSHOT_HASH);
32
+ }
33
+ const ttl = ev.ttlMs ?? prevState.policy.defaultLeaseTtlMs;
34
+ const lease = {
35
+ leaseId: ev.leaseId,
36
+ scopeId: ev.scopeId,
37
+ classId: ev.classId,
38
+ ownerId: cleanEnvelope.auth.origin.actorId,
39
+ attemptId: ev.attemptId,
40
+ leaseEpoch: prevState.nextLeaseEpoch,
41
+ expiresAtMs: cleanEnvelope.nowMs + ttl,
42
+ units: ev.units,
43
+ };
44
+ const nextState = {
45
+ ...stateAfterRedact,
46
+ leases: sortDeterministically([...currentLeases, lease], (l) => l.leaseId),
47
+ nextLeaseEpoch: prevState.nextLeaseEpoch + 1,
48
+ };
49
+ return commitEntry(prevState, nextState, cleanEnvelope, payloadHash, true, { code: 'ALLOW', reason: 'LEASE_ACQUIRED' }, [], ev.scopeId, ev.classId, null, EMPTY_SNAPSHOT_HASH);
50
+ }
51
+ export function handleRenewLease(prevState, stateAfterRedact, cleanEnvelope, payloadHash, ev, scopeId, classId) {
52
+ const currentLeases = activeLeasesAt(prevState.leases, cleanEnvelope.nowMs);
53
+ const lease = currentLeases.find((l) => l.leaseId === ev.leaseId);
54
+ if (lease && lease.ownerId !== cleanEnvelope.auth.origin.actorId) {
55
+ const { nextState, decision } = recordFailStreak({ ...stateAfterRedact, leases: currentLeases }, 'FORBIDDEN_LEASE_OWNER');
56
+ return commitEntry(prevState, nextState, cleanEnvelope, payloadHash, false, decision, [], lease.scopeId, lease.classId, null, EMPTY_SNAPSHOT_HASH);
57
+ }
58
+ if (!lease || lease.leaseEpoch !== ev.leaseEpoch) {
59
+ const { nextState, decision } = recordConflictStreak({ ...stateAfterRedact, leases: currentLeases }, 'LEASE_CONFLICT');
60
+ return commitEntry(prevState, nextState, cleanEnvelope, payloadHash, false, decision, [], scopeId, classId, null, EMPTY_SNAPSHOT_HASH);
61
+ }
62
+ const ttl = ev.ttlMs ?? prevState.policy.defaultLeaseTtlMs;
63
+ const renewed = { ...lease, expiresAtMs: cleanEnvelope.nowMs + ttl };
64
+ const nextState = {
65
+ ...stateAfterRedact,
66
+ leases: currentLeases.map((l) => (l.leaseId === lease.leaseId ? renewed : l)),
67
+ };
68
+ return commitEntry(prevState, nextState, cleanEnvelope, payloadHash, true, { code: 'ALLOW', reason: 'LEASE_RENEWED' }, [], lease.scopeId, lease.classId, null, EMPTY_SNAPSHOT_HASH);
69
+ }
70
+ export function handleReleaseLease(prevState, stateAfterRedact, cleanEnvelope, payloadHash, ev, scopeId, classId) {
71
+ const currentLeases = activeLeasesAt(prevState.leases, cleanEnvelope.nowMs);
72
+ const byId = currentLeases.find((l) => l.leaseId === ev.leaseId);
73
+ if (byId && byId.ownerId !== cleanEnvelope.auth.origin.actorId) {
74
+ const { nextState, decision } = recordFailStreak({ ...stateAfterRedact, leases: currentLeases }, 'FORBIDDEN_LEASE_OWNER');
75
+ return commitEntry(prevState, nextState, cleanEnvelope, payloadHash, false, decision, [], byId.scopeId, byId.classId, null, EMPTY_SNAPSHOT_HASH);
76
+ }
77
+ const lease = byId && byId.leaseEpoch === ev.leaseEpoch ? byId : undefined;
78
+ if (!lease) {
79
+ return commitEntry(prevState, { ...stateAfterRedact, leases: currentLeases }, cleanEnvelope, payloadHash, false, { code: 'REJECT', reason: 'LEASE_NOT_FOUND' }, [], scopeId, classId, null, EMPTY_SNAPSHOT_HASH);
80
+ }
81
+ const nextState = {
82
+ ...stateAfterRedact,
83
+ leases: currentLeases.filter((l) => l.leaseId !== ev.leaseId),
84
+ };
85
+ return commitEntry(prevState, nextState, cleanEnvelope, payloadHash, true, { code: 'ALLOW', reason: 'LEASE_RELEASED' }, [], lease.scopeId, lease.classId, null, EMPTY_SNAPSHOT_HASH);
86
+ }
@@ -0,0 +1,10 @@
1
+ import { DEFAULT_POLICY, computePolicyHash, computeScopeHash, scopeEpochOf, slotKey } from './common.ts';
2
+ import type { DeterministicHooks, EventEnvelope, KernelState, PolicyConfig, StepResult } from './types.ts';
3
+ export { DEFAULT_POLICY, computePolicyHash, computeScopeHash, scopeEpochOf, slotKey };
4
+ export declare function createInitialState(policyOverrides?: Partial<PolicyConfig>): KernelState;
5
+ export declare function computeStateHash(state: KernelState): string;
6
+ /**
7
+ * Pure, deterministic transition function of the Certal kernel.
8
+ * No I/O, no Date.now(), no Math.random(), no regular expressions. It never mutates the input state.
9
+ */
10
+ export declare function step(state: KernelState, envelope: EventEnvelope, hooks?: DeterministicHooks): StepResult;