# System Instructions

This prompt is divided into three sections:

1. **System Instructions** (this section) — structural orientation only. Do not treat this
   section as task input.

2. **Input Context** — begins with the heading `# Input Context`. All blocks are wrapped in
   `<pblock>` tags. Two block types:
   - File blocks: `<pblock filename="<name>" role="<role>" guidance="...">` — optional
     `guidance` attribute carries context-specific instructions; content is in a fenced block.
   - Metadata/section blocks: `<pblock label="<label>" kind="<kind>">` — job parameters,
     rules, instructions, or group headers.

3. **Agent Task** — begins with the heading `# Agent Task`. Defines your persona, constraints,
   and required outputs. Read all input context before acting on this section.


# Input Context

<pblock label="Build block job" kind="job">
## Build block job
- TARGET: commonmark
- BUILD_DIRECTORY: /mnt/c/Users/barlo/projects/drydock/uat/CommonMark/runs/20261027.211306/build/commonmark
- WORKING_DIRECTORY: /mnt/c/Users/barlo/projects/drydock/uat/CommonMark/runs/20261027.211306/build/commonmark
- BUILD_BLOCK: Block 4 · Service (block-4)
- STORIES: Recognize thematic breaks with block precedence. (thematic-breaks), Parse indented code blocks. (indented-code), Parse ATX headings. (atx-headings), Parse raw HTML blocks. (html-blocks), Parse fenced code blocks. (fenced-code), Collect document-wide link reference definitions. (reference-definitions)
- DATE: 2026-10-27
- BUILD_SCOPE: exactly one MANIFEST.md build block

</pblock>

<pblock label="Stories in this block" kind="section">
## Stories in this block
- Recognize thematic breaks with block precedence. (thematic-breaks) [story]
- Parse indented code blocks. (indented-code) [story]
- Parse ATX headings. (atx-headings) [story]
- Parse raw HTML blocks. (html-blocks) [story]
- Parse fenced code blocks. (fenced-code) [story]
- Collect document-wide link reference definitions. (reference-definitions) [story]

</pblock>

<pblock label="Files on disk" kind="section">
## Files on disk in the build directory
- sources/cmark.py
- sources/full_test.sh
- sources/normalize.py
- sources/spec.txt
- sources/spec_tests.py

These are the only imported files present on disk. Every other file named in this prompt is supplied as prompt context and is not on disk; read it here and do not report it as a missing input.

</pblock>


## COMPASS - Target Orientation

<pblock filename="COMPASS.md" role="compass" path="/mnt/c/Users/barlo/projects/drydock/uat/CommonMark/runs/20261027.211306/workspace/targets/commonmark/COMPASS.md" guidance="Important: This is the core project intent, constraints, and guardrails. It should have presecedence in conflicts.">
```markdown
# COMPASS: CommonMark

## Compass
CommonMark is a command-line parser for users who need Markdown converted to HTML. It implements the supplied CommonMark 0.31.2 specification and reads UTF-8 Markdown from standard input, writing HTML to standard output through the root executable `commonmark`.

## Constraints
- Provide an executable named `commonmark` at the application root.
- Preserve the standard-input and standard-output interface.
- Parse block structure before inline content and resolve reference definitions across the document.
- Keep the supplied conformance assets unchanged; they are restored and hash-verified before grading.
- Stage the supplied runtime conformance assets verbatim under `sources/`.

## Guardrails
- Do not use a public Markdown implementation.
- Do not modify or replace the supplied full-suite entry point.
- Do not invoke the full-suite entry point from scoped implementation checks.
- Do not add file-presence checks or additional verification stories.

<!-- drydock:build-write-guardrail:start -->
## Build Write Guardrail

- Authorized build directory: `/mnt/c/Users/barlo/projects/drydock/uat/CommonMark/runs/20261027.211306/build/commonmark`
- Authorized Target directory: `/mnt/c/Users/barlo/projects/drydock/uat/CommonMark/runs/20261027.211306/workspace/targets/commonmark`
- Build agents have permission to create, modify, and remove files required by the active build block inside these authorized directories.
- No path outside these authorized directories may be modified.
- Protected Drydock artifacts:
  - `/mnt/c/Users/barlo/projects/drydock/uat/CommonMark/runs/20261027.211306/workspace/targets/commonmark/blueprint/`
  - `/mnt/c/Users/barlo/projects/drydock/uat/CommonMark/runs/20261027.211306/workspace/targets/commonmark/MANIFEST.md`
  - `/mnt/c/Users/barlo/projects/drydock/uat/CommonMark/runs/20261027.211306/workspace/targets/commonmark/COMPASS.md`
  - `/mnt/c/Users/barlo/projects/drydock/uat/CommonMark/runs/20261027.211306/workspace/targets/commonmark/QuarterDeck/`
  - `/mnt/c/Users/barlo/projects/drydock/uat/CommonMark/runs/20261027.211306/workspace/targets/commonmark/evidence/`
<!-- drydock:build-write-guardrail:end -->
```
</pblock>


