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,297 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
/**
|
|
5
|
+
* Optional watcher that turns a manual file save into a human edit.
|
|
6
|
+
*
|
|
7
|
+
* The slot of a file is `(scope, class, relative path, "sha256")` and holds the hash of the file
|
|
8
|
+
* content. An agent declares the new hash in its batch before it writes the file, so a write that
|
|
9
|
+
* matches the slot is the agent's own. Any other change is reported as a human edit, which raises
|
|
10
|
+
* the scope epoch and evicts a colliding agent lease. A deleted file is reported with the value null.
|
|
11
|
+
*
|
|
12
|
+
* Limit: the watcher cannot tell who wrote a file. A process that writes a file without a batch
|
|
13
|
+
* is treated as the human. Use the watcher only where agents write through the gate.
|
|
14
|
+
*/
|
|
15
|
+
export const FILE_FIELD = 'sha256';
|
|
16
|
+
/** Longest object id that the gate reads. */
|
|
17
|
+
export const MAX_OBJECT_ID_LENGTH = 1024;
|
|
18
|
+
/** Matches one path segment against a segment pattern with `*` and `?`. Linear in practice, never exponential. */
|
|
19
|
+
function matchSegment(pattern, text) {
|
|
20
|
+
let p = 0;
|
|
21
|
+
let t = 0;
|
|
22
|
+
let star = -1;
|
|
23
|
+
let mark = 0;
|
|
24
|
+
while (t < text.length) {
|
|
25
|
+
if (p < pattern.length && (pattern[p] === '?' || pattern[p] === text[t])) {
|
|
26
|
+
p += 1;
|
|
27
|
+
t += 1;
|
|
28
|
+
}
|
|
29
|
+
else if (p < pattern.length && pattern[p] === '*') {
|
|
30
|
+
star = p;
|
|
31
|
+
mark = t;
|
|
32
|
+
p += 1;
|
|
33
|
+
}
|
|
34
|
+
else if (star >= 0) {
|
|
35
|
+
p = star + 1;
|
|
36
|
+
mark += 1;
|
|
37
|
+
t = mark;
|
|
38
|
+
}
|
|
39
|
+
else
|
|
40
|
+
return false;
|
|
41
|
+
}
|
|
42
|
+
while (p < pattern.length && pattern[p] === '*')
|
|
43
|
+
p += 1;
|
|
44
|
+
return p === pattern.length;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Tells whether a `/`-separated path matches a glob pattern. `*` and `?` stay inside one segment,
|
|
48
|
+
* and a segment `**` stands for any number of segments, also none. A pattern without a wildcard
|
|
49
|
+
* names a file or a directory with everything below it.
|
|
50
|
+
*
|
|
51
|
+
* The match ignores letter case on every platform, so `Policies/x.sql` and `policies/x.sql`, which
|
|
52
|
+
* are one file on Windows and macOS, always belong to the same scope. It uses no regular expression:
|
|
53
|
+
* the time grows with the product of the two lengths, so no input can stall it.
|
|
54
|
+
*/
|
|
55
|
+
export function matchGlob(pattern, relativePath) {
|
|
56
|
+
const glob = pattern.toLowerCase();
|
|
57
|
+
const text = relativePath.toLowerCase();
|
|
58
|
+
if (!/[*?]/.test(glob))
|
|
59
|
+
return text === glob || text.startsWith(`${glob}/`);
|
|
60
|
+
const segments = text.split('/');
|
|
61
|
+
// `reach[i]` is true when the pattern read so far matches the first `i` segments of the path.
|
|
62
|
+
let reach = new Array(segments.length + 1).fill(false);
|
|
63
|
+
reach[0] = true;
|
|
64
|
+
for (const part of glob.split('/')) {
|
|
65
|
+
const next = new Array(segments.length + 1).fill(false);
|
|
66
|
+
if (part === '**') {
|
|
67
|
+
let open = false;
|
|
68
|
+
for (let i = 0; i <= segments.length; i += 1) {
|
|
69
|
+
open = open || reach[i] === true;
|
|
70
|
+
next[i] = open;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
else {
|
|
74
|
+
const segmentPattern = part.replace(/\*+/g, '*');
|
|
75
|
+
for (let i = 0; i < segments.length; i += 1) {
|
|
76
|
+
if (reach[i] === true && matchSegment(segmentPattern, segments[i]))
|
|
77
|
+
next[i + 1] = true;
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
reach = next;
|
|
81
|
+
}
|
|
82
|
+
return reach[segments.length] === true;
|
|
83
|
+
}
|
|
84
|
+
/** The reason why a text cannot be a path pattern of a scope, or null. */
|
|
85
|
+
export function patternProblem(pattern) {
|
|
86
|
+
if (pattern === '')
|
|
87
|
+
return 'is empty';
|
|
88
|
+
if (/[{}[\]]/.test(pattern))
|
|
89
|
+
return 'uses "{", "}", "[" or "]", which the matcher does not have; write one pattern per alternative';
|
|
90
|
+
if (pattern.includes('\\'))
|
|
91
|
+
return 'uses "\\"; write "/" between directories';
|
|
92
|
+
if (pattern.startsWith('/') || /^[A-Za-z]:/.test(pattern))
|
|
93
|
+
return 'is absolute; write it relative to the manifest';
|
|
94
|
+
if (pattern.endsWith('/'))
|
|
95
|
+
return `ends with "/"; write "${pattern}**" for everything in the directory`;
|
|
96
|
+
if (pattern.split('/').some((segment) => segment === '..' || segment === '.' || segment === ''))
|
|
97
|
+
return 'has an empty, "." or ".." segment';
|
|
98
|
+
return null;
|
|
99
|
+
}
|
|
100
|
+
/** True for a control character and for a mark that changes the direction of the text around it. */
|
|
101
|
+
function hasUnsafeCharacter(text) {
|
|
102
|
+
for (let i = 0; i < text.length; i += 1) {
|
|
103
|
+
const code = text.charCodeAt(i);
|
|
104
|
+
if (code <= 0x1f || (code >= 0x7f && code <= 0x9f))
|
|
105
|
+
return true;
|
|
106
|
+
if (code === 0x200e || code === 0x200f || (code >= 0x202a && code <= 0x202e) || (code >= 0x2066 && code <= 0x2069))
|
|
107
|
+
return true;
|
|
108
|
+
}
|
|
109
|
+
return false;
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* One spelling for an object id that may be a path: `/` as the separator, no leading `./`, no empty
|
|
113
|
+
* segments, Unicode form NFC. Returns null for an absolute path, for a path with a `..` segment, for
|
|
114
|
+
* an id longer than 1024 characters and for an id with a control or text-direction character, so two
|
|
115
|
+
* spellings can never name the same file, no id can leave the project directory, and an id reads in
|
|
116
|
+
* a log the way it is stored.
|
|
117
|
+
*/
|
|
118
|
+
export function normalizeObjectPath(input) {
|
|
119
|
+
if (typeof input !== 'string' || input === '' || input.length > MAX_OBJECT_ID_LENGTH)
|
|
120
|
+
return null;
|
|
121
|
+
if (hasUnsafeCharacter(input))
|
|
122
|
+
return null;
|
|
123
|
+
const slashed = input.normalize('NFC').replace(/\\/g, '/');
|
|
124
|
+
if (slashed.startsWith('/') || /^[A-Za-z]:(\/|$)/.test(slashed))
|
|
125
|
+
return null;
|
|
126
|
+
const parts = slashed.split('/').filter((segment) => segment !== '' && segment !== '.');
|
|
127
|
+
if (parts.length === 0 || parts.includes('..'))
|
|
128
|
+
return null;
|
|
129
|
+
return parts.join('/');
|
|
130
|
+
}
|
|
131
|
+
/** The directory of a whole-directory pattern: `''` for `**`, `'src/'` for `src/**`. Null for any other pattern. */
|
|
132
|
+
function wholeDirectory(pattern) {
|
|
133
|
+
if (pattern === '**')
|
|
134
|
+
return '';
|
|
135
|
+
// A pattern without a wildcard covers that path and everything below it.
|
|
136
|
+
if (!/[*?]/.test(pattern))
|
|
137
|
+
return `${pattern.toLowerCase()}/`;
|
|
138
|
+
if (!pattern.endsWith('/**'))
|
|
139
|
+
return null;
|
|
140
|
+
const dir = pattern.slice(0, -2);
|
|
141
|
+
return /[*?]/.test(dir) ? null : dir.toLowerCase();
|
|
142
|
+
}
|
|
143
|
+
/** The text of a pattern before its first wildcard. */
|
|
144
|
+
function literalPrefix(pattern) {
|
|
145
|
+
const at = pattern.search(/[*?]/);
|
|
146
|
+
return (at < 0 ? pattern : pattern.slice(0, at)).toLowerCase();
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* The scopes that claim a path. The order of the scopes in the manifest does not matter.
|
|
150
|
+
*
|
|
151
|
+
* A whole-directory pattern (`dir/**` or `**`) is a fallback. It gives way to a pattern of another
|
|
152
|
+
* scope that lies inside that directory: a deeper whole-directory pattern, or any other pattern
|
|
153
|
+
* that starts there. So `**` gives way to `policies/**`, and `src/**` gives way to `src/db/**`
|
|
154
|
+
* and to `src/*.sql`.
|
|
155
|
+
*
|
|
156
|
+
* Every other overlap is left as it is: `src/**` and a pattern like `**` + `/*.secret` both claim
|
|
157
|
+
* `src/a.secret`, and the result has two scopes. A caller must treat such a path as owned by nobody.
|
|
158
|
+
*/
|
|
159
|
+
export function claimantsOfPath(scopes, relativePath) {
|
|
160
|
+
const normalized = normalizeObjectPath(relativePath);
|
|
161
|
+
if (normalized === null)
|
|
162
|
+
return [];
|
|
163
|
+
const matches = scopes
|
|
164
|
+
.map((scope) => ({ scope, patterns: scope.paths.filter((pattern) => matchGlob(pattern, normalized)) }))
|
|
165
|
+
.filter((entry) => entry.patterns.length > 0);
|
|
166
|
+
const givesWay = (wide, narrow) => wide.patterns.every((pattern) => {
|
|
167
|
+
const dir = wholeDirectory(pattern);
|
|
168
|
+
if (dir === null)
|
|
169
|
+
return false;
|
|
170
|
+
return narrow.patterns.some((other) => {
|
|
171
|
+
const otherDir = wholeDirectory(other);
|
|
172
|
+
return literalPrefix(other).startsWith(dir) && (otherDir === null || otherDir.length > dir.length);
|
|
173
|
+
});
|
|
174
|
+
});
|
|
175
|
+
return matches
|
|
176
|
+
.filter((entry) => !matches.some((other) => other !== entry && givesWay(entry, other)))
|
|
177
|
+
.map((entry) => entry.scope);
|
|
178
|
+
}
|
|
179
|
+
/** The one scope that owns the path, or null when no scope or more than one scope claims it. */
|
|
180
|
+
export function scopeOfPath(scopes, relativePath) {
|
|
181
|
+
const claimants = claimantsOfPath(scopes, relativePath);
|
|
182
|
+
return claimants.length === 1 ? claimants[0] : null;
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* Checks where a write to an object of a file scope would really land. Returns the reason for a
|
|
186
|
+
* refusal, or null.
|
|
187
|
+
*
|
|
188
|
+
* A symbolic link, also one in a parent directory, can lead the write into another scope or out of
|
|
189
|
+
* the project: the real path must belong to the leased scope. A file with a second hard link has
|
|
190
|
+
* another name that this check cannot see, so it is refused.
|
|
191
|
+
*/
|
|
192
|
+
export function linkProblem(baseDir, scopes, scopeId, objectId) {
|
|
193
|
+
const parts = objectId.split('/');
|
|
194
|
+
let existing = parts.length;
|
|
195
|
+
// The deepest part of the path that exists. A link below it cannot exist.
|
|
196
|
+
while (existing > 0 && fs.lstatSync(path.join(baseDir, ...parts.slice(0, existing)), { throwIfNoEntry: false }) === undefined)
|
|
197
|
+
existing -= 1;
|
|
198
|
+
if (existing === 0)
|
|
199
|
+
return null;
|
|
200
|
+
let real;
|
|
201
|
+
let realBase;
|
|
202
|
+
try {
|
|
203
|
+
realBase = fs.realpathSync.native(baseDir);
|
|
204
|
+
real = fs.realpathSync.native(path.join(baseDir, ...parts.slice(0, existing)));
|
|
205
|
+
}
|
|
206
|
+
catch {
|
|
207
|
+
// A link that leads nowhere, or a path that cannot be read.
|
|
208
|
+
return 'OBJECT_OUT_OF_SCOPE';
|
|
209
|
+
}
|
|
210
|
+
const relative = path.relative(realBase, path.join(real, ...parts.slice(existing)));
|
|
211
|
+
if (relative === '' || relative.startsWith('..') || path.isAbsolute(relative))
|
|
212
|
+
return 'OBJECT_OUT_OF_SCOPE';
|
|
213
|
+
const claimants = claimantsOfPath(scopes, relative.split(path.sep).join('/'));
|
|
214
|
+
if (claimants.length !== 1 || claimants[0]?.id !== scopeId)
|
|
215
|
+
return 'OBJECT_OUT_OF_SCOPE';
|
|
216
|
+
if (existing === parts.length) {
|
|
217
|
+
const stat = fs.statSync(real, { throwIfNoEntry: false });
|
|
218
|
+
if (stat?.isFile() && stat.nlink > 1)
|
|
219
|
+
return 'OBJECT_HARD_LINKED';
|
|
220
|
+
}
|
|
221
|
+
return null;
|
|
222
|
+
}
|
|
223
|
+
export function hashFile(file) {
|
|
224
|
+
try {
|
|
225
|
+
return createHash('sha256').update(fs.readFileSync(file)).digest('hex');
|
|
226
|
+
}
|
|
227
|
+
catch {
|
|
228
|
+
return null;
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
export class HumanFileWatcher {
|
|
232
|
+
baseDir;
|
|
233
|
+
scopes;
|
|
234
|
+
sink;
|
|
235
|
+
ignore;
|
|
236
|
+
debounceMs;
|
|
237
|
+
timers = new Map();
|
|
238
|
+
watcher = null;
|
|
239
|
+
chain = Promise.resolve();
|
|
240
|
+
constructor(options) {
|
|
241
|
+
this.baseDir = options.baseDir;
|
|
242
|
+
this.scopes = options.scopes;
|
|
243
|
+
this.sink = options.sink;
|
|
244
|
+
this.ignore = options.ignore ?? ['.git', 'node_modules', '.certal'];
|
|
245
|
+
this.debounceMs = options.debounceMs ?? 50;
|
|
246
|
+
}
|
|
247
|
+
start() {
|
|
248
|
+
if (this.watcher)
|
|
249
|
+
return;
|
|
250
|
+
this.watcher = fs.watch(this.baseDir, { recursive: true }, (_event, filename) => {
|
|
251
|
+
if (typeof filename !== 'string')
|
|
252
|
+
return;
|
|
253
|
+
const relativePath = filename.split(path.sep).join('/');
|
|
254
|
+
if (this.ignore.some((dir) => relativePath === dir || relativePath.startsWith(`${dir}/`)))
|
|
255
|
+
return;
|
|
256
|
+
const pending = this.timers.get(relativePath);
|
|
257
|
+
if (pending)
|
|
258
|
+
clearTimeout(pending);
|
|
259
|
+
this.timers.set(relativePath, setTimeout(() => {
|
|
260
|
+
this.timers.delete(relativePath);
|
|
261
|
+
this.chain = this.chain.then(() => this.inspect(relativePath)).catch(() => { });
|
|
262
|
+
}, this.debounceMs));
|
|
263
|
+
});
|
|
264
|
+
}
|
|
265
|
+
/** Compares one file with its slot and reports a human edit when they differ. */
|
|
266
|
+
async inspect(relativePath) {
|
|
267
|
+
const file = path.join(this.baseDir, relativePath);
|
|
268
|
+
const hash = hashFile(file);
|
|
269
|
+
// A file that several scopes claim is reported to each of them: the human edit wins everywhere.
|
|
270
|
+
for (const scope of claimantsOfPath(this.scopes, relativePath)) {
|
|
271
|
+
const known = this.sink.currentHash(scope, relativePath);
|
|
272
|
+
if (hash === null) {
|
|
273
|
+
// A directory or an unreadable file is not a change. A file that is gone is one, when its slot holds a hash.
|
|
274
|
+
if (fs.existsSync(file) || known === undefined || known === null)
|
|
275
|
+
continue;
|
|
276
|
+
await this.sink.humanEdit(scope, relativePath, null);
|
|
277
|
+
continue;
|
|
278
|
+
}
|
|
279
|
+
if (known === hash)
|
|
280
|
+
continue;
|
|
281
|
+
await this.sink.humanEdit(scope, relativePath, hash);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
/** Resolves when every change seen so far has been handled. */
|
|
285
|
+
async settled() {
|
|
286
|
+
while (this.timers.size > 0)
|
|
287
|
+
await new Promise((resolve) => setTimeout(resolve, this.debounceMs));
|
|
288
|
+
await this.chain;
|
|
289
|
+
}
|
|
290
|
+
stop() {
|
|
291
|
+
this.watcher?.close();
|
|
292
|
+
this.watcher = null;
|
|
293
|
+
for (const timer of this.timers.values())
|
|
294
|
+
clearTimeout(timer);
|
|
295
|
+
this.timers.clear();
|
|
296
|
+
}
|
|
297
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import type { DeterministicHooks, Grade, InputSnapshot, KernelState, Reversibility, StateOp, WitnessStage } from '../kernel/index.ts';
|
|
2
|
+
import type { DeliveryAdapterOutcome, OutboxRecord, OutboxTransport } from '../runtime/index.ts';
|
|
3
|
+
import type { DeterministicEvaluator, EvaluationResult, ScopeReadResult, StateSubstrateAdapter, WitnessOracle, WitnessStageExecution } from './contracts.ts';
|
|
4
|
+
export interface SimulatedRecipientBehavior {
|
|
5
|
+
/** When set, simulates a lost deliver response. The effect may still have been applied (appliedOnTimeout). */
|
|
6
|
+
dropResponseTimes?: number;
|
|
7
|
+
appliedOnTimeout?: boolean;
|
|
8
|
+
refuseDeliver?: boolean;
|
|
9
|
+
refuseCompensate?: boolean;
|
|
10
|
+
unknownReconcile?: boolean;
|
|
11
|
+
}
|
|
12
|
+
export interface InMemoryExternalEntry {
|
|
13
|
+
readonly effectId: string;
|
|
14
|
+
readonly payload: unknown;
|
|
15
|
+
readonly version: number;
|
|
16
|
+
readonly compensated: boolean;
|
|
17
|
+
readonly compensationPayload?: unknown;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Reference in-memory adapter. It implements slots S1, S2, S4 and the S5 transport (OutboxTransport)
|
|
21
|
+
* and the checkUndoDependencies hook, which finds dependent child objects owned by a human.
|
|
22
|
+
*/
|
|
23
|
+
export declare class InMemoryReferenceAdapter implements StateSubstrateAdapter, DeterministicEvaluator, WitnessOracle, OutboxTransport {
|
|
24
|
+
private readonly externalRecords;
|
|
25
|
+
private readonly behaviors;
|
|
26
|
+
private readonly witnessOverrides;
|
|
27
|
+
deliverCalls: number;
|
|
28
|
+
reconcileCalls: number;
|
|
29
|
+
compensateCalls: number;
|
|
30
|
+
setRecipientBehavior(recipientId: string, behavior: SimulatedRecipientBehavior): void;
|
|
31
|
+
setWitnessOverride(stage: WitnessStage, override: Partial<WitnessStageExecution>): void;
|
|
32
|
+
clearWitnessOverrides(): void;
|
|
33
|
+
getExternalRecord(effectId: string): InMemoryExternalEntry | undefined;
|
|
34
|
+
/**
|
|
35
|
+
* Deterministic hook: blocks the undo of object A when an active child object B exists that
|
|
36
|
+
* a human created or modified, with parentObjectId === A.
|
|
37
|
+
*/
|
|
38
|
+
readonly hooks: DeterministicHooks;
|
|
39
|
+
readScope(state: KernelState, scopeId: string, classId: string): ScopeReadResult;
|
|
40
|
+
classifyReversibility(op: StateOp): Reversibility;
|
|
41
|
+
freezeInputs(scopeId: string, rawInputs: unknown, confidence: Grade, nowMs: number): InputSnapshot;
|
|
42
|
+
evaluate(state: KernelState, snapshot: InputSnapshot): EvaluationResult;
|
|
43
|
+
runStage(intent: {
|
|
44
|
+
readonly verifyId: string;
|
|
45
|
+
readonly attemptId: string;
|
|
46
|
+
readonly stage: WitnessStage;
|
|
47
|
+
readonly budgetCpuMs: number;
|
|
48
|
+
readonly requireNearMiss: boolean;
|
|
49
|
+
}): Promise<WitnessStageExecution>;
|
|
50
|
+
deliver(record: OutboxRecord): Promise<DeliveryAdapterOutcome>;
|
|
51
|
+
reconcile(record: OutboxRecord): Promise<DeliveryAdapterOutcome>;
|
|
52
|
+
compensate(record: OutboxRecord): Promise<DeliveryAdapterOutcome>;
|
|
53
|
+
}
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
import { computeScopeHash, hashCanonical, } from '../kernel/index.js';
|
|
2
|
+
/**
|
|
3
|
+
* Reference in-memory adapter. It implements slots S1, S2, S4 and the S5 transport (OutboxTransport)
|
|
4
|
+
* and the checkUndoDependencies hook, which finds dependent child objects owned by a human.
|
|
5
|
+
*/
|
|
6
|
+
export class InMemoryReferenceAdapter {
|
|
7
|
+
externalRecords = new Map();
|
|
8
|
+
behaviors = new Map();
|
|
9
|
+
witnessOverrides = new Map();
|
|
10
|
+
deliverCalls = 0;
|
|
11
|
+
reconcileCalls = 0;
|
|
12
|
+
compensateCalls = 0;
|
|
13
|
+
setRecipientBehavior(recipientId, behavior) {
|
|
14
|
+
this.behaviors.set(recipientId, behavior);
|
|
15
|
+
}
|
|
16
|
+
setWitnessOverride(stage, override) {
|
|
17
|
+
this.witnessOverrides.set(stage, override);
|
|
18
|
+
}
|
|
19
|
+
clearWitnessOverrides() {
|
|
20
|
+
this.witnessOverrides.clear();
|
|
21
|
+
}
|
|
22
|
+
getExternalRecord(effectId) {
|
|
23
|
+
return this.externalRecords.get(effectId);
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Deterministic hook: blocks the undo of object A when an active child object B exists that
|
|
27
|
+
* a human created or modified, with parentObjectId === A.
|
|
28
|
+
*/
|
|
29
|
+
hooks = {
|
|
30
|
+
checkUndoDependencies: (state, patch) => {
|
|
31
|
+
for (const slot of Object.values(state.slots)) {
|
|
32
|
+
if (slot.parentObjectId === patch.objectId &&
|
|
33
|
+
slot.owner.kind === 'Human' &&
|
|
34
|
+
slot.value !== null &&
|
|
35
|
+
slot.value !== undefined) {
|
|
36
|
+
return {
|
|
37
|
+
blocked: true,
|
|
38
|
+
reason: `Dependent child object ${slot.objectId}.${slot.field} created by ${slot.owner.actorId}`,
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
return { blocked: false };
|
|
43
|
+
},
|
|
44
|
+
};
|
|
45
|
+
readScope(state, scopeId, classId) {
|
|
46
|
+
const values = {};
|
|
47
|
+
let maxRev = 0;
|
|
48
|
+
const prefix = `${scopeId}\0`;
|
|
49
|
+
for (const [k, slot] of Object.entries(state.slots)) {
|
|
50
|
+
if (!k.startsWith(prefix))
|
|
51
|
+
continue;
|
|
52
|
+
if (classId !== '*' && slot.classId !== classId)
|
|
53
|
+
continue;
|
|
54
|
+
values[`${slot.objectId}.${slot.field}`] = slot.value;
|
|
55
|
+
if (slot.rev > maxRev)
|
|
56
|
+
maxRev = slot.rev;
|
|
57
|
+
}
|
|
58
|
+
return {
|
|
59
|
+
scopeId,
|
|
60
|
+
classId,
|
|
61
|
+
revision: maxRev,
|
|
62
|
+
scopeHash: computeScopeHash(state, scopeId, classId),
|
|
63
|
+
values,
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
classifyReversibility(op) {
|
|
67
|
+
return op.reversibility;
|
|
68
|
+
}
|
|
69
|
+
freezeInputs(scopeId, rawInputs, confidence, nowMs) {
|
|
70
|
+
return {
|
|
71
|
+
schemaVersion: 1,
|
|
72
|
+
dataRef: `mem://${scopeId}/${nowMs}`,
|
|
73
|
+
hash: hashCanonical('input_snapshot', 1, { scopeId, rawInputs, confidence }),
|
|
74
|
+
capturedAtMs: nowMs,
|
|
75
|
+
confidence,
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
evaluate(state, snapshot) {
|
|
79
|
+
return {
|
|
80
|
+
hardViolations: [],
|
|
81
|
+
pinViolations: state.pins.filter((p) => p.kind === 'H').map((p) => p.ruleId),
|
|
82
|
+
objectiveMicroUnits: 0,
|
|
83
|
+
confidence: snapshot.confidence,
|
|
84
|
+
};
|
|
85
|
+
}
|
|
86
|
+
async runStage(intent) {
|
|
87
|
+
const ov = this.witnessOverrides.get(intent.stage);
|
|
88
|
+
return {
|
|
89
|
+
verifyId: intent.verifyId,
|
|
90
|
+
stage: intent.stage,
|
|
91
|
+
verdict: ov?.verdict ?? 'PASS',
|
|
92
|
+
cpuMs: ov?.cpuMs ?? 5,
|
|
93
|
+
nearMissPassed: ov?.nearMissPassed ?? true,
|
|
94
|
+
...(ov?.optimization !== undefined ? { optimization: ov.optimization } : {}),
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
async deliver(record) {
|
|
98
|
+
this.deliverCalls += 1;
|
|
99
|
+
const behavior = this.behaviors.get(record.recipientId);
|
|
100
|
+
if (behavior?.refuseDeliver) {
|
|
101
|
+
return { status: 'REFUSED', reason: 'RECIPIENT_REJECTED' };
|
|
102
|
+
}
|
|
103
|
+
if (behavior?.dropResponseTimes && behavior.dropResponseTimes > 0) {
|
|
104
|
+
behavior.dropResponseTimes -= 1;
|
|
105
|
+
if (behavior.appliedOnTimeout !== false) {
|
|
106
|
+
this.externalRecords.set(record.effectId, {
|
|
107
|
+
effectId: record.effectId,
|
|
108
|
+
payload: JSON.parse(record.payloadJson),
|
|
109
|
+
version: 1,
|
|
110
|
+
compensated: false,
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
return { status: 'UNKNOWN', reason: 'RESPONSE_TIMEOUT' };
|
|
114
|
+
}
|
|
115
|
+
this.externalRecords.set(record.effectId, {
|
|
116
|
+
effectId: record.effectId,
|
|
117
|
+
payload: JSON.parse(record.payloadJson),
|
|
118
|
+
version: 1,
|
|
119
|
+
compensated: false,
|
|
120
|
+
});
|
|
121
|
+
return { status: 'APPLIED' };
|
|
122
|
+
}
|
|
123
|
+
async reconcile(record) {
|
|
124
|
+
this.reconcileCalls += 1;
|
|
125
|
+
const behavior = this.behaviors.get(record.recipientId);
|
|
126
|
+
if (behavior?.unknownReconcile) {
|
|
127
|
+
return { status: 'UNKNOWN', reason: 'RECONCILE_TIMEOUT' };
|
|
128
|
+
}
|
|
129
|
+
if (record.effectKind === 'Compensate') {
|
|
130
|
+
const orig = this.externalRecords.get(record.batchId);
|
|
131
|
+
if (!orig) {
|
|
132
|
+
return { status: 'REFUSED', reason: 'ORIGINAL_EFFECT_NOT_FOUND' };
|
|
133
|
+
}
|
|
134
|
+
return orig.compensated
|
|
135
|
+
? { status: 'APPLIED' }
|
|
136
|
+
: { status: 'REFUSED', reason: 'COMPENSATION_NOT_APPLIED' };
|
|
137
|
+
}
|
|
138
|
+
const existing = this.externalRecords.get(record.effectId);
|
|
139
|
+
if (existing) {
|
|
140
|
+
return { status: 'APPLIED' };
|
|
141
|
+
}
|
|
142
|
+
return { status: 'REFUSED', reason: 'EFFECT_ABSENT_AT_RECIPIENT' };
|
|
143
|
+
}
|
|
144
|
+
async compensate(record) {
|
|
145
|
+
this.compensateCalls += 1;
|
|
146
|
+
const behavior = this.behaviors.get(record.recipientId);
|
|
147
|
+
if (behavior?.refuseCompensate) {
|
|
148
|
+
return { status: 'REFUSED', reason: 'COMPENSATION_REFUSED' };
|
|
149
|
+
}
|
|
150
|
+
const orig = this.externalRecords.get(record.batchId);
|
|
151
|
+
if (!orig) {
|
|
152
|
+
return { status: 'REFUSED', reason: 'ORIGINAL_EFFECT_NOT_FOUND' };
|
|
153
|
+
}
|
|
154
|
+
if (orig.version !== 1) {
|
|
155
|
+
return { status: 'REFUSED', reason: 'CAS_VERSION_MISMATCH' };
|
|
156
|
+
}
|
|
157
|
+
this.externalRecords.set(record.batchId, {
|
|
158
|
+
...orig,
|
|
159
|
+
version: orig.version + 1,
|
|
160
|
+
compensated: true,
|
|
161
|
+
compensationPayload: JSON.parse(record.payloadJson),
|
|
162
|
+
});
|
|
163
|
+
return { status: 'APPLIED' };
|
|
164
|
+
}
|
|
165
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export * from './contracts.ts';
|
|
2
|
+
export * from './in-memory.ts';
|
|
3
|
+
export * from './tool-sdk.ts';
|
|
4
|
+
export * from './manifest.ts';
|
|
5
|
+
export * from './commands.ts';
|
|
6
|
+
export * from './operator-auth.ts';
|
|
7
|
+
export * from './approval-channel.ts';
|
|
8
|
+
export * from './file-watcher.ts';
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export * from './contracts.js';
|
|
2
|
+
export * from './in-memory.js';
|
|
3
|
+
export * from './tool-sdk.js';
|
|
4
|
+
export * from './manifest.js';
|
|
5
|
+
export * from './commands.js';
|
|
6
|
+
export * from './operator-auth.js';
|
|
7
|
+
export * from './approval-channel.js';
|
|
8
|
+
export * from './file-watcher.js';
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import type { PinKind, PolicyConfig, Reversibility, WitnessStage } from '../kernel/index.ts';
|
|
2
|
+
/**
|
|
3
|
+
* The declarative manifest `certal.json`.
|
|
4
|
+
*
|
|
5
|
+
* A manifest is plain JSON. Manifests found on the way from the working directory up to the
|
|
6
|
+
* filesystem root are merged, outermost first. A manifest in a subdirectory may only tighten
|
|
7
|
+
* what its parents declare: it may add pins and lower budgets, and it may never remove a pin
|
|
8
|
+
* or relax a limit. A merge that would relax anything fails with the list of violations.
|
|
9
|
+
*/
|
|
10
|
+
export declare const MANIFEST_FILE = "certal.json";
|
|
11
|
+
export type ManifestProfile = 'sdk' | 'exchange' | 'vibeops' | 'solver' | 'custom';
|
|
12
|
+
export type Command = readonly string[];
|
|
13
|
+
export interface ManifestScope {
|
|
14
|
+
readonly id: string;
|
|
15
|
+
readonly classId: string;
|
|
16
|
+
/** Glob patterns, relative to the manifest directory, of the files that belong to the scope. */
|
|
17
|
+
readonly paths: readonly string[];
|
|
18
|
+
}
|
|
19
|
+
export interface ManifestPin {
|
|
20
|
+
readonly id: string;
|
|
21
|
+
readonly kind: PinKind;
|
|
22
|
+
readonly scopeId: string;
|
|
23
|
+
readonly classId: string;
|
|
24
|
+
readonly rule: string;
|
|
25
|
+
readonly costPenaltyMicroUnits?: number;
|
|
26
|
+
}
|
|
27
|
+
export interface ManifestTool {
|
|
28
|
+
readonly reversibility: Reversibility;
|
|
29
|
+
readonly supportsCas: boolean;
|
|
30
|
+
readonly preflightCommand?: Command;
|
|
31
|
+
readonly deliverCommand?: Command;
|
|
32
|
+
readonly reconcileCommand?: Command;
|
|
33
|
+
readonly compensateCommand?: Command;
|
|
34
|
+
}
|
|
35
|
+
export interface ManifestWitnessStage {
|
|
36
|
+
/** The check to run. Exit code 0 is PASS, 1 is FAIL, anything else is UNKNOWN. */
|
|
37
|
+
readonly command?: Command;
|
|
38
|
+
/** `accept` passes the stage without a check. Use it only where no check exists yet. */
|
|
39
|
+
readonly builtin?: 'accept';
|
|
40
|
+
readonly budgetCpuMs: number;
|
|
41
|
+
readonly requireNearMiss: boolean;
|
|
42
|
+
readonly nearMissProbeCommand?: Command;
|
|
43
|
+
}
|
|
44
|
+
export interface ManifestOperator {
|
|
45
|
+
readonly humanId: string;
|
|
46
|
+
/** Ed25519 public keys in PEM format, by key id. */
|
|
47
|
+
readonly publicKeys: Readonly<Record<string, string>>;
|
|
48
|
+
}
|
|
49
|
+
export interface ManifestApprovals {
|
|
50
|
+
readonly channel: 'local-cli' | 'webhook';
|
|
51
|
+
readonly url?: string;
|
|
52
|
+
}
|
|
53
|
+
export interface CertalManifest {
|
|
54
|
+
readonly version: 1;
|
|
55
|
+
readonly profile: ManifestProfile;
|
|
56
|
+
readonly stateDir?: string;
|
|
57
|
+
readonly operator?: ManifestOperator;
|
|
58
|
+
readonly policy?: Partial<PolicyConfig>;
|
|
59
|
+
readonly scopes?: readonly ManifestScope[];
|
|
60
|
+
readonly pins?: readonly ManifestPin[];
|
|
61
|
+
readonly tools?: Readonly<Record<string, ManifestTool>>;
|
|
62
|
+
readonly witness?: Partial<Readonly<Record<WitnessStage, ManifestWitnessStage>>>;
|
|
63
|
+
readonly approvals?: ManifestApprovals;
|
|
64
|
+
readonly watch?: boolean;
|
|
65
|
+
/** Set in the outermost manifest to let subdirectories declare tools of their own. Default: false. */
|
|
66
|
+
readonly allowSubdirectoryTools?: boolean;
|
|
67
|
+
}
|
|
68
|
+
export interface ResolvedManifest {
|
|
69
|
+
readonly profile: ManifestProfile;
|
|
70
|
+
/** Directory of the innermost manifest. Commands run here and the state directory lives here. */
|
|
71
|
+
readonly baseDir: string;
|
|
72
|
+
readonly stateDir: string;
|
|
73
|
+
/** Manifest files that were merged, outermost first. */
|
|
74
|
+
readonly sources: readonly string[];
|
|
75
|
+
readonly operator: ManifestOperator | null;
|
|
76
|
+
readonly policy: Partial<PolicyConfig>;
|
|
77
|
+
readonly scopes: readonly ManifestScope[];
|
|
78
|
+
readonly pins: readonly ManifestPin[];
|
|
79
|
+
readonly tools: Readonly<Record<string, ManifestTool>>;
|
|
80
|
+
readonly witness: Partial<Readonly<Record<WitnessStage, ManifestWitnessStage>>>;
|
|
81
|
+
readonly approvals: ManifestApprovals;
|
|
82
|
+
readonly watch: boolean;
|
|
83
|
+
readonly allowSubdirectoryTools: boolean;
|
|
84
|
+
}
|
|
85
|
+
export declare class ManifestError extends Error {
|
|
86
|
+
readonly problems: readonly string[];
|
|
87
|
+
constructor(problems: readonly string[]);
|
|
88
|
+
}
|
|
89
|
+
/** Checks the shape of one manifest. Returns the list of problems, empty when the manifest is valid. */
|
|
90
|
+
export declare function validateManifest(raw: unknown, label?: string): string[];
|
|
91
|
+
/** Manifest files from `startDir` up to the filesystem root, outermost first. */
|
|
92
|
+
export declare function findManifestFiles(startDir: string): string[];
|
|
93
|
+
/**
|
|
94
|
+
* Loads and merges the manifests that apply to `startDir`.
|
|
95
|
+
* Throws ManifestError when a file is invalid, when a subdirectory relaxes a parent,
|
|
96
|
+
* or when a required witness stage has no declaration.
|
|
97
|
+
*/
|
|
98
|
+
export declare function loadManifest(startDir: string): ResolvedManifest;
|
|
99
|
+
/**
|
|
100
|
+
* Lists the places where `next` would relax the policy `current`. Used when a manifest changes
|
|
101
|
+
* after the log has started: a tighter policy is applied, a looser one is refused.
|
|
102
|
+
*/
|
|
103
|
+
export declare function policyRelaxations(current: PolicyConfig, next: Partial<PolicyConfig>): string[];
|
|
104
|
+
/** The part of `next` that differs from `current`. Empty when the manifest policy is already in force. */
|
|
105
|
+
export declare function policyDifference(current: PolicyConfig, next: Partial<PolicyConfig>): Partial<PolicyConfig>;
|