diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..a98c154 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,19 @@ +name: CI + +on: + pull_request: + push: + branches: [main] + +permissions: + contents: read + +jobs: + verify: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4 + - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065 # v5 + with: + python-version: "3.11" + - run: ./scripts/verify-outcome.sh diff --git a/.gitignore b/.gitignore index 9e740c6..349b74b 100644 --- a/.gitignore +++ b/.gitignore @@ -4,3 +4,5 @@ build/ local.properties *.keystore *.jks +__pycache__/ +*.py[cod] diff --git a/LICENSE b/LICENSE index 0424cef..79c12e3 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,7 @@ MIT License Copyright (c) 2026 BeFeast +Copyright (c) 2026 Matt Pocock Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/README.md b/README.md index 62c8b12..7c8023b 100644 --- a/README.md +++ b/README.md @@ -3,3 +3,29 @@ Native interactive questionnaire rounds replace Markdown-only grilling while preserving the complete linked grill-me -> grilling flow across Codex, Claude Code, and OpenCode. Project: `BeFeast/dev-workflow`. + +The first supported harness is Codex. Its committed bundle lives under +`harnesses/codex/`; `grill-me` remains a user-invoked wrapper over the reusable +model-invoked `grilling` primitive. The canonical frontier-round behavior is +defined in `contracts/grilling-v1.md` and enforced by the Python fixtures. + +Run the complete repository gate with: + +```sh +./scripts/verify-outcome.sh +``` + +The canonical single-path skill installer does not consume this repository's +`bundle.json`, so selecting only its `grill-me` path would omit `grilling` and +the upstream notice. Materialize a dependency-complete portable selection with +the repository selector instead: + +```sh +python3 scripts/select_codex_skills.py \ + --skill grill-me \ + --target /tmp/dev-workflow-codex-selection +``` + +The target must be empty. This command is safe for isolated inspection and +fixture roots; live harness installation remains a separate approval-gated +delivery step. diff --git a/contracts/grilling-v1.md b/contracts/grilling-v1.md new file mode 100644 index 0000000..f84c2ba --- /dev/null +++ b/contracts/grilling-v1.md @@ -0,0 +1,51 @@ +# Grilling contract v1 + +`grilling` is the model-invoked primitive. `grill-me` is a user-invoked wrapper +that delegates to it; callers must not copy or fork the interview logic. + +## Design tree + +- A decision has a stable `snake_case` id, prompt, choices, recommendation, + decision prerequisites, and optional discoverable-fact prerequisites. +- Resolve facts from the environment before asking the user. Facts do not + become user decisions. +- The frontier contains every unresolved decision whose decision and fact + prerequisites are settled. +- Preserve source order inside a frontier so generated calls and fixtures are + deterministic. + +## Frontier round + +1. Snapshot the complete frontier before invoking a harness tool. +2. Partition that immutable snapshot only when the harness limits one call. +3. Collect and normalize every answer from every partition, including custom + `Other` values and notes appended to a selected option. Discard a native + `Other` sentinel, never the user's free-form text. +4. Commit only the complete snapshot. Never expose decisions unblocked by a + partial partition. +5. Recompute the frontier and repeat. + +The session ends only after every known decision is settled and the user +confirms shared understanding through the same interaction surface. A frontier +temporarily empty because facts are still being resolved is not completion. A +rejection or custom concern extends the tree. Do not implement the grilled plan +before confirmation. + +## Adapter seam + +An adapter may only: + +- detect whether its real native questionnaire tool is callable in the active + harness and mode; +- serialize a frontier snapshot within that tool's schema and call limits; +- normalize native and custom answers into the canonical answer shape; +- state the unavailable capability and use the documented fallback. + +The Codex adapter further constrains each native question prompt to one +sentence and each option description to one short sentence, regardless of the +more permissive prose shape in the upstream skill. Its two or three choices +must be mutually exclusive; this semantic requirement stays in the skill and +fixtures because a serializer cannot infer exclusivity from arbitrary prose. + +An adapter must not invent a neutral tool name, change the frontier, answer for +the user, silently claim native interaction, or recompute between chunks. diff --git a/dev_workflow/__init__.py b/dev_workflow/__init__.py new file mode 100644 index 0000000..209c3a0 --- /dev/null +++ b/dev_workflow/__init__.py @@ -0,0 +1,21 @@ +"""Shared contracts for generated multi-harness workflow skills.""" + +from .grilling import ( + Answer, + Decision, + DesignTree, + InterviewState, + Option, + Question, + RoundSnapshot, +) + +__all__ = [ + "Answer", + "Decision", + "DesignTree", + "InterviewState", + "Option", + "Question", + "RoundSnapshot", +] diff --git a/dev_workflow/bundle.py b/dev_workflow/bundle.py new file mode 100644 index 0000000..db0f0eb --- /dev/null +++ b/dev_workflow/bundle.py @@ -0,0 +1,78 @@ +"""Dependency-aware selective materialization for the Codex bundle.""" + +from __future__ import annotations + +import json +import shutil +from pathlib import Path + + +def resolve_skills(manifest: dict, selected: list[str]) -> tuple[str, ...]: + skills = manifest.get("skills") + if not isinstance(skills, dict): + raise ValueError("bundle manifest must define skills") + resolved: list[str] = [] + visiting: set[str] = set() + + def add(name: str) -> None: + if name in resolved: + return + if name in visiting: + raise ValueError("skill dependency cycle") + if name not in skills: + raise ValueError(f"unknown skill {name!r}") + visiting.add(name) + dependencies = skills[name].get("requires") + if not isinstance(dependencies, list) or not all( + isinstance(item, str) for item in dependencies + ): + raise ValueError(f"skill {name!r} has invalid requires") + for dependency in dependencies: + add(dependency) + visiting.remove(name) + resolved.append(name) + + for skill in selected: + add(skill) + return tuple(resolved) + + +def materialize_selection( + bundle_root: Path, target_root: Path, selected: list[str] +) -> tuple[str, ...]: + """Copy a complete portable selection into an empty isolated target. + + The output is shaped like a Codex skill root, but issue #1 callers use only + temporary or otherwise isolated targets. Live installation remains a + separate approval-gated delivery concern. + """ + + manifest = json.loads((bundle_root / "bundle.json").read_text(encoding="utf-8")) + resolved = resolve_skills(manifest, selected) + target_root.mkdir(parents=True, exist_ok=True) + if any(target_root.iterdir()): + raise FileExistsError(f"selection target must be empty: {target_root}") + + for name in resolved: + relative = manifest["skills"][name]["path"] + source = bundle_root / relative + target = target_root / name + shutil.copytree(source, target) + + selected_manifest = { + **{key: value for key, value in manifest.items() if key != "skills"}, + "selected": selected, + "skills": { + name: {**manifest["skills"][name], "path": name} + for name in resolved + }, + } + (target_root / "dev-workflow-bundle.json").write_text( + json.dumps(selected_manifest, indent=2, sort_keys=True) + "\n", + encoding="utf-8", + ) + shutil.copyfile( + bundle_root / "UPSTREAM_LICENSE", + target_root / "dev-workflow-UPSTREAM_LICENSE", + ) + return resolved diff --git a/dev_workflow/codex.py b/dev_workflow/codex.py new file mode 100644 index 0000000..29af4fc --- /dev/null +++ b/dev_workflow/codex.py @@ -0,0 +1,218 @@ +"""Codex/T3 serialization for the canonical grilling contract.""" + +from __future__ import annotations + +from dataclasses import dataclass +from enum import Enum +import re +from typing import Mapping, Sequence + +from .grilling import Option, Question, RoundSnapshot + + +CODEX_MAX_QUESTIONS = 3 +CODEX_MAX_OPTIONS = 3 +CODEX_MAX_PROMPT_CHARS = 240 +CODEX_MAX_DESCRIPTION_CHARS = 160 +MULTIPLE_SENTENCES = re.compile(r"[.!?](?:[\"')\]]+)?\s+\S") + + +class Surface(str, Enum): + NATIVE = "request_user_input" + FALLBACK = "text-fallback" + + +class ConfirmationDisposition(str, Enum): + CONFIRMED = "confirmed" + REOPEN = "reopen" + EXTEND = "extend" + + +@dataclass(frozen=True) +class ConfirmationResult: + disposition: ConfirmationDisposition + concern: str | None = None + + @property + def may_act(self) -> bool: + return self.disposition is ConfirmationDisposition.CONFIRMED + + @property + def continue_interview(self) -> bool: + return not self.may_act + + @property + def extends_tree(self) -> bool: + return self.disposition in { + ConfirmationDisposition.REOPEN, + ConfirmationDisposition.EXTEND, + } + + +@dataclass(frozen=True) +class Capabilities: + """Facts observed from the active harness, never inferred from this package.""" + + request_user_input_exposed: bool + mode_allows_request_user_input: bool + + @property + def surface(self) -> Surface: + if self.request_user_input_exposed and self.mode_allows_request_user_input: + return Surface.NATIVE + return Surface.FALLBACK + + @property + def fallback_reason(self) -> str | None: + if not self.request_user_input_exposed: + return "request_user_input is not exposed by the active harness" + if not self.mode_allows_request_user_input: + return "the active collaboration mode does not permit request_user_input" + return None + + +def plan_chunks(snapshot: RoundSnapshot) -> tuple[tuple[Question, ...], ...]: + """Chunk one already-captured frontier without recomputing it.""" + + return snapshot.chunks(CODEX_MAX_QUESTIONS) + + +def _native_option(option: Option, recommended: bool) -> dict[str, str]: + label = option.label + if recommended and not label.endswith("(Recommended)"): + label = f"{label} (Recommended)" + return {"label": label, "description": option.description} + + +def serialize_native(questions: Sequence[Question]) -> dict[str, list[dict[str, object]]]: + """Build one request_user_input payload from at most three questions.""" + + if not 1 <= len(questions) <= CODEX_MAX_QUESTIONS: + raise ValueError("Codex native chunks must contain one to three questions") + payload: list[dict[str, object]] = [] + for question in questions: + if len(question.header) > 12: + raise ValueError(f"Codex header for {question.id!r} exceeds 12 characters") + if ( + MULTIPLE_SENTENCES.search(question.prompt.strip()) + or len(question.prompt) > CODEX_MAX_PROMPT_CHARS + ): + raise ValueError( + f"Codex prompt for {question.id!r} must be one short sentence" + ) + if not 2 <= len(question.options) <= CODEX_MAX_OPTIONS: + raise ValueError(f"Codex question {question.id!r} needs two or three options") + if any(not 1 <= len(option.label.split()) <= 5 for option in question.options): + raise ValueError(f"Codex option labels for {question.id!r} need one to five words") + if any( + MULTIPLE_SENTENCES.search(option.description.strip()) + or len(option.description) > CODEX_MAX_DESCRIPTION_CHARS + for option in question.options + ): + raise ValueError( + f"Codex option descriptions for {question.id!r} must be one short sentence" + ) + ordered = ( + question.options[question.recommended], + *( + option + for index, option in enumerate(question.options) + if index != question.recommended + ), + ) + native_options = [ + _native_option(option, index == 0) + for index, option in enumerate(ordered) + ] + if any(len(option["label"].split()) > 5 for option in native_options): + raise ValueError( + f"Codex option labels for {question.id!r} exceed five words " + "after recommendation marking" + ) + payload.append( + { + "id": question.id, + "header": question.header, + "question": question.prompt, + "options": native_options, + } + ) + return {"questions": payload} + + +def normalize_native_response( + questions: Sequence[Question], response: Mapping[str, object] +) -> dict[str, str]: + """Normalize the request_user_input response envelope into canonical strings.""" + + raw_answers = response.get("answers") + if not isinstance(raw_answers, Mapping): + raise ValueError("native response must contain an answers mapping") + expected = {question.id for question in questions} + if set(raw_answers) != expected: + raise ValueError("native response ids do not match the submitted chunk") + + normalized: dict[str, str] = {} + for question in questions: + entry = raw_answers[question.id] + if isinstance(entry, Mapping): + entry = entry.get("answers") + if isinstance(entry, list): + if not entry or any( + not isinstance(value, str) or not value.strip() for value in entry + ): + raise ValueError( + f"native answer for {question.id!r} must contain non-empty strings" + ) + values = [value.strip() for value in entry] + sentinel = values[0].casefold() + if sentinel in {"none of the above", "other"} and len(values) > 1: + entry = " ".join(values[1:]) + else: + entry = " — ".join(values) + if not isinstance(entry, str) or not entry.strip(): + raise ValueError(f"native answer for {question.id!r} must be a non-empty string") + normalized[question.id] = entry.strip() + return normalized + + +def render_fallback(questions: Sequence[Question], reason: str) -> str: + """Render an explicit, truthful fallback when the native surface is absent.""" + + lines = [f"Native questionnaire unavailable: {reason}.", ""] + for index, question in enumerate(questions, start=1): + lines.append(f"{index}. {question.header}: {question.prompt}") + for option_index, option in enumerate(question.options): + marker = " (Recommended)" if option_index == question.recommended else "" + lines.append(f" - {option.label}{marker}: {option.description}") + lines.append(" - Other: provide a custom answer.") + lines.append("") + lines.append("Reply with one answer for every numbered question.") + return "\n".join(lines) + + +def confirmation_question() -> Question: + return Question( + id="shared_understanding", + header="Confirm", + prompt="Have we reached a complete shared understanding?", + options=( + Option("Confirmed", "The design tree is complete; stop interviewing."), + Option("Reopen", "Add the missing concern to the design tree and continue."), + ), + recommended=0, + ) + + +def resolve_confirmation(value: str) -> ConfirmationResult: + """Gate action on one explicit confirmation; every other answer continues.""" + + answer = value.strip() + if not answer: + raise ValueError("confirmation answer must be non-empty") + canonical = answer.removesuffix(" (Recommended)").removesuffix(" (recommended)") + if canonical == "Confirmed": + return ConfirmationResult(ConfirmationDisposition.CONFIRMED) + if canonical == "Reopen": + return ConfirmationResult(ConfirmationDisposition.REOPEN) + return ConfirmationResult(ConfirmationDisposition.EXTEND, concern=answer) diff --git a/dev_workflow/generated_codex.py b/dev_workflow/generated_codex.py new file mode 100644 index 0000000..4a2bc1d --- /dev/null +++ b/dev_workflow/generated_codex.py @@ -0,0 +1,180 @@ +"""Deterministic source for the generated Codex skill pair.""" + +from __future__ import annotations + +import json + + +UPSTREAM_COMMIT = "6654f6b60cd9d5be8b54c6fafe44346dabeb3b76" + +UPSTREAM_LICENSE = """MIT License + +Copyright (c) 2026 Matt Pocock + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +""" + + +GRILL_ME_SKILL = """--- +name: grill-me +description: Start a native, relentless interview that sharpens a plan, decision, or design. Use only when the user explicitly invokes grill-me or asks to be grilled. +--- + +# Grill Me + +Invoke the linked model-invoked `$grilling` skill with the current conversation +as its subject. Keep this wrapper thin; all interview behavior belongs to that +primitive. + +If `$grilling` is missing, stop and report that the linked skill bundle is +incomplete. Do not reconstruct the primitive from memory. Do not implement the +result until `$grilling` obtains explicit shared-understanding confirmation. +""" + + +GRILLING_SKILL = """--- +name: grilling +description: Interview the user relentlessly about a plan, decision, or idea through Codex's native questionnaire UI. Use for grill requests and when another skill delegates to the reusable grilling primitive. +--- + +# Grilling + +Treat the subject as a design tree. Each decision may unlock later decisions. +The frontier is every unresolved decision whose prerequisites are settled. + +## Build the frontier + +1. Resolve discoverable facts from the filesystem, tools, or other available + evidence. Never ask the user for a fact you can establish safely. +2. Keep unresolved fact lookups as prerequisites; ask the rest of the frontier + while independent facts are being resolved. +3. Give every decision a stable `snake_case` id, a short header, two or three + concrete choices, a concise trade-off per choice, and your recommendation. + Keep decisions with unsettled prerequisites out of the current frontier. +4. Snapshot the complete frontier before asking any question. + +The decisions are the user's. Never select an answer for them. + +## Select the active surface + +Inspect the tools and collaboration-mode instructions in the current session. +Use `request_user_input` only when that exact tool is exposed and the current +mode permits the call. Do not assume availability merely because this skill +names the tool. + +When native interaction is unavailable, say exactly which capability is absent +or denied, then use the text fallback below. Never describe a text response as +the native questionnaire UI. + +## Ask a native Codex round + +- Send one to three questions per `request_user_input` call. +- Write each question prompt as exactly one short sentence. Use a header of at + most 12 characters, a stable `snake_case` id, and two or three options with + 1-5 word labels. +- Make the two or three choices mutually exclusive. Give each choice one short + sentence that explains its impact or trade-off. +- Put the recommended option first and suffix its label with `(Recommended)`. +- Keep the recommended base label to at most four words so the suffix stays + within the five-word label limit. +- Do not add an `Other` option; the native client supplies the free-form escape. + +If the frontier snapshot has more than three questions, partition that snapshot +into ordered chunks of at most three. Collect every chunk before applying any +answer or recomputing the tree. Normalize selected options and free-form Other +answers only after the whole snapshot is answered. Preserve appended native +notes. For an Other response, discard only the native sentinel and keep all of +the user's free-form text. + +## Use the unavailable-tool fallback + +State `Native questionnaire unavailable: .` Then render the same +snapshotted questions as a compact numbered list with choices, trade-offs, +recommendations, and an explicit custom-answer escape. Wait for one answer per +question. For a frontier larger than three, keep the same immutable-snapshot +rule even though the fallback is not constrained by the native call limit. + +## Continue and confirm + +After the whole round is answered, record the user's decisions, reshape the +tree, and recompute the frontier. Repeat without a fixed question limit. + +When every known decision is settled, use the same active surface for one final question. +Do not treat a temporarily empty frontier blocked on fact lookup as completion. +Ask: +`Have we reached a complete shared understanding?` Offer `Confirmed +(Recommended)` and `Reopen`. A Reopen or custom concern extends the design tree +and resumes the rounds. Stop only on explicit confirmation, and do not act on +the grilled plan before it arrives. +""" + + +GRILL_ME_OPENAI = """interface: + display_name: "Grill Me" + short_description: "Start a native decision-tree interview" + default_prompt: "Use $grill-me to interview me until our plan is fully understood." +policy: + allow_implicit_invocation: false +""" + + +GRILLING_OPENAI = """interface: + display_name: "Grilling" + short_description: "Run reusable native questionnaire rounds" + default_prompt: "Use $grilling to stress-test this plan through native questionnaire rounds." +policy: + allow_implicit_invocation: true +""" + + +def manifest_text() -> str: + value = { + "schema_version": 1, + "harness": "codex", + "upstream": { + "repository": "mattpocock/skills", + "commit": UPSTREAM_COMMIT, + "license": "MIT", + "copyright": "Copyright (c) 2026 Matt Pocock", + }, + "skills": { + "grill-me": { + "path": "skills/grill-me", + "invocation": "user", + "requires": ["grilling"], + }, + "grilling": { + "path": "skills/grilling", + "invocation": "model", + "requires": [], + }, + }, + } + return json.dumps(value, indent=2, sort_keys=True) + "\n" + + +def generated_files() -> dict[str, str]: + return { + "skills/grill-me/SKILL.md": GRILL_ME_SKILL, + "skills/grill-me/agents/openai.yaml": GRILL_ME_OPENAI, + "skills/grilling/SKILL.md": GRILLING_SKILL, + "skills/grilling/agents/openai.yaml": GRILLING_OPENAI, + "bundle.json": manifest_text(), + "UPSTREAM_LICENSE": UPSTREAM_LICENSE, + } diff --git a/dev_workflow/grilling.py b/dev_workflow/grilling.py new file mode 100644 index 0000000..bfde478 --- /dev/null +++ b/dev_workflow/grilling.py @@ -0,0 +1,221 @@ +"""Canonical design-tree and frontier-round contract. + +The types in this module are harness-neutral. Harness adapters serialize an +immutable ``RoundSnapshot`` and return normalized answers. Only a complete +snapshot may be committed, which prevents adapter question limits from +changing the dependency frontier mid-round. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field, replace +import re +from typing import Iterable, Mapping, Sequence + + +@dataclass(frozen=True) +class Option: + """One user-owned choice and its concise trade-off.""" + + label: str + description: str + + def __post_init__(self) -> None: + if not self.label.strip(): + raise ValueError("option label must be non-empty") + if not self.description.strip(): + raise ValueError("option description must be non-empty") + + +@dataclass(frozen=True) +class Decision: + """A design-tree node whose prerequisites determine frontier membership.""" + + id: str + header: str + prompt: str + options: tuple[Option, ...] + recommended: int = 0 + depends_on: frozenset[str] = field(default_factory=frozenset) + facts_required: frozenset[str] = field(default_factory=frozenset) + + def __post_init__(self) -> None: + if not re.fullmatch(r"[a-z][a-z0-9]*(?:_[a-z0-9]+)*", self.id): + raise ValueError("decision id must be lowercase snake_case") + if not self.header.strip() or not self.prompt.strip(): + raise ValueError("decision header and prompt must be non-empty") + if len(self.options) < 2: + raise ValueError("a decision needs at least two options") + if not 0 <= self.recommended < len(self.options): + raise ValueError("recommended option index is out of range") + if self.id in self.depends_on: + raise ValueError("a decision cannot depend on itself") + + +@dataclass(frozen=True) +class Question: + """A decision projected into the canonical questionnaire shape.""" + + id: str + header: str + prompt: str + options: tuple[Option, ...] + recommended: int + + def __post_init__(self) -> None: + if not re.fullmatch(r"[a-z][a-z0-9]*(?:_[a-z0-9]+)*", self.id): + raise ValueError("question id must be lowercase snake_case") + if not self.header.strip() or not self.prompt.strip(): + raise ValueError("question header and prompt must be non-empty") + if len(self.options) < 2 or not 0 <= self.recommended < len(self.options): + raise ValueError("question choices and recommendation are invalid") + + @classmethod + def from_decision(cls, decision: Decision) -> "Question": + return cls( + id=decision.id, + header=decision.header, + prompt=decision.prompt, + options=decision.options, + recommended=decision.recommended, + ) + + +@dataclass(frozen=True) +class Answer: + """A normalized native or free-form answer.""" + + question_id: str + value: str + custom: bool + + +@dataclass(frozen=True) +class RoundSnapshot: + """The complete immutable frontier captured before any adapter calls.""" + + questions: tuple[Question, ...] + + @property + def ids(self) -> tuple[str, ...]: + return tuple(question.id for question in self.questions) + + def chunks(self, maximum: int) -> tuple[tuple[Question, ...], ...]: + if maximum < 1: + raise ValueError("maximum chunk size must be positive") + return tuple( + self.questions[index : index + maximum] + for index in range(0, len(self.questions), maximum) + ) + + +@dataclass(frozen=True) +class InterviewState: + """Settled decisions and facts at a frontier boundary.""" + + answers: Mapping[str, Answer] = field(default_factory=dict) + facts: frozenset[str] = field(default_factory=frozenset) + + def with_facts(self, facts: Iterable[str]) -> "InterviewState": + return replace(self, facts=self.facts | frozenset(facts)) + + +class DesignTree: + """Validate and traverse one deterministic design tree.""" + + def __init__(self, decisions: Sequence[Decision]) -> None: + self._decisions = tuple(decisions) + self._by_id = {decision.id: decision for decision in self._decisions} + if len(self._by_id) != len(self._decisions): + raise ValueError("decision ids must be unique") + known = set(self._by_id) + for decision in self._decisions: + unknown = decision.depends_on - known + if unknown: + raise ValueError( + f"decision {decision.id!r} has unknown dependencies: {sorted(unknown)}" + ) + self._reject_cycles() + + def _reject_cycles(self) -> None: + visiting: set[str] = set() + visited: set[str] = set() + + def visit(decision_id: str) -> None: + if decision_id in visiting: + raise ValueError("design tree contains a dependency cycle") + if decision_id in visited: + return + visiting.add(decision_id) + for dependency in self._by_id[decision_id].depends_on: + visit(dependency) + visiting.remove(decision_id) + visited.add(decision_id) + + for decision_id in self._by_id: + visit(decision_id) + + def frontier(self, state: InterviewState) -> tuple[Decision, ...]: + settled = set(state.answers) + return tuple( + decision + for decision in self._decisions + if decision.id not in settled + and decision.depends_on <= settled + and decision.facts_required <= state.facts + ) + + def snapshot(self, state: InterviewState) -> RoundSnapshot: + return RoundSnapshot( + tuple(Question.from_decision(decision) for decision in self.frontier(state)) + ) + + def complete(self, state: InterviewState) -> bool: + """Return true only when every known decision is settled.""" + + return set(state.answers) >= set(self._by_id) + + def blocked_on_facts(self, state: InterviewState) -> tuple[Decision, ...]: + """Expose decisions that must wait for discoverable evidence, not the user.""" + + settled = set(state.answers) + return tuple( + decision + for decision in self._decisions + if decision.id not in settled + and decision.depends_on <= settled + and not decision.facts_required <= state.facts + ) + + def commit_snapshot( + self, + state: InterviewState, + snapshot: RoundSnapshot, + raw_answers: Mapping[str, str], + ) -> InterviewState: + """Commit one whole frontier or reject the partial adapter result.""" + + expected = set(snapshot.ids) + received = set(raw_answers) + if received != expected: + missing = sorted(expected - received) + unexpected = sorted(received - expected) + raise ValueError( + f"snapshot answers must be complete; missing={missing}, unexpected={unexpected}" + ) + + answers = dict(state.answers) + for question in snapshot.questions: + value = str(raw_answers[question.id]).strip() + if not value: + raise ValueError(f"answer for {question.id!r} must be non-empty") + known_labels = {option.label for option in question.options} + canonical_value = value.removesuffix(" (Recommended)").removesuffix( + " (recommended)" + ) + answers[question.id] = Answer( + question_id=question.id, + value=canonical_value if canonical_value in known_labels else value, + custom=canonical_value not in known_labels, + ) + return replace(state, answers=answers) diff --git a/harnesses/codex/UPSTREAM_LICENSE b/harnesses/codex/UPSTREAM_LICENSE new file mode 100644 index 0000000..f1dd2c0 --- /dev/null +++ b/harnesses/codex/UPSTREAM_LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Matt Pocock + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/harnesses/codex/bundle.json b/harnesses/codex/bundle.json new file mode 100644 index 0000000..dfac902 --- /dev/null +++ b/harnesses/codex/bundle.json @@ -0,0 +1,24 @@ +{ + "harness": "codex", + "schema_version": 1, + "skills": { + "grill-me": { + "invocation": "user", + "path": "skills/grill-me", + "requires": [ + "grilling" + ] + }, + "grilling": { + "invocation": "model", + "path": "skills/grilling", + "requires": [] + } + }, + "upstream": { + "commit": "6654f6b60cd9d5be8b54c6fafe44346dabeb3b76", + "copyright": "Copyright (c) 2026 Matt Pocock", + "license": "MIT", + "repository": "mattpocock/skills" + } +} diff --git a/harnesses/codex/skills/grill-me/SKILL.md b/harnesses/codex/skills/grill-me/SKILL.md new file mode 100644 index 0000000..f0a37e3 --- /dev/null +++ b/harnesses/codex/skills/grill-me/SKILL.md @@ -0,0 +1,14 @@ +--- +name: grill-me +description: Start a native, relentless interview that sharpens a plan, decision, or design. Use only when the user explicitly invokes grill-me or asks to be grilled. +--- + +# Grill Me + +Invoke the linked model-invoked `$grilling` skill with the current conversation +as its subject. Keep this wrapper thin; all interview behavior belongs to that +primitive. + +If `$grilling` is missing, stop and report that the linked skill bundle is +incomplete. Do not reconstruct the primitive from memory. Do not implement the +result until `$grilling` obtains explicit shared-understanding confirmation. diff --git a/harnesses/codex/skills/grill-me/agents/openai.yaml b/harnesses/codex/skills/grill-me/agents/openai.yaml new file mode 100644 index 0000000..0db425e --- /dev/null +++ b/harnesses/codex/skills/grill-me/agents/openai.yaml @@ -0,0 +1,6 @@ +interface: + display_name: "Grill Me" + short_description: "Start a native decision-tree interview" + default_prompt: "Use $grill-me to interview me until our plan is fully understood." +policy: + allow_implicit_invocation: false diff --git a/harnesses/codex/skills/grilling/SKILL.md b/harnesses/codex/skills/grilling/SKILL.md new file mode 100644 index 0000000..920920f --- /dev/null +++ b/harnesses/codex/skills/grilling/SKILL.md @@ -0,0 +1,74 @@ +--- +name: grilling +description: Interview the user relentlessly about a plan, decision, or idea through Codex's native questionnaire UI. Use for grill requests and when another skill delegates to the reusable grilling primitive. +--- + +# Grilling + +Treat the subject as a design tree. Each decision may unlock later decisions. +The frontier is every unresolved decision whose prerequisites are settled. + +## Build the frontier + +1. Resolve discoverable facts from the filesystem, tools, or other available + evidence. Never ask the user for a fact you can establish safely. +2. Keep unresolved fact lookups as prerequisites; ask the rest of the frontier + while independent facts are being resolved. +3. Give every decision a stable `snake_case` id, a short header, two or three + concrete choices, a concise trade-off per choice, and your recommendation. + Keep decisions with unsettled prerequisites out of the current frontier. +4. Snapshot the complete frontier before asking any question. + +The decisions are the user's. Never select an answer for them. + +## Select the active surface + +Inspect the tools and collaboration-mode instructions in the current session. +Use `request_user_input` only when that exact tool is exposed and the current +mode permits the call. Do not assume availability merely because this skill +names the tool. + +When native interaction is unavailable, say exactly which capability is absent +or denied, then use the text fallback below. Never describe a text response as +the native questionnaire UI. + +## Ask a native Codex round + +- Send one to three questions per `request_user_input` call. +- Write each question prompt as exactly one short sentence. Use a header of at + most 12 characters, a stable `snake_case` id, and two or three options with + 1-5 word labels. +- Make the two or three choices mutually exclusive. Give each choice one short + sentence that explains its impact or trade-off. +- Put the recommended option first and suffix its label with `(Recommended)`. +- Keep the recommended base label to at most four words so the suffix stays + within the five-word label limit. +- Do not add an `Other` option; the native client supplies the free-form escape. + +If the frontier snapshot has more than three questions, partition that snapshot +into ordered chunks of at most three. Collect every chunk before applying any +answer or recomputing the tree. Normalize selected options and free-form Other +answers only after the whole snapshot is answered. Preserve appended native +notes. For an Other response, discard only the native sentinel and keep all of +the user's free-form text. + +## Use the unavailable-tool fallback + +State `Native questionnaire unavailable: .` Then render the same +snapshotted questions as a compact numbered list with choices, trade-offs, +recommendations, and an explicit custom-answer escape. Wait for one answer per +question. For a frontier larger than three, keep the same immutable-snapshot +rule even though the fallback is not constrained by the native call limit. + +## Continue and confirm + +After the whole round is answered, record the user's decisions, reshape the +tree, and recompute the frontier. Repeat without a fixed question limit. + +When every known decision is settled, use the same active surface for one final question. +Do not treat a temporarily empty frontier blocked on fact lookup as completion. +Ask: +`Have we reached a complete shared understanding?` Offer `Confirmed +(Recommended)` and `Reopen`. A Reopen or custom concern extends the design tree +and resumes the rounds. Stop only on explicit confirmation, and do not act on +the grilled plan before it arrives. diff --git a/harnesses/codex/skills/grilling/agents/openai.yaml b/harnesses/codex/skills/grilling/agents/openai.yaml new file mode 100644 index 0000000..1f3e53b --- /dev/null +++ b/harnesses/codex/skills/grilling/agents/openai.yaml @@ -0,0 +1,6 @@ +interface: + display_name: "Grilling" + short_description: "Run reusable native questionnaire rounds" + default_prompt: "Use $grilling to stress-test this plan through native questionnaire rounds." +policy: + allow_implicit_invocation: true diff --git a/scripts/generate_codex_skills.py b/scripts/generate_codex_skills.py new file mode 100755 index 0000000..b4e7dbe --- /dev/null +++ b/scripts/generate_codex_skills.py @@ -0,0 +1,47 @@ +#!/usr/bin/env python3 +"""Generate or verify the deterministic Codex skill bundle.""" + +from __future__ import annotations + +import argparse +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) + +from dev_workflow.generated_codex import generated_files # noqa: E402 + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--check", action="store_true") + parser.add_argument( + "--output", + type=Path, + default=ROOT / "harnesses" / "codex", + ) + args = parser.parse_args() + + failures: list[str] = [] + for relative, expected in generated_files().items(): + target = args.output / relative + if args.check: + if not target.is_file(): + failures.append(f"missing generated file: {target}") + elif target.read_text(encoding="utf-8") != expected: + failures.append(f"stale generated file: {target}") + continue + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(expected, encoding="utf-8") + + if failures: + print("\n".join(failures), file=sys.stderr) + return 1 + action = "verified" if args.check else "generated" + print(f"{action} {len(generated_files())} Codex bundle files") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/select_codex_skills.py b/scripts/select_codex_skills.py new file mode 100755 index 0000000..6205cbd --- /dev/null +++ b/scripts/select_codex_skills.py @@ -0,0 +1,39 @@ +#!/usr/bin/env python3 +"""Materialize a dependency-complete Codex skill selection into an empty root.""" + +from __future__ import annotations + +import argparse +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) + +from dev_workflow.bundle import materialize_selection # noqa: E402 + + +def main() -> int: + parser = argparse.ArgumentParser( + description=( + "Materialize a portable Codex selection. Use an isolated target; " + "live installation is outside this command contract." + ) + ) + parser.add_argument("--skill", action="append", required=True) + parser.add_argument("--target", type=Path, required=True) + args = parser.parse_args() + + try: + resolved = materialize_selection( + ROOT / "harnesses" / "codex", args.target, args.skill + ) + except (FileExistsError, OSError, ValueError) as error: + print(f"error: {error}", file=sys.stderr) + return 2 + print("materialized: " + ", ".join(resolved)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/validate_skills.py b/scripts/validate_skills.py new file mode 100755 index 0000000..f4000c6 --- /dev/null +++ b/scripts/validate_skills.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python3 +"""Dependency-free repository gate mirroring quick skill validation.""" + +from __future__ import annotations + +import argparse +import re +from pathlib import Path + + +FRONTMATTER = re.compile(r"^---\n(?P.*?)\n---\n", re.DOTALL) + + +def parse_frontmatter(text: str) -> dict[str, str]: + match = FRONTMATTER.match(text) + if not match: + raise ValueError("missing or malformed YAML frontmatter") + result: dict[str, str] = {} + for line in match.group("body").splitlines(): + key, separator, value = line.partition(":") + if not separator or not key.strip() or not value.strip(): + raise ValueError(f"unsupported frontmatter line: {line!r}") + result[key.strip()] = value.strip() + return result + + +def validate_skill(path: Path) -> list[str]: + errors: list[str] = [] + skill_md = path / "SKILL.md" + if not skill_md.is_file(): + return [f"{path}: SKILL.md not found"] + text = skill_md.read_text(encoding="utf-8") + try: + frontmatter = parse_frontmatter(text) + except ValueError as error: + return [f"{path}: {error}"] + if set(frontmatter) != {"name", "description"}: + errors.append(f"{path}: frontmatter must contain exactly name and description") + name = frontmatter.get("name", "") + if not re.fullmatch(r"[a-z0-9]+(?:-[a-z0-9]+)*", name): + errors.append(f"{path}: invalid skill name {name!r}") + if name != path.name: + errors.append(f"{path}: folder and skill name differ") + description = frontmatter.get("description", "") + if not description or len(description) > 1024 or "<" in description or ">" in description: + errors.append(f"{path}: invalid skill description") + if len(text.splitlines()) > 500: + errors.append(f"{path}: SKILL.md exceeds 500 lines") + return errors + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("paths", nargs="+", type=Path) + args = parser.parse_args() + errors = [error for path in args.paths for error in validate_skill(path)] + if errors: + print("\n".join(errors)) + return 1 + print(f"validated {len(args.paths)} skill folders") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/verify-outcome.sh b/scripts/verify-outcome.sh new file mode 100755 index 0000000..b58cdbd --- /dev/null +++ b/scripts/verify-outcome.sh @@ -0,0 +1,14 @@ +#!/usr/bin/env bash +set -euo pipefail + +repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" +cd "$repo_root" + +python3 -m compileall -q dev_workflow scripts tests +python3 scripts/generate_codex_skills.py --check +python3 scripts/validate_skills.py \ + harnesses/codex/skills/grill-me \ + harnesses/codex/skills/grilling +python3 -m unittest discover -s tests -v + +printf 'dev-workflow outcome verified\n' diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..8a0c24b --- /dev/null +++ b/tests/__init__.py @@ -0,0 +1 @@ +"""Repository verification fixtures.""" diff --git a/tests/test_codex_adapter.py b/tests/test_codex_adapter.py new file mode 100644 index 0000000..f814f2b --- /dev/null +++ b/tests/test_codex_adapter.py @@ -0,0 +1,231 @@ +from __future__ import annotations + +from dataclasses import replace +import unittest + +from dev_workflow.codex import ( + Capabilities, + ConfirmationDisposition, + Surface, + confirmation_question, + normalize_native_response, + plan_chunks, + render_fallback, + resolve_confirmation, + serialize_native, +) +from dev_workflow.grilling import Decision, DesignTree, InterviewState, Option + + +def root(decision_id: str, *, depends_on: frozenset[str] = frozenset()) -> Decision: + return Decision( + id=decision_id, + header=decision_id[:12], + prompt=f"Choose the {decision_id} direction", + options=( + Option("Speed first", "Choose delivery speed as the priority."), + Option("Durability first", "Choose future flexibility as the priority."), + ), + recommended=1, + depends_on=depends_on, + ) + + +class CodexAdapterTests(unittest.TestCase): + def test_native_surface_requires_tool_and_permitted_mode(self) -> None: + self.assertEqual(Capabilities(True, True).surface, Surface.NATIVE) + denied = Capabilities(True, False) + self.assertEqual(denied.surface, Surface.FALLBACK) + self.assertIn("mode", denied.fallback_reason or "") + absent = Capabilities(False, True) + self.assertEqual(absent.surface, Surface.FALLBACK) + self.assertIn("not exposed", absent.fallback_reason or "") + + def test_larger_frontier_is_snapshotted_before_three_question_chunks(self) -> None: + tree = DesignTree( + [ + *(root(f"root_{index}") for index in range(1, 6)), + root("child", depends_on=frozenset({"root_1"})), + ] + ) + initial = InterviewState() + snapshot = tree.snapshot(initial) + self.assertEqual( + snapshot.ids, ("root_1", "root_2", "root_3", "root_4", "root_5") + ) + chunks = plan_chunks(snapshot) + self.assertEqual(tuple(len(chunk) for chunk in chunks), (3, 2)) + self.assertEqual( + tuple(item["id"] for item in serialize_native(chunks[0])["questions"]), + ("root_1", "root_2", "root_3"), + ) + + with self.assertRaisesRegex(ValueError, "must be complete"): + tree.commit_snapshot( + initial, + snapshot, + { + question.id: "Durability first (Recommended)" + for question in chunks[0] + }, + ) + self.assertNotIn("child", tree.snapshot(initial).ids) + + collected = { + question.id: "Durability first (Recommended)" + for chunk in chunks + for question in chunk + } + settled = tree.commit_snapshot(initial, snapshot, collected) + self.assertEqual(tree.snapshot(settled).ids, ("child",)) + + def test_native_payload_reorders_recommendation_and_uses_exact_schema(self) -> None: + tree = DesignTree([root("delivery")]) + question = tree.snapshot(InterviewState()).questions[0] + payload = serialize_native((question,)) + self.assertEqual(set(payload), {"questions"}) + native = payload["questions"][0] + self.assertEqual( + set(native), {"id", "header", "question", "options"} + ) + self.assertEqual( + native["options"][0]["label"], "Durability first (Recommended)" + ) + self.assertEqual(native["options"][1]["label"], "Speed first") + self.assertNotIn("Other", [option["label"] for option in native["options"]]) + + def test_native_response_normalizes_recommended_and_other_values(self) -> None: + tree = DesignTree([root("delivery"), root("scope")]) + questions = tree.snapshot(InterviewState()).questions + normalized = normalize_native_response( + questions, + { + "answers": { + "delivery": { + "answers": ["Durability first (Recommended)"] + }, + "scope": {"answers": ["Keep both linked skills"]}, + } + }, + ) + state = tree.commit_snapshot( + InterviewState(), tree.snapshot(InterviewState()), normalized + ) + self.assertEqual(state.answers["delivery"].value, "Durability first") + self.assertFalse(state.answers["delivery"].custom) + self.assertEqual(state.answers["scope"].value, "Keep both linked skills") + self.assertTrue(state.answers["scope"].custom) + + def test_native_response_preserves_option_notes_and_other_text(self) -> None: + tree = DesignTree([root("delivery"), root("scope")]) + snapshot = tree.snapshot(InterviewState()) + normalized = normalize_native_response( + snapshot.questions, + { + "answers": { + "delivery": { + "answers": [ + "Durability first (Recommended)", + "Only if generation stays deterministic", + ] + }, + "scope": { + "answers": [ + "None of the above", + "Keep both linked skills", + "and retain attribution", + ] + }, + } + }, + ) + self.assertEqual( + normalized["delivery"], + "Durability first (Recommended) — Only if generation stays deterministic", + ) + self.assertEqual( + normalized["scope"], "Keep both linked skills and retain attribution" + ) + state = tree.commit_snapshot(InterviewState(), snapshot, normalized) + self.assertTrue(state.answers["delivery"].custom) + self.assertEqual( + state.answers["scope"].value, + "Keep both linked skills and retain attribution", + ) + self.assertTrue(state.answers["scope"].custom) + + def test_unavailable_tool_fallback_is_explicit_and_supports_other(self) -> None: + tree = DesignTree([root("delivery")]) + snapshot = tree.snapshot(InterviewState()) + output = render_fallback(snapshot.questions, "request_user_input is not exposed") + self.assertIn("Native questionnaire unavailable:", output) + self.assertIn("request_user_input is not exposed", output) + self.assertIn("Other: provide a custom answer", output) + self.assertIn("Durability first (Recommended)", output) + state = tree.commit_snapshot( + InterviewState(), + snapshot, + {"delivery": "Durability first (Recommended)"}, + ) + self.assertEqual(state.answers["delivery"].value, "Durability first") + self.assertFalse(state.answers["delivery"].custom) + + def test_native_schema_rejects_multi_sentence_prompt_or_description(self) -> None: + question = DesignTree([root("delivery")]).snapshot(InterviewState()).questions[0] + with self.assertRaisesRegex(ValueError, "prompt.*one short sentence"): + serialize_native( + ( + replace(question, prompt="Choose a direction. Then explain it."), + ) + ) + options = ( + Option("Speed first", "Choose speed. Accept less flexibility."), + question.options[1], + ) + with self.assertRaisesRegex(ValueError, "descriptions.*one short sentence"): + serialize_native((replace(question, options=options),)) + + def test_final_confirmation_uses_native_questionnaire_shape(self) -> None: + payload = serialize_native((confirmation_question(),)) + question = payload["questions"][0] + self.assertEqual(question["id"], "shared_understanding") + self.assertEqual(question["header"], "Confirm") + self.assertEqual(question["options"][0]["label"], "Confirmed (Recommended)") + self.assertEqual(question["options"][1]["label"], "Reopen") + + def test_only_explicit_confirmation_allows_action(self) -> None: + question = confirmation_question() + normalized = normalize_native_response( + (question,), + { + "answers": { + "shared_understanding": { + "answers": ["Confirmed (Recommended)"] + } + } + }, + ) + confirmed = resolve_confirmation(normalized["shared_understanding"]) + self.assertEqual( + confirmed.disposition, ConfirmationDisposition.CONFIRMED + ) + self.assertTrue(confirmed.may_act) + self.assertFalse(confirmed.continue_interview) + self.assertFalse(confirmed.extends_tree) + + reopened = resolve_confirmation("Reopen") + self.assertEqual(reopened.disposition, ConfirmationDisposition.REOPEN) + self.assertFalse(reopened.may_act) + self.assertTrue(reopened.continue_interview) + self.assertTrue(reopened.extends_tree) + + custom = resolve_confirmation("We still need an offline decision") + self.assertEqual(custom.disposition, ConfirmationDisposition.EXTEND) + self.assertEqual(custom.concern, "We still need an offline decision") + self.assertFalse(custom.may_act) + self.assertTrue(custom.continue_interview) + self.assertTrue(custom.extends_tree) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_generation.py b/tests/test_generation.py new file mode 100644 index 0000000..de03ebb --- /dev/null +++ b/tests/test_generation.py @@ -0,0 +1,84 @@ +from __future__ import annotations + +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +from dev_workflow.generated_codex import generated_files +from scripts.validate_skills import parse_frontmatter, validate_skill + + +ROOT = Path(__file__).resolve().parents[1] +BUNDLE = ROOT / "harnesses" / "codex" + + +class GenerationTests(unittest.TestCase): + def test_committed_bundle_is_current(self) -> None: + result = subprocess.run( + [sys.executable, "scripts/generate_codex_skills.py", "--check"], + cwd=ROOT, + text=True, + capture_output=True, + check=False, + ) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + + def test_generation_is_byte_deterministic(self) -> None: + with tempfile.TemporaryDirectory() as first, tempfile.TemporaryDirectory() as second: + for output in (first, second): + result = subprocess.run( + [ + sys.executable, + "scripts/generate_codex_skills.py", + "--output", + output, + ], + cwd=ROOT, + text=True, + capture_output=True, + check=False, + ) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + for relative in generated_files(): + self.assertEqual( + (Path(first) / relative).read_bytes(), + (Path(second) / relative).read_bytes(), + ) + + def test_generated_skills_follow_skill_creator_contract(self) -> None: + for name in ("grill-me", "grilling"): + path = BUNDLE / "skills" / name + self.assertEqual(validate_skill(path), []) + frontmatter = parse_frontmatter((path / "SKILL.md").read_text()) + self.assertEqual(set(frontmatter), {"name", "description"}) + + def test_wrapper_and_primitive_remain_linked_and_distinct(self) -> None: + wrapper = (BUNDLE / "skills/grill-me/SKILL.md").read_text() + primitive = (BUNDLE / "skills/grilling/SKILL.md").read_text() + wrapper_metadata = ( + BUNDLE / "skills/grill-me/agents/openai.yaml" + ).read_text() + primitive_metadata = ( + BUNDLE / "skills/grilling/agents/openai.yaml" + ).read_text() + self.assertIn("$grilling", wrapper) + self.assertNotIn("request_user_input", wrapper) + self.assertIn("Use `request_user_input`", primitive) + self.assertIn("partition that snapshot", primitive) + self.assertIn("Do not assume availability", primitive) + self.assertIn("choices mutually exclusive", primitive) + self.assertIn("one short", primitive) + self.assertIn("allow_implicit_invocation: false", wrapper_metadata) + self.assertIn("allow_implicit_invocation: true", primitive_metadata) + + def test_generated_bundle_retains_upstream_mit_notice(self) -> None: + notice = (BUNDLE / "UPSTREAM_LICENSE").read_text() + manifest = (BUNDLE / "bundle.json").read_text() + self.assertIn("Copyright (c) 2026 Matt Pocock", notice) + self.assertIn("6654f6b60cd9d5be8b54c6fafe44346dabeb3b76", manifest) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_grilling_contract.py b/tests/test_grilling_contract.py new file mode 100644 index 0000000..5e6c5ac --- /dev/null +++ b/tests/test_grilling_contract.py @@ -0,0 +1,94 @@ +from __future__ import annotations + +import unittest + +from dev_workflow.grilling import Decision, DesignTree, InterviewState, Option + + +def decision( + decision_id: str, + *, + depends_on: frozenset[str] = frozenset(), + facts_required: frozenset[str] = frozenset(), +) -> Decision: + return Decision( + id=decision_id, + header=decision_id[:12], + prompt=f"Choose {decision_id}", + options=( + Option("Preferred", "The recommended balanced choice."), + Option("Alternate", "A valid choice with a different trade-off."), + ), + depends_on=depends_on, + facts_required=facts_required, + ) + + +class DesignTreeTests(unittest.TestCase): + def test_frontier_waits_for_decisions_and_discoverable_facts(self) -> None: + tree = DesignTree( + [ + decision("root"), + decision("fact_gate", facts_required=frozenset({"repo_state"})), + decision("child", depends_on=frozenset({"root"})), + ] + ) + state = InterviewState() + self.assertEqual(tree.snapshot(state).ids, ("root",)) + self.assertFalse(tree.complete(state)) + self.assertEqual( + tuple(item.id for item in tree.blocked_on_facts(state)), ("fact_gate",) + ) + + state = state.with_facts({"repo_state"}) + snapshot = tree.snapshot(state) + self.assertEqual(snapshot.ids, ("root", "fact_gate")) + state = tree.commit_snapshot( + state, + snapshot, + {"root": "Preferred", "fact_gate": "Alternate"}, + ) + self.assertEqual(tree.snapshot(state).ids, ("child",)) + self.assertFalse(tree.complete(state)) + child = tree.snapshot(state) + state = tree.commit_snapshot(state, child, {"child": "Preferred"}) + self.assertTrue(tree.complete(state)) + + def test_partial_snapshot_cannot_be_committed(self) -> None: + tree = DesignTree([decision("one"), decision("two")]) + snapshot = tree.snapshot(InterviewState()) + with self.assertRaisesRegex(ValueError, "must be complete"): + tree.commit_snapshot(InterviewState(), snapshot, {"one": "Preferred"}) + + def test_recommended_native_suffix_normalizes_to_known_option(self) -> None: + tree = DesignTree([decision("shape")]) + snapshot = tree.snapshot(InterviewState()) + state = tree.commit_snapshot( + InterviewState(), snapshot, {"shape": "Preferred (Recommended)"} + ) + answer = state.answers["shape"] + self.assertEqual(answer.value, "Preferred") + self.assertFalse(answer.custom) + + def test_free_form_other_is_preserved_as_custom(self) -> None: + tree = DesignTree([decision("shape")]) + snapshot = tree.snapshot(InterviewState()) + state = tree.commit_snapshot( + InterviewState(), snapshot, {"shape": "Use the existing contract verbatim"} + ) + answer = state.answers["shape"] + self.assertEqual(answer.value, "Use the existing contract verbatim") + self.assertTrue(answer.custom) + + def test_cycles_are_rejected(self) -> None: + with self.assertRaisesRegex(ValueError, "cycle"): + DesignTree( + [ + decision("one", depends_on=frozenset({"two"})), + decision("two", depends_on=frozenset({"one"})), + ] + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_selective_bundle.py b/tests/test_selective_bundle.py new file mode 100644 index 0000000..5c6c2b8 --- /dev/null +++ b/tests/test_selective_bundle.py @@ -0,0 +1,85 @@ +from __future__ import annotations + +import json +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +from dev_workflow.bundle import resolve_skills + + +ROOT = Path(__file__).resolve().parents[1] +BUNDLE = ROOT / "harnesses" / "codex" + + +class SelectiveBundleTests(unittest.TestCase): + def test_selecting_wrapper_includes_model_invoked_dependency(self) -> None: + with tempfile.TemporaryDirectory() as temporary: + target = Path(temporary) / "selection" + result = subprocess.run( + [ + sys.executable, + "scripts/select_codex_skills.py", + "--skill", + "grill-me", + "--target", + str(target), + ], + cwd=ROOT, + text=True, + capture_output=True, + check=False, + ) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + self.assertEqual( + result.stdout.strip(), "materialized: grilling, grill-me" + ) + self.assertTrue((target / "grill-me/SKILL.md").is_file()) + self.assertTrue((target / "grilling/SKILL.md").is_file()) + notice = (target / "dev-workflow-UPSTREAM_LICENSE").read_text() + self.assertIn("Copyright (c) 2026 Matt Pocock", notice) + selection = json.loads( + (target / "dev-workflow-bundle.json").read_text() + ) + self.assertEqual( + tuple(selection["skills"]), ("grill-me", "grilling") + ) + self.assertEqual(selection["skills"]["grill-me"]["requires"], ["grilling"]) + self.assertEqual(selection["skills"]["grill-me"]["path"], "grill-me") + self.assertEqual(selection["skills"]["grilling"]["path"], "grilling") + self.assertEqual( + selection["upstream"]["commit"], + "6654f6b60cd9d5be8b54c6fafe44346dabeb3b76", + ) + + def test_selecting_primitive_does_not_invent_reverse_dependency(self) -> None: + manifest = json.loads((BUNDLE / "bundle.json").read_text()) + self.assertEqual(resolve_skills(manifest, ["grilling"]), ("grilling",)) + + def test_selector_refuses_a_nonempty_target(self) -> None: + with tempfile.TemporaryDirectory() as temporary: + target = Path(temporary) + (target / "existing.txt").write_text("preserve me") + result = subprocess.run( + [ + sys.executable, + "scripts/select_codex_skills.py", + "--skill", + "grill-me", + "--target", + str(target), + ], + cwd=ROOT, + text=True, + capture_output=True, + check=False, + ) + self.assertEqual(result.returncode, 2) + self.assertIn("selection target must be empty", result.stderr) + self.assertEqual((target / "existing.txt").read_text(), "preserve me") + + +if __name__ == "__main__": + unittest.main()