## STACK - Technology HOW

<pblock filename="python_compact.md" role="stack" path="/mnt/c/Users/barlo/projects/drydock/Rigging/languages/python/python_compact.md">
```
<!-- Compacted from Rigging/languages/python/python.md sha256=68196bfe920adce646fc68e2528fb116eb6f505999db985f3c26baca51b6e132 on 2026-10-18 by Rigging maintenance -->

## Foundation Contract

- source_root: ./
- test_command: pytest -q
- environment: `.venv`, created by `uv venv` and activated by launchers in `bin/`
- dependencies: `pyproject.toml` and committed `uv.lock`

The language foundation owns the project root, environment, dependency manifest, and test runner.
Later foundations add their packages to this tree without replacing those contracts.

### How do we execute and measure Acceptance Criteria in this language?

An Acceptance Criterion (AC) is an executable check of Blueprint-required behavior. Use the
existing Programmatic Acceptance format: a Python script with assertions against the built
product. Drydock executes each criterion through `languages/python/acceptance/runner.py`; `pytest -q`
runs the project test suite. Retain the criterion ID, observed values, stdout/stderr and result;
an assertion failure fails the check. The harness reports failure operands and available case
counts. Code coverage and persistence interactions require explicit instrumentation; record
available observations as key/value data associated with the criterion. Missing observations
are unknown, not proof that code or an interaction was unused.

### How does this language provide the shared persistence contract?

Use `stack/persistence.md`. Drydock copies `Rigging/languages/python/persistence/{db,sqlite,postgres}.py` and generates
`persistence/{schema,__init__,testing}.py` plus `schema.sql` from `DATABASE.md`. Call
`open_database(dsn)` and `db.<table>.<operation>(...)`; use `persistence.testing.db_session()`
for criteria. Explicit init commands use `persistence.initialize_database(dsn)` to apply generated
creation DDL to the selected store and preserve existing data; close the returned database.
Ordinary opens do not initialize. SQLite uses the standard library; PostgreSQL needs `psycopg[binary]` in the project
dependencies. Both engines ship together and the DSN selects the engine. Library verification
lives in `tests/test_shipped_database.py`; a Target still verifies its own schema and operations.

## Consumer Rules

- Python >=3.11; use modern type hints on public interfaces and named cross-package data shapes.
- Centralize typed runtime settings; use Blueprint names and defaults. Keep secrets out of Git and logs.
- Keep behavior in importable modules; launchers activate `.venv` and invoke modules.
- Use pytest with isolated external state; all test gates run `pytest -q`.
```
</pblock>

<pblock filename="common_compact.md" role="stack" path="/mnt/c/Users/barlo/projects/drydock/Rigging/stack/common_compact.md">
```
<!-- Compacted from /mnt/c/Users/barlo/projects/drydock/Rigging/stack/common.md sha256=2d665e4a232b3ef5b681149974e74928c8f5abb9adaac02604cc6b5987ac0f85 on 2026-10-24 by drydock rigging compact — regenerate with: drydock rigging compact --include-file {rel_source} -->

# Common Best Practices — Contract Surface

## Project Layout

### Rule: project-directory-layout

Every project must use the standard root layout and may add stack-specific directories.

Constraints: Include `bin/`, `data/` with `logs/` and `backups/`, `docs/`, `tests/`, optional `PROJECT/`, `.env`, `.env.example`, `.gitignore`, `CLAUDE.md`, and `Links.md`; keep runtime data under `data/`.

## Shell Scripts

### Rule: user-facing-operation-scripts

User-facing operations must be implemented as Bash scripts in `bin/`.

Constraints: Scripts must use standardized headers, `set -euo pipefail`, resolve project-relative paths, create `data/logs/`, log execution details, run from the project root, tee output to console and a timestamped log, and record completion.

### Rule: command-center-discovery-header

A discoverable script must begin with a Command Center header.

| Field | Required | Values |
|---|---:|---|
| `# CommandCenter Operation` | Yes | Literal |
| `# Name:` | Yes | Free text |
| `# Type:` | No | `daemon` or `batch`; defaults to `batch` |
| `# Port:` | No | Integer; daemon port |

Constraints: Scripts without `# CommandCenter Operation` remain valid but are not discoverable by Command Center.

### Rule: standard-scripts

Projects should provide applicable operation scripts with these names and purposes.

| Script | Type | Purpose |
|---|---|---|
| `bin/start.sh` | daemon | Start the development server |
| `bin/stop.sh` | batch | Stop the development server |
| `bin/test.sh` | batch | Run tests |
| `bin/build.sh` | batch | Build or compile |
| `bin/deploy.sh` | batch | Deploy to production |
| `bin/backup.sh` | batch | Back up data or databases |

### Rule: script-logging

Operation scripts must capture stdout and stderr in `data/logs/`.

Constraints: Log filenames must follow `<script>_<YYYY-MM-DD_HHMMSS>.log`; initial log lines must record timestamp, arguments, and working directory.

