Skip to content

abc_mine.prompts

WARNING

This documentation is almost entirely "vibe coded"; while a helpful resource for humans and agents to understand this codebase, it should not be considered a source of ground truth in the way documentation normally is, and the user is responsible for verifying that all instructions given here are safe.

abc_mine.prompts

Prompt composition: generic templates, per-codebase slots, and overrides.

abc-mine ships generic prompt templates (abc_mine/templates/) that know nothing about any particular codebase. There are two, deliberately distinct, mechanisms for adapting them to a specific repository.

.. _prompt-layering:

The two layers

A prompt pack is a directory the user points at with prompts.pack:

.. code-block:: text

my-codebase-prompts/
  slots/                     # (1) ADDITIVE context — the normal path
    codebase_overview.md
    build_test_guidance.md
    verification_guidance.md
    screening_notes.md
    ranking_notes.md
    construction_notes.md
    exclusions.md
  overrides/                 # (2) FULL REPLACEMENT — advanced, opt-in
    screen_system.md
    ...

(1) Slots — additive, the expected path. Each file fills one named slot in the shipped templates. A slot renders as a whole titled section that disappears entirely when the file is absent, so the surrounding prose reads correctly whether or not the user supplied anything. Writing a slot pack requires no knowledge of the base templates. Every slot is optional; the tool works with an empty pack, or no pack at all.

(2) Overrides — full replacement, deliberately gated. Occasionally a user needs to rewrite a base template outright rather than append to it. That is supported, but it is intentionally hard to do by accident, because a silently overridden system prompt is a debugging nightmare. Three independent things must line up:

  1. the file must live in overrides/ (not slots/),
  2. it must be named exactly after a known base template (unknown names are a hard error, never a silent no-op),
  3. the run config must set prompts.allow_template_overrides: true.

If overrides/ contains files but the flag is not set, loading fails loudly rather than ignoring them — the one thing worse than an accidental override is an accidentally-ignored one. Active overrides are recorded in the run manifest with their SHA-256 and announced in a banner at every stage start, so a run using them can never be mistaken for a stock run.

Overrides still receive normal placeholder substitution (including slots), and are validated: a template that drops a mechanically required placeholder — an output path the stage depends on — is rejected, since the stage could not function. Dropping a merely advisory placeholder (e.g. the rubric table) warns instead. That severity split is deliberate: mechanical breakage is an error, prompt-quality regression is the user's call.

Placeholder syntax

All substitution uses @@name@@. Unlike {name}, this cannot collide with the JSON braces that appear throughout these prompts (the original Truchas pipeline needed a single-pass regex hack to work around exactly that), so injected JSON blocks are never re-scanned or mangled.

Slots are referenced as @@slot:codebase_overview@@.

Slot dataclass

One named, optional, per-codebase prompt slot.

Attributes:

Name Type Description
key str

Slot name; the file stem under slots/ and the @@slot:<key>@@ placeholder token.

heading str

Markdown heading emitted above the user's content when the slot is filled. Omitted entirely when the slot is empty.

purpose str

One-line description shown by abc-mine prompts slots, and used as the doc comment when scaffolding an empty pack.

templates tuple[str, ...]

Base templates in which this slot appears.

Source code in abc_mine/prompts.py
@dataclass(frozen=True)
class Slot:
    """One named, optional, per-codebase prompt slot.

    Attributes
    ----------
    key : str
        Slot name; the file stem under ``slots/`` and the ``@@slot:<key>@@``
        placeholder token.
    heading : str
        Markdown heading emitted above the user's content when the slot is
        filled. Omitted entirely when the slot is empty.
    purpose : str
        One-line description shown by ``abc-mine prompts slots``, and used
        as the doc comment when scaffolding an empty pack.
    templates : tuple[str, ...]
        Base templates in which this slot appears.
    """

    key: str
    heading: str
    purpose: str
    templates: tuple[str, ...]

PromptError

Bases: RuntimeError

Raised for malformed prompt packs, bad overrides, or missing templates.

Source code in abc_mine/prompts.py
class PromptError(RuntimeError):
    """Raised for malformed prompt packs, bad overrides, or missing templates."""

PromptPack dataclass

A loaded prompt pack: per-codebase slot content plus any overrides.

Attributes:

Name Type Description
root Path or None

The pack directory, or None when no pack was configured.

slots dict[str, str]

Slot key -> file content, for slots the user actually supplied. Absent and whitespace-only files are omitted, so an empty file behaves exactly like a missing one (a blank slot must not emit a dangling heading).

overrides dict[str, str]

Template name -> replacement body, for active overrides only.

override_digests dict[str, str]

Template name -> SHA-256 of the override body, recorded in the run manifest so an overridden run is auditable after the fact.

