hematite-cli 0.13.0

Senior SysAdmin, Network Admin, Data Analyst, and Software Engineer living in your terminal. A high-precision local AI agent harness for LM Studio, Ollama, and other local OpenAI-compatible runtimes that runs 100% on your own silicon. Reads repos, edits files, runs builds, inspects full network state and workstation telemetry, and runs real Python/JS for data analysis.
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
687
688
689
690
691
692
693
694
695
696
697
698
699
use serde_json::Value;
use std::collections::BTreeMap;
use std::path::PathBuf;

pub async fn execute(args: &Value) -> Result<String, String> {
    let template = args
        .get("template")
        .and_then(|v| v.as_str())
        .ok_or("template_gen: 'template' is required")?;

    // Handle list action
    if template == "list" {
        return Ok(list_templates());
    }

    let root = if let Some(r) = args.get("_root").and_then(|v| v.as_str()) {
        PathBuf::from(r)
    } else {
        crate::tools::file_ops::workspace_root()
    };

    let output_path = args.get("output").and_then(|v| v.as_str());
    let dry_run = args
        .get("dry_run")
        .and_then(|v| v.as_bool())
        .unwrap_or(false);

    // Collect substitution variables from args
    let mut vars: BTreeMap<String, String> = BTreeMap::new();
    if let Some(obj) = args.as_object() {
        for (k, v) in obj {
            if matches!(k.as_str(), "template" | "output" | "dry_run" | "_root") {
                continue;
            }
            if let Some(s) = v.as_str() {
                vars.insert(k.clone(), s.to_string());
            }
        }
    }

    let (default_path, content) = render_template(template, &vars)?;
    let dest_name = output_path.unwrap_or(default_path);
    let dest = root.join(dest_name);

    if dry_run {
        return Ok(format!(
            "template_gen [DRY RUN]: would write to {}\n\n{content}",
            dest.display()
        ));
    }

    // Check if file already exists
    if dest.exists() {
        return Err(format!(
            "template_gen: '{}' already exists. Pass output='path/to/file' to write elsewhere, \
             or rename the existing file first.",
            dest.display()
        ));
    }

    // Create parent dirs
    if let Some(parent) = dest.parent() {
        if !parent.exists() {
            std::fs::create_dir_all(parent)
                .map_err(|e| format!("template_gen: failed to create directory: {e}"))?;
        }
    }

    std::fs::write(&dest, &content)
        .map_err(|e| format!("template_gen: failed to write '{}': {e}", dest.display()))?;

    Ok(format!(
        "template_gen: wrote {} ({} bytes)\n\nContent preview (first 400 chars):\n{}",
        dest.display(),
        content.len(),
        &content[..content.len().min(400)]
    ))
}

fn list_templates() -> String {
    let mut out = "AVAILABLE TEMPLATES\n".to_string();
    out.push_str(&"".repeat(60));
    out.push('\n');
    let templates: &[(&str, &str)] = &[
        ("dockerfile-node", "Dockerfile for a Node.js application"),
        ("dockerfile-python", "Dockerfile for a Python application"),
        (
            "dockerfile-rust",
            "Dockerfile for a Rust application (multi-stage)",
        ),
        (
            "dockerfile-go",
            "Dockerfile for a Go application (multi-stage)",
        ),
        (
            "ci-github-node",
            ".github/workflows/ci.yml for Node.js (GitHub Actions)",
        ),
        (
            "ci-github-python",
            ".github/workflows/ci.yml for Python (GitHub Actions)",
        ),
        (
            "ci-github-rust",
            ".github/workflows/ci.yml for Rust (GitHub Actions)",
        ),
        ("gitignore-node", ".gitignore for Node.js projects"),
        ("gitignore-python", ".gitignore for Python projects"),
        ("gitignore-rust", ".gitignore for Rust projects"),
        (
            "gitignore-general",
            ".gitignore with common OS and editor exclusions",
        ),
        ("env-template", ".env.example with common variable stubs"),
        ("makefile-node", "Makefile with common Node.js targets"),
        ("makefile-python", "Makefile with common Python targets"),
        ("makefile-rust", "Makefile with common Rust targets"),
        (
            "docker-compose",
            "docker-compose.yml with web + db + redis services",
        ),
        ("pre-commit", ".pre-commit-config.yaml with common hooks"),
        ("editorconfig", ".editorconfig for consistent formatting"),
        (
            "dependabot",
            ".github/dependabot.yml for automated dependency updates",
        ),
        ("codeowners", ".github/CODEOWNERS template"),
        ("pr-template", ".github/pull_request_template.md"),
        ("issue-bug", ".github/ISSUE_TEMPLATE/bug_report.md"),
        ("issue-feature", ".github/ISSUE_TEMPLATE/feature_request.md"),
    ];
    for (name, desc) in templates {
        out.push_str(&format!("  {:30}  {desc}\n", name));
    }
    out.push_str("\nUsage: template_gen(template: \"dockerfile-rust\") or template_gen(template: \"ci-github-node\", project_name: \"my-app\")");
    out
}