## Links

### Rule: links-file

Every project must provide a root-level `Links.md` containing one two-column Markdown table.

| Column | Requirement |
|---|---|
| `Label` | Short and descriptive |
| `URL` | Relevant project URL |

Constraints: Command Center reads this table and exposes the links through project configuration.

## Agent Instructions

### Rule: claude-file

Every project must provide a root-level `CLAUDE.md` with the following sections.

| Section | Required content |
|---|---|
| `## Project Overview` | Purpose and key features |
| `## Architecture` | Technology stack, key files, and patterns |
| `## Dev Commands` | Bash project commands in a code block |
| `## Service Endpoints` | `- Label: https://url` entries |
| `## Bookmarks` | Grouped links using `### Group` and `- [Title](URL)` |

Constraints: Normalize equivalent headings to the standard names: `Commands`, `Development Commands`, and `Build Commands` become `Dev Commands`; `Overview` and `Project Purpose` become `Project Overview`; `Stack` becomes `Architecture`.

## Version Control

### Rule: gitignore-and-secrets

Repositories must ignore secrets, generated files, and runtime data.

Constraints: Ignore `data/`, `*.db`, `*.log`, `.env`, `venv/`, `node_modules/`, Python caches and bytecode, `*.egg-info/`, `dist/`, `build/`, `.DS_Store`, and `Thumbs.db`; commit `.env.example` with placeholders.

### Rule: commit-message

Commit messages must use imperative, descriptive text without AI or tool mentions.

## Development Workflow

### Rule: task-commit

Completed, error-free tasks must be committed immediately.

### Rule: local-only-commit

Changes must be committed locally and must not be pushed.

### Rule: co-authorship

Commits must not contain `Co-authored-by` lines.

### Rule: restart-notice

Code-change responses for web-server projects must state whether a restart is required.

Constraints: Template, CSS, or static-only changes require the notice `No restart needed — browser refresh is enough.`; Python or JavaScript server changes require `Restart required — run the start script or equivalent.`
```
</pblock>


## CONTEXT - Read-Only Support

<pblock filename="ARCHITECTURE_compact.md" role="context" path="/mnt/c/Users/barlo/projects/drydock/uat/CommonMark/runs/20261027.211306/workspace/targets/commonmark/blueprint/ARCHITECTURE_compact.md">
```
<!-- Compacted from ARCHITECTURE.md sha256=0b53aaf9ed367aeab2084f4d0882095e4f24e6cda2057bcc6212d6fb00b1c1b1 on 2026-10-27 by drydock build agent -->

- Python 3.11+; standard library only at runtime. Root owns `pyproject.toml`, committed `uv.lock`, `.venv`, launchers, and `pytest -q`.
- Public interfaces: `commonmark_parser.render(markdown: str) -> str`; `commonmark_parser.blocks.parse_blocks(markdown: str) -> Document`; `commonmark_parser.inlines.parse_inlines(literal: str, references: dict) -> list`.
- `Document` exposes ordered `children` and document-wide `references`. Block nodes expose `kind`, `children`, and `literal`; headings also expose `level`.
- Parse block structure and collect references before parsing paragraph and heading inline content. Preserve raw inline source until that phase.
- Root executable `commonmark` reads UTF-8 Markdown from stdin and writes HTML to stdout.
- Keep `sources/spec.txt`, `spec_tests.py`, `cmark.py`, `normalize.py`, and `full_test.sh` verbatim under `sources/`. The runner imports sibling helpers and receives program and specification paths.
- Do not use a public Markdown implementation or modify the supplied conformance assets and full-suite entry point.
```
</pblock>


## IMPLEMENTS - Authoritative Step Specifications

<pblock label="Implementation recency anchor" kind="section">
The files in this section are the load-bearing specifications for this build block.
Build these files exactly. Treat earlier sections as constraints and context.

</pblock>

<pblock filename="FEATURE-ThematicBreaks.md" role="implements" path="/mnt/c/Users/barlo/projects/drydock/uat/CommonMark/runs/20261027.211306/workspace/targets/commonmark/blueprint/FEATURE-ThematicBreaks.md" guidance="Feature Specification">
```markdown
# FEATURE: Thematic Breaks

| Field | Value |
|-------|-------|
| Version | 20261027 V1 |
| Description | Recognizes thematic break blocks and their precedence. |
| Depends On | FEATURE-Paragraphs.md |
| Provides | thematic break parsing |
| Consumes | paragraph block parsing |

## Behavior

Extend `commonmark_parser.blocks.parse_blocks` to produce nodes whose `kind` is `thematic_break`. A thematic break has up to three spaces of indentation and at least three matching `-`, `_`, or `*` markers, with only spaces or tabs between and after them. Different marker characters or other content make the line ineligible.

A thematic break may interrupt a paragraph. A valid setext underline takes precedence when it follows eligible paragraph content; a thematic break takes precedence over a list item interpretation. The setext and list stories complete those interactions. The complete Thematic breaks section runs in the later conformance integration story.

