canting 1.0.5

The official Artisan-like CLI toolchain for Pakem Framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
use std::fs;
use std::io;
use std::path::Path;

/// Generate universal `AGENTS.md` context instructions for any AI agent (Antigravity, Cline, Windsurf, ChatGPT, etc.)
pub fn generate_agents_md(app_name: &str) -> String {
    format!(
        r#"# 🤖 Pakem Framework — Developer & AI Agent Guidelines ({app_name})

> **Visi Inti Pakem:**  
> *"Look like Laravel, Run at Rust Speed. Cuantik, elegan, tercepat, dan menghadirkan pengalaman pengembangan (Developer Experience) paling menyenangkan di dunia backend."*

Dokumen ini adalah pedoman mutlak (**Rules & Standards**) bagi seluruh AI Agent (Antigravity, Cursor, Copilot, Claude Code, ChatGPT, dsb.) dan developer yang menulis, mengedit, atau melakukan maintenance kode pada proyek **{app_name}**.

---

## 🏛️ 1. Prinsip Utama Desain Kode

1. **Laravel Elegance**: Sintaks harus ekspresif, ringkas, bersih (*human-readable*), dan deklaratif. Hindari kode bertele-tele (*boilerplate*) yang menghambat kecepatan berpikir developer.
2. **Rust Raw Speed & Safety**: Menggunakan Tokio async runtime, Axum engine, dan zero-cost abstractions tanpa Garbage Collector.
3. **Batteries-Included**: ORM, Blade view engine, autentikasi, router, WebSocket, scheduler, dan background job queue sudah terintegrasi secara harmonis.

---

## 🎮 2. Rules Mutlak untuk Controller (`src/app/controllers/`)

### A. Wajib Menggunakan Unified `Request` Bundle
- ❌ **DILARANG KERAS** menggunakan puluhan extractor mentah Axum (`State(state)`, `Path(id)`, `Query(q)`, `Session(s)`, `CsrfToken`, dsb.) pada controller aplikasi.
- ✅ **WAJIB** menggunakan satu parameter tunggal: `req: Request` (dari `pakem::prelude::*`).

### B. Standardisasi Return Type
- **Controller Halaman Web (HTML View)**:
  - **WAJIB** mengembalikan `impl IntoResponse`.
  - **WAJIB** merender view menggunakan `View::make("nama.view").with("kunci", nilai)...render(req).await` (Bebas tanda ampersand `&` yang merepotkan).
  - Contoh:
    ```rust
    pub async fn index(req: Request) -> impl IntoResponse {{
        let user = req.user.clone().expect("Unauthorized");
        let users = User::query(req.db()).with("posts").get().await.unwrap_or_default();

        View::make("dashboard.index")
            .with("title", "Dashboard — Pakem")
            .with("user", user)
            .with("users", users)
            .render(req)
            .await
    }}
    ```

- **Controller RESTful API (JSON)**:
  - **WAJIB** mengembalikan `PakemResult` (alias untuk `Result<Response, AppError>`).
  - **WAJIB** memanfaatkan shortcut helper response bawaan `Request`:
    - `req.ok(data)` ➔ HTTP 200 `{{ "success": true, "data": ... }}`
    - `req.success(data, "Pesan sukses")` ➔ HTTP 200 `{{ "success": true, "message": "...", "data": ... }}`
    - `req.created_with(data, "Pesan dibuat")` ➔ HTTP 201 `{{ "success": true, "message": "...", "data": ... }}`
    - `req.paginate(paginator)` ➔ HTTP 200 dengan metadata paginasi lengkap
    - `req.not_found("Pesan error")` ➔ HTTP 404
    - `req.bad_request("Pesan error")` ➔ HTTP 400
    - `req.unauthorized("Pesan error")` ➔ HTTP 401
  - Contoh:
    ```rust
    pub async fn api_index(req: Request) -> PakemResult {{
        let (page, per_page) = req.pagination();
        let paginator = Product::paginate(req.db(), page, per_page).await?;
        req.paginate(paginator)
    }}
    ```

### C. Validasi Input Otomatis
- **Form Web**: Gunakan `ValidatedForm<T>`. Jika validasi gagal, engine Pakem otomatis me-redirect balik dengan flash error dan input lama (*old input*).
- **REST API**: Gunakan `ValidatedJson<T>`. Jika validasi gagal, engine otomatis mengembalikan HTTP 422 Unprocessable Entity berformat JSON.

### D. Akses Data Kontekstual via `Request`
- Database: `req.db()` atau `req.db_arc()`
- User Login: `req.user` atau `req.user()`
- Path Param / ID: `let id = req.id_or_fail()?;` atau `req.param("id")`
- Query Param: `let q = req.query_val("search");`
- Paginasi: `let (page, per_page) = req.pagination();`
- Redirect: `req.redirect("/products").with_success("Berhasil disimpan!").go(&req).await`

---

## 🗄️ 3. Rules untuk Model & ORM (`src/app/models/`)

1. **Macro Derivation**:
   Setiap entitas model **WAJIB** menambahkan derive:
   ```rust
   #[derive(Debug, Serialize, Deserialize, FromRow, Clone, Default, PakemModel)]
   #[table("products")]
   pub struct Product {{
       pub id: i64,
       pub name: String,
       pub price: f64,
       pub created_at: Option<String>,
       pub updated_at: Option<String>,
       pub deleted_at: Option<String>,
   }}
   ```
2. **Fluent Query Builder**:
   Gunakan query builder yang lancar ala Laravel:
   ```rust
   let active_items = Product::query(req.db())
       .where_eq("is_active", true)
       .where_gt("price", 10000.0)
       .order_by("created_at", "DESC")
       .limit(10)
       .get()
       .await?;
   ```
3. **One-Line Relationships**:
   ```rust
   has_many!(Comment, "product_id");
   belongs_to!(Category, "category_id");
   ```
4. **Cegah Masalah N+1 Query**:
   Gunakan `.with("relation_name")` saat mengambil data relasi untuk koleksi:
   ```rust
   let products = Product::query(req.db()).with("category").get().await?;
   ```

---

## 🎨 4. Rules untuk View (Blade Engine — `resources/views/`)

1. **Template Native Blade**:
   - File template bertipe `.blade.rs` dan disimpan di bawah folder `resources/views/`.
   - Hindari logika bisnis berat di dalam view. View hanya bertugas untuk presentasi.
2. **Pewarisan Layout**:
   - Gunakan `@extends('layouts.app')`, `@section('content')`, dan `@yield('content')`.
3. **Looping & Kontrol Alur**:
   - Gunakan `@foreach($items as $item)` dan manfaatkan objek `$loop` (`$loop.index`, `$loop.first`, `$loop.last`).
   - Gunakan `@if`, `@elseif`, `@else`, `@endif`.
   - Gunakan `@auth` / `@guest`.
4. **Form Security**:
   - Form method `POST` wajib menyertakan `@csrf`.
   - Gunakan `@method('PUT')` atau `@method('DELETE')` untuk spoofing HTTP method.

---

## ⚡ 5. Pakem Live (Reactive Server-Driven UI)

Jika membuat komponen interaktif tanpa menulis JavaScript/SPA:
- Gunakan direktif `kilat:*`, `wire:*`, atau `live:*`.
- Contoh: `<button wire:click="increment">+</button>` atau `<input wire:model="search" />`.
- Komponen backend mengimplementasikan trait `PakemLiveComponent`.

---

## 📋 6. Standard CRUD Blueprint (Resep Baku Pembuatan Fitur)

Ketika diminta membuat fitur CRUD baru (misal: `Product`), ikuti 6 langkah terstruktur ini:

### Langkah 1: Migrasi Database (`database/migrations/`)
```sql
CREATE TABLE IF NOT EXISTS products (
    id INTEGER PRIMARY KEY AUTOINCREMENT, -- atau BIGSERIAL di Postgres
    name VARCHAR(255) NOT NULL,
    price DOUBLE PRECISION NOT NULL DEFAULT 0,
    description TEXT,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    deleted_at TIMESTAMP NULL
);
```

### Langkah 2: Model (`src/app/models/product.rs`)
```rust
use pakem::prelude::*;

#[derive(Debug, Serialize, Deserialize, FromRow, Clone, Default, PakemModel)]
#[table("products")]
pub struct Product {{
    pub id: i64,
    pub name: String,
    pub price: f64,
    pub description: Option<String>,
    pub created_at: Option<String>,
    pub updated_at: Option<String>,
    pub deleted_at: Option<String>,
}}
```

### Langkah 3: Request Validation (`src/app/requests/product_request.rs`)
```rust
use serde::Deserialize;
use validator::Validate;

#[derive(Debug, Deserialize, Validate)]
pub struct CreateProductRequest {{
    #[validate(length(min = 3, message = "Nama produk minimal 3 karakter"))]
    pub name: String,
    #[validate(range(min = 0.0, message = "Harga tidak boleh minus"))]
    pub price: f64,
    pub description: Option<String>,
}}
```

### Langkah 4: Controller 7 RESTful Actions (`src/app/controllers/product_controller.rs`)
```rust
use pakem::prelude::*;
use crate::app::models::product::Product;
use crate::app::requests::product_request::CreateProductRequest;

pub struct ProductController;

impl ProductController {{
    // 1. GET /products (Index)
    pub async fn index(req: Request) -> impl IntoResponse {{
        let products = Product::query(req.db()).order_by("id", "DESC").get().await.unwrap_or_default();
        View::make("products.index").with("products", products).render(req).await
    }}

    // 2. GET /products/create (Form Tambah)
    pub async fn create(req: Request) -> impl IntoResponse {{
        View::make("products.create").render(req).await
    }}

    // 3. POST /products (Simpan)
    pub async fn store(req: Request) -> impl IntoResponse {{
        let form = match req.validate_form::<CreateProductRequest>().await {{
            Ok(f) => f,
            Err(e) => return req.redirect("/products/create").with_errors(e).with_input().go(&req).await,
        }};

        let new_item = Product {{
            name: form.name,
            price: form.price,
            description: form.description,
            ..Default::default()
        }};

        if let Err(e) = new_item.save(req.db()).await {{
            return req.redirect("/products/create").with_error(format!("Gagal: {{}}", e)).go(&req).await;
        }}

        req.redirect("/products").with_success("Produk berhasil ditambahkan!").go(&req).await
    }}

    // 4. GET /products/:id (Detail)
    pub async fn show(req: Request) -> impl IntoResponse {{
        let id: i64 = req.id_or_fail().unwrap_or(0);
        let product = Product::find(req.db(), id).await.ok().flatten();
        View::make("products.show").with("product", product).render(req).await
    }}

    // 5. GET /products/:id/edit (Form Edit)
    pub async fn edit(req: Request) -> impl IntoResponse {{
        let id: i64 = req.id_or_fail().unwrap_or(0);
        let product = Product::find(req.db(), id).await.ok().flatten();
        View::make("products.edit").with("product", product).render(req).await
    }}

    // 6. PUT /products/:id (Update)
    pub async fn update(req: Request) -> impl IntoResponse {{
        let id: i64 = req.id_or_fail().unwrap_or(0);
        let form = match req.validate_form::<CreateProductRequest>().await {{
            Ok(f) => f,
            Err(e) => return req.redirect(&format!("/products/{{}}/edit", id)).with_errors(e).go(&req).await,
        }};

        let mut product = match Product::find(req.db(), id).await.ok().flatten() {{
            Some(p) => p,
            None => return req.redirect("/products").with_error("Produk tidak ditemukan!").go(&req).await,
        }};

        product.name = form.name;
        product.price = form.price;
        product.description = form.description;
        let _ = product.save(req.db()).await;

        req.redirect("/products").with_success("Produk berhasil diperbarui!").go(&req).await
    }}

    // 7. DELETE /products/:id (Hapus)
    pub async fn destroy(req: Request) -> impl IntoResponse {{
        let id: i64 = req.id_or_fail().unwrap_or(0);
        if let Ok(Some(product)) = Product::find(req.db(), id).await {{
            let _ = product.delete(req.db()).await;
        }}
        req.redirect("/products").with_success("Produk berhasil dihapus!").go(&req).await
    }}

    // --- RESTful API Handlers (JSON) ---
    pub async fn api_index(req: Request) -> PakemResult {{
        let (page, per_page) = req.pagination();
        let paginator = Product::paginate(req.db(), page, per_page).await?;
        req.paginate(paginator)
    }}

    pub async fn api_store(req: Request) -> PakemResult {{
        let payload = req.validate_json::<CreateProductRequest>().await?;
        let product = Product {{
            name: payload.name,
            price: payload.price,
            description: payload.description,
            ..Default::default()
        }};
        let saved = product.save(req.db()).await?;
        req.created_with(saved, "Produk berhasil dibuat")
    }}
}}
```

### Langkah 5: Registrasi Route (`src/routes/web.rs` & `api.rs`)
```rust
// Web Routes (src/routes/web.rs)
router = router
    .route("/products", get(ProductController::index).post(ProductController::store))
    .route("/products/create", get(ProductController::create))
    .route("/products/:id", get(ProductController::show).put(ProductController::update).delete(ProductController::destroy))
    .route("/products/:id/edit", get(ProductController::edit));

// API Routes (src/routes/api.rs)
router = router
    .route("/api/products", get(ProductController::api_index).post(ProductController::api_store));
```

---

## 🚫 7. Larangan Keras (Strict Prohibitions)

1. ❌ **DILARANG** mengembalikan boilerplate Axum mentah di Controller (`State(state)`, `Path(id)`). Selalu gunakan parameter tunggal `req: Request`.
2. ❌ **DILARANG** menulis query mentah SQL yang rentan SQL Injection — gunakan query builder atau parameterized statement.
3. ❌ **DILARANG** menggunakan `unwrap()` atau `expect()` secara sembarangan di handler publik — selalu tangani error dengan operator `?` atau `AppError`.

---

## 🛡️ 8. Perlindungan Data, Privasi & AI Governance (Vibe Coding Guidelines)

Ketika mengembangkan aplikasi dengan bantuan AI Agent (Antigravity, Cursor, Copilot, Windsurf, dsb.):
1. **Patuhi File Ignore AI (`.aiignore`, `.cursorignore`, `.gitignore`)**:
   - Rahasia (.env), sertifikat (.pem, .key), dan dump database (.sql) tidak boleh dibaca atau diindeks oleh AI.
2. **Dilarang Menggunakan Data Produksi di Lokal**:
   - Selalu gunakan `Model::factory()` atau generator `Faker` untuk data dummy pengujian lokal.
3. **Approval Mode**:
   - Jangan jalankan perintah terminal destruktif atau mutasi file sensitif tanpa persetujuan manual developer.
4. **Pengaturan Privasi Model**:
   - Pastikan opsi data retention / training opt-out aktif pada akun AI Anda.
5. **Model Lokal untuk Logika Rahasia**:
   - Gunakan model intranet (Ollama / LM Studio) jika menangani IP / rahasia dagang super sensitif.

---

*Pakem Framework: Keringat performa Rust di balik keindahan dan kemudahan Laravel.*
"#,
        app_name = app_name
    )
}