fn render_template(
    name: &str,
    vars: &BTreeMap<String, String>,
) -> Result<(&'static str, String), String> {
    let project = vars
        .get("project_name")
        .map(|s| s.as_str())
        .unwrap_or("my-app");
    let port = vars.get("port").map(|s| s.as_str()).unwrap_or("3000");
    let python_ver = vars
        .get("python_version")
        .map(|s| s.as_str())
        .unwrap_or("3.12");
    let node_ver = vars.get("node_version").map(|s| s.as_str()).unwrap_or("20");
    let rust_ver = vars
        .get("rust_version")
        .map(|s| s.as_str())
        .unwrap_or("1.82");
    let go_ver = vars.get("go_version").map(|s| s.as_str()).unwrap_or("1.23");
    let _registry = vars
        .get("registry")
        .map(|s| s.as_str())
        .unwrap_or("ghcr.io/your-org");

    match name {
        "dockerfile-node" => Ok(("Dockerfile", format!(r#"FROM node:{node_ver}-alpine AS deps
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production

FROM node:{node_ver}-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production
COPY --from=deps /app/node_modules ./node_modules
COPY . .
EXPOSE {port}
CMD ["node", "src/index.js"]
"#))),

        "dockerfile-python" => Ok(("Dockerfile", format!(r#"FROM python:{python_ver}-slim
WORKDIR /app
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE {port}
CMD ["python", "main.py"]
"#))),

        "dockerfile-rust" => Ok(("Dockerfile", format!(r#"FROM rust:{rust_ver}-slim AS builder
WORKDIR /app
COPY Cargo.toml Cargo.lock ./
RUN mkdir src && echo "fn main() {{}}" > src/main.rs && cargo build --release && rm -rf src
COPY src ./src
RUN touch src/main.rs && cargo build --release

FROM debian:bookworm-slim AS runner
RUN apt-get update && apt-get install -y ca-certificates && rm -rf /var/lib/apt/lists/*
COPY --from=builder /app/target/release/{project} /usr/local/bin/{project}
EXPOSE {port}
CMD ["{project}"]
"#, project=project, port=port, rust_ver=rust_ver))),

        "dockerfile-go" => Ok(("Dockerfile", format!(r#"FROM golang:{go_ver}-alpine AS builder
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -ldflags="-s -w" -o /app/{project} .

FROM scratch
COPY --from=builder /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/
COPY --from=builder /app/{project} /{project}
EXPOSE {port}
ENTRYPOINT ["/{project}"]
"#, project=project, port=port, go_ver=go_ver))),

        "ci-github-node" => Ok((".github/workflows/ci.yml", format!(r#"name: CI

on:
  push:
    branches: [main, master]
  pull_request:
    branches: [main, master]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: '{node_ver}'
          cache: 'npm'
      - run: npm ci
      - run: npm test
      - run: npm run lint --if-present
      - run: npm run build --if-present
"#))),

        "ci-github-python" => Ok((".github/workflows/ci.yml", format!(r#"name: CI

on:
  push:
    branches: [main, master]
  pull_request:
    branches: [main, master]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: '{python_ver}'
          cache: 'pip'
      - run: pip install -r requirements.txt
      - run: pip install pytest ruff mypy
      - run: ruff check .
      - run: pytest
"#))),

        "ci-github-rust" => Ok((".github/workflows/ci.yml", format!(r#"name: CI

on:
  push:
    branches: [main, master]
  pull_request:
    branches: [main, master]

env:
  CARGO_TERM_COLOR: always

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: dtolnay/rust-toolchain@stable
        with:
          components: clippy, rustfmt
      - uses: Swatinem/rust-cache@v2
      - run: cargo fmt --check
      - run: cargo clippy -- -D warnings
      - run: cargo test

  build-release:
    runs-on: ubuntu-latest
    needs: test
    if: github.ref == 'refs/heads/main'
    steps:
      - uses: actions/checkout@v4
      - uses: dtolnay/rust-toolchain@stable
      - uses: Swatinem/rust-cache@v2
      - run: cargo build --release
"#))),

        "gitignore-node" => Ok((".gitignore", r#"node_modules/
dist/
build/
.next/
.nuxt/
coverage/
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
.env
.env.local
.env.*.local
.DS_Store
*.tsbuildinfo
"#.to_string())),

        "gitignore-python" => Ok((".gitignore", r#"__pycache__/
*.pyc
*.pyo
*.pyd
.Python
.venv/
venv/
ENV/
env/
.env
dist/
build/
*.egg-info/
.eggs/
*.egg
.pytest_cache/
.mypy_cache/
.ruff_cache/
coverage.xml
.coverage
htmlcov/
.DS_Store
"#.to_string())),

        "gitignore-rust" => Ok((".gitignore", r#"/target/
Cargo.lock
**/*.rs.bk
.env
.DS_Store
*.pdb
"#.to_string())),

        "gitignore-general" => Ok((".gitignore", r#"# OS
.DS_Store
.DS_Store?
._*
.Spotlight-V100
.Trashes
ehthumbs.db
Thumbs.db
desktop.ini

# Editors
.idea/
.vscode/
*.swp
*.swo
*~
.project
.classpath
.settings/
*.sublime-project
*.sublime-workspace

# Secrets
.env
.env.local
*.pem
*.key
secrets.json
credentials.json

# Build artifacts
dist/
build/
out/
"#.to_string())),

        "env-template" => Ok((".env.example", r#"# Application
NODE_ENV=development
PORT=3000
APP_NAME=my-app
LOG_LEVEL=info

# Database
DATABASE_URL=postgres://user:password@localhost:5432/dbname
REDIS_URL=redis://localhost:6379

# Authentication
JWT_SECRET=change-me-in-production
SESSION_SECRET=change-me-in-production

# External APIs
# STRIPE_SECRET_KEY=sk_test_...
# SENDGRID_API_KEY=SG...
# AWS_ACCESS_KEY_ID=AKIA...
# AWS_SECRET_ACCESS_KEY=...
# AWS_REGION=us-east-1

# Feature flags
ENABLE_EXPERIMENTAL=false
"#.to_string())),

        "makefile-node" => Ok(("Makefile", r#".PHONY: install dev build test lint clean docker-build docker-run

install:
	npm ci

dev:
	npm run dev

build:
	npm run build

test:
	npm test

lint:
	npm run lint

clean:
	rm -rf node_modules dist build .next

docker-build:
	docker build -t $(IMAGE_NAME) .

docker-run:
	docker run -p 3000:3000 $(IMAGE_NAME)
"#.to_string())),

        "makefile-python" => Ok(("Makefile", r#".PHONY: install dev test lint format check clean

install:
	pip install -r requirements.txt

dev:
	pip install -r requirements-dev.txt

test:
	pytest

lint:
	ruff check .
	mypy .

format:
	ruff format .

check: lint test

clean:
	find . -type d -name __pycache__ -exec rm -rf {} +
	find . -name "*.pyc" -delete
	rm -rf .pytest_cache .mypy_cache .ruff_cache
"#.to_string())),

        "makefile-rust" => Ok(("Makefile", r#".PHONY: build release test check fmt clippy clean doc

build:
	cargo build

release:
	cargo build --release

test:
	cargo test

check:
	cargo check

fmt:
	cargo fmt

clippy:
	cargo clippy -- -D warnings

clean:
	cargo clean

doc:
	cargo doc --open
"#.to_string())),

        "docker-compose" => Ok(("docker-compose.yml", format!(r#"version: '3.9'

services:
  web:
    build: .
    ports:
      - "{port}:{port}"
    environment:
      - NODE_ENV=development
      - DATABASE_URL=postgres://app:secret@db:5432/app
      - REDIS_URL=redis://redis:6379
    depends_on:
      db:
        condition: service_healthy
      redis:
        condition: service_started
    volumes:
      - .:/app
      - /app/node_modules

  db:
    image: postgres:16-alpine
    environment:
      POSTGRES_USER: app
      POSTGRES_PASSWORD: secret
      POSTGRES_DB: app
    ports:
      - "5432:5432"
    volumes:
      - pg_data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U app"]
      interval: 5s
      timeout: 5s
      retries: 5

  redis:
    image: redis:7-alpine
    ports:
      - "6379:6379"

volumes:
  pg_data:
"#))),

        "pre-commit" => Ok((".pre-commit-config.yaml", r#"repos:
  - repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v4.6.0
    hooks:
      - id: trailing-whitespace
      - id: end-of-file-fixer
      - id: check-yaml
      - id: check-json
      - id: check-toml
      - id: check-merge-conflict
      - id: detect-private-key
      - id: no-commit-to-branch
        args: [--branch, main, --branch, master]

  - repo: https://github.com/gitleaks/gitleaks
    rev: v8.18.4
    hooks:
      - id: gitleaks
"#.to_string())),

        "editorconfig" => Ok((".editorconfig", r#"root = true

[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

[*.{rs,java,kt}]
indent_size = 4

[*.{md,txt}]
trim_trailing_whitespace = false

[Makefile]
indent_style = tab
"#.to_string())),

        "dependabot" => Ok((".github/dependabot.yml", r#"version: 2
updates:
  - package-ecosystem: "npm"
    directory: "/"
    schedule:
      interval: "weekly"
      day: "monday"
    open-pull-requests-limit: 5

  - package-ecosystem: "cargo"
    directory: "/"
    schedule:
      interval: "weekly"
      day: "monday"
    open-pull-requests-limit: 5

  - package-ecosystem: "pip"
    directory: "/"
    schedule:
      interval: "weekly"
      day: "monday"
    open-pull-requests-limit: 5

  - package-ecosystem: "github-actions"
    directory: "/"
    schedule:
      interval: "weekly"
      day: "monday"
"#.to_string())),

        "codeowners" => Ok((".github/CODEOWNERS", format!(r#"# CODEOWNERS — reviewed on every PR
# https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/about-code-owners

*       @{owner}

# Domain ownership
/src/   @{owner}
/docs/  @{owner}
"#, owner=vars.get("owner").map(|s| s.as_str()).unwrap_or("your-team")))),

        "pr-template" => Ok((".github/pull_request_template.md", r#"## Summary

<!-- What does this PR do? Why? -->

## Changes

-
-

## Test plan

- [ ] Unit tests pass
- [ ] Manual test performed
- [ ] Edge cases considered

## Checklist

- [ ] Code follows project conventions
- [ ] No secrets or credentials included
- [ ] Documentation updated if needed
"#.to_string())),

        "issue-bug" => Ok((".github/ISSUE_TEMPLATE/bug_report.md", r#"---
name: Bug report
about: Report a reproducible bug
title: '[BUG] '
labels: bug
---

## Describe the bug

<!-- A clear and concise description of what the bug is. -->

## Steps to reproduce

1.
2.
3.

## Expected behavior

<!-- What did you expect to happen? -->

## Actual behavior

<!-- What actually happened? -->

## Environment

- OS:
- Version:
- Browser/Runtime:

## Logs / Screenshots

<!-- Paste relevant logs or attach screenshots. -->
"#.to_string())),

        "issue-feature" => Ok((".github/ISSUE_TEMPLATE/feature_request.md", r#"---
name: Feature request
about: Suggest a new feature or improvement
title: '[FEATURE] '
labels: enhancement
---

## Problem

<!-- What problem does this feature solve? -->

## Proposed solution

<!-- Describe the feature you'd like. -->

## Alternatives considered

<!-- Other approaches you considered. -->

## Additional context

<!-- Any other context, mockups, or examples. -->
"#.to_string())),

        _ => Err(format!(
            "template_gen: unknown template '{name}'. Run template_gen(template: 'list') to see all available templates."
        )),
    }
}