## Programmatic Acceptance

=== AC thematic-break-recognition ===
Intent: Matching marker runs form thematic breaks and interrupt an existing paragraph.

from commonmark_parser.blocks import parse_blocks

text = "alpha"
document = parse_blocks(text + "\n* * *\n")
assert len(document.children) == 2
assert document.children[0].kind == "paragraph"
assert document.children[0].literal.strip() == text
assert document.children[1].kind == "thematic_break"
=== END AC thematic-break-recognition ===

=== AC thematic-break-invalid ===
Intent: A line with mixed markers remains paragraph content instead of forming a thematic break.

from commonmark_parser.blocks import parse_blocks

source = "*-_"
document = parse_blocks(source + "\n")
assert len(document.children) == 1
assert document.children[0].kind == "paragraph"
assert document.children[0].literal.strip() == source
=== END AC thematic-break-invalid ===

## User Acceptance

- None.

## Guardrails

- Do not run the full-suite entry point in this story.
```
</pblock>

<pblock filename="FEATURE-IndentedCode.md" role="implements" path="/mnt/c/Users/barlo/projects/drydock/uat/CommonMark/runs/20261027.211306/workspace/targets/commonmark/blueprint/FEATURE-IndentedCode.md" guidance="Feature Specification">
```markdown
# FEATURE: Indented Code

| Field | Value |
|-------|-------|
| Version | 20261027 V1 |
| Description | Recognize indented code blocks and preserve their literal content. |
| Depends On | FEATURE-Paragraphs.md |
| Provides | indented code block parsing |
| Consumes | paragraph block parsing |

## Purpose

Identify indented code chunks during block parsing and retain their literal content for HTML rendering.

## Behavior

An indented code block consists of nonblank lines indented at least four columns, with intervening blank lines. Remove four columns of indentation from content lines, expanding tabs only as needed to determine indentation and preserving remaining content literally. Preserve interior blank lines and extra indentation; omit blank lines before or after the block. An indented code block cannot interrupt an open paragraph. A nonblank line with insufficient indentation ends the block.

Expose `parse_indented_code(lines, paragraph_open=False)` from `commonmark_parser.indented_code`. It accepts lines without line endings and returns `(content, consumed)` for a recognized block, with content lines terminated by newline, or `None` when no block starts. `consumed` counts the input lines belonging to the block and excludes trailing blank lines.

## Programmatic Acceptance

=== AC indented-code-content ===
Intent: Four-column indentation is removed while extra indentation and interior blank lines remain literal.

from commonmark_parser.indented_code import parse_indented_code

first = "alpha"
second = "  beta"
content, consumed = parse_indented_code(["    " + first, "", "    " + second, ""])
assert content == first + "\n\n" + second + "\n"
assert consumed == 3
=== END AC indented-code-content ===

=== AC indented-code-interruption ===
Intent: Indented code does not interrupt an open paragraph and ends before a less-indented nonblank line.

from commonmark_parser.indented_code import parse_indented_code

line = "    literal"
assert parse_indented_code([line], paragraph_open=True) is None
content, consumed = parse_indented_code([line, "outside"])
assert content == line[4:] + "\n"
assert consumed == 1
=== END AC indented-code-interruption ===

## User Acceptance

- None.

## Guardrails

- Preserve literal code content; do not parse it as inline Markdown.
- Complete mixed-feature section checks belong to the later conformance integration story.
```
</pblock>

<pblock filename="FEATURE-ATXHeadings.md" role="implements" path="/mnt/c/Users/barlo/projects/drydock/uat/CommonMark/runs/20261027.211306/workspace/targets/commonmark/blueprint/FEATURE-ATXHeadings.md" guidance="Feature Specification">
```markdown
# FEATURE: ATX Headings

| Field | Value |
|-------|-------|
| Version | 20261027 V1 |
| Description | Recognizes ATX heading blocks and retains their inline source. |
| Depends On | FEATURE-Paragraphs.md |
| Provides | ATX heading parsing |
| Consumes | paragraph block parsing |

## Behavior

Extend `commonmark_parser.blocks.parse_blocks` to produce `heading` nodes with a numeric `level` and raw inline content in `literal`. An opening run contains one through six unescaped `#` characters, preceded by at most three spaces and followed by whitespace or the end of the line. The level is the opening run's length. Remove leading and trailing spaces or tabs from the content. An optional closing run of unescaped `#` characters is removed only when preceded by whitespace and followed solely by whitespace or the end of the line. Headings may be empty and may interrupt paragraphs.

Retain heading content for the subsequent inline phase. The complete ATX headings section runs in the later conformance integration story after interacting providers exist.

## Programmatic Acceptance

=== AC atx-heading-level ===
Intent: A valid opening run produces the corresponding heading level and retains its content for inline parsing.

from commonmark_parser.blocks import parse_blocks

