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
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Raisul khairi
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,142 @@
1
- # Temporary Holding Version
1
+ # checkpost
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Pipeline mirip CI/CD yang berjalan di komputer sendiri. Stage didefinisikan sebagai file Markdown, dan stage yang butuh penilaian dijalankan oleh AI CLI (saat ini Claude Code). Kalau semua stage green, gate menyatakan project boleh deploy.
4
+
5
+ ```
6
+ Checkpost · claude-code · main@a1b2c3d
7
+ ──────────────────────────────────────────
8
+ ✔ lint 4.1s
9
+ ✔ unit-test 12.4s
10
+ ✔ build 31.0s
11
+ ⠹ security (paralel)
12
+ ├ ✔ secrets [AI] 9.8s
13
+ ├ ✖ xss-audit [AI] 22.3s 2 temuan (1 blokir)
14
+ ├ ⠹ env-audit [AI] 18.0s
15
+ ○ code-standard [AI]
16
+ ```
17
+
18
+ ## Syarat
19
+ - Node.js 22+
20
+ - [Claude Code](https://docs.claude.com/claude-code) terinstall dan sudah login (`claude`)
21
+
22
+ ## Install
23
+ Langsung pakai tanpa install:
24
+ ```bash
25
+ npx check-post init
26
+ npx check-post run
27
+ ```
28
+ Atau install permanen:
29
+ ```bash
30
+ npm install -g check-post
31
+ ```
32
+ Perintahnya bisa ditulis `check-post` atau `checkpost`.
33
+
34
+ Versi terbaru langsung dari GitHub:
35
+ ```bash
36
+ npx github:raisulkhairi/check-post init
37
+ ```
38
+ Hindari `npm install -g github:…`. npm gagal membangun paket dari git dalam mode global (`tsc: not found`). Untuk install permanen versi GitHub:
39
+ ```bash
40
+ git clone https://github.com/raisulkhairi/check-post.git
41
+ cd check-post && npm install && npm link
42
+ ```
43
+
44
+ ## Mulai
45
+ Jalankan di root project yang ingin diperiksa:
46
+ ```bash
47
+ checkpost init # wizard: deteksi project, pilih preset & stage
48
+ checkpost list # cek urutan stage
49
+ checkpost run # jalankan dengan tampilan terminal
50
+ checkpost status # GREEN/RED, exit code 0/1
51
+ ```
52
+ Tidak perlu membuka `claude` lebih dulu. Checkpost memanggil Claude Code sendiri untuk stage AI.
53
+
54
+ ## Stage = file Markdown
55
+ ```
56
+ checkpost/
57
+ pipeline.md # config global + konteks project untuk semua stage AI
58
+ 01-lint.md
59
+ 02-unit-test.md
60
+ 03-build.md
61
+ 04-security/ # subfolder = grup
62
+ _group.md # parallel: true
63
+ 01-secrets.md
64
+ 02-xss-audit.md
65
+ 05-code-standard.md
66
+ _draft.md # awalan _ atau . = diabaikan
67
+ ```
68
+
69
+ **Urutan** mengikuti prefix angka (`2-` sebelum `10-`). Item tanpa prefix ditaruh terakhir, urut abjad. Prefix tidak ikut ditampilkan.
70
+
71
+ **Jenis stage ditentukan dari isi file:**
72
+
73
+ | Isi | Perilaku | Lulus jika |
74
+ |---|---|---|
75
+ | `run:` saja | jalankan perintah | exit code 0 |
76
+ | body saja | body menjadi instruksi AI | tidak ada temuan ≥ `fail_on` |
77
+ | `run:` + body | jalankan perintah, lalu AI meninjau output-nya | tidak ada temuan ≥ `fail_on` |
78
+
79
+ ```md
80
+ ---
81
+ paths: ["src/**/*.ts", "src/**/*.html"]
82
+ fail_on: high
83
+ ---
84
+ # XSS audit
85
+ Cari pemakaian bypassSecurityTrustHtml dan [innerHTML] berisi data dari user...
86
+ ```
87
+
88
+ ### Frontmatter
89
+
90
+ | Field | Di mana | Default | Keterangan |
91
+ |---|---|---|---|
92
+ | `run` | stage | – | perintah shell |
93
+ | `timeout` | stage | 15m (command), 10m (AI) | `30s`, `5m`, `1h`, atau angka detik |
94
+ | `fail_on` | stage | `high` | `critical`, `high`, `medium`, `low`, `info` |
95
+ | `paths` | stage | – | batasi file yang diperiksa AI |
96
+ | `allow_failure` | stage | `false` | gagal tidak menghalangi gate |
97
+ | `enabled` | stage, grup | `true` | |
98
+ | `name` | stage, grup | nama file | nama tampilan |
99
+ | `model`, `max_budget_usd` | stage, pipeline | `sonnet`, `1` | |
100
+ | `parallel` | grup | `false` | jalankan isi grup bersamaan |
101
+ | `fail_fast` | grup, pipeline | `true` | berhenti di kegagalan pertama |
102
+ | `require_clean_tree` | pipeline | `true` | gate RED bila ada perubahan belum di-commit |
103
+ | `sensitive_paths` | pipeline | `.env*`, `.npmrc`, `*.pem`, `*.key` | path yang tidak boleh dibaca AI |
104
+ | `confirm_ai` | pipeline | `true` | konfirmasi sekali sebelum memakai kuota AI |
105
+
106
+ Body `pipeline.md` dan `_group.md` ikut menjadi konteks untuk setiap stage AI di bawahnya.
107
+
108
+ ## Keamanan stage AI
109
+ - AI hanya diberi tool baca (Read, Grep, Glob) dan tidak bisa mengubah file atau menjalankan perintah.
110
+ - `sensitive_paths` diblokir lewat aturan permission deny Claude Code. Percobaan membaca path itu tercatat di log sebagai `akses diblokir`.
111
+ - Claude Code dijalankan tanpa MCP server, plugin, dan setting user, supaya konteks kecil dan biayanya sekitar sen per stage, bukan dolar.
112
+ - Jawaban AI wajib berbentuk JSON terstruktur yang divalidasi. Kalau tidak valid, diminta ulang sekali. Kalau tetap tidak valid, stage berstatus `error`, bukan lulus.
113
+
114
+ ## Gate
115
+ `checkpost status` hanya GREEN kalau:
116
+ - semua stage lulus (atau `allow_failure`),
117
+ - hasil run untuk commit yang sama dengan `HEAD`,
118
+ - definisi stage tidak berubah sejak run,
119
+ - working tree bersih (bisa dimatikan dengan `require_clean_tree: false`).
120
+
121
+ ```bash
122
+ checkpost status && vercel --prod
123
+ ```
124
+
125
+ ## Mode CI / skrip
126
+ ```bash
127
+ checkpost run --ci # output polos + exit code
128
+ checkpost run --ci --json # hasil akhir JSON di stdout, log di stderr
129
+ checkpost run security # satu grup/stage saja (id atau nama)
130
+ ```
131
+ `init` juga bisa memasang slash command `/checkpost` untuk Claude Code.
132
+
133
+ ## Repo yang bukan milik sendiri
134
+ `checkpost init --share local` menulis `checkpost/`, `.checkpost/`, dan slash command ke `.git/info/exclude`. Repo tidak berubah sama sekali.
135
+
136
+ ## Pengembangan
137
+ ```bash
138
+ npm install
139
+ npm test # vitest
140
+ npm run build # tsc → dist/
141
+ npm link # perintah checkpost tersedia global dari folder ini
142
+ ```
package/dist/cli.js ADDED
@@ -0,0 +1,51 @@
1
+ #!/usr/bin/env node
2
+ import { Command, Option } from 'commander';
3
+ import { initCommand } from './commands/init.js';
4
+ import { listCommand } from './commands/list.js';
5
+ import { runCommand } from './commands/run.js';
6
+ import { statusCommand } from './commands/status.js';
7
+ const program = new Command();
8
+ program
9
+ .name('checkpost')
10
+ .description('Pipeline CI/CD lokal: stage dari file Markdown, dijalankan oleh AI CLI')
11
+ .version('0.1.0')
12
+ .option('-C, --cwd <dir>', 'root project', process.cwd());
13
+ const cwd = () => program.opts().cwd;
14
+ const finish = (code) => {
15
+ process.exitCode = code;
16
+ };
17
+ program
18
+ .command('init')
19
+ .description('buat folder checkpost/ dari preset')
20
+ .addOption(new Option('--preset <name>', 'preset stage').choices(['angular', 'nextjs', 'node', 'empty']))
21
+ .addOption(new Option('--share <mode>', 'simpan lokal saja atau bagikan ke tim').choices(['local', 'team']))
22
+ .option('--no-slash-command', 'jangan pasang slash command /checkpost')
23
+ .option('-y, --yes', 'pakai default tanpa bertanya')
24
+ .option('--force', 'timpa folder checkpost/ yang sudah ada')
25
+ .action(async (o) => {
26
+ const slashCommand = process.argv.includes('--no-slash-command') ? false : o.yes ? true : undefined;
27
+ finish(await initCommand({ cwd: cwd(), preset: o.preset, share: o.share, slashCommand, yes: o.yes, force: o.force }));
28
+ });
29
+ program
30
+ .command('list')
31
+ .description('tampilkan urutan stage tanpa menjalankannya')
32
+ .option('--json', 'output JSON')
33
+ .action((o) => finish(listCommand({ cwd: cwd(), json: o.json })));
34
+ program
35
+ .command('run')
36
+ .argument('[stage]', 'jalankan satu stage atau grup saja (id atau nama)')
37
+ .description('jalankan pipeline')
38
+ .option('--ci', 'mode non-interaktif (otomatis bila bukan terminal)')
39
+ .option('--json', 'cetak hasil akhir sebagai JSON di stdout')
40
+ .option('-y, --yes', 'lewati konfirmasi pemakaian AI')
41
+ .option('-v, --verbose', 'tampilkan seluruh log perintah di mode CI')
42
+ .action(async (stage, o) => finish(await runCommand(stage, { cwd: cwd(), ci: o.ci, json: o.json, yes: o.yes, verbose: o.verbose })));
43
+ program
44
+ .command('status')
45
+ .description('cek gate: GREEN (boleh deploy) atau RED; exit code 0/1')
46
+ .option('--json', 'output JSON')
47
+ .action(async (o) => finish(await statusCommand({ cwd: cwd(), json: o.json })));
48
+ program.parseAsync().catch((err) => {
49
+ console.error(err instanceof Error ? err.message : err);
50
+ process.exitCode = 1;
51
+ });
@@ -0,0 +1,218 @@
1
+ import { cpSync, existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
2
+ import path from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { checkbox, confirm, select } from '@inquirer/prompts';
5
+ import pc from 'picocolors';
6
+ import { AGENTS } from '../core/adapters/index.js';
7
+ import { GROUP_FILE, PIPELINE_DIR, splitPrefix } from '../core/discovery.js';
8
+ import { STATE_DIR, readGitState } from '../core/gate.js';
9
+ import { detectProject, ignorePaths, npmScriptOf } from '../core/project.js';
10
+ import { parseMarkdown } from '../core/stage-file.js';
11
+ import { StageConfigSchema } from '../core/types.js';
12
+ const PRESETS_DIR = fileURLToPath(new URL('../../presets/', import.meta.url));
13
+ const PRESETS = [
14
+ { id: 'angular', label: 'Angular' },
15
+ { id: 'nextjs', label: 'Next.js' },
16
+ { id: 'node', label: 'Node.js / API' },
17
+ { id: 'empty', label: 'Kosong (satu contoh stage)' },
18
+ ];
19
+ const EXTRA_SENSITIVE = {
20
+ angular: ['src/environments/**'],
21
+ };
22
+ const SLASH_COMMAND_PATH = '.claude/commands/checkpost.md';
23
+ function presetStages(presetDir, scripts) {
24
+ const out = [];
25
+ const walk = (dir, depth) => {
26
+ for (const name of readdirSync(dir).sort()) {
27
+ const full = path.join(dir, name);
28
+ const rel = path.relative(presetDir, full);
29
+ if (statSync(full).isDirectory()) {
30
+ walk(full, depth + 1);
31
+ continue;
32
+ }
33
+ if (name === GROUP_FILE || name === 'context.md' || !name.endsWith('.md'))
34
+ continue;
35
+ const { data, body } = parseMarkdown(readFileSync(full, 'utf8'), StageConfigSchema, rel);
36
+ const script = data.run ? npmScriptOf(data.run) : null;
37
+ const missingScript = script && script !== 'test' ? (scripts[script] ? null : script) : script === 'test' && !scripts.test ? 'test' : null;
38
+ const groupName = depth > 0 ? splitPrefix(path.basename(path.dirname(full))).name + '/' : '';
39
+ const kind = data.run ? (body ? `${data.run} + AI` : data.run) : 'AI';
40
+ out.push({
41
+ rel,
42
+ label: `${groupName}${splitPrefix(name).name} ${pc.gray(kind)}${missingScript ? pc.yellow(` (script "${missingScript}" tidak ada)`) : ''}`,
43
+ missingScript,
44
+ });
45
+ }
46
+ };
47
+ walk(presetDir, 0);
48
+ return out;
49
+ }
50
+ function pipelineMd(opts) {
51
+ const sensitive = EXTRA_SENSITIVE[opts.kind] ?? [];
52
+ const front = [
53
+ '---',
54
+ 'agent: claude-code',
55
+ 'model: sonnet # model untuk stage AI (sonnet | opus | haiku)',
56
+ 'fail_fast: true # berhenti di stage pertama yang gagal',
57
+ 'require_clean_tree: true # gate hanya green bila tidak ada perubahan belum di-commit',
58
+ 'max_budget_usd: 1 # batas biaya per stage AI',
59
+ ];
60
+ if (sensitive.length) {
61
+ front.push('sensitive_paths: # tidak boleh dibaca AI (selain .env*, .npmrc, *.pem, *.key)');
62
+ for (const s of sensitive)
63
+ front.push(` - ${s}`);
64
+ }
65
+ front.push('---', '');
66
+ const body = [`Project: ${opts.label}.`, opts.context.trim()];
67
+ if (opts.docs.length)
68
+ body.push(`Konvensi project tertulis di: ${opts.docs.join(', ')}. Baca file tersebut bila relevan.`);
69
+ return front.join('\n') + body.join('\n\n') + '\n';
70
+ }
71
+ const SLASH_COMMAND = `---
72
+ description: Jalankan Checkpost (stage di folder checkpost/) dan ringkas hasilnya
73
+ allowed-tools: Bash(checkpost:*), Bash(npx checkpost:*)
74
+ ---
75
+ Jalankan perintah berikut di root project (bisa beberapa menit):
76
+
77
+ \`\`\`
78
+ checkpost run --ci --json --yes $ARGUMENTS
79
+ \`\`\`
80
+
81
+ Output JSON ada di stdout. Lalu ringkas dalam bahasa Indonesia:
82
+ 1. Status gate (GREEN = boleh deploy, RED = belum) dan alasannya.
83
+ 2. Stage yang gagal beserta temuan utamanya (severity, file:baris, pesan).
84
+ 3. Saran langkah berikutnya. Jangan mengubah kode kecuali diminta.
85
+ `;
86
+ export async function initCommand(flags) {
87
+ const root = path.resolve(flags.cwd);
88
+ const interactive = Boolean(process.stdin.isTTY && !flags.yes);
89
+ const targetDir = path.join(root, PIPELINE_DIR);
90
+ console.log(pc.bold('\n◆ Checkpost · setup\n'));
91
+ if (existsSync(targetDir) && !flags.force) {
92
+ console.error(pc.red(` ${PIPELINE_DIR}/ sudah ada. Pakai --force untuk menimpa file preset.`));
93
+ return 2;
94
+ }
95
+ const git = await readGitState(root);
96
+ console.log(git.isRepo ? pc.green(` ✔ Git repository (branch: ${git.branch})`) : pc.yellow(' ⚠ Bukan git repository: gate tidak bisa mengecek commit'));
97
+ const project = detectProject(root);
98
+ console.log(project.kind === 'unknown' ? pc.yellow(' ⚠ Jenis project tidak dikenali') : pc.green(` ✔ Project: ${project.label}`));
99
+ const claude = AGENTS['claude-code'].create();
100
+ const detected = await claude.detect();
101
+ if (!detected.installed) {
102
+ console.error(pc.red(' ✖ Claude Code tidak ditemukan. Install: npm install -g @anthropic-ai/claude-code, lalu jalankan "claude" sekali untuk login.'));
103
+ return 2;
104
+ }
105
+ console.log(pc.green(` ✔ AI CLI: Claude Code ${detected.version ?? ''}`));
106
+ if (project.docs.length)
107
+ console.log(pc.green(` ✔ Dokumen konvensi: ${project.docs.join(', ')}`));
108
+ console.log('');
109
+ if (interactive) {
110
+ await select({
111
+ message: 'Pilih AI agent',
112
+ choices: Object.entries(AGENTS).map(([id, a]) => ({
113
+ value: id,
114
+ name: a.available ? a.label : `${a.label} ${pc.gray('(segera)')}`,
115
+ disabled: !a.available,
116
+ })),
117
+ });
118
+ }
119
+ const detectedPreset = PRESETS.find((p) => p.id === project.kind)?.id ?? 'empty';
120
+ let preset = (flags.preset ?? detectedPreset);
121
+ if (!PRESETS.some((p) => p.id === preset)) {
122
+ console.error(pc.red(` Preset "${preset}" tidak dikenal. Pilihan: ${PRESETS.map((p) => p.id).join(', ')}`));
123
+ return 2;
124
+ }
125
+ if (interactive && !flags.preset) {
126
+ preset = await select({
127
+ message: 'Pilih preset stage',
128
+ default: detectedPreset,
129
+ choices: PRESETS.map((p) => ({
130
+ value: p.id,
131
+ name: p.id === detectedPreset && p.id !== 'empty' ? `${p.label} ${pc.green('(Recommended, terdeteksi)')}` : p.label,
132
+ })),
133
+ });
134
+ }
135
+ let chosen = [];
136
+ let context = '';
137
+ const presetDir = path.join(PRESETS_DIR, preset);
138
+ if (preset !== 'empty') {
139
+ context = readFileSync(path.join(presetDir, 'context.md'), 'utf8');
140
+ const stages = presetStages(presetDir, project.scripts);
141
+ chosen = stages.filter((s) => !s.missingScript).map((s) => s.rel);
142
+ if (interactive) {
143
+ chosen = await checkbox({
144
+ message: 'Stage mana yang diaktifkan? (spasi = pilih, enter = lanjut)',
145
+ choices: stages.map((s) => ({ value: s.rel, name: s.label, checked: !s.missingScript })),
146
+ pageSize: 15,
147
+ });
148
+ }
149
+ }
150
+ let share = flags.share ?? 'local';
151
+ if (interactive && !flags.share) {
152
+ share = await select({
153
+ message: 'Folder checkpost/ disimpan bagaimana?',
154
+ choices: [
155
+ { value: 'local', name: `Hanya di komputer ini ${pc.gray('(.git/info/exclude, repo tidak berubah)')}` },
156
+ { value: 'team', name: `Bagikan ke tim ${pc.gray('(commit checkpost/, state di .gitignore)')}` },
157
+ ],
158
+ });
159
+ }
160
+ let installSlash = flags.slashCommand ?? true;
161
+ if (interactive && flags.slashCommand === undefined) {
162
+ installSlash = await confirm({ message: 'Pasang slash command /checkpost untuk Claude Code?', default: true });
163
+ }
164
+ // Tulis file
165
+ mkdirSync(targetDir, { recursive: true });
166
+ writeFileSync(path.join(targetDir, 'pipeline.md'), pipelineMd({ kind: preset === 'empty' ? project.kind : preset, context, docs: project.docs, label: project.label }));
167
+ const written = ['pipeline.md'];
168
+ if (preset === 'empty') {
169
+ writeFileSync(path.join(targetDir, '01-build.md'), '---\nrun: npm run build\n---\n');
170
+ written.push('01-build.md');
171
+ }
172
+ const groups = new Set();
173
+ for (const rel of chosen) {
174
+ const dest = path.join(targetDir, rel);
175
+ mkdirSync(path.dirname(dest), { recursive: true });
176
+ cpSync(path.join(presetDir, rel), dest);
177
+ written.push(rel);
178
+ const dir = path.dirname(rel);
179
+ if (dir !== '.' && !groups.has(dir) && existsSync(path.join(presetDir, dir, GROUP_FILE))) {
180
+ groups.add(dir);
181
+ cpSync(path.join(presetDir, dir, GROUP_FILE), path.join(targetDir, dir, GROUP_FILE));
182
+ written.push(path.join(dir, GROUP_FILE));
183
+ }
184
+ }
185
+ if (installSlash) {
186
+ const slash = path.join(root, SLASH_COMMAND_PATH);
187
+ mkdirSync(path.dirname(slash), { recursive: true });
188
+ writeFileSync(slash, SLASH_COMMAND);
189
+ }
190
+ const ignored = [];
191
+ if (git.isRepo) {
192
+ if (share === 'local') {
193
+ const patterns = [`/${PIPELINE_DIR}/`, `/${STATE_DIR}/`];
194
+ if (installSlash)
195
+ patterns.push(`/${SLASH_COMMAND_PATH}`);
196
+ ignored.push(...(await ignorePaths(root, patterns, 'exclude')));
197
+ }
198
+ else {
199
+ ignored.push(...(await ignorePaths(root, [`/${STATE_DIR}/`], 'gitignore')));
200
+ }
201
+ }
202
+ console.log(pc.green('\n ✔ Dibuat:'));
203
+ for (const f of written.sort())
204
+ console.log(pc.gray(` ${PIPELINE_DIR}/${f.split(path.sep).join('/')}`));
205
+ if (installSlash)
206
+ console.log(pc.gray(` ${SLASH_COMMAND_PATH}`));
207
+ if (ignored.length) {
208
+ const where = share === 'local' ? '.git/info/exclude' : '.gitignore';
209
+ console.log(pc.green(` ✔ Ditambahkan ke ${where}: ${ignored.join(', ')}`));
210
+ }
211
+ console.log(`
212
+ Langkah berikutnya:
213
+ 1. Sesuaikan isi file .md di ${PIPELINE_DIR}/ (opsional)
214
+ 2. checkpost list → cek urutan stage
215
+ 3. checkpost run → jalankan pipeline
216
+ `);
217
+ return 0;
218
+ }
@@ -0,0 +1,50 @@
1
+ import path from 'node:path';
2
+ import pc from 'picocolors';
3
+ import { discoverPipeline, flatten } from '../core/discovery.js';
4
+ import { typeLabel } from '../ui/format.js';
5
+ import { printDefinitionError } from './shared.js';
6
+ export function listCommand(flags) {
7
+ const root = path.resolve(flags.cwd);
8
+ let pipeline;
9
+ try {
10
+ pipeline = discoverPipeline(root);
11
+ }
12
+ catch (err) {
13
+ return printDefinitionError(err);
14
+ }
15
+ const rows = flatten(pipeline.children);
16
+ if (flags.json) {
17
+ console.log(JSON.stringify(rows.map(({ node, depth }) => ({
18
+ id: node.id,
19
+ name: node.name,
20
+ depth,
21
+ kind: node.kind,
22
+ type: node.kind === 'stage' ? node.type : node.config.parallel ? 'parallel' : 'sequential',
23
+ run: node.kind === 'stage' ? node.config.run : undefined,
24
+ })), null, 2));
25
+ return 0;
26
+ }
27
+ const c = pipeline.config;
28
+ console.log(pc.bold(`Checkpost · ${c.agent} (${c.model}) · fail_fast: ${c.fail_fast}`));
29
+ let top = 0;
30
+ for (const { node, depth } of rows) {
31
+ const num = depth === 0 ? String(++top).padStart(2) : ' ';
32
+ const indent = depth === 0 ? '' : ' '.repeat(depth - 1) + '├ ';
33
+ const name = (indent + node.name).padEnd(24);
34
+ const kind = typeLabel(node).padEnd(13);
35
+ let detail = '';
36
+ if (node.kind === 'stage') {
37
+ const bits = [];
38
+ if (node.config.run)
39
+ bits.push(node.config.run);
40
+ if (node.type !== 'command')
41
+ bits.push(`fail_on: ${node.config.fail_on}`);
42
+ if (node.config.allow_failure)
43
+ bits.push('allow_failure');
44
+ detail = bits.join(' · ');
45
+ }
46
+ const color = node.kind === 'group' ? pc.bold : node.type === 'command' ? (s) => s : pc.cyan;
47
+ console.log(`${pc.gray(num)} ${color(name)} ${pc.gray(kind)} ${pc.dim(detail)}`);
48
+ }
49
+ return 0;
50
+ }
@@ -0,0 +1,149 @@
1
+ import { jsx as _jsx } from "react/jsx-runtime";
2
+ import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
3
+ import path from 'node:path';
4
+ import { render } from 'ink';
5
+ import { confirm } from '@inquirer/prompts';
6
+ import pc from 'picocolors';
7
+ import { getAdapter } from '../core/adapters/index.js';
8
+ import { allStages, discoverPipeline, findNode } from '../core/discovery.js';
9
+ import { evaluateGate, readGitState, saveRun, STATE_DIR } from '../core/gate.js';
10
+ import { ignorePaths } from '../core/project.js';
11
+ import { runPipeline } from '../core/scheduler.js';
12
+ import { App } from '../ui/tui/App.js';
13
+ import { createPlainRenderer } from '../ui/plain.js';
14
+ import { printDefinitionError } from './shared.js';
15
+ function readUiState(root) {
16
+ try {
17
+ return JSON.parse(readFileSync(path.join(root, STATE_DIR, 'state.json'), 'utf8'));
18
+ }
19
+ catch {
20
+ return {};
21
+ }
22
+ }
23
+ function writeUiState(root, state) {
24
+ mkdirSync(path.join(root, STATE_DIR), { recursive: true });
25
+ writeFileSync(path.join(root, STATE_DIR, 'state.json'), JSON.stringify(state, null, 2));
26
+ }
27
+ const stagesOf = (nodes) => allStages(nodes);
28
+ export async function runCommand(target, flags) {
29
+ const root = path.resolve(flags.cwd);
30
+ let pipeline;
31
+ try {
32
+ pipeline = discoverPipeline(root);
33
+ }
34
+ catch (err) {
35
+ return printDefinitionError(err);
36
+ }
37
+ let nodes;
38
+ if (target) {
39
+ const node = findNode(pipeline.children, target);
40
+ if (!node) {
41
+ console.error(pc.red(`Stage atau grup "${target}" tidak ditemukan. Lihat "checkpost list".`));
42
+ return 2;
43
+ }
44
+ nodes = [node];
45
+ }
46
+ const selected = stagesOf(nodes ?? pipeline.children);
47
+ const aiStages = selected.filter((s) => s.type !== 'command');
48
+ const interactive = Boolean(process.stdout.isTTY && process.stdin.isTTY && !flags.ci && !flags.json);
49
+ let adapter;
50
+ if (aiStages.length) {
51
+ try {
52
+ adapter = getAdapter(pipeline.config.agent);
53
+ }
54
+ catch (err) {
55
+ console.error(pc.red(err.message));
56
+ return 2;
57
+ }
58
+ const detected = await adapter.detect();
59
+ if (!detected.installed) {
60
+ console.error(pc.red(`${adapter.label} tidak ditemukan. Install dulu: npm install -g @anthropic-ai/claude-code`));
61
+ return 2;
62
+ }
63
+ const ui = readUiState(root);
64
+ if (interactive && !flags.yes && pipeline.config.confirm_ai && !ui.aiConfirmed) {
65
+ const ok = await confirm({
66
+ message: `${aiStages.length} stage AI akan memakai kuota ${adapter.label} (model: ${pipeline.config.model}, batas $${pipeline.config.max_budget_usd}/stage). Lanjutkan?`,
67
+ default: true,
68
+ });
69
+ if (!ok)
70
+ return 1;
71
+ writeUiState(root, { ...ui, aiConfirmed: true });
72
+ }
73
+ }
74
+ // State run tidak boleh mengotori working tree project.
75
+ await ignorePaths(root, [`${STATE_DIR}/`], 'exclude');
76
+ const git = await readGitState(root);
77
+ const header = [
78
+ adapter ? pipeline.config.agent : null,
79
+ git.sha ? `${git.branch}@${git.sha.slice(0, 7)}` : null,
80
+ path.basename(root),
81
+ ]
82
+ .filter(Boolean)
83
+ .join(' · ');
84
+ const execute = async (runNodes, onEvent, signal) => {
85
+ const gitBefore = await readGitState(root);
86
+ const outcome = await runPipeline(pipeline, { nodes: runNodes, adapter, onEvent, signal });
87
+ if (!signal.aborted)
88
+ saveRun(pipeline, gitBefore, outcome.results, Boolean(runNodes));
89
+ return evaluateGate(pipeline);
90
+ };
91
+ if (interactive) {
92
+ let lastGate = null;
93
+ const wrapped = async (n, onEvent, signal) => {
94
+ lastGate = await execute(n, onEvent, signal);
95
+ return lastGate;
96
+ };
97
+ const app = render(_jsx(App, { pipeline: pipeline, header: header, execute: wrapped, initialNodes: nodes }), { exitOnCtrlC: false });
98
+ await app.waitUntilExit();
99
+ const gate = lastGate;
100
+ return gate?.green ? 0 : 1;
101
+ }
102
+ // Mode CI / non-TTY
103
+ const write = flags.json ? (s) => process.stderr.write(s + '\n') : undefined;
104
+ const stageMap = new Map(allStages(pipeline.children).map((s) => [s.id, s]));
105
+ const renderer = createPlainRenderer(stageMap, { verbose: Boolean(flags.verbose), write });
106
+ const out = write ?? ((s) => console.log(s));
107
+ out(pc.bold(`Checkpost · ${header}`));
108
+ const ac = new AbortController();
109
+ const onSigint = () => ac.abort();
110
+ process.once('SIGINT', onSigint);
111
+ const gate = await execute(nodes, renderer, ac.signal);
112
+ process.off('SIGINT', onSigint);
113
+ if (flags.json) {
114
+ const results = gate.lastRun?.results ?? {};
115
+ process.stdout.write(JSON.stringify({
116
+ gate: gate.green ? 'green' : 'red',
117
+ reasons: gate.reasons,
118
+ commit: gate.git.sha,
119
+ branch: gate.git.branch,
120
+ stages: allStages(pipeline.children).map((s) => {
121
+ const r = results[s.id];
122
+ return {
123
+ id: s.id,
124
+ status: r?.status ?? 'not-run',
125
+ allowFailure: s.config.allow_failure,
126
+ durationMs: r?.durationMs,
127
+ costUsd: r?.costUsd,
128
+ summary: r?.summary,
129
+ error: r?.error,
130
+ findings: r?.findings ?? [],
131
+ };
132
+ }),
133
+ }, null, 2) + '\n');
134
+ }
135
+ else {
136
+ out('');
137
+ if (gate.green)
138
+ out(pc.green(pc.bold('✔ GATE GREEN · boleh deploy')));
139
+ else {
140
+ out(pc.red(pc.bold('✖ GATE RED · belum boleh deploy')));
141
+ for (const r of gate.reasons)
142
+ out(pc.gray(` • ${r}`));
143
+ }
144
+ const cost = Object.values(gate.lastRun?.results ?? {}).reduce((sum, r) => sum + (r.costUsd ?? 0), 0);
145
+ if (cost)
146
+ out(pc.gray(` Biaya AI: $${cost.toFixed(3)}`));
147
+ }
148
+ return gate.green ? 0 : 1;
149
+ }
@@ -0,0 +1,12 @@
1
+ import pc from 'picocolors';
2
+ import { DefinitionError } from '../core/stage-file.js';
3
+ /** Cetak error definisi stage dan kembalikan exit code 2; error lain dilempar ulang. */
4
+ export function printDefinitionError(err) {
5
+ if (err instanceof DefinitionError) {
6
+ console.error(pc.red(pc.bold('Definisi pipeline tidak valid:')));
7
+ for (const p of err.problems)
8
+ console.error(pc.red(` • ${p}`));
9
+ return 2;
10
+ }
11
+ throw err;
12
+ }