/// Generate `.cursorrules` optimized for Cursor IDE AI Agent and Composer
pub fn generate_cursorrules(app_name: &str) -> String {
    format!(
        r#"# Cursor Rules for Pakem Framework ({app_name})
# Philosophy: "Look like Laravel, Run at Rust Speed"

## Core Controller Rules
- ALWAYS use a single parameter for controllers: `req: Request` from `pakem::prelude::*`.
- NEVER use raw Axum extractors (`State(...)`, `Path(...)`, `Query(...)`, `Form(...)`) in application controllers.
- Web HTML Controllers:
  - Return `impl IntoResponse`.
  - Render with `View::make("view.name").with("key", val).render(req).await`.
- REST API Controllers:
  - Return `PakemResult` (alias for `Result<Response, AppError>`).
  - Use helpers: `req.ok(data)`, `req.created_with(data, msg)`, `req.paginate(paginator)`, `req.not_found(msg)`.

## Model & ORM Rules
- Entities MUST derive: `#[derive(Debug, Serialize, Deserialize, FromRow, Clone, Default, PakemModel)]`.
- Entities MUST specify table: `#[table("table_name")]`.
- Always use the fluent query builder: `Model::query(req.db()).where_eq("col", val).get().await?`.
- Relationships: `has_many!(Child, "parent_id");`, `belongs_to!(Parent, "parent_id");`.
- Eager load with `.with("relation")` to prevent N+1 queries.

## Validation Rules
- Web forms: `req.validate_form::<FormType>().await` or `ValidatedForm<T>`.
- API endpoints: `req.validate_json::<JsonType>().await` or `ValidatedJson<T>`.

## Blade Views & Livewire
- Files in `resources/views/` must end in `.blade.rs`.
- Form methods POST require `@csrf`.
- Reactive UI components use Pakem Live directives: `kilat:*`, `wire:*`, `live:*`.

## CLI Commands
- `canting serve` : Run app
- `canting watch` : Run app with hot auto-reload
- `canting tinker` : Interactive REPL shell
- `canting migrate` : Run database migrations
- `canting make:crud <Name>` : Scaffold complete CRUD
- `canting make:ai-context` : Refresh AI instructions
"#
    )
}