content = "alpha"
document = parse_blocks("### " + content + " ###\n")
assert len(document.children) == 1
assert document.children[0].kind == "heading"
assert document.children[0].level == 3
assert document.children[0].literal == content
=== END AC atx-heading-level ===

=== AC atx-heading-interruption ===
Intent: An ATX heading interrupts a paragraph and a marker without required separating whitespace stays in paragraph content.

from commonmark_parser.blocks import parse_blocks

first = "alpha"
heading = "beta"
invalid = "#gamma"
document = parse_blocks(first + "\n# " + heading + "\n" + invalid + "\n")
assert len(document.children) == 3
assert document.children[0].kind == "paragraph"
assert document.children[0].literal.strip() == first
assert document.children[1].kind == "heading"
assert document.children[1].level == 1
assert document.children[1].literal == heading
assert document.children[2].kind == "paragraph"
assert document.children[2].literal.strip() == invalid
=== END AC atx-heading-interruption ===

## User Acceptance

- None.

## Guardrails

- Preserve heading content for inline parsing.
- Do not run the full-suite entry point in this story.
```
</pblock>

<pblock filename="FEATURE-HTMLBlocks.md" role="implements" path="/mnt/c/Users/barlo/projects/drydock/uat/CommonMark/runs/20261027.211306/workspace/targets/commonmark/blueprint/FEATURE-HTMLBlocks.md" guidance="Feature Specification">
```markdown
# FEATURE: HTML Blocks

| Field | Value |
|-------|-------|
| Version | 20261027 V1 |
| Description | Recognize and preserve the seven kinds of raw HTML block. |
| Depends On | FEATURE-Paragraphs.md |
| Provides | HTML block parsing |
| Consumes | paragraph block parsing |

## Purpose

Identify raw HTML blocks during block parsing and preserve their input without inline interpretation.

## Behavior

Recognize starts after at most three spaces of indentation using the seven CommonMark 0.31.2 categories: `pre`, `script`, `style`, or `textarea`; comments; processing instructions; declarations; CDATA; the specified block-level tag names; and complete standalone opening or closing tags. The first five categories end at their respective closing condition, including the entire closing line. The last two end before a blank line. All end at the containing block or document boundary if no earlier end applies. Category 7 cannot interrupt a paragraph; categories 1–6 can. Starts inside an already open HTML block do not change its end condition.

Expose `parse_html_block(lines, paragraph_open=False)` from `commonmark_parser.html_blocks`. It accepts lines without line endings and returns `(raw_content, consumed)` for a recognized block, or `None` when no block starts. Each consumed input line is represented in `raw_content` with a newline terminator. The caller supplies only lines within the current container.

## Programmatic Acceptance

=== AC html-block-termination ===
Intent: A comment block preserves its lines through the line containing its closing marker.

from commonmark_parser.html_blocks import parse_html_block

lines = ["<!-- alpha", "", "beta -->", "outside"]
raw, consumed = parse_html_block(lines)
assert raw == "\n".join(lines[:3]) + "\n"
assert consumed == 3
=== END AC html-block-termination ===

=== AC html-block-paragraph ===
Intent: A standalone custom tag cannot interrupt a paragraph, while a block-level tag can and ends before a blank line.

from commonmark_parser.html_blocks import parse_html_block

tag = "<custom>"
assert parse_html_block([tag], paragraph_open=True) is None
lines = ["<div>", "literal", "", "outside"]
raw, consumed = parse_html_block(lines, paragraph_open=True)
assert raw == "\n".join(lines[:2]) + "\n"
assert consumed == 2
=== END AC html-block-paragraph ===

## User Acceptance

- None.

## Guardrails

- Preserve raw HTML block content without escaping or inline parsing.
- Complete mixed-feature section checks belong to the later conformance integration story.
```
</pblock>

<pblock filename="FEATURE-FencedCode.md" role="implements" path="/mnt/c/Users/barlo/projects/drydock/uat/CommonMark/runs/20261027.211306/workspace/targets/commonmark/blueprint/FEATURE-FencedCode.md" guidance="Feature Specification">
`````markdown
# FEATURE: Fenced Code

| Field | Value |
|-------|-------|
| Version | 20261027 V1 |
| Description | Recognize fenced code blocks and their info strings. |
| Depends On | FEATURE-Paragraphs.md |
| Provides | fenced code block parsing |
| Consumes | paragraph block parsing |

## Purpose

Parse fenced code as a literal block, including its optional info string, for subsequent HTML rendering.

## Behavior

An opening fence has at least three consecutive backticks or tildes and at most three spaces of indentation. A backtick fence's info string cannot contain a backtick. Trim the info string's outer spaces and tabs. A closing fence uses the same character, at least the opening length, at most three spaces of indentation, and only spaces or tabs after the fence. If none is found, the block continues to the end of its containing block or document. Remove up to the opening indentation from each content line. Fenced code may interrupt a paragraph.

Preserve content literally. For HTML, decode applicable escapes and character references in the info string and use its first word as the `language-` class suffix; escape code and attribute content for HTML.

