check-post 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 (55) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +141 -2
  3. package/dist/cli.js +51 -0
  4. package/dist/commands/init.js +218 -0
  5. package/dist/commands/list.js +50 -0
  6. package/dist/commands/run.js +149 -0
  7. package/dist/commands/shared.js +12 -0
  8. package/dist/commands/status.js +31 -0
  9. package/dist/core/adapters/claude-code.js +145 -0
  10. package/dist/core/adapters/index.js +14 -0
  11. package/dist/core/adapters/types.js +1 -0
  12. package/dist/core/discovery.js +183 -0
  13. package/dist/core/events.js +1 -0
  14. package/dist/core/gate.js +111 -0
  15. package/dist/core/process.js +20 -0
  16. package/dist/core/project.js +67 -0
  17. package/dist/core/runners/ai.js +91 -0
  18. package/dist/core/runners/command.js +48 -0
  19. package/dist/core/scheduler.js +157 -0
  20. package/dist/core/stage-file.js +61 -0
  21. package/dist/core/types.js +62 -0
  22. package/dist/ui/format.js +46 -0
  23. package/dist/ui/plain.js +47 -0
  24. package/dist/ui/tui/App.js +207 -0
  25. package/package.json +67 -4
  26. package/presets/angular/01-lint.md +4 -0
  27. package/presets/angular/02-unit-test.md +4 -0
  28. package/presets/angular/03-build.md +4 -0
  29. package/presets/angular/04-security/01-secrets.md +19 -0
  30. package/presets/angular/04-security/02-xss-audit.md +17 -0
  31. package/presets/angular/04-security/03-env-audit.md +11 -0
  32. package/presets/angular/04-security/04-dependency.md +5 -0
  33. package/presets/angular/04-security/_group.md +4 -0
  34. package/presets/angular/05-code-standard.md +15 -0
  35. package/presets/angular/context.md +2 -0
  36. package/presets/nextjs/01-lint.md +4 -0
  37. package/presets/nextjs/02-unit-test.md +4 -0
  38. package/presets/nextjs/03-build.md +4 -0
  39. package/presets/nextjs/04-security/01-secrets.md +19 -0
  40. package/presets/nextjs/04-security/02-xss-audit.md +16 -0
  41. package/presets/nextjs/04-security/03-env-audit.md +11 -0
  42. package/presets/nextjs/04-security/04-dependency.md +5 -0
  43. package/presets/nextjs/04-security/_group.md +4 -0
  44. package/presets/nextjs/05-code-standard.md +15 -0
  45. package/presets/nextjs/context.md +1 -0
  46. package/presets/node/01-lint.md +4 -0
  47. package/presets/node/02-unit-test.md +4 -0
  48. package/presets/node/03-build.md +4 -0
  49. package/presets/node/04-security/01-secrets.md +19 -0
  50. package/presets/node/04-security/02-injection-audit.md +15 -0
  51. package/presets/node/04-security/03-env-audit.md +11 -0
  52. package/presets/node/04-security/04-dependency.md +5 -0
  53. package/presets/node/04-security/_group.md +4 -0
  54. package/presets/node/05-code-standard.md +15 -0
  55. 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: proses jadi pemimpin process group, sehingga timeout/batal bisa menghentikan
