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,465 @@
1
+ import fs from 'node:fs';
2
+ import { patternProblem } from './file-watcher.js';
3
+ import path from 'node:path';
4
+ import { DEFAULT_POLICY, validatePolicyBounds } from '../kernel/index.js';
5
+ /**
6
+ * The declarative manifest `certal.json`.
7
+ *
8
+ * A manifest is plain JSON. Manifests found on the way from the working directory up to the
9
+ * filesystem root are merged, outermost first. A manifest in a subdirectory may only tighten
10
+ * what its parents declare: it may add pins and lower budgets, and it may never remove a pin
11
+ * or relax a limit. A merge that would relax anything fails with the list of violations.
12
+ */
13
+ export const MANIFEST_FILE = 'certal.json';
14
+ export class ManifestError extends Error {
15
+ problems;
16
+ constructor(problems) {
17
+ super(`Invalid manifest:\n- ${problems.join('\n- ')}`);
18
+ this.name = 'ManifestError';
19
+ this.problems = problems;
20
+ }
21
+ }
22
+ const PROFILES = ['sdk', 'exchange', 'vibeops', 'solver', 'custom'];
23
+ const STAGES = ['L0', 'L1', 'L2', 'L3'];
24
+ const REVERSIBILITY_RANK = { REVERSIBLE: 0, COMPENSABLE: 1, IRREVERSIBLE: 2 };
25
+ const TOP_LEVEL_KEYS = ['$schema', 'version', 'profile', 'stateDir', 'operator', 'policy', 'scopes', 'pins', 'tools', 'witness', 'approvals', 'watch', 'allowSubdirectoryTools'];
26
+ /** Policy fields by the direction in which a subdirectory may change them. */
27
+ const LOWER_ONLY = ['maxAttempts', 'maxFailStreak', 'maxConflictStreak', 'maxCpuMs', 'maxCostMicroUnits', 'maxReconcileAttempts', 'defaultLeaseTtlMs', 'maxConcurrentPerScope', 'maxEventBytes'];
28
+ const RAISE_ONLY = ['minImprovementMicroUnits'];
29
+ const ENABLE_ONLY = ['escalatePartialToC2', 'denyPartial', 'escalateSoftPinToC2', 'enforceApprovalSignature', 'enforceAutonomyLadder'];
30
+ const FIXED = ['undoWindowTtlMs'];
31
+ const POOL_KEYS = ['inferenceSlots', 'witnessSlots', 'mutationSlots'];
32
+ const POLICY_KEYS = [...LOWER_ONLY, ...RAISE_ONLY, ...ENABLE_ONLY, ...FIXED, 'resourcePoolCapacity', 'requiredWitnessStages'];
33
+ const isRecord = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
34
+ const isText = (v) => typeof v === 'string' && v.length > 0;
35
+ const isCount = (v) => typeof v === 'number' && Number.isSafeInteger(v) && v >= 0;
36
+ const isCommand = (v) => Array.isArray(v) && v.length > 0 && v.every(isText);
37
+ const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
38
+ /** Checks the shape of one manifest. Returns the list of problems, empty when the manifest is valid. */
39
+ export function validateManifest(raw, label = MANIFEST_FILE) {
40
+ const problems = [];
41
+ const bad = (message) => void problems.push(`${label}: ${message}`);
42
+ if (!isRecord(raw))
43
+ return [`${label}: the manifest must be a JSON object`];
44
+ for (const key of Object.keys(raw))
45
+ if (!TOP_LEVEL_KEYS.includes(key))
46
+ bad(`unknown key "${key}"`);
47
+ if (raw.version !== 1)
48
+ bad('"version" must be 1');
49
+ if (!PROFILES.includes(raw.profile))
50
+ bad(`"profile" must be one of: ${PROFILES.join(', ')}`);
51
+ if (raw.stateDir !== undefined && !isText(raw.stateDir))
52
+ bad('"stateDir" must be a non-empty string');
53
+ if (raw.watch !== undefined && typeof raw.watch !== 'boolean')
54
+ bad('"watch" must be a boolean');
55
+ if (raw.allowSubdirectoryTools !== undefined && typeof raw.allowSubdirectoryTools !== 'boolean')
56
+ bad('"allowSubdirectoryTools" must be a boolean');
57
+ if (raw.operator !== undefined) {
58
+ const op = raw.operator;
59
+ if (!isRecord(op) || !isText(op.humanId) || !isRecord(op.publicKeys) || !Object.values(op.publicKeys).every(isText)) {
60
+ bad('"operator" needs "humanId" and "publicKeys" (key id to PEM text)');
61
+ }
62
+ }
63
+ if (raw.policy !== undefined) {
64
+ if (!isRecord(raw.policy))
65
+ bad('"policy" must be an object');
66
+ else {
67
+ const p = raw.policy;
68
+ for (const key of Object.keys(p))
69
+ if (!POLICY_KEYS.includes(key))
70
+ bad(`policy: unknown key "${key}"`);
71
+ for (const key of [...LOWER_ONLY, ...RAISE_ONLY, ...FIXED])
72
+ if (p[key] !== undefined && !isCount(p[key]))
73
+ bad(`policy.${key} must be a non-negative integer`);
74
+ for (const key of ENABLE_ONLY)
75
+ if (p[key] !== undefined && typeof p[key] !== 'boolean')
76
+ bad(`policy.${key} must be a boolean`);
77
+ if (p.resourcePoolCapacity !== undefined) {
78
+ const pool = p.resourcePoolCapacity;
79
+ if (!isRecord(pool) || Object.keys(pool).some((k) => !POOL_KEYS.includes(k)) || !Object.values(pool).every(isCount)) {
80
+ bad(`policy.resourcePoolCapacity may hold only ${POOL_KEYS.join(', ')} as non-negative integers`);
81
+ }
82
+ }
83
+ if (p.requiredWitnessStages !== undefined) {
84
+ const stages = p.requiredWitnessStages;
85
+ if (!Array.isArray(stages) || stages.length === 0 || !stages.every((s) => STAGES.includes(s))) {
86
+ bad(`policy.requiredWitnessStages must be a non-empty list of: ${STAGES.join(', ')}`);
87
+ }
88
+ }
89
+ // The kernel has lower bounds of its own (most limits are at least 1). Report them here, before a log starts.
90
+ if (problems.length === 0 && validatePolicyBounds(p) !== null) {
91
+ bad('policy: a value is below the bound that the kernel accepts (limits and TTLs are at least 1, maxEventBytes at least 1024)');
92
+ }
93
+ }
94
+ }
95
+ const scopeIds = new Set();
96
+ if (raw.scopes !== undefined) {
97
+ if (!Array.isArray(raw.scopes))
98
+ bad('"scopes" must be a list');
99
+ else {
100
+ for (const [i, s] of raw.scopes.entries()) {
101
+ if (!isRecord(s) || !isText(s.id) || !isText(s.classId) || !Array.isArray(s.paths) || !s.paths.every(isText)) {
102
+ bad(`scopes[${i}] needs "id", "classId" and "paths" (a list of glob patterns)`);
103
+ }
104
+ else if (scopeIds.has(s.id))
105
+ bad(`scopes[${i}]: duplicate id "${s.id}"`);
106
+ else {
107
+ scopeIds.add(s.id);
108
+ for (const pattern of s.paths) {
109
+ const problem = patternProblem(pattern);
110
+ if (problem)
111
+ bad(`scope "${s.id}": the pattern "${pattern}" ${problem}`);
112
+ }
113
+ }
114
+ }
115
+ }
116
+ }
117
+ if (raw.pins !== undefined) {
118
+ if (!Array.isArray(raw.pins))
119
+ bad('"pins" must be a list');
120
+ else {
121
+ const ids = new Set();
122
+ for (const [i, p] of raw.pins.entries()) {
123
+ if (!isRecord(p) || !isText(p.id) || !['H', 'T', 'N'].includes(p.kind) || !isText(p.scopeId) || !isText(p.classId) || !isText(p.rule)) {
124
+ bad(`pins[${i}] needs "id", "kind" (H, T or N), "scopeId", "classId" and "rule"`);
125
+ continue;
126
+ }
127
+ if (p.kind === 'T')
128
+ bad(`pins[${i}]: a timed pin has an expiry and cannot be declared in a manifest`);
129
+ if (p.costPenaltyMicroUnits !== undefined && !isCount(p.costPenaltyMicroUnits))
130
+ bad(`pins[${i}].costPenaltyMicroUnits must be a non-negative integer`);
131
+ if (ids.has(p.id))
132
+ bad(`pins[${i}]: duplicate id "${p.id}"`);
133
+ ids.add(p.id);
134
+ }
135
+ }
136
+ }
137
+ if (raw.tools !== undefined) {
138
+ if (!isRecord(raw.tools))
139
+ bad('"tools" must be an object');
140
+ else {
141
+ for (const [id, t] of Object.entries(raw.tools)) {
142
+ if (!isRecord(t) || !(String(t.reversibility) in REVERSIBILITY_RANK) || typeof t.supportsCas !== 'boolean') {
143
+ bad(`tools.${id} needs "reversibility" and "supportsCas"`);
144
+ continue;
145
+ }
146
+ for (const key of ['preflightCommand', 'deliverCommand', 'reconcileCommand', 'compensateCommand']) {
147
+ if (t[key] !== undefined && !isCommand(t[key]))
148
+ bad(`tools.${id}.${key} must be a non-empty list of strings`);
149
+ }
150
+ }
151
+ }
152
+ }
153
+ if (raw.witness !== undefined) {
154
+ if (!isRecord(raw.witness))
155
+ bad('"witness" must be an object');
156
+ else {
157
+ for (const [stage, w] of Object.entries(raw.witness)) {
158
+ if (!STAGES.includes(stage)) {
159
+ bad(`witness: unknown stage "${stage}"`);
160
+ continue;
161
+ }
162
+ if (!isRecord(w) || !isCount(w.budgetCpuMs) || typeof w.requireNearMiss !== 'boolean') {
163
+ bad(`witness.${stage} needs "budgetCpuMs" and "requireNearMiss"`);
164
+ continue;
165
+ }
166
+ const hasCommand = w.command !== undefined;
167
+ if (hasCommand === (w.builtin !== undefined))
168
+ bad(`witness.${stage} needs exactly one of "command" and "builtin"`);
169
+ if (hasCommand && !isCommand(w.command))
170
+ bad(`witness.${stage}.command must be a non-empty list of strings`);
171
+ if (w.builtin !== undefined && w.builtin !== 'accept')
172
+ bad(`witness.${stage}.builtin must be "accept"`);
173
+ if (w.nearMissProbeCommand !== undefined && !isCommand(w.nearMissProbeCommand))
174
+ bad(`witness.${stage}.nearMissProbeCommand must be a non-empty list of strings`);
175
+ }
176
+ }
177
+ }
178
+ if (raw.approvals !== undefined) {
179
+ const a = raw.approvals;
180
+ if (!isRecord(a) || (a.channel !== 'local-cli' && a.channel !== 'webhook'))
181
+ bad('"approvals.channel" must be "local-cli" or "webhook"');
182
+ else if (a.channel === 'webhook' && !isText(a.url))
183
+ bad('"approvals.url" is required for the webhook channel');
184
+ }
185
+ return problems;
186
+ }
187
+ function emptyLayer() {
188
+ return { profile: 'custom', stateDirRaw: null, operator: null, policy: {}, scopes: [], pins: [], tools: {}, witness: {}, approvals: { channel: 'local-cli' }, watch: false, allowSubdirectoryTools: false };
189
+ }
190
+ /**
191
+ * Merges a child manifest into the result of its parents. Appends to `violations` every place
192
+ * where the child would relax the parents.
193
+ */
194
+ function mergeLayer(parent, child, label, violations, isOutermost) {
195
+ const no = (message) => void violations.push(`${label}: ${message}`);
196
+ const effective = (key) => parent.policy[key] ?? DEFAULT_POLICY[key];
197
+ const policy = { ...parent.policy };
198
+ const childPolicy = (child.policy ?? {});
199
+ for (const key of LOWER_ONLY) {
200
+ const v = childPolicy[key];
201
+ if (v === undefined)
202
+ continue;
203
+ if (!isOutermost && v > effective(key))
204
+ no(`policy.${key} = ${String(v)} raises the parent limit ${String(effective(key))}`);
205
+ else
206
+ policy[key] = v;
207
+ }
208
+ for (const key of RAISE_ONLY) {
209
+ const v = childPolicy[key];
210
+ if (v === undefined)
211
+ continue;
212
+ if (!isOutermost && v < effective(key))
213
+ no(`policy.${key} = ${String(v)} lowers the parent threshold ${String(effective(key))}`);
214
+ else
215
+ policy[key] = v;
216
+ }
217
+ for (const key of ENABLE_ONLY) {
218
+ const v = childPolicy[key];
219
+ if (v === undefined)
220
+ continue;
221
+ if (!isOutermost && v === false && effective(key) === true)
222
+ no(`policy.${key} = false switches off a check that the parent keeps on`);
223
+ else
224
+ policy[key] = v;
225
+ }
226
+ for (const key of FIXED) {
227
+ const v = childPolicy[key];
228
+ if (v === undefined)
229
+ continue;
230
+ if (!isOutermost && v !== effective(key))
231
+ no(`policy.${key} cannot change in a subdirectory`);
232
+ else
233
+ policy[key] = v;
234
+ }
235
+ if (childPolicy.resourcePoolCapacity !== undefined) {
236
+ const parentPool = { ...DEFAULT_POLICY.resourcePoolCapacity, ...(parent.policy.resourcePoolCapacity ?? {}) };
237
+ const childPool = childPolicy.resourcePoolCapacity;
238
+ const pool = { ...parentPool };
239
+ for (const key of POOL_KEYS) {
240
+ const v = childPool[key];
241
+ if (v === undefined)
242
+ continue;
243
+ if (!isOutermost && v > parentPool[key])
244
+ no(`policy.resourcePoolCapacity.${key} = ${v} raises the parent limit ${parentPool[key]}`);
245
+ else
246
+ pool[key] = v;
247
+ }
248
+ policy.resourcePoolCapacity = pool;
249
+ }
250
+ if (childPolicy.requiredWitnessStages !== undefined) {
251
+ const parentStages = effective('requiredWitnessStages');
252
+ const childStages = childPolicy.requiredWitnessStages;
253
+ const missing = parentStages.filter((s) => !childStages.includes(s));
254
+ if (!isOutermost && missing.length > 0)
255
+ no(`policy.requiredWitnessStages drops the stage ${missing.join(', ')} that the parent requires`);
256
+ else
257
+ policy.requiredWitnessStages = STAGES.filter((s) => childStages.includes(s));
258
+ }
259
+ const scopes = [...parent.scopes];
260
+ for (const scope of child.scopes ?? []) {
261
+ const existing = scopes.find((s) => s.id === scope.id);
262
+ if (!existing)
263
+ scopes.push(scope);
264
+ else if (!same(existing, scope))
265
+ no(`scope "${scope.id}" is declared by a parent and cannot change`);
266
+ }
267
+ const pins = [...parent.pins];
268
+ for (const pin of child.pins ?? []) {
269
+ const existing = pins.find((p) => p.id === pin.id);
270
+ if (!existing)
271
+ pins.push(pin);
272
+ else if (!same(existing, pin))
273
+ no(`pin "${pin.id}" is declared by a parent and cannot change`);
274
+ }
275
+ const tools = { ...parent.tools };
276
+ for (const [id, tool] of Object.entries(child.tools ?? {})) {
277
+ const existing = tools[id];
278
+ if (!existing) {
279
+ // A new tool brings commands of its own, so a subdirectory needs the outermost manifest's consent.
280
+ if (!isOutermost && !parent.allowSubdirectoryTools)
281
+ no(`tool "${id}" is new in a subdirectory. Declare it in the outermost manifest or set "allowSubdirectoryTools" there`);
282
+ else
283
+ tools[id] = tool;
284
+ continue;
285
+ }
286
+ const { reversibility: parentRev, ...parentRest } = existing;
287
+ const { reversibility: childRev, ...childRest } = tool;
288
+ if (!same(parentRest, childRest))
289
+ no(`tool "${id}" is declared by a parent and only its reversibility may become stricter`);
290
+ else if (REVERSIBILITY_RANK[childRev] < REVERSIBILITY_RANK[parentRev])
291
+ no(`tool "${id}": ${childRev} is weaker than the parent ${parentRev}`);
292
+ else
293
+ tools[id] = tool;
294
+ }
295
+ const witness = { ...parent.witness };
296
+ for (const [stage, cfg] of Object.entries(child.witness ?? {})) {
297
+ const existing = witness[stage];
298
+ if (!existing) {
299
+ witness[stage] = cfg;
300
+ continue;
301
+ }
302
+ if (!same(existing.command ?? null, cfg.command ?? null) || !same(existing.builtin ?? null, cfg.builtin ?? null) || !same(existing.nearMissProbeCommand ?? null, cfg.nearMissProbeCommand ?? null)) {
303
+ no(`witness.${stage} is declared by a parent and its commands cannot change`);
304
+ }
305
+ else if (cfg.budgetCpuMs > existing.budgetCpuMs)
306
+ no(`witness.${stage}.budgetCpuMs = ${cfg.budgetCpuMs} raises the parent budget ${existing.budgetCpuMs}`);
307
+ else if (existing.requireNearMiss && !cfg.requireNearMiss)
308
+ no(`witness.${stage}.requireNearMiss cannot be switched off in a subdirectory`);
309
+ else
310
+ witness[stage] = cfg;
311
+ }
312
+ let operator = parent.operator;
313
+ if (child.operator !== undefined) {
314
+ if (operator === null)
315
+ operator = child.operator;
316
+ else if (!same(operator, child.operator))
317
+ no('"operator" is declared by a parent and cannot change: a subdirectory cannot add an approver');
318
+ }
319
+ if (!isOutermost && child.allowSubdirectoryTools !== undefined && child.allowSubdirectoryTools !== parent.allowSubdirectoryTools) {
320
+ no('"allowSubdirectoryTools" is decided by the outermost manifest');
321
+ }
322
+ let approvals = parent.approvals;
323
+ if (child.approvals !== undefined) {
324
+ if (isOutermost || same(approvals, child.approvals))
325
+ approvals = child.approvals;
326
+ else
327
+ no('"approvals" is declared by a parent and cannot change');
328
+ }
329
+ return {
330
+ profile: child.profile,
331
+ stateDirRaw: child.stateDir ?? null,
332
+ operator,
333
+ policy: policy,
334
+ scopes,
335
+ pins,
336
+ tools,
337
+ witness,
338
+ approvals,
339
+ watch: parent.watch || child.watch === true,
340
+ allowSubdirectoryTools: isOutermost ? child.allowSubdirectoryTools === true : parent.allowSubdirectoryTools,
341
+ };
342
+ }
343
+ /** Manifest files from `startDir` up to the filesystem root, outermost first. */
344
+ export function findManifestFiles(startDir) {
345
+ const found = [];
346
+ let dir = path.resolve(startDir);
347
+ for (;;) {
348
+ const candidate = path.join(dir, MANIFEST_FILE);
349
+ if (fs.existsSync(candidate))
350
+ found.unshift(candidate);
351
+ const parent = path.dirname(dir);
352
+ if (parent === dir)
353
+ break;
354
+ dir = parent;
355
+ }
356
+ return found;
357
+ }
358
+ /**
359
+ * Loads and merges the manifests that apply to `startDir`.
360
+ * Throws ManifestError when a file is invalid, when a subdirectory relaxes a parent,
361
+ * or when a required witness stage has no declaration.
362
+ */
363
+ export function loadManifest(startDir) {
364
+ const files = findManifestFiles(startDir);
365
+ if (files.length === 0)
366
+ throw new ManifestError([`no ${MANIFEST_FILE} found in ${path.resolve(startDir)} or above it. Run \`certal init\`.`]);
367
+ const problems = [];
368
+ let layer = emptyLayer();
369
+ for (const [index, file] of files.entries()) {
370
+ let raw;
371
+ try {
372
+ raw = JSON.parse(fs.readFileSync(file, 'utf8'));
373
+ }
374
+ catch (err) {
375
+ problems.push(`${file}: not valid JSON (${err.message})`);
376
+ continue;
377
+ }
378
+ const shape = validateManifest(raw, file);
379
+ if (shape.length > 0) {
380
+ problems.push(...shape);
381
+ continue;
382
+ }
383
+ layer = mergeLayer(layer, raw, file, problems, index === 0);
384
+ }
385
+ const required = (layer.policy.requiredWitnessStages ?? DEFAULT_POLICY.requiredWitnessStages);
386
+ for (const stage of required) {
387
+ if (layer.witness[stage] === undefined)
388
+ problems.push(`witness.${stage} is required by the policy and has no declaration`);
389
+ }
390
+ const scopeIds = new Set(layer.scopes.map((s) => s.id));
391
+ for (const pin of layer.pins) {
392
+ const pinned = layer.scopes.find((s) => s.id === pin.scopeId);
393
+ if (pin.scopeId !== '*' && !scopeIds.has(pin.scopeId))
394
+ problems.push(`pin "${pin.id}" names the unknown scope "${pin.scopeId}"`);
395
+ // A lease on a declared scope always has the class of that scope, so a pin on another class would never apply.
396
+ else if (pinned && pin.classId !== '*' && pin.classId !== pinned.classId) {
397
+ problems.push(`pin "${pin.id}" names the class "${pin.classId}", but the scope "${pin.scopeId}" has the class "${pinned.classId}": the pin would never apply. Use "*" or give those objects a scope of their own`);
398
+ }
399
+ else if (pin.scopeId === '*' && pin.classId !== '*' && layer.scopes.length > 0 && !layer.scopes.some((s) => s.classId === pin.classId)) {
400
+ problems.push(`pin "${pin.id}" names the class "${pin.classId}", which no declared scope has: the pin would never apply`);
401
+ }
402
+ }
403
+ // The same pattern in two scopes gives every matching file two owners, and such a file is refused.
404
+ const patternOwner = new Map();
405
+ for (const scope of layer.scopes) {
406
+ for (const pattern of scope.paths) {
407
+ const key = pattern.toLowerCase();
408
+ const other = patternOwner.get(key);
409
+ if (other !== undefined && other !== scope.id)
410
+ problems.push(`scopes "${other}" and "${scope.id}" both list the pattern "${pattern}"`);
411
+ else
412
+ patternOwner.set(key, scope.id);
413
+ }
414
+ }
415
+ if (problems.length > 0)
416
+ throw new ManifestError(problems);
417
+ const baseDir = path.dirname(files[files.length - 1]);
418
+ const { stateDirRaw, ...rest } = layer;
419
+ return { ...rest, baseDir, stateDir: path.resolve(baseDir, stateDirRaw ?? '.certal'), sources: files };
420
+ }
421
+ /**
422
+ * Lists the places where `next` would relax the policy `current`. Used when a manifest changes
423
+ * after the log has started: a tighter policy is applied, a looser one is refused.
424
+ */
425
+ export function policyRelaxations(current, next) {
426
+ const out = [];
427
+ const cur = current;
428
+ const nxt = next;
429
+ for (const key of LOWER_ONLY)
430
+ if (nxt[key] !== undefined && nxt[key] > cur[key])
431
+ out.push(`policy.${key}: ${String(cur[key])} -> ${String(nxt[key])}`);
432
+ for (const key of RAISE_ONLY)
433
+ if (nxt[key] !== undefined && nxt[key] < cur[key])
434
+ out.push(`policy.${key}: ${String(cur[key])} -> ${String(nxt[key])}`);
435
+ for (const key of ENABLE_ONLY)
436
+ if (nxt[key] === false && cur[key] === true)
437
+ out.push(`policy.${key}: true -> false`);
438
+ for (const key of FIXED)
439
+ if (nxt[key] !== undefined && nxt[key] !== cur[key])
440
+ out.push(`policy.${key}: ${String(cur[key])} -> ${String(nxt[key])}`);
441
+ if (next.resourcePoolCapacity !== undefined) {
442
+ for (const key of POOL_KEYS) {
443
+ const v = next.resourcePoolCapacity[key];
444
+ if (v !== undefined && v > current.resourcePoolCapacity[key])
445
+ out.push(`policy.resourcePoolCapacity.${key}: ${current.resourcePoolCapacity[key]} -> ${v}`);
446
+ }
447
+ }
448
+ if (next.requiredWitnessStages !== undefined) {
449
+ const dropped = current.requiredWitnessStages.filter((s) => !next.requiredWitnessStages?.includes(s));
450
+ if (dropped.length > 0)
451
+ out.push(`policy.requiredWitnessStages drops ${dropped.join(', ')}`);
452
+ }
453
+ return out;
454
+ }
455
+ /** The part of `next` that differs from `current`. Empty when the manifest policy is already in force. */
456
+ export function policyDifference(current, next) {
457
+ const diff = {};
458
+ for (const [key, value] of Object.entries(next)) {
459
+ const now = current[key];
460
+ const merged = key === 'resourcePoolCapacity' ? { ...now, ...value } : value;
461
+ if (!same(now, merged))
462
+ diff[key] = merged;
463
+ }
464
+ return diff;
465
+ }
@@ -0,0 +1,53 @@
1
+ import type { ApprovalToken, Binding } from '../kernel/index.ts';
2
+ /**
3
+ * The operator's Ed25519 key. It signs approval tokens and the commands that the CLI sends to a
4
+ * running server. The private key lives in the operator's home directory, never in a repository.
5
+ */
6
+ export interface OperatorKey {
7
+ readonly keyId: string;
8
+ readonly publicKeyPem: string;
9
+ readonly privateKeyPem: string;
10
+ }
11
+ export interface SignedOperatorCommand {
12
+ readonly body: {
13
+ readonly command: string;
14
+ readonly args: unknown;
15
+ readonly issuedAtMs: number;
16
+ readonly nonce: string;
17
+ };
18
+ readonly keyId: string;
19
+ readonly signature: string;
20
+ }
21
+ /** A signed command is accepted only this close to the server clock. */
22
+ export declare const COMMAND_MAX_AGE_MS = 60000;
23
+ /** Directory of operator secrets. `CERTAL_HOME` overrides the default `~/.certal`. */
24
+ export declare function operatorHome(): string;
25
+ export declare function operatorKeyPath(): string;
26
+ /**
27
+ * Directory of the per-agent bearer tokens of the HTTP transport for one project. It is in the
28
+ * operator home, not in the project, so an agent that can read the project files does not find
29
+ * the token of another agent there.
30
+ */
31
+ export declare function agentTokenDir(projectDir: string): string;
32
+ export declare function keyIdOf(publicKeyPem: string): string;
33
+ /** Reads the operator key. Returns null when there is none. */
34
+ export declare function loadOperatorKey(file?: string): OperatorKey | null;
35
+ /**
36
+ * Creates the operator key when it does not exist yet. The file is written with mode 0600.
37
+ * On Windows the mode has no effect, and the file is protected by the profile directory only.
38
+ */
39
+ export declare function ensureOperatorKey(file?: string): {
40
+ readonly key: OperatorKey;
41
+ readonly created: boolean;
42
+ };
43
+ /** Builds an approval token for the content of an attempt and signs it with the operator key. */
44
+ export declare function signApprovalToken(key: OperatorKey, input: {
45
+ readonly approvalId: string;
46
+ readonly humanId: string;
47
+ readonly attemptId: string;
48
+ readonly binding: Binding;
49
+ readonly expiresAtMs: number;
50
+ }): ApprovalToken;
51
+ export declare function signOperatorCommand(key: OperatorKey, command: string, args: unknown, nowMs: number): SignedOperatorCommand;
52
+ /** Checks the signature of a command against the operator keys of the manifest. It does not check age or replay. */
53
+ export declare function verifyOperatorCommand(signed: SignedOperatorCommand, publicKeys: Readonly<Record<string, string>>): boolean;
@@ -0,0 +1,81 @@
1
+ import { createHash, createPublicKey, generateKeyPairSync, randomBytes, sign, verify } from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { hashBinding, jcs, signApprovalEd25519 } from '../kernel/index.js';
6
+ const COMMAND_DOMAIN = 'certal:v1:operator_cmd:1\0';
7
+ /** A signed command is accepted only this close to the server clock. */
8
+ export const COMMAND_MAX_AGE_MS = 60_000;
9
+ /** Directory of operator secrets. `CERTAL_HOME` overrides the default `~/.certal`. */
10
+ export function operatorHome() {
11
+ return process.env.CERTAL_HOME ?? path.join(os.homedir(), '.certal');
12
+ }
13
+ export function operatorKeyPath() {
14
+ return path.join(operatorHome(), 'operator.key');
15
+ }
16
+ /**
17
+ * Directory of the per-agent bearer tokens of the HTTP transport for one project. It is in the
18
+ * operator home, not in the project, so an agent that can read the project files does not find
19
+ * the token of another agent there.
20
+ */
21
+ export function agentTokenDir(projectDir) {
22
+ const id = createHash('sha256').update(path.resolve(projectDir)).digest('hex').slice(0, 16);
23
+ return path.join(operatorHome(), 'run', id, 'agents');
24
+ }
25
+ export function keyIdOf(publicKeyPem) {
26
+ const der = createPublicKey(publicKeyPem).export({ type: 'spki', format: 'der' });
27
+ return `op-${createHash('sha256').update(der).digest('hex').slice(0, 16)}`;
28
+ }
29
+ function fromPrivatePem(privateKeyPem) {
30
+ const publicKeyPem = createPublicKey(privateKeyPem).export({ type: 'spki', format: 'pem' }).toString();
31
+ return { keyId: keyIdOf(publicKeyPem), publicKeyPem, privateKeyPem };
32
+ }
33
+ /** Reads the operator key. Returns null when there is none. */
34
+ export function loadOperatorKey(file = operatorKeyPath()) {
35
+ if (!fs.existsSync(file))
36
+ return null;
37
+ return fromPrivatePem(fs.readFileSync(file, 'utf8'));
38
+ }
39
+ /**
40
+ * Creates the operator key when it does not exist yet. The file is written with mode 0600.
41
+ * On Windows the mode has no effect, and the file is protected by the profile directory only.
42
+ */
43
+ export function ensureOperatorKey(file = operatorKeyPath()) {
44
+ const existing = loadOperatorKey(file);
45
+ if (existing)
46
+ return { key: existing, created: false };
47
+ const { privateKey } = generateKeyPairSync('ed25519');
48
+ const privateKeyPem = privateKey.export({ type: 'pkcs8', format: 'pem' }).toString();
49
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
50
+ fs.writeFileSync(file, privateKeyPem, { mode: 0o600, flag: 'wx' });
51
+ return { key: fromPrivatePem(privateKeyPem), created: true };
52
+ }
53
+ /** Builds an approval token for the content of an attempt and signs it with the operator key. */
54
+ export function signApprovalToken(key, input) {
55
+ const value = signApprovalEd25519(key.privateKeyPem, {
56
+ approvalId: input.approvalId,
57
+ humanId: input.humanId,
58
+ attemptId: input.attemptId,
59
+ bindingHash: hashBinding(input.binding.diffHash, input.binding.scopeHash, input.binding.inputSnapshotHash),
60
+ expiresAtMs: input.expiresAtMs,
61
+ singleUse: true,
62
+ });
63
+ return { ...input, singleUse: true, signature: { algorithm: 'Ed25519', keyId: key.keyId, value } };
64
+ }
65
+ export function signOperatorCommand(key, command, args, nowMs) {
66
+ const body = { command, args, issuedAtMs: nowMs, nonce: randomBytes(12).toString('hex') };
67
+ const signature = sign(null, Buffer.from(COMMAND_DOMAIN + jcs(body), 'utf8'), key.privateKeyPem).toString('base64');
68
+ return { body, keyId: key.keyId, signature };
69
+ }
70
+ /** Checks the signature of a command against the operator keys of the manifest. It does not check age or replay. */
71
+ export function verifyOperatorCommand(signed, publicKeys) {
72
+ const pem = publicKeys[signed.keyId];
73
+ if (!pem)
74
+ return false;
75
+ try {
76
+ return verify(null, Buffer.from(COMMAND_DOMAIN + jcs(signed.body), 'utf8'), pem, Buffer.from(signed.signature, 'base64'));
77
+ }
78
+ catch {
79
+ return false;
80
+ }
81
+ }