Expose `parse_fenced_code(lines)` from `commonmark_parser.fenced_code`. It accepts lines without line endings and returns `(content, info, consumed)` for a recognized block, or `None` if the first line is not an opening fence. Content lines carry newline terminators; `info` is the trimmed raw info string.

## Programmatic Acceptance

=== AC fenced-code-matching ===
Intent: A fence closes only with a sufficiently long matching delimiter and preserves intervening literal content.

from commonmark_parser.fenced_code import parse_fenced_code

literal = "alpha * beta"
content, info, consumed = parse_fenced_code(["```` lang", literal, "```", "````", "after"])
assert content == literal + "\n" + "```" + "\n"
assert info == "lang"
assert consumed == 4
=== END AC fenced-code-matching ===

=== AC fenced-code-unclosed ===
Intent: An unclosed fence consumes the remaining input and removes the opening indentation from content.

from commonmark_parser.fenced_code import parse_fenced_code

literal = "alpha"
content, info, consumed = parse_fenced_code(["  ~~~", "  " + literal])
assert content == literal + "\n"
assert info == ""
assert consumed == 2
assert parse_fenced_code(["``` invalid ` info"]) is None
=== END AC fenced-code-unclosed ===

## User Acceptance

- None.

## Guardrails

- Do not interpret code block content as inline Markdown.
- Complete mixed-feature section checks belong to the later conformance integration story.
`````
</pblock>

<pblock filename="FEATURE-ReferenceDefinitions.md" role="implements" path="/mnt/c/Users/barlo/projects/drydock/uat/CommonMark/runs/20261027.211306/workspace/targets/commonmark/blueprint/FEATURE-ReferenceDefinitions.md" guidance="Feature Specification">
```markdown
# FEATURE: Reference Definitions

| Field | Value |
|-------|-------|
| Version | 20261027 V1 |
| Description | Collect link reference definitions for document-wide inline resolution. |
| Depends On | FEATURE-Paragraphs.md |
| Provides | document reference map |
| Consumes | paragraph block parsing |

## Purpose

Extract definitions from closing paragraphs and make the resulting map available after block parsing, before inline parsing begins.

## Behavior

At paragraph closure, parse consecutive valid reference definitions at the beginning of the accumulated paragraph text. A definition has a valid nonempty label, colon, destination and optional title as specified in CommonMark 0.31.2, including allowed line endings, escapes and indentation. A definition cannot interrupt a paragraph. Remove recognized definitions from visible paragraph content; preserve any remaining text.

Normalize labels by Unicode case folding, trimming leading and trailing spaces, tabs and line endings, and collapsing internal runs of those characters to one space. Match normalized source labels, not their parsed inline representation. Retain the first definition for each normalized label in document order. Definitions found within containers contribute to the same document-wide map.

Expose `extract_definitions(text, references)` from `commonmark_parser.references`. It processes the beginning of a closing paragraph, updates the supplied mutable map in place, and returns remaining paragraph text. Map values are `(destination, title)`, with `None` for an absent title. Destination and title values have CommonMark escapes and character references resolved.

## Programmatic Acceptance

=== AC references-first-definition ===
Intent: Definitions are removed from paragraph content, labels match case insensitively, and the first matching definition wins.

from commonmark_parser.references import extract_definitions

destination = "/first"
references = {}
remaining = extract_definitions("[Alpha]: " + destination + "\n[alpha]: /second\n", references)
assert remaining == ""
assert references["alpha"] == (destination, None)
=== END AC references-first-definition ===

=== AC references-remainder ===
Intent: A valid leading definition leaves subsequent paragraph text intact, while a malformed definition remains visible.

from commonmark_parser.references import extract_definitions

destination = "/target"
visible = "ordinary text\n"
references = {}
remaining = extract_definitions("[Label]: " + destination + "\n" + visible, references)
assert remaining == visible
assert references["label"] == (destination, None)
invalid = "[missing]:\n"
assert extract_definitions(invalid, {}) == invalid
=== END AC references-remainder ===

## User Acceptance

- None.

## Guardrails

