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,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,77 @@
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
+ * A command that ends in time takes its background processes with it on POSIX, where the command
23
+ * leads a process group. On Windows such a process cannot be found after its parent is gone: it
24
+ * keeps running, but it does not hold the caller, because the output pipes are closed here.
25
+ */
26
+ export declare function runCommand(command: Command, input: unknown, cwd: string, timeoutMs: number): Promise<CommandResult>;
27
+ export interface WitnessContext {
28
+ readonly verifyId: string;
29
+ readonly attemptId: string;
30
+ readonly stage: WitnessStage;
31
+ readonly binding: Binding;
32
+ readonly scopeId: string;
33
+ readonly classId: string;
34
+ readonly toolId: string;
35
+ readonly ops: readonly StateOp[];
36
+ /** Budget that the kernel grants to this stage. */
37
+ readonly budgetCpuMs: number;
38
+ /** True when the kernel itself requires a near-miss proof for this stage. */
39
+ readonly requireNearMiss: boolean;
40
+ }
41
+ /**
42
+ * Runs a declared witness stage in a child process. The budget of a stage is the smaller of the
43
+ * manifest budget and the budget that the kernel grants, enforced as a wall-clock limit, which is
44
+ * never looser than the CPU time. Exit code 0 is PASS, 1 is FAIL. A timeout, a crash or any other
45
+ * exit code is UNKNOWN, which the kernel does not accept as proof.
46
+ *
47
+ * A near-miss proof is needed when the manifest or the kernel asks for it. Without a passing
48
+ * probe the stage reports FAIL, also where only the manifest asked.
49
+ */
50
+ export declare class CommandWitness {
51
+ private readonly stages;
52
+ private readonly cwd;
53
+ constructor(stages: Partial<Readonly<Record<WitnessStage, ManifestWitnessStage>>>, cwd: string);
54
+ /** True when the manifest asks for a near-miss proof at this stage. */
55
+ requiresNearMiss(stage: WitnessStage): boolean;
56
+ runStage(ctx: WitnessContext): Promise<WitnessStageExecution>;
57
+ }
58
+ /**
59
+ * Outbox transport backed by the commands of the declared tools. The recipient of an effect is
60
+ * the tool id. Exit code 0 means applied, 2 means refused, anything else means unknown, and an
61
+ * unknown outcome can only be reconciled. A tool without a command for a step answers unknown.
62
+ */
63
+ export declare class CommandTransport implements OutboxTransport {
64
+ private readonly tools;
65
+ private readonly cwd;
66
+ private readonly timeoutMs;
67
+ constructor(tools: Readonly<Record<string, ManifestTool>>, cwd: string, timeoutMs?: number);
68
+ private run;
69
+ deliver(record: OutboxRecord): Promise<DeliveryAdapterOutcome>;
70
+ reconcile(record: OutboxRecord): Promise<DeliveryAdapterOutcome>;
71
+ compensate(record: OutboxRecord): Promise<DeliveryAdapterOutcome>;
72
+ }
73
+ /**
74
+ * Preflight check of the outbox: runs the tool's `preflightCommand` right before a send.
75
+ * Exit code 0 lets the send go. The command runs asynchronously, so a human event is never held behind it.
76
+ */
77
+ export declare function createCommandPreflight(tools: Readonly<Record<string, ManifestTool>>, cwd: string, timeoutMs?: number): OutboxPreflightCheck;
@@ -0,0 +1,209 @@
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
+ /** Kills what a command that has ended left in its process group. Only POSIX has such a group. */
21
+ function killLeftovers(child) {
22
+ if (child.pid === undefined || process.platform === 'win32')
23
+ return;
24
+ try {
25
+ process.kill(-child.pid, 'SIGKILL');
26
+ }
27
+ catch {
28
+ // The group is empty: nothing was left.
29
+ }
30
+ }
31
+ /**
32
+ * Runs one command with a hard wall-clock limit. When the limit passes, the whole process tree is
33
+ * killed and the call returns as soon as the process is gone, also when a grandchild still holds
34
+ * the output pipes.
35
+ *
36
+ * A command that ends in time takes its background processes with it on POSIX, where the command
37
+ * leads a process group. On Windows such a process cannot be found after its parent is gone: it
38
+ * keeps running, but it does not hold the caller, because the output pipes are closed here.
39
+ */
40
+ export function runCommand(command, input, cwd, timeoutMs) {
41
+ return new Promise((resolve) => {
42
+ const started = performance.now();
43
+ let stdout = '';
44
+ let stderr = '';
45
+ let timedOut = false;
46
+ let settled = false;
47
+ let drain = null;
48
+ const finish = (exitCode) => {
49
+ if (settled)
50
+ return;
51
+ settled = true;
52
+ clearTimeout(timer);
53
+ if (drain)
54
+ clearTimeout(drain);
55
+ resolve({ exitCode: timedOut ? null : exitCode, timedOut, wallMs: Math.round(performance.now() - started), stdout, stderr });
56
+ };
57
+ const child = spawn(command[0], command.slice(1), {
58
+ cwd,
59
+ stdio: ['pipe', 'pipe', 'pipe'],
60
+ windowsHide: true,
61
+ detached: process.platform !== 'win32',
62
+ });
63
+ const timer = setTimeout(() => {
64
+ timedOut = true;
65
+ killTree(child);
66
+ child.stdout.destroy();
67
+ child.stderr.destroy();
68
+ // Normally `exit` follows at once. This is the last resort for a process that cannot be killed.
69
+ drain = setTimeout(() => finish(null), 1000);
70
+ }, Math.max(1, timeoutMs));
71
+ child.stdout.on('data', (chunk) => { if (stdout.length < OUTPUT_LIMIT)
72
+ stdout += chunk.toString('utf8'); });
73
+ child.stderr.on('data', (chunk) => { if (stderr.length < OUTPUT_LIMIT)
74
+ stderr += chunk.toString('utf8'); });
75
+ child.on('error', (err) => { stderr += String(err); finish(null); });
76
+ child.on('exit', (code) => {
77
+ if (timedOut) {
78
+ finish(null);
79
+ return;
80
+ }
81
+ killLeftovers(child);
82
+ // `close` brings the rest of the output. A process that keeps the pipes open must not hold the answer,
83
+ // and the open pipes must not keep the event loop of the caller alive.
84
+ if (!drain) {
85
+ drain = setTimeout(() => {
86
+ child.stdout.destroy();
87
+ child.stderr.destroy();
88
+ finish(code);
89
+ }, 200);
90
+ }
91
+ });
92
+ child.on('close', (code) => finish(code));
93
+ child.stdin.on('error', () => { });
94
+ child.stdin.end(JSON.stringify(input));
95
+ });
96
+ }
97
+ /**
98
+ * Runs a declared witness stage in a child process. The budget of a stage is the smaller of the
99
+ * manifest budget and the budget that the kernel grants, enforced as a wall-clock limit, which is
100
+ * never looser than the CPU time. Exit code 0 is PASS, 1 is FAIL. A timeout, a crash or any other
101
+ * exit code is UNKNOWN, which the kernel does not accept as proof.
102
+ *
103
+ * A near-miss proof is needed when the manifest or the kernel asks for it. Without a passing
104
+ * probe the stage reports FAIL, also where only the manifest asked.
105
+ */
106
+ export class CommandWitness {
107
+ stages;
108
+ cwd;
109
+ constructor(stages, cwd) {
110
+ this.stages = stages;
111
+ this.cwd = cwd;
112
+ }
113
+ /** True when the manifest asks for a near-miss proof at this stage. */
114
+ requiresNearMiss(stage) {
115
+ return this.stages[stage]?.requireNearMiss === true;
116
+ }
117
+ async runStage(ctx) {
118
+ const cfg = this.stages[ctx.stage];
119
+ if (cfg === undefined)
120
+ return { verifyId: ctx.verifyId, stage: ctx.stage, verdict: 'UNKNOWN', cpuMs: 0, nearMissPassed: false };
121
+ const needsNearMiss = cfg.requireNearMiss || ctx.requireNearMiss;
122
+ if (cfg.command === undefined) {
123
+ // `accept` has no check, so it cannot show a near miss.
124
+ return { verifyId: ctx.verifyId, stage: ctx.stage, verdict: needsNearMiss ? 'FAIL' : 'PASS', cpuMs: 0, nearMissPassed: false };
125
+ }
126
+ const budget = Math.min(cfg.budgetCpuMs, ctx.budgetCpuMs);
127
+ if (budget <= 0)
128
+ return { verifyId: ctx.verifyId, stage: ctx.stage, verdict: 'UNKNOWN', cpuMs: 0, nearMissPassed: false };
129
+ const main = await runCommand(cfg.command, { ...ctx, budgetCpuMs: budget }, this.cwd, budget);
130
+ let verdict = main.timedOut ? 'UNKNOWN' : main.exitCode === 0 ? 'PASS' : main.exitCode === 1 ? 'FAIL' : 'UNKNOWN';
131
+ let spent = Math.min(main.wallMs, budget);
132
+ let nearMissPassed = false;
133
+ if (verdict === 'PASS' && needsNearMiss) {
134
+ if (cfg.nearMissProbeCommand !== undefined && spent < budget) {
135
+ const probe = await runCommand(cfg.nearMissProbeCommand, { ...ctx, budgetCpuMs: budget - spent }, this.cwd, budget - spent);
136
+ nearMissPassed = !probe.timedOut && probe.exitCode === 0;
137
+ spent = Math.min(budget, spent + probe.wallMs);
138
+ }
139
+ if (!nearMissPassed)
140
+ verdict = 'FAIL';
141
+ }
142
+ return { verifyId: ctx.verifyId, stage: ctx.stage, verdict, cpuMs: spent, nearMissPassed };
143
+ }
144
+ }
145
+ function outcomeOf(result) {
146
+ if (result.timedOut || result.exitCode === null)
147
+ return { status: 'UNKNOWN', reason: result.timedOut ? 'COMMAND_TIMEOUT' : 'COMMAND_NOT_STARTED' };
148
+ if (result.exitCode === 0)
149
+ return { status: 'APPLIED' };
150
+ if (result.exitCode === 2)
151
+ return { status: 'REFUSED', reason: result.stderr.trim().slice(0, 200) || 'REFUSED_BY_COMMAND' };
152
+ return { status: 'UNKNOWN', reason: `EXIT_${result.exitCode}` };
153
+ }
154
+ function recordInput(record) {
155
+ let payload = null;
156
+ try {
157
+ payload = JSON.parse(record.payloadJson);
158
+ }
159
+ catch {
160
+ payload = record.payloadJson;
161
+ }
162
+ return { effectId: record.effectId, effectKind: record.effectKind, batchId: record.batchId, scopeId: record.scopeId, classId: record.classId, toolId: record.recipientId, payload };
163
+ }
164
+ /**
165
+ * Outbox transport backed by the commands of the declared tools. The recipient of an effect is
166
+ * the tool id. Exit code 0 means applied, 2 means refused, anything else means unknown, and an
167
+ * unknown outcome can only be reconciled. A tool without a command for a step answers unknown.
168
+ */
169
+ export class CommandTransport {
170
+ tools;
171
+ cwd;
172
+ timeoutMs;
173
+ constructor(tools, cwd, timeoutMs = DEFAULT_TIMEOUT_MS) {
174
+ this.tools = tools;
175
+ this.cwd = cwd;
176
+ this.timeoutMs = timeoutMs;
177
+ }
178
+ async run(record, pick, step) {
179
+ const tool = this.tools[record.recipientId];
180
+ const command = tool ? pick(tool) : undefined;
181
+ if (command === undefined)
182
+ return { status: 'UNKNOWN', reason: `NO_${step}_COMMAND` };
183
+ return outcomeOf(await runCommand(command, recordInput(record), this.cwd, this.timeoutMs));
184
+ }
185
+ deliver(record) {
186
+ return this.run(record, (t) => t.deliverCommand, 'DELIVER');
187
+ }
188
+ reconcile(record) {
189
+ return this.run(record, (t) => t.reconcileCommand, 'RECONCILE');
190
+ }
191
+ compensate(record) {
192
+ return this.run(record, (t) => t.compensateCommand, 'COMPENSATE');
193
+ }
194
+ }
195
+ /**
196
+ * Preflight check of the outbox: runs the tool's `preflightCommand` right before a send.
197
+ * Exit code 0 lets the send go. The command runs asynchronously, so a human event is never held behind it.
198
+ */
199
+ export function createCommandPreflight(tools, cwd, timeoutMs = 10_000) {
200
+ return async (record, _state, nowMs) => {
201
+ const command = tools[record.recipientId]?.preflightCommand;
202
+ if (command === undefined)
203
+ return { ok: true };
204
+ const result = await runCommand(command, { ...recordInput(record), nowMs }, cwd, timeoutMs);
205
+ if (!result.timedOut && result.exitCode === 0)
206
+ return { ok: true };
207
+ return { ok: false, reason: result.timedOut ? 'PREFLIGHT_TIMEOUT' : result.stderr.trim().slice(0, 200) || `PREFLIGHT_EXIT_${String(result.exitCode)}` };
208
+ };
209
+ }
@@ -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,88 @@
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
+ /** Longest object id that the gate reads. */
15
+ export declare const MAX_OBJECT_ID_LENGTH = 1024;
16
+ /**
17
+ * Tells whether a `/`-separated path matches a glob pattern. `*` and `?` stay inside one segment,
18
+ * and a segment `**` stands for any number of segments, also none. A pattern without a wildcard
19
+ * names a file or a directory with everything below it.
20
+ *
21
+ * The match ignores letter case on every platform, so `Policies/x.sql` and `policies/x.sql`, which
22
+ * are one file on Windows and macOS, always belong to the same scope. It uses no regular expression:
23
+ * the time grows with the product of the two lengths, so no input can stall it.
24
+ */
25
+ export declare function matchGlob(pattern: string, relativePath: string): boolean;
26
+ /** The reason why a text cannot be a path pattern of a scope, or null. */
27
+ export declare function patternProblem(pattern: string): string | null;
28
+ /**
29
+ * One spelling for an object id that may be a path: `/` as the separator, no leading `./`, no empty
30
+ * segments, Unicode form NFC. Returns null for an absolute path, for a path with a `..` segment, for
31
+ * an id longer than 1024 characters and for an id with a control or text-direction character, so two
32
+ * spellings can never name the same file, no id can leave the project directory, and an id reads in
33
+ * a log the way it is stored.
34
+ */
35
+ export declare function normalizeObjectPath(input: string): string | null;
36
+ /**
37
+ * The scopes that claim a path. The order of the scopes in the manifest does not matter.
38
+ *
39
+ * A whole-directory pattern (`dir/**` or `**`) is a fallback. It gives way to a pattern of another
40
+ * scope that lies inside that directory: a deeper whole-directory pattern, or any other pattern
41
+ * that starts there. So `**` gives way to `policies/**`, and `src/**` gives way to `src/db/**`
42
+ * and to `src/*.sql`.
43
+ *
44
+ * Every other overlap is left as it is: `src/**` and a pattern like `**` + `/*.secret` both claim
45
+ * `src/a.secret`, and the result has two scopes. A caller must treat such a path as owned by nobody.
46
+ */
47
+ export declare function claimantsOfPath(scopes: readonly ManifestScope[], relativePath: string): ManifestScope[];
48
+ /** The one scope that owns the path, or null when no scope or more than one scope claims it. */
49
+ export declare function scopeOfPath(scopes: readonly ManifestScope[], relativePath: string): ManifestScope | null;
50
+ /**
51
+ * Checks where a write to an object of a file scope would really land. Returns the reason for a
52
+ * refusal, or null.
53
+ *
54
+ * A symbolic link, also one in a parent directory, can lead the write into another scope or out of
55
+ * the project: the real path must belong to the leased scope. A file with a second hard link has
56
+ * another name that this check cannot see, so it is refused.
57
+ */
58
+ export declare function linkProblem(baseDir: string, scopes: readonly ManifestScope[], scopeId: string, objectId: string): 'OBJECT_OUT_OF_SCOPE' | 'OBJECT_HARD_LINKED' | null;
59
+ export declare function hashFile(file: string): string | null;
60
+ export interface FileEditSink {
61
+ /** Current value of the slot of a file, or undefined when the slot does not exist. */
62
+ currentHash(scope: ManifestScope, relativePath: string): unknown;
63
+ /** `hash` is null when the file was deleted. */
64
+ humanEdit(scope: ManifestScope, relativePath: string, hash: string | null): Promise<void>;
65
+ }
66
+ export declare class HumanFileWatcher {
67
+ private readonly baseDir;
68
+ private readonly scopes;
69
+ private readonly sink;
70
+ private readonly ignore;
71
+ private readonly debounceMs;
72
+ private readonly timers;
73
+ private watcher;
74
+ private chain;
75
+ constructor(options: {
76
+ readonly baseDir: string;
77
+ readonly scopes: readonly ManifestScope[];
78
+ readonly sink: FileEditSink;
79
+ readonly ignore?: readonly string[];
80
+ readonly debounceMs?: number;
81
+ });
82
+ start(): void;
83
+ /** Compares one file with its slot and reports a human edit when they differ. */
84
+ inspect(relativePath: string): Promise<void>;
85
+ /** Resolves when every change seen so far has been handled. */
86
+ settled(): Promise<void>;
87
+ stop(): void;
88
+ }