@cairul/mcp 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 (44) hide show
  1. package/LICENSE +202 -0
  2. package/bin/cairul-mcp.mjs +3 -0
  3. package/dist/api/index.d.ts +6 -0
  4. package/dist/api/index.js +12 -0
  5. package/dist/check-executions.d.ts +16 -0
  6. package/dist/check-executions.js +89 -0
  7. package/dist/check-kinds.d.ts +16 -0
  8. package/dist/check-kinds.js +69 -0
  9. package/dist/checks/github.d.ts +1 -0
  10. package/dist/checks/github.js +1 -0
  11. package/dist/checks/shell.d.ts +10 -0
  12. package/dist/checks/shell.js +62 -0
  13. package/dist/environment.d.ts +1 -0
  14. package/dist/environment.js +4 -0
  15. package/dist/index.d.ts +1 -0
  16. package/dist/index.js +76 -0
  17. package/dist/journeys.d.ts +14 -0
  18. package/dist/journeys.js +183 -0
  19. package/dist/local-config.d.ts +112 -0
  20. package/dist/local-config.js +210 -0
  21. package/dist/local-journeys.d.ts +647 -0
  22. package/dist/local-journeys.js +332 -0
  23. package/dist/local-plugins.d.ts +2 -0
  24. package/dist/local-plugins.js +54 -0
  25. package/dist/logging.d.ts +4 -0
  26. package/dist/logging.js +19 -0
  27. package/dist/observations/codex-rollout.d.ts +67 -0
  28. package/dist/observations/codex-rollout.js +241 -0
  29. package/dist/observations/codex.d.ts +18 -0
  30. package/dist/observations/codex.js +289 -0
  31. package/dist/observations/execution.d.ts +27 -0
  32. package/dist/observations/execution.js +84 -0
  33. package/dist/observations/harness.d.ts +40 -0
  34. package/dist/observations/harness.js +17 -0
  35. package/dist/observations/mcp.d.ts +8 -0
  36. package/dist/observations/mcp.js +15 -0
  37. package/dist/observations/publisher.d.ts +33 -0
  38. package/dist/observations/publisher.js +120 -0
  39. package/dist/observations/settings.d.ts +1 -0
  40. package/dist/observations/settings.js +2 -0
  41. package/dist/plugin.d.ts +22 -0
  42. package/dist/plugin.js +1 -0
  43. package/package.json +42 -3
  44. package/README.md +0 -3