warnings list[str]

Non-fatal problems (e.g. an override dropping an advisory placeholder), surfaced by the CLI at stage start.

Source code in abc_mine/prompts.py
@dataclass
class PromptPack:
    """A loaded prompt pack: per-codebase slot content plus any overrides.

    Attributes
    ----------
    root : Path or None
        The pack directory, or ``None`` when no pack was configured.
    slots : dict[str, str]
        Slot key -> file content, for slots the user actually supplied. Absent
        and whitespace-only files are omitted, so an empty file behaves exactly
        like a missing one (a blank slot must not emit a dangling heading).
    overrides : dict[str, str]
        Template name -> replacement body, for active overrides only.
    override_digests : dict[str, str]
        Template name -> SHA-256 of the override body, recorded in the run
        manifest so an overridden run is auditable after the fact.
    warnings : list[str]
        Non-fatal problems (e.g. an override dropping an advisory placeholder),
        surfaced by the CLI at stage start.
    """

    root: Path | None = None
    slots: dict[str, str] = field(default_factory=dict)
    overrides: dict[str, str] = field(default_factory=dict)
    override_digests: dict[str, str] = field(default_factory=dict)
    warnings: list[str] = field(default_factory=list)

    @property
    def has_overrides(self) -> bool:
        """True if any base template is being replaced."""
        return bool(self.overrides)

    def banner(self) -> str | None:
        """Return a loud multi-line banner when overrides are active, else None."""
        if not self.has_overrides:
            return None
        lines = [
            "!" * 72,
            "PROMPT TEMPLATE OVERRIDES ACTIVE — this run does NOT use stock prompts.",
            "",
        ]
        for name in sorted(self.overrides):
            lines.append(f"  {name:<16} overridden  (sha256 {self.override_digests[name][:16]})")
        lines += [
            "",
            "Recorded in the run manifest. Re-run without "
            "prompts.allow_template_overrides",
            "to restore the shipped templates.",
            "!" * 72,
        ]
        return "\n".join(lines)

has_overrides property

has_overrides: bool

True if any base template is being replaced.

banner

banner() -> str | None

Return a loud multi-line banner when overrides are active, else None.

Source code in abc_mine/prompts.py
def banner(self) -> str | None:
    """Return a loud multi-line banner when overrides are active, else None."""
    if not self.has_overrides:
        return None
    lines = [
        "!" * 72,
        "PROMPT TEMPLATE OVERRIDES ACTIVE — this run does NOT use stock prompts.",
        "",
    ]
    for name in sorted(self.overrides):
        lines.append(f"  {name:<16} overridden  (sha256 {self.override_digests[name][:16]})")
    lines += [
        "",
        "Recorded in the run manifest. Re-run without "
        "prompts.allow_template_overrides",
        "to restore the shipped templates.",
        "!" * 72,
    ]
    return "\n".join(lines)

slot_by_key

slot_by_key(key: str) -> Slot

Return the :class:Slot named key or raise :class:KeyError.

Source code in abc_mine/prompts.py
def slot_by_key(key: str) -> Slot:
    """Return the :class:`Slot` named ``key`` or raise :class:`KeyError`."""
    for s in SLOTS:
        if s.key == key:
            return s
    raise KeyError(key)

load_pack

load_pack(pack_dir: Path | str | None, *, allow_template_overrides: bool = False) -> PromptPack

Load a prompt pack from pack_dir.

Parameters:

Name Type Description Default
pack_dir Path, str, or None

The pack directory. None yields an empty pack (fully generic prompts) — the tool is usable with no pack at all.

required
allow_template_overrides bool

Whether overrides/ may take effect. Defaults to False.

False

Raises:

Type Description
PromptError

If the directory does not exist; if slots/ or overrides/ contains an unrecognized filename; if overrides/ is non-empty while allow_template_overrides is False; or if an override drops a mechanically required placeholder.

Source code in abc_mine/prompts.py
def load_pack(
    pack_dir: Path | str | None,
    *,
    allow_template_overrides: bool = False,
) -> PromptPack:
    """Load a prompt pack from ``pack_dir``.

    Parameters
    ----------
    pack_dir : Path, str, or None
        The pack directory. ``None`` yields an empty pack (fully generic
        prompts) — the tool is usable with no pack at all.
    allow_template_overrides : bool, optional
        Whether ``overrides/`` may take effect. Defaults to False.

    Raises
    ------
    PromptError
        If the directory does not exist; if ``slots/`` or ``overrides/``
        contains an unrecognized filename; if ``overrides/`` is non-empty while
        ``allow_template_overrides`` is False; or if an override drops a
        mechanically required placeholder.
    """
    if pack_dir is None:
        return PromptPack()

    root = Path(pack_dir).expanduser()
    if not root.is_dir():
        raise PromptError(
            f"prompt pack directory not found: {root}\n"
            "Create one with `abc-mine prompts scaffold <dir>`, or omit "
            "prompts.pack to use the generic prompts unchanged."
        )

    pack = PromptPack(root=root)
    _load_slots(root, pack)
    _load_overrides(root, pack, allow_template_overrides=allow_template_overrides)
    return pack