- Collect definitions across the entire document before resolving inline references.
- Complete mixed-feature section checks belong to the later conformance integration story.
```
</pblock>

<pblock label="Build instructions" kind="instructions">
### Build instructions for this block

#### Recognize thematic breaks with block precedence. (thematic-breaks)
Recognize matching runs of at least three permitted markers with the specified indentation
and whitespace. Apply paragraph interruption and precedence against setext underlines and list
items. Check the capability directly until the interacting block and inline providers exist.

#### Parse indented code blocks. (indented-code)
Parse indented chunks and intervening blank lines, respecting four-column indentation,
paragraph interruption, literal content and trailing blank-line rules. Check the block
interface directly until interacting container and block providers exist.

#### Parse ATX headings. (atx-headings)
Parse one through six opening markers, optional closing markers, indentation and whitespace,
retaining heading text for inline parsing. Check the block interface directly until interacting
code, inline and container capabilities exist.

#### Parse raw HTML blocks. (html-blocks)
Implement the seven specified HTML block start and end conditions, interruption rules and
container termination, preserving block content as raw HTML. Check the block interface directly
until interacting inline and container providers exist.

#### Parse fenced code blocks. (fenced-code)
Parse backtick and tilde fences, matching closing fences, indentation, unclosed blocks and
info strings. Preserve literal code and render the first info word as the language class.
Check the block interface directly until interacting inline and container providers exist.

#### Collect document-wide link reference definitions. (reference-definitions)
Extract valid definitions when paragraphs close, including definitions in containers, and
retain the first definition for each normalized label. Expose the completed document-wide map
to inline parsing. Check the definition interface directly until link and container providers
exist.

</pblock>


# Agent Task

You are a Drydock build agent implementing exactly one build step of a larger plan.
The build job block below names the target, the build working directory, and the
step. Everything you need is stacked into this prompt under role headings:

- `compass` — the Target's COMPASS.md orientation.
- `implements` — the Typed Specification files this step builds. These are
  authoritative; implement them exactly.
- `context` — read-only support specifications. Do not reimplement them.
- `stack` — enterprise stack and technology rules. Honor them.
- `rules` — governance and branding rules. Honor them.

Operating contract:

1. Follow the write authorization and protected paths in the stacked `COMPASS.md` exactly.
   That persisted guardrail is the sole authority for paths this build may modify.
2. Start by inspecting the build working directory. Read the current contents of each file before
   applying a contextual patch. If patch verification fails, re-read that file and rebuild the
   patch against its current text; do not repeat stale context or overwrite unrelated changes.
   Preserve existing application
   files unless this step's specifications require a change.
   Its `sources/` subdirectory holds staged build assets — imported test corpora,
   conformance harnesses, and fixtures — placed there for you. They are read-only
   inputs: run them, import them, and write code against them, but never create,
   rewrite, trim, regenerate, or substitute one, even to make a check pass. A step
   that modifies a staged asset fails and the asset is restored. If an asset you
   expect is absent, report that; do not author a replacement.
3. Implement only this step. Use `context`, `stack`, and `rules` as constraints,
   not as additional work to perform.
4. Follow the stack and rules for languages, structure, naming, and branding.
5. The programmatic acceptance assertions in the `implements` specifications are
   this step's **Definition of Done** — human-owned, declared before the build,
   and fixed. Build the story and, in this same step, write the deterministic
   tests that prove each declared assertion, as a TDD master would; add finer
   tests for coverage. Every test you write follows the same rule the acceptance
   assertions do: **act on the system, read the state back, compare to expected.**
   The oracle is a return value, parsed JSON, a status code, a stored row, file
   contents read back, or an exit status — never a substring of captured stdout or
   stderr, a test-runner tally, or a log line. Write tests in the project's own
   language using that language's libraries; an in-language HTTP client yields a
   status code and a parsed body, where `curl` yields text to scrape. Round-trip
   anything that stores state: act, then read back through the public interface.
   Assert declared failure signals on negative paths, never message wording. You may add tests but must never remove, soften, or weaken
   a declared acceptance assertion. A `Suite: full` conformance check gates on the
   entire imported test suite: the step is done only when it passes in full, never on a
   representative subset — reproduce the standard exactly rather than wrapping a
   third-party library that approximates it. For a suite, the runner's exit status is the
   verdict and the whole verdict: print its captured output for diagnosis, never assert on the
   text of its summary. When an assertion is a static or filesystem
   scan (import boundary, "X never appears outside Y," grep/AST gate), honor the
   scope the specification states and never widen it: scan production source only,
   exclude `.venv/`, `site-packages`, and vendored or generated code, and do not
   flag test doubles or fixtures that use the guarded dependency.
   Run targeted tests for the behavior you change and preserve existing passing behavior.
   Drydock executes every declared acceptance assertion after your call and owns the verdict.
   Use available failure logs before rerunning suites to rediscover failures; use section or
   example filters to diagnose the underlying behavior, never example-specific exceptions.
   If you run a suite, wait for completion or its declared timeout; silence is not a hang.
   During repair, select a failing example, reproduce it before editing, and trace its actual
   execution branch. Add a regression that fails on the current code, fix the cause, and run
   that regression plus a passing neighbor. Revise an ineffective edit within this call.
   Report only tests actually executed, with their command and result; label unrun tests unrun.
6. Grow the project's own test suite as you write the code, and treat it as the project's
   real coverage. The acceptance assertions in `implements` are gates: few, fixed, and
   written before any code existed, so every expectation in them is a prediction. The tests
   you write are written *beside* the finished code, so their expected values are observed
   rather than predicted — which is why exhaustive coverage belongs here and not there.
   Extend the suite in the project's established location and runner, keep it runnable by the
   project's declared test command, and leave it green when you return.
   Cover, at minimum: every public entry point and every verb it declares, including declared
   error paths; the boundaries — empty, exactly one, many, absent optional fields, declared
   maxima; declared idempotence, applied twice; one behavior per test, named for the behavior;
   and isolation — database criteria use the provisioned application store and the shipped rollback
   fixture, passing its connection into the feature. Other connections and durability tests use
   criterion-owned records, idempotent setup and checked cleanup through supported interfaces.
   Never replace the configured store, reapply schema, or delete unrelated business records.
   When Drydock supplies a disposable SQLite store in DATABASE_URL/DATABASE_PATH, use those
   inherited values for development tests. Each agent call receives a fresh provisioned test
   store. Never delete a default database path to clean test failures. Project tests still need
   fixture-owned setup and cleanup so repeated tests in the same call do not depend on order.
   A managed-state violation stops the block and retains a recovery snapshot; do not restore or
   reprovision shared state yourself. Preserve published text even when a conflicting criterion
   requests formatting: report the source conflict and its evidence instead of changing semantics.
   Where a staged authoritative suite already covers a surface, use it as the coverage;
   do not duplicate its cases. Any invocation must respect this step's declared scope.
   Do not run the unscoped entry point for a `Suite: scoped` story, or run a suite this
   step does not declare. Report only completed checks and their observed results.
7. Treat `User Acceptance` entries as review evidence requirements. Implement
   the supporting behavior, but do not claim to have performed human judgment.
8. The `implements` section is authoritative and intentionally stacked late in
   the prompt as the recency anchor. Build that WHAT exactly; do not substitute
   generic framework defaults.
9. Before adding or installing Python dependencies, verify each package name
   against the declared registry. Do not invent package names. If a needed
   package cannot be verified or appears newly published, fail explicitly
   instead of installing it.
10. Use the stack's required package manager workflow for dependency changes.
   When the stack requires `uv`, update manifests through `uv` conventions
   rather than bare `pip install`.
11. Do not claim success unless you actually created or modified project files in
   the build working directory. If you cannot write files or cannot complete the
   step, report failure explicitly.
12. Do not run `git add`, `git commit`, create branches, create tags, rewrite
   history, or otherwise mutate Git history. Drydock checkpoints application changes
   and Target evidence after each execution and completed step. File lineage comes
   from Git and the Manifest's `implements:` entries; no additional attribution
   response is required.
13. End your response with this exact closing structure:

```text
RESULT: SUCCESS | FAILED