@@ -0,0 +1,332 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { lstat, mkdir, mkdtemp, rename, rm, writeFile } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+ import { DatabaseSync } from 'node:sqlite';
5
+ import { z } from 'zod';
6
+ import { cancelExecution, createExecution, executionSchema, launchExecution, observeExecution, removeExecution, } from './check-executions.js';
7
+ import { localActionSchema, optionsSchema } from './check-kinds.js';
8
+ import { shellAction } from './checks/shell.js';
9
+ import { checkSchema, configDirectory, effectivePlan, isMissing, planSchema, } from './local-config.js';
10
+ import { journeyState } from './observations/harness.js';
11
+ export const backendStatus = journeyState.extend({
12
+ phase: z.string(),
13
+ incomplete_checks: z.array(checkSchema),
14
+ ready_to_complete: z.boolean(),
15
+ });
16
+ export const backendStart = z.object({
17
+ journey_id: z.uuid(),
18
+ plan: planSchema,
19
+ journey: backendStatus.extend({
20
+ identity_id: z.uuid(),
21
+ work_item_url: z.url(),
22
+ created_at: z.string(),
23
+ }),
24
+ });
25
+ const resultFields = z.object({
26
+ attempts: z.number().int().positive(),
27
+ checked_at: z.string(),
28
+ detail: z.string().optional(),
29
+ });
30
+ const checkResult = z.discriminatedUnion('status', [
31
+ resultFields.extend({ status: z.literal('running'), execution: executionSchema }),
32
+ resultFields.extend({ status: z.enum(['passed', 'failed']) }),
33
+ ]);
34
+ const journeyFields = z.object({
35
+ id: z.uuid(),
36
+ identity: z.object({
37
+ id: z.uuid(),
38
+ session_id: z.string(),
39
+ harness: z.string(),
40
+ harness_version: z.string().optional(),
41
+ thread_id: z.string().optional(),
42
+ user_id: z.string().optional(),
43
+ }),
44
+ work_item_url: z.string(),
45
+ status: journeyState.shape.status,
46
+ capture_policy: journeyState.shape.capture_policy,
47
+ created_at: z.string(),
48
+ updated_at: z.string(),
49
+ plan: planSchema,
50
+ phase: z.number().int().nonnegative(),
51
+ results: z.record(z.uuid(), checkResult),
52
+ backend: z.object({ phases: z.array(z.string()), status: backendStatus }).optional(),
53
+ });
54
+ const storedAction = z.union([
55
+ localActionSchema.required({ options: true }),
56
+ localActionSchema
57
+ .omit({ options: true })
58
+ .extend({ config: optionsSchema })
59
+ .transform(({ kind, config }) => ({
60
+ kind,
61
+ options: config,
62
+ })),
63
+ ]);
64
+ const storedJourney = z.union([
65
+ journeyFields.extend({ version: z.literal(2), local_actions: z.record(z.uuid(), storedAction) }),
66
+ journeyFields
67
+ .extend({ version: z.literal(1), commands: z.record(z.uuid(), z.string()) })
68
+ .transform(({ commands, ...state }) => ({
69
+ ...state,
70
+ version: 2,
71
+ local_actions: Object.fromEntries(Object.entries(commands).map(([id, command]) => [id, shellAction(command)])),
72
+ })),
73
+ ]);
74
+ const database = (folder) => join(folder, 'journey.db');
75
+ async function isDirectory(path) {
76
+ const entry = await lstat(path).catch((error) => {
77
+ if (!isMissing(error))
78
+ throw error;
79
+ });
80
+ if (entry && !entry.isDirectory())
81
+ throw new Error(`${path} must be a directory.`);
82
+ return Boolean(entry);
83
+ }
84
+ export async function startLocalJourney(project, config, input, remote) {
85
+ const root = join(await configDirectory(project), 'journeys');
86
+ await mkdir(root, { recursive: true, mode: 0o700 });
87
+ await isDirectory(root);
88
+ const staging = await mkdtemp(join(root, '.starting-'));
89
+ let started;
90
+ try {
91
+ await Promise.all(config.files.map(({ name, source }) => writeFile(join(staging, name), source, { mode: 0o600 })));
92
+ const db = new DatabaseSync(database(staging));
93
+ let state;
94
+ try {
95
+ db.exec('CREATE TABLE journey (id INTEGER PRIMARY KEY CHECK (id = 1), state TEXT NOT NULL)');
96
+ started = await remote?.start();
97
+ const { plan, actions, customized } = effectivePlan(config, started?.plan);
98
+ const now = started?.journey.created_at ?? new Date().toISOString();
99
+ state = {
100
+ ...input,
101
+ version: 2,
102
+ id: started && !customized ? started.journey_id : randomUUID(),
103
+ identity: { ...input.identity, id: started?.journey.identity_id ?? randomUUID() },
104
+ work_item_url: started?.journey.work_item_url ?? input.work_item_url,
105
+ capture_policy: started?.journey.capture_policy ?? input.capture_policy,
106
+ status: started?.journey.status ?? 'active',
107
+ created_at: now,
108
+ updated_at: started?.journey.updated_at ?? now,
109
+ phase: 0,
110
+ plan,
111
+ local_actions: actions,
112
+ results: {},
113
+ backend: started && { phases: started.plan.phases.map(({ name }) => name), status: started.journey },
114
+ };
115
+ advance(state);
116
+ db.prepare('INSERT INTO journey (id, state) VALUES (1, ?)').run(JSON.stringify(state));
117
+ }
118
+ finally {
119
+ db.close();
120
+ }
121
+ await rename(staging, join(root, state.id));
122
+ return {
123
+ payload: { journey_id: state.id, plan: state.plan, journey: view(state) },
124
+ backend: state.backend?.status,
125
+ };
126
+ }
127
+ catch (error) {
128
+ if (started && remote)
129
+ await remote.update('abort', started.journey_id).catch(() => undefined);
130
+ throw error;
131
+ }
132
+ finally {
133
+ await rm(staging, { recursive: true, force: true });
134
+ }
135
+ }
136
+ function pending(state) {
137
+ const { backend } = state;
138
+ const phase = state.plan.phases[state.phase];
139
+ const backendPhase = backend?.phases.indexOf(backend.status.phase) ?? -1;
140
+ const phaseOnBackend = backend?.phases.indexOf(phase.name) ?? -1;
141
+ return phase.checks.filter(({ id }) => {
142
+ if (Object.hasOwn(state.local_actions, id))
143
+ return state.results[id]?.status !== 'passed';
144
+ if (!backend || backend.status.status === 'completed' || backendPhase > phaseOnBackend)
145
+ return false;
146
+ if (backendPhase < phaseOnBackend)
147
+ return true;
148
+ return backend.status.incomplete_checks.some((check) => check.id === id);
149
+ });
150
+ }
151
+ function ready(state) {
152
+ const remote = state.backend?.status;
153
+ return (state.status === 'active' &&
154
+ state.phase === state.plan.phases.length - 1 &&
155
+ pending(state).length === 0 &&
156
+ (!remote || remote.ready_to_complete || remote.status === 'completed'));
157
+ }
158
+ function advance(state) {
159
+ if (state.status !== 'active')
160
+ return;
161
+ while (state.phase < state.plan.phases.length - 1 && pending(state).length === 0)
162
+ state.phase++;
163
+ }
164
+ function view(state) {
165
+ const phase = state.plan.phases[state.phase];
166
+ return {
167
+ id: state.id,
168
+ identity_id: state.identity.id,
169
+ session_id: state.identity.session_id,
170
+ ...(state.backend && { backend_journey_id: state.backend.status.id }),
171
+ work_item_url: state.work_item_url,
172
+ status: state.status,
173
+ capture_policy: state.capture_policy,
174
+ created_at: state.created_at,
175
+ updated_at: state.updated_at,
176
+ plan_id: state.plan.id,
177
+ plan_name: state.plan.name,
178
+ plan_revision: state.plan.revision,
179
+ phase: phase.name,
180
+ incomplete_checks: pending(state).map((check) => {
181
+ const result = state.results[check.id];
182
+ if (!result)
183
+ return check;
184
+ if (result.status !== 'running')
185
+ return { ...check, last_result: result };
186
+ const { execution, ...visible } = result;
187
+ return { ...check, last_result: { ...visible, detail: `Test execution ${execution.id} is running.` } };
188
+ }),
189
+ ready_to_complete: ready(state),
190
+ };
191
+ }
192
+ async function refreshChecks(state, project, folder, registry, signal, afterCommit) {
193
+ const budget = AbortSignal.any([signal, AbortSignal.timeout(25_000)]);
194
+ while (!budget.aborted) {
195
+ const phase = state.phase;
196
+ for (const check of pending(state)) {
197
+ if (budget.aborted)
198
+ break;
199
+ const action = state.local_actions[check.id];
200
+ if (!action)
201
+ continue;
202
+ const previous = state.results[check.id];
203
+ if (previous?.status === 'running') {
204
+ const outcome = await observeExecution(folder, previous.execution);
205
+ if (outcome) {
206
+ state.results[check.id] = {
207
+ status: outcome.detail ? 'failed' : 'passed',
208
+ attempts: previous.attempts,
209
+ checked_at: new Date().toISOString(),
210
+ detail: outcome.detail,
211
+ };
212
+ afterCommit.push(() => {
213
+ void removeExecution(folder, previous.execution).catch(() => undefined);
214
+ });
215
+ }
216
+ continue;
217
+ }
218
+ const attempts = (previous?.attempts ?? 0) + 1;
219
+ const checked_at = new Date().toISOString();
220
+ const run = (signal) => registry.run(action, { projectDir: project, workItemUrl: state.work_item_url, signal });
221
+ const timeout = registry.backgroundTimeout(action);
222
+ if (timeout !== undefined) {
223
+ if (Object.values(state.results).some((result) => result.status === 'running'))
224
+ continue;
225
+ const execution = createExecution(timeout);
226
+ state.results[check.id] = { status: 'running', attempts, checked_at, execution };
227
+ afterCommit.push(() => launchExecution(folder, execution, run));
228
+ continue;
229
+ }
230
+ const detail = await run(AbortSignal.any([budget, AbortSignal.timeout(15_000)]));
231
+ state.results[check.id] = { status: detail ? 'failed' : 'passed', attempts, checked_at, detail };
232
+ }
233
+ advance(state);
234
+ if (state.phase === phase)
235
+ break;
236
+ }
237
+ }
238
+ export async function updateLocalJourney(project, id, action, signal, registry, updateBackend) {
239
+ const root = join(await configDirectory(project), 'journeys');
240
+ const folder = join(root, id);
241
+ if (!(await isDirectory(root)) || !(await isDirectory(folder)))
242
+ return;
243
+ const db = new DatabaseSync(database(folder), { open: false });
244
+ try {
245
+ if (!(await lstat(database(folder))).isFile())
246
+ throw new Error('The local journey database must be a regular file.');
247
+ db.open();
248
+ try {
249
+ db.exec('BEGIN IMMEDIATE');
250
+ }
251
+ catch (error) {
252
+ if (error.errcode === 5) {
253
+ throw new Error('Another request is updating this journey. Retry after it finishes.', { cause: error });
254
+ }
255
+ throw error;
256
+ }
257
+ const row = db.prepare('SELECT state FROM journey WHERE id = 1').get();
258
+ const previous = String(row?.state);
259
+ const state = storedJourney.parse(JSON.parse(previous));
260
+ if (state.id !== id || state.phase >= state.plan.phases.length)
261
+ throw new Error('Invalid local journey state.');
262
+ let conflict;
263
+ const afterCommit = [];
264
+ if (state.status === 'active') {
265
+ if (state.backend) {
266
+ if (!updateBackend)
267
+ throw new Error('Set CAIRUL_BACKEND_ENABLED=true to update this backend-linked journey.');
268
+ const remote = state.backend;
269
+ remote.status = await updateBackend('status', remote.status.id);
270
+ if (remote.status.id === id)
271
+ advance(state);
272
+ if (remote.status.status === 'aborted' || (remote.status.status === 'completed' && remote.status.id === id)) {
273
+ state.status = remote.status.status;
274
+ }
275
+ }
276
+ if (state.status === 'active') {
277
+ if (action === 'status') {
278
+ await refreshChecks(state, project, folder, await registry(), signal, afterCommit);
279
+ }
280
+ else if (action === 'abort') {
281
+ if (state.backend?.status.status === 'active') {
282
+ state.backend.status = await updateBackend('abort', state.backend.status.id);
283
+ }
284
+ state.status = 'aborted';
285
+ }
286
+ else {
287
+ advance(state);
288
+ if (ready(state)) {
289
+ if (state.backend?.status.status === 'active') {
290
+ state.backend.status = await updateBackend('complete', state.backend.status.id);
291
+ }
292
+ state.status = 'completed';
293
+ }
294
+ }
295
+ }
296
+ }
297
+ if (state.status === 'aborted') {
298
+ for (const [id, result] of Object.entries(state.results)) {
299
+ if (result.status !== 'running')
300
+ continue;
301
+ await cancelExecution(folder, result.execution);
302
+ state.results[id] = {
303
+ status: 'failed',
304
+ attempts: result.attempts,
305
+ checked_at: new Date().toISOString(),
306
+ detail: 'Test execution was cancelled.',
307
+ };
308
+ }
309
+ }
310
+ if (action === 'abort' && state.status !== 'aborted')
311
+ conflict = 'A completed journey cannot be aborted.';
312
+ if (action === 'complete' && state.status !== 'completed') {
313
+ conflict =
314
+ 'Journey can complete only after every phase and check is satisfied. Call journey_status to run local checks.';
315
+ }
316
+ const next = JSON.stringify(state);
317
+ if (next !== previous) {
318
+ state.updated_at = new Date().toISOString();
319
+ db.prepare('UPDATE journey SET state = ? WHERE id = 1').run(JSON.stringify(state));
320
+ }
321
+ db.exec('COMMIT');
322
+ for (const execute of afterCommit)
323
+ execute();
324
+ if (conflict)
325
+ throw new Error(conflict);
326
+ return { journey: view(state), backend: state.backend?.status };
327
+ }
328
+ finally {
329
+ if (db.isOpen)
330
+ db.close();
331
+ }
332
+ }
@@ -0,0 +1,2 @@
1
+ import { CheckRegistry } from './check-kinds.js';
2
+ export declare function getCheckRegistry(project: string): Promise<CheckRegistry>;
@@ -0,0 +1,54 @@
1
+ import { join } from 'node:path';
2
+ import { pathToFileURL } from 'node:url';
3
+ import { resolve } from 'import-meta-resolve';
4
+ import { z } from 'zod';
5
+ import { CheckRegistry, optionsSchema } from './check-kinds.js';
6
+ import shellPlugin from './checks/shell.js';
7
+ import { configDirectory, readConfig } from './local-config.js';
8
+ const packageName = z
9
+ .string()
10
+ .regex(/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/, 'Use an installed package name.');
11
+ const pluginConfig = z.strictObject({
12
+ plugins: z.array(z.strictObject({ package: packageName, options: optionsSchema.default({}) })),
13
+ });
14
+ const builtInPlugins = [shellPlugin];
15
+ async function loadRegistry(project) {
16
+ const registry = new CheckRegistry();
17
+ for (const factory of builtInPlugins)
18
+ registry.use(await factory({}));
19
+ const directory = await configDirectory(project);
20
+ const configured = await readConfig(directory, 'plugins', pluginConfig);
21
+ if (!configured)
22
+ return registry;
23
+ const { plugins } = configured.data;
24
+ const packages = new Set(plugins.map((plugin) => plugin.package));
25
+ if (packages.size !== plugins.length)
26
+ throw new Error(`Duplicate plugin packages in ${join(directory, configured.file.name)}.`);
27
+ const parent = pathToFileURL(join(project, 'package.json')).href;
28
+ for (const plugin of plugins) {
29
+ try {
30
+ const entrypoint = resolve(plugin.package, parent);
31
+ const module = (await import(entrypoint));
32
+ if (typeof module.default !== 'function')
33
+ throw new Error('Expected a default plugin factory export.');
34
+ const factory = module.default;
35
+ registry.use(await factory(plugin.options));
36
+ }
37
+ catch (error) {
38
+ throw new Error(`Could not load plugin "${plugin.package}" for ${project}. ${error instanceof Error ? error.message : String(error)}`, { cause: error });
39
+ }
40
+ }
41
+ return registry;
42
+ }
43
+ const registries = new Map();
44
+ export function getCheckRegistry(project) {
45
+ let registry = registries.get(project);
46
+ if (!registry) {
47
+ registry = loadRegistry(project).catch((error) => {
48
+ registries.delete(project);
49
+ throw error;
50
+ });
51
+ registries.set(project, registry);
52
+ }
53
+ return registry;
54
+ }
@@ -0,0 +1,4 @@
1
+ declare const levels: readonly ["debug", "info", "warn", "error"];
2
+ type Level = (typeof levels)[number];
3
+ export declare function log(level: Level, message: string, attributes?: Record<string, string | number>): void;
4
+ export {};
@@ -0,0 +1,19 @@
1
+ import { stderr } from 'node:process';
2
+ import { setting } from './environment.js';
3
+ const levels = ['debug', 'info', 'warn', 'error'];
4
+ const configuredLevel = setting('LOG_LEVEL')?.trim().toLowerCase() || 'info';
5
+ const minimumLevel = levels.find((level) => level === configuredLevel) ?? 'info';
6
+ export function log(level, message, attributes = {}) {
7
+ if (levels.indexOf(level) >= levels.indexOf(minimumLevel)) {
8
+ stderr.write(JSON.stringify({
9
+ time: new Date().toISOString(),
10
+ level: level.toUpperCase(),
11
+ msg: message,
12
+ component: 'mcp',
13
+ ...attributes,
14
+ }) + '\n');
15
+ }
16
+ }
17
+ if (minimumLevel !== configuredLevel) {
18
+ log('warn', 'using info for an invalid CAIRUL_LOG_LEVEL');
19
+ }
@@ -0,0 +1,67 @@
1
+ import type { TokenUsage } from '@cairul/sdk';
2
+ export declare function readCodexIdentity(input: unknown): {
3
+ sessionId: string;
4
+ threadId: string;
5
+ harnessVersion: string | undefined;
6
+ } | undefined;
7
+ export declare function readCodexCall(input: unknown, name: string, at: number): {
8
+ session: string;
9
+ thread: string;
10
+ call: string;
11
+ turn: string;
12
+ model: string | undefined;
13
+ version: string | undefined;
14
+ tool: string;
15
+ at: number;
16
+ } | undefined;
17
+ export type CodexCall = NonNullable<ReturnType<typeof readCodexCall>>;
18
+ export type RolloutEvent = {
19
+ type: 'session';
20
+ at: number;
21
+ provider?: string;
22
+ version?: string;
23
+ } | {
24
+ type: 'turn';
25
+ at: number;
26
+ turn: string;
27
+ model?: string;
28
+ } | {
29
+ type: 'output';
30
+ at: number;
31
+ } | {
32
+ type: 'generation';
33
+ at: number;
34
+ turn: string;
35
+ response: string;
36
+ usage: TokenUsage;
37
+ } | {
38
+ type: 'tool';
39
+ at: number;
40
+ call: string;
41
+ name: string;
42
+ } | {
43
+ type: 'tool_end';
44
+ at: number;
45
+ call: string;
46
+ name?: string;
47
+ started?: number;
48
+ failed?: boolean;
49
+ } | {
50
+ type: 'stop' | 'interrupt';
51
+ at: number;
52
+ turn: string;
53
+ };
54
+ export declare function readCodexProject(thread: string): Promise<string | undefined>;
55
+ export declare class CodexRollout {
56
+ private readonly thread;
57
+ private file?;
58
+ private offset;
59
+ private pending;
60
+ private skipLine;
61
+ private nextLookup;
62
+ constructor(thread: string);
63
+ private locate;
64
+ read(): AsyncGenerator<RolloutEvent>;
65
+ get available(): boolean;
66
+ close(): Promise<void>;
67
+ }