8 Commits
Author SHA1 Message Date
Daniel SamsonandClaude Sonnet 5.5 4bb97b80b0 docs: add git skill for agents
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-17 15:37:50 +01:00
daniel 6ca12e6d99 Merge pull request 'docs: move agent instructions to AGENTS.md (CLAUDE.md imports it)' (#70) from chore/agents-md into main 2026-10-17 11:55:35 +00:00
Daniel SamsonandClaude Opus 5.5 b556daedb8 docs: add CLAUDE.md stub that imports AGENTS.md
Claude Code reads CLAUDE.md, so keep a thin stub that pulls in AGENTS.md
via @import. Claude-only notes can go below the import.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 12:53:42 +01:00
Daniel SamsonandClaude Opus 5.5 0f1fd16a58 docs: rename CLAUDE.md to AGENTS.md for cross-agent support
AGENTS.md is the instruction file read by most coding agents (Codex,
Gemini CLI, Cursor, Copilot, etc.), so the guidance now applies to all of
them rather than Claude Code only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 12:53:42 +01:00
Daniel SamsonandClaude Opus 4.6 e0dbbae413 fix(ci): replace HOMEBREW_TAP_TOKEN PAT with GitHub App token
The personal access token expired, causing the v0.3.0 release job to
fail at the homebrew tap checkout step. Switch to a GitHub App
(actions/create-github-app-token) which auto-rotates tokens per run
and has no expiry to manage.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 20:10:01 +00:00
Daniel SamsonandClaude Opus 4.6 215ba3845d Release v0.3.0
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 19:44:39 +00:00
Daniel SamsonandClaude Opus 4.6 b53b4a3287 feat(cli): add retry columns to barn status output
Surface retryCount and retryAt fields in the human table format for
barn status, so retrying jobs are distinguishable from freshly queued
jobs. Also add retryAt to the single job detail view.

- Add RETRIES and NEXT RETRY columns to StatusCommand and HumanFormatter
- Add retryAt display to HumanFormatter single job detail
- Update README and testing-manual docs with new columns
- Add tests for retry display in StatusCommand, HumanFormatter, and XmlFormatter

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 19:40:43 +00:00
Daniel SamsonandClaude Opus 4.5 14bb82fc9d fix(config): add load section to config show and fix env var override
- Add [load] section to `barn config show` output displaying max_high_jobs,
  max_medium_jobs, and max_low_jobs
- Fix bug where BARN_LOADLEVELS_* environment variables were ignored if
  config file had a [load_levels] section
- Bump version to 0.2.1

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-24 16:06:52 +00:00
16 changed files with 1173 additions and 944 deletions

No files matched your search

+75
View File
@@ -0,0 +1,75 @@
---
name: git
description: How to do git in the barn repo — branches, commits, pushing, pull requests and the Gitea remote. Use whenever committing, branching, pushing, rebasing or opening a PR here.
---
# Git in `barn`
Remote: `https://gitea.samson.media/samson-media/barn.git` (Gitea, not GitHub). Default branch: `main`.
## Ground rules
- Pull requests go through **`tea`** (already logged in as `gitea.samson.media`), not `gh` — `gh` can't resolve these repos. Some older docs still show `gh pr create`; translate it:
`tea pulls create --base main --head <branch> --title "..." --description "..."`
- PRs are merged in Gitea with **"Create merge commit"**, which produces `Merge pull request '<title>' (#N) from <branch> into <base>`. Don't squash or rebase-merge unless the user asks.
- Only commit, push or open a PR when the user asked for it. Approval for one push doesn't cover the next.
- Stage specific paths (`git add path/to/file`), never `git add -A` / `git add .` — untracked local dirs such as `.ignore/` (secret mirrors) must never be committed.
- Never commit secrets, `.env` files or credentials.
- Never `git push --force`, `git reset --hard`, `git clean -f` or delete remote branches without the user typing **CONFIRM DESTRUCTIVE ACTION**. If a push is rejected, fetch and rebase; don't force.
- Never `--no-verify` to get past a hook. Fix the cause.
- End commit messages with the attribution trailer your harness specifies (e.g. `Co-Authored-By: ...`).
## Everyday flow
```bash
git status -sb # check branch and ahead/behind first
git fetch origin
git rebase origin/main # or the branch you're on; rebase unpushed work, don't merge it
git add <paths>
git commit -m "<message>"
git push origin <branch> # use -u the first time for a new branch
```
Diverged from the remote (ahead N, behind M)? `git fetch` then `git rebase origin/<branch>`. Rebasing is fine for commits that are not pushed yet; for pushed commits ask first.
## Branches
Default branch `main`. Work on a branch (`feat/...`, `fix/...`, `chore/...`, `docs/...`), PR into `main`, merge with a merge commit. Releases are cut with a `Release vX.Y.Z` commit (see `release.yml`) — never tag or bump versions unless asked.
```bash
git checkout main && git pull origin main
git checkout -b feat/retry-columns
# ...work...
mvn verify # must pass before every commit
git add <paths>
git commit -m "feat(cli): add retry columns to barn status output"
git push -u origin feat/retry-columns
tea pulls create --base main --head feat/retry-columns --title "feat(cli): ..." --description "..."
```
## Commit messages — Conventional Commits
`type(scope): description`, lower-case, imperative. Types: `feat`, `fix`, `docs`, `test`, `refactor`, `chore`, `ci`; breaking changes get `!`. Examples from history:
```
feat(cli): add retry columns to barn status output
fix(config): add load section to config show and fix env var override
fix(ci): replace HOMEBREW_TAP_TOKEN PAT with GitHub App token
chore: bump version to 0.2.0
```
If there is a tracking issue, mention it in the body (`Refs #N`).
## Pre-commit hook
`.githooks/pre-commit` runs quality checks on staged `.java` files. Enable it once per clone:
```bash
git config core.hooksPath .githooks
```
If it fails, fix the problem and commit again — don't `--no-verify`. See the Commit Checklist in `AGENTS.md`.
## After pushing
Update this repo's pointer in the parent `development` repo (see the root git skill).
+1
View File
@@ -0,0 +1 @@
../.agents/skills
+10 -1
View File
@@ -128,11 +128,20 @@ jobs:
echo "linux_arm64_sha=$(grep barn-linux-arm64 SHA256SUMS | awk '{print $1}')" >> $GITHUB_OUTPUT echo "linux_arm64_sha=$(grep barn-linux-arm64 SHA256SUMS | awk '{print $1}')" >> $GITHUB_OUTPUT
echo "linux_x64_sha=$(grep barn-linux-x64 SHA256SUMS | awk '{print $1}')" >> $GITHUB_OUTPUT echo "linux_x64_sha=$(grep barn-linux-x64 SHA256SUMS | awk '{print $1}')" >> $GITHUB_OUTPUT
- name: Generate Homebrew tap token
uses: actions/create-github-app-token@v2
id: homebrew-token
with:
app-id: ${{ vars.HOMEBREW_APP_ID }}
private-key: ${{ secrets.HOMEBREW_APP_PRIVATE_KEY }}
owner: samson-media
repositories: homebrew-tap
- name: Checkout homebrew tap - name: Checkout homebrew tap
uses: actions/checkout@v4 uses: actions/checkout@v4
with: with:
repository: samson-media/homebrew-tap repository: samson-media/homebrew-tap
token: ${{ secrets.HOMEBREW_TAP_TOKEN }} token: ${{ steps.homebrew-token.outputs.token }}
path: homebrew-tap path: homebrew-tap
- name: Update Homebrew formula - name: Update Homebrew formula
+929
View File
@@ -0,0 +1,929 @@
# Agent Instructions for Barn
> **FIRST STEP - MANDATORY**: Before writing ANY code, read these files:
> 1. `README.md` - Project overview
> 2. `docs/coding-standards.md` - Code style and conventions
> 3. `docs/jobs.md` - Filesystem state layout
> 4. `docs/config.md` - Configuration options
---
## Ticket Implementation Process (MANDATORY)
When assigned a GitHub issue/ticket, follow this **exact process**. Do NOT skip steps.
### Phase 1: READ (Do Not Write Any Code Yet)
```
┌─────────────────────────────────────────────────────────────┐
│ STOP! Read everything before writing a single line of code │
└─────────────────────────────────────────────────────────────┘
```
**Step 1.1: Fetch and Read the Ticket**
```bash
gh issue view <issue-number>
```
Read the ENTIRE ticket including:
- Overview and Context
- Requirements (every numbered item)
- Acceptance Criteria (every checkbox)
- Implementation Notes
- Tests Required
**Step 1.2: Check Dependencies**
```bash
# List dependency issues
gh issue view <issue-number> --json body | grep -o '#[0-9]*'
# Check if dependencies are closed
gh issue view <dep-number> --json state
```
If dependencies are NOT closed: **STOP**. Work on dependencies first or inform the user.
**Step 1.3: Read Referenced Documentation**
The ticket's "Context" section lists docs to read. Read ALL of them:
```bash
# Example: if ticket says "Read first: docs/jobs.md"
cat docs/jobs.md
```
**Step 1.4: Read Related Existing Code**
If the ticket depends on other issues, read the code they produced:
```bash
# Find relevant files
find src -name "*.java" | xargs grep -l "RelatedClass"
```
### Phase 2: PLAN (Still No Implementation Code)
**Step 2.1: List All Deliverables**
Extract from the ticket:
- [ ] Classes/files to create
- [ ] Methods to implement
- [ ] Tests to write
- [ ] Acceptance criteria to satisfy
**Step 2.2: Identify Test Cases**
From the "Tests Required" section, list every test:
```
Example:
- JobManagerTest.java
- createJob_withValidCommand_shouldReturnJobWithUniqueId
- createJob_withNullCommand_shouldThrowNullPointerException
- findJob_withExistingId_shouldReturnJob
- findJob_withMissingId_shouldReturnEmpty
```
### Phase 3: TEST (Write Tests FIRST)
```
┌─────────────────────────────────────────────────────────┐
│ Write ALL tests before writing ANY implementation code │
└─────────────────────────────────────────────────────────┘
```
**Step 3.1: Create Test File**
```java
// src/test/java/com/samsonmedia/barn/<package>/<Class>Test.java
class JobManagerTest {
@Test
void methodName_condition_expectedResult() {
// Arrange
// Act
// Assert - use AssertJ
}
}
```
**Step 3.2: Write ALL Test Cases**
Write tests for:
1. Happy path (normal success)
2. Edge cases (empty, boundary values)
3. Error cases (null, invalid state)
4. Every acceptance criterion
**Step 3.3: Run Tests (Must FAIL)**
```bash
mvn test -Dtest=<TestClass>
# Expected: FAILURE (code not implemented yet)
```
If tests pass before implementation, the tests are wrong.
### Phase 4: IMPLEMENT (Now Write Code)
**Step 4.1: Implement Minimum Code**
Write the minimum code to make ONE test pass at a time:
```bash
# After each small change
mvn test -Dtest=<TestClass>#<testMethod>
```
**Step 4.2: Follow Coding Standards**
Every file must:
- Have no wildcard imports
- Use `Optional<T>` not null returns
- Use `Objects.requireNonNull()` for parameters
- Use `final` for immutable fields
- Have proper Javadoc on public methods
**Step 4.3: Iterate Until All Tests Pass**
```bash
mvn test -Dtest=<TestClass>
# Expected: SUCCESS for all tests
```
### Phase 5: VERIFY (Full Quality Check)
**Step 5.1: Run Full Verification**
```bash
mvn verify
```
This MUST pass:
- ✓ Checkstyle (formatting)
- ✓ Compilation (no warnings)
- ✓ All unit tests
- ✓ SpotBugs (no bugs)
- ✓ PMD (no violations)
- ✓ JaCoCo (80%+ coverage)
**Step 5.2: Check Acceptance Criteria**
Go through EVERY checkbox in the ticket:
```
- [ ] Criterion 1 → Verify manually or with test
- [ ] Criterion 2 → Verify manually or with test
...
```
**Step 5.3: Fix Any Issues**
If `mvn verify` fails:
1. Read the error message
2. Fix the issue
3. Run `mvn verify` again
4. Repeat until clean
### Phase 6: COMPLETE (Commit and Close)
**Step 6.1: Commit with Conventional Message**
```bash
git add .
git commit -m "feat(<scope>): <description>
Implements #<issue-number>
- Added <component>
- Implemented <feature>
- Tests for <functionality>
Co-Authored-By: <your agent's attribution line, if any>"
```
**Step 6.2: Verify Commit**
```bash
# Ensure nothing is missed
git status
mvn verify # Run one final time
```
**Step 6.3: Close the Ticket**
```bash
gh issue close <issue-number> --comment "Implemented in commit <sha>"
```
---
## Ticket Process Checklist
Copy this checklist for each ticket:
```markdown
## Ticket #XX: <Title>
### Phase 1: READ
- [ ] Fetched ticket with `gh issue view`
- [ ] Read entire ticket description
- [ ] Checked all dependencies are closed
- [ ] Read all referenced documentation
- [ ] Read related existing code
### Phase 2: PLAN
- [ ] Listed all classes/files to create
- [ ] Listed all methods to implement
- [ ] Listed all test cases from ticket
### Phase 3: TEST
- [ ] Created test file(s)
- [ ] Wrote all test cases
- [ ] Tests fail (code not implemented)
### Phase 4: IMPLEMENT
- [ ] Implemented code to pass tests
- [ ] All tests pass
- [ ] Followed coding standards
### Phase 5: VERIFY
- [ ] `mvn verify` passes
- [ ] All acceptance criteria checked
- [ ] No TODO/FIXME without issue
### Phase 6: COMPLETE
- [ ] Committed with conventional message
- [ ] Closed ticket with `gh issue close`
```
---
## Critical Requirements
### 1. ALWAYS Write Tests First
**Every code change MUST include automated tests.** No exceptions.
```
Code without tests = Incomplete work
```
Before implementing any feature or fix:
1. Write failing tests that define the expected behavior
2. Implement the code to make tests pass
3. Run `mvn verify` to ensure all checks pass
4. Only then consider the work complete
### 2. ALWAYS Validate with Tests
After writing code, ALWAYS run:
```bash
mvn verify
```
This runs:
- Compilation with `-Werror` (warnings are errors)
- Checkstyle (code formatting)
- Unit tests
- SpotBugs (bug detection)
- PMD (static analysis)
- JaCoCo (coverage check - must be 80%+)
**Do NOT consider code complete until `mvn verify` passes.**
### 3. ALWAYS Follow Coding Standards
Read `docs/coding-standards.md` before writing code. Key rules:
- 4 spaces indentation, 120 char line limit
- No wildcard imports
- Use `Optional<T>` instead of returning `null`
- Use `Objects.requireNonNull()` for constructor params
- Use `final` for fields that don't change
---
## Project Overview
Barn is a cross-platform job daemon for managing long-running media processing tasks (FFmpeg, WebDAV transfers). It runs as an OS service on Windows, macOS, and Linux.
## Technology Stack
- **Language**: Java 21+
- **Build**: Maven
- **Native Image**: GraalVM Native Image
- **Code Style**: Checkstyle (Google Java Style)
- **Static Analysis**: SpotBugs, PMD
- **Testing**: JUnit 5, Mockito, AssertJ
- **Coverage**: JaCoCo (80% minimum)
---
## Testing Requirements (MANDATORY)
### Test Coverage Requirements
| Type | Minimum | Target |
|------|---------|--------|
| Line coverage | 80% | 90%+ |
| Branch coverage | 70% | 80%+ |
| New code | 100% | 100% |
### Test Naming Convention
```java
// Pattern: methodName_condition_expectedResult
@Test
void createJob_withValidCommand_shouldReturnJobWithUniqueId() { }
@Test
void createJob_withNullCommand_shouldThrowNullPointerException() { }
@Test
void processJob_whenServiceNotRunning_shouldThrowIllegalStateException() { }
```
### Test Structure (AAA Pattern)
```java
@Test
void findJob_withExistingId_shouldReturnJob() {
// Arrange
var manager = new JobManager(testConfig);
var job = manager.createJob(new Command("echo", "test"));
// Act
var result = manager.findJob(job.getId());
// Assert
assertThat(result).isPresent();
assertThat(result.get().getId()).isEqualTo(job.getId());
}
```
### What to Test
For EVERY class you create or modify:
1. **Happy path** - Normal successful operation
2. **Edge cases** - Empty inputs, boundary values
3. **Error cases** - Null inputs, invalid states
4. **Integration** - Component interactions
### Test File Location
```
src/
main/java/com/samsonmedia/barn/
jobs/
JobManager.java
test/java/com/samsonmedia/barn/
jobs/
JobManagerTest.java # Unit tests
JobManagerIT.java # Integration tests
```
### Running Tests
```bash
# Run all tests
mvn test
# Run specific test class
mvn test -Dtest=JobManagerTest
# Run with coverage report
mvn test jacoco:report
# View: target/site/jacoco/index.html
# Run full verification (ALWAYS do this before committing)
mvn verify
```
---
## Workflow for Every Code Change
### Step 1: Understand the Requirement
- Read relevant docs
- Understand existing code patterns
### Step 2: Write Tests FIRST
```java
// Write test that defines expected behavior
@Test
void newFeature_shouldDoExpectedThing() {
// Arrange
var component = new Component();
// Act
var result = component.newFeature();
// Assert
assertThat(result).isEqualTo(expected);
}
```
### Step 3: Run Tests (Should Fail)
```bash
mvn test -Dtest=ComponentTest#newFeature_shouldDoExpectedThing
# Expected: FAILURE (test written, code not yet implemented)
```
### Step 4: Implement the Code
Write minimal code to make the test pass.
### Step 5: Run Tests (Should Pass)
```bash
mvn test -Dtest=ComponentTest#newFeature_shouldDoExpectedThing
# Expected: SUCCESS
```
### Step 6: Run Full Verification
```bash
mvn verify
# Must pass ALL checks:
# - Checkstyle
# - Compilation
# - All tests
# - SpotBugs
# - PMD
# - Coverage thresholds
```
### Step 7: Only THEN Consider Complete
If `mvn verify` fails, fix the issues and repeat.
---
## Code Standards Summary
### Formatting
- 4 spaces indentation (no tabs)
- 120 character line limit
- K&R brace style (opening brace on same line)
- Static imports first, then regular imports, alphabetically
### Naming
- Packages: `lowercase`
- Classes/Interfaces: `PascalCase`
- Methods/Variables: `camelCase`
- Constants: `SCREAMING_SNAKE_CASE`
### Java Idioms
```java
// Use final for immutable fields
private final Config config;
// Use Optional for nullable returns
public Optional<Job> findJob(String id) {
return Optional.ofNullable(jobs.get(id));
}
// Validate constructor params
public JobManager(Config config) {
this.config = Objects.requireNonNull(config, "config must not be null");
}
// Use records for value objects
public record Job(String id, JobState state, Instant createdAt) {}
// Use switch expressions
String status = switch (state) {
case QUEUED -> "Waiting";
case RUNNING -> "Executing";
case FAILED -> "Failed";
case SUCCEEDED -> "Done";
};
```
### Error Handling
```java
// Use Optional, not null
public Optional<Job> findJob(String id);
// Validate preconditions
public void processJob(Job job) {
Objects.requireNonNull(job, "job");
if (job.getState() != JobState.QUEUED) {
throw new IllegalStateException("Job must be QUEUED");
}
}
// Create domain exceptions
public class JobNotFoundException extends RuntimeException {
public JobNotFoundException(String jobId) {
super("Job not found: " + jobId);
}
}
```
---
## Architecture Principles
### Filesystem as Database
- Job state stored in `/tmp/barn/jobs/<job-id>/`
- Use atomic file operations
- Human-readable plain text files
- No external database dependencies
### Cross-Platform
- Use `System.getProperty("java.io.tmpdir")` for temp paths
- Avoid platform-specific commands
- Test on Windows, macOS, and Linux
### GraalVM Native Image
- Avoid reflection where possible
- Register any reflection in `reflect-config.json`
---
## File Structure
```
barn/
src/
main/java/com/samsonmedia/barn/
Main.java # Entry point
cli/ # CLI commands (picocli)
config/ # Configuration parsing
jobs/ # Job management
service/ # Daemon/service logic
state/ # Filesystem state management
test/java/com/samsonmedia/barn/
# Mirror structure with Test suffix
config/
checkstyle/ # Checkstyle rules
spotbugs/ # SpotBugs exclusions
pmd/ # PMD ruleset
docs/ # Documentation
pom.xml # Maven build
```
---
## Commit Checklist
Before EVERY commit:
- [ ] Tests written for new/changed code
- [ ] `mvn verify` passes
- [ ] No `TODO` or `FIXME` without tracking issue
- [ ] Javadoc for public API
- [ ] Commit message follows Conventional Commits format
```bash
# Commit message format
feat(jobs): add retry mechanism for failed jobs
fix(cli): handle spaces in file paths
test(jobs): add integration tests for job lifecycle
```
---
## What NOT to Do
- **Don't skip tests** - Every change needs tests
- **Don't commit without `mvn verify`** - Ensures all checks pass
- **Don't return `null`** - Use `Optional<T>` instead
- **Don't catch `Exception`** - Catch specific exceptions
- **Don't use `System.out.println`** - Use SLF4J logging
- **Don't use wildcard imports** - Import specific classes
- **Don't use raw types** - Always specify generics
- **Don't ignore warnings** - Fix them (they're errors with `-Werror`)
---
## Quick Reference
```bash
# Build
mvn package
# Test
mvn test
# Full verification (ALWAYS before commit)
mvn verify
# Coverage report
mvn test jacoco:report
# Fast build (skip checks - use sparingly)
mvn package -Pfast
# Specific test
mvn test -Dtest=JobManagerTest
# View SpotBugs in GUI
mvn compile spotbugs:gui
```
---
## Pre-Release Testing Checklist (MANDATORY)
Before creating ANY release tag, you MUST test ALL subcommands with the native binary locally.
### Prerequisites
1. **Build the native image locally:**
```bash
export JAVA_HOME="/Library/Java/JavaVirtualMachines/graalvm-25.jdk/Contents/Home"
mvn package -Pnative -DskipTests -Dspotbugs.skip=true -Dpmd.skip=true -Dcheckstyle.skip=true -Djacoco.skip=true
```
2. **Verify the binary exists:**
```bash
ls -la target/barn
```
### Test Every Subcommand
Run each command and verify the expected output. **Do NOT skip any command.**
#### Basic Commands
```bash
# Should show usage/help
./target/barn
# Expected: Shows "Usage: barn [-hV] [COMMAND]" and lists all subcommands
./target/barn --help
# Expected: Same as above
./target/barn --version
# Expected: Shows "barn X.Y.Z"
```
#### Service Commands (Start service first)
```bash
# Stop any existing service
./target/barn service stop 2>/dev/null || true
# Start the service
./target/barn service start
# Expected: "Barn service started (PID: XXXXX)"
# Check service status
./target/barn service status
# Expected: Shows "Status: running", PID, uptime, job counts
# Test reload (reloads config without restart)
./target/barn service reload
# Expected: "Configuration reloaded"
# View logs
./target/barn service logs
# Expected: Shows recent log entries or "No logs found"
# Restart the service
./target/barn service restart
# Expected: "Barn service restarted"
```
#### Job Commands (Service must be running)
```bash
# Run a test job
./target/barn run -- echo "test from native binary"
# Expected: "Job created: job-XXXXXXXX" with state: queued
# Wait a moment, then check status
sleep 2
./target/barn status
# Expected: Shows table with jobs, including the new job as "succeeded"
# Get the job ID from status output, then describe it
./target/barn describe <job-id>
# Expected: Shows detailed job info including timestamps, exit code, files
# Check resource usage
./target/barn usage <job-id>
# Expected: Shows CPU/memory/disk usage samples
# Test kill on a non-running job (should fail gracefully)
./target/barn kill <job-id>
# Expected: "Error: Job is not running: SUCCEEDED"
# Clean with dry-run
./target/barn clean --dry-run
# Expected: "Would clean X jobs:" followed by list
```
#### Config Commands
```bash
./target/barn config show
# Expected: Shows configuration with all sections (service, jobs, cleanup, storage)
```
#### Autocompletion Commands
```bash
./target/barn autocompletion --bash | head -5
# Expected: Shows bash completion script starting with "#!/usr/bin/env bash"
./target/barn autocompletion --zsh | head -5
# Expected: Shows zsh completion script
```
#### Service Stop (Clean up)
```bash
./target/barn service stop
# Expected: "Barn service stopped"
./target/barn service status
# Expected: "Barn service is not running"
```
### Checklist Summary
Copy this checklist and verify each item:
```markdown
## Pre-Release Testing for vX.Y.Z
### Build
- [ ] Native image builds successfully
- [ ] Binary exists at target/barn
### Basic Commands
- [ ] `barn` shows help
- [ ] `barn --help` shows help
- [ ] `barn --version` shows correct version
### Service Commands
- [ ] `barn service start` starts the service
- [ ] `barn service status` shows running status
- [ ] `barn service reload` reloads config
- [ ] `barn service logs` shows logs
- [ ] `barn service restart` restarts cleanly
- [ ] `barn service stop` stops the service
### Job Commands (with service running)
- [ ] `barn run -- echo test` creates a job
- [ ] `barn status` shows job list
- [ ] `barn describe <id>` shows job details
- [ ] `barn usage <id>` shows resource usage
- [ ] `barn kill <id>` handles non-running job gracefully
- [ ] `barn clean --dry-run` shows what would be cleaned
### Config Commands
- [ ] `barn config show` displays configuration
### Autocompletion
- [ ] `barn autocompletion --bash` generates bash script
- [ ] `barn autocompletion --zsh` generates zsh script
### Final
- [ ] All commands return expected output
- [ ] No crashes or exceptions
- [ ] Service starts and stops cleanly
```
### Only After All Tests Pass
1. Commit any fixes
2. Push to main
3. Wait for CI to pass
4. Create the release tag: `git tag vX.Y.Z && git push origin vX.Y.Z`
**NEVER create a release tag without completing this checklist.**
---
## Questions to Ask Before Implementing
1. Have I read the relevant documentation?
2. Have I written tests that define the expected behavior?
3. Does this work on Windows, macOS, AND Linux?
4. Will this survive a crash/restart?
5. Can the state be manually inspected in the filesystem?
6. Does `mvn verify` pass?
---
## Working with GitHub Issues
### Viewing the Backlog
```bash
# List all open issues
gh issue list
# List issues by milestone
gh issue list --milestone "M1: Foundation"
# List issues by label
gh issue list --label "foundation"
# View specific issue
gh issue view 1
```
### Dependency Graph
Issues must be completed in dependency order. The milestones define the general order:
```
M1: Foundation (#1, #2, #3, #4, #22)
↓
M2: Job Execution (#5, #6, #7, #20)
↓
M3: CLI Commands (#8, #9, #10, #11, #12, #13, #21)
↓
M4: Service Infrastructure (#14, #15, #16)
↓
M5: Platform Integration (#17, #18, #19)
```
**Recommended order within M1:**
```
#1 (project structure)
→ #22 (logging)
→ #2 (configuration)
→ #3 (filesystem state)
→ #4 (job model)
```
### Starting a New Ticket
```bash
# 1. Check what's ready to work on (no open dependencies)
gh issue list --milestone "M1: Foundation" --state open
# 2. Pick the next ticket with closed dependencies
gh issue view 1
# 3. Follow the Ticket Implementation Process above
```
### Progress Tracking
After completing a ticket:
```bash
# Close with comment
gh issue close <number> --comment "Implemented in commit abc123"
# Verify milestone progress
gh issue list --milestone "M1: Foundation"
```
---
## Emergency Procedures
### If `mvn verify` Fails
1. **Read the error** - Don't guess, read the actual message
2. **Identify the phase** - Checkstyle? Compile? Test? SpotBugs? PMD? JaCoCo?
3. **Fix incrementally** - Run just that check until it passes:
```bash
mvn checkstyle:check # Formatting issues
mvn compile # Compilation errors
mvn test # Test failures
mvn spotbugs:check # Bug detection
mvn pmd:check # Static analysis
mvn jacoco:check # Coverage issues
```
4. **Run full verify again** - `mvn verify`
### If Tests Won't Pass
1. **Check the test is correct** - Is the expected behavior right?
2. **Check dependencies** - Is required code from other tickets present?
3. **Check test isolation** - Does the test depend on external state?
4. **Run single test** - `mvn test -Dtest=ClassName#methodName`
### If Stuck on a Ticket
1. **Re-read the ticket** - Often the answer is in the description
2. **Check Implementation Notes** - Specific guidance is provided
3. **Check referenced docs** - Context section lists what to read
4. **Look at similar code** - How did other tickets solve similar problems?
---
## Ticket Template Reference
Every ticket follows this structure:
```markdown
## Overview
Brief description of what to implement.
## Context
- **Read first**: docs to read before starting
- **Depends on**: prerequisite tickets
## Requirements
### 1. Component Name
Detailed requirements with code examples.
### 2. Another Component
More requirements...
## Tests Required
- TestClass1.java: description
- TestClass2.java: description
## Acceptance Criteria
- [ ] Criterion 1
- [ ] Criterion 2
- [ ] `mvn verify` passes
- [ ] Tests have 80%+ coverage
## Implementation Notes
Specific guidance, code patterns, edge cases.
## Definition of Done
Summary of completion requirements.
```
Use this structure to know exactly what's expected.
+8
View File
@@ -5,6 +5,13 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/), The format is based on [Keep a Changelog](https://keepachangelog.com/),
and this project adheres to [Semantic Versioning](https://semver.org/). and this project adheres to [Semantic Versioning](https://semver.org/).
## [0.3.0] - 2026-03-03
### Added
- RETRIES and NEXT RETRY columns in `barn status` human table output
- Retry At field in single job detail view (`barn describe`)
- Retry display tests for human, JSON, and XML output formats
## [0.1.7] - 2026-01-22 ## [0.1.7] - 2026-01-22
### Fixed ### Fixed
@@ -67,6 +74,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/).
- Jobs that fail to start now properly transition to FAILED state - Jobs that fail to start now properly transition to FAILED state
- Startup errors are written to stderr.log for visibility - Startup errors are written to stderr.log for visibility
[0.3.0]: https://github.com/samson-media/barn/releases/tag/v0.3.0
[0.1.7]: https://github.com/samson-media/barn/releases/tag/v0.1.7 [0.1.7]: https://github.com/samson-media/barn/releases/tag/v0.1.7
[0.1.6]: https://github.com/samson-media/barn/releases/tag/v0.1.6 [0.1.6]: https://github.com/samson-media/barn/releases/tag/v0.1.6
[0.1.5]: https://github.com/samson-media/barn/releases/tag/v0.1.5 [0.1.5]: https://github.com/samson-media/barn/releases/tag/v0.1.5
+5 -927
View File
@@ -1,929 +1,7 @@
# Claude AI Instructions for Barn # CLAUDE.md
> **FIRST STEP - MANDATORY**: Before writing ANY code, read these files: Agent instructions for this repository live in [AGENTS.md](AGENTS.md) so they are
> 1. `README.md` - Project overview shared across coding agents (Claude Code, Codex, Gemini CLI, Cursor, etc.).
> 2. `docs/coding-standards.md` - Code style and conventions Claude Code loads them via the import below; add Claude-only notes underneath.
> 3. `docs/jobs.md` - Filesystem state layout
> 4. `docs/config.md` - Configuration options
--- @AGENTS.md
## Ticket Implementation Process (MANDATORY)
When assigned a GitHub issue/ticket, follow this **exact process**. Do NOT skip steps.
### Phase 1: READ (Do Not Write Any Code Yet)
```
┌─────────────────────────────────────────────────────────────┐
│ STOP! Read everything before writing a single line of code │
└─────────────────────────────────────────────────────────────┘
```
**Step 1.1: Fetch and Read the Ticket**
```bash
gh issue view <issue-number>
```
Read the ENTIRE ticket including:
- Overview and Context
- Requirements (every numbered item)
- Acceptance Criteria (every checkbox)
- Implementation Notes
- Tests Required
**Step 1.2: Check Dependencies**
```bash
# List dependency issues
gh issue view <issue-number> --json body | grep -o '#[0-9]*'
# Check if dependencies are closed
gh issue view <dep-number> --json state
```
If dependencies are NOT closed: **STOP**. Work on dependencies first or inform the user.
**Step 1.3: Read Referenced Documentation**
The ticket's "Context" section lists docs to read. Read ALL of them:
```bash
# Example: if ticket says "Read first: docs/jobs.md"
cat docs/jobs.md
```
**Step 1.4: Read Related Existing Code**
If the ticket depends on other issues, read the code they produced:
```bash
# Find relevant files
find src -name "*.java" | xargs grep -l "RelatedClass"
```
### Phase 2: PLAN (Still No Implementation Code)
**Step 2.1: List All Deliverables**
Extract from the ticket:
- [ ] Classes/files to create
- [ ] Methods to implement
- [ ] Tests to write
- [ ] Acceptance criteria to satisfy
**Step 2.2: Identify Test Cases**
From the "Tests Required" section, list every test:
```
Example:
- JobManagerTest.java
- createJob_withValidCommand_shouldReturnJobWithUniqueId
- createJob_withNullCommand_shouldThrowNullPointerException
- findJob_withExistingId_shouldReturnJob
- findJob_withMissingId_shouldReturnEmpty
```
### Phase 3: TEST (Write Tests FIRST)
```
┌─────────────────────────────────────────────────────────┐
│ Write ALL tests before writing ANY implementation code │
└─────────────────────────────────────────────────────────┘
```
**Step 3.1: Create Test File**
```java
// src/test/java/com/samsonmedia/barn/<package>/<Class>Test.java
class JobManagerTest {
@Test
void methodName_condition_expectedResult() {
// Arrange
// Act
// Assert - use AssertJ
}
}
```
**Step 3.2: Write ALL Test Cases**
Write tests for:
1. Happy path (normal success)
2. Edge cases (empty, boundary values)
3. Error cases (null, invalid state)
4. Every acceptance criterion
**Step 3.3: Run Tests (Must FAIL)**
```bash
mvn test -Dtest=<TestClass>
# Expected: FAILURE (code not implemented yet)
```
If tests pass before implementation, the tests are wrong.
### Phase 4: IMPLEMENT (Now Write Code)
**Step 4.1: Implement Minimum Code**
Write the minimum code to make ONE test pass at a time:
```bash
# After each small change
mvn test -Dtest=<TestClass>#<testMethod>
```
**Step 4.2: Follow Coding Standards**
Every file must:
- Have no wildcard imports
- Use `Optional<T>` not null returns
- Use `Objects.requireNonNull()` for parameters
- Use `final` for immutable fields
- Have proper Javadoc on public methods
**Step 4.3: Iterate Until All Tests Pass**
```bash
mvn test -Dtest=<TestClass>
# Expected: SUCCESS for all tests
```
### Phase 5: VERIFY (Full Quality Check)
**Step 5.1: Run Full Verification**
```bash
mvn verify
```
This MUST pass:
- ✓ Checkstyle (formatting)
- ✓ Compilation (no warnings)
- ✓ All unit tests
- ✓ SpotBugs (no bugs)
- ✓ PMD (no violations)
- ✓ JaCoCo (80%+ coverage)
**Step 5.2: Check Acceptance Criteria**
Go through EVERY checkbox in the ticket:
```
- [ ] Criterion 1 → Verify manually or with test
- [ ] Criterion 2 → Verify manually or with test
...
```
**Step 5.3: Fix Any Issues**
If `mvn verify` fails:
1. Read the error message
2. Fix the issue
3. Run `mvn verify` again
4. Repeat until clean
### Phase 6: COMPLETE (Commit and Close)
**Step 6.1: Commit with Conventional Message**
```bash
git add .
git commit -m "feat(<scope>): <description>
Implements #<issue-number>
- Added <component>
- Implemented <feature>
- Tests for <functionality>
Co-Authored-By: Claude <noreply@anthropic.com>"
```
**Step 6.2: Verify Commit**
```bash
# Ensure nothing is missed
git status
mvn verify # Run one final time
```
**Step 6.3: Close the Ticket**
```bash
gh issue close <issue-number> --comment "Implemented in commit <sha>"
```
---
## Ticket Process Checklist
Copy this checklist for each ticket:
```markdown
## Ticket #XX: <Title>
### Phase 1: READ
- [ ] Fetched ticket with `gh issue view`
- [ ] Read entire ticket description
- [ ] Checked all dependencies are closed
- [ ] Read all referenced documentation
- [ ] Read related existing code
### Phase 2: PLAN
- [ ] Listed all classes/files to create
- [ ] Listed all methods to implement
- [ ] Listed all test cases from ticket
### Phase 3: TEST
- [ ] Created test file(s)
- [ ] Wrote all test cases
- [ ] Tests fail (code not implemented)
### Phase 4: IMPLEMENT
- [ ] Implemented code to pass tests
- [ ] All tests pass
- [ ] Followed coding standards
### Phase 5: VERIFY
- [ ] `mvn verify` passes
- [ ] All acceptance criteria checked
- [ ] No TODO/FIXME without issue
### Phase 6: COMPLETE
- [ ] Committed with conventional message
- [ ] Closed ticket with `gh issue close`
```
---
## Critical Requirements
### 1. ALWAYS Write Tests First
**Every code change MUST include automated tests.** No exceptions.
```
Code without tests = Incomplete work
```
Before implementing any feature or fix:
1. Write failing tests that define the expected behavior
2. Implement the code to make tests pass
3. Run `mvn verify` to ensure all checks pass
4. Only then consider the work complete
### 2. ALWAYS Validate with Tests
After writing code, ALWAYS run:
```bash
mvn verify
```
This runs:
- Compilation with `-Werror` (warnings are errors)
- Checkstyle (code formatting)
- Unit tests
- SpotBugs (bug detection)
- PMD (static analysis)
- JaCoCo (coverage check - must be 80%+)
**Do NOT consider code complete until `mvn verify` passes.**
### 3. ALWAYS Follow Coding Standards
Read `docs/coding-standards.md` before writing code. Key rules:
- 4 spaces indentation, 120 char line limit
- No wildcard imports
- Use `Optional<T>` instead of returning `null`
- Use `Objects.requireNonNull()` for constructor params
- Use `final` for fields that don't change
---
## Project Overview
Barn is a cross-platform job daemon for managing long-running media processing tasks (FFmpeg, WebDAV transfers). It runs as an OS service on Windows, macOS, and Linux.
## Technology Stack
- **Language**: Java 21+
- **Build**: Maven
- **Native Image**: GraalVM Native Image
- **Code Style**: Checkstyle (Google Java Style)
- **Static Analysis**: SpotBugs, PMD
- **Testing**: JUnit 5, Mockito, AssertJ
- **Coverage**: JaCoCo (80% minimum)
---
## Testing Requirements (MANDATORY)
### Test Coverage Requirements
| Type | Minimum | Target |
|------|---------|--------|
| Line coverage | 80% | 90%+ |
| Branch coverage | 70% | 80%+ |
| New code | 100% | 100% |
### Test Naming Convention
```java
// Pattern: methodName_condition_expectedResult
@Test
void createJob_withValidCommand_shouldReturnJobWithUniqueId() { }
@Test
void createJob_withNullCommand_shouldThrowNullPointerException() { }
@Test
void processJob_whenServiceNotRunning_shouldThrowIllegalStateException() { }
```
### Test Structure (AAA Pattern)
```java
@Test
void findJob_withExistingId_shouldReturnJob() {
// Arrange
var manager = new JobManager(testConfig);
var job = manager.createJob(new Command("echo", "test"));
// Act
var result = manager.findJob(job.getId());
// Assert
assertThat(result).isPresent();
assertThat(result.get().getId()).isEqualTo(job.getId());
}
```
### What to Test
For EVERY class you create or modify:
1. **Happy path** - Normal successful operation
2. **Edge cases** - Empty inputs, boundary values
3. **Error cases** - Null inputs, invalid states
4. **Integration** - Component interactions
### Test File Location
```
src/
main/java/com/samsonmedia/barn/
jobs/
JobManager.java
test/java/com/samsonmedia/barn/
jobs/
JobManagerTest.java # Unit tests
JobManagerIT.java # Integration tests
```
### Running Tests
```bash
# Run all tests
mvn test
# Run specific test class
mvn test -Dtest=JobManagerTest
# Run with coverage report
mvn test jacoco:report
# View: target/site/jacoco/index.html
# Run full verification (ALWAYS do this before committing)
mvn verify
```
---
## Workflow for Every Code Change
### Step 1: Understand the Requirement
- Read relevant docs
- Understand existing code patterns
### Step 2: Write Tests FIRST
```java
// Write test that defines expected behavior
@Test
void newFeature_shouldDoExpectedThing() {
// Arrange
var component = new Component();
// Act
var result = component.newFeature();
// Assert
assertThat(result).isEqualTo(expected);
}
```
### Step 3: Run Tests (Should Fail)
```bash
mvn test -Dtest=ComponentTest#newFeature_shouldDoExpectedThing
# Expected: FAILURE (test written, code not yet implemented)
```
### Step 4: Implement the Code
Write minimal code to make the test pass.
### Step 5: Run Tests (Should Pass)
```bash
mvn test -Dtest=ComponentTest#newFeature_shouldDoExpectedThing
# Expected: SUCCESS
```
### Step 6: Run Full Verification
```bash
mvn verify
# Must pass ALL checks:
# - Checkstyle
# - Compilation
# - All tests
# - SpotBugs
# - PMD
# - Coverage thresholds
```
### Step 7: Only THEN Consider Complete
If `mvn verify` fails, fix the issues and repeat.
---
## Code Standards Summary
### Formatting
- 4 spaces indentation (no tabs)
- 120 character line limit
- K&R brace style (opening brace on same line)
- Static imports first, then regular imports, alphabetically
### Naming
- Packages: `lowercase`
- Classes/Interfaces: `PascalCase`
- Methods/Variables: `camelCase`
- Constants: `SCREAMING_SNAKE_CASE`
### Java Idioms
```java
// Use final for immutable fields
private final Config config;
// Use Optional for nullable returns
public Optional<Job> findJob(String id) {
return Optional.ofNullable(jobs.get(id));
}
// Validate constructor params
public JobManager(Config config) {
this.config = Objects.requireNonNull(config, "config must not be null");
}
// Use records for value objects
public record Job(String id, JobState state, Instant createdAt) {}
// Use switch expressions
String status = switch (state) {
case QUEUED -> "Waiting";
case RUNNING -> "Executing";
case FAILED -> "Failed";
case SUCCEEDED -> "Done";
};
```
### Error Handling
```java
// Use Optional, not null
public Optional<Job> findJob(String id);
// Validate preconditions
public void processJob(Job job) {
Objects.requireNonNull(job, "job");
if (job.getState() != JobState.QUEUED) {
throw new IllegalStateException("Job must be QUEUED");
}
}
// Create domain exceptions
public class JobNotFoundException extends RuntimeException {
public JobNotFoundException(String jobId) {
super("Job not found: " + jobId);
}
}
```
---
## Architecture Principles
### Filesystem as Database
- Job state stored in `/tmp/barn/jobs/<job-id>/`
- Use atomic file operations
- Human-readable plain text files
- No external database dependencies
### Cross-Platform
- Use `System.getProperty("java.io.tmpdir")` for temp paths
- Avoid platform-specific commands
- Test on Windows, macOS, and Linux
### GraalVM Native Image
- Avoid reflection where possible
- Register any reflection in `reflect-config.json`
---
## File Structure
```
barn/
src/
main/java/com/samsonmedia/barn/
Main.java # Entry point
cli/ # CLI commands (picocli)
config/ # Configuration parsing
jobs/ # Job management
service/ # Daemon/service logic
state/ # Filesystem state management
test/java/com/samsonmedia/barn/
# Mirror structure with Test suffix
config/
checkstyle/ # Checkstyle rules
spotbugs/ # SpotBugs exclusions
pmd/ # PMD ruleset
docs/ # Documentation
pom.xml # Maven build
```
---
## Commit Checklist
Before EVERY commit:
- [ ] Tests written for new/changed code
- [ ] `mvn verify` passes
- [ ] No `TODO` or `FIXME` without tracking issue
- [ ] Javadoc for public API
- [ ] Commit message follows Conventional Commits format
```bash
# Commit message format
feat(jobs): add retry mechanism for failed jobs
fix(cli): handle spaces in file paths
test(jobs): add integration tests for job lifecycle
```
---
## What NOT to Do
- **Don't skip tests** - Every change needs tests
- **Don't commit without `mvn verify`** - Ensures all checks pass
- **Don't return `null`** - Use `Optional<T>` instead
- **Don't catch `Exception`** - Catch specific exceptions
- **Don't use `System.out.println`** - Use SLF4J logging
- **Don't use wildcard imports** - Import specific classes
- **Don't use raw types** - Always specify generics
- **Don't ignore warnings** - Fix them (they're errors with `-Werror`)
---
## Quick Reference
```bash
# Build
mvn package
# Test
mvn test
# Full verification (ALWAYS before commit)
mvn verify
# Coverage report
mvn test jacoco:report
# Fast build (skip checks - use sparingly)
mvn package -Pfast
# Specific test
mvn test -Dtest=JobManagerTest
# View SpotBugs in GUI
mvn compile spotbugs:gui
```
---
## Pre-Release Testing Checklist (MANDATORY)
Before creating ANY release tag, you MUST test ALL subcommands with the native binary locally.
### Prerequisites
1. **Build the native image locally:**
```bash
export JAVA_HOME="/Library/Java/JavaVirtualMachines/graalvm-25.jdk/Contents/Home"
mvn package -Pnative -DskipTests -Dspotbugs.skip=true -Dpmd.skip=true -Dcheckstyle.skip=true -Djacoco.skip=true
```
2. **Verify the binary exists:**
```bash
ls -la target/barn
```
### Test Every Subcommand
Run each command and verify the expected output. **Do NOT skip any command.**
#### Basic Commands
```bash
# Should show usage/help
./target/barn
# Expected: Shows "Usage: barn [-hV] [COMMAND]" and lists all subcommands
./target/barn --help
# Expected: Same as above
./target/barn --version
# Expected: Shows "barn X.Y.Z"
```
#### Service Commands (Start service first)
```bash
# Stop any existing service
./target/barn service stop 2>/dev/null || true
# Start the service
./target/barn service start
# Expected: "Barn service started (PID: XXXXX)"
# Check service status
./target/barn service status
# Expected: Shows "Status: running", PID, uptime, job counts
# Test reload (reloads config without restart)
./target/barn service reload
# Expected: "Configuration reloaded"
# View logs
./target/barn service logs
# Expected: Shows recent log entries or "No logs found"
# Restart the service
./target/barn service restart
# Expected: "Barn service restarted"
```
#### Job Commands (Service must be running)
```bash
# Run a test job
./target/barn run -- echo "test from native binary"
# Expected: "Job created: job-XXXXXXXX" with state: queued
# Wait a moment, then check status
sleep 2
./target/barn status
# Expected: Shows table with jobs, including the new job as "succeeded"
# Get the job ID from status output, then describe it
./target/barn describe <job-id>
# Expected: Shows detailed job info including timestamps, exit code, files
# Check resource usage
./target/barn usage <job-id>
# Expected: Shows CPU/memory/disk usage samples
# Test kill on a non-running job (should fail gracefully)
./target/barn kill <job-id>
# Expected: "Error: Job is not running: SUCCEEDED"
# Clean with dry-run
./target/barn clean --dry-run
# Expected: "Would clean X jobs:" followed by list
```
#### Config Commands
```bash
./target/barn config show
# Expected: Shows configuration with all sections (service, jobs, cleanup, storage)
```
#### Autocompletion Commands
```bash
./target/barn autocompletion --bash | head -5
# Expected: Shows bash completion script starting with "#!/usr/bin/env bash"
./target/barn autocompletion --zsh | head -5
# Expected: Shows zsh completion script
```
#### Service Stop (Clean up)
```bash
./target/barn service stop
# Expected: "Barn service stopped"
./target/barn service status
# Expected: "Barn service is not running"
```
### Checklist Summary
Copy this checklist and verify each item:
```markdown
## Pre-Release Testing for vX.Y.Z
### Build
- [ ] Native image builds successfully
- [ ] Binary exists at target/barn
### Basic Commands
- [ ] `barn` shows help
- [ ] `barn --help` shows help
- [ ] `barn --version` shows correct version
### Service Commands
- [ ] `barn service start` starts the service
- [ ] `barn service status` shows running status
- [ ] `barn service reload` reloads config
- [ ] `barn service logs` shows logs
- [ ] `barn service restart` restarts cleanly
- [ ] `barn service stop` stops the service
### Job Commands (with service running)
- [ ] `barn run -- echo test` creates a job
- [ ] `barn status` shows job list
- [ ] `barn describe <id>` shows job details
- [ ] `barn usage <id>` shows resource usage
- [ ] `barn kill <id>` handles non-running job gracefully
- [ ] `barn clean --dry-run` shows what would be cleaned
### Config Commands
- [ ] `barn config show` displays configuration
### Autocompletion
- [ ] `barn autocompletion --bash` generates bash script
- [ ] `barn autocompletion --zsh` generates zsh script
### Final
- [ ] All commands return expected output
- [ ] No crashes or exceptions
- [ ] Service starts and stops cleanly
```
### Only After All Tests Pass
1. Commit any fixes
2. Push to main
3. Wait for CI to pass
4. Create the release tag: `git tag vX.Y.Z && git push origin vX.Y.Z`
**NEVER create a release tag without completing this checklist.**
---
## Questions to Ask Before Implementing
1. Have I read the relevant documentation?
2. Have I written tests that define the expected behavior?
3. Does this work on Windows, macOS, AND Linux?
4. Will this survive a crash/restart?
5. Can the state be manually inspected in the filesystem?
6. Does `mvn verify` pass?
---
## Working with GitHub Issues
### Viewing the Backlog
```bash
# List all open issues
gh issue list
# List issues by milestone
gh issue list --milestone "M1: Foundation"
# List issues by label
gh issue list --label "foundation"
# View specific issue
gh issue view 1
```
### Dependency Graph
Issues must be completed in dependency order. The milestones define the general order:
```
M1: Foundation (#1, #2, #3, #4, #22)
↓
M2: Job Execution (#5, #6, #7, #20)
↓
M3: CLI Commands (#8, #9, #10, #11, #12, #13, #21)
↓
M4: Service Infrastructure (#14, #15, #16)
↓
M5: Platform Integration (#17, #18, #19)
```
**Recommended order within M1:**
```
#1 (project structure)
→ #22 (logging)
→ #2 (configuration)
→ #3 (filesystem state)
→ #4 (job model)
```
### Starting a New Ticket
```bash
# 1. Check what's ready to work on (no open dependencies)
gh issue list --milestone "M1: Foundation" --state open
# 2. Pick the next ticket with closed dependencies
gh issue view 1
# 3. Follow the Ticket Implementation Process above
```
### Progress Tracking
After completing a ticket:
```bash
# Close with comment
gh issue close <number> --comment "Implemented in commit abc123"
# Verify milestone progress
gh issue list --milestone "M1: Foundation"
```
---
## Emergency Procedures
### If `mvn verify` Fails
1. **Read the error** - Don't guess, read the actual message
2. **Identify the phase** - Checkstyle? Compile? Test? SpotBugs? PMD? JaCoCo?
3. **Fix incrementally** - Run just that check until it passes:
```bash
mvn checkstyle:check # Formatting issues
mvn compile # Compilation errors
mvn test # Test failures
mvn spotbugs:check # Bug detection
mvn pmd:check # Static analysis
mvn jacoco:check # Coverage issues
```
4. **Run full verify again** - `mvn verify`
### If Tests Won't Pass
1. **Check the test is correct** - Is the expected behavior right?
2. **Check dependencies** - Is required code from other tickets present?
3. **Check test isolation** - Does the test depend on external state?
4. **Run single test** - `mvn test -Dtest=ClassName#methodName`
### If Stuck on a Ticket
1. **Re-read the ticket** - Often the answer is in the description
2. **Check Implementation Notes** - Specific guidance is provided
3. **Check referenced docs** - Context section lists what to read
4. **Look at similar code** - How did other tickets solve similar problems?
---
## Ticket Template Reference
Every ticket follows this structure:
```markdown
## Overview
Brief description of what to implement.
## Context
- **Read first**: docs to read before starting
- **Depends on**: prerequisite tickets
## Requirements
### 1. Component Name
Detailed requirements with code examples.
### 2. Another Component
More requirements...
## Tests Required
- TestClass1.java: description
- TestClass2.java: description
## Acceptance Criteria
- [ ] Criterion 1
- [ ] Criterion 2
- [ ] `mvn verify` passes
- [ ] Tests have 80%+ coverage
## Implementation Notes
Specific guidance, code patterns, edge cases.
## Definition of Done
Summary of completion requirements.
```
Use this structure to know exactly what's expected.
+4 -2
View File
@@ -209,6 +209,8 @@ There needs to be a barn service in order to run jobs (unless you use --offline)
| `error` | Human-readable failure reason | | `error` | Human-readable failure reason |
| `pid` | OS process ID (best-effort) | | `pid` | OS process ID (best-effort) |
| `heartbeat` | Last liveness update | | `heartbeat` | Last liveness update |
| `retryCount` | Current retry attempt (0 if never retried) |
| `retryAt` | Timestamp for next retry attempt (null if not retrying)|
Users can tag jobs for the purpose of filtering using the `--tag=string` CLI option. Users can tag jobs for the purpose of filtering using the `--tag=string` CLI option.
@@ -245,8 +247,8 @@ Developers can use the `--offline` command line option to test how the service b
**Example: `barn status`** **Example: `barn status`**
``` ```
ID STATE LOAD TAG CREATED EXIT PID ID STATE LOAD TAG CREATED EXIT PID RETRIES NEXT RETRY
job-6d368040 succeeded medium - 2026-01-22 01:48:46 0 17486 job-6d368040 succeeded medium - 2026-01-22 01:48:46 0 17486 - -
Total: 1 job (1 succeeded) Total: 1 job (1 succeeded)
``` ```
+4 -2
View File
@@ -503,6 +503,7 @@ retry_delay_seconds = 5
**Expected:** **Expected:**
- Job retries automatically - Job retries automatically
- `barn status` shows retry count in **RETRIES** column and next retry time in **NEXT RETRY** column
- Eventually succeeds on 3rd attempt - Eventually succeeds on 3rd attempt
- retry_count file shows retry history - retry_count file shows retry history
@@ -523,7 +524,8 @@ retry_delay_seconds = 5
**Expected:** **Expected:**
- Job state is "failed" - Job state is "failed"
- retry_count equals max_retries - **RETRIES** column shows retry count equal to max_retries
- **NEXT RETRY** column shows `-` (no further retries)
- No more retry attempts - No more retry attempts
--- ---
@@ -538,7 +540,7 @@ barn status
``` ```
**Expected:** **Expected:**
- Formatted table or list - Formatted table with columns: ID, STATE, LOAD, TAG, CREATED, EXIT, PID, RETRIES, NEXT RETRY
- Human-readable timestamps - Human-readable timestamps
- Clear column headers - Clear column headers
+1 -1
View File
@@ -6,7 +6,7 @@
<groupId>com.samsonmedia</groupId> <groupId>com.samsonmedia</groupId>
<artifactId>barn</artifactId> <artifactId>barn</artifactId>
<version>0.2.0</version> <version>0.3.0</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>Barn</name> <name>Barn</name>
@@ -121,6 +121,13 @@ public class ConfigShowCommand extends BaseCommand {
sb.append(String.format("base_dir = %s%n", config.storage().baseDir())); sb.append(String.format("base_dir = %s%n", config.storage().baseDir()));
sb.append(String.format("max_disk_usage_gb = %d%n", config.storage().maxDiskUsageGb())); sb.append(String.format("max_disk_usage_gb = %d%n", config.storage().maxDiskUsageGb()));
sb.append(String.format("preserve_work_dir = %b%n", config.storage().preserveWorkDir())); sb.append(String.format("preserve_work_dir = %b%n", config.storage().preserveWorkDir()));
sb.append("\n");
// Load section
sb.append("[load]\n");
sb.append(String.format("max_high_jobs = %d%n", config.loadLevels().maxHighJobs()));
sb.append(String.format("max_medium_jobs = %d%n", config.loadLevels().maxMediumJobs()));
sb.append(String.format("max_low_jobs = %d%n", config.loadLevels().maxLowJobs()));
getOut().println(sb.toString().trim()); getOut().println(sb.toString().trim());
} }
@@ -131,6 +138,7 @@ public class ConfigShowCommand extends BaseCommand {
map.put("jobs", buildJobsSection(config)); map.put("jobs", buildJobsSection(config));
map.put("cleanup", buildCleanupSection(config)); map.put("cleanup", buildCleanupSection(config));
map.put("storage", buildStorageSection(config)); map.put("storage", buildStorageSection(config));
map.put("load", buildLoadSection(config));
return map; return map;
} }
@@ -171,4 +179,12 @@ public class ConfigShowCommand extends BaseCommand {
storage.put("preserve_work_dir", config.storage().preserveWorkDir()); storage.put("preserve_work_dir", config.storage().preserveWorkDir());
return storage; return storage;
} }
private Map<String, Object> buildLoadSection(Config config) {
Map<String, Object> load = new LinkedHashMap<>();
load.put("max_high_jobs", config.loadLevels().maxHighJobs());
load.put("max_medium_jobs", config.loadLevels().maxMediumJobs());
load.put("max_low_jobs", config.loadLevels().maxLowJobs());
return load;
}
} }
@@ -135,12 +135,17 @@ public class HumanFormatter implements OutputFormatter {
sb.append(" Retries: ").append(job.retryCount()).append("\n"); sb.append(" Retries: ").append(job.retryCount()).append("\n");
} }
if (job.retryAt() != null) {
sb.append(" Retry At: ").append(formatTimestamp(job.retryAt())).append("\n");
}
return sb.toString().trim(); return sb.toString().trim();
} }
private String formatJobTable(List<Job> jobs) { private String formatJobTable(List<Job> jobs) {
// Define columns // Define columns
List<String> headers = List.of("ID", "STATE", "LOAD", "TAG", "CREATED", "EXIT"); List<String> headers = List.of(
"ID", "STATE", "LOAD", "TAG", "CREATED", "EXIT", "RETRIES", "NEXT RETRY");
// Convert jobs to rows // Convert jobs to rows
List<List<String>> rows = new ArrayList<>(); List<List<String>> rows = new ArrayList<>();
@@ -151,7 +156,9 @@ public class HumanFormatter implements OutputFormatter {
job.loadLevel().toString().toLowerCase(Locale.ROOT), job.loadLevel().toString().toLowerCase(Locale.ROOT),
job.tag() != null ? job.tag() : "-", job.tag() != null ? job.tag() : "-",
formatTimestamp(job.createdAt()), formatTimestamp(job.createdAt()),
job.exitCode() != null ? job.exitCode().toString() : "-" job.exitCode() != null ? job.exitCode().toString() : "-",
job.retryCount() > 0 ? String.valueOf(job.retryCount()) : "-",
job.retryAt() != null ? formatTimestamp(job.retryAt()) : "-"
)); ));
} }
@@ -195,19 +195,23 @@ public class StatusCommand extends BaseCommand {
.max().orElse(3)); .max().orElse(3));
// Header // Header
sb.append(String.format("%-" + idWidth + "s %-9s %-6s %-" + tagWidth + "s %-19s %-4s %-8s%n", sb.append(String.format(
"ID", "STATE", "LOAD", "TAG", "CREATED", "EXIT", "PID")); "%-" + idWidth + "s %-9s %-6s %-" + tagWidth + "s %-19s %-4s %-8s %-7s %-19s%n",
"ID", "STATE", "LOAD", "TAG", "CREATED", "EXIT", "PID", "RETRIES", "NEXT RETRY"));
// Rows // Rows
for (Job job : jobs) { for (Job job : jobs) {
sb.append(String.format("%-" + idWidth + "s %-9s %-6s %-" + tagWidth + "s %-19s %-4s %-8s%n", sb.append(String.format(
"%-" + idWidth + "s %-9s %-6s %-" + tagWidth + "s %-19s %-4s %-8s %-7s %-19s%n",
job.id(), job.id(),
job.state().toString().toLowerCase(Locale.ROOT), job.state().toString().toLowerCase(Locale.ROOT),
job.loadLevel().toString().toLowerCase(Locale.ROOT), job.loadLevel().toString().toLowerCase(Locale.ROOT),
job.tag() != null ? job.tag() : "-", job.tag() != null ? job.tag() : "-",
formatTimestamp(job.createdAt()), formatTimestamp(job.createdAt()),
job.exitCode() != null ? job.exitCode().toString() : "-", job.exitCode() != null ? job.exitCode().toString() : "-",
job.pid() != null ? job.pid().toString() : "-")); job.pid() != null ? job.pid().toString() : "-",
job.retryCount() > 0 ? String.valueOf(job.retryCount()) : "-",
job.retryAt() != null ? formatTimestamp(job.retryAt()) : "-"));
} }
// Summary // Summary
@@ -186,11 +186,11 @@ public final class ConfigLoader {
} }
private Config buildConfig(Map<String, Map<String, Object>> data) { private Config buildConfig(Map<String, Map<String, Object>> data) {
// Handle both "load_levels" (from TOML) and "loadlevels" (from env vars) // Merge both "load_levels" (from TOML) and "loadlevels" (from env vars)
Map<String, Object> loadLevelData = data.getOrDefault("load_levels", Map.of()); // Env vars (loadlevels) take precedence over config file (load_levels)
if (loadLevelData.isEmpty()) { Map<String, Object> loadLevelData = new HashMap<>(data.getOrDefault("load_levels", Map.of()));
loadLevelData = data.getOrDefault("loadlevels", Map.of()); loadLevelData.putAll(data.getOrDefault("loadlevels", Map.of()));
}
return new Config( return new Config(
buildServiceConfig(data.getOrDefault("service", Map.of())), buildServiceConfig(data.getOrDefault("service", Map.of())),
buildJobsConfig(data.getOrDefault("jobs", Map.of())), buildJobsConfig(data.getOrDefault("jobs", Map.of())),
@@ -79,6 +79,18 @@ class HumanFormatterTest {
assertThat(result).contains("Process failed"); assertThat(result).contains("Process failed");
} }
@Test
void format_withRetryingJob_shouldShowRetryInfo() {
Job job = createRetryingJob("job-retry1234", 3,
Instant.parse("2026-01-15T10:30:00Z"));
String result = formatter.format(job);
assertThat(result).contains("Retries:");
assertThat(result).contains("3");
assertThat(result).contains("Retry At:");
}
@Test @Test
void format_withMap_shouldFormatKeyValues() { void format_withMap_shouldFormatKeyValues() {
Map<String, Object> map = new LinkedHashMap<>(); Map<String, Object> map = new LinkedHashMap<>();
@@ -127,6 +139,18 @@ class HumanFormatterTest {
assertThat(result).contains("medium"); assertThat(result).contains("medium");
} }
@Test
void formatList_withRetryingJob_shouldShowRetryColumns() {
List<Job> jobs = List.of(createRetryingJob("job-retry1234", 2,
Instant.parse("2026-01-15T10:30:00Z")));
String result = formatter.formatList(jobs);
assertThat(result).contains("RETRIES");
assertThat(result).contains("NEXT RETRY");
assertThat(result).contains("2");
}
@Test @Test
void formatList_withStrings_shouldFormatEach() { void formatList_withStrings_shouldFormatEach() {
List<String> strings = List.of("item1", "item2", "item3"); List<String> strings = List.of("item1", "item2", "item3");
@@ -242,4 +266,23 @@ class HumanFormatterTest {
MEDIUM MEDIUM
); );
} }
private Job createRetryingJob(String id, int retryCount, Instant retryAt) {
return new Job(
id,
JobState.QUEUED,
List.of("echo", "test"),
"tag",
Instant.now().minus(Duration.ofMinutes(5)),
null,
null,
null,
null,
null,
null,
retryCount,
retryAt,
MEDIUM
);
}
} }
@@ -6,6 +6,8 @@ import java.io.IOException;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.io.StringWriter; import java.io.StringWriter;
import java.nio.file.Path; import java.nio.file.Path;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.List; import java.util.List;
import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.BeforeEach;
@@ -14,6 +16,7 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.api.io.TempDir;
import com.samsonmedia.barn.config.JobsConfig; import com.samsonmedia.barn.config.JobsConfig;
import com.samsonmedia.barn.jobs.Job;
import com.samsonmedia.barn.jobs.JobRepository; import com.samsonmedia.barn.jobs.JobRepository;
import com.samsonmedia.barn.state.BarnDirectories; import com.samsonmedia.barn.state.BarnDirectories;
@@ -100,6 +103,22 @@ class StatusCommandTest {
assertThat(exitCode).isZero(); assertThat(exitCode).isZero();
assertThat(stdout.toString().toLowerCase()).contains("queued"); assertThat(stdout.toString().toLowerCase()).contains("queued");
} }
@Test
void status_withRetryingJob_shouldShowRetryColumns() throws IOException {
Job job = repository.create(List.of("echo", "test"), "test", config);
repository.markStarted(job.id(), 12345L);
repository.markCompleted(job.id(), 1, "test failure");
Instant retryAt = Instant.now().plus(5, ChronoUnit.MINUTES);
repository.scheduleRetry(job.id(), retryAt);
int exitCode = cmd.execute("--offline");
assertThat(exitCode).isZero();
String output = stdout.toString();
assertThat(output).contains("RETRIES");
assertThat(output).contains("NEXT RETRY");
}
} }
@Nested @Nested
@@ -192,8 +192,44 @@ class XmlFormatterTest {
} }
} }
@Nested
class RetryFields {
@Test
void format_withRetryingJob_shouldIncludeRetryFields() {
Job job = createRetryingJob("job-retry1234", 2,
Instant.parse("2026-01-15T10:30:00Z"));
String result = formatter.format(job);
assertThat(result).contains("<retry_count>2</retry_count>");
assertThat(result).contains("<retry_at>");
assertThat(result).contains("2026-01-15T10:30:00Z");
assertThat(result).contains("</retry_at>");
}
}
// Helper methods // Helper methods
private Job createRetryingJob(String id, int retryCount, Instant retryAt) {
return new Job(
id,
JobState.QUEUED,
List.of("echo", "test"),
"tag",
Instant.now(),
null,
null,
null,
null,
null,
null,
retryCount,
retryAt,
MEDIUM
);
}
private Job createJob(String id, JobState state, String tag) { private Job createJob(String id, JobState state, String tag) {
return new Job( return new Job(
id, id,