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,48 @@
|
|
|
1
|
+
import { execa } from 'execa';
|
|
2
|
+
import { killTree } from '../process.js';
|
|
3
|
+
const MAX_KEPT_OUTPUT = 200_000;
|
|
4
|
+
export async function runCommand(command, opts) {
|
|
5
|
+
// detached: the process leads its own process group, so a timeout or cancel can stop
|
|
6
|
+
// every descendant (e.g. `ng test` spawning a browser), not just the shell.
|
|
7
|
+
const child = execa(command, {
|
|
8
|
+
shell: true,
|
|
9
|
+
cwd: opts.cwd,
|
|
10
|
+
detached: true,
|
|
11
|
+
reject: false,
|
|
12
|
+
stdin: 'ignore',
|
|
13
|
+
all: true,
|
|
14
|
+
lines: true,
|
|
15
|
+
buffer: false,
|
|
16
|
+
env: { CI: '1', FORCE_COLOR: '0', NO_COLOR: '1' },
|
|
17
|
+
});
|
|
18
|
+
let timedOut = false;
|
|
19
|
+
let canceled = false;
|
|
20
|
+
const timer = setTimeout(() => {
|
|
21
|
+
timedOut = true;
|
|
22
|
+
killTree(child.pid);
|
|
23
|
+
}, opts.timeoutMs);
|
|
24
|
+
const onAbort = () => {
|
|
25
|
+
canceled = true;
|
|
26
|
+
killTree(child.pid);
|
|
27
|
+
};
|
|
28
|
+
if (opts.signal?.aborted)
|
|
29
|
+
onAbort();
|
|
30
|
+
opts.signal?.addEventListener('abort', onAbort, { once: true });
|
|
31
|
+
let output = '';
|
|
32
|
+
try {
|
|
33
|
+
for await (const line of child.iterable({ from: 'all' })) {
|
|
34
|
+
const text = String(line);
|
|
35
|
+
opts.onLine(text);
|
|
36
|
+
output += text + '\n';
|
|
37
|
+
if (output.length > MAX_KEPT_OUTPUT)
|
|
38
|
+
output = output.slice(-MAX_KEPT_OUTPUT);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
catch {
|
|
42
|
+
/* stream closed when the process is killed */
|
|
43
|
+
}
|
|
44
|
+
const done = await child;
|
|
45
|
+
clearTimeout(timer);
|
|
46
|
+
opts.signal?.removeEventListener('abort', onAbort);
|
|
47
|
+
return { exitCode: done.exitCode ?? null, output, timedOut, canceled };
|
|
48
|
+
}
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
import { createWriteStream, mkdirSync } from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { runAiStage, isBlocking } from './runners/ai.js';
|
|
4
|
+
import { runCommand } from './runners/command.js';
|
|
5
|
+
import { parseDuration } from './stage-file.js';
|
|
6
|
+
// Same as STATE_DIR in gate.ts (not imported, to avoid a circular import).
|
|
7
|
+
const STATE_DIR_NAME = '.checkpost';
|
|
8
|
+
const DEFAULT_COMMAND_TIMEOUT_MS = 15 * 60_000;
|
|
9
|
+
const DEFAULT_AI_TIMEOUT_MS = 10 * 60_000;
|
|
10
|
+
/** A stage/group blocks the pipeline when it failed and is not allow_failure. */
|
|
11
|
+
export const isBlockingFailure = (r) => (r.status === 'failed' || r.status === 'error') && !r.allowFailure;
|
|
12
|
+
function stagesIn(node) {
|
|
13
|
+
return node.kind === 'stage' ? [node] : node.children.flatMap(stagesIn);
|
|
14
|
+
}
|
|
15
|
+
export async function runPipeline(pipeline, opts) {
|
|
16
|
+
const started = Date.now();
|
|
17
|
+
const runId = opts.runId ?? new Date(started).toISOString().replace(/[:.]/g, '-');
|
|
18
|
+
const logDir = path.join(opts.stateDir ?? path.join(pipeline.root, STATE_DIR_NAME), 'logs', runId);
|
|
19
|
+
mkdirSync(logDir, { recursive: true });
|
|
20
|
+
const results = {};
|
|
21
|
+
const skip = (nodes, reason) => {
|
|
22
|
+
for (const stage of nodes.flatMap(stagesIn)) {
|
|
23
|
+
const result = {
|
|
24
|
+
id: stage.id,
|
|
25
|
+
status: 'skipped',
|
|
26
|
+
durationMs: 0,
|
|
27
|
+
findings: [],
|
|
28
|
+
summary: reason,
|
|
29
|
+
allowFailure: stage.config.allow_failure,
|
|
30
|
+
};
|
|
31
|
+
results[stage.id] = result;
|
|
32
|
+
opts.onEvent({ type: 'stage:finish', id: stage.id, result });
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
const runStage = async (stage) => {
|
|
36
|
+
const t0 = Date.now();
|
|
37
|
+
opts.onEvent({ type: 'stage:start', id: stage.id, at: t0 });
|
|
38
|
+
const logFile = path.join(logDir, stage.id.replace(/\//g, '__') + '.log');
|
|
39
|
+
const log = createWriteStream(logFile);
|
|
40
|
+
const emit = (line) => {
|
|
41
|
+
log.write(line + '\n');
|
|
42
|
+
opts.onEvent({ type: 'stage:log', id: stage.id, line });
|
|
43
|
+
};
|
|
44
|
+
const finish = (partial) => {
|
|
45
|
+
const result = {
|
|
46
|
+
id: stage.id,
|
|
47
|
+
durationMs: Date.now() - t0,
|
|
48
|
+
allowFailure: stage.config.allow_failure,
|
|
49
|
+
findings: [],
|
|
50
|
+
logFile,
|
|
51
|
+
...partial,
|
|
52
|
+
};
|
|
53
|
+
log.end();
|
|
54
|
+
results[stage.id] = result;
|
|
55
|
+
opts.onEvent({ type: 'stage:finish', id: stage.id, result });
|
|
56
|
+
return result;
|
|
57
|
+
};
|
|
58
|
+
try {
|
|
59
|
+
let command;
|
|
60
|
+
if (stage.type === 'command' || stage.type === 'command+ai') {
|
|
61
|
+
const run = stage.config.run;
|
|
62
|
+
emit(`$ ${run}`);
|
|
63
|
+
const res = await runCommand(run, {
|
|
64
|
+
cwd: pipeline.root,
|
|
65
|
+
timeoutMs: parseDuration(stage.config.timeout, DEFAULT_COMMAND_TIMEOUT_MS),
|
|
66
|
+
signal: opts.signal,
|
|
67
|
+
onLine: emit,
|
|
68
|
+
});
|
|
69
|
+
if (res.canceled)
|
|
70
|
+
return finish({ status: 'skipped', summary: 'cancelled', exitCode: res.exitCode });
|
|
71
|
+
if (res.timedOut)
|
|
72
|
+
return finish({ status: 'error', error: 'timeout', exitCode: res.exitCode });
|
|
73
|
+
if (stage.type === 'command') {
|
|
74
|
+
return finish({
|
|
75
|
+
status: res.exitCode === 0 ? 'passed' : 'failed',
|
|
76
|
+
exitCode: res.exitCode,
|
|
77
|
+
summary: res.exitCode === 0 ? undefined : `exit code ${res.exitCode}`,
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
command = { run, exitCode: res.exitCode, output: res.output };
|
|
81
|
+
emit(`[AI] reviewing the command result (exit code ${res.exitCode})…`);
|
|
82
|
+
}
|
|
83
|
+
if (!opts.adapter)
|
|
84
|
+
throw new Error('AI stage needs an agent, but none is available');
|
|
85
|
+
const outcome = await runAiStage(opts.adapter, stage, {
|
|
86
|
+
cwd: pipeline.root,
|
|
87
|
+
model: pipeline.config.model,
|
|
88
|
+
language: pipeline.config.language,
|
|
89
|
+
sensitivePaths: pipeline.config.sensitive_paths,
|
|
90
|
+
maxBudgetUsd: pipeline.config.max_budget_usd,
|
|
91
|
+
timeoutMs: parseDuration(stage.config.timeout, DEFAULT_AI_TIMEOUT_MS),
|
|
92
|
+
signal: opts.signal,
|
|
93
|
+
onLog: emit,
|
|
94
|
+
command,
|
|
95
|
+
});
|
|
96
|
+
for (const denied of outcome.deniedReads)
|
|
97
|
+
emit(`[AI] access blocked: ${denied}`);
|
|
98
|
+
const blocking = outcome.verdict.findings.filter((f) => isBlocking(f, stage.config.fail_on));
|
|
99
|
+
emit(`[AI] ${outcome.verdict.summary}`);
|
|
100
|
+
return finish({
|
|
101
|
+
status: blocking.length ? 'failed' : 'passed',
|
|
102
|
+
exitCode: command?.exitCode,
|
|
103
|
+
summary: outcome.verdict.summary,
|
|
104
|
+
findings: outcome.verdict.findings,
|
|
105
|
+
costUsd: outcome.costUsd,
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
catch (err) {
|
|
109
|
+
if (opts.signal?.aborted)
|
|
110
|
+
return finish({ status: 'skipped', summary: 'cancelled' });
|
|
111
|
+
const message = err.message;
|
|
112
|
+
emit(`ERROR: ${message}`);
|
|
113
|
+
return finish({ status: 'error', error: message });
|
|
114
|
+
}
|
|
115
|
+
};
|
|
116
|
+
/** Returns true when the node ended in a blocking failure. */
|
|
117
|
+
const runNode = async (node, failFast) => {
|
|
118
|
+
if (node.kind === 'stage')
|
|
119
|
+
return isBlockingFailure(await runStage(node));
|
|
120
|
+
return runGroup(node, node.config.fail_fast ?? failFast);
|
|
121
|
+
};
|
|
122
|
+
const runGroup = async (group, failFast) => {
|
|
123
|
+
const t0 = Date.now();
|
|
124
|
+
opts.onEvent({ type: 'group:start', id: group.id });
|
|
125
|
+
const failed = group.config.parallel
|
|
126
|
+
? (await Promise.all(group.children.map((c) => runNode(c, failFast)))).some(Boolean)
|
|
127
|
+
: await runSequence(group.children, failFast);
|
|
128
|
+
const status = failed
|
|
129
|
+
? 'failed'
|
|
130
|
+
: stagesIn(group).every((s) => results[s.id]?.status === 'skipped')
|
|
131
|
+
? 'skipped'
|
|
132
|
+
: 'passed';
|
|
133
|
+
opts.onEvent({ type: 'group:finish', id: group.id, status, durationMs: Date.now() - t0 });
|
|
134
|
+
return failed;
|
|
135
|
+
};
|
|
136
|
+
const runSequence = async (nodes, failFast) => {
|
|
137
|
+
let failed = false;
|
|
138
|
+
for (let i = 0; i < nodes.length; i++) {
|
|
139
|
+
if (opts.signal?.aborted) {
|
|
140
|
+
skip(nodes.slice(i), 'cancelled');
|
|
141
|
+
break;
|
|
142
|
+
}
|
|
143
|
+
if (await runNode(nodes[i], failFast)) {
|
|
144
|
+
failed = true;
|
|
145
|
+
if (failFast) {
|
|
146
|
+
skip(nodes.slice(i + 1), 'skipped: an earlier stage failed');
|
|
147
|
+
break;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
return failed;
|
|
152
|
+
};
|
|
153
|
+
const failed = await runSequence(opts.nodes ?? pipeline.children, pipeline.config.fail_fast);
|
|
154
|
+
const durationMs = Date.now() - started;
|
|
155
|
+
const passed = !failed && !opts.signal?.aborted;
|
|
156
|
+
opts.onEvent({ type: 'pipeline:finish', results, passed, durationMs });
|
|
157
|
+
return { results, passed, durationMs };
|
|
158
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import matter from 'gray-matter';
|
|
2
|
+
export class DefinitionError extends Error {
|
|
3
|
+
problems;
|
|
4
|
+
constructor(problems) {
|
|
5
|
+
super(problems.join('\n'));
|
|
6
|
+
this.problems = problems;
|
|
7
|
+
this.name = 'DefinitionError';
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
/** Parse YAML frontmatter + Markdown body, then validate the frontmatter against a schema. */
|
|
11
|
+
export function parseMarkdown(source, schema, fileLabel) {
|
|
12
|
+
let parsed;
|
|
13
|
+
try {
|
|
14
|
+
// No cache: gray-matter caches by input string, which breaks tests.
|
|
15
|
+
parsed = matter(source, {});
|
|
16
|
+
}
|
|
17
|
+
catch (err) {
|
|
18
|
+
throw new DefinitionError([`${fileLabel}: invalid YAML frontmatter (${err.message})`]);
|
|
19
|
+
}
|
|
20
|
+
const result = schema.safeParse(parsed.data ?? {});
|
|
21
|
+
if (!result.success) {
|
|
22
|
+
const problems = result.error.issues.map((issue) => {
|
|
23
|
+
const key = issue.path.join('.') || '(frontmatter)';
|
|
24
|
+
return `${fileLabel}: ${key}: ${issue.message}`;
|
|
25
|
+
});
|
|
26
|
+
throw new DefinitionError(problems);
|
|
27
|
+
}
|
|
28
|
+
return { data: result.data, body: parsed.content.trim() };
|
|
29
|
+
}
|
|
30
|
+
export function stageTypeOf(run, body) {
|
|
31
|
+
const hasRun = Boolean(run && run.trim());
|
|
32
|
+
const hasBody = body.trim().length > 0;
|
|
33
|
+
if (hasRun && hasBody)
|
|
34
|
+
return 'command+ai';
|
|
35
|
+
if (hasRun)
|
|
36
|
+
return 'command';
|
|
37
|
+
if (hasBody)
|
|
38
|
+
return 'ai';
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
/** Convert `30s`, `5m`, `1h`, `500ms`, or a number (seconds) to milliseconds. */
|
|
42
|
+
export function parseDuration(value, fallbackMs) {
|
|
43
|
+
if (value === undefined)
|
|
44
|
+
return fallbackMs;
|
|
45
|
+
if (typeof value === 'number')
|
|
46
|
+
return value * 1000;
|
|
47
|
+
const m = value.trim().match(/^(\d+(?:\.\d+)?)\s*(ms|s|m|h)?$/);
|
|
48
|
+
if (!m)
|
|
49
|
+
return fallbackMs;
|
|
50
|
+
const n = Number(m[1]);
|
|
51
|
+
switch (m[2] ?? 's') {
|
|
52
|
+
case 'ms':
|
|
53
|
+
return n;
|
|
54
|
+
case 'm':
|
|
55
|
+
return n * 60_000;
|
|
56
|
+
case 'h':
|
|
57
|
+
return n * 3_600_000;
|
|
58
|
+
default:
|
|
59
|
+
return n * 1000;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
export const SEVERITIES = ['critical', 'high', 'medium', 'low', 'info'];
|
|
3
|
+
/** Severity rank: lower number = more severe. */
|
|
4
|
+
export const severityRank = (s) => SEVERITIES.indexOf(s);
|
|
5
|
+
const duration = z.union([z.number().positive(), z.string().regex(/^\d+(\.\d+)?\s*(ms|s|m|h)?$/)]);
|
|
6
|
+
export const StageConfigSchema = z
|
|
7
|
+
.object({
|
|
8
|
+
name: z.string().optional(),
|
|
9
|
+
// YAML reads `run: true` or `run: 123` as a boolean/number; treat it as a command.
|
|
10
|
+
run: z.union([z.string(), z.number(), z.boolean()]).transform(String).optional(),
|
|
11
|
+
timeout: duration.optional(),
|
|
12
|
+
fail_on: z.enum(SEVERITIES).default('high'),
|
|
13
|
+
paths: z.array(z.string()).optional(),
|
|
14
|
+
allow_failure: z.boolean().default(false),
|
|
15
|
+
enabled: z.boolean().default(true),
|
|
16
|
+
agent: z.string().optional(),
|
|
17
|
+
model: z.string().optional(),
|
|
18
|
+
max_budget_usd: z.number().positive().optional(),
|
|
19
|
+
})
|
|
20
|
+
.strict();
|
|
21
|
+
export const GroupConfigSchema = z
|
|
22
|
+
.object({
|
|
23
|
+
name: z.string().optional(),
|
|
24
|
+
parallel: z.boolean().default(false),
|
|
25
|
+
fail_fast: z.boolean().optional(),
|
|
26
|
+
enabled: z.boolean().default(true),
|
|
27
|
+
})
|
|
28
|
+
.strict();
|
|
29
|
+
export const DEFAULT_SENSITIVE_PATHS = [
|
|
30
|
+
'.env',
|
|
31
|
+
'.env.*',
|
|
32
|
+
'**/.env',
|
|
33
|
+
'**/.env.*',
|
|
34
|
+
'.npmrc',
|
|
35
|
+
'**/.npmrc',
|
|
36
|
+
'**/*.pem',
|
|
37
|
+
'**/*.key',
|
|
38
|
+
'**/id_rsa*',
|
|
39
|
+
];
|
|
40
|
+
export const PipelineConfigSchema = z
|
|
41
|
+
.object({
|
|
42
|
+
name: z.string().optional(),
|
|
43
|
+
agent: z.string().default('claude-code'),
|
|
44
|
+
model: z.string().default('sonnet'),
|
|
45
|
+
/** Language for AI summaries and findings, e.g. English or Indonesian. */
|
|
46
|
+
language: z.string().min(1).default('English'),
|
|
47
|
+
fail_fast: z.boolean().default(true),
|
|
48
|
+
require_clean_tree: z.boolean().default(true),
|
|
49
|
+
sensitive_paths: z.array(z.string()).default([]),
|
|
50
|
+
max_budget_usd: z.number().positive().default(1),
|
|
51
|
+
confirm_ai: z.boolean().default(true),
|
|
52
|
+
})
|
|
53
|
+
.strict();
|
|
54
|
+
export const FindingSchema = z.object({
|
|
55
|
+
severity: z.enum(SEVERITIES),
|
|
56
|
+
file: z.string().nullable(),
|
|
57
|
+
line: z.number().int().nullable(),
|
|
58
|
+
message: z.string(),
|
|
59
|
+
suggestion: z.string().nullable(),
|
|
60
|
+
});
|
|
61
|
+
export const AiVerdictSchema = z.object({
|
|
62
|
+
summary: z.string(),
|
|
63
|
+
findings: z.array(FindingSchema),
|
|
64
|
+
});
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
export const STATUS_ICON = {
|
|
2
|
+
pending: '○',
|
|
3
|
+
running: '●',
|
|
4
|
+
passed: '✔',
|
|
5
|
+
failed: '✖',
|
|
6
|
+
error: '✖',
|
|
7
|
+
skipped: '–',
|
|
8
|
+
};
|
|
9
|
+
export const STATUS_COLOR = {
|
|
10
|
+
pending: 'gray',
|
|
11
|
+
running: 'yellow',
|
|
12
|
+
passed: 'green',
|
|
13
|
+
failed: 'red',
|
|
14
|
+
error: 'red',
|
|
15
|
+
skipped: 'gray',
|
|
16
|
+
};
|
|
17
|
+
export const SEVERITY_COLOR = {
|
|
18
|
+
critical: 'magenta',
|
|
19
|
+
high: 'red',
|
|
20
|
+
medium: 'yellow',
|
|
21
|
+
low: 'cyan',
|
|
22
|
+
info: 'gray',
|
|
23
|
+
};
|
|
24
|
+
export function formatDuration(ms) {
|
|
25
|
+
if (ms < 1000)
|
|
26
|
+
return `${ms}ms`;
|
|
27
|
+
const s = ms / 1000;
|
|
28
|
+
if (s < 60)
|
|
29
|
+
return `${s.toFixed(1)}s`;
|
|
30
|
+
const m = Math.floor(s / 60);
|
|
31
|
+
return `${m}m ${Math.round(s % 60)}s`;
|
|
32
|
+
}
|
|
33
|
+
export function typeLabel(node) {
|
|
34
|
+
if (node.kind === 'group')
|
|
35
|
+
return node.config.parallel ? 'parallel group' : 'group';
|
|
36
|
+
if (node.type === 'ai')
|
|
37
|
+
return 'AI';
|
|
38
|
+
if (node.type === 'command+ai')
|
|
39
|
+
return 'cmd+AI';
|
|
40
|
+
return 'command';
|
|
41
|
+
}
|
|
42
|
+
export function findingLocation(f) {
|
|
43
|
+
if (!f.file)
|
|
44
|
+
return '';
|
|
45
|
+
return f.line ? `${f.file}:${f.line}` : f.file;
|
|
46
|
+
}
|
package/dist/ui/plain.js
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import pc from 'picocolors';
|
|
2
|
+
import { isBlocking } from '../core/runners/ai.js';
|
|
3
|
+
import { formatDuration, findingLocation } from './format.js';
|
|
4
|
+
const colorBySeverity = { critical: pc.magenta, high: pc.red, medium: pc.yellow, low: pc.cyan, info: pc.gray };
|
|
5
|
+
/** Renderer for CI / non-TTY: one line per event, stage logs prefixed. */
|
|
6
|
+
export function createPlainRenderer(stages, opts) {
|
|
7
|
+
const write = opts.write ?? ((s) => process.stdout.write(s + '\n'));
|
|
8
|
+
return (e) => {
|
|
9
|
+
switch (e.type) {
|
|
10
|
+
case 'stage:start':
|
|
11
|
+
write(pc.cyan(`▶ ${e.id}`));
|
|
12
|
+
break;
|
|
13
|
+
case 'stage:log':
|
|
14
|
+
if (opts.verbose || e.line.startsWith('[AI]'))
|
|
15
|
+
write(pc.dim(` │ ${e.line}`));
|
|
16
|
+
break;
|
|
17
|
+
case 'stage:finish': {
|
|
18
|
+
const r = e.result;
|
|
19
|
+
const stage = stages.get(e.id);
|
|
20
|
+
const time = formatDuration(r.durationMs);
|
|
21
|
+
const cost = r.costUsd ? ` · $${r.costUsd.toFixed(3)}` : '';
|
|
22
|
+
const label = `${e.id} ${pc.dim(`${time}${cost}`)}`;
|
|
23
|
+
if (r.status === 'passed')
|
|
24
|
+
write(pc.green(`✔ ${label}`));
|
|
25
|
+
else if (r.status === 'skipped')
|
|
26
|
+
write(pc.gray(`– ${e.id} (${r.summary ?? 'skipped'})`));
|
|
27
|
+
else {
|
|
28
|
+
const tag = r.allowFailure ? pc.yellow(' [allow_failure]') : '';
|
|
29
|
+
write(pc.red(`✖ ${label}`) + tag + (r.error ? pc.red(` · ${r.error}`) : r.summary ? pc.dim(` · ${r.summary}`) : ''));
|
|
30
|
+
if (r.status === 'failed' && stage?.type === 'command' && r.logFile)
|
|
31
|
+
write(pc.dim(` log: ${r.logFile}`));
|
|
32
|
+
}
|
|
33
|
+
for (const f of r.findings) {
|
|
34
|
+
const blocking = stage ? isBlocking(f, stage.config.fail_on) : false;
|
|
35
|
+
const sev = colorBySeverity[f.severity](f.severity.toUpperCase().padEnd(8));
|
|
36
|
+
write(` ${blocking ? '!' : ' '} ${sev} ${findingLocation(f)}`);
|
|
37
|
+
write(` ${f.message}`);
|
|
38
|
+
if (f.suggestion)
|
|
39
|
+
write(pc.dim(` → ${f.suggestion}`));
|
|
40
|
+
}
|
|
41
|
+
break;
|
|
42
|
+
}
|
|
43
|
+
default:
|
|
44
|
+
break;
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
}
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
import { spawn } from 'node:child_process';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
|
5
|
+
import { Box, Text, useApp, useInput, useWindowSize } from 'ink';
|
|
6
|
+
import { flatten } from '../../core/discovery.js';
|
|
7
|
+
import { isBlocking } from '../../core/runners/ai.js';
|
|
8
|
+
import { SEVERITY_COLOR, STATUS_COLOR, STATUS_ICON, findingLocation, formatDuration, typeLabel } from '../format.js';
|
|
9
|
+
const SPINNER = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
|
|
10
|
+
const MAX_LOG_LINES = 400;
|
|
11
|
+
export function App({ pipeline, header, execute, initialNodes }) {
|
|
12
|
+
const { exit } = useApp();
|
|
13
|
+
const { rows } = useWindowSize();
|
|
14
|
+
const rowsList = useMemo(() => flatten(pipeline.children), [pipeline]);
|
|
15
|
+
const [states, setStates] = useState({});
|
|
16
|
+
const [logs, setLogs] = useState({});
|
|
17
|
+
const [selected, setSelected] = useState(0);
|
|
18
|
+
const [follow, setFollow] = useState(true);
|
|
19
|
+
const [view, setView] = useState('list');
|
|
20
|
+
const [detailOffset, setDetailOffset] = useState(0);
|
|
21
|
+
const [running, setRunning] = useState(false);
|
|
22
|
+
const [gate, setGate] = useState(null);
|
|
23
|
+
const [notice, setNotice] = useState(null);
|
|
24
|
+
const [tick, setTick] = useState(0);
|
|
25
|
+
const controller = useRef(null);
|
|
26
|
+
const quitting = useRef(false);
|
|
27
|
+
useEffect(() => {
|
|
28
|
+
if (!running)
|
|
29
|
+
return;
|
|
30
|
+
const t = setInterval(() => setTick((x) => x + 1), 100);
|
|
31
|
+
return () => clearInterval(t);
|
|
32
|
+
}, [running]);
|
|
33
|
+
const onEvent = useCallback((e) => {
|
|
34
|
+
switch (e.type) {
|
|
35
|
+
case 'stage:start':
|
|
36
|
+
case 'group:start':
|
|
37
|
+
setStates((s) => ({ ...s, [e.id]: { status: 'running', startedAt: Date.now() } }));
|
|
38
|
+
if (e.type === 'stage:start') {
|
|
39
|
+
setLogs((l) => ({ ...l, [e.id]: [] }));
|
|
40
|
+
setFollow((f) => {
|
|
41
|
+
if (f) {
|
|
42
|
+
const idx = rowsList.findIndex((r) => r.node.id === e.id);
|
|
43
|
+
if (idx >= 0)
|
|
44
|
+
setSelected(idx);
|
|
45
|
+
}
|
|
46
|
+
return f;
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
break;
|
|
50
|
+
case 'stage:log':
|
|
51
|
+
setLogs((l) => {
|
|
52
|
+
const lines = [...(l[e.id] ?? []), e.line];
|
|
53
|
+
return { ...l, [e.id]: lines.length > MAX_LOG_LINES ? lines.slice(-MAX_LOG_LINES) : lines };
|
|
54
|
+
});
|
|
55
|
+
break;
|
|
56
|
+
case 'stage:finish':
|
|
57
|
+
setStates((s) => ({ ...s, [e.id]: { status: e.result.status, durationMs: e.result.durationMs, result: e.result } }));
|
|
58
|
+
break;
|
|
59
|
+
case 'group:finish':
|
|
60
|
+
setStates((s) => ({ ...s, [e.id]: { status: e.status, durationMs: e.durationMs } }));
|
|
61
|
+
break;
|
|
62
|
+
default:
|
|
63
|
+
break;
|
|
64
|
+
}
|
|
65
|
+
}, [rowsList]);
|
|
66
|
+
const start = useCallback((nodes) => {
|
|
67
|
+
const targets = nodes ?? pipeline.children;
|
|
68
|
+
const ids = new Set(flatten(targets).map((r) => r.node.id));
|
|
69
|
+
setStates((s) => {
|
|
70
|
+
const next = { ...s };
|
|
71
|
+
for (const id of ids)
|
|
72
|
+
next[id] = { status: 'pending' };
|
|
73
|
+
return next;
|
|
74
|
+
});
|
|
75
|
+
setGate(null);
|
|
76
|
+
setNotice(null);
|
|
77
|
+
setFollow(true);
|
|
78
|
+
setRunning(true);
|
|
79
|
+
const ac = new AbortController();
|
|
80
|
+
controller.current = ac;
|
|
81
|
+
execute(nodes, onEvent, ac.signal)
|
|
82
|
+
.then((g) => setGate(g))
|
|
83
|
+
.catch((err) => setNotice(`Error: ${err.message}`))
|
|
84
|
+
.finally(() => {
|
|
85
|
+
setRunning(false);
|
|
86
|
+
controller.current = null;
|
|
87
|
+
if (quitting.current)
|
|
88
|
+
exit();
|
|
89
|
+
});
|
|
90
|
+
}, [execute, onEvent, pipeline, exit]);
|
|
91
|
+
useEffect(() => {
|
|
92
|
+
start(initialNodes);
|
|
93
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
94
|
+
}, []);
|
|
95
|
+
const current = rowsList[selected]?.node;
|
|
96
|
+
useInput((input, key) => {
|
|
97
|
+
if (input === 'q' || (key.ctrl && input === 'c')) {
|
|
98
|
+
if (running && controller.current) {
|
|
99
|
+
quitting.current = true;
|
|
100
|
+
setNotice('Cancelling running stages…');
|
|
101
|
+
controller.current.abort();
|
|
102
|
+
}
|
|
103
|
+
else
|
|
104
|
+
exit();
|
|
105
|
+
return;
|
|
106
|
+
}
|
|
107
|
+
if (view === 'detail') {
|
|
108
|
+
if (key.escape || key.leftArrow || key.return) {
|
|
109
|
+
setView('list');
|
|
110
|
+
setDetailOffset(0);
|
|
111
|
+
}
|
|
112
|
+
else if (key.upArrow)
|
|
113
|
+
setDetailOffset((o) => Math.max(0, o - 1));
|
|
114
|
+
else if (key.downArrow)
|
|
115
|
+
setDetailOffset((o) => o + 1);
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
if (key.upArrow) {
|
|
119
|
+
setFollow(false);
|
|
120
|
+
setSelected((i) => Math.max(0, i - 1));
|
|
121
|
+
}
|
|
122
|
+
else if (key.downArrow) {
|
|
123
|
+
setFollow(false);
|
|
124
|
+
setSelected((i) => Math.min(rowsList.length - 1, i + 1));
|
|
125
|
+
}
|
|
126
|
+
else if (key.return || key.rightArrow) {
|
|
127
|
+
setView('detail');
|
|
128
|
+
}
|
|
129
|
+
else if (input === 'r' && current) {
|
|
130
|
+
if (running)
|
|
131
|
+
setNotice('Wait for the pipeline to finish before rerunning.');
|
|
132
|
+
else
|
|
133
|
+
start([current]);
|
|
134
|
+
}
|
|
135
|
+
else if (input === 'R') {
|
|
136
|
+
if (!running)
|
|
137
|
+
start();
|
|
138
|
+
}
|
|
139
|
+
else if (input === 'o' && current) {
|
|
140
|
+
const target = current.kind === 'stage' ? current.file : current.dir;
|
|
141
|
+
const editor = process.env.CHECKPOST_EDITOR || 'code';
|
|
142
|
+
const child = spawn(editor, [target], { detached: true, stdio: 'ignore' });
|
|
143
|
+
child.on('error', () => setNotice(`Could not open editor "${editor}". Set CHECKPOST_EDITOR.`));
|
|
144
|
+
child.unref();
|
|
145
|
+
setNotice(`Opening ${path.relative(pipeline.root, target)} in ${editor}`);
|
|
146
|
+
}
|
|
147
|
+
});
|
|
148
|
+
if (view === 'detail' && current) {
|
|
149
|
+
return _jsx(Detail, { node: current, state: states[current.id], log: logs[current.id] ?? [], offset: detailOffset, rows: rows, pipeline: pipeline });
|
|
150
|
+
}
|
|
151
|
+
const logLines = current ? (logs[current.id] ?? []) : [];
|
|
152
|
+
const logHeight = Math.max(4, Math.min(12, rows - rowsList.length - 10));
|
|
153
|
+
void tick;
|
|
154
|
+
return (_jsxs(Box, { flexDirection: "column", children: [_jsxs(Text, { bold: true, children: [' ', "Checkpost ", _jsxs(Text, { color: "gray", children: ["\u00B7 ", header] })] }), _jsx(Text, { color: "gray", children: '─'.repeat(60) }), rowsList.map(({ node, depth }, i) => {
|
|
155
|
+
const st = states[node.id] ?? { status: 'pending' };
|
|
156
|
+
const isSel = i === selected;
|
|
157
|
+
const icon = st.status === 'running' ? SPINNER[Math.floor(Date.now() / 100) % SPINNER.length] : STATUS_ICON[st.status];
|
|
158
|
+
const elapsed = st.status === 'running' && st.startedAt
|
|
159
|
+
? formatDuration(Date.now() - st.startedAt)
|
|
160
|
+
: st.durationMs !== undefined && st.status !== 'pending' && st.status !== 'skipped'
|
|
161
|
+
? formatDuration(st.durationMs)
|
|
162
|
+
: '';
|
|
163
|
+
const findings = st.result?.findings ?? [];
|
|
164
|
+
const blocking = node.kind === 'stage' ? findings.filter((f) => isBlocking(f, node.config.fail_on)).length : 0;
|
|
165
|
+
const tag = node.kind === 'group' ? (node.config.parallel ? '(parallel)' : '') : node.type === 'command' ? '' : `[${typeLabel(node)}]`;
|
|
166
|
+
const prefix = depth > 0 ? ' '.repeat(depth - 1) + '├ ' : '';
|
|
167
|
+
return (_jsxs(Text, { inverse: isSel, children: [' ', prefix, _jsx(Text, { color: STATUS_COLOR[st.status], children: icon }), " ", node.name.padEnd(Math.max(1, 22 - prefix.length)), _jsx(Text, { color: "cyan", children: tag.padEnd(10) }), _jsx(Text, { color: "gray", children: elapsed.padStart(8) }), findings.length > 0 && (_jsxs(Text, { color: blocking ? 'red' : 'yellow', children: [' ', findings.length, " finding", findings.length === 1 ? '' : 's', blocking ? ` (${blocking} blocking)` : ''] })), st.result?.allowFailure && (st.status === 'failed' || st.status === 'error') && _jsx(Text, { color: "yellow", children: " allow_failure" }), st.status === 'skipped' && st.result?.summary && _jsxs(Text, { color: "gray", children: [" ", st.result.summary] })] }, node.id));
|
|
168
|
+
}), _jsx(Text, { color: "gray", children: '─'.repeat(60) }), current && (_jsxs(Box, { flexDirection: "column", height: logHeight + 1, children: [_jsxs(Text, { color: "gray", children: [current.name, " \u203A log"] }), logLines.slice(-logHeight).map((line, i) => (_jsxs(Text, { wrap: "truncate-end", color: line.startsWith('[AI]') ? 'cyan' : undefined, children: [' ', line] }, i)))] })), _jsx(Text, { color: "gray", children: '─'.repeat(60) }), gate && _jsx(GateBox, { gate: gate }), notice && _jsxs(Text, { color: "yellow", children: [" ", notice] }), _jsxs(Text, { color: "gray", children: [' ', "\u2191\u2193 select enter details r rerun stage R rerun all o open .md q quit"] })] }));
|
|
169
|
+
}
|
|
170
|
+
function GateBox({ gate }) {
|
|
171
|
+
const sha = gate.git.sha ? `${gate.git.branch}@${gate.git.sha.slice(0, 7)}` : '';
|
|
172
|
+
if (gate.green) {
|
|
173
|
+
return (_jsxs(Box, { borderStyle: "round", borderColor: "green", paddingX: 1, flexDirection: "column", children: [_jsx(Text, { color: "green", bold: true, children: "\u2714 GATE GREEN \u00B7 ok to deploy" }), _jsx(Text, { color: "gray", children: sha })] }));
|
|
174
|
+
}
|
|
175
|
+
return (_jsxs(Box, { borderStyle: "round", borderColor: "red", paddingX: 1, flexDirection: "column", children: [_jsx(Text, { color: "red", bold: true, children: "\u2716 GATE RED \u00B7 not ready to deploy" }), gate.reasons.slice(0, 6).map((r, i) => (_jsxs(Text, { color: "gray", children: ["\u2022 ", r] }, i)))] }));
|
|
176
|
+
}
|
|
177
|
+
function Detail({ node, state, log, offset, rows, pipeline, }) {
|
|
178
|
+
const result = state?.result;
|
|
179
|
+
const lines = [];
|
|
180
|
+
if (node.kind === 'group') {
|
|
181
|
+
lines.push(_jsxs(Text, { children: ["Group with ", node.children.length, " items. Select a stage inside it to see details."] }, "g"));
|
|
182
|
+
}
|
|
183
|
+
else {
|
|
184
|
+
if (result?.summary)
|
|
185
|
+
lines.push(_jsx(Text, { children: result.summary }, "s"));
|
|
186
|
+
if (result?.error)
|
|
187
|
+
lines.push(_jsxs(Text, { color: "red", children: ["Error: ", result.error] }, "e"));
|
|
188
|
+
if (result?.findings.length) {
|
|
189
|
+
result.findings.forEach((f, i) => {
|
|
190
|
+
const blocking = isBlocking(f, node.config.fail_on);
|
|
191
|
+
lines.push(_jsxs(Box, { flexDirection: "column", marginTop: 1, children: [_jsxs(Text, { children: [_jsx(Text, { color: SEVERITY_COLOR[f.severity], bold: true, children: f.severity.toUpperCase().padEnd(9) }), _jsx(Text, { underline: true, children: findingLocation(f) }), blocking && _jsx(Text, { color: "red", children: " (blocking)" })] }), _jsxs(Text, { children: [' ', f.message] }), f.suggestion && _jsxs(Text, { color: "gray", children: [' ', "\u2192 ", f.suggestion] })] }, `f${i}`));
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
else if (node.type === 'command' || !result) {
|
|
195
|
+
lines.push(_jsx(Text, { color: "gray", children: "Log:" }, "lt"));
|
|
196
|
+
log.forEach((line, i) => lines.push(_jsxs(Text, { children: [" ", line] }, `l${i}`)));
|
|
197
|
+
}
|
|
198
|
+
if (result?.logFile)
|
|
199
|
+
lines.push(_jsxs(Text, { color: "gray", children: ["Full log: ", path.relative(pipeline.root, result.logFile)] }, "lf"));
|
|
200
|
+
}
|
|
201
|
+
const visible = Math.max(5, rows - 6);
|
|
202
|
+
const start = Math.min(offset, Math.max(0, lines.length - visible));
|
|
203
|
+
const header = node.kind === 'stage'
|
|
204
|
+
? `${node.name} · ${typeLabel(node)}${node.kind === 'stage' && node.type !== 'command' ? ` · fail_on: ${node.config.fail_on}` : ''}`
|
|
205
|
+
: node.name;
|
|
206
|
+
return (_jsxs(Box, { flexDirection: "column", children: [_jsxs(Text, { bold: true, children: [' ', _jsx(Text, { color: STATUS_COLOR[state?.status ?? 'pending'], children: STATUS_ICON[state?.status ?? 'pending'] }), " ", header, result?.costUsd ? _jsxs(Text, { color: "gray", children: [" \u00B7 $", result.costUsd.toFixed(3)] }) : null] }), _jsx(Text, { color: "gray", children: '─'.repeat(60) }), lines.slice(start, start + visible), _jsx(Text, { color: "gray", children: '─'.repeat(60) }), _jsx(Text, { color: "gray", children: " \u2191\u2193 scroll esc back q quit" })] }));
|
|
207
|
+
}
|