6
+ // seluruh turunannya (mis. `ng test` yang memanggil browser), bukan hanya shell-nya.
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 ditutup paksa saat proses dihentikan */
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,157 @@
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
+ // Sama dengan STATE_DIR di gate.ts (tidak diimpor untuk menghindari import melingkar).
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
+ /** Stage/grup dianggap menghalangi pipeline bila gagal dan tidak 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: 'dibatalkan', 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] meninjau hasil perintah (exit code ${res.exitCode})…`);
82
+ }
83
+ if (!opts.adapter)
84
+ throw new Error('Stage AI butuh agent, tetapi agent tidak tersedia');
85
+ const outcome = await runAiStage(opts.adapter, stage, {
86
+ cwd: pipeline.root,
87
+ model: pipeline.config.model,
88
+ sensitivePaths: pipeline.config.sensitive_paths,
89
+ maxBudgetUsd: pipeline.config.max_budget_usd,
90
+ timeoutMs: parseDuration(stage.config.timeout, DEFAULT_AI_TIMEOUT_MS),
91
+ signal: opts.signal,
92
+ onLog: emit,
93
+ command,
94
+ });
95
+ for (const denied of outcome.deniedReads)
96
+ emit(`[AI] akses diblokir: ${denied}`);
97
+ const blocking = outcome.verdict.findings.filter((f) => isBlocking(f, stage.config.fail_on));
98
+ emit(`[AI] ${outcome.verdict.summary}`);
99
+ return finish({
100
+ status: blocking.length ? 'failed' : 'passed',
101
+ exitCode: command?.exitCode,
102
+ summary: outcome.verdict.summary,
103
+ findings: outcome.verdict.findings,
104
+ costUsd: outcome.costUsd,
105
+ });
106
+ }
107
+ catch (err) {
108
+ if (opts.signal?.aborted)
109
+ return finish({ status: 'skipped', summary: 'dibatalkan' });
110
+ const message = err.message;
111
+ emit(`ERROR: ${message}`);
112
+ return finish({ status: 'error', error: message });
113
+ }
114
+ };
115
+ /** Mengembalikan true bila node berakhir dengan kegagalan yang menghalangi. */
116
+ const runNode = async (node, failFast) => {
117
+ if (node.kind === 'stage')
118
+ return isBlockingFailure(await runStage(node));
119
+ return runGroup(node, node.config.fail_fast ?? failFast);
120
+ };
121
+ const runGroup = async (group, failFast) => {
122
+ const t0 = Date.now();
123
+ opts.onEvent({ type: 'group:start', id: group.id });
124
+ const failed = group.config.parallel
125
+ ? (await Promise.all(group.children.map((c) => runNode(c, failFast)))).some(Boolean)
126
+ : await runSequence(group.children, failFast);
127
+ const status = failed
128
+ ? 'failed'
129
+ : stagesIn(group).every((s) => results[s.id]?.status === 'skipped')
130
+ ? 'skipped'
131
+ : 'passed';
132
+ opts.onEvent({ type: 'group:finish', id: group.id, status, durationMs: Date.now() - t0 });
133
+ return failed;
134
+ };
135
+ const runSequence = async (nodes, failFast) => {
136
+ let failed = false;
137
+ for (let i = 0; i < nodes.length; i++) {
138
+ if (opts.signal?.aborted) {
139
+ skip(nodes.slice(i), 'dibatalkan');
140
+ break;
141
+ }
142
+ if (await runNode(nodes[i], failFast)) {
143
+ failed = true;
144
+ if (failFast) {
145
+ skip(nodes.slice(i + 1), 'dilewati: stage sebelumnya gagal');
146
+ break;
147
+ }
148
+ }
149
+ }
150
+ return failed;
151
+ };
152
+ const failed = await runSequence(opts.nodes ?? pipeline.children, pipeline.config.fail_fast);
153
+ const durationMs = Date.now() - started;
154
+ const passed = !failed && !opts.signal?.aborted;
155
+ opts.onEvent({ type: 'pipeline:finish', results, passed, durationMs });
156
+ return { results, passed, durationMs };
157
+ }
@@ -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 frontmatter YAML + body Markdown, lalu validasi frontmatter dengan schema. */
11
+ export function parseMarkdown(source, schema, fileLabel) {
12
+ let parsed;
13
+ try {
14
+ // Tanpa cache: gray-matter meng-cache berdasarkan isi string, yang mengacaukan test.
15
+ parsed = matter(source, {});
16
+ }
17
+ catch (err) {
18
+ throw new DefinitionError([`${fileLabel}: frontmatter YAML tidak valid (${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
+ /** Ubah `30s`, `5m`, `1h`, `500ms`, atau angka (detik) menjadi milidetik. */
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,62 @@
1
+ import { z } from 'zod';
2
+ export const SEVERITIES = ['critical', 'high', 'medium', 'low', 'info'];
3
+ /** Peringkat severity: angka lebih kecil = lebih parah. */
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 membaca `run: true` atau `run: 123` sebagai boolean/angka; perlakukan sebagai perintah.
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
+ fail_fast: z.boolean().default(true),
46
+ require_clean_tree: z.boolean().default(true),
47
+ sensitive_paths: z.array(z.string()).default([]),
48
+ max_budget_usd: z.number().positive().default(1),
49
+ confirm_ai: z.boolean().default(true),
50
+ })
51
+ .strict();
52
+ export const FindingSchema = z.object({
53
+ severity: z.enum(SEVERITIES),
54
+ file: z.string().nullable(),
55
+ line: z.number().int().nullable(),
56
+ message: z.string(),
57
+ suggestion: z.string().nullable(),
58
+ });
59
+ export const AiVerdictSchema = z.object({
60
+ summary: z.string(),
61
+ findings: z.array(FindingSchema),
62
+ });
@@ -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 ? 'grup paralel' : 'grup';
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
+ }
@@ -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 untuk CI / non-TTY: satu baris per kejadian, log stage diberi prefix. */
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 ?? 'dilewati'})`));
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('Membatalkan stage yang sedang berjalan…');
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('Tunggu pipeline selesai sebelum rerun.');
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(`Tidak bisa membuka editor "${editor}". Set CHECKPOST_EDITOR.`));
144
+ child.unref();
145
+ setNotice(`Membuka ${path.relative(pipeline.root, target)} di ${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 ? '(paralel)' : '') : 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, " temuan", blocking ? ` (${blocking} blokir)` : ''] })), 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 pilih enter detail r rerun stage R rerun semua o buka .md q keluar"] })] }));
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 boleh 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 belum boleh 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: ["Grup berisi ", node.children.length, " item. Pilih stage di dalamnya untuk melihat detail."] }, "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: " (blokir)" })] }), _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: ["Log lengkap: ", 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 gulir esc kembali q keluar" })] }));
207
+ }