@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.
- package/LICENSE +202 -0
- package/bin/cairul-mcp.mjs +3 -0
- package/dist/api/index.d.ts +6 -0
- package/dist/api/index.js +12 -0
- package/dist/check-executions.d.ts +16 -0
- package/dist/check-executions.js +89 -0
- package/dist/check-kinds.d.ts +16 -0
- package/dist/check-kinds.js +69 -0
- package/dist/checks/github.d.ts +1 -0
- package/dist/checks/github.js +1 -0
- package/dist/checks/shell.d.ts +10 -0
- package/dist/checks/shell.js +62 -0
- package/dist/environment.d.ts +1 -0
- package/dist/environment.js +4 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +76 -0
- package/dist/journeys.d.ts +14 -0
- package/dist/journeys.js +183 -0
- package/dist/local-config.d.ts +112 -0
- package/dist/local-config.js +210 -0
- package/dist/local-journeys.d.ts +647 -0
- package/dist/local-journeys.js +332 -0
- package/dist/local-plugins.d.ts +2 -0
- package/dist/local-plugins.js +54 -0
- package/dist/logging.d.ts +4 -0
- package/dist/logging.js +19 -0
- package/dist/observations/codex-rollout.d.ts +67 -0
- package/dist/observations/codex-rollout.js +241 -0
- package/dist/observations/codex.d.ts +18 -0
- package/dist/observations/codex.js +289 -0
- package/dist/observations/execution.d.ts +27 -0
- package/dist/observations/execution.js +84 -0
- package/dist/observations/harness.d.ts +40 -0
- package/dist/observations/harness.js +17 -0
- package/dist/observations/mcp.d.ts +8 -0
- package/dist/observations/mcp.js +15 -0
- package/dist/observations/publisher.d.ts +33 -0
- package/dist/observations/publisher.js +120 -0
- package/dist/observations/settings.d.ts +1 -0
- package/dist/observations/settings.js +2 -0
- package/dist/plugin.d.ts +22 -0
- package/dist/plugin.js +1 -0
- package/package.json +42 -3
- package/README.md +0 -3
package/dist/journeys.js
ADDED
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { cwd } from 'node:process';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
import { z } from 'zod';
|
|
5
|
+
import { setting } from './environment.js';
|
|
6
|
+
import { errorResponse } from './api/index.js';
|
|
7
|
+
import { findProject, loadConfig } from './local-config.js';
|
|
8
|
+
import { backendStart, backendStatus, startLocalJourney, updateLocalJourney } from './local-journeys.js';
|
|
9
|
+
import { getCheckRegistry } from './local-plugins.js';
|
|
10
|
+
import { log } from './logging.js';
|
|
11
|
+
import { readCodexIdentity, readCodexProject } from './observations/codex-rollout.js';
|
|
12
|
+
import { capturePolicy, journeyState } from './observations/harness.js';
|
|
13
|
+
const journeyInput = z.object({
|
|
14
|
+
journey_id: z
|
|
15
|
+
.uuid()
|
|
16
|
+
.transform((id) => id.toLowerCase())
|
|
17
|
+
.describe('ID returned by journey_start'),
|
|
18
|
+
});
|
|
19
|
+
export async function readJourneyState(api, id) {
|
|
20
|
+
const { raw } = await api.getJourneyStatusRaw({ id }, { signal: AbortSignal.timeout(1000) });
|
|
21
|
+
return journeyState.parse(await raw.json());
|
|
22
|
+
}
|
|
23
|
+
const updates = {
|
|
24
|
+
status: 'getJourneyStatusRaw',
|
|
25
|
+
abort: 'abortJourneyRaw',
|
|
26
|
+
complete: 'completeJourneyRaw',
|
|
27
|
+
};
|
|
28
|
+
async function projectDirectory(server, threadId, signal) {
|
|
29
|
+
const configuredProject = setting('PROJECT_DIR');
|
|
30
|
+
if (configuredProject)
|
|
31
|
+
return findProject(configuredProject);
|
|
32
|
+
const project = threadId && (await readCodexProject(threadId).catch(() => undefined));
|
|
33
|
+
if (project)
|
|
34
|
+
return findProject(project);
|
|
35
|
+
if (server.server.getClientCapabilities()?.roots) {
|
|
36
|
+
const response = await server.server.listRoots(undefined, { signal, timeout: 1000 }).catch(() => undefined);
|
|
37
|
+
const roots = response?.roots.filter(({ uri }) => uri.startsWith('file:')) ?? [];
|
|
38
|
+
if (roots.length > 1)
|
|
39
|
+
throw new Error('Set CAIRUL_PROJECT_DIR when the harness exposes multiple project roots.');
|
|
40
|
+
if (roots.length === 1)
|
|
41
|
+
return findProject(fileURLToPath(roots[0].uri));
|
|
42
|
+
}
|
|
43
|
+
return findProject(cwd());
|
|
44
|
+
}
|
|
45
|
+
export function registerJourneyTools(server, api, instrument, harness) {
|
|
46
|
+
server.registerTool('journey_start', {
|
|
47
|
+
description: 'Start a journey for a work item URL and pin its plan and local check configuration.',
|
|
48
|
+
inputSchema: z.object({
|
|
49
|
+
session_id: z.string().trim().min(1).max(200).describe('Session ID issued by the agent harness.'),
|
|
50
|
+
user_id: z.string().trim().min(1).max(200).optional().describe('User ID from the harness, when known.'),
|
|
51
|
+
work_item_url: z.url({ protocol: /^https?$/ }).describe('Work item URL'),
|
|
52
|
+
capture_policy: capturePolicy.optional().describe('Optional whole-execution filter for backend observations.'),
|
|
53
|
+
}),
|
|
54
|
+
annotations: { destructiveHint: false },
|
|
55
|
+
}, ({ session_id, user_id, work_item_url, capture_policy }, context) => instrument('journey_start', context, (call) => respond('journey_start', call, async () => {
|
|
56
|
+
const identity = harness === 'codex' ? readCodexIdentity(context.mcpReq._meta) : undefined;
|
|
57
|
+
if (identity && identity.sessionId !== session_id) {
|
|
58
|
+
throw new Error('Pass the Codex session ID for this session as session_id.');
|
|
59
|
+
}
|
|
60
|
+
const mode = capture_policy?.mode ?? 'all';
|
|
61
|
+
const toolNames = [...new Set(capture_policy?.tool_names)].sort();
|
|
62
|
+
if (mode === 'none' && toolNames.length)
|
|
63
|
+
throw new Error('Capture mode none cannot include tool names.');
|
|
64
|
+
const project = await projectDirectory(server, identity?.threadId, call.signal);
|
|
65
|
+
const config = await loadConfig(project, work_item_url, await getCheckRegistry(project));
|
|
66
|
+
const eventPublication = {
|
|
67
|
+
version: 1,
|
|
68
|
+
type: 'journey.start',
|
|
69
|
+
id: randomUUID(),
|
|
70
|
+
start: {
|
|
71
|
+
sessionId: session_id,
|
|
72
|
+
harness,
|
|
73
|
+
harnessVersion: identity?.harnessVersion,
|
|
74
|
+
threadId: identity?.threadId,
|
|
75
|
+
userId: user_id,
|
|
76
|
+
workItemUrl: work_item_url,
|
|
77
|
+
capturePolicy: { mode, toolNames },
|
|
78
|
+
localCheckNames: Array.from(config.catalog.keys()),
|
|
79
|
+
},
|
|
80
|
+
};
|
|
81
|
+
const remote = api && config.selected?.mode !== 'override'
|
|
82
|
+
? {
|
|
83
|
+
start: async () => {
|
|
84
|
+
const body = await backendRequest(call, async (signal) => {
|
|
85
|
+
const send = () => api.publishEventRaw({ eventPublication }, { signal });
|
|
86
|
+
try {
|
|
87
|
+
return await send();
|
|
88
|
+
}
|
|
89
|
+
catch (error) {
|
|
90
|
+
const status = errorResponse(error)?.status;
|
|
91
|
+
if (signal.aborted || (status !== undefined && status < 500))
|
|
92
|
+
throw error;
|
|
93
|
+
return send();
|
|
94
|
+
}
|
|
95
|
+
});
|
|
96
|
+
return backendStart.parse(body.started);
|
|
97
|
+
},
|
|
98
|
+
update: async (action, id) => backendStatus.parse(await backendRequest(call, (signal) => api[updates[action]]({ id }, { signal }))),
|
|
99
|
+
}
|
|
100
|
+
: undefined;
|
|
101
|
+
const result = await startLocalJourney(project, config, {
|
|
102
|
+
work_item_url,
|
|
103
|
+
identity: {
|
|
104
|
+
session_id,
|
|
105
|
+
harness,
|
|
106
|
+
harness_version: identity?.harnessVersion,
|
|
107
|
+
thread_id: identity?.threadId,
|
|
108
|
+
user_id,
|
|
109
|
+
},
|
|
110
|
+
capture_policy: { version: 1, mode, ...(toolNames.length && { tool_names: toolNames }) },
|
|
111
|
+
}, remote);
|
|
112
|
+
call.journey = result.backend;
|
|
113
|
+
return result.payload;
|
|
114
|
+
})));
|
|
115
|
+
const tools = [
|
|
116
|
+
{ action: 'status', description: 'Run pending local checks and return the current phase and incomplete checks.' },
|
|
117
|
+
{ action: 'abort', description: 'Abort an active journey even when checks are incomplete.' },
|
|
118
|
+
{ action: 'complete', description: 'Complete a journey after every phase and check is satisfied.' },
|
|
119
|
+
];
|
|
120
|
+
for (const { action, description } of tools) {
|
|
121
|
+
const name = `journey_${action}`;
|
|
122
|
+
server.registerTool(name, {
|
|
123
|
+
description,
|
|
124
|
+
inputSchema: journeyInput,
|
|
125
|
+
annotations: { destructiveHint: action !== 'complete', idempotentHint: action !== 'status' },
|
|
126
|
+
}, ({ journey_id }, context) => instrument(name, context, (call) => respond(name, call, async () => {
|
|
127
|
+
const identity = harness === 'codex' ? readCodexIdentity(context.mcpReq._meta) : undefined;
|
|
128
|
+
const project = await projectDirectory(server, identity?.threadId, call.signal);
|
|
129
|
+
const remote = api &&
|
|
130
|
+
((action, id) => backendRequest(call, (signal) => api[updates[action]]({ id }, { signal })));
|
|
131
|
+
const result = await updateLocalJourney(project, journey_id, action, call.signal, () => getCheckRegistry(project), remote && (async (action, id) => backendStatus.parse(await remote(action, id))));
|
|
132
|
+
if (result) {
|
|
133
|
+
call.journey = result.backend;
|
|
134
|
+
return result.journey;
|
|
135
|
+
}
|
|
136
|
+
if (!remote)
|
|
137
|
+
throw new Error(`Journey ${journey_id} was not found in ${project}.`);
|
|
138
|
+
const payload = await remote(action, journey_id);
|
|
139
|
+
call.journey = journeyState.safeParse(payload).data;
|
|
140
|
+
return payload;
|
|
141
|
+
})));
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
async function backendRequest(call, send) {
|
|
145
|
+
try {
|
|
146
|
+
const { raw } = await send(AbortSignal.any([call.signal, AbortSignal.timeout(5000)]));
|
|
147
|
+
call.httpStatus = raw.status;
|
|
148
|
+
return (await raw.json());
|
|
149
|
+
}
|
|
150
|
+
catch (error) {
|
|
151
|
+
const response = errorResponse(error);
|
|
152
|
+
if (response) {
|
|
153
|
+
call.httpStatus = response.status;
|
|
154
|
+
const body = await response.json().catch(() => null);
|
|
155
|
+
if (body && typeof body === 'object' && 'message' in body && typeof body.message === 'string') {
|
|
156
|
+
throw new Error(body.message, { cause: error });
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
throw new Error('The cairul API request failed.', { cause: error });
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
async function respond(tool, call, run) {
|
|
163
|
+
const started = Date.now();
|
|
164
|
+
try {
|
|
165
|
+
const payload = await run();
|
|
166
|
+
log('debug', 'journey tool succeeded', { tool, status: call.httpStatus ?? 0, duration_ms: Date.now() - started });
|
|
167
|
+
return { content: [{ type: 'text', text: JSON.stringify(payload) }], structuredContent: payload };
|
|
168
|
+
}
|
|
169
|
+
catch (error) {
|
|
170
|
+
log(call.signal.aborted ? 'debug' : 'warn', 'journey tool failed', {
|
|
171
|
+
tool,
|
|
172
|
+
status: call.httpStatus ?? 0,
|
|
173
|
+
duration_ms: Date.now() - started,
|
|
174
|
+
error_type: error instanceof Error ? error.name : 'unknown',
|
|
175
|
+
});
|
|
176
|
+
return {
|
|
177
|
+
isError: true,
|
|
178
|
+
content: [
|
|
179
|
+
{ type: 'text', text: error instanceof Error ? error.message : 'The journey request failed.' },
|
|
180
|
+
],
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
}
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { type CheckRegistry } from './check-kinds.js';
|
|
3
|
+
export declare const checkSchema: z.ZodObject<{
|
|
4
|
+
id: z.ZodUUID;
|
|
5
|
+
name: z.ZodString;
|
|
6
|
+
action: z.ZodObject<{
|
|
7
|
+
type: z.ZodString;
|
|
8
|
+
}, z.core.$loose>;
|
|
9
|
+
}, z.core.$strip>;
|
|
10
|
+
export declare const planSchema: z.ZodObject<{
|
|
11
|
+
id: z.ZodUUID;
|
|
12
|
+
name: z.ZodString;
|
|
13
|
+
instructions: z.ZodString;
|
|
14
|
+
revision: z.ZodNumber;
|
|
15
|
+
active: z.ZodBoolean;
|
|
16
|
+
created_at: z.ZodString;
|
|
17
|
+
phases: z.ZodArray<z.ZodObject<{
|
|
18
|
+
id: z.ZodUUID;
|
|
19
|
+
name: z.ZodString;
|
|
20
|
+
checks: z.ZodArray<z.ZodObject<{
|
|
21
|
+
id: z.ZodUUID;
|
|
22
|
+
name: z.ZodString;
|
|
23
|
+
action: z.ZodObject<{
|
|
24
|
+
type: z.ZodString;
|
|
25
|
+
}, z.core.$loose>;
|
|
26
|
+
}, z.core.$strip>>;
|
|
27
|
+
}, z.core.$strip>>;
|
|
28
|
+
}, z.core.$strip>;
|
|
29
|
+
export declare const isMissing: (error: unknown) => boolean;
|
|
30
|
+
export declare function configDirectory(project: string): Promise<string>;
|
|
31
|
+
export declare function findProject(start: string): Promise<string>;
|
|
32
|
+
export declare function readConfig<T>(directory: string, stem: string, schema: z.ZodType<T>): Promise<{
|
|
33
|
+
file: {
|
|
34
|
+
name: string;
|
|
35
|
+
source: string;
|
|
36
|
+
};
|
|
37
|
+
data: Awaited<T>;
|
|
38
|
+
} | undefined>;
|
|
39
|
+
export declare function loadConfig(project: string, url: string, registry: CheckRegistry): Promise<{
|
|
40
|
+
selected: {
|
|
41
|
+
phases: {
|
|
42
|
+
checks: {
|
|
43
|
+
definition: {
|
|
44
|
+
kind: string;
|
|
45
|
+
options: Record<string, z.core.util.JSONType>;
|
|
46
|
+
name: string;
|
|
47
|
+
} | {
|
|
48
|
+
kind: string;
|
|
49
|
+
options: Record<string, z.core.util.JSONType>;
|
|
50
|
+
name: string;
|
|
51
|
+
};
|
|
52
|
+
inline: boolean;
|
|
53
|
+
}[];
|
|
54
|
+
name: string;
|
|
55
|
+
}[];
|
|
56
|
+
match: string;
|
|
57
|
+
mode: "override" | "extend";
|
|
58
|
+
name?: string | undefined;
|
|
59
|
+
instructions?: string | undefined;
|
|
60
|
+
};
|
|
61
|
+
catalog: Map<string, {
|
|
62
|
+
kind: string;
|
|
63
|
+
options: Record<string, z.core.util.JSONType>;
|
|
64
|
+
name: string;
|
|
65
|
+
} | {
|
|
66
|
+
kind: string;
|
|
67
|
+
options: Record<string, z.core.util.JSONType>;
|
|
68
|
+
name: string;
|
|
69
|
+
}>;
|
|
70
|
+
files: {
|
|
71
|
+
name: string;
|
|
72
|
+
source: string;
|
|
73
|
+
}[];
|
|
74
|
+
}>;
|
|
75
|
+
export type LocalConfig = Awaited<ReturnType<typeof loadConfig>>;
|
|
76
|
+
export type Plan = z.infer<typeof planSchema>;
|
|
77
|
+
export declare function effectivePlan({ selected, catalog }: LocalConfig, backend?: Plan): {
|
|
78
|
+
plan: {
|
|
79
|
+
id: string;
|
|
80
|
+
name: string;
|
|
81
|
+
instructions: string;
|
|
82
|
+
revision: number;
|
|
83
|
+
active: boolean;
|
|
84
|
+
created_at: string;
|
|
85
|
+
phases: {
|
|
86
|
+
checks: ({
|
|
87
|
+
id: string;
|
|
88
|
+
name: string;
|
|
89
|
+
action: {
|
|
90
|
+
[x: string]: unknown;
|
|
91
|
+
type: string;
|
|
92
|
+
};
|
|
93
|
+
} | {
|
|
94
|
+
id: `${string}-${string}-${string}-${string}-${string}`;
|
|
95
|
+
name: string;
|
|
96
|
+
action: {
|
|
97
|
+
type: string;
|
|
98
|
+
kind: string;
|
|
99
|
+
};
|
|
100
|
+
})[];
|
|
101
|
+
id: string;
|
|
102
|
+
name: string;
|
|
103
|
+
}[];
|
|
104
|
+
};
|
|
105
|
+
customized: boolean;
|
|
106
|
+
actions: {
|
|
107
|
+
[k: string]: {
|
|
108
|
+
kind: string;
|
|
109
|
+
options: Record<string, z.core.util.JSONType>;
|
|
110
|
+
};
|
|
111
|
+
};
|
|
112
|
+
};
|
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { lstat, readFile, realpath, stat } from 'node:fs/promises';
|
|
3
|
+
import { dirname, isAbsolute, join } from 'node:path';
|
|
4
|
+
import { parse } from 'yaml';
|
|
5
|
+
import { z } from 'zod';
|
|
6
|
+
import { localActionSchema } from './check-kinds.js';
|
|
7
|
+
import { shellAction, shellKind, shellOptions } from './checks/shell.js';
|
|
8
|
+
const label = z
|
|
9
|
+
.string()
|
|
10
|
+
.trim()
|
|
11
|
+
.min(1)
|
|
12
|
+
.max(200)
|
|
13
|
+
.regex(/^[^\r\n\t\0]+$/);
|
|
14
|
+
function checkConfigFor(registry) {
|
|
15
|
+
return z
|
|
16
|
+
.union([
|
|
17
|
+
localActionSchema.extend({ name: label }),
|
|
18
|
+
shellOptions.extend({ name: label }).transform(({ name, command }) => ({ name, ...shellAction(command) })),
|
|
19
|
+
])
|
|
20
|
+
.superRefine(async ({ name, ...action }, context) => {
|
|
21
|
+
try {
|
|
22
|
+
await registry.validate(action);
|
|
23
|
+
}
|
|
24
|
+
catch (error) {
|
|
25
|
+
context.addIssue({
|
|
26
|
+
code: 'custom',
|
|
27
|
+
message: `Check "${name}": ${error instanceof Error ? error.message : String(error)}`,
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
const planConfig = (checkConfig) => z.strictObject({
|
|
33
|
+
match: z.string().regex(/^[^*\s]*\*$/, 'Use a URL prefix followed by * or a standalone *.'),
|
|
34
|
+
mode: z.enum(['extend', 'override']).default('extend'),
|
|
35
|
+
name: label.optional(),
|
|
36
|
+
instructions: z.string().trim().min(1).optional(),
|
|
37
|
+
phases: z
|
|
38
|
+
.array(z.strictObject({ name: label, checks: z.array(z.union([label, checkConfig])).default([]) }))
|
|
39
|
+
.default([]),
|
|
40
|
+
});
|
|
41
|
+
export const checkSchema = z.object({
|
|
42
|
+
id: z.uuid(),
|
|
43
|
+
name: z.string(),
|
|
44
|
+
action: z.looseObject({ type: z.string() }),
|
|
45
|
+
});
|
|
46
|
+
const phaseSchema = z.object({ id: z.uuid(), name: z.string(), checks: z.array(checkSchema) });
|
|
47
|
+
export const planSchema = z.object({
|
|
48
|
+
id: z.uuid(),
|
|
49
|
+
name: z.string(),
|
|
50
|
+
instructions: z.string(),
|
|
51
|
+
revision: z.number().int().positive(),
|
|
52
|
+
active: z.boolean(),
|
|
53
|
+
created_at: z.string(),
|
|
54
|
+
phases: z.array(phaseSchema).min(1),
|
|
55
|
+
});
|
|
56
|
+
export const isMissing = (error) => error?.code === 'ENOENT';
|
|
57
|
+
async function existingConfigDirectory(project) {
|
|
58
|
+
for (const name of ['.cairul', '.kair0', '.nauxt', '.minerva']) {
|
|
59
|
+
const path = join(project, name);
|
|
60
|
+
const entry = await lstat(path).catch((error) => {
|
|
61
|
+
if (!isMissing(error))
|
|
62
|
+
throw error;
|
|
63
|
+
});
|
|
64
|
+
if (!entry)
|
|
65
|
+
continue;
|
|
66
|
+
if (!entry.isDirectory())
|
|
67
|
+
throw new Error(`${path} must be a directory.`);
|
|
68
|
+
return path;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
export async function configDirectory(project) {
|
|
72
|
+
return (await existingConfigDirectory(project)) ?? join(project, '.cairul');
|
|
73
|
+
}
|
|
74
|
+
export async function findProject(start) {
|
|
75
|
+
if (!isAbsolute(start))
|
|
76
|
+
throw new Error('The Cairul project directory must be an absolute path.');
|
|
77
|
+
const cwd = await realpath(start);
|
|
78
|
+
if (!(await stat(cwd)).isDirectory())
|
|
79
|
+
throw new Error('The Cairul project path must be a directory.');
|
|
80
|
+
let gitRoot;
|
|
81
|
+
for (let dir = cwd;; dir = dirname(dir)) {
|
|
82
|
+
if (await existingConfigDirectory(dir))
|
|
83
|
+
return dir;
|
|
84
|
+
gitRoot ??=
|
|
85
|
+
(await lstat(join(dir, '.git')).catch((error) => {
|
|
86
|
+
if (!isMissing(error))
|
|
87
|
+
throw error;
|
|
88
|
+
return undefined;
|
|
89
|
+
})) && dir;
|
|
90
|
+
if (dirname(dir) === dir)
|
|
91
|
+
return gitRoot ?? cwd;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
export async function readConfig(directory, stem, schema) {
|
|
95
|
+
const files = await Promise.all(['yaml', 'yml'].map(async (extension) => {
|
|
96
|
+
const name = `${stem}.${extension}`;
|
|
97
|
+
try {
|
|
98
|
+
const path = join(directory, name);
|
|
99
|
+
if (!(await lstat(path)).isFile())
|
|
100
|
+
throw new Error(`${path} must be a regular file.`);
|
|
101
|
+
return { name, source: await readFile(path, 'utf8') };
|
|
102
|
+
}
|
|
103
|
+
catch (error) {
|
|
104
|
+
if (!isMissing(error))
|
|
105
|
+
throw error;
|
|
106
|
+
}
|
|
107
|
+
}));
|
|
108
|
+
const present = files.filter((file) => file !== undefined);
|
|
109
|
+
if (present.length > 1)
|
|
110
|
+
throw new Error(`Use only one of ${stem}.yaml and ${stem}.yml in ${directory}.`);
|
|
111
|
+
const [file] = present;
|
|
112
|
+
if (!file)
|
|
113
|
+
return;
|
|
114
|
+
try {
|
|
115
|
+
return { file, data: await schema.parseAsync(parse(file.source, { maxAliasCount: 0 })) };
|
|
116
|
+
}
|
|
117
|
+
catch (error) {
|
|
118
|
+
throw new Error(`Invalid ${join(directory, file.name)}. ${error instanceof Error ? error.message : String(error)}`, {
|
|
119
|
+
cause: error,
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
function requireUnique(names, location) {
|
|
124
|
+
if (new Set(names).size !== names.length)
|
|
125
|
+
throw new Error(`Duplicate names in ${location}.`);
|
|
126
|
+
}
|
|
127
|
+
export async function loadConfig(project, url, registry) {
|
|
128
|
+
const directory = await configDirectory(project);
|
|
129
|
+
const checkConfig = checkConfigFor(registry);
|
|
130
|
+
const checks = await readConfig(directory, 'checks', z.strictObject({ checks: z.array(checkConfig) }));
|
|
131
|
+
const definitions = checks?.data.checks ?? [];
|
|
132
|
+
requireUnique(definitions.map(({ name }) => name), 'checks');
|
|
133
|
+
const catalog = new Map(definitions.map((check) => [check.name, check]));
|
|
134
|
+
const plans = await readConfig(directory, 'plans', z.strictObject({ plans: z.array(planConfig(checkConfig)) }));
|
|
135
|
+
const candidates = plans?.data.plans ?? [];
|
|
136
|
+
requireUnique(candidates.map(({ match }) => match), 'plan patterns');
|
|
137
|
+
const resolvedPlans = candidates.map((plan) => {
|
|
138
|
+
requireUnique(plan.phases.map(({ name }) => name), `phases for ${plan.match}`);
|
|
139
|
+
const phases = plan.phases.map((phase) => {
|
|
140
|
+
const checks = phase.checks.map((entry) => {
|
|
141
|
+
if (typeof entry !== 'string')
|
|
142
|
+
return { definition: entry, inline: true };
|
|
143
|
+
const definition = catalog.get(entry);
|
|
144
|
+
if (!definition)
|
|
145
|
+
throw new Error(`Unknown local check "${entry}" in phase "${phase.name}".`);
|
|
146
|
+
return { definition, inline: false };
|
|
147
|
+
});
|
|
148
|
+
requireUnique(checks.map(({ definition }) => definition.name), `checks in phase "${phase.name}" for ${plan.match}`);
|
|
149
|
+
return { ...phase, checks };
|
|
150
|
+
});
|
|
151
|
+
return { ...plan, phases };
|
|
152
|
+
});
|
|
153
|
+
const selected = resolvedPlans
|
|
154
|
+
.filter(({ match }) => url.startsWith(match.slice(0, -1)))
|
|
155
|
+
.sort((left, right) => right.match.length - left.match.length)[0];
|
|
156
|
+
const files = [checks?.file, plans?.file].filter((file) => file !== undefined);
|
|
157
|
+
return { selected, catalog, files };
|
|
158
|
+
}
|
|
159
|
+
export function effectivePlan({ selected, catalog }, backend) {
|
|
160
|
+
const overlays = new Map(selected?.phases.map((phase) => [phase.name, phase.checks]));
|
|
161
|
+
const configuredChecks = new Map();
|
|
162
|
+
const localCheck = ({ name, ...action }) => {
|
|
163
|
+
const id = randomUUID();
|
|
164
|
+
configuredChecks.set(id, action);
|
|
165
|
+
return {
|
|
166
|
+
id,
|
|
167
|
+
name,
|
|
168
|
+
action: { type: action.kind === shellKind ? 'local_command' : 'local_check', kind: action.kind },
|
|
169
|
+
};
|
|
170
|
+
};
|
|
171
|
+
const phases = (backend?.phases ?? []).map((phase) => {
|
|
172
|
+
const additions = overlays.get(phase.name) ?? [];
|
|
173
|
+
overlays.delete(phase.name);
|
|
174
|
+
const existing = new Set(phase.checks.map(({ name }) => name));
|
|
175
|
+
const localAdditions = additions.filter(({ definition, inline }) => {
|
|
176
|
+
if (!existing.has(definition.name))
|
|
177
|
+
return true;
|
|
178
|
+
if (inline) {
|
|
179
|
+
throw new Error(`Inline check "${definition.name}" in phase "${phase.name}" conflicts with a backend check. Use a different name or a named check in checks.yaml.`);
|
|
180
|
+
}
|
|
181
|
+
return false;
|
|
182
|
+
});
|
|
183
|
+
return {
|
|
184
|
+
...phase,
|
|
185
|
+
checks: [
|
|
186
|
+
...phase.checks.map((check) => {
|
|
187
|
+
const definition = catalog.get(check.name);
|
|
188
|
+
return definition ? localCheck(definition) : check;
|
|
189
|
+
}),
|
|
190
|
+
...localAdditions.map(({ definition }) => localCheck(definition)),
|
|
191
|
+
],
|
|
192
|
+
};
|
|
193
|
+
});
|
|
194
|
+
for (const [name, checks] of overlays)
|
|
195
|
+
phases.push({ id: randomUUID(), name, checks: checks.map(({ definition }) => localCheck(definition)) });
|
|
196
|
+
if (!phases.length)
|
|
197
|
+
phases.push({ id: randomUUID(), name: 'Work item', checks: [] });
|
|
198
|
+
const customized = Boolean(selected || configuredChecks.size);
|
|
199
|
+
const instructions = [backend?.instructions, selected?.instructions].filter(Boolean).join('\n\n');
|
|
200
|
+
const plan = {
|
|
201
|
+
id: backend && !customized ? backend.id : randomUUID(),
|
|
202
|
+
name: selected?.name ?? backend?.name ?? 'Local',
|
|
203
|
+
instructions,
|
|
204
|
+
revision: backend && !customized ? backend.revision : 1,
|
|
205
|
+
active: true,
|
|
206
|
+
created_at: backend && !customized ? backend.created_at : new Date().toISOString(),
|
|
207
|
+
phases,
|
|
208
|
+
};
|
|
209
|
+
return { plan, customized, actions: Object.fromEntries(configuredChecks) };
|
|
210
|
+
}
|