check-post 0.0.0-stage → 0.2.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 +21 -0
- package/README.md +147 -2
- package/dist/cli.js +51 -0
- package/dist/commands/init.js +219 -0
- package/dist/commands/list.js +50 -0
- package/dist/commands/run.js +149 -0
- package/dist/commands/shared.js +12 -0
- package/dist/commands/status.js +31 -0
- package/dist/core/adapters/claude-code.js +145 -0
- package/dist/core/adapters/index.js +14 -0
- package/dist/core/adapters/types.js +1 -0
- package/dist/core/discovery.js +183 -0
- package/dist/core/events.js +1 -0
- package/dist/core/gate.js +111 -0
- package/dist/core/process.js +20 -0
- package/dist/core/project.js +67 -0
- package/dist/core/runners/ai.js +91 -0
- package/dist/core/runners/command.js +48 -0
- package/dist/core/scheduler.js +158 -0
- package/dist/core/stage-file.js +61 -0
- package/dist/core/types.js +64 -0
- package/dist/ui/format.js +46 -0
- package/dist/ui/plain.js +47 -0
- package/dist/ui/tui/App.js +207 -0
- package/package.json +67 -4
- package/presets/angular/01-lint.md +4 -0
- package/presets/angular/02-unit-test.md +4 -0
- package/presets/angular/03-build.md +4 -0
- package/presets/angular/04-security/01-secrets.md +19 -0
- package/presets/angular/04-security/02-xss-audit.md +17 -0
- package/presets/angular/04-security/03-env-audit.md +11 -0
- package/presets/angular/04-security/04-dependency.md +5 -0
- package/presets/angular/04-security/_group.md +4 -0
- package/presets/angular/05-code-standard.md +15 -0
- package/presets/angular/context.md +2 -0
- package/presets/nextjs/01-lint.md +4 -0
- package/presets/nextjs/02-unit-test.md +4 -0
- package/presets/nextjs/03-build.md +4 -0
- package/presets/nextjs/04-security/01-secrets.md +19 -0
- package/presets/nextjs/04-security/02-xss-audit.md +16 -0
- package/presets/nextjs/04-security/03-env-audit.md +11 -0
- package/presets/nextjs/04-security/04-dependency.md +5 -0
- package/presets/nextjs/04-security/_group.md +4 -0
- package/presets/nextjs/05-code-standard.md +15 -0
- package/presets/nextjs/context.md +1 -0
- package/presets/node/01-lint.md +4 -0
- package/presets/node/02-unit-test.md +4 -0
- package/presets/node/03-build.md +4 -0
- package/presets/node/04-security/01-secrets.md +19 -0
- package/presets/node/04-security/02-injection-audit.md +15 -0
- package/presets/node/04-security/03-env-audit.md +11 -0
- package/presets/node/04-security/04-dependency.md +5 -0
- package/presets/node/04-security/_group.md +4 -0
- package/presets/node/05-code-standard.md +15 -0
- package/presets/node/context.md +1 -0
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
import pc from 'picocolors';
|
|
3
|
+
import { discoverPipeline } from '../core/discovery.js';
|
|
4
|
+
import { evaluateGate } from '../core/gate.js';
|
|
5
|
+
import { formatDuration } from '../ui/format.js';
|
|
6
|
+
import { printDefinitionError } from './shared.js';
|
|
7
|
+
export async function statusCommand(flags) {
|
|
8
|
+
const root = path.resolve(flags.cwd);
|
|
9
|
+
let pipeline;
|
|
10
|
+
try {
|
|
11
|
+
pipeline = discoverPipeline(root);
|
|
12
|
+
}
|
|
13
|
+
catch (err) {
|
|
14
|
+
return printDefinitionError(err);
|
|
15
|
+
}
|
|
16
|
+
const gate = await evaluateGate(pipeline);
|
|
17
|
+
if (flags.json) {
|
|
18
|
+
console.log(JSON.stringify({ gate: gate.green ? 'green' : 'red', reasons: gate.reasons, commit: gate.git.sha, lastRunAt: gate.lastRun?.updatedAt ?? null }, null, 2));
|
|
19
|
+
return gate.green ? 0 : 1;
|
|
20
|
+
}
|
|
21
|
+
const ref = gate.git.sha ? `${gate.git.branch}@${gate.git.sha.slice(0, 7)}` : '';
|
|
22
|
+
const ago = gate.lastRun ? ` · ran ${formatDuration(Date.now() - Date.parse(gate.lastRun.updatedAt))} ago` : '';
|
|
23
|
+
if (gate.green) {
|
|
24
|
+
console.log(pc.green(pc.bold(`✔ GREEN · ok to deploy`)) + pc.gray(` · ${ref}${ago}`));
|
|
25
|
+
return 0;
|
|
26
|
+
}
|
|
27
|
+
console.log(pc.red(pc.bold('✖ RED · not ready to deploy')) + pc.gray(ref ? ` · ${ref}${ago}` : ''));
|
|
28
|
+
for (const r of gate.reasons)
|
|
29
|
+
console.log(pc.gray(` • ${r}`));
|
|
30
|
+
return 1;
|
|
31
|
+
}
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import { execa } from 'execa';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { killTree } from '../process.js';
|
|
4
|
+
const READ_TOOLS = ['Read', 'Grep', 'Glob'];
|
|
5
|
+
/** Turn sensitive_paths globs into Claude Code permission deny rules. */
|
|
6
|
+
export function denyRules(globs) {
|
|
7
|
+
const rules = [];
|
|
8
|
+
for (const glob of globs) {
|
|
9
|
+
const pattern = glob.startsWith('/') || glob.startsWith('./') || glob.startsWith('**') ? glob : `./${glob}`;
|
|
10
|
+
for (const tool of READ_TOOLS)
|
|
11
|
+
rules.push(`${tool}(${pattern})`);
|
|
12
|
+
}
|
|
13
|
+
return rules;
|
|
14
|
+
}
|
|
15
|
+
function describeToolUse(name, input, cwd) {
|
|
16
|
+
const rel = (p) => (typeof p === 'string' ? path.relative(cwd, p) || p : '');
|
|
17
|
+
switch (name) {
|
|
18
|
+
case 'Read':
|
|
19
|
+
return `reading ${rel(input.file_path)}`;
|
|
20
|
+
case 'Grep':
|
|
21
|
+
return `searching "${String(input.pattern ?? '')}"${input.path ? ` in ${rel(input.path)}` : ''}`;
|
|
22
|
+
case 'Glob':
|
|
23
|
+
return `finding files ${String(input.pattern ?? '')}`;
|
|
24
|
+
default:
|
|
25
|
+
return name;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
export function createClaudeCodeAdapter(bin = 'claude') {
|
|
29
|
+
return {
|
|
30
|
+
id: 'claude-code',
|
|
31
|
+
label: 'Claude Code',
|
|
32
|
+
async detect() {
|
|
33
|
+
try {
|
|
34
|
+
const { stdout } = await execa(bin, ['--version'], { timeout: 15_000 });
|
|
35
|
+
return { installed: true, version: stdout.trim().split(/\s+/)[0] };
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
return { installed: false };
|
|
39
|
+
}
|
|
40
|
+
},
|
|
41
|
+
async run(o) {
|
|
42
|
+
const settings = { permissions: { deny: denyRules(o.denyPaths) } };
|
|
43
|
+
const args = [
|
|
44
|
+
'-p',
|
|
45
|
+
o.prompt,
|
|
46
|
+
'--output-format',
|
|
47
|
+
'stream-json',
|
|
48
|
+
'--verbose',
|
|
49
|
+
'--tools',
|
|
50
|
+
READ_TOOLS.join(','),
|
|
51
|
+
'--permission-mode',
|
|
52
|
+
'dontAsk',
|
|
53
|
+
'--no-session-persistence',
|
|
54
|
+
// Minimal context: no MCP servers, plugins, or user settings. This cuts the cost
|
|
55
|
+
// per stage from dollars to cents.
|
|
56
|
+
'--strict-mcp-config',
|
|
57
|
+
'--setting-sources',
|
|
58
|
+
'project',
|
|
59
|
+
'--disable-slash-commands',
|
|
60
|
+
'--system-prompt',
|
|
61
|
+
o.systemPrompt,
|
|
62
|
+
'--settings',
|
|
63
|
+
JSON.stringify(settings),
|
|
64
|
+
'--json-schema',
|
|
65
|
+
JSON.stringify(o.schema),
|
|
66
|
+
];
|
|
67
|
+
if (o.model)
|
|
68
|
+
args.push('--model', o.model);
|
|
69
|
+
if (o.maxBudgetUsd)
|
|
70
|
+
args.push('--max-budget-usd', String(o.maxBudgetUsd));
|
|
71
|
+
const child = execa(bin, args, {
|
|
72
|
+
cwd: o.cwd,
|
|
73
|
+
detached: true,
|
|
74
|
+
reject: false,
|
|
75
|
+
stdin: 'ignore',
|
|
76
|
+
lines: true,
|
|
77
|
+
buffer: { stdout: false, stderr: true },
|
|
78
|
+
});
|
|
79
|
+
let timedOut = false;
|
|
80
|
+
let canceled = false;
|
|
81
|
+
const timer = setTimeout(() => {
|
|
82
|
+
timedOut = true;
|
|
83
|
+
killTree(child.pid);
|
|
84
|
+
}, o.timeoutMs);
|
|
85
|
+
const onAbort = () => {
|
|
86
|
+
canceled = true;
|
|
87
|
+
killTree(child.pid);
|
|
88
|
+
};
|
|
89
|
+
if (o.signal?.aborted)
|
|
90
|
+
onAbort();
|
|
91
|
+
o.signal?.addEventListener('abort', onAbort, { once: true });
|
|
92
|
+
let final = null;
|
|
93
|
+
try {
|
|
94
|
+
for await (const line of child.iterable({ from: 'stdout' })) {
|
|
95
|
+
let event;
|
|
96
|
+
try {
|
|
97
|
+
event = JSON.parse(String(line));
|
|
98
|
+
}
|
|
99
|
+
catch {
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
if (event.type === 'assistant') {
|
|
103
|
+
const content = event.message?.content ?? [];
|
|
104
|
+
for (const block of content) {
|
|
105
|
+
if (block.type === 'tool_use' && block.name !== 'StructuredOutput') {
|
|
106
|
+
o.onActivity?.(describeToolUse(String(block.name), (block.input ?? {}), o.cwd));
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
else if (event.type === 'result') {
|
|
111
|
+
final = event;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
catch {
|
|
116
|
+
/* stream closed when the process is killed */
|
|
117
|
+
}
|
|
118
|
+
const done = await child;
|
|
119
|
+
clearTimeout(timer);
|
|
120
|
+
o.signal?.removeEventListener('abort', onAbort);
|
|
121
|
+
if (!final) {
|
|
122
|
+
const stderr = Array.isArray(done.stderr) ? done.stderr.join('\n') : String(done.stderr ?? '');
|
|
123
|
+
const reason = canceled
|
|
124
|
+
? 'cancelled'
|
|
125
|
+
: timedOut
|
|
126
|
+
? `timed out after ${Math.round(o.timeoutMs / 1000)}s`
|
|
127
|
+
: stderr.trim() || `claude exited with code ${done.exitCode}`;
|
|
128
|
+
throw new Error(`Claude Code failed: ${reason}`);
|
|
129
|
+
}
|
|
130
|
+
if (final.is_error) {
|
|
131
|
+
throw new Error(`Claude Code error: ${String(final.result ?? final.subtype ?? 'unknown')}`);
|
|
132
|
+
}
|
|
133
|
+
const denials = final.permission_denials ?? [];
|
|
134
|
+
return {
|
|
135
|
+
output: final.structured_output ?? null,
|
|
136
|
+
rawText: String(final.result ?? ''),
|
|
137
|
+
costUsd: typeof final.total_cost_usd === 'number' ? final.total_cost_usd : undefined,
|
|
138
|
+
deniedReads: denials.map((d) => {
|
|
139
|
+
const target = d.tool_input?.file_path ?? d.tool_input?.path ?? d.tool_input?.pattern;
|
|
140
|
+
return typeof target === 'string' ? path.relative(o.cwd, target) || target : '?';
|
|
141
|
+
}),
|
|
142
|
+
};
|
|
143
|
+
},
|
|
144
|
+
};
|
|
145
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { createClaudeCodeAdapter } from './claude-code.js';
|
|
2
|
+
export const AGENTS = {
|
|
3
|
+
'claude-code': { label: 'Claude Code', available: true, create: () => createClaudeCodeAdapter() },
|
|
4
|
+
gemini: { label: 'Gemini CLI', available: false },
|
|
5
|
+
codex: { label: 'Codex CLI', available: false },
|
|
6
|
+
};
|
|
7
|
+
export function getAdapter(id) {
|
|
8
|
+
const agent = AGENTS[id];
|
|
9
|
+
if (!agent)
|
|
10
|
+
throw new Error(`Unknown agent "${id}". Options: ${Object.keys(AGENTS).join(', ')}`);
|
|
11
|
+
if (!agent.create)
|
|
12
|
+
throw new Error(`Agent "${agent.label}" is not supported yet. Use claude-code for now.`);
|
|
13
|
+
return agent.create();
|
|
14
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { GroupConfigSchema, PipelineConfigSchema, StageConfigSchema, DEFAULT_SENSITIVE_PATHS, } from './types.js';
|
|
4
|
+
import { DefinitionError, parseMarkdown, stageTypeOf } from './stage-file.js';
|
|
5
|
+
export const PIPELINE_DIR = 'checkpost';
|
|
6
|
+
export const PIPELINE_FILE = 'pipeline.md';
|
|
7
|
+
export const GROUP_FILE = '_group.md';
|
|
8
|
+
/** `03-security` → { prefix: 3, name: 'security' }; `build.md` → { prefix: null, name: 'build' }. */
|
|
9
|
+
export function splitPrefix(fsName) {
|
|
10
|
+
const base = fsName.replace(/\.md$/i, '');
|
|
11
|
+
const m = base.match(/^(\d+)[-_.\s]+(.+)$/);
|
|
12
|
+
if (m)
|
|
13
|
+
return { prefix: Number(m[1]), name: m[2] };
|
|
14
|
+
return { prefix: null, name: base };
|
|
15
|
+
}
|
|
16
|
+
export function compareEntries(a, b) {
|
|
17
|
+
if (a.prefix !== null && b.prefix !== null && a.prefix !== b.prefix)
|
|
18
|
+
return a.prefix - b.prefix;
|
|
19
|
+
if (a.prefix !== null && b.prefix === null)
|
|
20
|
+
return -1;
|
|
21
|
+
if (a.prefix === null && b.prefix !== null)
|
|
22
|
+
return 1;
|
|
23
|
+
return a.name.localeCompare(b.name);
|
|
24
|
+
}
|
|
25
|
+
function listEntries(dir, isRoot) {
|
|
26
|
+
const entries = [];
|
|
27
|
+
for (const fsName of readdirSync(dir)) {
|
|
28
|
+
if (fsName.startsWith('.'))
|
|
29
|
+
continue;
|
|
30
|
+
if (fsName.startsWith('_'))
|
|
31
|
+
continue; // includes _group.md, which is read separately
|
|
32
|
+
if (isRoot && fsName === PIPELINE_FILE)
|
|
33
|
+
continue;
|
|
34
|
+
const full = path.join(dir, fsName);
|
|
35
|
+
const isDir = statSync(full).isDirectory();
|
|
36
|
+
if (!isDir && !fsName.toLowerCase().endsWith('.md'))
|
|
37
|
+
continue;
|
|
38
|
+
entries.push({ fsName, full, isDir, ...splitPrefix(fsName) });
|
|
39
|
+
}
|
|
40
|
+
return entries.sort(compareEntries);
|
|
41
|
+
}
|
|
42
|
+
export function discoverPipeline(root, dirName = PIPELINE_DIR) {
|
|
43
|
+
const dir = path.join(root, dirName);
|
|
44
|
+
if (!existsSync(dir) || !statSync(dir).isDirectory()) {
|
|
45
|
+
throw new DefinitionError([`Folder ${dirName}/ not found in ${root}. Run "checkpost init" first.`]);
|
|
46
|
+
}
|
|
47
|
+
const problems = [];
|
|
48
|
+
const rel = (p) => path.relative(root, p);
|
|
49
|
+
let pipelineConfig = PipelineConfigSchema.parse({});
|
|
50
|
+
let rootContext = [];
|
|
51
|
+
const pipelineFile = path.join(dir, PIPELINE_FILE);
|
|
52
|
+
if (existsSync(pipelineFile)) {
|
|
53
|
+
try {
|
|
54
|
+
const { data, body } = parseMarkdown(readFileSync(pipelineFile, 'utf8'), PipelineConfigSchema, rel(pipelineFile));
|
|
55
|
+
pipelineConfig = data;
|
|
56
|
+
if (body)
|
|
57
|
+
rootContext = [body];
|
|
58
|
+
}
|
|
59
|
+
catch (err) {
|
|
60
|
+
if (err instanceof DefinitionError)
|
|
61
|
+
problems.push(...err.problems);
|
|
62
|
+
else
|
|
63
|
+
throw err;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
pipelineConfig.sensitive_paths = [...new Set([...DEFAULT_SENSITIVE_PATHS, ...pipelineConfig.sensitive_paths])];
|
|
67
|
+
const walk = (current, context, isRoot) => {
|
|
68
|
+
const entries = listEntries(current, isRoot);
|
|
69
|
+
const seen = new Map();
|
|
70
|
+
for (const e of entries) {
|
|
71
|
+
if (e.prefix === null)
|
|
72
|
+
continue;
|
|
73
|
+
const other = seen.get(e.prefix);
|
|
74
|
+
if (other)
|
|
75
|
+
problems.push(`${rel(current) || '.'}: prefix ${e.prefix} is used twice (${other} and ${e.fsName})`);
|
|
76
|
+
else
|
|
77
|
+
seen.set(e.prefix, e.fsName);
|
|
78
|
+
}
|
|
79
|
+
const nodes = [];
|
|
80
|
+
for (const e of entries) {
|
|
81
|
+
const id = path.relative(dir, e.full).replace(/\.md$/i, '').split(path.sep).join('/');
|
|
82
|
+
if (e.isDir) {
|
|
83
|
+
let groupConfig = GroupConfigSchema.parse({});
|
|
84
|
+
let groupContext = context;
|
|
85
|
+
const groupFile = path.join(e.full, GROUP_FILE);
|
|
86
|
+
if (existsSync(groupFile)) {
|
|
87
|
+
try {
|
|
88
|
+
const { data, body } = parseMarkdown(readFileSync(groupFile, 'utf8'), GroupConfigSchema, rel(groupFile));
|
|
89
|
+
groupConfig = data;
|
|
90
|
+
if (body)
|
|
91
|
+
groupContext = [...context, body];
|
|
92
|
+
}
|
|
93
|
+
catch (err) {
|
|
94
|
+
if (err instanceof DefinitionError)
|
|
95
|
+
problems.push(...err.problems);
|
|
96
|
+
else
|
|
97
|
+
throw err;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
if (!groupConfig.enabled)
|
|
101
|
+
continue;
|
|
102
|
+
const children = walk(e.full, groupContext, false);
|
|
103
|
+
if (children.length === 0) {
|
|
104
|
+
problems.push(`${rel(e.full)}/: empty group (no enabled .md stages)`);
|
|
105
|
+
continue;
|
|
106
|
+
}
|
|
107
|
+
const group = {
|
|
108
|
+
kind: 'group',
|
|
109
|
+
id,
|
|
110
|
+
name: groupConfig.name ?? e.name,
|
|
111
|
+
dir: e.full,
|
|
112
|
+
config: groupConfig,
|
|
113
|
+
children,
|
|
114
|
+
context: groupContext,
|
|
115
|
+
};
|
|
116
|
+
nodes.push(group);
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
try {
|
|
120
|
+
const { data, body } = parseMarkdown(readFileSync(e.full, 'utf8'), StageConfigSchema, rel(e.full));
|
|
121
|
+
if (!data.enabled)
|
|
122
|
+
continue;
|
|
123
|
+
const type = stageTypeOf(data.run, body);
|
|
124
|
+
if (!type) {
|
|
125
|
+
problems.push(`${rel(e.full)}: empty stage. Add "run:" to the frontmatter, AI instructions to the body, or both.`);
|
|
126
|
+
continue;
|
|
127
|
+
}
|
|
128
|
+
const stage = {
|
|
129
|
+
kind: 'stage',
|
|
130
|
+
id,
|
|
131
|
+
name: data.name ?? e.name,
|
|
132
|
+
file: e.full,
|
|
133
|
+
type,
|
|
134
|
+
config: data,
|
|
135
|
+
body,
|
|
136
|
+
context,
|
|
137
|
+
};
|
|
138
|
+
nodes.push(stage);
|
|
139
|
+
}
|
|
140
|
+
catch (err) {
|
|
141
|
+
if (err instanceof DefinitionError)
|
|
142
|
+
problems.push(...err.problems);
|
|
143
|
+
else
|
|
144
|
+
throw err;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
return nodes;
|
|
148
|
+
};
|
|
149
|
+
const children = walk(dir, rootContext, true);
|
|
150
|
+
if (problems.length === 0 && children.length === 0) {
|
|
151
|
+
problems.push(`${dirName}/: no stages yet. Add a file such as 01-build.md.`);
|
|
152
|
+
}
|
|
153
|
+
if (problems.length)
|
|
154
|
+
throw new DefinitionError(problems);
|
|
155
|
+
return { root, dir, config: pipelineConfig, children };
|
|
156
|
+
}
|
|
157
|
+
/** Every node in display order, with its depth. */
|
|
158
|
+
export function flatten(nodes, depth = 0) {
|
|
159
|
+
const out = [];
|
|
160
|
+
for (const node of nodes) {
|
|
161
|
+
out.push({ node, depth });
|
|
162
|
+
if (node.kind === 'group')
|
|
163
|
+
out.push(...flatten(node.children, depth + 1));
|
|
164
|
+
}
|
|
165
|
+
return out;
|
|
166
|
+
}
|
|
167
|
+
export function allStages(nodes) {
|
|
168
|
+
return flatten(nodes)
|
|
169
|
+
.map((x) => x.node)
|
|
170
|
+
.filter((n) => n.kind === 'stage');
|
|
171
|
+
}
|
|
172
|
+
/** Find a node by exact id, id without prefixes, or name. */
|
|
173
|
+
export function findNode(nodes, query) {
|
|
174
|
+
const q = query.replace(/\.md$/i, '').replace(/\/+$/, '');
|
|
175
|
+
const all = flatten(nodes).map((x) => x.node);
|
|
176
|
+
const stripped = (id) => id
|
|
177
|
+
.split('/')
|
|
178
|
+
.map((seg) => splitPrefix(seg).name)
|
|
179
|
+
.join('/');
|
|
180
|
+
return (all.find((n) => n.id === q) ??
|
|
181
|
+
all.find((n) => stripped(n.id) === q) ??
|
|
182
|
+
all.find((n) => n.name === q));
|
|
183
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { execa } from 'execa';
|
|
5
|
+
import { allStages } from './discovery.js';
|
|
6
|
+
import { isBlockingFailure } from './scheduler.js';
|
|
7
|
+
export const STATE_DIR = '.checkpost';
|
|
8
|
+
const LAST_RUN = 'last-run.json';
|
|
9
|
+
/** checkpost's own paths do not count as project changes. */
|
|
10
|
+
const isOwnPath = (file) => file.startsWith(`${STATE_DIR}/`) || file.startsWith('checkpost/') || file === '.claude/commands/checkpost.md';
|
|
11
|
+
export async function readGitState(cwd) {
|
|
12
|
+
try {
|
|
13
|
+
const { stdout: top } = await execa('git', ['rev-parse', '--is-inside-work-tree'], { cwd });
|
|
14
|
+
if (top.trim() !== 'true')
|
|
15
|
+
throw new Error('not a repo');
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
return { isRepo: false, sha: null, branch: null, dirtyFiles: [] };
|
|
19
|
+
}
|
|
20
|
+
const sha = await execa('git', ['rev-parse', 'HEAD'], { cwd, reject: false });
|
|
21
|
+
// symbolic-ref also works in a repo with no commits (rev-parse HEAD fails there).
|
|
22
|
+
const branch = await execa('git', ['symbolic-ref', '--short', '-q', 'HEAD'], { cwd, reject: false });
|
|
23
|
+
const status = await execa('git', ['status', '--porcelain', '--untracked-files=all'], { cwd });
|
|
24
|
+
const dirtyFiles = status.stdout
|
|
25
|
+
.split('\n')
|
|
26
|
+
.filter(Boolean)
|
|
27
|
+
.map((l) => l.slice(3).replace(/^"|"$/g, '').split(' -> ').pop())
|
|
28
|
+
.filter((f) => !isOwnPath(f));
|
|
29
|
+
return {
|
|
30
|
+
isRepo: true,
|
|
31
|
+
sha: sha.exitCode === 0 ? sha.stdout.trim() : null,
|
|
32
|
+
branch: branch.exitCode === 0 ? branch.stdout.trim() : null,
|
|
33
|
+
dirtyFiles,
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
/** Hash of every stage definition, so editing a .md file invalidates old results. */
|
|
37
|
+
export function definitionsHash(pipeline) {
|
|
38
|
+
const h = createHash('sha256');
|
|
39
|
+
h.update(JSON.stringify(pipeline.config));
|
|
40
|
+
for (const s of allStages(pipeline.children)) {
|
|
41
|
+
h.update(s.id);
|
|
42
|
+
h.update(JSON.stringify(s.config));
|
|
43
|
+
h.update(s.body);
|
|
44
|
+
h.update(s.context.join('\n'));
|
|
45
|
+
}
|
|
46
|
+
return h.digest('hex').slice(0, 16);
|
|
47
|
+
}
|
|
48
|
+
const lastRunPath = (root) => path.join(root, STATE_DIR, LAST_RUN);
|
|
49
|
+
export function readLastRun(root) {
|
|
50
|
+
const file = lastRunPath(root);
|
|
51
|
+
if (!existsSync(file))
|
|
52
|
+
return null;
|
|
53
|
+
try {
|
|
54
|
+
return JSON.parse(readFileSync(file, 'utf8'));
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Save run results. A partial run (one stage/group) is merged into the previous results
|
|
62
|
+
* as long as the commit and stage definitions are unchanged.
|
|
63
|
+
*/
|
|
64
|
+
export function saveRun(pipeline, git, results, partial) {
|
|
65
|
+
const hash = definitionsHash(pipeline);
|
|
66
|
+
const previous = readLastRun(pipeline.root);
|
|
67
|
+
const canMerge = partial && previous && previous.sha === git.sha && previous.definitionsHash === hash;
|
|
68
|
+
const record = {
|
|
69
|
+
version: 1,
|
|
70
|
+
sha: git.sha,
|
|
71
|
+
branch: git.branch,
|
|
72
|
+
definitionsHash: hash,
|
|
73
|
+
dirtyAtRun: git.dirtyFiles,
|
|
74
|
+
updatedAt: new Date().toISOString(),
|
|
75
|
+
results: canMerge ? { ...previous.results, ...results } : results,
|
|
76
|
+
};
|
|
77
|
+
mkdirSync(path.join(pipeline.root, STATE_DIR), { recursive: true });
|
|
78
|
+
writeFileSync(lastRunPath(pipeline.root), JSON.stringify(record, null, 2));
|
|
79
|
+
return record;
|
|
80
|
+
}
|
|
81
|
+
export async function evaluateGate(pipeline) {
|
|
82
|
+
const git = await readGitState(pipeline.root);
|
|
83
|
+
const lastRun = readLastRun(pipeline.root);
|
|
84
|
+
const reasons = [];
|
|
85
|
+
if (!lastRun) {
|
|
86
|
+
reasons.push('pipeline has never been run');
|
|
87
|
+
return { green: false, reasons, lastRun, git };
|
|
88
|
+
}
|
|
89
|
+
if (git.isRepo && lastRun.sha !== git.sha) {
|
|
90
|
+
reasons.push(`last results are for commit ${lastRun.sha?.slice(0, 7) ?? '?'}, HEAD is now ${git.sha?.slice(0, 7) ?? '?'}`);
|
|
91
|
+
}
|
|
92
|
+
if (lastRun.definitionsHash !== definitionsHash(pipeline)) {
|
|
93
|
+
reasons.push('stage definitions changed since the last run');
|
|
94
|
+
}
|
|
95
|
+
if (pipeline.config.require_clean_tree && git.isRepo) {
|
|
96
|
+
if (git.dirtyFiles.length)
|
|
97
|
+
reasons.push(`working tree is dirty (${git.dirtyFiles.length} uncommitted file${git.dirtyFiles.length === 1 ? '' : 's'})`);
|
|
98
|
+
else if (lastRun.dirtyAtRun.length)
|
|
99
|
+
reasons.push('the last run happened on a dirty working tree');
|
|
100
|
+
}
|
|
101
|
+
for (const stage of allStages(pipeline.children)) {
|
|
102
|
+
const r = lastRun.results[stage.id];
|
|
103
|
+
if (!r)
|
|
104
|
+
reasons.push(`stage ${stage.id} has not run`);
|
|
105
|
+
else if (isBlockingFailure(r))
|
|
106
|
+
reasons.push(`stage ${stage.id} ${r.status === 'error' ? 'errored' : 'failed'}`);
|
|
107
|
+
else if (r.status === 'skipped' || r.status === 'pending' || r.status === 'running')
|
|
108
|
+
reasons.push(`stage ${stage.id} did not finish (${r.status})`);
|
|
109
|
+
}
|
|
110
|
+
return { green: reasons.length === 0, reasons, lastRun, git };
|
|
111
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/** Stop a whole process group (SIGTERM, then SIGKILL if still alive). */
|
|
2
|
+
export function killTree(pid, graceMs = 3000) {
|
|
3
|
+
if (!pid)
|
|
4
|
+
return;
|
|
5
|
+
const send = (signal) => {
|
|
6
|
+
try {
|
|
7
|
+
process.kill(-pid, signal);
|
|
8
|
+
}
|
|
9
|
+
catch {
|
|
10
|
+
try {
|
|
11
|
+
process.kill(pid, signal);
|
|
12
|
+
}
|
|
13
|
+
catch {
|
|
14
|
+
/* already dead */
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
};
|
|
18
|
+
send('SIGTERM');
|
|
19
|
+
setTimeout(() => send('SIGKILL'), graceMs).unref();
|
|
20
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { appendFileSync, existsSync, mkdirSync, readFileSync } from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { execa } from 'execa';
|
|
4
|
+
export function detectProject(root) {
|
|
5
|
+
const pkgFile = path.join(root, 'package.json');
|
|
6
|
+
let scripts = {};
|
|
7
|
+
let deps = {};
|
|
8
|
+
if (existsSync(pkgFile)) {
|
|
9
|
+
try {
|
|
10
|
+
const pkg = JSON.parse(readFileSync(pkgFile, 'utf8'));
|
|
11
|
+
scripts = pkg.scripts ?? {};
|
|
12
|
+
deps = { ...pkg.dependencies, ...pkg.devDependencies };
|
|
13
|
+
}
|
|
14
|
+
catch {
|
|
15
|
+
/* broken package.json: treat as a project without scripts */
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
const docs = ['AGENTS.md', 'CLAUDE.md', '.claude/CLAUDE.md', 'CONTRIBUTING.md'].filter((f) => existsSync(path.join(root, f)));
|
|
19
|
+
const version = (name) => (deps[name] ? ` ${deps[name].replace(/^[^\d]*/, '').split('.')[0]}` : '');
|
|
20
|
+
if (existsSync(path.join(root, 'angular.json')) || deps['@angular/core']) {
|
|
21
|
+
return { kind: 'angular', label: `Angular${version('@angular/core')}`, scripts, docs };
|
|
22
|
+
}
|
|
23
|
+
if (deps.next || ['next.config.js', 'next.config.mjs', 'next.config.ts'].some((f) => existsSync(path.join(root, f)))) {
|
|
24
|
+
return { kind: 'nextjs', label: `Next.js${version('next')}`, scripts, docs };
|
|
25
|
+
}
|
|
26
|
+
if (existsSync(pkgFile))
|
|
27
|
+
return { kind: 'node', label: 'Node.js', scripts, docs };
|
|
28
|
+
return { kind: 'unknown', label: 'unknown', scripts, docs };
|
|
29
|
+
}
|
|
30
|
+
/** npm script required by a `run` command, or null if it is not an npm command. */
|
|
31
|
+
export function npmScriptOf(run) {
|
|
32
|
+
const m = run.trim().match(/^npm\s+(?:run(?:-script)?\s+([\w:.-]+)|(test|start))\b/);
|
|
33
|
+
return m ? (m[1] ?? m[2]) : null;
|
|
34
|
+
}
|
|
35
|
+
export async function gitDir(root) {
|
|
36
|
+
const res = await execa('git', ['rev-parse', '--git-dir'], { cwd: root, reject: false });
|
|
37
|
+
return res.exitCode === 0 ? path.resolve(root, res.stdout.trim()) : null;
|
|
38
|
+
}
|
|
39
|
+
export async function isIgnored(root, rel) {
|
|
40
|
+
const res = await execa('git', ['check-ignore', '-q', rel], { cwd: root, reject: false });
|
|
41
|
+
return res.exitCode === 0;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Add patterns to `.git/info/exclude` (local only) or `.gitignore` (shared),
|
|
45
|
+
* only when git does not already ignore them.
|
|
46
|
+
*/
|
|
47
|
+
export async function ignorePaths(root, patterns, where) {
|
|
48
|
+
const added = [];
|
|
49
|
+
const target = where === 'gitignore'
|
|
50
|
+
? path.join(root, '.gitignore')
|
|
51
|
+
: await gitDir(root).then((d) => (d ? path.join(d, 'info', 'exclude') : null));
|
|
52
|
+
if (!target)
|
|
53
|
+
return added;
|
|
54
|
+
for (const pattern of patterns) {
|
|
55
|
+
const probe = pattern.replace(/\/$/, '/x');
|
|
56
|
+
if (await isIgnored(root, probe))
|
|
57
|
+
continue;
|
|
58
|
+
added.push(pattern);
|
|
59
|
+
}
|
|
60
|
+
if (added.length) {
|
|
61
|
+
mkdirSync(path.dirname(target), { recursive: true });
|
|
62
|
+
const existing = existsSync(target) ? readFileSync(target, 'utf8') : '';
|
|
63
|
+
const sep = existing && !existing.endsWith('\n') ? '\n' : '';
|
|
64
|
+
appendFileSync(target, `${sep}# checkpost\n${added.join('\n')}\n`);
|
|
65
|
+
}
|
|
66
|
+
return added;
|
|
67
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { AiVerdictSchema, SEVERITIES, severityRank } from '../types.js';
|
|
3
|
+
/**
|
|
4
|
+
* JSON Schema sent to the AI; must stay in sync with AiVerdictSchema.
|
|
5
|
+
* The `$schema` key is dropped because Claude Code rejects the draft 2020-12 reference.
|
|
6
|
+
*/
|
|
7
|
+
export const VERDICT_JSON_SCHEMA = (() => {
|
|
8
|
+
const { $schema: _ignored, ...schema } = z.toJSONSchema(AiVerdictSchema);
|
|
9
|
+
return schema;
|
|
10
|
+
})();
|
|
11
|
+
const MAX_COMMAND_OUTPUT_CHARS = 30_000;
|
|
12
|
+
export function buildSystemPrompt(sensitivePaths, language = 'English') {
|
|
13
|
+
return [
|
|
14
|
+
'You are an automated stage in a local CI pipeline. You audit a software project and report findings.',
|
|
15
|
+
'Rules:',
|
|
16
|
+
'- You are strictly read-only. You can only use Read, Grep and Glob. Never suggest you changed anything.',
|
|
17
|
+
`- Never try to read secret files. These paths are blocked and must be skipped: ${sensitivePaths.join(', ')}. ` +
|
|
18
|
+
'For environment configuration you may reason about variable NAMES only, never values.',
|
|
19
|
+
'- Be precise. Report only real, verifiable problems found in the code you actually read. No speculative or generic advice.',
|
|
20
|
+
'- Each finding must point to a file path relative to the project root and a 1-based line number when possible.',
|
|
21
|
+
'- Severity scale: critical (exploitable now / leaked secret), high (likely exploitable or serious bug), ' +
|
|
22
|
+
'medium (should be fixed soon), low (minor / hardening), info (observation, not a problem).',
|
|
23
|
+
'- If nothing is wrong, return an empty findings array.',
|
|
24
|
+
`- Write summary, message and suggestion in ${language}, regardless of the language of the code or instructions.`,
|
|
25
|
+
'- Your final answer MUST be the structured output object: { summary, findings[] }.',
|
|
26
|
+
].join('\n');
|
|
27
|
+
}
|
|
28
|
+
export function buildStagePrompt(stage, command) {
|
|
29
|
+
const parts = [];
|
|
30
|
+
if (stage.context.length) {
|
|
31
|
+
parts.push('## Project context', ...stage.context);
|
|
32
|
+
}
|
|
33
|
+
if (stage.config.paths?.length) {
|
|
34
|
+
parts.push('## Scope', `Only inspect files matching: ${stage.config.paths.join(', ')}`);
|
|
35
|
+
}
|
|
36
|
+
if (command) {
|
|
37
|
+
const out = command.output.length > MAX_COMMAND_OUTPUT_CHARS
|
|
38
|
+
? '[... earlier output truncated ...]\n' + command.output.slice(-MAX_COMMAND_OUTPUT_CHARS)
|
|
39
|
+
: command.output;
|
|
40
|
+
parts.push('## Command result', `Command: \`${command.run}\``, `Exit code: ${command.exitCode ?? 'unknown'}`, 'Output:', '```', out.trimEnd(), '```', 'Review this command result according to the stage instructions below. If the command failed because of a real problem, report it as a finding.');
|
|
41
|
+
}
|
|
42
|
+
parts.push(`## Stage: ${stage.name}`, stage.body);
|
|
43
|
+
return parts.join('\n\n');
|
|
44
|
+
}
|
|
45
|
+
export function isBlocking(finding, failOn) {
|
|
46
|
+
return severityRank(finding.severity) <= severityRank(failOn);
|
|
47
|
+
}
|
|
48
|
+
export function sortFindings(findings) {
|
|
49
|
+
return [...findings].sort((a, b) => severityRank(a.severity) - severityRank(b.severity));
|
|
50
|
+
}
|
|
51
|
+
/** Run an AI stage; ask again once if the answer does not match the schema. */
|
|
52
|
+
export async function runAiStage(adapter, stage, opts) {
|
|
53
|
+
const systemPrompt = buildSystemPrompt(opts.sensitivePaths, opts.language);
|
|
54
|
+
let prompt = buildStagePrompt(stage, opts.command);
|
|
55
|
+
let cost = 0;
|
|
56
|
+
const denied = [];
|
|
57
|
+
for (let attempt = 1; attempt <= 2; attempt++) {
|
|
58
|
+
const res = await adapter.run({
|
|
59
|
+
cwd: opts.cwd,
|
|
60
|
+
systemPrompt,
|
|
61
|
+
prompt,
|
|
62
|
+
schema: VERDICT_JSON_SCHEMA,
|
|
63
|
+
model: stage.config.model ?? opts.model,
|
|
64
|
+
denyPaths: opts.sensitivePaths,
|
|
65
|
+
maxBudgetUsd: stage.config.max_budget_usd ?? opts.maxBudgetUsd,
|
|
66
|
+
timeoutMs: opts.timeoutMs,
|
|
67
|
+
signal: opts.signal,
|
|
68
|
+
onActivity: (line) => opts.onLog(`[AI] ${line}`),
|
|
69
|
+
});
|
|
70
|
+
cost += res.costUsd ?? 0;
|
|
71
|
+
denied.push(...res.deniedReads);
|
|
72
|
+
let candidate = res.output;
|
|
73
|
+
if (candidate == null) {
|
|
74
|
+
try {
|
|
75
|
+
candidate = JSON.parse(res.rawText);
|
|
76
|
+
}
|
|
77
|
+
catch {
|
|
78
|
+
candidate = null;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
const parsed = AiVerdictSchema.safeParse(candidate);
|
|
82
|
+
if (parsed.success) {
|
|
83
|
+
return { verdict: { ...parsed.data, findings: sortFindings(parsed.data.findings) }, costUsd: cost, deniedReads: denied };
|
|
84
|
+
}
|
|
85
|
+
opts.onLog(`[AI] answer did not match the required format (attempt ${attempt}/2)`);
|
|
86
|
+
prompt =
|
|
87
|
+
buildStagePrompt(stage, opts.command) +
|
|
88
|
+
`\n\nIMPORTANT: your previous answer was not valid. Return ONLY the structured object with "summary" and "findings" (severity one of ${SEVERITIES.join(', ')}).`;
|
|
89
|
+
}
|
|
90
|
+
throw new Error('AI did not return a validly formatted answer after 2 attempts');
|
|
91
|
+
}
|