/// Generate `.github/copilot-instructions.md` for GitHub Copilot Workspace
pub fn generate_copilot_instructions(app_name: &str) -> String {
    format!(
        r#"# GitHub Copilot Instructions for {app_name} (Pakem Framework)

You are an expert Pakem Framework developer. Pakem is an enterprise Rust web framework that combines Laravel's DX and elegance with Rust's raw speed and memory safety.

## Architectural Mandates
1. **Controllers**:
   - Single signature: `pub async fn handler_name(req: Request) -> impl IntoResponse` (or `-> PakemResult` for JSON APIs).
   - Do NOT suggest raw Axum extractors like `State(state)`, `Path(id)`. Access context via `req.db()`, `req.id_or_fail()?`, `req.user()`, `req.query_val()`.
   - Render views with `View::make("path").with("key", value).render(req).await`.
   - Return API responses with `req.ok(data)`, `req.paginate(paginator)`, or `req.created_with(data, msg)`.

2. **Models & Database**:
   - Must derive `PakemModel`: `#[derive(Debug, Serialize, Deserialize, FromRow, Clone, Default, PakemModel)]`.
   - Fluent queries: `User::query(req.db()).where_eq("is_active", true).get().await?`.
   - Relationship macros: `has_many!(Post, "user_id")` and `belongs_to!(User, "user_id")`.

3. **Views**:
   - Blade engine templates in `resources/views/**/*.blade.rs`.
   - Use `@extends('layouts.app')`, `@section('content')`, `@yield('content')`, `@csrf`.

4. **Safety & Style**:
   - Avoid raw `unwrap()` in production handlers; use `?` operator or return `AppError`.
   - Avoid raw SQL strings vulnerable to injection; use Pakem query builder or prepared parameters.
"#
    )
}