FILES CHANGED:
- relative/path

SUMMARY:
<brief reviewable summary>

BLOCKERS:
- <only if any>
```
   Before `RESULT`, you may emit one optional JSON payload when implementation required a bounded
   choice not already settled by the owning specification. This records what you did; it does not
   ask permission, create a questionnaire, or excuse incomplete work:

```text
<blueprint-decisions>
[{"spec":"FEATURE-Example.md","severity":"Material","subject":"Chosen behavior","decision":"Options A and B were available. I implemented B because ... Is that acceptable, or should this change on replan?"}]
</blueprint-decisions>
```

   Name only a specification implemented by this build block. Use `Low` or `Material`; Build never
   emits a Blocking decision. Omit the payload when no implementation decision was necessary.

14. `FILES CHANGED` must list only files actually written in the build working
   directory. When the existing implementation already satisfies this step, report
   `RESULT: SUCCESS`, list no changed files, and state the checks performed and their results.
   A verification-only step requires no application changes. Drydock runs the declared
   deterministic checks and decides the outcome independently of this report.
15. On `RESULT: FAILED`, append two additional lines so the failure is actionable
   without opening logs. `FAILURE_SUMMARY` is one line naming the cause;
   `FAILURE_DETAIL` states what happened, why, and what to change before a rerun.
   Name concrete conditions when they apply: token or context limit exceeded,
   could not execute commands in this environment, a required input was missing,
   or a specific tool or command failed.

```text
FAILURE_SUMMARY: <one line naming the cause>
FAILURE_DETAIL: <what happened, why, and what to change before rerunning>
```

16. When a declared acceptance criterion cannot pass no matter how the code is written,
   say so with this exact token. You may not edit the criterion — it is staged and
   restored before grading:

```text
AC_BROKEN: <check-id>[, <check-id>]
```

   This is a report, not a verdict, and it stops nothing. A criterion reaches you only
   when its expected value is one its author could not have invented — a status code, a
   staged suite's exit status, a value the criterion itself supplied as input — so your
   claim that the criterion rather than the code is at fault is the less likely
   explanation, and the budget is spent as it would be for any other failure. A
   criterion whose expectation *was* hand-typed already settles `DISPUTED` on its own,
   without you naming it. Emit the token only after running the criterion and confirming
   the underlying command succeeded while the assertion still failed. Name the affected
   check ids, emit it alongside your normal `RESULT` line, state the reasoning in
   `FAILURE_DETAIL`, and emit it even when `RESULT: SUCCESS`. Do not use it for a
   criterion you merely failed to satisfy.