strip_comments

strip_comments(text: str) -> str

Remove HTML comments from slot content and normalize surrounding blanks.

Scaffolded slot files consist of an instructional <!-- ... --> block describing what to write. Those comments must never reach a live prompt: a freshly-scaffolded pack would otherwise inject "this file is OPTIONAL, delete it" into the agent's instructions under a real heading. Stripping them also means a comment-only file is correctly treated as empty, so its slot vanishes exactly as an absent file's would — which is what a user who scaffolded a pack and filled in only two slots expects.

Users may also keep explanatory comments alongside real content; those are removed too, so a slot's rendered form is only its prose.

Source code in abc_mine/prompts.py
def strip_comments(text: str) -> str:
    """Remove HTML comments from slot content and normalize surrounding blanks.

    Scaffolded slot files consist of an instructional ``<!-- ... -->`` block
    describing what to write. Those comments must never reach a live prompt: a
    freshly-scaffolded pack would otherwise inject "this file is OPTIONAL, delete
    it" into the agent's instructions under a real heading. Stripping them also
    means a comment-only file is correctly treated as *empty*, so its slot
    vanishes exactly as an absent file's would — which is what a user who
    scaffolded a pack and filled in only two slots expects.

    Users may also keep explanatory comments alongside real content; those are
    removed too, so a slot's rendered form is only its prose.
    """
    return _COMMENT_RE.sub("", text).strip()

load_template

load_template(name: str, pack: PromptPack | None = None) -> str

Return the body of base template name, honoring an active override.

Source code in abc_mine/prompts.py
def load_template(name: str, pack: PromptPack | None = None) -> str:
    """Return the body of base template ``name``, honoring an active override."""
    if name not in TEMPLATE_NAMES:
        raise PromptError(
            f"unknown template {name!r}; expected one of {', '.join(TEMPLATE_NAMES)}"
        )
    if pack is not None and name in pack.overrides:
        return pack.overrides[name]
    path = TEMPLATE_DIR / f"{name}{PROMPT_SUFFIX}"
    if not path.is_file():
        raise PromptError(f"shipped template missing from installation: {path}")
    return path.read_text()

render_slot

render_slot(key: str, pack: PromptPack | None) -> str

Render one slot as a complete titled section, or an empty string.

This all-or-nothing shape is what lets the base templates read naturally in both states: an unfilled slot leaves no heading, no lead-in, and no stray whitespace behind — as though the section had never been written.

Source code in abc_mine/prompts.py
def render_slot(key: str, pack: PromptPack | None) -> str:
    """Render one slot as a complete titled section, or an empty string.

    This all-or-nothing shape is what lets the base templates read naturally in
    both states: an unfilled slot leaves no heading, no lead-in, and no stray
    whitespace behind — as though the section had never been written.
    """
    slot = slot_by_key(key)
    content = (pack.slots.get(key, "") if pack else "").strip()
    if not content:
        return ""
    return f"{slot.heading}\n\n{content}"

render

render(name: str, *, pack: PromptPack | None = None, variables: Mapping[str, Any] | None = None, strict: bool = True) -> str

Render template name with slots and variables substituted.

Substitution is a single simultaneous pass: replaced content is never re-scanned, so an injected value that happens to contain @@foo@@ (or JSON braces) is left intact.

Parameters:

Name Type Description Default
name str

Base template name.

required
pack PromptPack

Loaded prompt pack supplying slot content and overrides.

None
variables mapping

Values for @@name@@ placeholders.

None
strict bool

If True (default), an unresolved non-slot placeholder raises. This catches the class of bug where a stage forgets to pass a path and the agent receives a literal @@summary_path@@ in its instructions. Unresolved slot placeholders are always fine — that is how an unfilled slot vanishes.

True

Raises:

Type Description
PromptError

If strict and an unknown placeholder remains.