/// Generate `CLAUDE.md` for Anthropic Claude Code CLI
pub fn generate_claude_md(app_name: &str) -> String {
    format!(
        r#"# CLAUDE.md — {app_name} (Pakem Framework)

This document guides Claude Code when working in this Pakem repository.

## Commands
- Run server: `canting serve` (or `cargo run`)
- Watch server (auto-reload): `canting watch`
- Interactive REPL shell: `canting tinker`
- Database migrations: `canting migrate` (rollback: `canting migrate:rollback`)
- Database seeding: `canting db:seed`
- Generate CRUD: `canting make:crud <ModelName>`
- Run tests: `cargo test`

## Architecture & Code Conventions
- **Controller signature**: Always `pub async fn action(req: Request) -> impl IntoResponse` (Web) or `-> PakemResult` (API). Never use raw Axum extractors.
- **ORM**: Derive `PakemModel` on all models. Use `Model::query(req.db())` for queries.
- **Views**: Blade templates live in `resources/views/` as `.blade.rs`.
- **Validation**: `req.validate_form::<T>()` for HTML forms, `req.validate_json::<T>()` for REST APIs.
- **Error Handling**: Use `AppError` and the `?` operator instead of `unwrap()`.
"#
    )
}

/// Scaffold all universal AI context files in the given project base path
pub fn scaffold_ai_context(base: &Path, app_name: &str) -> io::Result<()> {
    // 1. Ensure .github folder exists
    let github_dir = base.join(".github");
    if !github_dir.exists() {
        fs::create_dir_all(&github_dir)?;
    }

    // 2. Write AGENTS.md
    fs::write(base.join("AGENTS.md"), generate_agents_md(app_name))?;

    // 3. Write .cursorrules
    fs::write(base.join(".cursorrules"), generate_cursorrules(app_name))?;

    // 4. Write .github/copilot-instructions.md
    fs::write(
        github_dir.join("copilot-instructions.md"),
        generate_copilot_instructions(app_name),
    )?;

    // 5. Write CLAUDE.md
    fs::write(base.join("CLAUDE.md"), generate_claude_md(app_name))?;

    // 6. Write .aiignore and .cursorignore (Data Protection & AI Governance)
    let ai_ignore_content = r#"# ==============================================================================
# Pakem Framework - AI Context & Training Ignore Policy (.aiignore / .cursorignore)
# Mencegah file rahasia, data pengguna, sertifikat, dan dump database
# terbaca atau terindeks oleh AI Agents (Antigravity, Cursor, Copilot, dll.)
# ==============================================================================

# 1. Environment Secrets & Credentials
.env
.env.*
!.env.example
*.env
*.secret
secrets.*

# 2. Certificates & Private Keys
*.pem
*.key
*.crt
*.pfx
*.p12
*.cer
*.der
id_rsa
id_rsa.pub
*.pub
*.token

# 3. Database Dumps, Backups & Real Customer Data
*.sql
*.dump
*.sqlite
*.sqlite3
*.db
database/dumps/
database/backups/
storage/backups/
backup/
backups/

# 4. Storage Uploads, User Private Data & Logs
storage/logs/
storage/app/private/
storage/app/public/uploads/
storage/cache/
*.log

# 5. Build Artifacts & Compiled Binaries
/target/
*.exe
*.dll
*.so
*.dylib
*.wasm
*.tar.gz
*.zip
"#;
    fs::write(base.join(".aiignore"), ai_ignore_content)?;
    fs::write(base.join(".cursorignore"), ai_ignore_content)?;

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_generate_agents_md_contains_canting_rules_and_crud() {
        let content = generate_agents_md("TokoApp");
        assert!(content.contains("Pakem Framework — Developer & AI Agent Guidelines (TokoApp)"));
        assert!(content.contains("req: Request"));
        assert!(content.contains("PakemModel"));
        assert!(content.contains("Standard CRUD Blueprint"));
        assert!(content.contains("View::make"));
        assert!(content.contains("req.paginate"));
        assert!(content.contains("DILARANG KERAS"));
    }

    #[test]
    fn test_generate_cursorrules_contains_rules() {
        let content = generate_cursorrules("TokoApp");
        assert!(content.contains("Cursor Rules for Pakem Framework (TokoApp)"));
        assert!(content.contains("ALWAYS use a single parameter for controllers: `req: Request`"));
        assert!(content.contains("NEVER use raw Axum extractors"));
    }

    #[test]
    fn test_generate_copilot_instructions_contains_mandates() {
        let content = generate_copilot_instructions("TokoApp");
        assert!(content.contains("GitHub Copilot Instructions for TokoApp (Pakem Framework)"));
        assert!(content.contains("Do NOT suggest raw Axum extractors"));
    }

    #[test]
    fn test_generate_claude_md_contains_commands_and_conventions() {
        let content = generate_claude_md("TokoApp");
        assert!(content.contains("CLAUDE.md — TokoApp (Pakem Framework)"));
        assert!(content.contains("canting serve"));
        assert!(content.contains("canting tinker"));
        assert!(content.contains("canting make:crud"));
    }

    #[test]
    fn test_scaffold_ai_context_creates_all_files() {
        let temp_dir = std::env::temp_dir().join(format!("canting_ai_test_{}", std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()));
        fs::create_dir_all(&temp_dir).expect("Failed to create temp dir");

        let res = scaffold_ai_context(&temp_dir, "TestApp");
        assert!(res.is_ok());

        assert!(temp_dir.join("AGENTS.md").exists());
        assert!(temp_dir.join(".cursorrules").exists());
        assert!(temp_dir.join(".github/copilot-instructions.md").exists());
        assert!(temp_dir.join("CLAUDE.md").exists());
        assert!(temp_dir.join(".aiignore").exists());
        assert!(temp_dir.join(".cursorignore").exists());

        let agents = fs::read_to_string(temp_dir.join("AGENTS.md")).unwrap();
        assert!(agents.contains("TestApp"));

        // Clean up
        let _ = fs::remove_dir_all(temp_dir);
    }

    #[test]
    fn test_skeleton_includes_ai_context() {
        let temp_dir = std::env::temp_dir().join(format!("canting_skel_test_{}", std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()));
        fs::create_dir_all(&temp_dir).expect("Failed to create temp dir");

        crate::skeleton::create_full_skeleton(&temp_dir, "SkelApp", "sqlite");

        assert!(temp_dir.join("Cargo.toml").exists());
        assert!(temp_dir.join(".gitignore").exists());
        assert!(temp_dir.join(".aiignore").exists());
        assert!(temp_dir.join(".cursorignore").exists());
        assert!(temp_dir.join("AGENTS.md").exists());
        assert!(temp_dir.join(".cursorrules").exists());
        assert!(temp_dir.join(".github/copilot-instructions.md").exists());
        assert!(temp_dir.join("CLAUDE.md").exists());

        // Clean up
        let _ = fs::remove_dir_all(temp_dir);
    }

    #[test]
    fn test_generate_ai_context_command() {
        let temp_dir = std::env::temp_dir().join(format!("canting_ctx_cmd_test_{}", std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()));
        fs::create_dir_all(temp_dir.join("src/app")).expect("Failed to create src/app");
        fs::write(temp_dir.join("Cargo.toml"), "[package]\nname = \"test_ctx_app\"\nversion = \"0.1.0\"\n").unwrap();

        crate::generator::generate_ai_context_at(&temp_dir, "all", true);

        assert!(temp_dir.join("AGENTS.md").exists());
        assert!(temp_dir.join(".cursorrules").exists());
        assert!(temp_dir.join(".github/copilot-instructions.md").exists());
        assert!(temp_dir.join("CLAUDE.md").exists());

        let agents_content = fs::read_to_string(temp_dir.join("AGENTS.md")).unwrap();
        assert!(agents_content.contains("test_ctx_app"));

        let _ = fs::remove_dir_all(temp_dir);
    }

    #[test]
    fn test_generate_ai_skill_creates_schemas_and_stubs() {
        let temp_dir = std::env::temp_dir().join(format!("canting_skill_test_{}", std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()));
        fs::create_dir_all(temp_dir.join("src/app")).expect("Failed to create src/app");
        fs::write(temp_dir.join("Cargo.toml"), "[package]\nname = \"test_skill_app\"\nversion = \"0.1.0\"\n").unwrap();

        let fields = vec!["keyword:string".to_string(), "limit:i64".to_string()];
        crate::generator::generate_ai_skill_at(&temp_dir, "SearchProducts", &fields, "all");

        assert!(temp_dir.join("app/ai/tools/search_products.json").exists());
        assert!(temp_dir.join("app/ai/skills/search_products/SKILL.md").exists());
        assert!(temp_dir.join("src/app/services/ai/search_products_tool.rs").exists());

        let json_content = fs::read_to_string(temp_dir.join("app/ai/tools/search_products.json")).unwrap();
        assert!(json_content.contains("openai_tool"));
        assert!(json_content.contains("gemini_declaration"));
        assert!(json_content.contains("claude_tool"));

        let rust_code = fs::read_to_string(temp_dir.join("src/app/services/ai/search_products_tool.rs")).unwrap();
        assert!(rust_code.contains("pub struct SearchProductsInput"));
        assert!(rust_code.contains("pub keyword: String"));
        assert!(rust_code.contains("pub limit: i64"));
        assert!(rust_code.contains("SearchProductsTool"));

        let _ = fs::remove_dir_all(temp_dir);
    }

    #[test]
    fn test_generate_ai_skill_reverse_engineer() {
        let temp_dir = std::env::temp_dir().join(format!("canting_rev_test_{}", std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()));
        fs::create_dir_all(temp_dir.join("src/app")).expect("Failed to create src/app");
        fs::write(temp_dir.join("Cargo.toml"), "[package]\nname = \"test_rev_app\"\nversion = \"0.1.0\"\n").unwrap();

        crate::generator::generate_ai_skill_at(&temp_dir, "ReverseEngineer", &[], "all");

        assert!(temp_dir.join("app/ai/tools/reverse_engineer.json").exists());
        assert!(temp_dir.join("app/ai/skills/reverse_engineer/SKILL.md").exists());
        assert!(temp_dir.join("src/app/services/ai/reverse_engineer_tool.rs").exists());

        let skill_doc = fs::read_to_string(temp_dir.join("app/ai/skills/reverse_engineer/SKILL.md")).unwrap();
        assert!(skill_doc.contains("Reverse Engineer"));
        assert!(skill_doc.contains("Pakem Live"));
        assert!(skill_doc.contains("Tailwind"));

        let rust_code = fs::read_to_string(temp_dir.join("src/app/services/ai/reverse_engineer_tool.rs")).unwrap();
        assert!(rust_code.contains("ReverseEngineerInput"));
        assert!(rust_code.contains("ReverseEngineerTool"));

        let _ = fs::remove_dir_all(temp_dir);
    }
}