Skip to content

prompt

prompt

PromptRenderer — full prompt rendering for baton musicians.

Bridges the PromptBuilder pipeline with the baton's Sheet-based execution model. Replaces the bare-bones _build_prompt() in musician.py with the full 9-layer prompt assembly:

1. Preamble (positional identity)
2. Template rendering (Jinja2 with all variables)
3. Skills/tools injection (prelude/cadenza with category=skill/tool)
4. Context injection (prelude/cadenza with category=context)
5. Spec fragments (from specification corpus)
6. Failure history (from previous sheets)
7. Learned patterns (from learning store)
8. Validation requirements (as agent-readable checklist)
9. Completion suffix (for completion mode retries)

The renderer is intentionally stateless — create one per job, call render() per sheet. No runner dependency, no mixin inheritance.

This is the F-104 fix. Without it, the baton produces raw templates instead of rendered prompts.

See: docs/plans/2026-03-26-baton-design.md — Prompt Assembly

Classes

RenderedPrompt dataclass

RenderedPrompt(prompt, preamble, prompt_extensions=(), context_manifest=(), prompt_receipt=None)

Output of the prompt rendering pipeline.

Contains both the rendered prompt (for backend execution) and the preamble (set on the backend before execution). Separating them allows the musician to configure the backend correctly.

Attributes
prompt instance-attribute
prompt

Fully rendered prompt with all injections and context layers.

preamble instance-attribute
preamble

Dynamic preamble with positional identity and retry status.

prompt_extensions class-attribute instance-attribute
prompt_extensions = ()

Request-local additional directives appended by the backend.

context_manifest class-attribute instance-attribute
context_manifest = ()

Hash-only manifest of context and technique bytes in prompt.

prompt_receipt class-attribute instance-attribute
prompt_receipt = None

