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,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 ? ` · dijalankan ${formatDuration(Date.now() - Date.parse(gate.lastRun.updatedAt))} lalu` : '';
23
+ if (gate.green) {
24
+ console.log(pc.green(pc.bold(`✔ GREEN · boleh deploy`)) + pc.gray(` · ${ref}${ago}`));
25
+ return 0;
26
+ }
27
+ console.log(pc.red(pc.bold('✖ RED · belum boleh 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
+ /** Ubah glob sensitive_paths menjadi aturan permission deny Claude Code. */
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 `membaca ${rel(input.file_path)}`;
20
+ case 'Grep':
21
+ return `mencari "${String(input.pattern ?? '')}"${input.path ? ` di ${rel(input.path)}` : ''}`;
22
+ case 'Glob':
23
+ return `mencari file ${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
+ // Konteks seminimal mungkin: tanpa MCP, plugin, dan setting user. Ini menekan biaya
55
+ // per stage dari dolar ke sen.
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 ditutup paksa saat proses dihentikan */
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
+ ? 'dibatalkan'
125
+ : timedOut
126
+ ? `timeout setelah ${Math.round(o.timeoutMs / 1000)}s`
127
+ : stderr.trim() || `claude keluar dengan kode ${done.exitCode}`;
128
+ throw new Error(`Claude Code gagal: ${reason}`);
129
+ }
130
+ if (final.is_error) {
131
+ throw new Error(`Claude Code error: ${String(final.result ?? final.subtype ?? 'tidak diketahui')}`);
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(`Agent "${id}" tidak dikenal. Pilihan: ${Object.keys(AGENTS).join(', ')}`);
11
+ if (!agent.create)
12
+ throw new Error(`Agent "${agent.label}" belum didukung. Gunakan claude-code untuk saat ini.`);
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; // termasuk _group.md, dibaca terpisah
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}/ tidak ditemukan di ${root}. Jalankan "checkpost init" dulu.`]);
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} dipakai dua kali (${other} dan ${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)}/: grup kosong (tidak ada stage .md yang aktif)`);
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)}: stage kosong. Isi "run:" di frontmatter, instruksi AI di body, atau keduanya.`);
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}/: belum ada stage. Tambahkan file seperti 01-build.md.`);
152
+ }
153
+ if (problems.length)
154
+ throw new DefinitionError(problems);
155
+ return { root, dir, config: pipelineConfig, children };
156
+ }
157
+ /** Semua stage dalam urutan tampil, beserta kedalamannya. */
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
+ /** Cari node berdasarkan id persis, id tanpa prefix, atau nama. */
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
+ /** Path milik checkpost sendiri tidak dihitung sebagai perubahan project. */
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 juga bekerja di repo yang belum punya commit (rev-parse HEAD gagal di sana).
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 dari seluruh definisi stage, supaya edit file .md membatalkan hasil lama. */
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
+ * Simpan hasil run. Run parsial (satu stage/grup) digabung dengan hasil sebelumnya
62
+ * selama commit dan definisi stage masih sama.
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 belum pernah dijalankan');
87
+ return { green: false, reasons, lastRun, git };
88
+ }
89
+ if (git.isRepo && lastRun.sha !== git.sha) {
90
+ reasons.push(`hasil terakhir untuk commit ${lastRun.sha?.slice(0, 7) ?? '?'}, HEAD sekarang ${git.sha?.slice(0, 7) ?? '?'}`);
91
+ }
92
+ if (lastRun.definitionsHash !== definitionsHash(pipeline)) {
93
+ reasons.push('definisi stage berubah sejak run terakhir');
94
+ }
95
+ if (pipeline.config.require_clean_tree && git.isRepo) {
96
+ if (git.dirtyFiles.length)
97
+ reasons.push(`working tree kotor (${git.dirtyFiles.length} file belum di-commit)`);
98
+ else if (lastRun.dirtyAtRun.length)
99
+ reasons.push('run terakhir dilakukan saat working tree kotor');
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} belum dijalankan`);
105
+ else if (isBlockingFailure(r))
106
+ reasons.push(`stage ${stage.id} ${r.status === 'error' ? 'error' : 'gagal'}`);
107
+ else if (r.status === 'skipped' || r.status === 'pending' || r.status === 'running')
108
+ reasons.push(`stage ${stage.id} tidak selesai (${r.status})`);
109
+ }
110
+ return { green: reasons.length === 0, reasons, lastRun, git };
111
+ }
@@ -0,0 +1,20 @@
1
+ /** Hentikan seluruh process group (SIGTERM, lalu SIGKILL bila masih hidup). */
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
+ /* sudah mati */
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
+ /* package.json rusak: perlakukan sebagai project tanpa script */
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: 'tidak dikenali', scripts, docs };
29
+ }
30
+ /** Script npm yang dibutuhkan sebuah perintah `run`, atau null bila bukan perintah npm. */
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
+ * Tambahkan pola ke `.git/info/exclude` (hanya lokal) atau `.gitignore` (dibagikan),
45
+ * hanya bila belum diabaikan git.
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 yang dikirim ke AI; harus sejalan dengan AiVerdictSchema.
5
+ * Field `$schema` dibuang karena Claude Code menolak referensi draft 2020-12.
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) {
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 the same language as the stage 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
+ ? '[... output awal dipotong ...]\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
+ /** Jalankan stage AI; minta ulang sekali bila jawaban tidak sesuai schema. */
52
+ export async function runAiStage(adapter, stage, opts) {
53
+ const systemPrompt = buildSystemPrompt(opts.sensitivePaths);
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] jawaban tidak sesuai format (percobaan ${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 tidak mengembalikan jawaban dengan format yang valid setelah 2 percobaan');
91
+ }