certal 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/.claude-plugin/plugin.json +11 -0
  2. package/CHANGELOG.md +32 -0
  3. package/LICENSE +21 -0
  4. package/README.md +277 -2
  5. package/SECURITY.md +36 -0
  6. package/bin/certal.mjs +12 -0
  7. package/certal.schema.json +156 -0
  8. package/dist/adapters/approval-channel.d.ts +44 -0
  9. package/dist/adapters/approval-channel.js +74 -0
  10. package/dist/adapters/commands.d.ts +73 -0
  11. package/dist/adapters/commands.js +185 -0
  12. package/dist/adapters/contracts.d.ts +59 -0
  13. package/dist/adapters/contracts.js +1 -0
  14. package/dist/adapters/file-watcher.d.ts +53 -0
  15. package/dist/adapters/file-watcher.js +142 -0
  16. package/dist/adapters/in-memory.d.ts +53 -0
  17. package/dist/adapters/in-memory.js +165 -0
  18. package/dist/adapters/index.d.ts +8 -0
  19. package/dist/adapters/index.js +8 -0
  20. package/dist/adapters/manifest.d.ts +105 -0
  21. package/dist/adapters/manifest.js +438 -0
  22. package/dist/adapters/operator-auth.d.ts +47 -0
  23. package/dist/adapters/operator-auth.js +72 -0
  24. package/dist/adapters/tool-sdk.d.ts +150 -0
  25. package/dist/adapters/tool-sdk.js +336 -0
  26. package/dist/cli/index.d.ts +1 -0
  27. package/dist/cli/index.js +1 -0
  28. package/dist/cli/main.d.ts +1 -0
  29. package/dist/cli/main.js +386 -0
  30. package/dist/kernel/common.d.ts +46 -0
  31. package/dist/kernel/common.js +238 -0
  32. package/dist/kernel/crypto.d.ts +35 -0
  33. package/dist/kernel/crypto.js +54 -0
  34. package/dist/kernel/effects.d.ts +4 -0
  35. package/dist/kernel/effects.js +178 -0
  36. package/dist/kernel/index.d.ts +9 -0
  37. package/dist/kernel/index.js +9 -0
  38. package/dist/kernel/jcs.d.ts +24 -0
  39. package/dist/kernel/jcs.js +93 -0
  40. package/dist/kernel/leases.d.ts +11 -0
  41. package/dist/kernel/leases.js +86 -0
  42. package/dist/kernel/step.d.ts +10 -0
  43. package/dist/kernel/step.js +967 -0
  44. package/dist/kernel/types.d.ts +538 -0
  45. package/dist/kernel/types.js +1 -0
  46. package/dist/kernel/undo.d.ts +4 -0
  47. package/dist/kernel/undo.js +180 -0
  48. package/dist/kernel/validation.d.ts +13 -0
  49. package/dist/kernel/validation.js +307 -0
  50. package/dist/kernel/witness.d.ts +34 -0
  51. package/dist/kernel/witness.js +279 -0
  52. package/dist/mcp/host.d.ts +141 -0
  53. package/dist/mcp/host.js +517 -0
  54. package/dist/mcp/index.d.ts +2 -0
  55. package/dist/mcp/index.js +2 -0
  56. package/dist/mcp/server.d.ts +70 -0
  57. package/dist/mcp/server.js +508 -0
  58. package/dist/runtime/dp1.d.ts +48 -0
  59. package/dist/runtime/dp1.js +229 -0
  60. package/dist/runtime/engine.d.ts +86 -0
  61. package/dist/runtime/engine.js +320 -0
  62. package/dist/runtime/index.d.ts +4 -0
  63. package/dist/runtime/index.js +4 -0
  64. package/dist/runtime/outbox.d.ts +69 -0
  65. package/dist/runtime/outbox.js +238 -0
  66. package/dist/runtime/store.d.ts +204 -0
  67. package/dist/runtime/store.js +746 -0
  68. package/package.json +91 -4
  69. package/presets/exchange-firewall.json +40 -0
  70. package/presets/sdk.json +32 -0
  71. package/presets/solver.json +22 -0
  72. package/presets/vibeops.json +34 -0
  73. package/skills/certal/SKILL.md +49 -0