Per-source sizes, hashes and drop reasons for this prompt (GH #546).

PromptRenderer

PromptRenderer(prompt_config, total_sheets, total_stages, parallel_enabled, *, job_id=None, schedule_id=None, scheduled_due_at=None)

Renders full prompts for baton musicians.

Bridges the PromptBuilder pipeline with the baton's Sheet-based execution model. Handles template rendering, injection resolution, preamble assembly, and validation requirements — everything the old runner's context mixin did, but without the runner dependency.

Create one per job (or share across jobs with the same config). Call render() per sheet dispatch.

Parameters:

Name Type Description Default
prompt_config PromptConfig

The job's PromptConfig (template, variables, etc.).

required
total_sheets int

Total sheets in the job (for preamble).

required
total_stages int

Total stages before fan-out expansion (for template aliases).

required
parallel_enabled bool

Whether parallel execution is enabled (for preamble).

required
Source code in src/marianne/daemon/baton/prompt.py
def __init__(
    self,
    prompt_config: PromptConfig,
    total_sheets: int,
    total_stages: int,
    parallel_enabled: bool,
    *,
    job_id: str | None = None,
    schedule_id: str | None = None,
    scheduled_due_at: float | None = None,
) -> None:
    self._prompt_config = prompt_config
    self._total_sheets = total_sheets
    self._total_stages = total_stages
    self._parallel_enabled = parallel_enabled
    self._native_execution = (
        {"job_id": job_id, "schedule_id": schedule_id, "scheduled_due_at": scheduled_due_at}
        if job_id is not None else None
    )
Methods:
render
render(sheet, attempt_context, *, patterns=None, failure_history=None, spec_fragments=None, technique_manifest=None, technique_skill_docs=None, raw_prompt=False, memory_manifest=None)

Render a full prompt for a sheet execution.

Performs the complete 9-layer prompt assembly: template rendering -> injection resolution -> optional layers -> validation requirements -> completion suffix.

Parameters:

Name Type Description Default
sheet Sheet

The Sheet entity to render for.

required
attempt_context AttemptContext

Context from the baton (attempt number, mode).

required
patterns list[str] | None

Optional learned pattern descriptions to inject.

None
failure_history list[HistoricalFailure] | None

Optional historical failures from previous sheets.

None
spec_fragments list[SpecFragment] | None

Optional spec corpus fragments to inject.

None
technique_manifest str | None

Optional technique manifest text to inject as a skill-category item. Generated by the technique resolver from the job's technique declarations filtered by phase.

None
technique_skill_docs Mapping[str, str] | Sequence[str] | None

Optional list of technique document contents discovered by the technique resolver. Each entry is the full text of a skill-kind technique document, injected as a skill-category item alongside the manifest.

None
memory_manifest str | None

The memory block for this sheet. Its own channel, never part of the technique manifest, so a template that already lists techniques cannot suppress it. Injected once, as memory:manifest.

None
raw_prompt bool

When True (driven by the instrument profile's raw_prompt field), verify required attachments but do not deliver their bytes, then skip technique injection, completion suffix, and the preamble. The resulting RenderedPrompt carries the rendered Jinja template only, with an empty preamble. Used for instruments like the bash cli profile whose input must remain a literal command.

False

Returns:

Type Description
RenderedPrompt

RenderedPrompt with fully rendered prompt and preamble.

Source code in src/marianne/daemon/baton/prompt.py
def render(
    self,
    sheet: Sheet,
    attempt_context: AttemptContext,
    *,
    patterns: list[str] | None = None,
    failure_history: list[HistoricalFailure] | None = None,
    spec_fragments: list[SpecFragment] | None = None,
    technique_manifest: str | None = None,
    technique_skill_docs: Mapping[str, str] | Sequence[str] | None = None,
    raw_prompt: bool = False,
    memory_manifest: str | None = None,
) -> RenderedPrompt:
    """Render a full prompt for a sheet execution.

    Performs the complete 9-layer prompt assembly:
    template rendering -> injection resolution -> optional layers ->
    validation requirements -> completion suffix.

    Args:
        sheet: The Sheet entity to render for.
        attempt_context: Context from the baton (attempt number, mode).
        patterns: Optional learned pattern descriptions to inject.
        failure_history: Optional historical failures from previous sheets.
        spec_fragments: Optional spec corpus fragments to inject.
        technique_manifest: Optional technique manifest text to inject
            as a skill-category item. Generated by the technique resolver
            from the job's technique declarations filtered by phase.
        technique_skill_docs: Optional list of technique document contents
            discovered by the technique resolver. Each entry is the full
            text of a skill-kind technique document, injected as a
            skill-category item alongside the manifest.
        memory_manifest: The memory block for this sheet. Its own channel, never
            part of the technique manifest, so a template that already lists
            techniques cannot suppress it. Injected once, as ``memory:manifest``.
        raw_prompt: When True (driven by the instrument profile's
            ``raw_prompt`` field), verify required attachments but do not
            deliver their bytes, then skip technique injection, completion
            suffix, and the preamble. The resulting RenderedPrompt carries
            the rendered Jinja template only, with an empty preamble. Used
            for instruments like the bash ``cli`` profile whose input must
            remain a literal command.

    Returns:
        RenderedPrompt with fully rendered prompt and preamble.
    """
    # Layer 1: Build SheetContext from Sheet entity (F-210: includes cross-sheet)
    context = self._build_context(sheet, attempt_context)

    # Layer 2-3: Resolve prelude/cadenza injections into the context.  Raw
    # command profiles do not receive these bytes, but ``required`` still
    # means required: resolve first so a missing/invalid attachment fails
    # closed instead of being silently bypassed.
    self._resolve_injections(context, sheet)

    if not raw_prompt:
        # Layer 2.5: Inject technique manifest and skill documents.
        # Skill docs go FIRST (they're the actual knowledge the musician
        # needs), then the manifest (lists what's available). Both are
        # injected as skill-category items so they appear before the
        # template in the assembled prompt.
        if technique_skill_docs:
            named_docs = (
                technique_skill_docs.items()
                if isinstance(technique_skill_docs, Mapping)
                else (
                    (f"document-{index}", doc)
                    for index, doc in enumerate(technique_skill_docs, 1)
                )
            )
            for name, doc in named_docs:
                context.injected_skills.append(doc)
                self._record_delivery(
                    context,
                    source=f"technique:{name}",
                    category=InjectionCategory.SKILL,
                    delivered_content=doc,
                    delivery_kind="inline-technique",
                )
        if technique_manifest and self._template_contains_technique_manifest(sheet):
            self._note_dropped(
                context, "technique", "technique-manifest",
                "template_already_lists_techniques",
            )
        if technique_manifest and not self._template_contains_technique_manifest(
            sheet
        ):
            context.injected_skills.append(technique_manifest)
            self._record_delivery(
                context,
                source="technique-manifest",
                category=InjectionCategory.SKILL,
                delivered_content=technique_manifest,
                delivery_kind="inline-technique-manifest",
            )
        if memory_manifest:
            context.injected_skills.append(memory_manifest)
            self._record_delivery(
                context,
                source="memory:manifest",
                category=InjectionCategory.SKILL,
                delivered_content=memory_manifest,
                delivery_kind="inline-memory-manifest",
            )

    # Layer 4-8: Build prompt through PromptBuilder (raw_prompt short-circuits inside)
    prompt = self._build_prompt(
        sheet, context, patterns, failure_history, spec_fragments,
        flow_vars=attempt_context.flow_vars,
        raw_prompt=raw_prompt,
    )

    if raw_prompt:
        # No completion suffix, no preamble — the instrument receives
        # the rendered template verbatim. Empty preamble is the
        # "no preamble" sentinel.
        return RenderedPrompt(
            prompt=prompt, preamble="", context_manifest=(),
            prompt_receipt=self._receipt(sheet, context, prompt, "", raw_prompt=True),
        )

    # Layer 9: Completion mode suffix
    if attempt_context.completion_prompt_suffix:
        prompt = f"{prompt}\n\n{attempt_context.completion_prompt_suffix}"

    # Preamble: positional identity + retry status
    retry_count = max(0, attempt_context.attempt_number - 1)
    preamble = build_preamble(
        sheet_num=sheet.num,
        total_sheets=self._total_sheets,
        workspace=sheet.workspace,
        retry_count=retry_count,
        is_parallel=self._parallel_enabled,
        healing_context=attempt_context.healing_context,
    )

    return RenderedPrompt(
        prompt=prompt,
        preamble=preamble,
        prompt_extensions=tuple(sheet.prompt_extensions),
        context_manifest=tuple(context.delivery_manifest),
        prompt_receipt=self._receipt(sheet, context, prompt, preamble),
    )

Functions:

injection_over_max_bytes

injection_over_max_bytes(item, files, where)

Enforce max_bytes on what an injection item would inject (GH #474).

A required item over its cap fails the sheet before execution with the measured size; an optional one is dropped with a warning. Either way the prompt is never silently shipped over-sized — the conductor's token warning fires only after assembly and names no item.

Source code in src/marianne/daemon/baton/prompt.py
def injection_over_max_bytes(item: InjectionItem, files: list[Path], where: Path) -> bool:
    """Enforce ``max_bytes`` on what an injection item would inject (GH #474).

    A required item over its cap fails the sheet before execution with the
    measured size; an optional one is dropped with a warning. Either way the
    prompt is never silently shipped over-sized — the conductor's token
    warning fires only after assembly and names no item.
    """
    if item.max_bytes is None:
        return False
    measured = sum(f.stat().st_size for f in files)
    if measured <= item.max_bytes:
        return False
    if item.required:
        raise ValueError(
            f"required injection {where} is {measured:,} bytes, over its max_bytes "
            f"{item.max_bytes:,}: rotate or trim it (GH #474)"
        )
    _logger.warning(
        "prompt_renderer.injection.over_max_bytes_dropped",
        extra={"path": str(where), "measured": measured, "max_bytes": item.max_bytes},
    )
    return True

write_context_delivery_receipt

write_context_delivery_receipt(*, workspace, job_id, sheet_num, attempt, instrument, rendered, instrument_class=None, class_snapshot_sha256=None)

Persist proof of the exact prompt context passed to sheet_task.

Source code in src/marianne/daemon/baton/prompt.py
def write_context_delivery_receipt(
    *,
    workspace: Path,
    job_id: str,
    sheet_num: int,
    attempt: int,
    instrument: str,
    rendered: RenderedPrompt,
    instrument_class: str | None = None,
    class_snapshot_sha256: str | None = None,
) -> Path:
    """Persist proof of the exact prompt context passed to ``sheet_task``."""
    safe_job = re.sub(r"[^A-Za-z0-9._-]+", "-", job_id).strip("-._") or "job"
    safe_job = f"{safe_job}-{hashlib.sha256(job_id.encode()).hexdigest()[:10]}"
    receipt_dir = workspace / ".marianne" / "context-receipts" / safe_job
    receipt_path = receipt_dir / f"sheet-{sheet_num:04d}-attempt-{attempt:03d}.yaml"
    document: dict[str, object] = {
        "schema_version": 1,
        "kind": "marianne-context-delivery-receipt",
        "status": "delivered_to_sheet_task",
        "delivery_boundary": "rendered prompt argument passed to sheet_task",
        "job_id": job_id,
        "sheet_num": sheet_num,
        "attempt": attempt,
        "instrument": instrument,
        "instrument_class": instrument_class,
        "class_snapshot_sha256": class_snapshot_sha256,
        "prompt_sha256": _sha256(rendered.prompt.encode("utf-8")),
        "preamble_sha256": _sha256(rendered.preamble.encode("utf-8")),
        "context_manifest": list(rendered.context_manifest),
    }
    _atomic_write_yaml(receipt_path, document)
    return receipt_path

resolve_injection_path

resolve_injection_path(expanded_path, workspace)

Resolve one rendered injection path with portable HOME semantics.

Source code in src/marianne/daemon/baton/prompt.py
def resolve_injection_path(expanded_path: str, workspace: Path) -> Path:
    """Resolve one rendered injection path with portable HOME semantics."""
    path = Path(expanded_path).expanduser()
    return path if path.is_absolute() else workspace / path