✓
Passing This code compiles and runs correctly.
Code
// Pins the named-gate surface end to end. The program itself is a decoy —
// post.sh drives `koruc input.k gate …` over the declarations this file
// carries:
// * `gate` lists the declared profiles and their membership
// * `gate dev` (advisory) runs the deterministic `check:` instrument and
// reports the judgment-class row — UNJUDGED when the profile declares
// no judge, with the cause named
// * odds-0 always misses, odds-100 always fires — the roll's verdict is
// independent of whatever happens to be staged in the enclosing repo
// * `gate broken` exits 1 on a failing instrument (check violations
// always block; advisory only softens judgment rows)
// * `gate strict --repo <scratch>` delegates the judgment row to the
// profile's judge binary — VIOLATION under enforcing → exit 1,
// --advisory → exit 0; `gate clean` pins the CLEAN verdict passing
// * `gate nosuch` refuses and names the declared set
import std/io
import std/invariants
import std/gate
std/gate:profile(dev) {
"block": false,
"description": "the dev commit gate — advisory"
}
std/gate:profile(broken) {
"block": true,
"description": "a profile whose instrument fails"
}
std/gate:profile(strict) {
"block": true,
"description": "enforcement over a judgment-class row — the judge decides",
"judge": "scratch/strict-judge"
}
std/gate:profile(clean) {
"block": true,
"description": "enforcement with a judge that returns CLEAN",
"judge": "scratch/clean-judge"
}
std/invariants:inferred {
"name": "shape-is-named",
"tags": ["dev"],
"rule": "every declared shape carries a name",
"check": "true"
}
std/invariants:inferred {
"name": "prose-rule",
"tags": ["dev"],
"rule": "a judgment-class row whose profile declares no judge"
}
std/invariants:inferred {
"name": "never-fires",
"tags": ["dev", "odds-0"],
"rule": "a row whose alarm can never roll low enough",
"check": "true"
}
std/invariants:inferred {
"name": "always-fires",
"tags": ["dev", "odds-100"],
"rule": "a row whose alarm always rolls low enough",
"check": "true"
}
std/invariants:inferred {
"name": "always-fails",
"tags": ["broken"],
"rule": "an instrument that always exits non-zero",
"check": "false"
}
std/invariants:inferred {
"name": "strict-rule",
"tags": ["strict"],
"rule": "a judgment-class row under an enforcing profile"
}
std/invariants:inferred {
"name": "clean-rule",
"tags": ["clean"],
"rule": "a judgment-class row whose judge returns CLEAN"
}
std/io:print.ln("gate-me")
Actual
gate-me
Expected output
✓ Zig✓ C#gate-me
Emitted Zig source
// Access compiler flags via the per-user compiler_env module
const CompilerEnv = @import("compiler_env").CompilerEnv;
pub const panic = if (@import("builtin").mode == .Debug)
@import("std").debug.FullPanic(@import("std").debug.defaultPanic)
else
@import("std").debug.simple_panic;
const __koru_bare = struct {
extern fn posix_memalign(memptr: *?*anyopaque, alignment: usize, size: usize) c_int;
extern fn free(ptr: ?*anyopaque) void;
fn bareAlloc(_: *anyopaque, len: usize, alignment: @import("std").mem.Alignment, _: usize) ?[*]u8 {
var p: ?*anyopaque = null;
const a = @max(alignment.toByteUnits(), @sizeOf(usize));
if (posix_memalign(&p, a, len) != 0) return null;
return @ptrCast(p);
}
fn bareResize(_: *anyopaque, _: []u8, _: @import("std").mem.Alignment, _: usize, _: usize) bool { return false; }
fn bareRemap(_: *anyopaque, _: []u8, _: @import("std").mem.Alignment, _: usize, _: usize) ?[*]u8 { return null; }
fn bareFree(_: *anyopaque, memory: []u8, _: @import("std").mem.Alignment, _: usize) void { free(@ptrCast(memory.ptr)); }
const vtable = @import("std").mem.Allocator.VTable{ .alloc = bareAlloc, .resize = bareResize, .remap = bareRemap, .free = bareFree };
const allocator = @import("std").mem.Allocator{ .ptr = undefined, .vtable = &vtable };
};
const __koru_backing = if (@import("builtin").link_libc) @import("std").heap.c_allocator else if (@import("builtin").os.tag == .freestanding and !@import("builtin").cpu.arch.isWasm()) __koru_bare.allocator else @import("std").heap.page_allocator;
var __koru_leak_count: @import("std").atomic.Value(usize) = .init(0);
var __koru_par_tasks: @import("std").atomic.Value(usize) = .init(0);
const __koru_par_CAP: usize = 128;
threadlocal var __koru_par_depth: usize = 0;
const __koru_par_DEPTH_CAP: usize = 7;
var __koru_par_pool: @import("std").Thread.Pool = undefined;
var __koru_par_pool_ready: bool = false;
var __koru_par_pool_mtx: @import("std").Thread.Mutex = .{};
fn __koru_par_pool_ensure() *@import("std").Thread.Pool {
__koru_par_pool_mtx.lock();
defer __koru_par_pool_mtx.unlock();
if (!__koru_par_pool_ready) {
@import("std").Thread.Pool.init(&__koru_par_pool, .{ .allocator = @import("std").heap.smp_allocator }) catch @panic("koru: thread pool init failed");
__koru_par_pool_ready = true;
}
return &__koru_par_pool;
}
fn __koru_alloc(ctx: *anyopaque, len: usize, alignment: @import("std").mem.Alignment, ret_addr: usize) ?[*]u8 {
_ = ctx;
const r = __koru_backing.rawAlloc(len, alignment, ret_addr);
if (comptime @import("builtin").mode == .Debug) {
if (r != null) _ = __koru_leak_count.fetchAdd(1, .monotonic);
}
return r;
}
fn __koru_resize(ctx: *anyopaque, memory: []u8, alignment: @import("std").mem.Alignment, new_len: usize, ret_addr: usize) bool {
_ = ctx;
return __koru_backing.rawResize(memory, alignment, new_len, ret_addr);
}
fn __koru_remap(ctx: *anyopaque, memory: []u8, alignment: @import("std").mem.Alignment, new_len: usize, ret_addr: usize) ?[*]u8 {
_ = ctx;
return __koru_backing.rawRemap(memory, alignment, new_len, ret_addr);
}
fn __koru_free(ctx: *anyopaque, memory: []u8, alignment: @import("std").mem.Alignment, ret_addr: usize) void {
_ = ctx;
__koru_backing.rawFree(memory, alignment, ret_addr);
if (comptime @import("builtin").mode == .Debug) {
_ = __koru_leak_count.fetchSub(1, .monotonic);
}
}
const __koru_vtable = @import("std").mem.Allocator.VTable{ .alloc = __koru_alloc, .resize = __koru_resize, .remap = __koru_remap, .free = __koru_free };
pub fn koru_allocator() @import("std").mem.Allocator {
return .{ .ptr = undefined, .vtable = &__koru_vtable };
}
pub inline fn __koru_intcast(comptime T: type, x: anytype) T {
if (comptime (@import("builtin").mode == .Debug or @import("builtin").mode == .ReleaseSafe))
return @as(T, @intCast(x));
const dst = @typeInfo(T);
const src = @typeInfo(@TypeOf(x));
if (comptime (dst == .int and src == .int and dst.int.bits == src.int.bits and dst.int.signedness != src.int.signedness))
return @as(T, @bitCast(x));
return @as(T, @intCast(x));
}
fn __KoruPadI(comptime T: type) type {
const V = switch (@typeInfo(T)) { .comptime_int => i64, .comptime_float => f64, else => T };
return struct {
v: V,
width: usize,
pub fn format(self: @This(), w: *@import("std").Io.Writer) @import("std").Io.Writer.Error!void {
const rendered = @import("std").fmt.count("{d}", .{self.v});
const pad = self.width -| rendered;
for (0..pad) |_| try w.writeByte(' ');
try w.print("{d}", .{self.v});
}
};
}
pub fn __koru_pad_i(width: usize, value: anytype) __KoruPadI(@TypeOf(value)) {
return .{ .v = value, .width = width };
}
pub fn koru_leak_check() void {
if (comptime @import("builtin").mode != .Debug) return;
if (__koru_leak_count.load(.acquire) == 0) return;
if (comptime @import("builtin").target.os.tag == .freestanding) {
if (comptime @import("builtin").cpu.arch == .wasm32 or @import("builtin").cpu.arch == .wasm64) {
@panic("KORU LEAK CHECK FAILED: the produced program leaked");
} else {
const __klc = struct { extern var stdout: ?*anyopaque; extern fn fputs(__s: [*:0]const u8, __st: ?*anyopaque) c_int; };
var __lb: [128]u8 = undefined;
const __lm = "KORU LEAK CHECK FAILED: allocations still outstanding at end of run: ";
@memcpy(__lb[0..__lm.len], __lm);
var __ln: usize = __lm.len;
var __lv = __koru_leak_count.load(.acquire);
var __ld: [20]u8 = undefined;
var __lk: usize = 0;
while (__lv > 0) : (__lk += 1) { __ld[__lk] = @intCast('0' + __lv % 10); __lv /= 10; }
for (0..__lk) |__li| { __lb[__ln] = __ld[__lk - 1 - __li]; __ln += 1; }
__lb[__ln] = '\n'; __ln += 1; __lb[__ln] = 0;
_ = __klc.fputs(@as([*:0]const u8, @ptrCast(&__lb)), __klc.stdout);
@trap();
}
} else {
@import("std").debug.print("KORU LEAK CHECK FAILED: the produced program leaked (trace above)\n", .{});
@import("std").process.exit(1);
}
}
pub const main_module = struct {
// >>> FLOW: tests/regression/200_COMPILER_FEATURES/220_COMPILATION/220_049_gate_named_profiles/input.k:89 ~std.io:print.impl()
pub fn flow0() void {
(struct { fn __kout(__fd: i32, __b: []const u8) void { if (@import("builtin").os.tag == .freestanding) { const __kc = struct { extern var stdout: ?*anyopaque; extern var stderr: ?*anyopaque; extern fn fputs(__s: [*:0]const u8, __st: ?*anyopaque) c_int; }; var __kt: [4096]u8 = undefined; for (0..(__b.len + __kt.len - 2) / (__kt.len - 1)) |__ki| { const __kn = @min(__kt.len - 1, __b.len - __ki * (__kt.len - 1)); @memcpy(__kt[0..__kn], __b[__ki * (__kt.len - 1)..][0..__kn]); __kt[__kn] = 0; @import("std").mem.doNotOptimizeAway(__kc.fputs(@as([*:0]const u8, @ptrCast(&__kt)), if (__fd == 2) __kc.stderr else __kc.stdout)); } } else { @import("std").mem.doNotOptimizeAway(@import("std").posix.write(__fd, __b) catch @as(usize, 0)); } } fn __kw(comptime __f: []const u8, __a: anytype) void { var __kb: [65536]u8 = undefined; const __ks = @import("std").fmt.bufPrint(&__kb, __f, __a) catch __kb[0..0]; __kout(1, __ks); } }).__kw("gate-me\n", .{});
}
pub fn koru_start_flow() void {
const result_0 = koru_koru.start_event.handler(.{ });
const result_0_done = result_0.done;
_ = &result_0_done;
}
pub fn koru_end_flow() void {
const result_0 = koru_koru.end_event.handler(.{ });
const result_0_done = result_0.done;
_ = &result_0_done;
}
};
pub const koru_koru = struct {
pub const start_event = struct {
pub const Input = struct {
};
pub const Output = union(enum(u8)) {
done: struct {
},
};
pub fn handler(__koru_event_input: @This().Input) @This().Output {
_ = &__koru_event_input;
return .{ .done = .{} };
}
};
pub const end_event = struct {
pub const Input = struct {
};
pub const Output = union(enum(u8)) {
done: struct {
},
};
pub fn handler(__koru_event_input: @This().Input) @This().Output {
_ = &__koru_event_input;
return .{ .done = .{} };
}
};
};
pub fn main() void {
main_module.koru_start_flow();
main_module.flow0();
main_module.koru_end_flow();
if (comptime @import("builtin").mode == .Debug) koru_leak_check();
}
test {
@import("std").testing.refAllDeclsRecursive(@This());
}
Emitted C# source
static class main_module {
public static void __koru_stdout_write(object s) => global::System.Console.Out.Write(s);
public static void __koru_stderr_write(object s) => global::System.Console.Error.Write(s);
// The mutable handle carrier — `*String`-style resources are
// `new __KoruBox { data = … }` because C# anonymous types are
// read-only: `s.data = …` (std/string append/clear, handle
// mutation generally) needs a settable member. `object`, not
// `dynamic`: the field is storage — every `x.data` read reaches
// it through a dynamic-typed handle (`*T` Input fields, the
// `dynamic` borrow locals below), so the member itself only
// needs to hold the value, and `object` keeps the DLR out of
// the store/load path.
public class __KoruBox { public object data; }
// Textification for `{{ … }}` operands: C# bool ToStrings as
// `True` where Koru prints `true`, and the operand's static type
// is unknown at this boundary — a `(x) is bool` inline test would
// be a compile error on statically-typed operands instead. Generic
// on purpose: `dynamic` boxed every value-type operand — measured
// ~1s/10M elements on 012_threat_scanner — while T specializes to
// the operand's own ToString() with no box.
public static string __koru_str<T>(T v) => v is bool b ? (b ? "true" : "false") : v?.ToString();
public static class std_io_print_impl_event {
public struct Input {
public string expr;
}
public static object handler(Input __koru_input) {
throw new global::System.Exception("std.io:impl has no C# implementation — its body resolves only to a non-cs target (|zig / [comptime]), directly or through a callee");
}
}
public static class koru_start_event {
public struct Input {
}
public struct Output {
public string tag;
public object done;
}
public static Output handler(Input __koru_input) => new Output { tag = "done" };
}
public static class koru_end_event {
public struct Input {
}
public struct Output {
public string tag;
public object done;
}
public static Output handler(Input __koru_input) => new Output { tag = "done" };
}
public static void flow0() {
__koru_stdout_write("gate-me" + "\n");
}
public static void flow1() {
main_module.koru_start_event.handler(new koru_start_event.Input { });
}
public static void flow2() {
main_module.koru_end_event.handler(new koru_end_event.Input { });
}
}
static class Program {
static void Main() {
main_module.flow1();
main_module.flow0();
main_module.flow2();
}
}
Flows
flow ~profile click a branch to expand · @labels scroll to their anchor
profile (expr: dev, source: "block": false,
"description": "the dev commit gate — advisory")
flow ~profile click a branch to expand · @labels scroll to their anchor
profile (expr: broken, source: "block": true,
"description": "a profile whose instrument fails")
flow ~profile click a branch to expand · @labels scroll to their anchor
profile (expr: strict, source: "block": true,
"description": "enforcement over a judgment-class row — the judge decides",
"judge": "scratch/strict-judge")
flow ~profile click a branch to expand · @labels scroll to their anchor
profile (expr: clean, source: "block": true,
"description": "enforcement with a judge that returns CLEAN",
"judge": "scratch/clean-judge")
flow ~inferred click a branch to expand · @labels scroll to their anchor
inferred (source: "name": "shape-is-named",
"tags": ["dev"],
"rule": "every declared shape carries a name",
"check": "true")
flow ~inferred click a branch to expand · @labels scroll to their anchor
inferred (source: "name": "prose-rule",
"tags": ["dev"],
"rule": "a judgment-class row whose profile declares no judge")
flow ~inferred click a branch to expand · @labels scroll to their anchor
inferred (source: "name": "never-fires",
"tags": ["dev", "odds-0"],
"rule": "a row whose alarm can never roll low enough",
"check": "true")
flow ~inferred click a branch to expand · @labels scroll to their anchor
inferred (source: "name": "always-fires",
"tags": ["dev", "odds-100"],
"rule": "a row whose alarm always rolls low enough",
"check": "true")
flow ~inferred click a branch to expand · @labels scroll to their anchor
inferred (source: "name": "always-fails",
"tags": ["broken"],
"rule": "an instrument that always exits non-zero",
"check": "false")
flow ~inferred click a branch to expand · @labels scroll to their anchor
inferred (source: "name": "strict-rule",
"tags": ["strict"],
"rule": "a judgment-class row under an enforcing profile")
flow ~inferred click a branch to expand · @labels scroll to their anchor
inferred (source: "name": "clean-rule",
"tags": ["clean"],
"rule": "a judgment-class row whose judge returns CLEAN")
flow ~print.ln click a branch to expand · @labels scroll to their anchor
print.ln (expr: "gate-me")
Test Configuration
MUST_RUN LANGUAGES: zig cs
Post-validation Script:
#!/bin/bash
# The named-gate matrix. Git-dependent verdicts are driven through
# --repo into scratch repositories the test creates, so the pin does not
# depend on whatever happens to be staged in the enclosing repo.
set -u
cd "$(dirname "$0")"
fail() { echo "FAIL: $1"; exit 1; }
# 1. Bare `gate` lists declared profiles and their membership.
LIST=$(koruc "$KORU_INPUT" gate 2>&1)
echo "$LIST"
echo "$LIST" | grep -qE "dev +advisory +4 rows" || fail "dev profile not listed with 4 rows"
echo "$LIST" | grep -qE "broken +blocking +1 row" || fail "broken profile not listed blocking"
echo "$LIST" | grep -qE "strict +blocking +1 row" || fail "strict profile not listed blocking"
echo "$LIST" | grep -qE "clean +blocking +1 row" || fail "clean profile not listed blocking"
# 2. `gate dev` — advisory profile: the instrument runs, the judged row is
# reported (skip without a staged diff, UNJUDGED with one — both honest),
# and the odds modifiers roll deterministically.
DEV=$(koruc "$KORU_INPUT" gate dev 2>&1)
echo "$DEV"
echo "$DEV" | grep -qE "shape-is-named +check ok" || fail "check row did not pass"
echo "$DEV" | grep -qE "prose-rule +(no staged changes|UNJUDGED)" || fail "judged row not reported"
echo "$DEV" | grep -qE "never-fires +rolled [0-9]+, needed < 0" || fail "odds-0 row fired"
echo "$DEV" | grep -qE "always-fires +check ok · rolled [0-9]+ < 100" || fail "odds-100 row missed"
# 3. json verdicts — the machine-readable block.
JSON=$(koruc "$KORU_INPUT" gate dev json 2>&1)
echo "$JSON"
echo "$JSON" | grep -q '"profile":"dev"' || fail "json: profile missing"
echo "$JSON" | grep -q '"mode":"advisory"' || fail "json: mode missing"
echo "$JSON" | grep -q '"name":"shape-is-named","verdict":"pass"' || fail "json: pass verdict missing"
# 4. `gate broken` — a failing instrument blocks regardless of stance.
if koruc "$KORU_INPUT" gate broken > broken.log 2>&1; then
cat broken.log; fail "gate broken exited 0 on a failing check"
fi
cat broken.log
grep -qE "✗ always-fails +check failed" broken.log || fail "check failure not reported"
grep -q "blocking violation" broken.log || fail "blocking summary missing"
# 5. `gate nosuch` refuses and names the declared set.
if koruc "$KORU_INPUT" gate nosuch > nosuch.log 2>&1; then
cat nosuch.log; fail "gate nosuch exited 0"
fi
cat nosuch.log
grep -q "no profile named 'nosuch'" nosuch.log || fail "unknown-profile refusal missing"
grep -q "declared:" nosuch.log || fail "declared set not named"
# 6. `gate strict` over a scratch repo — the judgment row delegates to the
# profile's judge. The judge is an executable contract: argv is
# (rule, staged-state), the verdict is the first stdout line —
# VIOLATION / CLEAN / anything else reads UNJUDGED. These stubs speak
# the protocol; koru/odds is the real judge.
rm -rf scratch
mkdir -p scratch
git -C scratch init -q .
git -C scratch config user.email gate@test
git -C scratch config user.name gate-test
git -C scratch commit -qm init --allow-empty
# empty repo: no staged diff → the judged row skips, gate is clean
CLEAN0=$(koruc "$KORU_INPUT" gate strict --repo "$PWD/scratch" 2>&1) || fail "empty staged diff did not skip"
echo "$CLEAN0"
echo "$CLEAN0" | grep -qE "strict-rule +no staged changes" || fail "judge-skip missing"
printf '#!/bin/sh\necho "VIOLATION p=0.87"\n' > scratch/strict-judge
printf '#!/bin/sh\necho "CLEAN p=0.91"\n' > scratch/clean-judge
chmod +x scratch/strict-judge scratch/clean-judge
echo x > scratch/f.txt
git -C scratch add f.txt
# enforcing profile + a VIOLATION verdict → exit 1
if koruc "$KORU_INPUT" gate strict --repo "$PWD/scratch" > strict.log 2>&1; then
cat strict.log; fail "enforcing profile exited 0 on a judge VIOLATION"
fi
cat strict.log
grep -qE "✗ strict-rule +VIOLATION p=0.87" strict.log || fail "judge VIOLATION missing"
grep -q "blocking violation" strict.log || fail "enforcement did not block"
# the same verdict, softened by --advisory → exit 0
SOFT=$(koruc "$KORU_INPUT" gate strict --repo "$PWD/scratch" --advisory 2>&1) || fail "--advisory still blocked"
echo "$SOFT"
echo "$SOFT" | grep -q "advisory" || fail "advisory mode not reported"
# a CLEAN verdict passes an enforcing profile
CLEAN=$(koruc "$KORU_INPUT" gate clean --repo "$PWD/scratch" 2>&1) || fail "clean profile exited nonzero on CLEAN"
echo "$CLEAN"
echo "$CLEAN" | grep -qE "✓ clean-rule +CLEAN p=0.91" || fail "judge CLEAN missing"
echo "$CLEAN" | grep -q "gate clean — clean" || fail "clean verdict summary missing"
# a profile with no judge declared is honest about it — UNJUDGED with the
# cause, never a silent pass; --judge-only skips check rows entirely
DEVJ=$(koruc "$KORU_INPUT" gate dev --repo "$PWD/scratch" --judge-only 2>&1)
echo "$DEVJ"
echo "$DEVJ" | grep -qE "prose-rule +UNJUDGED" || fail "no-judge UNJUDGED missing"
echo "$DEVJ" | grep -q 'declares no "judge"' || fail "no-judge cause not named"
echo "$DEVJ" | grep -q "check ok" && fail "--judge-only ran a check row"
rm -rf scratch broken.log nosuch.log strict.log
echo "=== PASS: named gates select rows, delegate judgment, and enforce ==="