@@ -0,0 +1,74 @@
1
+ import { createKeyringSignatureVerifier, hashBinding } from '../kernel/index.js';
2
+ /**
3
+ * Default channel. It sends nothing: the attempt stays in the pending list of `certal status`
4
+ * until the operator runs `certal approve <attemptId>` with the local Ed25519 key.
5
+ */
6
+ export class LocalCliApprovalChannel {
7
+ name = 'local-cli';
8
+ async notify(_notice) {
9
+ return null;
10
+ }
11
+ }
12
+ /** True when `token` is an Ed25519-signed approval of exactly this attempt content by a known operator key. */
13
+ export function isValidSignedApproval(token, notice, publicKeys) {
14
+ if (typeof token !== 'object' || token === null)
15
+ return false;
16
+ const t = token;
17
+ if (typeof t.approvalId !== 'string' || typeof t.humanId !== 'string' || t.attemptId !== notice.attemptId)
18
+ return false;
19
+ if (typeof t.expiresAtMs !== 'number' || t.singleUse !== true || !t.binding || !t.signature)
20
+ return false;
21
+ if (t.signature.algorithm !== 'Ed25519')
22
+ return false;
23
+ const bindingHash = hashBinding(t.binding.diffHash, t.binding.scopeHash, t.binding.inputSnapshotHash);
24
+ if (bindingHash !== notice.bindingHash)
25
+ return false;
26
+ return createKeyringSignatureVerifier({ ed25519PublicKeysPem: publicKeys }).verifyApprovalSignature({
27
+ algorithm: 'Ed25519',
28
+ keyId: t.signature.keyId,
29
+ signature: t.signature.value,
30
+ payload: { approvalId: t.approvalId, humanId: t.humanId, attemptId: t.attemptId, bindingHash, expiresAtMs: t.expiresAtMs, singleUse: true },
31
+ });
32
+ }
33
+ /**
34
+ * Sends the binding hash, a summary of the change and the expiry to a webhook. The receiver may
35
+ * answer with `{ "approvalToken": ... }`. Only a token with a valid Ed25519 signature of a known
36
+ * operator key over this exact binding is passed on. Anything else is dropped.
37
+ */
38
+ export class WebhookApprovalChannel {
39
+ name = 'webhook';
40
+ url;
41
+ publicKeys;
42
+ timeoutMs;
43
+ constructor(url, publicKeys, timeoutMs = 10_000) {
44
+ this.url = url;
45
+ this.publicKeys = publicKeys;
46
+ this.timeoutMs = timeoutMs;
47
+ }
48
+ async notify(notice) {
49
+ try {
50
+ const response = await fetch(this.url, {
51
+ method: 'POST',
52
+ headers: { 'content-type': 'application/json' },
53
+ body: JSON.stringify({
54
+ attemptId: notice.attemptId,
55
+ scopeId: notice.scopeId,
56
+ toolId: notice.toolId,
57
+ reason: notice.reason,
58
+ binding: notice.binding,
59
+ bindingHash: notice.bindingHash,
60
+ diffSummary: notice.diffSummary,
61
+ expiresAtMs: notice.expiresAtMs,
62
+ }),
63
+ signal: AbortSignal.timeout(this.timeoutMs),
64
+ });
65
+ if (!response.ok)
66
+ return null;
67
+ const answer = (await response.json());
68
+ return isValidSignedApproval(answer.approvalToken, notice, this.publicKeys) ? answer.approvalToken : null;
69
+ }
70
+ catch {
71
+ return null;
72
+ }
73
+ }
74
+ }
@@ -0,0 +1,73 @@
1
+ import type { Binding, StateOp, WitnessStage } from '../kernel/index.ts';
2
+ import type { DeliveryAdapterOutcome, OutboxPreflightCheck, OutboxRecord, OutboxTransport } from '../runtime/index.ts';
3
+ import type { WitnessStageExecution } from './contracts.ts';
4
+ import type { Command, ManifestTool, ManifestWitnessStage } from './manifest.ts';
5
+ /**
6
+ * Runs the commands that a manifest declares: witness stages and the deliver, reconcile,
7
+ * compensate and preflight steps of a tool. A command is a list of strings and runs without
8
+ * a shell. It reads one JSON document on stdin and answers with its exit code.
9
+ */
10
+ export interface CommandResult {
11
+ readonly exitCode: number | null;
12
+ readonly timedOut: boolean;
13
+ readonly wallMs: number;
14
+ readonly stdout: string;
15
+ readonly stderr: string;
16
+ }
17
+ /**
18
+ * Runs one command with a hard wall-clock limit. When the limit passes, the whole process tree is
19
+ * killed and the call returns as soon as the process is gone, also when a grandchild still holds
20
+ * the output pipes.
21
+ */
22
+ export declare function runCommand(command: Command, input: unknown, cwd: string, timeoutMs: number): Promise<CommandResult>;
23
+ export interface WitnessContext {
24
+ readonly verifyId: string;
25
+ readonly attemptId: string;
26
+ readonly stage: WitnessStage;
27
+ readonly binding: Binding;
28
+ readonly scopeId: string;
29
+ readonly classId: string;
30
+ readonly toolId: string;
31
+ readonly ops: readonly StateOp[];
32
+ /** Budget that the kernel grants to this stage. */
33
+ readonly budgetCpuMs: number;
34
+ /** True when the kernel itself requires a near-miss proof for this stage. */
35
+ readonly requireNearMiss: boolean;
36
+ }
37
+ /**
38
+ * Runs a declared witness stage in a child process. The budget of a stage is the smaller of the
39
+ * manifest budget and the budget that the kernel grants, enforced as a wall-clock limit, which is
40
+ * never looser than the CPU time. Exit code 0 is PASS, 1 is FAIL. A timeout, a crash or any other
41
+ * exit code is UNKNOWN, which the kernel does not accept as proof.
42
+ *
43
+ * A near-miss proof is needed when the manifest or the kernel asks for it. Without a passing
44
+ * probe the stage reports FAIL, also where only the manifest asked.
45
+ */
46
+ export declare class CommandWitness {
47
+ private readonly stages;
48
+ private readonly cwd;
49
+ constructor(stages: Partial<Readonly<Record<WitnessStage, ManifestWitnessStage>>>, cwd: string);
50
+ /** True when the manifest asks for a near-miss proof at this stage. */
51
+ requiresNearMiss(stage: WitnessStage): boolean;
52
+ runStage(ctx: WitnessContext): Promise<WitnessStageExecution>;
53
+ }
54
+ /**
55
+ * Outbox transport backed by the commands of the declared tools. The recipient of an effect is
56
+ * the tool id. Exit code 0 means applied, 2 means refused, anything else means unknown, and an
57
+ * unknown outcome can only be reconciled. A tool without a command for a step answers unknown.
58
+ */
59
+ export declare class CommandTransport implements OutboxTransport {
60
+ private readonly tools;
61
+ private readonly cwd;
62
+ private readonly timeoutMs;
63
+ constructor(tools: Readonly<Record<string, ManifestTool>>, cwd: string, timeoutMs?: number);
64
+ private run;
65
+ deliver(record: OutboxRecord): Promise<DeliveryAdapterOutcome>;
66
+ reconcile(record: OutboxRecord): Promise<DeliveryAdapterOutcome>;
67
+ compensate(record: OutboxRecord): Promise<DeliveryAdapterOutcome>;
68
+ }
69
+ /**
70
+ * Preflight check of the outbox: runs the tool's `preflightCommand` right before a send.
71
+ * Exit code 0 lets the send go. The command runs asynchronously, so a human event is never held behind it.
72
+ */
73
+ export declare function createCommandPreflight(tools: Readonly<Record<string, ManifestTool>>, cwd: string, timeoutMs?: number): OutboxPreflightCheck;
@@ -0,0 +1,185 @@
1
+ import { spawn } from 'node:child_process';
2
+ const OUTPUT_LIMIT = 64 * 1024;
3
+ const DEFAULT_TIMEOUT_MS = 60_000;
4
+ /** Kills a process with everything it started. A plain kill would leave grandchildren running. */
5
+ function killTree(child) {
6
+ if (child.pid === undefined)
7
+ return;
8
+ if (process.platform === 'win32') {
9
+ spawn('taskkill', ['/PID', String(child.pid), '/T', '/F'], { stdio: 'ignore', windowsHide: true }).on('error', () => child.kill());
10
+ return;
11
+ }
12
+ try {
13
+ // The child leads its own process group (see `detached` below), so the negative pid addresses the group.
14
+ process.kill(-child.pid, 'SIGKILL');
15
+ }
16
+ catch {
17
+ child.kill('SIGKILL');
18
+ }
19
+ }
20
+ /**
21
+ * Runs one command with a hard wall-clock limit. When the limit passes, the whole process tree is
22
+ * killed and the call returns as soon as the process is gone, also when a grandchild still holds
23
+ * the output pipes.
24
+ */
25
+ export function runCommand(command, input, cwd, timeoutMs) {
26
+ return new Promise((resolve) => {
27
+ const started = performance.now();
28
+ let stdout = '';
29
+ let stderr = '';
30
+ let timedOut = false;
31
+ let settled = false;
32
+ let drain = null;
33
+ const finish = (exitCode) => {
34
+ if (settled)
35
+ return;
36
+ settled = true;
37
+ clearTimeout(timer);
38
+ if (drain)
39
+ clearTimeout(drain);
40
+ resolve({ exitCode: timedOut ? null : exitCode, timedOut, wallMs: Math.round(performance.now() - started), stdout, stderr });
41
+ };
42
+ const child = spawn(command[0], command.slice(1), {
43
+ cwd,
44
+ stdio: ['pipe', 'pipe', 'pipe'],
45
+ windowsHide: true,
46
+ detached: process.platform !== 'win32',
47
+ });
48
+ const timer = setTimeout(() => {
49
+ timedOut = true;
50
+ killTree(child);
51
+ child.stdout.destroy();
52
+ child.stderr.destroy();
53
+ // Normally `exit` follows at once. This is the last resort for a process that cannot be killed.
54
+ drain = setTimeout(() => finish(null), 1000);
55
+ }, Math.max(1, timeoutMs));
56
+ child.stdout.on('data', (chunk) => { if (stdout.length < OUTPUT_LIMIT)
57
+ stdout += chunk.toString('utf8'); });
58
+ child.stderr.on('data', (chunk) => { if (stderr.length < OUTPUT_LIMIT)
59
+ stderr += chunk.toString('utf8'); });
60
+ child.on('error', (err) => { stderr += String(err); finish(null); });
61
+ child.on('exit', (code) => {
62
+ if (timedOut)
63
+ finish(null);
64
+ // `close` brings the rest of the output. A grandchild that keeps the pipes open must not hold the answer.
65
+ else if (!drain)
66
+ drain = setTimeout(() => finish(code), 200);
67
+ });
68
+ child.on('close', (code) => finish(code));
69
+ child.stdin.on('error', () => { });
70
+ child.stdin.end(JSON.stringify(input));
71
+ });
72
+ }
73
+ /**
74
+ * Runs a declared witness stage in a child process. The budget of a stage is the smaller of the
75
+ * manifest budget and the budget that the kernel grants, enforced as a wall-clock limit, which is
76
+ * never looser than the CPU time. Exit code 0 is PASS, 1 is FAIL. A timeout, a crash or any other
77
+ * exit code is UNKNOWN, which the kernel does not accept as proof.
78
+ *
79
+ * A near-miss proof is needed when the manifest or the kernel asks for it. Without a passing
80
+ * probe the stage reports FAIL, also where only the manifest asked.
81
+ */
82
+ export class CommandWitness {
83
+ stages;
84
+ cwd;
85
+ constructor(stages, cwd) {
86
+ this.stages = stages;
87
+ this.cwd = cwd;
88
+ }
89
+ /** True when the manifest asks for a near-miss proof at this stage. */
90
+ requiresNearMiss(stage) {
91
+ return this.stages[stage]?.requireNearMiss === true;
92
+ }
93
+ async runStage(ctx) {
94
+ const cfg = this.stages[ctx.stage];
95
+ if (cfg === undefined)
96
+ return { verifyId: ctx.verifyId, stage: ctx.stage, verdict: 'UNKNOWN', cpuMs: 0, nearMissPassed: false };
97
+ const needsNearMiss = cfg.requireNearMiss || ctx.requireNearMiss;
98
+ if (cfg.command === undefined) {
99
+ // `accept` has no check, so it cannot show a near miss.
100
+ return { verifyId: ctx.verifyId, stage: ctx.stage, verdict: needsNearMiss ? 'FAIL' : 'PASS', cpuMs: 0, nearMissPassed: false };
101
+ }
102
+ const budget = Math.min(cfg.budgetCpuMs, ctx.budgetCpuMs);
103
+ if (budget <= 0)
104
+ return { verifyId: ctx.verifyId, stage: ctx.stage, verdict: 'UNKNOWN', cpuMs: 0, nearMissPassed: false };
105
+ const main = await runCommand(cfg.command, { ...ctx, budgetCpuMs: budget }, this.cwd, budget);
106
+ let verdict = main.timedOut ? 'UNKNOWN' : main.exitCode === 0 ? 'PASS' : main.exitCode === 1 ? 'FAIL' : 'UNKNOWN';
107
+ let spent = Math.min(main.wallMs, budget);
108
+ let nearMissPassed = false;
109
+ if (verdict === 'PASS' && needsNearMiss) {
110
+ if (cfg.nearMissProbeCommand !== undefined && spent < budget) {
111
+ const probe = await runCommand(cfg.nearMissProbeCommand, { ...ctx, budgetCpuMs: budget - spent }, this.cwd, budget - spent);
112
+ nearMissPassed = !probe.timedOut && probe.exitCode === 0;
113
+ spent = Math.min(budget, spent + probe.wallMs);
114
+ }
115
+ if (!nearMissPassed)
116
+ verdict = 'FAIL';
117
+ }
118
+ return { verifyId: ctx.verifyId, stage: ctx.stage, verdict, cpuMs: spent, nearMissPassed };
119
+ }
120
+ }
121
+ function outcomeOf(result) {
122
+ if (result.timedOut || result.exitCode === null)
123
+ return { status: 'UNKNOWN', reason: result.timedOut ? 'COMMAND_TIMEOUT' : 'COMMAND_NOT_STARTED' };
124
+ if (result.exitCode === 0)
125
+ return { status: 'APPLIED' };
126
+ if (result.exitCode === 2)
127
+ return { status: 'REFUSED', reason: result.stderr.trim().slice(0, 200) || 'REFUSED_BY_COMMAND' };
128
+ return { status: 'UNKNOWN', reason: `EXIT_${result.exitCode}` };
129
+ }
130
+ function recordInput(record) {
131
+ let payload = null;
132
+ try {
133
+ payload = JSON.parse(record.payloadJson);
134
+ }
135
+ catch {
136
+ payload = record.payloadJson;
137
+ }
138
+ return { effectId: record.effectId, effectKind: record.effectKind, batchId: record.batchId, scopeId: record.scopeId, classId: record.classId, toolId: record.recipientId, payload };
139
+ }
140
+ /**
141
+ * Outbox transport backed by the commands of the declared tools. The recipient of an effect is
142
+ * the tool id. Exit code 0 means applied, 2 means refused, anything else means unknown, and an
143
+ * unknown outcome can only be reconciled. A tool without a command for a step answers unknown.
144
+ */
145
+ export class CommandTransport {
146
+ tools;
147
+ cwd;
148
+ timeoutMs;
149
+ constructor(tools, cwd, timeoutMs = DEFAULT_TIMEOUT_MS) {
150
+ this.tools = tools;
151
+ this.cwd = cwd;
152
+ this.timeoutMs = timeoutMs;
153
+ }
154
+ async run(record, pick, step) {
155
+ const tool = this.tools[record.recipientId];
156
+ const command = tool ? pick(tool) : undefined;
157
+ if (command === undefined)
158
+ return { status: 'UNKNOWN', reason: `NO_${step}_COMMAND` };
159
+ return outcomeOf(await runCommand(command, recordInput(record), this.cwd, this.timeoutMs));
160
+ }
161
+ deliver(record) {
162
+ return this.run(record, (t) => t.deliverCommand, 'DELIVER');
163
+ }
164
+ reconcile(record) {
165
+ return this.run(record, (t) => t.reconcileCommand, 'RECONCILE');
166
+ }
167
+ compensate(record) {
168
+ return this.run(record, (t) => t.compensateCommand, 'COMPENSATE');
169
+ }
170
+ }
171
+ /**
172
+ * Preflight check of the outbox: runs the tool's `preflightCommand` right before a send.
173
+ * Exit code 0 lets the send go. The command runs asynchronously, so a human event is never held behind it.
174
+ */
175
+ export function createCommandPreflight(tools, cwd, timeoutMs = 10_000) {
176
+ return async (record, _state, nowMs) => {
177
+ const command = tools[record.recipientId]?.preflightCommand;
178
+ if (command === undefined)
179
+ return { ok: true };
180
+ const result = await runCommand(command, { ...recordInput(record), nowMs }, cwd, timeoutMs);
181
+ if (!result.timedOut && result.exitCode === 0)
182
+ return { ok: true };
183
+ return { ok: false, reason: result.timedOut ? 'PREFLIGHT_TIMEOUT' : result.stderr.trim().slice(0, 200) || `PREFLIGHT_EXIT_${String(result.exitCode)}` };
184
+ };
185
+ }
@@ -0,0 +1,59 @@
1
+ import type { Binding, EventEnvelope, Grade, InputSnapshot, KernelState, OptimizationVector, Reversibility, StateOp, StepResult, WitnessStage, WitnessVerdictCode } from '../kernel/index.ts';
2
+ import type { DeliveryAdapterOutcome, OutboxRecord } from '../runtime/index.ts';
3
+ export interface ScopeReadResult {
4
+ readonly scopeId: string;
5
+ readonly classId: string;
6
+ readonly revision: number;
7
+ readonly scopeHash: string;
8
+ readonly values: Readonly<Record<string, unknown>>;
9
+ }
10
+ export interface StateSubstrateAdapter {
11
+ readScope(state: KernelState, scopeId: string, classId: string): ScopeReadResult;
12
+ classifyReversibility(op: StateOp): Reversibility;
13
+ }
14
+ export interface EvaluationResult {
15
+ readonly hardViolations: readonly string[];
16
+ readonly pinViolations: readonly string[];
17
+ readonly objectiveMicroUnits: number;
18
+ readonly confidence: Grade;
19
+ }
20
+ export interface DeterministicEvaluator {
21
+ freezeInputs(scopeId: string, rawInputs: unknown, confidence: Grade, nowMs: number): InputSnapshot;
22
+ evaluate(state: KernelState, snapshot: InputSnapshot): EvaluationResult;
23
+ }
24
+ export interface ExecutionActorPool {
25
+ getExecutorMeta(): {
26
+ readonly id: string;
27
+ readonly tier: number;
28
+ readonly version: string;
29
+ };
30
+ propose(context: {
31
+ readonly scopeId: string;
32
+ readonly classId: string;
33
+ readonly snapshot: InputSnapshot;
34
+ }): Promise<readonly StateOp[]>;
35
+ }
36
+ export interface WitnessStageExecution {
37
+ readonly verifyId: string;
38
+ readonly stage: WitnessStage;
39
+ readonly verdict: WitnessVerdictCode;
40
+ readonly cpuMs: number;
41
+ readonly nearMissPassed: boolean;
42
+ readonly optimization?: OptimizationVector;
43
+ }
44
+ export interface WitnessOracle {
45
+ runStage(intent: {
46
+ readonly verifyId: string;
47
+ readonly attemptId: string;
48
+ readonly stage: WitnessStage;
49
+ readonly budgetCpuMs: number;
50
+ readonly requireNearMiss: boolean;
51
+ readonly binding: Binding;
52
+ }): Promise<WitnessStageExecution>;
53
+ }
54
+ export interface DeploymentTransport {
55
+ submit(envelope: EventEnvelope): Promise<StepResult>;
56
+ deliver(record: OutboxRecord): Promise<DeliveryAdapterOutcome>;
57
+ reconcile(record: OutboxRecord): Promise<DeliveryAdapterOutcome>;
58
+ compensate(record: OutboxRecord): Promise<DeliveryAdapterOutcome>;
59
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,53 @@
1
+ import type { ManifestScope } from './manifest.ts';
2
+ /**
3
+ * Optional watcher that turns a manual file save into a human edit.
4
+ *
5
+ * The slot of a file is `(scope, class, relative path, "sha256")` and holds the hash of the file
6
+ * content. An agent declares the new hash in its batch before it writes the file, so a write that
7
+ * matches the slot is the agent's own. Any other change is reported as a human edit, which raises
8
+ * the scope epoch and evicts a colliding agent lease. A deleted file is reported with the value null.
9
+ *
10
+ * Limit: the watcher cannot tell who wrote a file. A process that writes a file without a batch
11
+ * is treated as the human. Use the watcher only where agents write through the gate.
12
+ */
13
+ export declare const FILE_FIELD = "sha256";
14
+ /** Converts a glob pattern with `**`, `*` and `?` to a regular expression over `/`-separated paths. */
15
+ export declare function globToRegExp(glob: string): RegExp;
16
+ /**
17
+ * One spelling for an object id that may be a path: `/` as the separator, no leading `./`, no empty
18
+ * segments. Returns null for an absolute path and for a path with a `..` segment, so two spellings
19
+ * can never name the same file and no id can leave the project directory.
20
+ */
21
+ export declare function normalizeObjectPath(input: string): string | null;
22
+ /** The first declared scope whose patterns match the path, or null. The order of the scopes in the manifest decides. */
23
+ export declare function scopeOfPath(scopes: readonly ManifestScope[], relativePath: string): ManifestScope | null;
24
+ export declare function hashFile(file: string): string | null;
25
+ export interface FileEditSink {
26
+ /** Current value of the slot of a file, or undefined when the slot does not exist. */
27
+ currentHash(scope: ManifestScope, relativePath: string): unknown;
28
+ /** `hash` is null when the file was deleted. */
29
+ humanEdit(scope: ManifestScope, relativePath: string, hash: string | null): Promise<void>;
30
+ }
31
+ export declare class HumanFileWatcher {
32
+ private readonly baseDir;
33
+ private readonly scopes;
34
+ private readonly sink;
35
+ private readonly ignore;
36
+ private readonly debounceMs;
37
+ private readonly timers;
38
+ private watcher;
39
+ private chain;
40
+ constructor(options: {
41
+ readonly baseDir: string;
42
+ readonly scopes: readonly ManifestScope[];
43
+ readonly sink: FileEditSink;
44
+ readonly ignore?: readonly string[];
45
+ readonly debounceMs?: number;
46
+ });
47
+ start(): void;
48
+ /** Compares one file with its slot and reports a human edit when they differ. */
49
+ inspect(relativePath: string): Promise<void>;
50
+ /** Resolves when every change seen so far has been handled. */
51
+ settled(): Promise<void>;
52
+ stop(): void;
53
+ }
@@ -0,0 +1,142 @@
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
+ /** Converts a glob pattern with `**`, `*` and `?` to a regular expression over `/`-separated paths. */
17
+ export function globToRegExp(glob) {
18
+ let out = '';
19
+ for (let i = 0; i < glob.length; i += 1) {
20
+ const ch = glob[i];
21
+ if (ch === '*') {
22
+ if (glob[i + 1] === '*') {
23
+ i += 1;
24
+ if (glob[i + 1] === '/') {
25
+ i += 1;
26
+ out += '(?:.*/)?';
27
+ }
28
+ else
29
+ out += '.*';
30
+ }
31
+ else
32
+ out += '[^/]*';
33
+ }
34
+ else if (ch === '?')
35
+ out += '[^/]';
36
+ else
37
+ out += ch.replace(/[.+^${}()|[\]\\]/g, '\\$&');
38
+ }
39
+ return new RegExp(`^${out}$`);
40
+ }
41
+ /**
42
+ * One spelling for an object id that may be a path: `/` as the separator, no leading `./`, no empty
43
+ * segments. Returns null for an absolute path and for a path with a `..` segment, so two spellings
44
+ * can never name the same file and no id can leave the project directory.
45
+ */
46
+ export function normalizeObjectPath(input) {
47
+ if (typeof input !== 'string' || input === '')
48
+ return null;
49
+ const slashed = input.replace(/\\/g, '/');
50
+ if (slashed.startsWith('/') || /^[A-Za-z]:(\/|$)/.test(slashed))
51
+ return null;
52
+ const parts = slashed.split('/').filter((segment) => segment !== '' && segment !== '.');
53
+ if (parts.length === 0 || parts.includes('..'))
54
+ return null;
55
+ return parts.join('/');
56
+ }
57
+ /** The first declared scope whose patterns match the path, or null. The order of the scopes in the manifest decides. */
58
+ export function scopeOfPath(scopes, relativePath) {
59
+ const normalized = normalizeObjectPath(relativePath);
60
+ if (normalized === null)
61
+ return null;
62
+ for (const scope of scopes) {
63
+ if (scope.paths.some((pattern) => globToRegExp(pattern).test(normalized)))
64
+ return scope;
65
+ }
66
+ return null;
67
+ }
68
+ export function hashFile(file) {
69
+ try {
70
+ return createHash('sha256').update(fs.readFileSync(file)).digest('hex');
71
+ }
72
+ catch {
73
+ return null;
74
+ }
75
+ }
76
+ export class HumanFileWatcher {
77
+ baseDir;
78
+ scopes;
79
+ sink;
80
+ ignore;
81
+ debounceMs;
82
+ timers = new Map();
83
+ watcher = null;
84
+ chain = Promise.resolve();
85
+ constructor(options) {
86
+ this.baseDir = options.baseDir;
87
+ this.scopes = options.scopes;
88
+ this.sink = options.sink;
89
+ this.ignore = options.ignore ?? ['.git', 'node_modules', '.certal'];
90
+ this.debounceMs = options.debounceMs ?? 50;
91
+ }
92
+ start() {
93
+ if (this.watcher)
94
+ return;
95
+ this.watcher = fs.watch(this.baseDir, { recursive: true }, (_event, filename) => {
96
+ if (typeof filename !== 'string')
97
+ return;
98
+ const relativePath = filename.split(path.sep).join('/');
99
+ if (this.ignore.some((dir) => relativePath === dir || relativePath.startsWith(`${dir}/`)))
100
+ return;
101
+ const pending = this.timers.get(relativePath);
102
+ if (pending)
103
+ clearTimeout(pending);
104
+ this.timers.set(relativePath, setTimeout(() => {
105
+ this.timers.delete(relativePath);
106
+ this.chain = this.chain.then(() => this.inspect(relativePath)).catch(() => { });
107
+ }, this.debounceMs));
108
+ });
109
+ }
110
+ /** Compares one file with its slot and reports a human edit when they differ. */
111
+ async inspect(relativePath) {
112
+ const scope = scopeOfPath(this.scopes, relativePath);
113
+ if (!scope)
114
+ return;
115
+ const file = path.join(this.baseDir, relativePath);
116
+ const hash = hashFile(file);
117
+ const known = this.sink.currentHash(scope, relativePath);
118
+ if (hash === null) {
119
+ // A directory or an unreadable file is not a change. A file that is gone is one, when its slot holds a hash.
120
+ if (fs.existsSync(file) || known === undefined || known === null)
121
+ return;
122
+ await this.sink.humanEdit(scope, relativePath, null);
123
+ return;
124
+ }
125
+ if (known === hash)
126
+ return;
127
+ await this.sink.humanEdit(scope, relativePath, hash);
128
+ }
129
+ /** Resolves when every change seen so far has been handled. */
130
+ async settled() {
131
+ while (this.timers.size > 0)
132
+ await new Promise((resolve) => setTimeout(resolve, this.debounceMs));
133
+ await this.chain;
134
+ }
135
+ stop() {
136
+ this.watcher?.close();
137
+ this.watcher = null;
138
+ for (const timer of this.timers.values())
139
+ clearTimeout(timer);
140
+ this.timers.clear();
141
+ }
142
+ }
@@ -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
+ }