feat: add duration parser, ISO timestamps, job state machine; add AGENTS.md

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Daniel SamsonandClaude Sonnet 5.5 committed 2026-10-17 13:10:09 +01:00
1 parent 9e5c3e3af1
commit 8cf40344a4
6 files changed
+261 -16

No files matched your search

+26
View File
@@ -0,0 +1,26 @@
# AGENTS.md
Guidance for AI coding agents working in `zag`, the Zig port of the
[barn](../barn) Java job daemon. See `README.md` for the user-facing description.
## Toolchain
- Zig 0.16.0 (`zig build`, `zig build test`). The 0.16 std API differs from older
releases (`std.Io`, `std.process.Init`); check the scaffold in `src/main.zig` first.
- Library code lives in `src/` and is exposed through `src/root.zig`; `src/main.zig` is the CLI.
## Porting rules
- Reference implementation: `../barn/src/main/java/com/samsonmedia/barn/`.
- Implement the *documented* behaviour (README, `../barn/docs/`), not barn's bugs.
- Keep CLI flags, JSON/XML output field order, config defaults and the on-disk job
directory layout compatible with barn (`zag` replaces `barn` in names and paths).
- Port specs from barn's unit tests alongside each module (`test` blocks).
## Layout
| Path | Purpose |
|------|---------|
| `src/duration.zig` | `\d+[mhdwMHDW]` duration parser |
| `src/timestamp.zig` | ISO-8601 instant formatting/parsing (barn-compatible) |
| `src/state.zig` | Job states and the transition state machine |
+7
View File
@@ -0,0 +1,7 @@
# CLAUDE.md
Agent instructions for this repository live in [AGENTS.md](AGENTS.md) so they are
shared across coding agents (Claude Code, Codex, Gemini CLI, Cursor, etc.).
Claude Code loads them via the import below; add Claude-only notes underneath.
@AGENTS.md
+37
View File
@@ -0,0 +1,37 @@
//! Duration parser for values like `30m`, `12h`, `7d`, `2w` (case-insensitive unit).
//! `M` is minutes, not months, matching barn's `DurationParser`.
const std = @import("std");
pub const Error = error{InvalidDuration};
/// Parses `^\d+[mhdwMHDW]$` and returns the duration in seconds.
pub fn parseSeconds(text: []const u8) Error!u64 {
if (text.len < 2) return error.InvalidDuration;
const unit = text[text.len - 1];
const digits = text[0 .. text.len - 1];
for (digits) |c| if (!std.ascii.isDigit(c)) return error.InvalidDuration;
const n = std.fmt.parseInt(u64, digits, 10) catch return error.InvalidDuration;
const mult: u64 = switch (std.ascii.toLower(unit)) {
'm' => 60,
'h' => 60 * 60,
'd' => 24 * 60 * 60,
'w' => 7 * 24 * 60 * 60,
else => return error.InvalidDuration,
};
return std.math.mul(u64, n, mult) catch error.InvalidDuration;
}
test "parses each unit" {
try std.testing.expectEqual(@as(u64, 30 * 60), try parseSeconds("30m"));
try std.testing.expectEqual(@as(u64, 12 * 3600), try parseSeconds("12H"));
try std.testing.expectEqual(@as(u64, 7 * 86400), try parseSeconds("7d"));
try std.testing.expectEqual(@as(u64, 2 * 604800), try parseSeconds("2W"));
try std.testing.expectEqual(@as(u64, 60), try parseSeconds("1M"));
}
test "rejects invalid input" {
for ([_][]const u8{ "", "m", "10", "10s", "-5m", "1.5h", "5 m", "abc" }) |bad| {
try std.testing.expectError(error.InvalidDuration, parseSeconds(bad));
}
try std.testing.expectError(error.InvalidDuration, parseSeconds("99999999999999999999w"));
}
+6 -16
View File
@@ -1,18 +1,8 @@
//! By convention, root.zig is the root source file when making a package. //! zag: cross-platform job daemon (Zig port of barn).
const std = @import("std"); pub const duration = @import("duration.zig");
const Io = std.Io; pub const timestamp = @import("timestamp.zig");
pub const state = @import("state.zig");
/// This is a documentation comment to explain the `printAnotherMessage` function below. test {
/// @import("std").testing.refAllDecls(@This());
/// Accepting an `Io.Writer` instance is a handy way to write reusable code.
pub fn printAnotherMessage(writer: *Io.Writer) Io.Writer.Error!void {
try writer.print("Run `zig build test` to run the tests.\n", .{});
}
pub fn add(a: i32, b: i32) i32 {
return a + b;
}
test "basic add functionality" {
try std.testing.expect(add(3, 7) == 10);
} }
+65
View File
@@ -0,0 +1,65 @@
//! Job states and the allowed transitions between them.
const std = @import("std");
pub const State = enum {
queued,
running,
succeeded,
failed,
canceled,
killed,
pub fn isTerminal(self: State) bool {
return switch (self) {
.succeeded, .canceled => true,
else => false,
};
}
/// Lowercase form used in the `state` file and in `describe` output.
pub fn lower(self: State) []const u8 {
return @tagName(self);
}
/// Parses a state name, case-insensitively.
pub fn parse(text: []const u8) ?State {
inline for (@typeInfo(State).@"enum".fields) |f| {
if (std.ascii.eqlIgnoreCase(text, f.name)) return @field(State, f.name);
}
return null;
}
/// QUEUED -> RUNNING | FAILED | CANCELED
/// RUNNING -> SUCCEEDED | FAILED | CANCELED | KILLED
/// FAILED | KILLED -> QUEUED (retry)
pub fn canTransitionTo(self: State, next: State) bool {
return switch (self) {
.queued => next == .running or next == .failed or next == .canceled,
.running => next == .succeeded or next == .failed or next == .canceled or next == .killed,
.failed, .killed => next == .queued,
.succeeded, .canceled => false,
};
}
};
test "valid transitions" {
try std.testing.expect(State.queued.canTransitionTo(.running));
try std.testing.expect(State.running.canTransitionTo(.killed));
try std.testing.expect(State.failed.canTransitionTo(.queued));
try std.testing.expect(State.killed.canTransitionTo(.queued));
}
test "invalid transitions" {
try std.testing.expect(!State.succeeded.canTransitionTo(.queued));
try std.testing.expect(!State.canceled.canTransitionTo(.running));
try std.testing.expect(!State.queued.canTransitionTo(.succeeded));
try std.testing.expect(!State.failed.canTransitionTo(.running));
}
test "parse and terminal" {
try std.testing.expectEqual(State.running, State.parse("RUNNING").?);
try std.testing.expectEqual(State.killed, State.parse("killed").?);
try std.testing.expect(State.parse("bogus") == null);
try std.testing.expect(State.succeeded.isTerminal());
try std.testing.expect(!State.failed.isTerminal());
}
+120
View File
@@ -0,0 +1,120 @@
//! ISO-8601 instants, compatible with Java's `Instant.toString()`:
//! `2026-01-22T01:48:46Z`, `...46.749Z`, `...46.749629Z` or `...46.749629123Z`
//! (0, 3, 6 or 9 fractional digits, whichever is the shortest exact form).
const std = @import("std");
const epoch = std.time.epoch;
pub const Error = error{InvalidTimestamp};
/// Longest possible output, e.g. `2026-01-22T01:48:46.749629123Z`.
pub const max_len = 30;
/// Formats nanoseconds since the Unix epoch (UTC). Years must be 1970..9999.
pub fn format(buf: *[max_len]u8, unix_ns: i128) []const u8 {
const secs: u64 = @intCast(@divFloor(unix_ns, std.time.ns_per_s));
const nanos: u32 = @intCast(@mod(unix_ns, std.time.ns_per_s));
const es = epoch.EpochSeconds{ .secs = secs };
const ym = es.getEpochDay().calculateYearDay();
const md = ym.calculateMonthDay();
const ds = es.getDaySeconds();
var w = std.Io.Writer.fixed(buf);
w.print("{d:0>4}-{d:0>2}-{d:0>2}T{d:0>2}:{d:0>2}:{d:0>2}", .{
ym.year,
md.month.numeric(),
md.day_index + 1,
ds.getHoursIntoDay(),
ds.getMinutesIntoHour(),
ds.getSecondsIntoMinute(),
}) catch unreachable;
if (nanos != 0) {
if (nanos % 1_000_000 == 0) {
w.print(".{d:0>3}", .{nanos / 1_000_000}) catch unreachable;
} else if (nanos % 1_000 == 0) {
w.print(".{d:0>6}", .{nanos / 1_000}) catch unreachable;
} else {
w.print(".{d:0>9}", .{nanos}) catch unreachable;
}
}
w.writeByte('Z') catch unreachable;
return w.buffered();
}
/// Parses `YYYY-MM-DDTHH:MM:SS[.f{1,9}]Z` into nanoseconds since the Unix epoch.
pub fn parse(text: []const u8) Error!i128 {
if (text.len < 20 or text[text.len - 1] != 'Z') return error.InvalidTimestamp;
if (text[4] != '-' or text[7] != '-' or text[10] != 'T' or text[13] != ':' or text[16] != ':')
return error.InvalidTimestamp;
const year = try num(text[0..4]);
const month = try num(text[5..7]);
const day = try num(text[8..10]);
const hour = try num(text[11..13]);
const minute = try num(text[14..16]);
const second = try num(text[17..19]);
var nanos: u32 = 0;
const rest = text[19 .. text.len - 1];
if (rest.len > 0) {
if (rest[0] != '.' or rest.len < 2 or rest.len > 10) return error.InvalidTimestamp;
const frac = rest[1..];
nanos = try num(frac);
var i: usize = frac.len;
while (i < 9) : (i += 1) nanos *= 10;
}
if (year < 1970 or month < 1 or month > 12 or hour > 23 or minute > 59 or second > 59)
return error.InvalidTimestamp;
const m: epoch.Month = @enumFromInt(month);
const dim = epoch.getDaysInMonth(@intCast(year), m);
if (day < 1 or day > dim) return error.InvalidTimestamp;
var days: u64 = 0;
var y: u32 = 1970;
while (y < year) : (y += 1) days += epoch.getDaysInYear(@intCast(y));
var mi: u4 = 1;
while (mi < month) : (mi += 1) days += epoch.getDaysInMonth(@intCast(year), @enumFromInt(mi));
days += day - 1;
const secs: i128 = @as(i128, days) * epoch.secs_per_day + hour * 3600 + minute * 60 + second;
return secs * std.time.ns_per_s + nanos;
}
fn num(s: []const u8) Error!u32 {
for (s) |c| if (!std.ascii.isDigit(c)) return error.InvalidTimestamp;
return std.fmt.parseInt(u32, s, 10) catch error.InvalidTimestamp;
}
fn expectFormat(expected: []const u8, ns: i128) !void {
var buf: [max_len]u8 = undefined;
try std.testing.expectEqualStrings(expected, format(&buf, ns));
}
test "format drops trailing zero groups like Instant.toString" {
const base: i128 = 1_769_046_526 * std.time.ns_per_s; // 2026-01-22T01:48:46Z
try expectFormat("2026-01-22T01:48:46Z", base);
try expectFormat("2026-01-22T01:48:46.749Z", base + 749_000_000);
try expectFormat("2026-01-22T01:48:46.749629Z", base + 749_629_000);
try expectFormat("2026-01-22T01:48:46.749629123Z", base + 749_629_123);
try expectFormat("2026-01-22T01:48:46.000000001Z", base + 1);
try expectFormat("1970-01-01T00:00:00Z", 0);
}
test "parse round-trips" {
const base: i128 = 1_769_046_526 * std.time.ns_per_s;
for ([_]i128{ 0, base, base + 749_000_000, base + 749_629_000, base + 749_629_123 }) |ns| {
var buf: [max_len]u8 = undefined;
try std.testing.expectEqual(ns, try parse(format(&buf, ns)));
}
}
test "parse handles leap years and short fractions" {
try std.testing.expectEqual(@as(i128, 951_782_400) * std.time.ns_per_s, try parse("2000-02-29T00:00:00Z"));
try std.testing.expectEqual(@as(i128, 500_000_000), try parse("1970-01-01T00:00:00.5Z"));
}
test "parse rejects garbage" {
for ([_][]const u8{ "", "2026-01-22", "2026-13-01T00:00:00Z", "2026-02-30T00:00:00Z", "2026-01-22T25:00:00Z", "2026-01-22T01:48:46", "2026-01-22T01:48:46.Z" }) |bad| {
try std.testing.expectError(error.InvalidTimestamp, parse(bad));
}
}