Source code in abc_mine/prompts.py
def render(
    name: str,
    *,
    pack: PromptPack | None = None,
    variables: Mapping[str, Any] | None = None,
    strict: bool = True,
) -> str:
    """Render template ``name`` with slots and variables substituted.

    Substitution is a **single simultaneous pass**: replaced content is never
    re-scanned, so an injected value that happens to contain ``@@foo@@`` (or JSON
    braces) is left intact.

    Parameters
    ----------
    name : str
        Base template name.
    pack : PromptPack, optional
        Loaded prompt pack supplying slot content and overrides.
    variables : mapping, optional
        Values for ``@@name@@`` placeholders.
    strict : bool, optional
        If True (default), an unresolved non-slot placeholder raises. This
        catches the class of bug where a stage forgets to pass a path and the
        agent receives a literal ``@@summary_path@@`` in its instructions.
        Unresolved *slot* placeholders are always fine — that is how an unfilled
        slot vanishes.

    Raises
    ------
    PromptError
        If ``strict`` and an unknown placeholder remains.
    """
    body = load_template(name, pack)
    variables = dict(variables or {})
    unresolved: list[str] = []

    def _sub(match: re.Match) -> str:
        is_slot, key = match.group(1), match.group(2)
        if is_slot:
            try:
                return render_slot(key, pack)
            except KeyError:
                unresolved.append(f"slot:{key}")
                return match.group(0)
        if key in variables:
            return str(variables[key])
        unresolved.append(key)
        return match.group(0)

    rendered = _VAR_RE.sub(_sub, body)

    if strict and unresolved:
        raise PromptError(
            f"template {name!r} has unresolved placeholder(s): "
            f"{', '.join('@@' + u + '@@' for u in sorted(set(unresolved)))}. "
            "Every non-slot placeholder must be supplied by the stage; leaving "
            "one unsubstituted would put a literal token into the agent's "
            "instructions."
        )

    return _tidy(rendered)

compose

compose(system_name: str, task_name: str, *, pack: PromptPack | None = None, variables: Mapping[str, Any] | None = None, strict: bool = True) -> str

Render a system + task template pair into one prompt string.

The agent harness takes a single task prompt, so the stage-specific "system" guidance is prepended to the task instructions with a horizontal rule between them (matching how the original pipeline composed its prompts).

Source code in abc_mine/prompts.py
def compose(
    system_name: str,
    task_name: str,
    *,
    pack: PromptPack | None = None,
    variables: Mapping[str, Any] | None = None,
    strict: bool = True,
) -> str:
    """Render a system + task template pair into one prompt string.

    The agent harness takes a single task prompt, so the stage-specific "system"
    guidance is prepended to the task instructions with a horizontal rule
    between them (matching how the original pipeline composed its prompts).
    """
    system = render(system_name, pack=pack, variables=variables, strict=strict)
    task = render(task_name, pack=pack, variables=variables, strict=strict)
    return f"{system}\n\n---\n\n{task}"

scaffold

scaffold(dest: Path | str, *, with_overrides: bool = False) -> list[Path]

Create an empty, commented prompt pack at dest.

Writes one placeholder file per slot under slots/, each containing only a comment describing its purpose — so a user can fill in what they need and delete the rest. overrides/ is created only when explicitly requested, keeping the advanced mechanism out of sight for users who do not need it.

Returns the list of created paths.

Source code in abc_mine/prompts.py
def scaffold(dest: Path | str, *, with_overrides: bool = False) -> list[Path]:
    """Create an empty, commented prompt pack at ``dest``.

    Writes one placeholder file per slot under ``slots/``, each containing only a
    comment describing its purpose — so a user can fill in what they need and
    delete the rest. ``overrides/`` is created **only** when explicitly
    requested, keeping the advanced mechanism out of sight for users who do not
    need it.

    Returns the list of created paths.
    """
    root = Path(dest).expanduser()
    slots_dir = root / SLOTS_SUBDIR
    slots_dir.mkdir(parents=True, exist_ok=True)

    created: list[Path] = []
    for slot in SLOTS:
        path = slots_dir / f"{slot.key}{PROMPT_SUFFIX}"
        if path.exists():
            continue
        stages = ", ".join(n.split("_")[0] for n in slot.templates)
        path.write_text(
            f"<!-- {slot.key} — used by: {stages}\n"
            f"\n"
            f"{slot.purpose}\n"
            f"\n"
            f"This file is OPTIONAL. Delete it, or leave it empty, and the\n"
            f"corresponding prompt section is omitted entirely — the surrounding\n"
            f"prompt still reads correctly. Write plain markdown below; it is\n"
            f"inserted under the heading \"{slot.heading.lstrip('# ')}\".\n"
            f"-->\n"
        )
        created.append(path)

    if with_overrides:
        ov_dir = root / OVERRIDES_SUBDIR
        ov_dir.mkdir(parents=True, exist_ok=True)
        readme = ov_dir / "README.md"
        if not readme.exists():
            readme.write_text(_OVERRIDES_README)
            created.append(readme)

    return created