System Instructions
This prompt is divided into three sections:
- System Instructions (this section) — structural orientation only. Do not treat this
section as task input.
- Input Context — begins with the heading
# Input Context. All blocks are wrapped in
<pblock> tags. Two block types:
- File blocks:
<pblock filename="<name>" role="<role>" guidance="...">— optional
guidance attribute carries context-specific instructions; content is in a fenced block.
- Metadata/section blocks:
<pblock label="<label>" kind="<kind>">— job parameters,
rules, instructions, or group headers.
- Agent Task — begins with the heading
# Agent Task. Defines your persona, constraints,
and required outputs. Read all input context before acting on this section.
Input Context
<pblock label="Repair job" kind="job">
Repair job
- DATE: 2026-10-28
- CRITERIA: 15
</pblock>
<pblock file="FEATURE-Control.md" check_id="control-corpus" kind="invalid-selection-probe">
Error: line 7: sources/run_conformance.py --select '^\\[if (1,null,2|empty|1|null) then|^\\[if (true|false) then|^if false then 3' selects a subset of a staged corpus: Probe: "JQ=./jq python3 sources/run_conformance.py --select '^\\[if (1,null,2|empty|1|null) then|^\\[if (true|false) then|^if false then 3' --json" is empty or not a plain flag literal
Intent: Conditional and alternative expressions execute the selected corpus cases with jq truth and stream semantics.
Suite: scoped
Requires: executable=python3; scope=test
Probe: JQ=./jq python3 sources/run_conformance.py --select '^\[if (1,null,2|empty|1|null) then|^\[if (true|false) then|^if false then 3' --json
import json
import os
import subprocess
import sys
SELECT = r"^\[if (1,null,2|empty|1|null) then|^\[if (true|false) then|^if false then 3"
result = subprocess.run(
[sys.executable, "sources/run_conformance.py", "--select", SELECT, "--json"],
capture_output=True, text=True,
env={**os.environ, "JQ": os.path.abspath("jq")},
)
print(result.stdout)
print(result.stderr, file=sys.stderr)
report = json.loads(result.stdout)
tally = report["summary"]
print(f"{tally['pass']} passed, {tally['fail']} failed, {tally['error']} errored")
assert sum(tally.values()) > 0
assert tally["fail"] == 0 and tally["error"] == 0, tally
assert result.returncode == 0, result.returncode
</pblock>
<pblock file="FEATURE-Conversion.md" check_id="conversion-conformance" kind="invalid-selection-probe">
Error: line 7: sources/run_conformance.py --select '^(?:utf8bytelength|\\[\\.\\[\\] \\| length\\]|\\[\\.\\[\\] \\| try utf8bytelength catch \\.\\]|implode\\|explode|fromjson \\| isnan|tojson \\| fromjson)$' selects a subset of a staged corpus: Probe: "JQ=./jq python3 sources/run_conformance.py --select '^(?:utf8bytelength|\\[\\.\\[\\] \\| length\\]|\\[\\.\\[\\] \\| try utf8bytelength catch \\.\\]|implode\\|explode|fromjson \\| isnan|tojson \\| fromjson)$' --json" is empty or not a plain flag literal
Intent: Type, length, conversion, and Unicode filters execute their applicable corpus cases.
Suite: scoped
Requires: executable=python3; scope=test
Probe: JQ=./jq python3 sources/run_conformance.py --select '^(?:utf8bytelength|\[\.\[\] \| length\]|\[\.\[\] \| try utf8bytelength catch \.\]|implode\|explode|fromjson \| isnan|tojson \| fromjson)$' --json
import json
import os
import subprocess
import sys
SELECT = r"^(?:utf8bytelength|\[\.\[\] \| length\]|\[\.\[\] \| try utf8bytelength catch \.\]|implode\|explode|fromjson \| isnan|tojson \| fromjson)$"
result = subprocess.run(
[sys.executable, "sources/run_conformance.py", "--select", SELECT, "--json"],
capture_output=True, text=True,
env={**os.environ, "JQ": os.path.abspath("jq")},
)
print(result.stdout)
print(result.stderr, file=sys.stderr)
report = json.loads(result.stdout)
tally = report["summary"]
assert sum(tally.values()) > 0, SELECT
assert tally["fail"] == 0 and tally["error"] == 0, tally
assert result.returncode == 0, result.returncode
</pblock>
<pblock file="FEATURE-Dates.md" check_id="dates-corpus" kind="invalid-selection-probe">
Error: line 7: sources/run_conformance.py --select '\\b(?:strftime|strflocaltime|strptime|mktime|gmtime)\\b' selects a subset of a staged corpus: Probe: "JQ=./jq python3 sources/run_conformance.py --select '\\b(?:strftime|strflocaltime|strptime|mktime|gmtime)\\b' --json" is empty or not a plain flag literal
Intent: Date parsing, formatting, and time conversion pass their executing corpus slice.
Suite: scoped
Requires: executable=python3; scope=test
Probe: JQ=./jq python3 sources/run_conformance.py --select '\b(?:strftime|strflocaltime|strptime|mktime|gmtime)\b' --json
import json
import os
import subprocess
import sys
SELECT = r"\b(?:strftime|strflocaltime|strptime|mktime|gmtime)\b"
result = subprocess.run(
[sys.executable, "sources/run_conformance.py", "--select", SELECT, "--json"],
capture_output=True, text=True,
env={**os.environ, "JQ": os.path.abspath("jq")},
)
print(result.stdout)
print(result.stderr, file=sys.stderr)
report = json.loads(result.stdout)
tally = report["summary"]
assert sum(tally.values()) > 0, f"selector matched no case: {SELECT}"
assert tally["fail"] == 0 and tally["error"] == 0, tally
assert result.returncode == 0, result.returncode
</pblock>
<pblock file="FEATURE-Documentation.md" check_id="documented-corpus" kind="invalid-selection-probe">
Error: line 7: sources/run_conformance.py --select '^\\.$' selects a subset of a staged corpus: Probe: "JQ=./jq python3 sources/run_conformance.py --select '^\\.$' --json" is empty or not a plain flag literal
Intent: The documented command passes an executing slice of identity filters.
Suite: scoped
Requires: executable=python3; scope=test
Probe: JQ=./jq python3 sources/run_conformance.py --select '^\.$' --json
import json
import os
import subprocess
import sys
SELECT = r"^\.$"
result = subprocess.run(
[sys.executable, "sources/run_conformance.py", "--select", SELECT, "--json"],
capture_output=True,
text=True,
env={**os.environ, "JQ": os.path.abspath("jq")},
)
print(result.stdout)
print(result.stderr, file=sys.stderr)
report = json.loads(result.stdout)
tally = report["summary"]
print(f"{tally['pass']} passed, {tally['fail']} failed, {tally['error']} errored")
assert sum(tally.values()) > 0, f"selector matched no case: {SELECT}"
assert tally["fail"] == 0 and tally["error"] == 0, tally
assert result.returncode == 0, result.returncode
</pblock>
<pblock file="FEATURE-Formats.md" check_id="formats-corpus" kind="invalid-selection-probe">
Error: line 7: sources/run_conformance.py --select '@(?:text|json|html|uri|urid|csv|tsv|sh|base64d?)\\b' selects a subset of a staged corpus: Probe: "JQ=./jq python3 sources/run_conformance.py --select '@(?:text|json|html|uri|urid|csv|tsv|sh|base64d?)\\b' --json" is empty or not a plain flag literal
Intent: Format filters execute the corpus cases that exercise their encoding and interpolation behavior.
Suite: scoped
Requires: executable=python3; scope=test
Probe: JQ=./jq python3 sources/run_conformance.py --select '@(?:text|json|html|uri|urid|csv|tsv|sh|base64d?)\b' --json
import json
import os
import subprocess
import sys
SELECT = r"@(?:text|json|html|uri|urid|csv|tsv|sh|base64d?)\b"
result = subprocess.run(
[sys.executable, "sources/run_conformance.py", "--select", SELECT, "--json"],
capture_output=True, text=True,
env={**os.environ, "JQ": os.path.abspath("jq")},
)
print(result.stdout)
print(result.stderr, file=sys.stderr)
report = json.loads(result.stdout)
tally = report["summary"]
assert sum(tally.values()) > 0, f"selector matched no case: {SELECT}"
assert tally["fail"] == 0 and tally["error"] == 0, tally
assert result.returncode == 0, result.returncode
</pblock>
<pblock file="FEATURE-GeneratorControl.md" check_id="generator-control-conformance" kind="missing-selection-probe">
Error: line 7: sources/run_conformance.py --select '^(?:reduce \\.\\[\\] as \\$x \\(0; \\. \\+ \\$x\\)|\\[foreach \\.\\[\\] as \\[\\$i, \\$j\\] \\(0; \\. \\+ \\$i - \\$j\\)\\]|\\[limit\\(3; \\.\\[\\]\\)\\]|\\[skip\\(3; \\.\\[\\]\\)\\]|first\\(1,error\\(\\"foo\\"\\)\\)|nth\\(1; 0,1,error\\(\\"foo\\"\\)\\))$' selects a subset of a staged corpus with no declared Probe: to prove the selection is non-empty before build
Intent: Reduction, intermediate extraction, and bounded generator consumption pass their applicable corpus cases.
Suite: scoped
Requires: executable=python3; scope=test
import json
import os
import subprocess
import sys
SELECT = r"^(?:reduce \.\[\] as \$x \(0; \. \+ \$x\)|\[foreach \.\[\] as \[\$i, \$j\] \(0; \. \+ \$i - \$j\)\]|\[limit\(3; \.\[\]\)\]|\[skip\(3; \.\[\]\)\]|first\(1,error\(\"foo\"\)\)|nth\(1; 0,1,error\(\"foo\"\)\))$"
result = subprocess.run(
[sys.executable, "sources/run_conformance.py", "--select", SELECT, "--json"],
capture_output=True, text=True,
env={**os.environ, "JQ": os.path.abspath("jq")},
)
print(result.stdout)
print(result.stderr, file=sys.stderr)
report = json.loads(result.stdout)
tally = report["summary"]
assert sum(tally.values()) > 0, SELECT
assert tally["fail"] == 0 and tally["error"] == 0, tally
assert result.returncode == 0, result.returncode
</pblock>
<pblock file="FEATURE-GeneratorCore.md" check_id="core-corpus" kind="missing-selection-probe">
Error: line 7: sources/run_conformance.py --select '^(true|false|null|1|-1|\\.|1,1|1,\\.)$' selects a subset of a staged corpus with no declared Probe: to prove the selection is non-empty before build
Intent: The basic literal and identity corpus cases execute successfully through the command interface.
Suite: scoped
Requires: executable=python3; scope=test
import json
import os
import subprocess
import sys
SELECT = r"^(true|false|null|1|-1|\.|1,1|1,\.)$"
result = subprocess.run(
[sys.executable, "sources/run_conformance.py", "--select", SELECT, "--json"],
capture_output=True,
text=True,
env={**os.environ, "JQ": os.path.abspath("jq")},
)
print(result.stdout)
print(result.stderr, file=sys.stderr)
report = json.loads(result.stdout)
tally = report["summary"]
print(f"{tally['pass']} passed, {tally['fail']} failed, {tally['error']} errored")
assert sum(tally.values()) > 0, f"selector matched no case: {SELECT}"
assert tally["fail"] == 0 and tally["error"] == 0, tally
assert result.returncode == 0, result.returncode
</pblock>
<pblock file="FEATURE-InputDiagnostics.md" check_id="input-diagnostics-corpus" kind="missing-selection-probe">
Error: line 7: sources/run_conformance.py --select '\\b(?:input|debug)\\b|\\$loc' selects a subset of a staged corpus with no declared Probe: to prove the selection is non-empty before build
Intent: Input exhaustion, diagnostics, and source locations execute the corresponding corpus cases.
Suite: scoped
Requires: executable=python3; scope=test
import json
import os
import subprocess
import sys
SELECT = r"\b(?:input|debug)\b|\$__loc__"
result = subprocess.run(
[sys.executable, "sources/run_conformance.py", "--select", SELECT, "--json"],
capture_output=True, text=True,
env={**os.environ, "JQ": os.path.abspath("jq")},
)
print(result.stdout)
print(result.stderr, file=sys.stderr)
report = json.loads(result.stdout)
tally = report["summary"]
assert sum(tally.values()) > 0, f"selector matched no case: {SELECT}"
assert tally["fail"] == 0 and tally["error"] == 0, tally
assert result.returncode == 0, result.returncode
</pblock>
<pblock file="FEATURE-Numeric.md" check_id="numeric-corpus" kind="missing-selection-probe">
Error: line 7: sources/run_conformance.py --select 'have_decnum|isnan|infinite|pow\\(|\\bfabs\\b|\\bsqrt\\b|\\bfloor\\b' selects a subset of a staged corpus with no declared Probe: to prove the selection is non-empty before build
Intent: Numeric functions and the selected non-decnum cases execute with the corpus-defined results.
Suite: scoped
Requires: executable=python3; scope=test
import json
import os
import subprocess
import sys
SELECT = r"have_decnum|isnan|infinite|pow\(|\bfabs\b|\bsqrt\b|\bfloor\b"
result = subprocess.run(
[sys.executable, "sources/run_conformance.py", "--select", SELECT, "--json"],
capture_output=True, text=True,
env={**os.environ, "JQ": os.path.abspath("jq")},
)
print(result.stdout)
print(result.stderr, file=sys.stderr)
report = json.loads(result.stdout)
tally = report["summary"]
assert sum(tally.values()) > 0, f"selector matched no case: {SELECT}"
assert tally["fail"] == 0 and tally["error"] == 0, tally
assert result.returncode == 0, result.returncode
</pblock>
<pblock file="FEATURE-Operators.md" check_id="operators-corpus" kind="missing-selection-probe">
Error: line 7: sources/run_conformance.py --select '^1\\+1$|^2-1$|^2-\\(-1\\)$|^25 % 7$|^49732 % 472$|^1 \\+ 2 \\* 2 \\+ 10 / 2$' selects a subset of a staged corpus with no declared Probe: to prove the selection is non-empty before build
Intent: Arithmetic and comparison expressions execute the selected corpus cases with jq operand and result semantics.
Suite: scoped
Requires: executable=python3; scope=test
import json
import os
import subprocess
import sys
SELECT = r"^1\+1$|^2-1$|^2-\(-1\)$|^25 % 7$|^49732 % 472$|^1 \+ 2 \* 2 \+ 10 / 2$"
result = subprocess.run(
[sys.executable, "sources/run_conformance.py", "--select", SELECT, "--json"],
capture_output=True, text=True,
env={**os.environ, "JQ": os.path.abspath("jq")},
)
print(result.stdout)
print(result.stderr, file=sys.stderr)
report = json.loads(result.stdout)
tally = report["summary"]
print(f"{tally['pass']} passed, {tally['fail']} failed, {tally['error']} errored")
assert sum(tally.values()) > 0
assert tally["fail"] == 0 and tally["error"] == 0, tally
assert result.returncode == 0, result.returncode
</pblock>
<pblock file="FEATURE-Paths.md" check_id="paths-corpus" kind="missing-selection-probe">
Error: line 7: sources/run_conformance.py --select '^path\\(\\.foo\\[0,1\\]\\)$|^path\\(\\.\\)$|^pick\\(\\.a\\.b\\.c\\)$' selects a subset of a staged corpus with no declared Probe: to prove the selection is non-empty before build
Intent: Path generation and lookup execute the selected corpus cases with the required path values.
Suite: scoped
Requires: executable=python3; scope=test
import json
import os
import subprocess
import sys
SELECT = r"^path\(\.foo\[0,1\]\)$|^path\(\.\)$|^pick\(\.a\.b\.c\)$"
result = subprocess.run(
[sys.executable, "sources/run_conformance.py", "--select", SELECT, "--json"],
capture_output=True, text=True,
env={**os.environ, "JQ": os.path.abspath("jq")},
)
print(result.stdout)
print(result.stderr, file=sys.stderr)
report = json.loads(result.stdout)
tally = report["summary"]
print(f"{tally['pass']} passed, {tally['fail']} failed, {tally['error']} errored")
assert sum(tally.values()) > 0
assert tally["fail"] == 0 and tally["error"] == 0, tally
assert result.returncode == 0, result.returncode
</pblock>
<pblock file="FEATURE-ScopedConformance.md" check_id="integration-programs" kind="missing-selection-probe">
Error: line 7: sources/run_conformance.py --select '.+' selects a subset of a staged corpus with no declared Probe: to prove the selection is non-empty before build
Intent: All nonempty program texts, including cross-feature and front-end cases, pass an executing selected corpus run.
Suite: scoped
Requires: executable=python3; scope=test
import json
import os
import subprocess
import sys
SELECT = r".+"
result = subprocess.run(
[sys.executable, "sources/run_conformance.py", "--select", SELECT, "--json"],
capture_output=True,
text=True,
env={**os.environ, "JQ": os.path.abspath("jq")},
)
print(result.stdout)
print(result.stderr, file=sys.stderr)
report = json.loads(result.stdout)
tally = report["summary"]
print(f"{tally['pass']} passed, {tally['fail']} failed, {tally['error']} errored")
assert sum(tally.values()) > 0, f"selector matched no case: {SELECT}"
assert tally["fail"] == 0 and tally["error"] == 0, tally
assert result.returncode == 0, result.returncode
</pblock>
<pblock file="FEATURE-SqlBuiltins.md" check_id="sql-builtins-corpus" kind="missing-selection-probe">
Error: line 7: sources/run_conformance.py --select '\\b(INDEX|JOIN|IN|builtins)\\b' selects a subset of a staged corpus with no declared Probe: to prove the selection is non-empty before build
Intent: The SQL-style operators and builtin inventory pass their matching corpus programs.
Suite: scoped
Requires: executable=python3; scope=test
import json
import os
import subprocess
import sys
SELECT = r"\b(INDEX|JOIN|IN|builtins)\b"
result = subprocess.run(
[sys.executable, "sources/run_conformance.py", "--select", SELECT, "--json"],
capture_output=True,
text=True,
env={**os.environ, "JQ": os.path.abspath("jq")},
)
print(result.stdout)
print(result.stderr, file=sys.stderr)
report = json.loads(result.stdout)
tally = report["summary"]
print(f"{tally['pass']} passed, {tally['fail']} failed, {tally['error']} errored")
assert sum(tally.values()) > 0, f"selector matched no case: {SELECT}"
assert tally["fail"] == 0 and tally["error"] == 0, tally
assert result.returncode == 0, result.returncode
</pblock>
<pblock file="FEATURE-Strings.md" check_id="string-conformance" kind="missing-selection-probe">
Error: line 7: sources/run_conformance.py --select '^(?:split\\(\\"\\"\\)|indices\\(1\\)|indices\\(\\[1,2\\]\\)|indices\\(\\", \\"\\)|index\\(\\"!\\"\\)|ascii_upcase|trim, ltrim, rtrim|join\\(\\",\\"\\))$' selects a subset of a staged corpus with no declared Probe: to prove the selection is non-empty before build
Intent: String searches, trimming, splitting, and joining execute their applicable corpus cases.
Suite: scoped
Requires: executable=python3; scope=test
import json
import os
import subprocess
import sys
SELECT = r"^(?:split\(\"\"\)|indices\(1\)|indices\(\[1,2\]\)|indices\(\", \"\)|index\(\"!\"\)|ascii_upcase|trim, ltrim, rtrim|join\(\",\"\))$"
result = subprocess.run(
[sys.executable, "sources/run_conformance.py", "--select", SELECT, "--json"],
capture_output=True, text=True,
env={**os.environ, "JQ": os.path.abspath("jq")},
)
print(result.stdout)
print(result.stderr, file=sys.stderr)
report = json.loads(result.stdout)
tally = report["summary"]
assert sum(tally.values()) > 0, SELECT
assert tally["fail"] == 0 and tally["error"] == 0, tally
assert result.returncode == 0, result.returncode
</pblock>
<pblock file="FEATURE-Traversal.md" check_id="traversal-corpus" kind="missing-selection-probe">
Error: line 7: sources/run_conformance.py --select '\\b(?:walk|tostream|fromstream|truncate_stream|recurse)\\b' selects a subset of a staged corpus with no declared Probe: to prove the selection is non-empty before build
Intent: Recursive walking and stream conversion execute their corpus cases with their required ordering.
Suite: scoped
Requires: executable=python3; scope=test
import json
import os
import subprocess
import sys
SELECT = r"\b(?:walk|tostream|fromstream|truncate_stream|recurse)\b"
result = subprocess.run(
[sys.executable, "sources/run_conformance.py", "--select", SELECT, "--json"],
capture_output=True, text=True,
env={**os.environ, "JQ": os.path.abspath("jq")},
)
print(result.stdout)
print(result.stderr, file=sys.stderr)
report = json.loads(result.stdout)
tally = report["summary"]
assert sum(tally.values()) > 0, f"selector matched no case: {SELECT}"
assert tally["fail"] == 0 and tally["error"] == 0, tally
assert result.returncode == 0, result.returncode
</pblock>
<pblock filename="sources/run_conformance.py" role="staged runner contract for selection probe repair">
#!/usr/bin/env python3
"""Run the upstream jq conformance corpus against a candidate implementation.
This is the scoring instrument. It is supplied, not authored: it is staged verbatim into the
build directory, hash-verified against the import, and restored before grading. Its exit status
is the acceptance verdict.
It is deliberately external to the implementation. Upstream jq grades itself, through its own
``--run-tests`` flag; a self-graded suite proves nothing here, so this runner re-implements the
corpus protocol and drives the candidate as a subprocess, one process per case.
Imported sources land in ``sources/`` inside the application directory, so this is normally
invoked as ``python3 sources/run_conformance.py`` from that directory.
Usage:
JQ=./jq python3 sources/run_conformance.py # full corpus, the scored run
JQ=./jq python3 sources/run_conformance.py -v # list passing cases too
JQ=./jq python3 sources/run_conformance.py --json # machine-readable report
JQ=./jq python3 sources/run_conformance.py --list # print cases, run nothing
JQ=./jq python3 sources/run_conformance.py --select 'reduce' # develop one construct
Environment:
JQ command that runs the candidate. Required -- this harness is language-neutral
and deliberately has no default implementation language.
Exit codes:
0 every case that ran passed
1 at least one case failed or errored
2 the harness could not run: bad usage, missing corpus, or a stale exclusion
"""
from __future__ import annotations
import argparse
import json
import os
import re
import shlex
import subprocess
import sys
from dataclasses import dataclass, field
from pathlib import Path
HERE = Path(__file__).resolve().parent
CORPUS = HERE / "jq.test"
EXCLUSIONS = HERE / "exclusions.txt"
#: A case that has not produced output in this long is not going to. jq's own suite runs the
#: whole corpus in under a second; anything near this bound is a runaway generator.
DEFAULT_TIMEOUT = 10.0
PASS, FAIL, ERROR, SKIP = "pass", "fail", "error", "skip"
#: jq's documented exit codes, which this kit's interface contract adopts. The distinction is
#: load-bearing: the corpus's %%FAIL cases are programs that must not compile, while an ordinary
#: case may legitimately raise at run time part-way through its output and still be correct.
EXIT_COMPILE_ERROR = 3
EXIT_RUNTIME_ERROR = 5
def split_lines(text: str) -> list[str]:
"""Split on newlines only.
``str.splitlines`` is Unicode-aware and also breaks on U+000B, U+000C, U+0085, U+2028, and
U+2029. The corpus contains cases whose expected output embeds those code points inside JSON
strings -- ``trim, ltrim, rtrim`` over the Unicode whitespace set is one -- and splitting
there shreds one JSON value into several, failing a correct implementation.
"""
lines = text.split("\n")
if lines and lines[-1] == "":
lines.pop()
return lines
@dataclass
class Case:
"""One corpus case: a program, an input, and what it must produce.
``expect_failure`` cases are the corpus's ``%%FAIL`` blocks. Upstream compares their
diagnostic text; this runner requires only that the candidate reject the program. The
expected strings are jq's exact C-implementation diagnostics, down to the caret art
underlining the offending token -- reproducing them is reverse-engineering an
implementation, not conforming to a specification. The text is parsed and reported so a
reader can see what upstream said, and is never compared.
"""
line: int
program: str
stdin: str = ""
expected: list[str] = field(default_factory=list)
expect_failure: bool = False
diagnostic: str = ""
@dataclass
class Result:
case: Case
status: str
detail: str = ""
actual: list[str] = field(default_factory=list)
return_code: int | None = None
stderr: str = ""
class HarnessError(Exception):
"""A fault in the kit or its invocation, never a fault in the candidate."""
# --------------------------------------------------------------------------------------------
# Corpus parsing
# --------------------------------------------------------------------------------------------
def parse_corpus(text: str) -> list[Case]:
"""Parse the jq test corpus.
The format is documented in the corpus's own header: cases are groups of lines separated by
blank lines; blank lines and lines starting with ``#`` are ignored. A case is a program
line, an input line, and then zero or more expected output lines. A case preceded by a
``%%FAIL`` or ``%%FAIL IGNORE MSG`` marker is a program line followed by the diagnostic
upstream jq emits, which may itself span several lines of source excerpt and caret art.
"""
cases: list[Case] = []
block: list[tuple[int, str]] = []
expect_failure = False
lines = split_lines(text)
def flush() -> None:
nonlocal block, expect_failure
if block:
cases.append(_case_from_block(block, expect_failure))
block = []
expect_failure = False
for number, raw in enumerate(lines, start=1):
stripped = raw.strip()
if not stripped:
flush()
continue
if raw.startswith("%%FAIL"):
flush()
expect_failure = True
continue
# A '#' comment closes nothing: upstream places section banners between cases, always
# with blank lines around them, and never inside a case.
if raw.lstrip().startswith("#") and not block:
continue
if raw.lstrip().startswith("#"):
continue
block.append((number, raw))
flush()
return cases
def _case_from_block(block: list[tuple[int, str]], expect_failure: bool) -> Case:
line, program = block[0]
if expect_failure:
diagnostic = "\n".join(text for _, text in block[1:])
return Case(line=line, program=program, expect_failure=True, diagnostic=diagnostic)
if len(block) < 2:
raise HarnessError(
f"{CORPUS.name}:{line}: case has a program but no input line; the corpus is malformed"
)
return Case(
line=line,
program=program,
stdin=block[1][1],
expected=[text for _, text in block[2:]],
)
# --------------------------------------------------------------------------------------------
# Exclusions
# --------------------------------------------------------------------------------------------
def parse_exclusions(path: Path) -> list[str]:
"""Read the declared exclusions: one verbatim program line per entry, ``#`` for reasons."""
if not path.is_file():
return []
return [
line
for line in split_lines(path.read_text(encoding="utf-8"))
if line.strip() and not line.lstrip().startswith("#")
]
def apply_exclusions(cases: list[Case], exclusions: list[str]) -> set[int]:
"""Return the corpus line numbers of excluded cases.
An exclusion that matches nothing is a hard error rather than a shrug. The corpus is pinned
by hash, so a stale exclusion means the pin moved without the exclusion list being revisited
-- and a silent no-op there would quietly re-admit a case the kit cannot run.
"""
by_program: dict[str, list[Case]] = {}
for case in cases:
by_program.setdefault(case.program, []).append(case)
excluded: set[int] = set()
stale: list[str] = []
for program in exclusions:
matched = by_program.get(program)
if not matched:
stale.append(program)
continue
excluded.update(case.line for case in matched)
if stale:
listed = "\n".join(f" {program}" for program in stale)
raise HarnessError(
f"{EXCLUSIONS.name}: these exclusions match no case in {CORPUS.name}:\n{listed}\n"
"The corpus and the exclusion list have drifted apart."
)
return excluded
# --------------------------------------------------------------------------------------------
# Comparison
# --------------------------------------------------------------------------------------------
def jv_equal(left: object, right: object) -> bool:
"""Compare two decoded JSON values the way jq's own ``jv_equal`` does.
Structural, not textual: ``1`` and ``1.0`` are the same jq value and the corpus relies on
that. Python's ``==`` almost does this, but it also equates ``True`` with ``1`` and
``False`` with ``0``, which jq does not; booleans are therefore matched by identity of type
before anything else.
"""
if isinstance(left, bool) or isinstance(right, bool):
return isinstance(left, bool) and isinstance(right, bool) and left is right
if isinstance(left, (int, float)) and isinstance(right, (int, float)):
return left == right
if isinstance(left, list) and isinstance(right, list):
return len(left) == len(right) and all(jv_equal(a, b) for a, b in zip(left, right))
if isinstance(left, dict) and isinstance(right, dict):
return left.keys() == right.keys() and all(jv_equal(left[k], right[k]) for k in left)
if type(left) is not type(right):
return False
return left == right
def _decode(line: str) -> tuple[bool, object]:
try:
return True, json.loads(line)
except ValueError:
return False, line
def outputs_match(expected: list[str], actual: list[str]) -> bool:
if len(expected) != len(actual):
return False
for want, got in zip(expected, actual):
want_ok, want_value = _decode(want)
got_ok, got_value = _decode(got)
if want_ok and got_ok:
if not jv_equal(want_value, got_value):
return False
elif want.strip() != got.strip():
return False
return True
# --------------------------------------------------------------------------------------------
# Execution
# --------------------------------------------------------------------------------------------
def run_case(case: Case, argv: list[str], timeout: float) -> Result:
try:
completed = subprocess.run(
[*argv, "-c", case.program],
input=case.stdin,
capture_output=True,
text=True,
timeout=timeout,
)
except subprocess.TimeoutExpired:
return Result(case, ERROR, detail=f"timed out after {timeout:g}s")
except OSError as exc:
raise HarnessError(f"cannot execute {shlex.join(argv)}: {exc}") from exc
actual = split_lines(completed.stdout)
stderr = completed.stderr.strip()
code = completed.returncode
first_diagnostic = split_lines(stderr)[0] if stderr else ""
if case.expect_failure:
# The corpus's %%FAIL cases are programs that must be rejected at compile time. Accepting
# one and then failing at run time is a different, wrong behaviour, so the compile-error
# code specifically -- not merely a non-zero exit -- is what passes here.
if code == EXIT_COMPILE_ERROR:
return Result(case, PASS, return_code=code, stderr=stderr)
detail = (
"program was accepted, but the corpus marks it %%FAIL"
if code == 0
else f"exited {code}; a rejected program must exit {EXIT_COMPILE_ERROR}"
)
return Result(case, FAIL, detail=detail, actual=actual, return_code=code, stderr=stderr)
if code == EXIT_COMPILE_ERROR:
return Result(
case,
FAIL,
detail=f"program did not compile: {first_diagnostic}",
actual=actual,
return_code=code,
stderr=stderr,
)
if code not in (0, EXIT_RUNTIME_ERROR):
# A runtime error is legitimate: several cases raise part-way through a generator and are
# judged on the outputs produced before the raise, exactly as upstream judges them. Any
# other non-zero status is the program failing in a way the contract does not describe.
return Result(
case,
FAIL,
detail=f"exited {code}: {first_diagnostic}",
actual=actual,
return_code=code,
stderr=stderr,
)
if not outputs_match(case.expected, actual):
return Result(
case,
FAIL,
detail="output mismatch",
actual=actual,
return_code=code,
stderr=stderr,
)
return Result(case, PASS, actual=actual, return_code=code, stderr=stderr)
# --------------------------------------------------------------------------------------------
# Reporting
# --------------------------------------------------------------------------------------------
def _render_failure(result: Result) -> str:
case = result.case
lines = [
f"FAIL {CORPUS.name}:{case.line} {result.detail}",
f" program: {case.program}",
]
if not case.expect_failure:
lines.append(f" input: {case.stdin}")
lines.append(f" expected: {case.expected if case.expected else '(no output)'}")
lines.append(f" actual: {result.actual if result.actual else '(no output)'}")
if result.stderr:
lines.append(f" stderr: {split_lines(result.stderr)[0]}")
return "\n".join(lines)
def main(argv: list[str] | None = None) -> int:
parser = argparse.ArgumentParser(
description="Run the upstream jq conformance corpus against a candidate implementation.",
)
parser.add_argument("--jq", default=None, help="candidate command (default: $JQ)")
parser.add_argument("--timeout", type=float, default=DEFAULT_TIMEOUT, help="seconds per case")
parser.add_argument("--json", action="store_true", help="machine-readable report")
parser.add_argument("-v", "--verbose", action="store_true", help="list passing cases too")
parser.add_argument("--list", action="store_true", help="print the cases and run nothing")
parser.add_argument(
"--select",
default=None,
metavar="REGEX",
help="run only cases whose program matches REGEX (development aid; the acceptance "
"gate always runs the whole corpus)",
)
args = parser.parse_args(argv)
try:
return _run(args)
except HarnessError as exc:
print(f"error: {exc}", file=sys.stderr)
return 2
def _run(args: argparse.Namespace) -> int:
if not CORPUS.is_file():
raise HarnessError(f"corpus not found at {CORPUS}")
cases = parse_corpus(CORPUS.read_text(encoding="utf-8"))
excluded = apply_exclusions(cases, parse_exclusions(EXCLUSIONS))
selector = re.compile(args.select) if args.select else None
if selector is not None:
cases = [case for case in cases if selector.search(case.program)]
if args.list:
for case in cases:
mark = "skip" if case.line in excluded else "run "
print(f"{mark} {CORPUS.name}:{case.line} {case.program}")
print(f"\n{len(cases)} cases, {sum(1 for c in cases if c.line in excluded)} excluded")
return 0
command = args.jq or os.environ.get("JQ") or ""
if not command.strip():
raise HarnessError(
"JQ is not set; give the command that runs your implementation, e.g.\n"
' JQ="$PWD/jq" python3 sources/run_conformance.py'
)
jq_argv = shlex.split(command)
results: list[Result] = []
for case in cases:
if case.line in excluded:
results.append(Result(case, SKIP, detail="declared in exclusions.txt"))
continue
results.append(run_case(case, jq_argv, args.timeout))
tally = {status: sum(1 for r in results if r.status == status) for status in
(PASS, FAIL, ERROR, SKIP)}
summary = (
f"jq conformance: {tally[PASS]} passed, {tally[FAIL]} failed, "
f"{tally[ERROR]} errored, {tally[SKIP]} skipped "
f"(corpus {CORPUS.name} @ jq-1.8.2)"
)
if args.json:
print(json.dumps(
{
"candidate": jq_argv,
"corpus": CORPUS.name,
"summary": tally,
"cases": [
{
"line": r.case.line,
"program": r.case.program,
"status": r.status,
"detail": r.detail,
"expect_failure": r.case.expect_failure,
"expected": r.case.expected,
"actual": r.actual,
}
for r in results
if args.verbose or r.status != PASS
],
},
indent=2,
))
else:
for result in results:
if result.status in (FAIL, ERROR):
print(_render_failure(result))
elif args.verbose and result.status == PASS:
print(f"ok {CORPUS.name}:{result.case.line} {result.case.program}")
elif args.verbose and result.status == SKIP:
print(f"skip {CORPUS.name}:{result.case.line} {result.case.program}")
print(summary)
return 0 if tally[FAIL] == 0 and tally[ERROR] == 0 else 1
if __name__ == "__main__":
raise SystemExit(main())
</pblock>
Agent Task
Agent for: making a broken acceptance criterion runnable
You are given a batch of acceptance criteria that cannot execute as written, possibly drawn from several different Blueprint specification files in one request. Each one raises before it tests anything, or cannot be proven to test anything: a missing import, an undefined name, a syntax error, a regex pattern that does not compile in the criterion or in a staged runner it invokes, or a staged-runner selector missing, malformed, or proven to select zero cases. A criterion in this state is not a failing test. It is a test that never ran — or that runs against nothing — and the build cannot tell either apart from a genuine product defect.
Each criterion arrives as its own self-contained block:
<pblock file="<filename>" check_id="<check-id>" kind="<defect kind>">
Error: <one sentence naming the fault>
<the criterion's own Intent and Python, exactly as written>
</pblock>
Nothing else about that criterion's file, and nothing about any other criterion, is provided. For a bad-citation defect, numbered source files may also be supplied as context. Use only those sources to repair its Cite: declaration; never infer missing source text or line numbers.
Selection-probe repairs also receive the implicated staged runner source. Derive supported flags and count formats from that source; never invent a listing flag or edit the supplied runner. Probe Count: json counts JSON array elements; [] means zero, not one output line.
Your job is to make each criterion named in its own block run. Nothing else.
A second, independent job shape may also appear: when the input names a Bad acceptance container, the file has no safely addressable criterion, and the whole file's source is provided instead of a per-criterion block. Repair only its === AC <id> === and === END AC <id> === delimiter lines. Do not alter any other line, including Python, assertions, Intent, or Markdown. A closer that names the wrong id may mean a boundary is missing entirely: two criteria were fused under one opener, and fixing it requires inserting the missing === AC <id> === line for the second criterion immediately before its body, not only renaming the existing closer to match the first. Return the complete corrected file using the container output form below.
The one rule
Repair the mechanics. Never touch the assertion.
The criterion's expected values, comparisons, inputs, program text, and intent are correct until proven otherwise by executing them. You are not judging whether the criterion is right. You are removing the reason it cannot be judged at all.
Permitted:
- for a
bad-citationfault, correct only the existingCite:declaration to name the supplied
source lines supporting the unchanged expectation. Source line numbers are one-based and inclusive; use sources/<file>:<line> or sources/<file>:<start>-<end>. Preserve every other line, including all inputs, assertions, and metadata. Never remove the citation. If the supporting source is not supplied or does not state the expectation, emit REPAIR_IMPOSSIBLE;
- add an
importfor a name the criterion reads but never binds; - bind a name the criterion clearly intends to use, in the obvious way;
- correct a syntax error, preserving the evident meaning of the line;
- correct a regex pattern passed to
re.compileor anotherre.*call that fails to compile,
preserving the evident set of forms it is meant to select — the usual cause is a raw string that escapes the backslash instead of the metacharacter (r'\\[' matches one literal backslash then opens an unterminated class; r'\[' matches a literal [, which is normally the intended fix);
- correct a literal regex supplied to a staged runner option whose contract compiles that option
as a regex, preserving the intended selected forms;
- reorder imports to the top of the criterion;
- for a
test-transportfault, replace the namedRequires: python-package=httpx; scope=test
line with Requires: python-package=httpx2; scope=test, and only that line;
- for a
missing-selection-probeorinvalid-selection-probefault, add or correct the
criterion's Probe: and Probe Count: declaration lines so the selector it already invokes can be proven non-empty, and only that;
- for a
probe-failedfault, correctProbe:andProbe Count:to match the supplied runner's
supported listing flag and count format, preserving the existing command, filter, corpus path, Suite:, Intent:, and assertions; never drop probe declarations to bypass validation;
- for an
empty-selectionfault, correct the selector value itself so it selects the existing
section the criterion's Intent: names; never widen it to "select everything", and emit REPAIR_IMPOSSIBLE if the supplied evidence cannot establish a correct section;
- for a
harness-exitfault, change the named call's expected exit status to the value the
Error: line says the staged harness expects, and correct any later assertion in the same criterion that held only because that call had the wrong outcome. The staged harness is the user's own test and outranks the criterion. Change no input and no command.
- for an
unchecked-callfault, bind each namedcli_runnercall as
code, out, err = cli_runner(...) and add assert code == 0 directly after it — a setup call must succeed before the criterion relies on it. Change no argument and no other assert;
- for a
staged-valuefault, create the state the criterion depends on inside the criterion,
under an identifier no staged file holds, with the same commands the other criteria in the Blueprint use to create it, each followed by assert code == 0, and use that identifier in place of the staged one throughout the criterion. Keep every expected exit status and output.
- for a
go-runorgo-package-launchfault, replace each namedgo run <package> <args...>
or direct ./cmd/<name> <args...> invocation with code, out, err = cli_runner(<args...>) after from drydock_go import cli_runner, passing the same arguments, input= for the same standard input, and package="<package>" only when the package is not the sole ./cmd/<name>. Read the exit status, standard output, and standard error from code, out, and err in place of the subprocess result. The helper returns text; replace byte-stream .decode(...) calls with the returned text. Keep every expected value, including bytes comparisons by encoding the returned text when necessary. ./cmd/<name> is the Go source package directory; never chmod it or execute it directly.
- for an
acceptance-storefault that launches the application (subprocess,os.system, or a
launcher such as ./<name>), replace each launch with the in-process fixture the selected foundation contract below publishes — cli_runner, imported from the module its fixture_source names, for a command; web_client() for an HTTP request — passing the same command arguments without the executable. Bind code, out, err = cli_runner(...) and read the exit status, standard output, and standard error from them in place of the subprocess result. Keep every store read, expected value, and input. Remove an import the replacement leaves unused.
Go CLI client contract:
from drydock_go import cli_runner
# Signature: cli_runner(*args: str, package: str | None = None,
# input: str | None = None) -> tuple[int, str, str]
code, out, err = cli_runner() # no command arguments
code, out, err = cli_runner("--summary", ".") # separate string arguments
Never pass a list or tuple as one positional argument. For a go-cli-args fault, unpack that sequence with * and preserve every argument and assertion.
For a configuration-only acceptance-store defect, the database_environment fixture relocation specified below is also allowed, including its necessary path-operand substitution. Preserve the same configuration cases and assertions about behavior.
Forbidden:
- changing any
assert— its operands, its comparison, or its expected value — except as
permitted above for a harness-exit fault, or renaming its operands to code, out, and err for a go-run, go-package-launch, or acceptance-store fault, or substituting relocated scratch path operands for a configuration-only acceptance-store fault;
- changing the input payload, the program under test, or the command invoked, except as
permitted above for an unchecked-call, staged-value, go-run, go-package-launch, or acceptance-store fault;
- adding
try,except,pytest.skip, or any construct that lets the criterion pass without
testing what it claims to test;
- deleting a criterion, renaming its id, or altering its
Intent:line; - adding a
Suite:orRequires:line that was not already there; - adding, correcting, or removing
Probe:/Probe Count:for any fault other than
missing-selection-probe, invalid-selection-probe, empty-selection, or probe-failed;
- touching a criterion that was not named in its own block;
- editing any other part of a specification.
Preserve the product requirement and assertion intent. Mechanical repair does not decide a new expected outcome, move coverage or change dependencies. If the named defect requires those changes, follow Impossible repair and state the required source-aware authoring action.
Impossible repair
If a criterion cannot be made runnable without changing what it asserts, do not change it. Emit its block unmodified and add one line immediately after the block:
REPAIR_IMPOSSIBLE: <file> :: <check-id> — <one sentence saying what the criterion would have to change>
The separator between the id and the reason is always an em dash (—); filenames and check_ids commonly contain hyphens, so no other character can be used to tell them apart.
Output
For a Bad acceptance container, emit exactly:
=== BEGIN REPAIRED SPECIFICATION ===
<the complete original specification with only AC delimiter lines corrected>
=== END REPAIRED SPECIFICATION ===
For every defective criterion in the batch, emit one block, and nothing else:
Use no prose, no summary, and no fenced code around a criterion block. Use the exact delimiters, with the criterion's own file and id, copied exactly from its file= and check_id= attributes — this is what tells two criteria that happen to share a check_id in different files apart:
=== AC <file> :: <check-id> ===
Intent: <unchanged>
<the repaired Python>
=== END AC <file> :: <check-id> ===
Identify the criterion by its file and id; you do not need to know or reproduce its file's own internal delimiter format. Include the whole criterion — every line that was inside its block — not a patch or a diff.
Acceptance persistence lifecycle
Acceptance store lifecycle. The DATABASE step provisions and verifies the configured store once. Ordinary persistence criteria never replace DATABASE_URL/DATABASE_PATH, create a temporary database, apply DDL, or assume an empty store. Configuration behavior is tested separately using the harness fixture below. The store may hold data before any criterion runs: assert on records the criterion created, or on a count read before setup (after == before + 5), never on an absolute table count.
SQLite configuration tests (Python acceptance container). The harness supplies from drydock_acceptance import database_environment. Use it only to test configuration selection, default paths, or source-required open failures, never ordinary CRUD acceptance:
import os
from drydock_acceptance import database_environment
from <declared_config_module> import database_path
with database_environment(url="sqlite://primary.db", path="fallback.db") as root:
assert str(database_path()) == str(root / "primary.db")
with database_environment(path="fallback.db") as root:
assert str(database_path()) == str(root / "fallback.db")
with database_environment() as root:
assert str(database_path()) == "data/app.db"
None (the default) unsets a variable; "" sets it empty. Other arguments are relative SQLite file names within a fresh temporary working directory; only url permits the sqlite:// prefix. The fixture maps names to absolute scratch paths, yields that directory as a Path, and restores both variables and cwd on exit, including failures. It applies no schema and creates no parent directories: url="missing/app.db" exercises an unopenable path. Invoke the declared application interface inside the context, assert the source-required outcome, and do not read or write the managed store. Import the declared configuration module, never invent a module or an exit requirement absent from the source. Do not replace environment variables directly or bypass this fixture with monkeypatches.
For acceptance-store repair of an existing configuration test, move its environment setup and restoration into this fixture. Preserve URL-prefix/precedence/unset/empty conditions, command arguments, error behavior and expected results. Replace arbitrary fixture paths with relative names and derive asserted absolute paths from root; this is a mechanical fixture relocation, not permission to change which configured value wins or weaken any assertion. If the criterion needs a populated replacement store, report REPAIR_IMPOSSIBLE instead.
The acceptance harness owns isolation. It begins one transaction before each Python criterion and rolls it back when the criterion ends, pass or fail. Every database the criterion's process opens joins it: db_session(), the application behind web_client(), and commands run through cli_runner(). Setup, behavior and readback therefore see one another's writes, and none persists; leaving a with db_session() as db: block rolls nothing back. Seed with with db_session() as db: and pass that database into feature operations. Never commit, clean up, or open a transaction.
A criterion that launches a process (subprocess, a server on a port, a shell script) cannot see that transaction. It does not open the store and does not depend on rows it wrote; exercise stored behavior in-process instead. Go criteria use OpenSession(ctx, "") with checked deferred cleanup, which rolls back its own transaction. Go HTTP, CLI and restart criteria use OpenCommittedSession(ctx, "") with a criterion-owned identifier and checked defer cleanup through supported product interfaces. Database acceptance must not be replaced by a project test count: runtime catalog and row-count evidence proves provisioning, feature criteria prove behavior.