Compare commits

..
Author SHA1 Message Date
Gabriel 1520ee3242 agent_queue: add dry-run legacy issue migration inventory
Signed-off-by: Gabriel <gabriel05mortimer@gmail.com>
2026-11-23 23:40:04 -08:00
Ranveer Soni 0cac6c4fcf Merge pull request #214 from elforeign/test/metal-bc2-bc3
test(metal): BC2/BC3 upload and sampling conformance (#168)
2026-11-24 12:30:21 +05:30
Ranveer Soni b69d4b97c6 Merge pull request #166 from elforeign/feat/gpu-compatibility-expansion
isa: complete gfx1030 instruction metadata and identification
2026-11-24 12:26:27 +05:30
elforeign 6d7523f5d1 Merge upstream main into test/metal-bc2-bc3
Resolves the CHANGELOG.md conflict with the claim-rules entry; both
entries are kept.

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 00:55:23 -06:00
elforeign 59ee786a12 metal: upload and read BC2 and BC3 blocks natively
BC2 and BC3 had CPU decoders (#167) but no native Metal path, so nothing
showed that the original 16-byte blocks reach the GPU and decode as the
specifications describe. This adds a pitched BcAlphaUpload with the BC1
upload's validation (shared, now measured in 16-byte blocks) and
NativeCompute::read_bc_alpha_upload, which places the blocks in BC2_RGBA
or BC3_RGBA textures behind the existing BC capability check.

The GPU tests cover explicit 4-bit alpha, six- and eight-value
interpolated alpha (equal endpoints included), descending, ascending and
equal colour endpoints, padded row and slice pitches, two layers and two
mips. Texels are compared with the CPU decoders and hand-derived anchors.
On an Apple M5 Pro interpolated values lie within 1.14 codes of the exact
values, two codes at most from the truncating CPU reference, which sets
the tolerance. Uploading BC3 as BC2, BC2 as BC1, or ignoring the row
pitch each fails the tests.

Refs #168

Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com>
2026-11-24 00:49:17 -06:00
11 changed files with 1240 additions and 60 deletions

No files matched your search

+8
View File
@@ -11,7 +11,15 @@ remains unsupported.
### Added
- Added a dry-run legacy issue migration inventory (`scripts/agent_queue/migrate.py` and `python3 -m agent_queue migrate-inventory`) with unit tests (`tests/agent_queue/test_migrate.py`) and coordination docs (`docs/coordination/issue-migration.md`). Compares legacy `##` headings against the parser's `###` headings across area, owned files, acceptance command, and dependencies, preserves existing issue history in `### Context`, refuses to fabricate file ownership, and requires explicit maintainer approval before any issue edit or `agent:ready` label.
- 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 native Metal upload and readback of BC2 and BC3 textures: `xenora-texture` gains a
pitched `BcAlphaUpload` for 16-byte blocks, and `NativeCompute::read_bc_alpha_upload` sends
the original blocks to `BC2_RGBA` or `BC3_RGBA` textures when the device reports BC support.
GPU tests cover explicit and interpolated (six- and eight-value) alpha, both colour endpoint
orders, padded row and slice pitches, two layers and two mips against the CPU decoders and
hand-derived anchors. On an Apple M5 Pro the native decoder's interpolated values were within
1.14 codes of the exact values, so up to two codes from the truncating CPU reference.
- 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
+66 -21
View File
@@ -16,7 +16,7 @@ use objc2_metal::{
MTLResourceOptions, MTLShaderValidation, MTLSize, MTLStorageMode, MTLTexture,
MTLTextureDescriptor, MTLTextureUsage,
};
use xenora_texture::{Bc1Upload, TiledBc1};
use xenora_texture::{Bc1Upload, BcAlphaFormat, BcAlphaUpload, TiledBc1};
#[path = "render.rs"]
mod render;
@@ -26,12 +26,12 @@ const MAX_GROUPS: usize = 64;
const MAX_GRID_WORDS: usize = MAX_GROUPS * MAX_THREADS_PER_GROUP;
const MAX_SOURCE_BYTES: usize = 64 * 1024;
const BC1_READBACK: &str = r"
const BC_READBACK: &str = r"
#include <metal_stdlib>
using namespace metal;
kernel void read_bc1(texture2d<float, access::read> image [[texture(0)]],
device uint *output [[buffer(1)]],
uint index [[thread_position_in_grid]]) {
kernel void read_bc(texture2d<float, access::read> image [[texture(0)]],
device uint *output [[buffer(1)]],
uint index [[thread_position_in_grid]]) {
uint width = image.get_width();
uint4 channels = uint4(round(image.read(uint2(index % width, index / width)) * 255.0f));
output[index] = channels.r | (channels.g << 8u) | (channels.b << 16u) | (channels.a << 24u);
@@ -184,11 +184,18 @@ impl NativeCompute {
let (width, height) = tiled
.mip_extent(mip)
.map_err(|error| MetalError::new("texture subresource", format!("{error:?}")))?;
let pixels = self.validate_bc1_extent(width, height)?;
let pixels = self.validate_bc_extent(width, height, "BC1")?;
let blocks = tiled
.linearize(layer, mip)
.map_err(|error| MetalError::new("texture subresource", format!("{error:?}")))?;
self.read_bc1_blocks(&blocks, width.div_ceil(4) * 8, width, height, pixels)
self.read_bc_blocks(
MTLPixelFormat::BC1_RGBA,
&blocks,
width.div_ceil(4) * 8,
width,
height,
pixels,
)
}
/// Sample a native Metal RGBA8 texture using a native Metal sampler on Apple Silicon GPU.
@@ -269,8 +276,9 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
let level = upload
.subresource(layer, mip)
.map_err(|error| MetalError::new("texture subresource", format!("{error:?}")))?;
let pixels = self.validate_bc1_extent(level.width, level.height)?;
self.read_bc1_blocks(
let pixels = self.validate_bc_extent(level.width, level.height, "BC1")?;
self.read_bc_blocks(
MTLPixelFormat::BC1_RGBA,
level.bytes,
level.row_pitch,
level.width,
@@ -279,7 +287,45 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
)
}
fn validate_bc1_extent(&self, width: usize, height: usize) -> Result<usize, MetalError> {
/// Read a selected subresource from a validated pitched BC2 or BC3 upload.
///
/// The original 16-byte blocks go to a native `BC2_RGBA` or `BC3_RGBA`
/// texture, and the output has the layout of [`Self::read_bc1_upload`].
///
/// # Errors
///
/// Returns an error for an invalid layer or mip, out-of-policy size,
/// unavailable BC compression, or Metal setup or execution failure.
pub fn read_bc_alpha_upload(
&self,
upload: &BcAlphaUpload<'_>,
layer: usize,
mip: u32,
) -> Result<Vec<u32>, MetalError> {
let level = upload
.subresource(layer, mip)
.map_err(|error| MetalError::new("texture subresource", format!("{error:?}")))?;
let (format, name) = match upload.format() {
BcAlphaFormat::Bc2 => (MTLPixelFormat::BC2_RGBA, "BC2"),
BcAlphaFormat::Bc3 => (MTLPixelFormat::BC3_RGBA, "BC3"),
};
let pixels = self.validate_bc_extent(level.width, level.height, name)?;
self.read_bc_blocks(
format,
level.bytes,
level.row_pitch,
level.width,
level.height,
pixels,
)
}
fn validate_bc_extent(
&self,
width: usize,
height: usize,
name: &str,
) -> Result<usize, MetalError> {
let pixels = width
.checked_mul(height)
.filter(|pixels| (1..=MAX_GRID_WORDS).contains(pixels))
@@ -287,14 +333,15 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
if !self.device.supportsBCTextureCompression() {
return Err(MetalError::new(
"supportsBCTextureCompression",
"BC1 is unavailable",
format!("{name} is unavailable"),
));
}
Ok(pixels)
}
fn read_bc1_blocks(
fn read_bc_blocks(
&self,
format: MTLPixelFormat,
blocks: &[u8],
row_pitch: usize,
width: usize,
@@ -302,14 +349,11 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
pixels: usize,
) -> Result<Vec<u32>, MetalError> {
autoreleasepool(|_| {
// SAFETY: The positive bounded dimensions and supported BC1 format
// SAFETY: The positive bounded dimensions and supported BC format
// describe a 2D texture with just its base level.
let descriptor = unsafe {
MTLTextureDescriptor::texture2DDescriptorWithPixelFormat_width_height_mipmapped(
MTLPixelFormat::BC1_RGBA,
width,
height,
false,
format, width, height, false,
)
};
descriptor.setStorageMode(MTLStorageMode::Shared);
@@ -318,7 +362,7 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
.device
.newTextureWithDescriptor(&descriptor)
.ok_or_else(|| {
MetalError::new("newTextureWithDescriptor", "BC1 allocation failed")
MetalError::new("newTextureWithDescriptor", "BC allocation failed")
})?;
let region = MTLRegion {
origin: MTLOrigin { x: 0, y: 0, z: 0 },
@@ -332,7 +376,8 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
let bytes_per_row = if height <= 4 { 0 } else { row_pitch };
// SAFETY: The region spans the whole level, including any partial
// edge block. Both callers validate that the input holds all rows
// of complete BC1 blocks at the supplied, block-aligned stride.
// of complete blocks of this format at the supplied, block-aligned
// stride.
unsafe {
texture.replaceRegion_mipmapLevel_withBytes_bytesPerRow(
region,
@@ -342,8 +387,8 @@ kernel void sample_rgba8(texture2d<float, access::sample> tex [[texture(0)]],
);
}
self.run(
BC1_READBACK,
"read_bc1",
BC_READBACK,
"read_bc",
ComputeInput::Texture(&texture, pixels),
)
.map(|profile| profile.output)
@@ -0,0 +1,287 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Native Metal upload and readback of original BC2 and BC3 blocks.
//!
//! Every block below was written for this test. The full-texel reference is
//! the `xenora-texture` CPU decoder; the anchor texels are worked by hand from
//! the Microsoft Direct3D 11 block-compression documentation (BC2, BC3) and
//! the Khronos Data Format Specification 1.3 (S3TC DXT3/DXT5). Apple's GPU
//! decoder is the value under test, so expected and actual values come from
//! different decoders.
use super::context;
use xenora_texture::{BcAlphaFormat, BcAlphaUpload, BcAlphaUploadDesc, decode_bc2, decode_bc3};
/// The specifications define colour and BC3 alpha interpolation in real
/// numbers, and the CPU reference truncates them. On an Apple M5 Pro the
/// native decoder's interpolated values lie within 1.14 codes of the real
/// value (they match 6-bit fixed-point weights), so they can sit two codes
/// above the truncated reference: 124 against 122 for BC3 alpha
/// (4 * 200 + 3 * 20) / 7 = 122.86. Endpoints, BC2 alpha and BC3's fixed
/// 0 and 255 are exact and are pinned by the anchor checks.
const TOLERANCE: u8 = 2;
/// Bound for anchors against the real-number value of an interpolated code.
const REAL_TOLERANCE: f64 = 1.5;
fn assert_near(label: &str, actual: u8, real: f64) {
assert!(
(f64::from(actual) - real).abs() <= REAL_TOLERANCE,
"{label}: got {actual}, real value {real:.2}"
);
}
const WIDTH: usize = 5;
const HEIGHT: usize = 5;
const ROW_PITCH: usize = 48;
const SLICE_PITCH: usize = 112;
/// Colour half: two little-endian RGB565 endpoints, then 2-bit indices.
/// Every row of 0xe4 selects palette entries 0, 1, 2, 3 from left to right.
fn colour((first, second): (u16, u16)) -> [u8; 8] {
let [a, b] = first.to_le_bytes();
let [c, d] = second.to_le_bytes();
[a, b, c, d, 0xe4, 0xe4, 0xe4, 0xe4]
}
/// BC3 alpha half whose texel `t` selects palette entry `(t + 6) % 8`, so
/// every row starts with the indices 6 and 7 and a full block uses all eight.
fn bc3_alpha(first: u8, second: u8) -> [u8; 8] {
let bits = (0..16u64).fold(0, |bits, texel| bits | (((texel + 6) % 8) << (3 * texel)));
let i = bits.to_le_bytes();
[first, second, i[0], i[1], i[2], i[3], i[4], i[5]]
}
fn block(alpha: [u8; 8], colour: [u8; 8]) -> [u8; 16] {
let mut block = [0; 16];
block[..8].copy_from_slice(&alpha);
block[8..].copy_from_slice(&colour);
block
}
// First endpoint greater: red over blue.
const DESCENDING: (u16, u16) = (0xf800, 0x001f);
// First endpoint smaller, with odd channel values that exercise rounding.
const ASCENDING: (u16, u16) = (0x52aa, 0xad55);
// Equal endpoints: BC1 would decode index 3 as transparent black.
const EQUAL: (u16, u16) = (0x07e0, 0x07e0);
/// White with zero alpha (BC2 nibbles 0; BC3 endpoints 0 and 0) in every
/// padding slot, so a wrong row or slice pitch reads visibly wrong texels.
const PAD: [u8; 16] = [0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 0xff, 0xff, 0, 0, 0, 0];
/// Logical blocks of one layer: the 2×2 base-level grid, then mip 1.
type Layer = [[u8; 16]; 5];
/// Two layers of a 5×5 texture with two mips. Each subresource has seven
/// physical blocks: rows of two logical blocks plus one padding block, a
/// padding block that closes the slice, and mip 1 uses only its block zero.
fn upload_bytes(layers: [Layer; 2]) -> Vec<u8> {
let mut bytes = Vec::new();
for [b0, b1, b2, b3, small] in layers {
for slot in [b0, b1, PAD, b2, b3, PAD, PAD] {
bytes.extend_from_slice(&slot);
}
for slot in [small, PAD, PAD, PAD, PAD, PAD, PAD] {
bytes.extend_from_slice(&slot);
}
}
assert_eq!(bytes.len(), 2 * 2 * SLICE_PITCH);
bytes
}
/// Crops decoded blocks (a row-major block grid) to a `width`×`height` level
/// of words with red in the lowest byte, as the readback kernel writes them.
fn reference(blocks: &[[[u8; 4]; 16]], blocks_x: usize, width: usize, height: usize) -> Vec<u32> {
let mut texels = Vec::new();
for y in 0..height {
for x in 0..width {
let decoded = blocks[(y / 4) * blocks_x + x / 4];
texels.push(u32::from_le_bytes(decoded[(y % 4) * 4 + x % 4]));
}
}
texels
}
fn alpha(word: u32) -> u8 {
word.to_le_bytes()[3]
}
/// Returns the largest per-channel difference, failing on any texel above the
/// tolerance with its index and both values.
fn assert_close(label: &str, actual: &[u32], expected: &[u32]) -> u8 {
assert_eq!(actual.len(), expected.len(), "{label}: texel count");
let mut worst = 0;
for (texel, (&got, &want)) in actual.iter().zip(expected).enumerate() {
let diff = got
.to_le_bytes()
.iter()
.zip(want.to_le_bytes())
.map(|(g, w)| g.abs_diff(w))
.max()
.unwrap();
assert!(
diff <= TOLERANCE,
"{label}: texel {texel} got {got:#010x}, want {want:#010x}"
);
worst = worst.max(diff);
}
worst
}
/// GPU reads of both layers: `[layer][mip]`.
type Reads = [[Vec<u32>; 2]; 2];
/// Uploads both layers, reads all four subresources on the GPU, compares
/// them with the CPU decoder and returns the reads with the worst difference.
fn read_and_compare(
format: BcAlphaFormat,
decode: fn([u8; 16]) -> [[u8; 4]; 16],
layers: [Layer; 2],
) -> (Reads, u8) {
let bytes = upload_bytes(layers);
let upload = BcAlphaUpload::new(
&bytes,
BcAlphaUploadDesc {
width: WIDTH,
height: HEIGHT,
mips: 2,
layers: 2,
format,
row_pitch: ROW_PITCH,
slice_pitch: SLICE_PITCH,
},
)
.unwrap();
let gpu = context();
let mut worst = 0;
let reads = std::array::from_fn(|layer| {
let decoded = layers[layer].map(decode);
let base = gpu.read_bc_alpha_upload(&upload, layer, 0).unwrap();
let expected = reference(&decoded[..4], 2, WIDTH, HEIGHT);
let label = format!("{format:?} layer {layer}");
worst = worst.max(assert_close(&format!("{label} mip 0"), &base, &expected));
let small = gpu.read_bc_alpha_upload(&upload, layer, 1).unwrap();
let expected = reference(&decoded[4..], 1, 2, 2);
worst = worst.max(assert_close(&format!("{label} mip 1"), &small, &expected));
[base, small]
});
for (layer, mip) in [(2, 0), (0, 2)] {
assert_eq!(
gpu.read_bc_alpha_upload(&upload, layer, mip)
.unwrap_err()
.operation,
"texture subresource"
);
}
(reads, worst)
}
#[test]
fn reads_pitched_bc2_explicit_alpha_across_mips_and_layers() {
// Nibble t in texel t, low nibble first: alpha t * 17.
let ramp = [0x10, 0x32, 0x54, 0x76, 0x98, 0xba, 0xdc, 0xfe];
let reverse = ramp.map(|byte: u8| !byte);
let opaque = [0xff; 8];
let [descending, ascending, equal] = [DESCENDING, ASCENDING, EQUAL].map(colour);
let (reads, worst) = read_and_compare(
BcAlphaFormat::Bc2,
decode_bc2,
[
[
block(ramp, descending),
block(reverse, ascending),
block(opaque, equal),
block(ramp, ascending),
block(reverse, descending),
],
[
block(opaque, ascending),
block(ramp, equal),
block(reverse, descending),
block(opaque, descending),
block(ramp, equal),
],
],
);
// Hand-derived anchors, independent of the CPU decoder.
let base = &reads[0][0];
// (0, 0): red endpoint, nibble 0. (1, 0): blue endpoint, nibble 1.
assert_eq!(base[0], 0x0000_00ff);
assert_eq!(base[1], 0x11ff_0000);
// (0, 2) is texel 8 of block 0: red endpoint, nibble 8 -> 0x88.
assert_eq!(base[2 * WIDTH], 0x8800_00ff);
// (3, 3) is texel 15 of block 0: nibble 15 -> opaque.
assert_eq!(alpha(base[3 * WIDTH + 3]), 0xff);
// (4, 0) is texel 0 of block 1: reversed ramp, nibble 15.
assert_eq!(alpha(base[4]), 0xff);
// (3, 4) is index 3 of block 2's equal green endpoints: opaque green,
// not BC1's transparent black.
assert_eq!(base[4 * WIDTH + 3], 0xff00_ff00);
// Layer 1 mip 1: green endpoints, ramp nibbles 0, 1, 4, 5.
assert_eq!(
reads[1][1],
[0x0000_ff00, 0x1100_ff00, 0x4400_ff00, 0x5500_ff00]
);
println!("checked 58 BC2 texels from four subresources, worst channel difference {worst}");
}
#[test]
fn reads_pitched_bc3_interpolated_alpha_across_mips_and_layers() {
// First endpoint greater: eight-value palette.
let eight = bc3_alpha(200, 20);
// First endpoint smaller: six-value palette with fixed 0 and 255.
let six = bc3_alpha(20, 200);
// Equal endpoints also select the six-value palette.
let level = bc3_alpha(128, 128);
let [descending, ascending, equal] = [DESCENDING, ASCENDING, EQUAL].map(colour);
let (reads, worst) = read_and_compare(
BcAlphaFormat::Bc3,
decode_bc3,
[
[
block(eight, descending),
block(six, ascending),
block(level, equal),
block(eight, ascending),
block(six, descending),
],
[
block(six, equal),
block(eight, ascending),
block(level, descending),
block(six, ascending),
block(eight, equal),
],
],
);
// Hand-derived anchors, independent of the CPU decoder.
let base = &reads[0][0];
let a = |x: usize, y: usize| alpha(base[y * WIDTH + x]);
// Block 0, eight-value: row 0 holds indices 6, 7, 0, 1, and row 1
// indices 2, 3, 4, 5, each (k = index - 1) ((7 - k) * 200 + k * 20) / 7.
assert_near("index 6", a(0, 0), (2.0 * 200.0 + 5.0 * 20.0) / 7.0);
assert_near("index 7", a(1, 0), (200.0 + 6.0 * 20.0) / 7.0);
for (x, k) in (0..4).zip(1..) {
let real = f64::from((7 - k) * 200 + k * 20) / 7.0;
assert_near(&format!("index {}", k + 1), a(x, 1), real);
}
// Then the endpoints themselves, exactly; texel (0, 0) is the red endpoint.
assert_eq!([a(2, 0), a(3, 0)], [200, 20]);
assert_eq!(base[0] & 0x00ff_ffff, 0x0000_00ff);
// Block 1, six-value: column 4 holds indices 6, 2, 6, 2. Index 6 is the
// fixed 0 and index 2 is (4 * 20 + 200) / 5 = 56.
assert_eq!([a(4, 0), a(4, 2)], [0, 0]);
assert_near("six-value index 2", a(4, 1), 56.0);
assert_near("six-value index 2", a(4, 3), 56.0);
// Block 2, equal endpoints of 128: row 4 holds indices 6, 7, 0, 1, so the
// six-value mode shows as the fixed 0 and 255.
assert_eq!([a(0, 4), a(1, 4), a(2, 4), a(3, 4)], [0, 255, 128, 128]);
// Mip 1, six-value: indices 6, 7, 2, 3 -> 0, 255, 56, (3 * 20 + 2 * 200) / 5 = 92.
let small: Vec<_> = reads[0][1].iter().copied().map(alpha).collect();
assert_eq!(small[..2], [0, 255]);
assert_near("six-value index 2", small[2], 56.0);
assert_near("six-value index 3", small[3], 92.0);
println!("checked 58 BC3 texels from four subresources, worst channel difference {worst}");
}
+2
View File
@@ -6,6 +6,8 @@ mod guest_buffer;
mod offscreen;
#[path = "native/texture.rs"]
mod texture;
#[path = "native/texture_bc_alpha.rs"]
mod texture_bc_alpha;
#[path = "native/texture_sampling.rs"]
mod texture_sampling;
#[path = "native/translated_render.rs"]
+3 -1
View File
@@ -14,7 +14,9 @@ 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};
pub use upload::{
Bc1Subresource, Bc1Upload, Bc1UploadDesc, BcAlphaFormat, BcAlphaUpload, BcAlphaUploadDesc,
};
const BLOCK_BYTES: usize = 8;
const TILE_BLOCKS: usize = 2;
+207 -37
View File
@@ -32,56 +32,153 @@ pub struct Bc1Subresource<'a> {
impl<'a> Bc1Upload<'a> {
pub fn new(bytes: &'a [u8], desc: Bc1UploadDesc) -> Result<Self, TextureError> {
let max_mips = usize::BITS - desc.width.max(desc.height).leading_zeros();
if desc.format != 1
|| desc.usage != 1
|| desc.width == 0
|| desc.height == 0
|| desc.layers == 0
|| desc.mips == 0
|| desc.mips > max_mips
{
if desc.format != 1 || desc.usage != 1 {
return Err(TextureError::InvalidLayout);
}
let (blocks_x, blocks_y) = mip_blocks(desc.width, desc.height, 0);
let tight_row = blocks_x
.checked_mul(BLOCK_BYTES)
.ok_or(TextureError::SizeOverflow)?;
if desc.row_pitch < tight_row || !desc.row_pitch.is_multiple_of(BLOCK_BYTES) {
return Err(TextureError::InvalidLayout);
}
let minimum_slice = desc
.row_pitch
.checked_mul(blocks_y)
.ok_or(TextureError::SizeOverflow)?;
if desc.slice_pitch < minimum_slice || !desc.slice_pitch.is_multiple_of(BLOCK_BYTES) {
return Err(TextureError::InvalidLayout);
}
let size = desc
.slice_pitch
.checked_mul(desc.mips as usize)
.and_then(|size| size.checked_mul(desc.layers))
.ok_or(TextureError::SizeOverflow)?;
if bytes.len() != size {
return Err(TextureError::InvalidByteLength);
}
Self::layout(desc).validate(bytes.len(), BLOCK_BYTES)?;
Ok(Self { bytes, desc })
}
pub fn subresource(&self, layer: usize, mip: u32) -> Result<Bc1Subresource<'a>, TextureError> {
if layer >= self.desc.layers || mip >= self.desc.mips {
Self::layout(self.desc).subresource(self.bytes, layer, mip)
}
fn layout(desc: Bc1UploadDesc) -> PitchedLayout {
PitchedLayout {
width: desc.width,
height: desc.height,
mips: desc.mips,
layers: desc.layers,
row_pitch: desc.row_pitch,
slice_pitch: desc.slice_pitch,
}
}
}
/// A block-compressed format whose 16-byte block holds an alpha half followed
/// by a BC1-style colour half.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BcAlphaFormat {
/// Explicit 4-bit alpha per texel.
Bc2,
/// Interpolated alpha from two 8-bit endpoints and 3-bit indices.
Bc3,
}
/// A layer-major BC2 or BC3 upload with the same pitch rules as
/// [`Bc1UploadDesc`], measured in 16-byte blocks.
#[derive(Clone, Copy, Debug)]
pub struct BcAlphaUploadDesc {
pub width: usize,
pub height: usize,
pub mips: u32,
pub layers: usize,
pub format: BcAlphaFormat,
pub row_pitch: usize,
pub slice_pitch: usize,
}
#[derive(Debug)]
pub struct BcAlphaUpload<'a> {
bytes: &'a [u8],
desc: BcAlphaUploadDesc,
}
impl<'a> BcAlphaUpload<'a> {
/// Size of one BC2 or BC3 block in bytes.
pub const BLOCK_BYTES: usize = 16;
pub fn new(bytes: &'a [u8], desc: BcAlphaUploadDesc) -> Result<Self, TextureError> {
Self::layout(desc).validate(bytes.len(), Self::BLOCK_BYTES)?;
Ok(Self { bytes, desc })
}
pub fn format(&self) -> BcAlphaFormat {
self.desc.format
}
/// Selects one level; the returned rows hold 16-byte blocks.
pub fn subresource(&self, layer: usize, mip: u32) -> Result<Bc1Subresource<'a>, TextureError> {
Self::layout(self.desc).subresource(self.bytes, layer, mip)
}
fn layout(desc: BcAlphaUploadDesc) -> PitchedLayout {
PitchedLayout {
width: desc.width,
height: desc.height,
mips: desc.mips,
layers: desc.layers,
row_pitch: desc.row_pitch,
slice_pitch: desc.slice_pitch,
}
}
}
/// Format-independent pitch rules shared by the pitched uploads.
struct PitchedLayout {
width: usize,
height: usize,
mips: u32,
layers: usize,
row_pitch: usize,
slice_pitch: usize,
}
impl PitchedLayout {
fn validate(&self, len: usize, block_bytes: usize) -> Result<(), TextureError> {
let max_mips = usize::BITS - self.width.max(self.height).leading_zeros();
if self.width == 0
|| self.height == 0
|| self.layers == 0
|| self.mips == 0
|| self.mips > max_mips
{
return Err(TextureError::InvalidLayout);
}
let (blocks_x, blocks_y) = mip_blocks(self.width, self.height, 0);
let tight_row = blocks_x
.checked_mul(block_bytes)
.ok_or(TextureError::SizeOverflow)?;
if self.row_pitch < tight_row || !self.row_pitch.is_multiple_of(block_bytes) {
return Err(TextureError::InvalidLayout);
}
let minimum_slice = self
.row_pitch
.checked_mul(blocks_y)
.ok_or(TextureError::SizeOverflow)?;
if self.slice_pitch < minimum_slice || !self.slice_pitch.is_multiple_of(block_bytes) {
return Err(TextureError::InvalidLayout);
}
let size = self
.slice_pitch
.checked_mul(self.mips as usize)
.and_then(|size| size.checked_mul(self.layers))
.ok_or(TextureError::SizeOverflow)?;
if len != size {
return Err(TextureError::InvalidByteLength);
}
Ok(())
}
fn subresource<'a>(
&self,
bytes: &'a [u8],
layer: usize,
mip: u32,
) -> Result<Bc1Subresource<'a>, TextureError> {
if layer >= self.layers || mip >= self.mips {
return Err(TextureError::OutOfBounds);
}
// Construction proved that the complete array fits in the source span.
let offset = (layer * self.desc.mips as usize + mip as usize) * self.desc.slice_pitch;
let width = (self.desc.width >> mip).max(1);
let height = (self.desc.height >> mip).max(1);
let offset = (layer * self.mips as usize + mip as usize) * self.slice_pitch;
let width = (self.width >> mip).max(1);
let height = (self.height >> mip).max(1);
let rows = height.div_ceil(4);
Ok(Bc1Subresource {
bytes: &self.bytes[offset..offset + rows * self.desc.row_pitch],
bytes: &bytes[offset..offset + rows * self.row_pitch],
width,
height,
row_pitch: self.desc.row_pitch,
row_pitch: self.row_pitch,
})
}
}
@@ -182,4 +279,77 @@ mod tests {
);
}
}
const ALPHA_DESC: BcAlphaUploadDesc = BcAlphaUploadDesc {
width: 5,
height: 5,
mips: 2,
layers: 2,
format: BcAlphaFormat::Bc3,
row_pitch: 48,
slice_pitch: 112,
};
#[test]
fn selects_bc_alpha_subresources_in_sixteen_byte_blocks() {
let mut bytes = [0; 448];
// Layer 1 starts at 224; its base row 1, block 1 is at 224 + 48 + 16.
bytes[288..304].fill(0x5c);
bytes[336] = 0xa7; // Layer 1, mip 1, block 0.
let upload = BcAlphaUpload::new(&bytes, ALPHA_DESC).unwrap();
assert_eq!(upload.format(), BcAlphaFormat::Bc3);
let base = upload.subresource(1, 0).unwrap();
assert_eq!((base.width, base.height, base.row_pitch), (5, 5, 48));
assert_eq!(base.bytes.len(), 96);
assert_eq!(base.bytes[64..80], [0x5c; 16]);
let small = upload.subresource(1, 1).unwrap();
assert_eq!((small.width, small.height, small.bytes.len()), (2, 2, 48));
assert_eq!(small.bytes[0], 0xa7);
assert_eq!(
upload.subresource(2, 0).unwrap_err(),
TextureError::OutOfBounds
);
assert_eq!(
upload.subresource(0, 2).unwrap_err(),
TextureError::OutOfBounds
);
}
#[test]
fn rejects_bc1_pitches_for_sixteen_byte_blocks() {
let bytes = [0; 448];
// Each pitch is a valid BC1 multiple of 8 but not of 16, or is
// shorter than two 16-byte blocks.
for desc in [
BcAlphaUploadDesc {
row_pitch: 24,
..ALPHA_DESC
},
BcAlphaUploadDesc {
row_pitch: 40,
..ALPHA_DESC
},
BcAlphaUploadDesc {
slice_pitch: 104,
..ALPHA_DESC
},
BcAlphaUploadDesc {
slice_pitch: 80,
..ALPHA_DESC
},
BcAlphaUploadDesc {
mips: 4,
..ALPHA_DESC
},
] {
assert_eq!(
BcAlphaUpload::new(&bytes, desc).unwrap_err(),
TextureError::InvalidLayout
);
}
assert_eq!(
BcAlphaUpload::new(&bytes[..447], ALPHA_DESC).unwrap_err(),
TextureError::InvalidByteLength
);
}
}
+1
View File
@@ -49,3 +49,4 @@ either path. The [changelog](../CHANGELOG.md) records notable changes.
- [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.
- [Legacy issue migration inventory](coordination/issue-migration.md) — Dry-run inventory for migrating legacy `##` issue headings to the `###` agent-task form with explicit maintainer review.
+50
View File
@@ -0,0 +1,50 @@
# Legacy Issue Migration Inventory
The agent task queue parser (`scripts/agent_queue/tasks.py`) reads GitHub issue-form fields from
level-3 Markdown headings (`### Area`, `### Priority`, `### Files`, `### Acceptance command`,
`### Depends on`, `### Interface`). Earlier backlog issues in Xenora use level-2 headings (`## Area`,
`## Files`, `## Acceptance command`, `## Depends on`, `## Objective and acceptance criteria`), so the
parser sees empty `area`, `files`, `acceptance`, and `depends` fields until those issues are
migrated to the agent task form.
## Safety rules
1. **Dry-run by default:** `migrate-inventory` is read-only. It never edits GitHub issues and never
adds `agent:ready` labels.
2. **Explicit maintainer review required:** Every non-compliant issue is flagged with
`requires_maintainer_review: true` and `safe_to_apply_without_review: false`. Maintainers must
review each proposed body before applying edits or adding `agent:ready`.
3. **Never fabricate file ownership:** Issues without an explicit `Files` section are classified as
`incomplete` with `missing_fields: ["files"]`. `plan_apply` refuses to generate an edit or
`agent:ready` label for any incomplete issue until a maintainer explicitly supplies owned paths.
4. **Preserve issue history:** Proposed migrated bodies map recognized legacy `##` sections to the
canonical `###` headings and preserve any original preamble text and unrecognized `##` sections
verbatim under `### Context`.
5. **Text is data only:** Issue text is parsed with fixed string and regular-expression rules and is
never executed. Code fences inside `Files` sections are stripped so fence markers (such as
`text`) are never treated as owned paths.
## Running the dry-run inventory
Gather open issues into a local state snapshot, then inspect the inventory as JSON or a review table:
```sh
PYTHONPATH=scripts python3 -m agent_queue gather --repo ranveersoni98/Xenora --no-prs > state.json
PYTHONPATH=scripts python3 -m agent_queue migrate-inventory --state state.json --text
PYTHONPATH=scripts python3 -m agent_queue migrate-inventory --state state.json > migration-inventory.json
```
Each issue in the inventory is classified into one of three states:
- `compliant` — already uses `###` headings with a valid `Area`, explicit `Files`, and a non-empty
`Acceptance command`.
- `legacy_migratable` — uses `##` or mixed `##`/`###` headings and already declares explicit `Area`,
`Files`, and `Acceptance command`; includes a non-destructive `proposed_body` for maintainer review.
- `incomplete` — missing one or more required fields (`area`, `files`, or `acceptance command`);
blocked from automated edits and `agent:ready` labeling until completed by a maintainer.
## Tests
```sh
PYTHONPATH=scripts python3 -m unittest discover -s tests/agent_queue -v
```
+8 -1
View File
@@ -8,7 +8,7 @@ from datetime import datetime, timezone
from . import config as cfgmod
from . import ghio
from . import lease as L
from . import prcheck, queue
from . import migrate, prcheck, queue
from . import tasks as T
from . import decide as decide_mod
from .decide import decide
@@ -48,6 +48,7 @@ def main(argv):
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("migrate-inventory"); s.add_argument("--state", required=True); s.add_argument("--text", action="store_true"); s.add_argument("--include-closed", action="store_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)
@@ -139,6 +140,12 @@ def main(argv):
return 1
print("area:" + t["area"])
print("priority:" + t["priority"])
elif a.cmd == "migrate-inventory":
res = migrate.inventory(_load(a.state), include_closed=a.include_closed)
if a.text:
sys.stdout.write(migrate.format_report(res))
else:
_out(res)
elif a.cmd == "touch":
# stdin lines "<sha>\t<path>"; report those touching patterns of tasks held by login
state, hits = _load(a.state), []
+364
View File
@@ -0,0 +1,364 @@
# SPDX-License-Identifier: GPL-3.0-or-later
"""Dry-run migration inventory for legacy ## issue bodies versus ### agent-task headings.
Text is data only: nothing parsed from issue bodies is ever executed.
Never fabricates file ownership or edits issues without explicit maintainer approval.
"""
import re
from . import config as cfgmod
from . import tasks as T
HEADING = re.compile(r"^(#{2,3})\s+(.+?)\s*$")
PLACEHOLDER = "_no response_"
ALIASES = {
"area": "area",
"priority": "priority",
"interface": "interface",
"goal": "goal",
"objective": "goal",
"objective and acceptance criteria": "goal",
"files": "files",
"owned files": "files",
"acceptance command": "acceptance command",
"acceptance": "acceptance command",
"depends on": "depends on",
"dependencies": "depends on",
"context": "context",
}
CANONICAL_ORDER = (
("area", "Area"),
("priority", "Priority"),
("interface", "Interface"),
("goal", "Goal"),
("files", "Files"),
("acceptance command", "Acceptance command"),
("depends on", "Depends on"),
("context", "Context"),
)
def parse_sections_with_levels(body):
"""Parse ## and ### headings while ignoring headings inside fenced code blocks.
Returns (preamble, entries) where each entry is (level, raw_heading, text).
"""
text = (body or "").replace("\r\n", "\n")
lines = text.split("\n")
in_fence = False
preamble_lines = []
entries = []
cur = None
for line in lines:
stripped = line.strip()
if stripped.startswith("```"):
in_fence = not in_fence
if cur is None:
preamble_lines.append(line)
else:
cur[2].append(line)
continue
if not in_fence:
m = HEADING.match(line)
if m:
if cur is not None:
entries.append((cur[0], cur[1], "\n".join(cur[2]).strip()))
cur = (len(m.group(1)), m.group(2).strip(), [])
continue
if cur is None:
preamble_lines.append(line)
else:
cur[2].append(line)
if cur is not None:
entries.append((cur[0], cur[1], "\n".join(cur[2]).strip()))
preamble = "\n".join(preamble_lines).strip()
return preamble, entries
def _clean_text(text):
t = (text or "").strip()
return "" if t.lower() == PLACEHOLDER else t
def _parse_files(text):
"""Extract owned file patterns without leaking code fence markers or fabricating paths."""
out = []
for raw in (text or "").splitlines():
line = raw.strip()
if not line or line.startswith("```"):
continue
if line.startswith(("- ", "* ")):
line = line[2:].strip()
line = line.strip("`").strip()
if not line or line.lower() == PLACEHOLDER:
continue
out.append(line)
return out
def _heading_style(entries):
levels = {lvl for lvl, _, _ in entries}
if not levels:
return "none"
if levels == {3}:
return "h3"
if levels == {2}:
return "h2_legacy"
return "mixed"
def render_migrated_body(preamble, canonical, extra_sections, parsed):
"""Render a ### agent-task body while preserving preamble and extra legacy sections."""
blocks = []
def add(heading, value):
blocks.append("### %s\n\n%s" % (heading, value if value else "_No response_"))
add("Area", parsed["area"])
add("Priority", parsed["priority"])
add("Interface", canonical.get("interface", ""))
add("Goal", canonical.get("goal", ""))
if parsed["files"]:
files_text = "\n".join("- %s" % p for p in parsed["files"])
else:
files_text = ""
add("Files", files_text)
acc = T.normalise_acceptance(parsed["acceptance"])
add("Acceptance command", acc)
deps_raw = canonical.get("depends on", "")
if not deps_raw and parsed["depends"]:
deps_raw = ", ".join("#%d" % n for n in parsed["depends"])
add("Depends on", deps_raw)
context_parts = []
if canonical.get("context"):
context_parts.append(canonical["context"])
if preamble:
context_parts.append("Preserved issue preamble:\n\n" + preamble)
for lvl, raw_heading, raw_text in extra_sections:
if raw_text:
context_parts.append("%s %s\n\n%s" % ("#" * lvl, raw_heading, raw_text))
else:
context_parts.append("%s %s" % ("#" * lvl, raw_heading))
add("Context", "\n\n".join(context_parts))
return "\n\n".join(blocks) + "\n"
def classify_issue(issue):
"""Inspect one issue dict and build a dry-run migration inventory record."""
body = issue.get("body") or ""
labels = T.label_names(issue)
current = T.parse_task(issue)
preamble, entries = parse_sections_with_levels(body)
style = _heading_style(entries)
canonical = {}
extra_sections = []
warnings = []
raw_area_text = ""
for lvl, raw_heading, raw_text in entries:
cleaned = _clean_text(raw_text)
key = ALIASES.get(raw_heading.lower())
if key is None:
extra_sections.append((lvl, raw_heading, cleaned))
continue
if key == "area":
raw_area_text = cleaned.strip().lower()
if key in canonical and cleaned:
if canonical[key]:
canonical[key] = canonical[key] + "\n\n" + cleaned
else:
canonical[key] = cleaned
else:
canonical[key] = cleaned
area_candidate = raw_area_text or T.label_value(labels, "area:")
area = area_candidate if area_candidate in cfgmod.AREAS else ""
if raw_area_text and raw_area_text not in cfgmod.AREAS:
warnings.append("unrecognized_area")
prio_candidate = canonical.get("priority", "").strip().lower() or T.label_value(labels, "priority:")
priority = prio_candidate if prio_candidate in cfgmod.PRIORITIES else "medium"
if canonical.get("priority", "").strip() and prio_candidate not in cfgmod.PRIORITIES:
warnings.append("unrecognized_priority")
files = _parse_files(canonical.get("files", ""))
acceptance = canonical.get("acceptance command", "")
depends = sorted({int(n) for n in re.findall(r"#(\d+)", canonical.get("depends on", ""))})
interface = canonical.get("interface", "")
parsed_legacy = {
"area": area,
"priority": priority,
"files": files,
"depends": depends,
"acceptance": T.normalise_acceptance(acceptance),
"interface": interface,
}
missing = []
if not area:
missing.append("area")
if not files:
missing.append("files")
warnings.append("no_explicit_file_ownership")
if not parsed_legacy["acceptance"]:
missing.append("acceptance command")
if style in ("h2_legacy", "mixed"):
warnings.append("legacy_h2_headings")
if preamble or extra_sections:
warnings.append("extra_content_preserved_in_context")
current_ok = (
style == "h3"
and bool(current["area"])
and bool(current["files"])
and bool(T.normalise_acceptance(current["acceptance"]))
and not any(f.startswith("```") or f in ("text", "sh") for f in current["files"])
)
if current_ok:
status = "compliant"
proposed_body = None
elif not missing:
status = "legacy_migratable"
proposed_body = render_migrated_body(preamble, canonical, extra_sections, parsed_legacy)
else:
status = "incomplete"
proposed_body = render_migrated_body(preamble, canonical, extra_sections, parsed_legacy)
parser_gap = {
"area_missed": bool(area) and current["area"] != area,
"files_missed": bool(files) and current["files"] != files,
"acceptance_missed": bool(parsed_legacy["acceptance"])
and T.normalise_acceptance(current["acceptance"]) != parsed_legacy["acceptance"],
"depends_missed": bool(depends) and current["depends"] != depends,
}
return {
"number": int(issue["number"]),
"title": issue.get("title", ""),
"state": str(issue.get("state", "OPEN")).upper(),
"labels": labels,
"status": status,
"heading_style": style,
"current_parsed": {
"area": current["area"],
"priority": current["priority"],
"files": current["files"],
"depends": current["depends"],
"acceptance": T.normalise_acceptance(current["acceptance"]),
"interface": current["interface"],
},
"legacy_parsed": parsed_legacy,
"parser_gap": parser_gap,
"missing_fields": missing,
"warnings": warnings,
"requires_maintainer_review": status != "compliant",
"safe_to_apply_without_review": False,
"proposed_body": proposed_body,
}
def inventory(state, include_closed=False):
"""Build a dry-run migration inventory across issues in a gathered state dict."""
items = []
for issue in state.get("issues") or []:
st = str(issue.get("state", "OPEN")).upper()
if not include_closed and st != "OPEN":
continue
items.append(classify_issue(issue))
items.sort(key=lambda r: r["number"])
counts = {"compliant": 0, "legacy_migratable": 0, "incomplete": 0}
for r in items:
counts[r["status"]] += 1
return {
"dry_run": True,
"total": len(items),
"counts": counts,
"issues": items,
}
def format_report(report):
"""Format a dry-run inventory as a concise human-readable review table."""
c = report["counts"]
lines = [
"Dry-run issue migration inventory (no issues edited, no labels changed)",
"Total: %d | compliant: %d | legacy_migratable: %d | incomplete: %d"
% (report["total"], c["compliant"], c["legacy_migratable"], c["incomplete"]),
"",
"number\tstatus\theading_style\tarea\tfiles\tdepends\tmissing\ttitle",
]
for r in report["issues"]:
lp = r["legacy_parsed"]
lines.append(
"#%d\t%s\t%s\t%s\t%d\t%s\t%s\t%s"
% (
r["number"],
r["status"],
r["heading_style"],
lp["area"] or "-",
len(lp["files"]),
",".join("#%d" % d for d in lp["depends"]) or "-",
",".join(r["missing_fields"]) or "-",
r["title"],
)
)
return "\n".join(lines) + "\n"
def plan_apply(report, approved_issues, actor, cfg, add_ready=False):
"""Produce guarded edit plans only for maintainer-approved, complete legacy issues.
Never fabricates missing fields or file ownership, and never adds agent:ready unless
explicitly requested by a maintainer for a complete issue.
"""
if not cfgmod.is_maintainer(cfg, actor):
return {
"ok": False,
"error": "only a maintainer may approve issue body migrations or ready labels",
"actions": [],
"skipped": [],
}
approved = {int(n) for n in approved_issues}
actions = []
skipped = []
for r in report.get("issues") or []:
n = r["number"]
if n not in approved:
continue
if r["status"] == "compliant":
skipped.append({"issue": n, "reason": "already compliant"})
continue
if r["status"] != "legacy_migratable" or r["missing_fields"]:
skipped.append(
{
"issue": n,
"reason": "incomplete (missing: %s); maintainer must supply explicit fields without fabricating ownership"
% ", ".join(r["missing_fields"]),
}
)
continue
actions.append(
{
"issue": n,
"edit_body": r["proposed_body"],
"add_labels": ["agent:ready"] if add_ready else [],
"preserved_history": True,
"approved_by": actor,
}
)
return {"ok": True, "actions": actions, "skipped": skipped}
+244
View File
@@ -0,0 +1,244 @@
# SPDX-License-Identifier: GPL-3.0-or-later
import json
import os
import subprocess
import sys
import tempfile
import unittest
sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "..", "scripts"))
from agent_queue import migrate as M
from agent_queue import tasks as T
from helpers import CFG, ROOT, issue
LEGACY_H2_BODY = """## Area
shared
## Priority
high
## Files
- `scripts/agent_queue/`
- `tests/agent_queue/`
- `docs/coordination/`
## Acceptance command
```sh
PYTHONPATH=scripts python3 -m unittest discover -s tests/agent_queue
```
## Depends on
#165
## Interface
Existing public interfaces; coordinate changes before editing.
## Objective and acceptance criteria
Build a dry-run migration inventory for legacy ## headings versus ### headings.
Baseline: 951189c; preserve existing issue history.
"""
INCOMPLETE_LEGACY_BODY = """## Area
runtime
## Priority
medium
## Acceptance command
cargo test --workspace
## Objective and acceptance criteria
Add missing runtime checks without guessing owned paths.
"""
COMPLIANT_H3_BODY = """### Area
gpu
### Priority
high
### Files
crates/xenora-metal/
### Acceptance command
cargo test -p xenora-metal
### Depends on
#165
"""
class MigrationInventory(unittest.TestCase):
def test_reproducible_gap_and_round_trip(self):
i = {"number": 179, "title": "[SHARED] Migrate legacy issues", "state": "OPEN", "labels": ["p2"], "body": LEGACY_H2_BODY}
# Reproducible gap: current ### parser misses every legacy ## section.
current = T.parse_task(i)
self.assertEqual(current["area"], "")
self.assertEqual(current["files"], [])
self.assertEqual(current["depends"], [])
self.assertEqual(current["acceptance"], "")
rec = M.classify_issue(i)
self.assertEqual(rec["status"], "legacy_migratable")
self.assertEqual(rec["heading_style"], "h2_legacy")
self.assertTrue(rec["requires_maintainer_review"])
self.assertFalse(rec["safe_to_apply_without_review"])
self.assertEqual(rec["missing_fields"], [])
self.assertEqual(rec["legacy_parsed"]["area"], "shared")
self.assertEqual(rec["legacy_parsed"]["priority"], "high")
self.assertEqual(
rec["legacy_parsed"]["files"],
["scripts/agent_queue/", "tests/agent_queue/", "docs/coordination/"],
)
self.assertEqual(rec["legacy_parsed"]["depends"], [165])
self.assertEqual(
rec["legacy_parsed"]["acceptance"],
"PYTHONPATH=scripts python3 -m unittest discover -s tests/agent_queue",
)
self.assertTrue(all(rec["parser_gap"].values()))
# Round-trip: proposed ### body parses cleanly under tasks.parse_task.
reparsed = T.parse_task({"number": 179, "title": i["title"], "state": "OPEN", "labels": [], "body": rec["proposed_body"]})
self.assertEqual(reparsed["area"], "shared")
self.assertEqual(reparsed["priority"], "high")
self.assertEqual(
reparsed["files"],
["scripts/agent_queue/", "tests/agent_queue/", "docs/coordination/"],
)
self.assertEqual(reparsed["depends"], [165])
self.assertEqual(
T.normalise_acceptance(reparsed["acceptance"]),
"PYTHONPATH=scripts python3 -m unittest discover -s tests/agent_queue",
)
self.assertIn("Baseline: 951189c; preserve existing issue history.", rec["proposed_body"])
def test_never_fabricates_file_ownership(self):
i = {"number": 201, "title": "[RUNTIME] Missing files", "state": "OPEN", "labels": [], "body": INCOMPLETE_LEGACY_BODY}
rec = M.classify_issue(i)
self.assertEqual(rec["status"], "incomplete")
self.assertEqual(rec["legacy_parsed"]["files"], [])
self.assertIn("files", rec["missing_fields"])
self.assertIn("no_explicit_file_ownership", rec["warnings"])
self.assertTrue(rec["requires_maintainer_review"])
def test_preserves_preamble_and_extra_sections(self):
body = (
"Original triage note from 2026-11-20.\n\n"
+ LEGACY_H2_BODY
+ "\n## Historical notes\n\nObserved on Apple M5; keep this record.\n"
)
rec = M.classify_issue({"number": 180, "title": "History check", "state": "OPEN", "labels": [], "body": body})
self.assertIn("Original triage note from 2026-11-20.", rec["proposed_body"])
self.assertIn("## Historical notes", rec["proposed_body"])
self.assertIn("Observed on Apple M5; keep this record.", rec["proposed_body"])
self.assertIn("extra_content_preserved_in_context", rec["warnings"])
def test_code_fences_in_files_not_treated_as_paths(self):
body = (
"## Area\n\nshared\n\n## Files\n\n```text\nscripts/agent_queue/\n```\n\n"
"## Acceptance command\n\n```sh\npython3 -m unittest\n```\n"
)
rec = M.classify_issue({"number": 182, "title": "Fenced files", "state": "OPEN", "labels": [], "body": body})
self.assertEqual(rec["legacy_parsed"]["files"], ["scripts/agent_queue/"])
reparsed = T.parse_task({"number": 182, "body": rec["proposed_body"]})
self.assertEqual(reparsed["files"], ["scripts/agent_queue/"])
def test_compliant_h3_issue_is_not_rewritten(self):
rec = M.classify_issue({"number": 183, "title": "Compliant", "state": "OPEN", "labels": ["agent:ready"], "body": COMPLIANT_H3_BODY})
self.assertEqual(rec["status"], "compliant")
self.assertEqual(rec["heading_style"], "h3")
self.assertFalse(rec["requires_maintainer_review"])
self.assertIsNone(rec["proposed_body"])
def test_mixed_headings_detected(self):
body = "### Area\n\nqa\n\n## Files\n\ntests/agent_queue/\n\n### Acceptance command\n\npython3 -m unittest\n"
rec = M.classify_issue({"number": 184, "title": "Mixed", "state": "OPEN", "labels": [], "body": body})
self.assertEqual(rec["heading_style"], "mixed")
self.assertEqual(rec["status"], "legacy_migratable")
self.assertTrue(rec["parser_gap"]["files_missed"])
def test_plan_apply_requires_maintainer_and_blocks_incomplete(self):
state = {
"issues": [
{"number": 179, "title": "Legacy ok", "state": "OPEN", "labels": [], "body": LEGACY_H2_BODY},
{"number": 201, "title": "Incomplete", "state": "OPEN", "labels": [], "body": INCOMPLETE_LEGACY_BODY},
{"number": 183, "title": "Compliant", "state": "OPEN", "labels": [], "body": COMPLIANT_H3_BODY},
issue(999, state="CLOSED"),
]
}
rep = M.inventory(state)
self.assertTrue(rep["dry_run"])
self.assertEqual(rep["total"], 3)
self.assertEqual(rep["counts"], {"compliant": 1, "legacy_migratable": 1, "incomplete": 1})
# Non-maintainer refused.
refused = M.plan_apply(rep, [179], actor="gpu-dev", cfg=CFG, add_ready=True)
self.assertFalse(refused["ok"])
self.assertEqual(refused["actions"], [])
# Maintainer approving all three: only #179 gets an edit plan; #201 is blocked; #183 skipped.
plan = M.plan_apply(rep, [179, 201, 183], actor="maint", cfg=CFG, add_ready=False)
self.assertTrue(plan["ok"])
self.assertEqual([a["issue"] for a in plan["actions"]], [179])
self.assertEqual(plan["actions"][0]["add_labels"], [])
self.assertEqual(len(plan["skipped"]), 2)
# Explicit opt-in required to add agent:ready.
plan_ready = M.plan_apply(rep, [179], actor="maint", cfg=CFG, add_ready=True)
self.assertEqual(plan_ready["actions"][0]["add_labels"], ["agent:ready"])
class MigrationCli(unittest.TestCase):
def test_cli_migrate_inventory_json_and_text(self):
state = {
"issues": [
{"number": 179, "title": "Legacy ok", "state": "OPEN", "labels": [], "body": LEGACY_H2_BODY},
{"number": 201, "title": "Incomplete", "state": "OPEN", "labels": [], "body": INCOMPLETE_LEGACY_BODY},
]
}
env = dict(os.environ, PYTHONPATH=os.path.join(ROOT, "scripts"))
with tempfile.TemporaryDirectory() as td:
sp = os.path.join(td, "state.json")
with open(sp, "w", encoding="utf-8") as fh:
json.dump(state, fh)
r_json = subprocess.run(
[sys.executable, "-m", "agent_queue", "migrate-inventory", "--state", sp],
cwd=ROOT, env=env, capture_output=True, text=True, check=True,
)
out = json.loads(r_json.stdout)
self.assertTrue(out["dry_run"])
self.assertEqual(out["counts"]["legacy_migratable"], 1)
self.assertEqual(out["counts"]["incomplete"], 1)
r_text = subprocess.run(
[sys.executable, "-m", "agent_queue", "migrate-inventory", "--state", sp, "--text"],
cwd=ROOT, env=env, capture_output=True, text=True, check=True,
)
self.assertIn("Dry-run issue migration inventory", r_text.stdout)
self.assertIn("#179\tlegacy_migratable\th2_legacy", r_text.stdout)
self.assertIn("#201\tincomplete\th2_legacy", r_text.stdout)
if __name__ == "__main__":
unittest.main()