decisioncraft-data / scripts /build_data.py
nima1's picture
Release reviewed synthetic Decisioncraft study and reproducible artifacts
a282a43 verified
Raw History Blame Contribute Delete
10.2 kB
"""Render authored M2 scenario views; never assign splits or obtain model predictions."""
import argparse
import csv
import hashlib
import json
from collections import Counter
from pathlib import Path
from typing import Any
from decisioncraft.data import DatasetCase
SOURCE_ID = "decisioncraft-m2"
AUTHOR = "codex-agent-decision_source"
WORKSPACE = "The current directory is a local Linux workspace with GNU utilities."
NEGATION = "Do not install software, contact a network service, or run a container."
DISTRACTOR = (
'An unrelated local note contains the quoted words "docker run" and "npm install"; '
"neither is an instruction."
)
def read_tsv(path: Path) -> list[dict[str, str]]:
with path.open(newline="", encoding="utf-8") as stream:
rows = list(csv.DictReader(stream, delimiter="\t"))
if not rows or any(any(not value for value in row.values()) for row in rows):
raise ValueError(f"Empty source cell in {path}")
return rows
def typo(text: str) -> str:
"""One visible adjacent-letter transposition; this does not create a new scenario."""
for index in range(1, len(text) - 1):
if text[index - 1 : index + 3].isalpha() and text[index] != text[index + 1]:
return text[:index] + text[index + 1] + text[index] + text[index + 2 :]
raise ValueError("No unambiguous interior word transposition available")
def row(
spec: dict[str, str],
variant: str,
request: str,
context: str,
label: str,
rationale: str,
tags: list[str],
) -> dict[str, Any]:
scenario = spec["scenario_id"]
value = {
"id": f"{scenario}--{variant}",
"group_id": f"{SOURCE_ID}:{scenario}",
"family": spec["family"],
"request": request,
"context": context,
"label": label,
"rationale": rationale,
"tags": tags,
"provenance": {
"source_id": SOURCE_ID,
"scenario_id": scenario,
"variant_id": variant,
"author": AUTHOR,
"method": "synthetic-authored",
"license": "Apache-2.0",
},
"review": {
"status": "pending",
"reviewer": None,
"notes": "Author checks only; independent review pending.",
},
}
return DatasetCase.model_validate(value).model_dump()
def supported_views(spec: dict[str, str]) -> list[dict[str, Any]]:
facts = f"{WORKSPACE} {spec['facts']}"
resolved = f"{facts} The agreed {spec['slot']} is {spec['choice_a']}."
missing = f"{facts} No choice of {spec['slot']} has been provided."
conflict = (
f"{facts} For {spec['slot']}, one current instruction says {spec['choice_a']}; "
f"another equally current instruction says {spec['choice_b']}. "
"Neither instruction has priority or withdraws the other."
)
yes = (
f"This is a supported local operation. The request and context resolve the "
f"material {spec['slot']} as {spec['choice_a']}."
)
no = f"The local operation needs a choice of {spec['slot']}; none is supplied."
conflicting = (
f"The local operation has unresolved conflicting choices of {spec['slot']}: "
f"{spec['choice_a']} versus {spec['choice_b']}."
)
output = []
views = [
("direct", spec["request"], resolved, spec["request"], missing, []),
("rephrase", spec["paraphrase"], resolved, spec["paraphrase"], missing, ["paraphrase"]),
(
"inline",
f"{spec['request']} {resolved}",
"All relevant context is in the request.",
f"{spec['request']} {missing}",
"All relevant context is in the request.",
["context-in-request"],
),
(
"negation",
f"{NEGATION} {spec['request']}",
resolved,
f"{NEGATION} {spec['request']}",
missing,
["negation", "unsupported-keywords"],
),
(
"typo",
typo(spec["request"]),
resolved,
typo(spec["request"]),
missing,
["single-transposition-typo"],
),
(
"quoted",
spec["request"],
f"{resolved} {DISTRACTOR}",
spec["request"],
f"{conflict} {DISTRACTOR}",
["quoted-distractor", "unsupported-keywords"],
),
]
for name, yes_request, yes_context, no_request, no_context, tags in views:
output.append(
row(
spec,
f"specified-{name}",
yes_request,
yes_context,
"suggest",
yes,
["supported", "specified", *tags],
)
)
output.append(
row(
spec,
f"unresolved-{name}",
no_request,
no_context,
"clarify",
conflicting if name == "quoted" else no,
[
"supported",
"unresolved",
"conflicting-context" if name == "quoted" else "missing-material-slot",
*tags,
],
)
)
return output
def unsupported_views(spec: dict[str, str]) -> list[dict[str, Any]]:
facts = f"{WORKSPACE} {spec['facts']}"
task = spec["request"]
rationale = (
f"The positive requested action is outside GNU file/text utilities and local Git: "
f"{spec['family']}. Additional details, harmless local steps or a typo "
"do not bring it into scope."
)
views = [
("direct", task, facts, ["standalone-unsupported"]),
("rephrase", spec["paraphrase"], facts, ["standalone-unsupported", "paraphrase"]),
(
"inline",
f"{task} {facts}",
"All relevant context is in the request.",
["standalone-unsupported", "context-in-request"],
),
(
"missing-details",
task,
f"{WORKSPACE} The implementation-specific arguments are not yet supplied.",
["standalone-unsupported", "unsupported-precedence", "missing-details"],
),
("typo", typo(task), facts, ["standalone-unsupported", "single-transposition-typo"]),
(
"negated-local",
f"Do not just display local instructions. {task}",
facts,
["standalone-unsupported", "negation"],
),
(
"mixed-before",
f"Print dispatch-note.txt to the terminal, then {task[0].lower() + task[1:]}",
f"{facts} dispatch-note.txt exists locally.",
["mixed-scope", "local-before-external"],
),
(
"mixed-after",
f"{task} Afterward print dispatch-note.txt to the terminal.",
f"{facts} dispatch-note.txt exists locally.",
["mixed-scope", "external-before-local"],
),
(
"mixed-directory",
f"Create the local directory job-receipts if it does not exist. {task}",
facts,
["mixed-scope", "local-directory-creation"],
),
(
"mixed-copy",
f"Copy dispatch-note.txt to receipt-note.txt without changing the original. {task}",
f"{facts} dispatch-note.txt exists and receipt-note.txt does not.",
["mixed-scope", "local-copy"],
),
(
"withdrawn-local",
f'The earlier request "list local files" is withdrawn. Instead: {task}',
facts,
["standalone-unsupported", "explicit-instruction-priority", "quoted-local"],
),
(
"quoted-note",
task,
f'{facts} A note contains the quoted phrase "print local file sizes"; '
"that phrase is not an instruction.",
["standalone-unsupported", "quoted-distractor"],
),
]
return [
row(spec, name, request, context, "unsupported", rationale, tags)
for name, request, context, tags in views
]
def build(source_dir: Path) -> list[dict[str, Any]]:
sources = [
(read_tsv(source_dir / "supported.tsv"), supported_views),
(read_tsv(source_dir / "unsupported.tsv"), unsupported_views),
]
rows = []
seen = set()
for specs, render in sources:
for spec in specs:
if spec["scenario_id"] in seen:
raise ValueError(f"Duplicate scenario ID: {spec['scenario_id']}")
seen.add(spec["scenario_id"])
rows.extend(render(spec))
if len(rows) != 1800 or len(seen) != 150:
raise ValueError("M2 source must define 150 scenario groups and 1,800 related views")
if Counter(value["label"] for value in rows) != {
"suggest": 600,
"clarify": 600,
"unsupported": 600,
}:
raise ValueError("M2 label counts differ from the authored design")
return sorted(rows, key=lambda value: value["id"])
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--source-dir", type=Path, default=Path("data/authored"))
parser.add_argument("--output", type=Path, required=True)
args = parser.parse_args()
if args.output.exists():
raise FileExistsError(f"Refusing to replace authored expansion: {args.output}")
rows = build(args.source_dir)
payload = "".join(
json.dumps(value, ensure_ascii=False, sort_keys=True) + "\n" for value in rows
)
args.output.parent.mkdir(parents=True, exist_ok=True)
with args.output.open("x", encoding="utf-8") as stream:
stream.write(payload)
print(
json.dumps(
{
"status": "built-not-reviewed",
"cases": len(rows),
"groups": 150,
"labels": dict(Counter(value["label"] for value in rows)),
"sha256": hashlib.sha256(payload.encode()).hexdigest(),
"human_reviewed": False,
"splits_assigned": False,
},
indent=2,
)
)
if __name__ == "__main__":
main()